Compare commits

...

300 Commits

Author SHA1 Message Date
Wouter van Oortmerssen
eba6b6f7c9 1.4 prep fixes
Change-Id: I001ad8dd5f95e6e5ad43daf956663218d19f5c96
2016-08-15 17:29:35 -07:00
Wouter van Oortmerssen
a0b8f669ee Added "Direct" suffix to vector/string object creation functions.
They were overloaded, but also had default arguments, so would
become ambiguous when used with few arguments.

Change-Id: Ifac7f3ea3a6391d971dfeda8e33129c8c38d6f12
Tested: on Linux.
2016-08-12 11:12:12 -07:00
Wouter van Oortmerssen
18d67ed83b Clarified in the docs how to get to the serialized bytes.
This was a frequent source of confusion, since in all implementations
the data doesn't start at offset 0 in the buffer.

Change-Id: I045966e65928e9acd9def84e215914ecb5510653
2016-08-10 17:53:40 -07:00
Wouter van Oortmerssen
205ddb175f Added union namespacing test case.
Change-Id: I9a4f90889c311c454a9c19e78c7db3c79800b44e
Tested: on Linux.
2016-08-10 11:52:09 -07:00
Wouter van Oortmerssen
be908939da Fixed __builtin_bswap16 not being available on GCC <4.8
See e.g. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52624

Change-Id: Idae99196c47e015a2ba2416aaf1526f77498ce5d
2016-08-10 10:49:17 -07:00
Wouter van Oortmerssen
c96fc7fcef Added missing generated code from previous commits.
Change-Id: Ie2f1f65be451979d9f8d4da999b1c10737e867af
2016-08-08 12:18:07 -07:00
Wouter van Oortmerssen
026c6ddb17 Merge branch 'master' of https://github.com/google/flatbuffers 2016-08-08 12:17:10 -07:00
Wouter van Oortmerssen
3eebba789f Fixed incorrect generated code on convenient vector constructors.
Change-Id: Ib283eade157a436e0f3ca0e68d74e7dc6c51c65b
2016-08-08 12:16:10 -07:00
Robert
b36bd67b39 Merge pull request #3976 from gonzaloserrano/fix/gofmt
Make most of the Go code comply with gofmt (except enums).
2016-08-03 17:41:10 -04:00
gonzaloserrano
ec20233fab Make most of the Go code comply with gofmt (except enums).
Enums are not fixed because depending on they have comments or not they
will be aligned alogn the asssignment character.
2016-08-02 18:21:47 +02:00
Wouter van Oortmerssen
73d5bf46b4 Merge pull request #3975 from bhamiltoncx/validate-utf8
Allow Unicode values > U+FFFF in string literals, validate UTF-8 by default
2016-08-01 15:06:23 -07:00
Ben Hamilton
f6416d8471 Validate UTF-8 by default when parsing IDL. Support Unicode values > U+FFFF in parse 2016-08-01 14:05:24 -07:00
Wouter van Oortmerssen
d70f5ac6b0 Added backwards compatible --no-union-value-namespacing
Change-Id: Ia78dd3b0f213e9ffa49dcec699dcbb21fe6517da
Tested: on Linux.
2016-07-29 11:35:08 -07:00
Wouter van Oortmerssen
c9b9fd0407 Merge remote-tracking branch 'mbp/mutable-js' into ghfix 2016-07-29 11:32:00 -07:00
Caleb Epstein
6897bb99bb Use fully qualified names of structs in UnPack 2016-07-28 15:22:29 -04:00
Caleb Epstein
c9ee9fb99d Merge branch 'master' of https://github.com/google/flatbuffers
* 'master' of https://github.com/google/flatbuffers:
  Added AppVeyor CI.
  Removed pre-made VS2010 and XCode projects.
2016-07-28 08:33:35 -04:00
Caleb Epstein
50e13ef9c6 Need unique_ptr.get not pointee.get 2016-07-28 08:31:19 -04:00
Wouter van Oortmerssen
f624065eaa Added AppVeyor CI.
Change-Id: I01cf630026e25382b585785b471bad21153338f6
2016-07-27 18:38:27 -07:00
Wouter van Oortmerssen
03adfa7b1a Merge branch 'master' of https://github.com/google/flatbuffers 2016-07-27 17:20:35 -07:00
Wouter van Oortmerssen
97a9a82324 Removed pre-made VS2010 and XCode projects.
CMake is now required on all platforms.

Change-Id: Iad81d9244a05ed70ce8b8860d6b729a873f137c1
Tested: on Windows and OS X.
2016-07-27 17:10:37 -07:00
Wouter van Oortmerssen
307694e397 Merge pull request #3965 from Bklyn/master
Fix docs for object API usage
2016-07-27 13:41:22 -07:00
Michael Paulson
d268d11ca2 feat(test): Added mutation testing for scalar values.
This is a port of the tests found in test.cpp
2016-07-27 13:32:53 -07:00
Caleb Epstein
094f4d1bad Fix docs for object API usage 2016-07-27 16:15:55 -04:00
Wouter van Oortmerssen
a0398ce0f5 Merge branch 'master' of https://github.com/google/flatbuffers 2016-07-27 12:29:21 -07:00
Jason Sanmiya
30c07f4e55 Fix Mac build.
The new line in the set(CMAKE_CXX_FLAGS...) line was getting insert
verbatim into the Makefile. Makefiles don't like new lines in their
assignment operators.

The newline escape fix works for CMake 3.0 and above, but since
we support 2.x, we need to use the legacy solution, which is to
split into two separate statements.

Tested: cmake -G"Unix Makefiles" works now on Mac.
Change-Id: I6f4655981b85087c4760c3d26ed0c97c4469ba93
2016-07-26 07:26:25 -07:00
Robert
fc19f746b0 Merge pull request #210 from splhack/add_enumnames_to_go
Add EnumNames to Go code
2016-07-25 20:44:33 -07:00
Michael Paulson
a351124cfd chore(generate-code): Generate the JS code after mutation has been added. 2016-07-25 20:00:22 -07:00
Michael Paulson
0230a7173f feat(mutable-js): The mutable Scalar generation.
This is just the initial commit to start the conversation on adding mutation to javascript.
2016-07-25 20:00:22 -07:00
Kazuki Sakamoto
5f351a35a2 Add EnumNames to Go code
Tested: on Darwin
2016-07-25 19:37:16 -07:00
Wouter van Oortmerssen
2d427e0502 Pulled out EndianSwap into its own function.
Change-Id: I4a587102db8c435b739c92b6c464c94c4ea1fe42
2016-07-25 16:26:50 -07:00
Wouter van Oortmerssen
1bba4fd9ea Fixed reflection.h not modifying certain table configurations.
It would write 64bits offsets instead of 32bit ones, and update
the vtable pointer before the fields were processed.

Change-Id: I0c0fa942bbd3b42839294f5653ba8fa048612624
Tested: on Linux.
2016-07-25 15:01:37 -07:00
Wouter van Oortmerssen
f98870715a Adding missing generated code from recent commits.
Also updated generated_code.sh to prevent this from happening in
the future.

Change-Id: Ib282e9b6c762a79d4b4e09bee06b14781cd2a4c1
2016-07-25 15:01:37 -07:00
Wouter van Oortmerssen
f61f0449c7 Merge pull request #3935 from kazimuth/jsns
Add @namespace annotation to namespaces in javascript
2016-07-25 10:47:46 -07:00
Wouter van Oortmerssen
42e0b02149 Fixed missing \ in CMakeLists.txt that broke the build 2016-07-22 15:46:26 -07:00
Robert
a56c6e5195 Merge pull request #363 from danring/fix-341
Emit GetRootAs methods for all types in Go and Python
2016-07-22 15:12:35 -07:00
Wouter van Oortmerssen
5efa22447e Fixed conversion warning in generated code. 2016-07-20 18:17:33 -07:00
Wouter van Oortmerssen
bdd668df7b Fixed VS2010 build 2016-07-20 18:13:11 -07:00
Wouter van Oortmerssen
05b00c50ad Added way to test two schemas for safe evolution.
Change-Id: I1dfc867e6df5932ab61dad431eb3cb02f15d04df
Tested: on Linux.
Bug: 30202327
2016-07-20 17:56:59 -07:00
Wouter van Oortmerssen
77e9122681 Merge "This is a minimal amount of #ifdef's to make stlport work." into ub-games-master 2016-07-21 00:55:05 +00:00
Wouter van Oortmerssen
e067040375 Fixed unused parameter warning.
Change-Id: I7a2576c6f366b89ef3e1f83941f90294ca7a07fd
2016-07-20 17:52:41 -07:00
Wouter van Oortmerssen
370e101a69 Added missing Go generated files.
Change-Id: I9d738e84ab2e01ec117c825ade44cc865cf5f1c2
2016-07-20 17:43:03 -07:00
Wouter van Oortmerssen
91f5cf357c Merge branch 'master' of https://github.com/google/flatbuffers into grpc2 2016-07-20 17:41:36 -07:00
Wouter van Oortmerssen
7c7c571bbe This is a minimal amount of #ifdef's to make stlport work.
Minimal, in the sense that this will only allow flatbuffers.h +
generated code to work. Everything else (tests, parsing, reflection
etc.) may still not compile with stlport.

Functionality has been reduced, some utility functions are not
available.

Tested: on Linux (no stlport), Android (stlport).

Change-Id: I3f8b6a88258c07d78964dd455fb9f99f65266301
2016-07-20 17:29:47 -07:00
Wouter van Oortmerssen
3101e327c0 Added optional object based API for C++.
Change-Id: If927f3ea3fb3723088fa287f24bdd1ad43c8d1d1
Tested: on Linux.
2016-07-20 14:58:57 -07:00
Wouter van Oortmerssen
46bf9f5177 Merge pull request #259 from kadirahq/golang-mutators
(Go) Add setter methods for scalar values.
2016-07-20 10:51:30 -07:00
Wouter van Oortmerssen
694725beb0 Xcode fixes 2016-07-20 10:48:37 -07:00
Wouter van Oortmerssen
ce3e7fbd72 VS2010 fixes 2016-07-20 10:41:26 -07:00
Muhammed Thanish
53e9606ea2 Implement mutators for Go 2016-07-20 22:58:22 +05:30
Wouter van Oortmerssen
ffc0d6209a Merge pull request #3954 from yakiro/master
fixed ArrayOutOfBoundsException in java example
2016-07-20 10:01:32 -07:00
Wouter van Oortmerssen
9fdb6dcf1f Merge pull request #3951 from devantoine/patch-2
[PHP] Fix typo
2016-07-20 09:40:50 -07:00
Yakir Buskilla
298dd21ec8 fixed ArrayOutOfBoundsException in java example 2016-07-20 10:46:43 +03:00
Antoine Descamps
64fa8ba9a9 Fix typo
Related to https://github.com/google/flatbuffers/pull/3904#issuecomment-224724181
2016-07-19 12:22:37 +02:00
Wouter van Oortmerssen
a8d2eeee34 Merge pull request #3904 from devantoine/patch-1
Fix typo
2016-07-18 17:35:43 -07:00
Wouter van Oortmerssen
e21a61d458 Merge pull request #3902 from rgilles/master
Create a maven like project structure for java development + OSGi + generation for test
2016-07-18 14:13:36 -07:00
Wouter van Oortmerssen
410fb15a07 Merge pull request #3915 from Lakedaemon/clangFormat
clang formating header and code generators for cpp, general, js, php
2016-07-18 14:12:03 -07:00
Wouter van Oortmerssen
a69b19fa8f Merge pull request #3948 from mortonfox/patch-1
Fix link to CONTRIBUTING
2016-07-18 11:12:43 -07:00
Morton Fox
58924538a3 Fix link to CONTRIBUTING 2016-07-16 00:26:50 -04:00
lakedaemon
e750268f0c clang formating cpp code generator and add missing generated classes 2016-07-15 16:08:59 +02:00
lakedaemon
0328dedab5 clangFormating base class 2016-07-15 15:21:09 +02:00
Romain Gilles
9605dc5981 Added OSGi header generation for maven project.
This allow jar generated with maven to be used in OSGi environment.
2016-07-15 14:34:56 +02:00
Romain Gilles
00694d271e Merge branch 'master' of github.com:google/flatbuffers 2016-07-15 14:27:31 +02:00
Wouter van Oortmerssen
b22db6e8eb Merge pull request #3905 from bog-dan-ro/master
Verifier computes the buffersize, useful when streaming multiple flatbuffers
2016-07-14 10:55:22 -07:00
Wouter van Oortmerssen
14e7e8260e Merge pull request #3939 from TGIshib/hex-bug
Fixed bug with negative hex constants (2).
2016-07-14 10:47:34 -07:00
BogDan Vatra
3a1f776132 Verify everything in one shot 2016-07-14 20:16:07 +03:00
BogDan Vatra
4b53762cf2 Verifier computes the buffersize, useful for streaming
Close #3898
2016-07-14 20:15:44 +03:00
Raman
0d56276102 Update test.cpp 2016-07-14 18:51:23 +02:00
Raman
98c7a0c169 Update test.cpp 2016-07-14 10:30:06 +02:00
Raman
676f0712fd Update test.cpp 2016-07-14 10:01:08 +02:00
Wouter van Oortmerssen
7a3f1cf78e Merge pull request #3943 from bog-dan-ro/crash
Don't crash if str is null
2016-07-13 11:17:12 -07:00
BogDan Vatra
49c10bc219 Don't crash if str is null
Is useful especially when we want to create a string from another message string that might be null.
2016-07-13 21:04:26 +03:00
Wouter van Oortmerssen
df9990acf5 Merge pull request #3940 from rushabhy/patch-1
Rename CONTRIBUTING to CONTRIBUTING.md
2016-07-13 10:00:56 -07:00
Rushabh Yapuram
3d7b1a32a3 Rename CONTRIBUTING to CONTRIBUTING.md 2016-07-13 07:57:36 +05:30
Raman
db99c1aa64 Update test.cpp 2016-07-12 19:55:35 +02:00
Raman
f6f88e567e Update idl_parser.cpp 2016-07-12 19:47:53 +02:00
Wouter van Oortmerssen
e527b992f9 Merge pull request #3923 from daksenik/master
Fixed operator++. Added CreateXXX for vector types.
2016-07-11 10:55:17 -07:00
daksenik
aade31b263 Fixed spaces. Removed redundant == nullptr. Vectors pointers made const. 2016-07-11 20:27:38 +03:00
Wouter van Oortmerssen
e733d95e66 Merge pull request #3924 from TGIshib/master
Added --escape-proto-identifiers command-line option.
2016-07-11 09:47:31 -07:00
Wouter van Oortmerssen
14bdce41fe Merge pull request #3931 from jonathantullett/java_public_access
Fix for issue #3922
2016-07-11 09:20:43 -07:00
James Gilles
4a49493e27 js:add @namespace annotation to namespaces 2016-07-11 01:40:38 -04:00
Raman
df5575de17 Update idl_gen_fbs.cpp 2016-07-09 13:33:30 +02:00
Raman
f0b2cc8f6e Update flatc.cpp 2016-07-09 13:32:45 +02:00
Raman
5f2b4e7872 Update idl_parser.cpp 2016-07-09 12:57:07 +02:00
Raman
22697722d9 Update test.cpp 2016-07-09 12:51:06 +02:00
Raman
ffbc93526e Update flatc.cpp 2016-07-09 12:47:14 +02:00
Raman
d9d47a53bd Update idl_gen_fbs.cpp 2016-07-09 12:40:50 +02:00
Raman
71d30d5c02 Update idl.h 2016-07-09 12:28:02 +02:00
daksenik
1661f3a2e8 Added function GenSimpleParam. Tests added. 2016-07-09 13:00:21 +03:00
Jonathan Tullett
d9767b8315 Fix for issue #3922
Also, clean up redundant ';' at end of java classes.
2016-07-09 09:16:26 +01:00
Wouter van Oortmerssen
193a631708 Merge pull request #3929 from Lakedaemon/fixForMake
same fix for general code generator
2016-07-08 14:24:08 -07:00
lakedaemon
a6764b9bf1 same fix for general code generator 2016-07-08 22:54:51 +02:00
Wouter van Oortmerssen
0f5dc152b8 Merge pull request #3928 from Lakedaemon/fixForMake
Fix for make
2016-07-08 13:37:05 -07:00
lakedaemon
8e1aae0fd6 fix missing space (clang format) 2016-07-08 22:02:47 +02:00
lakedaemon
084e5dbc4b fixed initialization of member var for old make (hopefully) 2016-07-08 22:00:15 +02:00
daksenik
dfbda986d7 New CreateXXX (with vectors and strings) calls old CreateXXX (with offsets). 2016-07-08 12:35:57 +03:00
Raman
248432b92d Update idl_gen_fbs.cpp 2016-07-05 23:23:17 +02:00
Raman
f738981ed5 Update idl_gen_fbs.cpp 2016-07-05 22:26:21 +02:00
Raman
4bb6ab3cd5 Update flatc.cpp 2016-07-05 22:24:21 +02:00
Raman
72e8219a65 Update idl_parser.cpp 2016-07-05 22:20:57 +02:00
Romain Gilles
7a955a09f4 Move maven pom.xml from the java folder to the root folder.
This avoid to put the pom.xml file into the source directory. Normally the pom file is in a parent (/parent) folder and it is not mixed with the java source code.
An other thing is: this will make import of the project more easy from a IDE.

The side effect is that the target folder where maven build artifacts will move from the <flatbuffers>/java/target to <flatbuffers>/target therefore the gitignore file has been updated in consequences.
2016-07-05 14:29:12 +02:00
Romain Gilles
b730a74a19 Merge branch 'master' of github.com:google/flatbuffers 2016-07-05 11:40:33 +02:00
Romain Gilles
cc2b04ce1c Revert "Create a maven like project structure for java development. Make it OSGi compliant. Generate the flatbuffers code for testing (example)."
This reverts commit 9875b0e0f8.
2016-07-05 11:38:17 +02:00
Raman
4f8abaaf10 Update flatc.cpp 2016-07-04 22:58:58 +02:00
Raman
5043764247 Update test.cpp 2016-07-04 21:55:44 +02:00
Raman
9fd4d66438 Update flatc.cpp 2016-07-04 21:51:34 +02:00
Raman
aae48e3a9d Update idl.h 2016-07-04 21:41:01 +02:00
Raman
ff57f52b72 Update flatc.cpp 2016-07-04 21:37:50 +02:00
Raman
7d84a4914f Update idl_gen_fbs.cpp 2016-07-04 21:34:42 +02:00
daksenik
c2411e9c8c Fixed operator++. Added CreateXXX for vector types. 2016-07-04 17:37:23 +03:00
daksenik
bf26a0eccc Fixed operator++. Added CreateXXX for vector types. 2016-07-04 16:34:41 +03:00
Wouter van Oortmerssen
68a83eddd4 Merge pull request #3921 from LouisCAD/master
Fixed typo
2016-07-01 10:15:54 -07:00
Wouter van Oortmerssen
b999d49945 Merge pull request #3920 from love-ginger/master
Fix mac build error
2016-07-01 09:48:09 -07:00
Louis Cognault
c94cb6dae9 Fixed typo
is => it
2016-07-01 17:22:36 +02:00
吴凡
5ea2b49f58 Fix some error 2016-07-01 11:17:03 +08:00
吴凡
70deb70b76 Sync from upstream 2016-07-01 11:03:25 +08:00
Wouter van Oortmerssen
48f37f9e0a Added GRPC code generator to flatc.
Also added simple (in-process) test.

Change-Id: I38580d554dd52f590e3396ec4846e07546dcf07d
Tested: on Linux.
2016-06-29 15:51:44 -07:00
Wouter van Oortmerssen
6dff7c68f1 Merge pull request #3916 from YuryBandarchuk16/master
Added new constants
2016-06-27 09:52:57 -07:00
Yury Bandarchuk
ec59dc026f Update Constants.java 2016-06-23 21:30:32 +03:00
Yury Bandarchuk
c97abb1eea Added new constants
Add new constants in Constants.java

All single ints int FlatBufferBuilder.java were replaced by constants
from Constants.java
2016-06-23 19:51:55 +04:00
Wouter van Oortmerssen
2fdafa9a49 Merge pull request #3908 from Lakedaemon/intoTheClass
pulling methods inside the class... so as to share wrapInNamespace later
2016-06-22 18:00:48 -07:00
lakedaemon
f794f97d88 fixing spaces 2016-06-23 00:37:55 +02:00
lakedaemon
03ad8fa4d9 sharing the WrapInNameSpace methods 2016-06-23 00:37:55 +02:00
lakedaemon
43fedfa8ba removed static from wrapInNamespace method 2016-06-23 00:36:33 +02:00
lakedaemon
2f52618c4e removed parser from the method signatures 2016-06-23 00:36:33 +02:00
lakedaemon
a9e21170bc js:pulled methods inside the class 2016-06-23 00:36:33 +02:00
lakedaemon
cb6cc3dfb6 php:removed parser from method signatures 2016-06-23 00:36:33 +02:00
lakedaemon
66f2aac26f php:pulled methods inside the generator 2016-06-23 00:36:33 +02:00
lakedaemon
4a249752ff removed lang signature method 2016-06-23 00:31:27 +02:00
lakedaemon
f0695e0edf removed parser & static from method signatures 2016-06-23 00:28:35 +02:00
lakedaemon
07d4066847 general: moved methods into the class 2016-06-23 00:27:19 +02:00
Wouter van Oortmerssen
57ba8a4d46 Merge branch 'master' of https://github.com/google/flatbuffers 2016-06-20 16:41:40 -07:00
Wouter van Oortmerssen
9e6c5f9f2c JSON Parser allows union type fields to come after unions.
This is useful because many JSON generators will sort the fields,
cause X_type to follow X.

Change-Id: I00ef3ac05418224fc05aee93e6b3b3597e73ffe3
Tested: on Linux.
Bug: 29221752
2016-06-20 16:30:14 -07:00
Wouter van Oortmerssen
3639032d1e Allow unions of table types with the same name but from different namespaces.
Also fixed most codegenerators using the wrong namespace when multiple
namespace were used in a file, with some files not being generated.

Change-Id: Ib42969221239d7244e431cbd667ef69200fc415f
Tested: on Linux.
Bug: 29338474
2016-06-20 11:47:04 -07:00
Robert
6f75ec8490 Merge pull request #3913 from rw/fix-pytest-binary-type
Fix test using compat.binary_types (from March).
2016-06-18 13:02:02 -07:00
rw
fd43d3709e Fix test using compat.binary_types (from March). 2016-06-18 01:12:56 -07:00
Wouter van Oortmerssen
6e177bf03f Merge branch 'master' of https://github.com/google/flatbuffers 2016-06-17 17:44:00 -07:00
Wouter van Oortmerssen
d3ac0bc149 Added conversion operations that can be used inline in JSON.
e.g.: { myfield: cos(rad(180)) } is equivalent to writing { myfield: -1.0 }

Bug: 29338398
Change-Id: I6fc4ef1fd10bda3ba78cba464414dd071a2f50ca
Tested: on Linux.
2016-06-15 14:54:44 -07:00
Wouter van Oortmerssen
afa276288c Added additional convenience overloads to CreateVector().
Bug: 29337887, 29336299
Change-Id: Iad8b3b2263f6cea7ee7e45994369194960df293b
Tested: on Linux.
2016-06-15 14:31:34 -07:00
Dan Ring
4832238708 Add tests for GetRootAs* in Go and Python 2016-06-14 18:41:33 -04:00
Dan Ring
1f8e3c13e6 Emit GetRootAs methods for all types in Go and Python 2016-06-14 18:41:33 -04:00
Wouter van Oortmerssen
5a401aef57 Merge pull request #3897 from Lakedaemon/namespaceWork
Namespace work
2016-06-13 15:16:28 -07:00
Wouter van Oortmerssen
78ecf45527 Merge pull request #3903 from senior7515/master
Add env var for flatc schema compiler cmake module
2016-06-13 13:07:17 -07:00
Alexander Gallego
3ae503a191 Add env var for flatc schema compiler cmake module 2016-06-10 15:39:14 -04:00
Wouter van Oortmerssen
bafd48d96c Merge branch 'master' of https://github.com/google/flatbuffers into fuzzer2 2016-06-08 11:51:49 -07:00
Antoine Descamps
cf7e4b027a Fix typo
"your platform can't handling..." => "your platform can't handle"
2016-06-08 09:32:37 +02:00
lakedaemon
15863c34a0 SetNameSpace algorithm documentation and more meaningful variable names 2016-06-07 14:46:25 +02:00
Romain Gilles
9875b0e0f8 Create a maven like project structure for java development. Make it OSGi compliant. Generate the flatbuffers code for testing (example).
Java developer are mostly comfortable with maven project structure. One one the main concept behind maven is convention. If you follow the maven project convention then your development team will get more effective as they now this project structure and can easily find the production code versus the test code.
 In this pull request I have structured the java project around 2 main parts:
  * the `flatbuffers` project. This project is the api / lib project and contains the test code structure + an example of code generation for testing. This avoid to commit generated code. Pre-configure JUnit for test driven development and make this project OSGi compliant.
  * the `jmh` project. This project aims to provide a placeholder for micro-benchmarking. JMH is a 'de facto' standard for micro benchmarking you can find more details here: http://openjdk.java.net/projects/code-tools/jmh/

For now I didn't move the JavaTest class but it could be a next step with a migration to the JUnit framework.
The only impacts are the move of the class and the project structure => no code change.
2016-06-07 09:05:56 +02:00
Wouter van Oortmerssen
2bdf44a25d Added a way to get mutable tables out of a mutable vector of tables.
Change-Id: I8f9ef1d14f86671ced929c7a159115b1d8510327
Tested: on Linux.
2016-06-06 17:38:21 -07:00
Wouter van Oortmerssen
4ffc881fb6 Fixed LoadFile crashing on directory arguments.
Change-Id: I737f6fd0bb1302ab7cfa6ab8b06108e221ebb63c
Tested: on Linux.
2016-06-06 11:34:31 -07:00
Wouter van Oortmerssen
e92ae5199d Fixed compile errors on Windows 2016-06-02 14:55:35 -07:00
lakedaemon
a3a2bf890f Better C++ namespace management 2016-06-02 23:11:51 +02:00
lakedaemon
a9194c4c68 cpp generator : pulling all methods inside the class 2016-06-02 21:56:27 +02:00
Wouter van Oortmerssen
ca32eb77f3 Merge pull request #3885 from Lakedaemon/shareWarningAndTwoMethods
Share warning and two methods
2016-06-02 11:35:41 -07:00
Wouter van Oortmerssen
886441df98 Merge pull request #3870 from martinus/master
Added helpers to access objects while creating the flatbuffer.
2016-06-02 11:26:16 -07:00
Wouter van Oortmerssen
e02ceca54b Merge pull request #3891 from bog-dan-ro/master
More bit fields patches
2016-06-02 11:24:48 -07:00
Martin Ankerl
b3c35750c2 renamed functions
More descriptive name, show that it's really just a temporary object.
2016-06-01 13:13:00 +02:00
BogDan Vatra
3e52fecd1e Don't generate MIN & MAX enum values if "--no-prefix" is used.
Close #3892
2016-06-01 10:23:44 +03:00
BogDan Vatra
cccd7003ed MIN & MAX are useless for bit_flags
Instead we need NONE (0) and ANY (all orred values), if the user didn't
already defined them
2016-06-01 10:15:41 +03:00
BogDan Vatra
038ea7c1d3 Add ! operator 2016-06-01 10:05:27 +03:00
BogDan Vatra
0b0cf58f24 We already know the underlying_type.
We just need to pass it to DEFINE_BITMASK_OPERATORS macro
2016-06-01 10:04:55 +03:00
Wouter van Oortmerssen
7d1f372ba6 Merge pull request #3888 from bog-dan-ro/master
Define bit mask operators for scoped enums bitfields
2016-05-31 11:59:51 -07:00
Wouter van Oortmerssen
25e4ad19f6 Merge pull request #3889 from PSPDFKit-labs/james/avoid-msvc-align-error
MSVC doesn't allow alignment on function params.
2016-05-31 11:33:10 -07:00
BogDan Vatra
7dfe8e726b Define bit mask operators for scoped enums bitfields
Close #3887
2016-05-30 14:04:37 +03:00
lakedaemon
61b101d442 sharing namespace_dir and the namespace string methods 2016-05-28 20:59:22 +02:00
lakedaemon
cd1493b082 sharing the Flatbuffers warning 2016-05-26 15:26:58 +02:00
Wouter van Oortmerssen
a98bff3ea1 Add simple libfuzzer based test.
This tests the verifier and the parser.

Tested: on Linux.
Bug: 27230459
Change-Id: I3417faba9385dc941199c57a08d8a50c2faec1aa
2016-05-25 17:25:40 -07:00
Wouter van Oortmerssen
06eb6e94e3 Merge pull request #3880 from Lakedaemon/IsEverythingGenerated
shared method that exits early if everything is generated
2016-05-25 10:38:56 -07:00
Lakedaemon
4a8801da34 shared method that exits early if everything is generated 2016-05-25 15:15:56 +02:00
James Swift
b1e8be27a9 MSVC doesn't allow alignment on function params. This prevents the copy and thus avoids this issue https://msdn.microsoft.com/en-us/library/373ak2y1.aspx 2016-05-24 17:16:03 +02:00
Wouter van Oortmerssen
b922a3c952 Merge "Uncomment the corpus attribute since b/28762769 is fixed, add more items to the corpus (taken from the ClusterFuzz-generated corpus)." into ub-games-master 2016-05-23 23:58:50 +00:00
Wouter van Oortmerssen
b52826e7cc Merge "Add a fuzzer for flatbuffers, derived from the one used in Chromium: https://code.google.com/p/chromium/codesearch#chromium/src/testing/libfuzzer/fuzzers/flatbuffers_verifier_fuzzer.cc" into ub-games-master 2016-05-23 23:58:27 +00:00
Wouter van Oortmerssen
0ef72db7bf Merge pull request #3865 from bhamiltoncx/surrogate-pairs
Handle \u-escaped surrogate pairs correctly in IDL parser
2016-05-23 16:51:07 -07:00
Stewart Miles
505d0f2288 Merge "Removed reference to deprecated NDK toolchain version." into ub-games-master 2016-05-23 23:49:56 +00:00
Ben Gertzfield
6704b19db6 Handle \u-escaped surrogate pairs correctly in IDL parser 2016-05-23 16:38:55 -07:00
Wouter van Oortmerssen
64b91da9cf Uncomment the corpus attribute since b/28762769 is fixed,
add more items to the corpus (taken from the ClusterFuzz-generated corpus).

(mirrored from cl 122690857)

Change-Id: I98c7672169a9a27fe18bedae8501e6fb85a0681d
2016-05-23 16:37:57 -07:00
Wouter van Oortmerssen
fe9787e58d Add a fuzzer for flatbuffers, derived from the one used in Chromium:
https://code.google.com/p/chromium/codesearch#chromium/src/testing/libfuzzer/fuzzers/flatbuffers_verifier_fuzzer.cc

(mirrored from cl 122676317)

Change-Id: I0074af435cf37f5e6368b040563c3733d9e02345
2016-05-23 16:35:20 -07:00
Stewart Miles
d06e571b31 Removed reference to deprecated NDK toolchain version.
Change-Id: I8d39a66ca5642427619c60f349fa78917aec2455
2016-05-23 16:27:35 -07:00
Wouter van Oortmerssen
208c15f29d Merge branch 'master' of https://github.com/google/flatbuffers 2016-05-23 14:56:47 -07:00
Wouter van Oortmerssen
a82dbb6e01 Fixed Google Groups link in documentation.
Change-Id: I64307ccd0a6f23a7c3860d602813e637415e7c91
2016-05-23 14:08:21 -07:00
Wouter van Oortmerssen
a42a99029f Made .sh files all have same comment formatting.
Change-Id: Ie7cc268a8823aec1d06c8b7cbef54068d832de3a
2016-05-23 14:08:21 -07:00
Wouter van Oortmerssen
0c7b700895 Merge pull request #3878 from pjulien/no_alloc_on_cb
Remove Remaining FBB#createString Allocation
2016-05-23 13:55:21 -07:00
pjulien
1aa3ee2170 Clarify documentation based on review comments 2016-05-23 16:47:41 -04:00
Wouter van Oortmerssen
8c0d56d55a Removed BOM marker from some files.
Also removed some trailing whitespace.

Change-Id: I40bf4f776ca4d467b7ee6f2c9a7500c13700f9d5
2016-05-23 12:24:44 -07:00
Wouter van Oortmerssen
c41a0453c1 Merge branch 'master' of https://github.com/google/flatbuffers 2016-05-23 10:59:47 -07:00
Wouter van Oortmerssen
1a161a8333 Added missing licenses to some sh/cs/py files.
Bug: https://github.com/google/flatbuffers/issues/3872
Change-Id: I5d551168e9bc925e867e5e4ddf5d809418fd44eb
Tested: on Linux.
2016-05-23 09:51:41 -07:00
pjulien
9d8ae1b0c3 If the user passes in a {{CharBuffer}} himser, reward him by
eliminating the last remaining allocation in string creation
2016-05-21 09:19:43 -04:00
Wouter van Oortmerssen
2de558057d Merge pull request #3867 from dreifachstein/master
Use the build output flatc to compile test schemas by default.
2016-05-20 13:19:52 -07:00
Wouter van Oortmerssen
0756caa42e Merge pull request #3866 from bhamiltoncx/fix-undefined-bit-shift
Fix undefined behavior when CheckBitsFit left-shifts 64-bit value by 64 bits
2016-05-20 13:10:52 -07:00
Wouter van Oortmerssen
99c1ddc792 Merge branch 'master' of https://github.com/google/flatbuffers 2016-05-18 18:01:17 -07:00
Wouter van Oortmerssen
69eef0a0ec Fixes verifier not catching odd vtable sizes.
Bug: 28762769
Change-Id: Iec370482f67c4585e97dd5175c1a4258ddba47fe
Tested: on Linux.
2016-05-18 18:00:25 -07:00
Wouter van Oortmerssen
42bd6447c0 Merge pull request #3877 from ozkuran/patch-1
Fixed Library Location in CppUsage.md
2016-05-18 10:33:55 -07:00
Mahmut Ali ÖZKURAN
747a8c628e Fixed Library Location in CppUsage.md
Fixed Library Location 
"https://github.com/google/flatbuffers/tree/master/include/flatbuffers"
in CppUsage.md
2016-05-18 12:02:32 +03:00
Martin Ankerl
023fec627e Added helpers to access objects while creating the flatbuffer.
GetObject and GetMutableObject are similar to GetRoot and GetMutableRoot,
and can be useful when wanting to access data that has just been created.
Unfortunately there is a danger in using these methods, as it is possible
that the buffer reallocates which will invalidate the pointers.
2016-05-03 17:20:14 +02:00
Xiaolei Yu
3a8bc309e2 Use the build output flatc to compile test schemas by default. 2016-05-01 11:15:53 +08:00
Ben Gertzfield
3400727fff Fix undefined behavior in CheckBitsFit bit-shift on size_t 2016-04-29 15:15:09 -07:00
Robert
77742a3fba Merge pull request #3806 from mediagraph/fix-create-string
Fix CreateString with already-encoded string or bytearray in Python 2.7.
2016-04-27 20:31:55 -07:00
Wouter van Oortmerssen
7cce55d8f0 Merge pull request #3854 from pjulien/3853
Fix for #3853
2016-04-27 18:12:15 -07:00
Wouter van Oortmerssen
933c195e51 Merge pull request #3843 from Lakedaemon/refactoring
Transition 1 (nice diffs) Go, C++ and General generators with class
2016-04-27 13:59:16 -07:00
Wouter van Oortmerssen
d0898fd0c8 Merge pull request #3863 from pjulien/cseq
Can now use ``CharSequence`` of ``String``.  Works with
2016-04-27 13:50:04 -07:00
Lakedaemon
6765c19d45 memory leak fix + php/js/python transition to class based generator 2016-04-26 20:36:43 +02:00
pjulien
599f5e3915 Can now use `CharSequence of String`. Works with
1. [AsciiString]
(http://netty.io/4.1/api/io/netty/util/AsciiString.html)
2. [CharBuffer]
(https://docs.oracle.com/javase/8/docs/api/java/nio/CharBuffer.html)
3. [StringBuilder]
(https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)
2016-04-25 22:07:57 -04:00
Robert
ba7204a7b7 Merge pull request #3859 from rw/go-zero-alloc-strings
Go: Fix heap allocation when reading a string.
2016-04-23 18:38:03 -07:00
rw
e8ac0f293e Fix heap allocation when reading a string. 2016-04-23 12:32:43 -07:00
Wouter van Oortmerssen
a0d1161feb Merge pull request #3850 from pjulien/3849
Fix for #3849
2016-04-22 11:42:14 -07:00
Wouter van Oortmerssen
828b2680c0 Merge branch 'master' of https://github.com/google/flatbuffers 2016-04-22 11:35:10 -07:00
Wouter van Oortmerssen
c17cf022ea Fixed a verifier check that didn't return from its parent.
Change-Id: I1aef5fdba72de0c3bb8276c9f50fffa494f26e29
Tested: on Linux.
2016-04-22 11:31:35 -07:00
Wouter van Oortmerssen
f6330ab8f1 Fixed SkipByteOrderMark advancing cursor_ too early.
Change-Id: Ie60f01d935ca6b4aa6ce0eab7598602ac0758342
Tested: on Linux.
2016-04-22 11:27:35 -07:00
pjulien
6908826f95 Fix for #3849
This avoids the following allocations over repeated use:

- A ``CharsetEncoder``
- A byte array to contain the contents of the string
- A wrapper, via ``ByteBuffer#wrap``, for the previously mentioned byte
  array

This also removes a copy of the temporary byte array.  This extra copy
is needed because ``String#getBytes`` returns a byte array and its
length must match the exact size of the contents.

This implementation requires that the builder retain a ``ByteBuffer``
and ``CharEncoder``.  This is considered slower only for users that
will only allocate a single string in their buffers or none at all.

The improvement is especially potent if the builder is constantly reused
by its caller.  This also eliminates the penalty for users that do not
use strings at all since the cost of allocating these fields is
now amortized.

The only allocation left in this code is a ``CharBuffer`` wrapper.  It's
possible to eliminate this allocation using an additional copy but need
further profiling to see which is the bigger problem.
2016-04-21 20:20:14 -04:00
Wouter van Oortmerssen
fd542c71e3 Fixed float suffix not being added on implicit float defaults.
Change-Id: I8dcbb5e93836356511d411ef86452babd3dd3c0b
Tested: on Linux.
2016-04-20 12:06:32 -07:00
pjulien
9fb87f813b size the allocation to the required bytes 2016-04-18 21:43:28 -04:00
pjulien
b0146b3d9a fix file permission 2016-04-18 20:19:56 -04:00
pjulien
286587d151 Fix for #3853
Removes the following allocations:
- ``CharsetDecoder`` is reused between calls
- ``CharBuffer#wrap`` removed in favor of heap
  based char buffer that is reused
- Temporary ``char[]``, an intermediate copy inside ``StringCoding``
- Another ``char[]``, this is needed because ``StringCoding`` uses
  a ``CharBuffer`` internally but returns a ``char[]``.  Extra
  characters need to be trimmed so this means yet another allocation
- Yet another ``char[]`` directly from ``__string`` for non-heap
  based buffers

Removes the following copies
- No copy is performed to trim the allocation since a ``CharBuffer``
  is used directly
- For non-heap based byte buffers, removes the copy that was
  previously done in the __string function

This does need to get the TLS entry which implies at least some
contention on the thread object table and a fence.
2016-04-18 20:04:00 -04:00
Wouter van Oortmerssen
6f751d5d26 Merge pull request #3848 from pjulien/3847
Fix for 3847
2016-04-18 15:54:34 -07:00
Wouter van Oortmerssen
4d7890c2c9 Fixed whole-number float default values missing a .0 suffix.
A previous commit that added "f" for C++/Java/C# would break
on gcc of constants like 3f, which are now output as 3.0f

Tested: on Linux

Change-Id: If9cabbe3c6d6948a5050b8b123bda9c06e181f52
2016-04-18 11:50:46 -07:00
pjulien
fdfaf23361 3847 2016-04-16 20:09:28 -04:00
Lakedaemon
38597160f2 Enforcing the google C++ style guide 2016-04-15 13:20:26 +02:00
Wouter van Oortmerssen
791c83aa7e Merge branch 'master' of https://github.com/google/flatbuffers 2016-04-13 17:44:23 -07:00
Wouter van Oortmerssen
29d957ed5e Fixed missing "f" on float default values in C++/Java/C#
Bug: 28145201
Change-Id: I5a1818c40c2f4fbd00cfec3362040407976f7a39
Tested: on Linux.
2016-04-13 17:29:03 -07:00
Wouter van Oortmerssen
8d8b7c19b7 Merge pull request #3844 from Nnamdi/CreateUninitializedVector_fix
Stop CreateUninitializedVector returning a pointer to invalid memory.
2016-04-13 16:14:11 -07:00
Nnamdi
039ab48b7a Stop CreateUninitializedVector returning a pointer to invalid memory.
CreateUninitializedVector was performing the following actions:
    1. call StartVector.
    2. call make_space, and set buf to point to the reserved space.
    3. call EndVector.

The problem is that a call to EndVector can ultimately call make_space, which
if the buffer is full, will cause a reallocation, invalidating the value stored
in buf.  So setting buf needs to be delayed until after EndVector.

The following code, when run under valgrind shows a write to free'd memory before
the change, but no such error after:

int main()
{
    flatbuffers::FlatBufferBuilder fbb(128);
    char *buf = nullptr;
    fbb.CreateUninitializedVector(128, &buf);
    *buf = 0;
}
2016-04-13 23:04:27 +01:00
Lakedaemon
8a64afabfd Transition 1 (with nice diffs) Go, Cpp and General code generators with class 2016-04-13 23:21:18 +02:00
Wouter van Oortmerssen
4a04bac250 Fixed struct -> class pre-declaration error.
Change-Id: I3730a6823d603982c4250d514e827e3f93d1f81e
Tested: on Linux.
2016-04-13 12:02:22 -07:00
Wouter van Oortmerssen
72fc45aa6a Made user-defined attributes available in the reflection data.
Tested: on Linux.

Bug: 27923233
Change-Id: Ic16675650e4a8e138c163f1e2131a3aad7008ada
2016-04-11 17:36:56 -07:00
Wouter van Oortmerssen
9f2b05df1b Merge branch 'master' of https://github.com/google/flatbuffers 2016-04-11 13:48:57 -07:00
Wouter van Oortmerssen
83dc5ed4a7 Fixed JSON integers as strings not being parsed correctly.
Change-Id: If34aef46ef619e06de799cff14948b02e98da86d
Tested: on Linux.
2016-04-11 11:08:09 -07:00
Wouter van Oortmerssen
e597ad8f0f Fixed pre-declarations of included types in generated code.
This was harmless, but unnecessary.

Change-Id: I1365a725e254d4ebbda081110a50277cb5118323
Tested: on Linux.
2016-04-11 11:05:42 -07:00
Wouter van Oortmerssen
3ea5446680 Merge pull request #3789 from Chippiewill/master
Allow builds on platforms with unsigned chars by default
2016-04-08 11:32:16 -07:00
Wouter van Oortmerssen
8b18e487bd Merge pull request #3839 from klapek/net/bytebuffer-assert-optimization
Remove unnecessary condition in AssertOffsetAndLength.
2016-04-08 11:18:58 -07:00
Wojciech Jaszczak
c837d29eab Remove unnecessary condition in AssertOffsetAndLength.
Condition is already checked and covered in the following condition, the second one was excess.

Signed-off-by: Wojciech Jaszczak <jaszczakw@gmail.com>
2016-04-08 19:56:02 +02:00
Wouter van Oortmerssen
ec1daef858 Merge pull request #3832 from mikkelfj/c_docs
Documentation for C bindings
2016-04-08 10:54:27 -07:00
Mikkel Fahnøe Jørgensen
7d396bc2e7 Update C documentation with supported MSVC versions, and other minor updates. 2016-04-07 18:52:00 +02:00
Wouter van Oortmerssen
8128df7655 Added missing util.cpp to VS project 2016-04-04 17:09:07 -07:00
Wouter van Oortmerssen
cfaa7782b6 Adding missing util.cpp to Xcode project 2016-04-04 17:07:05 -07:00
Wouter van Oortmerssen
5e3f9d5175 Merge branch 'master' of https://github.com/google/flatbuffers 2016-04-04 16:55:25 -07:00
Wouter van Oortmerssen
cdc5d5b18d Merge pull request #3836 from tkelman/cygwinbuild
Fix build on Cygwin
2016-04-04 15:38:32 -07:00
Wouter van Oortmerssen
e98b1912b3 add setloadfile and setfileexists functions to flatbuffers
to allow for custom file loaders. The targeted use case is android runtime.

(from CL 116980408)

Change-Id: I8785c0acf714fab41d8f6fc9f1c52875423b8f5b
2016-04-04 13:03:22 -07:00
Wouter van Oortmerssen
c8c0082413 Fix flatbuffers conversion warnings.
(from CL 116785833)

Change-Id: I0fb0e1318fd70cba51e229a93f535c6639bbb331
2016-04-04 13:03:22 -07:00
Wouter van Oortmerssen
1c1d079113 Fix flatc build for msvc.
(from CL 117010760)

Change-Id: I0ee77cf87d0cb00b94887356745b85423b1375a6
2016-04-04 13:03:22 -07:00
Wouter van Oortmerssen
7523e4ad49 Fixed potential integer overflow in the Verifier.
This overflow could allow malformed FlatBuffers to pass the verifier.

Change-Id: Ia993299a761b00b93e53e8aff2689b631755763c
Tested: on Linux.
Bug: 27903580
2016-04-04 13:03:22 -07:00
Wouter van Oortmerssen
f4a5c9de50 Fixed VS assignment constructor warning. 2016-04-04 13:00:48 -07:00
Mikkel Fahnøe Jørgensen
1db9783bfc Remove details on FlatCC builds that would easily become outdated 2016-04-04 16:33:20 +02:00
Mikkel Fahnøe Jørgensen
5b38134431 Document FlatCC support for Windows 2016-04-03 21:37:57 +02:00
Tony Kelman
4c16038e72 Fix build on Cygwin
use -std=gnu++11 instead of c++0x on cygwin to avoid
error: realpath was not declared in this scope

ref http://www.cygwin.com/ml/cygwin/2016-03/msg00005.html
2016-04-01 21:42:23 -07:00
Wouter van Oortmerssen
2f7f50b8cb Merge pull request #3816 from armen/master
Implement __vector_as_bytes and methods to get [ubyte] efficiently
2016-03-30 14:04:36 -07:00
Wouter van Oortmerssen
a1633055f7 Merge pull request #3834 from Nnamdi/gen_name_strings
Added --gen-name-strings command line option.
2016-03-30 13:14:49 -07:00
Nnamdi
35f6bb5060 Added --gen-name-strings command line option.
To support the use case described in issue google/flatbuffers#3826, a new command line option --gen-name-strings
has been added, which will cause a static GetFullyQualifiedName function to be added
to the C++ output for tables/structs.
2016-03-29 22:25:04 +01:00
Armen Baghumian
28a3c939e7 Implement __vector_as_bytes and methods to get [ubyte] efficiently
Currently in order to get a value type of [ubyte] in PHP, iteration is
necessary which is not efficient. Helper __vector_as_bytes has been
implemented in order to return the byte arrays in PHP efficiently.

Appropriate methods also been added to use aforementioned method to return
the byte array. (e.g. get*Bytes()).

The reason the methods are named get*Bytes() and not for instance
get*ByteArray() is the fact that PHP doesn't support byte arrays and the
binary safe string implementation in PHP is used to simulate byte arrays
and since there is chance for PHP users to confuse this with PHP arrays
the name get*Bytes() has been chosen.

In the future __vector_as_bytebuffer() method can also be implemented to
return PHP implementation of ByteBuffer.
2016-03-29 14:56:09 +11:00
Mikkel Fahnøe Jørgensen
7d9779fc67 Move some C specifics out of tutorial and clarify platform support 2016-03-28 22:52:10 +02:00
Mikkel Fahnøe Jørgensen
9b8c91c90b Add C support in README, minor updates in other C doc 2016-03-26 09:22:56 +01:00
Mikkel Fahnøe Jørgensen
47d4b46950 Documentation for C bindings 2016-03-26 00:28:31 +01:00
Wouter van Oortmerssen
a649cb7db5 Merge pull request #3822 from cage433/tutorial-java-type-error
Tutorial's Java example uses incorrect types
2016-03-23 12:45:24 -07:00
Alex McGuire
68c69b3717 Tutorial's Java example uses incorrect types
`FlatBufferBuilder.createString` returns an int offset, not a string
2016-03-20 12:59:39 +00:00
Will Gardner
ce4d3316d3 Allow builds on platforms with unsigned chars by default
Certain architectures, such as ARM, use unsigned chars by default
so require the `-fsigned-char` for certain value comparisons to
make sense and in order to compile.
2016-03-14 16:19:38 +00:00
Wouter van Oortmerssen
e6b79f0002 Added stream & idempotent annotations for RPCs.
Change-Id: Ia8651c1051808fdda0dc0ba52ec991777f868e88
Tested: on Linux.
2016-03-09 15:03:05 -08:00
Wouter van Oortmerssen
1a63eb46bb Added RPC declarations to the schema parser.
This is the first step in RPC support. Actual code generation
to follow.

Change-Id: I96c40fec3db671d100dd9eb509a71c5cbe55bfb2
Tested: on Linux.
Bug: 20122696
2016-03-09 13:47:40 -08:00
Wouter van Oortmerssen
91c27148c0 Merge pull request #3805 from artiom/patch-1
Update google user group link
2016-03-09 09:58:51 -08:00
Alex Kerfoot
1e7310e6cd Fix CreateString with already-encoded string or bytearray in Python 2.7.
There was no way to pass an already-encoded string to 
`builder.CreateString` in Python 2.7:

- Passing a `bytearray` raised a TypeError because `bytearray` was not
  recognized as an instance of `compat.binary_type`.
- Passing a utf-8 encoded `str` would cause the string to be
  double-encoded, because `compat.string_types = (basestring,)` and
  `basestring` is the base class of `str` and `unicode`, so the logic
  would never reach the `elif isinstance(s, compat.binary_type)` case.
- Converting a utf-8 encoded bytearray to `bytes` like
  `builder.CreateString(bytes(encoded_string))` does not work because
  in Python 2.7, bytes is just an alias for `str` so it behaves as
  above.

This change allows either `bytes` or `bytearray` as an already-encoded
string to be passed to `CreateString` in versions of Python that support
`bytearray`, and falls back to `str` in older versions.

In Python 2, it restricts unencoded string types to `unicode`, so `str`
can be used as an encoded, binary representaiton.
2016-03-08 16:05:02 -08:00
artiom
b49a7d146d Update google user group link
Original link returns 404.
2016-03-08 23:57:12 +00:00
Wouter van Oortmerssen
fbc8af40e3 Allow JSON numeric fields to be specified by a numeric data in a string.
Change-Id: I6a3fae1e71434a7384edc39b8602bd84a0432edb
Tested: on Linux.
Bug: 24140897
2016-03-07 17:22:51 -08:00
Wouter van Oortmerssen
709e720839 Merge branch 'master' of https://github.com/google/flatbuffers 2016-03-07 15:04:18 -08:00
Wouter van Oortmerssen
3cd9181ef8 Fixed Java pom.xml file still having wrong version number.
Change-Id: I95bc50ecd3b49d91fb81477a8818e3c1f253ff77
2016-03-07 14:15:01 -08:00
Wouter van Oortmerssen
81e4d3c6c3 Moved the build dir to build_ide to not clash with BUILD files.
Change-Id: I9576e130142acc697fadbfb6aacfd5969f25866a
Tested: on Windows.
Bug: 27426239
2016-03-07 12:58:36 -08:00
Wouter van Oortmerssen
958fc6ec49 Added support for easy string pooling.
Change-Id: I790cf681c1bffff800d77afb0e2f908d1c827679
Tested: on Linux.
Bug: 26186542
2016-03-07 12:58:36 -08:00
Wouter van Oortmerssen
19afcdc704 Clarified how to test for the presence of fields.
This is FAQ on the issue tracker.

Bug: 26863353
Change-Id: I227e10a5c0134dbe7fd7f59e64cd57a0752c568e
2016-03-07 12:58:36 -08:00
Wouter van Oortmerssen
51d48bd953 Merge pull request #3793 from yurivict/master
Fixed missing -lc++abi on FreeBSD.
2016-03-02 17:46:30 -08:00
Yuri
26f15bcd77 Fixed missing -lc++abi on FreeBSD. 2016-03-02 17:15:42 -08:00
Wouter van Oortmerssen
412b8d2c80 Merge pull request #3788 from franc0is/layout-typo
Fix small typo in documentation navigation
2016-02-26 10:14:39 -08:00
Wouter van Oortmerssen
617fedf349 Merge pull request #3765 from Mischanix/js-typed-arrays
Javascript helper to get typed array views
2016-02-26 09:51:50 -08:00
Wouter van Oortmerssen
59caa536ed Merge pull request #3784 from evanw/fix-for-3773
Fix #3773: Generated JS now avoids the flatbuffers object
2016-02-26 09:37:55 -08:00
François Baldassari
3d5f7f64f8 Remove erroneous extra character 2016-02-26 09:03:22 -08:00
François Baldassari
66126cc32d Fix typo in documentation navigation 2016-02-26 09:00:46 -08:00
Evan Wallace
31b30335f6 Fix #3773: Generated JS now avoids the flatbuffers object 2016-02-25 01:06:16 -08:00
Wouter van Oortmerssen
959866b848 Merge pull request #3776 from ncpenke/fix-bug-skipping-unknown-fields
Fix bug skipping unknown fields
2016-02-22 13:38:14 -08:00
Nalinichandra Penke
cbab26673b Fix #3775: Skip unknown field names if they're quoted 2016-02-22 14:34:20 -06:00
ncpenke
1cf5e3f751 Merge pull request #4 from google/master
Catchup
2016-02-22 14:34:05 -06:00
Wouter van Oortmerssen
9a76ce8a65 Disabled broken biicode builds on Travis for the moment.
Change-Id: I834e6da091ea704a3fe599a5b99f338d29cd3bf1
2016-02-22 11:33:14 -08:00
Wouter van Oortmerssen
574404e2ee Merge branch 'master' of https://github.com/google/flatbuffers 2016-02-17 13:29:34 -08:00
Wouter van Oortmerssen
20c0082ee5 Fixed namespace code generation for C++
The code generator was assuming all declarations for the current
file sit in the same namepace. Now uses the "on demand" namespace
switching we had for the forward declarations.

Also fixed a bug related to namespace lookup.

Change-Id: Ib54a3efbc752cbb9590302fa0707c0c73448db3d
Tested: on Linux.
2016-02-17 11:26:38 -08:00
Robert Nix
9d92aeb182 Add helper for javascript typed arrays
For scalar vector fields, emit an Array helper that
returns a typed array view of the underlying bytes buffer.
2016-02-12 12:41:28 -06:00
Robert Nix
2f5d7ae645 Fix javascript unicode test
The generated buffer should be tested for semantic equivalence
to the correct buffer, instead of being tested for bytewise
equality.
2016-02-12 12:31:25 -06:00
Wouter van Oortmerssen
d2bc73bbbe Merge pull request #3761 from msb-at-yahoo/fix-gcc-4.4-build
fix gcc-4.4 build: -Werror=unused-result is not supported
2016-02-10 16:13:59 -08:00
maurice barnum
697cad7027 fix gcc-4.4 build: -Werror=unused-result is not supported 2016-02-11 00:05:04 +00:00
Wouter van Oortmerssen
472fb12273 Merge branch 'master' of https://github.com/google/flatbuffers 2016-02-10 13:51:10 -08:00
Wouter van Oortmerssen
d779308b3e Fixed enum declaration values being parsed as int.
This caused values in the uint range to be made negative values.

Change-Id: Ia4284747f48508b589c034ff3aae0d141e96eb3c
Tested: on Linux.
2016-02-10 11:25:31 -08:00
Wouter van Oortmerssen
a03f3287b3 Merge pull request #3760 from rw/python-remove-ctypes-dependency
Python: remove ctypes dependency in runtime library.
2016-02-08 14:35:45 -08:00
rw
a88cf317fd Python: remove ctypes dependency in runtime library. 2016-02-08 14:15:02 -08:00
Wouter van Oortmerssen
b611dc4b99 Fixed implicit dereference in flatc.
Change-Id: If2e62a325b47399561b4c20d2def55ede4831d19
Tested: on Linux.
2015-11-30 17:53:00 -08:00
Wouter van Oortmerssen
5f19ea5e45 Merge pull request #610 from iperry/master
Link clang builds against libc++abi on Linux
2015-11-30 16:56:08 -08:00
Perry Hung
e4abeef65c Link clang builds against libc++abi on Linux
Simply running clang with -stdlib=libc++ requires a manual link against
libc++abi on Linux. This is documented in the libc++ documentation:
    http://libcxx.llvm.org/

Tested on Arch Linux, using clang 3.7.0 RELEASE.

Signed-off-by: Perry Hung <iperry@gmail.com>
2015-11-30 19:48:49 -05:00
Wouter van Oortmerssen
ac49eda053 Multiple schemas parsed by flatc are now parsed independently.
It used to be such that later schemas could depend on earlier
schemas. This was a convenience from days before include files
were implemented. Nowadays they cause subtle bugs rather than being
useful, so this functionality has been removed.

You now need to explicitly include files you depend upon.

Change-Id: Id8292c3c621fc38fbd796da2d2cbdd63efc230d1
Tested: on Linux.
2015-11-30 16:48:31 -08:00
Wouter van Oortmerssen
1fa803d187 C++ generated code now has constants for vtable offsets.
Besides making the generated code looking a lot more readable,
it also allows you to use these offsets in calls to
Table::CheckField, to see if a field is present in a table.

Change-Id: I1b4cc350c4f27c4e474c31add40c701ef4ae63b2
Tested: On Linux.
2015-11-30 14:27:47 -08:00
Wouter van Oortmerssen
6d1ff8a525 Merge branch 'master' of https://github.com/google/flatbuffers 2015-11-30 13:55:34 -08:00
Wouter van Oortmerssen
59dc29a19a Made C++ generated code use "bool" instead of uint8_t wire type.
Change-Id: I5756d15a758429ca67456264842017063d1f755e
Tested: on Linux.
2015-11-30 13:54:24 -08:00
Wouter van Oortmerssen
6db667b6b1 Merge pull request #602 from chrisstaite/master
Fix flatbuffers::String to std::string and import of Windows.h
2015-11-30 12:21:41 -08:00
Wouter van Oortmerssen
07da3fc216 Allow vectors to be aligned beyond their natural type.
Change-Id: I09ade6b688a6b97d65fd832558917225d86c9118
2015-11-30 11:50:09 -08:00
Wouter van Oortmerssen
c5835b896c Java builder now checks if buffer was finished upon access.
Also checks for nesting of objects in vector construction.

This avoids common errors in FlatBuffer construction.

Change-Id: I5507c5d767684e20e94883a92448f05acefba4d6
Tested: on Linux.
2015-11-30 11:25:21 -08:00
Chris
345e8ca804 Fix use of std::max when Windows.h is imported. 2015-11-27 20:06:41 +00:00
Chris
9202f0cf09 Return the full string when requested from a flatbuffers::String, even if it contains a NULL byte. 2015-11-27 20:05:48 +00:00
Wouter van Oortmerssen
d10f9a6abc Added long form options for all generators (--cpp etc.)
Short-form versions are still supported, but are deprecated.

Change-Id: I15f70ca8d69ba5790368205caa9603b65e1b7fff
Tested: on Linux.
2015-11-25 17:26:34 -08:00
Wouter van Oortmerssen
ec0c0b14ca Made generated C++ code respect gcc -Werror=shadow.
Change-Id: I17de0bcc462770124227a9967e2aab620467f6eb
Tested: on Linux.
2015-11-25 16:48:28 -08:00
Wouter van Oortmerssen
6267f8c6c0 Fixed crash related to flatc parsing duplicate input files.
Thanks @Chaosvex for reporting.

Change-Id: I73f60ab0bf875a3e0849eaec5f42f6d036881094
Tested: on Linux.
2015-11-25 15:50:30 -08:00
205 changed files with 11062 additions and 4847 deletions

7
.gitignore vendored
View File

@@ -40,6 +40,8 @@ flatsamplebinary
flatsamplebinary.exe
flatsampletext
flatsampletext.exe
grpctest
grpctest.exe
snapshot.sh
tests/go_gen
tests/monsterdata_java_wire.mon
@@ -55,9 +57,10 @@ build/Xcode/FlatBuffers.xcodeproj/xcuserdata/**
FlatBuffers.xcodeproj/
java/.idea
java/*.iml
java/target
**/*.pyc
.idea
*.iml
target
**/*.pyc
build/VS2010/FlatBuffers.sdf
build/VS2010/FlatBuffers.opensdf
build/VS2010/ipch/**/*.ipch

View File

@@ -12,8 +12,9 @@ env:
matrix:
- BUILD_TYPE=Debug BIICODE=false
- BUILD_TYPE=Release BIICODE=false
- BUILD_TYPE=Release BIICODE=true
- BUILD_TYPE=Debug BIICODE=true
# biicode .deb files no longer available.
# - BUILD_TYPE=Release BIICODE=true
# - BUILD_TYPE=Debug BIICODE=true
global:
- GCC_VERSION="4.9"

View File

@@ -63,6 +63,13 @@ function(build_flatbuffers flatbuffers_schemas
set(FLATC_TARGET flatc)
set(FLATC flatc)
endif()
set(FLATC_SCHEMA_ARGS --gen-mutable)
if(FLATBUFFERS_FLATC_SCHEMA_EXTRA_ARGS)
set(FLATC_SCHEMA_ARGS
${FLATBUFFERS_FLATC_SCHEMA_EXTRA_ARGS}
${FLATC_SCHEMA_ARGS}
)
endif()
set(schema_glob "*.fbs")
# Generate the include files parameters.
@@ -86,7 +93,7 @@ function(build_flatbuffers flatbuffers_schemas
set(generated_include ${generated_includes_dir}/${filename}_generated.h)
add_custom_command(
OUTPUT ${generated_include}
COMMAND ${FLATC} --gen-mutable
COMMAND ${FLATC} ${FLATC_SCHEMA_ARGS}
-o ${generated_includes_dir}
${include_params}
-c ${schema}

View File

@@ -6,9 +6,12 @@ project(FlatBuffers)
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_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)
option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF)
if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS)
message(WARNING
@@ -17,6 +20,7 @@ if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS)
endif()
set(FlatBuffers_Library_SRCS
include/flatbuffers/code_generators.h
include/flatbuffers/flatbuffers.h
include/flatbuffers/hash.h
include/flatbuffers/idl.h
@@ -26,6 +30,7 @@ set(FlatBuffers_Library_SRCS
src/idl_parser.cpp
src/idl_gen_text.cpp
src/reflection.cpp
src/util.cpp
)
set(FlatBuffers_Compiler_SRCS
@@ -37,7 +42,10 @@ set(FlatBuffers_Compiler_SRCS
src/idl_gen_php.cpp
src/idl_gen_python.cpp
src/idl_gen_fbs.cpp
src/idl_gen_grpc.cpp
src/flatc.cpp
grpc/src/compiler/cpp_generator.h
grpc/src/compiler/cpp_generator.cc
)
set(FlatHash_SRCS
@@ -68,25 +76,62 @@ set(FlatBuffers_Sample_Text_SRCS
include/flatbuffers/util.h
src/idl_parser.cpp
src/idl_gen_text.cpp
src/util.cpp
samples/sample_text.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
)
set(FlatBuffers_GRPCTest_SRCS
include/flatbuffers/flatbuffers.h
include/flatbuffers/grpc.h
tests/monster_test.grpc.fb.h
tests/monster_test.grpc.fb.cc
grpc/tests/grpctest.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
)
# source_group(Compiler FILES ${FlatBuffers_Compiler_SRCS})
# source_group(Tests FILES ${FlatBuffers_Tests_SRCS})
if(APPLE)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++ -Wall -pedantic -Werror -Wextra")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra")
elseif(CMAKE_COMPILER_IS_GNUCXX)
if(CYGWIN)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -std=gnu++11")
else(CYGWIN)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -std=c++0x")
endif(CYGWIN)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -std=c++0x -Wall -pedantic -Werror -Wextra -Werror=shadow -Wunused-result -Werror=unused-result")
"${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Werror=shadow")
if (GCC_VERSION VERSION_GREATER 4.4)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -Wunused-result -Werror=unused-result")
endif()
# Certain platforms such as ARM do not use signed chars by default
# which causes issues with certain bounds checks.
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -fsigned-char")
elseif("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -std=c++0x -stdlib=libc++ -Wall -pedantic -Werror -Wextra")
set(CMAKE_EXE_LINKER_FLAGS
"${CMAKE_EXE_LINKER_FLAGS} -lc++abi")
"${CMAKE_CXX_FLAGS} -std=c++0x -stdlib=libc++ -Wall -pedantic -Werror \
-Wextra")
if(NOT "${CMAKE_SYSTEM_NAME}" MATCHES "FreeBSD")
set(CMAKE_EXE_LINKER_FLAGS
"${CMAKE_EXE_LINKER_FLAGS} -lc++abi")
endif()
# Certain platforms such as ARM do not use signed chars by default
# which causes issues with certain bounds checks.
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -fsigned-char")
endif()
if(FLATBUFFERS_CODE_COVERAGE)
@@ -101,6 +146,7 @@ if(BIICODE)
endif()
include_directories(include)
include_directories(grpc)
if(FLATBUFFERS_BUILD_FLATLIB)
add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
@@ -108,6 +154,9 @@ endif()
if(FLATBUFFERS_BUILD_FLATC)
add_executable(flatc ${FlatBuffers_Compiler_SRCS})
if(NOT FLATBUFFERS_FLATC_EXECUTABLE)
set(FLATBUFFERS_FLATC_EXECUTABLE $<TARGET_FILE:flatc>)
endif()
endif()
if(FLATBUFFERS_BUILD_FLATHASH)
@@ -119,7 +168,9 @@ function(compile_flatbuffers_schema_to_cpp SRC_FBS)
string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS})
add_custom_command(
OUTPUT ${GEN_HEADER}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" -c --no-includes --gen-mutable -o "${SRC_FBS_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" -c --no-includes --gen-mutable
--gen-object-api -o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc)
endfunction()
@@ -128,7 +179,8 @@ function(compile_flatbuffers_schema_to_binary SRC_FBS)
string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS})
add_custom_command(
OUTPUT ${GEN_BINARY_SCHEMA}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" -b --schema -o "${SRC_FBS_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" -b --schema -o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc)
endfunction()
@@ -143,6 +195,14 @@ if(FLATBUFFERS_BUILD_TESTS)
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
endif()
if(FLATBUFFERS_BUILD_GRPCTEST)
if(CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter")
endif()
add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
target_link_libraries(grpctest grpc++_unsecure grpc pthread dl)
endif()
if(FLATBUFFERS_INSTALL)
install(DIRECTORY include/flatbuffers DESTINATION include)
if(FLATBUFFERS_BUILD_FLATLIB)

View File

@@ -1,4 +1,5 @@
#!/bin/bash -eu
#
# Copyright (c) 2013 Google, Inc.
#
# This software is provided 'as-is', without any express or implied

View File

@@ -33,7 +33,8 @@ include $(CLEAR_VARS)
LOCAL_MODULE := flatbuffers_extra
LOCAL_SRC_FILES := src/idl_parser.cpp \
src/idl_gen_text.cpp \
src/reflection.cpp
src/reflection.cpp \
src/util.cpp
LOCAL_STATIC_LIBRARIES := flatbuffers
include $(BUILD_STATIC_LIBRARY)

View File

@@ -18,5 +18,5 @@ APP_PROJECT_PATH := $(call my-dir)/..
APP_STL := gnustl_static
APP_ABI := armeabi-v7a
NDK_TOOLCHAIN_VERSION := 4.8
APP_CPPFLAGS += -std=c++11

26
appveyor.yml Normal file
View File

@@ -0,0 +1,26 @@
branches:
only:
- master
os: Visual Studio 2015
platform:
- x86
- x64
configuration:
- Debug
- Release
before_build:
- cmake -G"Visual Studio 10 2010"
build:
project: ALL_BUILD.vcxproj
#test_script:
# - Debug/flattests.exe
#artifacts:
# - path: Release/flatc.exe
# name: flatc.exe

View File

@@ -1,4 +1,18 @@
#!/bin/bash
#
# Copyright 2016 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.
sudo apt-get update -qq
sudo apt-get install libglu1-mesa-dev xorg-dev

View File

@@ -1,55 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "flatc", "flatc.vcxproj", "{5B5857E1-64E2-4CED-A12E-45E1B3880496}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "flatsamplebinary", "flatsamplebinary.vcxproj", "{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "flatsampletext", "flatsampletext.vcxproj", "{F0A15675-1017-4217-BB5B-3372F2C636AB}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "flattests", "flattests.vcxproj", "{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|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}.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}.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}.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}.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}.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}.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}.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}.Release|x64.ActiveCfg = Release|x64
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -1,285 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<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>
<Keyword>Win32Proj</Keyword>
<Platform>Win32</Platform>
<ProjectName>flatc</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<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>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<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>
<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> /machine:X86 /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)'=='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>
<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>
<AdditionalOptions> /machine:X86 %(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>false</GenerateDebugInformation>
<ImportLibrary>../../Release/flatc.lib</ImportLibrary>
<ProgramDataBaseFile>../../Release/flatc.pdb</ProgramDataBaseFile>
<SubSystem>Console</SubSystem>
<Version>
</Version>
</Link>
<ProjectReference>
<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_php.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_text.cpp" />
<ClCompile Include="..\..\src\flatc.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -1,27 +0,0 @@
<?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>..\..\tests</LocalDebuggerWorkingDirectory>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
<LocalDebuggerCommandArguments>-j -c -n -g --php --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>

View File

@@ -1,273 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<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>
<Keyword>Win32Proj</Keyword>
<Platform>Win32</Platform>
<ProjectName>flatsamplebinary</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<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>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<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>
<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> /machine:X86 /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)'=='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>
<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>
<AdditionalOptions> /machine:X86 %(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>false</GenerateDebugInformation>
<ImportLibrary>../../Release/flatsamplebinary.lib</ImportLibrary>
<ProgramDataBaseFile>../../Release/flatsamplebinary.pdb</ProgramDataBaseFile>
<SubSystem>Console</SubSystem>
<Version>
</Version>
</Link>
<ProjectReference>
<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>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

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

View File

@@ -1,277 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<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>
<Keyword>Win32Proj</Keyword>
<Platform>Win32</Platform>
<ProjectName>flatsampletext</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<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>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<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>
<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> /machine:X86 /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)'=='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>
<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>
<AdditionalOptions> /machine:X86 %(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>false</GenerateDebugInformation>
<ImportLibrary>../../Release/flatsampletext.lib</ImportLibrary>
<ProgramDataBaseFile>../../Release/flatsampletext.pdb</ProgramDataBaseFile>
<SubSystem>Console</SubSystem>
<Version>
</Version>
</Link>
<ProjectReference>
<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" />
<ClInclude Include="..\..\include\flatbuffers\util.h" />
<ClInclude Include="..\..\samples\monster_generated.h" />
<ClCompile Include="..\..\src\idl_parser.cpp" />
<ClCompile Include="..\..\src\idl_gen_text.cpp" />
<ClCompile Include="..\..\samples\sample_text.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -1,19 +0,0 @@
<?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>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<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>

View File

@@ -1,281 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<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>
<Keyword>Win32Proj</Keyword>
<Platform>Win32</Platform>
<ProjectName>flattests</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<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>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<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>
<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> /machine:X86 /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)'=='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>
<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>
<AdditionalOptions> /machine:X86 %(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>false</GenerateDebugInformation>
<ImportLibrary>../../Release/flattests.lib</ImportLibrary>
<ProgramDataBaseFile>../../Release/flattests.pdb</ProgramDataBaseFile>
<SubSystem>Console</SubSystem>
<Version>
</Version>
</Link>
<ProjectReference>
<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>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -1,19 +0,0 @@
<?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>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<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>

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,9 @@
Building {#flatbuffers_guide_building}
========
## Building with Visual Studio or Xcode projects
There are project files for Visual Studio and Xcode that should allow you
to build the compiler `flatc`, the samples and the tests out of the box.
## Building with CMake
Alternatively, the distribution comes with a `cmake` file that should allow
The distribution comes with a `cmake` file that should allow
you to build project/make files for any platform. For details on `cmake`, see
<http://www.cmake.org>. In brief, depending on your platform, use one of
e.g.:

224
docs/source/CUsage.md Normal file
View File

@@ -0,0 +1,224 @@
Use in C {#flatbuffers_guide_use_c}
==========
The C language binding exists in a separate project named [FlatCC](https://github.com/dvidelabs/flatcc).
The `flatcc` C schema compiler can generate code offline as well as
online via a C library. It can also generate buffer verifiers and fast
JSON parsers, printers.
Great care has been taken to ensure compatibily with the main `flatc`
project.
## General Documention
- [Tutorial](@ref flatbuffers_guide_tutorial) - select C as language
when scrolling down
- [FlatCC Guide](https://github.com/dvidelabs/flatcc#flatcc-flatbuffers-in-c-for-c)
- [The C Builder Interface](https://github.com/dvidelabs/flatcc/blob/master/doc/builder.md#the-builder-interface)
- [The Monster Sample in C](https://github.com/dvidelabs/flatcc/blob/master/samples/monster/monster.c)
- [GitHub](https://github.com/dvidelabs/flatcc)
## Supported Platforms
- Ubuntu (clang / gcc, ninja / gnu make)
- OS-X (clang / gcc, ninja / gnu make)
- Windows MSVC 2010, 2013, 2015
CI builds recent versions of gcc, clang and MSVC on OS-X, Ubuntu, and
Windows, and occasionally older compiler versions. See main project [Status](https://github.com/dvidelabs/flatcc#status).
Other platforms may well work, including Centos, but are not tested
regularly.
The monster sample project was specifically written for C99 in order to
follow the C++ version and for that reason it will not work with MSVC
2010.
## Modular Object Creation
In the tutorial we used the call `Monster_create_as_root` to create the
root buffer object since this is easier in simple use cases. Sometimes
we need more modularity so we can reuse a function to create nested
tables and root tables the same way. For this we need the
`flatcc_builder_buffer_create_call`. It is best to keep `flatcc_builder`
calls isolated at the top driver level, so we get:
<div class="language-c">
~~~{.c}
ns(Monster_ref_t) create_orc(flatcc_builder_t *B)
{
// ... same as in the tutorial.
return s(Monster_create(B, ...));
}
void create_monster_buffer()
{
uint8_t *buf;
size_t size;
flatcc_builder_t builder, *B;
// Initialize the builder object.
B = &builder;
flatcc_builder_init(B);
// Only use `buffer_create` without `create/start/end_as_root`.
flatcc_builder_buffer_create(create_orc(B));
// Allocate and copy buffer to user memory.
buf = flatcc_builder_finalize_buffer(B, &size);
// ... write the buffer to disk or network, or something.
free(buf);
flatcc_builder_clear(B);
}
~~~
</div>
The same principle applies with `start/end` vs `start/end_as_root` in
the top-down approach.
## Top Down Example
The tutorial uses a bottom up approach. In C it is also possible to use
a top-down approach by starting and ending objects nested within each
other. In the tutorial there is no deep nesting, so the difference is
limited, but it shows the idea:
<div class="language-c">
<br>
~~~{.c}
uint8_t treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
size_t treasure_count = c_vec_len(treasure);
ns(Weapon_ref_t) axe;
// NOTE: if we use end_as_root, we MUST also start as root.
ns(Monster_start_as_root(B));
ns(Monster_pos_create(B, 1.0f, 2.0f, 3.0f));
ns(Monster_hp_add(B, 300));
ns(Monster_mana_add(B, 150));
// We use create_str instead of add because we have no existing string reference.
ns(Monster_name_create_str(B, "Orc"));
// Again we use create because we no existing vector object, only a C-array.
ns(Monster_inventory_create(B, treasure, treasure_count));
ns(Monster_color_add(B, ns(Color_Red)));
if (1) {
ns(Monster_weapons_start(B));
ns(Monster_weapons_push_create(B, flatbuffers_string_create_str(B, "Sword"), 3));
// We reuse the axe object later. Note that we dereference a pointer
// because push always returns a short-term pointer to the stored element.
// We could also have created the axe object first and simply pushed it.
axe = *ns(Monster_weapons_push_create(B, flatbuffers_string_create_str(B, "Axe"), 5));
ns(Monster_weapons_end(B));
} else {
// We can have more control with the table elements added to a vector:
//
ns(Monster_weapons_start(B));
ns(Monster_weapons_push_start(B));
ns(Weapon_name_create_str(B, "Sword"));
ns(Weapon_damage_add(B, 3));
ns(Monster_weapons_push_end(B));
ns(Monster_weapons_push_start(B));
ns(Monster_weapons_push_start(B));
ns(Weapon_name_create_str(B, "Axe"));
ns(Weapon_damage_add(B, 5));
axe = *ns(Monster_weapons_push_end(B));
ns(Monster_weapons_end(B));
}
// Unions can get their type by using a type-specific add/create/start method.
ns(Monster_equipped_Weapon_add(B, axe));
ns(Monster_end_as_root(B));
~~~
</div>
## Basic Reflection
The C-API does support reading binary schema (.bfbs)
files via code generated from the `reflection.fbs` schema, and an
[example usage](https://github.com/dvidelabs/flatcc/tree/master/samples/reflection)
shows how to use this. The reflection schema files are pre-generated
in the [runtime distribution](https://github.com/dvidelabs/flatcc/tree/master/include/flatcc/reflection).
## Mutations and Reflection
The C-API does not support mutating reflection like C++ does, nor does
the reader interface support mutating scalars (and it is generally
unsafe to do so even after verification).
The generated reader interface supports sorting vectors in-place after
casting them to a mutating type because it is not practical to do so
while building a buffer. This is covered in the builder documentation.
The reflection example makes use of this feature to look up objects by
name.
It is possible to build new buffers using complex objects from existing
buffers as source. This can be very efficient due to direct copy
semantics without endian conversion or temporary stack allocation.
Scalars, structs and strings can be used as source, as well vectors of
these.
It is currently not possible to use an existing table or vector of table
as source, but it would be possible to add support for this at some
point.
## Namespaces
The `FLATBUFFERS_WRAP_NAMESPACE` approach used in the tutorial is convenient
when each function has a very long namespace prefix. But it isn't always
the best approach. If the namespace is absent, or simple and
informative, we might as well use the prefix directly. The
[reflection example](https://github.com/dvidelabs/flatcc/blob/master/samples/reflection/bfbs2json.c)
mentioned above uses this approach.
## Checking for Present Members
Not all languages support testing if a field is present, but in C we can
elaborate the reader section of the tutorial with tests for this. Recall
that `mana` was set to the default value `150` and therefore shouldn't
be present.
<div class="language-c">
~~~{.c}
int hp_present = ns(Monster_hp_is_present(monster)); // 1
int mana_present = ns(Monster_mana_is_present(monster)); // 0
~~~
</div>
## Alternative ways to add a Union
In the tutorial we used a single call to add a union. Here we show
different ways to accomplish the same thing. The last form is rarely
used, but is the low-level way to do it. It can be used to group small
values together in the table by adding type and data at different
points in time.
<div class="language-c">
~~~{.c}
ns(Equipment_union_ref_t) equipped = ns(Equipment_as_Weapon(axe));
ns(Monster_equipped_add(B, equipped));
// or alternatively
ns(Monster_equipped_Weapon_add(B, axe);
// or alternatively
ns(Monster_equipped_add_type(B, ns(Equipment_Weapon));
ns(Monster_equipped_add_member(B, axe));
~~~
</div>
## Why not integrate with the `flatc` tool?
[It was considered how the C code generator could be integrated into the
`flatc` tool](https://github.com/dvidelabs/flatcc/issues/1), but it
would either require that the standalone C implementation of the schema
compiler was dropped, or it would lead to excessive code duplication, or
a complicated intermediate representation would have to be invented.
Neither of these alternatives are very attractive, and it isn't a big
deal to use the `flatcc` tool instead of `flatc` given that the
FlatBuffers C runtime library needs to be made available regardless.

View File

@@ -33,6 +33,8 @@ For any schema input files, one or more generators can be specified:
- `--php`: Generate PHP code.
- `--grpc`: Generate RPC stub code for GRPC.
For any data input files:
- `--binary`, `-b` : If data is contained in this file, generate a
@@ -79,6 +81,11 @@ Additional options:
- `--gen-mutable` : Generate additional non-const accessors for mutating
FlatBuffers in-place.
`--gen-object-api` : Generate an additional object-based API. This API is
more convenient for object construction and mutation than the base API,
at the cost of efficiency (object allocation). Recommended only to be used
if other options are insufficient.
- `--gen-onefile` : Generate single output file (useful for C#)
- `--gen-all`: Generate not just code for the current schema files, but
@@ -101,5 +108,9 @@ Additional options:
to the reflection/reflection.fbs schema. Loading this binary file is the
basis for reflection functionality.
- `--conform FILE` : Specify a schema the following schemas should be
an evolution of. Gives errors if not. Useful to check if schema
modifications don't break schema evolution rules.
NOTE: short-form options for generators are deprecated, use the long form
whenever possible.

View File

@@ -26,8 +26,7 @@ your program by including the header. As noted, this header relies on
The code for the FlatBuffers C++ library can be found at
`flatbuffers/include/flatbuffers`. You can browse the library code on the
[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/
include/flatbuffers).
[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/include/flatbuffers).
## Testing the FlatBuffers C++ library
@@ -86,6 +85,27 @@ convenient accessors for all fields, e.g. `hp()`, `mana()`, etc:
*Note: That we never stored a `mana` value, so it will return the default.*
## Object based API.
FlatBuffers is all about memory efficiency, which is why its base API is written
around using as little as possible of it. This does make the API clumsier
(requiring pre-order construction of all data, and making mutation harder).
For times when efficiency is less important a more convenient object based API
can be used (through `--gen-object-api`) that is able to unpack & pack a
FlatBuffer into objects and standard STL containers, allowing for convenient
construction, access and mutation.
To use:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
auto monsterobj = GetMonster(buffer)->UnPack();
cout << monsterobj->name; // This is now a std::string!
monsterobj->name = "Bob"; // Change the name.
FlatBufferBuilder fbb;
CreateMonster(fbb, monsterobj.get()); // Serialize into new buffer.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
## Reflection (& Resizing)
There is experimental support for reflection in FlatBuffers, allowing you to

View File

@@ -4,9 +4,9 @@ FlatBuffers {#flatbuffers_index}
# Overview {#flatbuffers_overview}
[FlatBuffers](@ref flatbuffers_overview) is an efficient cross platform
serialization library for C++, C#, Go, Java, JavaScript, PHP, and Python
(C and Ruby in progress). It was originally created at Google for game
development and other performance-critical applications.
serialization library for C++, C#, C, Go, Java, JavaScript, PHP, and Python.
It was originally created at Google for game development and other
performance-critical applications.
It is available as Open Source on [GitHub](http://github.com/google/flatbuffers)
under the Apache license, v2 (see LICENSE.txt).
@@ -131,6 +131,8 @@ sections provide a more in-depth usage guide.
in your own programs.
- How to [use the generated Go code](@ref flatbuffers_guide_use_go) in your
own programs.
- How to [use FlatBuffers in C with `flatcc`](@ref flatbuffers_guide_use_c) in your
own programs.
- [Support matrix](@ref flatbuffers_support) for platforms/languages/features.
- Some [benchmarks](@ref flatbuffers_benchmarks) showing the advantage of
using FlatBuffers.
@@ -143,7 +145,7 @@ sections provide a more in-depth usage guide.
- [GitHub repository](http://github.com/google/flatbuffers)
- [Landing page](http://google.github.io/flatbuffers)
- [FlatBuffers Google Group](http://group.google.com/group/flatbuffers)
- [FlatBuffers Google Group](https://groups.google.com/forum/#!forum/flatbuffers)
- [FlatBuffers Issues Tracker](http://github.com/google/flatbuffers/issues)
- Independent implementations & tools:
- [FlatCC](https://github.com/dvidelabs/flatcc) Alternative FlatBuffers

View File

@@ -67,6 +67,29 @@ Now you can access values like this:
pos := monster.Pos(nil)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In some cases it's necessary to modify values in an existing FlatBuffer in place (without creating a copy). For this reason, scalar fields of a Flatbuffer table or struct can be mutated.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go}
monster := example.GetRootAsMonster(buf, 0)
// Set table field.
if ok := monster.MutateHp(10); !ok {
panic("failed to mutate Hp")
}
// Set struct field.
monster.Pos().MutateZ(4)
// This mutation will fail because the mana field is not available in
// the buffer. It should be set when creating the buffer.
if ok := monster.MutateMana(20); !ok {
panic("failed to mutate Hp")
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The term `mutate` is used instead of `set` to indicate that this is a special use case. All mutate functions return a boolean value which is false if the field we're trying to mutate is not available in the buffer.
## Text Parsing
There currently is no support for parsing text (Schema's and JSON) directly

View File

@@ -122,7 +122,8 @@ default to `NULL` when not present.
You generally do not want to change default values after they're initially
defined. Fields that have the default value are not actually stored in the
serialized data but are generated in code, so when you change the default, you'd
serialized data (see also Gotchas below) 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
@@ -224,6 +225,21 @@ This declaration in the schema will change that to whatever you want:
file_extension "ext";
### RPC interface declarations
You can declare RPC calls in a schema, that define a set of functions
that take a FlatBuffer as an argument (the request) and return a FlatBuffer
as the response (both of which must be table types):
rpc_service MonsterStorage {
Store(Monster):StoreResponse;
Retrieve(MonsterId):Monster;
}
What code this produces and how it is used depends on language and RPC system
used, there is preliminary support for GRPC through the `--grpc` code generator,
see `grpc/tests` for an example.
### Comments & documentation
May be written as in most C-based languages. Additionally, a triple
@@ -256,7 +272,7 @@ Current understood attributes:
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.
When a new field is added to the schema it must use the next available ID.
- `deprecated` (on a field): do not generate accessors for this field
anymore, code should stop using this data.
- `required` (on a non-scalar table field): this field must always be set.
@@ -318,6 +334,10 @@ JSON:
- A field that has the value `null` (e.g. `field: null`) is intended to
have the default value for that field (thus has the same effect as if
that field wasn't specified at all).
- It has some built in conversion functions, so you can write for example
`rad(180)` where ever you'd normally write `3.14159`.
Currently supports the following functions: `rad`, `deg`, `cos`, `sin`,
`tan`, `acos`, `asin`, `atan`.
When parsing JSON, it recognizes the following escape codes in strings:
@@ -425,4 +445,28 @@ incompatible with the actual binary buffers, since those only ever address
fields by id/offset.
<br>
### Testing whether a field is present in a table
Most serialization formats (e.g. JSON or Protocol Buffers) make it very
explicit in the format whether a field is present in an object or not,
allowing you to use this as "extra" information.
In FlatBuffers, this also holds for everything except scalar values.
FlatBuffers by default will not write fields that are equal to the default
value (for scalars), sometimes resulting in a significant space savings.
However, this also means testing whether a field is "present" is somewhat
meaningless, since it does not tell you if the field was actually written by
calling `add_field` style calls, unless you're only interested in this
information for non-default values.
Some `FlatBufferBuilder` implementations have an option called `force_defaults`
that circumvents this behavior, and writes fields even if they are equal to
the default. You can then use `IsFieldPresent` to query this.
Another option that works in all languages is to wrap a scalar field in a
struct. This way it will return null if it is not present. The cool thing
is that structs don't take up any more space than the scalar they represent.
[Interface Definition Language]: https://en.wikipedia.org/wiki/Interface_description_language

View File

@@ -18,23 +18,23 @@ In general:
NOTE: this table is a start, it needs to be extended.
Feature | C++ | Java | C# | Go | Python | JS | C | PHP | Ruby
------------------------------ | ------ | ------ | ------ | ------ | ------ | --------- | ---- | --- | ----
Codegen for all basic features | Yes | Yes | Yes | Yes | Yes | Yes | WiP | WiP | WiP
JSON parsing | Yes | No | No | No | No | No | No | No | No
Simple mutation | Yes | WIP | WIP | No | No | No | No | No | No
Reflection | Yes | No | No | No | No | No | No | No | No
Buffer verifier | Yes | No | No | No | No | No | No | No | No
Testing: basic | Yes | Yes | Yes | Yes | Yes | Yes | ? | ? | ?
Testing: fuzz | Yes | No | No | Yes | Yes | No | ? | ? | ?
Performance: | Superb | Great | Great | Great | Ok | ? |Superb| ? | ?
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) | gwvo | gwvo | ev*/js*| rw | rw | evanw/ev* | mik* | ch* | rw
Feature | C++ | Java | C# | Go | Python | JS | C | PHP | Ruby
------------------------------ | ------ | ------ | ------ | ------ | ------ | --------- | ------ | --- | ----
Codegen for all basic features | Yes | Yes | Yes | Yes | Yes | Yes | Yes | WiP | WiP
JSON parsing | Yes | No | No | No | No | No | Yes | No | No
Simple mutation | Yes | WIP | WIP | No | No | No | No | No | No
Reflection | Yes | No | No | No | No | No | Basic | No | No
Buffer verifier | Yes | No | No | No | No | No | Yes | No | No
Testing: basic | Yes | Yes | Yes | Yes | Yes | Yes | Yes | ? | ?
Testing: fuzz | Yes | No | No | Yes | Yes | No | No | ? | ?
Performance: | Superb | Great | Great | Great | Ok | ? | Superb | ? | ?
Platform: Windows | VS2010 | Yes | Yes | ? | ? | ? | VS2010 | ? | ?
Platform: Linux | GCC282 | Yes | ? | Yes | Yes | ? | Yes | ? | ?
Platform: OS X | Xcode4 | ? | ? | ? | Yes | ? | Yes | ? | ?
Platform: Android | NDK10d | Yes | ? | ? | ? | ? | ? | ? | ?
Platform: iOS | ? | ? | ? | ? | ? | ? | ? | ? | ?
Engine: Unity | ? | ? | Yes | ? | ? | ? | ? | ? | ?
Primary authors (github) | gwvo | gwvo | ev*/js*| rw | rw | evanw/ev* | mik* | ch* | rw
* ev = evolutional
* js = jonsimantov

View File

@@ -19,7 +19,6 @@ character, the hero of the story, needs to slay some `orc`s. We will walk
through each step necessary to create this monster type using FlatBuffers.
Please select your desired language for our quest:
\htmlonly
<form>
<input type="radio" name="language" value="cpp" checked="checked">C++</input>
@@ -29,6 +28,7 @@ Please select your desired language for our quest:
<input type="radio" name="language" value="python">Python</input>
<input type="radio" name="language" value="javascript">JavaScript</input>
<input type="radio" name="language" value="php">PHP</input>
<input type="radio" name="language" value="c">C</input>
</form>
\endhtmlonly
@@ -98,6 +98,10 @@ Samples demonstating the concepts in this example are located in the source code
package, under the `samples` directory. You can browse the samples on GitHub
[here](https://github.com/google/flatbuffers/tree/master/samples).
<div class="language-c">
*Note: The above does not apply to C, instead [look here](https://github.com/dvidelabs/flatcc/tree/master/samples).*
</div>
For your chosen language, please cross-reference with:
<div class="language-cpp">
@@ -121,6 +125,9 @@ For your chosen language, please cross-reference with:
<div class="language-php">
[SampleBinary.php](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.php)
</div>
<div class="language-c">
[monster.c](https://github.com/dvidelabs/flatcc/blob/master/samples/monster/monster.c)
</div>
## Writing the Monsters' FlatBuffer Schema
@@ -225,6 +232,15 @@ FlatBuffer compiler.
Once `flatc` is built successfully, compile the schema for your language:
<div class="language-c">
*Note: If you're working in C, you need to use the separate project [FlatCC](https://github.com/dvidelabs/flatcc) which contains a schema compiler and runtime library in C for C.*
<br>
See [flatcc build instructions](https://github.com/dvidelabs/flatcc#building).
<br>
Please be aware of the difference between `flatc` and `flatcc` tools.
<br>
</div>
<div class="language-cpp">
~~~{.sh}
cd flatbuffers/sample
@@ -267,8 +283,17 @@ Once `flatc` is built successfully, compile the schema for your language:
./../flatc --php samples/monster.fbs
~~~
</div>
<div class="language-c">
~~~{.sh}
cd flatcc
mkdir -p build/tmp/samples/monster
bin/flatcc -a -o build/tmp/samples/monster samples/monster/monster.fbs
# or just
flatcc/samples/monster/build.sh
~~~
</div>
For a more complete guide to using the `flatc` compiler, pleaes read the
For a more complete guide to using the `flatc` compiler, please read the
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler)
section of the Programmer's Guide.
@@ -359,6 +384,18 @@ The first step is to import/include the library, generated files, etc.
}
~~~
</div>
<div class="language-c">
~~~{.c}
#include "monster_builder.h" // Generated by `flatcc`.
// Convenient namespace macro to manage long namespace prefix.
#undef ns
#define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Sample, x) // Specified in the schema.
// A helper to simplify creating vectors from C-arrays.
#define c_vec_len(V) (sizeof(V)/sizeof((V)[0]))
~~~
</div>
Now we are ready to start building some buffers. In order to start, we need
to create an instance of the `FlatBufferBuilder`, which will contain the buffer
@@ -413,6 +450,14 @@ as it grows:
$builder = new Google\FlatBuffers\FlatbufferBuilder(0);
~~~
</div>
<div class="language-c">
~~~{.c}
flatcc_builder_t builder, *B;
B = &builder;
// Initialize the builder object.
flatcc_builder_init(B);
~~~
</div>
After creating the `builder`, we can start serializing our data. Before we make
our `orc` Monster, lets create some `Weapon`s: a `Sword` and an `Axe`.
@@ -432,10 +477,10 @@ our `orc` Monster, lets create some `Weapon`s: a `Sword` and an `Axe`.
</div>
<div class="language-java">
~~~{.java}
String weaponOneName = builder.createString("Sword")
int weaponOneName = builder.createString("Sword")
short weaponOneDamage = 3;
String weaponTwoName = builder.createString("Axe");
int weaponTwoName = builder.createString("Axe");
short weaponTwoDamage = 5;
// Use the `createWeapon()` helper function to create the weapons, since we set every field.
@@ -525,6 +570,18 @@ our `orc` Monster, lets create some `Weapon`s: a `Sword` and an `Axe`.
$weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps);
~~~
</div>
<div class="language-c">
~~~{.c}
ns(Weapon_ref_t) weapon_one_name = flatbuffers_string_create_str(B, "Sword");
uint16_t weapon_one_damage = 3;
ns(Weapon_ref_t) weapon_two_name = flatbuffers_string_create_str(B, "Axe");
uint16_t weapon_two_damage = 5;
ns(Weapon_ref_t) sword = ns(Weapon_create(B, weapon_one_name, weapon_one_damage));
ns(Weapon_ref_t) axe = ns(Weapon_create(B, weapon_two_name, weapon_two_damage));
~~~
</div>
Now let's create our monster, the `orc`. For this `orc`, lets make him
`red` with rage, positioned at `(1.0, 2.0, 3.0)`, and give him
@@ -627,6 +684,20 @@ traversal. This is generally easy to do on any tree structures.
$inv = \MyGame\Sample\Monster::CreateInventoryVector($builder, $treasure);
~~~
</div>
<div class="language-c">
~~~{.c}
// Serialize a name for our monster, called "Orc".
// The _str suffix indicates the source is an ascii-z string.
flatbuffers_string_ref_t name = flatbuffers_string_create_str(B, "Orc");
// Create a `vector` representing the inventory of the Orc. Each number
// could correspond to an item that can be claimed after he is slain.
uint8_t treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
flatbuffers_uint8_vec_ref_t inventory;
// `c_vec_len` is the convenience macro we defined earlier.
inventory = flatbuffers_uint8_vec_create(B, treasure, c_vec_len(treasure));
~~~
</div>
We serialized two built-in data types (`string` and `vector`) and captured
their return values. These values are offsets into the serialized data,
@@ -656,8 +727,8 @@ offsets.
// Place the two weapons into an array, and pass it to the `createWeaponsVector()` method to
// create a FlatBuffer vector.
int[] weaps = new int[2];
weaps[1] = sword;
weaps[2] = axe;
weaps[0] = sword;
weaps[1] = axe;
// Pass the `weaps` array into the `createWeaponsVector()` method to create a FlatBuffer vector.
int weapons = Monster.createWeaponsVector(builder, weaps);
@@ -709,8 +780,26 @@ offsets.
$weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps);
~~~
</div>
<div class="language-c">
~~~{.c}
// We use the internal builder stack to implement a dynamic vector.
ns(Weapon_vec_start(B));
ns(Weapon_vec_push(B, sword));
ns(Weapon_vec_push(B, axe));
ns(Weapon_vec_ref_t) weapons = ns(Weapon_vec_end(B));
~~~
</div>
To create a `struct`, use the `Vec3` class/struct that was generated by `flatc`:
<div class="language-cpp">
<br>
Note there's additional convenience overloads of `CreateVector`, allowing you
to work with data that's not in a `std::vector`, or allowing you to generate
elements by calling a lambda. For the common case of `std::vector<std::string>`
there's also `CreateVectorOfStrings`.
</div>
To create a `struct`, use the `Vec3` class/struct that was generated by
the schema compiler:
<div class="language-cpp">
~~~{.cpp}
@@ -754,6 +843,12 @@ To create a `struct`, use the `Vec3` class/struct that was generated by `flatc`:
$pos = \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0);
~~~
</div>
<div class="language-c">
~~~{.c}
// Create a `Vec3`, representing the Orc's position in 3-D space.
ns(Vec3_t) pos = { 1.0f, 2.0f, 3.0f };
~~~
</div>
We have now serialized the non-scalar components of the orc, so we
can serialize the monster itself:
@@ -862,16 +957,29 @@ can serialize the monster itself:
$orc = \MyGame\Sample\Monster::EndMonster($builder);
~~~
</div>
<div class="language-c">
~~~{.c}
// Set his hit points to 300 and his mana to 150.
uint16_t hp = 300;
uint16_t mana = 150;
<div class="language-cpp">
<br>
*Note: Since we passing `150` as the `mana` field, which happens to be the
// Define an equipment union. `create` calls in C has a single
// argument for unions where C++ has both a type and a data argument.
ns(Equipment_union_ref_t) equipped = ns(Equipment_as_Weapon(axe));
ns(Monster_create_as_root(B, &pos, mana, hp, name, inventory, ns(Color_Red),
weapons, equipped));
~~~
</div>
*Note: Since we are passing `150` as the `mana` field, which happens to be the
default value, the field will not actually be written to the buffer, since the
default value will be returned on query anyway. This is a nice space savings,
especially if default values are common in your data. It also means that you do
not need to be worried of adding a lot of fields that are only used in a small
number of instances, as it will not bloat the buffer if unused.*
<br><br>
<div class="language-cpp">
<br>
If you do not wish to set every field in a `table`, it may be more convenient to
manually set each field of your monster, instead of calling `CreateMonster()`.
The following snippet is functionally equivalent to the above code, but provides
@@ -892,6 +1000,31 @@ a bit more flexibility.
auto orc = monster_builder.Finish();
~~~
</div>
<div class="language-c">
If you do not wish to set every field in a `table`, it may be more convenient to
manually set each field of your monster, instead of calling `create_monster_as_root()`.
The following snippet is functionally equivalent to the above code, but provides
a bit more flexibility.
<br>
~~~{.c}
// It is important to pair `start_as_root` with `end_as_root`.
ns(Monster_start_as_root(B));
ns(Monster_pos_create(B, 1.0f, 2.0f, 3.0f));
// or alternatively
//ns(Monster_pos_add(&pos);
ns(Monster_hp_add(B, hp));
// Notice that `Monser_name_add` adds a string reference unlike the
// add_str and add_strn variants.
ns(Monster_name_add(B, name));
ns(Monster_inventory_add(B, inventory));
ns(Monster_color_add(B, ns(Color_Red)));
ns(Monster_weapons_add(B, weapons));
ns(Monster_equipped_add(B, equipped));
// Complete the monster object and make it the buffer root object.
ns(Monster_end_as_root(B));
~~~
</div>
Before finishing the serialization, let's take a quick look at FlatBuffer
`union Equipped`. There are two parts to each FlatBuffer `union`. The first, is
@@ -947,11 +1080,18 @@ Here is a repetition these lines, to help highlight them more clearly:
\MyGame\Sample\Monster::AddEquipped($builder, $axe); // Union data
~~~
</div>
<div class="language-c">
~~~{.c}
// Add union type and data simultanously.
ns(Monster_equipped_Weapon_add(B, axe));
~~~
</div>
After you have created your buffer, you will have the offset to the root of the
data in the `orc` variable, so you can finish the buffer by calling the
appropriate `finish` method.
<div class="language-cpp">
~~~{.cpp}
// Call `Finish()` to instruct the builder that this monster is complete.
@@ -999,6 +1139,11 @@ appropriate `finish` method.
// $builder, $orc);`.
~~~
</div>
<div class="language-c">
~~~{.c}
// Because we used `Monster_create_as_root`, we do not need a `finish` call in C`.
~~~
</div>
The buffer is now ready to be stored somewhere, sent over the network, be
compressed, or whatever you'd like to do with it. You can access the buffer
@@ -1016,12 +1161,23 @@ like so:
~~~{.java}
// This must be called after `finish()`.
java.nio.ByteBuffer buf = builder.dataBuffer();
// The data in this ByteBuffer does NOT start at 0, but at buf.position().
// The number of bytes is buf.remaining().
// Alternatively this copies the above data out of the ByteBuffer for you:
bytes[] buf = builder.sizedByteArray();
~~~
</div>
<div class="language-csharp">
~~~{.cs}
// This must be called after `Finish()`.
var buf = builder.DataBuffer; // Of type `FlatBuffers.ByteBuffer`.
// The data in this ByteBuffer does NOT start at 0, but at buf.Position.
// The end of the data is marked by buf.Length, so the size is
// buf.Length - buf.Position.
// Alternatively this copies the above data out of the ByteBuffer for you:
bytes[] buf = builder.SizedByteArray();
~~~
</div>
<div class="language-go">
@@ -1039,13 +1195,39 @@ like so:
<div class="language-javascript">
~~~{.js}
// This must be called after `finish()`.
var buf = builder.dataBuffer(); // Of type `flatbuffers.ByteBuffer`.
var buf = builder.asUint8Array(); // Of type `Uint8Array`.
~~~
</div>
<div class="language-php">
~~~{.php}
// This must be called after `finish()`.
$buf = $builder->dataBuffer(); // Of type `Google\FlatBuffers\ByteBuffer`
// The data in this ByteBuffer does NOT start at 0, but at buf->getPosition().
// The end of the data is marked by buf->capacity(), so the size is
// buf->capacity() - buf->getPosition().
~~~
</div>
<div class="language-c">
~~~{.c}
uint8_t *buf;
size_t size;
// Allocate and extract a readable buffer from internal builder heap.
// The returned buffer must be deallocated using `free`.
// NOTE: Finalizing the buffer does NOT change the builder, it
// just creates a snapshot of the builder content.
buf = flatcc_builder_finalize_buffer(B, &size);
// use buf
free(buf);
// Optionally reset builder to reuse builder without deallocating
// internal stack and heap.
flatcc_builder_reset(B);
// build next buffer.
// ...
// Cleanup.
flatcc_builder_clear(B);
~~~
</div>
@@ -1055,7 +1237,7 @@ Now that we have successfully created an `Orc` FlatBuffer, the monster data can
be saved, sent over a network, etc. Let's now adventure into the inverse, and
deserialize a FlatBuffer.
This seciton requires the same import/include, namespace, etc. requirements as
This section requires the same import/include, namespace, etc. requirements as
before:
<div class="language-cpp">
@@ -1134,6 +1316,15 @@ before:
}
~~~
</div>
<div class="language-c">
~~~{.c}
// Only needed if we don't have `#include "monster_builder.h"`.
#include "monster_reader.h"
#undef ns
#define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Sample, x) // Specified in the schema.
~~~
</div>
Then, assuming you have a variable containing to the bytes of data from disk,
network, etc., you can create a monster from this data:
@@ -1224,8 +1415,18 @@ network, etc., you can create a monster from this data:
$monster = \MyGame\Sample\Monster::GetRootAsMonster($buf);
~~~
</div>
<div class="language-c">
~~~{.c}
// Note that we use the `table_t` suffix when reading a table object
// as opposed to the `ref_t` suffix used during the construction of
// the buffer.
ns(Monster_table_t) monster = ns(Monster_as_root(buffer));
If you look in the generated files from `flatc`, you will see it generated
// Note: root object pointers are NOT the same as the `buffer` pointer.
~~~
</div>
If you look in the generated files from the schema compiler, you will see it generated
accessors for all non-`deprecated` fields. For example:
<div class="language-cpp">
@@ -1279,10 +1480,17 @@ accessors for all non-`deprecated` fields. For example:
$name = monster->getName();
~~~
</div>
<div class="language-c">
~~~{.c}
uint16_t hp = ns(Monster_hp(monster));
uint16_t mana = ns(Monster_mana(monster));
flatbuffers_string_t name = ns(Monster_name(monster));
~~~
</div>
These should hold `300`, `150`, and `"Orc"` respectively.
*Note: We never stored a value in `mp`, so we got the default value of `150`.*
*Note: The default value `150` wasn't stored in `mana`, but we are still able to retrieve it.*
To access sub-objects, in the case of our `pos`, which is a `Vec3`:
@@ -1348,10 +1556,18 @@ To access sub-objects, in the case of our `pos`, which is a `Vec3`:
$z = $pos->getZ();
~~~
</div>
<div class="language-c">
~~~{.c}
ns(Vec3_struct_t) pos = ns(Monster_pos(monster));
float x = ns(Vec3_x(pos));
float y = ns(Vec3_y(pos));
float z = ns(Vec3_z(pos));
~~~
</div>
`x`, `y`, and `z` will contain `1.0`, `2.0`, and `3.0`, respectively.
*Note: Had we not set `pos` during serialization, it would be `NULL`-value.*
*Note: Had we not set `pos` during serialization, it would be a `NULL`-value.*
Similarly, we can access elements of the inventory `vector` by indexing it. You
can also iterate over the length of the array/vector representing the
@@ -1400,6 +1616,14 @@ FlatBuffers `vector`.
$third_item = $monster->getInventory(2);
~~~
</div>
<div class="language-c">
~~~{.c}
// If `inv` hasn't been set, it will be null. It is valid get
// the length of null which will be 0, useful for iteration.
flatbuffers_uint8_vec_t inv = ns(Monster_inventory(monster));
size_t inv_len = flatbuffers_uint8_vec_len(inv);
~~~
</div>
For `vector`s of `table`s, you can access the elements like any other vector,
except your need to handle the result as a FlatBuffer `table`:
@@ -1458,6 +1682,15 @@ except your need to handle the result as a FlatBuffer `table`:
$second_weapon_damage = $monster->getWeapons(1)->getDamage();
~~~
</div>
<div class="language-c">
~~~{.c}
ns(Weapon_vec_t) weapons = ns(Monster_weapons(monster));
size_t weapons_len = ns(Weapon_vec_len(weapons));
// We can use `const char *` instead of `flatbuffers_string_t`.
const char *second_weapon_name = ns(Weapon_name(ns(Weapon_vec_at(weapons, 1))));
uint16_t second_weapon_damage = ns(Weapon_damage(ns(Weapon_vec_at(weapons, 1))));
~~~
</div>
Last, we can access our `Equipped` FlatBuffer `union`. Just like when we created
the `union`, we need to get both parts of the `union`: the type and the data.
@@ -1560,6 +1793,18 @@ We can access the type to dynamically cast the data as needed (since the
}
~~~
</div>
<div class="language-c">
~~~{.c}
// Access union type field.
if (ns(Monster_equipped_type(monster)) == ns(Equipment_Weapon)) {
// Cast to appropriate type:
// C allows for silent void pointer assignment, so we need no explicit cast.
ns(Weapon_table_t) weapon = ns(Monster_equipped(monster));
const char *weapon_name = ns(Weapon_name(weapon)); // "Axe"
uint16_t weapon_damage = ns(Weapon_damage(weapon)); // 5
}
~~~
</div>
## Mutating FlatBuffers
@@ -1624,6 +1869,12 @@ mutators like so:
<API for mutating FlatBuffers is not yet supported in PHP.>
~~~
</div>
<div class="language-c">
~~~{.c}
<API for in-place mutating FlatBuffers will not be supported in C
(except in-place vector sorting is possible).>
~~~
</div>
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
@@ -1644,6 +1895,9 @@ One way to solve this is to call `ForceDefaults` on a FlatBufferBuilder to
force all fields you set to actually be written. This, of course, increases the
size of the buffer somewhat, but this may be acceptable for a mutable buffer.
If this is not sufficient, other ways of mutating FlatBuffers may be supported
in your language through an object based API (`--gen-object-api`) or reflection.
See the individual language documents for support.
## JSON with FlatBuffers
@@ -1687,6 +1941,14 @@ FlatBuffer binary representation of the contents from our `.json` file.
[Use in C++](@ref flatbuffers_guide_use_cpp) section of the Programmer's
Guide for more information.*
</div>
<div class="language-c">
*Note: If you're working in C, the `flatcc --json` (not `flatc`)
compiler will generate schema specific high performance json parsers and
printers that you can compile and use at runtime. The `flatc` compiler (not
`flatcc`) on the other hand, is still useful for general offline json to
flatbuffer conversion from a given schema. There are no current plans
for `flatcc` to support this.*
</div>
## Advanced Features for Each Language
@@ -1716,5 +1978,8 @@ For your chosen language, see:
<div class="language-php">
[Use in PHP](@ref flatbuffers_guide_use_php)
</div>
<div class="language-c">
[Use in C](@ref flatbuffers_guide_use_c)
</div>
<br>

View File

@@ -750,6 +750,7 @@ INPUT = "FlatBuffers.md" \
"Compiler.md" \
"Schemas.md" \
"CppUsage.md" \
"CUsage.md" \
"GoUsage.md" \
"JavaCsharpUsage.md" \
"JavaScriptUsage.md" \
@@ -760,7 +761,7 @@ INPUT = "FlatBuffers.md" \
"WhitePaper.md" \
"Internals.md" \
"Grammar.md" \
"CONTRIBUTING.md" \
"../../CONTRIBUTING.md" \
"Tutorial.md" \
"GoApi.md" \
"groups" \

View File

@@ -25,6 +25,8 @@
title="Writing a schema"/>
<tab type="user" url="@ref flatbuffers_guide_use_cpp"
title="Use in C++"/>
<tab type="user" url="@ref flatbuffers_guide_use_c"
title="Use in C"/>
<tab type="user" url="@ref flatbuffers_guide_use_go"
title="Use in Go"/>
<tab type="user" url="@ref flatbuffers_guide_use_java_c-sharp"
@@ -45,7 +47,7 @@
<tab type="user" url="@ref flatbuffers_internals"
title="FlatBuffers internals"/>
<tab type="user" url="@ref flatbuffers_grammar"
title="Grammar of the schema langauge"/>
title="Grammar of the schema language"/>
<tab type="usergroup" url="" title="API Reference">
<tab type="modules" visible="yes" title="APIs" intro=""/>
<tab type="classes" visible="yes" title="">

View File

@@ -26,7 +26,8 @@ func (t *Table) Indirect(off UOffsetT) UOffsetT {
// String gets a string from data stored inside the flatbuffer.
func (t *Table) String(off UOffsetT) string {
return string(t.ByteVector(off))
b := t.ByteVector(off)
return byteSliceToString(b)
}
// ByteVector gets a byte slice from data stored inside the flatbuffer.
@@ -292,3 +293,213 @@ func (t *Table) GetVOffsetTSlot(slot VOffsetT, d VOffsetT) VOffsetT {
}
return VOffsetT(off)
}
// MutateBool updates a bool at the given offset.
func (t *Table) MutateBool(off UOffsetT, n bool) bool {
WriteBool(t.Bytes[off:], n)
return true
}
// MutateByte updates a Byte at the given offset.
func (t *Table) MutateByte(off UOffsetT, n byte) bool {
WriteByte(t.Bytes[off:], n)
return true
}
// MutateUint8 updates a Uint8 at the given offset.
func (t *Table) MutateUint8(off UOffsetT, n uint8) bool {
WriteUint8(t.Bytes[off:], n)
return true
}
// MutateUint16 updates a Uint16 at the given offset.
func (t *Table) MutateUint16(off UOffsetT, n uint16) bool {
WriteUint16(t.Bytes[off:], n)
return true
}
// MutateUint32 updates a Uint32 at the given offset.
func (t *Table) MutateUint32(off UOffsetT, n uint32) bool {
WriteUint32(t.Bytes[off:], n)
return true
}
// MutateUint64 updates a Uint64 at the given offset.
func (t *Table) MutateUint64(off UOffsetT, n uint64) bool {
WriteUint64(t.Bytes[off:], n)
return true
}
// MutateInt8 updates a Int8 at the given offset.
func (t *Table) MutateInt8(off UOffsetT, n int8) bool {
WriteInt8(t.Bytes[off:], n)
return true
}
// MutateInt16 updates a Int16 at the given offset.
func (t *Table) MutateInt16(off UOffsetT, n int16) bool {
WriteInt16(t.Bytes[off:], n)
return true
}
// MutateInt32 updates a Int32 at the given offset.
func (t *Table) MutateInt32(off UOffsetT, n int32) bool {
WriteInt32(t.Bytes[off:], n)
return true
}
// MutateInt64 updates a Int64 at the given offset.
func (t *Table) MutateInt64(off UOffsetT, n int64) bool {
WriteInt64(t.Bytes[off:], n)
return true
}
// MutateFloat32 updates a Float32 at the given offset.
func (t *Table) MutateFloat32(off UOffsetT, n float32) bool {
WriteFloat32(t.Bytes[off:], n)
return true
}
// MutateFloat64 updates a Float64 at the given offset.
func (t *Table) MutateFloat64(off UOffsetT, n float64) bool {
WriteFloat64(t.Bytes[off:], n)
return true
}
// MutateUOffsetT updates a UOffsetT at the given offset.
func (t *Table) MutateUOffsetT(off UOffsetT, n UOffsetT) bool {
WriteUOffsetT(t.Bytes[off:], n)
return true
}
// MutateVOffsetT updates a VOffsetT at the given offset.
func (t *Table) MutateVOffsetT(off UOffsetT, n VOffsetT) bool {
WriteVOffsetT(t.Bytes[off:], n)
return true
}
// MutateSOffsetT updates a SOffsetT at the given offset.
func (t *Table) MutateSOffsetT(off UOffsetT, n SOffsetT) bool {
WriteSOffsetT(t.Bytes[off:], n)
return true
}
// MutateBoolSlot updates the bool at given vtable location
func (t *Table) MutateBoolSlot(slot VOffsetT, n bool) bool {
if off := t.Offset(slot); off != 0 {
t.MutateBool(t.Pos+UOffsetT(off), n)
return true
}
return false
}
// MutateByteSlot updates the byte at given vtable location
func (t *Table) MutateByteSlot(slot VOffsetT, n byte) bool {
if off := t.Offset(slot); off != 0 {
t.MutateByte(t.Pos+UOffsetT(off), n)
return true
}
return false
}
// MutateInt8Slot updates the int8 at given vtable location
func (t *Table) MutateInt8Slot(slot VOffsetT, n int8) bool {
if off := t.Offset(slot); off != 0 {
t.MutateInt8(t.Pos+UOffsetT(off), n)
return true
}
return false
}
// MutateUint8Slot updates the uint8 at given vtable location
func (t *Table) MutateUint8Slot(slot VOffsetT, n uint8) bool {
if off := t.Offset(slot); off != 0 {
t.MutateUint8(t.Pos+UOffsetT(off), n)
return true
}
return false
}
// MutateInt16Slot updates the int16 at given vtable location
func (t *Table) MutateInt16Slot(slot VOffsetT, n int16) bool {
if off := t.Offset(slot); off != 0 {
t.MutateInt16(t.Pos+UOffsetT(off), n)
return true
}
return false
}
// MutateUint16Slot updates the uint16 at given vtable location
func (t *Table) MutateUint16Slot(slot VOffsetT, n uint16) bool {
if off := t.Offset(slot); off != 0 {
t.MutateUint16(t.Pos+UOffsetT(off), n)
return true
}
return false
}
// MutateInt32Slot updates the int32 at given vtable location
func (t *Table) MutateInt32Slot(slot VOffsetT, n int32) bool {
if off := t.Offset(slot); off != 0 {
t.MutateInt32(t.Pos+UOffsetT(off), n)
return true
}
return false
}
// MutateUint32Slot updates the uint32 at given vtable location
func (t *Table) MutateUint32Slot(slot VOffsetT, n uint32) bool {
if off := t.Offset(slot); off != 0 {
t.MutateUint32(t.Pos+UOffsetT(off), n)
return true
}
return false
}
// MutateInt64Slot updates the int64 at given vtable location
func (t *Table) MutateInt64Slot(slot VOffsetT, n int64) bool {
if off := t.Offset(slot); off != 0 {
t.MutateInt64(t.Pos+UOffsetT(off), n)
return true
}
return false
}
// MutateUint64Slot updates the uint64 at given vtable location
func (t *Table) MutateUint64Slot(slot VOffsetT, n uint64) bool {
if off := t.Offset(slot); off != 0 {
t.MutateUint64(t.Pos+UOffsetT(off), n)
return true
}
return false
}
// MutateFloat32Slot updates the float32 at given vtable location
func (t *Table) MutateFloat32Slot(slot VOffsetT, n float32) bool {
if off := t.Offset(slot); off != 0 {
t.MutateFloat32(t.Pos+UOffsetT(off), n)
return true
}
return false
}
// MutateFloat64Slot updates the float64 at given vtable location
func (t *Table) MutateFloat64Slot(slot VOffsetT, n float64) bool {
if off := t.Offset(slot); off != 0 {
t.MutateFloat64(t.Pos+UOffsetT(off), n)
return true
}
return false
}

View File

@@ -43,3 +43,8 @@ var (
// SizeVOffsetT is the byte size of an VOffsetT.
SizeVOffsetT = int(unsafe.Sizeof(VOffsetT(0)))
)
// byteSliceToString converts a []byte to string without a heap allocation.
func byteSliceToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

11
grpc/README.md Normal file
View File

@@ -0,0 +1,11 @@
GRPC implementation and test
============================
NOTE: files in `src/` are shared with the GRPC project, and maintained there
(any changes should be submitted to GRPC instead). These files are copied
from GRPC, and work with both the Protobuf and FlatBuffers code generator.
`tests/` contains a GRPC specific test, you need to have built and installed
the GRPC libraries for this to compile. This test will build using the
`FLATBUFFERS_BUILD_GRPCTEST` option to the main FlatBuffers CMake project.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,147 @@
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
#define GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
// cpp_generator.h/.cc do not directly depend on GRPC/ProtoBuf, such that they
// can be used to generate code for other serialization systems, such as
// FlatBuffers.
#include <memory>
#include <vector>
#ifndef GRPC_CUSTOM_STRING
#include <string>
#define GRPC_CUSTOM_STRING std::string
#endif
namespace grpc {
typedef GRPC_CUSTOM_STRING string;
} // namespace grpc
namespace grpc_cpp_generator {
// Contains all the parameters that are parsed from the command line.
struct Parameters {
// Puts the service into a namespace
grpc::string services_namespace;
// Use system includes (<>) or local includes ("")
bool use_system_headers;
// Prefix to any grpc include
grpc::string grpc_search_path;
};
// An abstract interface representing a method.
struct Method {
virtual ~Method() {}
virtual grpc::string name() const = 0;
virtual grpc::string input_type_name() const = 0;
virtual grpc::string output_type_name() const = 0;
virtual bool NoStreaming() const = 0;
virtual bool ClientOnlyStreaming() const = 0;
virtual bool ServerOnlyStreaming() const = 0;
virtual bool BidiStreaming() const = 0;
};
// An abstract interface representing a service.
struct Service {
virtual ~Service() {}
virtual grpc::string name() const = 0;
virtual int method_count() const = 0;
virtual std::unique_ptr<const Method> method(int i) const = 0;
};
struct Printer {
virtual ~Printer() {}
virtual void Print(const std::map<grpc::string, grpc::string> &vars,
const char *template_string) = 0;
virtual void Print(const char *string) = 0;
virtual void Indent() = 0;
virtual void Outdent() = 0;
};
// An interface that allows the source generated to be output using various
// libraries/idls/serializers.
struct File {
virtual ~File() {}
virtual grpc::string filename() const = 0;
virtual grpc::string filename_without_ext() const = 0;
virtual grpc::string message_header_ext() const = 0;
virtual grpc::string service_header_ext() const = 0;
virtual grpc::string package() const = 0;
virtual std::vector<grpc::string> package_parts() const = 0;
virtual grpc::string additional_headers() const = 0;
virtual int service_count() const = 0;
virtual std::unique_ptr<const Service> service(int i) const = 0;
virtual std::unique_ptr<Printer> CreatePrinter(grpc::string *str) const = 0;
};
// Return the prologue of the generated header file.
grpc::string GetHeaderPrologue(File *file, const Parameters &params);
// Return the includes needed for generated header file.
grpc::string GetHeaderIncludes(File *file, const Parameters &params);
// Return the includes needed for generated source file.
grpc::string GetSourceIncludes(File *file, const Parameters &params);
// Return the epilogue of the generated header file.
grpc::string GetHeaderEpilogue(File *file, const Parameters &params);
// Return the prologue of the generated source file.
grpc::string GetSourcePrologue(File *file, const Parameters &params);
// Return the services for generated header file.
grpc::string GetHeaderServices(File *file, const Parameters &params);
// Return the services for generated source file.
grpc::string GetSourceServices(File *file, const Parameters &params);
// Return the epilogue of the generated source file.
grpc::string GetSourceEpilogue(File *file, const Parameters &params);
} // namespace grpc_cpp_generator
#endif // GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H

124
grpc/tests/grpctest.cpp Normal file
View File

@@ -0,0 +1,124 @@
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thread>
#include <grpc++/grpc++.h>
#include "monster_test_generated.h"
#include "monster_test.grpc.fb.h"
using namespace MyGame::Example;
// The callback implementation of our server, that derives from the generated
// code. It implements all rpcs specified in the FlatBuffers schema.
class ServiceImpl final : public MyGame::Example::MonsterStorage::Service {
virtual ::grpc::Status Store(::grpc::ServerContext* context,
const flatbuffers::BufferRef<Monster> *request,
flatbuffers::BufferRef<Stat> *response)
override {
// Create a response from the incoming request name.
fbb_.Clear();
auto stat_offset = CreateStat(fbb_, fbb_.CreateString("Hello, " +
request->GetRoot()->name()->str()));
fbb_.Finish(stat_offset);
// Since we keep reusing the same FlatBufferBuilder, the memory it owns
// remains valid until the next call (this BufferRef doesn't own the
// memory it points to).
*response = flatbuffers::BufferRef<Stat>(fbb_.GetBufferPointer(),
fbb_.GetSize());
return grpc::Status::OK;
}
virtual ::grpc::Status Retrieve(::grpc::ServerContext *context,
const flatbuffers::BufferRef<Stat> *request,
flatbuffers::BufferRef<Monster> *response)
override {
assert(false); // We're not actually using this RPC.
return grpc::Status::CANCELLED;
}
private:
flatbuffers::FlatBufferBuilder fbb_;
};
// Track the server instance, so we can terminate it later.
grpc::Server *server_instance = nullptr;
// Mutex to protec this variable.
std::mutex wait_for_server;
std::condition_variable server_instance_cv;
// This function implements the server thread.
void RunServer() {
auto server_address = "0.0.0.0:50051";
// Callback interface we implemented above.
ServiceImpl service;
grpc::ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
// Start the server. Lock to change the variable we're changing.
wait_for_server.lock();
server_instance = builder.BuildAndStart().release();
wait_for_server.unlock();
server_instance_cv.notify_one();
std::cout << "Server listening on " << server_address << std::endl;
// This will block the thread and serve requests.
server_instance->Wait();
}
int main(int /*argc*/, const char * /*argv*/[]) {
// Launch server.
std::thread server_thread(RunServer);
// wait for server to spin up.
std::unique_lock<std::mutex> lock(wait_for_server);
while (!server_instance) server_instance_cv.wait(lock);
// Now connect the client.
auto channel = grpc::CreateChannel("localhost:50051",
grpc::InsecureChannelCredentials());
auto stub = MyGame::Example::MonsterStorage::NewStub(channel);
grpc::ClientContext context;
// Build a request with the name set.
flatbuffers::FlatBufferBuilder fbb;
auto monster_offset = CreateMonster(fbb, 0, 0, 0, fbb.CreateString("Fred"));
fbb.Finish(monster_offset);
auto request = flatbuffers::BufferRef<Monster>(fbb.GetBufferPointer(),
fbb.GetSize());
flatbuffers::BufferRef<Stat> response;
// The actual RPC.
auto status = stub->Store(&context, request, &response);
if (status.ok()) {
auto resp = response.GetRoot()->id();
std::cout << "RPC response: " << resp->str() << std::endl;
} else {
std::cout << "RPC failed" << std::endl;
}
server_instance->Shutdown();
server_thread.join();
delete server_instance;
return 0;
}

View File

@@ -0,0 +1,124 @@
/*
* 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.
*/
#ifndef FLATBUFFERS_CODE_GENERATORS_H_
#define FLATBUFFERS_CODE_GENERATORS_H_
namespace flatbuffers {
class BaseGenerator {
public:
virtual bool generate() = 0;
static const std::string NamespaceDir(const Parser &parser,
const std::string &path,
const Namespace &ns) {
EnsureDirExists(path.c_str());
if (parser.opts.one_file) return path;
std::string namespace_dir = path; // Either empty or ends in separator.
auto &namespaces = ns.components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
namespace_dir += *it + kPathSeparator;
EnsureDirExists(namespace_dir.c_str());
}
return namespace_dir;
}
protected:
BaseGenerator(const Parser &parser, const std::string &path,
const std::string &file_name,
const std::string qualifying_start,
const std::string qualifying_separator)
: parser_(parser),
path_(path),
file_name_(file_name),
qualifying_start_(qualifying_start),
qualifying_separator_(qualifying_separator){};
virtual ~BaseGenerator(){};
// No copy/assign.
BaseGenerator &operator=(const BaseGenerator &);
BaseGenerator(const BaseGenerator &);
const std::string NamespaceDir(const Namespace &ns) {
return BaseGenerator::NamespaceDir(parser_, path_, ns);
}
const char *FlatBuffersGeneratedWarning() {
return "automatically generated by the FlatBuffers compiler,"
" do not modify\n\n";
}
bool IsEverythingGenerated() {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
if (!(*it)->generated) return false;
}
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
if (!(*it)->generated) return false;
}
return true;
}
std::string FullNamespace(const char *separator, const Namespace &ns) {
std::string namespace_name;
auto &namespaces = ns.components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
if (namespace_name.length()) namespace_name += separator;
namespace_name += *it;
}
return namespace_name;
}
const std::string LastNamespacePart(const Namespace &ns) {
auto &namespaces = ns.components;
if (namespaces.size())
return *(namespaces.end() - 1);
else
return std::string("");
}
// tracks the current namespace for early exit in WrapInNameSpace
// c++, java and csharp returns a different namespace from
// the following default (no early exit, always fully qualify),
// which works for js and php
virtual const Namespace *CurrentNameSpace() { return nullptr; }
// Ensure that a type is prefixed with its namespace whenever it is used
// outside of its namespace.
std::string WrapInNameSpace(const Namespace *ns, const std::string &name) {
if (CurrentNameSpace() == ns) return name;
std::string qualified_name = qualifying_start_;
for (auto it = ns->components.begin(); it != ns->components.end(); ++it)
qualified_name += *it + qualifying_separator_;
return qualified_name + name;
}
std::string WrapInNameSpace(const Definition &def) {
return WrapInNameSpace(def.defined_namespace, def.name);
}
const Parser &parser_;
const std::string &path_;
const std::string &file_name_;
const std::string qualifying_start_;
const std::string qualifying_separator_;
};
} // namespace flatbuffers
#endif // FLATBUFFERS_CODE_GENERATORS_H_

View File

@@ -24,27 +24,36 @@
#include <cstdlib>
#include <cstring>
#include <string>
#include <utility>
#include <type_traits>
#include <vector>
#include <set>
#include <algorithm>
#include <functional>
#include <memory>
#ifdef _STLPORT_VERSION
#define FLATBUFFERS_CPP98_STL
#endif
#ifndef FLATBUFFERS_CPP98_STL
#include <functional>
#endif
/// @cond FLATBUFFERS_INTERNAL
#if __cplusplus <= 199711L && \
(!defined(_MSC_VER) || _MSC_VER < 1600) && \
(!defined(__GNUC__) || \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ < 40400))
#error A C++11 compatible compiler with support for the auto typing is required for FlatBuffers.
#error A C++11 compatible compiler with support for the auto typing is \
required for FlatBuffers.
#error __cplusplus _MSC_VER __GNUC__ __GNUC_MINOR__ __GNUC_PATCHLEVEL__
#endif
#if !defined(__clang__) && \
defined(__GNUC__) && \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ < 40600)
// Backwards compatability for g++ 4.4, and 4.5 which don't have the nullptr and constexpr
// keywords. Note the __clang__ check is needed, because clang presents itself as an older GNUC
// compiler.
// Backwards compatability for g++ 4.4, and 4.5 which don't have the nullptr
// and constexpr keywords. Note the __clang__ check is needed, because clang
// presents itself as an older GNUC compiler.
#ifndef nullptr_t
const class nullptr_t {
public:
@@ -90,6 +99,14 @@
#else
#define FLATBUFFERS_FINAL_CLASS
#endif
#if (!defined(_MSC_VER) || _MSC_VER >= 1900) && \
(!defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 406))
#define FLATBUFFERS_CONSTEXPR constexpr
#else
#define FLATBUFFERS_CONSTEXPR
#endif
/// @endcond
/// @file
@@ -110,9 +127,14 @@ typedef uint16_t voffset_t;
typedef uintmax_t largest_scalar_t;
// In 32bits, this evaluates to 2GB - 1
#define FLATBUFFERS_MAX_BUFFER_SIZE ((1ULL << (sizeof(soffset_t) * 8 - 1)) - 1)
#ifndef FLATBUFFERS_CPP98_STL
// Pointer to relinquished memory.
typedef std::unique_ptr<uint8_t, std::function<void(uint8_t * /* unused */)>>
unique_ptr_t;
#endif
// Wrapper for uoffset_t to allow safe template specialization.
template<typename T> struct Offset {
@@ -129,39 +151,43 @@ inline void EndianCheck() {
(void)endiantest;
}
template<typename T> T EndianSwap(T t) {
#if defined(_MSC_VER)
#define FLATBUFFERS_BYTESWAP16 _byteswap_ushort
#define FLATBUFFERS_BYTESWAP32 _byteswap_ulong
#define FLATBUFFERS_BYTESWAP64 _byteswap_uint64
#else
#if defined(__GNUC__) && __GNUC__ * 100 + __GNUC_MINOR__ < 408
// __builtin_bswap16 was missing prior to GCC 4.8.
#define FLATBUFFERS_BYTESWAP16(x) \
static_cast<uint16_t>(__builtin_bswap32(static_cast<uint32_t>(x) << 16))
#else
#define FLATBUFFERS_BYTESWAP16 __builtin_bswap16
#endif
#define FLATBUFFERS_BYTESWAP32 __builtin_bswap32
#define FLATBUFFERS_BYTESWAP64 __builtin_bswap64
#endif
if (sizeof(T) == 1) { // Compile-time if-then's.
return t;
} else if (sizeof(T) == 2) {
auto r = FLATBUFFERS_BYTESWAP16(*reinterpret_cast<uint16_t *>(&t));
return *reinterpret_cast<T *>(&r);
} else if (sizeof(T) == 4) {
auto r = FLATBUFFERS_BYTESWAP32(*reinterpret_cast<uint32_t *>(&t));
return *reinterpret_cast<T *>(&r);
} else if (sizeof(T) == 8) {
auto r = FLATBUFFERS_BYTESWAP64(*reinterpret_cast<uint64_t *>(&t));
return *reinterpret_cast<T *>(&r);
} else {
assert(0);
}
}
template<typename T> T EndianScalar(T t) {
#if FLATBUFFERS_LITTLEENDIAN
return t;
#else
#if defined(_MSC_VER)
#pragma push_macro("__builtin_bswap16")
#pragma push_macro("__builtin_bswap32")
#pragma push_macro("__builtin_bswap64")
#define __builtin_bswap16 _byteswap_ushort
#define __builtin_bswap32 _byteswap_ulong
#define __builtin_bswap64 _byteswap_uint64
#endif
// If you're on the few remaining big endian platforms, we make the bold
// assumption you're also on gcc/clang, and thus have bswap intrinsics:
if (sizeof(T) == 1) { // Compile-time if-then's.
return t;
} else if (sizeof(T) == 2) {
auto r = __builtin_bswap16(*reinterpret_cast<uint16_t *>(&t));
return *reinterpret_cast<T *>(&r);
} else if (sizeof(T) == 4) {
auto r = __builtin_bswap32(*reinterpret_cast<uint32_t *>(&t));
return *reinterpret_cast<T *>(&r);
} else if (sizeof(T) == 8) {
auto r = __builtin_bswap64(*reinterpret_cast<uint64_t *>(&t));
return *reinterpret_cast<T *>(&r);
} else {
assert(0);
}
#if defined(_MSC_VER)
#pragma pop_macro("__builtin_bswap16")
#pragma pop_macro("__builtin_bswap32")
#pragma pop_macro("__builtin_bswap64")
#endif
return EndianSwap(t);
#endif
}
@@ -195,6 +221,7 @@ template<typename T> size_t AlignOf() {
// (avoiding the need for a trailing return decltype)
template<typename T> struct IndirectHelper {
typedef T return_type;
typedef T mutable_return_type;
static const size_t element_stride = sizeof(T);
static return_type Read(const uint8_t *p, uoffset_t i) {
return EndianScalar((reinterpret_cast<const T *>(p))[i]);
@@ -202,6 +229,7 @@ template<typename T> struct IndirectHelper {
};
template<typename T> struct IndirectHelper<Offset<T>> {
typedef const T *return_type;
typedef T *mutable_return_type;
static const size_t element_stride = sizeof(uoffset_t);
static return_type Read(const uint8_t *p, uoffset_t i) {
p += i * sizeof(uoffset_t);
@@ -210,6 +238,7 @@ template<typename T> struct IndirectHelper<Offset<T>> {
};
template<typename T> struct IndirectHelper<const T *> {
typedef const T *return_type;
typedef T *mutable_return_type;
static const size_t element_stride = sizeof(T);
static return_type Read(const uint8_t *p, uoffset_t i) {
return reinterpret_cast<const T *>(p + i * sizeof(T));
@@ -218,23 +247,19 @@ template<typename T> struct IndirectHelper<const T *> {
// An STL compatible iterator implementation for Vector below, effectively
// calling Get() for every element.
template<typename T, bool bConst>
struct VectorIterator : public
std::iterator < std::input_iterator_tag,
typename std::conditional < bConst,
const typename IndirectHelper<T>::return_type,
typename IndirectHelper<T>::return_type > ::type, uoffset_t > {
template<typename T, typename IT>
struct VectorIterator
: public std::iterator<std::input_iterator_tag, IT, uoffset_t> {
typedef std::iterator<std::input_iterator_tag,
typename std::conditional<bConst,
const typename IndirectHelper<T>::return_type,
typename IndirectHelper<T>::return_type>::type, uoffset_t> super_type;
typedef std::iterator<std::input_iterator_tag, IT, uoffset_t> super_type;
public:
VectorIterator(const uint8_t *data, uoffset_t i) :
data_(data + IndirectHelper<T>::element_stride * i) {};
VectorIterator(const VectorIterator &other) : data_(other.data_) {}
#ifndef FLATBUFFERS_CPP98_STL
VectorIterator(VectorIterator &&other) : data_(std::move(other.data_)) {}
#endif
VectorIterator &operator=(const VectorIterator &other) {
data_ = other.data_;
@@ -272,7 +297,7 @@ public:
}
VectorIterator operator++(int) {
VectorIterator temp(data_);
VectorIterator temp(data_,0);
data_ += IndirectHelper<T>::element_stride;
return temp;
}
@@ -285,8 +310,10 @@ private:
// Vector::data() assumes the vector elements start after the length field.
template<typename T> class Vector {
public:
typedef VectorIterator<T, false> iterator;
typedef VectorIterator<T, true> const_iterator;
typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type>
iterator;
typedef VectorIterator<T, typename IndirectHelper<T>::return_type>
const_iterator;
uoffset_t size() const { return EndianScalar(length_); }
@@ -294,6 +321,7 @@ public:
uoffset_t Length() const { return size(); }
typedef typename IndirectHelper<T>::return_type return_type;
typedef typename IndirectHelper<T>::mutable_return_type mutable_return_type;
return_type Get(uoffset_t i) const {
assert(i < size());
@@ -321,7 +349,7 @@ public:
// Change elements if you have a non-const pointer to this object.
// Scalars only. See reflection.h, and the documentation.
void Mutate(uoffset_t i, T val) {
void Mutate(uoffset_t i, const T& val) {
assert(i < size());
WriteScalar(data() + i, val);
}
@@ -332,7 +360,14 @@ public:
void MutateOffset(uoffset_t i, const uint8_t *val) {
assert(i < size());
assert(sizeof(T) == sizeof(uoffset_t));
WriteScalar(data() + i, val - (Data() + i * sizeof(uoffset_t)));
WriteScalar(data() + i,
static_cast<uoffset_t>(val - (Data() + i * sizeof(uoffset_t))));
}
// Get a mutable pointer to tables/strings inside this vector.
mutable_return_type GetMutableObject(uoffset_t i) const {
assert(i < size());
return const_cast<mutable_return_type>(IndirectHelper<T>::Read(Data(), i));
}
// The raw data in little endian format. Use with care.
@@ -448,6 +483,7 @@ class vector_downward {
cur_ = buf_ + reserved_;
}
#ifndef FLATBUFFERS_CPP98_STL
// Relinquish the pointer to the caller.
unique_ptr_t release() {
// Actually deallocate from the start of the allocated memory.
@@ -463,6 +499,7 @@ class vector_downward {
return retval;
}
#endif
size_t growth_policy(size_t bytes) {
return (bytes / 2) & ~(sizeof(largest_scalar_t) - 1);
@@ -485,7 +522,7 @@ class vector_downward {
cur_ -= len;
// Beyond this, signed offsets may not have enough range:
// (FlatBuffers > 2GB not supported).
assert(size() < (1UL << (sizeof(soffset_t) * 8 - 1)) - 1);
assert(size() < FLATBUFFERS_MAX_BUFFER_SIZE);
return cur_;
}
@@ -499,7 +536,7 @@ class vector_downward {
return cur_;
}
uint8_t *data_at(size_t offset) { return buf_ + reserved_ - offset; }
uint8_t *data_at(size_t offset) const { return buf_ + reserved_ - offset; }
// push() & fill() are most frequently called with small byte counts (<= 4),
// which is why we're using loops rather than calling memcpy/memset.
@@ -530,7 +567,7 @@ class vector_downward {
inline voffset_t FieldIndexToOffset(voffset_t field_id) {
// Should correspond to what EndTable() below builds up.
const int fixed_fields = 2; // Vtable size and Object Size.
return (field_id + fixed_fields) * sizeof(voffset_t);
return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
}
// Computes how many bytes you'd have to pad to be able to write an
@@ -539,6 +576,10 @@ inline voffset_t FieldIndexToOffset(voffset_t field_id) {
inline size_t PaddingBytes(size_t buf_size, size_t scalar_size) {
return ((~buf_size) + 1) & (scalar_size - 1);
}
template <typename T> const T* data(const std::vector<T> &v) {
return v.empty() ? nullptr : &v.front();
}
/// @endcond
/// @addtogroup flatbuffers_cpp_api
@@ -565,12 +606,17 @@ FLATBUFFERS_FINAL_CLASS
explicit FlatBufferBuilder(uoffset_t initial_size = 1024,
const simple_allocator *allocator = nullptr)
: buf_(initial_size, allocator ? *allocator : default_allocator),
nested(false), finished(false), minalign_(1), force_defaults_(false) {
nested(false), finished(false), minalign_(1), force_defaults_(false),
string_pool(nullptr) {
offsetbuf_.reserve(16); // Avoid first few reallocs.
vtables_.reserve(16);
EndianCheck();
}
~FlatBufferBuilder() {
if (string_pool) delete string_pool;
}
/// @brief Reset all the state in this FlatBufferBuilder so it can be reused
/// to construct another buffer.
void Clear() {
@@ -580,6 +626,7 @@ FLATBUFFERS_FINAL_CLASS
finished = false;
vtables_.clear();
minalign_ = 1;
if (string_pool) string_pool->clear();
}
/// @brief The current size of the serialized buffer, counting from the end.
@@ -598,6 +645,7 @@ FLATBUFFERS_FINAL_CLASS
/// @return Returns a `uint8_t` pointer to the unfinished buffer.
uint8_t *GetCurrentBufferPointer() const { return buf_.data(); }
#ifndef FLATBUFFERS_CPP98_STL
/// @brief Get the released pointer to the serialized buffer.
/// @warning Do NOT attempt to use this FlatBufferBuilder afterwards!
/// @return The `unique_ptr` returned has a special allocator that knows how
@@ -608,6 +656,7 @@ FLATBUFFERS_FINAL_CLASS
Finished();
return buf_.release();
}
#endif
/// @cond FLATBUFFERS_INTERNAL
void Finished() const {
@@ -645,11 +694,13 @@ FLATBUFFERS_FINAL_CLASS
void PopBytes(size_t amount) { buf_.pop(amount); }
template<typename T> void AssertScalarT() {
#ifndef FLATBUFFERS_CPP98_STL
// The code assumes power of 2 sizes and endian-swap-ability.
static_assert(std::is_scalar<T>::value
// The Offset<T> type is essentially a scalar but fails is_scalar.
|| sizeof(T) == sizeof(Offset<void>),
"T must be a scalar type");
#endif
}
// Write a single aligned scalar to the buffer
@@ -705,7 +756,7 @@ FLATBUFFERS_FINAL_CLASS
Align(sizeof(uoffset_t));
// Offset must refer to something already in buffer.
assert(off && off <= GetSize());
return GetSize() - off + sizeof(uoffset_t);
return GetSize() - off + static_cast<uoffset_t>(sizeof(uoffset_t));
}
void NotNested() {
@@ -829,7 +880,7 @@ FLATBUFFERS_FINAL_CLASS
return Offset<String>(GetSize());
}
/// @brief Store a string in the buffer, which can contain any binary data.
/// @brief Store a string in the buffer, which is null-terminated.
/// @param[in] str A const char pointer to a C-string to add to the buffer.
/// @return Returns the offset in the buffer where the string starts.
Offset<String> CreateString(const char *str) {
@@ -847,7 +898,59 @@ FLATBUFFERS_FINAL_CLASS
/// @param[in] str A const pointer to a `String` struct to add to the buffer.
/// @return Returns the offset in the buffer where the string starts
Offset<String> CreateString(const String *str) {
return CreateString(str->c_str(), str->Length());
return str ? CreateString(str->c_str(), str->Length()) : 0;
}
/// @brief Store a string in the buffer, which can contain any binary data.
/// If a string with this exact contents has already been serialized before,
/// instead simply returns the offset of the existing string.
/// @param[in] str A const char pointer to the data to be stored as a string.
/// @param[in] len The number of bytes that should be stored from `str`.
/// @return Returns the offset in the buffer where the string starts.
Offset<String> CreateSharedString(const char *str, size_t len) {
if (!string_pool)
string_pool = new StringOffsetMap(StringOffsetCompare(buf_));
auto size_before_string = buf_.size();
// Must first serialize the string, since the set is all offsets into
// buffer.
auto off = CreateString(str, len);
auto it = string_pool->find(off);
// If it exists we reuse existing serialized data!
if (it != string_pool->end()) {
// We can remove the string we serialized.
buf_.pop(buf_.size() - size_before_string);
return *it;
}
// Record this string for future use.
string_pool->insert(off);
return off;
}
/// @brief Store a string in the buffer, which null-terminated.
/// If a string with this exact contents has already been serialized before,
/// instead simply returns the offset of the existing string.
/// @param[in] str A const char pointer to a C-string to add to the buffer.
/// @return Returns the offset in the buffer where the string starts.
Offset<String> CreateSharedString(const char *str) {
return CreateSharedString(str, strlen(str));
}
/// @brief Store a string in the buffer, which can contain any binary data.
/// If a string with this exact contents has already been serialized before,
/// instead simply returns the offset of the existing string.
/// @param[in] str A const reference to a std::string to store in the buffer.
/// @return Returns the offset in the buffer where the string starts.
Offset<String> CreateSharedString(const std::string &str) {
return CreateSharedString(str.c_str(), str.length());
}
/// @brief Store a string in the buffer, which can contain any binary data.
/// If a string with this exact contents has already been serialized before,
/// instead simply returns the offset of the existing string.
/// @param[in] str A const pointer to a `String` struct to add to the buffer.
/// @return Returns the offset in the buffer where the string starts
Offset<String> CreateSharedString(const String *str) {
return CreateSharedString(str->c_str(), str->Length());
}
/// @cond FLATBUFFERS_INTERNAL
@@ -900,7 +1003,47 @@ FLATBUFFERS_FINAL_CLASS
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T> Offset<Vector<T>> CreateVector(const std::vector<T> &v) {
return CreateVector(v.data(), v.size());
return CreateVector(data(v), v.size());
}
// vector<bool> may be implemented using a bit-set, so we can't access it as
// an array. Instead, read elements manually.
// Background: https://isocpp.org/blog/2012/11/on-vectorbool
Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) {
StartVector(v.size(), sizeof(uint8_t));
for (auto i = v.size(); i > 0; ) {
PushElement(static_cast<uint8_t>(v[--i]));
}
return Offset<Vector<uint8_t>>(EndVector(v.size()));
}
#ifndef FLATBUFFERS_CPP98_STL
/// @brief Serialize values returned by a function into a FlatBuffer `vector`.
/// This is a convenience function that takes care of iteration for you.
/// @tparam T The data type of the `std::vector` elements.
/// @param f A function that takes the current iteration 0..vector_size-1 and
/// returns any type that you can construct a FlatBuffers vector out of.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T> Offset<Vector<T>> CreateVector(size_t vector_size,
const std::function<T (size_t i)> &f) {
std::vector<T> elems(vector_size);
for (size_t i = 0; i < vector_size; i++) elems[i] = f(i);
return CreateVector(elems);
}
#endif
/// @brief Serialize a `std::vector<std::string>` into a FlatBuffer `vector`.
/// This is a convenience function for a common case.
/// @param v A const reference to the `std::vector` to serialize into the
/// buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
Offset<Vector<Offset<String>>> CreateVectorOfStrings(
const std::vector<std::string> &v) {
std::vector<Offset<String>> offsets(v.size());
for (size_t i = 0; i < v.size(); i++) offsets[i] = CreateString(v[i]);
return CreateVector(offsets);
}
/// @brief Serialize an array of structs into a FlatBuffer `vector`.
@@ -911,7 +1054,7 @@ FLATBUFFERS_FINAL_CLASS
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T> Offset<Vector<const T *>> CreateVectorOfStructs(
const T *v, size_t len) {
const T *v, size_t len) {
StartVector(len * sizeof(T) / AlignOf<T>(), AlignOf<T>());
PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
return Offset<Vector<const T *>>(EndVector(len));
@@ -924,8 +1067,8 @@ FLATBUFFERS_FINAL_CLASS
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T> Offset<Vector<const T *>> CreateVectorOfStructs(
const std::vector<T> &v) {
return CreateVectorOfStructs(v.data(), v.size());
const std::vector<T> &v) {
return CreateVectorOfStructs(data(v), v.size());
}
/// @cond FLATBUFFERS_INTERNAL
@@ -953,7 +1096,7 @@ FLATBUFFERS_FINAL_CLASS
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T> Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
Offset<T> *v, size_t len) {
Offset<T> *v, size_t len) {
std::sort(v, v + len, TableKeyComparator<T>(buf_));
return CreateVector(v, len);
}
@@ -966,7 +1109,7 @@ FLATBUFFERS_FINAL_CLASS
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T> Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
std::vector<Offset<T>> *v) {
std::vector<Offset<T>> *v) {
return CreateVectorOfSortedTables(v->data(), v->size());
}
@@ -981,8 +1124,11 @@ FLATBUFFERS_FINAL_CLASS
uint8_t **buf) {
NotNested();
StartVector(len, elemsize);
*buf = buf_.make_space(len * elemsize);
return EndVector(len);
buf_.make_space(len * elemsize);
auto vec_start = GetSize();
auto vec_end = EndVector(len);
*buf = buf_.data_at(vec_start);
return vec_end;
}
/// @brief Specialized version of `CreateVector` for non-copying use cases.
@@ -994,7 +1140,7 @@ FLATBUFFERS_FINAL_CLASS
/// written to at a later time to serialize the data into a `vector`
/// in the buffer.
template<typename T> Offset<Vector<T>> CreateUninitializedVector(
size_t len, T **buf) {
size_t len, T **buf) {
return CreateUninitializedVector(len, sizeof(T),
reinterpret_cast<uint8_t **>(buf));
}
@@ -1048,6 +1194,21 @@ FLATBUFFERS_FINAL_CLASS
size_t minalign_;
bool force_defaults_; // Serialize values equal to their defaults anyway.
struct StringOffsetCompare {
StringOffsetCompare(const vector_downward &buf) : buf_(&buf) {}
bool operator() (const Offset<String> &a, const Offset<String> &b) const {
auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o));
auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o));
return strncmp(stra->c_str(), strb->c_str(),
std::min(stra->size(), strb->size()) + 1) < 0;
}
const vector_downward *buf_;
};
// For use with CreateSharedString. Instantiated on first use only.
typedef std::set<Offset<String>, StringOffsetCompare> StringOffsetMap;
StringOffsetMap *string_pool;
};
/// @}
@@ -1063,6 +1224,20 @@ template<typename T> const T *GetRoot(const void *buf) {
return GetMutableRoot<T>(const_cast<void *>(buf));
}
/// Helpers to get a typed pointer to objects that are currently beeing built.
/// @warning Creating new objects will lead to reallocations and invalidates
/// the pointer!
template<typename T> T *GetMutableTemporaryPointer(FlatBufferBuilder &fbb,
Offset<T> offset) {
return reinterpret_cast<T *>(fbb.GetCurrentBufferPointer() +
fbb.GetSize() - offset.o);
}
template<typename T> const T *GetTemporaryPointer(FlatBufferBuilder &fbb,
Offset<T> offset) {
return GetMutableTemporaryPointer<T>(fbb, offset);
}
// Helper to see if the identifier in a buffer has the expected value.
inline bool BufferHasIdentifier(const void *buf, const char *identifier) {
return strncmp(reinterpret_cast<const char *>(buf) + sizeof(uoffset_t),
@@ -1076,6 +1251,9 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
size_t _max_tables = 1000000)
: buf_(buf), end_(buf + buf_len), depth_(0), max_depth_(_max_depth),
num_tables_(0), max_tables_(_max_tables)
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
, upper_bound_(buf)
#endif
{}
// Central location where any verification failures register.
@@ -1083,12 +1261,23 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
#ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
assert(ok);
#endif
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
if (!ok)
upper_bound_ = buf_;
#endif
return ok;
}
// Verify any range within the buffer.
bool Verify(const void *elem, size_t elem_len) const {
return Check(elem_len <= (size_t) (end_ - buf_) && elem >= buf_ && elem <= end_ - elem_len);
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
auto upper_bound = reinterpret_cast<const uint8_t *>(elem) + elem_len;
if (upper_bound_ < upper_bound)
upper_bound_ = upper_bound;
#endif
return Check(elem_len <= (size_t) (end_ - buf_) &&
elem >= buf_ &&
elem <= end_ - elem_len);
}
// Verify a range indicated by sizeof(T).
@@ -1131,6 +1320,9 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
// Check the whole array. If this is a string, the byte past the array
// must be 0.
auto size = ReadScalar<uoffset_t>(vec);
auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size;
if (!Check(size < max_elems))
return false; // Protect against byte_size overflowing.
auto byte_size = sizeof(size) + elem_size * size;
*end = vec + byte_size;
return Verify(vec, byte_size);
@@ -1157,11 +1349,20 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
}
// Verify this whole buffer, starting with root type T.
template<typename T> bool VerifyBuffer() {
template<typename T> bool VerifyBuffer(const char *identifier) {
if (identifier && (size_t(end_ - buf_) < 2 * sizeof(flatbuffers::uoffset_t) ||
!BufferHasIdentifier(buf_, identifier))) {
return false;
}
// Call T::Verify, which must be in the generated code for this type.
return Verify<uoffset_t>(buf_) &&
reinterpret_cast<const T *>(buf_ + ReadScalar<uoffset_t>(buf_))->
Verify(*this);
Verify(*this)
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
&& GetComputedSize()
#endif
;
}
// Called at the start of a table to increase counters measuring data
@@ -1180,6 +1381,16 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
return true;
}
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
// Returns the message size in bytes
size_t GetComputedSize() const {
uintptr_t size = upper_bound_ - buf_;
// Align the size to uoffset_t
size = (size - 1 + sizeof(uoffset_t)) & ~(sizeof(uoffset_t) - 1);
return (buf_ + size > end_) ? 0 : size;
}
#endif
private:
const uint8_t *buf_;
const uint8_t *end_;
@@ -1187,6 +1398,32 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
size_t max_depth_;
size_t num_tables_;
size_t max_tables_;
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
mutable const uint8_t *upper_bound_;
#endif
};
// Convenient way to bundle a buffer and its length, to pass it around
// typed by its root.
// A BufferRef does not own its buffer.
struct BufferRefBase {}; // for std::is_base_of
template<typename T> struct BufferRef : BufferRefBase {
BufferRef() : buf(nullptr), len(0), must_free(false) {}
BufferRef(uint8_t *_buf, uoffset_t _len)
: buf(_buf), len(_len), must_free(false) {}
~BufferRef() { if (must_free) free(buf); }
const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); }
bool Verify() {
Verifier verifier(buf, len);
return verifier.VerifyBuffer<T>();
}
uint8_t *buf;
uoffset_t len;
bool must_free;
};
// "structs" are flat structures that do not have an offset table, thus
@@ -1263,7 +1500,8 @@ class Table {
bool SetPointer(voffset_t field, const uint8_t *val) {
auto field_offset = GetOptionalFieldOffset(field);
if (!field_offset) return false;
WriteScalar(data_ + field_offset, val - (data_ + field_offset));
WriteScalar(data_ + field_offset,
static_cast<uoffset_t>(val - (data_ + field_offset)));
return true;
}
@@ -1290,6 +1528,7 @@ class Table {
// Check the vtable size field, then check vtable fits in its entirety.
return verifier.VerifyComplexity() &&
verifier.Verify<voffset_t>(vtable) &&
(ReadScalar<voffset_t>(vtable) & (sizeof(voffset_t) - 1)) == 0 &&
verifier.Verify(vtable, ReadScalar<voffset_t>(vtable));
}
@@ -1320,6 +1559,12 @@ class Table {
uint8_t data_[1];
};
// Base class for native objects (FlatBuffer data de-serialized into native
// C++ data structures).
// Contains no functionality, purely documentative.
struct NativeTable {
};
// Helper function to test if a field is present, using any of the field
// enums in the generated code.
// `table` must be a generated table type. Since this is a template parameter,
@@ -1391,6 +1636,35 @@ volatile __attribute__((weak)) const char *flatbuffer_version_string =
#endif // !defined(_WIN32) && !defined(__CYGWIN__)
#define DEFINE_BITMASK_OPERATORS(E, T)\
inline E operator | (E lhs, E rhs){\
return E(T(lhs) | T(rhs));\
}\
inline E operator & (E lhs, E rhs){\
return E(T(lhs) & T(rhs));\
}\
inline E operator ^ (E lhs, E rhs){\
return E(T(lhs) ^ T(rhs));\
}\
inline E operator ~ (E lhs){\
return E(~T(lhs));\
}\
inline E operator |= (E &lhs, E rhs){\
lhs = lhs | rhs;\
return lhs;\
}\
inline E operator &= (E &lhs, E rhs){\
lhs = lhs & rhs;\
return lhs;\
}\
inline E operator ^= (E &lhs, E rhs){\
lhs = lhs ^ rhs;\
return lhs;\
}\
inline bool operator !(E rhs) \
{\
return !bool(T(rhs)); \
}
/// @endcond
} // namespace flatbuffers

View File

@@ -0,0 +1,72 @@
/*
* 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.
*/
#ifndef FLATBUFFERS_GRPC_H_
#define FLATBUFFERS_GRPC_H_
// Helper functionality to glue FlatBuffers and GRPC.
#include "grpc++/support/byte_buffer.h"
#include "grpc/byte_buffer_reader.h"
namespace grpc {
template <class T>
class SerializationTraits<T, typename std::enable_if<std::is_base_of<
flatbuffers::BufferRefBase, T>::value>::type> {
public:
// The type we're passing here is a BufferRef, which is already serialized
// FlatBuffer data, which then gets passed to GRPC.
static grpc::Status Serialize(const T& msg,
grpc_byte_buffer **buffer,
bool *own_buffer) {
// TODO(wvo): make this work without copying.
auto slice = gpr_slice_from_copied_buffer(
reinterpret_cast<const char *>(msg.buf), msg.len);
*buffer = grpc_raw_byte_buffer_create(&slice, 1);
*own_buffer = true;
return grpc::Status();
}
// There is no de-serialization step in FlatBuffers, so we just receive
// the data from GRPC.
static grpc::Status Deserialize(grpc_byte_buffer *buffer,
T *msg,
int max_message_size) {
// TODO(wvo): make this more efficient / zero copy when possible.
auto len = grpc_byte_buffer_length(buffer);
msg->buf = reinterpret_cast<uint8_t *>(malloc(len));
msg->len = static_cast<flatbuffers::uoffset_t>(len);
msg->must_free = true;
uint8_t *current = msg->buf;
grpc_byte_buffer_reader reader;
grpc_byte_buffer_reader_init(&reader, buffer);
gpr_slice slice;
while (grpc_byte_buffer_reader_next(&reader, &slice)) {
memcpy(current, GPR_SLICE_START_PTR(slice), GPR_SLICE_LENGTH(slice));
current += GPR_SLICE_LENGTH(slice);
gpr_slice_unref(slice);
}
GPR_ASSERT(current == msg->buf + msg->len);
grpc_byte_buffer_reader_destroy(&reader);
grpc_byte_buffer_destroy(buffer);
return grpc::Status();
}
};
} // namespace grpc;
#endif // FLATBUFFERS_GRPC_H_

View File

@@ -18,7 +18,6 @@
#define FLATBUFFERS_IDL_H_
#include <map>
#include <set>
#include <stack>
#include <memory>
#include <functional>
@@ -113,6 +112,7 @@ inline size_t SizeOf(BaseType t) {
struct StructDef;
struct EnumDef;
class Parser;
// Represents any type in the IDL, which is a combination of the BaseType
// and additional information for vectors/structs_.
@@ -184,10 +184,8 @@ template<typename T> class SymbolTable {
return it == dict.end() ? nullptr : it->second;
}
private:
std::map<std::string, T *> dict; // quick lookup
public:
std::map<std::string, T *> dict; // quick lookup
std::vector<T *> vec; // Used to iterate in order of insertion
};
@@ -208,6 +206,11 @@ struct Definition {
Definition() : generated(false), defined_namespace(nullptr),
serialized_location(0), index(-1) {}
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<
reflection::KeyValue>>>
SerializeAttributes(FlatBufferBuilder *builder,
const Parser &parser) const;
std::string name;
std::string file;
std::vector<std::string> doc_comment;
@@ -223,8 +226,8 @@ struct Definition {
struct FieldDef : public Definition {
FieldDef() : deprecated(false), required(false), key(false), padding(0) {}
Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id)
const;
Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id,
const Parser &parser) const;
Value value;
bool deprecated; // Field is allowed to be present in old data, but can't be
@@ -250,7 +253,8 @@ struct StructDef : public Definition {
if (fields.vec.size()) fields.vec.back()->padding = padding;
}
Offset<reflection::Object> Serialize(FlatBufferBuilder *builder) const;
Offset<reflection::Object> Serialize(FlatBufferBuilder *builder,
const Parser &parser) const;
SymbolTable<FieldDef> fields;
bool fixed; // If it's struct, not a table.
@@ -299,13 +303,32 @@ struct EnumDef : public Definition {
return nullptr;
}
Offset<reflection::Enum> Serialize(FlatBufferBuilder *builder) const;
Offset<reflection::Enum> Serialize(FlatBufferBuilder *builder,
const Parser &parser) const;
SymbolTable<EnumVal> vals;
bool is_union;
Type underlying_type;
};
inline bool EqualByName(const Type &a, const Type &b) {
return a.base_type == b.base_type && a.element == b.element &&
(a.struct_def == b.struct_def ||
a.struct_def->name == b.struct_def->name) &&
(a.enum_def == b.enum_def ||
a.enum_def->name == b.enum_def->name);
}
struct RPCCall {
std::string name;
SymbolTable<Value> attributes;
StructDef *request, *response;
};
struct ServiceDef : public Definition {
SymbolTable<RPCCall> calls;
};
// Container of options that may apply to any of the source/text generators.
struct IDLOptions {
bool strict_json;
@@ -321,6 +344,11 @@ struct IDLOptions {
bool proto_mode;
bool generate_all;
bool skip_unexpected_fields_in_json;
bool generate_name_strings;
bool escape_proto_identifiers;
bool generate_object_based_api;
bool union_value_namespacing;
bool allow_non_utf8;
// Possible options for the more general generator below.
enum Language { kJava, kCSharp, kGo, kMAX };
@@ -339,9 +367,27 @@ struct IDLOptions {
proto_mode(false),
generate_all(false),
skip_unexpected_fields_in_json(false),
generate_name_strings(false),
escape_proto_identifiers(false),
generate_object_based_api(false),
union_value_namespacing(true),
allow_non_utf8(false),
lang(IDLOptions::kJava) {}
};
// This encapsulates where the parser is in the current source file.
struct ParserState {
ParserState() : cursor_(nullptr), line_(1), token_(-1) {}
protected:
const char *cursor_;
int line_; // the current line being parsed
int token_;
std::string attribute_;
std::vector<std::string> doc_comment_;
};
// A way to make error propagation less error prone by requiring values to be
// checked.
// Once you create a value of this type you must either:
@@ -383,27 +429,27 @@ class CheckedError {
#define FLATBUFFERS_CHECKED_ERROR CheckedError
#endif
class Parser {
class Parser : public ParserState {
public:
explicit Parser(const IDLOptions &options = IDLOptions())
: root_struct_def_(nullptr),
opts(options),
source_(nullptr),
cursor_(nullptr),
line_(1),
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");
known_attributes_.insert("csharp_partial");
known_attributes_["deprecated"] = true;
known_attributes_["required"] = true;
known_attributes_["key"] = true;
known_attributes_["hash"] = true;
known_attributes_["id"] = true;
known_attributes_["force_align"] = true;
known_attributes_["bit_flags"] = true;
known_attributes_["original_order"] = true;
known_attributes_["nested_flatbuffer"] = true;
known_attributes_["csharp_partial"] = true;
known_attributes_["streaming"] = true;
known_attributes_["idempotent"] = true;
}
~Parser() {
@@ -439,6 +485,10 @@ class Parser {
// See reflection/reflection.fbs
void Serialize();
// Checks that the schema represented by this parser is a safe evolution
// of the schema provided. Returns non-empty error on any problems.
std::string ConformTo(const Parser &base);
FLATBUFFERS_CHECKED_ERROR CheckBitsFit(int64_t val, size_t bits);
private:
@@ -459,18 +509,19 @@ private:
FieldDef **dest);
FLATBUFFERS_CHECKED_ERROR ParseField(StructDef &struct_def);
FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value &val, FieldDef *field,
size_t parent_fieldn);
size_t parent_fieldn,
const StructDef *parent_struct_def);
FLATBUFFERS_CHECKED_ERROR ParseTable(const StructDef &struct_def,
std::string *value, uoffset_t *ovalue);
void SerializeStruct(const StructDef &struct_def, const Value &val);
void AddVector(bool sortbysize, int count);
FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue);
FLATBUFFERS_CHECKED_ERROR ParseMetaData(Definition &def);
FLATBUFFERS_CHECKED_ERROR ParseMetaData(SymbolTable<Value> *attributes);
FLATBUFFERS_CHECKED_ERROR TryTypedValue(int dtoken, bool check, Value &e,
BaseType req, bool *destmatch);
FLATBUFFERS_CHECKED_ERROR ParseHash(Value &e, FieldDef* field);
FLATBUFFERS_CHECKED_ERROR ParseSingleValue(Value &e);
FLATBUFFERS_CHECKED_ERROR ParseIntegerFromString(Type &type, int64_t *result);
FLATBUFFERS_CHECKED_ERROR ParseEnumFromString(Type &type, int64_t *result);
StructDef *LookupCreateStruct(const std::string &name,
bool create_if_new = true,
bool definition = false);
@@ -479,6 +530,7 @@ private:
FLATBUFFERS_CHECKED_ERROR StartStruct(const std::string &name,
StructDef **dest);
FLATBUFFERS_CHECKED_ERROR ParseDecl();
FLATBUFFERS_CHECKED_ERROR ParseService();
FLATBUFFERS_CHECKED_ERROR ParseProtoFields(StructDef *struct_def,
bool isextend, bool inside_oneof);
FLATBUFFERS_CHECKED_ERROR ParseProtoOption();
@@ -501,6 +553,7 @@ private:
public:
SymbolTable<StructDef> structs_;
SymbolTable<EnumDef> enums_;
SymbolTable<ServiceDef> services_;
std::vector<Namespace *> namespaces_;
std::string error_; // User readable error_ if Parse() == false
@@ -512,21 +565,17 @@ private:
std::map<std::string, bool> included_files_;
std::map<std::string, std::set<std::string>> files_included_per_file_;
std::map<std::string, bool> known_attributes_;
IDLOptions opts;
private:
const char *source_, *cursor_;
int line_; // the current line being parsed
int token_;
const char *source_;
std::string file_being_parsed_;
std::string attribute_;
std::vector<std::string> doc_comment_;
std::vector<std::pair<Value, FieldDef *>> field_stack_;
std::set<std::string> known_attributes_;
int anonymous_counter;
};
@@ -650,6 +699,12 @@ extern std::string BinaryMakeRule(const Parser &parser,
const std::string &path,
const std::string &file_name);
// Generate GRPC interfaces.
// See idl_gen_grpc.cpp.
bool GenerateGRPC(const Parser &parser,
const std::string &path,
const std::string &file_name);
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_H_

View File

@@ -335,6 +335,8 @@ template<typename T, typename U> pointer_inside_vector<T, U> piv(T *ptr,
return pointer_inside_vector<T, U>(ptr, vec);
}
inline const char *UnionTypeFieldSuffix() { return "_type"; }
// 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,
@@ -342,7 +344,7 @@ inline const reflection::Object &GetUnionType(
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());
(unionfield.name()->str() + UnionTypeFieldSuffix()).c_str());
assert(type_field);
auto union_type = GetFieldI<uint8_t>(table, *type_field);
auto enumval = enumdef->values()->LookupByKey(union_type);
@@ -368,6 +370,7 @@ uint8_t *ResizeAnyVector(const reflection::Schema &schema, uoffset_t newsize,
uoffset_t elem_size, std::vector<uint8_t> *flatbuf,
const reflection::Object *root_table = nullptr);
#ifndef FLATBUFFERS_CPP98_STL
template <typename T>
void ResizeVector(const reflection::Schema &schema, uoffset_t newsize, T val,
const Vector<T> *vec, std::vector<uint8_t> *flatbuf,
@@ -389,6 +392,7 @@ void ResizeVector(const reflection::Schema &schema, uoffset_t newsize, T val,
}
}
}
#endif
// 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
@@ -415,12 +419,14 @@ inline bool SetFieldT(Table *table, const reflection::Field &field,
// 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).
// DAG, the copy will be a tree instead (with duplicates). Strings can be
// shared however, by passing true for use_string_pooling.
Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
const reflection::Schema &schema,
const reflection::Object &objectdef,
const Table &table);
const Table &table,
bool use_string_pooling = false);
} // namespace flatbuffers

View File

@@ -5,14 +5,20 @@
#include "flatbuffers/flatbuffers.h"
namespace reflection {
struct Type;
struct KeyValue;
struct EnumVal;
struct Enum;
struct Field;
struct Object;
struct Schema;
enum BaseType {
@@ -32,7 +38,7 @@ enum BaseType {
String = 13,
Vector = 14,
Obj = 15,
Union = 16
Union = 16,
};
inline const char **EnumNamesBaseType() {
@@ -40,17 +46,22 @@ inline const char **EnumNamesBaseType() {
return names;
}
inline const char *EnumNameBaseType(BaseType e) { return EnumNamesBaseType()[e]; }
inline const char *EnumNameBaseType(BaseType e) { return EnumNamesBaseType()[static_cast<int>(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); }
enum {
VT_BASE_TYPE = 4,
VT_ELEMENT = 6,
VT_INDEX = 8
};
BaseType base_type() const { return static_cast<BaseType>(GetField<int8_t>(VT_BASE_TYPE, 0)); }
BaseType element() const { return static_cast<BaseType>(GetField<int8_t>(VT_ELEMENT, 0)); }
int32_t index() const { return GetField<int32_t>(VT_INDEX, -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 */) &&
VerifyField<int8_t>(verifier, VT_BASE_TYPE) &&
VerifyField<int8_t>(verifier, VT_ELEMENT) &&
VerifyField<int32_t>(verifier, VT_INDEX) &&
verifier.EndTable();
}
};
@@ -58,9 +69,9 @@ struct Type FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
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); }
void add_base_type(BaseType base_type) { fbb_.AddElement<int8_t>(Type::VT_BASE_TYPE, static_cast<int8_t>(base_type), 0); }
void add_element(BaseType element) { fbb_.AddElement<int8_t>(Type::VT_ELEMENT, static_cast<int8_t>(element), 0); }
void add_index(int32_t index) { fbb_.AddElement<int32_t>(Type::VT_INDEX, index, -1); }
TypeBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
TypeBuilder &operator=(const TypeBuilder &);
flatbuffers::Offset<Type> Finish() {
@@ -70,9 +81,9 @@ struct TypeBuilder {
};
inline flatbuffers::Offset<Type> CreateType(flatbuffers::FlatBufferBuilder &_fbb,
BaseType base_type = None,
BaseType element = None,
int32_t index = -1) {
BaseType base_type = None,
BaseType element = None,
int32_t index = -1) {
TypeBuilder builder_(_fbb);
builder_.add_index(index);
builder_.add_element(element);
@@ -80,18 +91,71 @@ inline flatbuffers::Offset<Type> CreateType(flatbuffers::FlatBufferBuilder &_fbb
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); }
struct KeyValue FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
enum {
VT_KEY = 4,
VT_VALUE = 6
};
const flatbuffers::String *key() const { return GetPointer<const flatbuffers::String *>(VT_KEY); }
bool KeyCompareLessThan(const KeyValue *o) const { return *key() < *o->key(); }
int KeyCompareWithValue(const char *val) const { return strcmp(key()->c_str(), val); }
const flatbuffers::String *value() const { return GetPointer<const flatbuffers::String *>(VT_VALUE); }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 4 /* name */) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, VT_KEY) &&
verifier.Verify(key()) &&
VerifyField<flatbuffers::uoffset_t>(verifier, VT_VALUE) &&
verifier.Verify(value()) &&
verifier.EndTable();
}
};
struct KeyValueBuilder {
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_key(flatbuffers::Offset<flatbuffers::String> key) { fbb_.AddOffset(KeyValue::VT_KEY, key); }
void add_value(flatbuffers::Offset<flatbuffers::String> value) { fbb_.AddOffset(KeyValue::VT_VALUE, value); }
KeyValueBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
KeyValueBuilder &operator=(const KeyValueBuilder &);
flatbuffers::Offset<KeyValue> Finish() {
auto o = flatbuffers::Offset<KeyValue>(fbb_.EndTable(start_, 2));
fbb_.Required(o, KeyValue::VT_KEY); // key
return o;
}
};
inline flatbuffers::Offset<KeyValue> CreateKeyValue(flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<flatbuffers::String> key = 0,
flatbuffers::Offset<flatbuffers::String> value = 0) {
KeyValueBuilder builder_(_fbb);
builder_.add_value(value);
builder_.add_key(key);
return builder_.Finish();
}
inline flatbuffers::Offset<KeyValue> CreateKeyValueDirect(flatbuffers::FlatBufferBuilder &_fbb,
const char *key = nullptr,
const char *value = nullptr) {
return CreateKeyValue(_fbb, key ? _fbb.CreateString(key) : 0, value ? _fbb.CreateString(value) : 0);
}
struct EnumVal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
enum {
VT_NAME = 4,
VT_VALUE = 6,
VT_OBJECT = 8
};
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(VT_NAME); }
int64_t value() const { return GetField<int64_t>(VT_VALUE, 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 *>(VT_OBJECT); }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, VT_NAME) &&
verifier.Verify(name()) &&
VerifyField<int64_t>(verifier, 6 /* value */) &&
VerifyField<flatbuffers::uoffset_t>(verifier, 8 /* object */) &&
VerifyField<int64_t>(verifier, VT_VALUE) &&
VerifyField<flatbuffers::uoffset_t>(verifier, VT_OBJECT) &&
verifier.VerifyTable(object()) &&
verifier.EndTable();
}
@@ -100,22 +164,22 @@ struct EnumVal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
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); }
void add_name(flatbuffers::Offset<flatbuffers::String> name) { fbb_.AddOffset(EnumVal::VT_NAME, name); }
void add_value(int64_t value) { fbb_.AddElement<int64_t>(EnumVal::VT_VALUE, value, 0); }
void add_object(flatbuffers::Offset<Object> object) { fbb_.AddOffset(EnumVal::VT_OBJECT, 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
fbb_.Required(o, EnumVal::VT_NAME); // 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) {
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);
@@ -123,23 +187,41 @@ inline flatbuffers::Offset<EnumVal> CreateEnumVal(flatbuffers::FlatBufferBuilder
return builder_.Finish();
}
inline flatbuffers::Offset<EnumVal> CreateEnumValDirect(flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
int64_t value = 0,
flatbuffers::Offset<Object> object = 0) {
return CreateEnumVal(_fbb, name ? _fbb.CreateString(name) : 0, value, object);
}
struct Enum FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(4); }
enum {
VT_NAME = 4,
VT_VALUES = 6,
VT_IS_UNION = 8,
VT_UNDERLYING_TYPE = 10,
VT_ATTRIBUTES = 12
};
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(VT_NAME); }
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); }
const flatbuffers::Vector<flatbuffers::Offset<EnumVal>> *values() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<EnumVal>> *>(VT_VALUES); }
bool is_union() const { return GetField<uint8_t>(VT_IS_UNION, 0) != 0; }
const Type *underlying_type() const { return GetPointer<const Type *>(VT_UNDERLYING_TYPE); }
const flatbuffers::Vector<flatbuffers::Offset<KeyValue>> *attributes() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<KeyValue>> *>(VT_ATTRIBUTES); }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 4 /* name */) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, VT_NAME) &&
verifier.Verify(name()) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 6 /* values */) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, VT_VALUES) &&
verifier.Verify(values()) &&
verifier.VerifyVectorOfTables(values()) &&
VerifyField<uint8_t>(verifier, 8 /* is_union */) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 10 /* underlying_type */) &&
VerifyField<uint8_t>(verifier, VT_IS_UNION) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, VT_UNDERLYING_TYPE) &&
verifier.VerifyTable(underlying_type()) &&
VerifyField<flatbuffers::uoffset_t>(verifier, VT_ATTRIBUTES) &&
verifier.Verify(attributes()) &&
verifier.VerifyVectorOfTables(attributes()) &&
verifier.EndTable();
}
};
@@ -147,27 +229,30 @@ struct Enum FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
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); }
void add_name(flatbuffers::Offset<flatbuffers::String> name) { fbb_.AddOffset(Enum::VT_NAME, name); }
void add_values(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<EnumVal>>> values) { fbb_.AddOffset(Enum::VT_VALUES, values); }
void add_is_union(bool is_union) { fbb_.AddElement<uint8_t>(Enum::VT_IS_UNION, static_cast<uint8_t>(is_union), 0); }
void add_underlying_type(flatbuffers::Offset<Type> underlying_type) { fbb_.AddOffset(Enum::VT_UNDERLYING_TYPE, underlying_type); }
void add_attributes(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<KeyValue>>> attributes) { fbb_.AddOffset(Enum::VT_ATTRIBUTES, attributes); }
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
auto o = flatbuffers::Offset<Enum>(fbb_.EndTable(start_, 5));
fbb_.Required(o, Enum::VT_NAME); // name
fbb_.Required(o, Enum::VT_VALUES); // values
fbb_.Required(o, Enum::VT_UNDERLYING_TYPE); // 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) {
flatbuffers::Offset<flatbuffers::String> name = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<EnumVal>>> values = 0,
bool is_union = false,
flatbuffers::Offset<Type> underlying_type = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<KeyValue>>> attributes = 0) {
EnumBuilder builder_(_fbb);
builder_.add_attributes(attributes);
builder_.add_underlying_type(underlying_type);
builder_.add_values(values);
builder_.add_name(name);
@@ -175,31 +260,56 @@ inline flatbuffers::Offset<Enum> CreateEnum(flatbuffers::FlatBufferBuilder &_fbb
return builder_.Finish();
}
inline flatbuffers::Offset<Enum> CreateEnumDirect(flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
const std::vector<flatbuffers::Offset<EnumVal>> *values = nullptr,
bool is_union = false,
flatbuffers::Offset<Type> underlying_type = 0,
const std::vector<flatbuffers::Offset<KeyValue>> *attributes = nullptr) {
return CreateEnum(_fbb, name ? _fbb.CreateString(name) : 0, values ? _fbb.CreateVector<flatbuffers::Offset<EnumVal>>(*values) : 0, is_union, underlying_type, attributes ? _fbb.CreateVector<flatbuffers::Offset<KeyValue>>(*attributes) : 0);
}
struct Field FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(4); }
enum {
VT_NAME = 4,
VT_TYPE = 6,
VT_ID = 8,
VT_OFFSET = 10,
VT_DEFAULT_INTEGER = 12,
VT_DEFAULT_REAL = 14,
VT_DEPRECATED = 16,
VT_REQUIRED = 18,
VT_KEY = 20,
VT_ATTRIBUTES = 22
};
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(VT_NAME); }
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); }
const Type *type() const { return GetPointer<const Type *>(VT_TYPE); }
uint16_t id() const { return GetField<uint16_t>(VT_ID, 0); }
uint16_t offset() const { return GetField<uint16_t>(VT_OFFSET, 0); }
int64_t default_integer() const { return GetField<int64_t>(VT_DEFAULT_INTEGER, 0); }
double default_real() const { return GetField<double>(VT_DEFAULT_REAL, 0.0); }
bool deprecated() const { return GetField<uint8_t>(VT_DEPRECATED, 0) != 0; }
bool required() const { return GetField<uint8_t>(VT_REQUIRED, 0) != 0; }
bool key() const { return GetField<uint8_t>(VT_KEY, 0) != 0; }
const flatbuffers::Vector<flatbuffers::Offset<KeyValue>> *attributes() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<KeyValue>> *>(VT_ATTRIBUTES); }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 4 /* name */) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, VT_NAME) &&
verifier.Verify(name()) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 6 /* type */) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, VT_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 */) &&
VerifyField<uint16_t>(verifier, VT_ID) &&
VerifyField<uint16_t>(verifier, VT_OFFSET) &&
VerifyField<int64_t>(verifier, VT_DEFAULT_INTEGER) &&
VerifyField<double>(verifier, VT_DEFAULT_REAL) &&
VerifyField<uint8_t>(verifier, VT_DEPRECATED) &&
VerifyField<uint8_t>(verifier, VT_REQUIRED) &&
VerifyField<uint8_t>(verifier, VT_KEY) &&
VerifyField<flatbuffers::uoffset_t>(verifier, VT_ATTRIBUTES) &&
verifier.Verify(attributes()) &&
verifier.VerifyVectorOfTables(attributes()) &&
verifier.EndTable();
}
};
@@ -207,38 +317,41 @@ struct Field FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
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); }
void add_name(flatbuffers::Offset<flatbuffers::String> name) { fbb_.AddOffset(Field::VT_NAME, name); }
void add_type(flatbuffers::Offset<Type> type) { fbb_.AddOffset(Field::VT_TYPE, type); }
void add_id(uint16_t id) { fbb_.AddElement<uint16_t>(Field::VT_ID, id, 0); }
void add_offset(uint16_t offset) { fbb_.AddElement<uint16_t>(Field::VT_OFFSET, offset, 0); }
void add_default_integer(int64_t default_integer) { fbb_.AddElement<int64_t>(Field::VT_DEFAULT_INTEGER, default_integer, 0); }
void add_default_real(double default_real) { fbb_.AddElement<double>(Field::VT_DEFAULT_REAL, default_real, 0.0); }
void add_deprecated(bool deprecated) { fbb_.AddElement<uint8_t>(Field::VT_DEPRECATED, static_cast<uint8_t>(deprecated), 0); }
void add_required(bool required) { fbb_.AddElement<uint8_t>(Field::VT_REQUIRED, static_cast<uint8_t>(required), 0); }
void add_key(bool key) { fbb_.AddElement<uint8_t>(Field::VT_KEY, static_cast<uint8_t>(key), 0); }
void add_attributes(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<KeyValue>>> attributes) { fbb_.AddOffset(Field::VT_ATTRIBUTES, attributes); }
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
auto o = flatbuffers::Offset<Field>(fbb_.EndTable(start_, 10));
fbb_.Required(o, Field::VT_NAME); // name
fbb_.Required(o, Field::VT_TYPE); // 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) {
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,
bool deprecated = false,
bool required = false,
bool key = false,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<KeyValue>>> attributes = 0) {
FieldBuilder builder_(_fbb);
builder_.add_default_real(default_real);
builder_.add_default_integer(default_integer);
builder_.add_attributes(attributes);
builder_.add_type(type);
builder_.add_name(name);
builder_.add_offset(offset);
@@ -249,24 +362,50 @@ inline flatbuffers::Offset<Field> CreateField(flatbuffers::FlatBufferBuilder &_f
return builder_.Finish();
}
inline flatbuffers::Offset<Field> CreateFieldDirect(flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
flatbuffers::Offset<Type> type = 0,
uint16_t id = 0,
uint16_t offset = 0,
int64_t default_integer = 0,
double default_real = 0.0,
bool deprecated = false,
bool required = false,
bool key = false,
const std::vector<flatbuffers::Offset<KeyValue>> *attributes = nullptr) {
return CreateField(_fbb, name ? _fbb.CreateString(name) : 0, type, id, offset, default_integer, default_real, deprecated, required, key, attributes ? _fbb.CreateVector<flatbuffers::Offset<KeyValue>>(*attributes) : 0);
}
struct Object FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(4); }
enum {
VT_NAME = 4,
VT_FIELDS = 6,
VT_IS_STRUCT = 8,
VT_MINALIGN = 10,
VT_BYTESIZE = 12,
VT_ATTRIBUTES = 14
};
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(VT_NAME); }
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); }
const flatbuffers::Vector<flatbuffers::Offset<Field>> *fields() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<Field>> *>(VT_FIELDS); }
bool is_struct() const { return GetField<uint8_t>(VT_IS_STRUCT, 0) != 0; }
int32_t minalign() const { return GetField<int32_t>(VT_MINALIGN, 0); }
int32_t bytesize() const { return GetField<int32_t>(VT_BYTESIZE, 0); }
const flatbuffers::Vector<flatbuffers::Offset<KeyValue>> *attributes() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<KeyValue>> *>(VT_ATTRIBUTES); }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 4 /* name */) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, VT_NAME) &&
verifier.Verify(name()) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 6 /* fields */) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, VT_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 */) &&
VerifyField<uint8_t>(verifier, VT_IS_STRUCT) &&
VerifyField<int32_t>(verifier, VT_MINALIGN) &&
VerifyField<int32_t>(verifier, VT_BYTESIZE) &&
VerifyField<flatbuffers::uoffset_t>(verifier, VT_ATTRIBUTES) &&
verifier.Verify(attributes()) &&
verifier.VerifyVectorOfTables(attributes()) &&
verifier.EndTable();
}
};
@@ -274,28 +413,31 @@ struct Object FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
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); }
void add_name(flatbuffers::Offset<flatbuffers::String> name) { fbb_.AddOffset(Object::VT_NAME, name); }
void add_fields(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Field>>> fields) { fbb_.AddOffset(Object::VT_FIELDS, fields); }
void add_is_struct(bool is_struct) { fbb_.AddElement<uint8_t>(Object::VT_IS_STRUCT, static_cast<uint8_t>(is_struct), 0); }
void add_minalign(int32_t minalign) { fbb_.AddElement<int32_t>(Object::VT_MINALIGN, minalign, 0); }
void add_bytesize(int32_t bytesize) { fbb_.AddElement<int32_t>(Object::VT_BYTESIZE, bytesize, 0); }
void add_attributes(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<KeyValue>>> attributes) { fbb_.AddOffset(Object::VT_ATTRIBUTES, attributes); }
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
auto o = flatbuffers::Offset<Object>(fbb_.EndTable(start_, 6));
fbb_.Required(o, Object::VT_NAME); // name
fbb_.Required(o, Object::VT_FIELDS); // 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) {
flatbuffers::Offset<flatbuffers::String> name = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Field>>> fields = 0,
bool is_struct = false,
int32_t minalign = 0,
int32_t bytesize = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<KeyValue>>> attributes = 0) {
ObjectBuilder builder_(_fbb);
builder_.add_attributes(attributes);
builder_.add_bytesize(bytesize);
builder_.add_minalign(minalign);
builder_.add_fields(fields);
@@ -304,25 +446,42 @@ inline flatbuffers::Offset<Object> CreateObject(flatbuffers::FlatBufferBuilder &
return builder_.Finish();
}
inline flatbuffers::Offset<Object> CreateObjectDirect(flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
const std::vector<flatbuffers::Offset<Field>> *fields = nullptr,
bool is_struct = false,
int32_t minalign = 0,
int32_t bytesize = 0,
const std::vector<flatbuffers::Offset<KeyValue>> *attributes = nullptr) {
return CreateObject(_fbb, name ? _fbb.CreateString(name) : 0, fields ? _fbb.CreateVector<flatbuffers::Offset<Field>>(*fields) : 0, is_struct, minalign, bytesize, attributes ? _fbb.CreateVector<flatbuffers::Offset<KeyValue>>(*attributes) : 0);
}
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); }
enum {
VT_OBJECTS = 4,
VT_ENUMS = 6,
VT_FILE_IDENT = 8,
VT_FILE_EXT = 10,
VT_ROOT_TABLE = 12
};
const flatbuffers::Vector<flatbuffers::Offset<Object>> *objects() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<Object>> *>(VT_OBJECTS); }
const flatbuffers::Vector<flatbuffers::Offset<Enum>> *enums() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<Enum>> *>(VT_ENUMS); }
const flatbuffers::String *file_ident() const { return GetPointer<const flatbuffers::String *>(VT_FILE_IDENT); }
const flatbuffers::String *file_ext() const { return GetPointer<const flatbuffers::String *>(VT_FILE_EXT); }
const Object *root_table() const { return GetPointer<const Object *>(VT_ROOT_TABLE); }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 4 /* objects */) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, VT_OBJECTS) &&
verifier.Verify(objects()) &&
verifier.VerifyVectorOfTables(objects()) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 6 /* enums */) &&
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, VT_ENUMS) &&
verifier.Verify(enums()) &&
verifier.VerifyVectorOfTables(enums()) &&
VerifyField<flatbuffers::uoffset_t>(verifier, 8 /* file_ident */) &&
VerifyField<flatbuffers::uoffset_t>(verifier, VT_FILE_IDENT) &&
verifier.Verify(file_ident()) &&
VerifyField<flatbuffers::uoffset_t>(verifier, 10 /* file_ext */) &&
VerifyField<flatbuffers::uoffset_t>(verifier, VT_FILE_EXT) &&
verifier.Verify(file_ext()) &&
VerifyField<flatbuffers::uoffset_t>(verifier, 12 /* root_table */) &&
VerifyField<flatbuffers::uoffset_t>(verifier, VT_ROOT_TABLE) &&
verifier.VerifyTable(root_table()) &&
verifier.EndTable();
}
@@ -331,27 +490,27 @@ struct Schema FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
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); }
void add_objects(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Object>>> objects) { fbb_.AddOffset(Schema::VT_OBJECTS, objects); }
void add_enums(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Enum>>> enums) { fbb_.AddOffset(Schema::VT_ENUMS, enums); }
void add_file_ident(flatbuffers::Offset<flatbuffers::String> file_ident) { fbb_.AddOffset(Schema::VT_FILE_IDENT, file_ident); }
void add_file_ext(flatbuffers::Offset<flatbuffers::String> file_ext) { fbb_.AddOffset(Schema::VT_FILE_EXT, file_ext); }
void add_root_table(flatbuffers::Offset<Object> root_table) { fbb_.AddOffset(Schema::VT_ROOT_TABLE, 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
fbb_.Required(o, Schema::VT_OBJECTS); // objects
fbb_.Required(o, Schema::VT_ENUMS); // 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) {
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);
@@ -361,14 +520,23 @@ inline flatbuffers::Offset<Schema> CreateSchema(flatbuffers::FlatBufferBuilder &
return builder_.Finish();
}
inline const reflection::Schema *GetSchema(const void *buf) { return flatbuffers::GetRoot<reflection::Schema>(buf); }
inline flatbuffers::Offset<Schema> CreateSchemaDirect(flatbuffers::FlatBufferBuilder &_fbb,
const std::vector<flatbuffers::Offset<Object>> *objects = nullptr,
const std::vector<flatbuffers::Offset<Enum>> *enums = nullptr,
const char *file_ident = nullptr,
const char *file_ext = nullptr,
flatbuffers::Offset<Object> root_table = 0) {
return CreateSchema(_fbb, objects ? _fbb.CreateVector<flatbuffers::Offset<Object>>(*objects) : 0, enums ? _fbb.CreateVector<flatbuffers::Offset<Enum>>(*enums) : 0, file_ident ? _fbb.CreateString(file_ident) : 0, file_ext ? _fbb.CreateString(file_ext) : 0, root_table);
}
inline bool VerifySchemaBuffer(flatbuffers::Verifier &verifier) { return verifier.VerifyBuffer<reflection::Schema>(); }
inline const reflection::Schema *GetSchema(const void *buf) { return flatbuffers::GetRoot<reflection::Schema>(buf); }
inline const char *SchemaIdentifier() { return "BFBS"; }
inline bool SchemaBufferHasIdentifier(const void *buf) { return flatbuffers::BufferHasIdentifier(buf, SchemaIdentifier()); }
inline bool VerifySchemaBuffer(flatbuffers::Verifier &verifier) { return verifier.VerifyBuffer<reflection::Schema>(SchemaIdentifier()); }
inline const char *SchemaExtension() { return "bfbs"; }
inline void FinishSchemaBuffer(flatbuffers::FlatBufferBuilder &fbb, flatbuffers::Offset<reflection::Schema> root) { fbb.Finish(root, SchemaIdentifier()); }

View File

@@ -21,6 +21,7 @@
#include <iomanip>
#include <string>
#include <sstream>
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#ifdef _WIN32
@@ -34,9 +35,10 @@
#include <winbase.h>
#include <direct.h>
#else
#include <sys/stat.h>
#include <limits.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include "flatbuffers/flatbuffers.h"
@@ -110,33 +112,27 @@ inline int64_t StringToUInt(const char *str, int base = 10) {
#endif
}
typedef bool (*LoadFileFunction)(const char *filename, bool binary,
std::string *dest);
typedef bool (*FileExistsFunction)(const char *filename);
LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function);
FileExistsFunction SetFileExistsFunction(FileExistsFunction
file_exists_function);
// Check if file "name" exists.
inline bool FileExists(const char *name) {
std::ifstream ifs(name);
return ifs.good();
}
bool FileExists(const char *name);
// Check if "name" exists and it is also a directory.
bool DirExists(const char *name);
// 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
// no transcoding.
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;
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();
}
bool LoadFile(const char *name, bool binary, std::string *buf);
// Save data "buf" of length "len" bytes into a file
// "name" returning true if successful, false otherwise.
@@ -280,6 +276,10 @@ inline int FromUTF8(const char **in) {
}
if ((**in << len) & 0x80) return -1; // Bit after leading 1's must be 0.
if (!len) return *(*in)++;
// UTF-8 encoded values with a length are between 2 and 4 bytes.
if (len < 2 || len > 4) {
return -1;
}
// Grab initial bits of the code.
int ucc = *(*in)++ & ((1 << (7 - len)) - 1);
for (int i = 0; i < len - 1; i++) {
@@ -287,6 +287,32 @@ inline int FromUTF8(const char **in) {
ucc <<= 6;
ucc |= *(*in)++ & 0x3F; // Grab 6 more bits of the code.
}
// UTF-8 cannot encode values between 0xD800 and 0xDFFF (reserved for
// UTF-16 surrogate pairs).
if (ucc >= 0xD800 && ucc <= 0xDFFF) {
return -1;
}
// UTF-8 must represent code points in their shortest possible encoding.
switch (len) {
case 2:
// Two bytes of UTF-8 can represent code points from U+0080 to U+07FF.
if (ucc < 0x0080 || ucc > 0x07FF) {
return -1;
}
break;
case 3:
// Three bytes of UTF-8 can represent code points from U+0800 to U+FFFF.
if (ucc < 0x0800 || ucc > 0xFFFF) {
return -1;
}
break;
case 4:
// Four bytes of UTF-8 can represent code points from U+10000 to U+10FFFF.
if (ucc < 0x10000 || ucc > 0x10FFFF) {
return -1;
}
break;
}
return ucc;
}

View File

@@ -23,10 +23,18 @@ package com.google.flatbuffers;
*/
public class Constants {
// Java doesn't seem to have these.
/** The number of bytes in an `byte`. */
static final int SIZEOF_BYTE = 1;
/** The number of bytes in a `short`. */
static final int SIZEOF_SHORT = 2;
/** The number of bytes in an `int`. */
static final int SIZEOF_INT = 4;
/** The number of bytes in an `float`. */
static final int SIZEOF_FLOAT = 4;
/** The number of bytes in an `long`. */
static final int SIZEOF_LONG = 8;
/** The number of bytes in an `double`. */
static final int SIZEOF_DOUBLE = 8;
/** The number of bytes in a file identifier. */
static final int FILE_IDENTIFIER_LENGTH = 4;
}

View File

@@ -17,6 +17,11 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.util.Arrays;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -28,8 +33,7 @@ import java.nio.charset.Charset;
/**
* Class that helps you build a FlatBuffer. See the section
* @ref flatbuffers_guide_use_java_c-sharp "Use in Java/C#" in the
* main FlatBuffers documentation.
* "Use in Java/C#" in the main FlatBuffers documentation.
*/
public class FlatBufferBuilder {
/// @cond FLATBUFFERS_INTERNAL
@@ -46,6 +50,8 @@ public class FlatBufferBuilder {
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.
CharsetEncoder encoder = utf8charset.newEncoder();
ByteBuffer dst;
/// @endcond
/**
@@ -182,7 +188,7 @@ public class FlatBufferBuilder {
*
* @param x A `boolean` to put into the buffer.
*/
public void putBoolean(boolean x) { bb.put (space -= 1, (byte)(x ? 1 : 0)); }
public void putBoolean(boolean x) { bb.put (space -= Constants.SIZEOF_BYTE, (byte)(x ? 1 : 0)); }
/**
* Add a `byte` to the buffer, backwards from the current location. Doesn't align nor
@@ -190,7 +196,7 @@ public class FlatBufferBuilder {
*
* @param x A `byte` to put into the buffer.
*/
public void putByte (byte x) { bb.put (space -= 1, x); }
public void putByte (byte x) { bb.put (space -= Constants.SIZEOF_BYTE, x); }
/**
* Add a `short` to the buffer, backwards from the current location. Doesn't align nor
@@ -198,7 +204,7 @@ public class FlatBufferBuilder {
*
* @param x A `short` to put into the buffer.
*/
public void putShort (short x) { bb.putShort (space -= 2, x); }
public void putShort (short x) { bb.putShort (space -= Constants.SIZEOF_SHORT, x); }
/**
* Add an `int` to the buffer, backwards from the current location. Doesn't align nor
@@ -206,7 +212,7 @@ public class FlatBufferBuilder {
*
* @param x An `int` to put into the buffer.
*/
public void putInt (int x) { bb.putInt (space -= 4, x); }
public void putInt (int x) { bb.putInt (space -= Constants.SIZEOF_INT, x); }
/**
* Add a `long` to the buffer, backwards from the current location. Doesn't align nor
@@ -214,7 +220,7 @@ public class FlatBufferBuilder {
*
* @param x A `long` to put into the buffer.
*/
public void putLong (long x) { bb.putLong (space -= 8, x); }
public void putLong (long x) { bb.putLong (space -= Constants.SIZEOF_LONG, x); }
/**
* Add a `float` to the buffer, backwards from the current location. Doesn't align nor
@@ -222,7 +228,7 @@ public class FlatBufferBuilder {
*
* @param x A `float` to put into the buffer.
*/
public void putFloat (float x) { bb.putFloat (space -= 4, x); }
public void putFloat (float x) { bb.putFloat (space -= Constants.SIZEOF_FLOAT, x); }
/**
* Add a `double` to the buffer, backwards from the current location. Doesn't align nor
@@ -230,7 +236,7 @@ public class FlatBufferBuilder {
*
* @param x A `double` to put into the buffer.
*/
public void putDouble (double x) { bb.putDouble(space -= 8, x); }
public void putDouble (double x) { bb.putDouble(space -= Constants.SIZEOF_DOUBLE, x); }
/// @endcond
/**
@@ -238,49 +244,49 @@ public class FlatBufferBuilder {
*
* @param x A `boolean` to put into the buffer.
*/
public void addBoolean(boolean x) { prep(1, 0); putBoolean(x); }
public void addBoolean(boolean x) { prep(Constants.SIZEOF_BYTE, 0); putBoolean(x); }
/**
* Add a `byte` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x A `byte` to put into the buffer.
*/
public void addByte (byte x) { prep(1, 0); putByte (x); }
public void addByte (byte x) { prep(Constants.SIZEOF_BYTE, 0); putByte (x); }
/**
* Add a `short` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x A `short` to put into the buffer.
*/
public void addShort (short x) { prep(2, 0); putShort (x); }
public void addShort (short x) { prep(Constants.SIZEOF_SHORT, 0); putShort (x); }
/**
* Add an `int` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x An `int` to put into the buffer.
*/
public void addInt (int x) { prep(4, 0); putInt (x); }
public void addInt (int x) { prep(Constants.SIZEOF_INT, 0); putInt (x); }
/**
* Add a `long` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x A `long` to put into the buffer.
*/
public void addLong (long x) { prep(8, 0); putLong (x); }
public void addLong (long x) { prep(Constants.SIZEOF_LONG, 0); putLong (x); }
/**
* Add a `float` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x A `float` to put into the buffer.
*/
public void addFloat (float x) { prep(4, 0); putFloat (x); }
public void addFloat (float x) { prep(Constants.SIZEOF_FLOAT, 0); putFloat (x); }
/**
* Add a `double` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x A `double` to put into the buffer.
*/
public void addDouble (double x) { prep(8, 0); putDouble (x); }
public void addDouble (double x) { prep(Constants.SIZEOF_DOUBLE, 0); putDouble (x); }
/**
* Adds on offset, relative to where it will be written.
@@ -362,18 +368,34 @@ public class FlatBufferBuilder {
/// @endcond
/**
* Encode the string `s` in the buffer using UTF-8.
* Encode the string `s` in the buffer using UTF-8. If {@code s} is
* already a {@link CharBuffer}, this method is allocation free.
*
* @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();
public int createString(CharSequence s) {
int length = s.length();
int estimatedDstCapacity = (int) (length * encoder.maxBytesPerChar());
if (dst == null || dst.capacity() < estimatedDstCapacity) {
dst = ByteBuffer.allocate(Math.max(128, estimatedDstCapacity));
}
dst.clear();
CharBuffer src = s instanceof CharBuffer ? (CharBuffer) s :
CharBuffer.wrap(s);
CoderResult result = encoder.encode(src, dst, true);
if (result.isError()) {
try {
result.throwException();
} catch (CharacterCodingException x) {
throw new Error(x);
}
}
dst.flip();
return createString(dst);
}
/**
@@ -428,8 +450,7 @@ public class FlatBufferBuilder {
* call this directly. The `FlatBuffers` compiler will generate helper methods
* that call this method internally.
* <p>
* For example, using the "Monster" code found on the
* @ref flatbuffers_guide_use_java_c-sharp "landing page". An
* For example, using the "Monster" code found on the "landing page". An
* object of type `Monster` can be created using the following code:
*
* <pre>{@code
@@ -708,6 +729,8 @@ public class FlatBufferBuilder {
* 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`.
*
* @return The {@link ByteBuffer} representing the FlatBuffer
*/
public ByteBuffer dataBuffer() {
finished();

View File

@@ -19,6 +19,11 @@ package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
/// @cond FLATBUFFERS_INTERNAL
@@ -26,6 +31,13 @@ import java.nio.ByteOrder;
* All tables in the generated code derive from this class, and add their own accessors.
*/
public class Table {
private final static ThreadLocal<CharsetDecoder> UTF8_DECODER = new ThreadLocal<CharsetDecoder>() {
@Override
protected CharsetDecoder initialValue() {
return Charset.forName("UTF-8").newDecoder();
}
};
private final static ThreadLocal<CharBuffer> CHAR_BUFFER = new ThreadLocal<CharBuffer>();
/** Used to hold the position of the `bb` buffer. */
protected int bb_pos;
/** The underlying ByteBuffer to hold the data of the Table. */
@@ -71,20 +83,34 @@ public class Table {
* @return Returns a `String` from the data stored inside the FlatBuffer at `offset`.
*/
protected String __string(int offset) {
CharsetDecoder decoder = UTF8_DECODER.get();
decoder.reset();
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);
ByteBuffer src = bb.duplicate().order(ByteOrder.LITTLE_ENDIAN);
int length = src.getInt(offset);
src.position(offset + SIZEOF_INT);
src.limit(offset + SIZEOF_INT + length);
int required = (int)((float)length * decoder.maxCharsPerByte());
CharBuffer dst = CHAR_BUFFER.get();
if (dst == null || dst.capacity() < required) {
dst = CharBuffer.allocate(required);
CHAR_BUFFER.set(dst);
}
dst.clear();
try {
CoderResult cr = decoder.decode(src, dst, true);
if (!cr.isUnderflow()) {
cr.throwException();
}
} catch (CharacterCodingException x) {
throw new Error(x);
}
return dst.flip().toString();
}
/**
@@ -113,9 +139,13 @@ public class Table {
/**
* 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.
* This is efficient, since it only allocates a new {@link 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.
*
* @param vector_offset The position of the vector in the byte buffer
* @param elem_size The size of each element in the array
* @return The {@link ByteBuffer} for the array
*/
protected ByteBuffer __vector_as_bytebuffer(int vector_offset, int elem_size) {
int o = __offset(vector_offset);
@@ -142,10 +172,12 @@ public class Table {
}
/**
* Check if a ByteBuffer contains a file identifier.
* Check if a {@link ByteBuffer} contains a file identifier.
*
* @param bb A `ByteBuffer` to check if it contains the identifier `ident`.
* @param ident A `String` identifier of the flatbuffer file.
* @param bb A {@code ByteBuffer} to check if it contains the identifier
* `ident`.
* @param ident A `String` identifier of the FlatBuffer file.
* @return True if the buffer contains the file identifier
*/
protected static boolean __has_identifier(ByteBuffer bb, String ident) {
if (ident.length() != FILE_IDENTIFIER_LENGTH)

View File

@@ -2,6 +2,10 @@
/// @addtogroup flatbuffers_javascript_api
/// @{
/// @cond FLATBUFFERS_INTERNAL
/**
* @const
* @namespace
*/
var flatbuffers = {};
/**
@@ -88,6 +92,16 @@ flatbuffers.Long = function(low, high) {
this.high = high | 0;
};
/**
* @param {number} high
* @param {number} low
* @returns {flatbuffers.Long}
*/
flatbuffers.Long.create = function(low, high) {
// Special-case zero to avoid GC overhead for default values
return low == 0 && high == 0 ? flatbuffers.Long.ZERO : new flatbuffers.Long(low, high);
};
/**
* @returns {number}
*/
@@ -224,9 +238,8 @@ flatbuffers.Builder.prototype.dataBuffer = function() {
};
/**
* 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.
* Get the bytes representing the FlatBuffer. Only call this after you've
* called finish().
*
* @returns {Uint8Array}
*/
@@ -751,6 +764,17 @@ flatbuffers.Builder.prototype.createString = function(s) {
}
return this.endVector();
};
/**
* A helper function to avoid generated code depending on this file directly.
*
* @param {number} low
* @param {number} high
* @returns {flatbuffers.Long}
*/
flatbuffers.Builder.prototype.createLong = function(low, high) {
return flatbuffers.Long.create(low, high);
};
////////////////////////////////////////////////////////////////////////////////
/// @cond FLATBUFFERS_INTERNAL
/**
@@ -1101,6 +1125,17 @@ flatbuffers.ByteBuffer.prototype.__has_identifier = function(ident) {
return true;
};
/**
* A helper function to avoid generated code depending on this file directly.
*
* @param {number} low
* @param {number} high
* @returns {flatbuffers.Long}
*/
flatbuffers.ByteBuffer.prototype.createLong = function(low, high) {
return flatbuffers.Long.create(low, high);
};
// Exports for Node.js and RequireJS
this.flatbuffers = flatbuffers;

View File

@@ -1,4 +1,4 @@
/*
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -129,8 +129,7 @@ namespace FlatBuffers
private void AssertOffsetAndLength(int offset, int length)
{
if (offset < 0 ||
offset >= _buffer.Length ||
offset + length > _buffer.Length)
offset > _buffer.Length - length)
throw new ArgumentOutOfRangeException();
}

View File

@@ -80,9 +80,9 @@ namespace FlatBuffers
/// <summary>
/// Gets and sets a Boolean to disable the optimization when serializing
/// default values to a Table.
///
///
/// In order to save space, fields that are set to their default value
/// don't get serialized into the buffer.
/// don't get serialized into the buffer.
/// </summary>
public bool ForceDefaults { get; set; }
@@ -349,7 +349,7 @@ namespace FlatBuffers
/// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param>
/// <param name="d">The default value to compare the value against</param>
public void AddBool(int o, bool x, bool d) { if (ForceDefaults || x != d) { AddBool(x); Slot(o); } }
/// <summary>
/// Adds a SByte to the Table at index `o` in its vtable using the value `x` and default `d`
/// </summary>
@@ -358,7 +358,7 @@ namespace FlatBuffers
/// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param>
/// <param name="d">The default value to compare the value against</param>
public void AddSbyte(int o, sbyte x, sbyte d) { if (ForceDefaults || x != d) { AddSbyte(x); Slot(o); } }
/// <summary>
/// Adds a Byte to the Table at index `o` in its vtable using the value `x` and default `d`
/// </summary>
@@ -582,6 +582,8 @@ namespace FlatBuffers
/// </summary>
/// <remarks>
/// This is typically only called after you call `Finish()`.
/// The actual data starts at the ByteBuffer's current position,
/// not necessarily at `0`.
/// </remarks>
/// <returns>
/// Returns the ByteBuffer for this FlatBuffer.

View File

@@ -1,4 +1,4 @@
/*
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");

View File

@@ -1,4 +1,4 @@
/*
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -26,7 +26,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FlatBuffers")]
[assembly: AssemblyCopyright("Copyright © 2015 Google Inc")]
[assembly: AssemblyCopyright("Copyright (c) 2015 Google Inc")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

View File

@@ -1,4 +1,4 @@
/*
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");

View File

@@ -233,7 +233,7 @@ class FlatbufferBuilder
public function putUint($x)
{
if ($x > PHP_INT_MAX) {
throw new \InvalidArgumentException("your platform can't handling uint correctly. use 64bit machine.");
throw new \InvalidArgumentException("your platform can't handle uint correctly. use 64bit machine.");
}
$this->bb->putUint($this->space -= 4, $x);
@@ -245,7 +245,7 @@ class FlatbufferBuilder
public function putLong($x)
{
if ($x > PHP_INT_MAX) {
throw new \InvalidArgumentException("your platform can't handling long correctly. use 64bit machine.");
throw new \InvalidArgumentException("Your platform can't handle long correctly. Use a 64bit machine.");
}
$this->bb->putLong($this->space -= 8, $x);
@@ -257,7 +257,7 @@ class FlatbufferBuilder
public function putUlong($x)
{
if ($x > PHP_INT_MAX) {
throw new \InvalidArgumentException("your platform can't handling ulong correctly. this is php limitations. please wait extension release.");
throw new \InvalidArgumentException("Your platform can't handle ulong correctly. This is a php limitation. Please wait for the extension release.");
}
$this->bb->putUlong($this->space -= 8, $x);

View File

@@ -89,9 +89,15 @@ abstract class Table
return $offset + $this->bb->getInt($offset) + Constants::SIZEOF_INT;
}
// protected function __vector_as_bytebuffer($vector_offset, $elem_size)
// {
// }
protected function __vector_as_bytes($vector_offset, $elem_size=1)
{
$o = $this->__offset($vector_offset);
if ($o == 0) {
return null;
}
return substr($this->bb->_buffer, $this->__vector($o), $this->__vector_len($o) * $elem_size);
}
/**
* @param Table $table

View File

@@ -5,8 +5,8 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-java</artifactId>
<version>1.2.0-SNAPSHOT</version>
<packaging>jar</packaging>
<version>1.4.0-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>FlatBuffers Java API</name>
<description>
Memory Efficient Serialization Library
@@ -33,7 +33,7 @@
<dependencies>
</dependencies>
<build>
<sourceDirectory>./</sourceDirectory>
<sourceDirectory>java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
@@ -78,6 +78,12 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.0.1</version>
<extensions>true</extensions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -401,7 +401,7 @@ class Builder(object):
if isinstance(s, compat.string_types):
x = s.encode(encoding, errors)
elif isinstance(s, compat.binary_type):
elif isinstance(s, compat.binary_types):
x = s
else:
raise TypeError("non-string passed to CreateString")

View File

@@ -1,3 +1,17 @@
# Copyright 2016 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.
""" A tiny version of `six` to help with backwards compability. """
import sys
@@ -11,13 +25,16 @@ PY34 = sys.version_info[0:2] >= (3, 4)
if PY3:
string_types = (str,)
binary_type = bytes
binary_types = (bytes,bytearray)
range_func = range
memoryview_type = memoryview
struct_bool_decl = "?"
else:
string_types = (basestring,)
binary_type = str
string_types = (unicode,)
if PY26 or PY27:
binary_types = (str,bytearray)
else:
binary_types = (str,)
range_func = xrange
if PY26 or (PY27 and not PY275):
memoryview_type = buffer

View File

@@ -12,8 +12,6 @@
# 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

View File

@@ -12,10 +12,8 @@
# 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

View File

@@ -1,3 +1,17 @@
# Copyright 2016 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.
"""
Provide pre-compiled struct packers for encoding and decoding.

View File

@@ -1,3 +1,17 @@
# Copyright 2016 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 setuptools import setup
setup(

View File

@@ -1,8 +1,10 @@
![logo](http://google.github.io/flatbuffers/fpl_logo_small.png) FlatBuffers [![Build Status](https://travis-ci.org/google/flatbuffers.svg?branch=master)](https://travis-ci.org/google/flatbuffers)
![logo](http://google.github.io/flatbuffers/fpl_logo_small.png) FlatBuffers
===========
**FlatBuffers** is an efficient cross platform serialization library for games and
other memory constrained apps. It allows you to directly access serialized data without
unpacking/parsing it first, while still having great forwards/backwards compatibility.
[![Build Status](https://travis-ci.org/google/flatbuffers.svg?branch=master)](https://travis-ci.org/google/flatbuffers) [![Build status](https://ci.appveyor.com/api/projects/status/yg5idd2fnusv1n10?svg=true)](https://ci.appveyor.com/project/gwvo/flatbuffers)
**FlatBuffers** is an efficient cross platform serialization library for games and
other memory constrained apps. It allows you to directly access serialized data without
unpacking/parsing it first, while still having great forwards/backwards compatibility.
**Go to our [landing page][] to browse our documentation.**
@@ -11,10 +13,11 @@ unpacking/parsing it first, while still having great forwards/backwards compatib
* Windows
* MacOS X
* Linux
## Supported programming languages
* C++
* C#
* C
* Go
* Java
* JavaScript
@@ -23,7 +26,7 @@ unpacking/parsing it first, while still having great forwards/backwards compatib
*and many more in progress...*
## Contribution
## Contribution
* [FlatBuffers Google Group][] to discuss FlatBuffers with other developers and users.
* [FlatBuffers Issues Tracker][] to submit an issue.
* [stackoverflow.com][] with [`flatbuffers` tag][] for any questions regarding FlatBuffers.
@@ -45,9 +48,9 @@ you would leave it in.
<br>
[CONTRIBUTING]: http://github.com/google/flatbuffers/blob/master/CONTRIBUTING
[CONTRIBUTING]: http://github.com/google/flatbuffers/blob/master/CONTRIBUTING.md
[`flatbuffers` tag]: https://stackoverflow.com/questions/tagged/flatbuffers
[FlatBuffers Google Group]: http://group.google.com/group/flatbuffers
[FlatBuffers Google Group]: https://groups.google.com/forum/#!forum/flatbuffers
[FlatBuffers Issues Tracker]: http://github.com/google/flatbuffers/issues
[stackoverflow.com]: http://www.stackoverflow.com
[landing page]: http://google.github.io/flatbuffers

View File

@@ -1 +1,17 @@
#!/bin/bash
#
# Copyright 2016 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.
../flatc -c --no-prefix -o ../include/flatbuffers reflection.fbs

View File

@@ -34,6 +34,11 @@ table Type {
// from an enum, index into "enums" below.
}
table KeyValue {
key:string (required, key);
value:string;
}
table EnumVal {
name:string (required);
value:long (key);
@@ -45,6 +50,7 @@ table Enum {
values:[EnumVal] (required); // In order of their values.
is_union:bool = false;
underlying_type:Type (required);
attributes:[KeyValue];
}
table Field {
@@ -57,6 +63,7 @@ table Field {
deprecated:bool = false;
required:bool = false;
key:bool = false;
attributes:[KeyValue];
}
table Object { // Used for both tables and structs.
@@ -65,6 +72,7 @@ table Object { // Used for both tables and structs.
is_struct:bool = false;
minalign:int;
bytesize:int; // For structs.
attributes:[KeyValue];
}
table Schema {

View File

@@ -1,4 +1,5 @@
#!/bin/bash -eu
#
# Copyright (c) 2013 Google, Inc.
#
# This software is provided 'as-is', without any express or implied

View File

@@ -18,5 +18,5 @@ APP_PROJECT_PATH := $(call my-dir)/..
APP_STL := gnustl_static
APP_ABI := armeabi-v7a
NDK_TOOLCHAIN_VERSION := 4.8
APP_CPPFLAGS += -std=c++11

View File

@@ -1,4 +1,5 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,7 +13,7 @@
# 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.
#
# Note: This script requires the Android NDK and Android SDK to be installed.
# It also requires an Android device to be connected for installing and
# running the applicaton.

View File

@@ -1,4 +1,5 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,7 +13,7 @@
# 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.
#
# Note: This script runs on Mac and Linux. It requires `mono` to be installed
# and `flatc` to be built (using `cmake` in the root directory).

View File

@@ -1,4 +1,5 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,7 +13,7 @@
# 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.
#
# Note: This script runs on Mac and Linux. It requires `go` to be installed
# and 'flatc' to be built (using `cmake` in the root directory).

View File

@@ -1,4 +1,5 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,7 +13,7 @@
# 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.
#
# Note: This script runs on Mac and Linux. It requires `java` to be installed
# and `flatc` to be built (using `cmake` in the root directory).

View File

@@ -1,4 +1,5 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,7 +13,7 @@
# 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.
#
# Note: This script runs on Mac and Linux. It requires `Node.js` to be installed
# and `flatc` to be built (using `cmake` in the root directory).

View File

@@ -5,13 +5,16 @@
#include "flatbuffers/flatbuffers.h"
namespace MyGame {
namespace Sample {
struct Vec3;
struct Monster;
struct MonsterT;
struct Weapon;
struct WeaponT;
enum Color {
Color_Red = 0,
@@ -35,6 +38,21 @@ enum Equipment {
Equipment_MAX = Equipment_Weapon
};
struct EquipmentUnion {
Equipment type;
flatbuffers::NativeTable *table;
EquipmentUnion() : type(Equipment_NONE), table(nullptr) {}
EquipmentUnion(const EquipmentUnion &);
EquipmentUnion &operator=(const EquipmentUnion &);
~EquipmentUnion();
static flatbuffers::NativeTable *UnPack(const void *union_obj, Equipment type);
flatbuffers::Offset<void> Pack(flatbuffers::FlatBufferBuilder &_fbb) const;
WeaponT *AsWeapon() { return type == Equipment_Weapon ? reinterpret_cast<WeaponT *>(table) : nullptr; }
};
inline const char **EnumNamesEquipment() {
static const char *names[] = { "NONE", "Weapon", nullptr };
return names;
@@ -51,15 +69,31 @@ MANUALLY_ALIGNED_STRUCT(4) Vec3 FLATBUFFERS_FINAL_CLASS {
float z_;
public:
Vec3() { memset(this, 0, sizeof(Vec3)); }
Vec3(const Vec3 &_o) { memcpy(this, &_o, sizeof(Vec3)); }
Vec3(float _x, float _y, float _z)
: x_(flatbuffers::EndianScalar(_x)), y_(flatbuffers::EndianScalar(_y)), z_(flatbuffers::EndianScalar(_z)) { }
float x() const { return flatbuffers::EndianScalar(x_); }
void mutate_x(float _x) { flatbuffers::WriteScalar(&x_, _x); }
float y() const { return flatbuffers::EndianScalar(y_); }
void mutate_y(float _y) { flatbuffers::WriteScalar(&y_, _y); }
float z() const { return flatbuffers::EndianScalar(z_); }
void mutate_z(float _z) { flatbuffers::WriteScalar(&z_, _z); }
};
STRUCT_END(Vec3, 12);
struct MonsterT : public flatbuffers::NativeTable {
std::unique_ptr<Vec3> pos;
int16_t mana;
int16_t hp;
std::string name;
std::vector<uint8_t> inventory;
Color color;
std::vector<std::unique_ptr<WeaponT>> weapons;
EquipmentUnion equipped;
};
struct Monster FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
enum {
VT_POS = 4,
@@ -73,14 +107,23 @@ struct Monster FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_EQUIPPED = 22
};
const Vec3 *pos() const { return GetStruct<const Vec3 *>(VT_POS); }
Vec3 *mutable_pos() { return GetStruct<Vec3 *>(VT_POS); }
int16_t mana() const { return GetField<int16_t>(VT_MANA, 150); }
bool mutate_mana(int16_t _mana) { return SetField(VT_MANA, _mana); }
int16_t hp() const { return GetField<int16_t>(VT_HP, 100); }
bool mutate_hp(int16_t _hp) { return SetField(VT_HP, _hp); }
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(VT_NAME); }
flatbuffers::String *mutable_name() { return GetPointer<flatbuffers::String *>(VT_NAME); }
const flatbuffers::Vector<uint8_t> *inventory() const { return GetPointer<const flatbuffers::Vector<uint8_t> *>(VT_INVENTORY); }
flatbuffers::Vector<uint8_t> *mutable_inventory() { return GetPointer<flatbuffers::Vector<uint8_t> *>(VT_INVENTORY); }
Color color() const { return static_cast<Color>(GetField<int8_t>(VT_COLOR, 2)); }
bool mutate_color(Color _color) { return SetField(VT_COLOR, static_cast<int8_t>(_color)); }
const flatbuffers::Vector<flatbuffers::Offset<Weapon>> *weapons() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<Weapon>> *>(VT_WEAPONS); }
flatbuffers::Vector<flatbuffers::Offset<Weapon>> *mutable_weapons() { return GetPointer<flatbuffers::Vector<flatbuffers::Offset<Weapon>> *>(VT_WEAPONS); }
Equipment equipped_type() const { return static_cast<Equipment>(GetField<uint8_t>(VT_EQUIPPED_TYPE, 0)); }
bool mutate_equipped_type(Equipment _equipped_type) { return SetField(VT_EQUIPPED_TYPE, static_cast<uint8_t>(_equipped_type)); }
const void *equipped() const { return GetPointer<const void *>(VT_EQUIPPED); }
void *mutable_equipped() { return GetPointer<void *>(VT_EQUIPPED); }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<Vec3>(verifier, VT_POS) &&
@@ -99,6 +142,7 @@ struct Monster FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VerifyEquipment(verifier, equipped(), equipped_type()) &&
verifier.EndTable();
}
std::unique_ptr<MonsterT> UnPack() const;
};
struct MonsterBuilder {
@@ -122,15 +166,15 @@ struct MonsterBuilder {
};
inline flatbuffers::Offset<Monster> CreateMonster(flatbuffers::FlatBufferBuilder &_fbb,
const Vec3 *pos = 0,
int16_t mana = 150,
int16_t hp = 100,
flatbuffers::Offset<flatbuffers::String> name = 0,
flatbuffers::Offset<flatbuffers::Vector<uint8_t>> inventory = 0,
Color color = Color_Blue,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Weapon>>> weapons = 0,
Equipment equipped_type = Equipment_NONE,
flatbuffers::Offset<void> equipped = 0) {
const Vec3 *pos = 0,
int16_t mana = 150,
int16_t hp = 100,
flatbuffers::Offset<flatbuffers::String> name = 0,
flatbuffers::Offset<flatbuffers::Vector<uint8_t>> inventory = 0,
Color color = Color_Blue,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Weapon>>> weapons = 0,
Equipment equipped_type = Equipment_NONE,
flatbuffers::Offset<void> equipped = 0) {
MonsterBuilder builder_(_fbb);
builder_.add_equipped(equipped);
builder_.add_weapons(weapons);
@@ -144,13 +188,35 @@ inline flatbuffers::Offset<Monster> CreateMonster(flatbuffers::FlatBufferBuilder
return builder_.Finish();
}
inline flatbuffers::Offset<Monster> CreateMonsterDirect(flatbuffers::FlatBufferBuilder &_fbb,
const Vec3 *pos = 0,
int16_t mana = 150,
int16_t hp = 100,
const char *name = nullptr,
const std::vector<uint8_t> *inventory = nullptr,
Color color = Color_Blue,
const std::vector<flatbuffers::Offset<Weapon>> *weapons = nullptr,
Equipment equipped_type = Equipment_NONE,
flatbuffers::Offset<void> equipped = 0) {
return CreateMonster(_fbb, pos, mana, hp, name ? _fbb.CreateString(name) : 0, inventory ? _fbb.CreateVector<uint8_t>(*inventory) : 0, color, weapons ? _fbb.CreateVector<flatbuffers::Offset<Weapon>>(*weapons) : 0, equipped_type, equipped);
}
inline flatbuffers::Offset<Monster> CreateMonster(flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o);
struct WeaponT : public flatbuffers::NativeTable {
std::string name;
int16_t damage;
};
struct Weapon FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
enum {
VT_NAME = 4,
VT_DAMAGE = 6
};
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(VT_NAME); }
flatbuffers::String *mutable_name() { return GetPointer<flatbuffers::String *>(VT_NAME); }
int16_t damage() const { return GetField<int16_t>(VT_DAMAGE, 0); }
bool mutate_damage(int16_t _damage) { return SetField(VT_DAMAGE, _damage); }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<flatbuffers::uoffset_t>(verifier, VT_NAME) &&
@@ -158,6 +224,7 @@ struct Weapon FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VerifyField<int16_t>(verifier, VT_DAMAGE) &&
verifier.EndTable();
}
std::unique_ptr<WeaponT> UnPack() const;
};
struct WeaponBuilder {
@@ -174,14 +241,62 @@ struct WeaponBuilder {
};
inline flatbuffers::Offset<Weapon> CreateWeapon(flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<flatbuffers::String> name = 0,
int16_t damage = 0) {
flatbuffers::Offset<flatbuffers::String> name = 0,
int16_t damage = 0) {
WeaponBuilder builder_(_fbb);
builder_.add_name(name);
builder_.add_damage(damage);
return builder_.Finish();
}
inline flatbuffers::Offset<Weapon> CreateWeaponDirect(flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
int16_t damage = 0) {
return CreateWeapon(_fbb, name ? _fbb.CreateString(name) : 0, damage);
}
inline flatbuffers::Offset<Weapon> CreateWeapon(flatbuffers::FlatBufferBuilder &_fbb, const WeaponT *_o);
inline std::unique_ptr<MonsterT> Monster::UnPack() const {
auto _o = new MonsterT();
{ auto _e = pos(); if (_e) _o->pos = std::unique_ptr<Vec3>(new Vec3(*_e)); };
{ auto _e = mana(); _o->mana = _e; };
{ auto _e = hp(); _o->hp = _e; };
{ auto _e = name(); if (_e) _o->name = _e->str(); };
{ auto _e = inventory(); if (_e) { for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->inventory.push_back(_e->Get(_i)); } } };
{ auto _e = color(); _o->color = _e; };
{ auto _e = weapons(); if (_e) { for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->weapons.push_back(_e->Get(_i)->UnPack()); } } };
{ auto _e = equipped_type(); _o->equipped.type = _e; };
{ auto _e = equipped(); if (_e) _o->equipped.table = EquipmentUnion::UnPack(_e, equipped_type()); };
return std::unique_ptr<MonsterT>(_o);
}
inline flatbuffers::Offset<Monster> CreateMonster(flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o) {
return CreateMonster(_fbb,
_o->pos ? _o->pos.get() : 0,
_o->mana,
_o->hp,
_o->name.size() ? _fbb.CreateString(_o->name) : 0,
_o->inventory.size() ? _fbb.CreateVector(_o->inventory) : 0,
_o->color,
_o->weapons.size() ? _fbb.CreateVector<flatbuffers::Offset<Weapon>>(_o->weapons.size(), [&](size_t i) { return CreateWeapon(_fbb, _o->weapons[i].get()); }) : 0,
_o->equipped.type,
_o->equipped.Pack(_fbb));
}
inline std::unique_ptr<WeaponT> Weapon::UnPack() const {
auto _o = new WeaponT();
{ auto _e = name(); if (_e) _o->name = _e->str(); };
{ auto _e = damage(); _o->damage = _e; };
return std::unique_ptr<WeaponT>(_o);
}
inline flatbuffers::Offset<Weapon> CreateWeapon(flatbuffers::FlatBufferBuilder &_fbb, const WeaponT *_o) {
return CreateWeapon(_fbb,
_o->name.size() ? _fbb.CreateString(_o->name) : 0,
_o->damage);
}
inline bool VerifyEquipment(flatbuffers::Verifier &verifier, const void *union_obj, Equipment type) {
switch (type) {
case Equipment_NONE: return true;
@@ -190,9 +305,34 @@ inline bool VerifyEquipment(flatbuffers::Verifier &verifier, const void *union_o
}
}
inline flatbuffers::NativeTable *EquipmentUnion::UnPack(const void *union_obj, Equipment type) {
switch (type) {
case Equipment_NONE: return nullptr;
case Equipment_Weapon: return reinterpret_cast<const Weapon *>(union_obj)->UnPack().release();
default: return nullptr;
}
}
inline flatbuffers::Offset<void> EquipmentUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb) const {
switch (type) {
case Equipment_NONE: return 0;
case Equipment_Weapon: return CreateWeapon(_fbb, reinterpret_cast<const WeaponT *>(table)).Union();
default: return 0;
}
}
inline EquipmentUnion::~EquipmentUnion() {
switch (type) {
case Equipment_Weapon: delete reinterpret_cast<WeaponT *>(table); break;
default:;
}
}
inline const MyGame::Sample::Monster *GetMonster(const void *buf) { return flatbuffers::GetRoot<MyGame::Sample::Monster>(buf); }
inline bool VerifyMonsterBuffer(flatbuffers::Verifier &verifier) { return verifier.VerifyBuffer<MyGame::Sample::Monster>(); }
inline Monster *GetMutableMonster(void *buf) { return flatbuffers::GetMutableRoot<Monster>(buf); }
inline bool VerifyMonsterBuffer(flatbuffers::Verifier &verifier) { return verifier.VerifyBuffer<MyGame::Sample::Monster>(nullptr); }
inline void FinishMonsterBuffer(flatbuffers::FlatBufferBuilder &fbb, flatbuffers::Offset<MyGame::Sample::Monster> root) { fbb.Finish(root); }

View File

@@ -1,4 +1,5 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,7 +13,7 @@
# 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.
#
# Note: This script runs on Mac and Linux. It requires `php` to be installed
# and `flatc` to be built (using `cmake` in the root directory).

View File

@@ -1,4 +1,5 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,7 +13,7 @@
# 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.
#
# Note: This script runs on Mac and Linux. It requires `python` to be installed
# and `flatc` to be built (using `cmake` in the root directory).

View File

@@ -19,7 +19,7 @@
#include "flatbuffers/util.h"
#include <limits>
#define FLATC_VERSION "1.3.0 (" __DATE__ ")"
#define FLATC_VERSION "1.4.0 (" __DATE__ ")"
static void Error(const std::string &err, bool usage = false,
bool show_exe_name = true);
@@ -74,20 +74,24 @@ const Generator generators[] = {
flatbuffers::IDLOptions::kMAX,
"Generate Python files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePhp, nullptr, "--php", "PHP",
{ flatbuffers::GeneratePhp, nullptr, "--php", "PHP",
flatbuffers::IDLOptions::kMAX,
"Generate PHP files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGRPC, nullptr, "--grpc", "GRPC",
flatbuffers::IDLOptions::kMAX,
"Generate GRPC interfaces",
flatbuffers::CPPMakeRule },
};
const char *program_name = nullptr;
flatbuffers::Parser *parser = nullptr;
const char *g_program_name = nullptr;
flatbuffers::Parser *g_parser = nullptr;
static void Error(const std::string &err, bool usage, bool show_exe_name) {
if (show_exe_name) printf("%s: ", program_name);
if (show_exe_name) printf("%s: ", g_program_name);
printf("%s\n", err.c_str());
if (usage) {
printf("usage: %s [OPTION]... FILE... [-- FILE...]\n", program_name);
printf("usage: %s [OPTION]... FILE... [-- FILE...]\n", g_program_name);
for (size_t i = 0; i < sizeof(generators) / sizeof(generators[0]); ++i)
printf(" %-12s %s %s.\n",
generators[i].generator_opt_long,
@@ -96,44 +100,65 @@ static void Error(const std::string &err, bool usage, bool show_exe_name) {
: " ",
generators[i].generator_help);
printf(
" -o PATH Prefix PATH to all generated files.\n"
" -I PATH Search for includes in the specified path.\n"
" -M Print make rules for generated files.\n"
" --version Print the version number of flatc and exit.\n"
" --strict-json Strict JSON: field names must be / will be quoted,\n"
" no trailing commas in tables/vectors.\n"
" --defaults-json Output fields whose value is the default when\n"
" writing JSON\n"
" --unknown-json Allow fields in JSON that are not defined in the\n"
" schema. These fields will be discared when generating\n"
" binaries.\n"
" --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
" --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
" also implies --no-prefix.\n"
" --gen-includes (deprecated), this is the default behavior.\n"
" If the original behavior is required (no include\n"
" statements) use --no-includes.\n"
" --no-includes Don\'t generate include statements for included\n"
" schemas the generated file depends on (C++).\n"
" --gen-mutable Generate accessors that can mutate buffers in-place.\n"
" --gen-onefile Generate single output file for C#\n"
" --raw-binary Allow binaries without file_indentifier to be read.\n"
" This may crash flatc given a mismatched schema.\n"
" --proto Input is a .proto, translate to .fbs.\n"
" --schema Serialize schemas instead of JSON (use with -b)\n"
" -o PATH Prefix PATH to all generated files.\n"
" -I PATH Search for includes in the specified path.\n"
" -M Print make rules for generated files.\n"
" --version Print the version number of flatc and exit.\n"
" --strict-json Strict JSON: field names must be / will be quoted,\n"
" no trailing commas in tables/vectors.\n"
" --allow-non-utf8 Pass non-UTF-8 input through parser and emit nonstandard\n"
" \\x escapes in JSON. (Default is to raise parse error on\n"
" non-UTF-8 input.)\n"
" --defaults-json Output fields whose value is the default when\n"
" writing JSON\n"
" --unknown-json Allow fields in JSON that are not defined in the\n"
" schema. These fields will be discared when generating\n"
" binaries.\n"
" --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
" --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
" also implies --no-prefix.\n"
" --gen-includes (deprecated), this is the default behavior.\n"
" If the original behavior is required (no include\n"
" statements) use --no-includes.\n"
" --no-includes Don\'t generate include statements for included\n"
" schemas the generated file depends on (C++).\n"
" --gen-mutable Generate accessors that can mutate buffers in-place.\n"
" --gen-onefile Generate single output file for C#.\n"
" --gen-name-strings Generate type name functions for C++.\n"
" --escape-proto-ids Disable appending '_' in namespaces names.\n"
" --gen-object-api Generate an additional object-based API\n"
" --raw-binary Allow binaries without file_indentifier to be read.\n"
" This may crash flatc given a mismatched schema.\n"
" --proto Input is a .proto, translate to .fbs.\n"
" --schema Serialize schemas instead of JSON (use with -b)\n"
" --conform FILE Specify a schema the following schemas should be\n"
" an evolution of. Gives errors if not.\n"
"FILEs may be schemas, or JSON files (conforming to preceding schema)\n"
"FILEs after the -- must be binary flatbuffer format files.\n"
"Output files are named using the base file name of the input,\n"
"and written to the current directory or the path given by -o.\n"
"example: %s -c -b schema1.fbs schema2.fbs data.json\n",
program_name);
g_program_name);
}
if (parser) delete parser;
if (g_parser) delete g_parser;
exit(1);
}
static void ParseFile(flatbuffers::Parser &parser, const std::string &filename,
const std::string &contents,
std::vector<const char *> &include_directories) {
auto local_include_directory = flatbuffers::StripFileName(filename);
include_directories.push_back(local_include_directory.c_str());
include_directories.push_back(nullptr);
if (!parser.Parse(contents.c_str(), &include_directories[0],
filename.c_str()))
Error(parser.error_, false, false);
include_directories.pop_back();
include_directories.pop_back();
}
int main(int argc, const char *argv[]) {
program_name = argv[0];
g_program_name = argv[0];
flatbuffers::IDLOptions opts;
std::string output_path;
const size_t num_generators = sizeof(generators) / sizeof(generators[0]);
@@ -145,6 +170,7 @@ int main(int argc, const char *argv[]) {
std::vector<std::string> filenames;
std::vector<const char *> include_directories;
size_t binary_files_from = std::numeric_limits<size_t>::max();
std::string conform_to_schema;
for (int argi = 1; argi < argc; argi++) {
std::string arg = argv[argi];
if (arg[0] == '-') {
@@ -156,8 +182,13 @@ int main(int argc, const char *argv[]) {
} else if(arg == "-I") {
if (++argi >= argc) Error("missing path following" + arg, true);
include_directories.push_back(argv[argi]);
} else if(arg == "--conform") {
if (++argi >= argc) Error("missing path following" + arg, true);
conform_to_schema = argv[argi];
} else if(arg == "--strict-json") {
opts.strict_json = true;
} else if(arg == "--allow-non-utf8") {
opts.allow_non_utf8 = true;
} else if(arg == "--no-js-exports") {
opts.skip_js_exports = true;
} else if(arg == "--defaults-json") {
@@ -169,8 +200,14 @@ int main(int argc, const char *argv[]) {
} else if(arg == "--scoped-enums") {
opts.prefixed_enums = false;
opts.scoped_enums = true;
} else if (arg == "--no-union-value-namespacing") {
opts.union_value_namespacing = false;
} else if(arg == "--gen-mutable") {
opts.mutable_buffer = true;
} else if(arg == "--gen-name-strings") {
opts.generate_name_strings = true;
} else if(arg == "--gen-object-api") {
opts.generate_object_based_api = true;
} else if(arg == "--gen-all") {
opts.generate_all = true;
opts.include_dependence_headers = false;
@@ -187,6 +224,8 @@ int main(int argc, const char *argv[]) {
binary_files_from = filenames.size();
} else if(arg == "--proto") {
opts.proto_mode = true;
} else if(arg == "--escape-proto-ids") {
opts.escape_proto_identifiers = true;
} else if(arg == "--schema") {
schema_binary = true;
} else if(arg == "-M") {
@@ -217,12 +256,20 @@ int main(int argc, const char *argv[]) {
if (opts.proto_mode) {
if (any_generator)
Error("cannot generate code directly from .proto files", true);
} else if (!any_generator) {
} else if (!any_generator && conform_to_schema.empty()) {
Error("no options: specify at least one generator.", true);
}
flatbuffers::Parser conform_parser;
if (!conform_to_schema.empty()) {
std::string contents;
if (!flatbuffers::LoadFile(conform_to_schema.c_str(), true, &contents))
Error("unable to load schema: " + conform_to_schema);
ParseFile(conform_parser, conform_to_schema, contents, include_directories);
}
// Now process the files:
parser = new flatbuffers::Parser(opts);
g_parser = new flatbuffers::Parser(opts);
for (auto file_it = filenames.begin();
file_it != filenames.end();
++file_it) {
@@ -233,8 +280,8 @@ int main(int argc, const char *argv[]) {
bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >=
binary_files_from;
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
g_parser->builder_.Clear();
g_parser->builder_.PushFlatBuffer(
reinterpret_cast<const uint8_t *>(contents.c_str()),
contents.length());
if (!raw_binary) {
@@ -243,17 +290,17 @@ int main(int argc, const char *argv[]) {
// does not contain a file identifier.
// We'd expect that typically any binary used as a file would have
// such an identifier, so by default we require them to match.
if (!parser->file_identifier_.length()) {
if (!g_parser->file_identifier_.length()) {
Error("current schema has no file_identifier: cannot test if \"" +
*file_it +
"\" matches the schema, use --raw-binary to read this file"
" anyway.");
} else if (!flatbuffers::BufferHasIdentifier(contents.c_str(),
parser->file_identifier_.c_str())) {
g_parser->file_identifier_.c_str())) {
Error("binary \"" +
*file_it +
"\" does not have expected file_identifier \"" +
parser->file_identifier_ +
g_parser->file_identifier_ +
"\", use --raw-binary to read this file anyway.");
}
}
@@ -262,36 +309,34 @@ int main(int argc, const char *argv[]) {
if (contents.length() != strlen(contents.c_str())) {
Error("input file appears to be binary: " + *file_it, true);
}
if (flatbuffers::GetExtension(*file_it) == "fbs") {
auto is_schema = flatbuffers::GetExtension(*file_it) == "fbs";
if (is_schema) {
// If we're processing multiple schemas, make sure to start each
// one from scratch. If it depends on previous schemas it must do
// so explicitly using an include.
delete parser;
parser = new flatbuffers::Parser(opts);
delete g_parser;
g_parser = new flatbuffers::Parser(opts);
}
ParseFile(*g_parser, *file_it, contents, include_directories);
if (is_schema && !conform_to_schema.empty()) {
auto err = g_parser->ConformTo(conform_parser);
if (!err.empty()) Error("schemas don\'t conform: " + err);
}
auto local_include_directory = flatbuffers::StripFileName(*file_it);
include_directories.push_back(local_include_directory.c_str());
include_directories.push_back(nullptr);
if (!parser->Parse(contents.c_str(), &include_directories[0],
file_it->c_str()))
Error(parser->error_, false, false);
if (schema_binary) {
parser->Serialize();
parser->file_extension_ = reflection::SchemaExtension();
g_parser->Serialize();
g_parser->file_extension_ = reflection::SchemaExtension();
}
include_directories.pop_back();
include_directories.pop_back();
}
std::string filebase = flatbuffers::StripPath(
flatbuffers::StripExtension(*file_it));
for (size_t i = 0; i < num_generators; ++i) {
parser->opts.lang = generators[i].lang;
g_parser->opts.lang = generators[i].lang;
if (generator_enabled[i]) {
if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path);
if (!generators[i].generate(*parser, output_path, filebase)) {
if (!generators[i].generate(*g_parser, output_path, filebase)) {
Error(std::string("Unable to generate ") +
generators[i].lang_name +
" for " +
@@ -299,7 +344,7 @@ int main(int argc, const char *argv[]) {
}
} else {
std::string make_rule = generators[i].make_rule(
*parser, output_path, *file_it);
*g_parser, output_path, *file_it);
if (!make_rule.empty())
printf("%s\n", flatbuffers::WordWrap(
make_rule, 80, " ", " \\").c_str());
@@ -307,13 +352,13 @@ int main(int argc, const char *argv[]) {
}
}
if (opts.proto_mode) GenerateFBS(*parser, output_path, filebase);
if (opts.proto_mode) GenerateFBS(*g_parser, output_path, filebase);
// We do not want to generate code for the definitions in this file
// in any files coming up next.
parser->MarkGenerated();
g_parser->MarkGenerated();
}
delete parser;
delete g_parser;
return 0;
}

File diff suppressed because it is too large Load Diff

View File

@@ -53,12 +53,14 @@ static void GenNameSpace(const Namespace &name_space, std::string *_schema,
// Generate a flatbuffer schema from the Parser's internal representation.
std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
// Proto namespaces may clash with table names, so we have to prefix all:
for (auto it = parser.namespaces_.begin(); it != parser.namespaces_.end();
++it) {
for (auto comp = (*it)->components.begin(); comp != (*it)->components.end();
++comp) {
(*comp) = "_" + (*comp);
// Proto namespaces may clash with table names, so we have to prefix all:
if (!parser.opts.escape_proto_identifiers) {
for (auto it = parser.namespaces_.begin(); it != parser.namespaces_.end();
++it) {
for (auto comp = (*it)->components.begin(); comp != (*it)->components.end();
++comp) {
(*comp) = "_" + (*comp);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -21,6 +21,7 @@
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include "flatbuffers/code_generators.h"
#ifdef _WIN32
#include <direct.h>
@@ -52,20 +53,6 @@ std::string OffsetPrefix(const FieldDef &field) {
"))\n\tif o != 0 {\n";
}
// Begin by declaring namespace and imports.
static void BeginFile(const std::string name_space_name,
const bool needs_imports,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "// automatically generated, do not modify\n\n";
code += "package " + name_space_name + "\n\n";
if (needs_imports) {
code += "import (\n";
code += "\tflatbuffers \"github.com/google/flatbuffers/go\"\n";
code += ")\n";
}
}
// Begin a class declaration.
static void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
@@ -98,7 +85,33 @@ static void EnumMember(const EnumDef &enum_def, const EnumVal ev,
// End enum code.
static void EndEnum(std::string *code_ptr) {
std::string &code = *code_ptr;
code += ")\n";
code += ")\n\n";
}
// Begin enum name code.
static void BeginEnumNames(const EnumDef &enum_def, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "var EnumNames";
code += enum_def.name;
code += " = map[int]string{\n";
}
// A single enum name member.
static void EnumNameMember(const EnumDef &enum_def, const EnumVal ev,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "\t";
code += enum_def.name;
code += ev.name;
code += ":\"";
code += ev.name;
code += "\",\n";
}
// End enum name code.
static void EndEnumNames(std::string *code_ptr) {
std::string &code = *code_ptr;
code += "}\n\n";
}
// Initialize a new struct or table from existing data.
@@ -113,7 +126,7 @@ static void NewRootTypeFromBuffer(const StructDef &struct_def,
code += " {\n";
code += "\tn := flatbuffers.GetUOffsetT(buf[offset:])\n";
code += "\tx := &" + struct_def.name + "{}\n";
code += "\tx.Init(buf, n + offset)\n";
code += "\tx.Init(buf, n+offset)\n";
code += "\treturn x\n";
code += "}\n\n";
}
@@ -165,9 +178,10 @@ static void GetScalarFieldOfStruct(const StructDef &struct_def,
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
code += " " + MakeCamel(field.name);
code += "() " + TypeName(field) + " { return " + getter;
code += "() " + TypeName(field) + " {\n";
code +="\treturn " + getter;
code += "(rcv._tab.Pos + flatbuffers.UOffsetT(";
code += NumToString(field.value.offset) + ")) }\n";
code += NumToString(field.value.offset) + "))\n}\n";
}
// Get the value of a table's scalar.
@@ -199,7 +213,7 @@ static void GetStructFieldOfStruct(const StructDef &struct_def,
code += "\tif obj == nil {\n";
code += "\t\tobj = new(" + TypeName(field) + ")\n";
code += "\t}\n";
code += "\tobj.Init(rcv._tab.Bytes, rcv._tab.Pos + ";
code += "\tobj.Init(rcv._tab.Bytes, rcv._tab.Pos+";
code += NumToString(field.value.offset) + ")";
code += "\n\treturn obj\n";
code += "}\n";
@@ -274,9 +288,9 @@ static void GetMemberOfVectorOfStruct(const StructDef &struct_def,
if (!(vectortype.struct_def->fixed)) {
code += "\t\tx = rcv._tab.Indirect(x)\n";
}
code += "\tif obj == nil {\n";
code += "\t\tobj = new(" + TypeName(field) + ")\n";
code += "\t}\n";
code += "\t\tif obj == nil {\n";
code += "\t\t\tobj = new(" + TypeName(field) + ")\n";
code += "\t\t}\n";
code += "\t\tobj.Init(rcv._tab.Bytes, x)\n";
code += "\t\treturn true\n\t}\n";
code += "\treturn false\n";
@@ -297,7 +311,7 @@ static void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
code += OffsetPrefix(field);
code += "\t\ta := rcv._tab.Vector(o)\n";
code += "\t\treturn " + GenGetter(field.value.type) + "(";
code += "a + flatbuffers.UOffsetT(j * ";
code += "a + flatbuffers.UOffsetT(j*";
code += NumToString(InlineSize(vectortype)) + "))\n";
code += "\t}\n";
if (vectortype.base_type == BASE_TYPE_STRING) {
@@ -313,7 +327,10 @@ static void BeginBuilderArgs(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "\n";
if (code.substr(code.length() - 2) != "\n\n") {
// a previous mutate has not put an extra new line
code += "\n";
}
code += "func Create" + struct_def.name;
code += "(builder *flatbuffers.Builder";
}
@@ -355,20 +372,20 @@ static void StructBuilderBody(const StructDef &struct_def,
const char *nameprefix,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += " builder.Prep(" + NumToString(struct_def.minalign) + ", ";
code += "\tbuilder.Prep(" + NumToString(struct_def.minalign) + ", ";
code += NumToString(struct_def.bytesize) + ")\n";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend();
++it) {
auto &field = **it;
if (field.padding)
code += " builder.Pad(" + NumToString(field.padding) + ")\n";
code += "\tbuilder.Pad(" + NumToString(field.padding) + ")\n";
if (IsStruct(field.value.type)) {
StructBuilderBody(*field.value.type.struct_def,
(nameprefix + (field.name + "_")).c_str(),
code_ptr);
} else {
code += " builder.Prepend" + GenMethod(field) + "(";
code += "\tbuilder.Prepend" + GenMethod(field) + "(";
code += nameprefix + MakeCamel(field.name, false) + ")\n";
}
}
@@ -376,7 +393,7 @@ static void StructBuilderBody(const StructDef &struct_def,
static void EndBuilderBody(std::string *code_ptr) {
std::string &code = *code_ptr;
code += " return builder.Offset()\n";
code += "\treturn builder.Offset()\n";
code += "}\n";
}
@@ -385,10 +402,10 @@ static void GetStartOfTable(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "func " + struct_def.name + "Start";
code += "(builder *flatbuffers.Builder) { ";
code += "builder.StartObject(";
code += "(builder *flatbuffers.Builder) {\n";
code += "\tbuilder.StartObject(";
code += NumToString(struct_def.fields.vec.size());
code += ") }\n";
code += ")\n}\n";
}
// Set the value of a table's field.
@@ -405,8 +422,8 @@ static void BuildFieldOfTable(const StructDef &struct_def,
} else {
code += GenTypeBasic(field.value.type);
}
code += ") ";
code += "{ builder.Prepend";
code += ") {\n";
code += "\tbuilder.Prepend";
code += GenMethod(field) + "Slot(";
code += NumToString(offset) + ", ";
if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
@@ -417,7 +434,7 @@ static void BuildFieldOfTable(const StructDef &struct_def,
code += MakeCamel(field.name, false);
}
code += ", " + field.value.constant;
code += ") }\n";
code += ")\n}\n";
}
// Set the value of one of the members of a table's vector.
@@ -428,7 +445,7 @@ static void BuildVectorOfTable(const StructDef &struct_def,
code += "func " + struct_def.name + "Start";
code += MakeCamel(field.name);
code += "Vector(builder *flatbuffers.Builder, numElems int) ";
code += "flatbuffers.UOffsetT { return builder.StartVector(";
code += "flatbuffers.UOffsetT {\n\treturn builder.StartVector(";
auto vector_type = field.value.type.VectorType();
auto alignment = InlineAlignment(vector_type);
auto elem_size = InlineSize(vector_type);
@@ -443,7 +460,7 @@ static void GetEndOffsetOnTable(const StructDef &struct_def,
std::string &code = *code_ptr;
code += "func " + struct_def.name + "End";
code += "(builder *flatbuffers.Builder) flatbuffers.UOffsetT ";
code += "{ return builder.EndObject() }\n";
code += "{\n\treturn builder.EndObject()\n}\n";
}
// Generate the receiver for function signatures.
@@ -452,7 +469,7 @@ static void GenReceiver(const StructDef &struct_def, std::string *code_ptr) {
code += "func (rcv *" + struct_def.name + ")";
}
// Generate a struct field, conditioned on its child type(s).
// Generate a struct field getter, conditioned on its child type(s).
static void GenStructAccessor(const StructDef &struct_def,
const FieldDef &field,
std::string *code_ptr) {
@@ -499,6 +516,48 @@ static void GenStructAccessor(const StructDef &struct_def,
}
}
// Mutate the value of a struct's scalar.
static void MutateScalarFieldOfStruct(const StructDef &struct_def,
const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
std::string type = MakeCamel(GenTypeBasic(field.value.type));
std::string setter = "rcv._tab.Mutate" + type;
GenReceiver(struct_def, code_ptr);
code += " Mutate" + MakeCamel(field.name);
code += "(n " + TypeName(field) + ") bool {\n\treturn " + setter;
code += "(rcv._tab.Pos+flatbuffers.UOffsetT(";
code += NumToString(field.value.offset) + "), n)\n}\n\n";
}
// Mutate the value of a table's scalar.
static void MutateScalarFieldOfTable(const StructDef &struct_def,
const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
std::string type = MakeCamel(GenTypeBasic(field.value.type));
std::string setter = "rcv._tab.Mutate" + type + "Slot";
GenReceiver(struct_def, code_ptr);
code += " Mutate" + MakeCamel(field.name);
code += "(n " + TypeName(field) + ") bool {\n\treturn ";
code += setter + "(" + NumToString(field.value.offset) + ", n)\n";
code += "}\n\n";
}
// Generate a struct field setter, conditioned on its child type(s).
static void GenStructMutator(const StructDef &struct_def,
const FieldDef &field,
std::string *code_ptr) {
GenComment(field.doc_comment, code_ptr, nullptr, "");
if (IsScalar(field.value.type.base_type)) {
if (struct_def.fixed) {
MutateScalarFieldOfStruct(struct_def, field, code_ptr);
} else {
MutateScalarFieldOfTable(struct_def, field, code_ptr);
}
}
}
// Generate table constructors, conditioned on its members' types.
static void GenTableBuilders(const StructDef &struct_def,
std::string *code_ptr) {
@@ -522,13 +581,12 @@ static void GenTableBuilders(const StructDef &struct_def,
// Generate struct or table methods.
static void GenStruct(const StructDef &struct_def,
std::string *code_ptr,
StructDef *root_struct_def) {
std::string *code_ptr) {
if (struct_def.generated) return;
GenComment(struct_def.doc_comment, code_ptr, nullptr);
BeginClass(struct_def, code_ptr);
if (&struct_def == root_struct_def) {
if (!struct_def.fixed) {
// Generate a special accessor for the table that has been declared as
// the root type.
NewRootTypeFromBuffer(struct_def, code_ptr);
@@ -543,6 +601,7 @@ static void GenStruct(const StructDef &struct_def,
if (field.deprecated) continue;
GenStructAccessor(struct_def, field, code_ptr);
GenStructMutator(struct_def, field, code_ptr);
}
if (struct_def.fixed) {
@@ -568,6 +627,15 @@ static void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
EnumMember(enum_def, ev, code_ptr);
}
EndEnum(code_ptr);
BeginEnumNames(enum_def, code_ptr);
for (auto it = enum_def.vals.vec.begin();
it != enum_def.vals.vec.end();
++it) {
auto &ev = **it;
EnumNameMember(enum_def, ev, code_ptr);
}
EndEnumNames(code_ptr);
}
// Returns the function name that is able to read a value of the given type.
@@ -588,32 +656,6 @@ static std::string GenMethod(const FieldDef &field) {
: (IsStruct(field.value.type) ? "Struct" : "UOffsetT");
}
// Save out the generated code for a Go Table type.
static bool SaveType(const Parser &parser, const Definition &def,
const std::string &classcode, const std::string &path,
bool needs_imports) {
if (!classcode.length()) return true;
std::string namespace_name;
std::string namespace_dir = path; // Either empty or ends in separator.
auto &namespaces = parser.namespaces_.back()->components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
if (namespace_name.length()) {
namespace_name += ".";
}
namespace_name = *it;
namespace_dir += *it + kPathSeparator;
}
EnsureDirExists(namespace_dir);
std::string code = "";
BeginFile(namespace_name, needs_imports, &code);
code += classcode;
std::string filename = namespace_dir + def.name + ".go";
return SaveFile(filename.c_str(), code, false);
}
static std::string GenTypeBasic(const Type &type) {
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
@@ -660,29 +702,63 @@ static void GenStructBuilder(const StructDef &struct_def,
EndBuilderBody(code_ptr);
}
class GoGenerator : public BaseGenerator {
public:
GoGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "" /* not used*/,
"" /* not used */){};
bool generate() {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
std::string enumcode;
go::GenEnum(**it, &enumcode);
if (!SaveType(**it, enumcode, false)) return false;
}
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
std::string declcode;
go::GenStruct(**it, &declcode);
if (!SaveType(**it, declcode, true)) return false;
}
return true;
}
private:
// Begin by declaring namespace and imports.
void BeginFile(const std::string name_space_name, const bool needs_imports,
std::string *code_ptr) {
std::string &code = *code_ptr;
code = code + "// " + FlatBuffersGeneratedWarning();
code += "package " + name_space_name + "\n\n";
if (needs_imports) {
code += "import (\n";
code += "\tflatbuffers \"github.com/google/flatbuffers/go\"\n";
code += ")\n\n";
}
}
// Save out the generated code for a Go Table type.
bool SaveType(const Definition &def, const std::string &classcode,
bool needs_imports) {
if (!classcode.length()) return true;
std::string code = "";
BeginFile(LastNamespacePart(*def.defined_namespace), needs_imports, &code);
code += classcode;
std::string filename =
NamespaceDir(*def.defined_namespace) + def.name + ".go";
return SaveFile(filename.c_str(), code, false);
}
};
} // namespace go
bool GenerateGo(const Parser &parser,
const std::string &path,
const std::string & /*file_name*/) {
for (auto it = parser.enums_.vec.begin();
it != parser.enums_.vec.end(); ++it) {
std::string enumcode;
go::GenEnum(**it, &enumcode);
if (!go::SaveType(parser, **it, enumcode, path, false))
return false;
}
for (auto it = parser.structs_.vec.begin();
it != parser.structs_.vec.end(); ++it) {
std::string declcode;
go::GenStruct(**it, &declcode, parser.root_struct_def_);
if (!go::SaveType(parser, **it, declcode, path, true))
return false;
}
return true;
bool GenerateGo(const Parser &parser, const std::string &path,
const std::string &file_name) {
go::GoGenerator generator(parser, path, file_name);
return generator.generate();
}
} // namespace flatbuffers

217
src/idl_gen_grpc.cpp Normal file
View File

@@ -0,0 +1,217 @@
/*
* 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.
*/
// independent from idl_parser, since this code is not needed for most clients
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include "src/compiler/cpp_generator.h"
namespace flatbuffers {
class FlatBufMethod : public grpc_cpp_generator::Method {
public:
enum Streaming { kNone, kClient, kServer, kBiDi };
FlatBufMethod(const RPCCall *method)
: method_(method) {
streaming_ = kNone;
auto val = method_->attributes.Lookup("streaming");
if (val) {
if (val->constant == "client") streaming_ = kClient;
if (val->constant == "server") streaming_ = kServer;
if (val->constant == "bidi") streaming_ = kBiDi;
}
}
std::string name() const { return method_->name; }
std::string GRPCType(const StructDef &sd) const {
return "flatbuffers::BufferRef<" + sd.name + ">";
}
std::string input_type_name() const {
return GRPCType(*method_->request);
}
std::string output_type_name() const {
return GRPCType(*method_->response);
}
bool NoStreaming() const { return streaming_ == kNone; }
bool ClientOnlyStreaming() const { return streaming_ == kClient; }
bool ServerOnlyStreaming() const { return streaming_ == kServer; }
bool BidiStreaming() const { return streaming_ == kBiDi; }
private:
const RPCCall *method_;
Streaming streaming_;
};
class FlatBufService : public grpc_cpp_generator::Service {
public:
FlatBufService(const ServiceDef *service) : service_(service) {}
std::string name() const { return service_->name; }
int method_count() const {
return static_cast<int>(service_->calls.vec.size());
};
std::unique_ptr<const grpc_cpp_generator::Method> method(int i) const {
return std::unique_ptr<const grpc_cpp_generator::Method>(
new FlatBufMethod(service_->calls.vec[i]));
};
private:
const ServiceDef *service_;
};
class FlatBufPrinter : public grpc_cpp_generator::Printer {
public:
FlatBufPrinter(std::string *str)
: str_(str), escape_char_('$'), indent_(0) {}
void Print(const std::map<std::string, std::string> &vars,
const char *string_template) {
std::string s = string_template;
// Replace any occurrences of strings in "vars" that are surrounded
// by the escape character by what they're mapped to.
size_t pos;
while ((pos = s.find(escape_char_)) != std::string::npos) {
// Found an escape char, must also find the closing one.
size_t pos2 = s.find(escape_char_, pos + 1);
// If placeholder not closed, ignore.
if (pos2 == std::string::npos) break;
auto it = vars.find(s.substr(pos + 1, pos2 - pos - 1));
// If unknown placeholder, ignore.
if (it == vars.end()) break;
// Subtitute placeholder.
s.replace(pos, pos2 - pos + 1, it->second);
}
Print(s.c_str());
}
void Print(const char *s) {
// Add this string, but for each part separated by \n, add indentation.
for (;;) {
// Current indentation.
str_->insert(str_->end(), indent_ * 2, ' ');
// See if this contains more than one line.
const char * lf = strchr(s, '\n');
if (lf) {
(*str_) += std::string(s, lf + 1);
s = lf + 1;
if (!*s) break; // Only continue if there's more lines.
} else {
(*str_) += s;
break;
}
}
}
void Indent() { indent_++; }
void Outdent() { indent_--; assert(indent_ >= 0); }
private:
std::string *str_;
char escape_char_;
int indent_;
};
class FlatBufFile : public grpc_cpp_generator::File {
public:
FlatBufFile(const Parser &parser, const std::string &file_name)
: parser_(parser), file_name_(file_name) {}
FlatBufFile &operator=(const FlatBufFile &);
std::string filename() const { return file_name_; }
std::string filename_without_ext() const {
return StripExtension(file_name_);
}
std::string message_header_ext() const { return "_generated.h"; }
std::string service_header_ext() const { return ".grpc.fb.h"; }
std::string package() const {
return parser_.namespaces_.back()->GetFullyQualifiedName("");
}
std::vector<std::string> package_parts() const {
return parser_.namespaces_.back()->components;
}
std::string additional_headers() const {
return "#include \"flatbuffers/grpc.h\"\n";
}
int service_count() const {
return static_cast<int>(parser_.services_.vec.size());
};
std::unique_ptr<const grpc_cpp_generator::Service> service(int i) const {
return std::unique_ptr<const grpc_cpp_generator::Service> (
new FlatBufService(parser_.services_.vec[i]));
}
std::unique_ptr<grpc_cpp_generator::Printer> CreatePrinter(std::string *str) const {
return std::unique_ptr<grpc_cpp_generator::Printer>(
new FlatBufPrinter(str));
}
private:
const Parser &parser_;
const std::string &file_name_;
};
bool GenerateGRPC(const Parser &parser,
const std::string &/*path*/,
const std::string &file_name) {
int nservices = 0;
for (auto it = parser.services_.vec.begin();
it != parser.services_.vec.end(); ++it) {
if (!(*it)->generated) nservices++;
}
if (!nservices) return true;
grpc_cpp_generator::Parameters generator_parameters;
// TODO(wvo): make the other parameters in this struct configurable.
generator_parameters.use_system_headers = true;
FlatBufFile fbfile(parser, file_name);
std::string header_code =
grpc_cpp_generator::GetHeaderPrologue(&fbfile, generator_parameters) +
grpc_cpp_generator::GetHeaderIncludes(&fbfile, generator_parameters) +
grpc_cpp_generator::GetHeaderServices(&fbfile, generator_parameters) +
grpc_cpp_generator::GetHeaderEpilogue(&fbfile, generator_parameters);
std::string source_code =
grpc_cpp_generator::GetSourcePrologue(&fbfile, generator_parameters) +
grpc_cpp_generator::GetSourceIncludes(&fbfile, generator_parameters) +
grpc_cpp_generator::GetSourceServices(&fbfile, generator_parameters) +
grpc_cpp_generator::GetSourceEpilogue(&fbfile, generator_parameters);
return flatbuffers::SaveFile((file_name + ".grpc.fb.h").c_str(),
header_code, false) &&
flatbuffers::SaveFile((file_name + ".grpc.fb.cc").c_str(),
source_code, false);
}
} // namespace flatbuffers

View File

@@ -19,16 +19,74 @@
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include "flatbuffers/code_generators.h"
namespace flatbuffers {
namespace js {
static void GenNamespaces(const Parser &parser, std::string *code_ptr,
std::string *exports_ptr) {
static std::string GeneratedFileName(const std::string &path,
const std::string &file_name) {
return path + file_name + "_generated.js";
}
namespace js {
// Iterate through all definitions we haven't generate code for (enums, structs,
// and tables) and output them to a single file.
class JsGenerator : public BaseGenerator {
public:
JsGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "", "."){};
// Iterate through all definitions we haven't generate code for (enums,
// structs, and tables) and output them to a single file.
bool generate() {
if (IsEverythingGenerated()) return true;
std::string enum_code, struct_code, exports_code, code;
generateEnums(&enum_code, &exports_code);
generateStructs(&struct_code, &exports_code);
code = code + "// " + FlatBuffersGeneratedWarning();
// Generate code for all the namespace declarations.
GenNamespaces(&code, &exports_code);
// Output the main declaration code from above.
code += enum_code;
code += struct_code;
if (!exports_code.empty() && !parser_.opts.skip_js_exports) {
code += "// Exports for Node.js and RequireJS\n";
code += exports_code;
}
return SaveFile(GeneratedFileName(path_, file_name_).c_str(), code, false);
}
private:
// Generate code for all enums.
void generateEnums(std::string *enum_code_ptr,
std::string *exports_code_ptr) {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
auto &enum_def = **it;
GenEnum(enum_def, enum_code_ptr, exports_code_ptr);
}
}
// Generate code for all structs.
void generateStructs(std::string *decl_code_ptr,
std::string *exports_code_ptr) {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
auto &struct_def = **it;
GenStruct(parser_, struct_def, decl_code_ptr, exports_code_ptr);
}
}
void GenNamespaces(std::string *code_ptr, std::string *exports_ptr) {
std::set<std::string> namespaces;
for (auto it = parser.namespaces_.begin();
it != parser.namespaces_.end(); ++it) {
for (auto it = parser_.namespaces_.begin();
it != parser_.namespaces_.end(); ++it) {
std::string namespace_so_far;
// Gather all parent namespaces for this namespace
@@ -52,7 +110,7 @@ static void GenNamespaces(const Parser &parser, std::string *code_ptr,
std::string &exports = *exports_ptr;
for (auto it = sorted_namespaces.begin();
it != sorted_namespaces.end(); it++) {
code += "/**\n * @const\n*/\n";
code += "/**\n * @const\n * @namespace\n */\n";
if (it->find('.') == std::string::npos) {
code += "var ";
exports += "this." + *it + " = " + *it + ";\n";
@@ -61,22 +119,6 @@ static void GenNamespaces(const Parser &parser, std::string *code_ptr,
}
}
// Ensure that a type is prefixed with its namespace whenever it is used
// outside of its namespace.
static std::string WrapInNameSpace(const Namespace *ns,
const std::string &name) {
std::string qualified_name;
for (auto it = ns->components.begin();
it != ns->components.end(); ++it) {
qualified_name += *it + ".";
}
return qualified_name + name;
}
static std::string WrapInNameSpace(const Definition &def) {
return WrapInNameSpace(def.defined_namespace, def.name);
}
// Generate a documentation comment, if available.
static void GenDocComment(const std::vector<std::string> &dc,
std::string *code_ptr,
@@ -122,7 +164,7 @@ static void GenDocComment(std::string *code_ptr,
}
// Generate an enum declaration and an enum string lookup table.
static void GenEnum(EnumDef &enum_def, std::string *code_ptr,
void GenEnum(EnumDef &enum_def, std::string *code_ptr,
std::string *exports_ptr) {
if (enum_def.generated) return;
std::string &code = *code_ptr;
@@ -169,7 +211,7 @@ static std::string GenType(const Type &type) {
}
}
static std::string GenGetter(const Type &type, const std::string &arguments) {
std::string GenGetter(const Type &type, const std::string &arguments) {
switch (type.base_type) {
case BASE_TYPE_STRING: return "this.bb.__string" + arguments;
case BASE_TYPE_STRUCT: return "this.bb.__struct" + arguments;
@@ -189,7 +231,7 @@ static std::string GenGetter(const Type &type, const std::string &arguments) {
}
}
static std::string GenDefaultValue(const Value &value) {
std::string GenDefaultValue(const Value &value, const std::string &context) {
if (value.type.enum_def) {
if (auto val = value.type.enum_def->ReverseLookup(
atoi(value.constant.c_str()), false)) {
@@ -205,20 +247,18 @@ static std::string GenDefaultValue(const Value &value) {
return "null";
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG:
if (value.constant != "0") {
int64_t constant = StringToInt(value.constant.c_str());
return "new flatbuffers.Long(" + NumToString((int32_t)constant) +
", " + NumToString((int32_t)(constant >> 32)) + ")";
}
return "flatbuffers.Long.ZERO";
case BASE_TYPE_ULONG: {
int64_t constant = StringToInt(value.constant.c_str());
return context + ".createLong(" + NumToString((int32_t)constant) +
", " + NumToString((int32_t)(constant >> 32)) + ")";
}
default:
return value.constant;
}
}
static std::string GenTypeName(const Type &type, bool input) {
std::string GenTypeName(const Type &type, bool input) {
if (!input) {
if (type.base_type == BASE_TYPE_STRING) {
return "string|Uint8Array";
@@ -270,7 +310,7 @@ static std::string MaybeScale(T value) {
return value != 1 ? " * " + NumToString(value) : "";
}
static void GenStructArgs(const StructDef &struct_def,
void GenStructArgs(const StructDef &struct_def,
std::string *annotations,
std::string *arguments,
const std::string &nameprefix) {
@@ -321,8 +361,7 @@ static void GenStructBody(const StructDef &struct_def,
}
// Generate an accessor struct with constructor for a flatbuffers struct.
static void GenStruct(const Parser &parser, StructDef &struct_def,
std::string *code_ptr, std::string *exports_ptr) {
void GenStruct(const Parser &parser, StructDef &struct_def, std::string *code_ptr, std::string *exports_ptr) {
if (struct_def.generated) return;
std::string &code = *code_ptr;
std::string &exports = *exports_ptr;
@@ -376,13 +415,13 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
code += "};\n\n";
// Generate the identifier check method
if (parser.root_struct_def_ == &struct_def &&
!parser.file_identifier_.empty()) {
if (parser_.root_struct_def_ == &struct_def &&
!parser_.file_identifier_.empty()) {
GenDocComment(code_ptr,
"@param {flatbuffers.ByteBuffer} bb\n"
"@returns {boolean}");
code += object_name + ".bufferHasIdentifier = function(bb) {\n";
code += " return bb.__has_identifier('" + parser.file_identifier_;
code += " return bb.__has_identifier('" + parser_.file_identifier_;
code += "');\n};\n\n";
}
}
@@ -417,7 +456,7 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
index += ", optionalEncoding";
}
code += offset_prefix + GenGetter(field.value.type,
"(" + index + ")") + " : " + GenDefaultValue(field.value);
"(" + index + ")") + " : " + GenDefaultValue(field.value, "this.bb");
code += ";\n";
}
}
@@ -485,7 +524,7 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
code += "false";
} else if (field.value.type.element == BASE_TYPE_LONG ||
field.value.type.element == BASE_TYPE_ULONG) {
code += "flatbuffers.Long.ZERO";
code += "this.bb.createLong(0, 0)";
} else if (IsScalar(field.value.type.element)) {
code += "0";
} else {
@@ -511,12 +550,40 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
}
code += "};\n\n";
// Emit a length helper
// Adds the mutable scalar value to the output
if (IsScalar(field.value.type.base_type) && parser.opts.mutable_buffer) {
std::string annotations = "@param {" + GenTypeName(field.value.type, true) + "} value\n";
GenDocComment(code_ptr, annotations +
"@returns {boolean}");
code += object_name + ".prototype.mutate_" + field.name + " = function(value) {\n";
code += " var offset = this.bb.__offset(this.bb_pos, " + NumToString(field.value.offset) + ")\n\n";
code += " if (offset === 0) {\n";
code += " return false;\n";
code += " }\n\n";
code += " this.bb.write" + MakeCamel(GenType(field.value.type)) + "(this.bb_pos + offset, value);\n";
code += " return true;\n";
code += "}\n\n";
}
// Emit vector helpers
if (field.value.type.base_type == BASE_TYPE_VECTOR) {
// Emit a length helper
GenDocComment(code_ptr, "@returns {number}");
code += object_name + ".prototype." + MakeCamel(field.name, false);
code += "Length = function() {\n" + offset_prefix;
code += "this.bb.__vector_len(this.bb_pos + offset) : 0;\n};\n\n";
// For scalar types, emit a typed array helper
auto vectorType = field.value.type.VectorType();
if (IsScalar(vectorType.base_type)) {
GenDocComment(code_ptr, "@returns {" + GenType(vectorType) + "Array}");
code += object_name + ".prototype." + MakeCamel(field.name, false);
code += "Array = function() {\n" + offset_prefix;
code += "new " + GenType(vectorType) + "Array(this.bb.bytes().buffer, "
"this.bb.__vector(this.bb_pos + offset), "
"this.bb.__vector_len(this.bb_pos + offset)) : null;\n};\n\n";
}
}
}
@@ -570,7 +637,7 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
if (field.value.type.base_type == BASE_TYPE_BOOL) {
code += "+";
}
code += GenDefaultValue(field.value);
code += GenDefaultValue(field.value, "builder");
}
code += ");\n};\n\n";
@@ -633,78 +700,28 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
code += "};\n\n";
// Generate the method to complete buffer construction
if (parser.root_struct_def_ == &struct_def) {
if (parser_.root_struct_def_ == &struct_def) {
GenDocComment(code_ptr,
"@param {flatbuffers.Builder} builder\n"
"@param {flatbuffers.Offset} offset");
code += object_name + ".finish" + struct_def.name + "Buffer";
code += " = function(builder, offset) {\n";
code += " builder.finish(offset";
if (!parser.file_identifier_.empty()) {
code += ", '" + parser.file_identifier_ + "'";
if (!parser_.file_identifier_.empty()) {
code += ", '" + parser_.file_identifier_ + "'";
}
code += ");\n";
code += "};\n\n";
}
}
}
};
} // namespace js
// Iterate through all definitions we haven't generate code for (enums, structs,
// and tables) and output them to a single file.
std::string GenerateJS(const Parser &parser) {
using namespace js;
// Generate code for all the enum declarations.
std::string enum_code, exports_code;
for (auto it = parser.enums_.vec.begin();
it != parser.enums_.vec.end(); ++it) {
GenEnum(**it, &enum_code, &exports_code);
}
// Generate code for all structs, then all tables.
std::string decl_code;
for (auto it = parser.structs_.vec.begin();
it != parser.structs_.vec.end(); ++it) {
GenStruct(parser, **it, &decl_code, &exports_code);
}
// Only output file-level code if there were any declarations.
if (enum_code.length() || decl_code.length()) {
std::string code;
code = "// automatically generated by the FlatBuffers compiler,"
" do not modify\n\n";
// Generate code for all the namespace declarations.
GenNamespaces(parser, &code, &exports_code);
// Output the main declaration code from above.
code += enum_code;
code += decl_code;
if (!exports_code.empty() && !parser.opts.skip_js_exports) {
code += "// Exports for Node.js and RequireJS\n";
code += exports_code;
}
return code;
}
return std::string();
}
static std::string GeneratedFileName(const std::string &path,
const std::string &file_name) {
return path + file_name + "_generated.js";
}
bool GenerateJS(const Parser &parser,
const std::string &path,
bool GenerateJS(const Parser &parser, const std::string &path,
const std::string &file_name) {
auto code = GenerateJS(parser);
return !code.length() ||
SaveFile(GeneratedFileName(path, file_name).c_str(), code, false);
js::JsGenerator generator(parser, path, file_name);
return generator.generate();
}
std::string JSMakeRule(const Parser &parser,

View File

@@ -21,56 +21,78 @@
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include "flatbuffers/code_generators.h"
namespace flatbuffers {
namespace php {
static std::string GenGetter(const Type &type);
static std::string GenDefaultValue(const Value &value);
static std::string GenMethod(const FieldDef &field);
static void GenStructBuilder(const StructDef &struct_def,
std::string *code_ptr);
static std::string GenTypeBasic(const Type &type);
static std::string GenTypeGet(const Type &type);
// Ensure that a type is prefixed with its namespace whenever it is used
// outside of its namespace.
static std::string WrapInNameSpace(const Namespace *ns,
const std::string &name) {
std::string qualified_name = "\\";
for (auto it = ns->components.begin();
it != ns->components.end(); ++it) {
qualified_name += *it + "\\";
}
return qualified_name + name;
}
static std::string WrapInNameSpace(const Definition &def) {
return WrapInNameSpace(def.defined_namespace, def.name);
}
// Hardcode spaces per indentation.
const std::string Indent = " ";
// Begin by declaring namespace and imports.
static void BeginFile(const std::string name_space_name,
const bool needs_imports,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "<?php\n";
code += "// automatically generated, do not modify\n\n";
code += "namespace " + name_space_name + ";\n\n";
if (needs_imports) {
code += "use \\Google\\FlatBuffers\\Struct;\n";
code += "use \\Google\\FlatBuffers\\Table;\n";
code += "use \\Google\\FlatBuffers\\ByteBuffer;\n";
code += "use \\Google\\FlatBuffers\\FlatBufferBuilder;\n";
code += "\n";
class PhpGenerator : public BaseGenerator {
public:
PhpGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "\\", "\\"){};
bool generate() {
if (!generateEnums()) return false;
if (!generateStructs()) return false;
return true;
}
}
private:
bool generateEnums() {
for (auto it = parser_.enums_.vec.begin();
it != parser_.enums_.vec.end(); ++it) {
auto &enum_def = **it;
std::string enumcode;
GenEnum(enum_def, &enumcode);
if (!SaveType(enum_def, enumcode, false)) return false;
}
return true;
}
bool generateStructs() {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
auto &struct_def = **it;
std::string declcode;
GenStruct(struct_def, &declcode);
if (!SaveType(struct_def, declcode, true)) return false;
}
return true;
}
// Begin by declaring namespace and imports.
void BeginFile(const std::string name_space_name,
const bool needs_imports, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "<?php\n";
code = code + "// " + FlatBuffersGeneratedWarning();
code += "namespace " + name_space_name + ";\n\n";
if (needs_imports) {
code += "use \\Google\\FlatBuffers\\Struct;\n";
code += "use \\Google\\FlatBuffers\\Table;\n";
code += "use \\Google\\FlatBuffers\\ByteBuffer;\n";
code += "use \\Google\\FlatBuffers\\FlatBufferBuilder;\n";
code += "\n";
}
}
// Save out the generated code for a Php Table type.
bool SaveType(const Definition &def, const std::string &classcode,
bool needs_imports) {
if (!classcode.length()) return true;
std::string code = "";
BeginFile(FullNamespace("\\", *def.defined_namespace),
needs_imports, &code);
code += classcode;
std::string filename = NamespaceDir(*def.defined_namespace) +
kPathSeparator + def.name + ".php";
return SaveFile(filename.c_str(), code, false);
}
// Begin a class declaration.
static void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
@@ -165,6 +187,22 @@ namespace php {
code += Indent + "}\n\n";
}
// Get a [ubyte] vector as a byte array.
static void GetUByte(const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @return string\n";
code += Indent + " */\n";
code += Indent + "public function get";
code += MakeCamel(field.name) + "Bytes()\n";
code += Indent + "{\n";
code += Indent + Indent + "return $this->__vector_as_bytes(";
code += NumToString(field.value.offset) + ");\n";
code += Indent + "}\n\n";
}
// Get the value of a struct's scalar.
static void GetScalarFieldOfStruct(const FieldDef &field,
std::string *code_ptr) {
@@ -190,8 +228,7 @@ namespace php {
}
// Get the value of a table's scalar.
static void GetScalarFieldOfTable(const FieldDef &field,
std::string *code_ptr) {
void GetScalarFieldOfTable(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
std::string getter = GenGetter(field.value.type);
@@ -214,8 +251,7 @@ namespace php {
// Get a struct by initializing an existing struct.
// Specific to Struct.
static void GetStructFieldOfStruct(const FieldDef &field,
std::string *code_ptr) {
void GetStructFieldOfStruct(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
code += Indent + "/**\n";
@@ -234,8 +270,7 @@ namespace php {
// Get a struct by initializing an existing struct.
// Specific to Table.
static void GetStructFieldOfTable(const FieldDef &field,
std::string *code_ptr) {
void GetStructFieldOfTable(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
code += Indent + "public function get";
@@ -250,7 +285,7 @@ namespace php {
");\n";
code += Indent + Indent;
code += "return $o != 0 ? $obj->init(";
if (field.value.type.struct_def->fixed)
if (field.value.type.struct_def->fixed)
{
code += "$o + $this->bb_pos, $this->bb) : ";
} else {
@@ -261,8 +296,7 @@ namespace php {
}
// Get the value of a string.
static void GetStringField(const FieldDef &field,
std::string *code_ptr) {
void GetStringField(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
code += Indent + "public function get";
code += MakeCamel(field.name);
@@ -279,8 +313,7 @@ namespace php {
}
// Get the value of a union from an object.
static void GetUnionField(const FieldDef &field,
std::string *code_ptr) {
void GetUnionField(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
code += Indent + "/**\n";
@@ -299,9 +332,8 @@ namespace php {
}
// Get the value of a vector's struct member.
static void GetMemberOfVectorOfStruct(const StructDef &struct_def,
const FieldDef &field,
std::string *code_ptr) {
void GetMemberOfVectorOfStruct(const StructDef &struct_def,
const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
@@ -363,7 +395,7 @@ namespace php {
// Get the value of a vector's non-struct member. Uses a named return
// argument to conveniently set the zero value for the result.
static void GetMemberOfVectorOfNonStruct(const FieldDef &field,
void GetMemberOfVectorOfNonStruct(const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
@@ -604,9 +636,7 @@ namespace php {
}
// Get the offset of the end of a table.
static void GetEndOffsetOnTable(const Parser &parser,
const StructDef &struct_def,
std::string *code_ptr) {
void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
@@ -633,7 +663,7 @@ namespace php {
code += Indent + Indent + "return $o;\n";
code += Indent + "}\n";
if (parser.root_struct_def_ == &struct_def) {
if (parser_.root_struct_def_ == &struct_def) {
code += "\n";
code += Indent + "public static function finish";
code += struct_def.name;
@@ -641,16 +671,15 @@ namespace php {
code += Indent + "{\n";
code += Indent + Indent + "$builder->finish($offset";
if (parser.file_identifier_.length())
code += ", \"" + parser.file_identifier_ + "\"";
if (parser_.file_identifier_.length())
code += ", \"" + parser_.file_identifier_ + "\"";
code += ");\n";
code += Indent + "}\n";
}
}
// Generate a struct field, conditioned on its child type(s).
static void GenStructAccessor(const StructDef &struct_def,
const FieldDef &field,
void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
GenComment(field.doc_comment, code_ptr, nullptr);
@@ -690,13 +719,14 @@ namespace php {
}
if (field.value.type.base_type == BASE_TYPE_VECTOR) {
GetVectorLen(field, code_ptr);
if (field.value.type.element == BASE_TYPE_UCHAR) {
GetUByte(field, code_ptr);
}
}
}
// Generate table constructors, conditioned on its members' types.
static void GenTableBuilders(const Parser &parser,
const StructDef &struct_def,
std::string *code_ptr) {
void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
GetStartOfTable(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
@@ -723,11 +753,11 @@ namespace php {
}
}
GetEndOffsetOnTable(parser, struct_def, code_ptr);
GetEndOffsetOnTable(struct_def, code_ptr);
}
// Generate struct or table methods.
static void GenStruct(const Parser &parser, const StructDef &struct_def,
void GenStruct(const StructDef &struct_def,
std::string *code_ptr) {
if (struct_def.generated) return;
@@ -742,13 +772,13 @@ namespace php {
std::string &code = *code_ptr;
if (!struct_def.fixed) {
if (parser.file_identifier_.length()) {
if (parser_.file_identifier_.length()) {
// Return the identifier
code += Indent + "public static function " + struct_def.name;
code += "Identifier()\n";
code += Indent + "{\n";
code += Indent + Indent + "return \"";
code += parser.file_identifier_ + "\";\n";
code += parser_.file_identifier_ + "\";\n";
code += Indent + "}\n\n";
// Check if a buffer has the identifier.
@@ -761,12 +791,12 @@ namespace php {
code += Indent + "}\n\n";
}
if (parser.file_extension_.length()) {
if (parser_.file_extension_.length()) {
// Return the extension
code += Indent + "public static function " + struct_def.name;
code += "Extension()\n";
code += Indent + "{\n";
code += Indent + Indent + "return \"" + parser.file_extension_;
code += Indent + Indent + "return \"" + parser_.file_extension_;
code += "\";\n";
code += Indent + "}\n\n";
}
@@ -789,7 +819,7 @@ namespace php {
GenStructBuilder(struct_def, code_ptr);
} else {
// Create a set of functions that allow table construction.
GenTableBuilders(parser, struct_def, code_ptr);
GenTableBuilders(struct_def, code_ptr);
}
EndClass(code_ptr);
}
@@ -847,35 +877,6 @@ namespace php {
: (IsStruct(field.value.type) ? "Struct" : "Offset");
}
// Save out the generated code for a Php Table type.
static bool SaveType(const Parser &parser, const Definition &def,
const std::string &classcode, const std::string &path,
bool needs_imports) {
if (!classcode.length()) return true;
std::string namespace_name;
std::string namespace_dir = path;
auto &namespaces = parser.namespaces_.back()->components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
if (namespace_name.length()) {
namespace_name += "\\";
namespace_dir += kPathSeparator;
}
namespace_name += *it;
namespace_dir += *it;
EnsureDirExists(namespace_dir.c_str());
}
std::string code = "";
BeginFile(namespace_name, needs_imports, &code);
code += classcode;
std::string filename = namespace_dir + kPathSeparator + def.name + ".php";
return SaveFile(filename.c_str(), code, false);
}
static std::string GenTypeBasic(const Type &type) {
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
@@ -886,7 +887,7 @@ namespace php {
return ctypename[type.base_type];
}
static std::string GenDefaultValue(const Value &value) {
std::string GenDefaultValue(const Value &value) {
if (value.type.enum_def) {
if (auto val = value.type.enum_def->ReverseLookup(
atoi(value.constant.c_str()), false)) {
@@ -954,30 +955,13 @@ namespace php {
code += Indent + Indent + "return $builder->offset();\n";
code += Indent + "}\n";
}
};
} // namespace php
} // namespace php
bool GeneratePhp(const Parser &parser,
const std::string &path,
const std::string & /*file_name*/) {
for (auto it = parser.enums_.vec.begin();
it != parser.enums_.vec.end(); ++it) {
std::string enumcode;
php::GenEnum(**it, &enumcode);
if (!php::SaveType(parser, **it, enumcode, path, false))
return false;
bool GeneratePhp(const Parser &parser, const std::string &path,
const std::string &file_name) {
php::PhpGenerator generator(parser, path, file_name);
return generator.generate();
}
for (auto it = parser.structs_.vec.begin();
it != parser.structs_.vec.end(); ++it) {
std::string declcode;
php::GenStruct(parser, **it, &declcode);
if (!php::SaveType(parser, **it, declcode, path, true))
return false;
}
return true;
}
} // namespace flatbuffers
} // namespace flatbuffers

View File

@@ -21,6 +21,7 @@
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include "flatbuffers/code_generators.h"
namespace flatbuffers {
namespace python {
@@ -48,18 +49,6 @@ std::string OffsetPrefix(const FieldDef &field) {
"))\n" + Indent + Indent + "if o != 0:\n";
}
// Begin by declaring namespace and imports.
static void BeginFile(const std::string name_space_name,
const bool needs_imports,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "# automatically generated, do not modify\n\n";
code += "# namespace: " + name_space_name + "\n\n";
if (needs_imports) {
code += "import flatbuffers\n\n";
}
}
// Begin a class declaration.
static void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
@@ -105,7 +94,7 @@ static void NewRootTypeFromBuffer(const StructDef &struct_def,
code += Indent + Indent + "x = " + struct_def.name + "()\n";
code += Indent + Indent + "x.Init(buf, n + offset)\n";
code += Indent + Indent + "return x\n";
code += "\n\n";
code += "\n";
}
// Initialize an existing object with other data, to avoid an allocation.
@@ -489,13 +478,12 @@ static void GenTableBuilders(const StructDef &struct_def,
// Generate struct or table methods.
static void GenStruct(const StructDef &struct_def,
std::string *code_ptr,
StructDef *root_struct_def) {
std::string *code_ptr) {
if (struct_def.generated) return;
GenComment(struct_def.doc_comment, code_ptr, nullptr, "# ");
BeginClass(struct_def, code_ptr);
if (&struct_def == root_struct_def) {
if (!struct_def.fixed) {
// Generate a special accessor for the table that has been declared as
// the root type.
NewRootTypeFromBuffer(struct_def, code_ptr);
@@ -557,37 +545,6 @@ static std::string GenMethod(const FieldDef &field) {
: (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative");
}
// Save out the generated code for a Python Table type.
static bool SaveType(const Parser &parser, const Definition &def,
const std::string &classcode, const std::string &path,
bool needs_imports) {
if (!classcode.length()) return true;
std::string namespace_name;
std::string namespace_dir = path;
auto &namespaces = parser.namespaces_.back()->components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
if (namespace_name.length()) {
namespace_name += ".";
namespace_dir += kPathSeparator;
}
namespace_name = *it;
namespace_dir += *it;
EnsureDirExists(namespace_dir.c_str());
std::string init_py_filename = namespace_dir + "/__init__.py";
SaveFile(init_py_filename.c_str(), "", false);
}
std::string code = "";
BeginFile(namespace_name, needs_imports, &code);
code += classcode;
std::string filename = namespace_dir + kPathSeparator + def.name + ".py";
return SaveFile(filename.c_str(), code, false);
}
static std::string GenTypeBasic(const Type &type) {
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
@@ -634,28 +591,81 @@ static void GenStructBuilder(const StructDef &struct_def,
EndBuilderBody(code_ptr);
}
class PythonGenerator : public BaseGenerator {
public:
PythonGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "" /* not used */,
"" /* not used */){};
bool generate() {
if (!generateEnums()) return false;
if (!generateStructs()) return false;
return true;
}
private:
bool generateEnums() {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
auto &enum_def = **it;
std::string enumcode;
GenEnum(enum_def, &enumcode);
if (!SaveType(enum_def, enumcode, false)) return false;
}
return true;
}
bool generateStructs() {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
auto &struct_def = **it;
std::string declcode;
GenStruct(struct_def, &declcode);
if (!SaveType(struct_def, declcode, true)) return false;
}
return true;
}
// Begin by declaring namespace and imports.
void BeginFile(const std::string name_space_name, const bool needs_imports,
std::string *code_ptr) {
std::string &code = *code_ptr;
code = code + "# " + FlatBuffersGeneratedWarning();
code += "# namespace: " + name_space_name + "\n\n";
if (needs_imports) {
code += "import flatbuffers\n\n";
}
}
// Save out the generated code for a Python Table type.
bool SaveType(const Definition &def, const std::string &classcode,
bool needs_imports) {
if (!classcode.length()) return true;
std::string namespace_dir = path_;
auto &namespaces = parser_.namespaces_.back()->components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
if (it != namespaces.begin()) namespace_dir += kPathSeparator;
namespace_dir += *it;
std::string init_py_filename = namespace_dir + "/__init__.py";
SaveFile(init_py_filename.c_str(), "", false);
}
std::string code = "";
BeginFile(LastNamespacePart(*def.defined_namespace), needs_imports, &code);
code += classcode;
std::string filename = NamespaceDir(*def.defined_namespace) +
kPathSeparator + def.name + ".py";
return SaveFile(filename.c_str(), code, false);
}
};
} // namespace python
bool GeneratePython(const Parser &parser,
const std::string &path,
const std::string & /*file_name*/) {
for (auto it = parser.enums_.vec.begin();
it != parser.enums_.vec.end(); ++it) {
std::string enumcode;
python::GenEnum(**it, &enumcode);
if (!python::SaveType(parser, **it, enumcode, path, false))
return false;
}
for (auto it = parser.structs_.vec.begin();
it != parser.structs_.vec.end(); ++it) {
std::string declcode;
python::GenStruct(**it, &declcode, parser.root_struct_def_);
if (!python::SaveType(parser, **it, declcode, path, true))
return false;
}
return true;
bool GeneratePython(const Parser &parser, const std::string &path,
const std::string &file_name) {
python::PythonGenerator generator(parser, path, file_name);
return generator.generate();
}
} // namespace flatbuffers

View File

@@ -93,7 +93,7 @@ template<typename T> void PrintVector(const Vector<T> &v, Type type,
text += "]";
}
static void EscapeString(const String &s, std::string *_text) {
static void EscapeString(const String &s, std::string *_text, const IDLOptions& opts) {
std::string &text = *_text;
text += "\"";
for (uoffset_t i = 0; i < s.size(); i++) {
@@ -113,17 +113,32 @@ static void EscapeString(const String &s, std::string *_text) {
// Not printable ASCII data. Let's see if it's valid UTF-8 first:
const char *utf8 = s.c_str() + i;
int ucc = FromUTF8(&utf8);
if (ucc >= 0x80 && ucc <= 0xFFFF) {
// Parses as Unicode within JSON's \uXXXX range, so use that.
text += "\\u";
text += IntToStringHex(ucc, 4);
if (ucc < 0) {
if (opts.allow_non_utf8) {
text += "\\x";
text += IntToStringHex(static_cast<uint8_t>(c), 2);
} else {
// We previously checked for non-UTF-8 and returned a parse error,
// so we shouldn't reach here.
assert(0);
}
} else {
if (ucc <= 0xFFFF) {
// Parses as Unicode within JSON's \uXXXX range, so use that.
text += "\\u";
text += IntToStringHex(ucc, 4);
} else if (ucc <= 0x10FFFF) {
// Encode Unicode SMP values to a surrogate pair using two \u escapes.
uint32_t base = ucc - 0x10000;
uint16_t highSurrogate = (base >> 10) + 0xD800;
uint16_t lowSurrogate = (base & 0x03FF) + 0xDC00;
text += "\\u";
text += IntToStringHex(highSurrogate, 4);
text += "\\u";
text += IntToStringHex(lowSurrogate, 4);
}
// Skip past characters recognized.
i = static_cast<uoffset_t>(utf8 - s.c_str() - 1);
} else {
// It's either unprintable ASCII, arbitrary binary, or Unicode data
// that doesn't fit \uXXXX, so use \xXX escape code instead.
text += "\\x";
text += IntToStringHex(static_cast<uint8_t>(c), 2);
}
}
break;
@@ -157,7 +172,7 @@ template<> void Print<const void *>(const void *val,
_text);
break;
case BASE_TYPE_STRING: {
EscapeString(*reinterpret_cast<const String *>(val), _text);
EscapeString(*reinterpret_cast<const String *>(val), _text, opts);
break;
}
case BASE_TYPE_VECTOR:

View File

@@ -17,6 +17,14 @@
#include <algorithm>
#include <list>
#ifdef _WIN32
#if !defined(_USE_MATH_DEFINES)
#define _USE_MATH_DEFINES // For M_PI.
#endif // !defined(_USE_MATH_DEFINES)
#endif // _WIN32
#include <math.h>
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
@@ -53,6 +61,17 @@ static_assert(BASE_TYPE_UNION ==
#define NEXT() ECHECK(Next())
#define EXPECT(tok) ECHECK(Expect(tok))
static bool ValidateUTF8(const std::string &str) {
const char *s = &str[0];
const char * const sEnd = s + str.length();
while (s < sEnd) {
if (FromUTF8(&s) < 0) {
return false;
}
}
return true;
}
CheckedError Parser::Error(const std::string &msg) {
error_ = file_being_parsed_.length() ? AbsolutePath(file_being_parsed_) : "";
#ifdef _WIN32
@@ -69,13 +88,16 @@ inline CheckedError NoError() { return CheckedError(false); }
// Ensure that integer values we parse fit inside the declared integer type.
CheckedError Parser::CheckBitsFit(int64_t val, size_t bits) {
// Bits we allow to be used.
auto mask = static_cast<int64_t>((1ull << bits) - 1);
if (bits < 64 &&
(val & ~mask) != 0 && // Positive or unsigned.
(val | mask) != -1) // Negative.
return Error("constant does not fit in a " + NumToString(bits) +
"-bit field");
// Left-shifting a 64-bit value by 64 bits or more is undefined
// behavior (C99 6.5.7), so check *before* we shift.
if (bits < 64) {
// Bits we allow to be used.
auto mask = static_cast<int64_t>((1ull << bits) - 1);
if ((val & ~mask) != 0 && // Positive or unsigned.
(val | mask) != -1) // Negative.
return Error("constant does not fit in a " + NumToString(bits) +
"-bit field");
}
return NoError();
}
@@ -152,7 +174,8 @@ std::string Namespace::GetFullyQualifiedName(const std::string &name,
TD(FileExtension, 268, "file_extension") \
TD(Include, 269, "include") \
TD(Attribute, 270, "attribute") \
TD(Null, 271, "null")
TD(Null, 271, "null") \
TD(Service, 272, "rpc_service")
#ifdef __GNUC__
__extension__ // Stop GCC complaining about trailing comma with -Wpendantic.
#endif
@@ -204,11 +227,17 @@ CheckedError Parser::ParseHexNum(int nibbles, int64_t *val) {
CheckedError Parser::SkipByteOrderMark() {
if (static_cast<unsigned char>(*cursor_) != 0xef) return NoError();
cursor_++;
if (static_cast<unsigned char>(*cursor_++) != 0xbb) return Error("invalid utf-8 byte order mark");
if (static_cast<unsigned char>(*cursor_++) != 0xbf) return Error("invalid utf-8 byte order mark");
if (static_cast<unsigned char>(*cursor_) != 0xbb) return Error("invalid utf-8 byte order mark");
cursor_++;
if (static_cast<unsigned char>(*cursor_) != 0xbf) return Error("invalid utf-8 byte order mark");
cursor_++;
return NoError();
}
bool IsIdentifierStart(char c) {
return isalpha(static_cast<unsigned char>(c)) || c == '_';
}
CheckedError Parser::Next() {
doc_comment_.clear();
bool seen_newline = false;
@@ -226,12 +255,19 @@ CheckedError Parser::Next() {
if(!isdigit(static_cast<const unsigned char>(*cursor_))) return NoError();
return Error("floating point constant can\'t start with \".\"");
case '\"':
case '\'':
case '\'': {
int unicode_high_surrogate = -1;
while (*cursor_ != c) {
if (*cursor_ < ' ' && *cursor_ >= 0)
return Error("illegal character in string constant");
if (*cursor_ == '\\') {
cursor_++;
if (unicode_high_surrogate != -1 &&
*cursor_ != 'u') {
return Error(
"illegal Unicode sequence (unpaired high surrogate)");
}
switch (*cursor_) {
case 'n': attribute_ += '\n'; cursor_++; break;
case 't': attribute_ += '\t'; cursor_++; break;
@@ -253,18 +289,54 @@ CheckedError Parser::Next() {
cursor_++;
int64_t val;
ECHECK(ParseHexNum(4, &val));
ToUTF8(static_cast<int>(val), &attribute_);
if (val >= 0xD800 && val <= 0xDBFF) {
if (unicode_high_surrogate != -1) {
return Error(
"illegal Unicode sequence (multiple high surrogates)");
} else {
unicode_high_surrogate = static_cast<int>(val);
}
} else if (val >= 0xDC00 && val <= 0xDFFF) {
if (unicode_high_surrogate == -1) {
return Error(
"illegal Unicode sequence (unpaired low surrogate)");
} else {
int code_point = 0x10000 +
((unicode_high_surrogate & 0x03FF) << 10) +
(val & 0x03FF);
ToUTF8(code_point, &attribute_);
unicode_high_surrogate = -1;
}
} else {
if (unicode_high_surrogate != -1) {
return Error(
"illegal Unicode sequence (unpaired high surrogate)");
}
ToUTF8(static_cast<int>(val), &attribute_);
}
break;
}
default: return Error("unknown escape code in string constant");
}
} else { // printable chars + UTF-8 bytes
if (unicode_high_surrogate != -1) {
return Error(
"illegal Unicode sequence (unpaired high surrogate)");
}
attribute_ += *cursor_++;
}
}
if (unicode_high_surrogate != -1) {
return Error(
"illegal Unicode sequence (unpaired high surrogate)");
}
cursor_++;
if (!opts.allow_non_utf8 && !ValidateUTF8(attribute_)) {
return Error("illegal UTF-8 sequence");
}
token_ = kTokenStringConstant;
return NoError();
}
case '/':
if (*cursor_ == '/') {
const char *start = ++cursor_;
@@ -288,7 +360,7 @@ CheckedError Parser::Next() {
}
// fall thru
default:
if (isalpha(static_cast<unsigned char>(c)) || c == '_') {
if (IsIdentifierStart(c)) {
// Collect all chars of an identifier:
const char *start = cursor_ - 1;
while (isalnum(static_cast<unsigned char>(*cursor_)) ||
@@ -356,11 +428,21 @@ CheckedError Parser::Next() {
token_ = kTokenNull;
return NoError();
}
if (attribute_ == "rpc_service") {
token_ = kTokenService;
return NoError();
}
// If not, it is a user-defined identifier:
token_ = kTokenIdentifier;
return NoError();
} else if (isdigit(static_cast<unsigned char>(c)) || c == '-') {
const char *start = cursor_ - 1;
if (c == '-' && *cursor_ == '0' && (cursor_[1] == 'x' || cursor_[1] == 'X')) {
++start;
++cursor_;
attribute_.append(&c, &c + 1);
c = '0';
}
if (c == '0' && (*cursor_ == 'x' || *cursor_ == 'X')) {
cursor_++;
while (isxdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
@@ -521,9 +603,9 @@ CheckedError Parser::ParseField(StructDef &struct_def) {
FieldDef *typefield = nullptr;
if (type.base_type == BASE_TYPE_UNION) {
// For union fields, add a second auto-generated field to hold the type,
// with _type appended as the name.
ECHECK(AddField(struct_def, name + "_type", type.enum_def->underlying_type,
&typefield));
// with a special suffix.
ECHECK(AddField(struct_def, name + UnionTypeFieldSuffix(),
type.enum_def->underlying_type, &typefield));
}
FieldDef *field;
@@ -535,6 +617,10 @@ CheckedError Parser::ParseField(StructDef &struct_def) {
return Error("default values currently only supported for scalars");
ECHECK(ParseSingleValue(field->value));
}
if (IsFloat(field->value.type.base_type)) {
if (!strpbrk(field->value.constant.c_str(), ".eE"))
field->value.constant += ".0";
}
if (type.enum_def &&
IsScalar(type.base_type) &&
@@ -547,7 +633,7 @@ CheckedError Parser::ParseField(StructDef &struct_def) {
field->value.constant);
field->doc_comment = dc;
ECHECK(ParseMetaData(*field));
ECHECK(ParseMetaData(&field->attributes));
field->deprecated = field->attributes.Lookup("deprecated") != nullptr;
auto hash_name = field->attributes.Lookup("hash");
if (hash_name) {
@@ -620,17 +706,45 @@ CheckedError Parser::ParseField(StructDef &struct_def) {
}
CheckedError Parser::ParseAnyValue(Value &val, FieldDef *field,
size_t parent_fieldn) {
size_t parent_fieldn,
const StructDef *parent_struct_def) {
switch (val.type.base_type) {
case BASE_TYPE_UNION: {
assert(field);
std::string constant;
if (!parent_fieldn ||
field_stack_.back().second->value.type.base_type != BASE_TYPE_UTYPE)
return Error("missing type field before this union value: " +
field->name);
field_stack_.back().second->value.type.base_type != BASE_TYPE_UTYPE) {
// We haven't seen the type field yet. Sadly a lot of JSON writers
// output these in alphabetical order, meaning it comes after this
// value. So we scan past the value to find it, then come back here.
auto type_name = field->name + UnionTypeFieldSuffix();
assert(parent_struct_def);
auto type_field = parent_struct_def->fields.Lookup(type_name);
assert(type_field); // Guaranteed by ParseField().
// Remember where we are in the source file, so we can come back here.
auto backup = *static_cast<ParserState *>(this);
ECHECK(SkipAnyJsonValue()); // The table.
EXPECT(',');
auto next_name = attribute_;
if (Is(kTokenStringConstant)) {
NEXT();
} else {
EXPECT(kTokenIdentifier);
}
if (next_name != type_name)
return Error("missing type field after this union value: " +
type_name);
EXPECT(':');
Value type_val = type_field->value;
ECHECK(ParseAnyValue(type_val, type_field, 0, nullptr));
constant = type_val.constant;
// Got the information we needed, now rewind:
*static_cast<ParserState *>(this) = backup;
} else {
constant = field_stack_.back().first.constant;
}
uint8_t enum_idx;
ECHECK(atot(field_stack_.back().first.constant.c_str(), *this,
&enum_idx));
ECHECK(atot(constant.c_str(), *this, &enum_idx));
auto enum_val = val.type.enum_def->ReverseLookup(enum_idx);
if (!enum_val) return Error("illegal type id for: " + field->name);
ECHECK(ParseTable(*enum_val->struct_def, &val.constant, nullptr));
@@ -705,7 +819,7 @@ CheckedError Parser::ParseTable(const StructDef &struct_def, std::string *value,
NEXT(); // Ignore this field.
} else {
Value val = field->value;
ECHECK(ParseAnyValue(val, field, fieldn));
ECHECK(ParseAnyValue(val, field, fieldn, &struct_def));
size_t i = field_stack_.size();
// Hardcoded insertion-sort with error-check.
// If fields are specified in order, then this loop exits immediately.
@@ -804,7 +918,7 @@ CheckedError Parser::ParseVector(const Type &type, uoffset_t *ovalue) {
if ((!opts.strict_json || !count) && Is(']')) { NEXT(); break; }
Value val;
val.type = type;
ECHECK(ParseAnyValue(val, nullptr, 0));
ECHECK(ParseAnyValue(val, nullptr, 0, nullptr));
field_stack_.push_back(std::make_pair(val, nullptr));
count++;
if (Is(']')) { NEXT(); break; }
@@ -837,7 +951,7 @@ CheckedError Parser::ParseVector(const Type &type, uoffset_t *ovalue) {
return NoError();
}
CheckedError Parser::ParseMetaData(Definition &def) {
CheckedError Parser::ParseMetaData(SymbolTable<Value> *attributes) {
if (Is('(')) {
NEXT();
for (;;) {
@@ -847,7 +961,7 @@ CheckedError Parser::ParseMetaData(Definition &def) {
return Error("user define attributes must be declared before use: " +
name);
auto e = new Value();
def.attributes.Add(name, e);
attributes->Add(name, e);
if (Is(':')) {
NEXT();
ECHECK(ParseSingleValue(*e));
@@ -880,7 +994,7 @@ CheckedError Parser::TryTypedValue(int dtoken, bool check, Value &e,
return NoError();
}
CheckedError Parser::ParseIntegerFromString(Type &type, int64_t *result) {
CheckedError Parser::ParseEnumFromString(Type &type, int64_t *result) {
*result = 0;
// Parse one or more enum identifiers, separated by spaces.
const char *next = attribute_.c_str();
@@ -946,14 +1060,49 @@ CheckedError Parser::ParseHash(Value &e, FieldDef* field) {
}
CheckedError Parser::ParseSingleValue(Value &e) {
// First check if this could be a string/identifier enum value:
if (e.type.base_type != BASE_TYPE_STRING &&
// First see if this could be a conversion function:
if (token_ == kTokenIdentifier && *cursor_ == '(') {
auto functionname = attribute_;
NEXT();
EXPECT('(');
ECHECK(ParseSingleValue(e));
EXPECT(')');
#define FLATBUFFERS_FN_DOUBLE(name, op) \
if (functionname == name) { \
auto x = strtod(e.constant.c_str(), nullptr); \
e.constant = NumToString(op); \
}
FLATBUFFERS_FN_DOUBLE("deg", x / M_PI * 180);
FLATBUFFERS_FN_DOUBLE("rad", x * M_PI / 180);
FLATBUFFERS_FN_DOUBLE("sin", sin(x));
FLATBUFFERS_FN_DOUBLE("cos", cos(x));
FLATBUFFERS_FN_DOUBLE("tan", tan(x));
FLATBUFFERS_FN_DOUBLE("asin", asin(x));
FLATBUFFERS_FN_DOUBLE("acos", acos(x));
FLATBUFFERS_FN_DOUBLE("atan", atan(x));
// TODO(wvo): add more useful conversion functions here.
#undef FLATBUFFERS_FN_DOUBLE
// Then check if this could be a string/identifier enum value:
} else if (e.type.base_type != BASE_TYPE_STRING &&
e.type.base_type != BASE_TYPE_NONE &&
(token_ == kTokenIdentifier || token_ == kTokenStringConstant)) {
int64_t val;
ECHECK(ParseIntegerFromString(e.type, &val));
e.constant = NumToString(val);
NEXT();
if (IsIdentifierStart(attribute_[0])) { // Enum value.
int64_t val;
ECHECK(ParseEnumFromString(e.type, &val));
e.constant = NumToString(val);
NEXT();
} else { // Numeric constant in string.
if (IsInteger(e.type.base_type)) {
// TODO(wvo): do we want to check for garbage after the number?
e.constant = NumToString(StringToInt(attribute_.c_str()));
} else if (IsFloat(e.type.base_type)) {
e.constant = NumToString(strtod(attribute_.c_str(), nullptr));
} else {
assert(0); // Shouldn't happen, we covered all types.
e.constant = "0";
}
NEXT();
}
} else {
bool match = false;
ECHECK(TryTypedValue(kTokenIntegerConstant,
@@ -981,15 +1130,26 @@ CheckedError Parser::ParseSingleValue(Value &e) {
StructDef *Parser::LookupCreateStruct(const std::string &name,
bool create_if_new, bool definition) {
std::string qualified_name = namespaces_.back()->GetFullyQualifiedName(name);
// See if it exists pre-declared by an unqualified use.
auto struct_def = structs_.Lookup(name);
if (struct_def && struct_def->predecl) {
if (definition) {
// Make sure it has the current namespace, and is registered under its
// qualified name.
struct_def->defined_namespace = namespaces_.back();
structs_.Move(name, qualified_name);
}
return struct_def;
}
// See if it exists pre-declared by an qualified use.
struct_def = structs_.Lookup(qualified_name);
if (struct_def && struct_def->predecl) {
if (definition) {
// Make sure it has the current namespace.
struct_def->defined_namespace = namespaces_.back();
}
return struct_def;
}
if (!definition) {
// Search thru parent namespaces.
for (size_t components = namespaces_.back()->components.size();
@@ -1057,7 +1217,7 @@ CheckedError Parser::ParseEnum(bool is_union, EnumDef **dest) {
// Make this type refer back to the enum it was derived from.
enum_def.underlying_type.enum_def = &enum_def;
}
ECHECK(ParseMetaData(enum_def));
ECHECK(ParseMetaData(&enum_def.attributes));
EXPECT('{');
if (is_union) enum_def.vals.Add("NONE", new EnumVal("NONE", 0));
for (;;) {
@@ -1068,7 +1228,15 @@ CheckedError Parser::ParseEnum(bool is_union, EnumDef **dest) {
auto full_name = value_name;
std::vector<std::string> value_comment = doc_comment_;
EXPECT(kTokenIdentifier);
if (is_union) ECHECK(ParseNamespacing(&full_name, &value_name));
if (is_union) {
ECHECK(ParseNamespacing(&full_name, &value_name));
if (opts.union_value_namespacing) {
// Since we can't namespace the actual enum identifiers, turn
// namespace parts into part of the identifier.
value_name = full_name;
std::replace(value_name.begin(), value_name.end(), '.', '_');
}
}
auto prevsize = enum_def.vals.vec.size();
auto value = enum_def.vals.vec.size()
? enum_def.vals.vec.back()->value + 1
@@ -1082,7 +1250,7 @@ CheckedError Parser::ParseEnum(bool is_union, EnumDef **dest) {
}
if (Is('=')) {
NEXT();
ev.value = atoi(attribute_.c_str());
ev.value = StringToInt(attribute_.c_str());
EXPECT(kTokenIntegerConstant);
if (!opts.proto_mode && prevsize &&
enum_def.vals.vec[prevsize - 1]->value >= ev.value)
@@ -1146,7 +1314,7 @@ CheckedError Parser::CheckClash(std::vector<FieldDef*> &fields,
}
return NoError();
}
static bool compareFieldDefs(const FieldDef *a, const FieldDef *b) {
auto a_id = atoi(a->attributes.Lookup("id")->constant.c_str());
auto b_id = atoi(b->attributes.Lookup("id")->constant.c_str());
@@ -1163,7 +1331,7 @@ CheckedError Parser::ParseDecl() {
ECHECK(StartStruct(name, &struct_def));
struct_def->doc_comment = dc;
struct_def->fixed = fixed;
ECHECK(ParseMetaData(*struct_def));
ECHECK(ParseMetaData(&struct_def->attributes));
struct_def->sortbysize =
struct_def->attributes.Lookup("original_order") == nullptr && !fixed;
EXPECT('{');
@@ -1206,7 +1374,8 @@ CheckedError Parser::ParseDecl() {
}
}
ECHECK(CheckClash(fields, struct_def, "_type", BASE_TYPE_UNION));
ECHECK(CheckClash(fields, struct_def, UnionTypeFieldSuffix(),
BASE_TYPE_UNION));
ECHECK(CheckClash(fields, struct_def, "Type", BASE_TYPE_UNION));
ECHECK(CheckClash(fields, struct_def, "_length", BASE_TYPE_VECTOR));
ECHECK(CheckClash(fields, struct_def, "Length", BASE_TYPE_VECTOR));
@@ -1216,6 +1385,46 @@ CheckedError Parser::ParseDecl() {
return NoError();
}
CheckedError Parser::ParseService() {
std::vector<std::string> service_comment = doc_comment_;
NEXT();
auto service_name = attribute_;
EXPECT(kTokenIdentifier);
auto &service_def = *new ServiceDef();
service_def.name = service_name;
service_def.file = file_being_parsed_;
service_def.doc_comment = service_comment;
service_def.defined_namespace = namespaces_.back();
if (services_.Add(namespaces_.back()->GetFullyQualifiedName(service_name),
&service_def))
return Error("service already exists: " + service_name);
ECHECK(ParseMetaData(&service_def.attributes));
EXPECT('{');
do {
auto rpc_name = attribute_;
EXPECT(kTokenIdentifier);
EXPECT('(');
Type reqtype, resptype;
ECHECK(ParseTypeIdent(reqtype));
EXPECT(')');
EXPECT(':');
ECHECK(ParseTypeIdent(resptype));
if (reqtype.base_type != BASE_TYPE_STRUCT || reqtype.struct_def->fixed ||
resptype.base_type != BASE_TYPE_STRUCT || resptype.struct_def->fixed)
return Error("rpc request and response types must be tables");
auto &rpc = *new RPCCall();
rpc.name = rpc_name;
rpc.request = reqtype.struct_def;
rpc.response = resptype.struct_def;
if (service_def.calls.Add(rpc_name, &rpc))
return Error("rpc already exists: " + rpc_name);
ECHECK(ParseMetaData(&rpc.attributes));
EXPECT(';');
} while (token_ != '}');
NEXT();
return NoError();
}
bool Parser::SetRootType(const char *name) {
root_struct_def_ = structs_.Lookup(name);
if (!root_struct_def_)
@@ -1236,6 +1445,10 @@ void Parser::MarkGenerated() {
it != structs_.vec.end(); ++it) {
(*it)->generated = true;
}
for (auto it = services_.vec.begin();
it != services_.vec.end(); ++it) {
(*it)->generated = true;
}
}
CheckedError Parser::ParseNamespace() {
@@ -1307,7 +1520,7 @@ CheckedError Parser::ParseProtoDecl() {
if (Is(';')) NEXT();
// Protobuf allows them to be specified in any order, so sort afterwards.
auto &v = enum_def->vals.vec;
std::sort(v.begin(), v.end(), compareEnumVals);
std::sort(v.begin(), v.end(), compareEnumVals);
// Temp: remove any duplicates, as .fbs files can't handle them.
for (auto it = v.begin(); it != v.end(); ) {
@@ -1546,8 +1759,12 @@ CheckedError Parser::SkipJsonObject() {
for (;;) {
if ((!opts.strict_json || !fieldn) && Is('}')) break;
if (!Is(kTokenStringConstant))
if (!Is(kTokenStringConstant)) {
EXPECT(opts.strict_json ? kTokenStringConstant : kTokenIdentifier);
}
else {
NEXT();
}
EXPECT(':');
ECHECK(SkipAnyJsonValue());
@@ -1707,7 +1924,9 @@ CheckedError Parser::DoParse(const char *source, const char **include_paths,
auto name = attribute_;
EXPECT(kTokenStringConstant);
EXPECT(';');
known_attributes_.insert(name);
known_attributes_[name] = false;
} else if (token_ == kTokenService) {
ECHECK(ParseService());
} else {
ECHECK(ParseDecl());
}
@@ -1774,13 +1993,13 @@ void Parser::Serialize() {
AssignIndices(enums_.vec);
std::vector<Offset<reflection::Object>> object_offsets;
for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) {
auto offset = (*it)->Serialize(&builder_);
auto offset = (*it)->Serialize(&builder_, *this);
object_offsets.push_back(offset);
(*it)->serialized_location = offset.o;
}
std::vector<Offset<reflection::Enum>> enum_offsets;
for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
auto offset = (*it)->Serialize(&builder_);
auto offset = (*it)->Serialize(&builder_, *this);
enum_offsets.push_back(offset);
(*it)->serialized_location = offset.o;
}
@@ -1796,13 +2015,13 @@ void Parser::Serialize() {
builder_.Finish(schema_offset, reflection::SchemaIdentifier());
}
Offset<reflection::Object> StructDef::Serialize(FlatBufferBuilder *builder)
const {
Offset<reflection::Object> StructDef::Serialize(FlatBufferBuilder *builder,
const Parser &parser) const {
std::vector<Offset<reflection::Field>> field_offsets;
for (auto it = fields.vec.begin(); it != fields.vec.end(); ++it) {
field_offsets.push_back(
(*it)->Serialize(builder,
static_cast<uint16_t>(it - fields.vec.begin())));
static_cast<uint16_t>(it - fields.vec.begin()), parser));
}
return reflection::CreateObject(*builder,
builder->CreateString(name),
@@ -1810,11 +2029,13 @@ Offset<reflection::Object> StructDef::Serialize(FlatBufferBuilder *builder)
&field_offsets),
fixed,
static_cast<int>(minalign),
static_cast<int>(bytesize));
static_cast<int>(bytesize),
SerializeAttributes(builder, parser));
}
Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder,
uint16_t id) const {
uint16_t id,
const Parser &parser) const {
return reflection::CreateField(*builder,
builder->CreateString(name),
value.type.Serialize(builder),
@@ -1828,12 +2049,14 @@ Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder,
: 0.0,
deprecated,
required,
key);
key,
SerializeAttributes(builder, parser));
// TODO: value.constant is almost always "0", we could save quite a bit of
// space by sharing it. Same for common values of value.type.
}
Offset<reflection::Enum> EnumDef::Serialize(FlatBufferBuilder *builder) const {
Offset<reflection::Enum> EnumDef::Serialize(FlatBufferBuilder *builder,
const Parser &parser) const {
std::vector<Offset<reflection::EnumVal>> enumval_offsets;
for (auto it = vals.vec.begin(); it != vals.vec.end(); ++it) {
enumval_offsets.push_back((*it)->Serialize(builder));
@@ -1842,7 +2065,8 @@ Offset<reflection::Enum> EnumDef::Serialize(FlatBufferBuilder *builder) const {
builder->CreateString(name),
builder->CreateVector(enumval_offsets),
is_union,
underlying_type.Serialize(builder));
underlying_type.Serialize(builder),
SerializeAttributes(builder, parser));
}
Offset<reflection::EnumVal> EnumVal::Serialize(FlatBufferBuilder *builder) const
@@ -1863,4 +2087,79 @@ Offset<reflection::Type> Type::Serialize(FlatBufferBuilder *builder) const {
(enum_def ? enum_def->index : -1));
}
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<
reflection::KeyValue>>>
Definition::SerializeAttributes(FlatBufferBuilder *builder,
const Parser &parser) const {
std::vector<flatbuffers::Offset<reflection::KeyValue>> attrs;
for (auto kv = attributes.dict.begin(); kv != attributes.dict.end(); ++kv) {
auto it = parser.known_attributes_.find(kv->first);
assert(it != parser.known_attributes_.end());
if (!it->second) { // Custom attribute.
attrs.push_back(
reflection::CreateKeyValue(*builder, builder->CreateString(kv->first),
builder->CreateString(
kv->second->constant)));
}
}
if (attrs.size()) {
return builder->CreateVectorOfSortedTables(&attrs);
} else {
return 0;
}
}
std::string Parser::ConformTo(const Parser &base) {
for (auto sit = structs_.vec.begin(); sit != structs_.vec.end(); ++sit) {
auto &struct_def = **sit;
auto qualified_name =
struct_def.defined_namespace->GetFullyQualifiedName(struct_def.name);
auto struct_def_base = base.structs_.Lookup(qualified_name);
if (!struct_def_base) continue;
for (auto fit = struct_def.fields.vec.begin();
fit != struct_def.fields.vec.end(); ++fit) {
auto &field = **fit;
auto field_base = struct_def_base->fields.Lookup(field.name);
if (field_base) {
if (field.value.offset != field_base->value.offset)
return "offsets differ for field: " + field.name;
if (field.value.constant != field_base->value.constant)
return "defaults differ for field: " + field.name;
if (!EqualByName(field.value.type, field_base->value.type))
return "types differ for field: " + field.name;
} else {
// Doesn't have to exist, deleting fields is fine.
// But we should check if there is a field that has the same offset
// but is incompatible (in the case of field renaming).
for (auto fbit = struct_def_base->fields.vec.begin();
fbit != struct_def_base->fields.vec.end(); ++fbit) {
field_base = *fbit;
if (field.value.offset == field_base->value.offset) {
if (!EqualByName(field.value.type, field_base->value.type))
return "field renamed to different type: " + field.name;
break;
}
}
}
}
}
for (auto eit = enums_.vec.begin(); eit != enums_.vec.end(); ++eit) {
auto &enum_def = **eit;
auto qualified_name =
enum_def.defined_namespace->GetFullyQualifiedName(enum_def.name);
auto enum_def_base = base.enums_.Lookup(qualified_name);
if (!enum_def_base) continue;
for (auto evit = enum_def.vals.vec.begin();
evit != enum_def.vals.vec.end(); ++evit) {
auto &enum_val = **evit;
auto enum_val_base = enum_def_base->vals.Lookup(enum_val.name);
if (enum_val_base) {
if (enum_val.value != enum_val_base->value)
return "values differ for enum: " + enum_val.name;
}
}
}
return "";
}
} // namespace flatbuffers

View File

@@ -204,72 +204,76 @@ class ResizeContext {
if (DagCheck(table))
return; // Table already visited.
auto vtable = table->GetVTable();
// Check if the vtable offset points beyond the insertion point.
Straddle<soffset_t, -1>(table, vtable, table);
// This direction shouldn't happen because vtables that sit before tables
// are always directly adjacent, but check just in case we ever change the
// way flatbuffers are built.
Straddle<soffset_t, -1>(vtable, table, table);
// Early out: since all fields inside the table must point forwards in
// memory, if the insertion point is before the table we can stop here.
auto tableloc = reinterpret_cast<uint8_t *>(table);
if (startptr_ <= tableloc) return;
// Check each field.
auto fielddefs = objectdef.fields();
for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
auto &fielddef = **it;
auto base_type = fielddef.type()->base_type();
// Ignore scalars.
if (base_type <= reflection::Double) continue;
// Ignore fields that are not stored.
auto offset = table->GetOptionalFieldOffset(fielddef.offset());
if (!offset) continue;
// Ignore structs.
auto subobjectdef = base_type == reflection::Obj ?
schema_.objects()->Get(fielddef.type()->index()) : nullptr;
if (subobjectdef && subobjectdef->is_struct()) continue;
// Get this fields' offset, and read it if safe.
auto offsetloc = tableloc + offset;
if (DagCheck(offsetloc))
continue; // This offset already visited.
auto ref = offsetloc + ReadScalar<uoffset_t>(offsetloc);
Straddle<uoffset_t, 1>(offsetloc, ref, offsetloc);
// Recurse.
switch (base_type) {
case reflection::Obj: {
ResizeTable(*subobjectdef, reinterpret_cast<Table *>(ref));
break;
}
case reflection::Vector: {
auto elem_type = fielddef.type()->element();
if (elem_type != reflection::Obj && elem_type != reflection::String)
if (startptr_ <= tableloc) {
// Check if insertion point is between the table and a vtable that
// precedes it. This can't happen in current construction code, but check
// just in case we ever change the way flatbuffers are built.
Straddle<soffset_t, -1>(vtable, table, table);
} else {
// Check each field.
auto fielddefs = objectdef.fields();
for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
auto &fielddef = **it;
auto base_type = fielddef.type()->base_type();
// Ignore scalars.
if (base_type <= reflection::Double) continue;
// Ignore fields that are not stored.
auto offset = table->GetOptionalFieldOffset(fielddef.offset());
if (!offset) continue;
// Ignore structs.
auto subobjectdef = base_type == reflection::Obj ?
schema_.objects()->Get(fielddef.type()->index()) : nullptr;
if (subobjectdef && subobjectdef->is_struct()) continue;
// Get this fields' offset, and read it if safe.
auto offsetloc = tableloc + offset;
if (DagCheck(offsetloc))
continue; // This offset already visited.
auto ref = offsetloc + ReadScalar<uoffset_t>(offsetloc);
Straddle<uoffset_t, 1>(offsetloc, ref, offsetloc);
// Recurse.
switch (base_type) {
case reflection::Obj: {
ResizeTable(*subobjectdef, reinterpret_cast<Table *>(ref));
break;
auto vec = reinterpret_cast<Vector<uoffset_t> *>(ref);
auto elemobjectdef = elem_type == reflection::Obj
? schema_.objects()->Get(fielddef.type()->index())
: nullptr;
if (elemobjectdef && elemobjectdef->is_struct()) break;
for (uoffset_t i = 0; i < vec->size(); i++) {
auto loc = vec->Data() + i * sizeof(uoffset_t);
if (DagCheck(loc))
continue; // This offset already visited.
auto dest = loc + vec->Get(i);
Straddle<uoffset_t, 1>(loc, dest ,loc);
if (elemobjectdef)
ResizeTable(*elemobjectdef, reinterpret_cast<Table *>(dest));
}
break;
case reflection::Vector: {
auto elem_type = fielddef.type()->element();
if (elem_type != reflection::Obj && elem_type != reflection::String)
break;
auto vec = reinterpret_cast<Vector<uoffset_t> *>(ref);
auto elemobjectdef = elem_type == reflection::Obj
? schema_.objects()->Get(fielddef.type()->index())
: nullptr;
if (elemobjectdef && elemobjectdef->is_struct()) break;
for (uoffset_t i = 0; i < vec->size(); i++) {
auto loc = vec->Data() + i * sizeof(uoffset_t);
if (DagCheck(loc))
continue; // This offset already visited.
auto dest = loc + vec->Get(i);
Straddle<uoffset_t, 1>(loc, dest ,loc);
if (elemobjectdef)
ResizeTable(*elemobjectdef, reinterpret_cast<Table *>(dest));
}
break;
}
case reflection::Union: {
ResizeTable(GetUnionType(schema_, objectdef, fielddef, *table),
reinterpret_cast<Table *>(ref));
break;
}
case reflection::String:
break;
default:
assert(false);
}
case reflection::Union: {
ResizeTable(GetUnionType(schema_, objectdef, fielddef, *table),
reinterpret_cast<Table *>(ref));
break;
}
case reflection::String:
break;
default:
assert(false);
}
// Check if the vtable offset points beyond the insertion point.
// Must do this last, since GetOptionalFieldOffset above still reads
// this value.
Straddle<soffset_t, -1>(table, vtable, table);
}
}
@@ -354,7 +358,8 @@ void CopyInline(FlatBufferBuilder &fbb, const reflection::Field &fielddef,
Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
const reflection::Schema &schema,
const reflection::Object &objectdef,
const Table &table) {
const Table &table,
bool use_string_pooling) {
// Before we can construct the table, we have to first generate any
// subobjects, and collect their offsets.
std::vector<uoffset_t> offsets;
@@ -366,7 +371,9 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
uoffset_t offset = 0;
switch (fielddef.type()->base_type()) {
case reflection::String: {
offset = fbb.CreateString(GetFieldS(table, fielddef)).o;
offset = use_string_pooling
? fbb.CreateSharedString(GetFieldS(table, fielddef)).o
: fbb.CreateString(GetFieldS(table, fielddef)).o;
break;
}
case reflection::Obj: {
@@ -395,7 +402,9 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
std::vector<Offset<const String *>> elements(vec->size());
auto vec_s = reinterpret_cast<const Vector<Offset<String>> *>(vec);
for (uoffset_t i = 0; i < vec_s->size(); i++) {
elements[i] = fbb.CreateString(vec_s->Get(i)).o;
elements[i] = use_string_pooling
? fbb.CreateSharedString(vec_s->Get(i)).o
: fbb.CreateString(vec_s->Get(i)).o;
}
offset = fbb.CreateVector(elements).o;
break;

86
src/util.cpp Normal file
View File

@@ -0,0 +1,86 @@
/*
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flatbuffers/util.h"
namespace flatbuffers {
bool FileExistsRaw(const char *name) {
std::ifstream ifs(name);
return ifs.good();
}
bool LoadFileRaw(const char *name, bool binary, std::string *buf) {
if (DirExists(name)) return false;
std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
if (!ifs.is_open()) return false;
if (binary) {
// The fastest way to read a file into a string.
ifs.seekg(0, std::ios::end);
auto size = ifs.tellg();
(*buf).resize(static_cast<size_t>(size));
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();
}
static LoadFileFunction g_load_file_function = LoadFileRaw;
static FileExistsFunction g_file_exists_function = FileExistsRaw;
bool LoadFile(const char *name, bool binary, std::string *buf) {
assert(g_load_file_function);
return g_load_file_function(name, binary, buf);
}
bool FileExists(const char *name) {
assert(g_file_exists_function);
return g_file_exists_function(name);
}
bool DirExists(const char *name) {
#ifdef _WIN32
#define flatbuffers_stat _stat
#define FLATBUFFERS_S_IFDIR _S_IFDIR
#else
#define flatbuffers_stat stat
#define FLATBUFFERS_S_IFDIR S_IFDIR
#endif
struct flatbuffers_stat file_info;
if (flatbuffers_stat(name, &file_info) != 0) return false;
return (file_info.st_mode & FLATBUFFERS_S_IFDIR) != 0;
}
LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function) {
LoadFileFunction previous_function = g_load_file_function;
g_load_file_function = load_file_function ? load_file_function : LoadFileRaw;
return previous_function;
}
FileExistsFunction SetFileExistsFunction(
FileExistsFunction file_exists_function) {
FileExistsFunction previous_function = g_file_exists_function;
g_file_exists_function = file_exists_function ?
file_exists_function : FileExistsRaw;
return previous_function;
}
} // namespace flatbuffers

View File

@@ -1,4 +1,4 @@
/*
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");

View File

@@ -1,4 +1,4 @@
/*
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");

View File

@@ -1,4 +1,4 @@
/*
/*
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");

View File

@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>

View File

@@ -1,4 +1,4 @@
/*
/*
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -124,13 +124,13 @@ namespace FlatBuffers.Test
builder.CreateString("moop");
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, // Padding to 32 bytes
4, 0, 0, 0,
4, 0, 0, 0,
(byte)'m', (byte)'o', (byte)'o', (byte)'p',
0, 0, 0, 0, // zero terminator with 3 byte pad
3, 0, 0, 0,
3, 0, 0, 0,
(byte)'f', (byte)'o', (byte)'o', 0
}, builder.DataBuffer.Data);
}
@@ -142,19 +142,19 @@ namespace FlatBuffers.Test
builder.CreateString("\x01\x02\x03");
Assert.ArrayEqual(new byte[]
{
3, 0, 0, 0,
3, 0, 0, 0,
0x01, 0x02, 0x03, 0
}, builder.DataBuffer.Data); // No padding
builder.CreateString("\x04\x05\x06\x07");
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, // Padding to 32 bytes
4, 0, 0, 0,
4, 0, 0, 0,
0x04, 0x05, 0x06, 0x07,
0, 0, 0, 0, // zero terminator with 3 byte pad
3, 0, 0, 0,
3, 0, 0, 0,
0x01, 0x02, 0x03, 0
}, builder.DataBuffer.Data); // No padding
}
@@ -168,9 +168,9 @@ namespace FlatBuffers.Test
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
4, 0, 4, 0,
4, 0, 4, 0,
4, 0, 0, 0
},
},
builder.DataBuffer.Data);
}
@@ -287,20 +287,20 @@ namespace FlatBuffers.Test
var vecEnd = builder.EndVector();
builder.StartObject(1);
builder.AddOffset(0, vecEnd.Value, 0);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, // Padding to 32 bytes
6, 0, // vtable bytes
8, 0, // object length inc vtable offset
4, 0, // start of vector offset value 0
6, 0, 0, 0, // int32 offset for start of vtable
4, 0, 0, 0,
4, 0, 0, 0,
0, 0, 0, 0,
},
builder.DataBuffer.Data);
@@ -320,7 +320,7 @@ namespace FlatBuffers.Test
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0, // Padding to 32 bytes
0, 0, 0, 0, // Padding to 32 bytes
8, 0, // vtable bytes
12, 0, // object length inc vtable offset
10, 0, // offset to int16 value 0
@@ -349,9 +349,9 @@ namespace FlatBuffers.Test
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0, // Padding to 32 bytes
0, 0, 0, 0, // Padding to 32 bytes
8, 0, // vtable bytes
12, 0, // object length
12, 0, // object length
6, 0, // start of value 0 from end of vtable
8, 0, // start of value 1 from end of buffer
8, 0, 0, 0, // int32 offset for start of vtable
@@ -382,9 +382,9 @@ namespace FlatBuffers.Test
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, // Padding to 32 bytes
0, 0, // Padding to 32 bytes
6, 0, // vtable bytes
16, 0, // object length
16, 0, // object length
4, 0, // start of struct from here
6, 0, 0, 0, // int32 offset for start of vtable
0x78, 0x56, 0x34, 0x12, // struct value 2
@@ -413,9 +413,9 @@ namespace FlatBuffers.Test
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, // Padding to 32 bytes
0, 0, // Padding to 32 bytes
6, 0, // vtable bytes
8, 0, // object length
8, 0, // object length
4, 0, // offset of vector offset
6, 0, 0, 0, // int32 offset for start of vtable
4, 0, 0, 0, // Vector start offset
@@ -442,16 +442,16 @@ namespace FlatBuffers.Test
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, //Padding to 32 bytes
12, 0, 0, 0, // root of table, pointing to vtable offset
0, 0, 0, 0, //Padding to 32 bytes
12, 0, 0, 0, // root of table, pointing to vtable offset
8, 0, // vtable bytes
8, 0, // object length
8, 0, // object length
7, 0, // start of value 0
4, 0, // start of value 1
8, 0, 0, 0, // int32 offset for start of vtable
66, 0, // value 1
0, 33, // value 0
},
builder.DataBuffer.Data);
}
@@ -480,23 +480,23 @@ namespace FlatBuffers.Test
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, // padding to 64 bytes
16, 0, 0, 0, // root of table, pointing to vtable offset (obj1)
16, 0, 0, 0, // root of table, pointing to vtable offset (obj1)
0, 0, // padding
10, 0, // vtable bytes
8, 0, // object length
8, 0, // object length
7, 0, // start of value 0
6, 0, // start of value 1
5, 0, // start of value 2
10, 0, 0, 0, // int32 offset for start of vtable
0, // pad
77, // values 2, 1, 0
66,
66,
55,
12, 0, 0, 0, // root of table, pointing to vtable offset (obj0)
8, 0, // vtable bytes
8, 0, // object length
8, 0, // object length
7, 0, // start of value 0
6, 0, // start of value 1
8, 0, 0, 0, // int32 offset for start of vtable
@@ -531,7 +531,7 @@ namespace FlatBuffers.Test
24, 0, 0, 0, // root of table, pointing to vtable offset (obj0)
20, 0, // vtable bytes
12, 0, // object length
12, 0, // object length
11, 0, // start of value 0
10, 0, // start of value 1
9, 0, // start of value 2
@@ -542,10 +542,10 @@ namespace FlatBuffers.Test
4, 0, // start of value 7
20, 0, 0, 0, // int32 offset for start of vtable
1, 1, 1, 1, // values
1, 1, 1, 1,
},
builder.DataBuffer.Data);
}
@@ -557,17 +557,17 @@ namespace FlatBuffers.Test
builder.StartObject(1);
builder.AddFloat(0, 1, 0);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
0, 0,
6, 0, // vtable bytes
8, 0, // object length
8, 0, // object length
4, 0, // start of value 0
6, 0, 0, 0, // int32 offset for start of vtable
0, 0, 128, 63, // value
},
builder.DataBuffer.Data);
}
@@ -660,7 +660,7 @@ namespace FlatBuffers.Test
}
_lcg.Reset();
// Test all objects are readable and return expected values...
for (var i = 0; i < objectCount; ++i)
{

View File

@@ -1,4 +1,20 @@
using System;
/*
* Copyright 2016 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;

View File

@@ -1,4 +1,20 @@
using System;
/*
* Copyright 2016 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;
namespace FlatBuffers.Test
{

View File

@@ -1,4 +1,20 @@
using System;
/*
* Copyright 2016 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;
namespace FlatBuffers.Test
{

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2016 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.Test
{
/// <summary>

View File

@@ -1,4 +1,4 @@
/*
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");

View File

@@ -1,4 +1,4 @@
/*
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -26,7 +26,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FlatBuffers.Test")]
[assembly: AssemblyCopyright("Copyright © 2014 Google Inc")]
[assembly: AssemblyCopyright("Copyright (c) 2014 Google Inc")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2016 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.Test
{
/// <summary>

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