diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 72cf595ee63..5a31f5f6db2 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -1,5 +1,9 @@ name: 'Close stale issues' on: + # NOTE: uncomment if you want to test changes to this file in PRs CI + # pull_request: + # branches: + # - master schedule: - cron: '30 1 * * *' # every day at 1:30am permissions: @@ -12,6 +16,7 @@ jobs: steps: - uses: actions/stale@v9 with: + operations-per-run: 3000 stale-issue-message: 'This issue seems to be stale. It will be closed in 30 days if no further activity occurs.' stale-pr-message: 'This PR seems to be stale. Is it still relevant?' days-before-issue-stale: 180 # 6 months diff --git a/.gitignore b/.gitignore index 9180d6fb50b..2e777a498a0 100644 --- a/.gitignore +++ b/.gitignore @@ -46,7 +46,6 @@ Thumbs.db /example/build/ /test/data/monaco.osrm* /test/data/ch -/test/data/corech /test/data/mld /cmake/postinst diff --git a/CHANGELOG.md b/CHANGELOG.md index d4ba8226934..b67841c9cf3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,9 @@ - NodeJS: - CHANGED: Use node-api instead of NAN. [#6452](https://github.com/Project-OSRM/osrm-backend/pull/6452) - Misc: + - CHANGED: Use thread_local instead of boost::thread_specific_ptr. [#6991](https://github.com/Project-OSRM/osrm-backend/pull/6991) + - CHANGED: Bump flatbuffers to v24.3.25 version. [#6988](https://github.com/Project-OSRM/osrm-backend/pull/6988) + - CHANGED: Add .reserve(...) to assembleGeometry function. [#6983](https://github.com/Project-OSRM/osrm-backend/pull/6983) - CHANGED: Get rid of boost::optional leftovers. [#6977](https://github.com/Project-OSRM/osrm-backend/pull/6977) - CHANGED: Use Link Time Optimisation whenever possible. [#6967](https://github.com/Project-OSRM/osrm-backend/pull/6967) - CHANGED: Use struct instead of tuple to define UnpackedPath. [#6974](https://github.com/Project-OSRM/osrm-backend/pull/6974) diff --git a/CMakeLists.txt b/CMakeLists.txt index 046d8877fcb..08e0a64fa89 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -133,6 +133,7 @@ endif() include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR}/include/) include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/include/) +include_directories(SYSTEM ${CMAKE_CURRENT_SOURCE_DIR}/generated/include/) include_directories(SYSTEM ${CMAKE_CURRENT_SOURCE_DIR}/third_party/sol2/include) set(BOOST_COMPONENTS date_time iostreams program_options thread unit_test_framework) diff --git a/features/guidance/collapse.feature b/features/guidance/collapse.feature index e7b4dad59ad..5d790d8fa35 100644 --- a/features/guidance/collapse.feature +++ b/features/guidance/collapse.feature @@ -1061,7 +1061,7 @@ Feature: Collapse # i # """ - And the node locations + Given the node locations | node | lat | lon | #id | | a | -33.9644254 | 151.1378673 | 33226063 | | b | -33.9644373 | 151.1377172 | 1072787030 | diff --git a/features/guidance/roundabout-left-sided.feature b/features/guidance/roundabout-left-sided.feature index 103da754430..9555a24cae2 100644 --- a/features/guidance/roundabout-left-sided.feature +++ b/features/guidance/roundabout-left-sided.feature @@ -9,7 +9,7 @@ Feature: Basic Roundabout """ Scenario: Roundabout exit counting for left sided driving - And a grid size of 10 meters + Given a grid size of 10 meters And the node map """ a @@ -33,7 +33,7 @@ Feature: Basic Roundabout | a,h | ab,gh,gh | depart,roundabout turn right exit-3,arrive | Scenario: Mixed Entry and Exit - And a grid size of 10 meters + Given a grid size of 10 meters And the node map """ c a diff --git a/features/options/contract/help.feature b/features/options/contract/help.feature deleted file mode 100644 index 50269483d96..00000000000 --- a/features/options/contract/help.feature +++ /dev/null @@ -1,44 +0,0 @@ -@prepare @options @help -Feature: osrm-contract command line options: help - - Scenario: osrm-contract - Help should be shown when no options are passed - When I try to run "osrm-contract" - Then stderr should be empty - And stdout should contain /osrm-contract(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--threads" - And stdout should contain "--core" - And stdout should contain "--segment-speed-file" - And it should exit with an error - - Scenario: osrm-contract - Help, short - When I run "osrm-contract -h" - Then stderr should be empty - And stdout should contain /osrm-contract(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--threads" - And stdout should contain "--core" - And stdout should contain "--segment-speed-file" - And it should exit successfully - - Scenario: osrm-contract - Help, long - When I run "osrm-contract --help" - Then stderr should be empty - And stdout should contain /osrm-contract(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--threads" - And stdout should contain "--core" - And stdout should contain "--segment-speed-file" - And it should exit successfully diff --git a/features/options/customize/help.feature b/features/options/customize/help.feature deleted file mode 100644 index 02a69e4ce34..00000000000 --- a/features/options/customize/help.feature +++ /dev/null @@ -1,38 +0,0 @@ -@contract @options @help -Feature: osrm-customize command line options: help - - Scenario: osrm-customize - Help should be shown when no options are passed - When I try to run "osrm-customize" - Then stderr should be empty - And stdout should contain /osrm-customize(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--threads" - And it should exit with an error - - Scenario: osrm-customize - Help, short - When I run "osrm-customize -h" - Then stderr should be empty - And stdout should contain /osrm-customize(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--threads" - And it should exit successfully - - Scenario: osrm-customize - Help, long - When I run "osrm-customize --help" - Then stderr should be empty - And stdout should contain /osrm-customize(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--threads" - And it should exit successfully diff --git a/features/options/datastore/datastore.feature b/features/options/datastore/datastore.feature index 667f245a56f..30d19615483 100644 --- a/features/options/datastore/datastore.feature +++ b/features/options/datastore/datastore.feature @@ -33,10 +33,6 @@ Feature: osrm-datastore command line options When I try to run "osrm-datastore {processed_file} --dataset-name cucumber/only_metric_test --only-metric" Then it should exit successfully - Scenario: osrm-datastore - Displaying help should work - When I try to run "osrm-datastore {processed_file} --help" - Then it should exit successfully - Scenario: osrm-datastore - Errors on invalid path When I try to run "osrm-datastore invalid_path.osrm" Then stderr should contain "[error] Config contains invalid file paths." diff --git a/features/options/extract/help.feature b/features/options/extract/help.feature deleted file mode 100644 index 3d86115e5aa..00000000000 --- a/features/options/extract/help.feature +++ /dev/null @@ -1,47 +0,0 @@ -@extract @options @help -Feature: osrm-extract command line options: help - - Background: - Given the profile "testbot" - - Scenario: osrm-extract - Help should be shown when no options are passed - When I run "osrm-extract" - Then stderr should be empty - And stdout should contain /osrm-extract(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--profile" - And stdout should contain "--threads" - And stdout should contain "--small-component-size" - And it should exit successfully - - Scenario: osrm-extract - Help, short - When I run "osrm-extract -h" - Then stderr should be empty - And stdout should contain /osrm-extract(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--profile" - And stdout should contain "--threads" - And stdout should contain "--small-component-size" - And it should exit successfully - - Scenario: osrm-extract - Help, long - When I run "osrm-extract --help" - Then stderr should be empty - And stdout should contain /osrm-extract(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--profile" - And stdout should contain "--threads" - And stdout should contain "--small-component-size" - And it should exit successfully diff --git a/features/options/partition/help.feature b/features/options/partition/help.feature deleted file mode 100644 index 08fb84c35b4..00000000000 --- a/features/options/partition/help.feature +++ /dev/null @@ -1,53 +0,0 @@ -@partition @options @help -Feature: osrm-partition command line options: help - - Scenario: osrm-partition - Help should be shown when no options are passed - When I try to run "osrm-partition" - Then stderr should be empty - And stdout should contain /osrm-partition(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--threads" - And stdout should contain "--balance" - And stdout should contain "--boundary" - And stdout should contain "--optimizing-cuts" - And stdout should contain "--small-component-size" - And stdout should contain "--max-cell-sizes" - And it should exit with an error - - Scenario: osrm-partition - Help, short - When I run "osrm-partition -h" - Then stderr should be empty - And stdout should contain /osrm-partition(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--threads" - And stdout should contain "--balance" - And stdout should contain "--boundary" - And stdout should contain "--optimizing-cuts" - And stdout should contain "--small-component-size" - And stdout should contain "--max-cell-sizes" - And it should exit successfully - - Scenario: osrm-partition - Help, long - When I run "osrm-partition --help" - Then stderr should be empty - And stdout should contain /osrm-partition(.exe)? \[options\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "Configuration:" - And stdout should contain "--threads" - And stdout should contain "--balance" - And stdout should contain "--boundary" - And stdout should contain "--optimizing-cuts" - And stdout should contain "--small-component-size" - And stdout should contain "--max-cell-sizes" - And it should exit successfully diff --git a/features/options/routed/help.feature b/features/options/routed/help.feature deleted file mode 100644 index fc37410788c..00000000000 --- a/features/options/routed/help.feature +++ /dev/null @@ -1,71 +0,0 @@ -@routed @options @help -Feature: osrm-routed command line options: help - - Background: - Given the profile "testbot" - - Scenario: osrm-routed - Help should be shown when no options are passed - When I run "osrm-routed" - Then stderr should be empty - And stdout should contain /osrm-routed(.exe)? \[\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "--trial" - And stdout should contain "Configuration:" - And stdout should contain "--ip" - And stdout should contain "--port" - And stdout should contain "--threads" - And stdout should contain "--shared-memory" - And stdout should contain "--max-viaroute-size" - And stdout should contain "--max-trip-size" - And stdout should contain "--max-table-size" - And stdout should contain "--max-matching-size" - And stdout should contain "--default-radius" - And stdout should contain "--keepalive-timeout" - And it should exit successfully - - Scenario: osrm-routed - Help, short - When I run "osrm-routed -h" - Then stderr should be empty - And stdout should contain /osrm-routed(.exe)? \[\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "--trial" - And stdout should contain "Configuration:" - And stdout should contain "--ip" - And stdout should contain "--port" - And stdout should contain "--threads" - And stdout should contain "--shared-memory" - And stdout should contain "--max-viaroute-size" - And stdout should contain "--max-trip-size" - And stdout should contain "--max-table-size" - And stdout should contain "--max-matching-size" - And stdout should contain "--default-radius" - And stdout should contain "--keepalive-timeout" - And it should exit successfully - - Scenario: osrm-routed - Help, long - When I run "osrm-routed --help" - Then stderr should be empty - And stdout should contain /osrm-routed(.exe)? \[\]:/ - And stdout should contain "Options:" - And stdout should contain "--version" - And stdout should contain "--help" - And stdout should contain "--verbosity" - And stdout should contain "--trial" - And stdout should contain "Configuration:" - And stdout should contain "--ip" - And stdout should contain "--port" - And stdout should contain "--threads" - And stdout should contain "--shared-memory" - And stdout should contain "--max-trip-size" - And stdout should contain "--max-table-size" - And stdout should contain "--max-table-size" - And stdout should contain "--max-matching-size" - And stdout should contain "--default-radius" - And stdout should contain "--keepalive-timeout" - And it should exit successfully diff --git a/features/testbot/loop.feature b/features/testbot/loop.feature index 985c8ba6a0e..6c8b0804837 100644 --- a/features/testbot/loop.feature +++ b/features/testbot/loop.feature @@ -75,7 +75,7 @@ Feature: Avoid weird loops caused by rounding errors @412 @via Scenario: Avoid weird loops 3 - And the node map + Given the node map """ a b e diff --git a/features/testbot/matching.feature b/features/testbot/matching.feature index b9df1f3b06d..1cf11147292 100644 --- a/features/testbot/matching.feature +++ b/features/testbot/matching.feature @@ -136,22 +136,6 @@ Feature: Basic Map Matching | trace | matchings | | abcbd | abbd | - Scenario: Testbot - Map matching with core factor - Given the contract extra arguments "--core 0.8" - Given the node map - """ - a b c d - e - """ - - And the ways - | nodes | oneway | - | abcd | no | - - When I match I should get - | trace | timestamps | matchings | - | abcd | 0 1 2 3 | abcd | - Scenario: Testbot - Map matching with small distortion Given the node map """ diff --git a/features/testbot/snap_intersection.feature b/features/testbot/snap_intersection.feature index 063986bab12..c577c685578 100644 --- a/features/testbot/snap_intersection.feature +++ b/features/testbot/snap_intersection.feature @@ -401,12 +401,12 @@ Feature: Snapping at intersections Given the extract extra arguments "--small-component-size=4" And the ways - | nodes | oneway | - | ab | no | - | bc | no | - | cd | no | - | fed | no | - | bg | yes | # small SCC + | nodes | oneway | # comment | + | ab | no | | + | bc | no | | + | cd | no | | + | fed | no | | + | bg | yes | small SCC | And the relations | type | way:from | way:to | node:via | restriction | @@ -437,14 +437,14 @@ Feature: Snapping at intersections Given the extract extra arguments "--small-component-size=4" And the ways - | nodes | oneway | - | ab | no | - | bc | no | - | cd | no | - | fed | no | - | ghi | no | - | jkl | no | - | bm | yes | # small SCC + | nodes | oneway | # comment | + | ab | no | | + | bc | no | | + | cd | no | | + | fed | no | | + | ghi | no | | + | jkl | no | | + | bm | yes | small SCC | And the relations | type | way:from | way:to | node:via | restriction | diff --git a/features/testbot/via.feature b/features/testbot/via.feature index 017cc54e6ec..44a2aaeebee 100644 --- a/features/testbot/via.feature +++ b/features/testbot/via.feature @@ -65,32 +65,6 @@ Feature: Via points | waypoints | route | turns | | 1,2,3 | cd,ac,ab,bd,cd | depart,new name right,new name right,new name right,arrive | - Scenario: Simple via point with core factor - Given the contract extra arguments "--core 0.8" - Given the node map - """ - a b c d - e f g - h i - j - """ - - And the ways - | nodes | - | abcd | - | efg | - | hi | - | be | - | cfh | - | dgij | - - When I route I should get - | waypoints | route | - | a,b,c | abcd,abcd,abcd,abcd | - | c,b,a | abcd,abcd,abcd,abcd | - | a,d,j | abcd,abcd,dgij,dgij | - | j,d,a | dgij,dgij,abcd,abcd | - Scenario: Via point at a dead end Given the node map """ diff --git a/include/engine/api/flatbuffers/fbresult.fbs b/generated/include/engine/api/flatbuffers/fbresult.fbs similarity index 93% rename from include/engine/api/flatbuffers/fbresult.fbs rename to generated/include/engine/api/flatbuffers/fbresult.fbs index a587899a38e..860f4624830 100644 --- a/include/engine/api/flatbuffers/fbresult.fbs +++ b/generated/include/engine/api/flatbuffers/fbresult.fbs @@ -14,7 +14,7 @@ table FBResult { data_version: string; waypoints: [Waypoint]; //Used as 'sources' waypoints for a 'Table' service routes: [RouteObject]; - table: Table; + table: TableResult; } root_type FBResult; \ No newline at end of file diff --git a/generated/include/engine/api/flatbuffers/fbresult_generated.h b/generated/include/engine/api/flatbuffers/fbresult_generated.h new file mode 100644 index 00000000000..0f01298198f --- /dev/null +++ b/generated/include/engine/api/flatbuffers/fbresult_generated.h @@ -0,0 +1,249 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_FBRESULT_OSRM_ENGINE_API_FBRESULT_H_ +#define FLATBUFFERS_GENERATED_FBRESULT_OSRM_ENGINE_API_FBRESULT_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && + FLATBUFFERS_VERSION_MINOR == 3 && + FLATBUFFERS_VERSION_REVISION == 25, + "Non-compatible flatbuffers version included"); + +#include "route_generated.h" +#include "table_generated.h" + +namespace osrm { +namespace engine { +namespace api { +namespace fbresult { + +struct Error; +struct ErrorBuilder; + +struct FBResult; +struct FBResultBuilder; + +struct Error FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ErrorBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_CODE = 4, + VT_MESSAGE = 6 + }; + const ::flatbuffers::String *code() const { + return GetPointer(VT_CODE); + } + const ::flatbuffers::String *message() const { + return GetPointer(VT_MESSAGE); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_CODE) && + verifier.VerifyString(code()) && + VerifyOffset(verifier, VT_MESSAGE) && + verifier.VerifyString(message()) && + verifier.EndTable(); + } +}; + +struct ErrorBuilder { + typedef Error Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_code(::flatbuffers::Offset<::flatbuffers::String> code) { + fbb_.AddOffset(Error::VT_CODE, code); + } + void add_message(::flatbuffers::Offset<::flatbuffers::String> message) { + fbb_.AddOffset(Error::VT_MESSAGE, message); + } + explicit ErrorBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateError( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> code = 0, + ::flatbuffers::Offset<::flatbuffers::String> message = 0) { + ErrorBuilder builder_(_fbb); + builder_.add_message(message); + builder_.add_code(code); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateErrorDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *code = nullptr, + const char *message = nullptr) { + auto code__ = code ? _fbb.CreateString(code) : 0; + auto message__ = message ? _fbb.CreateString(message) : 0; + return osrm::engine::api::fbresult::CreateError( + _fbb, + code__, + message__); +} + +struct FBResult FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef FBResultBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ERROR = 4, + VT_CODE = 6, + VT_DATA_VERSION = 8, + VT_WAYPOINTS = 10, + VT_ROUTES = 12, + VT_TABLE = 14 + }; + bool error() const { + return GetField(VT_ERROR, 0) != 0; + } + const osrm::engine::api::fbresult::Error *code() const { + return GetPointer(VT_CODE); + } + const ::flatbuffers::String *data_version() const { + return GetPointer(VT_DATA_VERSION); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *waypoints() const { + return GetPointer> *>(VT_WAYPOINTS); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *routes() const { + return GetPointer> *>(VT_ROUTES); + } + const osrm::engine::api::fbresult::TableResult *table() const { + return GetPointer(VT_TABLE); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_ERROR, 1) && + VerifyOffset(verifier, VT_CODE) && + verifier.VerifyTable(code()) && + VerifyOffset(verifier, VT_DATA_VERSION) && + verifier.VerifyString(data_version()) && + VerifyOffset(verifier, VT_WAYPOINTS) && + verifier.VerifyVector(waypoints()) && + verifier.VerifyVectorOfTables(waypoints()) && + VerifyOffset(verifier, VT_ROUTES) && + verifier.VerifyVector(routes()) && + verifier.VerifyVectorOfTables(routes()) && + VerifyOffset(verifier, VT_TABLE) && + verifier.VerifyTable(table()) && + verifier.EndTable(); + } +}; + +struct FBResultBuilder { + typedef FBResult Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_error(bool error) { + fbb_.AddElement(FBResult::VT_ERROR, static_cast(error), 0); + } + void add_code(::flatbuffers::Offset code) { + fbb_.AddOffset(FBResult::VT_CODE, code); + } + void add_data_version(::flatbuffers::Offset<::flatbuffers::String> data_version) { + fbb_.AddOffset(FBResult::VT_DATA_VERSION, data_version); + } + void add_waypoints(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> waypoints) { + fbb_.AddOffset(FBResult::VT_WAYPOINTS, waypoints); + } + void add_routes(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> routes) { + fbb_.AddOffset(FBResult::VT_ROUTES, routes); + } + void add_table(::flatbuffers::Offset table) { + fbb_.AddOffset(FBResult::VT_TABLE, table); + } + explicit FBResultBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateFBResult( + ::flatbuffers::FlatBufferBuilder &_fbb, + bool error = false, + ::flatbuffers::Offset code = 0, + ::flatbuffers::Offset<::flatbuffers::String> data_version = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> waypoints = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> routes = 0, + ::flatbuffers::Offset table = 0) { + FBResultBuilder builder_(_fbb); + builder_.add_table(table); + builder_.add_routes(routes); + builder_.add_waypoints(waypoints); + builder_.add_data_version(data_version); + builder_.add_code(code); + builder_.add_error(error); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateFBResultDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + bool error = false, + ::flatbuffers::Offset code = 0, + const char *data_version = nullptr, + const std::vector<::flatbuffers::Offset> *waypoints = nullptr, + const std::vector<::flatbuffers::Offset> *routes = nullptr, + ::flatbuffers::Offset table = 0) { + auto data_version__ = data_version ? _fbb.CreateString(data_version) : 0; + auto waypoints__ = waypoints ? _fbb.CreateVector<::flatbuffers::Offset>(*waypoints) : 0; + auto routes__ = routes ? _fbb.CreateVector<::flatbuffers::Offset>(*routes) : 0; + return osrm::engine::api::fbresult::CreateFBResult( + _fbb, + error, + code, + data_version__, + waypoints__, + routes__, + table); +} + +inline const osrm::engine::api::fbresult::FBResult *GetFBResult(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const osrm::engine::api::fbresult::FBResult *GetSizePrefixedFBResult(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline bool VerifyFBResultBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(nullptr); +} + +inline bool VerifySizePrefixedFBResultBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(nullptr); +} + +inline void FinishFBResultBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root); +} + +inline void FinishSizePrefixedFBResultBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root); +} + +} // namespace fbresult +} // namespace api +} // namespace engine +} // namespace osrm + +#endif // FLATBUFFERS_GENERATED_FBRESULT_OSRM_ENGINE_API_FBRESULT_H_ diff --git a/include/engine/api/flatbuffers/position.fbs b/generated/include/engine/api/flatbuffers/position.fbs similarity index 100% rename from include/engine/api/flatbuffers/position.fbs rename to generated/include/engine/api/flatbuffers/position.fbs diff --git a/generated/include/engine/api/flatbuffers/position_generated.h b/generated/include/engine/api/flatbuffers/position_generated.h new file mode 100644 index 00000000000..aa3ea2d8b21 --- /dev/null +++ b/generated/include/engine/api/flatbuffers/position_generated.h @@ -0,0 +1,51 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_POSITION_OSRM_ENGINE_API_FBRESULT_H_ +#define FLATBUFFERS_GENERATED_POSITION_OSRM_ENGINE_API_FBRESULT_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && + FLATBUFFERS_VERSION_MINOR == 3 && + FLATBUFFERS_VERSION_REVISION == 25, + "Non-compatible flatbuffers version included"); + +namespace osrm { +namespace engine { +namespace api { +namespace fbresult { + +struct Position; + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Position FLATBUFFERS_FINAL_CLASS { + private: + float longitude_; + float latitude_; + + public: + Position() + : longitude_(0), + latitude_(0) { + } + Position(float _longitude, float _latitude) + : longitude_(::flatbuffers::EndianScalar(_longitude)), + latitude_(::flatbuffers::EndianScalar(_latitude)) { + } + float longitude() const { + return ::flatbuffers::EndianScalar(longitude_); + } + float latitude() const { + return ::flatbuffers::EndianScalar(latitude_); + } +}; +FLATBUFFERS_STRUCT_END(Position, 8); + +} // namespace fbresult +} // namespace api +} // namespace engine +} // namespace osrm + +#endif // FLATBUFFERS_GENERATED_POSITION_OSRM_ENGINE_API_FBRESULT_H_ diff --git a/include/engine/api/flatbuffers/route.fbs b/generated/include/engine/api/flatbuffers/route.fbs similarity index 100% rename from include/engine/api/flatbuffers/route.fbs rename to generated/include/engine/api/flatbuffers/route.fbs diff --git a/generated/include/engine/api/flatbuffers/route_generated.h b/generated/include/engine/api/flatbuffers/route_generated.h new file mode 100644 index 00000000000..6ae492bd429 --- /dev/null +++ b/generated/include/engine/api/flatbuffers/route_generated.h @@ -0,0 +1,1156 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_ROUTE_OSRM_ENGINE_API_FBRESULT_H_ +#define FLATBUFFERS_GENERATED_ROUTE_OSRM_ENGINE_API_FBRESULT_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && + FLATBUFFERS_VERSION_MINOR == 3 && + FLATBUFFERS_VERSION_REVISION == 25, + "Non-compatible flatbuffers version included"); + +#include "waypoint_generated.h" + +namespace osrm { +namespace engine { +namespace api { +namespace fbresult { + +struct Metadata; +struct MetadataBuilder; + +struct Annotation; +struct AnnotationBuilder; + +struct StepManeuver; +struct StepManeuverBuilder; + +struct Lane; +struct LaneBuilder; + +struct Intersection; +struct IntersectionBuilder; + +struct Step; +struct StepBuilder; + +struct Leg; +struct LegBuilder; + +struct RouteObject; +struct RouteObjectBuilder; + +enum ManeuverType : int8_t { + ManeuverType_Turn = 0, + ManeuverType_NewName = 1, + ManeuverType_Depart = 2, + ManeuverType_Arrive = 3, + ManeuverType_Merge = 4, + ManeuverType_OnRamp = 5, + ManeuverType_OffRamp = 6, + ManeuverType_Fork = 7, + ManeuverType_EndOfRoad = 8, + ManeuverType_Continue = 9, + ManeuverType_Roundabout = 10, + ManeuverType_Rotary = 11, + ManeuverType_RoundaboutTurn = 12, + ManeuverType_Notification = 13, + ManeuverType_ExitRoundabout = 14, + ManeuverType_ExitRotary = 15, + ManeuverType_MIN = ManeuverType_Turn, + ManeuverType_MAX = ManeuverType_ExitRotary +}; + +inline const ManeuverType (&EnumValuesManeuverType())[16] { + static const ManeuverType values[] = { + ManeuverType_Turn, + ManeuverType_NewName, + ManeuverType_Depart, + ManeuverType_Arrive, + ManeuverType_Merge, + ManeuverType_OnRamp, + ManeuverType_OffRamp, + ManeuverType_Fork, + ManeuverType_EndOfRoad, + ManeuverType_Continue, + ManeuverType_Roundabout, + ManeuverType_Rotary, + ManeuverType_RoundaboutTurn, + ManeuverType_Notification, + ManeuverType_ExitRoundabout, + ManeuverType_ExitRotary + }; + return values; +} + +inline const char * const *EnumNamesManeuverType() { + static const char * const names[17] = { + "Turn", + "NewName", + "Depart", + "Arrive", + "Merge", + "OnRamp", + "OffRamp", + "Fork", + "EndOfRoad", + "Continue", + "Roundabout", + "Rotary", + "RoundaboutTurn", + "Notification", + "ExitRoundabout", + "ExitRotary", + nullptr + }; + return names; +} + +inline const char *EnumNameManeuverType(ManeuverType e) { + if (::flatbuffers::IsOutRange(e, ManeuverType_Turn, ManeuverType_ExitRotary)) return ""; + const size_t index = static_cast(e); + return EnumNamesManeuverType()[index]; +} + +enum Turn : int8_t { + Turn_None = 0, + Turn_UTurn = 1, + Turn_SharpRight = 2, + Turn_Right = 3, + Turn_SlightRight = 4, + Turn_Straight = 5, + Turn_SlightLeft = 6, + Turn_Left = 7, + Turn_SharpLeft = 8, + Turn_MIN = Turn_None, + Turn_MAX = Turn_SharpLeft +}; + +inline const Turn (&EnumValuesTurn())[9] { + static const Turn values[] = { + Turn_None, + Turn_UTurn, + Turn_SharpRight, + Turn_Right, + Turn_SlightRight, + Turn_Straight, + Turn_SlightLeft, + Turn_Left, + Turn_SharpLeft + }; + return values; +} + +inline const char * const *EnumNamesTurn() { + static const char * const names[10] = { + "None", + "UTurn", + "SharpRight", + "Right", + "SlightRight", + "Straight", + "SlightLeft", + "Left", + "SharpLeft", + nullptr + }; + return names; +} + +inline const char *EnumNameTurn(Turn e) { + if (::flatbuffers::IsOutRange(e, Turn_None, Turn_SharpLeft)) return ""; + const size_t index = static_cast(e); + return EnumNamesTurn()[index]; +} + +struct Metadata FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MetadataBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DATASOURCE_NAMES = 4 + }; + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *datasource_names() const { + return GetPointer> *>(VT_DATASOURCE_NAMES); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_DATASOURCE_NAMES) && + verifier.VerifyVector(datasource_names()) && + verifier.VerifyVectorOfStrings(datasource_names()) && + verifier.EndTable(); + } +}; + +struct MetadataBuilder { + typedef Metadata Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_datasource_names(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> datasource_names) { + fbb_.AddOffset(Metadata::VT_DATASOURCE_NAMES, datasource_names); + } + explicit MetadataBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMetadata( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> datasource_names = 0) { + MetadataBuilder builder_(_fbb); + builder_.add_datasource_names(datasource_names); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateMetadataDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *datasource_names = nullptr) { + auto datasource_names__ = datasource_names ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*datasource_names) : 0; + return osrm::engine::api::fbresult::CreateMetadata( + _fbb, + datasource_names__); +} + +struct Annotation FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef AnnotationBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DISTANCE = 4, + VT_DURATION = 6, + VT_DATASOURCES = 8, + VT_NODES = 10, + VT_WEIGHT = 12, + VT_SPEED = 14, + VT_METADATA = 16 + }; + const ::flatbuffers::Vector *distance() const { + return GetPointer *>(VT_DISTANCE); + } + const ::flatbuffers::Vector *duration() const { + return GetPointer *>(VT_DURATION); + } + const ::flatbuffers::Vector *datasources() const { + return GetPointer *>(VT_DATASOURCES); + } + const ::flatbuffers::Vector *nodes() const { + return GetPointer *>(VT_NODES); + } + const ::flatbuffers::Vector *weight() const { + return GetPointer *>(VT_WEIGHT); + } + const ::flatbuffers::Vector *speed() const { + return GetPointer *>(VT_SPEED); + } + const osrm::engine::api::fbresult::Metadata *metadata() const { + return GetPointer(VT_METADATA); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_DISTANCE) && + verifier.VerifyVector(distance()) && + VerifyOffset(verifier, VT_DURATION) && + verifier.VerifyVector(duration()) && + VerifyOffset(verifier, VT_DATASOURCES) && + verifier.VerifyVector(datasources()) && + VerifyOffset(verifier, VT_NODES) && + verifier.VerifyVector(nodes()) && + VerifyOffset(verifier, VT_WEIGHT) && + verifier.VerifyVector(weight()) && + VerifyOffset(verifier, VT_SPEED) && + verifier.VerifyVector(speed()) && + VerifyOffset(verifier, VT_METADATA) && + verifier.VerifyTable(metadata()) && + verifier.EndTable(); + } +}; + +struct AnnotationBuilder { + typedef Annotation Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_distance(::flatbuffers::Offset<::flatbuffers::Vector> distance) { + fbb_.AddOffset(Annotation::VT_DISTANCE, distance); + } + void add_duration(::flatbuffers::Offset<::flatbuffers::Vector> duration) { + fbb_.AddOffset(Annotation::VT_DURATION, duration); + } + void add_datasources(::flatbuffers::Offset<::flatbuffers::Vector> datasources) { + fbb_.AddOffset(Annotation::VT_DATASOURCES, datasources); + } + void add_nodes(::flatbuffers::Offset<::flatbuffers::Vector> nodes) { + fbb_.AddOffset(Annotation::VT_NODES, nodes); + } + void add_weight(::flatbuffers::Offset<::flatbuffers::Vector> weight) { + fbb_.AddOffset(Annotation::VT_WEIGHT, weight); + } + void add_speed(::flatbuffers::Offset<::flatbuffers::Vector> speed) { + fbb_.AddOffset(Annotation::VT_SPEED, speed); + } + void add_metadata(::flatbuffers::Offset metadata) { + fbb_.AddOffset(Annotation::VT_METADATA, metadata); + } + explicit AnnotationBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateAnnotation( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> distance = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> duration = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> datasources = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> nodes = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> weight = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> speed = 0, + ::flatbuffers::Offset metadata = 0) { + AnnotationBuilder builder_(_fbb); + builder_.add_metadata(metadata); + builder_.add_speed(speed); + builder_.add_weight(weight); + builder_.add_nodes(nodes); + builder_.add_datasources(datasources); + builder_.add_duration(duration); + builder_.add_distance(distance); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateAnnotationDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *distance = nullptr, + const std::vector *duration = nullptr, + const std::vector *datasources = nullptr, + const std::vector *nodes = nullptr, + const std::vector *weight = nullptr, + const std::vector *speed = nullptr, + ::flatbuffers::Offset metadata = 0) { + auto distance__ = distance ? _fbb.CreateVector(*distance) : 0; + auto duration__ = duration ? _fbb.CreateVector(*duration) : 0; + auto datasources__ = datasources ? _fbb.CreateVector(*datasources) : 0; + auto nodes__ = nodes ? _fbb.CreateVector(*nodes) : 0; + auto weight__ = weight ? _fbb.CreateVector(*weight) : 0; + auto speed__ = speed ? _fbb.CreateVector(*speed) : 0; + return osrm::engine::api::fbresult::CreateAnnotation( + _fbb, + distance__, + duration__, + datasources__, + nodes__, + weight__, + speed__, + metadata); +} + +struct StepManeuver FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef StepManeuverBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_LOCATION = 4, + VT_BEARING_BEFORE = 6, + VT_BEARING_AFTER = 8, + VT_TYPE = 10, + VT_MODIFIER = 12, + VT_EXIT = 14 + }; + const osrm::engine::api::fbresult::Position *location() const { + return GetStruct(VT_LOCATION); + } + uint16_t bearing_before() const { + return GetField(VT_BEARING_BEFORE, 0); + } + uint16_t bearing_after() const { + return GetField(VT_BEARING_AFTER, 0); + } + osrm::engine::api::fbresult::ManeuverType type() const { + return static_cast(GetField(VT_TYPE, 0)); + } + osrm::engine::api::fbresult::Turn modifier() const { + return static_cast(GetField(VT_MODIFIER, 0)); + } + uint8_t exit() const { + return GetField(VT_EXIT, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_LOCATION, 4) && + VerifyField(verifier, VT_BEARING_BEFORE, 2) && + VerifyField(verifier, VT_BEARING_AFTER, 2) && + VerifyField(verifier, VT_TYPE, 1) && + VerifyField(verifier, VT_MODIFIER, 1) && + VerifyField(verifier, VT_EXIT, 1) && + verifier.EndTable(); + } +}; + +struct StepManeuverBuilder { + typedef StepManeuver Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_location(const osrm::engine::api::fbresult::Position *location) { + fbb_.AddStruct(StepManeuver::VT_LOCATION, location); + } + void add_bearing_before(uint16_t bearing_before) { + fbb_.AddElement(StepManeuver::VT_BEARING_BEFORE, bearing_before, 0); + } + void add_bearing_after(uint16_t bearing_after) { + fbb_.AddElement(StepManeuver::VT_BEARING_AFTER, bearing_after, 0); + } + void add_type(osrm::engine::api::fbresult::ManeuverType type) { + fbb_.AddElement(StepManeuver::VT_TYPE, static_cast(type), 0); + } + void add_modifier(osrm::engine::api::fbresult::Turn modifier) { + fbb_.AddElement(StepManeuver::VT_MODIFIER, static_cast(modifier), 0); + } + void add_exit(uint8_t exit) { + fbb_.AddElement(StepManeuver::VT_EXIT, exit, 0); + } + explicit StepManeuverBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateStepManeuver( + ::flatbuffers::FlatBufferBuilder &_fbb, + const osrm::engine::api::fbresult::Position *location = nullptr, + uint16_t bearing_before = 0, + uint16_t bearing_after = 0, + osrm::engine::api::fbresult::ManeuverType type = osrm::engine::api::fbresult::ManeuverType_Turn, + osrm::engine::api::fbresult::Turn modifier = osrm::engine::api::fbresult::Turn_None, + uint8_t exit = 0) { + StepManeuverBuilder builder_(_fbb); + builder_.add_location(location); + builder_.add_bearing_after(bearing_after); + builder_.add_bearing_before(bearing_before); + builder_.add_exit(exit); + builder_.add_modifier(modifier); + builder_.add_type(type); + return builder_.Finish(); +} + +struct Lane FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef LaneBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_INDICATIONS = 4, + VT_VALID = 6 + }; + const ::flatbuffers::Vector *indications() const { + return GetPointer *>(VT_INDICATIONS); + } + bool valid() const { + return GetField(VT_VALID, 0) != 0; + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_INDICATIONS) && + verifier.VerifyVector(indications()) && + VerifyField(verifier, VT_VALID, 1) && + verifier.EndTable(); + } +}; + +struct LaneBuilder { + typedef Lane Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_indications(::flatbuffers::Offset<::flatbuffers::Vector> indications) { + fbb_.AddOffset(Lane::VT_INDICATIONS, indications); + } + void add_valid(bool valid) { + fbb_.AddElement(Lane::VT_VALID, static_cast(valid), 0); + } + explicit LaneBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateLane( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> indications = 0, + bool valid = false) { + LaneBuilder builder_(_fbb); + builder_.add_indications(indications); + builder_.add_valid(valid); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateLaneDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *indications = nullptr, + bool valid = false) { + auto indications__ = indications ? _fbb.CreateVector(*indications) : 0; + return osrm::engine::api::fbresult::CreateLane( + _fbb, + indications__, + valid); +} + +struct Intersection FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef IntersectionBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_LOCATION = 4, + VT_BEARINGS = 6, + VT_CLASSES = 8, + VT_ENTRY = 10, + VT_IN_BEARING = 12, + VT_OUT_BEARING = 14, + VT_LANES = 16 + }; + const osrm::engine::api::fbresult::Position *location() const { + return GetStruct(VT_LOCATION); + } + const ::flatbuffers::Vector *bearings() const { + return GetPointer *>(VT_BEARINGS); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *classes() const { + return GetPointer> *>(VT_CLASSES); + } + const ::flatbuffers::Vector *entry() const { + return GetPointer *>(VT_ENTRY); + } + uint32_t in_bearing() const { + return GetField(VT_IN_BEARING, 0); + } + uint32_t out_bearing() const { + return GetField(VT_OUT_BEARING, 0); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *lanes() const { + return GetPointer> *>(VT_LANES); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_LOCATION, 4) && + VerifyOffset(verifier, VT_BEARINGS) && + verifier.VerifyVector(bearings()) && + VerifyOffset(verifier, VT_CLASSES) && + verifier.VerifyVector(classes()) && + verifier.VerifyVectorOfStrings(classes()) && + VerifyOffset(verifier, VT_ENTRY) && + verifier.VerifyVector(entry()) && + VerifyField(verifier, VT_IN_BEARING, 4) && + VerifyField(verifier, VT_OUT_BEARING, 4) && + VerifyOffset(verifier, VT_LANES) && + verifier.VerifyVector(lanes()) && + verifier.VerifyVectorOfTables(lanes()) && + verifier.EndTable(); + } +}; + +struct IntersectionBuilder { + typedef Intersection Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_location(const osrm::engine::api::fbresult::Position *location) { + fbb_.AddStruct(Intersection::VT_LOCATION, location); + } + void add_bearings(::flatbuffers::Offset<::flatbuffers::Vector> bearings) { + fbb_.AddOffset(Intersection::VT_BEARINGS, bearings); + } + void add_classes(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> classes) { + fbb_.AddOffset(Intersection::VT_CLASSES, classes); + } + void add_entry(::flatbuffers::Offset<::flatbuffers::Vector> entry) { + fbb_.AddOffset(Intersection::VT_ENTRY, entry); + } + void add_in_bearing(uint32_t in_bearing) { + fbb_.AddElement(Intersection::VT_IN_BEARING, in_bearing, 0); + } + void add_out_bearing(uint32_t out_bearing) { + fbb_.AddElement(Intersection::VT_OUT_BEARING, out_bearing, 0); + } + void add_lanes(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> lanes) { + fbb_.AddOffset(Intersection::VT_LANES, lanes); + } + explicit IntersectionBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateIntersection( + ::flatbuffers::FlatBufferBuilder &_fbb, + const osrm::engine::api::fbresult::Position *location = nullptr, + ::flatbuffers::Offset<::flatbuffers::Vector> bearings = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> classes = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> entry = 0, + uint32_t in_bearing = 0, + uint32_t out_bearing = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> lanes = 0) { + IntersectionBuilder builder_(_fbb); + builder_.add_lanes(lanes); + builder_.add_out_bearing(out_bearing); + builder_.add_in_bearing(in_bearing); + builder_.add_entry(entry); + builder_.add_classes(classes); + builder_.add_bearings(bearings); + builder_.add_location(location); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateIntersectionDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const osrm::engine::api::fbresult::Position *location = nullptr, + const std::vector *bearings = nullptr, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *classes = nullptr, + const std::vector *entry = nullptr, + uint32_t in_bearing = 0, + uint32_t out_bearing = 0, + const std::vector<::flatbuffers::Offset> *lanes = nullptr) { + auto bearings__ = bearings ? _fbb.CreateVector(*bearings) : 0; + auto classes__ = classes ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*classes) : 0; + auto entry__ = entry ? _fbb.CreateVector(*entry) : 0; + auto lanes__ = lanes ? _fbb.CreateVector<::flatbuffers::Offset>(*lanes) : 0; + return osrm::engine::api::fbresult::CreateIntersection( + _fbb, + location, + bearings__, + classes__, + entry__, + in_bearing, + out_bearing, + lanes__); +} + +struct Step FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef StepBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DISTANCE = 4, + VT_DURATION = 6, + VT_POLYLINE = 8, + VT_COORDINATES = 10, + VT_WEIGHT = 12, + VT_NAME = 14, + VT_REF = 16, + VT_PRONUNCIATION = 18, + VT_DESTINATIONS = 20, + VT_EXITS = 22, + VT_MODE = 24, + VT_MANEUVER = 26, + VT_INTERSECTIONS = 28, + VT_ROTARY_NAME = 30, + VT_ROTARY_PRONUNCIATION = 32, + VT_DRIVING_SIDE = 34 + }; + float distance() const { + return GetField(VT_DISTANCE, 0.0f); + } + float duration() const { + return GetField(VT_DURATION, 0.0f); + } + const ::flatbuffers::String *polyline() const { + return GetPointer(VT_POLYLINE); + } + const ::flatbuffers::Vector *coordinates() const { + return GetPointer *>(VT_COORDINATES); + } + float weight() const { + return GetField(VT_WEIGHT, 0.0f); + } + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + const ::flatbuffers::String *ref() const { + return GetPointer(VT_REF); + } + const ::flatbuffers::String *pronunciation() const { + return GetPointer(VT_PRONUNCIATION); + } + const ::flatbuffers::String *destinations() const { + return GetPointer(VT_DESTINATIONS); + } + const ::flatbuffers::String *exits() const { + return GetPointer(VT_EXITS); + } + const ::flatbuffers::String *mode() const { + return GetPointer(VT_MODE); + } + const osrm::engine::api::fbresult::StepManeuver *maneuver() const { + return GetPointer(VT_MANEUVER); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *intersections() const { + return GetPointer> *>(VT_INTERSECTIONS); + } + const ::flatbuffers::String *rotary_name() const { + return GetPointer(VT_ROTARY_NAME); + } + const ::flatbuffers::String *rotary_pronunciation() const { + return GetPointer(VT_ROTARY_PRONUNCIATION); + } + bool driving_side() const { + return GetField(VT_DRIVING_SIDE, 0) != 0; + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_DISTANCE, 4) && + VerifyField(verifier, VT_DURATION, 4) && + VerifyOffset(verifier, VT_POLYLINE) && + verifier.VerifyString(polyline()) && + VerifyOffset(verifier, VT_COORDINATES) && + verifier.VerifyVector(coordinates()) && + VerifyField(verifier, VT_WEIGHT, 4) && + VerifyOffset(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_REF) && + verifier.VerifyString(ref()) && + VerifyOffset(verifier, VT_PRONUNCIATION) && + verifier.VerifyString(pronunciation()) && + VerifyOffset(verifier, VT_DESTINATIONS) && + verifier.VerifyString(destinations()) && + VerifyOffset(verifier, VT_EXITS) && + verifier.VerifyString(exits()) && + VerifyOffset(verifier, VT_MODE) && + verifier.VerifyString(mode()) && + VerifyOffset(verifier, VT_MANEUVER) && + verifier.VerifyTable(maneuver()) && + VerifyOffset(verifier, VT_INTERSECTIONS) && + verifier.VerifyVector(intersections()) && + verifier.VerifyVectorOfTables(intersections()) && + VerifyOffset(verifier, VT_ROTARY_NAME) && + verifier.VerifyString(rotary_name()) && + VerifyOffset(verifier, VT_ROTARY_PRONUNCIATION) && + verifier.VerifyString(rotary_pronunciation()) && + VerifyField(verifier, VT_DRIVING_SIDE, 1) && + verifier.EndTable(); + } +}; + +struct StepBuilder { + typedef Step Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_distance(float distance) { + fbb_.AddElement(Step::VT_DISTANCE, distance, 0.0f); + } + void add_duration(float duration) { + fbb_.AddElement(Step::VT_DURATION, duration, 0.0f); + } + void add_polyline(::flatbuffers::Offset<::flatbuffers::String> polyline) { + fbb_.AddOffset(Step::VT_POLYLINE, polyline); + } + void add_coordinates(::flatbuffers::Offset<::flatbuffers::Vector> coordinates) { + fbb_.AddOffset(Step::VT_COORDINATES, coordinates); + } + void add_weight(float weight) { + fbb_.AddElement(Step::VT_WEIGHT, weight, 0.0f); + } + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Step::VT_NAME, name); + } + void add_ref(::flatbuffers::Offset<::flatbuffers::String> ref) { + fbb_.AddOffset(Step::VT_REF, ref); + } + void add_pronunciation(::flatbuffers::Offset<::flatbuffers::String> pronunciation) { + fbb_.AddOffset(Step::VT_PRONUNCIATION, pronunciation); + } + void add_destinations(::flatbuffers::Offset<::flatbuffers::String> destinations) { + fbb_.AddOffset(Step::VT_DESTINATIONS, destinations); + } + void add_exits(::flatbuffers::Offset<::flatbuffers::String> exits) { + fbb_.AddOffset(Step::VT_EXITS, exits); + } + void add_mode(::flatbuffers::Offset<::flatbuffers::String> mode) { + fbb_.AddOffset(Step::VT_MODE, mode); + } + void add_maneuver(::flatbuffers::Offset maneuver) { + fbb_.AddOffset(Step::VT_MANEUVER, maneuver); + } + void add_intersections(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> intersections) { + fbb_.AddOffset(Step::VT_INTERSECTIONS, intersections); + } + void add_rotary_name(::flatbuffers::Offset<::flatbuffers::String> rotary_name) { + fbb_.AddOffset(Step::VT_ROTARY_NAME, rotary_name); + } + void add_rotary_pronunciation(::flatbuffers::Offset<::flatbuffers::String> rotary_pronunciation) { + fbb_.AddOffset(Step::VT_ROTARY_PRONUNCIATION, rotary_pronunciation); + } + void add_driving_side(bool driving_side) { + fbb_.AddElement(Step::VT_DRIVING_SIDE, static_cast(driving_side), 0); + } + explicit StepBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateStep( + ::flatbuffers::FlatBufferBuilder &_fbb, + float distance = 0.0f, + float duration = 0.0f, + ::flatbuffers::Offset<::flatbuffers::String> polyline = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> coordinates = 0, + float weight = 0.0f, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::String> ref = 0, + ::flatbuffers::Offset<::flatbuffers::String> pronunciation = 0, + ::flatbuffers::Offset<::flatbuffers::String> destinations = 0, + ::flatbuffers::Offset<::flatbuffers::String> exits = 0, + ::flatbuffers::Offset<::flatbuffers::String> mode = 0, + ::flatbuffers::Offset maneuver = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> intersections = 0, + ::flatbuffers::Offset<::flatbuffers::String> rotary_name = 0, + ::flatbuffers::Offset<::flatbuffers::String> rotary_pronunciation = 0, + bool driving_side = false) { + StepBuilder builder_(_fbb); + builder_.add_rotary_pronunciation(rotary_pronunciation); + builder_.add_rotary_name(rotary_name); + builder_.add_intersections(intersections); + builder_.add_maneuver(maneuver); + builder_.add_mode(mode); + builder_.add_exits(exits); + builder_.add_destinations(destinations); + builder_.add_pronunciation(pronunciation); + builder_.add_ref(ref); + builder_.add_name(name); + builder_.add_weight(weight); + builder_.add_coordinates(coordinates); + builder_.add_polyline(polyline); + builder_.add_duration(duration); + builder_.add_distance(distance); + builder_.add_driving_side(driving_side); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateStepDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + float distance = 0.0f, + float duration = 0.0f, + const char *polyline = nullptr, + const std::vector *coordinates = nullptr, + float weight = 0.0f, + const char *name = nullptr, + const char *ref = nullptr, + const char *pronunciation = nullptr, + const char *destinations = nullptr, + const char *exits = nullptr, + const char *mode = nullptr, + ::flatbuffers::Offset maneuver = 0, + const std::vector<::flatbuffers::Offset> *intersections = nullptr, + const char *rotary_name = nullptr, + const char *rotary_pronunciation = nullptr, + bool driving_side = false) { + auto polyline__ = polyline ? _fbb.CreateString(polyline) : 0; + auto coordinates__ = coordinates ? _fbb.CreateVectorOfStructs(*coordinates) : 0; + auto name__ = name ? _fbb.CreateString(name) : 0; + auto ref__ = ref ? _fbb.CreateString(ref) : 0; + auto pronunciation__ = pronunciation ? _fbb.CreateString(pronunciation) : 0; + auto destinations__ = destinations ? _fbb.CreateString(destinations) : 0; + auto exits__ = exits ? _fbb.CreateString(exits) : 0; + auto mode__ = mode ? _fbb.CreateString(mode) : 0; + auto intersections__ = intersections ? _fbb.CreateVector<::flatbuffers::Offset>(*intersections) : 0; + auto rotary_name__ = rotary_name ? _fbb.CreateString(rotary_name) : 0; + auto rotary_pronunciation__ = rotary_pronunciation ? _fbb.CreateString(rotary_pronunciation) : 0; + return osrm::engine::api::fbresult::CreateStep( + _fbb, + distance, + duration, + polyline__, + coordinates__, + weight, + name__, + ref__, + pronunciation__, + destinations__, + exits__, + mode__, + maneuver, + intersections__, + rotary_name__, + rotary_pronunciation__, + driving_side); +} + +struct Leg FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef LegBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DISTANCE = 4, + VT_DURATION = 6, + VT_WEIGHT = 8, + VT_SUMMARY = 10, + VT_ANNOTATIONS = 12, + VT_STEPS = 14 + }; + double distance() const { + return GetField(VT_DISTANCE, 0.0); + } + double duration() const { + return GetField(VT_DURATION, 0.0); + } + double weight() const { + return GetField(VT_WEIGHT, 0.0); + } + const ::flatbuffers::String *summary() const { + return GetPointer(VT_SUMMARY); + } + const osrm::engine::api::fbresult::Annotation *annotations() const { + return GetPointer(VT_ANNOTATIONS); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *steps() const { + return GetPointer> *>(VT_STEPS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_DISTANCE, 8) && + VerifyField(verifier, VT_DURATION, 8) && + VerifyField(verifier, VT_WEIGHT, 8) && + VerifyOffset(verifier, VT_SUMMARY) && + verifier.VerifyString(summary()) && + VerifyOffset(verifier, VT_ANNOTATIONS) && + verifier.VerifyTable(annotations()) && + VerifyOffset(verifier, VT_STEPS) && + verifier.VerifyVector(steps()) && + verifier.VerifyVectorOfTables(steps()) && + verifier.EndTable(); + } +}; + +struct LegBuilder { + typedef Leg Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_distance(double distance) { + fbb_.AddElement(Leg::VT_DISTANCE, distance, 0.0); + } + void add_duration(double duration) { + fbb_.AddElement(Leg::VT_DURATION, duration, 0.0); + } + void add_weight(double weight) { + fbb_.AddElement(Leg::VT_WEIGHT, weight, 0.0); + } + void add_summary(::flatbuffers::Offset<::flatbuffers::String> summary) { + fbb_.AddOffset(Leg::VT_SUMMARY, summary); + } + void add_annotations(::flatbuffers::Offset annotations) { + fbb_.AddOffset(Leg::VT_ANNOTATIONS, annotations); + } + void add_steps(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> steps) { + fbb_.AddOffset(Leg::VT_STEPS, steps); + } + explicit LegBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateLeg( + ::flatbuffers::FlatBufferBuilder &_fbb, + double distance = 0.0, + double duration = 0.0, + double weight = 0.0, + ::flatbuffers::Offset<::flatbuffers::String> summary = 0, + ::flatbuffers::Offset annotations = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> steps = 0) { + LegBuilder builder_(_fbb); + builder_.add_weight(weight); + builder_.add_duration(duration); + builder_.add_distance(distance); + builder_.add_steps(steps); + builder_.add_annotations(annotations); + builder_.add_summary(summary); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateLegDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + double distance = 0.0, + double duration = 0.0, + double weight = 0.0, + const char *summary = nullptr, + ::flatbuffers::Offset annotations = 0, + const std::vector<::flatbuffers::Offset> *steps = nullptr) { + auto summary__ = summary ? _fbb.CreateString(summary) : 0; + auto steps__ = steps ? _fbb.CreateVector<::flatbuffers::Offset>(*steps) : 0; + return osrm::engine::api::fbresult::CreateLeg( + _fbb, + distance, + duration, + weight, + summary__, + annotations, + steps__); +} + +struct RouteObject FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef RouteObjectBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DISTANCE = 4, + VT_DURATION = 6, + VT_WEIGHT = 8, + VT_WEIGHT_NAME = 10, + VT_CONFIDENCE = 12, + VT_POLYLINE = 14, + VT_COORDINATES = 16, + VT_LEGS = 18 + }; + float distance() const { + return GetField(VT_DISTANCE, 0.0f); + } + float duration() const { + return GetField(VT_DURATION, 0.0f); + } + float weight() const { + return GetField(VT_WEIGHT, 0.0f); + } + const ::flatbuffers::String *weight_name() const { + return GetPointer(VT_WEIGHT_NAME); + } + float confidence() const { + return GetField(VT_CONFIDENCE, 0.0f); + } + const ::flatbuffers::String *polyline() const { + return GetPointer(VT_POLYLINE); + } + const ::flatbuffers::Vector *coordinates() const { + return GetPointer *>(VT_COORDINATES); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *legs() const { + return GetPointer> *>(VT_LEGS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_DISTANCE, 4) && + VerifyField(verifier, VT_DURATION, 4) && + VerifyField(verifier, VT_WEIGHT, 4) && + VerifyOffset(verifier, VT_WEIGHT_NAME) && + verifier.VerifyString(weight_name()) && + VerifyField(verifier, VT_CONFIDENCE, 4) && + VerifyOffset(verifier, VT_POLYLINE) && + verifier.VerifyString(polyline()) && + VerifyOffset(verifier, VT_COORDINATES) && + verifier.VerifyVector(coordinates()) && + VerifyOffset(verifier, VT_LEGS) && + verifier.VerifyVector(legs()) && + verifier.VerifyVectorOfTables(legs()) && + verifier.EndTable(); + } +}; + +struct RouteObjectBuilder { + typedef RouteObject Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_distance(float distance) { + fbb_.AddElement(RouteObject::VT_DISTANCE, distance, 0.0f); + } + void add_duration(float duration) { + fbb_.AddElement(RouteObject::VT_DURATION, duration, 0.0f); + } + void add_weight(float weight) { + fbb_.AddElement(RouteObject::VT_WEIGHT, weight, 0.0f); + } + void add_weight_name(::flatbuffers::Offset<::flatbuffers::String> weight_name) { + fbb_.AddOffset(RouteObject::VT_WEIGHT_NAME, weight_name); + } + void add_confidence(float confidence) { + fbb_.AddElement(RouteObject::VT_CONFIDENCE, confidence, 0.0f); + } + void add_polyline(::flatbuffers::Offset<::flatbuffers::String> polyline) { + fbb_.AddOffset(RouteObject::VT_POLYLINE, polyline); + } + void add_coordinates(::flatbuffers::Offset<::flatbuffers::Vector> coordinates) { + fbb_.AddOffset(RouteObject::VT_COORDINATES, coordinates); + } + void add_legs(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> legs) { + fbb_.AddOffset(RouteObject::VT_LEGS, legs); + } + explicit RouteObjectBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateRouteObject( + ::flatbuffers::FlatBufferBuilder &_fbb, + float distance = 0.0f, + float duration = 0.0f, + float weight = 0.0f, + ::flatbuffers::Offset<::flatbuffers::String> weight_name = 0, + float confidence = 0.0f, + ::flatbuffers::Offset<::flatbuffers::String> polyline = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> coordinates = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> legs = 0) { + RouteObjectBuilder builder_(_fbb); + builder_.add_legs(legs); + builder_.add_coordinates(coordinates); + builder_.add_polyline(polyline); + builder_.add_confidence(confidence); + builder_.add_weight_name(weight_name); + builder_.add_weight(weight); + builder_.add_duration(duration); + builder_.add_distance(distance); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateRouteObjectDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + float distance = 0.0f, + float duration = 0.0f, + float weight = 0.0f, + const char *weight_name = nullptr, + float confidence = 0.0f, + const char *polyline = nullptr, + const std::vector *coordinates = nullptr, + const std::vector<::flatbuffers::Offset> *legs = nullptr) { + auto weight_name__ = weight_name ? _fbb.CreateString(weight_name) : 0; + auto polyline__ = polyline ? _fbb.CreateString(polyline) : 0; + auto coordinates__ = coordinates ? _fbb.CreateVectorOfStructs(*coordinates) : 0; + auto legs__ = legs ? _fbb.CreateVector<::flatbuffers::Offset>(*legs) : 0; + return osrm::engine::api::fbresult::CreateRouteObject( + _fbb, + distance, + duration, + weight, + weight_name__, + confidence, + polyline__, + coordinates__, + legs__); +} + +} // namespace fbresult +} // namespace api +} // namespace engine +} // namespace osrm + +#endif // FLATBUFFERS_GENERATED_ROUTE_OSRM_ENGINE_API_FBRESULT_H_ diff --git a/include/engine/api/flatbuffers/table.fbs b/generated/include/engine/api/flatbuffers/table.fbs similarity index 91% rename from include/engine/api/flatbuffers/table.fbs rename to generated/include/engine/api/flatbuffers/table.fbs index caf1855e6cf..0cbd947bc4b 100644 --- a/include/engine/api/flatbuffers/table.fbs +++ b/generated/include/engine/api/flatbuffers/table.fbs @@ -1,7 +1,7 @@ include "waypoint.fbs"; namespace osrm.engine.api.fbresult; -table Table { +table TableResult { durations: [float]; rows: ushort; cols: ushort; diff --git a/generated/include/engine/api/flatbuffers/table_generated.h b/generated/include/engine/api/flatbuffers/table_generated.h new file mode 100644 index 00000000000..30c6bd81ca8 --- /dev/null +++ b/generated/include/engine/api/flatbuffers/table_generated.h @@ -0,0 +1,149 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_TABLE_OSRM_ENGINE_API_FBRESULT_H_ +#define FLATBUFFERS_GENERATED_TABLE_OSRM_ENGINE_API_FBRESULT_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && + FLATBUFFERS_VERSION_MINOR == 3 && + FLATBUFFERS_VERSION_REVISION == 25, + "Non-compatible flatbuffers version included"); + +#include "waypoint_generated.h" + +namespace osrm { +namespace engine { +namespace api { +namespace fbresult { + +struct TableResult; +struct TableResultBuilder; + +struct TableResult FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TableResultBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DURATIONS = 4, + VT_ROWS = 6, + VT_COLS = 8, + VT_DISTANCES = 10, + VT_DESTINATIONS = 12, + VT_FALLBACK_SPEED_CELLS = 14 + }; + const ::flatbuffers::Vector *durations() const { + return GetPointer *>(VT_DURATIONS); + } + uint16_t rows() const { + return GetField(VT_ROWS, 0); + } + uint16_t cols() const { + return GetField(VT_COLS, 0); + } + const ::flatbuffers::Vector *distances() const { + return GetPointer *>(VT_DISTANCES); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *destinations() const { + return GetPointer> *>(VT_DESTINATIONS); + } + const ::flatbuffers::Vector *fallback_speed_cells() const { + return GetPointer *>(VT_FALLBACK_SPEED_CELLS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_DURATIONS) && + verifier.VerifyVector(durations()) && + VerifyField(verifier, VT_ROWS, 2) && + VerifyField(verifier, VT_COLS, 2) && + VerifyOffset(verifier, VT_DISTANCES) && + verifier.VerifyVector(distances()) && + VerifyOffset(verifier, VT_DESTINATIONS) && + verifier.VerifyVector(destinations()) && + verifier.VerifyVectorOfTables(destinations()) && + VerifyOffset(verifier, VT_FALLBACK_SPEED_CELLS) && + verifier.VerifyVector(fallback_speed_cells()) && + verifier.EndTable(); + } +}; + +struct TableResultBuilder { + typedef TableResult Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_durations(::flatbuffers::Offset<::flatbuffers::Vector> durations) { + fbb_.AddOffset(TableResult::VT_DURATIONS, durations); + } + void add_rows(uint16_t rows) { + fbb_.AddElement(TableResult::VT_ROWS, rows, 0); + } + void add_cols(uint16_t cols) { + fbb_.AddElement(TableResult::VT_COLS, cols, 0); + } + void add_distances(::flatbuffers::Offset<::flatbuffers::Vector> distances) { + fbb_.AddOffset(TableResult::VT_DISTANCES, distances); + } + void add_destinations(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> destinations) { + fbb_.AddOffset(TableResult::VT_DESTINATIONS, destinations); + } + void add_fallback_speed_cells(::flatbuffers::Offset<::flatbuffers::Vector> fallback_speed_cells) { + fbb_.AddOffset(TableResult::VT_FALLBACK_SPEED_CELLS, fallback_speed_cells); + } + explicit TableResultBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTableResult( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> durations = 0, + uint16_t rows = 0, + uint16_t cols = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> distances = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> destinations = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> fallback_speed_cells = 0) { + TableResultBuilder builder_(_fbb); + builder_.add_fallback_speed_cells(fallback_speed_cells); + builder_.add_destinations(destinations); + builder_.add_distances(distances); + builder_.add_durations(durations); + builder_.add_cols(cols); + builder_.add_rows(rows); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTableResultDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *durations = nullptr, + uint16_t rows = 0, + uint16_t cols = 0, + const std::vector *distances = nullptr, + const std::vector<::flatbuffers::Offset> *destinations = nullptr, + const std::vector *fallback_speed_cells = nullptr) { + auto durations__ = durations ? _fbb.CreateVector(*durations) : 0; + auto distances__ = distances ? _fbb.CreateVector(*distances) : 0; + auto destinations__ = destinations ? _fbb.CreateVector<::flatbuffers::Offset>(*destinations) : 0; + auto fallback_speed_cells__ = fallback_speed_cells ? _fbb.CreateVector(*fallback_speed_cells) : 0; + return osrm::engine::api::fbresult::CreateTableResult( + _fbb, + durations__, + rows, + cols, + distances__, + destinations__, + fallback_speed_cells__); +} + +} // namespace fbresult +} // namespace api +} // namespace engine +} // namespace osrm + +#endif // FLATBUFFERS_GENERATED_TABLE_OSRM_ENGINE_API_FBRESULT_H_ diff --git a/include/engine/api/flatbuffers/waypoint.fbs b/generated/include/engine/api/flatbuffers/waypoint.fbs similarity index 100% rename from include/engine/api/flatbuffers/waypoint.fbs rename to generated/include/engine/api/flatbuffers/waypoint.fbs diff --git a/generated/include/engine/api/flatbuffers/waypoint_generated.h b/generated/include/engine/api/flatbuffers/waypoint_generated.h new file mode 100644 index 00000000000..3fae94975d7 --- /dev/null +++ b/generated/include/engine/api/flatbuffers/waypoint_generated.h @@ -0,0 +1,205 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_WAYPOINT_OSRM_ENGINE_API_FBRESULT_H_ +#define FLATBUFFERS_GENERATED_WAYPOINT_OSRM_ENGINE_API_FBRESULT_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && + FLATBUFFERS_VERSION_MINOR == 3 && + FLATBUFFERS_VERSION_REVISION == 25, + "Non-compatible flatbuffers version included"); + +#include "position_generated.h" + +namespace osrm { +namespace engine { +namespace api { +namespace fbresult { + +struct Uint64Pair; + +struct Waypoint; +struct WaypointBuilder; + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Uint64Pair FLATBUFFERS_FINAL_CLASS { + private: + uint64_t first_; + uint64_t second_; + + public: + Uint64Pair() + : first_(0), + second_(0) { + } + Uint64Pair(uint64_t _first, uint64_t _second) + : first_(::flatbuffers::EndianScalar(_first)), + second_(::flatbuffers::EndianScalar(_second)) { + } + uint64_t first() const { + return ::flatbuffers::EndianScalar(first_); + } + uint64_t second() const { + return ::flatbuffers::EndianScalar(second_); + } +}; +FLATBUFFERS_STRUCT_END(Uint64Pair, 16); + +struct Waypoint FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef WaypointBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_HINT = 4, + VT_DISTANCE = 6, + VT_NAME = 8, + VT_LOCATION = 10, + VT_NODES = 12, + VT_MATCHINGS_INDEX = 14, + VT_WAYPOINT_INDEX = 16, + VT_ALTERNATIVES_COUNT = 18, + VT_TRIPS_INDEX = 20 + }; + const ::flatbuffers::String *hint() const { + return GetPointer(VT_HINT); + } + float distance() const { + return GetField(VT_DISTANCE, 0.0f); + } + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + const osrm::engine::api::fbresult::Position *location() const { + return GetStruct(VT_LOCATION); + } + const osrm::engine::api::fbresult::Uint64Pair *nodes() const { + return GetStruct(VT_NODES); + } + uint32_t matchings_index() const { + return GetField(VT_MATCHINGS_INDEX, 0); + } + uint32_t waypoint_index() const { + return GetField(VT_WAYPOINT_INDEX, 0); + } + uint32_t alternatives_count() const { + return GetField(VT_ALTERNATIVES_COUNT, 0); + } + uint32_t trips_index() const { + return GetField(VT_TRIPS_INDEX, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_HINT) && + verifier.VerifyString(hint()) && + VerifyField(verifier, VT_DISTANCE, 4) && + VerifyOffset(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyField(verifier, VT_LOCATION, 4) && + VerifyField(verifier, VT_NODES, 8) && + VerifyField(verifier, VT_MATCHINGS_INDEX, 4) && + VerifyField(verifier, VT_WAYPOINT_INDEX, 4) && + VerifyField(verifier, VT_ALTERNATIVES_COUNT, 4) && + VerifyField(verifier, VT_TRIPS_INDEX, 4) && + verifier.EndTable(); + } +}; + +struct WaypointBuilder { + typedef Waypoint Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_hint(::flatbuffers::Offset<::flatbuffers::String> hint) { + fbb_.AddOffset(Waypoint::VT_HINT, hint); + } + void add_distance(float distance) { + fbb_.AddElement(Waypoint::VT_DISTANCE, distance, 0.0f); + } + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Waypoint::VT_NAME, name); + } + void add_location(const osrm::engine::api::fbresult::Position *location) { + fbb_.AddStruct(Waypoint::VT_LOCATION, location); + } + void add_nodes(const osrm::engine::api::fbresult::Uint64Pair *nodes) { + fbb_.AddStruct(Waypoint::VT_NODES, nodes); + } + void add_matchings_index(uint32_t matchings_index) { + fbb_.AddElement(Waypoint::VT_MATCHINGS_INDEX, matchings_index, 0); + } + void add_waypoint_index(uint32_t waypoint_index) { + fbb_.AddElement(Waypoint::VT_WAYPOINT_INDEX, waypoint_index, 0); + } + void add_alternatives_count(uint32_t alternatives_count) { + fbb_.AddElement(Waypoint::VT_ALTERNATIVES_COUNT, alternatives_count, 0); + } + void add_trips_index(uint32_t trips_index) { + fbb_.AddElement(Waypoint::VT_TRIPS_INDEX, trips_index, 0); + } + explicit WaypointBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateWaypoint( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> hint = 0, + float distance = 0.0f, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + const osrm::engine::api::fbresult::Position *location = nullptr, + const osrm::engine::api::fbresult::Uint64Pair *nodes = nullptr, + uint32_t matchings_index = 0, + uint32_t waypoint_index = 0, + uint32_t alternatives_count = 0, + uint32_t trips_index = 0) { + WaypointBuilder builder_(_fbb); + builder_.add_trips_index(trips_index); + builder_.add_alternatives_count(alternatives_count); + builder_.add_waypoint_index(waypoint_index); + builder_.add_matchings_index(matchings_index); + builder_.add_nodes(nodes); + builder_.add_location(location); + builder_.add_name(name); + builder_.add_distance(distance); + builder_.add_hint(hint); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateWaypointDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *hint = nullptr, + float distance = 0.0f, + const char *name = nullptr, + const osrm::engine::api::fbresult::Position *location = nullptr, + const osrm::engine::api::fbresult::Uint64Pair *nodes = nullptr, + uint32_t matchings_index = 0, + uint32_t waypoint_index = 0, + uint32_t alternatives_count = 0, + uint32_t trips_index = 0) { + auto hint__ = hint ? _fbb.CreateString(hint) : 0; + auto name__ = name ? _fbb.CreateString(name) : 0; + return osrm::engine::api::fbresult::CreateWaypoint( + _fbb, + hint__, + distance, + name__, + location, + nodes, + matchings_index, + waypoint_index, + alternatives_count, + trips_index); +} + +} // namespace fbresult +} // namespace api +} // namespace engine +} // namespace osrm + +#endif // FLATBUFFERS_GENERATED_WAYPOINT_OSRM_ENGINE_API_FBRESULT_H_ diff --git a/include/engine/api/flatbuffers/fbresult_generated.h b/include/engine/api/flatbuffers/fbresult_generated.h deleted file mode 100644 index ec569002248..00000000000 --- a/include/engine/api/flatbuffers/fbresult_generated.h +++ /dev/null @@ -1,2433 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify - - -#ifndef FLATBUFFERS_GENERATED_FBRESULT_OSRM_ENGINE_API_FBRESULT_H_ -#define FLATBUFFERS_GENERATED_FBRESULT_OSRM_ENGINE_API_FBRESULT_H_ - -#include "flatbuffers/flatbuffers.h" - -namespace osrm::engine::api::fbresult { - -struct Position; - -struct Uint64Pair; - -struct Waypoint; -struct WaypointT; - -struct Metadata; -struct MetadataT; - -struct Annotation; -struct AnnotationT; - -struct StepManeuver; -struct StepManeuverT; - -struct Lane; -struct LaneT; - -struct Intersection; -struct IntersectionT; - -struct Step; -struct StepT; - -struct Leg; -struct LegT; - -struct RouteObject; -struct RouteObjectT; - -struct Table; -struct TableT; - -struct Error; -struct ErrorT; - -struct FBResult; -struct FBResultT; - -enum ManeuverType { - ManeuverType_Turn = 0, - ManeuverType_NewName = 1, - ManeuverType_Depart = 2, - ManeuverType_Arrive = 3, - ManeuverType_Merge = 4, - ManeuverType_OnRamp = 5, - ManeuverType_OffRamp = 6, - ManeuverType_Fork = 7, - ManeuverType_EndOfRoad = 8, - ManeuverType_Continue = 9, - ManeuverType_Roundabout = 10, - ManeuverType_Rotary = 11, - ManeuverType_RoundaboutTurn = 12, - ManeuverType_Notification = 13, - ManeuverType_ExitRoundabout = 14, - ManeuverType_ExitRotary = 15, - ManeuverType_MIN = ManeuverType_Turn, - ManeuverType_MAX = ManeuverType_ExitRotary -}; - -inline const ManeuverType (&EnumValuesManeuverType())[16] { - static const ManeuverType values[] = { - ManeuverType_Turn, - ManeuverType_NewName, - ManeuverType_Depart, - ManeuverType_Arrive, - ManeuverType_Merge, - ManeuverType_OnRamp, - ManeuverType_OffRamp, - ManeuverType_Fork, - ManeuverType_EndOfRoad, - ManeuverType_Continue, - ManeuverType_Roundabout, - ManeuverType_Rotary, - ManeuverType_RoundaboutTurn, - ManeuverType_Notification, - ManeuverType_ExitRoundabout, - ManeuverType_ExitRotary - }; - return values; -} - -inline const char * const *EnumNamesManeuverType() { - static const char * const names[17] = { - "Turn", - "NewName", - "Depart", - "Arrive", - "Merge", - "OnRamp", - "OffRamp", - "Fork", - "EndOfRoad", - "Continue", - "Roundabout", - "Rotary", - "RoundaboutTurn", - "Notification", - "ExitRoundabout", - "ExitRotary", - nullptr - }; - return names; -} - -inline const char *EnumNameManeuverType(ManeuverType e) { - if (e < ManeuverType_Turn || e > ManeuverType_ExitRotary) return ""; - const size_t index = static_cast(e); - return EnumNamesManeuverType()[index]; -} - -enum Turn { - Turn_None = 0, - Turn_UTurn = 1, - Turn_SharpRight = 2, - Turn_Right = 3, - Turn_SlightRight = 4, - Turn_Straight = 5, - Turn_SlightLeft = 6, - Turn_Left = 7, - Turn_SharpLeft = 8, - Turn_MIN = Turn_None, - Turn_MAX = Turn_SharpLeft -}; - -inline const Turn (&EnumValuesTurn())[9] { - static const Turn values[] = { - Turn_None, - Turn_UTurn, - Turn_SharpRight, - Turn_Right, - Turn_SlightRight, - Turn_Straight, - Turn_SlightLeft, - Turn_Left, - Turn_SharpLeft - }; - return values; -} - -inline const char * const *EnumNamesTurn() { - static const char * const names[10] = { - "None", - "UTurn", - "SharpRight", - "Right", - "SlightRight", - "Straight", - "SlightLeft", - "Left", - "SharpLeft", - nullptr - }; - return names; -} - -inline const char *EnumNameTurn(Turn e) { - if (e < Turn_None || e > Turn_SharpLeft) return ""; - const size_t index = static_cast(e); - return EnumNamesTurn()[index]; -} - -FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Position FLATBUFFERS_FINAL_CLASS { - private: - float longitude_; - float latitude_; - - public: - Position() { - memset(static_cast(this), 0, sizeof(Position)); - } - Position(float _longitude, float _latitude) - : longitude_(flatbuffers::EndianScalar(_longitude)), - latitude_(flatbuffers::EndianScalar(_latitude)) { - } - float longitude() const { - return flatbuffers::EndianScalar(longitude_); - } - float latitude() const { - return flatbuffers::EndianScalar(latitude_); - } -}; -FLATBUFFERS_STRUCT_END(Position, 8); - -FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Uint64Pair FLATBUFFERS_FINAL_CLASS { - private: - uint64_t first_; - uint64_t second_; - - public: - Uint64Pair() { - memset(static_cast(this), 0, sizeof(Uint64Pair)); - } - Uint64Pair(uint64_t _first, uint64_t _second) - : first_(flatbuffers::EndianScalar(_first)), - second_(flatbuffers::EndianScalar(_second)) { - } - uint64_t first() const { - return flatbuffers::EndianScalar(first_); - } - uint64_t second() const { - return flatbuffers::EndianScalar(second_); - } -}; -FLATBUFFERS_STRUCT_END(Uint64Pair, 16); - -struct WaypointT : public flatbuffers::NativeTable { - using TableType = Waypoint; - std::string hint; - float distance; - std::string name; - std::unique_ptr location; - std::unique_ptr nodes; - uint32_t matchings_index; - uint32_t waypoint_index; - uint32_t alternatives_count; - uint32_t trips_index; - WaypointT() - : distance(0.0f), - matchings_index(0), - waypoint_index(0), - alternatives_count(0), - trips_index(0) { - } -}; - -struct Waypoint FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = WaypointT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_HINT = 4, - VT_DISTANCE = 6, - VT_NAME = 8, - VT_LOCATION = 10, - VT_NODES = 12, - VT_MATCHINGS_INDEX = 14, - VT_WAYPOINT_INDEX = 16, - VT_ALTERNATIVES_COUNT = 18, - VT_TRIPS_INDEX = 20 - }; - const flatbuffers::String *hint() const { - return GetPointer(VT_HINT); - } - float distance() const { - return GetField(VT_DISTANCE, 0.0f); - } - const flatbuffers::String *name() const { - return GetPointer(VT_NAME); - } - const osrm::engine::api::fbresult::Position *location() const { - return GetStruct(VT_LOCATION); - } - const osrm::engine::api::fbresult::Uint64Pair *nodes() const { - return GetStruct(VT_NODES); - } - uint32_t matchings_index() const { - return GetField(VT_MATCHINGS_INDEX, 0); - } - uint32_t waypoint_index() const { - return GetField(VT_WAYPOINT_INDEX, 0); - } - uint32_t alternatives_count() const { - return GetField(VT_ALTERNATIVES_COUNT, 0); - } - uint32_t trips_index() const { - return GetField(VT_TRIPS_INDEX, 0); - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyOffset(verifier, VT_HINT) && - verifier.VerifyString(hint()) && - VerifyField(verifier, VT_DISTANCE) && - VerifyOffset(verifier, VT_NAME) && - verifier.VerifyString(name()) && - VerifyField(verifier, VT_LOCATION) && - VerifyField(verifier, VT_NODES) && - VerifyField(verifier, VT_MATCHINGS_INDEX) && - VerifyField(verifier, VT_WAYPOINT_INDEX) && - VerifyField(verifier, VT_ALTERNATIVES_COUNT) && - VerifyField(verifier, VT_TRIPS_INDEX) && - verifier.EndTable(); - } - WaypointT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(WaypointT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const WaypointT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct WaypointBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_hint(flatbuffers::Offset hint) { - fbb_.AddOffset(Waypoint::VT_HINT, hint); - } - void add_distance(float distance) { - fbb_.AddElement(Waypoint::VT_DISTANCE, distance, 0.0f); - } - void add_name(flatbuffers::Offset name) { - fbb_.AddOffset(Waypoint::VT_NAME, name); - } - void add_location(const osrm::engine::api::fbresult::Position *location) { - fbb_.AddStruct(Waypoint::VT_LOCATION, location); - } - void add_nodes(const osrm::engine::api::fbresult::Uint64Pair *nodes) { - fbb_.AddStruct(Waypoint::VT_NODES, nodes); - } - void add_matchings_index(uint32_t matchings_index) { - fbb_.AddElement(Waypoint::VT_MATCHINGS_INDEX, matchings_index, 0); - } - void add_waypoint_index(uint32_t waypoint_index) { - fbb_.AddElement(Waypoint::VT_WAYPOINT_INDEX, waypoint_index, 0); - } - void add_alternatives_count(uint32_t alternatives_count) { - fbb_.AddElement(Waypoint::VT_ALTERNATIVES_COUNT, alternatives_count, 0); - } - void add_trips_index(uint32_t trips_index) { - fbb_.AddElement(Waypoint::VT_TRIPS_INDEX, trips_index, 0); - } - explicit WaypointBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - WaypointBuilder &operator=(const WaypointBuilder &); - flatbuffers::Offset Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); - return o; - } -}; - -inline flatbuffers::Offset CreateWaypoint( - flatbuffers::FlatBufferBuilder &_fbb, - flatbuffers::Offset hint = 0, - float distance = 0.0f, - flatbuffers::Offset name = 0, - const osrm::engine::api::fbresult::Position *location = 0, - const osrm::engine::api::fbresult::Uint64Pair *nodes = 0, - uint32_t matchings_index = 0, - uint32_t waypoint_index = 0, - uint32_t alternatives_count = 0, - uint32_t trips_index = 0) { - WaypointBuilder builder_(_fbb); - builder_.add_trips_index(trips_index); - builder_.add_alternatives_count(alternatives_count); - builder_.add_waypoint_index(waypoint_index); - builder_.add_matchings_index(matchings_index); - builder_.add_nodes(nodes); - builder_.add_location(location); - builder_.add_name(name); - builder_.add_distance(distance); - builder_.add_hint(hint); - return builder_.Finish(); -} - -inline flatbuffers::Offset CreateWaypointDirect( - flatbuffers::FlatBufferBuilder &_fbb, - const char *hint = nullptr, - float distance = 0.0f, - const char *name = nullptr, - const osrm::engine::api::fbresult::Position *location = 0, - const osrm::engine::api::fbresult::Uint64Pair *nodes = 0, - uint32_t matchings_index = 0, - uint32_t waypoint_index = 0, - uint32_t alternatives_count = 0, - uint32_t trips_index = 0) { - auto hint__ = hint ? _fbb.CreateString(hint) : 0; - auto name__ = name ? _fbb.CreateString(name) : 0; - return osrm::engine::api::fbresult::CreateWaypoint( - _fbb, - hint__, - distance, - name__, - location, - nodes, - matchings_index, - waypoint_index, - alternatives_count, - trips_index); -} - -flatbuffers::Offset CreateWaypoint(flatbuffers::FlatBufferBuilder &_fbb, const WaypointT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -struct MetadataT : public flatbuffers::NativeTable { - using TableType = Metadata; - std::vector datasource_names; - MetadataT() { - } -}; - -struct Metadata FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = MetadataT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_DATASOURCE_NAMES = 4 - }; - const flatbuffers::Vector> *datasource_names() const { - return GetPointer> *>(VT_DATASOURCE_NAMES); - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyOffset(verifier, VT_DATASOURCE_NAMES) && - verifier.VerifyVector(datasource_names()) && - verifier.VerifyVectorOfStrings(datasource_names()) && - verifier.EndTable(); - } - MetadataT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(MetadataT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const MetadataT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct MetadataBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_datasource_names(flatbuffers::Offset>> datasource_names) { - fbb_.AddOffset(Metadata::VT_DATASOURCE_NAMES, datasource_names); - } - explicit MetadataBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - MetadataBuilder &operator=(const MetadataBuilder &); - flatbuffers::Offset Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); - return o; - } -}; - -inline flatbuffers::Offset CreateMetadata( - flatbuffers::FlatBufferBuilder &_fbb, - flatbuffers::Offset>> datasource_names = 0) { - MetadataBuilder builder_(_fbb); - builder_.add_datasource_names(datasource_names); - return builder_.Finish(); -} - -inline flatbuffers::Offset CreateMetadataDirect( - flatbuffers::FlatBufferBuilder &_fbb, - const std::vector> *datasource_names = nullptr) { - auto datasource_names__ = datasource_names ? _fbb.CreateVector>(*datasource_names) : 0; - return osrm::engine::api::fbresult::CreateMetadata( - _fbb, - datasource_names__); -} - -flatbuffers::Offset CreateMetadata(flatbuffers::FlatBufferBuilder &_fbb, const MetadataT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -struct AnnotationT : public flatbuffers::NativeTable { - using TableType = Annotation; - std::vector distance; - std::vector duration; - std::vector datasources; - std::vector nodes; - std::vector weight; - std::vector speed; - std::unique_ptr metadata; - AnnotationT() { - } -}; - -struct Annotation FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = AnnotationT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_DISTANCE = 4, - VT_DURATION = 6, - VT_DATASOURCES = 8, - VT_NODES = 10, - VT_WEIGHT = 12, - VT_SPEED = 14, - VT_METADATA = 16 - }; - const flatbuffers::Vector *distance() const { - return GetPointer *>(VT_DISTANCE); - } - const flatbuffers::Vector *duration() const { - return GetPointer *>(VT_DURATION); - } - const flatbuffers::Vector *datasources() const { - return GetPointer *>(VT_DATASOURCES); - } - const flatbuffers::Vector *nodes() const { - return GetPointer *>(VT_NODES); - } - const flatbuffers::Vector *weight() const { - return GetPointer *>(VT_WEIGHT); - } - const flatbuffers::Vector *speed() const { - return GetPointer *>(VT_SPEED); - } - const osrm::engine::api::fbresult::Metadata *metadata() const { - return GetPointer(VT_METADATA); - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyOffset(verifier, VT_DISTANCE) && - verifier.VerifyVector(distance()) && - VerifyOffset(verifier, VT_DURATION) && - verifier.VerifyVector(duration()) && - VerifyOffset(verifier, VT_DATASOURCES) && - verifier.VerifyVector(datasources()) && - VerifyOffset(verifier, VT_NODES) && - verifier.VerifyVector(nodes()) && - VerifyOffset(verifier, VT_WEIGHT) && - verifier.VerifyVector(weight()) && - VerifyOffset(verifier, VT_SPEED) && - verifier.VerifyVector(speed()) && - VerifyOffset(verifier, VT_METADATA) && - verifier.VerifyTable(metadata()) && - verifier.EndTable(); - } - AnnotationT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(AnnotationT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const AnnotationT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct AnnotationBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_distance(flatbuffers::Offset> distance) { - fbb_.AddOffset(Annotation::VT_DISTANCE, distance); - } - void add_duration(flatbuffers::Offset> duration) { - fbb_.AddOffset(Annotation::VT_DURATION, duration); - } - void add_datasources(flatbuffers::Offset> datasources) { - fbb_.AddOffset(Annotation::VT_DATASOURCES, datasources); - } - void add_nodes(flatbuffers::Offset> nodes) { - fbb_.AddOffset(Annotation::VT_NODES, nodes); - } - void add_weight(flatbuffers::Offset> weight) { - fbb_.AddOffset(Annotation::VT_WEIGHT, weight); - } - void add_speed(flatbuffers::Offset> speed) { - fbb_.AddOffset(Annotation::VT_SPEED, speed); - } - void add_metadata(flatbuffers::Offset metadata) { - fbb_.AddOffset(Annotation::VT_METADATA, metadata); - } - explicit AnnotationBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - AnnotationBuilder &operator=(const AnnotationBuilder &); - flatbuffers::Offset Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); - return o; - } -}; - -inline flatbuffers::Offset CreateAnnotation( - flatbuffers::FlatBufferBuilder &_fbb, - flatbuffers::Offset> distance = 0, - flatbuffers::Offset> duration = 0, - flatbuffers::Offset> datasources = 0, - flatbuffers::Offset> nodes = 0, - flatbuffers::Offset> weight = 0, - flatbuffers::Offset> speed = 0, - flatbuffers::Offset metadata = 0) { - AnnotationBuilder builder_(_fbb); - builder_.add_metadata(metadata); - builder_.add_speed(speed); - builder_.add_weight(weight); - builder_.add_nodes(nodes); - builder_.add_datasources(datasources); - builder_.add_duration(duration); - builder_.add_distance(distance); - return builder_.Finish(); -} - -inline flatbuffers::Offset CreateAnnotationDirect( - flatbuffers::FlatBufferBuilder &_fbb, - const std::vector *distance = nullptr, - const std::vector *duration = nullptr, - const std::vector *datasources = nullptr, - const std::vector *nodes = nullptr, - const std::vector *weight = nullptr, - const std::vector *speed = nullptr, - flatbuffers::Offset metadata = 0) { - auto distance__ = distance ? _fbb.CreateVector(*distance) : 0; - auto duration__ = duration ? _fbb.CreateVector(*duration) : 0; - auto datasources__ = datasources ? _fbb.CreateVector(*datasources) : 0; - auto nodes__ = nodes ? _fbb.CreateVector(*nodes) : 0; - auto weight__ = weight ? _fbb.CreateVector(*weight) : 0; - auto speed__ = speed ? _fbb.CreateVector(*speed) : 0; - return osrm::engine::api::fbresult::CreateAnnotation( - _fbb, - distance__, - duration__, - datasources__, - nodes__, - weight__, - speed__, - metadata); -} - -flatbuffers::Offset CreateAnnotation(flatbuffers::FlatBufferBuilder &_fbb, const AnnotationT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -struct StepManeuverT : public flatbuffers::NativeTable { - using TableType = StepManeuver; - std::unique_ptr location; - uint16_t bearing_before; - uint16_t bearing_after; - osrm::engine::api::fbresult::ManeuverType type; - osrm::engine::api::fbresult::Turn modifier; - uint8_t exit; - StepManeuverT() - : bearing_before(0), - bearing_after(0), - type(osrm::engine::api::fbresult::ManeuverType_Turn), - modifier(osrm::engine::api::fbresult::Turn_None), - exit(0) { - } -}; - -struct StepManeuver FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = StepManeuverT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_LOCATION = 4, - VT_BEARING_BEFORE = 6, - VT_BEARING_AFTER = 8, - VT_TYPE = 10, - VT_MODIFIER = 12, - VT_EXIT = 14 - }; - const osrm::engine::api::fbresult::Position *location() const { - return GetStruct(VT_LOCATION); - } - uint16_t bearing_before() const { - return GetField(VT_BEARING_BEFORE, 0); - } - uint16_t bearing_after() const { - return GetField(VT_BEARING_AFTER, 0); - } - osrm::engine::api::fbresult::ManeuverType type() const { - return static_cast(GetField(VT_TYPE, 0)); - } - osrm::engine::api::fbresult::Turn modifier() const { - return static_cast(GetField(VT_MODIFIER, 0)); - } - uint8_t exit() const { - return GetField(VT_EXIT, 0); - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyField(verifier, VT_LOCATION) && - VerifyField(verifier, VT_BEARING_BEFORE) && - VerifyField(verifier, VT_BEARING_AFTER) && - VerifyField(verifier, VT_TYPE) && - VerifyField(verifier, VT_MODIFIER) && - VerifyField(verifier, VT_EXIT) && - verifier.EndTable(); - } - StepManeuverT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(StepManeuverT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const StepManeuverT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct StepManeuverBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_location(const osrm::engine::api::fbresult::Position *location) { - fbb_.AddStruct(StepManeuver::VT_LOCATION, location); - } - void add_bearing_before(uint16_t bearing_before) { - fbb_.AddElement(StepManeuver::VT_BEARING_BEFORE, bearing_before, 0); - } - void add_bearing_after(uint16_t bearing_after) { - fbb_.AddElement(StepManeuver::VT_BEARING_AFTER, bearing_after, 0); - } - void add_type(osrm::engine::api::fbresult::ManeuverType type) { - fbb_.AddElement(StepManeuver::VT_TYPE, static_cast(type), 0); - } - void add_modifier(osrm::engine::api::fbresult::Turn modifier) { - fbb_.AddElement(StepManeuver::VT_MODIFIER, static_cast(modifier), 0); - } - void add_exit(uint8_t exit) { - fbb_.AddElement(StepManeuver::VT_EXIT, exit, 0); - } - explicit StepManeuverBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - StepManeuverBuilder &operator=(const StepManeuverBuilder &); - flatbuffers::Offset Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); - return o; - } -}; - -inline flatbuffers::Offset CreateStepManeuver( - flatbuffers::FlatBufferBuilder &_fbb, - const osrm::engine::api::fbresult::Position *location = 0, - uint16_t bearing_before = 0, - uint16_t bearing_after = 0, - osrm::engine::api::fbresult::ManeuverType type = osrm::engine::api::fbresult::ManeuverType_Turn, - osrm::engine::api::fbresult::Turn modifier = osrm::engine::api::fbresult::Turn_None, - uint8_t exit = 0) { - StepManeuverBuilder builder_(_fbb); - builder_.add_location(location); - builder_.add_bearing_after(bearing_after); - builder_.add_bearing_before(bearing_before); - builder_.add_exit(exit); - builder_.add_modifier(modifier); - builder_.add_type(type); - return builder_.Finish(); -} - -flatbuffers::Offset CreateStepManeuver(flatbuffers::FlatBufferBuilder &_fbb, const StepManeuverT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -struct LaneT : public flatbuffers::NativeTable { - using TableType = Lane; - std::vector indications; - bool valid; - LaneT() - : valid(false) { - } -}; - -struct Lane FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = LaneT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_INDICATIONS = 4, - VT_VALID = 6 - }; - const flatbuffers::Vector *indications() const { - return GetPointer *>(VT_INDICATIONS); - } - bool valid() const { - return GetField(VT_VALID, 0) != 0; - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyOffset(verifier, VT_INDICATIONS) && - verifier.VerifyVector(indications()) && - VerifyField(verifier, VT_VALID) && - verifier.EndTable(); - } - LaneT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(LaneT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const LaneT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct LaneBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_indications(flatbuffers::Offset> indications) { - fbb_.AddOffset(Lane::VT_INDICATIONS, indications); - } - void add_valid(bool valid) { - fbb_.AddElement(Lane::VT_VALID, static_cast(valid), 0); - } - explicit LaneBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - LaneBuilder &operator=(const LaneBuilder &); - flatbuffers::Offset Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); - return o; - } -}; - -inline flatbuffers::Offset CreateLane( - flatbuffers::FlatBufferBuilder &_fbb, - flatbuffers::Offset> indications = 0, - bool valid = false) { - LaneBuilder builder_(_fbb); - builder_.add_indications(indications); - builder_.add_valid(valid); - return builder_.Finish(); -} - -inline flatbuffers::Offset CreateLaneDirect( - flatbuffers::FlatBufferBuilder &_fbb, - const std::vector *indications = nullptr, - bool valid = false) { - auto indications__ = indications ? _fbb.CreateVector(*indications) : 0; - return osrm::engine::api::fbresult::CreateLane( - _fbb, - indications__, - valid); -} - -flatbuffers::Offset CreateLane(flatbuffers::FlatBufferBuilder &_fbb, const LaneT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -struct IntersectionT : public flatbuffers::NativeTable { - using TableType = Intersection; - std::unique_ptr location; - std::vector bearings; - std::vector classes; - std::vector entry; - uint32_t in_bearing; - uint32_t out_bearing; - std::vector> lanes; - IntersectionT() - : in_bearing(0), - out_bearing(0) { - } -}; - -struct Intersection FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = IntersectionT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_LOCATION = 4, - VT_BEARINGS = 6, - VT_CLASSES = 8, - VT_ENTRY = 10, - VT_IN_BEARING = 12, - VT_OUT_BEARING = 14, - VT_LANES = 16 - }; - const osrm::engine::api::fbresult::Position *location() const { - return GetStruct(VT_LOCATION); - } - const flatbuffers::Vector *bearings() const { - return GetPointer *>(VT_BEARINGS); - } - const flatbuffers::Vector> *classes() const { - return GetPointer> *>(VT_CLASSES); - } - const flatbuffers::Vector *entry() const { - return GetPointer *>(VT_ENTRY); - } - uint32_t in_bearing() const { - return GetField(VT_IN_BEARING, 0); - } - uint32_t out_bearing() const { - return GetField(VT_OUT_BEARING, 0); - } - const flatbuffers::Vector> *lanes() const { - return GetPointer> *>(VT_LANES); - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyField(verifier, VT_LOCATION) && - VerifyOffset(verifier, VT_BEARINGS) && - verifier.VerifyVector(bearings()) && - VerifyOffset(verifier, VT_CLASSES) && - verifier.VerifyVector(classes()) && - verifier.VerifyVectorOfStrings(classes()) && - VerifyOffset(verifier, VT_ENTRY) && - verifier.VerifyVector(entry()) && - VerifyField(verifier, VT_IN_BEARING) && - VerifyField(verifier, VT_OUT_BEARING) && - VerifyOffset(verifier, VT_LANES) && - verifier.VerifyVector(lanes()) && - verifier.VerifyVectorOfTables(lanes()) && - verifier.EndTable(); - } - IntersectionT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(IntersectionT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const IntersectionT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct IntersectionBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_location(const osrm::engine::api::fbresult::Position *location) { - fbb_.AddStruct(Intersection::VT_LOCATION, location); - } - void add_bearings(flatbuffers::Offset> bearings) { - fbb_.AddOffset(Intersection::VT_BEARINGS, bearings); - } - void add_classes(flatbuffers::Offset>> classes) { - fbb_.AddOffset(Intersection::VT_CLASSES, classes); - } - void add_entry(flatbuffers::Offset> entry) { - fbb_.AddOffset(Intersection::VT_ENTRY, entry); - } - void add_in_bearing(uint32_t in_bearing) { - fbb_.AddElement(Intersection::VT_IN_BEARING, in_bearing, 0); - } - void add_out_bearing(uint32_t out_bearing) { - fbb_.AddElement(Intersection::VT_OUT_BEARING, out_bearing, 0); - } - void add_lanes(flatbuffers::Offset>> lanes) { - fbb_.AddOffset(Intersection::VT_LANES, lanes); - } - explicit IntersectionBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - IntersectionBuilder &operator=(const IntersectionBuilder &); - flatbuffers::Offset Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); - return o; - } -}; - -inline flatbuffers::Offset CreateIntersection( - flatbuffers::FlatBufferBuilder &_fbb, - const osrm::engine::api::fbresult::Position *location = 0, - flatbuffers::Offset> bearings = 0, - flatbuffers::Offset>> classes = 0, - flatbuffers::Offset> entry = 0, - uint32_t in_bearing = 0, - uint32_t out_bearing = 0, - flatbuffers::Offset>> lanes = 0) { - IntersectionBuilder builder_(_fbb); - builder_.add_lanes(lanes); - builder_.add_out_bearing(out_bearing); - builder_.add_in_bearing(in_bearing); - builder_.add_entry(entry); - builder_.add_classes(classes); - builder_.add_bearings(bearings); - builder_.add_location(location); - return builder_.Finish(); -} - -inline flatbuffers::Offset CreateIntersectionDirect( - flatbuffers::FlatBufferBuilder &_fbb, - const osrm::engine::api::fbresult::Position *location = 0, - const std::vector *bearings = nullptr, - const std::vector> *classes = nullptr, - const std::vector *entry = nullptr, - uint32_t in_bearing = 0, - uint32_t out_bearing = 0, - const std::vector> *lanes = nullptr) { - auto bearings__ = bearings ? _fbb.CreateVector(*bearings) : 0; - auto classes__ = classes ? _fbb.CreateVector>(*classes) : 0; - auto entry__ = entry ? _fbb.CreateVector(*entry) : 0; - auto lanes__ = lanes ? _fbb.CreateVector>(*lanes) : 0; - return osrm::engine::api::fbresult::CreateIntersection( - _fbb, - location, - bearings__, - classes__, - entry__, - in_bearing, - out_bearing, - lanes__); -} - -flatbuffers::Offset CreateIntersection(flatbuffers::FlatBufferBuilder &_fbb, const IntersectionT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -struct StepT : public flatbuffers::NativeTable { - using TableType = Step; - float distance; - float duration; - std::string polyline; - std::vector coordinates; - float weight; - std::string name; - std::string ref; - std::string pronunciation; - std::string destinations; - std::string exits; - std::string mode; - std::unique_ptr maneuver; - std::vector> intersections; - std::string rotary_name; - std::string rotary_pronunciation; - bool driving_side; - StepT() - : distance(0.0f), - duration(0.0f), - weight(0.0f), - driving_side(false) { - } -}; - -struct Step FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = StepT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_DISTANCE = 4, - VT_DURATION = 6, - VT_POLYLINE = 8, - VT_COORDINATES = 10, - VT_WEIGHT = 12, - VT_NAME = 14, - VT_REF = 16, - VT_PRONUNCIATION = 18, - VT_DESTINATIONS = 20, - VT_EXITS = 22, - VT_MODE = 24, - VT_MANEUVER = 26, - VT_INTERSECTIONS = 28, - VT_ROTARY_NAME = 30, - VT_ROTARY_PRONUNCIATION = 32, - VT_DRIVING_SIDE = 34 - }; - float distance() const { - return GetField(VT_DISTANCE, 0.0f); - } - float duration() const { - return GetField(VT_DURATION, 0.0f); - } - const flatbuffers::String *polyline() const { - return GetPointer(VT_POLYLINE); - } - const flatbuffers::Vector *coordinates() const { - return GetPointer *>(VT_COORDINATES); - } - float weight() const { - return GetField(VT_WEIGHT, 0.0f); - } - const flatbuffers::String *name() const { - return GetPointer(VT_NAME); - } - const flatbuffers::String *ref() const { - return GetPointer(VT_REF); - } - const flatbuffers::String *pronunciation() const { - return GetPointer(VT_PRONUNCIATION); - } - const flatbuffers::String *destinations() const { - return GetPointer(VT_DESTINATIONS); - } - const flatbuffers::String *exits() const { - return GetPointer(VT_EXITS); - } - const flatbuffers::String *mode() const { - return GetPointer(VT_MODE); - } - const osrm::engine::api::fbresult::StepManeuver *maneuver() const { - return GetPointer(VT_MANEUVER); - } - const flatbuffers::Vector> *intersections() const { - return GetPointer> *>(VT_INTERSECTIONS); - } - const flatbuffers::String *rotary_name() const { - return GetPointer(VT_ROTARY_NAME); - } - const flatbuffers::String *rotary_pronunciation() const { - return GetPointer(VT_ROTARY_PRONUNCIATION); - } - bool driving_side() const { - return GetField(VT_DRIVING_SIDE, 0) != 0; - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyField(verifier, VT_DISTANCE) && - VerifyField(verifier, VT_DURATION) && - VerifyOffset(verifier, VT_POLYLINE) && - verifier.VerifyString(polyline()) && - VerifyOffset(verifier, VT_COORDINATES) && - verifier.VerifyVector(coordinates()) && - VerifyField(verifier, VT_WEIGHT) && - VerifyOffset(verifier, VT_NAME) && - verifier.VerifyString(name()) && - VerifyOffset(verifier, VT_REF) && - verifier.VerifyString(ref()) && - VerifyOffset(verifier, VT_PRONUNCIATION) && - verifier.VerifyString(pronunciation()) && - VerifyOffset(verifier, VT_DESTINATIONS) && - verifier.VerifyString(destinations()) && - VerifyOffset(verifier, VT_EXITS) && - verifier.VerifyString(exits()) && - VerifyOffset(verifier, VT_MODE) && - verifier.VerifyString(mode()) && - VerifyOffset(verifier, VT_MANEUVER) && - verifier.VerifyTable(maneuver()) && - VerifyOffset(verifier, VT_INTERSECTIONS) && - verifier.VerifyVector(intersections()) && - verifier.VerifyVectorOfTables(intersections()) && - VerifyOffset(verifier, VT_ROTARY_NAME) && - verifier.VerifyString(rotary_name()) && - VerifyOffset(verifier, VT_ROTARY_PRONUNCIATION) && - verifier.VerifyString(rotary_pronunciation()) && - VerifyField(verifier, VT_DRIVING_SIDE) && - verifier.EndTable(); - } - StepT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(StepT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const StepT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct StepBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_distance(float distance) { - fbb_.AddElement(Step::VT_DISTANCE, distance, 0.0f); - } - void add_duration(float duration) { - fbb_.AddElement(Step::VT_DURATION, duration, 0.0f); - } - void add_polyline(flatbuffers::Offset polyline) { - fbb_.AddOffset(Step::VT_POLYLINE, polyline); - } - void add_coordinates(flatbuffers::Offset> coordinates) { - fbb_.AddOffset(Step::VT_COORDINATES, coordinates); - } - void add_weight(float weight) { - fbb_.AddElement(Step::VT_WEIGHT, weight, 0.0f); - } - void add_name(flatbuffers::Offset name) { - fbb_.AddOffset(Step::VT_NAME, name); - } - void add_ref(flatbuffers::Offset ref) { - fbb_.AddOffset(Step::VT_REF, ref); - } - void add_pronunciation(flatbuffers::Offset pronunciation) { - fbb_.AddOffset(Step::VT_PRONUNCIATION, pronunciation); - } - void add_destinations(flatbuffers::Offset destinations) { - fbb_.AddOffset(Step::VT_DESTINATIONS, destinations); - } - void add_exits(flatbuffers::Offset exits) { - fbb_.AddOffset(Step::VT_EXITS, exits); - } - void add_mode(flatbuffers::Offset mode) { - fbb_.AddOffset(Step::VT_MODE, mode); - } - void add_maneuver(flatbuffers::Offset maneuver) { - fbb_.AddOffset(Step::VT_MANEUVER, maneuver); - } - void add_intersections(flatbuffers::Offset>> intersections) { - fbb_.AddOffset(Step::VT_INTERSECTIONS, intersections); - } - void add_rotary_name(flatbuffers::Offset rotary_name) { - fbb_.AddOffset(Step::VT_ROTARY_NAME, rotary_name); - } - void add_rotary_pronunciation(flatbuffers::Offset rotary_pronunciation) { - fbb_.AddOffset(Step::VT_ROTARY_PRONUNCIATION, rotary_pronunciation); - } - void add_driving_side(bool driving_side) { - fbb_.AddElement(Step::VT_DRIVING_SIDE, static_cast(driving_side), 0); - } - explicit StepBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - StepBuilder &operator=(const StepBuilder &); - flatbuffers::Offset Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); - return o; - } -}; - -inline flatbuffers::Offset CreateStep( - flatbuffers::FlatBufferBuilder &_fbb, - float distance = 0.0f, - float duration = 0.0f, - flatbuffers::Offset polyline = 0, - flatbuffers::Offset> coordinates = 0, - float weight = 0.0f, - flatbuffers::Offset name = 0, - flatbuffers::Offset ref = 0, - flatbuffers::Offset pronunciation = 0, - flatbuffers::Offset destinations = 0, - flatbuffers::Offset exits = 0, - flatbuffers::Offset mode = 0, - flatbuffers::Offset maneuver = 0, - flatbuffers::Offset>> intersections = 0, - flatbuffers::Offset rotary_name = 0, - flatbuffers::Offset rotary_pronunciation = 0, - bool driving_side = false) { - StepBuilder builder_(_fbb); - builder_.add_rotary_pronunciation(rotary_pronunciation); - builder_.add_rotary_name(rotary_name); - builder_.add_intersections(intersections); - builder_.add_maneuver(maneuver); - builder_.add_mode(mode); - builder_.add_exits(exits); - builder_.add_destinations(destinations); - builder_.add_pronunciation(pronunciation); - builder_.add_ref(ref); - builder_.add_name(name); - builder_.add_weight(weight); - builder_.add_coordinates(coordinates); - builder_.add_polyline(polyline); - builder_.add_duration(duration); - builder_.add_distance(distance); - builder_.add_driving_side(driving_side); - return builder_.Finish(); -} - -inline flatbuffers::Offset CreateStepDirect( - flatbuffers::FlatBufferBuilder &_fbb, - float distance = 0.0f, - float duration = 0.0f, - const char *polyline = nullptr, - const std::vector *coordinates = nullptr, - float weight = 0.0f, - const char *name = nullptr, - const char *ref = nullptr, - const char *pronunciation = nullptr, - const char *destinations = nullptr, - const char *exits = nullptr, - const char *mode = nullptr, - flatbuffers::Offset maneuver = 0, - const std::vector> *intersections = nullptr, - const char *rotary_name = nullptr, - const char *rotary_pronunciation = nullptr, - bool driving_side = false) { - auto polyline__ = polyline ? _fbb.CreateString(polyline) : 0; - auto coordinates__ = coordinates ? _fbb.CreateVectorOfStructs(*coordinates) : 0; - auto name__ = name ? _fbb.CreateString(name) : 0; - auto ref__ = ref ? _fbb.CreateString(ref) : 0; - auto pronunciation__ = pronunciation ? _fbb.CreateString(pronunciation) : 0; - auto destinations__ = destinations ? _fbb.CreateString(destinations) : 0; - auto exits__ = exits ? _fbb.CreateString(exits) : 0; - auto mode__ = mode ? _fbb.CreateString(mode) : 0; - auto intersections__ = intersections ? _fbb.CreateVector>(*intersections) : 0; - auto rotary_name__ = rotary_name ? _fbb.CreateString(rotary_name) : 0; - auto rotary_pronunciation__ = rotary_pronunciation ? _fbb.CreateString(rotary_pronunciation) : 0; - return osrm::engine::api::fbresult::CreateStep( - _fbb, - distance, - duration, - polyline__, - coordinates__, - weight, - name__, - ref__, - pronunciation__, - destinations__, - exits__, - mode__, - maneuver, - intersections__, - rotary_name__, - rotary_pronunciation__, - driving_side); -} - -flatbuffers::Offset CreateStep(flatbuffers::FlatBufferBuilder &_fbb, const StepT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -struct LegT : public flatbuffers::NativeTable { - using TableType = Leg; - double distance; - double duration; - double weight; - std::string summary; - std::unique_ptr annotations; - std::vector> steps; - LegT() - : distance(0.0), - duration(0.0), - weight(0.0) { - } -}; - -struct Leg FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = LegT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_DISTANCE = 4, - VT_DURATION = 6, - VT_WEIGHT = 8, - VT_SUMMARY = 10, - VT_ANNOTATIONS = 12, - VT_STEPS = 14 - }; - double distance() const { - return GetField(VT_DISTANCE, 0.0); - } - double duration() const { - return GetField(VT_DURATION, 0.0); - } - double weight() const { - return GetField(VT_WEIGHT, 0.0); - } - const flatbuffers::String *summary() const { - return GetPointer(VT_SUMMARY); - } - const osrm::engine::api::fbresult::Annotation *annotations() const { - return GetPointer(VT_ANNOTATIONS); - } - const flatbuffers::Vector> *steps() const { - return GetPointer> *>(VT_STEPS); - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyField(verifier, VT_DISTANCE) && - VerifyField(verifier, VT_DURATION) && - VerifyField(verifier, VT_WEIGHT) && - VerifyOffset(verifier, VT_SUMMARY) && - verifier.VerifyString(summary()) && - VerifyOffset(verifier, VT_ANNOTATIONS) && - verifier.VerifyTable(annotations()) && - VerifyOffset(verifier, VT_STEPS) && - verifier.VerifyVector(steps()) && - verifier.VerifyVectorOfTables(steps()) && - verifier.EndTable(); - } - LegT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(LegT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const LegT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct LegBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_distance(double distance) { - fbb_.AddElement(Leg::VT_DISTANCE, distance, 0.0); - } - void add_duration(double duration) { - fbb_.AddElement(Leg::VT_DURATION, duration, 0.0); - } - void add_weight(double weight) { - fbb_.AddElement(Leg::VT_WEIGHT, weight, 0.0); - } - void add_summary(flatbuffers::Offset summary) { - fbb_.AddOffset(Leg::VT_SUMMARY, summary); - } - void add_annotations(flatbuffers::Offset annotations) { - fbb_.AddOffset(Leg::VT_ANNOTATIONS, annotations); - } - void add_steps(flatbuffers::Offset>> steps) { - fbb_.AddOffset(Leg::VT_STEPS, steps); - } - explicit LegBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - LegBuilder &operator=(const LegBuilder &); - flatbuffers::Offset Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); - return o; - } -}; - -inline flatbuffers::Offset CreateLeg( - flatbuffers::FlatBufferBuilder &_fbb, - double distance = 0.0, - double duration = 0.0, - double weight = 0.0, - flatbuffers::Offset summary = 0, - flatbuffers::Offset annotations = 0, - flatbuffers::Offset>> steps = 0) { - LegBuilder builder_(_fbb); - builder_.add_weight(weight); - builder_.add_duration(duration); - builder_.add_distance(distance); - builder_.add_steps(steps); - builder_.add_annotations(annotations); - builder_.add_summary(summary); - return builder_.Finish(); -} - -inline flatbuffers::Offset CreateLegDirect( - flatbuffers::FlatBufferBuilder &_fbb, - double distance = 0.0, - double duration = 0.0, - double weight = 0.0, - const char *summary = nullptr, - flatbuffers::Offset annotations = 0, - const std::vector> *steps = nullptr) { - auto summary__ = summary ? _fbb.CreateString(summary) : 0; - auto steps__ = steps ? _fbb.CreateVector>(*steps) : 0; - return osrm::engine::api::fbresult::CreateLeg( - _fbb, - distance, - duration, - weight, - summary__, - annotations, - steps__); -} - -flatbuffers::Offset CreateLeg(flatbuffers::FlatBufferBuilder &_fbb, const LegT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -struct RouteObjectT : public flatbuffers::NativeTable { - using TableType = RouteObject; - float distance; - float duration; - float weight; - std::string weight_name; - float confidence; - std::string polyline; - std::vector coordinates; - std::vector> legs; - RouteObjectT() - : distance(0.0f), - duration(0.0f), - weight(0.0f), - confidence(0.0f) { - } -}; - -struct RouteObject FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = RouteObjectT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_DISTANCE = 4, - VT_DURATION = 6, - VT_WEIGHT = 8, - VT_WEIGHT_NAME = 10, - VT_CONFIDENCE = 12, - VT_POLYLINE = 14, - VT_COORDINATES = 16, - VT_LEGS = 18 - }; - float distance() const { - return GetField(VT_DISTANCE, 0.0f); - } - float duration() const { - return GetField(VT_DURATION, 0.0f); - } - float weight() const { - return GetField(VT_WEIGHT, 0.0f); - } - const flatbuffers::String *weight_name() const { - return GetPointer(VT_WEIGHT_NAME); - } - float confidence() const { - return GetField(VT_CONFIDENCE, 0.0f); - } - const flatbuffers::String *polyline() const { - return GetPointer(VT_POLYLINE); - } - const flatbuffers::Vector *coordinates() const { - return GetPointer *>(VT_COORDINATES); - } - const flatbuffers::Vector> *legs() const { - return GetPointer> *>(VT_LEGS); - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyField(verifier, VT_DISTANCE) && - VerifyField(verifier, VT_DURATION) && - VerifyField(verifier, VT_WEIGHT) && - VerifyOffset(verifier, VT_WEIGHT_NAME) && - verifier.VerifyString(weight_name()) && - VerifyField(verifier, VT_CONFIDENCE) && - VerifyOffset(verifier, VT_POLYLINE) && - verifier.VerifyString(polyline()) && - VerifyOffset(verifier, VT_COORDINATES) && - verifier.VerifyVector(coordinates()) && - VerifyOffset(verifier, VT_LEGS) && - verifier.VerifyVector(legs()) && - verifier.VerifyVectorOfTables(legs()) && - verifier.EndTable(); - } - RouteObjectT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(RouteObjectT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const RouteObjectT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct RouteObjectBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_distance(float distance) { - fbb_.AddElement(RouteObject::VT_DISTANCE, distance, 0.0f); - } - void add_duration(float duration) { - fbb_.AddElement(RouteObject::VT_DURATION, duration, 0.0f); - } - void add_weight(float weight) { - fbb_.AddElement(RouteObject::VT_WEIGHT, weight, 0.0f); - } - void add_weight_name(flatbuffers::Offset weight_name) { - fbb_.AddOffset(RouteObject::VT_WEIGHT_NAME, weight_name); - } - void add_confidence(float confidence) { - fbb_.AddElement(RouteObject::VT_CONFIDENCE, confidence, 0.0f); - } - void add_polyline(flatbuffers::Offset polyline) { - fbb_.AddOffset(RouteObject::VT_POLYLINE, polyline); - } - void add_coordinates(flatbuffers::Offset> coordinates) { - fbb_.AddOffset(RouteObject::VT_COORDINATES, coordinates); - } - void add_legs(flatbuffers::Offset>> legs) { - fbb_.AddOffset(RouteObject::VT_LEGS, legs); - } - explicit RouteObjectBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - RouteObjectBuilder &operator=(const RouteObjectBuilder &); - flatbuffers::Offset Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); - return o; - } -}; - -inline flatbuffers::Offset CreateRouteObject( - flatbuffers::FlatBufferBuilder &_fbb, - float distance = 0.0f, - float duration = 0.0f, - float weight = 0.0f, - flatbuffers::Offset weight_name = 0, - float confidence = 0.0f, - flatbuffers::Offset polyline = 0, - flatbuffers::Offset> coordinates = 0, - flatbuffers::Offset>> legs = 0) { - RouteObjectBuilder builder_(_fbb); - builder_.add_legs(legs); - builder_.add_coordinates(coordinates); - builder_.add_polyline(polyline); - builder_.add_confidence(confidence); - builder_.add_weight_name(weight_name); - builder_.add_weight(weight); - builder_.add_duration(duration); - builder_.add_distance(distance); - return builder_.Finish(); -} - -inline flatbuffers::Offset CreateRouteObjectDirect( - flatbuffers::FlatBufferBuilder &_fbb, - float distance = 0.0f, - float duration = 0.0f, - float weight = 0.0f, - const char *weight_name = nullptr, - float confidence = 0.0f, - const char *polyline = nullptr, - const std::vector *coordinates = nullptr, - const std::vector> *legs = nullptr) { - auto weight_name__ = weight_name ? _fbb.CreateString(weight_name) : 0; - auto polyline__ = polyline ? _fbb.CreateString(polyline) : 0; - auto coordinates__ = coordinates ? _fbb.CreateVectorOfStructs(*coordinates) : 0; - auto legs__ = legs ? _fbb.CreateVector>(*legs) : 0; - return osrm::engine::api::fbresult::CreateRouteObject( - _fbb, - distance, - duration, - weight, - weight_name__, - confidence, - polyline__, - coordinates__, - legs__); -} - -flatbuffers::Offset CreateRouteObject(flatbuffers::FlatBufferBuilder &_fbb, const RouteObjectT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -struct TableT : public flatbuffers::NativeTable { - using TableType = Table; - std::vector durations; - uint16_t rows; - uint16_t cols; - std::vector distances; - std::vector> destinations; - std::vector fallback_speed_cells; - TableT() - : rows(0), - cols(0) { - } -}; - -struct Table FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = TableT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_DURATIONS = 4, - VT_ROWS = 6, - VT_COLS = 8, - VT_DISTANCES = 10, - VT_DESTINATIONS = 12, - VT_FALLBACK_SPEED_CELLS = 14 - }; - const flatbuffers::Vector *durations() const { - return GetPointer *>(VT_DURATIONS); - } - uint16_t rows() const { - return GetField(VT_ROWS, 0); - } - uint16_t cols() const { - return GetField(VT_COLS, 0); - } - const flatbuffers::Vector *distances() const { - return GetPointer *>(VT_DISTANCES); - } - const flatbuffers::Vector> *destinations() const { - return GetPointer> *>(VT_DESTINATIONS); - } - const flatbuffers::Vector *fallback_speed_cells() const { - return GetPointer *>(VT_FALLBACK_SPEED_CELLS); - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyOffset(verifier, VT_DURATIONS) && - verifier.VerifyVector(durations()) && - VerifyField(verifier, VT_ROWS) && - VerifyField(verifier, VT_COLS) && - VerifyOffset(verifier, VT_DISTANCES) && - verifier.VerifyVector(distances()) && - VerifyOffset(verifier, VT_DESTINATIONS) && - verifier.VerifyVector(destinations()) && - verifier.VerifyVectorOfTables(destinations()) && - VerifyOffset(verifier, VT_FALLBACK_SPEED_CELLS) && - verifier.VerifyVector(fallback_speed_cells()) && - verifier.EndTable(); - } - TableT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(TableT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct TableBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_durations(flatbuffers::Offset> durations) { - fbb_.AddOffset(Table::VT_DURATIONS, durations); - } - void add_rows(uint16_t rows) { - fbb_.AddElement(Table::VT_ROWS, rows, 0); - } - void add_cols(uint16_t cols) { - fbb_.AddElement(Table::VT_COLS, cols, 0); - } - void add_distances(flatbuffers::Offset> distances) { - fbb_.AddOffset(Table::VT_DISTANCES, distances); - } - void add_destinations(flatbuffers::Offset>> destinations) { - fbb_.AddOffset(Table::VT_DESTINATIONS, destinations); - } - void add_fallback_speed_cells(flatbuffers::Offset> fallback_speed_cells) { - fbb_.AddOffset(Table::VT_FALLBACK_SPEED_CELLS, fallback_speed_cells); - } - explicit TableBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - TableBuilder &operator=(const TableBuilder &); - flatbuffers::Offset
Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset
(end); - return o; - } -}; - -inline flatbuffers::Offset
CreateTable( - flatbuffers::FlatBufferBuilder &_fbb, - flatbuffers::Offset> durations = 0, - uint16_t rows = 0, - uint16_t cols = 0, - flatbuffers::Offset> distances = 0, - flatbuffers::Offset>> destinations = 0, - flatbuffers::Offset> fallback_speed_cells = 0) { - TableBuilder builder_(_fbb); - builder_.add_fallback_speed_cells(fallback_speed_cells); - builder_.add_destinations(destinations); - builder_.add_distances(distances); - builder_.add_durations(durations); - builder_.add_cols(cols); - builder_.add_rows(rows); - return builder_.Finish(); -} - -inline flatbuffers::Offset
CreateTableDirect( - flatbuffers::FlatBufferBuilder &_fbb, - const std::vector *durations = nullptr, - uint16_t rows = 0, - uint16_t cols = 0, - const std::vector *distances = nullptr, - const std::vector> *destinations = nullptr, - const std::vector *fallback_speed_cells = nullptr) { - auto durations__ = durations ? _fbb.CreateVector(*durations) : 0; - auto distances__ = distances ? _fbb.CreateVector(*distances) : 0; - auto destinations__ = destinations ? _fbb.CreateVector>(*destinations) : 0; - auto fallback_speed_cells__ = fallback_speed_cells ? _fbb.CreateVector(*fallback_speed_cells) : 0; - return osrm::engine::api::fbresult::CreateTable( - _fbb, - durations__, - rows, - cols, - distances__, - destinations__, - fallback_speed_cells__); -} - -flatbuffers::Offset
CreateTable(flatbuffers::FlatBufferBuilder &_fbb, const TableT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -struct ErrorT : public flatbuffers::NativeTable { - using TableType = Error; - std::string code; - std::string message; - ErrorT() { - } -}; - -struct Error FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = ErrorT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_CODE = 4, - VT_MESSAGE = 6 - }; - const flatbuffers::String *code() const { - return GetPointer(VT_CODE); - } - const flatbuffers::String *message() const { - return GetPointer(VT_MESSAGE); - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyOffset(verifier, VT_CODE) && - verifier.VerifyString(code()) && - VerifyOffset(verifier, VT_MESSAGE) && - verifier.VerifyString(message()) && - verifier.EndTable(); - } - ErrorT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(ErrorT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const ErrorT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct ErrorBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_code(flatbuffers::Offset code) { - fbb_.AddOffset(Error::VT_CODE, code); - } - void add_message(flatbuffers::Offset message) { - fbb_.AddOffset(Error::VT_MESSAGE, message); - } - explicit ErrorBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - ErrorBuilder &operator=(const ErrorBuilder &); - flatbuffers::Offset Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); - return o; - } -}; - -inline flatbuffers::Offset CreateError( - flatbuffers::FlatBufferBuilder &_fbb, - flatbuffers::Offset code = 0, - flatbuffers::Offset message = 0) { - ErrorBuilder builder_(_fbb); - builder_.add_message(message); - builder_.add_code(code); - return builder_.Finish(); -} - -inline flatbuffers::Offset CreateErrorDirect( - flatbuffers::FlatBufferBuilder &_fbb, - const char *code = nullptr, - const char *message = nullptr) { - auto code__ = code ? _fbb.CreateString(code) : 0; - auto message__ = message ? _fbb.CreateString(message) : 0; - return osrm::engine::api::fbresult::CreateError( - _fbb, - code__, - message__); -} - -flatbuffers::Offset CreateError(flatbuffers::FlatBufferBuilder &_fbb, const ErrorT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -struct FBResultT : public flatbuffers::NativeTable { - using TableType = FBResult; - bool error; - std::unique_ptr code; - std::string data_version; - std::vector> waypoints; - std::vector> routes; - std::unique_ptr table; - FBResultT() - : error(false) { - } -}; - -struct FBResult FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { - using NativeTableType = FBResultT; - enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { - VT_ERROR = 4, - VT_CODE = 6, - VT_DATA_VERSION = 8, - VT_WAYPOINTS = 10, - VT_ROUTES = 12, - VT_TABLE = 14 - }; - bool error() const { - return GetField(VT_ERROR, 0) != 0; - } - const osrm::engine::api::fbresult::Error *code() const { - return GetPointer(VT_CODE); - } - const flatbuffers::String *data_version() const { - return GetPointer(VT_DATA_VERSION); - } - const flatbuffers::Vector> *waypoints() const { - return GetPointer> *>(VT_WAYPOINTS); - } - const flatbuffers::Vector> *routes() const { - return GetPointer> *>(VT_ROUTES); - } - const osrm::engine::api::fbresult::Table *table() const { - return GetPointer(VT_TABLE); - } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyField(verifier, VT_ERROR) && - VerifyOffset(verifier, VT_CODE) && - verifier.VerifyTable(code()) && - VerifyOffset(verifier, VT_DATA_VERSION) && - verifier.VerifyString(data_version()) && - VerifyOffset(verifier, VT_WAYPOINTS) && - verifier.VerifyVector(waypoints()) && - verifier.VerifyVectorOfTables(waypoints()) && - VerifyOffset(verifier, VT_ROUTES) && - verifier.VerifyVector(routes()) && - verifier.VerifyVectorOfTables(routes()) && - VerifyOffset(verifier, VT_TABLE) && - verifier.VerifyTable(table()) && - verifier.EndTable(); - } - FBResultT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; - void UnPackTo(FBResultT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; - static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const FBResultT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); -}; - -struct FBResultBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_error(bool error) { - fbb_.AddElement(FBResult::VT_ERROR, static_cast(error), 0); - } - void add_code(flatbuffers::Offset code) { - fbb_.AddOffset(FBResult::VT_CODE, code); - } - void add_data_version(flatbuffers::Offset data_version) { - fbb_.AddOffset(FBResult::VT_DATA_VERSION, data_version); - } - void add_waypoints(flatbuffers::Offset>> waypoints) { - fbb_.AddOffset(FBResult::VT_WAYPOINTS, waypoints); - } - void add_routes(flatbuffers::Offset>> routes) { - fbb_.AddOffset(FBResult::VT_ROUTES, routes); - } - void add_table(flatbuffers::Offset table) { - fbb_.AddOffset(FBResult::VT_TABLE, table); - } - explicit FBResultBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { - start_ = fbb_.StartTable(); - } - FBResultBuilder &operator=(const FBResultBuilder &); - flatbuffers::Offset Finish() { - const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); - return o; - } -}; - -inline flatbuffers::Offset CreateFBResult( - flatbuffers::FlatBufferBuilder &_fbb, - bool error = false, - flatbuffers::Offset code = 0, - flatbuffers::Offset data_version = 0, - flatbuffers::Offset>> waypoints = 0, - flatbuffers::Offset>> routes = 0, - flatbuffers::Offset table = 0) { - FBResultBuilder builder_(_fbb); - builder_.add_table(table); - builder_.add_routes(routes); - builder_.add_waypoints(waypoints); - builder_.add_data_version(data_version); - builder_.add_code(code); - builder_.add_error(error); - return builder_.Finish(); -} - -inline flatbuffers::Offset CreateFBResultDirect( - flatbuffers::FlatBufferBuilder &_fbb, - bool error = false, - flatbuffers::Offset code = 0, - const char *data_version = nullptr, - const std::vector> *waypoints = nullptr, - const std::vector> *routes = nullptr, - flatbuffers::Offset table = 0) { - auto data_version__ = data_version ? _fbb.CreateString(data_version) : 0; - auto waypoints__ = waypoints ? _fbb.CreateVector>(*waypoints) : 0; - auto routes__ = routes ? _fbb.CreateVector>(*routes) : 0; - return osrm::engine::api::fbresult::CreateFBResult( - _fbb, - error, - code, - data_version__, - waypoints__, - routes__, - table); -} - -flatbuffers::Offset CreateFBResult(flatbuffers::FlatBufferBuilder &_fbb, const FBResultT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); - -inline WaypointT *Waypoint::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new WaypointT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void Waypoint::UnPackTo(WaypointT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = hint(); if (_e) _o->hint = _e->str(); }; - { auto _e = distance(); _o->distance = _e; }; - { auto _e = name(); if (_e) _o->name = _e->str(); }; - { auto _e = location(); if (_e) _o->location = std::unique_ptr(new osrm::engine::api::fbresult::Position(*_e)); }; - { auto _e = nodes(); if (_e) _o->nodes = std::unique_ptr(new osrm::engine::api::fbresult::Uint64Pair(*_e)); }; - { auto _e = matchings_index(); _o->matchings_index = _e; }; - { auto _e = waypoint_index(); _o->waypoint_index = _e; }; - { auto _e = alternatives_count(); _o->alternatives_count = _e; }; - { auto _e = trips_index(); _o->trips_index = _e; }; -} - -inline flatbuffers::Offset Waypoint::Pack(flatbuffers::FlatBufferBuilder &_fbb, const WaypointT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateWaypoint(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset CreateWaypoint(flatbuffers::FlatBufferBuilder &_fbb, const WaypointT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const WaypointT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _hint = _o->hint.empty() ? 0 : _fbb.CreateString(_o->hint); - auto _distance = _o->distance; - auto _name = _o->name.empty() ? 0 : _fbb.CreateString(_o->name); - auto _location = _o->location ? _o->location.get() : 0; - auto _nodes = _o->nodes ? _o->nodes.get() : 0; - auto _matchings_index = _o->matchings_index; - auto _waypoint_index = _o->waypoint_index; - auto _alternatives_count = _o->alternatives_count; - auto _trips_index = _o->trips_index; - return osrm::engine::api::fbresult::CreateWaypoint( - _fbb, - _hint, - _distance, - _name, - _location, - _nodes, - _matchings_index, - _waypoint_index, - _alternatives_count, - _trips_index); -} - -inline MetadataT *Metadata::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new MetadataT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void Metadata::UnPackTo(MetadataT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = datasource_names(); if (_e) { _o->datasource_names.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->datasource_names[_i] = _e->Get(_i)->str(); } } }; -} - -inline flatbuffers::Offset Metadata::Pack(flatbuffers::FlatBufferBuilder &_fbb, const MetadataT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateMetadata(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset CreateMetadata(flatbuffers::FlatBufferBuilder &_fbb, const MetadataT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const MetadataT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _datasource_names = _o->datasource_names.size() ? _fbb.CreateVectorOfStrings(_o->datasource_names) : 0; - return osrm::engine::api::fbresult::CreateMetadata( - _fbb, - _datasource_names); -} - -inline AnnotationT *Annotation::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new AnnotationT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void Annotation::UnPackTo(AnnotationT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = distance(); if (_e) { _o->distance.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->distance[_i] = _e->Get(_i); } } }; - { auto _e = duration(); if (_e) { _o->duration.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->duration[_i] = _e->Get(_i); } } }; - { auto _e = datasources(); if (_e) { _o->datasources.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->datasources[_i] = _e->Get(_i); } } }; - { auto _e = nodes(); if (_e) { _o->nodes.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->nodes[_i] = _e->Get(_i); } } }; - { auto _e = weight(); if (_e) { _o->weight.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->weight[_i] = _e->Get(_i); } } }; - { auto _e = speed(); if (_e) { _o->speed.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->speed[_i] = _e->Get(_i); } } }; - { auto _e = metadata(); if (_e) _o->metadata = std::unique_ptr(_e->UnPack(_resolver)); }; -} - -inline flatbuffers::Offset Annotation::Pack(flatbuffers::FlatBufferBuilder &_fbb, const AnnotationT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateAnnotation(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset CreateAnnotation(flatbuffers::FlatBufferBuilder &_fbb, const AnnotationT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const AnnotationT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _distance = _o->distance.size() ? _fbb.CreateVector(_o->distance) : 0; - auto _duration = _o->duration.size() ? _fbb.CreateVector(_o->duration) : 0; - auto _datasources = _o->datasources.size() ? _fbb.CreateVector(_o->datasources) : 0; - auto _nodes = _o->nodes.size() ? _fbb.CreateVector(_o->nodes) : 0; - auto _weight = _o->weight.size() ? _fbb.CreateVector(_o->weight) : 0; - auto _speed = _o->speed.size() ? _fbb.CreateVector(_o->speed) : 0; - auto _metadata = _o->metadata ? CreateMetadata(_fbb, _o->metadata.get(), _rehasher) : 0; - return osrm::engine::api::fbresult::CreateAnnotation( - _fbb, - _distance, - _duration, - _datasources, - _nodes, - _weight, - _speed, - _metadata); -} - -inline StepManeuverT *StepManeuver::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new StepManeuverT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void StepManeuver::UnPackTo(StepManeuverT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = location(); if (_e) _o->location = std::unique_ptr(new osrm::engine::api::fbresult::Position(*_e)); }; - { auto _e = bearing_before(); _o->bearing_before = _e; }; - { auto _e = bearing_after(); _o->bearing_after = _e; }; - { auto _e = type(); _o->type = _e; }; - { auto _e = modifier(); _o->modifier = _e; }; - { auto _e = exit(); _o->exit = _e; }; -} - -inline flatbuffers::Offset StepManeuver::Pack(flatbuffers::FlatBufferBuilder &_fbb, const StepManeuverT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateStepManeuver(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset CreateStepManeuver(flatbuffers::FlatBufferBuilder &_fbb, const StepManeuverT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const StepManeuverT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _location = _o->location ? _o->location.get() : 0; - auto _bearing_before = _o->bearing_before; - auto _bearing_after = _o->bearing_after; - auto _type = _o->type; - auto _modifier = _o->modifier; - auto _exit = _o->exit; - return osrm::engine::api::fbresult::CreateStepManeuver( - _fbb, - _location, - _bearing_before, - _bearing_after, - _type, - _modifier, - _exit); -} - -inline LaneT *Lane::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new LaneT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void Lane::UnPackTo(LaneT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = indications(); if (_e) { _o->indications.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->indications[_i] = static_cast(_e->Get(_i)); } } }; - { auto _e = valid(); _o->valid = _e; }; -} - -inline flatbuffers::Offset Lane::Pack(flatbuffers::FlatBufferBuilder &_fbb, const LaneT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateLane(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset CreateLane(flatbuffers::FlatBufferBuilder &_fbb, const LaneT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const LaneT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _indications = _o->indications.size() ? _fbb.CreateVectorScalarCast(flatbuffers::data(_o->indications), _o->indications.size()) : 0; - auto _valid = _o->valid; - return osrm::engine::api::fbresult::CreateLane( - _fbb, - _indications, - _valid); -} - -inline IntersectionT *Intersection::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new IntersectionT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void Intersection::UnPackTo(IntersectionT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = location(); if (_e) _o->location = std::unique_ptr(new osrm::engine::api::fbresult::Position(*_e)); }; - { auto _e = bearings(); if (_e) { _o->bearings.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->bearings[_i] = _e->Get(_i); } } }; - { auto _e = classes(); if (_e) { _o->classes.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->classes[_i] = _e->Get(_i)->str(); } } }; - { auto _e = entry(); if (_e) { _o->entry.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->entry[_i] = _e->Get(_i) != 0; } } }; - { auto _e = in_bearing(); _o->in_bearing = _e; }; - { auto _e = out_bearing(); _o->out_bearing = _e; }; - { auto _e = lanes(); if (_e) { _o->lanes.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->lanes[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } }; -} - -inline flatbuffers::Offset Intersection::Pack(flatbuffers::FlatBufferBuilder &_fbb, const IntersectionT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateIntersection(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset CreateIntersection(flatbuffers::FlatBufferBuilder &_fbb, const IntersectionT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const IntersectionT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _location = _o->location ? _o->location.get() : 0; - auto _bearings = _o->bearings.size() ? _fbb.CreateVector(_o->bearings) : 0; - auto _classes = _o->classes.size() ? _fbb.CreateVectorOfStrings(_o->classes) : 0; - auto _entry = _o->entry.size() ? _fbb.CreateVector(_o->entry) : 0; - auto _in_bearing = _o->in_bearing; - auto _out_bearing = _o->out_bearing; - auto _lanes = _o->lanes.size() ? _fbb.CreateVector> (_o->lanes.size(), [](size_t i, _VectorArgs *__va) { return CreateLane(*__va->__fbb, __va->__o->lanes[i].get(), __va->__rehasher); }, &_va ) : 0; - return osrm::engine::api::fbresult::CreateIntersection( - _fbb, - _location, - _bearings, - _classes, - _entry, - _in_bearing, - _out_bearing, - _lanes); -} - -inline StepT *Step::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new StepT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void Step::UnPackTo(StepT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = distance(); _o->distance = _e; }; - { auto _e = duration(); _o->duration = _e; }; - { auto _e = polyline(); if (_e) _o->polyline = _e->str(); }; - { auto _e = coordinates(); if (_e) { _o->coordinates.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->coordinates[_i] = *_e->Get(_i); } } }; - { auto _e = weight(); _o->weight = _e; }; - { auto _e = name(); if (_e) _o->name = _e->str(); }; - { auto _e = ref(); if (_e) _o->ref = _e->str(); }; - { auto _e = pronunciation(); if (_e) _o->pronunciation = _e->str(); }; - { auto _e = destinations(); if (_e) _o->destinations = _e->str(); }; - { auto _e = exits(); if (_e) _o->exits = _e->str(); }; - { auto _e = mode(); if (_e) _o->mode = _e->str(); }; - { auto _e = maneuver(); if (_e) _o->maneuver = std::unique_ptr(_e->UnPack(_resolver)); }; - { auto _e = intersections(); if (_e) { _o->intersections.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->intersections[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } }; - { auto _e = rotary_name(); if (_e) _o->rotary_name = _e->str(); }; - { auto _e = rotary_pronunciation(); if (_e) _o->rotary_pronunciation = _e->str(); }; - { auto _e = driving_side(); _o->driving_side = _e; }; -} - -inline flatbuffers::Offset Step::Pack(flatbuffers::FlatBufferBuilder &_fbb, const StepT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateStep(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset CreateStep(flatbuffers::FlatBufferBuilder &_fbb, const StepT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const StepT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _distance = _o->distance; - auto _duration = _o->duration; - auto _polyline = _o->polyline.empty() ? 0 : _fbb.CreateString(_o->polyline); - auto _coordinates = _o->coordinates.size() ? _fbb.CreateVectorOfStructs(_o->coordinates) : 0; - auto _weight = _o->weight; - auto _name = _o->name.empty() ? 0 : _fbb.CreateString(_o->name); - auto _ref = _o->ref.empty() ? 0 : _fbb.CreateString(_o->ref); - auto _pronunciation = _o->pronunciation.empty() ? 0 : _fbb.CreateString(_o->pronunciation); - auto _destinations = _o->destinations.empty() ? 0 : _fbb.CreateString(_o->destinations); - auto _exits = _o->exits.empty() ? 0 : _fbb.CreateString(_o->exits); - auto _mode = _o->mode.empty() ? 0 : _fbb.CreateString(_o->mode); - auto _maneuver = _o->maneuver ? CreateStepManeuver(_fbb, _o->maneuver.get(), _rehasher) : 0; - auto _intersections = _o->intersections.size() ? _fbb.CreateVector> (_o->intersections.size(), [](size_t i, _VectorArgs *__va) { return CreateIntersection(*__va->__fbb, __va->__o->intersections[i].get(), __va->__rehasher); }, &_va ) : 0; - auto _rotary_name = _o->rotary_name.empty() ? 0 : _fbb.CreateString(_o->rotary_name); - auto _rotary_pronunciation = _o->rotary_pronunciation.empty() ? 0 : _fbb.CreateString(_o->rotary_pronunciation); - auto _driving_side = _o->driving_side; - return osrm::engine::api::fbresult::CreateStep( - _fbb, - _distance, - _duration, - _polyline, - _coordinates, - _weight, - _name, - _ref, - _pronunciation, - _destinations, - _exits, - _mode, - _maneuver, - _intersections, - _rotary_name, - _rotary_pronunciation, - _driving_side); -} - -inline LegT *Leg::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new LegT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void Leg::UnPackTo(LegT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = distance(); _o->distance = _e; }; - { auto _e = duration(); _o->duration = _e; }; - { auto _e = weight(); _o->weight = _e; }; - { auto _e = summary(); if (_e) _o->summary = _e->str(); }; - { auto _e = annotations(); if (_e) _o->annotations = std::unique_ptr(_e->UnPack(_resolver)); }; - { auto _e = steps(); if (_e) { _o->steps.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->steps[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } }; -} - -inline flatbuffers::Offset Leg::Pack(flatbuffers::FlatBufferBuilder &_fbb, const LegT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateLeg(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset CreateLeg(flatbuffers::FlatBufferBuilder &_fbb, const LegT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const LegT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _distance = _o->distance; - auto _duration = _o->duration; - auto _weight = _o->weight; - auto _summary = _o->summary.empty() ? 0 : _fbb.CreateString(_o->summary); - auto _annotations = _o->annotations ? CreateAnnotation(_fbb, _o->annotations.get(), _rehasher) : 0; - auto _steps = _o->steps.size() ? _fbb.CreateVector> (_o->steps.size(), [](size_t i, _VectorArgs *__va) { return CreateStep(*__va->__fbb, __va->__o->steps[i].get(), __va->__rehasher); }, &_va ) : 0; - return osrm::engine::api::fbresult::CreateLeg( - _fbb, - _distance, - _duration, - _weight, - _summary, - _annotations, - _steps); -} - -inline RouteObjectT *RouteObject::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new RouteObjectT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void RouteObject::UnPackTo(RouteObjectT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = distance(); _o->distance = _e; }; - { auto _e = duration(); _o->duration = _e; }; - { auto _e = weight(); _o->weight = _e; }; - { auto _e = weight_name(); if (_e) _o->weight_name = _e->str(); }; - { auto _e = confidence(); _o->confidence = _e; }; - { auto _e = polyline(); if (_e) _o->polyline = _e->str(); }; - { auto _e = coordinates(); if (_e) { _o->coordinates.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->coordinates[_i] = *_e->Get(_i); } } }; - { auto _e = legs(); if (_e) { _o->legs.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->legs[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } }; -} - -inline flatbuffers::Offset RouteObject::Pack(flatbuffers::FlatBufferBuilder &_fbb, const RouteObjectT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateRouteObject(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset CreateRouteObject(flatbuffers::FlatBufferBuilder &_fbb, const RouteObjectT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const RouteObjectT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _distance = _o->distance; - auto _duration = _o->duration; - auto _weight = _o->weight; - auto _weight_name = _o->weight_name.empty() ? 0 : _fbb.CreateString(_o->weight_name); - auto _confidence = _o->confidence; - auto _polyline = _o->polyline.empty() ? 0 : _fbb.CreateString(_o->polyline); - auto _coordinates = _o->coordinates.size() ? _fbb.CreateVectorOfStructs(_o->coordinates) : 0; - auto _legs = _o->legs.size() ? _fbb.CreateVector> (_o->legs.size(), [](size_t i, _VectorArgs *__va) { return CreateLeg(*__va->__fbb, __va->__o->legs[i].get(), __va->__rehasher); }, &_va ) : 0; - return osrm::engine::api::fbresult::CreateRouteObject( - _fbb, - _distance, - _duration, - _weight, - _weight_name, - _confidence, - _polyline, - _coordinates, - _legs); -} - -inline TableT *Table::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new TableT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void Table::UnPackTo(TableT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = durations(); if (_e) { _o->durations.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->durations[_i] = _e->Get(_i); } } }; - { auto _e = rows(); _o->rows = _e; }; - { auto _e = cols(); _o->cols = _e; }; - { auto _e = distances(); if (_e) { _o->distances.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->distances[_i] = _e->Get(_i); } } }; - { auto _e = destinations(); if (_e) { _o->destinations.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->destinations[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } }; - { auto _e = fallback_speed_cells(); if (_e) { _o->fallback_speed_cells.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->fallback_speed_cells[_i] = _e->Get(_i); } } }; -} - -inline flatbuffers::Offset
Table::Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateTable(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset
CreateTable(flatbuffers::FlatBufferBuilder &_fbb, const TableT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const TableT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _durations = _o->durations.size() ? _fbb.CreateVector(_o->durations) : 0; - auto _rows = _o->rows; - auto _cols = _o->cols; - auto _distances = _o->distances.size() ? _fbb.CreateVector(_o->distances) : 0; - auto _destinations = _o->destinations.size() ? _fbb.CreateVector> (_o->destinations.size(), [](size_t i, _VectorArgs *__va) { return CreateWaypoint(*__va->__fbb, __va->__o->destinations[i].get(), __va->__rehasher); }, &_va ) : 0; - auto _fallback_speed_cells = _o->fallback_speed_cells.size() ? _fbb.CreateVector(_o->fallback_speed_cells) : 0; - return osrm::engine::api::fbresult::CreateTable( - _fbb, - _durations, - _rows, - _cols, - _distances, - _destinations, - _fallback_speed_cells); -} - -inline ErrorT *Error::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new ErrorT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void Error::UnPackTo(ErrorT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = code(); if (_e) _o->code = _e->str(); }; - { auto _e = message(); if (_e) _o->message = _e->str(); }; -} - -inline flatbuffers::Offset Error::Pack(flatbuffers::FlatBufferBuilder &_fbb, const ErrorT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateError(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset CreateError(flatbuffers::FlatBufferBuilder &_fbb, const ErrorT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const ErrorT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _code = _o->code.empty() ? 0 : _fbb.CreateString(_o->code); - auto _message = _o->message.empty() ? 0 : _fbb.CreateString(_o->message); - return osrm::engine::api::fbresult::CreateError( - _fbb, - _code, - _message); -} - -inline FBResultT *FBResult::UnPack(const flatbuffers::resolver_function_t *_resolver) const { - auto _o = new FBResultT(); - UnPackTo(_o, _resolver); - return _o; -} - -inline void FBResult::UnPackTo(FBResultT *_o, const flatbuffers::resolver_function_t *_resolver) const { - (void)_o; - (void)_resolver; - { auto _e = error(); _o->error = _e; }; - { auto _e = code(); if (_e) _o->code = std::unique_ptr(_e->UnPack(_resolver)); }; - { auto _e = data_version(); if (_e) _o->data_version = _e->str(); }; - { auto _e = waypoints(); if (_e) { _o->waypoints.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->waypoints[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } }; - { auto _e = routes(); if (_e) { _o->routes.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->routes[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } }; - { auto _e = table(); if (_e) _o->table = std::unique_ptr(_e->UnPack(_resolver)); }; -} - -inline flatbuffers::Offset FBResult::Pack(flatbuffers::FlatBufferBuilder &_fbb, const FBResultT* _o, const flatbuffers::rehasher_function_t *_rehasher) { - return CreateFBResult(_fbb, _o, _rehasher); -} - -inline flatbuffers::Offset CreateFBResult(flatbuffers::FlatBufferBuilder &_fbb, const FBResultT *_o, const flatbuffers::rehasher_function_t *_rehasher) { - (void)_rehasher; - (void)_o; - struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const FBResultT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _error = _o->error; - auto _code = _o->code ? CreateError(_fbb, _o->code.get(), _rehasher) : 0; - auto _data_version = _o->data_version.empty() ? 0 : _fbb.CreateString(_o->data_version); - auto _waypoints = _o->waypoints.size() ? _fbb.CreateVector> (_o->waypoints.size(), [](size_t i, _VectorArgs *__va) { return CreateWaypoint(*__va->__fbb, __va->__o->waypoints[i].get(), __va->__rehasher); }, &_va ) : 0; - auto _routes = _o->routes.size() ? _fbb.CreateVector> (_o->routes.size(), [](size_t i, _VectorArgs *__va) { return CreateRouteObject(*__va->__fbb, __va->__o->routes[i].get(), __va->__rehasher); }, &_va ) : 0; - auto _table = _o->table ? CreateTable(_fbb, _o->table.get(), _rehasher) : 0; - return osrm::engine::api::fbresult::CreateFBResult( - _fbb, - _error, - _code, - _data_version, - _waypoints, - _routes, - _table); -} - -inline const osrm::engine::api::fbresult::FBResult *GetFBResult(const void *buf) { - return flatbuffers::GetRoot(buf); -} - -inline const osrm::engine::api::fbresult::FBResult *GetSizePrefixedFBResult(const void *buf) { - return flatbuffers::GetSizePrefixedRoot(buf); -} - -inline bool VerifyFBResultBuffer( - flatbuffers::Verifier &verifier) { - return verifier.VerifyBuffer(nullptr); -} - -inline bool VerifySizePrefixedFBResultBuffer( - flatbuffers::Verifier &verifier) { - return verifier.VerifySizePrefixedBuffer(nullptr); -} - -inline void FinishFBResultBuffer( - flatbuffers::FlatBufferBuilder &fbb, - flatbuffers::Offset root) { - fbb.Finish(root); -} - -inline void FinishSizePrefixedFBResultBuffer( - flatbuffers::FlatBufferBuilder &fbb, - flatbuffers::Offset root) { - fbb.FinishSizePrefixed(root); -} - -inline std::unique_ptr UnPackFBResult( - const void *buf, - const flatbuffers::resolver_function_t *res = nullptr) { - return std::unique_ptr(GetFBResult(buf)->UnPack(res)); -} - -inline std::unique_ptr UnPackSizePrefixedFBResult( - const void *buf, - const flatbuffers::resolver_function_t *res = nullptr) { - return std::unique_ptr(GetSizePrefixedFBResult(buf)->UnPack(res)); -} - -} // namespace osrm - -#endif // FLATBUFFERS_GENERATED_FBRESULT_OSRM_ENGINE_API_FBRESULT_H_ diff --git a/include/engine/api/table_api.hpp b/include/engine/api/table_api.hpp index 82bfe4e3809..2ba49d2ddf3 100644 --- a/include/engine/api/table_api.hpp +++ b/include/engine/api/table_api.hpp @@ -137,7 +137,7 @@ class TableAPI final : public BaseAPI speed_cells = MakeEstimatesTable(fb_result, fallback_speed_cells); } - fbresult::TableBuilder table(fb_result); + fbresult::TableResultBuilder table(fb_result); table.add_destinations(destinations); table.add_rows(number_of_sources); table.add_cols(number_of_destinations); diff --git a/include/engine/guidance/assemble_geometry.hpp b/include/engine/guidance/assemble_geometry.hpp index 4001f6089d6..e6925c51f69 100644 --- a/include/engine/guidance/assemble_geometry.hpp +++ b/include/engine/guidance/assemble_geometry.hpp @@ -37,6 +37,14 @@ inline LegGeometry assembleGeometry(const datafacade::BaseDataFacade &facade, { LegGeometry geometry; + // each container will at most have `leg_data.size()` + 1/2 elements in it + // these additional 1/2 elements come from processing of very first and very last segment + geometry.locations.reserve(leg_data.size() + 2); + geometry.segment_distances.reserve(leg_data.size() + 1); + geometry.segment_offsets.reserve(leg_data.size() + 1); + geometry.annotations.reserve(leg_data.size() + 1); + geometry.node_ids.reserve(leg_data.size() + 2); + // segment 0 first and last geometry.segment_offsets.push_back(0); geometry.locations.push_back(source_node.location); diff --git a/include/engine/search_engine_data.hpp b/include/engine/search_engine_data.hpp index 7c885343f34..30d8e7c192b 100644 --- a/include/engine/search_engine_data.hpp +++ b/include/engine/search_engine_data.hpp @@ -5,8 +5,6 @@ #include "util/query_heap.hpp" #include "util/typedefs.hpp" -#include - namespace osrm::engine { @@ -148,4 +146,4 @@ template <> struct SearchEngineData }; } // namespace osrm::engine -#endif // SEARCH_ENGINE_DATA_HPP +#endif // SEARCH_ENGINE_DATA_HPP \ No newline at end of file diff --git a/include/util/query_heap.hpp b/include/util/query_heap.hpp index 367796ce414..fc71f208b4b 100644 --- a/include/util/query_heap.hpp +++ b/include/util/query_heap.hpp @@ -16,48 +16,6 @@ namespace osrm::util { -template class GenerationArrayStorage -{ - using GenerationCounter = std::uint16_t; - - public: - explicit GenerationArrayStorage(std::size_t size) - : positions(size, 0), generation(1), generations(size, 0) - { - } - - Key &operator[](NodeID node) - { - generation[node] = generation; - return positions[node]; - } - - Key peek_index(const NodeID node) const - { - if (generations[node] < generation) - { - return std::numeric_limits::max(); - } - return positions[node]; - } - - void Clear() - { - generation++; - // if generation overflows we end up at 0 again and need to clear the vector - if (generation == 0) - { - generation = 1; - std::fill(generations.begin(), generations.end(), 0); - } - } - - private: - GenerationCounter generation; - std::vector generations; - std::vector positions; -}; - template class ArrayStorage { public: @@ -73,29 +31,6 @@ template class ArrayStorage std::vector positions; }; -template class MapStorage -{ - public: - explicit MapStorage(std::size_t) {} - - Key &operator[](NodeID node) { return nodes[node]; } - - void Clear() { nodes.clear(); } - - Key peek_index(const NodeID node) const - { - const auto iter = nodes.find(node); - if (nodes.end() != iter) - { - return iter->second; - } - return std::numeric_limits::max(); - } - - private: - std::map nodes; -}; - template class UnorderedMapStorage { public: diff --git a/scripts/ci/windows-build.bat b/scripts/ci/windows-build.bat index 2102c9340e1..e2c04c0ebca 100644 --- a/scripts/ci/windows-build.bat +++ b/scripts/ci/windows-build.bat @@ -59,7 +59,6 @@ IF %ERRORLEVEL% NEQ 0 GOTO ERROR SET test_region=monaco SET test_region_ch=ch\monaco -SET test_region_corech=corech\monaco SET test_region_mld=mld\monaco SET test_osm=%test_region%.osm.pbf COPY %PROJECT_DIR%\test\data\%test_region%.osm.pbf %test_osm% @@ -69,18 +68,13 @@ IF %ERRORLEVEL% NEQ 0 GOTO ERROR MKDIR ch XCOPY %test_region%.osrm.* ch\ XCOPY %test_region%.osrm ch\ -MKDIR corech -XCOPY %test_region%.osrm.* corech\ -XCOPY %test_region%.osrm corech\ MKDIR mld XCOPY %test_region%.osrm.* mld\ XCOPY %test_region%.osrm mld\ %CONFIGURATION%\osrm-contract.exe %test_region_ch%.osrm -%CONFIGURATION%\osrm-contract.exe --core 0.8 %test_region_corech%.osrm %CONFIGURATION%\osrm-partition.exe %test_region_mld%.osrm %CONFIGURATION%\osrm-customize.exe %test_region_mld%.osrm XCOPY /Y ch\*.* ..\test\data\ch\ -XCOPY /Y corech\*.* ..\test\data\corech\ XCOPY /Y mld\*.* ..\test\data\mld\ unit_tests\%CONFIGURATION%\library-tests.exe IF %ERRORLEVEL% NEQ 0 GOTO ERROR diff --git a/scripts/update_dependencies.sh b/scripts/update_dependencies.sh index ce9e48af007..d9cebbe4b81 100755 --- a/scripts/update_dependencies.sh +++ b/scripts/update_dependencies.sh @@ -30,6 +30,9 @@ VTZERO_TAG=v1.1.0 FMT_PATH="fmtlib/fmt" FMT_TAG=v10.2.1 +FLATBUFFERS_PATH="google/flatbuffers" +FLATBUFFERS_TAG=v24.3.25 + function update_subtree () { name=$(echo "$1" | tr '[:lower:]' '[:upper:]') path=$(tmpvar=${name}_PATH && echo ${!tmpvar}) @@ -53,6 +56,6 @@ function update_subtree () { } ## Update dependencies -for dep in osmium sol rapidjson microtar protozero vtzero fmt; do +for dep in osmium sol rapidjson microtar protozero vtzero fmt flatbuffers; do update_subtree $dep done diff --git a/src/engine/search_engine_data.cpp b/src/engine/search_engine_data.cpp index 1eb497a469d..be9e731d53c 100644 --- a/src/engine/search_engine_data.cpp +++ b/src/engine/search_engine_data.cpp @@ -11,8 +11,10 @@ thread_local SearchEngineData::SearchEngineHeapPtr SearchEngineData::for thread_local SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_2; thread_local SearchEngineData::SearchEngineHeapPtr SearchEngineData::forward_heap_3; thread_local SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_3; -thread_local SearchEngineData::SearchEngineHeapPtr SearchEngineData::map_matching_forward_heap_1; -thread_local SearchEngineData::SearchEngineHeapPtr SearchEngineData::map_matching_reverse_heap_1; +thread_local SearchEngineData::SearchEngineHeapPtr + SearchEngineData::map_matching_forward_heap_1; +thread_local SearchEngineData::SearchEngineHeapPtr + SearchEngineData::map_matching_reverse_heap_1; thread_local SearchEngineData::ManyToManyHeapPtr SearchEngineData::many_to_many_heap; @@ -116,8 +118,15 @@ void SearchEngineData::InitializeOrClearManyToManyThreadLocalStorage(unsigne using MLD = routing_algorithms::mld::Algorithm; thread_local SearchEngineData::SearchEngineHeapPtr SearchEngineData::forward_heap_1; thread_local SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_1; +<<<<<<< HEAD thread_local SearchEngineData::MapMatchingHeapPtr SearchEngineData::map_matching_forward_heap_1; thread_local SearchEngineData::MapMatchingHeapPtr SearchEngineData::map_matching_reverse_heap_1; +======= +thread_local SearchEngineData::MapMatchingHeapPtr + SearchEngineData::map_matching_forward_heap_1; +thread_local SearchEngineData::MapMatchingHeapPtr + SearchEngineData::map_matching_reverse_heap_1; +>>>>>>> master thread_local SearchEngineData::ManyToManyHeapPtr SearchEngineData::many_to_many_heap; void SearchEngineData::InitializeOrClearMapMatchingThreadLocalStorage( @@ -178,4 +187,4 @@ void SearchEngineData::InitializeOrClearManyToManyThreadLocalStorage( many_to_many_heap.reset(new ManyToManyQueryHeap(number_of_nodes, number_of_boundary_nodes)); } } -} // namespace osrm::engine +} // namespace osrm::engine \ No newline at end of file diff --git a/src/tools/contract.cpp b/src/tools/contract.cpp index 6f7900e6220..e0b0a830b91 100644 --- a/src/tools/contract.cpp +++ b/src/tools/contract.cpp @@ -46,25 +46,16 @@ return_code parseArguments(int argc, boost::program_options::value(&contractor_config.requested_num_threads) ->default_value(std::thread::hardware_concurrency()), "Number of threads to use")( - "core,k", - boost::program_options::value(&contractor_config.core_factor)->default_value(1.0), - "DEPRECATED: Will always be 1.0. Percentage of the graph (in vertices) to contract " - "[0..1].")("segment-speed-file", - boost::program_options::value>( - &contractor_config.updater_config.segment_speed_lookup_paths) - ->composing(), - "Lookup files containing nodeA, nodeB, speed data to adjust edge weights")( + "segment-speed-file", + boost::program_options::value>( + &contractor_config.updater_config.segment_speed_lookup_paths) + ->composing(), + "Lookup files containing nodeA, nodeB, speed data to adjust edge weights")( "turn-penalty-file", boost::program_options::value>( &contractor_config.updater_config.turn_penalty_lookup_paths) ->composing(), "Lookup files containing from_, to_, via_nodes, and turn penalties to adjust turn weights")( - "level-cache,o", - boost::program_options::bool_switch(&contractor_config.use_cached_priority) - ->default_value(false), - "DEPRECATED: Will always be false. Use .level file to retain the contraction level for " - "each " - "node from the last run.")( "edge-weight-updates-over-factor", boost::program_options::value( &contractor_config.updater_config.log_edge_updates_factor) diff --git a/third_party/flatbuffers/.appveyor/check-generate-code.bat b/third_party/flatbuffers/.appveyor/check-generate-code.bat deleted file mode 100644 index ba7398a2f08..00000000000 --- a/third_party/flatbuffers/.appveyor/check-generate-code.bat +++ /dev/null @@ -1,41 +0,0 @@ -:: Copyright 2018 Google Inc. All rights reserved. -:: -:: Licensed under the Apache License, Version 2.0 (the "License"); -:: you may not use this file except in compliance with the License. -:: You may obtain a copy of the License at -:: -:: http://www.apache.org/licenses/LICENSE-2.0 -:: -:: Unless required by applicable law or agreed to in writing, software -:: distributed under the License is distributed on an "AS IS" BASIS, -:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -:: See the License for the specific language governing permissions and -:: limitations under the License. -set buildtype=Release -if "%1"=="-b" set buildtype=%2 - -cd tests -call generate_code.bat -b %buildtype% || goto FAIL - -:: TODO: Release and Debug builds produce differences here for some reason. -git checkout HEAD -- monster_test.bfbs -git checkout HEAD -- arrays_test.bfbs - -git -c core.autocrlf=true diff --exit-code --quiet || goto :DIFFFOUND -goto SUCCESS - -:DIFFFOUND -@echo "" >&2 -@echo "ERROR: ********************************************************" >&2 -@echo "ERROR: The following differences were found after running the" >&2 -@echo "ERROR: tests/generate_code.sh script. Maybe you forgot to run" >&2 -@echo "ERROR: it after making changes in a generator or schema?" >&2 -@echo "ERROR: ********************************************************" >&2 -@echo "" >&2 -@git -c core.autocrlf=true --no-pager diff --binary - -:FAIL -set EXITCODE=1 -:SUCCESS -cd .. -EXIT /B %EXITCODE% \ No newline at end of file diff --git a/third_party/flatbuffers/.bazelci/presubmit.yml b/third_party/flatbuffers/.bazelci/presubmit.yml index a6e38fde214..bcab65430d6 100644 --- a/third_party/flatbuffers/.bazelci/presubmit.yml +++ b/third_party/flatbuffers/.bazelci/presubmit.yml @@ -1,18 +1,38 @@ --- buildifier: latest +bazel: 6.4.0 platforms: - ubuntu1604: + ubuntu1804: + environment: + CC: clang + SWIFT_VERSION: "5.5.3" + SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION" + PATH: "$PATH:$SWIFT_HOME/usr/bin" + shell_commands: + - "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME" + - "mkdir $SWIFT_HOME" + - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu1804/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu18.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" build_targets: - - "..." + - "//..." test_targets: - - "..." - ubuntu1804: + - "//..." + ubuntu2004: + environment: + CC: clang + SWIFT_VERSION: "5.5.3" + SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION" + PATH: "$PATH:$SWIFT_HOME/usr/bin" + shell_commands: + - "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME" + - "mkdir $SWIFT_HOME" + - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2004/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu20.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" build_targets: - - "..." + - "//..." test_targets: - - "..." + - "//..." macos: + xcode_version: "14.2" build_targets: - - "..." + - "//..." test_targets: - - "..." + - "//..." diff --git a/third_party/flatbuffers/.bazelignore b/third_party/flatbuffers/.bazelignore new file mode 100644 index 00000000000..3c3629e647f --- /dev/null +++ b/third_party/flatbuffers/.bazelignore @@ -0,0 +1 @@ +node_modules diff --git a/third_party/flatbuffers/.bazelrc b/third_party/flatbuffers/.bazelrc new file mode 100644 index 00000000000..f9f47a74237 --- /dev/null +++ b/third_party/flatbuffers/.bazelrc @@ -0,0 +1,4 @@ +# We cannot use "common" here because the "version" command doesn't support +# --deleted_packages. We need to specify it for both build and query instead. +build --deleted_packages=tests/ts/bazel_repository_test_dir +query --deleted_packages=tests/ts/bazel_repository_test_dir diff --git a/third_party/flatbuffers/.clang-tidy b/third_party/flatbuffers/.clang-tidy new file mode 100644 index 00000000000..7e9c1b7c7d6 --- /dev/null +++ b/third_party/flatbuffers/.clang-tidy @@ -0,0 +1,347 @@ +--- +FormatStyle: "file" +WarningsAsErrors: "*" +HeaderFilterRegex: ".*" +Checks: "google-build-explicit-make-pair, + google-build-namespaces, + google-build-using-namespace, + google-default-arguments, + google-explicit-constructor, + google-global-names-in-headers, + google-objc-avoid-nsobject-new, + google-objc-avoid-throwing-exception, + google-objc-function-naming, + google-objc-global-variable-declaration, + google-readability-avoid-underscore-in-googletest-name, + google-readability-braces-around-statements, + google-readability-casting, + google-readability-function-size, + google-readability-namespace-comments, + google-runtime-int, + google-runtime-operator, + google-upgrade-googletest-case, + clang-analyzer-apiModeling.StdCLibraryFunctions, + clang-analyzer-apiModeling.TrustNonnull, + clang-analyzer-apiModeling.google.GTest, + clang-analyzer-apiModeling.llvm.CastValue, + clang-analyzer-apiModeling.llvm.ReturnValue, + clang-analyzer-core.CallAndMessage, + clang-analyzer-core.CallAndMessageModeling, + clang-analyzer-core.DivideZero, + clang-analyzer-core.DynamicTypePropagation, + clang-analyzer-core.NonNullParamChecker, + clang-analyzer-core.NonnilStringConstants, + clang-analyzer-core.NullDereference, + clang-analyzer-core.StackAddrEscapeBase, + clang-analyzer-core.StackAddressEscape, + clang-analyzer-core.UndefinedBinaryOperatorResult, + clang-analyzer-core.VLASize, + clang-analyzer-core.builtin.BuiltinFunctions, + clang-analyzer-core.builtin.NoReturnFunctions, + clang-analyzer-core.uninitialized.ArraySubscript, + clang-analyzer-core.uninitialized.Assign, + clang-analyzer-core.uninitialized.Branch, + clang-analyzer-core.uninitialized.CapturedBlockVariable, + clang-analyzer-core.uninitialized.UndefReturn, + clang-analyzer-cplusplus.InnerPointer, + clang-analyzer-cplusplus.Move, + clang-analyzer-cplusplus.NewDelete, + clang-analyzer-cplusplus.NewDeleteLeaks, + clang-analyzer-cplusplus.PlacementNew, + clang-analyzer-cplusplus.PureVirtualCall, + clang-analyzer-cplusplus.SelfAssignment, + clang-analyzer-cplusplus.SmartPtrModeling, + clang-analyzer-cplusplus.StringChecker, + clang-analyzer-cplusplus.VirtualCallModeling, + clang-analyzer-deadcode.DeadStores, + clang-analyzer-fuchsia.HandleChecker, + clang-analyzer-nullability.NullPassedToNonnull, + clang-analyzer-nullability.NullReturnedFromNonnull, + clang-analyzer-nullability.NullabilityBase, + clang-analyzer-nullability.NullableDereferenced, + clang-analyzer-nullability.NullablePassedToNonnull, + clang-analyzer-nullability.NullableReturnedFromNonnull, + clang-analyzer-optin.cplusplus.UninitializedObject, + clang-analyzer-optin.cplusplus.VirtualCall, + clang-analyzer-optin.mpi.MPI-Checker, + clang-analyzer-optin.osx.OSObjectCStyleCast, + clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker, + clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker, + clang-analyzer-optin.performance.GCDAntipattern, + clang-analyzer-optin.performance.Padding, + clang-analyzer-optin.portability.UnixAPI, + clang-analyzer-osx.API, + clang-analyzer-osx.MIG, + clang-analyzer-osx.NSOrCFErrorDerefChecker, + clang-analyzer-osx.NumberObjectConversion, + clang-analyzer-osx.OSObjectRetainCount, + clang-analyzer-osx.ObjCProperty, + clang-analyzer-osx.SecKeychainAPI, + clang-analyzer-osx.cocoa.AtSync, + clang-analyzer-osx.cocoa.AutoreleaseWrite, + clang-analyzer-osx.cocoa.ClassRelease, + clang-analyzer-osx.cocoa.Dealloc, + clang-analyzer-osx.cocoa.IncompatibleMethodTypes, + clang-analyzer-osx.cocoa.Loops, + clang-analyzer-osx.cocoa.MissingSuperCall, + clang-analyzer-osx.cocoa.NSAutoreleasePool, + clang-analyzer-osx.cocoa.NSError, + clang-analyzer-osx.cocoa.NilArg, + clang-analyzer-osx.cocoa.NonNilReturnValue, + clang-analyzer-osx.cocoa.ObjCGenerics, + clang-analyzer-osx.cocoa.RetainCount, + clang-analyzer-osx.cocoa.RetainCountBase, + clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak, + clang-analyzer-osx.cocoa.SelfInit, + clang-analyzer-osx.cocoa.SuperDealloc, + clang-analyzer-osx.cocoa.UnusedIvars, + clang-analyzer-osx.cocoa.VariadicMethodTypes, + clang-analyzer-osx.coreFoundation.CFError, + clang-analyzer-osx.coreFoundation.CFNumber, + clang-analyzer-osx.coreFoundation.CFRetainRelease, + clang-analyzer-osx.coreFoundation.containers.OutOfBounds, + clang-analyzer-osx.coreFoundation.containers.PointerSizedValues, + clang-analyzer-security.FloatLoopCounter, + clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, + clang-analyzer-security.insecureAPI.SecuritySyntaxChecker, + clang-analyzer-security.insecureAPI.UncheckedReturn, + clang-analyzer-security.insecureAPI.bcmp, + clang-analyzer-security.insecureAPI.bcopy, + clang-analyzer-security.insecureAPI.bzero, + clang-analyzer-security.insecureAPI.decodeValueOfObjCType, + clang-analyzer-security.insecureAPI.getpw, + clang-analyzer-security.insecureAPI.gets, + clang-analyzer-security.insecureAPI.mkstemp, + clang-analyzer-security.insecureAPI.mktemp, + clang-analyzer-security.insecureAPI.rand, + clang-analyzer-security.insecureAPI.strcpy, + clang-analyzer-security.insecureAPI.vfork, + clang-analyzer-unix.API, + clang-analyzer-unix.DynamicMemoryModeling, + clang-analyzer-unix.Malloc, + clang-analyzer-unix.MallocSizeof, + clang-analyzer-unix.MismatchedDeallocator, + clang-analyzer-unix.Vfork, + clang-analyzer-unix.cstring.BadSizeArg, + clang-analyzer-unix.cstring.CStringModeling, + clang-analyzer-unix.cstring.NullArg, + clang-analyzer-valist.CopyToSelf, + clang-analyzer-valist.Uninitialized, + clang-analyzer-valist.Unterminated, + clang-analyzer-valist.ValistBase, + clang-analyzer-webkit.NoUncountedMemberChecker, + clang-analyzer-webkit.RefCntblBaseVirtualDtor, + clang-analyzer-webkit.UncountedLambdaCapturesChecker, + +################################################ Optional checks ################################################ + + #google-readability-todo, + #bugprone-argument-comment, + #bugprone-assert-side-effect, + #bugprone-bad-signal-to-kill-thread, + #bugprone-bool-pointer-implicit-conversion, + #bugprone-branch-clone, + #bugprone-copy-constructor-init, + #bugprone-dangling-handle, + #bugprone-dynamic-static-initializers, + #bugprone-easily-swappable-parameters, + #bugprone-exception-escape, + #bugprone-fold-init-type, + #bugprone-forward-declaration-namespace, + #bugprone-forwarding-reference-overload, + #bugprone-implicit-widening-of-multiplication-result, + #bugprone-inaccurate-erase, + #bugprone-incorrect-roundings, + #bugprone-infinite-loop, + #bugprone-integer-division, + #bugprone-lambda-function-name, + #bugprone-macro-parentheses, + #bugprone-macro-repeated-side-effects, + #bugprone-misplaced-operator-in-strlen-in-alloc, + #bugprone-misplaced-pointer-arithmetic-in-alloc, + #bugprone-misplaced-widening-cast, + #bugprone-move-forwarding-reference, + #bugprone-multiple-statement-macro, + #bugprone-narrowing-conversions, + #bugprone-no-escape, + #bugprone-not-null-terminated-result, + #bugprone-parent-virtual-call, + #bugprone-posix-return, + #bugprone-redundant-branch-condition, + #bugprone-reserved-identifier, + #bugprone-signal-handler, + #bugprone-signed-char-misuse, + #bugprone-sizeof-container, + #bugprone-sizeof-expression, + #bugprone-spuriously-wake-up-functions, + #bugprone-string-constructor, + #bugprone-string-integer-assignment, + #bugprone-string-literal-with-embedded-nul, + #bugprone-stringview-nullptr, + #bugprone-suspicious-enum-usage, + #bugprone-suspicious-include, + #bugprone-suspicious-memory-comparison, + #bugprone-suspicious-memset-usage, + #bugprone-suspicious-missing-comma, + #bugprone-suspicious-semicolon, + #bugprone-suspicious-string-compare, + #bugprone-swapped-arguments, + #bugprone-terminating-continue, + #bugprone-throw-keyword-missing, + #bugprone-too-small-loop-variable, + #bugprone-undefined-memory-manipulation, + #bugprone-undelegated-constructor, + #bugprone-unhandled-exception-at-new, + #bugprone-unhandled-self-assignment, + #bugprone-unused-raii, + #bugprone-unused-return-value, + #bugprone-use-after-move, + #bugprone-virtual-near-miss, + #cppcoreguidelines-avoid-c-arrays, + #cppcoreguidelines-avoid-goto, + #cppcoreguidelines-avoid-magic-numbers, + #cppcoreguidelines-avoid-non-const-global-variables, + #cppcoreguidelines-c-copy-assignment-signature, + #cppcoreguidelines-explicit-virtual-functions, + #cppcoreguidelines-init-variables, + #cppcoreguidelines-interfaces-global-init, + #cppcoreguidelines-macro-usage, + #cppcoreguidelines-narrowing-conversions, + #cppcoreguidelines-no-malloc, + #cppcoreguidelines-non-private-member-variables-in-classes, + #cppcoreguidelines-owning-memory, + #cppcoreguidelines-prefer-member-initializer, + #cppcoreguidelines-pro-bounds-array-to-pointer-decay, + #cppcoreguidelines-pro-bounds-constant-array-index, + #cppcoreguidelines-pro-bounds-pointer-arithmetic, + #cppcoreguidelines-pro-type-const-cast, + #cppcoreguidelines-pro-type-cstyle-cast, + #cppcoreguidelines-pro-type-member-init, + #cppcoreguidelines-pro-type-reinterpret-cast, + #cppcoreguidelines-pro-type-static-cast-downcast, + #cppcoreguidelines-pro-type-union-access, + #cppcoreguidelines-pro-type-vararg, + #cppcoreguidelines-slicing, + #cppcoreguidelines-special-member-functions, + #cppcoreguidelines-virtual-class-destructor, + #hicpp-avoid-c-arrays, + #hicpp-avoid-goto, + #hicpp-braces-around-statements, + #hicpp-deprecated-headers, + #hicpp-exception-baseclass, + #hicpp-explicit-conversions, + #hicpp-function-size, + #hicpp-invalid-access-moved, + #hicpp-member-init, + #hicpp-move-const-arg, + #hicpp-multiway-paths-covered, + #hicpp-named-parameter, + #hicpp-new-delete-operators, + #hicpp-no-array-decay, + #hicpp-no-assembler, + #hicpp-no-malloc, + #hicpp-noexcept-move, + #hicpp-signed-bitwise, + #hicpp-special-member-functions, + #hicpp-static-assert, + #hicpp-undelegated-constructor, + #hicpp-uppercase-literal-suffix, + #hicpp-use-auto, + #hicpp-use-emplace, + #hicpp-use-equals-default, + #hicpp-use-equals-delete, + #hicpp-use-noexcept, + #hicpp-use-nullptr, + #hicpp-use-override, + #hicpp-vararg, + #modernize-avoid-bind, + #modernize-avoid-c-arrays, + #modernize-concat-nested-namespaces, + #modernize-deprecated-headers, + #modernize-deprecated-ios-base-aliases, + #modernize-loop-convert, + #modernize-make-shared, + #modernize-make-unique, + #modernize-pass-by-value, + #modernize-raw-string-literal, + #modernize-redundant-void-arg, + #modernize-replace-auto-ptr, + #modernize-replace-disallow-copy-and-assign-macro, + #modernize-replace-random-shuffle, + #modernize-return-braced-init-list, + #modernize-shrink-to-fit, + #modernize-unary-static-assert, + #modernize-use-auto, + #modernize-use-bool-literals, + #modernize-use-default-member-init, + #modernize-use-emplace, + #modernize-use-equals-default, + #modernize-use-equals-delete, + #modernize-use-nodiscard, + #modernize-use-noexcept, + #modernize-use-nullptr, + #modernize-use-override, + #modernize-use-trailing-return-type, + #modernize-use-transparent-functors, + #modernize-use-uncaught-exceptions, + #modernize-use-using, + #performance-faster-string-find, + #performance-for-range-copy, + #performance-implicit-conversion-in-loop, + #performance-inefficient-algorithm, + #performance-inefficient-string-concatenation, + #performance-inefficient-vector-operation, + #performance-move-const-arg, + #performance-move-constructor-init, + #performance-no-automatic-move, + #performance-no-int-to-ptr, + #performance-noexcept-move-constructor, + #performance-trivially-destructible, + #performance-type-promotion-in-math-fn, + #performance-unnecessary-copy-initialization, + #performance-unnecessary-value-param, + #portability-restrict-system-includes, + #portability-simd-intrinsics, + #readability-avoid-const-params-in-decls, + #readability-braces-around-statements, + #readability-const-return-type, + #readability-container-contains, + #readability-container-data-pointer, + #readability-container-size-empty, + #readability-convert-member-functions-to-static, + #readability-delete-null-pointer, + #readability-duplicate-include, + #readability-else-after-return, + #readability-function-cognitive-complexity, + #readability-function-size, + #readability-identifier-length, + #readability-identifier-naming, + #readability-implicit-bool-conversion, + #readability-inconsistent-declaration-parameter-name, + #readability-isolate-declaration, + #readability-magic-numbers, + #readability-make-member-function-const, + #readability-misleading-indentation, + #readability-misplaced-array-index, + #readability-named-parameter, + #readability-non-const-parameter, + #readability-qualified-auto, + #readability-redundant-access-specifiers, + #readability-redundant-control-flow, + #readability-redundant-declaration, + #readability-redundant-function-ptr-dereference, + #readability-redundant-member-init, + #readability-redundant-preprocessor, + #readability-redundant-smartptr-get, + #readability-redundant-string-cstr, + #readability-redundant-string-init, + #readability-simplify-boolean-expr, + #readability-simplify-subscript-expr, + #readability-static-accessed-through-instance, + #readability-static-definition-in-anonymous-namespace, + #readability-string-compare, + #readability-suspicious-call-argument, + #readability-uniqueptr-delete-release, + #readability-uppercase-literal-suffix, + #readability-use-anyofallof + " diff --git a/third_party/flatbuffers/.editorconfig b/third_party/flatbuffers/.editorconfig index 6c549666eb3..6689bab2314 100644 --- a/third_party/flatbuffers/.editorconfig +++ b/third_party/flatbuffers/.editorconfig @@ -5,3 +5,4 @@ root = true indent_style = space indent_size = 2 insert_final_newline = true +trim_trailing_whitespace = true diff --git a/third_party/flatbuffers/.eslintrc.js b/third_party/flatbuffers/.eslintrc.js new file mode 100644 index 00000000000..321169b07c0 --- /dev/null +++ b/third_party/flatbuffers/.eslintrc.js @@ -0,0 +1,13 @@ +/* eslint-env node */ + +module.exports = { + root: true, + parser: '@typescript-eslint/parser', + plugins: [ + '@typescript-eslint', + ], + extends: [ + 'eslint:recommended', + 'plugin:@typescript-eslint/recommended', + ] +}; \ No newline at end of file diff --git a/third_party/flatbuffers/.github/ISSUE_TEMPLATE.md b/third_party/flatbuffers/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index a053fe4406a..00000000000 --- a/third_party/flatbuffers/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,12 +0,0 @@ -Thank you for submitting an issue! - -Please make sure you include the names of the affected language(s), compiler version(s), operating system version(s), and FlatBuffers version(s) in your issue title. - -This helps us get the correct maintainers to look at your issue. Here are examples of good titles: - -- Crash when accessing FlatBuffer [C++, gcc 4.8, OS X, master] -- Flatc converts a protobuf 'bytes' field to 'string' in fbs schema file [all languages, FlatBuffers 1.4] - -Include other details as appropriate. - -Thanks! diff --git a/third_party/flatbuffers/.github/PULL_REQUEST_TEMPLATE.md b/third_party/flatbuffers/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 819946532cc..00000000000 --- a/third_party/flatbuffers/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,16 +0,0 @@ -Thank you for submitting a PR! - -Please make sure you include the names of the affected language(s) in your PR title. -This helps us get the correct maintainers to look at your issue. - -If you make changes to any of the code generators, be sure to run -`cd tests && sh generate_code.sh` (or equivalent .bat) and include the generated -code changes in the PR. This allows us to better see the effect of the PR. - -If your PR includes C++ code, please adhere to the Google C++ Style Guide, -and don't forget we try to support older compilers (e.g. VS2010, GCC 4.6.3), -so only some C++11 support is available. - -Include other details as appropriate. - -Thanks! diff --git a/third_party/flatbuffers/.github/stale.yml b/third_party/flatbuffers/.github/stale.yml deleted file mode 100644 index 84ff87b56ce..00000000000 --- a/third_party/flatbuffers/.github/stale.yml +++ /dev/null @@ -1,18 +0,0 @@ -# Number of days of inactivity before an issue becomes stale -daysUntilStale: 365 -# Number of days of inactivity before a stale issue is closed -daysUntilClose: 14 -# Issues with these labels will never be considered stale -exemptLabels: - - pinned - - security -# Label to use when marking an issue as stale -staleLabel: stale -# Comment to post when marking an issue as stale. Set to `false` to disable -markComment: > - This issue has been automatically marked as stale because it has not had - activity for 1 year. It will be automatically closed if no further activity occurs. - To keep it open, simply post a new comment. Maintainers will re-open on - new activity. Thank you for your contributions. -# Comment to post when closing a stale issue. Set to `false` to disable -closeComment: false diff --git a/third_party/flatbuffers/.gitignore b/third_party/flatbuffers/.gitignore index b7b41acb330..828ca1d618e 100644 --- a/third_party/flatbuffers/.gitignore +++ b/third_party/flatbuffers/.gitignore @@ -1,6 +1,13 @@ *_wire.txt *_wire.bin .DS_Store +**/.build +build +**/Packages +/*.xcodeproj +**/xcuserdata/ +**/xcshareddata/ +**/.swiftpm/ *.o *.o.d *.class @@ -39,12 +46,16 @@ project.properties proguard-project.txt linklint_results Makefile +flatbenchmark +flatbenchmark.exe flatc flatc.exe flathash flathash.exe flattests flattests.exe +flattests_cpp17 +flattests_cpp17.exe flatsamplebinary flatsamplebinary.exe flatsampletext @@ -63,13 +74,11 @@ tests/monsterdata_go_wire.mon tests/monsterdata_javascript_wire.mon tests/monsterdata_lobster_wire.mon tests/monsterdata_rust_wire.mon -tests/unicode_test.mon -tests/ts/ tests/php/ CMakeLists.txt.user CMakeScripts/** CTestTestfile.cmake -FlatbuffersConfigVersion.cmake +flatbuffers-config-version.cmake FlatBuffers.cbp build/Xcode/FlatBuffers.xcodeproj/project.xcworkspace/** build/Xcode/FlatBuffers.xcodeproj/xcuserdata/** @@ -79,6 +88,7 @@ java/*.iml .idea *.iml target +java/target **/*.pyc build/VS2010/FlatBuffers.sdf build/VS2010/FlatBuffers.opensdf @@ -96,7 +106,10 @@ android/build/ samples/android/.externalNativeBuild/ samples/android/.gradle/ samples/android/build/ -js/flatbuffers.mjs +js/**/*.js +js/**/*.d.ts +mjs/**/*.js +mjs/**/*.d.ts /bazel-bin /bazel-flatbuffers /bazel-genfiles @@ -116,3 +129,27 @@ dart/doc/api/ Cargo.lock .corpus** .seed** +.crash** +grpc/google/ +**/Package.resolved +.clangd/** +package-lock.json +/*.ilk +/*.pdb +.clwb +yarn-error.log +.cache/ +/flatbuffers.lib +.cmake/ +**/dist +**/vendor +**/go.sum +flatbuffers.pc +**/FlatBuffers.Test.Swift.xcodeproj +**/html/** +**/latex/** +# https://cmake.org/cmake/help/latest/module/FetchContent.html#variable:FETCHCONTENT_BASE_DIR +cmake-build-debug/ +_deps/ +**/.gradle/** +kotlin/**/generated diff --git a/third_party/flatbuffers/.npmrc b/third_party/flatbuffers/.npmrc new file mode 100644 index 00000000000..84ff0791f0d --- /dev/null +++ b/third_party/flatbuffers/.npmrc @@ -0,0 +1 @@ +hoist=false diff --git a/third_party/flatbuffers/.travis.yml b/third_party/flatbuffers/.travis.yml deleted file mode 100644 index fd2959f5043..00000000000 --- a/third_party/flatbuffers/.travis.yml +++ /dev/null @@ -1,221 +0,0 @@ -env: - global: - # Set at the root level as this is ignored when set under matrix.env. - - GCC_VERSION="4.9" - # Fail on first error if UBSAN or ASAN enabled for a target - - UBSAN_OPTIONS=halt_on_error=1 - - ASAN_OPTIONS=halt_on_error=1 - # Travis machines have 2 cores - - JOBS=2 - - MAKEFLAGS="-j 2" - -conan-linux: &conan-linux - os: linux - dist: xenial - language: python - python: "3.7" - services: - - docker - install: - - ./conan/travis/install.sh - script: - - ./conan/travis/build.sh - if: tag IS present - -conan-linux-master: &conan-linux-master - os: linux - dist: xenial - language: python - python: "3.7" - services: - - docker - install: - - 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then bash ./conan/travis/install.sh; fi' - script: - - 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then bash ./conan/travis/build.sh; fi' - branches: - only: - - master - -conan-osx: &conan-osx - os: osx - language: generic - install: - - ./conan/travis/install.sh - script: - - ./conan/travis/build.sh - if: tag IS present - -matrix: - include: - #- language: python - # python: "2.7" - # install: - # - "pip install wheel twine" - # script: - # - "cd python/" - # - 'VERSION="$TRAVIS_TAG" python setup.py sdist bdist_wheel' - # - "cd ../" - # deploy: - # # Checkpointed release builds. - # - provider: script - # script: .travis/deploy-python.sh - # skip_cleanup: true - # on: - # tags: true - # # all_branches must be set with tags: true. See below post: - # # https://stackoverflow.com/a/27775257/1076585 - # all_branches: true - # # Produce a new build for the cutting edge when master changes. - # - provider: script - # script: .travis/deploy-python.sh - # skip_cleanup: true - # on: - # branch: master - - language: cpp - os: - - linux - - addons: - apt: - packages: - - docker-ce - script: - - bash .travis/build-and-run-docker-test-containers.sh - - - language: cpp - os: - - linux - - compiler: - - gcc - - env: - matrix: - - BUILD_TYPE=Debug - - BUILD_TYPE=Release - - before_install: - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get update -qq; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get install -qq g++-$GCC_VERSION; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get install -qq gcc-$GCC_VERSION; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s -v -f $(which g++-$GCC_VERSION) /usr/bin/g++; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s -v -f $(which gcc-$GCC_VERSION) /usr/bin/gcc; fi - - script: - - bash .travis/check-sources.sh - - bash grpc/build_grpc.sh - - cmake . - -DCMAKE_BUILD_TYPE=$BUILD_TYPE - -DFLATBUFFERS_BUILD_GRPCTEST=ON - -DGRPC_INSTALL_PATH=$TRAVIS_BUILD_DIR/google/grpc/install - -DPROTOBUF_DOWNLOAD_PATH=$TRAVIS_BUILD_DIR/google/grpc/third_party/protobuf - -DFLATBUFFERS_CODE_SANITIZE=ON - - cmake --build . -- -j${JOBS} - - LD_LIBRARY_PATH=$TRAVIS_BUILD_DIR/google/grpc/install/lib ctest --extra-verbose --output-on-failure - - bash .travis/check-generate-code.sh - - - language: cpp - os: osx - osx_image: xcode9.3 - env: - matrix: - - BUILD_TYPE=Debug - - BUILD_TYPE=Release - - script: - - bash grpc/build_grpc.sh - - cmake . - -DCMAKE_BUILD_TYPE=$BUILD_TYPE - -DFLATBUFFERS_BUILD_GRPCTEST=ON - -DGRPC_INSTALL_PATH=$TRAVIS_BUILD_DIR/google/grpc/install - -DPROTOBUF_DOWNLOAD_PATH=$TRAVIS_BUILD_DIR/google/grpc/third_party/protobuf - -DFLATBUFFERS_CODE_SANITIZE=ON - - cmake --build . -- -j${JOBS} - - DYLD_LIBRARY_PATH=$TRAVIS_BUILD_DIR/google/grpc/install/lib ctest --extra-verbose --output-on-failure - - bash .travis/check-generate-code.sh - - - <<: *conan-linux-master - env: CONAN_GCC_VERSIONS=8 CONAN_DOCKER_IMAGE=conanio/gcc8 - - <<: *conan-linux - env: CONAN_GCC_VERSIONS=4.9 CONAN_DOCKER_IMAGE=conanio/gcc49 - - <<: *conan-linux - env: CONAN_GCC_VERSIONS=5 CONAN_DOCKER_IMAGE=conanio/gcc5 - - <<: *conan-linux - env: CONAN_GCC_VERSIONS=6 CONAN_DOCKER_IMAGE=conanio/gcc6 - - <<: *conan-linux - env: CONAN_GCC_VERSIONS=7 CONAN_DOCKER_IMAGE=conanio/gcc7 - - <<: *conan-linux - env: CONAN_GCC_VERSIONS=8 CONAN_DOCKER_IMAGE=conanio/gcc8 - - <<: *conan-linux - env: CONAN_GCC_VERSIONS=9 CONAN_DOCKER_IMAGE=conanio/gcc9 - - <<: *conan-linux - env: CONAN_CLANG_VERSIONS=3.9 CONAN_DOCKER_IMAGE=conanio/clang39 - - <<: *conan-linux - env: CONAN_CLANG_VERSIONS=4.0 CONAN_DOCKER_IMAGE=conanio/clang40 - - <<: *conan-linux - env: CONAN_CLANG_VERSIONS=5.0 CONAN_DOCKER_IMAGE=conanio/clang50 - - <<: *conan-linux - env: CONAN_CLANG_VERSIONS=6.0 CONAN_DOCKER_IMAGE=conanio/clang60 - - <<: *conan-linux - env: CONAN_CLANG_VERSIONS=7.0 CONAN_DOCKER_IMAGE=conanio/clang7 - - <<: *conan-linux - env: CONAN_CLANG_VERSIONS=8 CONAN_DOCKER_IMAGE=conanio/clang8 - - <<: *conan-osx - osx_image: xcode7.3 - env: CONAN_APPLE_CLANG_VERSIONS=7.3 - - <<: *conan-osx - osx_image: xcode8.3 - env: CONAN_APPLE_CLANG_VERSIONS=8.1 - - <<: *conan-osx - osx_image: xcode9 - env: CONAN_APPLE_CLANG_VERSIONS=9.0 - - <<: *conan-osx - osx_image: xcode9.4 - env: CONAN_APPLE_CLANG_VERSIONS=9.1 - - <<: *conan-osx - osx_image: xcode10.2 - env: CONAN_APPLE_CLANG_VERSIONS=10.0 - - - language: android - sudo: true - dist: trusty - android: - components: - - tools - - platform-tools - - build-tools-25.0.2 - - android-25 - - extra-android-m2repository - compiler: - - gcc - - before_install: - # Output something every 10 minutes or Travis kills the job - - while sleep 540; do echo "=====[ $SECONDS seconds still running ]====="; done & - # Install the r17c version of the NDK that still so that we can continue to test with gnustl - # and stlport. - - export ANDROID_NDK_HOME=$HOME/android-ndk - - NDK_ZIP=$ANDROID_NDK_HOME/ndk.zip - - mkdir -p $ANDROID_NDK_HOME - - curl -o $NDK_ZIP https://dl.google.com/android/repository/android-ndk-r17c-linux-x86_64.zip - - unzip -q -d $ANDROID_NDK_HOME $NDK_ZIP - - rm $NDK_ZIP - - mv $ANDROID_NDK_HOME/android-ndk-*/* $ANDROID_NDK_HOME - - rmdir $ANDROID_NDK_HOME/android-ndk-* - - export CMAKE=$(which cmake) - # libc required for prebuilt llvm toolchain the NDK r17c. - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get update -qq; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get install -qq libc6; fi - # Setup environment for Linux build which is required to build the sample. - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get update -qq; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get install -qq g++-$GCC_VERSION; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get install -qq gcc-$GCC_VERSION; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s -v -f $(which g++-$GCC_VERSION) /usr/bin/g++; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s -v -f $(which gcc-$GCC_VERSION) /usr/bin/gcc; fi - script: - - failed=0; for build_gradle in $(git ls-files | grep build.gradle); do ( cd "$(dirname "${build_gradle}")" && ./gradlew build ) || failed=1; done; exit $((failed)) - # Kill the sleep loop - - kill %1 diff --git a/third_party/flatbuffers/.travis/build-and-run-docker-test-containers.sh b/third_party/flatbuffers/.travis/build-and-run-docker-test-containers.sh deleted file mode 100755 index e6039bf623f..00000000000 --- a/third_party/flatbuffers/.travis/build-and-run-docker-test-containers.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/bash -# -# Copyright 2018 Google Inc. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -set -e - -# build flatc on debian once to speed up the test loop below -docker build -t build_flatc_debian_stretch -f tests/docker/Dockerfile.testing.build_flatc_debian_stretch . -BUILD_CONTAINER_ID=$(docker create --read-only build_flatc_debian_stretch) -docker cp ${BUILD_CONTAINER_ID}:/code/flatc flatc_debian_stretch - -for f in $(ls tests/docker/languages | sort) -do - # docker pull sometimes fails for unknown reasons, probably travisci-related. this retries the pull we need a few times. - REQUIRED_BASE_IMAGE=$(cat tests/docker/languages/${f} | head -n 1 | awk ' { print $2 } ') - - set +e - n=0 - until [ $n -ge 5 ] - do - docker pull $REQUIRED_BASE_IMAGE && break - n=$[$n+1] - sleep 1 - done - set -e - - docker build -t $(echo ${f} | cut -f 3- -d .) -f tests/docker/languages/${f} . - echo "TEST OK: ${f}" -done diff --git a/third_party/flatbuffers/.travis/check-generate-code.sh b/third_party/flatbuffers/.travis/check-generate-code.sh deleted file mode 100755 index 37d81bb7146..00000000000 --- a/third_party/flatbuffers/.travis/check-generate-code.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/bash -# -# Copyright 2018 Google Inc. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -set -e - -cd tests -./generate_code.sh -cd .. - -# TODO: Linux and macos builds produce differences here for some reason. -git checkout HEAD -- tests/monster_test.bfbs -git checkout HEAD -- tests/arrays_test.bfbs - -if ! git diff --quiet; then - echo >&2 - echo "ERROR: ********************************************************" >&2 - echo "ERROR: The following differences were found after running the" >&2 - echo "ERROR: tests/generate_code.sh script. Maybe you forgot to run" >&2 - echo "ERROR: it after making changes in a generator or schema?" >&2 - echo "ERROR: ********************************************************" >&2 - echo >&2 - git diff --binary --exit-code -fi diff --git a/third_party/flatbuffers/.travis/check-sources.sh b/third_party/flatbuffers/.travis/check-sources.sh deleted file mode 100644 index 3e6dbf16bea..00000000000 --- a/third_party/flatbuffers/.travis/check-sources.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash -# -# Copyright 2018 Google Inc. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -set -e - -if [ -n "$1" ]; then - scan_dir="$1" -else - scan_dir="$( pwd )" -fi - -py_checker="$0.py" - -echo "scan root directory = '$scan_dir'" -python3 --version -# Scan recursively and search all *.cpp and *.h files using regex patterns. -# Assume that script running from a root of Flatbuffers working dir. -python3 $py_checker "ascii" "$scan_dir/include" "\.h$" -python3 $py_checker "ascii" "$scan_dir/src" "\.cpp$" -python3 $py_checker "ascii" "$scan_dir/tests" "\.h$" -python3 $py_checker "utf-8" "$scan_dir/tests" "\.cpp$" diff --git a/third_party/flatbuffers/.travis/check-sources.sh.py b/third_party/flatbuffers/.travis/check-sources.sh.py deleted file mode 100644 index 2b001d76357..00000000000 --- a/third_party/flatbuffers/.travis/check-sources.sh.py +++ /dev/null @@ -1,35 +0,0 @@ -import os -import re -import sys - -def check_encoding(encoding, scan_dir, regex_pattern): - fname = None - try: - assert encoding in ['ascii', 'utf-8'], "unexpected encoding" - cmp = re.compile(regex_pattern) - for root, dirs, files in os.walk(scan_dir): - fname = root - cmp_list = [f for f in files if cmp.search(f) is not None] - for f in cmp_list: - fname = os.path.join(root, f) - with open(fname, mode='rb') as test_file: - btext = test_file.read() - # check encoding - btext.decode(encoding=encoding, errors="strict") - if encoding == "utf-8" and btext.startswith(b'\xEF\xBB\xBF'): - raise ValueError("unexpected BOM in file") - # check LF line endings - LF = btext.count(b'\n') - CR = btext.count(b'\r') - if CR!=0: - raise ValueError("invalid line endings: LF({})/CR({})".format(LF, CR)) - except Exception as err: - print("ERROR with [{}]: {}".format(fname, err)) - return -1 - else: - return 0 - -if __name__ == "__main__": - # python check-sources.sh.py 'ascii' '.' '.*\.(cpp|h)$' - res = check_encoding(sys.argv[1], sys.argv[2], sys.argv[3]) - sys.exit(0 if res == 0 else -1) diff --git a/third_party/flatbuffers/.travis/deploy-python.sh b/third_party/flatbuffers/.travis/deploy-python.sh deleted file mode 100755 index 4cc03460f53..00000000000 --- a/third_party/flatbuffers/.travis/deploy-python.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -PROD_REPOSITORY="https://upload.pypi.org/legacy/" -TEST_REPOSITORY="https://test.pypi.org/legacy/" - -twine upload \ - --username "$PYPI_USERNAME" \ - --password "$PYPI_PASSWORD" \ - --repository-url "$PROD_REPOSITORY" \ - "$DIR/../python/dist/"* - diff --git a/third_party/flatbuffers/BUILD b/third_party/flatbuffers/BUILD deleted file mode 100644 index 520f98af842..00000000000 --- a/third_party/flatbuffers/BUILD +++ /dev/null @@ -1,225 +0,0 @@ -licenses(["notice"]) - -package( - default_visibility = ["//visibility:public"], - features = [ - "-layering_check", - "-parse_headers", - ], -) - -exports_files([ - "LICENSE", -]) - -load(":build_defs.bzl", "flatbuffer_cc_library") - -# Public flatc library to compile flatbuffer files at runtime. -cc_library( - name = "flatbuffers", - srcs = [ - "src/code_generators.cpp", - "src/idl_gen_fbs.cpp", - "src/idl_gen_general.cpp", - "src/idl_gen_text.cpp", - "src/idl_parser.cpp", - "src/reflection.cpp", - "src/util.cpp", - ], - hdrs = [":public_headers"], - includes = ["include/"], - linkstatic = 1, -) - -# Public C++ headers for the Flatbuffers library. -filegroup( - name = "public_headers", - srcs = [ - "include/flatbuffers/base.h", - "include/flatbuffers/code_generators.h", - "include/flatbuffers/flatbuffers.h", - "include/flatbuffers/flexbuffers.h", - "include/flatbuffers/hash.h", - "include/flatbuffers/idl.h", - "include/flatbuffers/minireflect.h", - "include/flatbuffers/reflection.h", - "include/flatbuffers/reflection_generated.h", - "include/flatbuffers/stl_emulation.h", - "include/flatbuffers/util.h", - ], -) - -# Public flatc compiler library. -cc_library( - name = "flatc_library", - srcs = [ - "src/code_generators.cpp", - "src/flatc.cpp", - "src/idl_gen_fbs.cpp", - "src/idl_parser.cpp", - "src/reflection.cpp", - "src/util.cpp", - ], - hdrs = [ - "include/flatbuffers/flatc.h", - ":public_headers", - ], - includes = [ - "grpc/", - "include/", - ], -) - -# Public flatc compiler. -cc_binary( - name = "flatc", - srcs = [ - "grpc/src/compiler/config.h", - "grpc/src/compiler/cpp_generator.cc", - "grpc/src/compiler/cpp_generator.h", - "grpc/src/compiler/go_generator.cc", - "grpc/src/compiler/go_generator.h", - "grpc/src/compiler/java_generator.cc", - "grpc/src/compiler/java_generator.h", - "grpc/src/compiler/schema_interface.h", - "src/flatc_main.cpp", - "src/idl_gen_cpp.cpp", - "src/idl_gen_dart.cpp", - "src/idl_gen_general.cpp", - "src/idl_gen_kotlin.cpp", - "src/idl_gen_go.cpp", - "src/idl_gen_grpc.cpp", - "src/idl_gen_js_ts.cpp", - "src/idl_gen_json_schema.cpp", - "src/idl_gen_lobster.cpp", - "src/idl_gen_lua.cpp", - "src/idl_gen_php.cpp", - "src/idl_gen_python.cpp", - "src/idl_gen_rust.cpp", - "src/idl_gen_text.cpp", - "src/util.cpp", - ], - includes = [ - "grpc/", - "include/", - ], - deps = [ - ":flatc_library", - ], -) - -cc_library( - name = "runtime_cc", - hdrs = [ - "include/flatbuffers/base.h", - "include/flatbuffers/flatbuffers.h", - "include/flatbuffers/flexbuffers.h", - "include/flatbuffers/stl_emulation.h", - "include/flatbuffers/util.h", - ], - includes = ["include/"], - linkstatic = 1, -) - -# Test binary. -cc_test( - name = "flatbuffers_test", - testonly = 1, - srcs = [ - "include/flatbuffers/minireflect.h", - "include/flatbuffers/registry.h", - "src/code_generators.cpp", - "src/idl_gen_fbs.cpp", - "src/idl_gen_general.cpp", - "src/idl_gen_text.cpp", - "src/idl_parser.cpp", - "src/reflection.cpp", - "src/util.cpp", - "tests/namespace_test/namespace_test1_generated.h", - "tests/namespace_test/namespace_test2_generated.h", - "tests/native_type_test_impl.h", - "tests/native_type_test_impl.cpp", - "tests/test.cpp", - "tests/test_assert.cpp", - "tests/test_assert.h", - "tests/test_builder.cpp", - "tests/test_builder.h", - "tests/union_vector/union_vector_generated.h", - ":public_headers", - ], - copts = [ - "-DFLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE", - "-DBAZEL_TEST_DATA_PATH", - ], - data = [ - ":tests/include_test/include_test1.fbs", - ":tests/include_test/sub/include_test2.fbs", - ":tests/monster_test.bfbs", - ":tests/monster_test.fbs", - ":tests/monsterdata_test.golden", - ":tests/monsterdata_test.json", - ":tests/prototest/imported.proto", - ":tests/prototest/test.golden", - ":tests/prototest/test.proto", - ":tests/prototest/test_union.golden", - ":tests/unicode_test.json", - ":tests/union_vector/union_vector.fbs", - ":tests/union_vector/union_vector.json", - ":tests/monster_extra.fbs", - ":tests/monsterdata_extra.json", - ":tests/arrays_test.bfbs", - ":tests/arrays_test.fbs", - ":tests/arrays_test.golden", - ":tests/native_type_test.fbs", - ], - includes = [ - "include/", - "tests/", - ], - deps = [ - ":monster_extra_cc_fbs", - ":monster_test_cc_fbs", - ":arrays_test_cc_fbs", - ":native_type_test_cc_fbs", - ], -) - -# Test bzl rules - -flatbuffer_cc_library( - name = "monster_test_cc_fbs", - srcs = ["tests/monster_test.fbs"], - include_paths = ["tests/include_test"], - includes = [ - "tests/include_test/include_test1.fbs", - "tests/include_test/sub/include_test2.fbs", - ], -) - -flatbuffer_cc_library( - name = "monster_extra_cc_fbs", - srcs = ["tests/monster_extra.fbs"], -) - -flatbuffer_cc_library( - name = "arrays_test_cc_fbs", - srcs = ["tests/arrays_test.fbs"], - flatc_args = [ - "--gen-object-api", - "--gen-compare", - "--no-includes", - "--gen-mutable", - "--reflect-names", - "--cpp-ptr-type flatbuffers::unique_ptr", - "--scoped-enums" ], -) - -flatbuffer_cc_library( - name = "native_type_test_cc_fbs", - srcs = ["tests/native_type_test.fbs"], - flatc_args = [ - "--gen-object-api", - "--gen-mutable", - "--cpp-ptr-type flatbuffers::unique_ptr" ], -) - diff --git a/third_party/flatbuffers/BUILD.bazel b/third_party/flatbuffers/BUILD.bazel new file mode 100644 index 00000000000..b4f015a0e29 --- /dev/null +++ b/third_party/flatbuffers/BUILD.bazel @@ -0,0 +1,139 @@ +load("@aspect_rules_js//npm:defs.bzl", "npm_link_package") +load("@npm//:defs.bzl", "npm_link_all_packages") +load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") + +licenses(["notice"]) + +package( + default_visibility = ["//visibility:public"], +) + +npm_link_all_packages(name = "node_modules") + +npm_link_package( + name = "node_modules/flatbuffers", + src = "//ts:flatbuffers", +) + +exports_files([ + "LICENSE", + "tsconfig.json", +]) + +config_setting( + name = "platform_freebsd", + constraint_values = [ + "@platforms//os:freebsd", + ], +) + +config_setting( + name = "platform_openbsd", + constraint_values = [ + "@platforms//os:openbsd", + ], +) + +filegroup( + name = "distribution", + srcs = [ + "BUILD.bazel", + "WORKSPACE", + "build_defs.bzl", + "typescript.bzl", + "//grpc/src/compiler:distribution", + "//reflection:distribution", + "//src:distribution", + "//ts:distribution", + ] + glob([ + "include/flatbuffers/*.h", + ]), + visibility = ["//visibility:public"], +) + +# Public flatc library to compile flatbuffer files at runtime. +cc_library( + name = "flatbuffers", + hdrs = ["//:public_headers"], + linkstatic = 1, + strip_include_prefix = "/include", + deps = ["//src:flatbuffers"], +) + +# Public C++ headers for the Flatbuffers library. +filegroup( + name = "public_headers", + srcs = [ + "include/flatbuffers/allocator.h", + "include/flatbuffers/array.h", + "include/flatbuffers/base.h", + "include/flatbuffers/buffer.h", + "include/flatbuffers/buffer_ref.h", + "include/flatbuffers/code_generator.h", + "include/flatbuffers/code_generators.h", + "include/flatbuffers/default_allocator.h", + "include/flatbuffers/detached_buffer.h", + "include/flatbuffers/file_manager.h", + "include/flatbuffers/flatbuffer_builder.h", + "include/flatbuffers/flatbuffers.h", + "include/flatbuffers/flex_flat_util.h", + "include/flatbuffers/flexbuffers.h", + "include/flatbuffers/grpc.h", + "include/flatbuffers/hash.h", + "include/flatbuffers/idl.h", + "include/flatbuffers/minireflect.h", + "include/flatbuffers/reflection.h", + "include/flatbuffers/reflection_generated.h", + "include/flatbuffers/registry.h", + "include/flatbuffers/stl_emulation.h", + "include/flatbuffers/string.h", + "include/flatbuffers/struct.h", + "include/flatbuffers/table.h", + "include/flatbuffers/util.h", + "include/flatbuffers/vector.h", + "include/flatbuffers/vector_downward.h", + "include/flatbuffers/verifier.h", + ], +) + +# Public flatc compiler library. +cc_library( + name = "flatc_library", + linkstatic = 1, + deps = [ + "//src:flatc_library", + ], +) + +# Public flatc compiler. +cc_binary( + name = "flatc", + data = ["//reflection:reflection_fbs_schema"], + deps = [ + "//src:flatc", + ], +) + +filegroup( + name = "flatc_headers", + srcs = [ + "include/flatbuffers/flatc.h", + ], + visibility = ["//:__subpackages__"], +) + +# Library used by flatbuffer_cc_library rules. +cc_library( + name = "runtime_cc", + hdrs = [ + "include/flatbuffers/base.h", + "include/flatbuffers/flatbuffers.h", + "include/flatbuffers/flexbuffers.h", + "include/flatbuffers/stl_emulation.h", + "include/flatbuffers/util.h", + "include/flatbuffers/vector.h", + "include/flatbuffers/verifier.h", + ], + linkstatic = 1, + strip_include_prefix = "/include", +) diff --git a/third_party/flatbuffers/CHANGELOG.md b/third_party/flatbuffers/CHANGELOG.md new file mode 100644 index 00000000000..2b0380df6c5 --- /dev/null +++ b/third_party/flatbuffers/CHANGELOG.md @@ -0,0 +1,168 @@ +# Flatbuffers Change Log + +All major or breaking changes will be documented in this file, as well as any +new features that should be highlighted. Minor fixes or improvements are not +necessarily listed. + +## [24.3.25] (March 25 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.25) + +* Fixed license metadata parsing (#8253) +* [C++] Allow string_view in `LookUpByKey` in addition to null-terminated c-style strings (#8203) + +## [24.3.7] (March 7 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.7) + +* Just to fix some of the CI build issues from the 24.3.6 release. + +## [24.3.6] (March 6 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.6) + +* Fix typescript object API to allow 0 values for null-default scalars (#7864) + +## [23.5.26 (May 26 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.26) + +* Mostly bug fixing for 64-bit support +* Adds support for specifying underling type of unions in C++ and TS/JS (#7954) + +## [23.5.9 (May 9 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.9) + +* 64-bit support for C++ (#7935) + +## [23.5.8 (May 8 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.8) + +* add key_field to compiled tests +* Add golden language directory +* Rework cmake flatc codegeneration (#7938) +* remove defining generated files in test srcs +* Add binary schema reflection (#7932) +* Migrate from rules_nodejs to rules_js/rules_ts (take 2) (#7928) +* `flat_buffers.dart`: mark const variable finals for internal Dart linters +* fixed some windows warnings (#7929) +* inject no long for FBS generation to remove logs in flattests (#7926) +* Revert "Migrate from rules_nodejs to rules_js/rules_ts (#7923)" (#7927) +* Migrate from rules_nodejs to rules_js/rules_ts (#7923) +* Only generate @kotlin.ExperimentalUnsigned annotation on create*Vector methods having an unsigned array type parameter. (#7881) +* additional check for absl::string_view availability (#7897) +* Optionally generate Python type annotations (#7858) +* Replace deprecated command with environment file (#7921) +* drop glibc from runtime dependencies (#7906) +* Make JSON supporting advanced union features (#7869) +* Allow to use functions from `BuildFlatBuffers.cmake` from a flatbuffers installation installed with CMake. (#7912) +* TS/JS: Use TypeError instead of Error when appropriate (#7910) +* Go: make generated code more compliant to "go fmt" (#7907) +* Support file_identifier in Go (#7904) +* Optionally generate type prefixes and suffixes for python code (#7857) +* Go: add test for FinishWithFileIdentifier (#7905) +* Fix go_sample.sh (#7903) +* [TS/JS] Upgrade dependencies (#7889) +* Add a FileWriter interface (#7821) +* TS/JS: Use minvalue from enum if not found (#7888) +* [CS] Verifier (#7850) +* README.md: PyPI case typo (#7880) +* Update go documentation link to point to root module (#7879) +* use Bool for flatbuffers bool instead of Byte (#7876) +* fix using null string in vector (#7872) +* Add `flatbuffers-64` branch to CI for pushes +* made changes to the rust docs so they would compile. new_with_capacity is deprecated should use with_capacity, get_root_as_monster should be root_as_monster (#7871) +* Adding comment for code clarification (#7856) +* ToCamelCase() when kLowerCamel now converts first char to lower. (#7838) +* Fix help output for --java-checkerframework (#7854) +* Update filename to README.md and improve formatting (#7855) +* Update stale.yml +* Updated remaining usages of LICENSE.txt + +## [23.3.3 (Mar 3 2023)](https://github.com/google/flatbuffers/releases/tag/v23.3.3) + +* Refactoring of `flatc` generators to use an interface (#7797). + +* Removed legacy cmake support and set min to 3.8 (#7801). + +## [23.1.21 (Jan 21 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.20) + +* Reworked entry points for Typescript/Javascript and compatibility for single + file build (#7510) + +## [23.1.20 (Jan 20 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.20) + +* Removed go.mod files after some versioning issues were being report (#7780). + +## [23.1.4 (Jan 4 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.4) + +* Major release! Just kidding, we are continuing the + [versioning scheme](https://github.com/google/flatbuffers/wiki/Versioning) of + using a date to signify releases. This results in the first release of the new + year to bump the tradition major version field. + +* Go minimum version is now 1.19 (#7720) with the addition of Go modules. + +* Added CI support for Big Endian regression testing (#7707). + +* Fixed `getFullyQualifiedName` in typescript to return name delimited by '.' + instead of '_' (#7730). + +* Fixed the versioning scheme to not include leading zeros which are not + consistently handled by every package manager. Only the last release + (12.12.06) should have suffered from this. + +## [22.12.06 (Dec 06 2022)](https://github.com/google/flatbuffers/releases/tag/v22.12.06) + +* Bug fixing release, no major changes. + +## [22.10.25 (Oct 25 2022)](https://github.com/google/flatbuffers/releases/tag/v22.10.25) + +* Added Nim language support with generator and runtime libraries (#7534). + +## [22.9.29 (Sept 29 2022)](https://github.com/google/flatbuffers/releases/tag/v22.9.29) + +* Rust soundness fixes to avoid the crate from bing labelled unsafe (#7518). + +## [22.9.24 (Sept 24 2022)](https://github.com/google/flatbuffers/releases/tag/v22.9.24) + +* 20 Major releases in a row? Nope, we switched to a new + [versioning scheme](https://github.com/google/flatbuffers/wiki/Versioning) + that is based on date. + +* Python supports fixed size arrays now (#7529). + +* Behavior change in how C++ object API uses `UnPackTo`. The original intent of + this was to reduce allocations by reusing an existing object to pack data + into. At some point, this logic started to merge the states of the two objects + instead of clearing the state of the packee. This change goes back to the + original intention, the packed object is cleared when getting data packed into + it (#7527). + +* Fixed a bug in C++ alignment that was using `sizeof()` instead of the intended + `AlignOf()` for structs (#7520). + +* C# has an + [official Nuget package](https://www.nuget.org/packages/Google.FlatBuffers) + now (#7496). + +## 2.0.8 (Aug 29 2022) + +* Fix for `--keep-prefix` the was generating the wrong include statements for + C++ (#7469). The bug was introduced in 2.0.7. + +* Added the `Verifier::Options` option struct to allow specifying runtime + configuration settings for the verifier (#7489). This allows to skip verifying + nested flatbuffers, a on-by-default change that was introduced in 2.0.7. This + deprecates the existing `Verifier` constructor, which may be removed in a + future version. + +* Refactor of `tests/test.cpp` that lead to ~10% speedup in compilation of the + entire project (#7487). + +## 2.0.7 (Aug 22 2022) + +* This is the first version with an explicit change log, so all the previous + features will not be listed. + +* Verifier now checks that buffers are at least the minimum size required to be + a flatbuffers (12 bytes). This includes nested flatbuffers, which previously + could be declared valid at size 0. + +* Annotated binaries. Given a flatbuffer binary and a schema (or binary schema) + one can generate an annotated flatbuffer (.afb) to describe each byte in the + binary with schema metadata and value. + +* First binary schema generator (Lua) to generate Lua code via a .bfbs file. + This is mostly an implementation detail of flatc internals, but will be slowly + applied to the other language generators. diff --git a/third_party/flatbuffers/CMake/BuildFlatBuffers.cmake b/third_party/flatbuffers/CMake/BuildFlatBuffers.cmake index 835f4b80c0a..631e5adfbf3 100644 --- a/third_party/flatbuffers/CMake/BuildFlatBuffers.cmake +++ b/third_party/flatbuffers/CMake/BuildFlatBuffers.cmake @@ -59,6 +59,9 @@ function(build_flatbuffers flatbuffers_schemas if(FLATBUFFERS_FLATC_EXECUTABLE) set(FLATC_TARGET "") set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE}) + elseif(TARGET flatbuffers::flatc) + set(FLATC_TARGET flatbuffers::flatc) + set(FLATC flatbuffers::flatc) else() set(FLATC_TARGET flatc) set(FLATC flatc) @@ -150,3 +153,297 @@ function(build_flatbuffers flatbuffers_schemas ${copy_text_schemas_dir}) endif() endfunction() + +# Creates a target that can be linked against that generates flatbuffer headers. +# +# This function takes a target name and a list of schemas. You can also specify +# other flagc flags using the FLAGS option to change the behavior of the flatc +# tool. +# +# When the target_link_libraries is done within a different directory than +# flatbuffers_generate_headers is called, then the target should also be dependent +# the custom generation target called GENERATE_. +# +# Arguments: +# TARGET: The name of the target to generate. +# SCHEMAS: The list of schema files to generate code for. +# BINARY_SCHEMAS_DIR: Optional. The directory in which to generate binary +# schemas. Binary schemas will only be generated if a path is provided. +# INCLUDE: Optional. Search for includes in the specified paths. (Use this +# instead of "-I " and the FLAGS option so that CMake is aware of +# the directories that need to be searched). +# INCLUDE_PREFIX: Optional. The directory in which to place the generated +# files. Use this instead of the --include-prefix option. +# FLAGS: Optional. A list of any additional flags that you would like to pass +# to flatc. +# +# Example: +# +# flatbuffers_generate_headers( +# TARGET my_generated_headers_target +# INCLUDE_PREFIX ${MY_INCLUDE_PREFIX}" +# SCHEMAS ${MY_SCHEMA_FILES} +# BINARY_SCHEMAS_DIR "${MY_BINARY_SCHEMA_DIRECTORY}" +# FLAGS --gen-object-api) +# +# target_link_libraries(MyExecutableTarget +# PRIVATE my_generated_headers_target +# ) +# +# Optional (only needed within different directory): +# add_dependencies(app GENERATE_my_generated_headers_target) +function(flatbuffers_generate_headers) + # Parse function arguments. + set(options) + set(one_value_args + "TARGET" + "INCLUDE_PREFIX" + "BINARY_SCHEMAS_DIR") + set(multi_value_args + "SCHEMAS" + "INCLUDE" + "FLAGS") + cmake_parse_arguments( + PARSE_ARGV 0 + FLATBUFFERS_GENERATE_HEADERS + "${options}" + "${one_value_args}" + "${multi_value_args}") + + # Test if including from FindFlatBuffers + if(FLATBUFFERS_FLATC_EXECUTABLE) + set(FLATC_TARGET "") + set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE}) + elseif(TARGET flatbuffers::flatc) + set(FLATC_TARGET flatbuffers::flatc) + set(FLATC flatbuffers::flatc) + else() + set(FLATC_TARGET flatc) + set(FLATC flatc) + endif() + + set(working_dir "${CMAKE_CURRENT_SOURCE_DIR}") + + # Generate the include files parameters. + set(include_params "") + foreach (include_dir ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE}) + set(include_params -I ${include_dir} ${include_params}) + endforeach() + + # Create a directory to place the generated code. + set(generated_target_dir "${CMAKE_CURRENT_BINARY_DIR}/${FLATBUFFERS_GENERATE_HEADERS_TARGET}") + set(generated_include_dir "${generated_target_dir}") + if (NOT ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX} STREQUAL "") + set(generated_include_dir "${generated_include_dir}/${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX}") + list(APPEND FLATBUFFERS_GENERATE_HEADERS_FLAGS + "--include-prefix" ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX}) + endif() + + set(generated_custom_commands) + + # Create rules to generate the code for each schema. + foreach(schema ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS}) + get_filename_component(filename ${schema} NAME_WE) + set(generated_include "${generated_include_dir}/${filename}_generated.h") + + # Generate files for grpc if needed + set(generated_source_file) + if("${FLATBUFFERS_GENERATE_HEADERS_FLAGS}" MATCHES "--grpc") + # Check if schema file contain a rpc_service definition + file(STRINGS ${schema} has_grpc REGEX "rpc_service") + if(has_grpc) + list(APPEND generated_include "${generated_include_dir}/${filename}.grpc.fb.h") + set(generated_source_file "${generated_include_dir}/${filename}.grpc.fb.cc") + endif() + endif() + + add_custom_command( + OUTPUT ${generated_include} ${generated_source_file} + COMMAND ${FLATC} ${FLATC_ARGS} + -o ${generated_include_dir} + ${include_params} + -c ${schema} + ${FLATBUFFERS_GENERATE_HEADERS_FLAGS} + DEPENDS ${FLATC_TARGET} ${schema} + WORKING_DIRECTORY "${working_dir}" + COMMENT "Building ${schema} flatbuffers...") + list(APPEND all_generated_header_files ${generated_include}) + list(APPEND all_generated_source_files ${generated_source_file}) + list(APPEND generated_custom_commands "${generated_include}" "${generated_source_file}") + + # Geneate the binary flatbuffers schemas if instructed to. + if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "") + set(binary_schema + "${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR}/${filename}.bfbs") + add_custom_command( + OUTPUT ${binary_schema} + COMMAND ${FLATC} -b --schema + -o ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} + ${include_params} + ${schema} + DEPENDS ${FLATC_TARGET} ${schema} + WORKING_DIRECTORY "${working_dir}") + list(APPEND generated_custom_commands "${binary_schema}") + list(APPEND all_generated_binary_files ${binary_schema}) + endif() + endforeach() + + # Create an additional target as add_custom_command scope is only within same directory (CMakeFile.txt) + set(generate_target GENERATE_${FLATBUFFERS_GENERATE_HEADERS_TARGET}) + add_custom_target(${generate_target} ALL + DEPENDS ${generated_custom_commands} + COMMENT "Generating flatbuffer target ${FLATBUFFERS_GENERATE_HEADERS_TARGET}") + + # Set up interface library + add_library(${FLATBUFFERS_GENERATE_HEADERS_TARGET} INTERFACE) + target_sources( + ${FLATBUFFERS_GENERATE_HEADERS_TARGET} + INTERFACE + ${all_generated_header_files} + ${all_generated_binary_files} + ${all_generated_source_files} + ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS}) + add_dependencies( + ${FLATBUFFERS_GENERATE_HEADERS_TARGET} + ${FLATC} + ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS}) + target_include_directories( + ${FLATBUFFERS_GENERATE_HEADERS_TARGET} + INTERFACE ${generated_target_dir}) + + # Organize file layout for IDEs. + source_group( + TREE "${generated_target_dir}" + PREFIX "Flatbuffers/Generated/Headers Files" + FILES ${all_generated_header_files}) + source_group( + TREE "${generated_target_dir}" + PREFIX "Flatbuffers/Generated/Source Files" + FILES ${all_generated_source_files}) + source_group( + TREE ${working_dir} + PREFIX "Flatbuffers/Schemas" + FILES ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS}) + if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "") + source_group( + TREE "${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR}" + PREFIX "Flatbuffers/Generated/Binary Schemas" + FILES ${all_generated_binary_files}) + endif() +endfunction() + +# Creates a target that can be linked against that generates flatbuffer binaries +# from json files. +# +# This function takes a target name and a list of schemas and Json files. You +# can also specify other flagc flags and options to change the behavior of the +# flatc compiler. +# +# Adding this target to your executable ensurses that the flatbuffer binaries +# are compiled before your executable is run. +# +# Arguments: +# TARGET: The name of the target to generate. +# JSON_FILES: The list of json files to compile to flatbuffers binaries. +# SCHEMA: The flatbuffers schema of the Json files to be compiled. +# INCLUDE: Optional. Search for includes in the specified paths. (Use this +# instead of "-I " and the FLAGS option so that CMake is aware of +# the directories that need to be searched). +# OUTPUT_DIR: The directly where the generated flatbuffers binaries should be +# placed. +# FLAGS: Optional. A list of any additional flags that you would like to pass +# to flatc. +# +# Example: +# +# flatbuffers_generate_binary_files( +# TARGET my_binary_data +# SCHEMA "${MY_SCHEMA_DIR}/my_example_schema.fbs" +# JSON_FILES ${MY_JSON_FILES} +# OUTPUT_DIR "${MY_BINARY_DATA_DIRECTORY}" +# FLAGS --strict-json) +# +# target_link_libraries(MyExecutableTarget +# PRIVATE my_binary_data +# ) +function(flatbuffers_generate_binary_files) + # Parse function arguments. + set(options) + set(one_value_args + "TARGET" + "SCHEMA" + "OUTPUT_DIR") + set(multi_value_args + "JSON_FILES" + "INCLUDE" + "FLAGS") + cmake_parse_arguments( + PARSE_ARGV 0 + FLATBUFFERS_GENERATE_BINARY_FILES + "${options}" + "${one_value_args}" + "${multi_value_args}") + + # Test if including from FindFlatBuffers + if(FLATBUFFERS_FLATC_EXECUTABLE) + set(FLATC_TARGET "") + set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE}) + elseif(TARGET flatbuffers::flatc) + set(FLATC_TARGET flatbuffers::flatc) + set(FLATC flatbuffers::flatc) + else() + set(FLATC_TARGET flatc) + set(FLATC flatc) + endif() + + set(working_dir "${CMAKE_CURRENT_SOURCE_DIR}") + + # Generate the include files parameters. + set(include_params "") + foreach (include_dir ${FLATBUFFERS_GENERATE_BINARY_FILES_INCLUDE}) + set(include_params -I ${include_dir} ${include_params}) + endforeach() + + # Create rules to generate the flatbuffers binary for each json file. + foreach(json_file ${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES}) + get_filename_component(filename ${json_file} NAME_WE) + set(generated_binary_file "${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR}/${filename}.bin") + add_custom_command( + OUTPUT ${generated_binary_file} + COMMAND ${FLATC} ${FLATC_ARGS} + -o ${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR} + ${include_params} + -b ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA} ${json_file} + ${FLATBUFFERS_GENERATE_BINARY_FILES_FLAGS} + DEPENDS ${FLATC_TARGET} ${json_file} + WORKING_DIRECTORY "${working_dir}" + COMMENT "Building ${json_file} binary flatbuffers...") + list(APPEND all_generated_binary_files ${generated_binary_file}) + endforeach() + + # Set up interface library + add_library(${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET} INTERFACE) + target_sources( + ${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET} + INTERFACE + ${all_generated_binary_files} + ${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES} + ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA}) + add_dependencies( + ${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET} + ${FLATC}) + + # Organize file layout for IDEs. + source_group( + TREE ${working_dir} + PREFIX "Flatbuffers/JSON Files" + FILES ${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES}) + source_group( + TREE ${working_dir} + PREFIX "Flatbuffers/Schemas" + FILES ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA}) + source_group( + TREE ${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR} + PREFIX "Flatbuffers/Generated/Binary Files" + FILES ${all_generated_binary_files}) +endfunction() diff --git a/third_party/flatbuffers/CMake/FindFlatBuffers.cmake b/third_party/flatbuffers/CMake/FindFlatBuffers.cmake index aad9a6bfb09..044cf7c9d27 100644 --- a/third_party/flatbuffers/CMake/FindFlatBuffers.cmake +++ b/third_party/flatbuffers/CMake/FindFlatBuffers.cmake @@ -30,7 +30,7 @@ find_program(FLATBUFFERS_FLATC_EXECUTABLE NAMES flatc) find_path(FLATBUFFERS_INCLUDE_DIR NAMES flatbuffers/flatbuffers.h) include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(flatbuffers +find_package_handle_standard_args(FlatBuffers DEFAULT_MSG FLATBUFFERS_FLATC_EXECUTABLE FLATBUFFERS_INCLUDE_DIR) if(FLATBUFFERS_FOUND) @@ -58,4 +58,4 @@ else() set(FLATBUFFERS_INCLUDE_DIR) endif() -include("${FLATBUFFERS_CMAKE_DIR}/BuildFlatBuffers.cmake") \ No newline at end of file +include("${FLATBUFFERS_CMAKE_DIR}/BuildFlatBuffers.cmake") diff --git a/third_party/flatbuffers/CMake/FlatbuffersConfig.cmake b/third_party/flatbuffers/CMake/FlatbuffersConfig.cmake deleted file mode 100644 index 107d78e98f6..00000000000 --- a/third_party/flatbuffers/CMake/FlatbuffersConfig.cmake +++ /dev/null @@ -1,4 +0,0 @@ -include("${CMAKE_CURRENT_LIST_DIR}/FlatbuffersTargets.cmake" OPTIONAL) -include("${CMAKE_CURRENT_LIST_DIR}/FlatcTargets.cmake" OPTIONAL) -include("${CMAKE_CURRENT_LIST_DIR}/FlatbuffersSharedTargets.cmake" OPTIONAL) - diff --git a/third_party/flatbuffers/CMake/PackageDebian.cmake b/third_party/flatbuffers/CMake/PackageDebian.cmake index f587ff7ffe2..d8692c63d23 100644 --- a/third_party/flatbuffers/CMake/PackageDebian.cmake +++ b/third_party/flatbuffers/CMake/PackageDebian.cmake @@ -17,23 +17,9 @@ if (UNIX) SET(CPACK_PACKAGE_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}-${VERSION_COMMIT}") SET(CPACK_DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}") - # Derive architecture - IF(NOT CPACK_DEBIAN_PACKAGE_ARCHITECTURE) - FIND_PROGRAM(DPKG_CMD dpkg) - IF(NOT DPKG_CMD) - MESSAGE(STATUS "Can not find dpkg in your path, default to i386.") - SET(CPACK_DEBIAN_PACKAGE_ARCHITECTURE i386) - ENDIF(NOT DPKG_CMD) - EXECUTE_PROCESS(COMMAND "${DPKG_CMD}" --print-architecture - OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE - OUTPUT_STRIP_TRAILING_WHITESPACE - ) - ENDIF(NOT CPACK_DEBIAN_PACKAGE_ARCHITECTURE) - # Package name SET(CPACK_DEBIAN_PACKAGE_NAME "flatbuffers") - SET(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE.txt) - SET(CPACK_PACKAGE_FILE_NAME - "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_DEBIAN_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") + SET(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE) + set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT") endif(UNIX) diff --git a/third_party/flatbuffers/CMake/PackageRedhat.cmake b/third_party/flatbuffers/CMake/PackageRedhat.cmake index 4545e729083..34302882fb3 100644 --- a/third_party/flatbuffers/CMake/PackageRedhat.cmake +++ b/third_party/flatbuffers/CMake/PackageRedhat.cmake @@ -15,14 +15,14 @@ if (UNIX) set(CPACK_RPM_PACKAGE_NAME "flatbuffers") - # Assume this is not a cross complation build. + # Assume this is not a cross compilation build. if(NOT CPACK_RPM_PACKAGE_ARCHITECTURE) set(CPACK_RPM_PACKAGE_ARCHITECTURE "${CMAKE_SYSTEM_PROCESSOR}") endif(NOT CPACK_RPM_PACKAGE_ARCHITECTURE) set(CPACK_RPM_PACKAGE_VENDOR "Google, Inc.") set(CPACK_RPM_PACKAGE_LICENSE "Apache 2.0") - set(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE.txt) + set(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE) set(CPACK_PACKAGE_DESCRIPTION_FILE ${CMAKE_SOURCE_DIR}/CMake/DESCRIPTION.txt) # This may reduce rpm compatiblity with very old systems. @@ -31,4 +31,14 @@ if (UNIX) set(CPACK_RPM_PACKAGE_NAME "flatbuffers") set(CPACK_PACKAGE_FILE_NAME "${CPACK_RPM_PACKAGE_NAME}_${CPACK_RPM_PACKAGE_VERSION}_${CPACK_RPM_PACKAGE_ARCHITECTURE}") + if(NOT DEFINED ${CPACK_PACKAGING_INSTALL_PREFIX}) + # Default packaging install prefix on RedHat systems is /usr. + # This is the assumed value when this variable is not defined. + # There is currently a conflict with + # /usr/${CMAKE_INSTALL_LIBDIR}/cmake which is installed by default + # by other packages on RedHat (most notably cmake-filesystem). Ensure + # that on these systems, flatbuffers does not package this path. + # This patch is required for cmake pre-3.17. + list(APPEND CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION "/usr/${CMAKE_INSTALL_LIBDIR}/cmake") + endif() endif(UNIX) diff --git a/third_party/flatbuffers/CMake/Version.cmake b/third_party/flatbuffers/CMake/Version.cmake index db6613b840f..df18fe47a08 100644 --- a/third_party/flatbuffers/CMake/Version.cmake +++ b/third_party/flatbuffers/CMake/Version.cmake @@ -1,11 +1,39 @@ -find_program(GIT git) -execute_process( - COMMAND ${GIT} describe - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - OUTPUT_VARIABLE GIT_DESCRIBE_DIRTY - OUTPUT_STRIP_TRAILING_WHITESPACE -) -string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" VERSION_MAJOR "${GIT_DESCRIBE_DIRTY}") -string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*" "\\1" VERSION_MINOR "${GIT_DESCRIBE_DIRTY}") -string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" VERSION_PATCH "${GIT_DESCRIBE_DIRTY}") -string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.[0-9]+\\-([0-9]+).*" "\\1" VERSION_COMMIT "${GIT_DESCRIBE_DIRTY}") +set(VERSION_MAJOR 24) +set(VERSION_MINOR 3) +set(VERSION_PATCH 25) +set(VERSION_COMMIT 0) + +if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git") + find_program(GIT git) + if(GIT) + execute_process( + COMMAND ${GIT} describe --tags + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + OUTPUT_VARIABLE GIT_DESCRIBE_DIRTY + OUTPUT_STRIP_TRAILING_WHITESPACE + RESULT_VARIABLE GIT_DESCRIBE_RESULT + ) + + if(GIT_DESCRIBE_RESULT EQUAL 0) + # Test if the most recent Git tag matches the pattern "v..*" + if(GIT_DESCRIBE_DIRTY MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+.*") + string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" VERSION_MAJOR "${GIT_DESCRIBE_DIRTY}") + string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*" "\\1" VERSION_MINOR "${GIT_DESCRIBE_DIRTY}") + string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" VERSION_PATCH "${GIT_DESCRIBE_DIRTY}") + string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.[0-9]+\\-([0-9]+).*" "\\1" VERSION_COMMIT "${GIT_DESCRIBE_DIRTY}") + # If the tag points to the commit, then only the tag is shown in "git describe" + if(VERSION_COMMIT STREQUAL GIT_DESCRIBE_DIRTY) + set(VERSION_COMMIT 0) + endif() + else() + message(WARNING "\"${GIT_DESCRIBE_DIRTY}\" does not match pattern v..-") + endif() + else() + message(WARNING "git describe failed with exit code: ${GIT_DESCRIBE_RESULT}\nMake sure you cloned with tags or run 'git fetch --tags'.") + endif() + else() + message(WARNING "git is not found") + endif() +endif() + +message(STATUS "Proceeding with version: ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_COMMIT}") diff --git a/third_party/flatbuffers/CMake/FlatbuffersConfigVersion.cmake.in b/third_party/flatbuffers/CMake/flatbuffers-config-version.cmake.in similarity index 100% rename from third_party/flatbuffers/CMake/FlatbuffersConfigVersion.cmake.in rename to third_party/flatbuffers/CMake/flatbuffers-config-version.cmake.in diff --git a/third_party/flatbuffers/CMake/flatbuffers-config.cmake b/third_party/flatbuffers/CMake/flatbuffers-config.cmake new file mode 100644 index 00000000000..0c32c2fe2bf --- /dev/null +++ b/third_party/flatbuffers/CMake/flatbuffers-config.cmake @@ -0,0 +1,4 @@ +include("${CMAKE_CURRENT_LIST_DIR}/FlatBuffersTargets.cmake" OPTIONAL) +include("${CMAKE_CURRENT_LIST_DIR}/FlatcTargets.cmake" OPTIONAL) +include("${CMAKE_CURRENT_LIST_DIR}/FlatBuffersSharedTargets.cmake" OPTIONAL) +include("${CMAKE_CURRENT_LIST_DIR}/BuildFlatBuffers.cmake" OPTIONAL) \ No newline at end of file diff --git a/third_party/flatbuffers/CMake/flatbuffers.pc.in b/third_party/flatbuffers/CMake/flatbuffers.pc.in new file mode 100644 index 00000000000..110770aba70 --- /dev/null +++ b/third_party/flatbuffers/CMake/flatbuffers.pc.in @@ -0,0 +1,9 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: FlatBuffers +Description: Memory Efficient Serialization Library +Version: @VERSION_MAJOR@.@VERSION_MINOR@.@VERSION_PATCH@ + +Libs: -L${libdir} -lflatbuffers +Cflags: -I${includedir} diff --git a/third_party/flatbuffers/CMakeLists.txt b/third_party/flatbuffers/CMakeLists.txt index 7da75f41aed..c03688533a7 100644 --- a/third_party/flatbuffers/CMakeLists.txt +++ b/third_party/flatbuffers/CMakeLists.txt @@ -1,9 +1,15 @@ -cmake_minimum_required(VERSION 2.8) +# This is the legacy minimum version flatbuffers supported for a while. +cmake_minimum_required(VERSION 3.8...3.25.2) + +# Attempt to read the current version of flatbuffers by looking at the latest tag. +include(CMake/Version.cmake) + +project(FlatBuffers + VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH} + LANGUAGES CXX) + # generate compile_commands.json set(CMAKE_EXPORT_COMPILE_COMMANDS ON) -include(CheckCXXSymbolExists) - -project(FlatBuffers) # NOTE: Code coverage only works on Linux & OSX. option(FLATBUFFERS_CODE_COVERAGE "Enable the code coverage build option." OFF) @@ -13,7 +19,11 @@ 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_STATIC_FLATC "Build flatbuffers compiler with -static flag" + OFF) +option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" OFF) +option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark." + OFF) option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF) option(FLATBUFFERS_BUILD_SHAREDLIB "Enable the build of the flatbuffers shared library" @@ -29,6 +39,47 @@ option(FLATBUFFERS_PACKAGE_REDHAT option(FLATBUFFERS_PACKAGE_DEBIAN "Build an deb using the 'package' target." OFF) +option(FLATBUFFERS_BUILD_CPP17 + "Enable the build of c++17 test target. \" + Requirements: Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914) or higher." + OFF) +option(FLATBUFFERS_BUILD_LEGACY + "Run C++ code generator with '--cpp-std c++0x' switch." + OFF) +option(FLATBUFFERS_ENABLE_PCH + "Enable precompile headers support for 'flatbuffers' and 'flatc'. \" + Only work if CMake supports 'target_precompile_headers'. \" + This can speed up compilation time." + OFF) +option(FLATBUFFERS_SKIP_MONSTER_EXTRA + "Skip generating monster_extra.fbs that contains non-supported numerical\" + types." OFF) +option(FLATBUFFERS_STRICT_MODE + "Build flatbuffers with all warnings as errors (-Werror or /WX)." + OFF) + +if(NOT DEFINED FLATBUFFERS_CPP_STD) + set(FLATBUFFERS_CPP_STD 11) +endif() + +set(MSVC_LIKE OFF) +if(MSVC OR CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC") + set(MSVC_LIKE ON) +endif() + +if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(IS_CLANG ON) +else() + set(IS_CLANG OFF) +endif() + +if(DEFINED FLATBUFFERS_COMPILATION_TIMINGS) + message("Recording Compilation Timings to ${FLATBUFFERS_COMPILATION_TIMINGS}") + file(REMOVE ${FLATBUFFERS_COMPILATION_TIMINGS}) + set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}") + set_property(GLOBAL PROPERTY RULE_LAUNCH_CUSTOM "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}") + set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}") +endif() if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS) message(WARNING @@ -44,8 +95,10 @@ endif() # Auto-detect locale-narrow 'strtod_l' and 'strtoull_l' functions. if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT) + include(CheckCXXSymbolExists) + set(FLATBUFFERS_LOCALE_INDEPENDENT 0) - if(MSVC) + if(MSVC_LIKE) check_cxx_symbol_exists(_strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L) check_cxx_symbol_exists(_strtoui64_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L) else() @@ -58,20 +111,41 @@ if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT) endif() add_definitions(-DFLATBUFFERS_LOCALE_INDEPENDENT=$) +if(NOT WIN32) + check_symbol_exists(realpath "stdlib.h" HAVE_REALPATH) + if(NOT HAVE_REALPATH) + add_definitions(-DFLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION) + endif() +endif() + set(FlatBuffers_Library_SRCS - include/flatbuffers/code_generators.h + include/flatbuffers/allocator.h + include/flatbuffers/array.h include/flatbuffers/base.h + include/flatbuffers/buffer.h + include/flatbuffers/buffer_ref.h + include/flatbuffers/default_allocator.h + include/flatbuffers/detached_buffer.h + include/flatbuffers/code_generator.h + include/flatbuffers/file_manager.h + include/flatbuffers/flatbuffer_builder.h include/flatbuffers/flatbuffers.h + include/flatbuffers/flexbuffers.h + include/flatbuffers/flex_flat_util.h include/flatbuffers/hash.h include/flatbuffers/idl.h - include/flatbuffers/util.h + include/flatbuffers/minireflect.h include/flatbuffers/reflection.h include/flatbuffers/reflection_generated.h - include/flatbuffers/stl_emulation.h - include/flatbuffers/flexbuffers.h include/flatbuffers/registry.h - include/flatbuffers/minireflect.h - src/code_generators.cpp + include/flatbuffers/stl_emulation.h + include/flatbuffers/string.h + include/flatbuffers/struct.h + include/flatbuffers/table.h + include/flatbuffers/util.h + include/flatbuffers/vector.h + include/flatbuffers/vector_downward.h + include/flatbuffers/verifier.h src/idl_parser.cpp src/idl_gen_text.cpp src/reflection.cpp @@ -80,22 +154,43 @@ set(FlatBuffers_Library_SRCS set(FlatBuffers_Compiler_SRCS ${FlatBuffers_Library_SRCS} + src/idl_gen_binary.cpp + src/idl_gen_text.cpp src/idl_gen_cpp.cpp + src/idl_gen_csharp.cpp src/idl_gen_dart.cpp - src/idl_gen_general.cpp src/idl_gen_kotlin.cpp + src/idl_gen_kotlin_kmp.cpp src/idl_gen_go.cpp - src/idl_gen_js_ts.cpp + src/idl_gen_java.cpp + src/idl_gen_ts.cpp src/idl_gen_php.cpp src/idl_gen_python.cpp src/idl_gen_lobster.cpp - src/idl_gen_lua.cpp src/idl_gen_rust.cpp src/idl_gen_fbs.cpp src/idl_gen_grpc.cpp src/idl_gen_json_schema.cpp + src/idl_gen_swift.cpp + src/file_name_saving_file_manager.cpp + src/file_binary_writer.cpp + src/file_writer.cpp + src/idl_namer.h + src/namer.h src/flatc.cpp src/flatc_main.cpp + src/bfbs_gen.h + src/bfbs_gen_lua.h + src/bfbs_gen_nim.h + src/bfbs_namer.h + include/flatbuffers/code_generators.h + src/binary_annotator.h + src/binary_annotator.cpp + src/annotated_binary_text_gen.h + src/annotated_binary_text_gen.cpp + src/bfbs_gen_lua.cpp + src/bfbs_gen_nim.cpp + src/code_generators.cpp grpc/src/compiler/schema_interface.h grpc/src/compiler/cpp_generator.h grpc/src/compiler/cpp_generator.cc @@ -103,6 +198,12 @@ set(FlatBuffers_Compiler_SRCS grpc/src/compiler/go_generator.cc grpc/src/compiler/java_generator.h grpc/src/compiler/java_generator.cc + grpc/src/compiler/python_generator.h + grpc/src/compiler/python_generator.cc + grpc/src/compiler/swift_generator.h + grpc/src/compiler/swift_generator.cc + grpc/src/compiler/ts_generator.h + grpc/src/compiler/ts_generator.cc ) set(FlatHash_SRCS @@ -113,41 +214,51 @@ set(FlatHash_SRCS set(FlatBuffers_Tests_SRCS ${FlatBuffers_Library_SRCS} src/idl_gen_fbs.cpp + tests/evolution_test.cpp + tests/flexbuffers_test.cpp + tests/fuzz_test.cpp + tests/json_test.cpp + tests/key_field_test.cpp + tests/monster_test.cpp + tests/optional_scalars_test.cpp + tests/parser_test.cpp + tests/proto_test.cpp + tests/reflection_test.cpp tests/test.cpp tests/test_assert.h tests/test_assert.cpp tests/test_builder.h tests/test_builder.cpp + tests/util_test.cpp tests/native_type_test_impl.h tests/native_type_test_impl.cpp - # file generate by running compiler on tests/monster_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h - # file generate by running compiler on tests/arrays_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/arrays_test_generated.h - # file generate by running compiler on tests/native_type_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/native_type_test_generated.h + tests/alignment_test.h + tests/alignment_test.cpp + tests/64bit/offset64_test.h + tests/64bit/offset64_test.cpp + include/flatbuffers/code_generators.h + src/code_generators.cpp +) + +set(FlatBuffers_Tests_CPP17_SRCS + ${FlatBuffers_Library_SRCS} + tests/test_assert.h + tests/test_assert.cpp + tests/cpp17/test_cpp17.cpp ) set(FlatBuffers_Sample_Binary_SRCS - include/flatbuffers/flatbuffers.h samples/sample_binary.cpp - # file generated by running compiler on samples/monster.fbs - ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h ) set(FlatBuffers_Sample_Text_SRCS ${FlatBuffers_Library_SRCS} samples/sample_text.cpp - # file generated by running compiler on samples/monster.fbs - ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h ) set(FlatBuffers_Sample_BFBS_SRCS ${FlatBuffers_Library_SRCS} - src/idl_gen_general.cpp samples/sample_bfbs.cpp - # file generated by running compiler on samples/monster.fbs - ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h ) set(FlatBuffers_GRPCTest_SRCS @@ -163,210 +274,316 @@ set(FlatBuffers_GRPCTest_SRCS tests/test_builder.cpp grpc/tests/grpctest.cpp grpc/tests/message_builder_test.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(EXISTS "${CMAKE_TOOLCHAIN_FILE}") - # do not apply any global settings if the toolchain - # is being configured externally - message(STATUS "Using toolchain file: ${CMAKE_TOOLCHAIN_FILE}.") -elseif(APPLE) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Wno-unused-parameter") - set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast") -elseif(CMAKE_COMPILER_IS_GNUCXX) - if(CYGWIN) - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -std=gnu++11") - else(CYGWIN) - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -std=c++0x") - endif(CYGWIN) - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Werror=shadow") - set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast") - if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.4) - if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 7.0) - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -faligned-new -Werror=implicit-fallthrough=2") +# TODO(dbaileychess): Figure out how this would now work. I posted a question on +# https://stackoverflow.com/questions/71772330/override-target-compile-options-via-cmake-command-line. +# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS. +if(DEFINED FLATBUFFERS_CXX_FLAGS) + message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLATBUFFERS_CXX_FLAGS}") +endif() +message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}") + +function(add_fsanitize_to_target _target _sanitizer) + if(WIN32) + target_compile_definitions(${_target} PRIVATE FLATBUFFERS_MEMORY_LEAK_TRACKING) + message(STATUS "Sanitizer MSVC::_CrtDumpMemoryLeaks added to ${_target}") + else() + # FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer. + # List of sanitizer is string starts with '=': "=address,undefined,thread,memory". + if(IS_CLANG OR (CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 4.9)) + set(_sanitizer_flags "=address,undefined") + if(_sanitizer MATCHES "=.*") + # override default by user-defined sanitizer list + set(_sanitizer_flags ${_sanitizer}) + endif() + target_compile_options(${_target} PRIVATE + -g -fsigned-char -fno-omit-frame-pointer + "-fsanitize${_sanitizer_flags}") + target_link_libraries(${_target} PRIVATE + "-fsanitize${_sanitizer_flags}") + set_target_properties(${_target} PROPERTIES POSITION_INDEPENDENT_CODE ON) + message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}") endif() - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -Wunused-result -Werror=unused-result -Wunused-parameter -Werror=unused-parameter") endif() +endfunction() - # 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 -Wall -pedantic -Werror -Wextra -Wno-unused-parameter") - set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast") - if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.8) - list(APPEND FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wimplicit-fallthrough" "-Wextra-semi" "-Werror=unused-private-field") # enable warning - endif() - if(FLATBUFFERS_LIBCXX_WITH_CLANG) - if(NOT "${CMAKE_SYSTEM_NAME}" MATCHES "Linux") - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -stdlib=libc++") - endif() - if(NOT ("${CMAKE_SYSTEM_NAME}" MATCHES "FreeBSD" OR - "${CMAKE_SYSTEM_NAME}" MATCHES "Linux")) - set(CMAKE_EXE_LINKER_FLAGS - "${CMAKE_EXE_LINKER_FLAGS} -lc++abi") +function(add_pch_to_target _target _pch_header) + # the command is available since cmake 3.16 + if(COMMAND target_precompile_headers) + target_precompile_headers(${_target} PRIVATE ${_pch_header}) + if(NOT MSVC) + set_source_files_properties(src/util.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS ON) endif() endif() +endfunction() - # Certain platforms such as ARM do not use signed chars by default - # which causes issues with certain bounds checks. - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -fsigned-char") - -elseif(MSVC) - # Visual Studio pedantic build settings - # warning C4512: assignment operator could not be generated - # warning C4316: object allocated on the heap may not be aligned - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /WX /wd4512 /wd4316") -endif() +include_directories(include) +include_directories(grpc) -if(FLATBUFFERS_CODE_COVERAGE) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fprofile-arcs -ftest-coverage") - set(CMAKE_EXE_LINKER_FLAGS - "${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage") -endif() +# Creates an interface library that stores the configuration settings that each +# target links too. This is a compromise between setting configuration globally +# with add_compile_options() and the more targetted target_compile_options(). +# This way each target in this file can share settings and override them if +# needed. +add_library(ProjectConfig INTERFACE) +target_compile_features(ProjectConfig + INTERFACE + cxx_std_${FLATBUFFERS_CPP_STD} +) -function(add_fsanitize_to_target _target _sanitizer) - # FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer. - # List of sanitizer is string starts with '=': "=address,undefined,thread,memory". - if((${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") OR - ((${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9")) +# Force the standard to be met. +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# We shouldn't rely on any compiler-extensions to make things work. +set(CMAKE_CXX_EXTENSIONS OFF) + +if(MSVC_LIKE) + target_compile_options(ProjectConfig + INTERFACE + /W4 + $<$: + /WX # Treat all compiler warnings as errors + > + /wd4512 # C4512: assignment operator could not be generated + /wd4316 # C4316: object allocated on the heap may not be aligned + /wd4456 # C4456: hides previous local declaration + $<$: + /D_CRT_SECURE_NO_WARNINGS + > ) - set(_sanitizer_flags "=address,undefined") - if(_sanitizer MATCHES "=.*") - # override default by user-defined sanitizer list - set(_sanitizer_flags ${_sanitizer}) - endif() - target_compile_options(${_target} PRIVATE - -g -fsigned-char -fno-omit-frame-pointer - "-fsanitize${_sanitizer_flags}") - target_link_libraries(${_target} PRIVATE - "-fsanitize${_sanitizer_flags}") - set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ON) - message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}") - endif() -endfunction() +else() + target_compile_options(ProjectConfig + INTERFACE + -Wall + $<$: + -Werror # Treat all compiler warnings as errors + + -fno-rtti # Disable runtime type information + + $<$: + # False positive string overflow + # https://github.com/google/flatbuffers/issues/7366 + -Wno-error=stringop-overflow + > + > + -pedantic + -Wextra + -Wno-unused-parameter + -Wold-style-cast + -fsigned-char + -Wnon-virtual-dtor + + # This isn't working for some reason: $<$: + $<$: + -Wnewline-eof + -Wno-unknown-warning-option + -Wmissing-declarations + -Wzero-as-null-pointer-constant + $<$,3.8>: + -Wimplicit-fallthrough + -Wextra-semi + $<$: + -Werror=unused-private-field + > + > + > + + $<$: + $<$,4.4>: + -Wunused-result + -Wunused-parameter + -Werror=unused-parameter + -Wmissing-declarations + > + $<$,4.7>: + -Wzero-as-null-pointer-constant + > + $<$,7.0>: + -faligned-new + $<$: + -Werror=implicit-fallthrough=2 + > + > + $<$,8.0>: + -Wextra-semi + > + > + + $<$: + -g + -fprofile-arcs + -ftest-coverage + > + ) -if(BIICODE) - include(biicode/cmake/biicode.cmake) - return() + if(FLATBUFFERS_CODE_COVERAGE) + target_link_options(ProjectConfig + INTERFACE + -fprofile-arcs + -ftest-coverage + ) + endif() endif() -include_directories(include) -include_directories(grpc) - if(FLATBUFFERS_BUILD_FLATLIB) add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS}) - # CMake > 2.8.11: Attach header directory for when build via add_subdirectory(). - target_include_directories(flatbuffers INTERFACE - $) - target_compile_options(flatbuffers PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}") + + # Attach header directory for when build via add_subdirectory(). + target_include_directories(flatbuffers + INTERFACE + $ + ) + target_link_libraries(flatbuffers PRIVATE $) + + if(FLATBUFFERS_ENABLE_PCH) + add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h) + endif() endif() if(FLATBUFFERS_BUILD_FLATC) add_executable(flatc ${FlatBuffers_Compiler_SRCS}) - target_compile_options(flatc PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}") + if(FLATBUFFERS_ENABLE_PCH) + add_pch_to_target(flatc include/flatbuffers/pch/flatc_pch.h) + endif() + + target_link_libraries(flatc PRIVATE $) + target_compile_options(flatc + PRIVATE + $<$,$>: + /MT + > + ) + if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32) add_fsanitize_to_target(flatc ${FLATBUFFERS_CODE_SANITIZE}) endif() if(NOT FLATBUFFERS_FLATC_EXECUTABLE) set(FLATBUFFERS_FLATC_EXECUTABLE $) endif() - if(MSVC) - # Make flatc.exe not depend on runtime dlls for easy distribution. - target_compile_options(flatc PUBLIC $<$:/MT>) + if(FLATBUFFERS_STATIC_FLATC AND NOT MSVC) + target_link_libraries(flatc PRIVATE -static) endif() endif() if(FLATBUFFERS_BUILD_FLATHASH) add_executable(flathash ${FlatHash_SRCS}) + target_link_libraries(flathash PRIVATE $) endif() if(FLATBUFFERS_BUILD_SHAREDLIB) add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS}) - - # Shared object version: "major.minor.micro" - # - micro updated every release when there is no API/ABI changes - # - minor updated when there are additions in API/ABI - # - major (ABI number) updated when there are changes in ABI (or removals) - set(FlatBuffers_Library_SONAME_MAJOR "1") - set(FlatBuffers_Library_SONAME_FULL "${FlatBuffers_Library_SONAME_MAJOR}.11.0") - set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers - SOVERSION "${FlatBuffers_Library_SONAME_MAJOR}" + target_link_libraries(flatbuffers_shared PRIVATE $) + # FlatBuffers use calendar-based versioning and do not provide any ABI + # stability guarantees. Therefore, always use the full version as SOVERSION + # in order to avoid breaking reverse dependencies on upgrades. + set(FlatBuffers_Library_SONAME_FULL "${PROJECT_VERSION}") + set_target_properties(flatbuffers_shared PROPERTIES + OUTPUT_NAME flatbuffers + SOVERSION "${FlatBuffers_Library_SONAME_FULL}" VERSION "${FlatBuffers_Library_SONAME_FULL}") + if(FLATBUFFERS_ENABLE_PCH) + add_pch_to_target(flatbuffers_shared include/flatbuffers/pch/pch.h) + endif() endif() -function(compile_flatbuffers_schema_to_cpp_opt SRC_FBS OPT) +function(compile_schema SRC_FBS OPT OUT_GEN_FILE) get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH) string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS}) add_custom_command( OUTPUT ${GEN_HEADER} - COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" -c --gen-mutable - --gen-object-api -o "${SRC_FBS_DIR}" - --cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs - --reflect-names ${OPT} - -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test" - "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" - DEPENDS flatc) + COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" + ${OPT} + -o "${SRC_FBS_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" + DEPENDS flatc ${SRC_FBS} + COMMENT "flatc generation: `${SRC_FBS}` -> `${GEN_HEADER}`" + ) + set(${OUT_GEN_FILE} ${GEN_HEADER} PARENT_SCOPE) endfunction() -function(compile_flatbuffers_schema_to_cpp SRC_FBS) - compile_flatbuffers_schema_to_cpp_opt(${SRC_FBS} "--no-includes;--gen-compare") +function(compile_schema_for_test SRC_FBS OPT) + compile_schema("${SRC_FBS}" "${OPT}" GEN_FILE) + target_sources(flattests PRIVATE ${GEN_FILE}) endfunction() -function(compile_flatbuffers_schema_to_binary SRC_FBS) - get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH) - string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS}) - add_custom_command( - OUTPUT ${GEN_BINARY_SCHEMA} - COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" -b --schema -o "${SRC_FBS_DIR}" - "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" - DEPENDS flatc) +function(compile_schema_for_samples SRC_FBS OPT) + compile_schema("${SRC_FBS}" "${OPT}" GEN_FILE) + target_sources(flatsample PRIVATE ${GEN_FILE}) endfunction() if(FLATBUFFERS_BUILD_TESTS) - compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs) - compile_flatbuffers_schema_to_cpp_opt(tests/native_type_test.fbs "") - compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs --scoped-enums) - include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests) add_executable(flattests ${FlatBuffers_Tests_SRCS}) - set_property(TARGET flattests - PROPERTY COMPILE_DEFINITIONS FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE - FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1) + target_link_libraries(flattests PRIVATE $) + target_include_directories(flattests PUBLIC + # Ideally everything is fully qualified from the root directories + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_BINARY_DIR} + # TODO(derekbailey): update includes to fully qualify src/ and tests/ + src + tests + ${CMAKE_CURRENT_BINARY_DIR}/tests + ) + + # Have tests load data from the source directory, not the build directory. + add_definitions(-DFLATBUFFERS_TEST_PATH_PREFIX=${CMAKE_CURRENT_SOURCE_DIR}/) + + # The flattest target needs some generated files + SET(FLATC_OPT --cpp --gen-mutable --gen-object-api --reflect-names) + SET(FLATC_OPT_COMP ${FLATC_OPT};--gen-compare) + SET(FLATC_OPT_SCOPED_ENUMS ${FLATC_OPT_COMP};--scoped-enums) + + compile_schema_for_test(tests/alignment_test.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/arrays_test.fbs "${FLATC_OPT_SCOPED_ENUMS}") + compile_schema_for_test(tests/native_inline_table_test.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/native_type_test.fbs "${FLATC_OPT}") + compile_schema_for_test(tests/key_field/key_field_sample.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/64bit/test_64bit.fbs "${FLATC_OPT_COMP};--bfbs-gen-embed") + compile_schema_for_test(tests/64bit/evolution/v1.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/64bit/evolution/v2.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/union_underlying_type_test.fbs "${FLATC_OPT_SCOPED_ENUMS}") + if(FLATBUFFERS_CODE_SANITIZE) - if(WIN32) - target_compile_definitions(flattests PRIVATE FLATBUFFERS_MEMORY_LEAK_TRACKING) - message(STATUS "Sanitizer MSVC::_CrtDumpMemoryLeaks added to flattests") - else() - add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE}) - endif() + add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE}) endif() - - compile_flatbuffers_schema_to_cpp(samples/monster.fbs) + include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples) + add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS}) add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS}) add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS}) + + # Add a library so there is a single target that the generated samples can + # link too. + if(MSVC OR ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.20.0") + add_library(flatsample INTERFACE) + else() + add_library(flatsample STATIC) + endif() + + # Since flatsample has no sources, we have to explicitly set the linker lang. + set_target_properties(flatsample PROPERTIES LINKER_LANGUAGE CXX) + + compile_schema_for_samples(samples/monster.fbs "${FLATC_OPT_COMP}") + + target_link_libraries(flatsamplebinary PRIVATE $ flatsample) + target_link_libraries(flatsampletext PRIVATE $ flatsample) + target_link_libraries(flatsamplebfbs PRIVATE $ flatsample) + + if(FLATBUFFERS_BUILD_CPP17) + add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS}) + target_link_libraries(flattests_cpp17 PRIVATE $) + target_include_directories(flattests_cpp17 PUBLIC src tests) + target_compile_features(flattests_cpp17 PRIVATE cxx_std_17) # requires cmake 3.8 + + if(FLATBUFFERS_CODE_SANITIZE) + add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE}) + endif() + endif(FLATBUFFERS_BUILD_CPP17) endif() if(FLATBUFFERS_BUILD_GRPCTEST) - if(CMAKE_COMPILER_IS_GNUCXX) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter -Wno-shadow") - endif() if(NOT GRPC_INSTALL_PATH) message(SEND_ERROR "GRPC_INSTALL_PATH variable is not defined. See grpc/README.md") endif() @@ -375,13 +592,22 @@ if(FLATBUFFERS_BUILD_GRPCTEST) endif() INCLUDE_DIRECTORIES(${GRPC_INSTALL_PATH}/include) INCLUDE_DIRECTORIES(${PROTOBUF_DOWNLOAD_PATH}/src) - LINK_DIRECTORIES(${GRPC_INSTALL_PATH}/lib) + find_package(Threads REQUIRED) + list(APPEND CMAKE_PREFIX_PATH ${GRPC_INSTALL_PATH}) + find_package(absl CONFIG REQUIRED) + find_package(protobuf CONFIG REQUIRED) + find_package(gRPC CONFIG REQUIRED) add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS}) - target_link_libraries(grpctest grpc++_unsecure grpc_unsecure gpr pthread dl) + target_link_libraries(grpctest + PRIVATE + $ + gRPC::grpc++_unsecure + gRPC::gpr + pthread + dl + ) endif() -include(CMake/Version.cmake) - if(FLATBUFFERS_INSTALL) include(GNUInstallDirs) @@ -389,28 +615,24 @@ if(FLATBUFFERS_INSTALL) set(FB_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/flatbuffers") - configure_file(CMake/FlatbuffersConfigVersion.cmake.in FlatbuffersConfigVersion.cmake @ONLY) + configure_file(CMake/flatbuffers-config-version.cmake.in flatbuffers-config-version.cmake @ONLY) install( - FILES "CMake/FlatbuffersConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/FlatbuffersConfigVersion.cmake" + FILES + "CMake/flatbuffers-config.cmake" + "CMake/BuildFlatBuffers.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-config-version.cmake" DESTINATION ${FB_CMAKE_DIR} ) if(FLATBUFFERS_BUILD_FLATLIB) - if(CMAKE_VERSION VERSION_LESS 3.0) - install( - TARGETS flatbuffers EXPORT FlatbuffersTargets - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - ) - else() - install( - TARGETS flatbuffers EXPORT FlatbuffersTargets - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} - ) - endif() + install( + TARGETS flatbuffers EXPORT FlatBuffersTargets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} + ) - install(EXPORT FlatbuffersTargets - FILE FlatbuffersTargets.cmake + install(EXPORT FlatBuffersTargets + FILE FlatBuffersTargets.cmake NAMESPACE flatbuffers:: DESTINATION ${FB_CMAKE_DIR} ) @@ -431,38 +653,38 @@ if(FLATBUFFERS_INSTALL) endif() if(FLATBUFFERS_BUILD_SHAREDLIB) - if(CMAKE_VERSION VERSION_LESS 3.0) - install( - TARGETS flatbuffers_shared EXPORT FlatbuffersSharedTargets - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ) - else() - install( - TARGETS flatbuffers_shared EXPORT FlatbuffersSharedTargets - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} - ) - endif() + install( + TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} + ) - install( - EXPORT FlatbuffersSharedTargets - FILE FlatbuffersSharedTargets.cmake + install( + EXPORT FlatBuffersSharedTargets + FILE FlatBuffersSharedTargets.cmake NAMESPACE flatbuffers:: DESTINATION ${FB_CMAKE_DIR} ) endif() + + if(FLATBUFFERS_BUILD_SHAREDLIB OR FLATBUFFERS_BUILD_FLATLIB) + configure_file(CMake/flatbuffers.pc.in flatbuffers.pc @ONLY) + install( + FILES "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers.pc" + DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig + ) + endif() endif() if(FLATBUFFERS_BUILD_TESTS) enable_testing() - file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION - "${CMAKE_CURRENT_BINARY_DIR}") add_test(NAME flattests COMMAND flattests) + if(FLATBUFFERS_BUILD_CPP17) + add_test(NAME flattests_cpp17 COMMAND flattests_cpp17) + endif() if(FLATBUFFERS_BUILD_GRPCTEST) add_test(NAME grpctest COMMAND grpctest) endif() @@ -474,9 +696,23 @@ if(UNIX) # Use of CPack only supported on Linux systems. if(FLATBUFFERS_PACKAGE_DEBIAN) include(CMake/PackageDebian.cmake) + include(CPack) endif() if (FLATBUFFERS_PACKAGE_REDHAT) include(CMake/PackageRedhat.cmake) + include(CPack) endif() - include(CPack) endif() + +# Include for running Google Benchmarks. +if(FLATBUFFERS_BUILD_BENCHMARKS) + add_subdirectory(benchmarks) +endif() + +# Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare +add_library(FlatBuffers INTERFACE) +add_library(FlatBuffers::FlatBuffers ALIAS FlatBuffers) +target_include_directories( + FlatBuffers + INTERFACE $ + $) diff --git a/third_party/flatbuffers/FlatBuffers.podspec b/third_party/flatbuffers/FlatBuffers.podspec new file mode 100644 index 00000000000..2aa69e2a027 --- /dev/null +++ b/third_party/flatbuffers/FlatBuffers.podspec @@ -0,0 +1,21 @@ +Pod::Spec.new do |s| + s.name = 'FlatBuffers' + s.version = '24.3.25' + s.summary = 'FlatBuffers: Memory Efficient Serialization Library' + + s.description = "FlatBuffers is a cross platform serialization library architected for + maximum memory efficiency. It allows you to directly access serialized + data without parsing/unpacking it first, while still having great + forwards/backwards compatibility." + + s.homepage = 'https://github.com/google/flatbuffers' + s.license = { :type => 'Apache2.0', :file => 'LICENSE' } + s.author = { 'mustii' => 'mustii@mmk.one' } + s.source = { :git => 'https://github.com/google/flatbuffers.git', :tag => s.version.to_s, :submodules => true } + + s.ios.deployment_target = '11.0' + s.osx.deployment_target = '10.14' + + s.swift_version = '5.0' + s.source_files = 'swift/Sources/Flatbuffers/*.swift' +end diff --git a/third_party/flatbuffers/Formatters.md b/third_party/flatbuffers/Formatters.md new file mode 100644 index 00000000000..877c5f2010a --- /dev/null +++ b/third_party/flatbuffers/Formatters.md @@ -0,0 +1,22 @@ +# Format Guidelines + +If you are interesting in contributing to the flatbuffers project, please take a second to read this document. Each language has it's own set of rules, that are defined in their respective formatter/linter documents. + +# Notes + +- Run the linter on the language you are working on before making a Pull Request. +- DONT format/lint the generated code. + +# Languages + +## C++ + +C++ uses `clang-format` as it's formatter. Run the following script `sh scripts/clang-format-git.sh`, and it should style the C++ code according to [google style guide](https://google.github.io/styleguide/cppguide.html). + +## Swift + +Swift uses swiftformat as it's formatter. Take a look at [how to install here](https://github.com/nicklockwood/SwiftFormat/blob/master/README.md#how-do-i-install-it). Run the following command `swiftformat --config swift.swiftformat .` in the root directory of the project + +## Typescript + +Typescript uses eslint as it's linter. Take a look at [how to install here](https://eslint.org/docs/user-guide/getting-started). Run the following command `eslint ts/** --ext .ts` in the root directory of the project \ No newline at end of file diff --git a/third_party/flatbuffers/dart/LICENSE b/third_party/flatbuffers/LICENSE similarity index 86% rename from third_party/flatbuffers/dart/LICENSE rename to third_party/flatbuffers/LICENSE index b2ae013b7e1..d6456956733 100644 --- a/third_party/flatbuffers/dart/LICENSE +++ b/third_party/flatbuffers/LICENSE @@ -1,34 +1,3 @@ -The code in lib/flat_buffers.dart is based on code that was releases under the -following license: - -Copyright 2012, the Dart project authors. All rights reserved. -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of Google Inc. nor the names of its - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -To the extent permissible, the changes to that code and the other assets in -this package are licensed under the Apache2 license: - Apache License Version 2.0, January 2004 @@ -218,7 +187,7 @@ this package are licensed under the Apache2 license: same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2014 Google Inc. + Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/third_party/flatbuffers/LICENSE.txt b/third_party/flatbuffers/LICENSE.txt deleted file mode 100644 index a4c5efd822f..00000000000 --- a/third_party/flatbuffers/LICENSE.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2014 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - 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. diff --git a/third_party/flatbuffers/Package.swift b/third_party/flatbuffers/Package.swift new file mode 100644 index 00000000000..0fc26da7601 --- /dev/null +++ b/third_party/flatbuffers/Package.swift @@ -0,0 +1,36 @@ +// swift-tools-version:5.6 +/* + * Copyright 2020 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import PackageDescription + +let package = Package( + name: "FlatBuffers", + platforms: [ + .iOS(.v11), + .macOS(.v10_14), + ], + products: [ + .library( + name: "FlatBuffers", + targets: ["FlatBuffers"]), + ], + targets: [ + .target( + name: "FlatBuffers", + dependencies: [], + path: "swift/Sources"), + ]) diff --git a/third_party/flatbuffers/Package@swift-5.5.swift b/third_party/flatbuffers/Package@swift-5.5.swift new file mode 100644 index 00000000000..13313560ee0 --- /dev/null +++ b/third_party/flatbuffers/Package@swift-5.5.swift @@ -0,0 +1,37 @@ +// swift-tools-version:5.5 +/* + * Copyright 2020 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import PackageDescription + +let package = Package( + name: "FlatBuffers", + platforms: [ + .iOS(.v11), + .macOS(.v10_14), + ], + products: [ + .library( + name: "FlatBuffers", + targets: ["FlatBuffers"]), + ], + targets: [ + .target( + name: "FlatBuffers", + dependencies: [], + path: "swift/Sources"), + ]) + diff --git a/third_party/flatbuffers/README.md b/third_party/flatbuffers/README.md new file mode 100644 index 00000000000..47d506720e1 --- /dev/null +++ b/third_party/flatbuffers/README.md @@ -0,0 +1,118 @@ +![logo](http://google.github.io/flatbuffers/fpl_logo_small.png) FlatBuffers +=========== + +![Build status](https://github.com/google/flatbuffers/actions/workflows/build.yml/badge.svg?branch=master) +[![BuildKite status](https://badge.buildkite.com/7979d93bc6279aa539971f271253c65d5e8fe2fe43c90bbb25.svg)](https://buildkite.com/bazel/flatbuffers) +[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/flatbuffers.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:flatbuffers) +[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers/badge)](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers) +[![Join the chat at https://gitter.im/google/flatbuffers](https://badges.gitter.im/google/flatbuffers.svg)](https://gitter.im/google/flatbuffers?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![Discord Chat](https://img.shields.io/discord/656202785926152206.svg)](https:///discord.gg/6qgKs3R) +[![Twitter Follow](https://img.shields.io/twitter/follow/wvo.svg?style=social)](https://twitter.com/wvo) +[![Twitter Follow](https://img.shields.io/twitter/follow/dbaileychess.svg?style=social)](https://twitter.com/dbaileychess) + + +**FlatBuffers** is a cross platform serialization library architected for +maximum memory efficiency. It allows you to directly access serialized data without parsing/unpacking it first, while still having great forwards/backwards compatibility. + +## Quick Start + +1. Build the compiler for flatbuffers (`flatc`) + + Use `cmake` to create the build files for your platform and then perform the compliation (Linux example). + + ``` + cmake -G "Unix Makefiles" + make -j + ``` + +2. Define your flatbuffer schema (`.fbs`) + + Write the [schema](https://flatbuffers.dev/flatbuffers_guide_writing_schema.html) to define the data you want to serialize. See [monster.fbs](https://github.com/google/flatbuffers/blob/master/samples/monster.fbs) for an example. + +3. Generate code for your language(s) + + Use the `flatc` compiler to take your schema and generate language-specific code: + + ``` + ./flatc --cpp --rust monster.fbs + ``` + + Which generates `monster_generated.h` and `monster_generated.rs` files. + +4. Serialize data + + Use the generated code, as well as the `FlatBufferBuilder` to construct your serialized buffer. ([`C++` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp#L24-L56)) + +5. Transmit/store/save Buffer + + Use your serialized buffer however you want. Send it to someone, save it for later, etc... + +6. Read the data + + Use the generated accessors to read the data from the serialized buffer. + + It doesn't need to be the same language/schema version, FlatBuffers ensures the data is readable across languages and schema versions. See the [`Rust` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs#L92-L106) reading the data written by `C++`. + +## Documentation + +**Go to our [landing page][] to browse our documentation.** + +## Supported operating systems +- Windows +- macOS +- Linux +- Android +- And any others with a recent C++ compiler (C++ 11 and newer) + +## Supported programming languages + +Code generation and runtime libraries for many popular languages. + +1. C +1. C++ - [snapcraft.io](https://snapcraft.io/flatbuffers) +1. C# - [nuget.org](https://www.nuget.org/packages/Google.FlatBuffers) +1. Dart - [pub.dev](https://pub.dev/packages/flat_buffers) +1. Go - [go.dev](https://pkg.go.dev/github.com/google/flatbuffers) +1. Java - [Maven](https://search.maven.org/artifact/com.google.flatbuffers/flatbuffers-java) +1. JavaScript - [NPM](https://www.npmjs.com/package/flatbuffers) +1. Kotlin +1. Lobster +1. Lua +1. PHP +1. Python - [PyPI](https://pypi.org/project/flatbuffers/) +1. Rust - [crates.io](https://crates.io/crates/flatbuffers) +1. Swift - [swiftpackageindex](https://swiftpackageindex.com/google/flatbuffers) +1. TypeScript - [NPM](https://www.npmjs.com/package/flatbuffers) +1. Nim + +## Versioning + +FlatBuffers does not follow traditional SemVer versioning (see [rationale](https://github.com/google/flatbuffers/wiki/Versioning)) but rather uses a format of the date of the release. + +## Contribution + +* [FlatBuffers Issues Tracker][] to submit an issue. +* [stackoverflow.com][] with [`flatbuffers` tag][] for any questions regarding FlatBuffers. + +*To contribute to this project,* see [CONTRIBUTING][]. + +## Community + +* [Discord Server](https:///discord.gg/6qgKs3R) + +## Security + +Please see our [Security Policy](SECURITY.md) for reporting vulnerabilities. + +## Licensing +*Flatbuffers* is licensed under the Apache License, Version 2.0. See [LICENSE][] for the full license text. + +
+ + [CONTRIBUTING]: http://github.com/google/flatbuffers/blob/master/CONTRIBUTING.md + [`flatbuffers` tag]: https://stackoverflow.com/questions/tagged/flatbuffers + [FlatBuffers Google Group]: https://groups.google.com/forum/#!forum/flatbuffers + [FlatBuffers Issues Tracker]: http://github.com/google/flatbuffers/issues + [stackoverflow.com]: http://stackoverflow.com/search?q=flatbuffers + [landing page]: https://google.github.io/flatbuffers + [LICENSE]: https://github.com/google/flatbuffers/blob/master/LICENSE diff --git a/third_party/flatbuffers/SECURITY.md b/third_party/flatbuffers/SECURITY.md new file mode 100644 index 00000000000..c61f66f84a0 --- /dev/null +++ b/third_party/flatbuffers/SECURITY.md @@ -0,0 +1,11 @@ +# Security Policy + +## Reporting a Vulnerability + +To report a security issue, please use http://g.co/vulnz. We use +http://g.co/vulnz for our intake, and do coordination and disclosure here on +GitHub (including using GitHub Security Advisory). The Google Security Team will +respond within 5 working days of your report on g.co/vulnz. + +Select the `I want to report a technical security or an abuse risk related bug +in a Google product (SQLi, XSS, etc.)` option and complete the form. diff --git a/third_party/flatbuffers/WORKSPACE b/third_party/flatbuffers/WORKSPACE index 2ccde8469a9..e56d4ce364b 100644 --- a/third_party/flatbuffers/WORKSPACE +++ b/third_party/flatbuffers/WORKSPACE @@ -1,18 +1,169 @@ workspace(name = "com_github_google_flatbuffers") -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file") + +http_archive( + name = "platforms", + sha256 = "3a561c99e7bdbe9173aa653fd579fe849f1d8d67395780ab4770b1f381431d51", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.7/platforms-0.0.7.tar.gz", + "https://github.com/bazelbuild/platforms/releases/download/0.0.7/platforms-0.0.7.tar.gz", + ], +) + +http_archive( + name = "build_bazel_rules_apple", + sha256 = "34c41bfb59cdaea29ac2df5a2fa79e5add609c71bb303b2ebb10985f93fa20e7", + url = "https://github.com/bazelbuild/rules_apple/releases/download/3.1.1/rules_apple.3.1.1.tar.gz", +) + +load( + "@build_bazel_rules_apple//apple:repositories.bzl", + "apple_rules_dependencies", +) + +apple_rules_dependencies() + +http_archive( + name = "build_bazel_rules_swift", + sha256 = "a2fd565e527f83fb3f9eb07eb9737240e668c9242d3bc318712efa54a7deda97", + url = "https://github.com/bazelbuild/rules_swift/releases/download/0.27.0/rules_swift.0.27.0.tar.gz", +) + +load( + "@build_bazel_rules_swift//swift:repositories.bzl", + "swift_rules_dependencies", +) + +swift_rules_dependencies() + +load( + "@build_bazel_rules_swift//swift:extras.bzl", + "swift_rules_extra_dependencies", +) + +swift_rules_extra_dependencies() http_archive( name = "io_bazel_rules_go", + sha256 = "278b7ff5a826f3dc10f04feaf0b70d48b68748ccd512d7f98bf442077f043fe3", urls = [ - "https://storage.googleapis.com/bazel-mirror/github.com/bazelbuild/rules_go/releases/download/0.18.6/rules_go-0.18.6.tar.gz", - "https://github.com/bazelbuild/rules_go/releases/download/0.18.6/rules_go-0.18.6.tar.gz", + "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.0.zip", + "https://github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.0.zip", ], - sha256 = "f04d2373bcaf8aa09bccb08a98a57e721306c8f6043a2a0ee610fd6853dcde3d", ) -load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") +load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies") go_rules_dependencies() -go_register_toolchains() +##### Protobuf +_PROTOBUF_VERSION = "3.15.2" + +http_archive( + name = "com_google_protobuf", + strip_prefix = "protobuf-" + _PROTOBUF_VERSION, + urls = [ + "https://github.com/protocolbuffers/protobuf/archive/v" + _PROTOBUF_VERSION + ".tar.gz", + ], +) + +##### GRPC +_GRPC_VERSION = "1.49.0" # https://github.com/grpc/grpc/releases/tag/v1.48.0 + +http_archive( + name = "com_github_grpc_grpc", + patch_args = ["-p1"], + patches = ["//grpc:build_grpc_with_cxx14.patch"], + sha256 = "15715e1847cc9e42014f02c727dbcb48e39dbdb90f79ad3d66fe4361709ff935", + strip_prefix = "grpc-" + _GRPC_VERSION, + urls = ["https://github.com/grpc/grpc/archive/refs/tags/v" + _GRPC_VERSION + ".tar.gz"], +) + +load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps") + +grpc_deps() + +load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps") + +grpc_extra_deps() + +# rules_go from https://github.com/bazelbuild/rules_go/releases/tag/v0.34.0 + +http_archive( + name = "aspect_rules_js", + sha256 = "76a04ef2120ee00231d85d1ff012ede23963733339ad8db81f590791a031f643", + strip_prefix = "rules_js-1.34.1", + url = "https://github.com/aspect-build/rules_js/releases/download/v1.34.1/rules_js-v1.34.1.tar.gz", +) + +load("@aspect_rules_js//js:repositories.bzl", "rules_js_dependencies") + +rules_js_dependencies() + +load("@aspect_rules_js//npm:npm_import.bzl", "npm_translate_lock", "pnpm_repository") + +pnpm_repository(name = "pnpm") + +http_archive( + name = "aspect_rules_ts", + sha256 = "4c3f34fff9f96ffc9c26635d8235a32a23a6797324486c7d23c1dfa477e8b451", + strip_prefix = "rules_ts-1.4.5", + url = "https://github.com/aspect-build/rules_ts/releases/download/v1.4.5/rules_ts-v1.4.5.tar.gz", +) + +load("@aspect_rules_ts//ts:repositories.bzl", "rules_ts_dependencies") + +rules_ts_dependencies( + # Since rules_ts doesn't always have the newest integrity hashes, we + # compute it manually here. + # $ curl --silent https://registry.npmjs.org/typescript/5.3.3 | jq ._integrity + ts_integrity = "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", + ts_version_from = "//:package.json", +) + +load("@rules_nodejs//nodejs:repositories.bzl", "DEFAULT_NODE_VERSION", "nodejs_register_toolchains") + +nodejs_register_toolchains( + name = "nodejs", + node_version = DEFAULT_NODE_VERSION, +) + +npm_translate_lock( + name = "npm", + npmrc = "//:.npmrc", + pnpm_lock = "//:pnpm-lock.yaml", + # Set this to True when the lock file needs to be updated, commit the + # changes, then set to False again. + update_pnpm_lock = False, + verify_node_modules_ignored = "//:.bazelignore", +) + +load("@npm//:repositories.bzl", "npm_repositories") + +npm_repositories() + +http_archive( + name = "aspect_rules_esbuild", + sha256 = "098e38e5ee868c14a6484ba263b79e57d48afacfc361ba30137c757a9c4716d6", + strip_prefix = "rules_esbuild-0.15.0", + url = "https://github.com/aspect-build/rules_esbuild/releases/download/v0.15.0/rules_esbuild-v0.15.0.tar.gz", +) + +# Register a toolchain containing esbuild npm package and native bindings +load("@aspect_rules_esbuild//esbuild:repositories.bzl", "LATEST_ESBUILD_VERSION", "esbuild_register_toolchains") + +esbuild_register_toolchains( + name = "esbuild", + esbuild_version = LATEST_ESBUILD_VERSION, +) + +http_file( + name = "bazel_linux_x86_64", + downloaded_file_path = "bazel", + executable = True, + sha256 = "e78fc3394deae5408d6f49a15c7b1e615901969ecf6e50d55ef899996b0b8458", + urls = [ + "https://github.com/bazelbuild/bazel/releases/download/6.3.2/bazel-6.3.2-linux-x86_64", + ], +) diff --git a/third_party/flatbuffers/android/AndroidManifest.xml b/third_party/flatbuffers/android/AndroidManifest.xml deleted file mode 100644 index 846fd13cba7..00000000000 --- a/third_party/flatbuffers/android/AndroidManifest.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/third_party/flatbuffers/android/build.gradle b/third_party/flatbuffers/android/build.gradle deleted file mode 100644 index 5e9809be769..00000000000 --- a/third_party/flatbuffers/android/build.gradle +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) 2017 Google, Inc. -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -buildscript { - repositories { - jcenter() - } - dependencies { - classpath 'com.android.tools.build:gradle:2.3.0' - } -} - -allprojects { - repositories { - jcenter() - } -} - -apply plugin: 'com.android.application' - -android { - compileSdkVersion 25 - buildToolsVersion '25.0.2' - - sourceSets { - main { - manifest.srcFile 'AndroidManifest.xml' - res.srcDirs = ['res'] - } - } - - externalNativeBuild { - ndkBuild { - path "jni/Android.mk" - } - } - - defaultConfig { - applicationId 'com.example.FlatBufferTest' - // This is the platform API where NativeActivity was introduced. - minSdkVersion 9 - targetSdkVersion 25 - versionCode 1 - versionName "1.0" - - buildTypes { - release { - minifyEnabled false - } - } - - externalNativeBuild { - ndkBuild { - targets "FlatBufferTest" - arguments "-j" + Runtime.getRuntime().availableProcessors() - abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64" - } - } - } - - lintOptions { - abortOnError false - } - - // Build with each STL variant. - productFlavors { - stlport { - applicationIdSuffix ".stlport" - versionNameSuffix "-stlport" - externalNativeBuild { - ndkBuild { - arguments "APP_STL=stlport_static" - } - } - } - gnustl { - applicationIdSuffix ".gnustl" - versionNameSuffix "-gnustl" - externalNativeBuild { - ndkBuild { - arguments "APP_STL=gnustl_static" - } - } - } - libcpp { - applicationIdSuffix ".libcpp" - versionNameSuffix "-libcpp" - externalNativeBuild { - ndkBuild { - arguments "APP_STL=c++_static" - } - } - } - } -} diff --git a/third_party/flatbuffers/android/gradle/wrapper/gradle-wrapper.properties b/third_party/flatbuffers/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 1e1168cf6cf..00000000000 --- a/third_party/flatbuffers/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Mon Jun 19 11:54:59 PDT 2017 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-all.zip diff --git a/third_party/flatbuffers/android/gradlew b/third_party/flatbuffers/android/gradlew deleted file mode 100755 index cccdd3d517f..00000000000 --- a/third_party/flatbuffers/android/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/third_party/flatbuffers/android/gradlew.bat b/third_party/flatbuffers/android/gradlew.bat deleted file mode 100644 index f9553162f12..00000000000 --- a/third_party/flatbuffers/android/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/third_party/flatbuffers/android/jni/Android.mk b/third_party/flatbuffers/android/jni/Android.mk deleted file mode 100644 index e29c87289f0..00000000000 --- a/third_party/flatbuffers/android/jni/Android.mk +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright (c) 2013 Google, Inc. -# -# This software is provided 'as-is', without any express or implied -# warranty. In no event will the authors be held liable for any damages -# arising from the use of this software. -# Permission is granted to anyone to use this software for any purpose, -# including commercial applications, and to alter it and redistribute it -# freely, subject to the following restrictions: -# 1. The origin of this software must not be misrepresented; you must not -# claim that you wrote the original software. If you use this software -# in a product, an acknowledgment in the product documentation would be -# appreciated but is not required. -# 2. Altered source versions must be plainly marked as such, and must not be -# misrepresented as being the original software. -# 3. This notice may not be removed or altered from any source distribution. - -LOCAL_PATH := $(call my-dir)/../.. - -include $(LOCAL_PATH)/android/jni/include.mk -LOCAL_PATH := $(call realpath-portable,$(LOCAL_PATH)) - -# Empty static library so that other projects can include just the basic -# FlatBuffers headers as a module. -include $(CLEAR_VARS) -LOCAL_MODULE := flatbuffers -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include -LOCAL_EXPORT_CPPFLAGS := -std=c++11 -fexceptions -Wall \ - -DFLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE - -include $(BUILD_STATIC_LIBRARY) - -# static library that additionally includes text parsing/generation/reflection -# for projects that want richer functionality. -include $(CLEAR_VARS) -LOCAL_MODULE := flatbuffers_extra -LOCAL_SRC_FILES := src/idl_parser.cpp \ - src/idl_gen_text.cpp \ - src/reflection.cpp \ - src/util.cpp \ - src/code_generators.cpp -LOCAL_STATIC_LIBRARIES := flatbuffers -LOCAL_ARM_MODE := arm -include $(BUILD_STATIC_LIBRARY) - -# FlatBuffers test -include $(CLEAR_VARS) -LOCAL_MODULE := FlatBufferTest -LOCAL_SRC_FILES := android/jni/main.cpp \ - tests/test.cpp \ - tests/test_assert.h \ - tests/test_builder.h \ - tests/test_assert.cpp \ - tests/test_builder.cpp \ - tests/native_type_test_impl.h \ - tests/native_type_test_impl.cpp \ - src/idl_gen_fbs.cpp \ - src/idl_gen_general.cpp -LOCAL_LDLIBS := -llog -landroid -latomic -LOCAL_STATIC_LIBRARIES := android_native_app_glue flatbuffers_extra -LOCAL_ARM_MODE := arm -include $(BUILD_SHARED_LIBRARY) - -$(call import-module,android/native_app_glue) - -$(call import-add-path,$(LOCAL_PATH)/../..) diff --git a/third_party/flatbuffers/android/jni/Application.mk b/third_party/flatbuffers/android/jni/Application.mk deleted file mode 100644 index ca9e8004dbf..00000000000 --- a/third_party/flatbuffers/android/jni/Application.mk +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) 2014 Google, Inc. -# -# This software is provided 'as-is', without any express or implied -# warranty. In no event will the authors be held liable for any damages -# arising from the use of this software. -# Permission is granted to anyone to use this software for any purpose, -# including commercial applications, and to alter it and redistribute it -# freely, subject to the following restrictions: -# 1. The origin of this software must not be misrepresented; you must not -# claim that you wrote the original software. If you use this software -# in a product, an acknowledgment in the product documentation would be -# appreciated but is not required. -# 2. Altered source versions must be plainly marked as such, and must not be -# misrepresented as being the original software. -# 3. This notice may not be removed or altered from any source distribution. -APP_PLATFORM := android-9 -APP_PROJECT_PATH := $(call my-dir)/.. -APP_STL ?= stlport_static -APP_ABI := armeabi-v7a -APP_CPPFLAGS += -std=c++11 diff --git a/third_party/flatbuffers/android/jni/build_flatc.bat b/third_party/flatbuffers/android/jni/build_flatc.bat deleted file mode 100644 index 0b3f2ad18d8..00000000000 --- a/third_party/flatbuffers/android/jni/build_flatc.bat +++ /dev/null @@ -1,68 +0,0 @@ -@rem Copyright (c) 2013 Google, Inc. -@rem -@rem This software is provided 'as-is', without any express or implied -@rem warranty. In no event will the authors be held liable for any damages -@rem arising from the use of this software. -@rem Permission is granted to anyone to use this software for any purpose, -@rem including commercial applications, and to alter it and redistribute it -@rem freely, subject to the following restrictions: -@rem 1. The origin of this software must not be misrepresented; you must not -@rem claim that you wrote the original software. If you use this software -@rem in a product, an acknowledgment in the product documentation would be -@rem appreciated but is not required. -@rem 2. Altered source versions must be plainly marked as such, and must not be -@rem misrepresented as being the original software. -@rem 3. This notice may not be removed or altered from any source distribution. -@echo off - -setlocal enabledelayedexpansion - -set thispath=%~dp0 - -rem Path to cmake passed in by caller. -set cmake=%1 -rem Path to cmake project to build. -set cmake_project_path=%2 - -rem Newest and oldest version of Visual Studio that it's possible to select. -set visual_studio_version_max=20 -set visual_studio_version_min=8 - -rem Determine the newest version of Visual Studio installed on this machine. -set visual_studio_version= -for /L %%a in (%visual_studio_version_max%,-1,%visual_studio_version_min%) do ( - echo Searching for Visual Studio %%a >&2 - reg query HKLM\SOFTWARE\Microsoft\VisualStudio\%%a.0 /ve 1>NUL 2>NUL - if !ERRORLEVEL! EQU 0 ( - set visual_studio_version=%%a - goto found_vs - ) -) -echo Unable to determine whether Visual Studio is installed. >&2 -exit /B 1 -:found_vs - -rem Map Visual Studio version to cmake generator name. -if "%visual_studio_version%"=="8" ( - set cmake_generator=Visual Studio 8 2005 -) -if "%visual_studio_version%"=="9" ( - set cmake_generator=Visual Studio 9 2008 -) -if %visual_studio_version% GEQ 10 ( - set cmake_generator=Visual Studio %visual_studio_version% -) -rem Set visual studio version variable for msbuild. -set VisualStudioVersion=%visual_studio_version%.0 - -rem Generate Visual Studio solution. -echo Generating solution for %cmake_generator%. >&2 -cd "%cmake_project_path%" -%cmake% -G"%cmake_generator%" -if %ERRORLEVEL% NEQ 0 ( - exit /B %ERRORLEVEL% -) - -rem Build flatc -python %thispath%\msbuild.py flatc.vcxproj -if ERRORLEVEL 1 exit /B 1 diff --git a/third_party/flatbuffers/android/jni/include.mk b/third_party/flatbuffers/android/jni/include.mk deleted file mode 100644 index b53e257398b..00000000000 --- a/third_party/flatbuffers/android/jni/include.mk +++ /dev/null @@ -1,237 +0,0 @@ -# Copyright 2014 Google Inc. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# This file contains utility functions for Android projects using Flatbuffers. -# To use this file, include it in your project's Android.mk by calling near the -# top of your android makefile like so: -# -# include $(FLATBUFFERS_DIR)/android/jni/include.mk -# -# You will also need to import the flatbuffers module using the standard -# import-module function. -# -# The main functionality this file provides are the following functions: -# flatbuffers_fbs_to_h: Converts flatbuffer schema paths to header paths. -# flatbuffers_header_build_rule: -# Creates a build rule for a schema's generated header. This build rule -# has a dependency on the flatc compiler which will be built if necessary. -# flatbuffers_header_build_rules: -# Creates build rules for generated headers for each schema listed and sets -# up depenedendies. -# -# More information and example usage can be found in the comments preceeding -# each function. - -# Targets to build the Flatbuffers compiler as well as some utility definitions -ifeq (,$(FLATBUFFERS_INCLUDE_MK_)) -FLATBUFFERS_INCLUDE_MK_ := 1 - -# Portable version of $(realpath) that omits drive letters on Windows. -realpath-portable = $(join $(filter %:,$(subst :,: ,$1)),\ - $(realpath $(filter-out %:,$(subst :,: ,$1)))) - -PROJECT_OS := $(OS) -ifeq (,$(OS)) -PROJECT_OS := $(shell uname -s) -else -ifneq ($(findstring Windows,$(PROJECT_OS)),) -PROJECT_OS := Windows -endif -endif - -# The following block generates build rules which result in headers being -# rebuilt from flatbuffers schemas. - -FLATBUFFERS_CMAKELISTS_DIR := \ - $(call realpath-portable,$(dir $(lastword $(MAKEFILE_LIST)))/../..) - -# Directory that contains the FlatBuffers compiler. -ifeq (Windows,$(PROJECT_OS)) -FLATBUFFERS_FLATC_PATH?=$(FLATBUFFERS_CMAKELISTS_DIR) -FLATBUFFERS_FLATC := $(lastword \ - $(wildcard $(FLATBUFFERS_FLATC_PATH)/*/flatc.exe) \ - $(wildcard $(FLATBUFFERS_FLATC_PATH)/flatc.exe)) -endif -ifeq (Linux,$(PROJECT_OS)) -FLATBUFFERS_FLATC_PATH?=$(FLATBUFFERS_CMAKELISTS_DIR) -FLATBUFFERS_FLATC := $(FLATBUFFERS_FLATC_PATH)/flatc -endif -ifeq (Darwin,$(PROJECT_OS)) -FLATBUFFERS_FLATC_PATH?=$(FLATBUFFERS_CMAKELISTS_DIR) -FLATBUFFERS_FLATC := $(lastword \ - $(wildcard $(FLATBUFFERS_FLATC_PATH)/*/flatc) \ - $(wildcard $(FLATBUFFERS_FLATC_PATH)/flatc)) -endif - -FLATBUFFERS_FLATC_ARGS?= - -# Search for cmake. -CMAKE_ROOT := \ - $(call realpath-portable,$(LOCAL_PATH)/../../../../../../prebuilts/cmake) -ifeq (,$(CMAKE)) -ifeq (Linux,$(PROJECT_OS)) -CMAKE := $(wildcard $(CMAKE_ROOT)/linux-x86/current/bin/cmake*) -endif -ifeq (Darwin,$(PROJECT_OS)) -CMAKE := \ - $(wildcard $(CMAKE_ROOT)/darwin-x86_64/current/*.app/Contents/bin/cmake) -endif -ifeq (Windows,$(PROJECT_OS)) -CMAKE := $(wildcard $(CMAKE_ROOT)/windows/current/bin/cmake*) -endif -endif -ifeq (,$(CMAKE)) -CMAKE := cmake -endif - -# Windows friendly portable local path. -# GNU-make doesn't like : in paths, must use relative paths on Windows. -ifeq (Windows,$(PROJECT_OS)) -PORTABLE_LOCAL_PATH = -else -PORTABLE_LOCAL_PATH = $(LOCAL_PATH)/ -endif - -# Generate a host build rule for the flatbuffers compiler. -ifeq (Windows,$(PROJECT_OS)) -define build_flatc_recipe - $(FLATBUFFERS_CMAKELISTS_DIR)\android\jni\build_flatc.bat \ - $(CMAKE) $(FLATBUFFERS_CMAKELISTS_DIR) -endef -endif -ifeq (Linux,$(PROJECT_OS)) -define build_flatc_recipe - +cd $(FLATBUFFERS_CMAKELISTS_DIR) && \ - $(CMAKE) . && \ - $(MAKE) flatc -endef -endif -ifeq (Darwin,$(PROJECT_OS)) -define build_flatc_recipe - cd $(FLATBUFFERS_CMAKELISTS_DIR) && "$(CMAKE)" -GXcode . && \ - xcodebuild -target flatc -endef -endif -ifeq (,$(build_flatc_recipe)) -ifeq (,$(FLATBUFFERS_FLATC)) -$(error flatc binary not found!) -endif -endif - -# Generate a build rule for flatc. -ifeq ($(strip $(FLATBUFFERS_FLATC)),) -flatc_target := build_flatc -.PHONY: $(flatc_target) -FLATBUFFERS_FLATC := \ - python $(FLATBUFFERS_CMAKELISTS_DIR)/android/jni/run_flatc.py \ - $(FLATBUFFERS_CMAKELISTS_DIR) -else -flatc_target := $(FLATBUFFERS_FLATC) -endif -$(flatc_target): - $(call build_flatc_recipe) - -# $(flatbuffers_fbs_to_h schema_dir,output_dir,path) -# -# Convert the specified schema path to a Flatbuffers generated header path. -# For example: -# -# $(call flatbuffers_fbs_to_h,$(MY_PROJ_DIR)/schemas,\ -# $(MY_PROJ_DIR)/gen/include,$(MY_PROJ_DIR)/schemas/example.fbs) -# -# This will convert the file path `$(MY_PROJ_DIR)/schemas/example.fbs)` to -# `$(MY_PROJ_DIR)/gen/include/example_generated.h` -define flatbuffers_fbs_to_h -$(subst $(1),$(2),$(patsubst %.fbs,%_generated.h,$(3))) -endef - -# $(flatbuffers_header_build_rule schema_file,schema_dir,output_dir,\ -# schema_include_dirs) -# -# Generate a build rule that will convert a Flatbuffers schema to a generated -# header derived from the schema filename using flatbuffers_fbs_to_h. For -# example: -# -# $(call flatbuffers_header_build_rule,$(MY_PROJ_DIR)/schemas/example.fbs,\ -# $(MY_PROJ_DIR)/schemas,$(MY_PROJ_DIR)/gen/include) -# -# The final argument, schema_include_dirs, is optional and is only needed when -# the schema files depend on other schema files outside their own directory. -define flatbuffers_header_build_rule -$(eval \ - $(call flatbuffers_fbs_to_h,$(2),$(3),$(1)): $(1) $(flatc_target) - $(call host-echo-build-step,generic,Generate) \ - $(subst $(LOCAL_PATH)/,,$(call flatbuffers_fbs_to_h,$(2),$(3),$(1))) - $(hide) $$(FLATBUFFERS_FLATC) $(FLATBUFFERS_FLATC_ARGS) \ - $(foreach include,$(4),-I $(include)) -o $$(dir $$@) -c $$<) -endef - -# TODO: Remove when the LOCAL_PATH expansion bug in the NDK is fixed. -# Override the default behavior of local-source-file-path to workaround -# a bug which prevents the build of deeply nested projects when NDK_OUT is -# set. -local-source-file-path=\ -$(if $(call host-path-is-absolute,$1),$1,$(call \ - realpath-portable,$(LOCAL_PATH)/$1)) - - -# $(flatbuffers_header_build_rules schema_files,schema_dir,output_dir,\ -# schema_include_dirs,src_files,[build_target],[dependencies])) -# -# $(1) schema_files: Space separated list of flatbuffer schema files. -# $(2) schema_dir: Directory containing the flatbuffer schemas. -# $(3) output_dir: Where to place the generated files. -# $(4) schema_include_dirs: Directories to include when generating schemas. -# $(5) src_files: Files that should depend upon the headers generated from the -# flatbuffer schemas. -# $(6) build_target: Name of a build target that depends upon all generated -# headers. -# $(7) dependencies: Space seperated list of additional build targets src_files -# should depend upon. -# -# Use this in your own Android.mk file to generate build rules that will -# generate header files for your flatbuffer schemas as well as automatically -# set your source files to be dependent on the generated headers. For example: -# -# $(call flatbuffers_header_build_rules,$(MY_PROJ_SCHEMA_FILES),\ -# $(MY_PROJ_SCHEMA_DIR),$(MY_PROJ_GENERATED_OUTPUT_DIR), -# $(MY_PROJ_SCHEMA_INCLUDE_DIRS),$(LOCAL_SRC_FILES)) -# -# NOTE: Due problesm with path processing in ndk-build when presented with -# deeply nested projects must redefine LOCAL_PATH after include this makefile -# using: -# -# LOCAL_PATH := $(call realpath-portable,$(LOCAL_PATH)) -# -define flatbuffers_header_build_rules -$(foreach schema,$(1),\ - $(call flatbuffers_header_build_rule,\ - $(schema),$(strip $(2)),$(strip $(3)),$(strip $(4))))\ -$(foreach src,$(strip $(5)),\ - $(eval $(call local-source-file-path,$(src)): \ - $(foreach schema,$(strip $(1)),\ - $(call flatbuffers_fbs_to_h,$(strip $(2)),$(strip $(3)),$(schema)))))\ -$(if $(6),\ - $(foreach schema,$(strip $(1)),\ - $(eval $(6): \ - $(call flatbuffers_fbs_to_h,$(strip $(2)),$(strip $(3)),$(schema)))),)\ -$(if $(7),\ - $(foreach src,$(strip $(5)),\ - $(eval $(call local-source-file-path,$(src)): $(strip $(7)))),)\ -$(if $(7),\ - $(foreach dependency,$(strip $(7)),\ - $(eval $(6): $(dependency))),) -endef - -endif # FLATBUFFERS_INCLUDE_MK_ diff --git a/third_party/flatbuffers/android/jni/msbuild.py b/third_party/flatbuffers/android/jni/msbuild.py deleted file mode 100644 index 5f92d70f405..00000000000 --- a/third_party/flatbuffers/android/jni/msbuild.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# 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. - -"""Simple script that locates the newest MSBuild in one of several locations. - -This script will find the highest version number of MSBuild and run it, -passing its arguments through to MSBuild. -""" - -import glob -import os -import re -import string -import subprocess -import sys - -SYSTEMROOT = os.getenv("SYSTEMROOT", "c:\\windows") -PROGRAM_FILES = os.getenv("ProgramFiles", "c:\\Program Files") -PROGRAM_FILES_X86 = os.getenv("ProgramFiles(x86)", "c:\\Program Files (x86)") - -SEARCH_FOLDERS = [ PROGRAM_FILES + "\\MSBuild\\*\\Bin\\MSBuild.exe", - PROGRAM_FILES_X86 + "\\MSBuild\\*\\Bin\\MSBuild.exe", - SYSTEMROOT + "\\Microsoft.NET\Framework\\*\\MSBuild.exe" ] - -def compare_version(a, b): - """Compare two version number strings of the form W.X.Y.Z. - - The numbers are compared most-significant to least-significant. - For example, 12.345.67.89 > 2.987.88.99. - - Args: - a: First version number string to compare - b: Second version number string to compare - - Returns: - 0 if the numbers are identical, a positive number if 'a' is larger, and - a negative number if 'b' is larger. - """ - aa = string.split(a, ".") - bb = string.split(b, ".") - for i in range(0, 4): - if aa[i] != bb[i]: - return cmp(int(aa[i]), int(bb[i])) - return 0 - -def main(): - msbuilds = [] - - for folder in SEARCH_FOLDERS: - for file in glob.glob(folder): - p = subprocess.Popen([file, "/version"], stdout=subprocess.PIPE) - out, err = p.communicate() - match = re.search("^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$", out, re.M) - if match: - msbuilds.append({ 'ver':match.group(), 'exe':file }) - msbuilds.sort(lambda x, y: compare_version(x['ver'], y['ver']), reverse=True) - if len(msbuilds) == 0: - print "Unable to find MSBuild.\n" - return -1; - cmd = [msbuilds[0]['exe']] - cmd.extend(sys.argv[1:]) - return subprocess.call(cmd) - -if __name__ == '__main__': - sys.exit(main()) diff --git a/third_party/flatbuffers/android/jni/run_flatc.py b/third_party/flatbuffers/android/jni/run_flatc.py deleted file mode 100755 index cda13bbf821..00000000000 --- a/third_party/flatbuffers/android/jni/run_flatc.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/python -# Copyright 2015 Google Inc. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import platform -import subprocess -import sys - -EXECUTABLE_EXTENSION = '.exe' if platform.system() == 'Windows' else '' -# Paths to search for flatc relative to the current working directory. -FLATC_SEARCH_PATHS = [os.path.curdir, 'Release', 'Debug'] - -def main(): - """Script that finds and runs flatc built from source.""" - if len(sys.argv) < 2: - sys.stderr.write('Usage: run_flatc.py flatbuffers_dir [flatc_args]\n') - return 1 - cwd = os.getcwd() - flatc = '' - flatbuffers_dir = sys.argv[1] - for path in FLATC_SEARCH_PATHS: - current = os.path.join(flatbuffers_dir, path, - 'flatc' + EXECUTABLE_EXTENSION) - if os.path.exists(current): - flatc = current - break - if not flatc: - sys.stderr.write('flatc not found\n') - return 1 - command = [flatc] + sys.argv[2:] - return subprocess.call(command) - -if __name__ == '__main__': - sys.exit(main()) diff --git a/third_party/flatbuffers/android/res/values/strings.xml b/third_party/flatbuffers/android/res/values/strings.xml deleted file mode 100644 index ec752393edd..00000000000 --- a/third_party/flatbuffers/android/res/values/strings.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - FlatBufferTest - diff --git a/third_party/flatbuffers/appveyor.yml b/third_party/flatbuffers/appveyor.yml deleted file mode 100644 index 75a63c87211..00000000000 --- a/third_party/flatbuffers/appveyor.yml +++ /dev/null @@ -1,105 +0,0 @@ -branches: - only: - - master - -os: Visual Studio 2015 - -environment: - - global: - # Workaround for https://github.com/conda/conda-build/issues/636 - PYTHONIOENCODING: UTF-8 - CONDA_INSTALL_LOCN: "C:\\Miniconda35-x64" - - matrix: - - CMAKE_VS_VERSION: "10 2010" - MONSTER_EXTRA: "skip" - - - CMAKE_VS_VERSION: "12 2013" - MONSTER_EXTRA: "skip" - - - CMAKE_VS_VERSION: "14 2015" - MONSTER_EXTRA: "" - -platform: - - x86 - - x64 - -configuration: - - Debug - - Release - -before_build: - - set MONSTER_EXTRA=%MONSTER_EXTRA% - - cmake -G"Visual Studio %CMAKE_VS_VERSION%" -DFLATBUFFERS_CODE_SANITIZE=1 . - # This cuts down on a lot of noise generated by xamarin warnings. - - del "C:\Program Files (x86)\MSBuild\14.0\Microsoft.Common.targets\ImportAfter\Xamarin.Common.targets" - -build: - project: ALL_BUILD.vcxproj - verbosity: minimal - -after_build: - - python conan/appveyor/install.py - - python conan/appveyor/build.py - -install: - - set PATH=%CONDA_INSTALL_LOCN%;%CONDA_INSTALL_LOCN%\scripts;%PATH%; - - curl -sSf -o rustup-init.exe https://win.rustup.rs/ - - rustup-init.exe -y - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - rustc -V - - cargo -V - -test_script: - - call .appveyor\check-generate-code.bat -b %CONFIGURATION% - - "cd tests" - - rem "Building all code" - - generate_code.bat -b %CONFIGURATION% - - 7z a GeneratedMyGameCode.zip MyGame\ - - rem "---------------- C++ -----------------" - - "cd .." - - "%CONFIGURATION%\\flattests.exe" - - "cd tests" - - rem "---------------- Java -----------------" - - "java -version" - - "JavaTest.bat" - - rem "---------------- Rust ----------------" - - "RustTest.bat" - - rem "---------------- JS -----------------" - - "node --version" - - "..\\%CONFIGURATION%\\flatc -b -I include_test monster_test.fbs unicode_test.json" - - "node JavaScriptTest ./monster_test_generated" - - rem "-------------- Python ---------------" - - where python - - python --version - - where pip - - pip --version - - where conda - - conda --version - - rem "installing flatbuffers python library" - - pip install ../python - - rem "testing without installing Numpy" - - python py_test.py 0 0 0 - - rem "testing after installing Numpy - disabled" - # FIXME: This has a LOT of unnecessary dependencies and makes the tests fail - # with timeouts. - # - conda install --yes numpy - # - python py_test.py 0 0 0 - - rem "---------------- C# -----------------" - # Have to compile this here rather than in "build" above because AppVeyor only - # supports building one project?? - - "cd FlatBuffers.Test" - - "msbuild.exe /property:Configuration=Release;OutputPath=tempcs /verbosity:minimal FlatBuffers.Test.csproj" - - "tempcs\\FlatBuffers.Test.exe" - # Run tests with UNSAFE_BYTEBUFFER - - "msbuild.exe /property:Configuration=Release;UnsafeByteBuffer=true;OutputPath=tempcsUnsafe /verbosity:minimal FlatBuffers.Test.csproj" - - "tempcsUnsafe\\FlatBuffers.Test.exe" - # TODO: add more languages. - - "cd ..\\.." - -artifacts: - - path: $(CONFIGURATION)\flatc.exe - name: flatc.exe - - path: tests\GeneratedMyGameCode.zip - name: GeneratedMyGameCode.zip diff --git a/third_party/flatbuffers/build_defs.bzl b/third_party/flatbuffers/build_defs.bzl index a92f0ed8f14..fff235448fd 100644 --- a/third_party/flatbuffers/build_defs.bzl +++ b/third_party/flatbuffers/build_defs.bzl @@ -5,14 +5,25 @@ Rules for building C++ flatbuffers with Bazel. """ -flatc_path = "@com_github_google_flatbuffers//:flatc" +load("@rules_cc//cc:defs.bzl", "cc_library") + +TRUE_FLATC_PATH = "@com_github_google_flatbuffers//:flatc" DEFAULT_INCLUDE_PATHS = [ "./", "$(GENDIR)", "$(BINDIR)", + "$(execpath @com_github_google_flatbuffers//:flatc).runfiles/com_github_google_flatbuffers", ] +def default_include_paths(flatc_path): + return [ + "./", + "$(GENDIR)", + "$(BINDIR)", + "$(execpath %s).runfiles/com_github_google_flatbuffers" % (flatc_path), + ] + DEFAULT_FLATC_ARGS = [ "--gen-object-api", "--gen-compare", @@ -29,11 +40,18 @@ def flatbuffer_library_public( language_flag, out_prefix = "", includes = [], - include_paths = DEFAULT_INCLUDE_PATHS, + include_paths = None, flatc_args = DEFAULT_FLATC_ARGS, reflection_name = "", reflection_visibility = None, - output_to_bindir = False): + compatible_with = None, + restricted_to = None, + target_compatible_with = None, + flatc_path = "@com_github_google_flatbuffers//:flatc", + output_to_bindir = False, + tools = None, + extra_env = None, + **kwargs): """Generates code files for reading/writing the given flatbuffers in the requested language using the public compiler. Args: @@ -50,14 +68,32 @@ def flatbuffer_library_public( reflection binaries for the schemas. reflection_visibility: The visibility of the generated reflection Fileset. output_to_bindir: Passed to genrule for output to bin directory. + compatible_with: Optional, The list of environments this rule can be + built for, in addition to default-supported environments. + restricted_to: Optional, The list of environments this rule can be built + for, instead of default-supported environments. + target_compatible_with: Optional, The list of target platform constraints + to use. + flatc_path: Bazel target corresponding to the flatc compiler to use. + output_to_bindir: Passed to genrule for output to bin directory. + tools: Optional, passed to genrule for list of tools to make available + during the action. + extra_env: Optional, must be a string of "VAR1=VAL1 VAR2=VAL2". These get + set as environment variables that "flatc_path" sees. + **kwargs: Passed to the underlying genrule. This rule creates a filegroup(name) with all generated source files, and optionally a Fileset([reflection_name]) with all generated reflection binaries. """ + reflection_include_paths = include_paths + if include_paths == None: + include_paths = default_include_paths(flatc_path) include_paths_cmd = ["-I %s" % (s) for s in include_paths] + extra_env = extra_env or "" + # '$(@D)' when given a single source target will give the appropriate # directory. Appending 'out_prefix' is only necessary when given a build # target with multiple sources. @@ -67,7 +103,7 @@ def flatbuffer_library_public( genrule_cmd = " ".join([ "SRCS=($(SRCS));", "for f in $${SRCS[@]:0:%s}; do" % len(srcs), - "$(location %s)" % (flatc_path), + "OUTPUT_FILE=\"$(OUTS)\" %s $(location %s)" % (extra_env, flatc_path), " ".join(include_paths_cmd), " ".join(flatc_args), language_flag, @@ -80,18 +116,25 @@ def flatbuffer_library_public( srcs = srcs + includes, outs = outs, output_to_bindir = output_to_bindir, - tools = [flatc_path], + tools = (tools or []) + [flatc_path], cmd = genrule_cmd, + compatible_with = compatible_with, + target_compatible_with = target_compatible_with, + restricted_to = restricted_to, message = "Generating flatbuffer files for %s:" % (name), + **kwargs ) if reflection_name: + if reflection_include_paths == None: + reflection_include_paths = default_include_paths(TRUE_FLATC_PATH) + reflection_include_paths_cmd = ["-I %s" % (s) for s in reflection_include_paths] reflection_genrule_cmd = " ".join([ "SRCS=($(SRCS));", "for f in $${SRCS[@]:0:%s}; do" % len(srcs), - "$(location %s)" % (flatc_path), + "$(location %s)" % (TRUE_FLATC_PATH), "-b --schema", " ".join(flatc_args), - " ".join(include_paths_cmd), + " ".join(reflection_include_paths_cmd), language_flag, output_directory, "$$f;", @@ -106,31 +149,40 @@ def flatbuffer_library_public( srcs = srcs + includes, outs = reflection_outs, output_to_bindir = output_to_bindir, - tools = [flatc_path], + tools = [TRUE_FLATC_PATH], + compatible_with = compatible_with, + restricted_to = restricted_to, + target_compatible_with = target_compatible_with, cmd = reflection_genrule_cmd, message = "Generating flatbuffer reflection binary for %s:" % (name), + visibility = reflection_visibility, ) - native.Fileset( - name = reflection_name, - out = "%s_out" % reflection_name, - entries = [ - native.FilesetEntry(files = reflection_outs), - ], + native.filegroup( + name = "%s_out" % reflection_name, + srcs = reflection_outs, visibility = reflection_visibility, + compatible_with = compatible_with, + restricted_to = restricted_to, ) def flatbuffer_cc_library( name, srcs, srcs_filegroup_name = "", + outs = [], out_prefix = "", + deps = [], includes = [], - include_paths = DEFAULT_INCLUDE_PATHS, + include_paths = None, + cc_include_paths = [], flatc_args = DEFAULT_FLATC_ARGS, visibility = None, + compatible_with = None, + restricted_to = None, + target_compatible_with = None, srcs_filegroup_visibility = None, gen_reflections = False): - '''A cc_library with the generated reader/writers for the given flatbuffer definitions. + """A cc_library with the generated reader/writers for the given flatbuffer definitions. Args: name: Rule name. @@ -138,11 +190,15 @@ def flatbuffer_cc_library( srcs_filegroup_name: Name of the output filegroup that holds srcs. Pass this filegroup into the `includes` parameter of any other flatbuffer_cc_library that depends on this one's schemas. + outs: Additional outputs expected to be generated by flatc. out_prefix: Prepend this path to the front of all generated files. Usually is a directory name. + deps: Optional, list of other flatbuffer_cc_library's to depend on. Cannot be specified + alongside includes. includes: Optional, list of filegroups of schemas that the srcs depend on. - ** SEE REMARKS BELOW ** + Use of this is discouraged, and may be deprecated. include_paths: Optional, list of paths the includes files can be found in. + cc_include_paths: Optional, list of paths to add to the cc_library includes attribute. flatc_args: Optional list of additional arguments to pass to flatc (e.g. --gen-mutable). visibility: The visibility of the generated cc_library. By default, use the @@ -151,6 +207,12 @@ def flatbuffer_cc_library( By default, use the value of the visibility parameter above. gen_reflections: Optional, if true this will generate the flatbuffer reflection binaries for the schemas. + compatible_with: Optional, The list of environments this rule can be built + for, in addition to default-supported environments. + restricted_to: Optional, The list of environments this rule can be built + for, instead of default-supported environments. + target_compatible_with: Optional, The list of target platform constraints + to use. This produces: filegroup([name]_srcs): all generated .h files. @@ -159,57 +221,36 @@ def flatbuffer_cc_library( parameter, if they depend on the schemas in this library. Fileset([name]_reflection): (Optional) all generated reflection binaries. cc_library([name]): library with sources and flatbuffers deps. - - Remarks: - ** Because the genrule used to call flatc does not have any trivial way of - computing the output list of files transitively generated by includes and - --gen-includes (the default) being defined for flatc, the --gen-includes - flag will not work as expected. The way around this is to add a dependency - to the flatbuffer_cc_library defined alongside the flatc included Fileset. - For example you might define: - - flatbuffer_cc_library( - name = "my_fbs", - srcs = [ "schemas/foo.fbs" ], - includes = [ "//third_party/bazz:bazz_fbs_includes" ], - ) - - In which foo.fbs includes a few files from the Fileset defined at - //third_party/bazz:bazz_fbs_includes. When compiling the library that - includes foo_generated.h, and therefore has my_fbs as a dependency, it - will fail to find any of the bazz *_generated.h files unless you also - add bazz's flatbuffer_cc_library to your own dependency list, e.g.: - - cc_library( - name = "my_lib", - deps = [ - ":my_fbs", - "//third_party/bazz:bazz_fbs" - ], - ) - - Happy dependent Flatbuffering! - ''' + """ output_headers = [ - (out_prefix + "%s_generated.h") % (s.replace(".fbs", "").split("/")[-1]) + (out_prefix + "%s_generated.h") % (s.replace(".fbs", "").split("/")[-1].split(":")[-1]) for s in srcs ] + if deps and includes: + # There is no inherent reason we couldn't support both, but this discourages + # use of includes without good reason. + fail("Cannot specify both deps and include in flatbuffer_cc_library.") + if deps: + includes = [d + "_includes" for d in deps] reflection_name = "%s_reflection" % name if gen_reflections else "" srcs_lib = "%s_srcs" % (name) flatbuffer_library_public( name = srcs_lib, srcs = srcs, - outs = output_headers, + outs = outs + output_headers, language_flag = "-c", out_prefix = out_prefix, includes = includes, include_paths = include_paths, flatc_args = flatc_args, + compatible_with = compatible_with, + restricted_to = restricted_to, + target_compatible_with = target_compatible_with, reflection_name = reflection_name, reflection_visibility = visibility, ) - native.cc_library( + cc_library( name = name, hdrs = [ ":" + srcs_lib, @@ -222,8 +263,12 @@ def flatbuffer_cc_library( ], deps = [ "@com_github_google_flatbuffers//:runtime_cc", - ], - includes = [], + "@com_github_google_flatbuffers//:flatbuffers", + ] + deps, + includes = cc_include_paths, + compatible_with = compatible_with, + restricted_to = restricted_to, + target_compatible_with = target_compatible_with, linkstatic = 1, visibility = visibility, ) @@ -232,6 +277,8 @@ def flatbuffer_cc_library( # Flatbuffer set. native.filegroup( name = srcs_filegroup_name if srcs_filegroup_name else "%s_includes" % (name), - srcs = srcs, + srcs = srcs + includes, + compatible_with = compatible_with, + restricted_to = restricted_to, visibility = srcs_filegroup_visibility if srcs_filegroup_visibility != None else visibility, ) diff --git a/third_party/flatbuffers/conan/CMakeLists.txt b/third_party/flatbuffers/conan/CMakeLists.txt index d32a013271f..65f902876e1 100644 --- a/third_party/flatbuffers/conan/CMakeLists.txt +++ b/third_party/flatbuffers/conan/CMakeLists.txt @@ -5,8 +5,8 @@ message(STATUS "Conan FlatBuffers Wrapper") include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup() -if (WIN32 AND MSVC AND FLATBUFFERS_BUILD_SHAREDLIB) +if (WIN32 AND MSVC_LIKE AND FLATBUFFERS_BUILD_SHAREDLIB) set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) -endif(WIN32 AND MSVC AND FLATBUFFERS_BUILD_SHAREDLIB) +endif(WIN32 AND MSVC_LIKE AND FLATBUFFERS_BUILD_SHAREDLIB) include(${CMAKE_SOURCE_DIR}/CMakeListsOriginal.txt) diff --git a/third_party/flatbuffers/conan/appveyor/build.py b/third_party/flatbuffers/conan/appveyor/build.py deleted file mode 100644 index 9bac46dbe7b..00000000000 --- a/third_party/flatbuffers/conan/appveyor/build.py +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -import os - -if os.getenv("APPVEYOR_REPO_TAG") != "true": - print("Skip build step. It's not TAG") -else: - os.system("python conan/build.py") diff --git a/third_party/flatbuffers/conan/appveyor/install.py b/third_party/flatbuffers/conan/appveyor/install.py deleted file mode 100644 index 962c7da6b7d..00000000000 --- a/third_party/flatbuffers/conan/appveyor/install.py +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -import os - -if os.getenv("APPVEYOR_REPO_TAG") != "true": - print("Skip step. It's not TAG") -else: - os.system("pip install conan conan-package-tools") diff --git a/third_party/flatbuffers/conan/build.py b/third_party/flatbuffers/conan/build.py index 55456311bad..62a37990794 100644 --- a/third_party/flatbuffers/conan/build.py +++ b/third_party/flatbuffers/conan/build.py @@ -6,16 +6,6 @@ from cpt.packager import ConanMultiPackager -def set_appveyor_environment(): - if os.getenv("APPVEYOR") is not None: - compiler_version = os.getenv("CMAKE_VS_VERSION").split(" ")[0].replace('"', '') - os.environ["CONAN_VISUAL_VERSIONS"] = compiler_version - os.environ["CONAN_STABLE_BRANCH_PATTERN"] = "master" - ci_platform = os.getenv("Platform").replace('"', '') - ci_platform = "x86" if ci_platform == "x86" else "x86_64" - os.environ["CONAN_ARCHS"] = ci_platform - os.environ["CONAN_BUILD_TYPES"] = os.getenv("Configuration").replace('"', '') - def get_branch(): try: @@ -31,14 +21,6 @@ def get_branch(): def get_version(): version = get_branch() - if os.getenv("TRAVIS", False): - version = os.getenv("TRAVIS_BRANCH") - - if os.getenv("APPVEYOR", False): - version = os.getenv("APPVEYOR_REPO_BRANCH") - if os.getenv("APPVEYOR_REPO_TAG") == "true": - version = os.getenv("APPVEYOR_REPO_TAG_NAME") - match = re.search(r"v(\d+\.\d+\.\d+.*)", version) if match: return match.group(1) @@ -56,7 +38,6 @@ def get_reference(username): stable_branch_pattern = os.getenv("CONAN_STABLE_BRANCH_PATTERN", r"v\d+\.\d+\.\d+.*") test_folder = os.getenv("CPT_TEST_FOLDER", os.path.join("conan", "test_package")) upload_only_when_stable = os.getenv("CONAN_UPLOAD_ONLY_WHEN_STABLE", True) - set_appveyor_environment() builder = ConanMultiPackager(reference=get_reference(username), username=username, diff --git a/third_party/flatbuffers/conan/travis/build.sh b/third_party/flatbuffers/conan/travis/build.sh deleted file mode 100755 index 069ced202f8..00000000000 --- a/third_party/flatbuffers/conan/travis/build.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash - -set -e -set -x - -if [[ "$(uname -s)" == 'Darwin' ]]; then - if which pyenv > /dev/null; then - eval "$(pyenv init -)" - fi - pyenv activate conan -fi - -conan user -python conan/build.py diff --git a/third_party/flatbuffers/conan/travis/install.sh b/third_party/flatbuffers/conan/travis/install.sh deleted file mode 100755 index f4208d82643..00000000000 --- a/third_party/flatbuffers/conan/travis/install.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/bash - -set -e -set -x - -if [[ "$(uname -s)" == 'Darwin' ]]; then - brew update || brew update - brew outdated pyenv || brew upgrade pyenv - brew install pyenv-virtualenv - brew install cmake || true - - if which pyenv > /dev/null; then - eval "$(pyenv init -)" - fi - - pyenv install 2.7.10 - pyenv virtualenv 2.7.10 conan - pyenv rehash - pyenv activate conan -fi - -pip install -U conan_package_tools conan diff --git a/third_party/flatbuffers/conanfile.py b/third_party/flatbuffers/conanfile.py index bdd832c36b8..9d622908acd 100644 --- a/third_party/flatbuffers/conanfile.py +++ b/third_party/flatbuffers/conanfile.py @@ -20,7 +20,7 @@ class FlatbuffersConan(ConanFile): options = {"shared": [True, False], "fPIC": [True, False]} default_options = {"shared": False, "fPIC": True} generators = "cmake" - exports = "LICENSE.txt" + exports = "LICENSE" exports_sources = ["CMake/*", "include/*", "src/*", "grpc/*", "CMakeLists.txt", "conan/CMakeLists.txt"] def source(self): @@ -56,7 +56,7 @@ def package(self): """ cmake = self.configure_cmake() cmake.install() - self.copy(pattern="LICENSE.txt", dst="licenses") + self.copy(pattern="LICENSE", dst="licenses") self.copy(pattern="FindFlatBuffers.cmake", dst=os.path.join("lib", "cmake", "flatbuffers"), src="CMake") self.copy(pattern="flathash*", dst="bin", src="bin") self.copy(pattern="flatc*", dst="bin", src="bin") diff --git a/third_party/flatbuffers/dart/CHANGELOG.md b/third_party/flatbuffers/dart/CHANGELOG.md deleted file mode 100644 index 5e2d2deea50..00000000000 --- a/third_party/flatbuffers/dart/CHANGELOG.md +++ /dev/null @@ -1,14 +0,0 @@ -# CHANGELOG - -## 1.9.2 - -- Ensure `_writeString` adds enough padding to null terminate strings. - -## 1.9.1 - -- Changed constant identifiers to be compatible with Dart 2.x -- No longer supports Dart 1.x - -## 1.9.0 - -- Initial release, supports Dart 1.x and many dev versions of Dart 2.x \ No newline at end of file diff --git a/third_party/flatbuffers/dart/README.md b/third_party/flatbuffers/dart/README.md deleted file mode 100644 index 11bc0c48f1b..00000000000 --- a/third_party/flatbuffers/dart/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# FlatBuffers for Dart - -This package is used to read and write FlatBuffer files in Dart. - -Most consumers will want to use the [`flatc`](https://github.com/google/flatbuffers) -compiler to generate Dart code from a FlatBuffers IDL schema. For example, the -`monster_my_game.sample_generated.dart` was generated with `flatc` from -`monster.fbs` in the example folder. The generated classes can be used to read -or write binary files that are interoperable with other languages and platforms -supported by FlatBuffers, as illustrated in the `example.dart` in the -examples folder. - -Additional documentation and examples are available [at the FlatBuffers site](https://google.github.io/flatbuffers/index.html) \ No newline at end of file diff --git a/third_party/flatbuffers/dart/example/example.dart b/third_party/flatbuffers/dart/example/example.dart deleted file mode 100644 index d95bb31f74e..00000000000 --- a/third_party/flatbuffers/dart/example/example.dart +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright 2018 Dan Field. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import 'package:flat_buffers/flat_buffers.dart' as fb; -import './monster_my_game.sample_generated.dart' as myGame; - -// Example how to use FlatBuffers to create and read binary buffers. - -void main() { - builderTest(); - objectBuilderTest(); -} - -void builderTest() { - final builder = new fb.Builder(initialSize: 1024); - final int weaponOneName = builder.writeString("Sword"); - final int weaponOneDamage = 3; - - final int weaponTwoName = builder.writeString("Axe"); - final int weaponTwoDamage = 5; - - final swordBuilder = new myGame.WeaponBuilder(builder) - ..begin() - ..addNameOffset(weaponOneName) - ..addDamage(weaponOneDamage); - final int sword = swordBuilder.finish(); - - final axeBuilder = new myGame.WeaponBuilder(builder) - ..begin() - ..addNameOffset(weaponTwoName) - ..addDamage(weaponTwoDamage); - final int axe = axeBuilder.finish(); - - // Serialize a name for our monster, called "Orc". - final int name = builder.writeString('Orc'); - - // Create a list representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - final List treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - final inventory = builder.writeListUint8(treasure); - final weapons = builder.writeList([sword, axe]); - - // Struct builders are very easy to reuse. - final vec3Builder = new myGame.Vec3Builder(builder); - - vec3Builder.finish(4.0, 5.0, 6.0); - vec3Builder.finish(1.0, 2.0, 3.0); - // Set his hit points to 300 and his mana to 150. - final int hp = 300; - final int mana = 150; - - final monster = new myGame.MonsterBuilder(builder) - ..begin() - ..addNameOffset(name) - ..addInventoryOffset(inventory) - ..addWeaponsOffset(weapons) - ..addEquippedType(myGame.EquipmentTypeId.Weapon) - ..addEquippedOffset(axe) - ..addHp(hp) - ..addMana(mana) - ..addPos(vec3Builder.finish(1.0, 2.0, 3.0)) - ..addColor(myGame.Color.Red); - - final int monsteroff = monster.finish(); - final buffer = builder.finish(monsteroff); - if (verify(buffer)) { - print( - "The FlatBuffer was successfully created with a builder and verified!"); - } -} - -void objectBuilderTest() { - // Create the builder here so we can use it for both weapons and equipped - // the actual data will only be written to the buffer once. - var axe = new myGame.WeaponObjectBuilder(name: 'Axe', damage: 5); - - var monsterBuilder = new myGame.MonsterObjectBuilder( - pos: new myGame.Vec3ObjectBuilder(x: 1.0, y: 2.0, z: 3.0), - mana: 150, - hp: 300, - name: 'Orc', - inventory: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], - color: myGame.Color.Red, - weapons: [new myGame.WeaponObjectBuilder(name: 'Sword', damage: 3), axe], - equippedType: myGame.EquipmentTypeId.Weapon, - equipped: axe, - ); - - var buffer = monsterBuilder.toBytes(); - - // We now have a FlatBuffer we can store on disk or send over a network. - - // ** file/network code goes here :) ** - - // Instead, we're going to access it right away (as if we just received it). - if (verify(buffer)) { - print( - "The FlatBuffer was successfully created with an object builder and verified!"); - } -} - -bool verify(List buffer) { - // Get access to the root: - var monster = new myGame.Monster(buffer); - - // Get and test some scalar types from the FlatBuffer. - assert(monster.hp == 80); - assert(monster.mana == 150); // default - assert(monster.name == "MyMonster"); - - // Get and test a field of the FlatBuffer's `struct`. - var pos = monster.pos; - assert(pos != null); - assert(pos.z == 3.0); - - // Get a test an element from the `inventory` FlatBuffer's `vector`. - var inv = monster.inventory; - assert(inv != null); - assert(inv.length == 10); - assert(inv[9] == 9); - - // Get and test the `weapons` FlatBuffers's `vector`. - var expected_weapon_names = ["Sword", "Axe"]; - var expected_weapon_damages = [3, 5]; - var weps = monster.weapons; - for (int i = 0; i < weps.length; i++) { - assert(weps[i].name == expected_weapon_names[i]); - assert(weps[i].damage == expected_weapon_damages[i]); - } - - // Get and test the `Equipment` union (`equipped` field). - assert(monster.equippedType.value == myGame.EquipmentTypeId.Weapon.value); - assert(monster.equippedType == myGame.EquipmentTypeId.Weapon); - - assert(monster.equipped is myGame.Weapon); - var equipped = monster.equipped as myGame.Weapon; - assert(equipped.name == "Axe"); - assert(equipped.damage == 5); - - print(monster); - return true; -} diff --git a/third_party/flatbuffers/dart/example/monster_my_game.sample_generated.dart b/third_party/flatbuffers/dart/example/monster_my_game.sample_generated.dart deleted file mode 100644 index 2c7c10d2cda..00000000000 --- a/third_party/flatbuffers/dart/example/monster_my_game.sample_generated.dart +++ /dev/null @@ -1,440 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// ignore_for_file: unused_import, non_constant_identifier_names - -library my_game.sample; - -import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; - - -class Color { - final int value; - const Color._(this.value); - - factory Color.fromValue(int value) { - if (value == null) return null; - if (!values.containsKey(value)) { - throw new StateError('Invalid value $value for bit flag enum Color'); - } - return values[value]; - } - - static const int minValue = 0; - static const int maxValue = 2; - static bool containsValue(int value) => values.containsKey(value); - - static const Color Red = const Color._(0); - static const Color Green = const Color._(1); - static const Color Blue = const Color._(2); - static get values => {0: Red,1: Green,2: Blue,}; - - static const fb.Reader reader = const _ColorReader(); - - @override - String toString() { - return 'Color{value: $value}'; - } -} - -class _ColorReader extends fb.Reader { - const _ColorReader(); - - @override - int get size => 1; - - @override - Color read(fb.BufferContext bc, int offset) => - new Color.fromValue(const fb.Int8Reader().read(bc, offset)); -} - -class EquipmentTypeId { - final int value; - const EquipmentTypeId._(this.value); - - factory EquipmentTypeId.fromValue(int value) { - if (value == null) return null; - if (!values.containsKey(value)) { - throw new StateError('Invalid value $value for bit flag enum EquipmentTypeId'); - } - return values[value]; - } - - static const int minValue = 0; - static const int maxValue = 1; - static bool containsValue(int value) => values.containsKey(value); - - static const EquipmentTypeId NONE = const EquipmentTypeId._(0); - static const EquipmentTypeId Weapon = const EquipmentTypeId._(1); - static get values => {0: NONE,1: Weapon,}; - - static const fb.Reader reader = const _EquipmentTypeIdReader(); - - @override - String toString() { - return 'EquipmentTypeId{value: $value}'; - } -} - -class _EquipmentTypeIdReader extends fb.Reader { - const _EquipmentTypeIdReader(); - - @override - int get size => 1; - - @override - EquipmentTypeId read(fb.BufferContext bc, int offset) => - new EquipmentTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); -} - -class Vec3 { - Vec3._(this._bc, this._bcOffset); - - static const fb.Reader reader = const _Vec3Reader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - double get x => const fb.Float32Reader().read(_bc, _bcOffset + 0); - double get y => const fb.Float32Reader().read(_bc, _bcOffset + 4); - double get z => const fb.Float32Reader().read(_bc, _bcOffset + 8); - - @override - String toString() { - return 'Vec3{x: $x, y: $y, z: $z}'; - } -} - -class _Vec3Reader extends fb.StructReader { - const _Vec3Reader(); - - @override - int get size => 12; - - @override - Vec3 createObject(fb.BufferContext bc, int offset) => - new Vec3._(bc, offset); -} - -class Vec3Builder { - Vec3Builder(this.fbBuilder) { - assert(fbBuilder != null); - } - - final fb.Builder fbBuilder; - - int finish(double x, double y, double z) { - fbBuilder.putFloat32(z); - fbBuilder.putFloat32(y); - fbBuilder.putFloat32(x); - return fbBuilder.offset; - } - -} - -class Vec3ObjectBuilder extends fb.ObjectBuilder { - final double _x; - final double _y; - final double _z; - - Vec3ObjectBuilder({ - double x, - double y, - double z, - }) - : _x = x, - _y = y, - _z = z; - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - - fbBuilder.putFloat32(_z); - fbBuilder.putFloat32(_y); - fbBuilder.putFloat32(_x); - return fbBuilder.offset; - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} -class Monster { - Monster._(this._bc, this._bcOffset); - factory Monster(List bytes) { - fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes); - return reader.read(rootRef, 0); - } - - static const fb.Reader reader = const _MonsterReader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - Vec3 get pos => Vec3.reader.vTableGet(_bc, _bcOffset, 4, null); - int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150); - int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100); - String get name => const fb.StringReader().vTableGet(_bc, _bcOffset, 10, null); - List get inventory => const fb.ListReader(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 14, null); - Color get color => new Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2)); - List get weapons => const fb.ListReader(Weapon.reader).vTableGet(_bc, _bcOffset, 18, null); - EquipmentTypeId get equippedType => new EquipmentTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 20, null)); - dynamic get equipped { - switch (equippedType?.value) { - case 1: return Weapon.reader.vTableGet(_bc, _bcOffset, 22, null); - default: return null; - } - } - List get path => const fb.ListReader(Vec3.reader).vTableGet(_bc, _bcOffset, 24, null); - - @override - String toString() { - return 'Monster{pos: $pos, mana: $mana, hp: $hp, name: $name, inventory: $inventory, color: $color, weapons: $weapons, equippedType: $equippedType, equipped: $equipped, path: $path}'; - } -} - -class _MonsterReader extends fb.TableReader { - const _MonsterReader(); - - @override - Monster createObject(fb.BufferContext bc, int offset) => - new Monster._(bc, offset); -} - -class MonsterBuilder { - MonsterBuilder(this.fbBuilder) { - assert(fbBuilder != null); - } - - final fb.Builder fbBuilder; - - void begin() { - fbBuilder.startTable(); - } - - int addPos(int offset) { - fbBuilder.addStruct(0, offset); - return fbBuilder.offset; - } - int addMana(int mana) { - fbBuilder.addInt16(1, mana); - return fbBuilder.offset; - } - int addHp(int hp) { - fbBuilder.addInt16(2, hp); - return fbBuilder.offset; - } - int addNameOffset(int offset) { - fbBuilder.addOffset(3, offset); - return fbBuilder.offset; - } - int addInventoryOffset(int offset) { - fbBuilder.addOffset(5, offset); - return fbBuilder.offset; - } - int addColor(Color color) { - fbBuilder.addInt8(6, color?.value); - return fbBuilder.offset; - } - int addWeaponsOffset(int offset) { - fbBuilder.addOffset(7, offset); - return fbBuilder.offset; - } - int addEquippedType(EquipmentTypeId equippedType) { - fbBuilder.addUint8(8, equippedType?.value); - return fbBuilder.offset; - } - int addEquippedOffset(int offset) { - fbBuilder.addOffset(9, offset); - return fbBuilder.offset; - } - int addPathOffset(int offset) { - fbBuilder.addOffset(10, offset); - return fbBuilder.offset; - } - - int finish() { - return fbBuilder.endTable(); - } -} - -class MonsterObjectBuilder extends fb.ObjectBuilder { - final Vec3ObjectBuilder _pos; - final int _mana; - final int _hp; - final String _name; - final List _inventory; - final Color _color; - final List _weapons; - final EquipmentTypeId _equippedType; - final dynamic _equipped; - final List _path; - - MonsterObjectBuilder({ - Vec3ObjectBuilder pos, - int mana, - int hp, - String name, - List inventory, - Color color, - List weapons, - EquipmentTypeId equippedType, - dynamic equipped, - List path, - }) - : _pos = pos, - _mana = mana, - _hp = hp, - _name = name, - _inventory = inventory, - _color = color, - _weapons = weapons, - _equippedType = equippedType, - _equipped = equipped, - _path = path; - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - final int nameOffset = fbBuilder.writeString(_name); - final int inventoryOffset = _inventory?.isNotEmpty == true - ? fbBuilder.writeListUint8(_inventory) - : null; - final int weaponsOffset = _weapons?.isNotEmpty == true - ? fbBuilder.writeList(_weapons.map((b) => b.getOrCreateOffset(fbBuilder)).toList()) - : null; - final int equippedOffset = _equipped?.getOrCreateOffset(fbBuilder); - final int pathOffset = _path?.isNotEmpty == true - ? fbBuilder.writeListOfStructs(_path) - : null; - - fbBuilder.startTable(); - if (_pos != null) { - fbBuilder.addStruct(0, _pos.finish(fbBuilder)); - } - fbBuilder.addInt16(1, _mana); - fbBuilder.addInt16(2, _hp); - if (nameOffset != null) { - fbBuilder.addOffset(3, nameOffset); - } - if (inventoryOffset != null) { - fbBuilder.addOffset(5, inventoryOffset); - } - fbBuilder.addInt8(6, _color?.value); - if (weaponsOffset != null) { - fbBuilder.addOffset(7, weaponsOffset); - } - fbBuilder.addUint8(8, _equippedType?.value); - if (equippedOffset != null) { - fbBuilder.addOffset(9, equippedOffset); - } - if (pathOffset != null) { - fbBuilder.addOffset(10, pathOffset); - } - return fbBuilder.endTable(); - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} -class Weapon { - Weapon._(this._bc, this._bcOffset); - factory Weapon(List bytes) { - fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes); - return reader.read(rootRef, 0); - } - - static const fb.Reader reader = const _WeaponReader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - String get name => const fb.StringReader().vTableGet(_bc, _bcOffset, 4, null); - int get damage => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, null); - - @override - String toString() { - return 'Weapon{name: $name, damage: $damage}'; - } -} - -class _WeaponReader extends fb.TableReader { - const _WeaponReader(); - - @override - Weapon createObject(fb.BufferContext bc, int offset) => - new Weapon._(bc, offset); -} - -class WeaponBuilder { - WeaponBuilder(this.fbBuilder) { - assert(fbBuilder != null); - } - - final fb.Builder fbBuilder; - - void begin() { - fbBuilder.startTable(); - } - - int addNameOffset(int offset) { - fbBuilder.addOffset(0, offset); - return fbBuilder.offset; - } - int addDamage(int damage) { - fbBuilder.addInt16(1, damage); - return fbBuilder.offset; - } - - int finish() { - return fbBuilder.endTable(); - } -} - -class WeaponObjectBuilder extends fb.ObjectBuilder { - final String _name; - final int _damage; - - WeaponObjectBuilder({ - String name, - int damage, - }) - : _name = name, - _damage = damage; - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - final int nameOffset = fbBuilder.writeString(_name); - - fbBuilder.startTable(); - if (nameOffset != null) { - fbBuilder.addOffset(0, nameOffset); - } - fbBuilder.addInt16(1, _damage); - return fbBuilder.endTable(); - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} diff --git a/third_party/flatbuffers/dart/lib/flat_buffers.dart b/third_party/flatbuffers/dart/lib/flat_buffers.dart deleted file mode 100644 index e2512604c24..00000000000 --- a/third_party/flatbuffers/dart/lib/flat_buffers.dart +++ /dev/null @@ -1,1241 +0,0 @@ -// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:collection'; -import 'dart:convert'; -import 'dart:math'; -import 'dart:typed_data'; - -const int _sizeofUint8 = 1; -const int _sizeofUint16 = 2; -const int _sizeofUint32 = 4; -const int _sizeofUint64 = 8; -const int _sizeofInt8 = 1; -const int _sizeofInt16 = 2; -const int _sizeofInt32 = 4; -const int _sizeofInt64 = 8; -const int _sizeofFloat32 = 4; -const int _sizeofFloat64 = 8; - -/// Callback used to invoke a struct builder's finish method. -/// -/// This callback is used by other struct's `finish` methods to write the nested -/// struct's fields inline. -typedef void StructBuilder(); - -/// Buffer with data and some context about it. -class BufferContext { - final ByteData _buffer; - - factory BufferContext.fromBytes(List byteList) { - Uint8List uint8List = _asUint8List(byteList); - ByteData buf = new ByteData.view(uint8List.buffer, uint8List.offsetInBytes); - return new BufferContext._(buf); - } - - BufferContext._(this._buffer); - - int derefObject(int offset) { - return offset + _getUint32(offset); - } - - Uint8List _asUint8LIst(int offset, int length) => - _buffer.buffer.asUint8List(_buffer.offsetInBytes + offset, length); - - double _getFloat64(int offset) => - _buffer.getFloat64(offset, Endian.little); - - double _getFloat32(int offset) => - _buffer.getFloat32(offset, Endian.little); - - int _getInt64(int offset) => - _buffer.getInt64(offset, Endian.little); - - int _getInt32(int offset) => - _buffer.getInt32(offset, Endian.little); - - int _getInt16(int offset) => - _buffer.getInt16(offset, Endian.little); - - int _getInt8(int offset) => _buffer.getInt8(offset); - - int _getUint64(int offset) => - _buffer.getUint64(offset, Endian.little); - - int _getUint32(int offset) => - _buffer.getUint32(offset, Endian.little); - - int _getUint16(int offset) => - _buffer.getUint16(offset, Endian.little); - - int _getUint8(int offset) => _buffer.getUint8(offset); - - /// If the [byteList] is already a [Uint8List] return it. - /// Otherwise return a [Uint8List] copy of the [byteList]. - static Uint8List _asUint8List(List byteList) { - if (byteList is Uint8List) { - return byteList; - } else { - return new Uint8List.fromList(byteList); - } - } -} - -/// Class implemented by typed builders generated by flatc. -abstract class ObjectBuilder { - int _firstOffset; - - /// Can be used to write the data represented by this builder to the [Builder] - /// and reuse the offset created in multiple tables. - /// - /// Note that this method assumes you call it using the same [Builder] instance - /// every time. The returned offset is only good for the [Builder] used in the - /// first call to this method. - int getOrCreateOffset(Builder fbBuilder) { - _firstOffset ??= finish(fbBuilder); - return _firstOffset; - } - - /// Writes the data in this helper to the [Builder]. - int finish(Builder fbBuilder); - - /// Convenience method that will create a new [Builder], [finish]es the data, - /// and returns the buffer as a [Uint8List] of bytes. - Uint8List toBytes(); -} - -/// Class that helps building flat buffers. -class Builder { - final int initialSize; - - /// The list of existing VTable(s). - //final List<_VTable> _vTables = <_VTable>[]; - final List _vTables = []; - - ByteData _buf; - - /// The maximum alignment that has been seen so far. If [_buf] has to be - /// reallocated in the future (to insert room at its start for more bytes) the - /// reallocation will need to be a multiple of this many bytes. - int _maxAlign; - - /// The number of bytes that have been written to the buffer so far. The - /// most recently written byte is this many bytes from the end of [_buf]. - int _tail; - - /// The location of the end of the current table, measured in bytes from the - /// end of [_buf], or `null` if a table is not currently being built. - int _currentTableEndTail; - - _VTable _currentVTable; - - /// Map containing all strings that have been written so far. This allows us - /// to avoid duplicating strings. - /// - /// Allocated only if `internStrings` is set to true on the constructor. - Map _strings; - - /// Creates a new FlatBuffers Builder. - /// - /// `initialSize` is the initial array size in bytes. The [Builder] will - /// automatically grow the array if/as needed. `internStrings`, if set to - /// true, will cause [writeString] to pool strings in the buffer so that - /// identical strings will always use the same offset in tables. - Builder({this.initialSize: 1024, bool internStrings = false}) { - if (internStrings == true) { - _strings = new Map(); - } - reset(); - } - - /// Add the [field] with the given boolean [value]. The field is not added if - /// the [value] is equal to [def]. Booleans are stored as 8-bit fields with - /// `0` for `false` and `1` for `true`. - void addBool(int field, bool value, [bool def]) { - _ensureCurrentVTable(); - if (value != null && value != def) { - _prepare(_sizeofUint8, 1); - _trackField(field); - _buf.setInt8(_buf.lengthInBytes - _tail, value ? 1 : 0); - } - } - - /// Add the [field] with the given 32-bit signed integer [value]. The field is - /// not added if the [value] is equal to [def]. - void addInt32(int field, int value, [int def]) { - _ensureCurrentVTable(); - if (value != null && value != def) { - _prepare(_sizeofInt32, 1); - _trackField(field); - _setInt32AtTail(_buf, _tail, value); - } - } - - /// Add the [field] with the given 32-bit signed integer [value]. The field is - /// not added if the [value] is equal to [def]. - void addInt16(int field, int value, [int def]) { - _ensureCurrentVTable(); - if (value != null && value != def) { - _prepare(_sizeofInt16, 1); - _trackField(field); - _setInt16AtTail(_buf, _tail, value); - } - } - - /// Add the [field] with the given 8-bit signed integer [value]. The field is - /// not added if the [value] is equal to [def]. - void addInt8(int field, int value, [int def]) { - _ensureCurrentVTable(); - if (value != null && value != def) { - _prepare(_sizeofInt8, 1); - _trackField(field); - _setInt8AtTail(_buf, _tail, value); - } - } - - void addStruct(int field, int offset) { - _ensureCurrentVTable(); - _trackField(field); - _currentVTable.addField(field, offset); - } - - /// Add the [field] referencing an object with the given [offset]. - void addOffset(int field, int offset) { - _ensureCurrentVTable(); - if (offset != null) { - _prepare(_sizeofUint32, 1); - _trackField(field); - _setUint32AtTail(_buf, _tail, _tail - offset); - } - } - - /// Add the [field] with the given 32-bit unsigned integer [value]. The field - /// is not added if the [value] is equal to [def]. - void addUint32(int field, int value, [int def]) { - _ensureCurrentVTable(); - if (value != null && value != def) { - _prepare(_sizeofUint32, 1); - _trackField(field); - _setUint32AtTail(_buf, _tail, value); - } - } - - /// Add the [field] with the given 32-bit unsigned integer [value]. The field - /// is not added if the [value] is equal to [def]. - void addUint16(int field, int value, [int def]) { - _ensureCurrentVTable(); - if (value != null && value != def) { - _prepare(_sizeofUint16, 1); - _trackField(field); - _setUint16AtTail(_buf, _tail, value); - } - } - - /// Add the [field] with the given 8-bit unsigned integer [value]. The field - /// is not added if the [value] is equal to [def]. - void addUint8(int field, int value, [int def]) { - _ensureCurrentVTable(); - if (value != null && value != def) { - _prepare(_sizeofUint8, 1); - _trackField(field); - _setUint8AtTail(_buf, _tail, value); - } - } - - /// Add the [field] with the given 32-bit float [value]. The field - /// is not added if the [value] is equal to [def]. - void addFloat32(int field, double value, [double def]) { - _ensureCurrentVTable(); - if (value != null && value != def) { - _prepare(_sizeofFloat32, 1); - _trackField(field); - _setFloat32AtTail(_buf, _tail, value); - } - } - - /// Add the [field] with the given 64-bit double [value]. The field - /// is not added if the [value] is equal to [def]. - void addFloat64(int field, double value, [double def]) { - _ensureCurrentVTable(); - if (value != null && value != def) { - _prepare(_sizeofFloat64, 1); - _trackField(field); - _setFloat64AtTail(_buf, _tail, value); - } - } - - /// Add the [field] with the given 64-bit unsigned integer [value]. The field - /// is not added if the [value] is equal to [def]. - void addUint64(int field, int value, [double def]) { - _ensureCurrentVTable(); - if (value != null && value != def) { - _prepare(_sizeofUint64, 1); - _trackField(field); - _setUint64AtTail(_buf, _tail, value); - } - } - - /// Add the [field] with the given 64-bit unsigned integer [value]. The field - /// is not added if the [value] is equal to [def]. - void addInt64(int field, int value, [double def]) { - _ensureCurrentVTable(); - if (value != null && value != def) { - _prepare(_sizeofInt64, 1); - _trackField(field); - _setInt64AtTail(_buf, _tail, value); - } - } - - /// End the current table and return its offset. - int endTable() { - if (_currentVTable == null) { - throw new StateError('Start a table before ending it.'); - } - // Prepare for writing the VTable. - _prepare(_sizeofInt32, 1); - int tableTail = _tail; - // Prepare the size of the current table. - _currentVTable.tableSize = tableTail - _currentTableEndTail; - // Prepare the VTable to use for the current table. - int vTableTail; - { - _currentVTable.computeFieldOffsets(tableTail); - // Try to find an existing compatible VTable. - // Search backward - more likely to have recently used one - for (int i = _vTables.length - 1; i >= 0; i--) { - final int vt2Offset = _vTables[i]; - final int vt2Start = _buf.lengthInBytes - vt2Offset; - final int vt2Size = _buf.getUint16(vt2Start, Endian.little); - - if (_currentVTable._vTableSize == vt2Size && - _currentVTable._offsetsMatch(vt2Start, _buf)) { - vTableTail = vt2Offset; - break; - } - } - // Write a new VTable. - if (vTableTail == null) { - _prepare(_sizeofUint16, _currentVTable.numOfUint16); - vTableTail = _tail; - _currentVTable.tail = vTableTail; - _currentVTable.output(_buf, _buf.lengthInBytes - _tail); - _vTables.add(_currentVTable.tail); - } - } - // Set the VTable offset. - _setInt32AtTail(_buf, tableTail, vTableTail - tableTail); - // Done with this table. - _currentVTable = null; - return tableTail; - } - - /// This method low level method can be used to return a raw piece of the buffer - /// after using the the put* methods. - /// - /// Most clients should prefer calling [finish]. - Uint8List lowFinish() { - int alignedTail = _tail + ((-_tail) % _maxAlign); - return _buf.buffer.asUint8List(_buf.lengthInBytes - alignedTail); - } - - /// Finish off the creation of the buffer. The given [offset] is used as the - /// root object offset, and usually references directly or indirectly every - /// written object. If [fileIdentifier] is specified (and not `null`), it is - /// interpreted as a 4-byte Latin-1 encoded string that should be placed at - /// bytes 4-7 of the file. - Uint8List finish(int offset, [String fileIdentifier]) { - _prepare(max(_sizeofUint32, _maxAlign), fileIdentifier == null ? 1 : 2); - int alignedTail = _tail + ((-_tail) % _maxAlign); - _setUint32AtTail(_buf, alignedTail, alignedTail - offset); - if (fileIdentifier != null) { - for (int i = 0; i < 4; i++) { - _setUint8AtTail(_buf, alignedTail - _sizeofUint32 - i, - fileIdentifier.codeUnitAt(i)); - } - } - return _buf.buffer.asUint8List(_buf.lengthInBytes - alignedTail); - } - - /// Writes a Float64 to the tail of the buffer after preparing space for it. - /// - /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. - void putFloat64(double value) { - _prepare(_sizeofFloat64, 1); - _setFloat32AtTail(_buf, _tail, value); - } - - /// Writes a Float32 to the tail of the buffer after preparing space for it. - /// - /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. - void putFloat32(double value) { - _prepare(_sizeofFloat32, 1); - _setFloat32AtTail(_buf, _tail, value); - } - - /// Writes a Int64 to the tail of the buffer after preparing space for it. - /// - /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. - void putInt64(int value) { - _prepare(_sizeofInt64, 1); - _setInt64AtTail(_buf, _tail, value); - } - - /// Writes a Uint32 to the tail of the buffer after preparing space for it. - /// - /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. - void putInt32(int value) { - _prepare(_sizeofInt32, 1); - _setInt32AtTail(_buf, _tail, value); - } - - /// Writes a Uint16 to the tail of the buffer after preparing space for it. - /// - /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. - void putInt16(int value) { - _prepare(_sizeofInt16, 1); - _setInt16AtTail(_buf, _tail, value); - } - - /// Writes a Uint8 to the tail of the buffer after preparing space for it. - /// - /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. - void putInt8(int value) { - _prepare(_sizeofInt8, 1); - _buf.setInt8(_buf.lengthInBytes - _tail, value); - } - - /// Writes a Uint64 to the tail of the buffer after preparing space for it. - /// - /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. - void putUint64(int value) { - _prepare(_sizeofUint64, 1); - _setUint64AtTail(_buf, _tail, value); - } - - /// Writes a Uint32 to the tail of the buffer after preparing space for it. - /// - /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. - void putUint32(int value) { - _prepare(_sizeofUint32, 1); - _setUint32AtTail(_buf, _tail, value); - } - - /// Writes a Uint16 to the tail of the buffer after preparing space for it. - /// - /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. - void putUint16(int value) { - _prepare(_sizeofUint16, 1); - _setUint16AtTail(_buf, _tail, value); - } - - /// Writes a Uint8 to the tail of the buffer after preparing space for it. - /// - /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. - void putUint8(int value) { - _prepare(_sizeofUint8, 1); - _buf.setUint8(_buf.lengthInBytes - _tail, value); - } - - /// Reset the builder and make it ready for filling a new buffer. - void reset() { - _buf = new ByteData(initialSize); - _maxAlign = 1; - _tail = 0; - _currentVTable = null; - if (_strings != null) { - _strings = new Map(); - } - } - - /// Start a new table. Must be finished with [endTable] invocation. - void startTable() { - if (_currentVTable != null) { - throw new StateError('Inline tables are not supported.'); - } - _currentVTable = new _VTable(); - _currentTableEndTail = _tail; - } - - /// Finish a Struct vector. Most callers should preferto use [writeListOfStructs]. - /// - /// Most callers should prefer [writeListOfStructs]. - int endStructVector(int count) { - putUint32(count); - return _tail; - } - - /// Writes a list of Structs to the buffer, returning the offset - int writeListOfStructs(List structBuilders) { - _ensureNoVTable(); - for (int i = structBuilders.length - 1; i >= 0; i--) { - structBuilders[i].finish(this); - } - return endStructVector(structBuilders.length); - } - - /// Write the given list of [values]. - int writeList(List values) { - _ensureNoVTable(); - _prepare(_sizeofUint32, 1 + values.length); - final int result = _tail; - int tail = _tail; - _setUint32AtTail(_buf, tail, values.length); - tail -= _sizeofUint32; - for (int value in values) { - _setUint32AtTail(_buf, tail, tail - value); - tail -= _sizeofUint32; - } - return result; - } - - /// Write the given list of 64-bit float [values]. - int writeListFloat64(List values) { - _ensureNoVTable(); - _prepare(4, 1 + (2 * values.length)); - final int result = _tail; - int tail = _tail; - _setUint32AtTail(_buf, tail, values.length); - tail -= _sizeofUint32; - for (double value in values) { - _setFloat64AtTail(_buf, tail, value); - tail -= _sizeofFloat64; - } - return result; - } - - /// Write the given list of 32-bit float [values]. - int writeListFloat32(List values) { - _ensureNoVTable(); - _prepare(_sizeofFloat32, 1 + values.length); - final int result = _tail; - int tail = _tail; - _setUint32AtTail(_buf, tail, values.length); - tail -= _sizeofUint32; - for (double value in values) { - _setFloat32AtTail(_buf, tail, value); - tail -= _sizeofFloat32; - } - return result; - } - - /// Write the given list of signed 64-bit integer [values]. - int writeListInt64(List values) { - _ensureNoVTable(); - _prepare(_sizeofUint32, 2 * values.length); - final int result = _tail; - int tail = _tail; - _setUint32AtTail(_buf, tail, values.length); - tail -= _sizeofUint32; - for (int value in values) { - _setInt64AtTail(_buf, tail, value); - tail -= _sizeofInt64; - } - return result; - } - - /// Write the given list of signed 64-bit integer [values]. - int writeListUint64(List values) { - _ensureNoVTable(); - _prepare(_sizeofUint32, 2 * values.length); - final int result = _tail; - int tail = _tail; - _setUint32AtTail(_buf, tail, values.length); - tail -= _sizeofUint32; - for (int value in values) { - _setUint64AtTail(_buf, tail, value); - tail -= _sizeofUint64; - } - return result; - } - - /// Write the given list of signed 32-bit integer [values]. - int writeListInt32(List values) { - _ensureNoVTable(); - _prepare(_sizeofUint32, 1 + values.length); - final int result = _tail; - int tail = _tail; - _setUint32AtTail(_buf, tail, values.length); - tail -= _sizeofUint32; - for (int value in values) { - _setInt32AtTail(_buf, tail, value); - tail -= _sizeofInt32; - } - return result; - } - - /// Write the given list of unsigned 32-bit integer [values]. - int writeListUint32(List values) { - _ensureNoVTable(); - _prepare(_sizeofUint32, 1 + values.length); - final int result = _tail; - int tail = _tail; - _setUint32AtTail(_buf, tail, values.length); - tail -= _sizeofUint32; - for (int value in values) { - _setUint32AtTail(_buf, tail, value); - tail -= _sizeofUint32; - } - return result; - } - - /// Write the given list of signed 16-bit integer [values]. - int writeListInt16(List values) { - _ensureNoVTable(); - _prepare(_sizeofUint32, 1, additionalBytes: 2 * values.length); - final int result = _tail; - int tail = _tail; - _setUint32AtTail(_buf, tail, values.length); - tail -= _sizeofUint32; - for (int value in values) { - _setInt16AtTail(_buf, tail, value); - tail -= _sizeofInt16; - } - return result; - } - - /// Write the given list of unsigned 16-bit integer [values]. - int writeListUint16(List values) { - _ensureNoVTable(); - _prepare(_sizeofUint32, 1, additionalBytes: 2 * values.length); - final int result = _tail; - int tail = _tail; - _setUint32AtTail(_buf, tail, values.length); - tail -= _sizeofUint32; - for (int value in values) { - _setUint16AtTail(_buf, tail, value); - tail -= _sizeofUint16; - } - return result; - } - - /// Write the given list of bools as unsigend 8-bit integer [values]. - int writeListBool(List values) { - return writeListUint8(values?.map((b) => b ? 1 : 0)?.toList()); - } - - /// Write the given list of signed 8-bit integer [values]. - int writeListInt8(List values) { - _ensureNoVTable(); - _prepare(_sizeofUint32, 1, additionalBytes: values.length); - final int result = _tail; - int tail = _tail; - _setUint32AtTail(_buf, tail, values.length); - tail -= _sizeofUint32; - for (int value in values) { - _setInt8AtTail(_buf, tail, value); - tail -= _sizeofUint8; - } - return result; - } - - /// Write the given list of unsigned 8-bit integer [values]. - int writeListUint8(List values) { - _ensureNoVTable(); - _prepare(_sizeofUint32, 1, additionalBytes: values.length); - final int result = _tail; - int tail = _tail; - _setUint32AtTail(_buf, tail, values.length); - tail -= _sizeofUint32; - for (int value in values) { - _setUint8AtTail(_buf, tail, value); - tail -= _sizeofUint8; - } - return result; - } - - /// Write the given string [value] and return its offset, or `null` if - /// the [value] is `null`. - int writeString(String value) { - _ensureNoVTable(); - if (value != null) { - if (_strings != null) { - return _strings.putIfAbsent(value, () => _writeString(value)); - } else { - return _writeString(value); - } - } - return null; - } - - int _writeString(String value) { - // TODO(scheglov) optimize for ASCII strings - List bytes = utf8.encode(value); - int length = bytes.length; - _prepare(4, 1, additionalBytes: length + 1); - final int result = _tail; - _setUint32AtTail(_buf, _tail, length); - int offset = _buf.lengthInBytes - _tail + 4; - for (int i = 0; i < length; i++) { - _buf.setUint8(offset++, bytes[i]); - } - return result; - } - - /// Throw an exception if there is not currently a vtable. - void _ensureCurrentVTable() { - if (_currentVTable == null) { - throw new StateError('Start a table before adding values.'); - } - } - - /// Throw an exception if there is currently a vtable. - void _ensureNoVTable() { - if (_currentVTable != null) { - throw new StateError( - 'Cannot write a non-scalar value while writing a table.'); - } - } - - /// The number of bytes that have been written to the buffer so far. The - /// most recently written byte is this many bytes from the end of the buffer. - int get offset => _tail; - - /// Zero-pads the buffer, which may be required for some struct layouts. - void pad(int howManyBytes) { - for (int i = 0; i < howManyBytes; i++) putUint8(0); - } - - /// Prepare for writing the given `count` of scalars of the given `size`. - /// Additionally allocate the specified `additionalBytes`. Update the current - /// tail pointer to point at the allocated space. - void _prepare(int size, int count, {int additionalBytes = 0}) { - // Update the alignment. - if (_maxAlign < size) { - _maxAlign = size; - } - // Prepare amount of required space. - int dataSize = size * count + additionalBytes; - int alignDelta = (-(_tail + dataSize)) % size; - int bufSize = alignDelta + dataSize; - // Ensure that we have the required amount of space. - { - int oldCapacity = _buf.lengthInBytes; - if (_tail + bufSize > oldCapacity) { - int desiredNewCapacity = (oldCapacity + bufSize) * 2; - int deltaCapacity = desiredNewCapacity - oldCapacity; - deltaCapacity += (-deltaCapacity) % _maxAlign; - int newCapacity = oldCapacity + deltaCapacity; - ByteData newBuf = new ByteData(newCapacity); - newBuf.buffer - .asUint8List() - .setAll(deltaCapacity, _buf.buffer.asUint8List()); - _buf = newBuf; - } - } - // Update the tail pointer. - _tail += bufSize; - } - - /// Record the offset of the given [field]. - void _trackField(int field) { - _currentVTable.addField(field, _tail); - } - - static void _setFloat64AtTail(ByteData _buf, int tail, double x) { - _buf.setFloat64(_buf.lengthInBytes - tail, x, Endian.little); - } - - static void _setFloat32AtTail(ByteData _buf, int tail, double x) { - _buf.setFloat32(_buf.lengthInBytes - tail, x, Endian.little); - } - - static void _setUint64AtTail(ByteData _buf, int tail, int x) { - _buf.setUint64(_buf.lengthInBytes - tail, x, Endian.little); - } - - static void _setInt64AtTail(ByteData _buf, int tail, int x) { - _buf.setInt64(_buf.lengthInBytes - tail, x, Endian.little); - } - - static void _setInt32AtTail(ByteData _buf, int tail, int x) { - _buf.setInt32(_buf.lengthInBytes - tail, x, Endian.little); - } - - static void _setUint32AtTail(ByteData _buf, int tail, int x) { - _buf.setUint32(_buf.lengthInBytes - tail, x, Endian.little); - } - - static void _setInt16AtTail(ByteData _buf, int tail, int x) { - _buf.setInt16(_buf.lengthInBytes - tail, x, Endian.little); - } - - static void _setUint16AtTail(ByteData _buf, int tail, int x) { - _buf.setUint16(_buf.lengthInBytes - tail, x, Endian.little); - } - - static void _setInt8AtTail(ByteData _buf, int tail, int x) { - _buf.setInt8(_buf.lengthInBytes - tail, x); - } - - static void _setUint8AtTail(ByteData _buf, int tail, int x) { - _buf.setUint8(_buf.lengthInBytes - tail, x); - } -} - -/// Reader of lists of boolean values. -/// -/// The returned unmodifiable lists lazily read values on access. -class BoolListReader extends Reader> { - const BoolListReader(); - - @override - int get size => _sizeofUint32; - - @override - List read(BufferContext bc, int offset) => - new _FbBoolList(bc, bc.derefObject(offset)); -} - -/// The reader of booleans. -class BoolReader extends Reader { - const BoolReader() : super(); - - @override - int get size => _sizeofUint8; - - @override - bool read(BufferContext bc, int offset) => bc._getInt8(offset) != 0; -} - -/// The reader of lists of 64-bit float values. -/// -/// The returned unmodifiable lists lazily read values on access. -class Float64ListReader extends Reader> { - const Float64ListReader(); - - @override - int get size => _sizeofFloat64; - - @override - List read(BufferContext bc, int offset) => - new _FbFloat64List(bc, bc.derefObject(offset)); -} - -class Float32ListReader extends Reader> { - const Float32ListReader(); - - @override - int get size => _sizeofFloat32; - - @override - List read(BufferContext bc, int offset) => - new _FbFloat32List(bc, bc.derefObject(offset)); -} - -class Float64Reader extends Reader { - const Float64Reader(); - - @override - int get size => _sizeofFloat64; - - @override - double read(BufferContext bc, int offset) => bc._getFloat64(offset); -} - -class Float32Reader extends Reader { - const Float32Reader(); - - @override - int get size => _sizeofFloat32; - - @override - double read(BufferContext bc, int offset) => bc._getFloat32(offset); -} - -class Int64Reader extends Reader { - const Int64Reader() : super(); - @override - int get size => _sizeofInt64; - - @override - int read(BufferContext bc, int offset) => bc._getInt64(offset); -} - -/// The reader of signed 32-bit integers. -class Int32Reader extends Reader { - const Int32Reader() : super(); - - @override - int get size => _sizeofInt32; - - @override - int read(BufferContext bc, int offset) => bc._getInt32(offset); -} - -/// The reader of signed 32-bit integers. -class Int16Reader extends Reader { - const Int16Reader() : super(); - - @override - int get size => _sizeofInt16; - - @override - int read(BufferContext bc, int offset) => bc._getInt16(offset); -} - -/// The reader of 8-bit signed integers. -class Int8Reader extends Reader { - const Int8Reader() : super(); - - @override - int get size => _sizeofInt8; - - @override - int read(BufferContext bc, int offset) => bc._getInt8(offset); -} - -/// The reader of lists of objects. -/// -/// The returned unmodifiable lists lazily read objects on access. -class ListReader extends Reader> { - final Reader _elementReader; - - const ListReader(this._elementReader); - - @override - int get size => _sizeofUint32; - - @override - List read(BufferContext bc, int offset) => - new _FbGenericList(_elementReader, bc, bc.derefObject(offset)); -} - -/// Object that can read a value at a [BufferContext]. -abstract class Reader { - const Reader(); - - /// The size of the value in bytes. - int get size; - - /// Read the value at the given [offset] in [bc]. - T read(BufferContext bc, int offset); - - /// Read the value of the given [field] in the given [object]. - T vTableGet(BufferContext object, int offset, int field, [T defaultValue]) { - int vTableSOffset = object._getInt32(offset); - int vTableOffset = offset - vTableSOffset; - int vTableSize = object._getUint16(vTableOffset); - int vTableFieldOffset = field; - if (vTableFieldOffset < vTableSize) { - int fieldOffsetInObject = - object._getUint16(vTableOffset + vTableFieldOffset); - if (fieldOffsetInObject != 0) { - return read(object, offset + fieldOffsetInObject); - } - } - return defaultValue; - } -} - -/// The reader of string values. -class StringReader extends Reader { - const StringReader() : super(); - - @override - int get size => 4; - - @override - String read(BufferContext bc, int offset) { - int strOffset = bc.derefObject(offset); - int length = bc._getUint32(strOffset); - Uint8List bytes = bc._asUint8LIst(strOffset + 4, length); - if (_isLatin(bytes)) { - return new String.fromCharCodes(bytes); - } - return utf8.decode(bytes); - } - - static bool _isLatin(Uint8List bytes) { - int length = bytes.length; - for (int i = 0; i < length; i++) { - if (bytes[i] > 127) { - return false; - } - } - return true; - } -} - -/// An abstract reader for structs. -abstract class StructReader extends Reader { - const StructReader(); - - /// Return the object at `offset`. - T createObject(BufferContext bc, int offset); - - T read(BufferContext bp, int offset) { - return createObject(bp, offset); - } -} - -/// An abstract reader for tables. -abstract class TableReader extends Reader { - const TableReader(); - - @override - int get size => 4; - - /// Return the object at [offset]. - T createObject(BufferContext bc, int offset); - - @override - T read(BufferContext bp, int offset) { - int objectOffset = bp.derefObject(offset); - return createObject(bp, objectOffset); - } -} - -/// Reader of lists of unsigned 32-bit integer values. -/// -/// The returned unmodifiable lists lazily read values on access. -class Uint32ListReader extends Reader> { - const Uint32ListReader(); - - @override - int get size => _sizeofUint32; - - @override - List read(BufferContext bc, int offset) => - new _FbUint32List(bc, bc.derefObject(offset)); -} - -/// The reader of unsigned 64-bit integers. -/// -/// WARNING: May have compatibility issues with JavaScript -class Uint64Reader extends Reader { - const Uint64Reader() : super(); - - @override - int get size => _sizeofUint64; - - @override - int read(BufferContext bc, int offset) => bc._getUint64(offset); -} - -/// The reader of unsigned 32-bit integers. -class Uint32Reader extends Reader { - const Uint32Reader() : super(); - - @override - int get size => _sizeofUint32; - - @override - int read(BufferContext bc, int offset) => bc._getUint32(offset); -} - -/// Reader of lists of unsigned 32-bit integer values. -/// -/// The returned unmodifiable lists lazily read values on access. -class Uint16ListReader extends Reader> { - const Uint16ListReader(); - - @override - int get size => _sizeofUint32; - - @override - List read(BufferContext bc, int offset) => - new _FbUint16List(bc, bc.derefObject(offset)); -} - -/// The reader of unsigned 32-bit integers. -class Uint16Reader extends Reader { - const Uint16Reader() : super(); - - @override - int get size => _sizeofUint16; - - @override - int read(BufferContext bc, int offset) => bc._getUint16(offset); -} - -/// Reader of lists of unsigned 8-bit integer values. -/// -/// The returned unmodifiable lists lazily read values on access. -class Uint8ListReader extends Reader> { - const Uint8ListReader(); - - @override - int get size => _sizeofUint32; - - @override - List read(BufferContext bc, int offset) => - new _FbUint8List(bc, bc.derefObject(offset)); -} - -/// The reader of unsigned 8-bit integers. -class Uint8Reader extends Reader { - const Uint8Reader() : super(); - - @override - int get size => _sizeofUint8; - - @override - int read(BufferContext bc, int offset) => bc._getUint8(offset); -} - -/// The list backed by 64-bit values - Uint64 length and Float64. -class _FbFloat64List extends _FbList { - _FbFloat64List(BufferContext bc, int offset) : super(bc, offset); - - @override - double operator [](int i) { - return bc._getFloat64(offset + 4 + 8 * i); - } -} - -/// The list backed by 32-bit values - Float32. -class _FbFloat32List extends _FbList { - _FbFloat32List(BufferContext bc, int offset) : super(bc, offset); - - @override - double operator [](int i) { - return bc._getFloat32(offset + 4 + 4 * i); - } -} - -/// List backed by a generic object which may have any size. -class _FbGenericList extends _FbList { - final Reader elementReader; - - List _items; - - _FbGenericList(this.elementReader, BufferContext bp, int offset) - : super(bp, offset); - - @override - E operator [](int i) { - _items ??= new List(length); - E item = _items[i]; - if (item == null) { - item = elementReader.read(bc, offset + 4 + elementReader.size * i); - _items[i] = item; - } - return item; - } -} - -/// The base class for immutable lists read from flat buffers. -abstract class _FbList extends Object with ListMixin implements List { - final BufferContext bc; - final int offset; - int _length; - - _FbList(this.bc, this.offset); - - @override - int get length { - _length ??= bc._getUint32(offset); - return _length; - } - - @override - void set length(int i) => - throw new StateError('Attempt to modify immutable list'); - - @override - void operator []=(int i, E e) => - throw new StateError('Attempt to modify immutable list'); -} - -/// List backed by 32-bit unsigned integers. -class _FbUint32List extends _FbList { - _FbUint32List(BufferContext bc, int offset) : super(bc, offset); - - @override - int operator [](int i) { - return bc._getUint32(offset + 4 + 4 * i); - } -} - -/// List backed by 16-bit unsigned integers. -class _FbUint16List extends _FbList { - _FbUint16List(BufferContext bc, int offset) : super(bc, offset); - - @override - int operator [](int i) { - return bc._getUint16(offset + 4 + 2 * i); - } -} - -/// List backed by 8-bit unsigned integers. -class _FbUint8List extends _FbList { - _FbUint8List(BufferContext bc, int offset) : super(bc, offset); - - @override - int operator [](int i) { - return bc._getUint8(offset + 4 + i); - } -} - -/// List backed by 8-bit unsigned integers. -class _FbBoolList extends _FbList { - _FbBoolList(BufferContext bc, int offset) : super(bc, offset); - - @override - bool operator [](int i) { - return bc._getUint8(offset + 4 + i) == 1 ? true : false; - } -} - -/// Class that describes the structure of a table. -class _VTable { - static const int _metadataLength = 4; - - final List fieldTails = []; - final List fieldOffsets = []; - - /// The size of the table that uses this VTable. - int tableSize; - - /// The tail of this VTable. It is used to share the same VTable between - /// multiple tables of identical structure. - int tail; - - int get _vTableSize => numOfUint16 * _sizeofUint16; - - int get numOfUint16 => 1 + 1 + fieldTails.length; - - void addField(int field, int offset) { - while (fieldTails.length <= field) { - fieldTails.add(null); - } - fieldTails[field] = offset; - } - - bool _offsetsMatch(int vt2Start, ByteData buf) { - for (int i = 0; i < fieldOffsets.length; i++) { - if (fieldOffsets[i] != - buf.getUint16( - vt2Start + _metadataLength + (2 * i), Endian.little)) { - return false; - } - } - return true; - } - - /// Fill the [fieldOffsets] field. - void computeFieldOffsets(int tableTail) { - assert(fieldOffsets.isEmpty); - for (int fieldTail in fieldTails) { - int fieldOffset = fieldTail == null ? 0 : tableTail - fieldTail; - fieldOffsets.add(fieldOffset); - } - } - - /// Outputs this VTable to [buf], which is is expected to be aligned to 16-bit - /// and have at least [numOfUint16] 16-bit words available. - void output(ByteData buf, int bufOffset) { - // VTable size. - buf.setUint16(bufOffset, numOfUint16 * 2, Endian.little); - bufOffset += 2; - // Table size. - buf.setUint16(bufOffset, tableSize, Endian.little); - bufOffset += 2; - // Field offsets. - for (int fieldOffset in fieldOffsets) { - buf.setUint16(bufOffset, fieldOffset, Endian.little); - bufOffset += 2; - } - } -} diff --git a/third_party/flatbuffers/dart/publish.sh b/third_party/flatbuffers/dart/publish.sh deleted file mode 100755 index 167a4a34ae7..00000000000 --- a/third_party/flatbuffers/dart/publish.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/sh -# -# Copyright 2018 Google Inc. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Note to pub consumers: this file is used to assist with publishing the -# pub package from the flatbuffers repository and is not meant for general use. -# As pub does not currently provide a way to exclude files, it is included here. - -command -v pub >/dev/null 2>&1 || { echo >&2 "Require `pub` but it's not installed. Aborting."; exit 1; } - -cp ../samples/monster.fbs example/ -cp ../tests/monster_test.fbs test/ -pub publish - -rm example/monster.fbs -rm test/monster_test.fbs \ No newline at end of file diff --git a/third_party/flatbuffers/dart/pubspec.yaml b/third_party/flatbuffers/dart/pubspec.yaml deleted file mode 100644 index 4761ffc2272..00000000000 --- a/third_party/flatbuffers/dart/pubspec.yaml +++ /dev/null @@ -1,20 +0,0 @@ -name: flat_buffers -version: 1.11.0 -description: > - FlatBuffers reading and writing library for Dart. Use the flatc compiler to - generate Dart classes for a FlatBuffers schema, and this library to assist with - reading and writing the binary format. - - Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team. -authors: -- Dan Field -- Konstantin Scheglov -- Paul Berry -homepage: https://github.com/google/flatbuffers -documentation: https://google.github.io/flatbuffers/index.html -dev_dependencies: - test: ^1.3.0 - test_reflective_loader: ^0.1.4 - path: ^1.5.1 -environment: - sdk: '>=2.0.0-dev.28.0 <3.0.0' \ No newline at end of file diff --git a/third_party/flatbuffers/dart/test/flat_buffers_test.dart b/third_party/flatbuffers/dart/test/flat_buffers_test.dart deleted file mode 100644 index f9c5e01cc38..00000000000 --- a/third_party/flatbuffers/dart/test/flat_buffers_test.dart +++ /dev/null @@ -1,573 +0,0 @@ -// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:typed_data'; -import 'dart:io' as io; - -import 'package:path/path.dart' as path; - -import 'package:flat_buffers/flat_buffers.dart'; -import 'package:test/test.dart'; -import 'package:test_reflective_loader/test_reflective_loader.dart'; - -import './monster_test_my_game.example_generated.dart' as example; - -main() { - defineReflectiveSuite(() { - defineReflectiveTests(BuilderTest); - defineReflectiveTests(CheckOtherLangaugesData); - }); -} - -int indexToField(int index) { - return (1 + 1 + index) * 2; -} - -@reflectiveTest -class CheckOtherLangaugesData { - test_cppData() async { - List data = await new io.File(path.join( - path.dirname(io.Platform.script.path), - 'monsterdata_test.mon', - )) - .readAsBytes(); - example.Monster mon = new example.Monster(data); - expect(mon.hp, 80); - expect(mon.mana, 150); - expect(mon.name, 'MyMonster'); - expect(mon.pos.x, 1.0); - expect(mon.pos.y, 2.0); - expect(mon.pos.z, 3.0); - expect(mon.pos.test1, 3.0); - expect(mon.pos.test2.value, 2.0); - expect(mon.pos.test3.a, 5); - expect(mon.pos.test3.b, 6); - expect(mon.testType.value, example.AnyTypeId.Monster.value); - expect(mon.test is example.Monster, true); - final monster2 = mon.test as example.Monster; - expect(monster2.name, "Fred"); - - expect(mon.inventory.length, 5); - expect(mon.inventory.reduce((cur, next) => cur + next), 10); - expect(mon.test4.length, 2); - expect( - mon.test4[0].a + mon.test4[0].b + mon.test4[1].a + mon.test4[1].b, 100); - expect(mon.testarrayofstring.length, 2); - expect(mon.testarrayofstring[0], "test1"); - expect(mon.testarrayofstring[1], "test2"); - - // this will fail if accessing any field fails. - expect(mon.toString(), - 'Monster{pos: Vec3{x: 1.0, y: 2.0, z: 3.0, test1: 3.0, test2: Color{value: 2}, test3: Test{a: 5, b: 6}}, mana: 150, hp: 80, name: MyMonster, inventory: [0, 1, 2, 3, 4], color: Color{value: 8}, testType: AnyTypeId{value: 1}, test: Monster{pos: null, mana: 150, hp: 100, name: Fred, inventory: null, color: Color{value: 8}, testType: AnyTypeId{value: 0}, test: null, test4: null, testarrayofstring: null, testarrayoftables: null, enemy: null, testnestedflatbuffer: null, testempty: null, testbool: false, testhashs32Fnv1: 0, testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, testf2: 3.0, testf3: 0.0, testarrayofstring2: null, testarrayofsortedstruct: null, flex: null, test5: null, vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, vectorOfReferrables: null, singleWeakReference: 0, vectorOfWeakReferences: null, vectorOfStrongReferrables: null, coOwningReference: 0, vectorOfCoOwningReferences: null, nonOwningReference: 0, vectorOfNonOwningReferences: null}, test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], testarrayofstring: [test1, test2], testarrayoftables: null, enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, inventory: null, color: Color{value: 8}, testType: AnyTypeId{value: 0}, test: null, test4: null, testarrayofstring: null, testarrayoftables: null, enemy: null, testnestedflatbuffer: null, testempty: null, testbool: false, testhashs32Fnv1: 0, testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, testf2: 3.0, testf3: 0.0, testarrayofstring2: null, testarrayofsortedstruct: null, flex: null, test5: null, vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, vectorOfReferrables: null, singleWeakReference: 0, vectorOfWeakReferences: null, vectorOfStrongReferrables: null, coOwningReference: 0, vectorOfCoOwningReferences: null, nonOwningReference: 0, vectorOfNonOwningReferences: null}, testnestedflatbuffer: null, testempty: null, testbool: false, testhashs32Fnv1: -579221183, testhashu32Fnv1: 3715746113, testhashs64Fnv1: 7930699090847568257, testhashu64Fnv1: 7930699090847568257, testhashs32Fnv1a: -1904106383, testhashu32Fnv1a: 2390860913, testhashs64Fnv1a: 4898026182817603057, testhashu64Fnv1a: 4898026182817603057, testarrayofbools: [true, false, true], testf: 3.14159, testf2: 3.0, testf3: 0.0, testarrayofstring2: null, testarrayofsortedstruct: null, flex: null, test5: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], vectorOfLongs: [1, 100, 10000, 1000000, 100000000], vectorOfDoubles: [-1.7976931348623157e+308, 0.0, 1.7976931348623157e+308], parentNamespaceTest: null, vectorOfReferrables: null, singleWeakReference: 0, vectorOfWeakReferences: null, vectorOfStrongReferrables: null, coOwningReference: 0, vectorOfCoOwningReferences: null, nonOwningReference: 0, vectorOfNonOwningReferences: null}'); - } -} - -@reflectiveTest -class BuilderTest { - void test_monsterBuilder() { - final fbBuilder = new Builder(); - final str = fbBuilder.writeString('MyMonster'); - - fbBuilder.writeString('test1'); - fbBuilder.writeString('test2'); - final testArrayOfString = fbBuilder.endStructVector(2); - - final fred = fbBuilder.writeString('Fred'); - - final List treasure = [0, 1, 2, 3, 4]; - final inventory = fbBuilder.writeListUint8(treasure); - - final monBuilder = new example.MonsterBuilder(fbBuilder) - ..begin() - ..addNameOffset(fred); - final mon2 = monBuilder.finish(); - - final testBuilder = new example.TestBuilder(fbBuilder); - testBuilder.finish(10, 20); - testBuilder.finish(30, 40); - final test4 = fbBuilder.endStructVector(2); - - - monBuilder - ..begin() - ..addPos( - new example.Vec3Builder(fbBuilder).finish( - 1.0, - 2.0, - 3.0, - 3.0, - example.Color.Green, - () => testBuilder.finish(5, 6), - ), - ) - ..addHp(80) - ..addNameOffset(str) - ..addInventoryOffset(inventory) - ..addTestType(example.AnyTypeId.Monster) - ..addTestOffset(mon2) - ..addTest4Offset(test4) - ..addTestarrayofstringOffset(testArrayOfString); - final mon = monBuilder.finish(); - fbBuilder.finish(mon); - } - - void test_error_addInt32_withoutStartTable() { - Builder builder = new Builder(); - expect(() { - builder.addInt32(0, 0); - }, throwsStateError); - } - - void test_error_addOffset_withoutStartTable() { - Builder builder = new Builder(); - expect(() { - builder.addOffset(0, 0); - }, throwsStateError); - } - - void test_error_endTable_withoutStartTable() { - Builder builder = new Builder(); - expect(() { - builder.endTable(); - }, throwsStateError); - } - - void test_error_startTable_duringTable() { - Builder builder = new Builder(); - builder.startTable(); - expect(() { - builder.startTable(); - }, throwsStateError); - } - - void test_error_writeString_duringTable() { - Builder builder = new Builder(); - builder.startTable(); - expect(() { - builder.writeString('12345'); - }, throwsStateError); - } - - void test_file_identifier() { - Uint8List byteList; - { - Builder builder = new Builder(initialSize: 0); - builder.startTable(); - int offset = builder.endTable(); - byteList = builder.finish(offset, 'Az~ÿ'); - } - // Convert byteList to a ByteData so that we can read data from it. - ByteData byteData = byteList.buffer.asByteData(byteList.offsetInBytes); - // First 4 bytes are an offset to the table data. - int tableDataLoc = byteData.getUint32(0, Endian.little); - // Next 4 bytes are the file identifier. - expect(byteData.getUint8(4), 65); // 'a' - expect(byteData.getUint8(5), 122); // 'z' - expect(byteData.getUint8(6), 126); // '~' - expect(byteData.getUint8(7), 255); // 'ÿ' - // First 4 bytes of the table data are a backwards offset to the vtable. - int vTableLoc = tableDataLoc - - byteData.getInt32(tableDataLoc, Endian.little); - // First 2 bytes of the vtable are the size of the vtable in bytes, which - // should be 4. - expect(byteData.getUint16(vTableLoc, Endian.little), 4); - // Next 2 bytes are the size of the object in bytes (including the vtable - // pointer), which should be 4. - expect(byteData.getUint16(vTableLoc + 2, Endian.little), 4); - } - - void test_low() { - Builder builder = new Builder(initialSize: 0); - expect((builder..putUint8(1)).lowFinish(), [1]); - expect((builder..putUint32(2)).lowFinish(), [2, 0, 0, 0, 0, 0, 0, 1]); - expect((builder..putUint8(3)).lowFinish(), - [0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 1]); - expect((builder..putUint8(4)).lowFinish(), - [0, 0, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]); - expect((builder..putUint8(5)).lowFinish(), - [0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]); - expect((builder..putUint32(6)).lowFinish(), - [6, 0, 0, 0, 0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]); - } - - void test_table_default() { - List byteList; - { - Builder builder = new Builder(initialSize: 0); - builder.startTable(); - builder.addInt32(0, 10, 10); - builder.addInt32(1, 20, 10); - int offset = builder.endTable(); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buffer = new BufferContext.fromBytes(byteList); - int objectOffset = buffer.derefObject(0); - // was not written, so uses the new default value - expect( - const Int32Reader() - .vTableGet(buffer, objectOffset, indexToField(0), 15), - 15); - // has the written value - expect( - const Int32Reader() - .vTableGet(buffer, objectOffset, indexToField(1), 15), - 20); - } - - void test_table_format() { - Uint8List byteList; - { - Builder builder = new Builder(initialSize: 0); - builder.startTable(); - builder.addInt32(0, 10); - builder.addInt32(1, 20); - builder.addInt32(2, 30); - byteList = builder.finish(builder.endTable()); - } - // Convert byteList to a ByteData so that we can read data from it. - ByteData byteData = byteList.buffer.asByteData(byteList.offsetInBytes); - // First 4 bytes are an offset to the table data. - int tableDataLoc = byteData.getUint32(0, Endian.little); - // First 4 bytes of the table data are a backwards offset to the vtable. - int vTableLoc = tableDataLoc - - byteData.getInt32(tableDataLoc, Endian.little); - // First 2 bytes of the vtable are the size of the vtable in bytes, which - // should be 10. - expect(byteData.getUint16(vTableLoc, Endian.little), 10); - // Next 2 bytes are the size of the object in bytes (including the vtable - // pointer), which should be 16. - expect(byteData.getUint16(vTableLoc + 2, Endian.little), 16); - // Remaining 6 bytes are the offsets within the object where the ints are - // located. - for (int i = 0; i < 3; i++) { - int offset = - byteData.getUint16(vTableLoc + 4 + 2 * i, Endian.little); - expect(byteData.getInt32(tableDataLoc + offset, Endian.little), - 10 + 10 * i); - } - } - - void test_table_string() { - String latinString = 'test'; - String unicodeString = 'Проба пера'; - List byteList; - { - Builder builder = new Builder(initialSize: 0); - int latinStringOffset = builder.writeString(latinString); - int unicodeStringOffset = builder.writeString(unicodeString); - builder.startTable(); - builder.addOffset(0, latinStringOffset); - builder.addOffset(1, unicodeStringOffset); - int offset = builder.endTable(); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - int objectOffset = buf.derefObject(0); - expect(const StringReader().vTableGet(buf, objectOffset, indexToField(0)), - latinString); - expect(const StringReader().vTableGet(buf, objectOffset, indexToField(1)), - unicodeString); - } - - void test_table_types() { - List byteList; - { - Builder builder = new Builder(initialSize: 0); - int stringOffset = builder.writeString('12345'); - builder.startTable(); - builder.addBool(0, true); - builder.addInt8(1, 10); - builder.addInt32(2, 20); - builder.addOffset(3, stringOffset); - builder.addInt32(4, 40); - builder.addUint32(5, 0x9ABCDEF0); - builder.addUint8(6, 0x9A); - int offset = builder.endTable(); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - int objectOffset = buf.derefObject(0); - expect( - const BoolReader().vTableGet(buf, objectOffset, indexToField(0)), true); - expect( - const Int8Reader().vTableGet(buf, objectOffset, indexToField(1)), 10); - expect( - const Int32Reader().vTableGet(buf, objectOffset, indexToField(2)), 20); - expect(const StringReader().vTableGet(buf, objectOffset, indexToField(3)), - '12345'); - expect( - const Int32Reader().vTableGet(buf, objectOffset, indexToField(4)), 40); - expect(const Uint32Reader().vTableGet(buf, objectOffset, indexToField(5)), - 0x9ABCDEF0); - expect(const Uint8Reader().vTableGet(buf, objectOffset, indexToField(6)), - 0x9A); - } - - void test_writeList_of_Uint32() { - List values = [10, 100, 12345, 0x9abcdef0]; - // write - List byteList; - { - Builder builder = new Builder(initialSize: 0); - int offset = builder.writeListUint32(values); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - List items = const Uint32ListReader().read(buf, 0); - expect(items, hasLength(4)); - expect(items, orderedEquals(values)); - } - - void test_writeList_ofBool() { - void verifyListBooleans(int len, List trueBits) { - // write - List byteList; - { - Builder builder = new Builder(initialSize: 0); - List values = new List.filled(len, false); - for (int bit in trueBits) { - values[bit] = true; - } - int offset = builder.writeListBool(values); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - List items = const BoolListReader().read(buf, 0); - expect(items, hasLength(len)); - for (int i = 0; i < items.length; i++) { - expect(items[i], trueBits.contains(i), reason: 'bit $i of $len'); - } - } - - verifyListBooleans(0, []); - verifyListBooleans(1, []); - verifyListBooleans(1, [0]); - verifyListBooleans(31, [0, 1]); - verifyListBooleans(31, [1, 2, 24, 25, 30]); - verifyListBooleans(31, [0, 30]); - verifyListBooleans(32, [1, 2, 24, 25, 31]); - verifyListBooleans(33, [1, 2, 24, 25, 32]); - verifyListBooleans(33, [1, 2, 24, 25, 31, 32]); - verifyListBooleans(63, []); - verifyListBooleans(63, [0, 1, 2, 61, 62]); - verifyListBooleans(63, new List.generate(63, (i) => i)); - verifyListBooleans(64, []); - verifyListBooleans(64, [0, 1, 2, 61, 62, 63]); - verifyListBooleans(64, [1, 2, 62]); - verifyListBooleans(64, [0, 1, 2, 63]); - verifyListBooleans(64, new List.generate(64, (i) => i)); - verifyListBooleans(100, [0, 3, 30, 60, 90, 99]); - } - - void test_writeList_ofInt32() { - List byteList; - { - Builder builder = new Builder(initialSize: 0); - int offset = builder.writeListInt32([1, 2, 3, 4, 5]); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - List items = const ListReader(const Int32Reader()).read(buf, 0); - expect(items, hasLength(5)); - expect(items, orderedEquals([1, 2, 3, 4, 5])); - } - - void test_writeList_ofFloat64() { - List values = [-1.234567, 3.4E+9, -5.6E-13, 7.8, 12.13]; - // write - List byteList; - { - Builder builder = new Builder(initialSize: 0); - int offset = builder.writeListFloat64(values); - byteList = builder.finish(offset); - } - - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - List items = const Float64ListReader().read(buf, 0); - - expect(items, hasLength(values.length)); - for (int i = 0; i < values.length; i++) { - expect(values[i], closeTo(items[i], .001)); - } - } - - void test_writeList_ofFloat32() { - List values = [1.0, 2.23, -3.213, 7.8, 12.13]; - // write - List byteList; - { - Builder builder = new Builder(initialSize: 0); - int offset = builder.writeListFloat32(values); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - List items = const Float32ListReader().read(buf, 0); - expect(items, hasLength(5)); - for (int i = 0; i < values.length; i++) { - expect(values[i], closeTo(items[i], .001)); - } - } - - void test_writeList_ofObjects() { - List byteList; - { - Builder builder = new Builder(initialSize: 0); - // write the object #1 - int object1; - { - builder.startTable(); - builder.addInt32(0, 10); - builder.addInt32(1, 20); - object1 = builder.endTable(); - } - // write the object #1 - int object2; - { - builder.startTable(); - builder.addInt32(0, 100); - builder.addInt32(1, 200); - object2 = builder.endTable(); - } - // write the list - int offset = builder.writeList([object1, object2]); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - List items = - const ListReader(const TestPointReader()).read(buf, 0); - expect(items, hasLength(2)); - expect(items[0].x, 10); - expect(items[0].y, 20); - expect(items[1].x, 100); - expect(items[1].y, 200); - } - - void test_writeList_ofStrings_asRoot() { - List byteList; - { - Builder builder = new Builder(initialSize: 0); - int str1 = builder.writeString('12345'); - int str2 = builder.writeString('ABC'); - int offset = builder.writeList([str1, str2]); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - List items = - const ListReader(const StringReader()).read(buf, 0); - expect(items, hasLength(2)); - expect(items, contains('12345')); - expect(items, contains('ABC')); - } - - void test_writeList_ofStrings_inObject() { - List byteList; - { - Builder builder = new Builder(initialSize: 0); - int listOffset = builder.writeList( - [builder.writeString('12345'), builder.writeString('ABC')]); - builder.startTable(); - builder.addOffset(0, listOffset); - int offset = builder.endTable(); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - StringListWrapperImpl reader = new StringListWrapperReader().read(buf, 0); - List items = reader.items; - expect(items, hasLength(2)); - expect(items, contains('12345')); - expect(items, contains('ABC')); - } - - void test_writeList_ofUint32() { - List byteList; - { - Builder builder = new Builder(initialSize: 0); - int offset = builder.writeListUint32([1, 2, 0x9ABCDEF0]); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - List items = const Uint32ListReader().read(buf, 0); - expect(items, hasLength(3)); - expect(items, orderedEquals([1, 2, 0x9ABCDEF0])); - } - - void test_writeList_ofUint16() { - List byteList; - { - Builder builder = new Builder(initialSize: 0); - int offset = builder.writeListUint16([1, 2, 60000]); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - List items = const Uint16ListReader().read(buf, 0); - expect(items, hasLength(3)); - expect(items, orderedEquals([1, 2, 60000])); - } - - void test_writeList_ofUint8() { - List byteList; - { - Builder builder = new Builder(initialSize: 0); - int offset = builder.writeListUint8([1, 2, 3, 4, 0x9A]); - byteList = builder.finish(offset); - } - // read and verify - BufferContext buf = new BufferContext.fromBytes(byteList); - List items = const Uint8ListReader().read(buf, 0); - expect(items, hasLength(5)); - expect(items, orderedEquals([1, 2, 3, 4, 0x9A])); - } -} - -class StringListWrapperImpl { - final BufferContext bp; - final int offset; - - StringListWrapperImpl(this.bp, this.offset); - - List get items => const ListReader(const StringReader()) - .vTableGet(bp, offset, indexToField(0)); -} - -class StringListWrapperReader extends TableReader { - const StringListWrapperReader(); - - @override - StringListWrapperImpl createObject(BufferContext object, int offset) { - return new StringListWrapperImpl(object, offset); - } -} - -class TestPointImpl { - final BufferContext bp; - final int offset; - - TestPointImpl(this.bp, this.offset); - - int get x => const Int32Reader().vTableGet(bp, offset, indexToField(0), 0); - - int get y => const Int32Reader().vTableGet(bp, offset, indexToField(1), 0); -} - -class TestPointReader extends TableReader { - const TestPointReader(); - - @override - TestPointImpl createObject(BufferContext object, int offset) { - return new TestPointImpl(object, offset); - } -} diff --git a/third_party/flatbuffers/dart/test/monster_test_my_game.example2_generated.dart b/third_party/flatbuffers/dart/test/monster_test_my_game.example2_generated.dart deleted file mode 100644 index 9a3ab6626c8..00000000000 --- a/third_party/flatbuffers/dart/test/monster_test_my_game.example2_generated.dart +++ /dev/null @@ -1,62 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// ignore_for_file: unused_import, unused_field, unused_local_variable - -library my_game.example2; - -import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; - -import 'include_test1_my_game.example2_generated.dart'; -import 'include_test2_my_game.example2_generated.dart'; -import './monster_test_my_game_generated.dart' as my_game; -import './monster_test_my_game.example_generated.dart' as my_game_example; - -class Monster { - Monster._(this._bc, this._bcOffset); - factory Monster(List bytes) { - fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes); - return reader.read(rootRef, 0); - } - - static const fb.Reader reader = const _MonsterReader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - - @override - String toString() { - return 'Monster{}'; - } -} - -class _MonsterReader extends fb.TableReader { - const _MonsterReader(); - - @override - Monster createObject(fb.BufferContext bc, int offset) => - new Monster._(bc, offset); -} - -class MonsterObjectBuilder extends fb.ObjectBuilder { - - MonsterObjectBuilder(); - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - - fbBuilder.startTable(); - return fbBuilder.endTable(); - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} diff --git a/third_party/flatbuffers/dart/test/monster_test_my_game.example_generated.dart b/third_party/flatbuffers/dart/test/monster_test_my_game.example_generated.dart deleted file mode 100644 index 49e2ec17014..00000000000 --- a/third_party/flatbuffers/dart/test/monster_test_my_game.example_generated.dart +++ /dev/null @@ -1,1486 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// ignore_for_file: unused_import, unused_field, unused_local_variable - -library my_game.example; - -import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; - -import 'include_test1_my_game.example_generated.dart'; -import 'include_test2_my_game.example_generated.dart'; -import './monster_test_my_game_generated.dart' as my_game; -import './monster_test_my_game.example2_generated.dart' as my_game_example2; - -class Color { - final int value; - const Color._(this.value); - - factory Color.fromValue(int value) { - if (value == null) value = 0; - if (!values.containsKey(value)) { - throw new StateError('Invalid value $value for bit flag enum Color'); - } - return values[value]; - } - - static bool containsValue(int value) => values.containsKey(value); - - static const Color Red = const Color._(1); - static const Color Green = const Color._(2); - static const Color Blue = const Color._(8); - static get values => {1: Red,2: Green,8: Blue,}; - - static const fb.Reader reader = const _ColorReader(); - - @override - String toString() { - return 'Color{value: $value}'; - } -} - -class _ColorReader extends fb.Reader { - const _ColorReader(); - - @override - int get size => 1; - - @override - Color read(fb.BufferContext bc, int offset) => - new Color.fromValue(const fb.Int8Reader().read(bc, offset)); -} - -class AnyTypeId { - final int value; - const AnyTypeId._(this.value); - - factory AnyTypeId.fromValue(int value) { - if (value == null) value = 0; - if (!values.containsKey(value)) { - throw new StateError('Invalid value $value for bit flag enum AnyTypeId'); - } - return values[value]; - } - - static const int minValue = 0; - static const int maxValue = 3; - static bool containsValue(int value) => values.containsKey(value); - - static const AnyTypeId NONE = const AnyTypeId._(0); - static const AnyTypeId Monster = const AnyTypeId._(1); - static const AnyTypeId TestSimpleTableWithEnum = const AnyTypeId._(2); - static const AnyTypeId MyGame_Example2_Monster = const AnyTypeId._(3); - static get values => {0: NONE,1: Monster,2: TestSimpleTableWithEnum,3: MyGame_Example2_Monster,}; - - static const fb.Reader reader = const _AnyTypeIdReader(); - - @override - String toString() { - return 'AnyTypeId{value: $value}'; - } -} - -class _AnyTypeIdReader extends fb.Reader { - const _AnyTypeIdReader(); - - @override - int get size => 1; - - @override - AnyTypeId read(fb.BufferContext bc, int offset) => - new AnyTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); -} - -class AnyUniqueAliasesTypeId { - final int value; - const AnyUniqueAliasesTypeId._(this.value); - - factory AnyUniqueAliasesTypeId.fromValue(int value) { - if (value == null) value = 0; - if (!values.containsKey(value)) { - throw new StateError('Invalid value $value for bit flag enum AnyUniqueAliasesTypeId'); - } - return values[value]; - } - - static const int minValue = 0; - static const int maxValue = 3; - static bool containsValue(int value) => values.containsKey(value); - - static const AnyUniqueAliasesTypeId NONE = const AnyUniqueAliasesTypeId._(0); - static const AnyUniqueAliasesTypeId M = const AnyUniqueAliasesTypeId._(1); - static const AnyUniqueAliasesTypeId T = const AnyUniqueAliasesTypeId._(2); - static const AnyUniqueAliasesTypeId M2 = const AnyUniqueAliasesTypeId._(3); - static get values => {0: NONE,1: M,2: T,3: M2,}; - - static const fb.Reader reader = const _AnyUniqueAliasesTypeIdReader(); - - @override - String toString() { - return 'AnyUniqueAliasesTypeId{value: $value}'; - } -} - -class _AnyUniqueAliasesTypeIdReader extends fb.Reader { - const _AnyUniqueAliasesTypeIdReader(); - - @override - int get size => 1; - - @override - AnyUniqueAliasesTypeId read(fb.BufferContext bc, int offset) => - new AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); -} - -class AnyAmbiguousAliasesTypeId { - final int value; - const AnyAmbiguousAliasesTypeId._(this.value); - - factory AnyAmbiguousAliasesTypeId.fromValue(int value) { - if (value == null) value = 0; - if (!values.containsKey(value)) { - throw new StateError('Invalid value $value for bit flag enum AnyAmbiguousAliasesTypeId'); - } - return values[value]; - } - - static const int minValue = 0; - static const int maxValue = 3; - static bool containsValue(int value) => values.containsKey(value); - - static const AnyAmbiguousAliasesTypeId NONE = const AnyAmbiguousAliasesTypeId._(0); - static const AnyAmbiguousAliasesTypeId M1 = const AnyAmbiguousAliasesTypeId._(1); - static const AnyAmbiguousAliasesTypeId M2 = const AnyAmbiguousAliasesTypeId._(2); - static const AnyAmbiguousAliasesTypeId M3 = const AnyAmbiguousAliasesTypeId._(3); - static get values => {0: NONE,1: M1,2: M2,3: M3,}; - - static const fb.Reader reader = const _AnyAmbiguousAliasesTypeIdReader(); - - @override - String toString() { - return 'AnyAmbiguousAliasesTypeId{value: $value}'; - } -} - -class _AnyAmbiguousAliasesTypeIdReader extends fb.Reader { - const _AnyAmbiguousAliasesTypeIdReader(); - - @override - int get size => 1; - - @override - AnyAmbiguousAliasesTypeId read(fb.BufferContext bc, int offset) => - new AnyAmbiguousAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); -} - -class Test { - Test._(this._bc, this._bcOffset); - - static const fb.Reader reader = const _TestReader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - int get a => const fb.Int16Reader().read(_bc, _bcOffset + 0); - int get b => const fb.Int8Reader().read(_bc, _bcOffset + 2); - - @override - String toString() { - return 'Test{a: $a, b: $b}'; - } -} - -class _TestReader extends fb.StructReader { - const _TestReader(); - - @override - int get size => 4; - - @override - Test createObject(fb.BufferContext bc, int offset) => - new Test._(bc, offset); -} - -class TestBuilder { - TestBuilder(this.fbBuilder) { - assert(fbBuilder != null); - } - - final fb.Builder fbBuilder; - - int finish(int a, int b) { - fbBuilder.pad(1); - fbBuilder.putInt8(b); - fbBuilder.putInt16(a); - return fbBuilder.offset; - } - -} - -class TestObjectBuilder extends fb.ObjectBuilder { - final int _a; - final int _b; - - TestObjectBuilder({ - int a, - int b, - }) - : _a = a, - _b = b; - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - - fbBuilder.pad(1); - fbBuilder.putInt8(_b); - fbBuilder.putInt16(_a); - return fbBuilder.offset; - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} -class TestSimpleTableWithEnum { - TestSimpleTableWithEnum._(this._bc, this._bcOffset); - factory TestSimpleTableWithEnum(List bytes) { - fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes); - return reader.read(rootRef, 0); - } - - static const fb.Reader reader = const _TestSimpleTableWithEnumReader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - Color get color => new Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 4, 2)); - - @override - String toString() { - return 'TestSimpleTableWithEnum{color: $color}'; - } -} - -class _TestSimpleTableWithEnumReader extends fb.TableReader { - const _TestSimpleTableWithEnumReader(); - - @override - TestSimpleTableWithEnum createObject(fb.BufferContext bc, int offset) => - new TestSimpleTableWithEnum._(bc, offset); -} - -class TestSimpleTableWithEnumBuilder { - TestSimpleTableWithEnumBuilder(this.fbBuilder) { - assert(fbBuilder != null); - } - - final fb.Builder fbBuilder; - - void begin() { - fbBuilder.startTable(); - } - - int addColor(Color color) { - fbBuilder.addInt8(0, color?.value); - return fbBuilder.offset; - } - - int finish() { - return fbBuilder.endTable(); - } -} - -class TestSimpleTableWithEnumObjectBuilder extends fb.ObjectBuilder { - final Color _color; - - TestSimpleTableWithEnumObjectBuilder({ - Color color, - }) - : _color = color; - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - - fbBuilder.startTable(); - fbBuilder.addInt8(0, _color?.value); - return fbBuilder.endTable(); - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} -class Vec3 { - Vec3._(this._bc, this._bcOffset); - - static const fb.Reader reader = const _Vec3Reader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - double get x => const fb.Float32Reader().read(_bc, _bcOffset + 0); - double get y => const fb.Float32Reader().read(_bc, _bcOffset + 4); - double get z => const fb.Float32Reader().read(_bc, _bcOffset + 8); - double get test1 => const fb.Float64Reader().read(_bc, _bcOffset + 16); - Color get test2 => new Color.fromValue(const fb.Int8Reader().read(_bc, _bcOffset + 24)); - Test get test3 => Test.reader.read(_bc, _bcOffset + 26); - - @override - String toString() { - return 'Vec3{x: $x, y: $y, z: $z, test1: $test1, test2: $test2, test3: $test3}'; - } -} - -class _Vec3Reader extends fb.StructReader { - const _Vec3Reader(); - - @override - int get size => 32; - - @override - Vec3 createObject(fb.BufferContext bc, int offset) => - new Vec3._(bc, offset); -} - -class Vec3Builder { - Vec3Builder(this.fbBuilder) { - assert(fbBuilder != null); - } - - final fb.Builder fbBuilder; - - int finish(double x, double y, double z, double test1, Color test2, fb.StructBuilder test3) { - fbBuilder.pad(2); - test3(); - fbBuilder.pad(1); - fbBuilder.putInt8(test2?.value); - fbBuilder.putFloat64(test1); - fbBuilder.pad(4); - fbBuilder.putFloat32(z); - fbBuilder.putFloat32(y); - fbBuilder.putFloat32(x); - return fbBuilder.offset; - } - -} - -class Vec3ObjectBuilder extends fb.ObjectBuilder { - final double _x; - final double _y; - final double _z; - final double _test1; - final Color _test2; - final TestObjectBuilder _test3; - - Vec3ObjectBuilder({ - double x, - double y, - double z, - double test1, - Color test2, - TestObjectBuilder test3, - }) - : _x = x, - _y = y, - _z = z, - _test1 = test1, - _test2 = test2, - _test3 = test3; - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - - fbBuilder.pad(2); - _test3.finish(fbBuilder); - fbBuilder.pad(1); - fbBuilder.putInt8(_test2?.value); - fbBuilder.putFloat64(_test1); - fbBuilder.pad(4); - fbBuilder.putFloat32(_z); - fbBuilder.putFloat32(_y); - fbBuilder.putFloat32(_x); - return fbBuilder.offset; - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} -class Ability { - Ability._(this._bc, this._bcOffset); - - static const fb.Reader reader = const _AbilityReader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - int get id => const fb.Uint32Reader().read(_bc, _bcOffset + 0); - int get distance => const fb.Uint32Reader().read(_bc, _bcOffset + 4); - - @override - String toString() { - return 'Ability{id: $id, distance: $distance}'; - } -} - -class _AbilityReader extends fb.StructReader { - const _AbilityReader(); - - @override - int get size => 8; - - @override - Ability createObject(fb.BufferContext bc, int offset) => - new Ability._(bc, offset); -} - -class AbilityBuilder { - AbilityBuilder(this.fbBuilder) { - assert(fbBuilder != null); - } - - final fb.Builder fbBuilder; - - int finish(int id, int distance) { - fbBuilder.putUint32(distance); - fbBuilder.putUint32(id); - return fbBuilder.offset; - } - -} - -class AbilityObjectBuilder extends fb.ObjectBuilder { - final int _id; - final int _distance; - - AbilityObjectBuilder({ - int id, - int distance, - }) - : _id = id, - _distance = distance; - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - - fbBuilder.putUint32(_distance); - fbBuilder.putUint32(_id); - return fbBuilder.offset; - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} -class Stat { - Stat._(this._bc, this._bcOffset); - factory Stat(List bytes) { - fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes); - return reader.read(rootRef, 0); - } - - static const fb.Reader reader = const _StatReader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - String get id => const fb.StringReader().vTableGet(_bc, _bcOffset, 4, null); - int get val => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 6, 0); - int get count => const fb.Uint16Reader().vTableGet(_bc, _bcOffset, 8, 0); - - @override - String toString() { - return 'Stat{id: $id, val: $val, count: $count}'; - } -} - -class _StatReader extends fb.TableReader { - const _StatReader(); - - @override - Stat createObject(fb.BufferContext bc, int offset) => - new Stat._(bc, offset); -} - -class StatBuilder { - StatBuilder(this.fbBuilder) { - assert(fbBuilder != null); - } - - final fb.Builder fbBuilder; - - void begin() { - fbBuilder.startTable(); - } - - int addIdOffset(int offset) { - fbBuilder.addOffset(0, offset); - return fbBuilder.offset; - } - int addVal(int val) { - fbBuilder.addInt64(1, val); - return fbBuilder.offset; - } - int addCount(int count) { - fbBuilder.addUint16(2, count); - return fbBuilder.offset; - } - - int finish() { - return fbBuilder.endTable(); - } -} - -class StatObjectBuilder extends fb.ObjectBuilder { - final String _id; - final int _val; - final int _count; - - StatObjectBuilder({ - String id, - int val, - int count, - }) - : _id = id, - _val = val, - _count = count; - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - final int idOffset = fbBuilder.writeString(_id); - - fbBuilder.startTable(); - if (idOffset != null) { - fbBuilder.addOffset(0, idOffset); - } - fbBuilder.addInt64(1, _val); - fbBuilder.addUint16(2, _count); - return fbBuilder.endTable(); - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} -class Referrable { - Referrable._(this._bc, this._bcOffset); - factory Referrable(List bytes) { - fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes); - return reader.read(rootRef, 0); - } - - static const fb.Reader reader = const _ReferrableReader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - int get id => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 4, 0); - - @override - String toString() { - return 'Referrable{id: $id}'; - } -} - -class _ReferrableReader extends fb.TableReader { - const _ReferrableReader(); - - @override - Referrable createObject(fb.BufferContext bc, int offset) => - new Referrable._(bc, offset); -} - -class ReferrableBuilder { - ReferrableBuilder(this.fbBuilder) { - assert(fbBuilder != null); - } - - final fb.Builder fbBuilder; - - void begin() { - fbBuilder.startTable(); - } - - int addId(int id) { - fbBuilder.addUint64(0, id); - return fbBuilder.offset; - } - - int finish() { - return fbBuilder.endTable(); - } -} - -class ReferrableObjectBuilder extends fb.ObjectBuilder { - final int _id; - - ReferrableObjectBuilder({ - int id, - }) - : _id = id; - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - - fbBuilder.startTable(); - fbBuilder.addUint64(0, _id); - return fbBuilder.endTable(); - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} -/// an example documentation comment: monster object -class Monster { - Monster._(this._bc, this._bcOffset); - factory Monster(List bytes) { - fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes); - return reader.read(rootRef, 0); - } - - static const fb.Reader reader = const _MonsterReader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - Vec3 get pos => Vec3.reader.vTableGet(_bc, _bcOffset, 4, null); - int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150); - int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100); - String get name => const fb.StringReader().vTableGet(_bc, _bcOffset, 10, null); - List get inventory => const fb.ListReader(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 14, null); - Color get color => new Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 8)); - AnyTypeId get testType => new AnyTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 18, 0)); - dynamic get test { - switch (testType?.value) { - case 1: return Monster.reader.vTableGet(_bc, _bcOffset, 20, null); - case 2: return TestSimpleTableWithEnum.reader.vTableGet(_bc, _bcOffset, 20, null); - case 3: return my_game_example2.Monster.reader.vTableGet(_bc, _bcOffset, 20, null); - default: return null; - } - } - List get test4 => const fb.ListReader(Test.reader).vTableGet(_bc, _bcOffset, 22, null); - List get testarrayofstring => const fb.ListReader(const fb.StringReader()).vTableGet(_bc, _bcOffset, 24, null); -/// an example documentation comment: this will end up in the generated code -/// multiline too - List get testarrayoftables => const fb.ListReader(Monster.reader).vTableGet(_bc, _bcOffset, 26, null); - Monster get enemy => Monster.reader.vTableGet(_bc, _bcOffset, 28, null); - List get testnestedflatbuffer => const fb.ListReader(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 30, null); - Stat get testempty => Stat.reader.vTableGet(_bc, _bcOffset, 32, null); - bool get testbool => const fb.BoolReader().vTableGet(_bc, _bcOffset, 34, false); - int get testhashs32Fnv1 => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 36, 0); - int get testhashu32Fnv1 => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 38, 0); - int get testhashs64Fnv1 => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 40, 0); - int get testhashu64Fnv1 => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 42, 0); - int get testhashs32Fnv1a => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 44, 0); - int get testhashu32Fnv1a => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 46, 0); - int get testhashs64Fnv1a => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 48, 0); - int get testhashu64Fnv1a => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 50, 0); - List get testarrayofbools => const fb.ListReader(const fb.BoolReader()).vTableGet(_bc, _bcOffset, 52, null); - double get testf => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 54, 3.14159); - double get testf2 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 56, 3.0); - double get testf3 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 58, 0.0); - List get testarrayofstring2 => const fb.ListReader(const fb.StringReader()).vTableGet(_bc, _bcOffset, 60, null); - List get testarrayofsortedstruct => const fb.ListReader(Ability.reader).vTableGet(_bc, _bcOffset, 62, null); - List get flex => const fb.ListReader(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 64, null); - List get test5 => const fb.ListReader(Test.reader).vTableGet(_bc, _bcOffset, 66, null); - List get vectorOfLongs => const fb.ListReader(const fb.Int64Reader()).vTableGet(_bc, _bcOffset, 68, null); - List get vectorOfDoubles => const fb.ListReader(const fb.Float64Reader()).vTableGet(_bc, _bcOffset, 70, null); - my_game.InParentNamespace get parentNamespaceTest => my_game.InParentNamespace.reader.vTableGet(_bc, _bcOffset, 72, null); - List get vectorOfReferrables => const fb.ListReader(Referrable.reader).vTableGet(_bc, _bcOffset, 74, null); - int get singleWeakReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 76, 0); - List get vectorOfWeakReferences => const fb.ListReader(const fb.Uint64Reader()).vTableGet(_bc, _bcOffset, 78, null); - List get vectorOfStrongReferrables => const fb.ListReader(Referrable.reader).vTableGet(_bc, _bcOffset, 80, null); - int get coOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 82, 0); - List get vectorOfCoOwningReferences => const fb.ListReader(const fb.Uint64Reader()).vTableGet(_bc, _bcOffset, 84, null); - int get nonOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 86, 0); - List get vectorOfNonOwningReferences => const fb.ListReader(const fb.Uint64Reader()).vTableGet(_bc, _bcOffset, 88, null); - AnyUniqueAliasesTypeId get anyUniqueType => new AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 90, 0)); - dynamic get anyUnique { - switch (anyUniqueType?.value) { - case 1: return M.reader.vTableGet(_bc, _bcOffset, 92, null); - case 2: return T.reader.vTableGet(_bc, _bcOffset, 92, null); - case 3: return M2.reader.vTableGet(_bc, _bcOffset, 92, null); - default: return null; - } - } - AnyAmbiguousAliasesTypeId get anyAmbiguousType => new AnyAmbiguousAliasesTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 94, 0)); - dynamic get anyAmbiguous { - switch (anyAmbiguousType?.value) { - case 1: return M1.reader.vTableGet(_bc, _bcOffset, 96, null); - case 2: return M2.reader.vTableGet(_bc, _bcOffset, 96, null); - case 3: return M3.reader.vTableGet(_bc, _bcOffset, 96, null); - default: return null; - } - } - List get vectorOfEnums => const fb.ListReader(Color.reader).vTableGet(_bc, _bcOffset, 98, null); - - @override - String toString() { - return 'Monster{pos: $pos, mana: $mana, hp: $hp, name: $name, inventory: $inventory, color: $color, testType: $testType, test: $test, test4: $test4, testarrayofstring: $testarrayofstring, testarrayoftables: $testarrayoftables, enemy: $enemy, testnestedflatbuffer: $testnestedflatbuffer, testempty: $testempty, testbool: $testbool, testhashs32Fnv1: $testhashs32Fnv1, testhashu32Fnv1: $testhashu32Fnv1, testhashs64Fnv1: $testhashs64Fnv1, testhashu64Fnv1: $testhashu64Fnv1, testhashs32Fnv1a: $testhashs32Fnv1a, testhashu32Fnv1a: $testhashu32Fnv1a, testhashs64Fnv1a: $testhashs64Fnv1a, testhashu64Fnv1a: $testhashu64Fnv1a, testarrayofbools: $testarrayofbools, testf: $testf, testf2: $testf2, testf3: $testf3, testarrayofstring2: $testarrayofstring2, testarrayofsortedstruct: $testarrayofsortedstruct, flex: $flex, test5: $test5, vectorOfLongs: $vectorOfLongs, vectorOfDoubles: $vectorOfDoubles, parentNamespaceTest: $parentNamespaceTest, vectorOfReferrables: $vectorOfReferrables, singleWeakReference: $singleWeakReference, vectorOfWeakReferences: $vectorOfWeakReferences, vectorOfStrongReferrables: $vectorOfStrongReferrables, coOwningReference: $coOwningReference, vectorOfCoOwningReferences: $vectorOfCoOwningReferences, nonOwningReference: $nonOwningReference, vectorOfNonOwningReferences: $vectorOfNonOwningReferences, anyUniqueType: $anyUniqueType, anyUnique: $anyUnique, anyAmbiguousType: $anyAmbiguousType, anyAmbiguous: $anyAmbiguous, vectorOfEnums: $vectorOfEnums}'; - } -} - -class _MonsterReader extends fb.TableReader { - const _MonsterReader(); - - @override - Monster createObject(fb.BufferContext bc, int offset) => - new Monster._(bc, offset); -} - -class MonsterBuilder { - MonsterBuilder(this.fbBuilder) { - assert(fbBuilder != null); - } - - final fb.Builder fbBuilder; - - void begin() { - fbBuilder.startTable(); - } - - int addPos(int offset) { - fbBuilder.addStruct(0, offset); - return fbBuilder.offset; - } - int addMana(int mana) { - fbBuilder.addInt16(1, mana); - return fbBuilder.offset; - } - int addHp(int hp) { - fbBuilder.addInt16(2, hp); - return fbBuilder.offset; - } - int addNameOffset(int offset) { - fbBuilder.addOffset(3, offset); - return fbBuilder.offset; - } - int addInventoryOffset(int offset) { - fbBuilder.addOffset(5, offset); - return fbBuilder.offset; - } - int addColor(Color color) { - fbBuilder.addInt8(6, color?.value); - return fbBuilder.offset; - } - int addTestType(AnyTypeId testType) { - fbBuilder.addUint8(7, testType?.value); - return fbBuilder.offset; - } - int addTestOffset(int offset) { - fbBuilder.addOffset(8, offset); - return fbBuilder.offset; - } - int addTest4Offset(int offset) { - fbBuilder.addOffset(9, offset); - return fbBuilder.offset; - } - int addTestarrayofstringOffset(int offset) { - fbBuilder.addOffset(10, offset); - return fbBuilder.offset; - } - int addTestarrayoftablesOffset(int offset) { - fbBuilder.addOffset(11, offset); - return fbBuilder.offset; - } - int addEnemyOffset(int offset) { - fbBuilder.addOffset(12, offset); - return fbBuilder.offset; - } - int addTestnestedflatbufferOffset(int offset) { - fbBuilder.addOffset(13, offset); - return fbBuilder.offset; - } - int addTestemptyOffset(int offset) { - fbBuilder.addOffset(14, offset); - return fbBuilder.offset; - } - int addTestbool(bool testbool) { - fbBuilder.addBool(15, testbool); - return fbBuilder.offset; - } - int addTesthashs32Fnv1(int testhashs32Fnv1) { - fbBuilder.addInt32(16, testhashs32Fnv1); - return fbBuilder.offset; - } - int addTesthashu32Fnv1(int testhashu32Fnv1) { - fbBuilder.addUint32(17, testhashu32Fnv1); - return fbBuilder.offset; - } - int addTesthashs64Fnv1(int testhashs64Fnv1) { - fbBuilder.addInt64(18, testhashs64Fnv1); - return fbBuilder.offset; - } - int addTesthashu64Fnv1(int testhashu64Fnv1) { - fbBuilder.addUint64(19, testhashu64Fnv1); - return fbBuilder.offset; - } - int addTesthashs32Fnv1a(int testhashs32Fnv1a) { - fbBuilder.addInt32(20, testhashs32Fnv1a); - return fbBuilder.offset; - } - int addTesthashu32Fnv1a(int testhashu32Fnv1a) { - fbBuilder.addUint32(21, testhashu32Fnv1a); - return fbBuilder.offset; - } - int addTesthashs64Fnv1a(int testhashs64Fnv1a) { - fbBuilder.addInt64(22, testhashs64Fnv1a); - return fbBuilder.offset; - } - int addTesthashu64Fnv1a(int testhashu64Fnv1a) { - fbBuilder.addUint64(23, testhashu64Fnv1a); - return fbBuilder.offset; - } - int addTestarrayofboolsOffset(int offset) { - fbBuilder.addOffset(24, offset); - return fbBuilder.offset; - } - int addTestf(double testf) { - fbBuilder.addFloat32(25, testf); - return fbBuilder.offset; - } - int addTestf2(double testf2) { - fbBuilder.addFloat32(26, testf2); - return fbBuilder.offset; - } - int addTestf3(double testf3) { - fbBuilder.addFloat32(27, testf3); - return fbBuilder.offset; - } - int addTestarrayofstring2Offset(int offset) { - fbBuilder.addOffset(28, offset); - return fbBuilder.offset; - } - int addTestarrayofsortedstructOffset(int offset) { - fbBuilder.addOffset(29, offset); - return fbBuilder.offset; - } - int addFlexOffset(int offset) { - fbBuilder.addOffset(30, offset); - return fbBuilder.offset; - } - int addTest5Offset(int offset) { - fbBuilder.addOffset(31, offset); - return fbBuilder.offset; - } - int addVectorOfLongsOffset(int offset) { - fbBuilder.addOffset(32, offset); - return fbBuilder.offset; - } - int addVectorOfDoublesOffset(int offset) { - fbBuilder.addOffset(33, offset); - return fbBuilder.offset; - } - int addParentNamespaceTestOffset(int offset) { - fbBuilder.addOffset(34, offset); - return fbBuilder.offset; - } - int addVectorOfReferrablesOffset(int offset) { - fbBuilder.addOffset(35, offset); - return fbBuilder.offset; - } - int addSingleWeakReference(int singleWeakReference) { - fbBuilder.addUint64(36, singleWeakReference); - return fbBuilder.offset; - } - int addVectorOfWeakReferencesOffset(int offset) { - fbBuilder.addOffset(37, offset); - return fbBuilder.offset; - } - int addVectorOfStrongReferrablesOffset(int offset) { - fbBuilder.addOffset(38, offset); - return fbBuilder.offset; - } - int addCoOwningReference(int coOwningReference) { - fbBuilder.addUint64(39, coOwningReference); - return fbBuilder.offset; - } - int addVectorOfCoOwningReferencesOffset(int offset) { - fbBuilder.addOffset(40, offset); - return fbBuilder.offset; - } - int addNonOwningReference(int nonOwningReference) { - fbBuilder.addUint64(41, nonOwningReference); - return fbBuilder.offset; - } - int addVectorOfNonOwningReferencesOffset(int offset) { - fbBuilder.addOffset(42, offset); - return fbBuilder.offset; - } - int addAnyUniqueType(AnyUniqueAliasesTypeId anyUniqueType) { - fbBuilder.addUint8(43, anyUniqueType?.value); - return fbBuilder.offset; - } - int addAnyUniqueOffset(int offset) { - fbBuilder.addOffset(44, offset); - return fbBuilder.offset; - } - int addAnyAmbiguousType(AnyAmbiguousAliasesTypeId anyAmbiguousType) { - fbBuilder.addUint8(45, anyAmbiguousType?.value); - return fbBuilder.offset; - } - int addAnyAmbiguousOffset(int offset) { - fbBuilder.addOffset(46, offset); - return fbBuilder.offset; - } - int addVectorOfEnumsOffset(int offset) { - fbBuilder.addOffset(47, offset); - return fbBuilder.offset; - } - - int finish() { - return fbBuilder.endTable(); - } -} - -class MonsterObjectBuilder extends fb.ObjectBuilder { - final Vec3ObjectBuilder _pos; - final int _mana; - final int _hp; - final String _name; - final List _inventory; - final Color _color; - final AnyTypeId _testType; - final dynamic _test; - final List _test4; - final List _testarrayofstring; - final List _testarrayoftables; - final MonsterObjectBuilder _enemy; - final List _testnestedflatbuffer; - final StatObjectBuilder _testempty; - final bool _testbool; - final int _testhashs32Fnv1; - final int _testhashu32Fnv1; - final int _testhashs64Fnv1; - final int _testhashu64Fnv1; - final int _testhashs32Fnv1a; - final int _testhashu32Fnv1a; - final int _testhashs64Fnv1a; - final int _testhashu64Fnv1a; - final List _testarrayofbools; - final double _testf; - final double _testf2; - final double _testf3; - final List _testarrayofstring2; - final List _testarrayofsortedstruct; - final List _flex; - final List _test5; - final List _vectorOfLongs; - final List _vectorOfDoubles; - final my_game.InParentNamespaceObjectBuilder _parentNamespaceTest; - final List _vectorOfReferrables; - final int _singleWeakReference; - final List _vectorOfWeakReferences; - final List _vectorOfStrongReferrables; - final int _coOwningReference; - final List _vectorOfCoOwningReferences; - final int _nonOwningReference; - final List _vectorOfNonOwningReferences; - final AnyUniqueAliasesTypeId _anyUniqueType; - final dynamic _anyUnique; - final AnyAmbiguousAliasesTypeId _anyAmbiguousType; - final dynamic _anyAmbiguous; - final List _vectorOfEnums; - - MonsterObjectBuilder({ - Vec3ObjectBuilder pos, - int mana, - int hp, - String name, - List inventory, - Color color, - AnyTypeId testType, - dynamic test, - List test4, - List testarrayofstring, - List testarrayoftables, - MonsterObjectBuilder enemy, - List testnestedflatbuffer, - StatObjectBuilder testempty, - bool testbool, - int testhashs32Fnv1, - int testhashu32Fnv1, - int testhashs64Fnv1, - int testhashu64Fnv1, - int testhashs32Fnv1a, - int testhashu32Fnv1a, - int testhashs64Fnv1a, - int testhashu64Fnv1a, - List testarrayofbools, - double testf, - double testf2, - double testf3, - List testarrayofstring2, - List testarrayofsortedstruct, - List flex, - List test5, - List vectorOfLongs, - List vectorOfDoubles, - my_game.InParentNamespaceObjectBuilder parentNamespaceTest, - List vectorOfReferrables, - int singleWeakReference, - List vectorOfWeakReferences, - List vectorOfStrongReferrables, - int coOwningReference, - List vectorOfCoOwningReferences, - int nonOwningReference, - List vectorOfNonOwningReferences, - AnyUniqueAliasesTypeId anyUniqueType, - dynamic anyUnique, - AnyAmbiguousAliasesTypeId anyAmbiguousType, - dynamic anyAmbiguous, - List vectorOfEnums, - }) - : _pos = pos, - _mana = mana, - _hp = hp, - _name = name, - _inventory = inventory, - _color = color, - _testType = testType, - _test = test, - _test4 = test4, - _testarrayofstring = testarrayofstring, - _testarrayoftables = testarrayoftables, - _enemy = enemy, - _testnestedflatbuffer = testnestedflatbuffer, - _testempty = testempty, - _testbool = testbool, - _testhashs32Fnv1 = testhashs32Fnv1, - _testhashu32Fnv1 = testhashu32Fnv1, - _testhashs64Fnv1 = testhashs64Fnv1, - _testhashu64Fnv1 = testhashu64Fnv1, - _testhashs32Fnv1a = testhashs32Fnv1a, - _testhashu32Fnv1a = testhashu32Fnv1a, - _testhashs64Fnv1a = testhashs64Fnv1a, - _testhashu64Fnv1a = testhashu64Fnv1a, - _testarrayofbools = testarrayofbools, - _testf = testf, - _testf2 = testf2, - _testf3 = testf3, - _testarrayofstring2 = testarrayofstring2, - _testarrayofsortedstruct = testarrayofsortedstruct, - _flex = flex, - _test5 = test5, - _vectorOfLongs = vectorOfLongs, - _vectorOfDoubles = vectorOfDoubles, - _parentNamespaceTest = parentNamespaceTest, - _vectorOfReferrables = vectorOfReferrables, - _singleWeakReference = singleWeakReference, - _vectorOfWeakReferences = vectorOfWeakReferences, - _vectorOfStrongReferrables = vectorOfStrongReferrables, - _coOwningReference = coOwningReference, - _vectorOfCoOwningReferences = vectorOfCoOwningReferences, - _nonOwningReference = nonOwningReference, - _vectorOfNonOwningReferences = vectorOfNonOwningReferences, - _anyUniqueType = anyUniqueType, - _anyUnique = anyUnique, - _anyAmbiguousType = anyAmbiguousType, - _anyAmbiguous = anyAmbiguous, - _vectorOfEnums = vectorOfEnums; - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - final int nameOffset = fbBuilder.writeString(_name); - final int inventoryOffset = _inventory?.isNotEmpty == true - ? fbBuilder.writeListUint8(_inventory) - : null; - final int testOffset = _test?.getOrCreateOffset(fbBuilder); - final int test4Offset = _test4?.isNotEmpty == true - ? fbBuilder.writeListOfStructs(_test4) - : null; - final int testarrayofstringOffset = _testarrayofstring?.isNotEmpty == true - ? fbBuilder.writeList(_testarrayofstring.map((b) => fbBuilder.writeString(b)).toList()) - : null; - final int testarrayoftablesOffset = _testarrayoftables?.isNotEmpty == true - ? fbBuilder.writeList(_testarrayoftables.map((b) => b.getOrCreateOffset(fbBuilder)).toList()) - : null; - final int enemyOffset = _enemy?.getOrCreateOffset(fbBuilder); - final int testnestedflatbufferOffset = _testnestedflatbuffer?.isNotEmpty == true - ? fbBuilder.writeListUint8(_testnestedflatbuffer) - : null; - final int testemptyOffset = _testempty?.getOrCreateOffset(fbBuilder); - final int testarrayofboolsOffset = _testarrayofbools?.isNotEmpty == true - ? fbBuilder.writeListBool(_testarrayofbools) - : null; - final int testarrayofstring2Offset = _testarrayofstring2?.isNotEmpty == true - ? fbBuilder.writeList(_testarrayofstring2.map((b) => fbBuilder.writeString(b)).toList()) - : null; - final int testarrayofsortedstructOffset = _testarrayofsortedstruct?.isNotEmpty == true - ? fbBuilder.writeListOfStructs(_testarrayofsortedstruct) - : null; - final int flexOffset = _flex?.isNotEmpty == true - ? fbBuilder.writeListUint8(_flex) - : null; - final int test5Offset = _test5?.isNotEmpty == true - ? fbBuilder.writeListOfStructs(_test5) - : null; - final int vectorOfLongsOffset = _vectorOfLongs?.isNotEmpty == true - ? fbBuilder.writeListInt64(_vectorOfLongs) - : null; - final int vectorOfDoublesOffset = _vectorOfDoubles?.isNotEmpty == true - ? fbBuilder.writeListFloat64(_vectorOfDoubles) - : null; - final int parentNamespaceTestOffset = _parentNamespaceTest?.getOrCreateOffset(fbBuilder); - final int vectorOfReferrablesOffset = _vectorOfReferrables?.isNotEmpty == true - ? fbBuilder.writeList(_vectorOfReferrables.map((b) => b.getOrCreateOffset(fbBuilder)).toList()) - : null; - final int vectorOfWeakReferencesOffset = _vectorOfWeakReferences?.isNotEmpty == true - ? fbBuilder.writeListUint64(_vectorOfWeakReferences) - : null; - final int vectorOfStrongReferrablesOffset = _vectorOfStrongReferrables?.isNotEmpty == true - ? fbBuilder.writeList(_vectorOfStrongReferrables.map((b) => b.getOrCreateOffset(fbBuilder)).toList()) - : null; - final int vectorOfCoOwningReferencesOffset = _vectorOfCoOwningReferences?.isNotEmpty == true - ? fbBuilder.writeListUint64(_vectorOfCoOwningReferences) - : null; - final int vectorOfNonOwningReferencesOffset = _vectorOfNonOwningReferences?.isNotEmpty == true - ? fbBuilder.writeListUint64(_vectorOfNonOwningReferences) - : null; - final int anyUniqueOffset = _anyUnique?.getOrCreateOffset(fbBuilder); - final int anyAmbiguousOffset = _anyAmbiguous?.getOrCreateOffset(fbBuilder); - final int vectorOfEnumsOffset = _vectorOfEnums?.isNotEmpty == true - ? fbBuilder.writeListInt8(_vectorOfEnums.map((f) => f.value)) - : null; - - fbBuilder.startTable(); - if (_pos != null) { - fbBuilder.addStruct(0, _pos.finish(fbBuilder)); - } - fbBuilder.addInt16(1, _mana); - fbBuilder.addInt16(2, _hp); - if (nameOffset != null) { - fbBuilder.addOffset(3, nameOffset); - } - if (inventoryOffset != null) { - fbBuilder.addOffset(5, inventoryOffset); - } - fbBuilder.addInt8(6, _color?.value); - fbBuilder.addUint8(7, _testType?.value); - if (testOffset != null) { - fbBuilder.addOffset(8, testOffset); - } - if (test4Offset != null) { - fbBuilder.addOffset(9, test4Offset); - } - if (testarrayofstringOffset != null) { - fbBuilder.addOffset(10, testarrayofstringOffset); - } - if (testarrayoftablesOffset != null) { - fbBuilder.addOffset(11, testarrayoftablesOffset); - } - if (enemyOffset != null) { - fbBuilder.addOffset(12, enemyOffset); - } - if (testnestedflatbufferOffset != null) { - fbBuilder.addOffset(13, testnestedflatbufferOffset); - } - if (testemptyOffset != null) { - fbBuilder.addOffset(14, testemptyOffset); - } - fbBuilder.addBool(15, _testbool); - fbBuilder.addInt32(16, _testhashs32Fnv1); - fbBuilder.addUint32(17, _testhashu32Fnv1); - fbBuilder.addInt64(18, _testhashs64Fnv1); - fbBuilder.addUint64(19, _testhashu64Fnv1); - fbBuilder.addInt32(20, _testhashs32Fnv1a); - fbBuilder.addUint32(21, _testhashu32Fnv1a); - fbBuilder.addInt64(22, _testhashs64Fnv1a); - fbBuilder.addUint64(23, _testhashu64Fnv1a); - if (testarrayofboolsOffset != null) { - fbBuilder.addOffset(24, testarrayofboolsOffset); - } - fbBuilder.addFloat32(25, _testf); - fbBuilder.addFloat32(26, _testf2); - fbBuilder.addFloat32(27, _testf3); - if (testarrayofstring2Offset != null) { - fbBuilder.addOffset(28, testarrayofstring2Offset); - } - if (testarrayofsortedstructOffset != null) { - fbBuilder.addOffset(29, testarrayofsortedstructOffset); - } - if (flexOffset != null) { - fbBuilder.addOffset(30, flexOffset); - } - if (test5Offset != null) { - fbBuilder.addOffset(31, test5Offset); - } - if (vectorOfLongsOffset != null) { - fbBuilder.addOffset(32, vectorOfLongsOffset); - } - if (vectorOfDoublesOffset != null) { - fbBuilder.addOffset(33, vectorOfDoublesOffset); - } - if (parentNamespaceTestOffset != null) { - fbBuilder.addOffset(34, parentNamespaceTestOffset); - } - if (vectorOfReferrablesOffset != null) { - fbBuilder.addOffset(35, vectorOfReferrablesOffset); - } - fbBuilder.addUint64(36, _singleWeakReference); - if (vectorOfWeakReferencesOffset != null) { - fbBuilder.addOffset(37, vectorOfWeakReferencesOffset); - } - if (vectorOfStrongReferrablesOffset != null) { - fbBuilder.addOffset(38, vectorOfStrongReferrablesOffset); - } - fbBuilder.addUint64(39, _coOwningReference); - if (vectorOfCoOwningReferencesOffset != null) { - fbBuilder.addOffset(40, vectorOfCoOwningReferencesOffset); - } - fbBuilder.addUint64(41, _nonOwningReference); - if (vectorOfNonOwningReferencesOffset != null) { - fbBuilder.addOffset(42, vectorOfNonOwningReferencesOffset); - } - fbBuilder.addUint8(43, _anyUniqueType?.value); - if (anyUniqueOffset != null) { - fbBuilder.addOffset(44, anyUniqueOffset); - } - fbBuilder.addUint8(45, _anyAmbiguousType?.value); - if (anyAmbiguousOffset != null) { - fbBuilder.addOffset(46, anyAmbiguousOffset); - } - if (vectorOfEnumsOffset != null) { - fbBuilder.addOffset(47, vectorOfEnumsOffset); - } - return fbBuilder.endTable(); - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} -class TypeAliases { - TypeAliases._(this._bc, this._bcOffset); - factory TypeAliases(List bytes) { - fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes); - return reader.read(rootRef, 0); - } - - static const fb.Reader reader = const _TypeAliasesReader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - int get i8 => const fb.Int8Reader().vTableGet(_bc, _bcOffset, 4, 0); - int get u8 => const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 6, 0); - int get i16 => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 0); - int get u16 => const fb.Uint16Reader().vTableGet(_bc, _bcOffset, 10, 0); - int get i32 => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 12, 0); - int get u32 => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 14, 0); - int get i64 => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 16, 0); - int get u64 => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 18, 0); - double get f32 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 20, 0.0); - double get f64 => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 22, 0.0); - List get v8 => const fb.ListReader(const fb.Int8Reader()).vTableGet(_bc, _bcOffset, 24, null); - List get vf64 => const fb.ListReader(const fb.Float64Reader()).vTableGet(_bc, _bcOffset, 26, null); - - @override - String toString() { - return 'TypeAliases{i8: $i8, u8: $u8, i16: $i16, u16: $u16, i32: $i32, u32: $u32, i64: $i64, u64: $u64, f32: $f32, f64: $f64, v8: $v8, vf64: $vf64}'; - } -} - -class _TypeAliasesReader extends fb.TableReader { - const _TypeAliasesReader(); - - @override - TypeAliases createObject(fb.BufferContext bc, int offset) => - new TypeAliases._(bc, offset); -} - -class TypeAliasesBuilder { - TypeAliasesBuilder(this.fbBuilder) { - assert(fbBuilder != null); - } - - final fb.Builder fbBuilder; - - void begin() { - fbBuilder.startTable(); - } - - int addI8(int i8) { - fbBuilder.addInt8(0, i8); - return fbBuilder.offset; - } - int addU8(int u8) { - fbBuilder.addUint8(1, u8); - return fbBuilder.offset; - } - int addI16(int i16) { - fbBuilder.addInt16(2, i16); - return fbBuilder.offset; - } - int addU16(int u16) { - fbBuilder.addUint16(3, u16); - return fbBuilder.offset; - } - int addI32(int i32) { - fbBuilder.addInt32(4, i32); - return fbBuilder.offset; - } - int addU32(int u32) { - fbBuilder.addUint32(5, u32); - return fbBuilder.offset; - } - int addI64(int i64) { - fbBuilder.addInt64(6, i64); - return fbBuilder.offset; - } - int addU64(int u64) { - fbBuilder.addUint64(7, u64); - return fbBuilder.offset; - } - int addF32(double f32) { - fbBuilder.addFloat32(8, f32); - return fbBuilder.offset; - } - int addF64(double f64) { - fbBuilder.addFloat64(9, f64); - return fbBuilder.offset; - } - int addV8Offset(int offset) { - fbBuilder.addOffset(10, offset); - return fbBuilder.offset; - } - int addVf64Offset(int offset) { - fbBuilder.addOffset(11, offset); - return fbBuilder.offset; - } - - int finish() { - return fbBuilder.endTable(); - } -} - -class TypeAliasesObjectBuilder extends fb.ObjectBuilder { - final int _i8; - final int _u8; - final int _i16; - final int _u16; - final int _i32; - final int _u32; - final int _i64; - final int _u64; - final double _f32; - final double _f64; - final List _v8; - final List _vf64; - - TypeAliasesObjectBuilder({ - int i8, - int u8, - int i16, - int u16, - int i32, - int u32, - int i64, - int u64, - double f32, - double f64, - List v8, - List vf64, - }) - : _i8 = i8, - _u8 = u8, - _i16 = i16, - _u16 = u16, - _i32 = i32, - _u32 = u32, - _i64 = i64, - _u64 = u64, - _f32 = f32, - _f64 = f64, - _v8 = v8, - _vf64 = vf64; - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - final int v8Offset = _v8?.isNotEmpty == true - ? fbBuilder.writeListInt8(_v8) - : null; - final int vf64Offset = _vf64?.isNotEmpty == true - ? fbBuilder.writeListFloat64(_vf64) - : null; - - fbBuilder.startTable(); - fbBuilder.addInt8(0, _i8); - fbBuilder.addUint8(1, _u8); - fbBuilder.addInt16(2, _i16); - fbBuilder.addUint16(3, _u16); - fbBuilder.addInt32(4, _i32); - fbBuilder.addUint32(5, _u32); - fbBuilder.addInt64(6, _i64); - fbBuilder.addUint64(7, _u64); - fbBuilder.addFloat32(8, _f32); - fbBuilder.addFloat64(9, _f64); - if (v8Offset != null) { - fbBuilder.addOffset(10, v8Offset); - } - if (vf64Offset != null) { - fbBuilder.addOffset(11, vf64Offset); - } - return fbBuilder.endTable(); - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} diff --git a/third_party/flatbuffers/dart/test/monster_test_my_game_generated.dart b/third_party/flatbuffers/dart/test/monster_test_my_game_generated.dart deleted file mode 100644 index 26bb73bb38b..00000000000 --- a/third_party/flatbuffers/dart/test/monster_test_my_game_generated.dart +++ /dev/null @@ -1,62 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// ignore_for_file: unused_import, unused_field, unused_local_variable - -library my_game; - -import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; - -import 'include_test1_my_game_generated.dart'; -import 'include_test2_my_game_generated.dart'; -import './monster_test_my_game.example_generated.dart' as my_game_example; -import './monster_test_my_game.example2_generated.dart' as my_game_example2; - -class InParentNamespace { - InParentNamespace._(this._bc, this._bcOffset); - factory InParentNamespace(List bytes) { - fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes); - return reader.read(rootRef, 0); - } - - static const fb.Reader reader = const _InParentNamespaceReader(); - - final fb.BufferContext _bc; - final int _bcOffset; - - - @override - String toString() { - return 'InParentNamespace{}'; - } -} - -class _InParentNamespaceReader extends fb.TableReader { - const _InParentNamespaceReader(); - - @override - InParentNamespace createObject(fb.BufferContext bc, int offset) => - new InParentNamespace._(bc, offset); -} - -class InParentNamespaceObjectBuilder extends fb.ObjectBuilder { - - InParentNamespaceObjectBuilder(); - - /// Finish building, and store into the [fbBuilder]. - @override - int finish( - fb.Builder fbBuilder) { - assert(fbBuilder != null); - - fbBuilder.startTable(); - return fbBuilder.endTable(); - } - - /// Convenience method to serialize to byte list. - @override - Uint8List toBytes([String fileIdentifier]) { - fb.Builder fbBuilder = new fb.Builder(); - int offset = finish(fbBuilder); - return fbBuilder.finish(offset, fileIdentifier); - } -} diff --git a/third_party/flatbuffers/docs/footer.html b/third_party/flatbuffers/docs/footer.html deleted file mode 100644 index 42bc5f2b903..00000000000 --- a/third_party/flatbuffers/docs/footer.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - diff --git a/third_party/flatbuffers/docs/header.html b/third_party/flatbuffers/docs/header.html deleted file mode 100644 index 0266e7c4f30..00000000000 --- a/third_party/flatbuffers/docs/header.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - -$projectname: $title -$title - - - -$treeview -$search -$mathjax - - -$extrastylesheet - - -
- - -
-
- - - - - - - - - - - - - - - - - - - - - -
-
$projectname -  $projectnumber -
-
- An open source project by FPL. -
-
$projectbrief
-
-
$projectbrief
-
$searchbox
- - - diff --git a/third_party/flatbuffers/docs/images/ftv2mnode.png b/third_party/flatbuffers/docs/images/ftv2mnode.png deleted file mode 100644 index 3caf47df8ad..00000000000 Binary files a/third_party/flatbuffers/docs/images/ftv2mnode.png and /dev/null differ diff --git a/third_party/flatbuffers/docs/images/ftv2pnode.png b/third_party/flatbuffers/docs/images/ftv2pnode.png deleted file mode 100644 index f1aaad3786e..00000000000 Binary files a/third_party/flatbuffers/docs/images/ftv2pnode.png and /dev/null differ diff --git a/third_party/flatbuffers/docs/source/Benchmarks.md b/third_party/flatbuffers/docs/source/Benchmarks.md deleted file mode 100644 index 848f4e39b5c..00000000000 --- a/third_party/flatbuffers/docs/source/Benchmarks.md +++ /dev/null @@ -1,63 +0,0 @@ -C++ Benchmarks {#flatbuffers_benchmarks} -========== - -Comparing against other serialization solutions, running on Windows 7 -64bit. We use the LITE runtime for Protocol Buffers (less code / lower -overhead), Rapid JSON (one of the fastest C++ JSON parsers around), -and pugixml, also one of the fastest XML parsers. - -We also compare against code that doesn't use a serialization library -at all (the column "Raw structs"), which is what you get if you write -hardcoded code that just writes structs. This is the fastest possible, -but of course is not cross platform nor has any kind of forwards / -backwards compatibility. - -We compare against Flatbuffers with the binary wire format (as -intended), and also with JSON as the wire format with the optional JSON -parser (which, using a schema, parses JSON into a binary buffer that can -then be accessed as before). - -The benchmark object is a set of about 10 objects containing an array, 4 -strings, and a large variety of int/float scalar values of all sizes, -meant to be representative of game data, e.g. a scene format. - -| | FlatBuffers (binary) | Protocol Buffers LITE | Rapid JSON | FlatBuffers (JSON) | pugixml | Raw structs | -|--------------------------------------------------------|-----------------------|-----------------------|-----------------------|------------------------| ----------------------| ----------------------| -| Decode + Traverse + Dealloc (1 million times, seconds) | 0.08 | 302 | 583 | 105 | 196 | 0.02 | -| Decode / Traverse / Dealloc (breakdown) | 0 / 0.08 / 0 | 220 / 0.15 / 81 | 294 / 0.9 / 287 | 70 / 0.08 / 35 | 41 / 3.9 / 150 | 0 / 0.02 / 0 | -| Encode (1 million times, seconds) | 3.2 | 185 | 650 | 169 | 273 | 0.15 | -| Wire format size (normal / zlib, bytes) | 344 / 220 | 228 / 174 | 1475 / 322 | 1029 / 298 | 1137 / 341 | 312 / 187 | -| Memory needed to store decoded wire (bytes / blocks) | 0 / 0 | 760 / 20 | 65689 / 4 | 328 / 1 | 34194 / 3 | 0 / 0 | -| Transient memory allocated during decode (KB) | 0 | 1 | 131 | 4 | 34 | 0 | -| Generated source code size (KB) | 4 | 61 | 0 | 4 | 0 | 0 | -| Field access in handwritten traversal code | typed accessors | typed accessors | manual error checking | typed accessors | manual error checking | typed but no safety | -| Library source code (KB) | 15 | some subset of 3800 | 87 | 43 | 327 | 0 | - -### Some other serialization systems we compared against but did not benchmark (yet), in rough order of applicability: - -- Cap'n'Proto promises to reduce Protocol Buffers much like FlatBuffers does, - though with a more complicated binary encoding and less flexibility (no - optional fields to allow deprecating fields or serializing with missing - fields for which defaults exist). - It currently also isn't fully cross-platform portable (lack of VS support). -- msgpack: has very minimal forwards/backwards compatibility support when used - with the typed C++ interface. Also lacks VS2010 support. -- Thrift: very similar to Protocol Buffers, but appears to be less efficient, - and have more dependencies. -- YAML: a superset of JSON and otherwise very similar. Used by e.g. Unity. -- C# comes with built-in serialization functionality, as used by Unity also. - Being tied to the language, and having no automatic versioning support - limits its applicability. -- Project Anarchy (the free mobile engine by Havok) comes with a serialization - system, that however does no automatic versioning (have to code around new - fields manually), is very much tied to the rest of the engine, and works - without a schema to generate code (tied to your C++ class definition). - -### Code for benchmarks - -Code for these benchmarks sits in `benchmarks/` in git branch `benchmarks`. -It sits in its own branch because it has submodule dependencies that the main -project doesn't need, and the code standards do not meet those of the main -project. Please read `benchmarks/cpp/README.txt` before working with the code. - -
diff --git a/third_party/flatbuffers/docs/source/Building.md b/third_party/flatbuffers/docs/source/Building.md deleted file mode 100644 index a89671109c3..00000000000 --- a/third_party/flatbuffers/docs/source/Building.md +++ /dev/null @@ -1,100 +0,0 @@ -Building {#flatbuffers_guide_building} -======== - -## Building with CMake - -The distribution comes with a `cmake` file that should allow -you to build project/make files for any platform. For details on `cmake`, see -. In brief, depending on your platform, use one of -e.g.: - - cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release - cmake -G "Visual Studio 10" -DCMAKE_BUILD_TYPE=Release - cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release - -Then, build as normal for your platform. This should result in a `flatc` -executable, essential for the next steps. -Note that to use clang instead of gcc, you may need to set up your environment -variables, e.g. -`CC=/usr/bin/clang CXX=/usr/bin/clang++ cmake -G "Unix Makefiles"`. - -Optionally, run the `flattests` executable from the root `flatbuffers/` -directory to ensure everything is working correctly on your system. If this -fails, please contact us! - -Building should also produce two sample executables, `flatsamplebinary` and -`flatsampletext`, see the corresponding `.cpp` files in the -`flatbuffers/samples` directory. - -*Note that you MUST be in the root of the FlatBuffers distribution when you -run 'flattests' or `flatsampletext`, or it will fail to load its files.* - -## Building for Android - -There is a `flatbuffers/android` directory that contains all you need to build -the test executable on android (use the included `build_apk.sh` script, or use -`ndk_build` / `adb` etc. as usual). Upon running, it will output to the log -if tests succeeded or not. - -You may also run an android sample from inside the `flatbuffers/samples`, by -running the `android_sample.sh` script. Optionally, you may go to the -`flatbuffers/samples/android` folder and build the sample with the -`build_apk.sh` script or `ndk_build` / `adb` etc. - -## Using FlatBuffers in your own projects - -For C++, there is usually no runtime to compile, as the code consists of a -single header, `include/flatbuffers/flatbuffers.h`. You should add the -`include` folder to your include paths. If you wish to be -able to load schemas and/or parse text into binary buffers at runtime, -you additionally need the other headers in `include/flatbuffers`. You must -also compile/link `src/idl_parser.cpp` (and `src/idl_gen_text.cpp` if you -also want to be able convert binary to text). - -To see how to include FlatBuffers in any of our supported languages, please -view the [Tutorial](@ref flatbuffers_guide_tutorial) and select your appropriate -language using the radio buttons. - -### Using in CMake-based projects -If you want to use FlatBuffers in a project which already uses CMake, then a more -robust and flexible approach is to build FlatBuffers as part of that project directly. -This is done by making the FlatBuffers source code available to the main build -and adding it using CMake's `add_subdirectory()` command. This has the -significant advantage that the same compiler and linker settings are used -between FlatBuffers and the rest of your project, so issues associated with using -incompatible libraries (eg debug/release), etc. are avoided. This is -particularly useful on Windows. - -Suppose you put FlatBuffers source code in directory `${FLATBUFFERS_SRC_DIR}`. -To build it as part of your project, add following code to your `CMakeLists.txt` file: -```cmake -# Add FlatBuffers directly to our build. This defines the `flatbuffers` target. -add_subdirectory(${FLATBUFFERS_SRC_DIR} - ${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-build - EXCLUDE_FROM_ALL) - -# Now simply link against flatbuffers as needed to your already declared target. -# The flatbuffers target carry header search path automatically if CMake > 2.8.11. -target_link_libraries(own_project_target PRIVATE flatbuffers) -``` -When build your project the `flatbuffers` library will be compiled and linked -to a target as part of your project. - -#### Override default depth limit of nested objects -To override [the depth limit of recursion](@ref flatbuffers_guide_use_cpp), -add this directive: -```cmake -set(FLATBUFFERS_MAX_PARSING_DEPTH 16) -``` -to `CMakeLists.txt` file before `add_subdirectory(${FLATBUFFERS_SRC_DIR})` line. - -#### For Google Play apps - -For applications on Google Play that integrate this library, usage is tracked. -This tracking is done automatically using the embedded version string -(flatbuffer_version_string), and helps us continue to optimize it. -Aside from consuming a few extra bytes in your application binary, it shouldn't -affect your application at all. We use this information to let us know if -FlatBuffers is useful and if we should continue to invest in it. Since this is -open source, you are free to remove the version string but we would appreciate -if you would leave it in. diff --git a/third_party/flatbuffers/docs/source/CONTRIBUTING.md b/third_party/flatbuffers/docs/source/CONTRIBUTING.md deleted file mode 120000 index f939e75f21a..00000000000 --- a/third_party/flatbuffers/docs/source/CONTRIBUTING.md +++ /dev/null @@ -1 +0,0 @@ -../../CONTRIBUTING.md \ No newline at end of file diff --git a/third_party/flatbuffers/docs/source/CUsage.md b/third_party/flatbuffers/docs/source/CUsage.md deleted file mode 100644 index 9aafa6f775e..00000000000 --- a/third_party/flatbuffers/docs/source/CUsage.md +++ /dev/null @@ -1,224 +0,0 @@ -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: - -
-~~~{.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); - } -~~~ -
- -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: - -
-
-~~~{.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)); -~~~ -
- - -## 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. - -
-~~~{.c} - int hp_present = ns(Monster_hp_is_present(monster)); // 1 - int mana_present = ns(Monster_mana_is_present(monster)); // 0 -~~~ -
- -## 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. - -
-~~~{.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)); -~~~ -
- -## 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. - - diff --git a/third_party/flatbuffers/docs/source/Compiler.md b/third_party/flatbuffers/docs/source/Compiler.md deleted file mode 100644 index 7889abdc207..00000000000 --- a/third_party/flatbuffers/docs/source/Compiler.md +++ /dev/null @@ -1,207 +0,0 @@ -Using the schema compiler {#flatbuffers_guide_using_schema_compiler} -========================= - -Usage: - - flatc [ GENERATOR OPTIONS ] [ -o PATH ] [ -I PATH ] FILES... - [ -- FILES...] - -The files are read and parsed in order, and can contain either schemas -or data (see below). Data files are processed according to the definitions of -the most recent schema specified. - -`--` indicates that the following files are binary files in -FlatBuffer format conforming to the schema indicated before it. - -Depending on the flags passed, additional files may -be generated for each file processed: - -For any schema input files, one or more generators can be specified: - -- `--cpp`, `-c` : Generate a C++ header for all definitions in this file (as - `filename_generated.h`). - -- `--java`, `-j` : Generate Java code. - -- `--kotlin`, `-k` : Generate Kotlin code. - -- `--csharp`, `-n` : Generate C# code. - -- `--go`, `-g` : Generate Go code. - -- `--python`, `-p`: Generate Python code. - -- `--js`, `-s`: Generate JavaScript code. - -- `--ts`: Generate TypeScript code. - -- `--php`: Generate PHP code. - -- `--grpc`: Generate RPC stub code for GRPC. - -- `--dart`: Generate Dart code. - -- `--lua`: Generate Lua code. - -- `--lobster`: Generate Lobster code. - -- `--rust`, `-r` : Generate Rust code. - -For any data input files: - -- `--binary`, `-b` : If data is contained in this file, generate a - `filename.bin` containing the binary flatbuffer (or a different extension - if one is specified in the schema). - -- `--json`, `-t` : If data is contained in this file, generate a - `filename.json` representing the data in the flatbuffer. - -Additional options: - -- `-o PATH` : Output all generated files to PATH (either absolute, or - relative to the current directory). If omitted, PATH will be the - current directory. PATH should end in your systems path separator, - e.g. `/` or `\`. - -- `-I PATH` : when encountering `include` statements, attempt to load the - files from this path. Paths will be tried in the order given, and if all - fail (or none are specified) it will try to load relative to the path of - the schema file being parsed. - -- `-M` : Print make rules for generated files. - -- `--strict-json` : Require & generate strict JSON (field names are enclosed - in quotes, no trailing commas in tables/vectors). By default, no quotes are - required/generated, and trailing commas are allowed. - -- `--allow-non-utf8` : Pass non-UTF-8 input through parser and emit nonstandard - \x escapes in JSON. (Default is to raise parse error on non-UTF-8 input.) - -- `--natural-utf8` : Output strings with UTF-8 as human-readable strings. - By default, UTF-8 characters are printed as \uXXXX escapes." - -- `--defaults-json` : Output fields whose value is equal to the default value - when writing JSON text. - -- `--no-prefix` : Don't prefix enum values in generated C++ by their enum - type. - -- `--scoped-enums` : Use C++11 style scoped and strongly typed enums in - generated C++. This also implies `--no-prefix`. - -- `--gen-includes` : (deprecated), this is the default behavior. - If the original behavior is required (no include - statements) use `--no-includes.` - -- `--no-includes` : Don't generate include statements for included schemas the - generated file depends on (C++). - -- `--gen-mutable` : Generate additional non-const accessors for mutating - FlatBuffers in-place. - -- `--gen-onefile` : Generate single output file for C# and Go. - -- `--gen-name-strings` : Generate type name functions for C++. - -- `--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-compare` : Generate operator== for object-based API types. - -- `--gen-nullable` : Add Clang _Nullable for C++ pointer. or @Nullable for Java. - -- `--gen-generated` : Add @Generated annotation for Java. - -- `--gen-all` : Generate not just code for the current schema files, but - for all files it includes as well. If the language uses a single file for - output (by default the case for C++ and JS), all code will end up in - this one file. - -- `--cpp-include` : Adds an #include in generated file - -- `--cpp-ptr-type T` : Set object API pointer type (default std::unique_ptr) - -- `--cpp-str-type T` : Set object API string type (default std::string) - T::c_str(), T::length() and T::empty() must be supported. - The custom type also needs to be constructible from std::string (see the - --cpp-str-flex-ctor option to change this behavior). - -- `--cpp-str-flex-ctor` : Don't construct custom string types by passing - std::string from Flatbuffers, but (char* + length). This allows efficient - construction of custom string types, including zero-copy construction. - -- `--object-prefix` : Customise class prefix for C++ object-based API. - -- `--object-suffix` : Customise class suffix for C++ object-based API. - -- `--no-js-exports` : Removes Node.js style export lines (useful for JS) - -- `--goog-js-export` : Uses goog.exportsSymbol and goog.exportsProperty - instead of Node.js style exporting. Needed for compatibility with the - Google closure compiler (useful for JS). - -- `--es6-js-export` : Generates ECMAScript v6 style export definitions - instead of Node.js style exporting. Useful when integrating flatbuffers - with modern Javascript projects. - -- `--go-namespace` : Generate the overrided namespace in Golang. - -- `--go-import` : Generate the overrided import for flatbuffers in Golang. - (default is "github.com/google/flatbuffers/go"). - -- `--raw-binary` : Allow binaries without a file_indentifier to be read. - This may crash flatc given a mismatched schema. - -- `--size-prefixed` : Input binaries are size prefixed buffers. - -- `--proto`: Expect input files to be .proto files (protocol buffers). - Output the corresponding .fbs file. - Currently supports: `package`, `message`, `enum`, nested declarations, - `import` (use `-I` for paths), `extend`, `oneof`, `group`. - Does not support, but will skip without error: `option`, `service`, - `extensions`, and most everything else. - -- `--oneof-union` : Translate .proto oneofs to flatbuffer unions. - -- `--grpc` : Generate GRPC interfaces for the specified languages. - -- `--schema`: Serialize schemas instead of JSON (use with -b). This will - output a binary version of the specified schema that itself corresponds - to the reflection/reflection.fbs schema. Loading this binary file is the - basis for reflection functionality. - -- `--bfbs-comments`: Add doc comments to the binary schema files. - -- `--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. - -- `--conform-includes PATH` : Include path for the schema given with - `--conform PATH`. - -- `--include-prefix PATH` : Prefix this path to any generated include - statements. - -- `--keep-prefix` : Keep original prefix of schema include statement. - -- `--no-fb-impor` : Don't include flatbuffers import statement for TypeScript. - -- `--no-ts-reexpor` : Don't re-export imported dependencies for TypeScript. - -- `--short-name` : Use short function names for JS and TypeScript. - -- `--reflect-types` : Add minimal type reflection to code generation. - -- `--reflect-names` : Add minimal type/name reflection. - -- `--root-type T` : Select or override the default root_type. - -- `--force-defaults` : Emit default values in binary output from JSON. - -- `--force-empty` : When serializing from object API representation, force - strings and vectors to empty rather than null. - -NOTE: short-form options for generators are deprecated, use the long form -whenever possible. diff --git a/third_party/flatbuffers/docs/source/CppUsage.md b/third_party/flatbuffers/docs/source/CppUsage.md deleted file mode 100644 index 7867f4be48c..00000000000 --- a/third_party/flatbuffers/docs/source/CppUsage.md +++ /dev/null @@ -1,608 +0,0 @@ -Use in C++ {#flatbuffers_guide_use_cpp} -========== - -## Before you get started - -Before diving into the FlatBuffers usage in C++, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide -to general FlatBuffers usage in all of the supported languages (including C++). -This page is designed to cover the nuances of FlatBuffers usage, specific to -C++. - -#### Prerequisites - -This page assumes you have written a FlatBuffers schema and compiled it -with the Schema Compiler. If you have not, please see -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) -and [Writing a schema](@ref flatbuffers_guide_writing_schema). - -Assuming you wrote a schema, say `mygame.fbs` (though the extension doesn't -matter), you've generated a C++ header called `mygame_generated.h` using the -compiler (e.g. `flatc -c mygame.fbs`), you can now start using this in -your program by including the header. As noted, this header relies on -`flatbuffers/flatbuffers.h`, which should be in your include path. - -## FlatBuffers C++ library code location - -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). - -## Testing the FlatBuffers C++ library - -The code to test the C++ library can be found at `flatbuffers/tests`. -The test code itself is located in -[test.cpp](https://github.com/google/flatbuffers/blob/master/tests/test.cpp). - -This test file is built alongside `flatc`. To review how to build the project, -please read the [Building](@ref flatbuffers_guide_building) documentation. - -To run the tests, execute `flattests` from the root `flatbuffers/` directory. -For example, on [Linux](https://en.wikipedia.org/wiki/Linux), you would simply -run: `./flattests`. - -## Using the FlatBuffers C++ library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in C++.* - -FlatBuffers supports both reading and writing FlatBuffers in C++. - -To use FlatBuffers in your code, first generate the C++ classes from your -schema with the `--cpp` option to `flatc`. Then you can include both FlatBuffers -and the generated code to read or write FlatBuffers. - -For example, here is how you would read a FlatBuffer binary file in C++: -First, include the library and generated code. Then read the file into -a `char *` array, which you pass to `GetMonster()`. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} - #include "flatbuffers/flatbuffers.h" - #include "monster_test_generate.h" - #include // C++ header file for printing - #include // C++ header file for file access - - - std::ifstream infile; - infile.open("monsterdata_test.mon", std::ios::binary | std::ios::in); - infile.seekg(0,std::ios::end); - int length = infile.tellg(); - infile.seekg(0,std::ios::beg); - char *data = new char[length]; - infile.read(data, length); - infile.close(); - - auto monster = GetMonster(data); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -`monster` is of type `Monster *`, and points to somewhere *inside* your -buffer (root object pointers are not the same as `buffer_pointer` !). -If you look in your generated header, you'll see it has -convenient accessors for all fields, e.g. `hp()`, `mana()`, etc: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} - std::cout << "hp : " << monster->hp() << std::endl; // `80` - std::cout << "mana : " << monster->mana() << std::endl; // default value of `150` - std::cout << "name : " << monster->name()->c_str() << std::endl; // "MyMonster" -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -*Note: That we never stored a `mana` value, so it will return the default.* - -The following attributes are supported: - -- `shared` (on a field): For string fields, this enables the usage of string - pooling (i.e. `CreateSharedString`) as default serialization behavior. - - Specifically, `CreateXxxDirect` functions and `Pack` functions for object - based API (see below) will use `CreateSharedString` to create strings. - -## Object based API. {#flatbuffers_cpp_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} - // Autogenerated class from table Monster. - MonsterT monsterobj; - - // Deserialize from buffer into object. - UnPackTo(&monsterobj, flatbuffer); - - // Update object directly like a C++ class instance. - cout << monsterobj->name; // This is now a std::string! - monsterobj->name = "Bob"; // Change the name. - - // Serialize into new flatbuffer. - FlatBufferBuilder fbb; - Pack(fbb, &monsterobj); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following attributes are specific to the object-based API code generation: - -- `native_inline` (on a field): Because FlatBuffer tables and structs are - optionally present in a given buffer, they are best represented as pointers - (specifically std::unique_ptrs) in the native class since they can be null. - This attribute changes the member declaration to use the type directly - rather than wrapped in a unique_ptr. - -- `native_default`: "value" (on a field): For members that are declared - "native_inline", the value specified with this attribute will be included - verbatim in the class constructor initializer list for this member. - -- `native_custom_alloc`:"custom_allocator" (on a table or struct): When using the - object-based API all generated NativeTables that are allocated when unpacking - your flatbuffer will use "custom allocator". The allocator is also used by - any std::vector that appears in a table defined with `native_custom_alloc`. - This can be used to provide allocation from a pool for example, for faster - unpacking when using the object-based API. - - Minimal Example: - - schema: - - table mytable(native_custom_alloc:"custom_allocator") { - ... - } - - with custom_allocator defined before flatbuffers.h is included, as: - - template struct custom_allocator : public std::allocator { - - typedef T *pointer; - - template - struct rebind { - typedef custom_allocator other; - }; - - pointer allocate(const std::size_t n) { - return std::allocator::allocate(n); - } - - void deallocate(T* ptr, std::size_t n) { - return std::allocator::deallocate(ptr,n); - } - - custom_allocator() throw() {} - template - custom_allocator(const custom_allocator&) throw() {} - }; - -- `native_type`' "type" (on a struct): In some cases, a more optimal C++ data - type exists for a given struct. For example, the following schema: - - struct Vec2 { - x: float; - y: float; - } - - generates the following Object-Based API class: - - struct Vec2T : flatbuffers::NativeTable { - float x; - float y; - }; - - However, it can be useful to instead use a user-defined C++ type since it - can provide more functionality, eg. - - struct vector2 { - float x = 0, y = 0; - vector2 operator+(vector2 rhs) const { ... } - vector2 operator-(vector2 rhs) const { ... } - float length() const { ... } - // etc. - }; - - The `native_type` attribute will replace the usage of the generated class - with the given type. So, continuing with the example, the generated - code would use |vector2| in place of |Vec2T| for all generated code. - - However, becuase the native_type is unknown to flatbuffers, the user must - provide the following functions to aide in the serialization process: - - namespace flatbuffers { - FlatbufferStruct Pack(const native_type& obj); - native_type UnPack(const FlatbufferStruct& obj); - } - -Finally, the following top-level attribute - -- `native_include`: "path" (at file level): Because the `native_type` attribute - can be used to introduce types that are unknown to flatbuffers, it may be - necessary to include "external" header files in the generated code. This - attribute can be used to directly add an #include directive to the top of - the generated code that includes the specified path directly. - -- `force_align`: this attribute may not be respected in the object API, - depending on the aligned of the allocator used with `new`. - -# External references. - -An additional feature of the object API is the ability to allow you to load -multiple independent FlatBuffers, and have them refer to eachothers objects -using hashes which are then represented as typed pointers in the object API. - -To make this work have a field in the objects you want to referred to which is -using the string hashing feature (see `hash` attribute in the -[schema](@ref flatbuffers_guide_writing_schema) documentation). Then you have -a similar hash in the field referring to it, along with a `cpp_type` -attribute specifying the C++ type this will refer to (this can be any C++ -type, and will get a `*` added). - -Then, in JSON or however you create these buffers, make sure they use the -same string (or hash). - -When you call `UnPack` (or `Create`), you'll need a function that maps from -hash to the object (see `resolver_function_t` for details). - -# Using different pointer types. - -By default the object tree is built out of `std::unique_ptr`, but you can -influence this either globally (using the `--cpp-ptr-type` argument to -`flatc`) or per field (using the `cpp_ptr_type` attribute) to by any smart -pointer type (`my_ptr`), or by specifying `naked` as the type to get `T *` -pointers. Unlike the smart pointers, naked pointers do not manage memory for -you, so you'll have to manage their lifecycles manually. To reference the -pointer type specified by the `--cpp-ptr-type` argument to `flatc` from a -flatbuffer field set the `cpp_ptr_type` attribute to `default_ptr_type`. - -# Using different string type. - -By default the object tree is built out of `std::string`, but you can -influence this either globally (using the `--cpp-str-type` argument to -`flatc`) or per field using the `cpp_str_type` attribute. - -The type must support T::c_str(), T::length() and T::empty() as member functions. - -Further, the type must be constructible from std::string, as by default a -std::string instance is constructed and then used to initialize the custom -string type. This behavior impedes efficient and zero-copy construction of -custom string types; the `--cpp-str-flex-ctor` argument to `flatc` or the -per field attribute `cpp_str_flex_ctor` can be used to change this behavior, -so that the custom string type is constructed by passing the pointer and -length of the FlatBuffers String. The custom string class will require a -constructor in the following format: custom_str_class(const char *, size_t). -Please note that the character array is not guaranteed to be NULL terminated, -you should always use the provided size to determine end of string. - -## Reflection (& Resizing) - -There is experimental support for reflection in FlatBuffers, allowing you to -read and write data even if you don't know the exact format of a buffer, and -even allows you to change sizes of strings and vectors in-place. - -The way this works is very elegant; there is actually a FlatBuffer schema that -describes schemas (!) which you can find in `reflection/reflection.fbs`. -The compiler, `flatc`, can write out any schemas it has just parsed as a binary -FlatBuffer, corresponding to this meta-schema. - -Loading in one of these binary schemas at runtime allows you traverse any -FlatBuffer data that corresponds to it without knowing the exact format. You -can query what fields are present, and then read/write them after. - -For convenient field manipulation, you can include the header -`flatbuffers/reflection.h` which includes both the generated code from the meta -schema, as well as a lot of helper functions. - -And example of usage, for the time being, can be found in -`test.cpp/ReflectionTest()`. - -## Mini Reflection - -A more limited form of reflection is available for direct inclusion in -generated code, which doesn't any (binary) schema access at all. It was designed -to keep the overhead of reflection as low as possible (on the order of 2-6 -bytes per field added to your executable), but doesn't contain all the -information the (binary) schema contains. - -You add this information to your generated code by specifying `--reflect-types` -(or instead `--reflect-names` if you also want field / enum names). - -You can now use this information, for example to print a FlatBuffer to text: - - auto s = flatbuffers::FlatBufferToString(flatbuf, MonsterTypeTable()); - -`MonsterTypeTable()` is declared in the generated code for each type. The -string produced is very similar to the JSON produced by the `Parser` based -text generator. - -You'll need `flatbuffers/minireflect.h` for this functionality. In there is also -a convenient visitor/iterator so you can write your own output / functionality -based on the mini reflection tables without having to know the FlatBuffers or -reflection encoding. - -## Storing maps / dictionaries in a FlatBuffer - -FlatBuffers doesn't support maps natively, but there is support to -emulate their behavior with vectors and binary search, which means you -can have fast lookups directly from a FlatBuffer without having to unpack -your data into a `std::map` or similar. - -To use it: -- Designate one of the fields in a table as they "key" field. You do this - by setting the `key` attribute on this field, e.g. - `name:string (key)`. - You may only have one key field, and it must be of string or scalar type. -- Write out tables of this type as usual, collect their offsets in an - array or vector. -- Instead of `CreateVector`, call `CreateVectorOfSortedTables`, - which will first sort all offsets such that the tables they refer to - are sorted by the key field, then serialize it. -- Now when you're accessing the FlatBuffer, you can use `Vector::LookupByKey` - instead of just `Vector::Get` to access elements of the vector, e.g.: - `myvector->LookupByKey("Fred")`, which returns a pointer to the - corresponding table type, or `nullptr` if not found. - `LookupByKey` performs a binary search, so should have a similar speed to - `std::map`, though may be faster because of better caching. `LookupByKey` - only works if the vector has been sorted, it will likely not find elements - if it hasn't been sorted. - -## Direct memory access - -As you can see from the above examples, all elements in a buffer are -accessed through generated accessors. This is because everything is -stored in little endian format on all platforms (the accessor -performs a swap operation on big endian machines), and also because -the layout of things is generally not known to the user. - -For structs, layout is deterministic and guaranteed to be the same -across platforms (scalars are aligned to their -own size, and structs themselves to their largest member), and you -are allowed to access this memory directly by using `sizeof()` and -`memcpy` on the pointer to a struct, or even an array of structs. - -To compute offsets to sub-elements of a struct, make sure they -are a structs themselves, as then you can use the pointers to -figure out the offset without having to hardcode it. This is -handy for use of arrays of structs with calls like `glVertexAttribPointer` -in OpenGL or similar APIs. - -It is important to note is that structs are still little endian on all -machines, so only use tricks like this if you can guarantee you're not -shipping on a big endian machine (an `assert(FLATBUFFERS_LITTLEENDIAN)` -would be wise). - -## Access of untrusted buffers - -The generated accessor functions access fields over offsets, which is -very quick. These offsets are not verified at run-time, so a malformed -buffer could cause a program to crash by accessing random memory. - -When you're processing large amounts of data from a source you know (e.g. -your own generated data on disk), this is acceptable, but when reading -data from the network that can potentially have been modified by an -attacker, this is undesirable. - -For this reason, you can optionally use a buffer verifier before you -access the data. This verifier will check all offsets, all sizes of -fields, and null termination of strings to ensure that when a buffer -is accessed, all reads will end up inside the buffer. - -Each root type will have a verification function generated for it, -e.g. for `Monster`, you can call: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} - bool ok = VerifyMonsterBuffer(Verifier(buf, len)); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -if `ok` is true, the buffer is safe to read. - -Besides untrusted data, this function may be useful to call in debug -mode, as extra insurance against data being corrupted somewhere along -the way. - -While verifying a buffer isn't "free", it is typically faster than -a full traversal (since any scalar data is not actually touched), -and since it may cause the buffer to be brought into cache before -reading, the actual overhead may be even lower than expected. - -In specialized cases where a denial of service attack is possible, -the verifier has two additional constructor arguments that allow -you to limit the nesting depth and total amount of tables the -verifier may encounter before declaring the buffer malformed. The default is -`Verifier(buf, len, 64 /* max depth */, 1000000, /* max tables */)` which -should be sufficient for most uses. - -## Text & schema parsing - -Using binary buffers with the generated header provides a super low -overhead use of FlatBuffer data. There are, however, times when you want -to use text formats, for example because it interacts better with source -control, or you want to give your users easy access to data. - -Another reason might be that you already have a lot of data in JSON -format, or a tool that generates JSON, and if you can write a schema for -it, this will provide you an easy way to use that data directly. - -(see the schema documentation for some specifics on the JSON format -accepted). - -There are two ways to use text formats: - -#### Using the compiler as a conversion tool - -This is the preferred path, as it doesn't require you to add any new -code to your program, and is maximally efficient since you can ship with -binary data. The disadvantage is that it is an extra step for your -users/developers to perform, though you might be able to automate it. - - flatc -b myschema.fbs mydata.json - -This will generate the binary file `mydata_wire.bin` which can be loaded -as before. - -#### Making your program capable of loading text directly - -This gives you maximum flexibility. You could even opt to support both, -i.e. check for both files, and regenerate the binary from text when -required, otherwise just load the binary. - -This option is currently only available for C++, or Java through JNI. - -As mentioned in the section "Building" above, this technique requires -you to link a few more files into your program, and you'll want to include -`flatbuffers/idl.h`. - -Load text (either a schema or json) into an in-memory buffer (there is a -convenient `LoadFile()` utility function in `flatbuffers/util.h` if you -wish). Construct a parser: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} - flatbuffers::Parser parser; -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can parse any number of text files in sequence: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} - parser.Parse(text_file.c_str()); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This works similarly to how the command-line compiler works: a sequence -of files parsed by the same `Parser` object allow later files to -reference definitions in earlier files. Typically this means you first -load a schema file (which populates `Parser` with definitions), followed -by one or more JSON files. - -As optional argument to `Parse`, you may specify a null-terminated list of -include paths. If not specified, any include statements try to resolve from -the current directory. - -If there were any parsing errors, `Parse` will return `false`, and -`Parser::err` contains a human readable error string with a line number -etc, which you should present to the creator of that file. - -After each JSON file, the `Parser::fbb` member variable is the -`FlatBufferBuilder` that contains the binary buffer version of that -file, that you can access as described above. - -`samples/sample_text.cpp` is a code sample showing the above operations. - -## Threading - -Reading a FlatBuffer does not touch any memory outside the original buffer, -and is entirely read-only (all const), so is safe to access from multiple -threads even without synchronisation primitives. - -Creating a FlatBuffer is not thread safe. All state related to building -a FlatBuffer is contained in a FlatBufferBuilder instance, and no memory -outside of it is touched. To make this thread safe, either do not -share instances of FlatBufferBuilder between threads (recommended), or -manually wrap it in synchronisation primites. There's no automatic way to -accomplish this, by design, as we feel multithreaded construction -of a single buffer will be rare, and synchronisation overhead would be costly. - -## Advanced union features - -The C++ implementation currently supports vectors of unions (i.e. you can -declare a field as `[T]` where `T` is a union type instead of a table type). It -also supports structs and strings in unions, besides tables. - -For an example of these features, see `tests/union_vector`, and -`UnionVectorTest` in `test.cpp`. - -Since these features haven't been ported to other languages yet, if you -choose to use them, you won't be able to use these buffers in other languages -(`flatc` will refuse to compile a schema that uses these features). - -These features reduce the amount of "table wrapping" that was previously -needed to use unions. - -To use scalars, simply wrap them in a struct. - -## Depth limit of nested objects and stack-overflow control -The parser of Flatbuffers schema or json-files is kind of recursive parser. -To avoid stack-overflow problem the parser has a built-in limiter of -recursion depth. Number of nested declarations in a schema or number of -nested json-objects is limited. By default, this depth limit set to `64`. -It is possible to override this limit with `FLATBUFFERS_MAX_PARSING_DEPTH` -definition. This definition can be helpful for testing purposes or embedded -applications. For details see [build](@ref flatbuffers_guide_building) of -CMake-based projects. - -## Dependence from C-locale {#flatbuffers_locale_cpp} -The Flatbuffers [grammar](@ref flatbuffers grammar) uses ASCII -character set for identifiers, alphanumeric literals, reserved words. - -Internal implementation of the Flatbuffers depends from functions which -depend from C-locale: `strtod()` or `strtof()`, for example. -The library expects the dot `.` symbol as the separator of an integer -part from the fractional part of a float number. -Another separator symbols (`,` for example) will break the compatibility -and may lead to an error while parsing a Flatbuffers schema or a json file. - -The Standard C locale is a global resource, there is only one locale for -the entire application. Some modern compilers and platforms have -locale-independent or locale-narrow functions `strtof_l`, `strtod_l`, -`strtoll_l`, `strtoull_l` to resolve this dependency. -These functions use specified locale rather than the global or per-thread -locale instead. They are part of POSIX-2008 but not part of the C/C++ -standard library, therefore, may be missing on some platforms. -The Flatbuffers library try to detect these functions at configuration and -compile time: -- CMake `"CMakeLists.txt"`: - - Check existence of `strtol_l` and `strtod_l` in the ``. -- Compile-time `"/include/base.h"`: - - `_MSC_VER >= 1900`: MSVC2012 or higher if build with MSVC. - - `_XOPEN_SOURCE>=700`: POSIX-2008 if build with GCC/Clang. - -After detection, the definition `FLATBUFFERS_LOCALE_INDEPENDENT` will be -set to `0` or `1`. -To override or stop this detection use CMake `-DFLATBUFFERS_LOCALE_INDEPENDENT={0|1}` -or predefine `FLATBUFFERS_LOCALE_INDEPENDENT` symbol. - -To test the compatibility of the Flatbuffers library with -a specific locale use the environment variable `FLATBUFFERS_TEST_LOCALE`: -```sh ->FLATBUFFERS_TEST_LOCALE="" ./flattests ->FLATBUFFERS_TEST_LOCALE="ru_RU.CP1251" ./flattests -``` - -## Support of floating-point numbers -The Flatbuffers library assumes that a C++ compiler and a CPU are -compatible with the `IEEE-754` floating-point standard. -The schema and json parser may fail if `fast-math` or `/fp:fast` mode is active. - -### Support of hexadecimal and special floating-point numbers -According to the [grammar](@ref flatbuffers_grammar) `fbs` and `json` files -may use hexadecimal and special (`NaN`, `Inf`) floating-point literals. -The Flatbuffers uses `strtof` and `strtod` functions to parse floating-point -literals. The Flatbuffers library has a code to detect a compiler compatibility -with the literals. If necessary conditions are met the preprocessor constant -`FLATBUFFERS_HAS_NEW_STRTOD` will be set to `1`. -The support of floating-point literals will be limited at compile time -if `FLATBUFFERS_HAS_NEW_STRTOD` constant is less than `1`. -In this case, schemas with hexadecimal or special literals cannot be used. - -### Comparison of floating-point NaN values -The floating-point `NaN` (`not a number`) is special value which -representing an undefined or unrepresentable value. -`NaN` may be explicitly assigned to variables, typically as a representation -for missing values or may be a result of a mathematical operation. -The `IEEE-754` defines two kind of `NaNs`: -- Quiet NaNs, or `qNaNs`. -- Signaling NaNs, or `sNaNs`. - -According to the `IEEE-754`, a comparison with `NaN` always returns -an unordered result even when compared with itself. As a result, a whole -Flatbuffers object will be not equal to itself if has one or more `NaN`. -Flatbuffers scalar fields that have the default value are not actually stored -in the serialized data but are generated in code (see [Writing a schema](@ref flatbuffers_guide_writing_schema)). -Scalar fields with `NaN` defaults break this behavior. -If a schema has a lot of `NaN` defaults the Flatbuffers can override -the unordered comparison by the ordered: `(NaN==NaN)->true`. -This ordered comparison is enabled when compiling a program with the symbol -`FLATBUFFERS_NAN_DEFAULTS` defined. -Additional computations added by `FLATBUFFERS_NAN_DEFAULTS` are very cheap -if GCC or Clang used. These compilers have a compile-time implementation -of `isnan` checking which MSVC does not. - -
diff --git a/third_party/flatbuffers/docs/source/DartUsage.md b/third_party/flatbuffers/docs/source/DartUsage.md deleted file mode 100644 index 6670cc59d01..00000000000 --- a/third_party/flatbuffers/docs/source/DartUsage.md +++ /dev/null @@ -1,108 +0,0 @@ -Use in Dart {#flatbuffers_guide_use_dart} -=========== - -## Before you get started - -Before diving into the FlatBuffers usage in Dart, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide -to general FlatBuffers usage in all of the supported languages (including Dart). -This page is designed to cover the nuances of FlatBuffers usage, specific to -Dart. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Dart library code location - -The code for the FlatBuffers Dart library can be found at -`flatbuffers/dart`. You can browse the library code on the [FlatBuffers -GitHub page](https://github.com/google/flatbuffers/tree/master/dart). - -## Testing the FlatBuffers Dart library - -The code to test the Dart library can be found at `flatbuffers/tests`. -The test code itself is located in [dart_test.dart](https://github.com/google/ -flatbuffers/blob/master/tests/dart_test.dart). - -To run the tests, use the [DartTest.sh](https://github.com/google/flatbuffers/ -blob/master/tests/DartTest.sh) shell script. - -*Note: The shell script requires the [Dart SDK](https://www.dartlang.org/tools/sdk) -to be installed.* - -## Using the FlatBuffers Dart library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Dart.* - -FlatBuffers supports reading and writing binary FlatBuffers in Dart. - -To use FlatBuffers in your own code, first generate Dart classes from your -schema with the `--dart` option to `flatc`. Then you can include both FlatBuffers -and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Dart: First, -include the library and generated code. Then read a FlatBuffer binary file into -a `List`, which you pass to the factory constructor for `Monster`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.dart} -import 'dart:io' as io; - -import 'package:flat_buffers/flat_buffers.dart' as fb; -import './monster_my_game.sample_generated.dart' as myGame; - -List data = await new io.File('monster.dat').readAsBytes(); -var monster = new myGame.Monster(data); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access values like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.dart} -var hp = monster.hp; -var pos = monster.pos; -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -## Differences from the Dart SDK Front End flat_buffers - -The work in this repository is signfiicantly based on the implementation used -internally by the Dart SDK in the front end/analyzer package. Several -significant changes have been made. - -1. Support for packed boolean lists has been removed. This is not standard - in other implementations and is not compatible with them. Do note that, - like in the JavaScript implementation, __null values in boolean lists - will be treated as false__. It is also still entirely possible to pack data - in a single scalar field, but that would have to be done on the application - side. -2. The SDK implementation supports enums with regular Dart enums, which - works if enums are always indexed at 1; however, FlatBuffers does not - require that. This implementation uses specialized enum-like classes to - ensure proper mapping from FlatBuffers to Dart and other platforms. -3. The SDK implementation does not appear to support FlatBuffer structs or - vectors of structs - it treated everything as a built-in scalar or a table. - This implementation treats structs in a way that is compatible with other - non-Dart implementations, and properly handles vectors of structs. Many of - the methods prefixed with 'low' have been prepurposed to support this. -4. The SDK implementation treats int64 and uint64 as float64s. This - implementation does not. This may cause problems with JavaScript - compatibility - however, it should be possible to use the JavaScript - implementation, or to do a customized implementation that treats all 64 bit - numbers as floats. Supporting the Dart VM and Flutter was a more important - goal of this implementation. Support for 16 bit integers was also added. -5. The code generation in this offers an "ObjectBuilder", which generates code - very similar to the SDK classes that consume FlatBuffers, as well as Builder - classes, which produces code which more closely resembles the builders in - other languages. The ObjectBuilder classes are easier to use, at the cost of - additional references allocated. - -## Text Parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from Dart, though you could use the C++ parser through Dart Native Extensions. -Please see the C++ documentation for more on text parsing (note that this is -not currently an option in Flutter - follow [this issue](https://github.com/flutter/flutter/issues/7053) -for the latest). - -
diff --git a/third_party/flatbuffers/docs/source/FlatBuffers.md b/third_party/flatbuffers/docs/source/FlatBuffers.md deleted file mode 100644 index dc77500de11..00000000000 --- a/third_party/flatbuffers/docs/source/FlatBuffers.md +++ /dev/null @@ -1,180 +0,0 @@ -FlatBuffers {#flatbuffers_index} -=========== - -# Overview {#flatbuffers_overview} - -[FlatBuffers](@ref flatbuffers_overview) is an efficient cross platform -serialization library for C++, C#, C, Go, Java, Kotlin, JavaScript, Lobster, Lua, TypeScript, PHP, Python, and Rust. -It was originally created at Google for game development and other -performance-critical applications. - -It is available as Open Source on [GitHub](http://github.com/google/flatbuffers) -under the Apache license, v2 (see LICENSE.txt). - -## Why use FlatBuffers? - -- **Access to serialized data without parsing/unpacking** - What sets - FlatBuffers apart is that it represents hierarchical data in a flat - binary buffer in such a way that it can still be accessed directly - without parsing/unpacking, while also still supporting data - structure evolution (forwards/backwards compatibility). - -- **Memory efficiency and speed** - The only memory needed to access - your data is that of the buffer. It requires 0 additional allocations - (in C++, other languages may vary). FlatBuffers is also very - suitable for use with mmap (or streaming), requiring only part of the - buffer to be in memory. Access is close to the speed of raw - struct access with only one extra indirection (a kind of vtable) to - allow for format evolution and optional fields. It is aimed at - projects where spending time and space (many memory allocations) to - be able to access or construct serialized data is undesirable, such - as in games or any other performance sensitive applications. See the - [benchmarks](@ref flatbuffers_benchmarks) for details. - -- **Flexible** - Optional fields means not only do you get great - forwards and backwards compatibility (increasingly important for - long-lived games: don't have to update all data with each new - version!). It also means you have a lot of choice in what data you - write and what data you don't, and how you design data structures. - -- **Tiny code footprint** - Small amounts of generated code, and just - a single small header as the minimum dependency, which is very easy - to integrate. Again, see the benchmark section for details. - -- **Strongly typed** - Errors happen at compile time rather than - manually having to write repetitive and error prone run-time checks. - Useful code can be generated for you. - -- **Convenient to use** - Generated C++ code allows for terse access - & construction code. Then there's optional functionality for parsing - schemas and JSON-like text representations at runtime efficiently if - needed (faster and more memory efficient than other JSON - parsers). - - Java, Kotlin and Go code supports object-reuse. C# has efficient struct based - accessors. - -- **Cross platform code with no dependencies** - C++ code will work - with any recent gcc/clang and VS2010. Comes with build files for the tests & - samples (Android .mk files, and cmake for all other platforms). - -### Why not use Protocol Buffers, or .. ? - -Protocol Buffers is indeed relatively similar to FlatBuffers, -with the primary difference being that FlatBuffers does not need a parsing/ -unpacking step to a secondary representation before you can -access data, often coupled with per-object memory allocation. The code -is an order of magnitude bigger, too. Protocol Buffers has neither optional -text import/export nor schema language features like unions. - -### But all the cool kids use JSON! - -JSON is very readable (which is why we use it as our optional text -format) and very convenient when used together with dynamically typed -languages (such as JavaScript). When serializing data from statically -typed languages, however, JSON not only has the obvious drawback of runtime -inefficiency, but also forces you to write *more* code to access data -(counterintuitively) due to its dynamic-typing serialization system. -In this context, it is only a better choice for systems that have very -little to no information ahead of time about what data needs to be stored. - -If you do need to store data that doesn't fit a schema, FlatBuffers also -offers a schema-less (self-describing) version! - -Read more about the "why" of FlatBuffers in the -[white paper](@ref flatbuffers_white_paper). - -### Who uses FlatBuffers? -- [Cocos2d-x](http://www.cocos2d-x.org/), the #1 open source mobile game - engine, uses it to serialize all their - [game data](http://www.cocos2d-x.org/reference/native-cpp/V3.5/d7/d2d/namespaceflatbuffers.html). -- [Facebook](http://facebook.com/) uses it for client-server communication in - their Android app. They have a nice - [article](https://code.facebook.com/posts/872547912839369/improving-facebook-s-performance-on-android-with-flatbuffers/) - explaining how it speeds up loading their posts. -- [Fun Propulsion Labs](https://developers.google.com/games/#Tools) - at Google uses it extensively in all their libraries and games. - -## Usage in brief - -This section is a quick rundown of how to use this system. Subsequent -sections provide a more in-depth usage guide. - -- Write a schema file that allows you to define the data structures - you may want to serialize. Fields can have a scalar type - (ints/floats of all sizes), or they can be a: string; array of any type; - reference to yet another object; or, a set of possible objects (unions). - Fields are optional and have defaults, so they don't need to be - present for every object instance. - -- Use `flatc` (the FlatBuffer compiler) to generate a C++ header (or - Java/Kotlin/C#/Go/Python.. classes) with helper classes to access and construct - serialized data. This header (say `mydata_generated.h`) only depends on - `flatbuffers.h`, which defines the core functionality. - -- Use the `FlatBufferBuilder` class to construct a flat binary buffer. - The generated functions allow you to add objects to this - buffer recursively, often as simply as making a single function call. - -- Store or send your buffer somewhere! - -- When reading it back, you can obtain the pointer to the root object - from the binary buffer, and from there traverse it conveniently - in-place with `object->field()`. - -## In-depth documentation - -- How to [build the compiler](@ref flatbuffers_guide_building) and samples on - various platforms. -- How to [use the compiler](@ref flatbuffers_guide_using_schema_compiler). -- How to [write a schema](@ref flatbuffers_guide_writing_schema). -- How to [use the generated C++ code](@ref flatbuffers_guide_use_cpp) in your - own programs. -- How to [use the generated Java/C# code](@ref flatbuffers_guide_use_java_c-sharp) - in your own programs. -- How to [use the generated Kotlin code](@ref flatbuffers_guide_use_kotlin) - in your own programs. -- How to [use the generated Go code](@ref flatbuffers_guide_use_go) in your - own programs. -- How to [use the generated Lua code](@ref flatbuffers_guide_use_lua) in your - own programs. -- How to [use the generated JavaScript code](@ref flatbuffers_guide_use_javascript) in your - own programs. -- How to [use the generated TypeScript code](@ref flatbuffers_guide_use_typescript) in your - own programs. -- How to [use FlatBuffers in C with `flatcc`](@ref flatbuffers_guide_use_c) in your - own programs. -- How to [use the generated Lobster code](@ref flatbuffers_guide_use_lobster) in your - own programs. -- How to [use the generated Rust code](@ref flatbuffers_guide_use_rust) in your - own programs. -- [Support matrix](@ref flatbuffers_support) for platforms/languages/features. -- Some [benchmarks](@ref flatbuffers_benchmarks) showing the advantage of - using FlatBuffers. -- A [white paper](@ref flatbuffers_white_paper) explaining the "why" of - FlatBuffers. -- How to use the [schema-less](@ref flexbuffers) version of - FlatBuffers. -- A description of the [internals](@ref flatbuffers_internals) of FlatBuffers. -- A formal [grammar](@ref flatbuffers_grammar) of the schema language. - -## Online resources - -- [GitHub repository](http://github.com/google/flatbuffers) -- [Landing page](http://google.github.io/flatbuffers) -- [FlatBuffers Google Group](https://groups.google.com/forum/#!forum/flatbuffers) -- [FlatBuffers Issues Tracker](http://github.com/google/flatbuffers/issues) -- Independent implementations & tools: - - [FlatCC](https://github.com/dvidelabs/flatcc) Alternative FlatBuffers - parser, code generator and runtime all in C. -- Videos: - - Colt's [DevByte](https://www.youtube.com/watch?v=iQTxMkSJ1dQ). - - GDC 2015 [Lightning Talk](https://www.youtube.com/watch?v=olmL1fUnQAQ). - - FlatBuffers for [Go](https://www.youtube.com/watch?v=-BPVId_lA5w). - - Evolution of FlatBuffers - [visualization](https://www.youtube.com/watch?v=a0QE0xS8rKM). -- Useful documentation created by others: - - [FlatBuffers in Go](https://rwinslow.com/tags/flatbuffers/) - - [FlatBuffers in Android](http://frogermcs.github.io/flatbuffers-in-android-introdution/) - - [Parsing JSON to FlatBuffers in Java](http://frogermcs.github.io/json-parsing-with-flatbuffers-in-android/) - - [FlatBuffers in Unity](http://exiin.com/blog/flatbuffers-for-unity-sample-code/) diff --git a/third_party/flatbuffers/docs/source/FlexBuffers.md b/third_party/flatbuffers/docs/source/FlexBuffers.md deleted file mode 100644 index a089df32dd4..00000000000 --- a/third_party/flatbuffers/docs/source/FlexBuffers.md +++ /dev/null @@ -1,166 +0,0 @@ -FlexBuffers {#flexbuffers} -========== - -FlatBuffers was designed around schemas, because when you want maximum -performance and data consistency, strong typing is helpful. - -There are however times when you want to store data that doesn't fit a -schema, because you can't know ahead of time what all needs to be stored. - -For this, FlatBuffers has a dedicated format, called FlexBuffers. -This is a binary format that can be used in conjunction -with FlatBuffers (by storing a part of a buffer in FlexBuffers -format), or also as its own independent serialization format. - -While it loses the strong typing, you retain the most unique advantage -FlatBuffers has over other serialization formats (schema-based or not): -FlexBuffers can also be accessed without parsing / copying / object allocation. -This is a huge win in efficiency / memory friendly-ness, and allows unique -use cases such as mmap-ing large amounts of free-form data. - -FlexBuffers' design and implementation allows for a very compact encoding, -combining automatic pooling of strings with automatic sizing of containers to -their smallest possible representation (8/16/32/64 bits). Many values and -offsets can be encoded in just 8 bits. While a schema-less representation is -usually more bulky because of the need to be self-descriptive, FlexBuffers -generates smaller binaries for many cases than regular FlatBuffers. - -FlexBuffers is still slower than regular FlatBuffers though, so we recommend to -only use it if you need it. - - -# Usage - -This is for C++, other languages may follow. - -Include the header `flexbuffers.h`, which in turn depends on `flatbuffers.h` -and `util.h`. - -To create a buffer: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} -flexbuffers::Builder fbb; -fbb.Int(13); -fbb.Finish(); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You create any value, followed by `Finish`. Unlike FlatBuffers which requires -the root value to be a table, here any value can be the root, including a lonely -int value. - -You can now access the `std::vector` that contains the encoded value -as `fbb.GetBuffer()`. Write it, send it, or store it in a parent FlatBuffer. In -this case, the buffer is just 3 bytes in size. - -To read this value back, you could just say: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} -auto root = flexbuffers::GetRoot(my_buffer); -int64_t i = root.AsInt64(); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -FlexBuffers stores ints only as big as needed, so it doesn't differentiate -between different sizes of ints. You can ask for the 64 bit version, -regardless of what you put in. In fact, since you demand to read the root -as an int, if you supply a buffer that actually contains a float, or a -string with numbers in it, it will convert it for you on the fly as well, -or return 0 if it can't. If instead you actually want to know what is inside -the buffer before you access it, you can call `root.GetType()` or `root.IsInt()` -etc. - -Here's a slightly more complex value you could write instead of `fbb.Int` above: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} -fbb.Map([&]() { - fbb.Vector("vec", [&]() { - fbb.Int(-100); - fbb.String("Fred"); - fbb.IndirectFloat(4.0f); - }); - fbb.UInt("foo", 100); -}); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This stores the equivalent of the JSON value -`{ vec: [ -100, "Fred", 4.0 ], foo: 100 }`. The root is a dictionary that has -just two key-value pairs, with keys `vec` and `foo`. Unlike FlatBuffers, it -actually has to store these keys in the buffer (which it does only once if -you store multiple such objects, by pooling key values), but also unlike -FlatBuffers it has no restriction on the keys (fields) that you use. - -The map constructor uses a C++11 Lambda to group its children, but you can -also use more conventional start/end calls if you prefer. - -The first value in the map is a vector. You'll notice that unlike FlatBuffers, -you can use mixed types. There is also a `TypedVector` variant that only -allows a single type, and uses a bit less memory. - -`IndirectFloat` is an interesting feature that allows you to store values -by offset rather than inline. Though that doesn't make any visible change -to the user, the consequence is that large values (especially doubles or -64 bit ints) that occur more than once can be shared. Another use case is -inside of vectors, where the largest element makes up the size of all elements -(e.g. a single double forces all elements to 64bit), so storing a lot of small -integers together with a double is more efficient if the double is indirect. - -Accessing it: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} -auto map = flexbuffers::GetRoot(my_buffer).AsMap(); -map.size(); // 2 -auto vec = map["vec"].AsVector(); -vec.size(); // 3 -vec[0].AsInt64(); // -100; -vec[1].AsString().c_str(); // "Fred"; -vec[1].AsInt64(); // 0 (Number parsing failed). -vec[2].AsDouble(); // 4.0 -vec[2].AsString().IsTheEmptyString(); // true (Wrong Type). -vec[2].AsString().c_str(); // "" (This still works though). -vec[2].ToString().c_str(); // "4" (Or have it converted). -map["foo"].AsUInt8(); // 100 -map["unknown"].IsNull(); // true -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -# Binary encoding - -A description of how FlexBuffers are encoded is in the -[internals](@ref flatbuffers_internals) document. - - -# Nesting inside a FlatBuffer - -You can mark a field as containing a FlexBuffer, e.g. - - a:[ubyte] (flexbuffer); - -A special accessor will be generated that allows you to access the root value -directly, e.g. `a_flexbuffer_root().AsInt64()`. - - -# Efficiency tips - -* Vectors generally are a lot more efficient than maps, so prefer them over maps - when possible for small objects. Instead of a map with keys `x`, `y` and `z`, - use a vector. Better yet, use a typed vector. Or even better, use a fixed - size typed vector. -* Maps are backwards compatible with vectors, and can be iterated as such. - You can iterate either just the values (`map.Values()`), or in parallel with - the keys vector (`map.Keys()`). If you intend - to access most or all elements, this is faster than looking up each element - by key, since that involves a binary search of the key vector. -* When possible, don't mix values that require a big bit width (such as double) - in a large vector of smaller values, since all elements will take on this - width. Use `IndirectDouble` when this is a possibility. Note that - integers automatically use the smallest width possible, i.e. if you ask - to serialize an int64_t whose value is actually small, you will use less - bits. Doubles are represented as floats whenever possible losslessly, but - this is only possible for few values. - Since nested vectors/maps are stored over offsets, they typically don't - affect the vector width. -* To store large arrays of byte data, use a blob. If you'd use a typed - vector, the bit width of the size field may make it use more space than - expected, and may not be compatible with `memcpy`. - Similarly, large arrays of (u)int16_t may be better off stored as a - binary blob if their size could exceed 64k elements. - Construction and use are otherwise similar to strings. diff --git a/third_party/flatbuffers/docs/source/GoApi.md b/third_party/flatbuffers/docs/source/GoApi.md deleted file mode 100644 index 98be2b6a9e4..00000000000 --- a/third_party/flatbuffers/docs/source/GoApi.md +++ /dev/null @@ -1,26 +0,0 @@ -Go API -====== - -\addtogroup flatbuffers_go_api - - -\snippet GoApi_generated.txt Go API diff --git a/third_party/flatbuffers/docs/source/GoApi_generated.txt b/third_party/flatbuffers/docs/source/GoApi_generated.txt deleted file mode 100644 index 3d4e0fc77ae..00000000000 --- a/third_party/flatbuffers/docs/source/GoApi_generated.txt +++ /dev/null @@ -1,125 +0,0 @@ -// This file was generated using `godoc` and customized for use with the -// API Reference documentation. To recreate this file, use the `godoc` tool -// (http://godoc.org) with the files in the `flatbuffers/go` folder. -// -// Note: You may need to ensure that copies of the files exist in the -// `src/` subfolder at the path set by the `$GOROOT` environment variable. -// You can either move the files to `$GOROOT/src/flatbuffers` manually, if -// `$GOROOT` is already set, otherwise you will need to manually set the -// `$GOROOT` variable to a path and create `src/flatbuffers` subfolders at that -// path. Then copy these files into `$GOROOT/src/flatbuffers`. (Some versions of -// `godoc` include a `-path` flag. This could be used instead, if available). -// -// Once the files exist at the `$GOROOT/src/flatbuffers` location, you can -// regenerate this doc using the following command: -// `godoc flatbuffers > GoApi_generated.txt`. -// -// After the documentation is generated, you will have to manually remove any -// non-user facing documentation from this file. - -/// [Go API] -PACKAGE DOCUMENTATION - -package flatbuffers - Package flatbuffers provides facilities to read and write flatbuffers - objects. - -TYPES - -type Builder struct { - // `Bytes` gives raw access to the buffer. Most users will want to use - // FinishedBytes() instead. - Bytes []byte -} - Builder is a state machine for creating FlatBuffer objects. Use a - Builder to construct object(s) starting from leaf nodes. - - A Builder constructs byte buffers in a last-first manner for simplicity - and performance. - -FUNCTIONS - -func NewBuilder(initialSize int) *Builder - NewBuilder initializes a Builder of size `initial_size`. The internal - buffer is grown as needed. - -func (b *Builder) CreateByteString(s []byte) UOffsetT - CreateByteString writes a byte slice as a string (null-terminated). - -func (b *Builder) CreateByteVector(v []byte) UOffsetT - CreateByteVector writes a ubyte vector - -func (b *Builder) CreateString(s string) UOffsetT - CreateString writes a null-terminated string as a vector. - -func (b *Builder) EndVector(vectorNumElems int) UOffsetT - EndVector writes data necessary to finish vector construction. - -func (b *Builder) Finish(rootTable UOffsetT) - Finish finalizes a buffer, pointing to the given `rootTable`. - -func (b *Builder) FinishedBytes() []byte - FinishedBytes returns a pointer to the written data in the byte buffer. - Panics if the builder is not in a finished state (which is caused by - calling `Finish()`). - -func (b *Builder) Head() UOffsetT - Head gives the start of useful data in the underlying byte buffer. Note: - unlike other functions, this value is interpreted as from the left. - -func (b *Builder) PrependBool(x bool) - PrependBool prepends a bool to the Builder buffer. Aligns and checks for - space. - -func (b *Builder) PrependByte(x byte) - PrependByte prepends a byte to the Builder buffer. Aligns and checks for - space. - -func (b *Builder) PrependFloat32(x float32) - PrependFloat32 prepends a float32 to the Builder buffer. Aligns and - checks for space. - -func (b *Builder) PrependFloat64(x float64) - PrependFloat64 prepends a float64 to the Builder buffer. Aligns and - checks for space. - -func (b *Builder) PrependInt16(x int16) - PrependInt16 prepends a int16 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependInt32(x int32) - PrependInt32 prepends a int32 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependInt64(x int64) - PrependInt64 prepends a int64 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependInt8(x int8) - PrependInt8 prepends a int8 to the Builder buffer. Aligns and checks for - space. - -func (b *Builder) PrependUOffsetT(off UOffsetT) - PrependUOffsetT prepends an UOffsetT, relative to where it will be - written. - -func (b *Builder) PrependUint16(x uint16) - PrependUint16 prepends a uint16 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependUint32(x uint32) - PrependUint32 prepends a uint32 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependUint64(x uint64) - PrependUint64 prepends a uint64 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependUint8(x uint8) - PrependUint8 prepends a uint8 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) Reset() - Reset truncates the underlying Builder buffer, facilitating alloc-free - reuse of a Builder. It also resets bookkeeping data. -/// [Go API] diff --git a/third_party/flatbuffers/docs/source/GoUsage.md b/third_party/flatbuffers/docs/source/GoUsage.md deleted file mode 100644 index ab6ddbd8238..00000000000 --- a/third_party/flatbuffers/docs/source/GoUsage.md +++ /dev/null @@ -1,99 +0,0 @@ -Use in Go {#flatbuffers_guide_use_go} -========= - -## Before you get started - -Before diving into the FlatBuffers usage in Go, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide -to general FlatBuffers usage in all of the supported languages (including Go). -This page is designed to cover the nuances of FlatBuffers usage, specific to -Go. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Go library code location - -The code for the FlatBuffers Go library can be found at -`flatbuffers/go`. You can browse the library code on the [FlatBuffers -GitHub page](https://github.com/google/flatbuffers/tree/master/go). - -## Testing the FlatBuffers Go library - -The code to test the Go library can be found at `flatbuffers/tests`. -The test code itself is located in [go_test.go](https://github.com/google/ -flatbuffers/blob/master/tests/go_test.go). - -To run the tests, use the [GoTest.sh](https://github.com/google/flatbuffers/ -blob/master/tests/GoTest.sh) shell script. - -*Note: The shell script requires [Go](https://golang.org/doc/install) to -be installed.* - -## Using the FlatBuffers Go library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Go.* - -FlatBuffers supports reading and writing binary FlatBuffers in Go. - -To use FlatBuffers in your own code, first generate Go classes from your -schema with the `--go` option to `flatc`. Then you can include both FlatBuffers -and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Go: First, -include the library and generated code. Then read a FlatBuffer binary file into -a `[]byte`, which you pass to the `GetRootAsMonster` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go} - import ( - example "MyGame/Example" - flatbuffers "github.com/google/flatbuffers/go" - - io/ioutil - ) - - buf, err := ioutil.ReadFile("monster.dat") - // handle err - monster := example.GetRootAsMonster(buf, 0) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access values like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go} - hp := monster.Hp() - pos := monster.Pos(nil) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -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 -from Go, though you could use the C++ parser through cgo. Please see the -C++ documentation for more on text parsing. - -
diff --git a/third_party/flatbuffers/docs/source/Grammar.md b/third_party/flatbuffers/docs/source/Grammar.md deleted file mode 100644 index 51cc5f0c075..00000000000 --- a/third_party/flatbuffers/docs/source/Grammar.md +++ /dev/null @@ -1,74 +0,0 @@ -Grammar of the schema language {#flatbuffers_grammar} -============================== - -schema = include* - ( namespace\_decl | type\_decl | enum\_decl | root\_decl | - file_extension_decl | file_identifier_decl | - attribute\_decl | rpc\_decl | object )* - -include = `include` string\_constant `;` - -namespace\_decl = `namespace` ident ( `.` ident )* `;` - -attribute\_decl = `attribute` ident | `"`ident`"` `;` - -type\_decl = ( `table` | `struct` ) ident metadata `{` field\_decl+ `}` - -enum\_decl = ( `enum` ident `:` type | `union` ident ) metadata `{` -commasep( enumval\_decl ) `}` - -root\_decl = `root_type` ident `;` - -field\_decl = ident `:` type [ `=` scalar ] metadata `;` - -rpc\_decl = `rpc_service` ident `{` rpc\_method+ `}` - -rpc\_method = ident `(` ident `)` `:` ident metadata `;` - -type = `bool` | `byte` | `ubyte` | `short` | `ushort` | `int` | `uint` | -`float` | `long` | `ulong` | `double` | -`int8` | `uint8` | `int16` | `uint16` | `int32` | `uint32`| `int64` | `uint64` | -`float32` | `float64` | -`string` | `[` type `]` | ident - -enumval\_decl = ident [ `=` integer\_constant ] - -metadata = [ `(` commasep( ident [ `:` single\_value ] ) `)` ] - -scalar = integer\_constant | float\_constant - -object = { commasep( ident `:` value ) } - -single\_value = scalar | string\_constant - -value = single\_value | object | `[` commasep( value ) `]` - -commasep(x) = [ x ( `,` x )\* ] - -file_extension_decl = `file_extension` string\_constant `;` - -file_identifier_decl = `file_identifier` string\_constant `;` - -string\_constant = `\".*?\"` - -ident = `[a-zA-Z_][a-zA-Z0-9_]*` - -`[:digit:]` = `[0-9]` - -`[:xdigit:]` = `[0-9a-fA-F]` - -dec\_integer\_constant = `[-+]?[:digit:]+` - -hex\_integer\_constant = `[-+]?0[xX][:xdigit:]+` - -integer\_constant = dec\_integer\_constant | hex\_integer\_constant - -dec\_float\_constant = `[-+]?(([.][:digit:]+)|([:digit:]+[.][:digit:]*)|([:digit:]+))([eE][-+]?[:digit:]+)?` - -hex\_float\_constant = `[-+]?0[xX](([.][:xdigit:]+)|([:xdigit:]+[.][:xdigit:]*)|([:xdigit:]+))([pP][-+]?[:digit:]+)` - -special\_float\_constant = `[-+]?(nan|inf|infinity)` - -float\_constant = decimal\_float\_constant | hexadecimal\_float\_constant | special\_float\_constant - -boolean\_constant = `(true|false)` | (integer\_constant ? `true` : `false`) diff --git a/third_party/flatbuffers/docs/source/Internals.md b/third_party/flatbuffers/docs/source/Internals.md deleted file mode 100644 index d2064ca6159..00000000000 --- a/third_party/flatbuffers/docs/source/Internals.md +++ /dev/null @@ -1,455 +0,0 @@ -FlatBuffer Internals {#flatbuffers_internals} -==================== - -This section is entirely optional for the use of FlatBuffers. In normal -usage, you should never need the information contained herein. If you're -interested however, it should give you more of an appreciation of why -FlatBuffers is both efficient and convenient. - -### Format components - -A FlatBuffer is a binary file and in-memory format consisting mostly of -scalars of various sizes, all aligned to their own size. Each scalar is -also always represented in little-endian format, as this corresponds to -all commonly used CPUs today. FlatBuffers will also work on big-endian -machines, but will be slightly slower because of additional -byte-swap intrinsics. - -It is assumed that the following conditions are met, to ensure -cross-platform interoperability: -- The binary `IEEE-754` format is used for floating-point numbers. -- The `two's complemented` representation is used for signed integers. -- The endianness is the same for floating-point numbers as for integers. - -On purpose, the format leaves a lot of details about where exactly -things live in memory undefined, e.g. fields in a table can have any -order, and objects to some extent can be stored in many orders. This is -because the format doesn't need this information to be efficient, and it -leaves room for optimization and extension (for example, fields can be -packed in a way that is most compact). Instead, the format is defined in -terms of offsets and adjacency only. This may mean two different -implementations may produce different binaries given the same input -values, and this is perfectly valid. - -### Format identification - -The format also doesn't contain information for format identification -and versioning, which is also by design. FlatBuffers is a statically typed -system, meaning the user of a buffer needs to know what kind of buffer -it is. FlatBuffers can of course be wrapped inside other containers -where needed, or you can use its union feature to dynamically identify -multiple possible sub-objects stored. Additionally, it can be used -together with the schema parser if full reflective capabilities are -desired. - -Versioning is something that is intrinsically part of the format (the -optionality / extensibility of fields), so the format itself does not -need a version number (it's a meta-format, in a sense). We're hoping -that this format can accommodate all data needed. If format breaking -changes are ever necessary, it would become a new kind of format rather -than just a variation. - -### Offsets - -The most important and generic offset type (see `flatbuffers.h`) is -`uoffset_t`, which is currently always a `uint32_t`, and is used to -refer to all tables/unions/strings/vectors (these are never stored -in-line). 32bit is -intentional, since we want to keep the format binary compatible between -32 and 64bit systems, and a 64bit offset would bloat the size for almost -all uses. A version of this format with 64bit (or 16bit) offsets is easy to set -when needed. Unsigned means they can only point in one direction, which -typically is forward (towards a higher memory location). Any backwards -offsets will be explicitly marked as such. - -The format starts with an `uoffset_t` to the root object in the buffer. - -We have two kinds of objects, structs and tables. - -### Structs - -These are the simplest, and as mentioned, intended for simple data that -benefits from being extra efficient and doesn't need versioning / -extensibility. They are always stored inline in their parent (a struct, -table, or vector) for maximum compactness. Structs define a consistent -memory layout where all components are aligned to their size, and -structs aligned to their largest scalar member. This is done independent -of the alignment rules of the underlying compiler to guarantee a cross -platform compatible layout. This layout is then enforced in the generated -code. - -### Tables - -Unlike structs, these are not stored in inline in their parent, but are -referred to by offset. - -They start with an `soffset_t` to a vtable. This is a signed version of -`uoffset_t`, since vtables may be stored anywhere relative to the object. -This offset is substracted (not added) from the object start to arrive at -the vtable start. This offset is followed by all the -fields as aligned scalars (or offsets). Unlike structs, not all fields -need to be present. There is no set order and layout. - -To be able to access fields regardless of these uncertainties, we go -through a vtable of offsets. Vtables are shared between any objects that -happen to have the same vtable values. - -The elements of a vtable are all of type `voffset_t`, which is -a `uint16_t`. The first element is the size of the vtable in bytes, -including the size element. The second one is the size of the object, in bytes -(including the vtable offset). This size could be used for streaming, to know -how many bytes to read to be able to access all *inline* fields of the object. -The remaining elements are the N offsets, where N is the amount of fields -declared in the schema when the code that constructed this buffer was -compiled (thus, the size of the table is N + 2). - -All accessor functions in the generated code for tables contain the -offset into this table as a constant. This offset is checked against the -first field (the number of elements), to protect against newer code -reading older data. If this offset is out of range, or the vtable entry -is 0, that means the field is not present in this object, and the -default value is return. Otherwise, the entry is used as offset to the -field to be read. - -### Strings and Vectors - -Strings are simply a vector of bytes, and are always -null-terminated. Vectors are stored as contiguous aligned scalar -elements prefixed by a 32bit element count (not including any -null termination). Neither is stored inline in their parent, but are referred to -by offset. - -### Construction - -The current implementation constructs these buffers backwards (starting -at the highest memory address of the buffer), since -that significantly reduces the amount of bookkeeping and simplifies the -construction API. - -### Code example - -Here's an example of the code that gets generated for the `samples/monster.fbs`. -What follows is the entire file, broken up by comments: - - // automatically generated, do not modify - - #include "flatbuffers/flatbuffers.h" - - namespace MyGame { - namespace Sample { - -Nested namespace support. - - enum { - Color_Red = 0, - Color_Green = 1, - Color_Blue = 2, - }; - - inline const char **EnumNamesColor() { - static const char *names[] = { "Red", "Green", "Blue", nullptr }; - return names; - } - - inline const char *EnumNameColor(int e) { return EnumNamesColor()[e]; } - -Enums and convenient reverse lookup. - - enum { - Any_NONE = 0, - Any_Monster = 1, - }; - - inline const char **EnumNamesAny() { - static const char *names[] = { "NONE", "Monster", nullptr }; - return names; - } - - inline const char *EnumNameAny(int e) { return EnumNamesAny()[e]; } - -Unions share a lot with enums. - - struct Vec3; - struct Monster; - -Predeclare all data types since circular references between types are allowed -(circular references between object are not, though). - - FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vec3 { - private: - float x_; - float y_; - float z_; - - public: - 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_); } - float y() const { return flatbuffers::EndianScalar(y_); } - float z() const { return flatbuffers::EndianScalar(z_); } - }; - FLATBUFFERS_STRUCT_END(Vec3, 12); - -These ugly macros do a couple of things: they turn off any padding the compiler -might normally do, since we add padding manually (though none in this example), -and they enforce alignment chosen by FlatBuffers. This ensures the layout of -this struct will look the same regardless of compiler and platform. Note that -the fields are private: this is because these store little endian scalars -regardless of platform (since this is part of the serialized data). -`EndianScalar` then converts back and forth, which is a no-op on all current -mobile and desktop platforms, and a single machine instruction on the few -remaining big endian platforms. - - struct Monster : private flatbuffers::Table { - const Vec3 *pos() const { return GetStruct(4); } - int16_t mana() const { return GetField(6, 150); } - int16_t hp() const { return GetField(8, 100); } - const flatbuffers::String *name() const { return GetPointer(10); } - const flatbuffers::Vector *inventory() const { return GetPointer *>(14); } - int8_t color() const { return GetField(16, 2); } - }; - -Tables are a bit more complicated. A table accessor struct is used to point at -the serialized data for a table, which always starts with an offset to its -vtable. It derives from `Table`, which contains the `GetField` helper functions. -GetField takes a vtable offset, and a default value. It will look in the vtable -at that offset. If the offset is out of bounds (data from an older version) or -the vtable entry is 0, the field is not present and the default is returned. -Otherwise, it uses the entry as an offset into the table to locate the field. - - struct MonsterBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_pos(const Vec3 *pos) { fbb_.AddStruct(4, pos); } - void add_mana(int16_t mana) { fbb_.AddElement(6, mana, 150); } - void add_hp(int16_t hp) { fbb_.AddElement(8, hp, 100); } - void add_name(flatbuffers::Offset name) { fbb_.AddOffset(10, name); } - void add_inventory(flatbuffers::Offset> inventory) { fbb_.AddOffset(14, inventory); } - void add_color(int8_t color) { fbb_.AddElement(16, color, 2); } - MonsterBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); } - flatbuffers::Offset Finish() { return flatbuffers::Offset(fbb_.EndTable(start_, 7)); } - }; - -`MonsterBuilder` is the base helper struct to construct a table using a -`FlatBufferBuilder`. You can add the fields in any order, and the `Finish` -call will ensure the correct vtable gets generated. - - inline flatbuffers::Offset CreateMonster(flatbuffers::FlatBufferBuilder &_fbb, - const Vec3 *pos, int16_t mana, - int16_t hp, - flatbuffers::Offset name, - flatbuffers::Offset> inventory, - int8_t color) { - MonsterBuilder builder_(_fbb); - builder_.add_inventory(inventory); - builder_.add_name(name); - builder_.add_pos(pos); - builder_.add_hp(hp); - builder_.add_mana(mana); - builder_.add_color(color); - return builder_.Finish(); - } - -`CreateMonster` is a convenience function that calls all functions in -`MonsterBuilder` above for you. Note that if you pass values which are -defaults as arguments, it will not actually construct that field, so -you can probably use this function instead of the builder class in -almost all cases. - - inline const Monster *GetMonster(const void *buf) { return flatbuffers::GetRoot(buf); } - -This function is only generated for the root table type, to be able to -start traversing a FlatBuffer from a raw buffer pointer. - - }; // namespace MyGame - }; // namespace Sample - -### Encoding example. - -Below is a sample encoding for the following JSON corresponding to the above -schema: - - { pos: { x: 1, y: 2, z: 3 }, name: "fred", hp: 50 } - -Resulting in this binary buffer: - - // Start of the buffer: - uint32_t 20 // Offset to the root table. - - // Start of the vtable. Not shared in this example, but could be: - uint16_t 16 // Size of table, starting from here. - uint16_t 22 // Size of object inline data. - uint16_t 4, 0, 20, 16, 0, 0 // Offsets to fields from start of (root) table, 0 for not present. - - // Start of the root table: - int32_t 16 // Offset to vtable used (default negative direction) - float 1, 2, 3 // the Vec3 struct, inline. - uint32_t 8 // Offset to the name string. - int16_t 50 // hp field. - int16_t 0 // Padding for alignment. - - // Start of name string: - uint32_t 4 // Length of string. - int8_t 'f', 'r', 'e', 'd', 0, 0, 0, 0 // Text + 0 termination + padding. - -Note that this not the only possible encoding, since the writer has some -flexibility in which of the children of root object to write first (though in -this case there's only one string), and what order to write the fields in. -Different orders may also cause different alignments to happen. - -### Additional reading. - -The author of the C language implementation has made a similar -[document](https://github.com/dvidelabs/flatcc/blob/master/doc/binary-format.md#flatbuffers-binary-format) -that may further help clarify the format. - -# FlexBuffers - -The [schema-less](@ref flexbuffers) version of FlatBuffers have their -own encoding, detailed here. - -It shares many properties mentioned above, in that all data is accessed -over offsets, all scalars are aligned to their own size, and -all data is always stored in little endian format. - -One difference is that FlexBuffers are built front to back, so children are -stored before parents, and the root of the data starts at the last byte. - -Another difference is that scalar data is stored with a variable number of bits -(8/16/32/64). The current width is always determined by the *parent*, i.e. if -the scalar sits in a vector, the vector determines the bit width for all -elements at once. Selecting the minimum bit width for a particular vector is -something the encoder does automatically and thus is typically of no concern -to the user, though being aware of this feature (and not sticking a double in -the same vector as a bunch of byte sized elements) is helpful for efficiency. - -Unlike FlatBuffers there is only one kind of offset, and that is an unsigned -integer indicating the number of bytes in a negative direction from the address -of itself (where the offset is stored). - -### Vectors - -The representation of the vector is at the core of how FlexBuffers works (since -maps are really just a combination of 2 vectors), so it is worth starting there. - -As mentioned, a vector is governed by a single bit width (supplied by its -parent). This includes the size field. For example, a vector that stores the -integer values `1, 2, 3` is encoded as follows: - - uint8_t 3, 1, 2, 3, 4, 4, 4 - -The first `3` is the size field, and is placed before the vector (an offset -from the parent to this vector points to the first element, not the size -field, so the size field is effectively at index -1). -Since this is an untyped vector `SL_VECTOR`, it is followed by 3 type -bytes (one per element of the vector), which are always following the vector, -and are always a uint8_t even if the vector is made up of bigger scalars. - -### Types - -A type byte is made up of 2 components (see flexbuffers.h for exact values): - -* 2 lower bits representing the bit-width of the child (8, 16, 32, 64). - This is only used if the child is accessed over an offset, such as a child - vector. It is ignored for inline types. -* 6 bits representing the actual type (see flexbuffers.h). - -Thus, in this example `4` means 8 bit child (value 0, unused, since the value is -in-line), type `SL_INT` (value 1). - -### Typed Vectors - -These are like the Vectors above, but omit the type bytes. The type is instead -determined by the vector type supplied by the parent. Typed vectors are only -available for a subset of types for which these savings can be significant, -namely inline signed/unsigned integers (`TYPE_VECTOR_INT` / `TYPE_VECTOR_UINT`), -floats (`TYPE_VECTOR_FLOAT`), and keys (`TYPE_VECTOR_KEY`, see below). - -Additionally, for scalars, there are fixed length vectors of sizes 2 / 3 / 4 -that don't store the size (`TYPE_VECTOR_INT2` etc.), for an additional savings -in space when storing common vector or color data. - -### Scalars - -FlexBuffers supports integers (`TYPE_INT` and `TYPE_UINT`) and floats -(`TYPE_FLOAT`), available in the bit-widths mentioned above. They can be stored -both inline and over an offset (`TYPE_INDIRECT_*`). - -The offset version is useful to encode costly 64bit (or even 32bit) quantities -into vectors / maps of smaller sizes, and to share / repeat a value multiple -times. - -### Booleans and Nulls - -Booleans (`TYPE_BOOL`) and nulls (`TYPE_NULL`) are encoded as inlined unsigned integers. - -### Blobs, Strings and Keys. - -A blob (`TYPE_BLOB`) is encoded similar to a vector, with one difference: the -elements are always `uint8_t`. The parent bit width only determines the width of -the size field, allowing blobs to be large without the elements being large. - -Strings (`TYPE_STRING`) are similar to blobs, except they have an additional 0 -termination byte for convenience, and they MUST be UTF-8 encoded (since an -accessor in a language that does not support pointers to UTF-8 data may have to -convert them to a native string type). - -A "Key" (`TYPE_KEY`) is similar to a string, but doesn't store the size -field. They're so named because they are used with maps, which don't care -for the size, and can thus be even more compact. Unlike strings, keys cannot -contain bytes of value 0 as part of their data (size can only be determined by -`strlen`), so while you can use them outside the context of maps if you so -desire, you're usually better off with strings. - -### Maps - -A map (`TYPE_MAP`) is like an (untyped) vector, but with 2 prefixes before the -size field: - -| index | field | -| ----: | :----------------------------------------------------------- | -| -3 | An offset to the keys vector (may be shared between tables). | -| -2 | Byte width of the keys vector. | -| -1 | Size (from here on it is compatible with `TYPE_VECTOR`) | -| 0 | Elements. | -| Size | Types. | - -Since a map is otherwise the same as a vector, it can be iterated like -a vector (which is probably faster than lookup by key). - -The keys vector is a typed vector of keys. Both the keys and corresponding -values *have* to be stored in sorted order (as determined by `strcmp`), such -that lookups can be made using binary search. - -The reason the key vector is a seperate structure from the value vector is -such that it can be shared between multiple value vectors, and also to -allow it to be treated as its own individual vector in code. - -An example map { foo: 13, bar: 14 } would be encoded as: - - 0 : uint8_t 'b', 'a', 'r', 0 - 4 : uint8_t 'f', 'o', 'o', 0 - 8 : uint8_t 2 // key vector of size 2 - // key vector offset points here - 9 : uint8_t 9, 6 // offsets to bar_key and foo_key - 11: uint8_t 2, 1 // offset to key vector, and its byte width - 13: uint8_t 2 // value vector of size - // value vector offset points here - 14: uint8_t 14, 13 // values - 16: uint8_t 4, 4 // types - -### The root - -As mentioned, the root starts at the end of the buffer. -The last uint8_t is the width in bytes of the root (normally the parent -determines the width, but the root has no parent). The uint8_t before this is -the type of the root, and the bytes before that are the root value (of the -number of bytes specified by the last byte). - -So for example, the integer value `13` as root would be: - - uint8_t 13, 4, 1 // Value, type, root byte width. - - -
diff --git a/third_party/flatbuffers/docs/source/JavaCsharpUsage.md b/third_party/flatbuffers/docs/source/JavaCsharpUsage.md deleted file mode 100644 index 102ce371d4b..00000000000 --- a/third_party/flatbuffers/docs/source/JavaCsharpUsage.md +++ /dev/null @@ -1,172 +0,0 @@ -Use in Java/C# {#flatbuffers_guide_use_java_c-sharp} -============== - -## Before you get started - -Before diving into the FlatBuffers usage in Java or C#, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to -general FlatBuffers usage in all of the supported languages (including both Java -and C#). This page is designed to cover the nuances of FlatBuffers usage, -specific to Java and C#. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Java and C-sharp code location - -#### Java - -The code for the FlatBuffers Java library can be found at -`flatbuffers/java/com/google/flatbuffers`. You can browse the library on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ -java/com/google/flatbuffers). - -#### C-sharp - -The code for the FlatBuffers C# library can be found at -`flatbuffers/net/FlatBuffers`. You can browse the library on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/net/ -FlatBuffers). - -## Testing the FlatBuffers Java and C-sharp libraries - -The code to test the libraries can be found at `flatbuffers/tests`. - -#### Java - -The test code for Java is located in [JavaTest.java](https://github.com/google -/flatbuffers/blob/master/tests/JavaTest.java). - -To run the tests, use either [JavaTest.sh](https://github.com/google/ -flatbuffers/blob/master/tests/JavaTest.sh) or [JavaTest.bat](https://github.com/ -google/flatbuffers/blob/master/tests/JavaTest.bat), depending on your operating -system. - -*Note: These scripts require that [Java](https://www.oracle.com/java/index.html) -is installed.* - -#### C-sharp - -The test code for C# is located in the [FlatBuffers.Test](https://github.com/ -google/flatbuffers/tree/master/tests/FlatBuffers.Test) subfolder. To run the -tests, open `FlatBuffers.Test.csproj` in [Visual Studio]( -https://www.visualstudio.com), and compile/run the project. - -Optionally, you can run this using [Mono](http://www.mono-project.com/) instead. -Once you have installed `Mono`, you can run the tests from the command line -by running the following commands from inside the `FlatBuffers.Test` folder: - -~~~{.sh} - mcs *.cs ../MyGame/Example/*.cs ../../net/FlatBuffers/*.cs - mono Assert.exe -~~~ - -## Using the FlatBuffers Java (and C#) library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Java or C#.* - -FlatBuffers supports reading and writing binary FlatBuffers in Java and C#. - -To use FlatBuffers in your own code, first generate Java classes from your -schema with the `--java` option to `flatc`. (Or for C# with `--csharp`). -Then you can include both FlatBuffers and the generated code to read -or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Java: -First, import the library and generated code. Then, you read a FlatBuffer binary -file into a `byte[]`. You then turn the `byte[]` into a `ByteBuffer`, which you -pass to the `getRootAsMyRootType` function: - -*Note: The code here is written from the perspective of Java. Code for both -languages is both generated and used in nearly the exact same way, with only -minor differences. These differences are -[explained in a section below](#differences_in_c-sharp).* - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java} - import MyGame.Example.*; - import com.google.flatbuffers.FlatBufferBuilder; - - // This snippet ignores exceptions for brevity. - File file = new File("monsterdata_test.mon"); - RandomAccessFile f = new RandomAccessFile(file, "r"); - byte[] data = new byte[(int)f.length()]; - f.readFully(data); - f.close(); - - ByteBuffer bb = ByteBuffer.wrap(data); - Monster monster = Monster.getRootAsMonster(bb); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access the data from the `Monster monster`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java} - short hp = monster.hp(); - Vec3 pos = monster.pos(); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -#### Differences in C-sharp - - -C# code works almost identically to Java, with only a few minor differences. -You can see an example of C# code in -`tests/FlatBuffers.Test/FlatBuffersExampleTests.cs` or -`samples/SampleBinary.cs`. - -First of all, naming follows standard C# style with `PascalCasing` identifiers, -e.g. `GetRootAsMyRootType`. Also, values (except vectors and unions) are -available as properties instead of parameterless accessor methods as in Java. -The performance-enhancing methods to which you can pass an already created -object are prefixed with `Get`, e.g.: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} - // property - var pos = monster.Pos; - - // method filling a preconstructed object - var preconstructedPos = new Vec3(); - monster.GetPos(preconstructedPos); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -## Storing dictionaries in a FlatBuffer - -FlatBuffers doesn't support dictionaries natively, but there is support to -emulate their behavior with vectors and binary search, which means you -can have fast lookups directly from a FlatBuffer without having to unpack -your data into a `Dictionary` or similar. - -To use it: -- Designate one of the fields in a table as the "key" field. You do this - by setting the `key` attribute on this field, e.g. - `name:string (key)`. - You may only have one key field, and it must be of string or scalar type. -- Write out tables of this type as usual, collect their offsets in an - array. -- Instead of calling standard generated method, - e.g.: `Monster.createTestarrayoftablesVector`, - call `CreateSortedVectorOfMonster` in C# or - `createSortedVectorOfTables` (from the `FlatBufferBuilder` object) in Java, - which will first sort all offsets such that the tables they refer to - are sorted by the key field, then serialize it. -- Now when you're accessing the FlatBuffer, you can use - the `ByKey` accessor to access elements of the vector, e.g.: - `monster.testarrayoftablesByKey("Frodo")` in Java or - `monster.TestarrayoftablesByKey("Frodo")` in C#, - which returns an object of the corresponding table type, - or `null` if not found. - `ByKey` performs a binary search, so should have a similar - speed to `Dictionary`, though may be faster because of better caching. - `ByKey` only works if the vector has been sorted, it will - likely not find elements if it hasn't been sorted. - -## Text parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from Java or C#, though you could use the C++ parser through native call -interfaces available to each language. Please see the -C++ documentation for more on text parsing. - -
diff --git a/third_party/flatbuffers/docs/source/JavaScriptUsage.md b/third_party/flatbuffers/docs/source/JavaScriptUsage.md deleted file mode 100644 index c321c95e3c8..00000000000 --- a/third_party/flatbuffers/docs/source/JavaScriptUsage.md +++ /dev/null @@ -1,105 +0,0 @@ -Use in JavaScript {#flatbuffers_guide_use_javascript} -================= - -## Before you get started - -Before diving into the FlatBuffers usage in JavaScript, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to -general FlatBuffers usage in all of the supported languages -(including JavaScript). This page is specifically designed to cover the nuances -of FlatBuffers usage in JavaScript. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers JavaScript library code location - -The code for the FlatBuffers JavaScript library can be found at -`flatbuffers/js`. You can browse the library code on the [FlatBuffers -GitHub page](https://github.com/google/flatbuffers/tree/master/js). - -## Testing the FlatBuffers JavaScript library - -The code to test the JavaScript library can be found at `flatbuffers/tests`. -The test code itself is located in [JavaScriptTest.js](https://github.com/ -google/flatbuffers/blob/master/tests/JavaScriptTest.js). - -To run the tests, use the [JavaScriptTest.sh](https://github.com/google/ -flatbuffers/blob/master/tests/JavaScriptTest.sh) shell script. - -*Note: The JavaScript test file requires [Node.js](https://nodejs.org/en/).* - -## Using the FlatBuffers JavaScript libary - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in JavaScript.* - -FlatBuffers supports both reading and writing FlatBuffers in JavaScript. - -To use FlatBuffers in your own code, first generate JavaScript classes from your -schema with the `--js` option to `flatc`. Then you can include both FlatBuffers -and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Javascript: -First, include the library and generated code. Then read the file into an -`Uint8Array`. Make a `flatbuffers.ByteBuffer` out of the `Uint8Array`, and pass -the ByteBuffer to the `getRootAsMonster` function. - -*Note: Both JavaScript module loaders (e.g. Node.js) and browser-based -HTML/JavaScript code segments are shown below in the following snippet:* - -~~~{.js} - // Note: These require functions are specific to JavaScript module loaders - // (namely, Node.js). See below for a browser-based example. - var fs = require('fs'); - - var flatbuffers = require('../flatbuffers').flatbuffers; - var MyGame = require('./monster_generated').MyGame; - - var data = new Uint8Array(fs.readFileSync('monster.dat')); - var buf = new flatbuffers.ByteBuffer(data); - - var monster = MyGame.Example.Monster.getRootAsMonster(buf); - - //--------------------------------------------------------------------------// - - // Note: This code is specific to browser-based HTML/JavaScript. See above - // for the code using JavaScript module loaders (e.g. Node.js). - - - - - // Open the HTML file in a browser and select "monster.dat" from with the - // field. - -~~~ - -Now you can access values like this: - -~~~{.js} - var hp = monster.hp(); - var pos = monster.pos(); -~~~ - -## Text parsing FlatBuffers in JavaScript - -There currently is no support for parsing text (Schema's and JSON) directly -from JavaScript. diff --git a/third_party/flatbuffers/docs/source/KotlinUsage.md b/third_party/flatbuffers/docs/source/KotlinUsage.md deleted file mode 100644 index 092fcd7f5b2..00000000000 --- a/third_party/flatbuffers/docs/source/KotlinUsage.md +++ /dev/null @@ -1,84 +0,0 @@ -Use in Kotlin {#flatbuffers_guide_use_kotlin} -============== - -## Before you get started - -Before diving into the FlatBuffers usage in Kotlin, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to -general FlatBuffers usage in all of the supported languages (including K). - -This page is designed to cover the nuances of FlatBuffers usage, specific to Kotlin. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## Kotlin and FlatBuffers Java code location - -Code generated for Kotlin currently uses the flatbuffers java runtime library. That means that Kotlin generated code can only have Java virtual machine as target architecture (which includes Android). Kotlin Native and Kotlin.js are currently not supported. - -The code for the FlatBuffers Java library can be found at -`flatbuffers/java/com/google/flatbuffers`. You can browse the library on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ -java/com/google/flatbuffers). - -## Testing FlatBuffers Kotlin - -The test code for Java is located in [KotlinTest.java](https://github.com/google -/flatbuffers/blob/master/tests/KotlinTest.kt). - -To run the tests, use [KotlinTest.sh](https://github.com/google/ -flatbuffers/blob/master/tests/KotlinTest.sh) shell script. - -*Note: These scripts require that [Kotlin](https://kotlinlang.org/) is installed.* - -## Using the FlatBuffers Kotlin library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Kotlin.* - -FlatBuffers supports reading and writing binary FlatBuffers in Kotlin. - -To use FlatBuffers in your own code, first generate Java classes from your -schema with the `--kotlin` option to `flatc`. -Then you can include both FlatBuffers and the generated code to read -or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Kotlin: -First, import the library and generated code. Then, you read a FlatBuffer binary -file into a `ByteArray`. You then turn the `ByteArray` into a `ByteBuffer`, which you -pass to the `getRootAsMyRootType` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.kt} - import MyGame.Example.* - import com.google.flatbuffers.FlatBufferBuilder - - // This snippet ignores exceptions for brevity. - val data = RandomAccessFile(File("monsterdata_test.mon"), "r").use { - val temp = ByteArray(it.length().toInt()) - it.readFully(temp) - temp - } - - val bb = ByteBuffer.wrap(data) - val monster = Monster.getRootAsMonster(bb) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access the data from the `Monster monster`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.kt} - val hp = monster.hp - val pos = monster.pos!!; -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - -## Differences between Kotlin and Java code - -Kotlin generated code was designed to be as close as possible to the java counterpart, as for now, we only support kotlin on java virtual machine. So the differences in implementation and usage are basically the ones introduced by the Kotlin language itself. You can find more in-depth information [here](https://kotlinlang.org/docs/reference/comparison-to-java.html). - -The most obvious ones are: - -* Fields as accessed as Kotlin [properties](https://kotlinlang.org/docs/reference/properties.html) -* Static methods are accessed in [companion object](https://kotlinlang.org/docs/reference/classes.html#companion-objects) \ No newline at end of file diff --git a/third_party/flatbuffers/docs/source/LobsterUsage.md b/third_party/flatbuffers/docs/source/LobsterUsage.md deleted file mode 100644 index 9d69caf85ff..00000000000 --- a/third_party/flatbuffers/docs/source/LobsterUsage.md +++ /dev/null @@ -1,85 +0,0 @@ -Use in Lobster {#flatbuffers_guide_use_lobster} -============== - -## Before you get started - -Before diving into the FlatBuffers usage in Lobster, it should be noted that the -[Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to general -FlatBuffers usage in all of the supported languages (including Lobster). This -page is designed to cover the nuances of FlatBuffers usage, specific to -Lobster. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Lobster library code location - -The code for the FlatBuffers Lobster library can be found at -`flatbuffers/lobster`. You can browse the library code on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ -lobster). - -## Testing the FlatBuffers Lobster library - -The code to test the Lobster library can be found at `flatbuffers/tests`. -The test code itself is located in [lobstertest.lobster](https://github.com/google/ -flatbuffers/blob/master/tests/lobstertest.lobster). - -To run the tests, run `lobster lobstertest.lobster`. To obtain Lobster itself, -go to the [Lobster homepage](http://strlen.com/lobster) or -[github](https://github.com/aardappel/lobster) to learn how to build it for your -platform. - -## Using the FlatBuffers Lobster library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Lobster.* - -There is support for both reading and writing FlatBuffers in Lobster. - -To use FlatBuffers in your own code, first generate Lobster classes from your -schema with the `--lobster` option to `flatc`. Then you can include both -FlatBuffers and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Lobster: -First, import the library and the generated code. Then read a FlatBuffer binary -file into a string, which you pass to the `GetRootAsMonster` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lobster} - include "monster_generated.lobster" - - let fb = read_file("monsterdata_test.mon") - assert fb - let monster = MyGame_Example_GetRootAsMonster(fb) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access values like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lobster} - let hp = monster.hp - let pos = monster.pos -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -As you can see, even though `hp` and `pos` are functions that access FlatBuffer -data in-place in the string buffer, they appear as field accesses. - -## Speed - -Using FlatBuffers in Lobster should be relatively fast, as the implementation -makes use of native support for writing binary values, and access of vtables. -Both generated code and the runtime library are therefore small and fast. - -Actual speed will depend on wether you use Lobster as bytecode VM or compiled to -C++. - -## Text Parsing - -Lobster has full support for parsing JSON into FlatBuffers, or generating -JSON from FlatBuffers. See `samples/sample_test.lobster` for an example. - -This uses the C++ parser and generator underneath, so should be both fast and -conformant. - -
diff --git a/third_party/flatbuffers/docs/source/LuaUsage.md b/third_party/flatbuffers/docs/source/LuaUsage.md deleted file mode 100644 index 75b1f3b8a8d..00000000000 --- a/third_party/flatbuffers/docs/source/LuaUsage.md +++ /dev/null @@ -1,81 +0,0 @@ -Use in Lua {#flatbuffers_guide_use_lua} -============= - -## Before you get started - -Before diving into the FlatBuffers usage in Lua, it should be noted that the -[Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to general -FlatBuffers usage in all of the supported languages (including Lua). This -page is designed to cover the nuances of FlatBuffers usage, specific to -Lua. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Lua library code location - -The code for the FlatBuffers Lua library can be found at -`flatbuffers/lua`. You can browse the library code on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/lua). - -## Testing the FlatBuffers Lua library - -The code to test the Lua library can be found at `flatbuffers/tests`. -The test code itself is located in [luatest.lua](https://github.com/google/ -flatbuffers/blob/master/tests/luatest.lua). - -To run the tests, use the [LuaTest.sh](https://github.com/google/flatbuffers/ -blob/master/tests/LuaTest.sh) shell script. - -*Note: This script requires [Lua 5.3](https://www.lua.org/) to be -installed.* - -## Using the FlatBuffers Lua library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Lua.* - -There is support for both reading and writing FlatBuffers in Lua. - -To use FlatBuffers in your own code, first generate Lua classes from your -schema with the `--lua` option to `flatc`. Then you can include both -FlatBuffers and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Lua: -First, require the module and the generated code. Then read a FlatBuffer binary -file into a `string`, which you pass to the `GetRootAsMonster` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lua} - -- require the library - local flatbuffers = require("flatbuffers") - - -- require the generated code - local monster = require("MyGame.Sample.Monster") - - -- read the flatbuffer from a file into a string - local f = io.open('monster.dat', 'rb') - local buf = f:read('*a') - f:close() - - -- parse the flatbuffer to get an instance to the root monster - local monster1 = monster.GetRootAsMonster(buf, 0) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access values like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lua} - -- use the : notation to access member data - local hp = monster1:Hp() - local pos = monster1:Pos() -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -## Text Parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from Lua, though you could use the C++ parser through SWIG or ctypes. Please -see the C++ documentation for more on text parsing. - -
diff --git a/third_party/flatbuffers/docs/source/PHPUsage.md b/third_party/flatbuffers/docs/source/PHPUsage.md deleted file mode 100644 index cdff44954dd..00000000000 --- a/third_party/flatbuffers/docs/source/PHPUsage.md +++ /dev/null @@ -1,89 +0,0 @@ -Use in PHP {#flatbuffers_guide_use_php} -========== - -## Before you get started - -Before diving into the FlatBuffers usage in PHP, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to -general FlatBuffers usage in all of the supported languages -(including PHP). This page is specifically designed to cover the nuances of -FlatBuffers usage in PHP. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers PHP library code location - -The code for FlatBuffers PHP library can be found at `flatbuffers/php`. You -can browse the library code on the [FlatBuffers -GitHub page](https://github.com/google/flatbuffers/tree/master/php). - -## Testing the FlatBuffers JavaScript library - -The code to test the PHP library can be found at `flatbuffers/tests`. -The test code itself is located in [phpTest.php](https://github.com/google/ -flatbuffers/blob/master/tests/phpTest.php). - -You can run the test with `php phpTest.php` from the command line. - -*Note: The PHP test file requires -[PHP](http://php.net/manual/en/install.php) to be installed.* - -## Using theFlatBuffers PHP library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in PHP.* - -FlatBuffers supports both reading and writing FlatBuffers in PHP. - -To use FlatBuffers in your own code, first generate PHP classes from your schema -with the `--php` option to `flatc`. Then you can include both FlatBuffers and -the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in PHP: -First, include the library and generated code (using the PSR `autoload` -function). Then you can read a FlatBuffer binary file, which you -pass the contents of to the `GetRootAsMonster` function: - -~~~{.php} - // It is recommended that your use PSR autoload when using FlatBuffers in PHP. - // Here is an example: - function __autoload($class_name) { - // The last segment of the class name matches the file name. - $class = substr($class_name, strrpos($class_name, "\\") + 1); - $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root. - - // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files. - $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")), - join(DIRECTORY_SEPARATOR, array($root_dir, "tests", "MyGame", "Example"))); - foreach ($paths as $path) { - $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php")); - if (file_exists($file)) { - require($file); - break; - } - } - - // Read the contents of the FlatBuffer binary file. - $filename = "monster.dat"; - $handle = fopen($filename, "rb"); - $contents = $fread($handle, filesize($filename)); - fclose($handle); - - // Pass the contents to `GetRootAsMonster`. - $monster = \MyGame\Example\Monster::GetRootAsMonster($contents); -~~~ - -Now you can access values like this: - -~~~{.php} - $hp = $monster->GetHp(); - $pos = $monster->GetPos(); -~~~ - -## Text Parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from PHP. diff --git a/third_party/flatbuffers/docs/source/PythonUsage.md b/third_party/flatbuffers/docs/source/PythonUsage.md deleted file mode 100644 index f338cda4368..00000000000 --- a/third_party/flatbuffers/docs/source/PythonUsage.md +++ /dev/null @@ -1,100 +0,0 @@ -Use in Python {#flatbuffers_guide_use_python} -============= - -## Before you get started - -Before diving into the FlatBuffers usage in Python, it should be noted that the -[Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to general -FlatBuffers usage in all of the supported languages (including Python). This -page is designed to cover the nuances of FlatBuffers usage, specific to -Python. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Python library code location - -The code for the FlatBuffers Python library can be found at -`flatbuffers/python/flatbuffers`. You can browse the library code on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ -python). - -## Testing the FlatBuffers Python library - -The code to test the Python library can be found at `flatbuffers/tests`. -The test code itself is located in [py_test.py](https://github.com/google/ -flatbuffers/blob/master/tests/py_test.py). - -To run the tests, use the [PythonTest.sh](https://github.com/google/flatbuffers/ -blob/master/tests/PythonTest.sh) shell script. - -*Note: This script requires [python](https://www.python.org/) to be -installed.* - -## Using the FlatBuffers Python library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Python.* - -There is support for both reading and writing FlatBuffers in Python. - -To use FlatBuffers in your own code, first generate Python classes from your -schema with the `--python` option to `flatc`. Then you can include both -FlatBuffers and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Python: -First, import the library and the generated code. Then read a FlatBuffer binary -file into a `bytearray`, which you pass to the `GetRootAsMonster` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} - import MyGame.Example as example - import flatbuffers - - buf = open('monster.dat', 'rb').read() - buf = bytearray(buf) - monster = example.GetRootAsMonster(buf, 0) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access values like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} - hp = monster.Hp() - pos = monster.Pos() -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -## Support for Numpy arrays - -The Flatbuffers python library also has support for accessing scalar -vectors as numpy arrays. This can be orders of magnitude faster than -iterating over the vector one element at a time, and is particularly -useful when unpacking large nested flatbuffers. The generated code for -a scalar vector will have a method `AsNumpy()`. In the -case of the Monster example, you could access the inventory vector -like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} - inventory = monster.InventoryAsNumpy() - # inventory is a numpy array of type np.dtype('uint8') -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -instead of - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} - inventory = [] - for i in range(monster.InventoryLength()): - inventory.append(int(monster.Inventory(i))) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Numpy is not a requirement. If numpy is not installed on your system, -then attempting to access one of the `*asNumpy()` methods will result -in a `NumpyRequiredForThisFeature` exception. - -## Text Parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from Python, though you could use the C++ parser through SWIG or ctypes. Please -see the C++ documentation for more on text parsing. - -
diff --git a/third_party/flatbuffers/docs/source/README_TO_GENERATE_DOCS.md b/third_party/flatbuffers/docs/source/README_TO_GENERATE_DOCS.md deleted file mode 100644 index 5df0b6a8b9b..00000000000 --- a/third_party/flatbuffers/docs/source/README_TO_GENERATE_DOCS.md +++ /dev/null @@ -1,32 +0,0 @@ -## Prerequisites - -To generate the docs for FlatBuffers from the source files, you -will first need to install two programs. - -1. You will need to install `doxygen`. See - [Download Doxygen](http://www.stack.nl/~dimitri/doxygen/download.html). - -2. You will need to install `doxypypy` to format python comments appropriately. - Install it from [here](https://github.com/Feneric/doxypypy). - -*Note: You will need both `doxygen` and `doxypypy` to be in your -[PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable.* - -After you have both of those files installed and in your path, you need to -set up the `py_filter` to invoke `doxypypy` from `doxygen`. - -Follow the steps -[here](https://github.com/Feneric/doxypypy#invoking-doxypypy-from-doxygen). - -## Generating Docs - -Run the following commands to generate the docs: - -`cd flatbuffers/docs/source` -`doxygen` - -The output is placed in `flatbuffers/docs/html`. - -*Note: The Go API Reference code must be generated ahead of time. For -instructions on how to regenerated this file, please read the comments -in `GoApi.md`.* diff --git a/third_party/flatbuffers/docs/source/RustUsage.md b/third_party/flatbuffers/docs/source/RustUsage.md deleted file mode 100644 index 68191179cec..00000000000 --- a/third_party/flatbuffers/docs/source/RustUsage.md +++ /dev/null @@ -1,174 +0,0 @@ -Use in Rust {#flatbuffers_guide_use_rust} -========== - -## Before you get started - -Before diving into the FlatBuffers usage in Rust, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide -to general FlatBuffers usage in all of the supported languages (including Rust). -This page is designed to cover the nuances of FlatBuffers usage, specific to -Rust. - -#### Prerequisites - -This page assumes you have written a FlatBuffers schema and compiled it -with the Schema Compiler. If you have not, please see -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) -and [Writing a schema](@ref flatbuffers_guide_writing_schema). - -Assuming you wrote a schema, say `mygame.fbs` (though the extension doesn't -matter), you've generated a Rust file called `mygame_generated.rs` using the -compiler (e.g. `flatc --rust mygame.fbs` or via helpers listed in "Useful -tools created by others" section bellow), you can now start using this in -your program by including the file. As noted, this header relies on the crate -`flatbuffers`, which should be in your include `Cargo.toml`. - -## FlatBuffers Rust library code location - -The code for the FlatBuffers Rust library can be found at -`flatbuffers/rust`. You can browse the library code on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/rust). - -## Testing the FlatBuffers Rust library - -The code to test the Rust library can be found at `flatbuffers/tests/rust_usage_test`. -The test code itself is located in -[integration_test.rs](https://github.com/google/flatbuffers/blob/master/tests/rust_usage_test/tests/integration_test.rs) - -This test file requires `flatc` to be present. To review how to build the project, -please read the [Building](@ref flatbuffers_guide_building) documenation. - -To run the tests, execute `RustTest.sh` from the `flatbuffers/tests` directory. -For example, on [Linux](https://en.wikipedia.org/wiki/Linux), you would simply -run: `cd tests && ./RustTest.sh`. - -*Note: The shell script requires [Rust](https://www.rust-lang.org) to -be installed.* - -## Using the FlatBuffers Rust library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Rust.* - -FlatBuffers supports both reading and writing FlatBuffers in Rust. - -To use FlatBuffers in your code, first generate the Rust modules from your -schema with the `--rust` option to `flatc`. Then you can import both FlatBuffers -and the generated code to read or write FlatBuffers. - -For example, here is how you would read a FlatBuffer binary file in Rust: -First, include the library and generated code. Then read the file into -a `u8` vector, which you pass, as a byte slice, to `get_root_as_monster()`. - -This full example program is available in the Rust test suite: -[monster_example.rs](https://github.com/google/flatbuffers/blob/master/tests/rust_usage_test/bin/monster_example.rs) - -It can be run by `cd`ing to the `rust_usage_test` directory and executing: `cargo run monster_example`. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.rs} - extern crate flatbuffers; - - #[allow(dead_code, unused_imports)] - #[path = "../../monster_test_generated.rs"] - mod monster_test_generated; - pub use monster_test_generated::my_game; - - use std::io::Read; - - fn main() { - let mut f = std::fs::File::open("../monsterdata_test.mon").unwrap(); - let mut buf = Vec::new(); - f.read_to_end(&mut buf).expect("file reading failed"); - - let monster = my_game::example::get_root_as_monster(&buf[..]); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -`monster` is of type `Monster`, and points to somewhere *inside* your -buffer (root object pointers are not the same as `buffer_pointer` !). -If you look in your generated header, you'll see it has -convenient accessors for all fields, e.g. `hp()`, `mana()`, etc: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.rs} - println!("{}", monster.hp()); // `80` - println!("{}", monster.mana()); // default value of `150` - println!("{:?}", monster.name()); // Some("MyMonster") - } -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -*Note: That we never stored a `mana` value, so it will return the default.* - -## Direct memory access - -As you can see from the above examples, all elements in a buffer are -accessed through generated accessors. This is because everything is -stored in little endian format on all platforms (the accessor -performs a swap operation on big endian machines), and also because -the layout of things is generally not known to the user. - -For structs, layout is deterministic and guaranteed to be the same -across platforms (scalars are aligned to their -own size, and structs themselves to their largest member), and you -are allowed to access this memory directly by using `safe_slice` and -on the reference to a struct, or even an array of structs. - -To compute offsets to sub-elements of a struct, make sure they -are structs themselves, as then you can use the pointers to -figure out the offset without having to hardcode it. This is -handy for use of arrays of structs with calls like `glVertexAttribPointer` -in OpenGL or similar APIs. - -It is important to note is that structs are still little endian on all -machines, so only use tricks like this if you can guarantee you're not -shipping on a big endian machine (using an `#[cfg(target_endian = "little")]` -attribute would be wise). - -The special function `safe_slice` is implemented on Vector objects that are -represented in memory the same way as they are represented on the wire. This -function is always available on vectors of struct, bool, u8, and i8. It is -conditionally-compiled on little-endian systems for all the remaining scalar -types. - -The FlatBufferBuilder function `create_vector_direct` is implemented for all -types that are endian-safe to write with a `memcpy`. It is the write-equivalent -of `safe_slice`. - -## Access of untrusted buffers - -The generated accessor functions access fields over offsets, which is -very quick. These offsets are used to index into Rust slices, so they are -bounds-checked by the Rust runtime. However, our Rust implementation may -change: we may convert access functions to use direct pointer dereferencing, to -improve lookup speed. As a result, users should not rely on the aforementioned -bounds-checking behavior. - -When you're processing large amounts of data from a source you know (e.g. -your own generated data on disk), this is acceptable, but when reading -data from the network that can potentially have been modified by an -attacker, this is undesirable. - -The C++ port provides a buffer verifier. At this time, Rust does not. Rust may -provide a verifier in a future version. In the meantime, Rust users can access -the buffer verifier generated by the C++ port through a foreign function -interface (FFI). - -## Threading - -Reading a FlatBuffer does not touch any memory outside the original buffer, -and is entirely read-only (all immutable), so is safe to access from multiple -threads even without synchronisation primitives. - -Creating a FlatBuffer is not thread safe. All state related to building -a FlatBuffer is contained in a FlatBufferBuilder instance, and no memory -outside of it is touched. To make this thread safe, either do not -share instances of FlatBufferBuilder between threads (recommended), or -manually wrap it in synchronisation primitives. There's no automatic way to -accomplish this, by design, as we feel multithreaded construction -of a single buffer will be rare, and synchronisation overhead would be costly. - -## Useful tools created by others - -* [flatc-rust](https://github.com/frol/flatc-rust) - FlatBuffers compiler -(flatc) as API for transparent `.fbs` to `.rs` code-generation via Cargo -build scripts integration. - -
diff --git a/third_party/flatbuffers/docs/source/Schemas.md b/third_party/flatbuffers/docs/source/Schemas.md deleted file mode 100644 index 403aebbe0fe..00000000000 --- a/third_party/flatbuffers/docs/source/Schemas.md +++ /dev/null @@ -1,629 +0,0 @@ -Writing a schema {#flatbuffers_guide_writing_schema} -================ - -The syntax of the schema language (aka IDL, [Interface Definition Language][]) -should look quite familiar to users of any of the C family of -languages, and also to users of other IDLs. Let's look at an example -first: - - // example IDL file - - namespace MyGame; - - attribute "priority"; - - enum Color : byte { Red = 1, Green, Blue } - - union Any { Monster, Weapon, Pickup } - - struct Vec3 { - x:float; - y:float; - z:float; - } - - table Monster { - pos:Vec3; - mana:short = 150; - hp:short = 100; - name:string; - friendly:bool = false (deprecated, priority: 1); - inventory:[ubyte]; - color:Color = Blue; - test:Any; - } - - root_type Monster; - -(`Weapon` & `Pickup` not defined as part of this example). - -### Tables - -Tables are the main way of defining objects in FlatBuffers, and consist -of a name (here `Monster`) and a list of fields. Each field has a name, -a type, and optionally a default value (if omitted, it defaults to `0` / -`NULL`). - -Each field is optional: It does not have to appear in the wire -representation, and you can choose to omit fields for each individual -object. As a result, you have the flexibility to add fields without fear of -bloating your data. This design is also FlatBuffer's mechanism for forward -and backwards compatibility. Note that: - -- You can add new fields in the schema ONLY at the end of a table - definition. Older data will still - read correctly, and give you the default value when read. Older code - will simply ignore the new field. - If you want to have flexibility to use any order for fields in your - schema, you can manually assign ids (much like Protocol Buffers), - see the `id` attribute below. - -- You cannot delete fields you don't use anymore from the schema, - but you can simply - stop writing them into your data for almost the same effect. - Additionally you can mark them as `deprecated` as in the example - above, which will prevent the generation of accessors in the - generated C++, as a way to enforce the field not being used any more. - (careful: this may break code!). - -- You may change field names and table names, if you're ok with your - code breaking until you've renamed them there too. - -See "Schema evolution examples" below for more on this -topic. - -### Structs - -Similar to a table, only now none of the fields are optional (so no defaults -either), and fields may not be added or be deprecated. Structs may only contain -scalars or other structs. Use this for -simple objects where you are very sure no changes will ever be made -(as quite clear in the example `Vec3`). Structs use less memory than -tables and are even faster to access (they are always stored in-line in their -parent object, and use no virtual table). - -### Types - -Built-in scalar types are - -- 8 bit: `byte` (`int8`), `ubyte` (`uint8`), `bool` - -- 16 bit: `short` (`int16`), `ushort` (`uint16`) - -- 32 bit: `int` (`int32`), `uint` (`uint32`), `float` (`float32`) - -- 64 bit: `long` (`int64`), `ulong` (`uint64`), `double` (`float64`) - -The type names in parentheses are alias names such that for example -`uint8` can be used in place of `ubyte`, and `int32` can be used in -place of `int` without affecting code generation. - -Built-in non-scalar types: - -- Vector of any other type (denoted with `[type]`). Nesting vectors - is not supported, instead you can wrap the inner vector in a table. - -- `string`, which may only hold UTF-8 or 7-bit ASCII. For other text encodings - or general binary data use vectors (`[byte]` or `[ubyte]`) instead. - -- References to other tables or structs, enums or unions (see - below). - -You can't change types of fields once they're used, with the exception -of same-size data where a `reinterpret_cast` would give you a desirable result, -e.g. you could change a `uint` to an `int` if no values in current data use the -high bit yet. - -### Arrays - -Arrays are a convenience short-hand for a fixed-length collection of elements. -Arrays can be used to replace the following schema: - - struct Vec3 { - x:float; - y:float; - z:float; - } - -with the following schema: - - struct Vec3 { - v:[float:3]; - } - -Both representations are binary equivalent. - -Arrays are currently only supported in a `struct`. - -### (Default) Values - -Values are a sequence of digits. Values may be optionally followed by a decimal -point (`.`) and more digits, for float constants, or optionally prefixed by -a `-`. Floats may also be in scientific notation; optionally ending with an `e` -or `E`, followed by a `+` or `-` and more digits. - -Only scalar values can have defaults, non-scalar (string/vector/table) fields -default to `NULL` when not present. - -You generally do not want to change default values after they're initially -defined. Fields that have the default value are not actually stored in the -serialized data (see also Gotchas below) but are generated in code, -so when you change the default, you'd -now get a different value than from code generated from an older version of -the schema. There are situations, however, where this may be -desirable, especially if you can ensure a simultaneous rebuild of -all code. - -### Enums - -Define a sequence of named constants, each with a given value, or -increasing by one from the previous one. The default first value -is `0`. As you can see in the enum declaration, you specify the underlying -integral type of the enum with `:` (in this case `byte`), which then determines -the type of any fields declared with this enum type. - -Only integer types are allowed, i.e. `byte`, `ubyte`, `short` `ushort`, `int`, -`uint`, `long` and `ulong`. - -Typically, enum values should only ever be added, never removed (there is no -deprecation for enums). This requires code to handle forwards compatibility -itself, by handling unknown enum values. - -### Unions - -Unions share a lot of properties with enums, but instead of new names -for constants, you use names of tables. You can then declare -a union field, which can hold a reference to any of those types, and -additionally a field with the suffix `_type` is generated that holds -the corresponding enum value, allowing you to know which type to cast -to at runtime. - -It's possible to give an alias name to a type union. This way a type can even be -used to mean different things depending on the name used: - - table PointPosition { x:uint; y:uint; } - table MarkerPosition {} - union Position { - Start:MarkerPosition, - Point:PointPosition, - Finish:MarkerPosition - } - -Unions contain a special `NONE` marker to denote that no value is stored so that -name cannot be used as an alias. - -Unions are a good way to be able to send multiple message types as a FlatBuffer. -Note that because a union field is really two fields, it must always be -part of a table, it cannot be the root of a FlatBuffer by itself. - -If you have a need to distinguish between different FlatBuffers in a more -open-ended way, for example for use as files, see the file identification -feature below. - -There is an experimental support only in C++ for a vector of unions -(and types). In the example IDL file above, use [Any] to add a -vector of Any to Monster table. - -### Namespaces - -These will generate the corresponding namespace in C++ for all helper -code, and packages in Java. You can use `.` to specify nested namespaces / -packages. - -### Includes - -You can include other schemas files in your current one, e.g.: - - include "mydefinitions.fbs"; - -This makes it easier to refer to types defined elsewhere. `include` -automatically ensures each file is parsed just once, even when referred to -more than once. - -When using the `flatc` compiler to generate code for schema definitions, -only definitions in the current file will be generated, not those from the -included files (those you still generate separately). - -### Root type - -This declares what you consider to be the root table (or struct) of the -serialized data. This is particularly important for parsing JSON data, -which doesn't include object type information. - -### File identification and extension - -Typically, a FlatBuffer binary buffer is not self-describing, i.e. it -needs you to know its schema to parse it correctly. But if you -want to use a FlatBuffer as a file format, it would be convenient -to be able to have a "magic number" in there, like most file formats -have, to be able to do a sanity check to see if you're reading the -kind of file you're expecting. - -Now, you can always prefix a FlatBuffer with your own file header, -but FlatBuffers has a built-in way to add an identifier to a -FlatBuffer that takes up minimal space, and keeps the buffer -compatible with buffers that don't have such an identifier. - -You can specify in a schema, similar to `root_type`, that you intend -for this type of FlatBuffer to be used as a file format: - - file_identifier "MYFI"; - -Identifiers must always be exactly 4 characters long. These 4 characters -will end up as bytes at offsets 4-7 (inclusive) in the buffer. - -For any schema that has such an identifier, `flatc` will automatically -add the identifier to any binaries it generates (with `-b`), -and generated calls like `FinishMonsterBuffer` also add the identifier. -If you have specified an identifier and wish to generate a buffer -without one, you can always still do so by calling -`FlatBufferBuilder::Finish` explicitly. - -After loading a buffer, you can use a call like -`MonsterBufferHasIdentifier` to check if the identifier is present. - -Note that this is best for open-ended uses such as files. If you simply wanted -to send one of a set of possible messages over a network for example, you'd -be better off with a union. - -Additionally, by default `flatc` will output binary files as `.bin`. -This declaration in the schema will change that to whatever you want: - - file_extension "ext"; - -### RPC interface declarations - -You can declare RPC calls in a schema, that define a set of functions -that take a FlatBuffer as an argument (the request) and return a FlatBuffer -as the response (both of which must be table types): - - rpc_service MonsterStorage { - Store(Monster):StoreResponse; - Retrieve(MonsterId):Monster; - } - -What code this produces and how it is used depends on language and RPC system -used, there is preliminary support for GRPC through the `--grpc` code generator, -see `grpc/tests` for an example. - -### Comments & documentation - -May be written as in most C-based languages. Additionally, a triple -comment (`///`) on a line by itself signals that a comment is documentation -for whatever is declared on the line after it -(table/struct/field/enum/union/element), and the comment is output -in the corresponding C++ code. Multiple such lines per item are allowed. - -### Attributes - -Attributes may be attached to a declaration, behind a field, or after -the name of a table/struct/enum/union. These may either have a value or -not. Some attributes like `deprecated` are understood by the compiler; -user defined ones need to be declared with the attribute declaration -(like `priority` in the example above), and are -available to query if you parse the schema at runtime. -This is useful if you write your own code generators/editors etc., and -you wish to add additional information specific to your tool (such as a -help text). - -Current understood attributes: - -- `id: n` (on a table field): manually set the field identifier to `n`. - If you use this attribute, you must use it on ALL fields of this table, - and the numbers must be a contiguous range from 0 onwards. - Additionally, since a union type effectively adds two fields, its - id must be that of the second field (the first field is the type - field and not explicitly declared in the schema). - For example, if the last field before the union field had id 6, - the union field should have id 8, and the unions type field will - implicitly be 7. - IDs allow the fields to be placed in any order in the schema. - When a new field is added to the schema it must use the next available ID. -- `deprecated` (on a field): do not generate accessors for this field - anymore, code should stop using this data. Old data may still contain this - field, but it won't be accessible anymore by newer code. Note that if you - deprecate a field that was previous required, old code may fail to validate - new data (when using the optional verifier). -- `required` (on a non-scalar table field): this field must always be set. - By default, all fields are optional, i.e. may be left out. This is - desirable, as it helps with forwards/backwards compatibility, and - flexibility of data structures. It is also a burden on the reading code, - since for non-scalar fields it requires you to check against NULL and - take appropriate action. By specifying this field, you force code that - constructs FlatBuffers to ensure this field is initialized, so the reading - code may access it directly, without checking for NULL. If the constructing - code does not initialize this field, they will get an assert, and also - the verifier will fail on buffers that have missing required fields. Note - that if you add this attribute to an existing field, this will only be - valid if existing data always contains this field / existing code always - writes this field. -- `force_align: size` (on a struct): force the alignment of this struct - to be something higher than what it is naturally aligned to. Causes - these structs to be aligned to that amount inside a buffer, IF that - buffer is allocated with that alignment (which is not necessarily - the case for buffers accessed directly inside a `FlatBufferBuilder`). - Note: currently not guaranteed to have an effect when used with - `--object-api`, since that may allocate objects at alignments less than - what you specify with `force_align`. -- `bit_flags` (on an unsigned enum): the values of this field indicate bits, - meaning that any unsigned value N specified in the schema will end up - representing 1< - -### Testing whether a field is present in a table - -Most serialization formats (e.g. JSON or Protocol Buffers) make it very -explicit in the format whether a field is present in an object or not, -allowing you to use this as "extra" information. - -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 diff --git a/third_party/flatbuffers/docs/source/Support.md b/third_party/flatbuffers/docs/source/Support.md deleted file mode 100644 index c8ac7f7e89d..00000000000 --- a/third_party/flatbuffers/docs/source/Support.md +++ /dev/null @@ -1,46 +0,0 @@ -Platform / Language / Feature support {#flatbuffers_support} -===================================== - -FlatBuffers is actively being worked on, which means that certain platform / -language / feature combinations may not be available yet. - -This page tries to track those issues, to make informed decisions easier. -In general: - - * Languages: language support beyond the ones created by the original - FlatBuffer authors typically depends on community contributions. - * Features: C++ was the first language supported, since our original - target was high performance game development. It thus has the richest - feature set, and is likely most robust. Other languages are catching up - however. - * Platforms: All language implementations are typically portable to most - platforms, unless where noted otherwise. - -NOTE: this table is a start, it needs to be extended. - -Feature | C++ | Java | C# | Go | Python | JS | TS | C | PHP | Dart | Lobster | Rust ------------------------------- | ------ | ------ | ------ | ------ | ------ | --------- | --------- | ------ | --- | ------- | ------- | ---- -Codegen for all basic features | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | WiP | Yes | Yes | Yes -JSON parsing | Yes | No | No | No | No | No | No | Yes | No | No | Yes | No -Simple mutation | Yes | Yes | Yes | Yes | No | No | No | No | No | No | No | No -Reflection | Yes | No | No | No | No | No | No | Basic | No | No | No | No -Buffer verifier | Yes | No | No | No | No | No | No | Yes | No | No | No | No -Testing: basic | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | ? | Yes | Yes | Yes -Testing: fuzz | Yes | No | No | Yes | Yes | No | No | No | ? | No | No | Yes -Performance: | Superb | Great | Great | Great | Ok | ? | ? | Superb | ? | ? | Great | Superb -Platform: Windows | VS2010 | Yes | Yes | ? | ? | ? | Yes | VS2010 | ? | Yes | Yes | Yes -Platform: Linux | GCC282 | Yes | ? | Yes | Yes | ? | Yes | Yes | ? | Yes | Yes | Yes -Platform: OS X | Xcode4 | ? | ? | ? | Yes | ? | Yes | Yes | ? | Yes | Yes | Yes -Platform: Android | NDK10d | Yes | ? | ? | ? | ? | ? | ? | ? | Flutter | Yes | ? -Platform: iOS | ? | ? | ? | ? | ? | ? | ? | ? | ? | Flutter | Yes | ? -Engine: Unity | ? | ? | Yes | ? | ? | ? | ? | ? | ? | ? | No | ? -Primary authors (github) | aard* | aard* | ev*/js*| rw | rw | evanw/ev* | kr* | mik* | ch* | dnfield | aard* | rw - - * aard = aardappel (previously: gwvo) - * ev = evolutional - * js = jonsimantov - * mik = mikkelfj - * ch = chobie - * kr = krojew - -
diff --git a/third_party/flatbuffers/docs/source/Tutorial.md b/third_party/flatbuffers/docs/source/Tutorial.md deleted file mode 100644 index e8d8519be6f..00000000000 --- a/third_party/flatbuffers/docs/source/Tutorial.md +++ /dev/null @@ -1,3219 +0,0 @@ -Tutorial {#flatbuffers_guide_tutorial} -======== - -## Overview - -This tutorial provides a basic example of how to work with -[FlatBuffers](@ref flatbuffers_overview). We will step through a simple example -application, which shows you how to: - - - Write a FlatBuffer `schema` file. - - Use the `flatc` FlatBuffer compiler. - - Parse [JSON](http://json.org) files that conform to a schema into - FlatBuffer binary files. - - Use the generated files in many of the supported languages (such as C++, - Java, and more.) - -During this example, imagine that you are creating a game where the main -character, the hero of the story, needs to slay some `orc`s. We will walk -through each step necessary to create this monster type using FlatBuffers. - -Please select your desired language for our quest: -\htmlonly -
- C++ - Java - Kotlin - C# - Go - Python - JavaScript - TypeScript - PHP - C - Dart - Lua - Lobster - Rust -
-\endhtmlonly - -\htmlonly - -\endhtmlonly - -## Where to Find the Example Code - -Samples demonstating the concepts in this example are located in the source code -package, under the `samples` directory. You can browse the samples on GitHub -[here](https://github.com/google/flatbuffers/tree/master/samples). - -
-*Note: The above does not apply to C, instead [look here](https://github.com/dvidelabs/flatcc/tree/master/samples).* -
- -For your chosen language, please cross-reference with: - -
-[sample_binary.cpp](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp) -
-
-[SampleBinary.java](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.java) -
-
-[SampleBinary.kt](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.kt) -
-
-[SampleBinary.cs](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.cs) -
-
-[sample_binary.go](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.go) -
-
-[sample_binary.py](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.py) -
-
-[samplebinary.js](https://github.com/google/flatbuffers/blob/master/samples/samplebinary.js) -
-
-none yet -
-
-[SampleBinary.php](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.php) -
-
-[monster.c](https://github.com/dvidelabs/flatcc/blob/master/samples/monster/monster.c) -
-
-[example.dart](https://github.com/google/flatbuffers/blob/master/dart/example/example.dart) -
-
-[sample_binary.lua](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.lua) -
-
-[sample_binary.lobster](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.lobster) -
-
-[sample_binary.rs](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs) -
- - -## Writing the Monsters' FlatBuffer Schema - -To start working with FlatBuffers, you first need to create a `schema` file, -which defines the format for each data structure you wish to serialize. Here is -the `schema` that defines the template for our monsters: - -~~~ - // Example IDL file for our monster's schema. - - namespace MyGame.Sample; - - enum Color:byte { Red = 0, Green, Blue = 2 } - - union Equipment { Weapon } // Optionally add more tables. - - struct Vec3 { - x:float; - y:float; - z:float; - } - - table Monster { - pos:Vec3; // Struct. - mana:short = 150; - hp:short = 100; - name:string; - friendly:bool = false (deprecated); - inventory:[ubyte]; // Vector of scalars. - color:Color = Blue; // Enum. - weapons:[Weapon]; // Vector of tables. - equipped:Equipment; // Union. - path:[Vec3]; // Vector of structs. - } - - table Weapon { - name:string; - damage:short; - } - - root_type Monster; -~~~ - -As you can see, the syntax for the `schema` -[Interface Definition Language (IDL)](https://en.wikipedia.org/wiki/Interface_description_language) -is similar to those of the C family of languages, and other IDL languages. Let's -examine each part of this `schema` to determine what it does. - -The `schema` starts with a `namespace` declaration. This determines the -corresponding package/namespace for the generated code. In our example, we have -the `Sample` namespace inside of the `MyGame` namespace. - -Next, we have an `enum` definition. In this example, we have an `enum` of type -`byte`, named `Color`. We have three values in this `enum`: `Red`, `Green`, and -`Blue`. We specify `Red = 0` and `Blue = 2`, but we do not specify an explicit -value for `Green`. Since the behavior of an `enum` is to increment if -unspecified, `Green` will receive the implicit value of `1`. - -Following the `enum` is a `union`. The `union` in this example is not very -useful, as it only contains the one `table` (named `Weapon`). If we had created -multiple tables that we would want the `union` to be able to reference, we -could add more elements to the `union Equipment`. - -After the `union` comes a `struct Vec3`, which represents a floating point -vector with `3` dimensions. We use a `struct` here, over a `table`, because -`struct`s are ideal for data structures that will not change, since they use -less memory and have faster lookup. - -The `Monster` table is the main object in our FlatBuffer. This will be used as -the template to store our `orc` monster. We specify some default values for -fields, such as `mana:short = 150`. All unspecified fields will default to `0` -or `NULL`. Another thing to note is the line -`friendly:bool = false (deprecated);`. Since you cannot delete fields from a -`table` (to support backwards compatability), you can set fields as -`deprecated`, which will prevent the generation of accessors for this field in -the generated code. Be careful when using `deprecated`, however, as it may break -legacy code that used this accessor. - -The `Weapon` table is a sub-table used within our FlatBuffer. It is -used twice: once within the `Monster` table and once within the `Equipment` -enum. For our `Monster`, it is used to populate a `vector of tables` via the -`weapons` field within our `Monster`. It is also the only table referenced by -the `Equipment` union. - -The last part of the `schema` is the `root_type`. The root type declares what -will be the root table for the serialized data. In our case, the root type is -our `Monster` table. - -The scalar types can also use alias type names such as `int16` instead -of `short` and `float32` instead of `float`. Thus we could also write -the `Weapon` table as: - - table Weapon { - name:string; - damage:int16; - } - -#### More Information About Schemas - -You can find a complete guide to writing `schema` files in the -[Writing a schema](@ref flatbuffers_guide_writing_schema) section of the -Programmer's Guide. You can also view the formal -[Grammar of the schema language](@ref flatbuffers_grammar). - -## Compiling the Monsters' Schema - -After you have written the FlatBuffers schema, the next step is to compile it. - -If you have not already done so, please follow -[these instructions](@ref flatbuffers_guide_building) to build `flatc`, the -FlatBuffer compiler. - -Once `flatc` is built successfully, compile the schema for your language: - -
-*Note: If you're working in C, you need to use the separate project [FlatCC](https://github.com/dvidelabs/flatcc) which contains a schema compiler and runtime library in C for C.* -
-See [flatcc build instructions](https://github.com/dvidelabs/flatcc#building). -
-Please be aware of the difference between `flatc` and `flatcc` tools. -
-
- -
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --cpp monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --java monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --kotlin monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --csharp monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --go monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --python monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --js monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --ts monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/sample - ./../flatc --php monster.fbs -~~~ -
-
-~~~{.sh} - cd flatcc - mkdir -p build/tmp/samples/monster - bin/flatcc -a -o build/tmp/samples/monster samples/monster/monster.fbs - # or just - flatcc/samples/monster/build.sh -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --dart monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --lua monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --lobster monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --rust monster.fbs -~~~ -
- -For a more complete guide to using the `flatc` compiler, please read the -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) -section of the Programmer's Guide. - -## Reading and Writing Monster FlatBuffers - -Now that we have compiled the schema for our programming language, we can -start creating some monsters and serializing/deserializing them from -FlatBuffers. - -#### Creating and Writing Orc FlatBuffers - -The first step is to import/include the library, generated files, etc. - -
-~~~{.cpp} - #include "monster_generated.h" // This was generated by `flatc`. - - using namespace MyGame::Sample; // Specified in the schema. -~~~ -
-
-~~~{.java} - import MyGame.Sample.*; //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder; -~~~ -
-
-~~~{.kotlin} - import MyGame.Sample.* //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder -~~~ -
-
-~~~{.cs} - using FlatBuffers; - using MyGame.Sample; // The `flatc` generated files. (Monster, Vec3, etc.) -~~~ -
-
-~~~{.go} - import ( - flatbuffers "github.com/google/flatbuffers/go" - sample "MyGame/Sample" - ) -~~~ -
-
-~~~{.py} - import flatbuffers - - # Generated by `flatc`. - import MyGame.Sample.Color - import MyGame.Sample.Equipment - import MyGame.Sample.Monster - import MyGame.Sample.Vec3 - import MyGame.Sample.Weapon -~~~ -
-
-~~~{.js} - // The following code is for JavaScript module loaders (e.g. Node.js). See - // below for a browser-based HTML/JavaScript example of including the library. - var flatbuffers = require('/js/flatbuffers').flatbuffers; - var MyGame = require('./monster_generated').MyGame; // Generated by `flatc`. - - //--------------------------------------------------------------------------// - - // The following code is for browser-based HTML/JavaScript. Use the above code - // for JavaScript module loaders (e.g. Node.js). - - // Generated by `flatc`. -~~~ -
-
- // note: import flatbuffers with your desired import method - - import { MyGame } from './monster_generated'; -
-
-~~~{.php} - // It is recommended that your use PSR autoload when using FlatBuffers in PHP. - // Here is an example from `SampleBinary.php`: - function __autoload($class_name) { - // The last segment of the class name matches the file name. - $class = substr($class_name, strrpos($class_name, "\\") + 1); - $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root. - - // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files. - $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")), - join(DIRECTORY_SEPARATOR, array($root_dir, "samples", "MyGame", "Sample"))); - foreach ($paths as $path) { - $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php")); - if (file_exists($file)) { - require($file); - break; - } - } - } -~~~ -
-
-~~~{.c} - #include "monster_builder.h" // Generated by `flatcc`. - - // Convenient namespace macro to manage long namespace prefix. - #undef ns - #define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Sample, x) // Specified in the schema. - - // A helper to simplify creating vectors from C-arrays. - #define c_vec_len(V) (sizeof(V)/sizeof((V)[0])) -~~~ -
-
-~~~{.dart} - import 'package:flat_buffers/flat_buffers.dart' as fb; - - // Generated by `flatc`. - import 'monster_my_game.sample_generated.dart' as myGame; -~~~ -
-
-~~~{.lua} - -- require the flatbuffers module - local flatbuffers = require("flatbuffers") - - -- require the generated files from `flatc`. - local color = require("MyGame.Sample.Color") - local equipment = require("MyGame.Sample.Equipment") - local monster = require("MyGame.Sample.Monster") - local vec3 = require("MyGame.Sample.Vec3") - local weapon = require("MyGame.Sample.Weapon") -~~~ -
-
-~~~{.lobster} - import from "../lobster/" // Where to find flatbuffers.lobster - import monster_generated -~~~ -
-
-~~~{.rs} - // import the flatbuffers runtime library - extern crate flatbuffers; - - // import the generated code - #[allow(dead_code, unused_imports)] - #[path = "./monster_generated.rs"] - mod monster_generated; - pub use monster_generated::my_game::sample::{get_root_as_monster, - Color, Equipment, - Monster, MonsterArgs, - Vec3, - Weapon, WeaponArgs}; -~~~ -
- -Now we are ready to start building some buffers. In order to start, we need -to create an instance of the `FlatBufferBuilder`, which will contain the buffer -as it grows. You can pass an initial size of the buffer (here 1024 bytes), -which will grow automatically if needed: - -
-~~~{.cpp} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - flatbuffers::FlatBufferBuilder builder(1024); -~~~ -
-
-~~~{.java} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - FlatBufferBuilder builder = new FlatBufferBuilder(1024); -~~~ -
-
-~~~{.kt} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - val builder = FlatBufferBuilder(1024) -~~~ -
-
-~~~{.cs} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - var builder = new FlatBufferBuilder(1024); -~~~ -
-
-~~~{.go} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - builder := flatbuffers.NewBuilder(1024) -~~~ -
-
-~~~{.py} - # Create a `FlatBufferBuilder`, which will be used to create our - # monsters' FlatBuffers. - builder = flatbuffers.Builder(1024) -~~~ -
-
-~~~{.js} - // Create a `flatbuffer.Builder`, which will be used to create our - // monsters' FlatBuffers. - var builder = new flatbuffers.Builder(1024); -~~~ -
-
-~~~{.ts} - // Create a `flatbuffer.Builder`, which will be used to create our - // monsters' FlatBuffers. - let builder = new flatbuffers.Builder(1024); -~~~ -
-
-~~~{.php} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - $builder = new Google\FlatBuffers\FlatbufferBuilder(1024); -~~~ -
-
-~~~{.c} - flatcc_builder_t builder, *B; - B = &builder; - // Initialize the builder object. - flatcc_builder_init(B); -~~~ -
-
-~~~{.dart} - // Create the fb.Builder object that will be used by our generated builders - // Note that if you are only planning to immediately get the byte array this builder would create, - // you can use the convenience method `toBytes()` on the generated builders. - // For example, you could do something like `new myGame.MonsterBuilder(...).toBytes()` - var builder = new fb.Builder(initialSize: 1024); -~~~ -
-
-~~~{.lua} - -- get access to the builder, providing an array of size 1024 - local builder = flatbuffers.Builder(1024) -~~~ -
-
-~~~{.lobster} - // get access to the builder - let builder = flatbuffers_builder {} -~~~ -
-
-~~~{.rs} - // Build up a serialized buffer algorithmically. - // Initialize it with a capacity of 1024 bytes. - let mut builder = flatbuffers::FlatBufferBuilder::new_with_capacity(1024); -~~~ -
- -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`. - -
-~~~{.cpp} - auto weapon_one_name = builder.CreateString("Sword"); - short weapon_one_damage = 3; - - auto weapon_two_name = builder.CreateString("Axe"); - short weapon_two_damage = 5; - - // Use the `CreateWeapon` shortcut to create Weapons with all the fields set. - auto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage); - auto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage); -~~~ -
-
-~~~{.java} - int weaponOneName = builder.createString("Sword") - short weaponOneDamage = 3; - - int weaponTwoName = builder.createString("Axe"); - short weaponTwoDamage = 5; - - // Use the `createWeapon()` helper function to create the weapons, since we set every field. - int sword = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage); - int axe = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage); -~~~ -
-
-~~~{.kt} - val weaponOneName = builder.createString("Sword") - val weaponOneDamage: Short = 3; - - val weaponTwoName = builder.createString("Axe") - val weaponTwoDamage: Short = 5; - - // Use the `createWeapon()` helper function to create the weapons, since we set every field. - val sword = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage) - val axe = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage) -~~~ -
-
-~~~{.cs} - var weaponOneName = builder.CreateString("Sword"); - var weaponOneDamage = 3; - - var weaponTwoName = builder.CreateString("Axe"); - var weaponTwoDamage = 5; - - // Use the `CreateWeapon()` helper function to create the weapons, since we set every field. - var sword = Weapon.CreateWeapon(builder, weaponOneName, (short)weaponOneDamage); - var axe = Weapon.CreateWeapon(builder, weaponTwoName, (short)weaponTwoDamage); -~~~ -
-
-~~~{.go} - weaponOne := builder.CreateString("Sword") - weaponTwo := builder.CreateString("Axe") - - // Create the first `Weapon` ("Sword"). - sample.WeaponStart(builder) - sample.WeaponAddName(builder, weaponOne) - sample.WeaponAddDamage(builder, 3) - sword := sample.WeaponEnd(builder) - - // Create the second `Weapon` ("Axe"). - sample.WeaponStart(builder) - sample.WeaponAddName(builder, weaponTwo) - sample.WeaponAddDamage(builder, 5) - axe := sample.WeaponEnd(builder) -~~~ -
-
-~~~{.py} - weapon_one = builder.CreateString('Sword') - weapon_two = builder.CreateString('Axe') - - # Create the first `Weapon` ('Sword'). - MyGame.Sample.Weapon.WeaponStart(builder) - MyGame.Sample.Weapon.WeaponAddName(builder, weapon_one) - MyGame.Sample.Weapon.WeaponAddDamage(builder, 3) - sword = MyGame.Sample.Weapon.WeaponEnd(builder) - - # Create the second `Weapon` ('Axe'). - MyGame.Sample.Weapon.WeaponStart(builder) - MyGame.Sample.Weapon.WeaponAddName(builder, weapon_two) - MyGame.Sample.Weapon.WeaponAddDamage(builder, 5) - axe = MyGame.Sample.Weapon.WeaponEnd(builder) -~~~ -
-
-~~~{.js} - var weaponOne = builder.createString('Sword'); - var weaponTwo = builder.createString('Axe'); - - // Create the first `Weapon` ('Sword'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponOne); - MyGame.Sample.Weapon.addDamage(builder, 3); - var sword = MyGame.Sample.Weapon.endWeapon(builder); - - // Create the second `Weapon` ('Axe'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponTwo); - MyGame.Sample.Weapon.addDamage(builder, 5); - var axe = MyGame.Sample.Weapon.endWeapon(builder); -~~~ -
-
-~~~{.js} - let weaponOne = builder.createString('Sword'); - let weaponTwo = builder.createString('Axe'); - - // Create the first `Weapon` ('Sword'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponOne); - MyGame.Sample.Weapon.addDamage(builder, 3); - let sword = MyGame.Sample.Weapon.endWeapon(builder); - - // Create the second `Weapon` ('Axe'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponTwo); - MyGame.Sample.Weapon.addDamage(builder, 5); - let axe = MyGame.Sample.Weapon.endWeapon(builder); -~~~ -
-
-~~~{.php} - // Create the `Weapon`s using the `createWeapon()` helper function. - $weapon_one_name = $builder->createString("Sword"); - $sword = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_one_name, 3); - - $weapon_two_name = $builder->createString("Axe"); - $axe = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_two_name, 5); - - // Create an array from the two `Weapon`s and pass it to the - // `CreateWeaponsVector()` method to create a FlatBuffer vector. - $weaps = array($sword, $axe); - $weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps); -~~~ -
-
-~~~{.c} - flatbuffers_string_ref_t weapon_one_name = flatbuffers_string_create_str(B, "Sword"); - uint16_t weapon_one_damage = 3; - - flatbuffers_string_ref_t weapon_two_name = flatbuffers_string_create_str(B, "Axe"); - uint16_t weapon_two_damage = 5; - - ns(Weapon_ref_t) sword = ns(Weapon_create(B, weapon_one_name, weapon_one_damage)); - ns(Weapon_ref_t) axe = ns(Weapon_create(B, weapon_two_name, weapon_two_damage)); -~~~ -
-
-~~~{.dart} - // The generated Builder classes work much like in other languages, - final int weaponOneName = builder.writeString("Sword"); - final int weaponOneDamage = 3; - - final int weaponTwoName = builder.writeString("Axe"); - final int weaponTwoDamage = 5; - - final swordBuilder = new myGame.WeaponBuilder(builder) - ..begin() - ..addNameOffset(weaponOneName) - ..addDamage(weaponOneDamage); - final int sword = swordBuilder.finish(); - - final axeBuilder = new myGame.WeaponBuilder(builder) - ..begin() - ..addNameOffset(weaponTwoName) - ..addDamage(weaponTwoDamage); - final int axe = axeBuilder.finish(); - - - - // The generated ObjectBuilder classes offer an easier to use alternative - // at the cost of requiring some additional reference allocations. If memory - // usage is critical, or if you'll be working with especially large messages - // or tables, you should prefer using the generated Builder classes. - // The following code would produce an identical buffer as above. - final String weaponOneName = "Sword"; - final int weaponOneDamage = 3; - - final String weaponTwoName = "Axe"; - final int weaponTwoDamage = 5; - - final myGame.WeaponBuilder sword = new myGame.WeaponObjectBuilder( - name: weaponOneName, - damage: weaponOneDamage, - ); - - final myGame.WeaponBuilder axe = new myGame.WeaponObjectBuilder( - name: weaponTwoName, - damage: weaponTwoDamage, - ); -~~~ -
-
-~~~{.lua} - local weaponOne = builder:CreateString("Sword") - local weaponTwo = builder:CreateString("Axe") - - -- Create the first 'Weapon' - weapon.Start(builder) - weapon.AddName(builder, weaponOne) - weapon.AddDamage(builder, 3) - local sword = weapon.End(builder) - - -- Create the second 'Weapon' - weapon.Start(builder) - weapon.AddName(builder, weaponTwo) - weapon.AddDamage(builder, 5) - local axe = weapon.End(builder) -~~~ -
-
-~~~{.lobster} - let weapon_names = [ "Sword", "Axe" ] - let weapon_damages = [ 3, 5 ] - - let weapon_offsets = map(weapon_names) name, i: - let ns = builder.CreateString(name) - MyGame_Sample_WeaponBuilder { b } - .start() - .add_name(ns) - .add_damage(weapon_damages[i]) - .end() -~~~ -
-
-~~~{.rs} - // Serialize some weapons for the Monster: A 'sword' and an 'axe'. - let weapon_one_name = builder.create_string("Sword"); - let weapon_two_name = builder.create_string("Axe"); - - // Use the `Weapon::create` shortcut to create Weapons with named field - // arguments. - let sword = Weapon::create(&mut builder, &WeaponArgs{ - name: Some(weapon_one_name), - damage: 3, - }); - let axe = Weapon::create(&mut builder, &WeaponArgs{ - name: Some(weapon_two_name), - damage: 5, - }); -~~~ -
- -Now let's create our monster, the `orc`. For this `orc`, lets make him -`red` with rage, positioned at `(1.0, 2.0, 3.0)`, and give him -a large pool of hit points with `300`. We can give him a vector of weapons -to choose from (our `Sword` and `Axe` from earlier). In this case, we will -equip him with the `Axe`, since it is the most powerful of the two. Lastly, -let's fill his inventory with some potential treasures that can be taken once he -is defeated. - -Before we serialize a monster, we need to first serialize any objects that are -contained there-in, i.e. we serialize the data tree using depth-first, pre-order -traversal. This is generally easy to do on any tree structures. - -
-~~~{.cpp} - // Serialize a name for our monster, called "Orc". - auto name = builder.CreateString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - unsigned char treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - auto inventory = builder.CreateVector(treasure, 10); -~~~ -
-
-~~~{.java} - // Serialize a name for our monster, called "Orc". - int name = builder.createString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - byte[] treasure = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - int inv = Monster.createInventoryVector(builder, treasure); -~~~ -
-
-~~~{.kt} - // Serialize a name for our monster, called "Orc". - val name = builder.createString("Orc") - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - val treasure = byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) - val inv = Monster.createInventoryVector(builder, treasure) -~~~ -
-
-~~~{.cs} - // Serialize a name for our monster, called "Orc". - var name = builder.CreateString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - // Note: Since we prepend the bytes, this loop iterates in reverse order. - Monster.StartInventoryVector(builder, 10); - for (int i = 9; i >= 0; i--) - { - builder.AddByte((byte)i); - } - var inv = builder.EndVector(); -~~~ -
-
-~~~{.go} - // Serialize a name for our monster, called "Orc". - name := builder.CreateString("Orc") - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - // Note: Since we prepend the bytes, this loop iterates in reverse. - sample.MonsterStartInventoryVector(builder, 10) - for i := 9; i >= 0; i-- { - builder.PrependByte(byte(i)) - } - inv := builder.EndVector(10) -~~~ -
-
-~~~{.py} - # Serialize a name for our monster, called "Orc". - name = builder.CreateString("Orc") - - # Create a `vector` representing the inventory of the Orc. Each number - # could correspond to an item that can be claimed after he is slain. - # Note: Since we prepend the bytes, this loop iterates in reverse. - MyGame.Sample.Monster.MonsterStartInventoryVector(builder, 10) - for i in reversed(range(0, 10)): - builder.PrependByte(i) - inv = builder.EndVector(10) -~~~ -
-
-~~~{.js} - // Serialize a name for our monster, called 'Orc'. - var name = builder.createString('Orc'); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - var treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - var inv = MyGame.Sample.Monster.createInventoryVector(builder, treasure); -~~~ -
-
-~~~{.js} - // Serialize a name for our monster, called 'Orc'. - let name = builder.createString('Orc'); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - let treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - let inv = MyGame.Sample.Monster.createInventoryVector(builder, treasure); -~~~ -
-
-~~~{.php} - // Serialize a name for our monster, called "Orc". - $name = $builder->createString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - $treasure = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); - $inv = \MyGame\Sample\Monster::CreateInventoryVector($builder, $treasure); -~~~ -
-
-~~~{.c} - // Serialize a name for our monster, called "Orc". - // The _str suffix indicates the source is an ascii-z string. - flatbuffers_string_ref_t name = flatbuffers_string_create_str(B, "Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - uint8_t treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - flatbuffers_uint8_vec_ref_t inventory; - // `c_vec_len` is the convenience macro we defined earlier. - inventory = flatbuffers_uint8_vec_create(B, treasure, c_vec_len(treasure)); -~~~ -
-
-~~~{.dart} - // Serialize a name for our monster, called "Orc". - final int name = builder.writeString('Orc'); - - // Create a list representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - final List treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - final inventory = builder.writeListUint8(treasure); - - // The following code should be used instead if you intend to use the - // ObjectBuilder classes: - // Serialize a name for our monster, called "Orc". - final String name = 'Orc'; - - // Create a list representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - final List treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; -~~~ -
-
-~~~{.py} - -- Serialize a name for our mosnter, called 'orc' - local name = builder:CreateString("Orc") - - -- Create a `vector` representing the inventory of the Orc. Each number - -- could correspond to an item that can be claimed after he is slain. - -- Note: Since we prepend the bytes, this loop iterates in reverse. - monster.StartInventoryVector(builder, 10) - for i=10,1,-1 do - builder:PrependByte(i) - end - local inv = builder:EndVector(10) -~~~ -
-
-~~~{.lobster} - // Name of the monster. - let name = builder.CreateString("Orc") - - // Inventory. - let inv = builder.MyGame_Sample_MonsterCreateInventoryVector(map(10): _) -~~~ -
-
-~~~{.rs} - // Name of the Monster. - let name = builder.create_string("Orc"); - - // Inventory. - let inventory = builder.create_vector(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9]); -~~~ -
- -We serialized two built-in data types (`string` and `vector`) and captured -their return values. These values are offsets into the serialized data, -indicating where they are stored, such that we can refer to them below when -adding fields to our monster. - -*Note: To create a `vector` of nested objects (e.g. `table`s, `string`s, or -other `vector`s), collect their offsets into a temporary data structure, and -then create an additional `vector` containing their offsets.* - -If instead of creating a vector from an existing array you serialize elements -individually one by one, take care to note that this happens in reverse order, -as buffers are built back to front. - -For example, take a look at the two `Weapon`s that we created earlier (`Sword` -and `Axe`). These are both FlatBuffer `table`s, whose offsets we now store in -memory. Therefore we can create a FlatBuffer `vector` to contain these -offsets. - -
-~~~{.cpp} - // Place the weapons into a `std::vector`, then convert that into a FlatBuffer `vector`. - std::vector> weapons_vector; - weapons_vector.push_back(sword); - weapons_vector.push_back(axe); - auto weapons = builder.CreateVector(weapons_vector); -~~~ -
-
-~~~{.java} - // Place the two weapons into an array, and pass it to the `createWeaponsVector()` method to - // create a FlatBuffer vector. - int[] weaps = new int[2]; - weaps[0] = sword; - weaps[1] = axe; - - // Pass the `weaps` array into the `createWeaponsVector()` method to create a FlatBuffer vector. - int weapons = Monster.createWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.kt} - // Place the two weapons into an array, and pass it to the `createWeaponsVector()` method to - // create a FlatBuffer vector. - val weaps = intArrayOf(sword, axe) - - // Pass the `weaps` array into the `createWeaponsVector()` method to create a FlatBuffer vector. - val weapons = Monster.createWeaponsVector(builder, weaps) -~~~ -
-
-~~~{.cs} - var weaps = new Offset[2]; - weaps[0] = sword; - weaps[1] = axe; - - // Pass the `weaps` array into the `CreateWeaponsVector()` method to create a FlatBuffer vector. - var weapons = Monster.CreateWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.go} - // Create a FlatBuffer vector and prepend the weapons. - // Note: Since we prepend the data, prepend them in reverse order. - sample.MonsterStartWeaponsVector(builder, 2) - builder.PrependUOffsetT(axe) - builder.PrependUOffsetT(sword) - weapons := builder.EndVector(2) -~~~ -
-
-~~~{.py} - # Create a FlatBuffer vector and prepend the weapons. - # Note: Since we prepend the data, prepend them in reverse order. - MyGame.Sample.Monster.MonsterStartWeaponsVector(builder, 2) - builder.PrependUOffsetTRelative(axe) - builder.PrependUOffsetTRelative(sword) - weapons = builder.EndVector(2) -~~~ -
-
-~~~{.js} - // Create an array from the two `Weapon`s and pass it to the - // `createWeaponsVector()` method to create a FlatBuffer vector. - var weaps = [sword, axe]; - var weapons = MyGame.Sample.Monster.createWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.ts} - // Create an array from the two `Weapon`s and pass it to the - // `createWeaponsVector()` method to create a FlatBuffer vector. - let weaps = [sword, axe]; - let weapons = MyGame.Sample.Monster.createWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.php} - // Create an array from the two `Weapon`s and pass it to the - // `CreateWeaponsVector()` method to create a FlatBuffer vector. - $weaps = array($sword, $axe); - $weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps); -~~~ -
-
-~~~{.c} - // We use the internal builder stack to implement a dynamic vector. - ns(Weapon_vec_start(B)); - ns(Weapon_vec_push(B, sword)); - ns(Weapon_vec_push(B, axe)); - ns(Weapon_vec_ref_t) weapons = ns(Weapon_vec_end(B)); -~~~ -
-
-~~~{.dart} - // If using the Builder classes, serialize the `[sword,axe]` - final weapons = builder.writeList([sword, axe]); - - // If using the ObjectBuilders, just create an array from the two `Weapon`s - final List weaps = [sword, axe]; -~~~ -
-
-~~~{.lua} - -- Create a FlatBuffer vector and prepend the weapons. - -- Note: Since we prepend the data, prepend them in reverse order. - monster.StartWeaponsVector(builder, 2) - builder:PrependUOffsetTRelative(axe) - builder:PrependUOffsetTRelative(sword) - local weapons = builder:EndVector(2) -~~~ -
-
-~~~{.lobster} - let weapons = builder.MyGame_Sample_MonsterCreateWeaponsVector(weapon_offsets) -~~~ -
-
-~~~{.rs} - // Create a FlatBuffer `vector` that contains offsets to the sword and axe - // we created above. - let weapons = builder.create_vector(&[sword, axe]); -~~~ -
- -
-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` -there's also `CreateVectorOfStrings`. - - -Note that vectors of structs are serialized differently from tables, since -structs are stored in-line in the vector. For example, to create a vector -for the `path` field above: - -
-~~~{.cpp} - Vec3 points[] = { Vec3(1.0f, 2.0f, 3.0f), Vec3(4.0f, 5.0f, 6.0f) }; - auto path = builder.CreateVectorOfStructs(points, 2); -~~~ -
-
-~~~{.java} - Monster.startPathVector(fbb, 2); - Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f); - Vec3.createVec3(builder, 4.0f, 5.0f, 6.0f); - int path = fbb.endVector(); -~~~ -
-
-~~~{.kt} - Monster.startPathVector(fbb, 2) - Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f) - Vec3.createVec3(builder, 4.0f, 5.0f, 6.0f) - val path = fbb.endVector() -~~~ -
-
-~~~{.cs} - Monster.StartPathVector(fbb, 2); - Vec3.CreateVec3(builder, 1.0f, 2.0f, 3.0f); - Vec3.CreateVec3(builder, 4.0f, 5.0f, 6.0f); - var path = fbb.EndVector(); -~~~ -
-
-~~~{.go} - sample.MonsterStartPathVector(builder, 2) - sample.CreateVec3(builder, 1.0, 2.0, 3.0) - sample.CreateVec3(builder, 4.0, 5.0, 6.0) - path := builder.EndVector(2) -~~~ -
-
-~~~{.py} - MyGame.Sample.Monster.MonsterStartPathVector(builder, 2) - MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0) - MyGame.Sample.Vec3.CreateVec3(builder, 4.0, 5.0, 6.0) - path = builder.EndVector(2) -~~~ -
-
-~~~{.js} - MyGame.Sample.Monster.startPathVector(builder, 2); - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0); - MyGame.Sample.Vec3.createVec3(builder, 4.0, 5.0, 6.0); - var path = builder.endVector(); -~~~ -
-
-~~~{.ts} - MyGame.Sample.Monster.startPathVector(builder, 2); - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0); - MyGame.Sample.Vec3.createVec3(builder, 4.0, 5.0, 6.0); - let path = builder.endVector(); -~~~ -
-
-~~~{.php} - \MyGame\Example\Monster::StartPathVector($builder, 2); - \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0); - \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0); - $path = $builder->endVector(); -~~~ -
-
-~~~{.c} - // TBD -~~~ -
-
-~~~{.dart} - // Using the Builder classes, you can write a list of structs like so: - // Note that the intended order should be reversed if order is important. - final vec3Builder = new myGame.Vec3Builder(builder); - vec3Builder.finish(4.0, 5.0, 6.0); - vec3Builder.finish(1.0, 2.0, 3.0); - final int path = builder.endStructVector(2); // the length of the vector - - // Otherwise, using the ObjectBuilder classes: - // The dart implementation provides a simple interface for writing vectors - // of structs, in `writeListOfStructs`. This method takes - // `List` and is used by the generated builder classes. - final List path = [ - new myGame.Vec3ObjectBuilder(x: 1.0, y: 2.0, z: 3.0), - new myGame.Vec3ObjectBuilder(x: 4.0, y: 5.0, z: 6.0) - ]; -~~~ -
-
-~~~{.lua} - -- Create a FlatBuffer vector and prepend the path locations. - -- Note: Since we prepend the data, prepend them in reverse order. - monster.StartPathVector(builder, 2) - vec3.CreateVec3(builder, 1.0, 2.0, 3.0) - vec3.CreateVec3(builder, 4.0, 5.0, 6.0) - local path = builder:EndVector(2) -~~~ -
-
-~~~{.lobster} - builder.MyGame_Sample_MonsterStartPathVector(2) - builder.MyGame_Sample_CreateVec3(1.0, 2.0, 3.0) - builder.MyGame_Sample_CreateVec3(4.0, 5.0, 6.0) - let path = builder.EndVector(2) -~~~ -
-
-~~~{.rs} - // Create the path vector of Vec3 objects. - let x = Vec3::new(1.0, 2.0, 3.0); - let y = Vec3::new(4.0, 5.0, 6.0); - let path = builder.create_vector(&[x, y]); - - // Note that, for convenience, it is also valid to create a vector of - // references to structs, like this: - // let path = builder.create_vector(&[&x, &y]); -~~~ -
- -We have now serialized the non-scalar components of the orc, so we -can serialize the monster itself: - -
-~~~{.cpp} - // Create the position struct - auto position = Vec3(1.0f, 2.0f, 3.0f); - - // Set his hit points to 300 and his mana to 150. - int hp = 300; - int mana = 150; - - // Finally, create the monster using the `CreateMonster` helper function - // to set all fields. - auto orc = CreateMonster(builder, &position, mana, hp, name, inventory, - Color_Red, weapons, Equipment_Weapon, axe.Union(), - path); -~~~ -
-
-~~~{.java} - // Create our monster using `startMonster()` and `endMonster()`. - Monster.startMonster(builder); - Monster.addPos(builder, Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f)); - Monster.addName(builder, name); - Monster.addColor(builder, Color.Red); - Monster.addHp(builder, (short)300); - Monster.addInventory(builder, inv); - Monster.addWeapons(builder, weapons); - Monster.addEquippedType(builder, Equipment.Weapon); - Monster.addEquipped(builder, axe); - Monster.addPath(builder, path); - int orc = Monster.endMonster(builder); -~~~ -
-
-~~~{.kt} - // Create our monster using `startMonster()` and `endMonster()`. - Monster.startMonster(builder) - Monster.addPos(builder, Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f)) - Monster.addName(builder, name) - Monster.addColor(builder, Color.Red) - Monster.addHp(builder, 300.toShort()) - Monster.addInventory(builder, inv) - Monster.addWeapons(builder, weapons) - Monster.addEquippedType(builder, Equipment.Weapon) - Monster.addEquipped(builder, axe) - Monster.addPath(builder, path) - val orc = Monster.endMonster(builder) -~~~ -
-
-~~~{.cs} - // Create our monster using `StartMonster()` and `EndMonster()`. - Monster.StartMonster(builder); - Monster.AddPos(builder, Vec3.CreateVec3(builder, 1.0f, 2.0f, 3.0f)); - Monster.AddHp(builder, (short)300); - Monster.AddName(builder, name); - Monster.AddInventory(builder, inv); - Monster.AddColor(builder, Color.Red); - Monster.AddWeapons(builder, weapons); - Monster.AddEquippedType(builder, Equipment.Weapon); - Monster.AddEquipped(builder, axe.Value); // Axe - Monster.AddPath(builder, path); - var orc = Monster.EndMonster(builder); -~~~ -
-
-~~~{.go} - // Create our monster using `MonsterStart()` and `MonsterEnd()`. - sample.MonsterStart(builder) - sample.MonsterAddPos(builder, sample.CreateVec3(builder, 1.0, 2.0, 3.0)) - sample.MonsterAddHp(builder, 300) - sample.MonsterAddName(builder, name) - sample.MonsterAddInventory(builder, inv) - sample.MonsterAddColor(builder, sample.ColorRed) - sample.MonsterAddWeapons(builder, weapons) - sample.MonsterAddEquippedType(builder, sample.EquipmentWeapon) - sample.MonsterAddEquipped(builder, axe) - sample.MonsterAddPath(builder, path) - orc := sample.MonsterEnd(builder) -~~~ -
-
-~~~{.py} - # Create our monster by using `MonsterStart()` and `MonsterEnd()`. - MyGame.Sample.Monster.MonsterStart(builder) - MyGame.Sample.Monster.MonsterAddPos(builder, - MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0)) - MyGame.Sample.Monster.MonsterAddHp(builder, 300) - MyGame.Sample.Monster.MonsterAddName(builder, name) - MyGame.Sample.Monster.MonsterAddInventory(builder, inv) - MyGame.Sample.Monster.MonsterAddColor(builder, - MyGame.Sample.Color.Color().Red) - MyGame.Sample.Monster.MonsterAddWeapons(builder, weapons) - MyGame.Sample.Monster.MonsterAddEquippedType( - builder, MyGame.Sample.Equipment.Equipment().Weapon) - MyGame.Sample.Monster.MonsterAddEquipped(builder, axe) - MyGame.Sample.Monster.MonsterAddPath(builder, path) - orc = MyGame.Sample.Monster.MonsterEnd(builder) -~~~ -
-
-~~~{.js} - // Create our monster by using `startMonster()` and `endMonster()`. - MyGame.Sample.Monster.startMonster(builder); - MyGame.Sample.Monster.addPos(builder, - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0)); - MyGame.Sample.Monster.addHp(builder, 300); - MyGame.Sample.Monster.addColor(builder, MyGame.Sample.Color.Red) - MyGame.Sample.Monster.addName(builder, name); - MyGame.Sample.Monster.addInventory(builder, inv); - MyGame.Sample.Monster.addWeapons(builder, weapons); - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); - MyGame.Sample.Monster.addEquipped(builder, axe); - MyGame.Sample.Monster.addPath(builder, path); - var orc = MyGame.Sample.Monster.endMonster(builder); -~~~ -
-
-~~~{.ts} - // Create our monster by using `startMonster()` and `endMonster()`. - MyGame.Sample.Monster.startMonster(builder); - MyGame.Sample.Monster.addPos(builder, - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0)); - MyGame.Sample.Monster.addHp(builder, 300); - MyGame.Sample.Monster.addColor(builder, MyGame.Sample.Color.Red) - MyGame.Sample.Monster.addName(builder, name); - MyGame.Sample.Monster.addInventory(builder, inv); - MyGame.Sample.Monster.addWeapons(builder, weapons); - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); - MyGame.Sample.Monster.addEquipped(builder, axe); - MyGame.Sample.Monster.addPath(builder, path); - let orc = MyGame.Sample.Monster.endMonster(builder); -~~~ -
-
-~~~{.php} - // Create our monster by using `StartMonster()` and `EndMonster()`. - \MyGame\Sample\Monster::StartMonster($builder); - \MyGame\Sample\Monster::AddPos($builder, - \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0)); - \MyGame\Sample\Monster::AddHp($builder, 300); - \MyGame\Sample\Monster::AddName($builder, $name); - \MyGame\Sample\Monster::AddInventory($builder, $inv); - \MyGame\Sample\Monster::AddColor($builder, \MyGame\Sample\Color::Red); - \MyGame\Sample\Monster::AddWeapons($builder, $weapons); - \MyGame\Sample\Monster::AddEquippedType($builder, \MyGame\Sample\Equipment::Weapon); - \MyGame\Sample\Monster::AddEquipped($builder, $axe); - \MyGame\Sample\Monster::AddPath($builder, $path); - $orc = \MyGame\Sample\Monster::EndMonster($builder); -~~~ -
-
-~~~{.c} - // Set his hit points to 300 and his mana to 150. - uint16_t hp = 300; - uint16_t mana = 150; - - // Define an equipment union. `create` calls in C has a single - // argument for unions where C++ has both a type and a data argument. - ns(Equipment_union_ref_t) equipped = ns(Equipment_as_Weapon(axe)); - ns(Vec3_t) pos = { 1.0f, 2.0f, 3.0f }; - ns(Monster_create_as_root(B, &pos, mana, hp, name, inventory, ns(Color_Red), - weapons, equipped, path)); -~~~ -
-
-~~~{.dart} - // Using the Builder API: - // Set his hit points to 300 and his mana to 150. - final int hp = 300; - final int mana = 150; - - final monster = new myGame.MonsterBuilder(builder) - ..begin() - ..addNameOffset(name) - ..addInventoryOffset(inventory) - ..addWeaponsOffset(weapons) - ..addEquippedType(myGame.EquipmentTypeId.Weapon) - ..addEquippedOffset(axe) - ..addHp(hp) - ..addMana(mana) - ..addPos(vec3Builder.finish(1.0, 2.0, 3.0)) - ..addPathOffset(path) - ..addColor(myGame.Color.Red); - - final int orc = monster.finish(); - - // -Or- using the ObjectBuilder API: - // Set his hit points to 300 and his mana to 150. - final int hp = 300; - final int mana = 150; - - // Note that these parameters are optional - it is not necessary to set - // all of them. - // Also note that it is not necessary to `finish` the builder helpers above - // - the generated code will automatically reuse offsets if the same object - // is used in more than one place (e.g. the axe appearing in `weapons` and - // `equipped`). - final myGame.MonsterBuilder orcBuilder = new myGame.MonsterBuilder( - name: name, - inventory: treasure, - weapons: weaps, - equippedType: myGame.EquipmentTypeId.Weapon, - equipped: axe, - path: path, - hp: hp, - mana: mana, - pos: new myGame.Vec3Builder(x: 1.0, y: 2.0, z: 3.0), - color: myGame.Color.Red, - path: [ - new myGame.Vec3ObjectBuilder(x: 1.0, y: 2.0, z: 3.0), - new myGame.Vec3ObjectBuilder(x: 4.0, y: 5.0, z: 6.0) - ]); - - final int orc = orcBuilder.finish(builder); -~~~ -
-
-~~~{.lua} - -- Create our monster by using Start() andEnd() - monster.Start(builder) - monster.AddPos(builder, vec3.CreateVec3(builder, 1.0, 2.0, 3.0)) - monster.AddHp(builder, 300) - monster.AddName(builder, name) - monster.AddInventory(builder, inv) - monster.AddColor(builder, color.Red) - monster.AddWeapons(builder, weapons) - monster.AddEquippedType(builder, equipment.Weapon) - monster.AddEquipped(builder, axe) - monster.AddPath(builder, path) - local orc = monster.End(builder) -~~~ -
-
-~~~{.lobster} - let orc = MyGame_Sample_MonsterBuilder { b } - .start() - .add_pos(b.MyGame_Sample_CreateVec3(1.0, 2.0, 3.0)) - .add_hp(300) - .add_name(name) - .add_inventory(inv) - .add_color(MyGame_Sample_Color_Red) - .add_weapons(weapons) - .add_equipped_type(MyGame_Sample_Equipment_Weapon) - .add_equipped(weapon_offsets[1]) - .add_path(path) - .end() -~~~ -
-
-~~~{.rs} - // Create the monster using the `Monster::create` helper function. This - // function accepts a `MonsterArgs` struct, which supplies all of the data - // needed to build a `Monster`. To supply empty/default fields, just use the - // Rust built-in `Default::default()` function, as demonstrated below. - let orc = Monster::create(&mut builder, &MonsterArgs{ - pos: Some(&Vec3::new(1.0f32, 2.0f32, 3.0f32)), - mana: 150, - hp: 80, - name: Some(name), - inventory: Some(inventory), - color: Color::Red, - weapons: Some(weapons), - equipped_type: Equipment::Weapon, - equipped: Some(axe.as_union_value()), - path: Some(path), - ..Default::default() - }); -~~~ -
- -Note how we create `Vec3` struct in-line in the table. Unlike tables, structs -are simple combinations of scalars that are always stored inline, just like -scalars themselves. - -**Important**: Unlike structs, you should not nest tables or other objects, -which is why we created all the strings/vectors/tables that this monster refers -to before `start`. If you try to create any of them between `start` and `end`, -you will get an assert/exception/panic depending on your language. - -*Note: Since we are passing `150` as the `mana` field, which happens to be the -default value, the field will not actually be written to the buffer, since the -default value will be returned on query anyway. This is a nice space savings, -especially if default values are common in your data. It also means that you do -not need to be worried 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.* - -
-
-If you do not wish to set every field in a `table`, it may be more convenient to -manually set each field of your monster, instead of calling `CreateMonster()`. -The following snippet is functionally equivalent to the above code, but provides -a bit more flexibility. -
-~~~{.cpp} - // You can use this code instead of `CreateMonster()`, to create our orc - // manually. - MonsterBuilder monster_builder(builder); - monster_builder.add_pos(&position); - monster_builder.add_hp(hp); - monster_builder.add_name(name); - monster_builder.add_inventory(inventory); - monster_builder.add_color(Color_Red); - monster_builder.add_weapons(weapons); - monster_builder.add_equipped_type(Equipment_Weapon); - monster_builder.add_equipped(axe.Union()); - auto orc = monster_builder.Finish(); -~~~ -
-
-If you do not wish to set every field in a `table`, it may be more convenient to -manually set each field of your monster, instead of calling `create_monster_as_root()`. -The following snippet is functionally equivalent to the above code, but provides -a bit more flexibility. -
-~~~{.c} - // It is important to pair `start_as_root` with `end_as_root`. - ns(Monster_start_as_root(B)); - ns(Monster_pos_create(B, 1.0f, 2.0f, 3.0f)); - // or alternatively - //ns(Monster_pos_add(&pos); - - ns(Monster_hp_add(B, hp)); - // Notice that `Monser_name_add` adds a string reference unlike the - // add_str and add_strn variants. - ns(Monster_name_add(B, name)); - ns(Monster_inventory_add(B, inventory)); - ns(Monster_color_add(B, ns(Color_Red))); - ns(Monster_weapons_add(B, weapons)); - ns(Monster_equipped_add(B, equipped)); - // Complete the monster object and make it the buffer root object. - ns(Monster_end_as_root(B)); -~~~ -
- -Before finishing the serialization, let's take a quick look at FlatBuffer -`union Equipped`. There are two parts to each FlatBuffer `union`. The first, is -a hidden field `_type`, that is generated to hold the type of `table` referred -to by the `union`. This allows you to know which type to cast to at runtime. -Second, is the `union`'s data. - -In our example, the last two things we added to our `Monster` were the -`Equipped Type` and the `Equipped` union itself. - -Here is a repetition these lines, to help highlight them more clearly: - -
- ~~~{.cpp} - monster_builder.add_equipped_type(Equipment_Weapon); // Union type - monster_builder.add_equipped(axe); // Union data - ~~~ -
-
- ~~~{.java} - Monster.addEquippedType(builder, Equipment.Weapon); // Union type - Monster.addEquipped(axe); // Union data - ~~~ -
-
- ~~~{.kt} - Monster.addEquippedType(builder, Equipment.Weapon) // Union type - Monster.addEquipped(axe) // Union data - ~~~ -
-
- ~~~{.cs} - Monster.AddEquippedType(builder, Equipment.Weapon); // Union type - Monster.AddEquipped(builder, axe.Value); // Union data - ~~~ -
-
- ~~~{.go} - sample.MonsterAddEquippedType(builder, sample.EquipmentWeapon) // Union type - sample.MonsterAddEquipped(builder, axe) // Union data - ~~~ -
-
- ~~~{.py} - MyGame.Sample.Monster.MonsterAddEquippedType( # Union type - builder, MyGame.Sample.Equipment.Equipment().Weapon) - MyGame.Sample.Monster.MonsterAddEquipped(builder, axe) # Union data - ~~~ -
-
- ~~~{.js} - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); // Union type - MyGame.Sample.Monster.addEquipped(builder, axe); // Union data - ~~~ -
-
- ~~~{.ts} - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); // Union type - MyGame.Sample.Monster.addEquipped(builder, axe); // Union data - ~~~ -
-
- ~~~{.php} - \MyGame\Sample\Monster::AddEquippedType($builder, \MyGame\Sample\Equipment::Weapon); // Union type - \MyGame\Sample\Monster::AddEquipped($builder, $axe); // Union data - ~~~ -
-
-~~~{.c} - // Add union type and data simultaneously. - ns(Monster_equipped_Weapon_add(B, axe)); -~~~ -
-
-~~~{.dart} - // using the builder API: - ..addEquippedType(myGame.EquipmentTypeId.Weapon) - ..addEquippedOffset(axe) - - // in the ObjectBuilder API: - equippedTypeId: myGame.EquipmentTypeId.Weapon, // Union type - equipped: axe, // Union data -~~~ -
-
-~~~{.lua} - monster.AddEquippedType(builder, equipment.Weapon) -- Union type - monster.AddEquipped(builder, axe) -- Union data -~~~ -
-
-~~~{.lobster} - .add_equipped_type(MyGame_Sample_Equipment_Weapon) - .add_equipped(axe) -~~~ -
-
- ~~~{.rs} - // You need to call `as_union_value` to turn an object into a type that - // can be used as a union value. - monster_builder.add_equipped_type(Equipment::Weapon); // Union type - monster_builder.add_equipped(axe.as_union_value()); // Union data - ~~~ -
- -After you have created your buffer, you will have the offset to the root of the -data in the `orc` variable, so you can finish the buffer by calling the -appropriate `finish` method. - - -
-~~~{.cpp} - // Call `Finish()` to instruct the builder that this monster is complete. - // Note: Regardless of how you created the `orc`, you still need to call - // `Finish()` on the `FlatBufferBuilder`. - builder.Finish(orc); // You could also call `FinishMonsterBuffer(builder, - // orc);`. -~~~ -
-
-~~~{.java} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc); // You could also call `Monster.finishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.kt} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc) // You could also call `Monster.finishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.cs} - // Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc.Value); // You could also call `Monster.FinishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.go} - // Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc) -~~~ -
-
-~~~{.py} - # Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc) -~~~ -
-
-~~~{.js} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc); // You could also call `MyGame.Sample.Monster.finishMonsterBuffer(builder, - // orc);`. -~~~ -
-
-~~~{.ts} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc); // You could also call `MyGame.Sample.Monster.finishMonsterBuffer(builder, - // orc);`. -~~~ -
-
-~~~{.php} - // Call `finish()` to instruct the builder that this monster is complete. - $builder->finish($orc); // You may also call `\MyGame\Sample\Monster::FinishMonsterBuffer( - // $builder, $orc);`. -~~~ -
-
-~~~{.c} - // Because we used `Monster_create_as_root`, we do not need a `finish` call in C`. -~~~ -
-
-~~~{.dart} - // Call `finish()` to instruct the builder that this monster is complete. - // See the next code section, as in Dart `finish` will also return the byte array. -~~~ -
-
-~~~{.lua} - -- Call 'Finish()' to instruct the builder that this monster is complete. - builder:Finish(orc) -~~~ -
-
-~~~{.lobster} - // Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc) -~~~ -
-
-~~~{.rs} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc, None); -~~~ -
- -The buffer is now ready to be stored somewhere, sent over the network, be -compressed, or whatever you'd like to do with it. You can access the buffer -like so: - -
-~~~{.cpp} - // This must be called after `Finish()`. - uint8_t *buf = builder.GetBufferPointer(); - int size = builder.GetSize(); // Returns the size of the buffer that - // `GetBufferPointer()` points to. -~~~ -
-
-~~~{.java} - // This must be called after `finish()`. - java.nio.ByteBuffer buf = builder.dataBuffer(); - // The data in this ByteBuffer does NOT start at 0, but at buf.position(). - // The number of bytes is buf.remaining(). - - // Alternatively this copies the above data out of the ByteBuffer for you: - byte[] buf = builder.sizedByteArray(); -~~~ -
-
-~~~{.kt} - // This must be called after `finish()`. - val buf = builder.dataBuffer() - // The data in this ByteBuffer does NOT start at 0, but at buf.position(). - // The number of bytes is buf.remaining(). - - // Alternatively this copies the above data out of the ByteBuffer for you: - val buf = builder.sizedByteArray() -~~~ -
-
-~~~{.cs} - // This must be called after `Finish()`. - var buf = builder.DataBuffer; // Of type `FlatBuffers.ByteBuffer`. - // The data in this ByteBuffer does NOT start at 0, but at buf.Position. - // The end of the data is marked by buf.Length, so the size is - // buf.Length - buf.Position. - - // Alternatively this copies the above data out of the ByteBuffer for you: - byte[] buf = builder.SizedByteArray(); -~~~ -
-
-~~~{.go} - // This must be called after `Finish()`. - buf := builder.FinishedBytes() // Of type `byte[]`. -~~~ -
-
-~~~{.py} - # This must be called after `Finish()`. - buf = builder.Output() // Of type `bytearray`. -~~~ -
-
-~~~{.js} - // This must be called after `finish()`. - var buf = builder.asUint8Array(); // Of type `Uint8Array`. -~~~ -
-
-~~~{.ts} - // This must be called after `finish()`. - let buf = builder.asUint8Array(); // Of type `Uint8Array`. -~~~ -
-
-~~~{.php} - // This must be called after `finish()`. - $buf = $builder->dataBuffer(); // Of type `Google\FlatBuffers\ByteBuffer` - // The data in this ByteBuffer does NOT start at 0, but at buf->getPosition(). - // The end of the data is marked by buf->capacity(), so the size is - // buf->capacity() - buf->getPosition(). -~~~ -
-
-~~~{.c} - uint8_t *buf; - size_t size; - - // Allocate and extract a readable buffer from internal builder heap. - // The returned buffer must be deallocated using `free`. - // NOTE: Finalizing the buffer does NOT change the builder, it - // just creates a snapshot of the builder content. - buf = flatcc_builder_finalize_buffer(B, &size); - // use buf - free(buf); - - // Optionally reset builder to reuse builder without deallocating - // internal stack and heap. - flatcc_builder_reset(B); - // build next buffer. - // ... - - // Cleanup. - flatcc_builder_clear(B); -~~~ -
-
-~~~{.dart} - final Uint8List buf = builder.finish(orc); -~~~ -
-
-~~~{.lua} - -- Get the flatbuffer as a string containing the binary data - local bufAsString = builder:Output() -~~~ -
-
-~~~{.lobster} - // This must be called after `Finish()`. - let buf = builder.SizedCopy() // Of type `string`. -~~~ -
-
-~~~{.rs} - // This must be called after `finish()`. - // `finished_data` returns a byte slice. - let buf = builder.finished_data(); // Of type `&[u8]` -~~~ -
- - -Now you can write the bytes to a file, send them over the network.. -**Make sure your file mode (or transfer protocol) is set to BINARY, not text.** -If you transfer a FlatBuffer in text mode, the buffer will be corrupted, -which will lead to hard to find problems when you read the buffer. - -#### Reading Orc FlatBuffers - -Now that we have successfully created an `Orc` FlatBuffer, the monster data can -be saved, sent over a network, etc. Let's now adventure into the inverse, and -access a FlatBuffer. - -This section requires the same import/include, namespace, etc. requirements as -before: - -
-~~~{.cpp} - #include "monster_generated.h" // This was generated by `flatc`. - - using namespace MyGame::Sample; // Specified in the schema. -~~~ -
-
-~~~{.java} - import MyGame.Sample.*; //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder; -~~~ -
-
-~~~{.kt} - import MyGame.Sample.* //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder -~~~ -
-
-~~~{.cs} - using FlatBuffers; - using MyGame.Sample; // The `flatc` generated files. (Monster, Vec3, etc.) -~~~ -
-
-~~~{.go} - import ( - flatbuffers "github.com/google/flatbuffers/go" - sample "MyGame/Sample" - ) -~~~ -
-
-~~~{.py} - import flatbuffers - - # Generated by `flatc`. - import MyGame.Sample.Any - import MyGame.Sample.Color - import MyGame.Sample.Monster - import MyGame.Sample.Vec3 -~~~ -
-
-~~~{.js} - // The following code is for JavaScript module loaders (e.g. Node.js). See - // below for a browser-based HTML/JavaScript example of including the library. - var flatbuffers = require('/js/flatbuffers').flatbuffers; - var MyGame = require('./monster_generated').MyGame; // Generated by `flatc`. - - //--------------------------------------------------------------------------// - - // The following code is for browser-based HTML/JavaScript. Use the above code - // for JavaScript module loaders (e.g. Node.js). - - // Generated by `flatc`. -~~~ -
-
-~~~{.js} - // note: import flabuffers with your desired import method - - import { MyGame } from './monster_generated'; -~~~ -
-
-~~~{.php} - // It is recommended that your use PSR autoload when using FlatBuffers in PHP. - // Here is an example from `SampleBinary.php`: - function __autoload($class_name) { - // The last segment of the class name matches the file name. - $class = substr($class_name, strrpos($class_name, "\\") + 1); - $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root. - - // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files. - $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")), - join(DIRECTORY_SEPARATOR, array($root_dir, "samples", "MyGame", "Sample"))); - foreach ($paths as $path) { - $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php")); - if (file_exists($file)) { - require($file); - break; - } - } - } -~~~ -
-
-~~~{.c} - // Only needed if we don't have `#include "monster_builder.h"`. - #include "monster_reader.h" - - #undef ns - #define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Sample, x) // Specified in the schema. -~~~ -
-
-~~~{.dart} -import 'package:flat_buffers/flat_buffers.dart' as fb; -import './monster_my_game.sample_generated.dart' as myGame; -~~~ -
-
-~~~{.lua} - -- require the flatbuffers module - local flatbuffers = require("flatbuffers") - - -- require the generated files from `flatc`. - local color = require("MyGame.Sample.Color") - local equipment = require("MyGame.Sample.Equipment") - local monster = require("MyGame.Sample.Monster") - local vec3 = require("MyGame.Sample.Vec3") - local weapon = require("MyGame.Sample.Weapon") -~~~ -
-
-~~~{.lobster} - import from "../lobster/" // Where to find flatbuffers.lobster - import monster_generated -~~~ -
-
-~~~{.rs} - // import the flatbuffers runtime library - extern crate flatbuffers; - - // import the generated code - #[allow(dead_code, unused_imports)] - #[path = "./monster_generated.rs"] - mod monster_generated; - pub use monster_generated::my_game::sample::{get_root_as_monster, - Color, Equipment, - Monster, MonsterArgs, - Vec3, - Weapon, WeaponArgs}; -~~~ -
- -Then, assuming you have a buffer of bytes received from disk, -network, etc., you can create start accessing the buffer like so: - -**Again, make sure you read the bytes in BINARY mode, otherwise the code below -won't work** - -
-~~~{.cpp} - uint8_t *buffer_pointer = /* the data you just read */; - - // Get a pointer to the root object inside the buffer. - auto monster = GetMonster(buffer_pointer); - - // `monster` is of type `Monster *`. - // Note: root object pointers are NOT the same as `buffer_pointer`. - // `GetMonster` is a convenience function that calls `GetRoot`, - // the latter is also available for non-root types. -~~~ -
-
-~~~{.java} - byte[] bytes = /* the data you just read */ - java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(bytes); - - // Get an accessor to the root object inside the buffer. - Monster monster = Monster.getRootAsMonster(buf); -~~~ -
-
-~~~{.kt} - val bytes = /* the data you just read */ - val buf = java.nio.ByteBuffer.wrap(bytes) - - // Get an accessor to the root object inside the buffer. - Monster monster = Monster.getRootAsMonster(buf) -~~~ -
-
-~~~{.cs} - byte[] bytes = /* the data you just read */ - var buf = new ByteBuffer(bytes); - - // Get an accessor to the root object inside the buffer. - var monster = Monster.GetRootAsMonster(buf); -~~~ -
-
-~~~{.go} - var buf []byte = /* the data you just read */ - - // Get an accessor to the root object inside the buffer. - monster := sample.GetRootAsMonster(buf, 0) - - // Note: We use `0` for the offset here, which is typical for most buffers - // you would read. If you wanted to read from `builder.Bytes` directly, you - // would need to pass in the offset of `builder.Head()`, as the builder - // constructs the buffer backwards, so may not start at offset 0. -~~~ -
-
-~~~{.py} - buf = /* the data you just read, in an object of type "bytearray" */ - - // Get an accessor to the root object inside the buffer. - monster = MyGame.Sample.Monster.Monster.GetRootAsMonster(buf, 0) - - # Note: We use `0` for the offset here, which is typical for most buffers - # you would read. If you wanted to read from the `builder.Bytes` directly, - # you would need to pass in the offset of `builder.Head()`, as the builder - # constructs the buffer backwards, so may not start at offset 0. -~~~ -
-
-~~~{.js} - var bytes = /* the data you just read, in an object of type "Uint8Array" */ - var buf = new flatbuffers.ByteBuffer(bytes); - - // Get an accessor to the root object inside the buffer. - var monster = MyGame.Sample.Monster.getRootAsMonster(buf); -~~~ -
-
-~~~{.ts} - let bytes = /* the data you just read, in an object of type "Uint8Array" */ - let buf = new flatbuffers.ByteBuffer(bytes); - - // Get an accessor to the root object inside the buffer. - let monster = MyGame.Sample.Monster.getRootAsMonster(buf); -~~~ -
-
-~~~{.php} - $bytes = /* the data you just read, in a string */ - $buf = Google\FlatBuffers\ByteBuffer::wrap($bytes); - - // Get an accessor to the root object inside the buffer. - $monster = \MyGame\Sample\Monster::GetRootAsMonster($buf); -~~~ -
-
-~~~{.c} - // Note that we use the `table_t` suffix when reading a table object - // as opposed to the `ref_t` suffix used during the construction of - // the buffer. - ns(Monster_table_t) monster = ns(Monster_as_root(buffer)); - - // Note: root object pointers are NOT the same as the `buffer` pointer. -~~~ -
-
-~~~{.dart} -List data = ... // the data, e.g. from file or network -// A generated factory constructor that will read the data. -myGame.Monster monster = new myGame.Monster(data); -~~~ -
-
-~~~{.lua} - local bufAsString = -- The data you just read in - - -- Convert the string representation into binary array Lua structure - local buf = flatbuffers.binaryArray.New(bufAsString) - - -- Get an accessor to the root object insert the buffer - local mon = monster.GetRootAsMonster(buf, 0) -~~~ -
-
-~~~{.lobster} - buf = /* the data you just read, in a string */ - - // Get an accessor to the root object inside the buffer. - let monster = MyGame_Sample_GetRootAsMonster(buf) -~~~ -
-
-~~~{.rs} - let buf = /* the data you just read, in a &[u8] */ - - // Get an accessor to the root object inside the buffer. - let monster = get_root_as_monster(buf); -~~~ -
- -If you look in the generated files from the schema compiler, you will see it generated -accessors for all non-`deprecated` fields. For example: - -
-~~~{.cpp} - auto hp = monster->hp(); - auto mana = monster->mana(); - auto name = monster->name()->c_str(); -~~~ -
-
-~~~{.java} - short hp = monster.hp(); - short mana = monster.mana(); - String name = monster.name(); -~~~ -
-
-~~~{.kt} - val hp = monster.hp - val mana = monster.mana - val name = monster.name -~~~ -
-
-~~~{.cs} - // For C#, unlike most other languages support by FlatBuffers, most values (except for - // vectors and unions) are available as properties instead of accessor methods. - var hp = monster.Hp - var mana = monster.Mana - var name = monster.Name -~~~ -
-
-~~~{.go} - hp := monster.Hp() - mana := monster.Mana() - name := string(monster.Name()) // Note: `monster.Name()` returns a byte[]. -~~~ -
-
-~~~{.py} - hp = monster.Hp() - mana = monster.Mana() - name = monster.Name() -~~~ -
-
-~~~{.js} - var hp = $monster.hp(); - var mana = $monster.mana(); - var name = $monster.name(); -~~~ -
-
-~~~{.ts} - let hp = $monster.hp(); - let mana = $monster.mana(); - let name = $monster.name(); -~~~ -
-
-~~~{.php} - $hp = $monster->getHp(); - $mana = $monster->getMana(); - $name = monster->getName(); -~~~ -
-
-~~~{.c} - uint16_t hp = ns(Monster_hp(monster)); - uint16_t mana = ns(Monster_mana(monster)); - flatbuffers_string_t name = ns(Monster_name(monster)); -~~~ -
-
-~~~{.dart} - // For Dart, unlike other languages support by FlatBuffers, most values - // are available as properties instead of accessor methods. - var hp = monster.hp; - var mana = monster.mana; - var name = monster.name; -~~~ -
-
-~~~{.lua} - local hp = mon:Hp() - local mana = mon:Mana() - local name = mon:Name() -~~~ -
-
-~~~{.lobster} - let hp = monster.hp - let mana = monster.mana - let name = monster.name -~~~ -
-
-~~~{.rs} - // Get and test some scalar types from the FlatBuffer. - let hp = monster.hp(); - let mana = monster.mana(); - let name = monster.name(); -~~~ -
- -These should hold `300`, `150`, and `"Orc"` respectively. - -*Note: The default value `150` wasn't stored in `mana`, but we are still able to retrieve it.* - -To access sub-objects, in the case of our `pos`, which is a `Vec3`: - -
-~~~{.cpp} - auto pos = monster->pos(); - auto x = pos->x(); - auto y = pos->y(); - auto z = pos->z(); -~~~ -
-
-~~~{.java} - Vec3 pos = monster.pos(); - float x = pos.x(); - float y = pos.y(); - float z = pos.z(); -~~~ -
-
-~~~{.kt} - val pos = monster.pos!! - val x = pos.x - val y = pos.y - val z = pos.z -~~~ -
-
-~~~{.cs} - var pos = monster.Pos.Value; - var x = pos.X; - var y = pos.Y; - var z = pos.Z; -~~~ -
-
-~~~{.go} - pos := monster.Pos(nil) - x := pos.X() - y := pos.Y() - z := pos.Z() - - // Note: Whenever you access a new object, like in `Pos()`, a new temporary - // accessor object gets created. If your code is very performance sensitive, - // you can pass in a pointer to an existing `Vec3` instead of `nil`. This - // allows you to reuse it across many calls to reduce the amount of object - // allocation/garbage collection. -~~~ -
-
-~~~{.py} - pos = monster.Pos() - x = pos.X() - y = pos.Y() - z = pos.Z() -~~~ -
-
-~~~{.js} - var pos = monster.pos(); - var x = pos.x(); - var y = pos.y(); - var z = pos.z(); -~~~ -
-
-~~~{.ts} - let pos = monster.pos(); - let x = pos.x(); - let y = pos.y(); - let z = pos.z(); -~~~ -
-
-~~~{.php} - $pos = $monster->getPos(); - $x = $pos->getX(); - $y = $pos->getY(); - $z = $pos->getZ(); -~~~ -
-
-~~~{.c} - ns(Vec3_struct_t) pos = ns(Monster_pos(monster)); - float x = ns(Vec3_x(pos)); - float y = ns(Vec3_y(pos)); - float z = ns(Vec3_z(pos)); -~~~ -
-
-~~~{.dart} - myGame.Vec3 pos = monster.pos; - double x = pos.x; - double y = pos.y; - double z = pos.z; -~~~ -
-
-~~~{.lua} - local pos = mon:Pos() - local x = pos:X() - local y = pos:Y() - local z = pos:Z() -~~~ -
-
-~~~{.lobster} - let pos = monster.pos - let x = pos.x - let y = pos.y - let z = pos.z -~~~ -
-
-~~~{.rs} - let pos = monster.pos().unwrap(); - let x = pos.x(); - let y = pos.y(); - let z = pos.z(); -~~~ -
- -`x`, `y`, and `z` will contain `1.0`, `2.0`, and `3.0`, respectively. - -*Note: Had we not set `pos` during serialization, it would be a `NULL`-value.* - -Similarly, we can access elements of the inventory `vector` by indexing it. You -can also iterate over the length of the array/vector representing the -FlatBuffers `vector`. - -
-~~~{.cpp} - auto inv = monster->inventory(); // A pointer to a `flatbuffers::Vector<>`. - auto inv_len = inv->size(); - auto third_item = inv->Get(2); -~~~ -
-
-~~~{.java} - int invLength = monster.inventoryLength(); - byte thirdItem = monster.inventory(2); -~~~ -
-
-~~~{.kotlin} - val invLength = monster.inventoryLength - val thirdItem = monster.inventory(2)!! -~~~ -
-
-~~~{.cs} - int invLength = monster.InventoryLength; - var thirdItem = monster.Inventory(2); -~~~ -
-
-~~~{.go} - invLength := monster.InventoryLength() - thirdItem := monster.Inventory(2) -~~~ -
-
-~~~{.py} - inv_len = monster.InventoryLength() - third_item = monster.Inventory(2) -~~~ -
-
-~~~{.js} - var invLength = monster.inventoryLength(); - var thirdItem = monster.inventory(2); -~~~ -
-
-~~~{.ts} - let invLength = monster.inventoryLength(); - let thirdItem = monster.inventory(2); -~~~ -
-
-~~~{.php} - $inv_len = $monster->getInventoryLength(); - $third_item = $monster->getInventory(2); -~~~ -
-
-~~~{.c} - // If `inv` hasn't been set, it will be null. It is valid get - // the length of null which will be 0, useful for iteration. - flatbuffers_uint8_vec_t inv = ns(Monster_inventory(monster)); - size_t inv_len = flatbuffers_uint8_vec_len(inv); -~~~ -
-
-~~~{.dart} - int invLength = monster.inventory.length; - var thirdItem = monster.inventory[2]; -~~~ -
-
-~~~{.lua} - local invLength = mon:InventoryLength() - local thirdItem = mon:Inventory(3) -- Lua is 1-based -~~~ -
-
-~~~{.lobster} - let inv_len = monster.inventory_length - let third_item = monster.inventory(2) -~~~ -
-
-~~~{.rs} - // Get a test an element from the `inventory` FlatBuffer's `vector`. - let inv = monster.inventory().unwrap(); - - // Note that this vector is returned as a slice, because direct access for - // this type, a `u8` vector, is safe on all platforms: - let third_item = inv[2]; -~~~ -
- -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`: - -
-~~~{.cpp} - auto weapons = monster->weapons(); // A pointer to a `flatbuffers::Vector<>`. - auto weapon_len = weapons->size(); - auto second_weapon_name = weapons->Get(1)->name()->str(); - auto second_weapon_damage = weapons->Get(1)->damage() -~~~ -
-
-~~~{.java} - int weaponsLength = monster.weaponsLength(); - String secondWeaponName = monster.weapons(1).name(); - short secondWeaponDamage = monster.weapons(1).damage(); -~~~ -
-
-~~~{.kt} - val weaponsLength = monster.weaponsLength - val secondWeaponName = monster.weapons(1)!!.name - val secondWeaponDamage = monster.weapons(1)!!.damage -~~~ -
-
-~~~{.cs} - int weaponsLength = monster.WeaponsLength; - var secondWeaponName = monster.Weapons(1).Name; - var secondWeaponDamage = monster.Weapons(1).Damage; -~~~ -
-
-~~~{.go} - weaponLength := monster.WeaponsLength() - weapon := new(sample.Weapon) // We need a `sample.Weapon` to pass into `monster.Weapons()` - // to capture the output of the function. - if monster.Weapons(weapon, 1) { - secondWeaponName := weapon.Name() - secondWeaponDamage := weapon.Damage() - } -~~~ -
-
-~~~{.py} - weapons_length = monster.WeaponsLength() - second_weapon_name = monster.Weapons(1).Name() - second_weapon_damage = monster.Weapons(1).Damage() -~~~ -
-
-~~~{.js} - var weaponsLength = monster.weaponsLength(); - var secondWeaponName = monster.weapons(1).name(); - var secondWeaponDamage = monster.weapons(1).damage(); -~~~ -
-
-~~~{.ts} - let weaponsLength = monster.weaponsLength(); - let secondWeaponName = monster.weapons(1).name(); - let secondWeaponDamage = monster.weapons(1).damage(); -~~~ -
-
-~~~{.php} - $weapons_len = $monster->getWeaponsLength(); - $second_weapon_name = $monster->getWeapons(1)->getName(); - $second_weapon_damage = $monster->getWeapons(1)->getDamage(); -~~~ -
-
-~~~{.c} - ns(Weapon_vec_t) weapons = ns(Monster_weapons(monster)); - size_t weapons_len = ns(Weapon_vec_len(weapons)); - // We can use `const char *` instead of `flatbuffers_string_t`. - const char *second_weapon_name = ns(Weapon_name(ns(Weapon_vec_at(weapons, 1)))); - uint16_t second_weapon_damage = ns(Weapon_damage(ns(Weapon_vec_at(weapons, 1)))); -~~~ -
-
-~~~{.dart} - int weaponsLength = monster.weapons.length; - var secondWeaponName = monster.weapons[1].name; - var secondWeaponDamage = monster.Weapons[1].damage; -~~~ -
-
-~~~{.lua} - local weaponsLength = mon:WeaponsLength() - local secondWeaponName = mon:Weapon(2):Name() - local secondWeaponDamage = mon:Weapon(2):Damage() -~~~ -
-
-~~~{.lobster} - let weapons_length = monster.weapons_length - let second_weapon_name = monster.weapons(1).name - let second_weapon_damage = monster.weapons(1).damage -~~~ -
-
-~~~{.rs} - // Get and test the `weapons` FlatBuffers's `vector`. - let weps = monster.weapons().unwrap(); - let weps_len = weps.len(); - - let wep2 = weps.get(1); - let second_weapon_name = wep2.name(); - let second_weapon_damage = wep2.damage(); -~~~ -
- -Last, we can access our `Equipped` FlatBuffer `union`. Just like when we created -the `union`, we need to get both parts of the `union`: the type and the data. - -We can access the type to dynamically cast the data as needed (since the -`union` only stores a FlatBuffer `table`). - -
-~~~{.cpp} - auto union_type = monster.equipped_type(); - - if (union_type == Equipment_Weapon) { - auto weapon = static_cast(monster->equipped()); // Requires `static_cast` - // to type `const Weapon*`. - - auto weapon_name = weapon->name()->str(); // "Axe" - auto weapon_damage = weapon->damage(); // 5 - } -~~~ -
-
-~~~{.java} - int unionType = monster.EquippedType(); - - if (unionType == Equipment.Weapon) { - Weapon weapon = (Weapon)monster.equipped(new Weapon()); // Requires explicit cast - // to `Weapon`. - - String weaponName = weapon.name(); // "Axe" - short weaponDamage = weapon.damage(); // 5 - } -~~~ -
-
-~~~{.kt} - val unionType = monster.EquippedType - - if (unionType == Equipment.Weapon) { - val weapon = monster.equipped(Weapon()) as Weapon // Requires explicit cast - // to `Weapon`. - - val weaponName = weapon.name // "Axe" - val weaponDamage = weapon.damage // 5 - } -~~~ -
-
-~~~{.cs} - var unionType = monster.EquippedType; - - if (unionType == Equipment.Weapon) { - var weapon = monster.Equipped().Value; - - var weaponName = weapon.Name; // "Axe" - var weaponDamage = weapon.Damage; // 5 - } -~~~ -
-
-~~~{.go} - // We need a `flatbuffers.Table` to capture the output of the - // `monster.Equipped()` function. - unionTable := new(flatbuffers.Table) - - if monster.Equipped(unionTable) { - unionType := monster.EquippedType() - - if unionType == sample.EquipmentWeapon { - // Create a `sample.Weapon` object that can be initialized with the contents - // of the `flatbuffers.Table` (`unionTable`), which was populated by - // `monster.Equipped()`. - unionWeapon = new(sample.Weapon) - unionWeapon.Init(unionTable.Bytes, unionTable.Pos) - - weaponName = unionWeapon.Name() - weaponDamage = unionWeapon.Damage() - } - } -~~~ -
-
-~~~{.py} - union_type = monster.EquippedType() - - if union_type == MyGame.Sample.Equipment.Equipment().Weapon: - # `monster.Equipped()` returns a `flatbuffers.Table`, which can be used to - # initialize a `MyGame.Sample.Weapon.Weapon()`. - union_weapon = MyGame.Sample.Weapon.Weapon() - union_weapon.Init(monster.Equipped().Bytes, monster.Equipped().Pos) - - weapon_name = union_weapon.Name() // 'Axe' - weapon_damage = union_weapon.Damage() // 5 -~~~ -
-
-~~~{.js} - var unionType = monster.equippedType(); - - if (unionType == MyGame.Sample.Equipment.Weapon) { - var weapon_name = monster.equipped(new MyGame.Sample.Weapon()).name(); // 'Axe' - var weapon_damage = monster.equipped(new MyGame.Sample.Weapon()).damage(); // 5 - } -~~~ -
-
-~~~{.ts} - let unionType = monster.equippedType(); - - if (unionType == MyGame.Sample.Equipment.Weapon) { - let weapon_name = monster.equipped(new MyGame.Sample.Weapon()).name(); // 'Axe' - let weapon_damage = monster.equipped(new MyGame.Sample.Weapon()).damage(); // 5 - } -~~~ -
-
-~~~{.php} - $union_type = $monster->getEquippedType(); - - if ($union_type == \MyGame\Sample\Equipment::Weapon) { - $weapon_name = $monster->getEquipped(new \MyGame\Sample\Weapon())->getName(); // "Axe" - $weapon_damage = $monster->getEquipped(new \MyGame\Sample\Weapon())->getDamage(); // 5 - } -~~~ -
-
-~~~{.c} - // Access union type field. - if (ns(Monster_equipped_type(monster)) == ns(Equipment_Weapon)) { - // Cast to appropriate type: - // C allows for silent void pointer assignment, so we need no explicit cast. - ns(Weapon_table_t) weapon = ns(Monster_equipped(monster)); - const char *weapon_name = ns(Weapon_name(weapon)); // "Axe" - uint16_t weapon_damage = ns(Weapon_damage(weapon)); // 5 - } -~~~ -
-
-~~~{.dart} - var unionType = monster.equippedType.value; - - if (unionType == myGame.EquipmentTypeId.Weapon.value) { - myGame.Weapon weapon = mon.equipped as myGame.Weapon; - - var weaponName = weapon.name; // "Axe" - var weaponDamage = weapon.damage; // 5 - } -~~~ -
-
-~~~{.lua} - local unionType = mon:EquippedType() - - if unionType == equipment.Weapon then - local unionWeapon = weapon.New() - unionWeapon:Init(mon:Equipped().bytes, mon:Equipped().pos) - - local weaponName = unionWeapon:Name() -- 'Axe' - local weaponDamage = unionWeapon:Damage() -- 5 - end -~~~ -
-
-~~~{.lobster} - union_type = monster.equipped_type - - if union_type == MyGame_Sample_Equipment_Weapon: - // `monster.equipped_as_Weapon` returns a FlatBuffer handle much like normal table fields, - // but this is only valid to call if we already know it is the correct type. - let union_weapon = monster.equipped_as_Weapon - - let weapon_name = union_weapon.name // "Axe" - let weapon_damage = union_weapon.damage // 5 -~~~ -
-
-~~~{.rs} - // Get and test the `Equipment` union (`equipped` field). - // `equipped_as_weapon` returns a FlatBuffer handle much like normal table - // fields, but this will return `None` is the union is not actually of that - // type. - if monster.equipped_type() == Equipment::Weapon { - let equipped = monster.equipped_as_weapon().unwrap(); - let weapon_name = equipped.name(); - let weapon_damage = equipped.damage(); -~~~ -
- -## Mutating FlatBuffers - -As you saw above, typically once you have created a FlatBuffer, it is read-only -from that moment on. There are, however, cases where you have just received a -FlatBuffer, and you'd like to modify something about it before sending it on to -another recipient. With the above functionality, you'd have to generate an -entirely new FlatBuffer, while tracking what you modified in your own data -structures. This is inconvenient. - -For this reason FlatBuffers can also be mutated in-place. While this is great -for making small fixes to an existing buffer, you generally want to create -buffers from scratch whenever possible, since it is much more efficient and the -API is much more general purpose. - -To get non-const accessors, invoke `flatc` with `--gen-mutable`. - -Similar to how we read fields using the accessors above, we can now use the -mutators like so: - -
-~~~{.cpp} - auto monster = GetMutableMonster(buffer_pointer); // non-const - monster->mutate_hp(10); // Set the table `hp` field. - monster->mutable_pos()->mutate_z(4); // Set struct field. - monster->mutable_inventory()->Mutate(0, 1); // Set vector element. -~~~ -
-
-~~~{.java} - Monster monster = Monster.getRootAsMonster(buf); - monster.mutateHp(10); // Set table field. - monster.pos().mutateZ(4); // Set struct field. - monster.mutateInventory(0, 1); // Set vector element. -~~~ -
-
-~~~{.kt} - val monster = Monster.getRootAsMonster(buf) - monster.mutateHp(10) // Set table field. - monster.pos!!.mutateZ(4) // Set struct field. - monster.mutateInventory(0, 1) // Set vector element. -~~~ -
-
-~~~{.cs} - var monster = Monster.GetRootAsMonster(buf); - monster.MutateHp(10); // Set table field. - monster.Pos.MutateZ(4); // Set struct field. - monster.MutateInventory(0, 1); // Set vector element. -~~~ -
-
-~~~{.go} - -~~~ -
-
-~~~{.py} - -~~~ -
-
-~~~{.js} - -~~~ -
-
-~~~{.ts} - -~~~ -
-
-~~~{.php} - -~~~ -
-
-~~~{.c} - -~~~ -
-
-~~~{.dart} - -~~~ -
-
-~~~{.lua} - -~~~ -
-
-~~~{.lobster} - -~~~ -
-
-~~~{.rs} - -~~~ -
- -We use the somewhat verbose term `mutate` instead of `set` to indicate that this -is a special use case, not to be confused with the default way of constructing -FlatBuffer data. - -After the above mutations, you can send on the FlatBuffer to a new recipient -without any further work! - -Note that any `mutate` functions on a table will return a boolean, which is -`false` if the field we're trying to set is not present in the buffer. Fields -that are not present if they weren't set, or even if they happen to be equal to -the default value. For example, in the creation code above, the `mana` -field is equal to `150`, which is the default value, so it was never stored in -the buffer. Trying to call the corresponding `mutate` method for `mana` on such -data will return `false`, and the value won't actually be modified! - -One way to solve this is to call `ForceDefaults` on a FlatBufferBuilder to -force all fields you set to actually be written. This, of course, increases the -size of the buffer somewhat, but this may be acceptable for a mutable buffer. - -If this is not sufficient, other ways of mutating FlatBuffers may be supported -in your language through an object based API (`--gen-object-api`) or reflection. -See the individual language documents for support. - -## Using `flatc` as a JSON Conversion Tool - -If you are working with C, C++, or Lobster, you can parse JSON at runtime. -If your language does not support JSON at the moment, `flatc` may provide an -alternative. Using `flatc` is often the preferred method, as it doesn't require you to -add any new code to your program. It is also efficient, since you can ship with -the binary data. The drawback is that it requires an extra step for your -users/developers to perform (although it may be able to be automated -as part of your compilation). - -#### JSON to binary representation - -Lets say you have a JSON file that describes your monster. In this example, -we will use the file `flatbuffers/samples/monsterdata.json`. - -Here are the contents of the file: - -~~~{.json} -{ - pos: { - x: 1.0, - y: 2.0, - z: 3.0 - }, - hp: 300, - name: "Orc", - weapons: [ - { - name: "axe", - damage: 100 - }, - { - name: "bow", - damage: 90 - } - ], - equipped_type: "Weapon", - equipped: { - name: "bow", - damage: 90 - } -} -~~~ - -You can run this file through the `flatc` compiler with the `-b` flag and -our `monster.fbs` schema to produce a FlatBuffer binary file. - -~~~{.sh} -./../flatc -b monster.fbs monsterdata.json -~~~ - -The output of this will be a file `monsterdata.bin`, which will contain the -FlatBuffer binary representation of the contents from our `.json` file. - -
-*Note: If you're working in C++, you can also parse JSON at runtime. See the -[Use in C++](@ref flatbuffers_guide_use_cpp) section of the Programmer's -Guide for more information.* -
-
-*Note: If you're working in C, the `flatcc --json` (not `flatc`) -compiler will generate schema specific high performance json parsers and -printers that you can compile and use at runtime. The `flatc` compiler (not -`flatcc`) on the other hand, is still useful for general offline json to -flatbuffer conversion from a given schema. There are no current plans -for `flatcc` to support this.* -
-
-*Note: If you're working in Lobster, you can also parse JSON at runtime. See the -[Use in Lobster](@ref flatbuffers_guide_use_lobster) section of the Programmer's -Guide for more information.* -
- -#### FlatBuffer binary to JSON - -Converting from a FlatBuffer binary representation to JSON is supported as well: -~~~{.sh} -./../flatc --json --raw-binary monster.fbs -- monsterdata.bin -~~~ -This will convert `monsterdata.bin` back to its original JSON representation. -You need to pass the corresponding FlatBuffers schema so that flatc knows how to -interpret the binary buffer. Since `monster.fbs` does not specify an explicit -`file_identifier` for binary buffers, `flatc` needs to be forced into reading -the `.bin` file using the `--raw-binary` option. - -The FlatBuffer binary representation does not explicitly encode default values, -therefore they are not present in the resulting JSON unless you specify -`--defaults-json`. - -If you intend to process the JSON with other tools, you may consider switching -on `--strict-json` so that identifiers are quoted properly. - -*Note: The resulting JSON file is not necessarily identical with the original JSON. -If the binary representation contains floating point numbers, floats and doubles -are rounded to 6 and 12 digits, respectively, in order to represent them as -decimals in the JSON document. * - -## Advanced Features for Each Language - -Each language has a dedicated `Use in XXX` page in the Programmer's Guide -to cover the nuances of FlatBuffers in that language. - -For your chosen language, see: - -
-[Use in C++](@ref flatbuffers_guide_use_cpp) -
-
-[Use in Java/C#](@ref flatbuffers_guide_use_java_c-sharp) -
-
-[Use in Kotlin](@ref flatbuffers_guide_use_kotlin) -
-
-[Use in Java/C#](@ref flatbuffers_guide_use_java_c-sharp) -
-
-[Use in Go](@ref flatbuffers_guide_use_go) -
-
-[Use in Python](@ref flatbuffers_guide_use_python) -
-
-[Use in JavaScript](@ref flatbuffers_guide_use_javascript) -
-
-[Use in TypeScript](@ref flatbuffers_guide_use_typescript) -
-
-[Use in PHP](@ref flatbuffers_guide_use_php) -
-
-[Use in C](@ref flatbuffers_guide_use_c) -
-
-[Use in Dart](@ref flatbuffers_guide_use_dart) -
-
-[Use in Lua](@ref flatbuffers_guide_use_lua) -
-
-[Use in Lobster](@ref flatbuffers_guide_use_lobster) -
-
-[Use in Rust](@ref flatbuffers_guide_use_rust) -
- -
diff --git a/third_party/flatbuffers/docs/source/TypeScriptUsage.md b/third_party/flatbuffers/docs/source/TypeScriptUsage.md deleted file mode 100644 index 02aa239e00f..00000000000 --- a/third_party/flatbuffers/docs/source/TypeScriptUsage.md +++ /dev/null @@ -1,66 +0,0 @@ -Use in TypeScript {#flatbuffers_guide_use_typescript} -================= - -## Before you get started - -Before diving into the FlatBuffers usage in TypeScript, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to -general FlatBuffers usage in all of the supported languages -(including TypeScript). This page is specifically designed to cover the nuances -of FlatBuffers usage in TypeScript. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers TypeScript library code location - -The code for the FlatBuffers TypeScript library can be found at -`flatbuffers/js` with typings available at `@types/flatbuffers`. - -## Testing the FlatBuffers TypeScript library - -To run the tests, use the [TypeScriptTest.sh](https://github.com/google/ -flatbuffers/blob/master/tests/TypeScriptTest.sh) shell script. - -*Note: The TypeScript test file requires [Node.js](https://nodejs.org/en/).* - -## Using the FlatBuffers TypeScript libary - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in TypeScript.* - -FlatBuffers supports both reading and writing FlatBuffers in TypeScript. - -To use FlatBuffers in your own code, first generate TypeScript classes from your -schema with the `--ts` option to `flatc`. Then you can include both FlatBuffers -and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in TypeScript: -First, include the library and generated code. Then read the file into an -`Uint8Array`. Make a `flatbuffers.ByteBuffer` out of the `Uint8Array`, and pass -the ByteBuffer to the `getRootAsMonster` function. - -~~~{.ts} - // note: import flatbuffers with your desired import method - - import { MyGame } from './monster_generated'; - - let data = new Uint8Array(fs.readFileSync('monster.dat')); - let buf = new flatbuffers.ByteBuffer(data); - - let monster = MyGame.Example.Monster.getRootAsMonster(buf); -~~~ - -Now you can access values like this: - -~~~{.ts} - let hp = monster.hp(); - let pos = monster.pos(); -~~~ - -## Text parsing FlatBuffers in TypeScript - -There currently is no support for parsing text (Schema's and JSON) directly -from TypeScript. diff --git a/third_party/flatbuffers/docs/source/WhitePaper.md b/third_party/flatbuffers/docs/source/WhitePaper.md deleted file mode 100644 index e504ada41d5..00000000000 --- a/third_party/flatbuffers/docs/source/WhitePaper.md +++ /dev/null @@ -1,128 +0,0 @@ -FlatBuffers white paper {#flatbuffers_white_paper} -======================= - -This document tries to shed some light on to the "why" of FlatBuffers, a -new serialization library. - -## Motivation - -Back in the good old days, performance was all about instructions and -cycles. Nowadays, processing units have run so far ahead of the memory -subsystem, that making an efficient application should start and finish -with thinking about memory. How much you use of it. How you lay it out -and access it. How you allocate it. When you copy it. - -Serialization is a pervasive activity in a lot programs, and a common -source of memory inefficiency, with lots of temporary data structures -needed to parse and represent data, and inefficient allocation patterns -and locality. - -If it would be possible to do serialization with no temporary objects, -no additional allocation, no copying, and good locality, this could be -of great value. The reason serialization systems usually don't manage -this is because it goes counter to forwards/backwards compatability, and -platform specifics like endianness and alignment. - -FlatBuffers is what you get if you try anyway. - -In particular, FlatBuffers focus is on mobile hardware (where memory -size and memory bandwidth is even more constrained than on desktop -hardware), and applications that have the highest performance needs: -games. - -## FlatBuffers - -*This is a summary of FlatBuffers functionality, with some rationale. -A more detailed description can be found in the FlatBuffers -documentation.* - -### Summary - -A FlatBuffer is a binary buffer containing nested objects (structs, -tables, vectors,..) organized using offsets so that the data can be -traversed in-place just like any pointer-based data structure. Unlike -most in-memory data structures however, it uses strict rules of -alignment and endianness (always little) to ensure these buffers are -cross platform. Additionally, for objects that are tables, FlatBuffers -provides forwards/backwards compatibility and general optionality of -fields, to support most forms of format evolution. - -You define your object types in a schema, which can then be compiled to -C++ or Java for low to zero overhead reading & writing. -Optionally, JSON data can be dynamically parsed into buffers. - -### Tables - -Tables are the cornerstone of FlatBuffers, since format evolution is -essential for most applications of serialization. Typically, dealing -with format changes is something that can be done transparently during -the parsing process of most serialization solutions out there. -But a FlatBuffer isn't parsed before it is accessed. - -Tables get around this by using an extra indirection to access fields, -through a *vtable*. Each table comes with a vtable (which may be shared -between multiple tables with the same layout), and contains information -where fields for this particular kind of instance of vtable are stored. -The vtable may also indicate that the field is not present (because this -FlatBuffer was written with an older version of the software, of simply -because the information was not necessary for this instance, or deemed -deprecated), in which case a default value is returned. - -Tables have a low overhead in memory (since vtables are small and -shared) and in access cost (an extra indirection), but provide great -flexibility. Tables may even cost less memory than the equivalent -struct, since fields do not need to be stored when they are equal to -their default. - -FlatBuffers additionally offers "naked" structs, which do not offer -forwards/backwards compatibility, but can be even smaller (useful for -very small objects that are unlikely to change, like e.g. a coordinate -pair or a RGBA color). - -### Schemas - -While schemas reduce some generality (you can't just read any data -without having its schema), they have a lot of upsides: - -- Most information about the format can be factored into the generated - code, reducing memory needed to store data, and time to access it. - -- The strong typing of the data definitions means less error - checking/handling at runtime (less can go wrong). - -- A schema enables us to access a buffer without parsing. - -FlatBuffer schemas are fairly similar to those of the incumbent, -Protocol Buffers, and generally should be readable to those familiar -with the C family of languages. We chose to improve upon the features -offered by .proto files in the following ways: - -- Deprecation of fields instead of manual field id assignment. - Extending an object in a .proto means hunting for a free slot among - the numbers (preferring lower numbers since they have a more compact - representation). Besides being inconvenient, it also makes removing - fields problematic: you either have to keep them, not making it - obvious that this field shouldn't be read/written anymore, and still - generating accessors. Or you remove it, but now you risk that - there's still old data around that uses that field by the time - someone reuses that field id, with nasty consequences. - -- Differentiating between tables and structs (see above). Effectively - all table fields are `optional`, and all struct fields are - `required`. - -- Having a native vector type instead of `repeated`. This gives you a - length without having to collect all items, and in the case of - scalars provides for a more compact representation, and one that - guarantees adjacency. - -- Having a native `union` type instead of using a series of `optional` - fields, all of which must be checked individually. - -- Being able to define defaults for all scalars, instead of having to - deal with their optionality at each access. - -- A parser that can deal with both schemas and data definitions (JSON - compatible) uniformly. - -
diff --git a/third_party/flatbuffers/docs/source/doxyfile b/third_party/flatbuffers/docs/source/doxyfile deleted file mode 100644 index 6ba3c108cc9..00000000000 --- a/third_party/flatbuffers/docs/source/doxyfile +++ /dev/null @@ -1,2371 +0,0 @@ -# Doxyfile 1.8.5 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project. -# -# All text after a double hash (##) is considered a comment and is placed in -# front of the TAG it is preceding. -# -# All text after a single hash (#) is considered a comment and will be ignored. -# The format is: -# TAG = value [value, ...] -# For lists, items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (\" \"). - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all text -# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv -# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv -# for the list of possible encodings. -# The default value is: UTF-8. - -DOXYFILE_ENCODING = UTF-8 - -# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by -# double-quotes, unless you are using Doxywizard) that should identify the -# project for which the documentation is generated. This name is used in the -# title of most generated pages and in a few other places. -# The default value is: My Project. - -PROJECT_NAME = "FlatBuffers" - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. This -# could be handy for archiving the generated documentation or if some version -# control system is used. - -PROJECT_NUMBER = - -# Using the PROJECT_BRIEF tag one can provide an optional one line description -# for a project that appears at the top of each page and should give viewer a -# quick idea about the purpose of the project. Keep the description short. - -PROJECT_BRIEF = - -# With the PROJECT_LOGO tag one can specify an logo or icon that is included in -# the documentation. The maximum height of the logo should not exceed 55 pixels -# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo -# to the output directory. - -PROJECT_LOGO = - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path -# into which the generated documentation will be written. If a relative path is -# entered, it will be relative to the location where doxygen was started. If -# left blank the current directory will be used. - -OUTPUT_DIRECTORY = ".." - -# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub- -# directories (in 2 levels) under the output directory of each output format and -# will distribute the generated files over these directories. Enabling this -# option can be useful when feeding doxygen a huge amount of source files, where -# putting all generated files in the same directory would otherwise causes -# performance problems for the file system. -# The default value is: NO. - -CREATE_SUBDIRS = NO - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# Possible values are: Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese- -# Traditional, Croatian, Czech, Danish, Dutch, English, Esperanto, Farsi, -# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en, -# Korean, Korean-en, Latvian, Norwegian, Macedonian, Persian, Polish, -# Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish, -# Turkish, Ukrainian and Vietnamese. -# The default value is: English. - -OUTPUT_LANGUAGE = English - -# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member -# descriptions after the members that are listed in the file and class -# documentation (similar to Javadoc). Set to NO to disable this. -# The default value is: YES. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief -# description of a member or function before the detailed description -# -# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. -# The default value is: YES. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator that is -# used to form the text in various listings. Each string in this list, if found -# as the leading text of the brief description, will be stripped from the text -# and the result, after processing the whole list, is used as the annotated -# text. Otherwise, the brief description is used as-is. If left blank, the -# following values are used ($name is automatically replaced with the name of -# the entity):The $name class, The $name widget, The $name file, is, provides, -# specifies, contains, represents, a, an and the. - -ABBREVIATE_BRIEF = "The $name class" \ - "The $name widget" \ - "The $name file" \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# doxygen will generate a detailed section even if there is only a brief -# description. -# The default value is: NO. - -ALWAYS_DETAILED_SEC = NO - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all -# inherited members of a class in the documentation of that class as if those -# members were ordinary class members. Constructors, destructors and assignment -# operators of the base classes will not be shown. -# The default value is: NO. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path -# before files name in the file list and in the header files. If set to NO the -# shortest path that makes the file name unique will be used -# The default value is: YES. - -FULL_PATH_NAMES = NO - -# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. -# Stripping is only done if one of the specified strings matches the left-hand -# part of the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the path to -# strip. -# -# Note that you can specify absolute paths here, but also relative paths, which -# will be relative from the directory where doxygen is started. -# This tag requires that the tag FULL_PATH_NAMES is set to YES. - -STRIP_FROM_PATH = - -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the -# path mentioned in the documentation of a class, which tells the reader which -# header file to include in order to use a class. If left blank only the name of -# the header file containing the class definition is used. Otherwise one should -# specify the list of include paths that are normally passed to the compiler -# using the -I flag. - -STRIP_FROM_INC_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but -# less readable) file names. This can be useful is your file systems doesn't -# support long names like on DOS, Mac, or CD-ROM. -# The default value is: NO. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the -# first line (until the first dot) of a Javadoc-style comment as the brief -# description. If set to NO, the Javadoc-style will behave just like regular Qt- -# style comments (thus requiring an explicit @brief command for a brief -# description.) -# The default value is: NO. - -JAVADOC_AUTOBRIEF = YES - -# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first -# line (until the first dot) of a Qt-style comment as the brief description. If -# set to NO, the Qt-style will behave just like regular Qt-style comments (thus -# requiring an explicit \brief command for a brief description.) -# The default value is: NO. - -QT_AUTOBRIEF = NO - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a -# multi-line C++ special comment block (i.e. a block of //! or /// comments) as -# a brief description. This used to be the default behavior. The new default is -# to treat a multi-line C++ comment block as a detailed description. Set this -# tag to YES if you prefer the old behavior instead. -# -# Note that setting this tag to YES also means that rational rose comments are -# not recognized any more. -# The default value is: NO. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the -# documentation from any documented member that it re-implements. -# The default value is: YES. - -INHERIT_DOCS = YES - -# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a -# new page for each member. If set to NO, the documentation of a member will be -# part of the file/class/namespace that contains it. -# The default value is: NO. - -SEPARATE_MEMBER_PAGES = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen -# uses this value to replace tabs by spaces in code fragments. -# Minimum value: 1, maximum value: 16, default value: 4. - -TAB_SIZE = 2 - -# This tag can be used to specify a number of aliases that act as commands in -# the documentation. An alias has the form: -# name=value -# For example adding -# "sideeffect=@par Side Effects:\n" -# will allow you to put the command \sideeffect (or @sideeffect) in the -# documentation, which will result in a user-defined paragraph with heading -# "Side Effects:". You can put \n's in the value part of an alias to insert -# newlines. - -ALIASES = - -# This tag can be used to specify a number of word-keyword mappings (TCL only). -# A mapping has the form "name=value". For example adding "class=itcl::class" -# will allow you to use the command class in the itcl::class meaning. - -TCL_SUBST = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources -# only. Doxygen will then generate output that is more tailored for C. For -# instance, some of the names that are used will be different. The list of all -# members will be omitted, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or -# Python sources only. Doxygen will then generate output that is more tailored -# for that language. For instance, namespaces will be presented as packages, -# qualified scopes will look different, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources. Doxygen will then generate output that is tailored for Fortran. -# The default value is: NO. - -OPTIMIZE_FOR_FORTRAN = NO - -# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for VHDL. -# The default value is: NO. - -OPTIMIZE_OUTPUT_VHDL = NO - -# Doxygen selects the parser to use depending on the extension of the files it -# parses. With this tag you can assign which parser to use for a given -# extension. Doxygen has a built-in mapping, but you can override or extend it -# using this tag. The format is ext=language, where ext is a file extension, and -# language is one of the parsers supported by doxygen: IDL, Java, Javascript, -# C#, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL. For instance to make -# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C -# (default is Fortran), use: inc=Fortran f=C. -# -# Note For files without extension you can use no_extension as a placeholder. -# -# Note that for custom extensions you also need to set FILE_PATTERNS otherwise -# the files are not read by doxygen. - -EXTENSION_MAPPING = - -# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments -# according to the Markdown format, which allows for more readable -# documentation. See http://daringfireball.net/projects/markdown/ for details. -# The output of markdown processing is further processed by doxygen, so you can -# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in -# case of backward compatibilities issues. -# The default value is: YES. - -MARKDOWN_SUPPORT = YES - -# When enabled doxygen tries to link words that correspond to documented -# classes, or namespaces to their corresponding documentation. Such a link can -# be prevented in individual cases by by putting a % sign in front of the word -# or globally by setting AUTOLINK_SUPPORT to NO. -# The default value is: YES. - -AUTOLINK_SUPPORT = NO # Due to the multiple languages included in the API - # reference for FlatBuffers, the Auto-links were - # wrong more often than not. - -# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should set this -# tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); -# versus func(std::string) {}). This also make the inheritance and collaboration -# diagrams that involve STL classes more complete and accurate. -# The default value is: NO. - -BUILTIN_STL_SUPPORT = NO - -# If you use Microsoft's C++/CLI language, you should set this option to YES to -# enable parsing support. -# The default value is: NO. - -CPP_CLI_SUPPORT = NO - -# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: -# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen -# will parse them like normal C++ but will assume all classes use public instead -# of private inheritance when no explicit protection keyword is present. -# The default value is: NO. - -SIP_SUPPORT = NO - -# For Microsoft's IDL there are propget and propput attributes to indicate -# getter and setter methods for a property. Setting this option to YES will make -# doxygen to replace the get and set methods by a property in the documentation. -# This will only work if the methods are indeed getting or setting a simple -# type. If this is not the case, or you want to show the methods anyway, you -# should set this option to NO. -# The default value is: YES. - -IDL_PROPERTY_SUPPORT = NO - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES, then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. -# The default value is: NO. - -DISTRIBUTE_GROUP_DOC = NO - -# Set the SUBGROUPING tag to YES to allow class member groups of the same type -# (for instance a group of public functions) to be put as a subgroup of that -# type (e.g. under the Public Functions section). Set it to NO to prevent -# subgrouping. Alternatively, this can be done per class using the -# \nosubgrouping command. -# The default value is: YES. - -SUBGROUPING = YES - -# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions -# are shown inside the group in which they are included (e.g. using \ingroup) -# instead of on a separate page (for HTML and Man pages) or section (for LaTeX -# and RTF). -# -# Note that this feature does not work in combination with -# SEPARATE_MEMBER_PAGES. -# The default value is: NO. - -INLINE_GROUPED_CLASSES = NO - -# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions -# with only public data fields or simple typedef fields will be shown inline in -# the documentation of the scope in which they are defined (i.e. file, -# namespace, or group documentation), provided this scope is documented. If set -# to NO, structs, classes, and unions are shown on a separate page (for HTML and -# Man pages) or section (for LaTeX and RTF). -# The default value is: NO. - -INLINE_SIMPLE_STRUCTS = NO - -# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or -# enum is documented as struct, union, or enum with the name of the typedef. So -# typedef struct TypeS {} TypeT, will appear in the documentation as a struct -# with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically be -# useful for C code in case the coding convention dictates that all compound -# types are typedef'ed and only the typedef is referenced, never the tag name. -# The default value is: NO. - -TYPEDEF_HIDES_STRUCT = NO - -# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This -# cache is used to resolve symbols given their name and scope. Since this can be -# an expensive process and often the same symbol appears multiple times in the -# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small -# doxygen will become slower. If the cache is too large, memory is wasted. The -# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range -# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 -# symbols. At the end of a run doxygen will report the cache usage and suggest -# the optimal cache size from a speed point of view. -# Minimum value: 0, maximum value: 9, default value: 0. - -LOOKUP_CACHE_SIZE = 0 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. Private -# class members and static file members will be hidden unless the -# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. -# Note: This will also disable the warnings about undocumented members that are -# normally produced when WARNINGS is set to YES. -# The default value is: NO. - -EXTRACT_ALL = NO - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will -# be included in the documentation. -# The default value is: NO. - -EXTRACT_PRIVATE = NO - -# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal -# scope will be included in the documentation. -# The default value is: NO. - -EXTRACT_PACKAGE = NO - -# If the EXTRACT_STATIC tag is set to YES all static members of a file will be -# included in the documentation. -# The default value is: NO. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined -# locally in source files will be included in the documentation. If set to NO -# only classes defined in header files are included. Does not have any effect -# for Java sources. -# The default value is: YES. - -EXTRACT_LOCAL_CLASSES = NO - -# This flag is only useful for Objective-C code. When set to YES local methods, -# which are defined in the implementation section but not in the interface are -# included in the documentation. If set to NO only methods in the interface are -# included. -# The default value is: NO. - -EXTRACT_LOCAL_METHODS = NO - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base name of -# the file that contains the anonymous namespace. By default anonymous namespace -# are hidden. -# The default value is: NO. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all -# undocumented members inside documented classes or files. If set to NO these -# members will be included in the various overviews, but no documentation -# section is generated. This option has no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. If set -# to NO these classes will be included in the various overviews. This option has -# no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend -# (class|struct|union) declarations. If set to NO these declarations will be -# included in the documentation. -# The default value is: NO. - -HIDE_FRIEND_COMPOUNDS = NO - -# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any -# documentation blocks found inside the body of a function. If set to NO these -# blocks will be appended to the function's detailed documentation block. -# The default value is: NO. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation that is typed after a -# \internal command is included. If the tag is set to NO then the documentation -# will be excluded. Set it to YES to include the internal documentation. -# The default value is: NO. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file -# names in lower-case letters. If set to YES upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. -# The default value is: system dependent. - -CASE_SENSE_NAMES = NO - -# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with -# their full class and namespace scopes in the documentation. If set to YES the -# scope will be hidden. -# The default value is: NO. - -HIDE_SCOPE_NAMES = NO - -# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of -# the files that are included by a file in the documentation of that file. -# The default value is: YES. - -SHOW_INCLUDE_FILES = YES - -# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include -# files with double quotes in the documentation rather than with sharp brackets. -# The default value is: NO. - -FORCE_LOCAL_INCLUDES = NO - -# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the -# documentation for inline members. -# The default value is: YES. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the -# (detailed) documentation of file and class members alphabetically by member -# name. If set to NO the members will appear in declaration order. -# The default value is: YES. - -SORT_MEMBER_DOCS = YES - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief -# descriptions of file, namespace and class members alphabetically by member -# name. If set to NO the members will appear in declaration order. -# The default value is: NO. - -SORT_BRIEF_DOCS = YES - -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the -# (brief and detailed) documentation of class members so that constructors and -# destructors are listed first. If set to NO the constructors will appear in the -# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. -# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief -# member documentation. -# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting -# detailed member documentation. -# The default value is: NO. - -SORT_MEMBERS_CTORS_1ST = NO - -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy -# of group names into alphabetical order. If set to NO the group names will -# appear in their defined order. -# The default value is: NO. - -SORT_GROUP_NAMES = NO - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by -# fully-qualified names, including namespaces. If set to NO, the class list will -# be sorted only by class name, not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the alphabetical -# list. -# The default value is: NO. - -SORT_BY_SCOPE_NAME = NO - -# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper -# type resolution of all parameters of a function it will reject a match between -# the prototype and the implementation of a member function even if there is -# only one candidate or it is obvious which candidate to choose by doing a -# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still -# accept a match between prototype and implementation in such cases. -# The default value is: NO. - -STRICT_PROTO_MATCHING = NO - -# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the -# todo list. This list is created by putting \todo commands in the -# documentation. -# The default value is: YES. - -GENERATE_TODOLIST = NO - -# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the -# test list. This list is created by putting \test commands in the -# documentation. -# The default value is: YES. - -GENERATE_TESTLIST = NO - -# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug -# list. This list is created by putting \bug commands in the documentation. -# The default value is: YES. - -GENERATE_BUGLIST = NO - -# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO) -# the deprecated list. This list is created by putting \deprecated commands in -# the documentation. -# The default value is: YES. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional documentation -# sections, marked by \if ... \endif and \cond -# ... \endcond blocks. - -ENABLED_SECTIONS = - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the -# initial value of a variable or macro / define can have for it to appear in the -# documentation. If the initializer consists of more lines than specified here -# it will be hidden. Use a value of 0 to hide initializers completely. The -# appearance of the value of individual variables and macros / defines can be -# controlled using \showinitializer or \hideinitializer command in the -# documentation regardless of this setting. -# Minimum value: 0, maximum value: 10000, default value: 30. - -MAX_INITIALIZER_LINES = 30 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at -# the bottom of the documentation of classes and structs. If set to YES the list -# will mention the files that were used to generate the documentation. -# The default value is: YES. - -SHOW_USED_FILES = YES - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This -# will remove the Files entry from the Quick Index and from the Folder Tree View -# (if specified). -# The default value is: YES. - -SHOW_FILES = YES - -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces -# page. This will remove the Namespaces entry from the Quick Index and from the -# Folder Tree View (if specified). -# The default value is: YES. - -SHOW_NAMESPACES = YES - -# The FILE_VERSION_FILTER tag can be used to specify a program or script that -# doxygen should invoke to get the current version for each file (typically from -# the version control system). Doxygen will invoke the program by executing (via -# popen()) the command command input-file, where command is the value of the -# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided -# by doxygen. Whatever the program writes to standard output is used as the file -# version. For an example see the documentation. - -FILE_VERSION_FILTER = - -# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed -# by doxygen. The layout file controls the global structure of the generated -# output files in an output format independent way. To create the layout file -# that represents doxygen's defaults, run doxygen with the -l option. You can -# optionally specify a file name after the option, if omitted DoxygenLayout.xml -# will be used as the name of the layout file. -# -# Note that if you run doxygen from a directory containing a file called -# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE -# tag is left empty. - -LAYOUT_FILE = doxygen_layout.xml - -# The CITE_BIB_FILES tag can be used to specify one or more bib files containing -# the reference definitions. This must be a list of .bib files. The .bib -# extension is automatically appended if omitted. This requires the bibtex tool -# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. -# For LaTeX the style of the bibliography can be controlled using -# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the -# search path. Do not use file names with spaces, bibtex cannot handle them. See -# also \cite for info how to create references. - -CITE_BIB_FILES = - -#--------------------------------------------------------------------------- -# Configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated to -# standard output by doxygen. If QUIET is set to YES this implies that the -# messages are off. -# The default value is: NO. - -QUIET = NO - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES -# this implies that the warnings are on. -# -# Tip: Turn warnings on while writing the documentation. -# The default value is: YES. - -WARNINGS = YES - -# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate -# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag -# will automatically be disabled. -# The default value is: YES. - -WARN_IF_UNDOCUMENTED = YES - -# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some parameters -# in a documented function, or documenting parameters that don't exist or using -# markup commands wrongly. -# The default value is: YES. - -WARN_IF_DOC_ERROR = NO - -# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that -# are documented, but have no documentation for their parameters or return -# value. If set to NO doxygen will only warn about wrong or incomplete parameter -# documentation, but not about the absence of documentation. -# The default value is: NO. - -WARN_NO_PARAMDOC = NO - -# The WARN_FORMAT tag determines the format of the warning messages that doxygen -# can produce. The string should contain the $file, $line, and $text tags, which -# will be replaced by the file and line number from which the warning originated -# and the warning text. Optionally the format may contain $version, which will -# be replaced by the version of the file (if it could be obtained via -# FILE_VERSION_FILTER) -# The default value is: $file:$line: $text. - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning and error -# messages should be written. If left blank the output is written to standard -# error (stderr). - -WARN_LOGFILE = - -#--------------------------------------------------------------------------- -# Configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag is used to specify the files and/or directories that contain -# documented source files. You may enter file names like myfile.cpp or -# directories like /usr/src/myproject. Separate the files or directories with -# spaces. -# Note: If this tag is empty the current directory is searched. - -INPUT = "FlatBuffers.md" \ - "Building.md" \ - "Compiler.md" \ - "Schemas.md" \ - "CppUsage.md" \ - "CUsage.md" \ - "DartUsage.md" \ - "GoUsage.md" \ - "JavaCsharpUsage.md" \ - "JavaScriptUsage.md" \ - "TypeScriptUsage.md" \ - "PHPUsage.md" \ - "PythonUsage.md" \ - "LuaUsage.md" \ - "LobsterUsage.md" \ - "RustUsage.md" \ - "Support.md" \ - "Benchmarks.md" \ - "WhitePaper.md" \ - "FlexBuffers.md" \ - "Internals.md" \ - "Grammar.md" \ - "../../CONTRIBUTING.md" \ - "Tutorial.md" \ - "GoApi.md" \ - "gRPC/CppUsage.md" \ - "groups" \ - "../../java/com/google/flatbuffers" \ - "../../python/flatbuffers/builder.py" \ - "../../js/flatbuffers.js" \ - "../../php/FlatbufferBuilder.php" \ - "../../net/FlatBuffers/FlatBufferBuilder.cs" \ - "../../include/flatbuffers/flatbuffers.h" \ - "../../go/builder.go" - "../../rust/flatbuffers/src/builder.rs" - -# This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses -# libiconv (or the iconv built into libc) for the transcoding. See the libiconv -# documentation (see: http://www.gnu.org/software/libiconv) for the list of -# possible encodings. -# The default value is: UTF-8. - -INPUT_ENCODING = UTF-8 - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and -# *.h) to filter out the source-files in the directories. If left blank the -# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii, -# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, -# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, -# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, -# *.qsf, *.as and *.js. - -FILE_PATTERNS = *.c \ - *.cc \ - *.cxx \ - *.cpp \ - *.c++ \ - *.java \ - *.ii \ - *.ixx \ - *.ipp \ - *.i++ \ - *.inl \ - *.idl \ - *.ddl \ - *.odl \ - *.h \ - *.hh \ - *.hxx \ - *.hpp \ - *.h++ \ - *.cs \ - *.d \ - *.php \ - *.php4 \ - *.php5 \ - *.phtml \ - *.inc \ - *.m \ - *.markdown \ - *.md \ - *.mm \ - *.dox \ - *.py \ - *.f90 \ - *.f \ - *.for \ - *.tcl \ - *.vhd \ - *.vhdl \ - *.ucf \ - *.qsf \ - *.as \ - *.js \ - *.go - -# The RECURSIVE tag can be used to specify whether or not subdirectories should -# be searched for input files as well. -# The default value is: NO. - -RECURSIVE = YES - -# The EXCLUDE tag can be used to specify files and/or directories that should be -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. -# -# Note that relative paths are relative to the directory from which doxygen is -# run. - -EXCLUDE = - -# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or -# directories that are symbolic links (a Unix file system feature) are excluded -# from the input. -# The default value is: NO. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories for example use the pattern */test/* - -EXCLUDE_PATTERNS = *_test.py | - __init__.py - -# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names -# (namespaces, classes, functions, etc.) that should be excluded from the -# output. The symbol name can be a fully qualified name, a word, or if the -# wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories use the pattern */test/* - -EXCLUDE_SYMBOLS = - -# The EXAMPLE_PATH tag can be used to specify one or more files or directories -# that contain example code fragments that are included (see the \include -# command). - -EXAMPLE_PATH = "GoApi_generated.txt" "../../grpc/samples" - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and -# *.h) to filter out the source-files in the directories. If left blank all -# files are included. - -EXAMPLE_PATTERNS = *.cpp *.h *.txt *.fbs - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude commands -# irrespective of the value of the RECURSIVE tag. -# The default value is: NO. - -EXAMPLE_RECURSIVE = YES - -# The IMAGE_PATH tag can be used to specify one or more files or directories -# that contain images that are to be included in the documentation (see the -# \image command). - -IMAGE_PATH = - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command: -# -# -# -# where is the value of the INPUT_FILTER tag, and is the -# name of an input file. Doxygen will then use the output that the filter -# program writes to standard output. If FILTER_PATTERNS is specified, this tag -# will be ignored. -# -# Note that the filter must not add or remove lines; it is applied before the -# code is scanned, but not when the output code is generated. If lines are added -# or removed, the anchors will not be placed correctly. - -INPUT_FILTER = - -# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. The filters are a list of the form: pattern=filter -# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how -# filters are used. If the FILTER_PATTERNS tag is empty or if none of the -# patterns match the file name, INPUT_FILTER is applied. - -FILTER_PATTERNS = *.py=py_filter - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER ) will also be used to filter the input files that are used for -# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). -# The default value is: NO. - -FILTER_SOURCE_FILES = NO - -# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file -# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and -# it is also possible to disable source filtering for a specific pattern using -# *.ext= (so without naming a filter). -# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. - -FILTER_SOURCE_PATTERNS = - -# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that -# is part of the input, its contents will be placed on the main page -# (index.html). This can be useful if you have a project on for instance GitHub -# and want to reuse the introduction page also for the doxygen output. - -USE_MDFILE_AS_MAINPAGE = FlatBuffers.md - -#--------------------------------------------------------------------------- -# Configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will be -# generated. Documented entities will be cross-referenced with these sources. -# -# Note: To get rid of all source code in the generated output, make sure that -# also VERBATIM_HEADERS is set to NO. -# The default value is: NO. - -SOURCE_BROWSER = NO - -# Setting the INLINE_SOURCES tag to YES will include the body of functions, -# classes and enums directly into the documentation. -# The default value is: NO. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any -# special comment blocks from generated source code fragments. Normal C, C++ and -# Fortran comments will always remain visible. -# The default value is: YES. - -STRIP_CODE_COMMENTS = NO - -# If the REFERENCED_BY_RELATION tag is set to YES then for each documented -# function all documented functions referencing it will be listed. -# The default value is: NO. - -REFERENCED_BY_RELATION = NO - -# If the REFERENCES_RELATION tag is set to YES then for each documented function -# all documented entities called/used by that function will be listed. -# The default value is: NO. - -REFERENCES_RELATION = NO - -# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set -# to YES, then the hyperlinks from functions in REFERENCES_RELATION and -# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will -# link to the documentation. -# The default value is: YES. - -REFERENCES_LINK_SOURCE = YES - -# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the -# source code will show a tooltip with additional information such as prototype, -# brief description and links to the definition and documentation. Since this -# will make the HTML file larger and loading of large files a bit slower, you -# can opt to disable this feature. -# The default value is: YES. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -SOURCE_TOOLTIPS = YES - -# If the USE_HTAGS tag is set to YES then the references to source code will -# point to the HTML generated by the htags(1) tool instead of doxygen built-in -# source browser. The htags tool is part of GNU's global source tagging system -# (see http://www.gnu.org/software/global/global.html). You will need version -# 4.8.6 or higher. -# -# To use it do the following: -# - Install the latest version of global -# - Enable SOURCE_BROWSER and USE_HTAGS in the config file -# - Make sure the INPUT points to the root of the source tree -# - Run doxygen as normal -# -# Doxygen will invoke htags (and that will in turn invoke gtags), so these -# tools must be available from the command line (i.e. in the search path). -# -# The result: instead of the source browser generated by doxygen, the links to -# source code will now point to the output of htags. -# The default value is: NO. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -USE_HTAGS = NO - -# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a -# verbatim copy of the header file for each class for which an include is -# specified. Set to NO to disable this. -# See also: Section \class. -# The default value is: YES. - -VERBATIM_HEADERS = YES - -#--------------------------------------------------------------------------- -# Configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all -# compounds will be generated. Enable this if the project contains a lot of -# classes, structs, unions or interfaces. -# The default value is: YES. - -ALPHABETICAL_INDEX = YES - -# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in -# which the alphabetical index list will be split. -# Minimum value: 1, maximum value: 20, default value: 5. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -COLS_IN_ALPHA_INDEX = 5 - -# In case all classes in a project start with a common prefix, all classes will -# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag -# can be used to specify a prefix (or a list of prefixes) that should be ignored -# while generating the index headers. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output -# The default value is: YES. - -GENERATE_HTML = YES - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a -# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of -# it. -# The default directory is: html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_OUTPUT = html - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each -# generated HTML page (for example: .htm, .php, .asp). -# The default value is: .html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a user-defined HTML header file for -# each generated HTML page. If the tag is left blank doxygen will generate a -# standard header. -# -# To get valid HTML the header file that includes any scripts and style sheets -# that doxygen needs, which is dependent on the configuration options used (e.g. -# the setting GENERATE_TREEVIEW). It is highly recommended to start with a -# default header using -# doxygen -w html new_header.html new_footer.html new_stylesheet.css -# YourConfigFile -# and then modify the file new_header.html. See also section "Doxygen usage" -# for information on how to generate the default header that doxygen normally -# uses. -# Note: The header is subject to change so you typically have to regenerate the -# default header when upgrading to a newer version of doxygen. For a description -# of the possible markers and block names see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_HEADER = ../header.html - -# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each -# generated HTML page. If the tag is left blank doxygen will generate a standard -# footer. See HTML_HEADER for more information on how to generate a default -# footer and what special commands can be used inside the footer. See also -# section "Doxygen usage" for information on how to generate the default footer -# that doxygen normally uses. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FOOTER = ../footer.html - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style -# sheet that is used by each HTML page. It can be used to fine-tune the look of -# the HTML output. If left blank doxygen will generate a default style sheet. -# See also section "Doxygen usage" for information on how to generate the style -# sheet that doxygen normally uses. -# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as -# it is more robust and this tag (HTML_STYLESHEET) will in the future become -# obsolete. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_STYLESHEET = - -# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional user- -# defined cascading style sheet that is included after the standard style sheets -# created by doxygen. Using this option one can overrule certain style aspects. -# This is preferred over using HTML_STYLESHEET since it does not replace the -# standard style sheet and is therefor more robust against future updates. -# Doxygen will copy the style sheet file to the output directory. For an example -# see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_STYLESHEET = style.css - -# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or -# other source files which should be copied to the HTML output directory. Note -# that these files will be copied to the base HTML output directory. Use the -# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these -# files. In the HTML_STYLESHEET file, use the file name only. Also note that the -# files will be copied as-is; there are no commands or markers available. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_FILES = "../images/fpl_logo_small.png" \ - "../images/ftv2mnode.png" \ - "../images/ftv2pnode.png" - -# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen -# will adjust the colors in the stylesheet and background images according to -# this color. Hue is specified as an angle on a colorwheel, see -# http://en.wikipedia.org/wiki/Hue for more information. For instance the value -# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 -# purple, and 360 is red again. -# Minimum value: 0, maximum value: 359, default value: 220. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_HUE = 220 - -# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors -# in the HTML output. For a value of 0 the output will use grayscales only. A -# value of 255 will produce the most vivid colors. -# Minimum value: 0, maximum value: 255, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_SAT = 100 - -# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the -# luminance component of the colors in the HTML output. Values below 100 -# gradually make the output lighter, whereas values above 100 make the output -# darker. The value divided by 100 is the actual gamma applied, so 80 represents -# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not -# change the gamma. -# Minimum value: 40, maximum value: 240, default value: 80. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_GAMMA = 80 - -# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting this -# to NO can help when comparing the output of multiple runs. -# The default value is: YES. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_TIMESTAMP = YES - -# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML -# documentation will contain sections that can be hidden and shown after the -# page has loaded. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_DYNAMIC_SECTIONS = NO - -# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries -# shown in the various tree structured indices initially; the user can expand -# and collapse entries dynamically later on. Doxygen will expand the tree to -# such a level that at most the specified number of entries are visible (unless -# a fully collapsed tree already exceeds this amount). So setting the number of -# entries 1 will produce a full collapsed tree by default. 0 is a special value -# representing an infinite number of entries and will result in a full expanded -# tree by default. -# Minimum value: 0, maximum value: 9999, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_INDEX_NUM_ENTRIES = 100 - -# If the GENERATE_DOCSET tag is set to YES, additional index files will be -# generated that can be used as input for Apple's Xcode 3 integrated development -# environment (see: http://developer.apple.com/tools/xcode/), introduced with -# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a -# Makefile in the HTML output directory. Running make will produce the docset in -# that directory and running make install will install the docset in -# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at -# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html -# for more information. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_DOCSET = NO - -# This tag determines the name of the docset feed. A documentation feed provides -# an umbrella under which multiple documentation sets from a single provider -# (such as a company or product suite) can be grouped. -# The default value is: Doxygen generated docs. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_FEEDNAME = "Doxygen generated docs" - -# This tag specifies a string that should uniquely identify the documentation -# set bundle. This should be a reverse domain-name style string, e.g. -# com.mycompany.MyDocSet. Doxygen will append .docset to the name. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_BUNDLE_ID = org.doxygen.Project - -# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify -# the documentation publisher. This should be a reverse domain-name style -# string, e.g. com.mycompany.MyDocSet.documentation. -# The default value is: org.doxygen.Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_ID = org.doxygen.Publisher - -# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. -# The default value is: Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_NAME = Publisher - -# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three -# additional HTML index files: index.hhp, index.hhc, and index.hhk. The -# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop -# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on -# Windows. -# -# The HTML Help Workshop contains a compiler that can convert all HTML output -# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML -# files are now used as the Windows 98 help format, and will replace the old -# Windows help format (.hlp) on all Windows platforms in the future. Compressed -# HTML files also contain an index, a table of contents, and you can search for -# words in the documentation. The HTML workshop also contains a viewer for -# compressed HTML files. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_HTMLHELP = NO - -# The CHM_FILE tag can be used to specify the file name of the resulting .chm -# file. You can add a path in front of the file if the result should not be -# written to the html output directory. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_FILE = - -# The HHC_LOCATION tag can be used to specify the location (absolute path -# including file name) of the HTML help compiler ( hhc.exe). If non-empty -# doxygen will try to run the HTML help compiler on the generated index.hhp. -# The file has to be specified with full path. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -HHC_LOCATION = - -# The GENERATE_CHI flag controls if a separate .chi index file is generated ( -# YES) or that it should be included in the master .chm file ( NO). -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -GENERATE_CHI = NO - -# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc) -# and project file content. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_INDEX_ENCODING = - -# The BINARY_TOC flag controls whether a binary table of contents is generated ( -# YES) or a normal table of contents ( NO) in the .chm file. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -BINARY_TOC = NO - -# The TOC_EXPAND flag can be set to YES to add extra items for group members to -# the table of contents of the HTML help documentation and to the tree view. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -TOC_EXPAND = NO - -# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and -# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that -# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help -# (.qch) of the generated HTML documentation. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_QHP = NO - -# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify -# the file name of the resulting .qch file. The path specified is relative to -# the HTML output folder. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QCH_FILE = - -# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help -# Project output. For more information please see Qt Help Project / Namespace -# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_NAMESPACE = org.doxygen.Project - -# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt -# Help Project output. For more information please see Qt Help Project / Virtual -# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- -# folders). -# The default value is: doc. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_VIRTUAL_FOLDER = doc - -# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom -# filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_NAME = - -# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the -# custom filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_ATTRS = - -# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this -# project's filter section matches. Qt Help Project / Filter Attributes (see: -# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_SECT_FILTER_ATTRS = - -# The QHG_LOCATION tag can be used to specify the location of Qt's -# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the -# generated .qhp file. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHG_LOCATION = - -# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be -# generated, together with the HTML files, they form an Eclipse help plugin. To -# install this plugin and make it available under the help contents menu in -# Eclipse, the contents of the directory containing the HTML and XML files needs -# to be copied into the plugins directory of eclipse. The name of the directory -# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. -# After copying Eclipse needs to be restarted before the help appears. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_ECLIPSEHELP = NO - -# A unique identifier for the Eclipse help plugin. When installing the plugin -# the directory name containing the HTML and XML files should also have this -# name. Each documentation set should have its own identifier. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. - -ECLIPSE_DOC_ID = org.doxygen.Project - -# If you want full control over the layout of the generated HTML pages it might -# be necessary to disable the index and replace it with your own. The -# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top -# of each HTML page. A value of NO enables the index and the value YES disables -# it. Since the tabs in the index contain the same information as the navigation -# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -DISABLE_INDEX = NO - -# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. If the tag -# value is set to YES, a side panel will be generated containing a tree-like -# index structure (just like the one that is generated for HTML Help). For this -# to work a browser that supports JavaScript, DHTML, CSS and frames is required -# (i.e. any modern browser). Windows users are probably better off using the -# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can -# further fine-tune the look of the index. As an example, the default style -# sheet generated by doxygen has an example that shows how to put an image at -# the root of the tree instead of the PROJECT_NAME. Since the tree basically has -# the same information as the tab index, you could consider setting -# DISABLE_INDEX to YES when enabling this option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_TREEVIEW = YES - -# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that -# doxygen will group on one line in the generated HTML documentation. -# -# Note that a value of 0 will completely suppress the enum values from appearing -# in the overview section. -# Minimum value: 0, maximum value: 20, default value: 4. -# This tag requires that the tag GENERATE_HTML is set to YES. - -ENUM_VALUES_PER_LINE = 4 - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used -# to set the initial width (in pixels) of the frame in which the tree is shown. -# Minimum value: 0, maximum value: 1500, default value: 250. -# This tag requires that the tag GENERATE_HTML is set to YES. - -TREEVIEW_WIDTH = 250 - -# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to -# external symbols imported via tag files in a separate window. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -EXT_LINKS_IN_WINDOW = NO - -# Use this tag to change the font size of LaTeX formulas included as images in -# the HTML documentation. When you change the font size after a successful -# doxygen run you need to manually remove any form_*.png images from the HTML -# output directory to force them to be regenerated. -# Minimum value: 8, maximum value: 50, default value: 10. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_FONTSIZE = 10 - -# Use the FORMULA_TRANPARENT tag to determine whether or not the images -# generated for formulas are transparent PNGs. Transparent PNGs are not -# supported properly for IE 6.0, but are supported on all modern browsers. -# -# Note that when changing this option you need to delete any form_*.png files in -# the HTML output directory before the changes have effect. -# The default value is: YES. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_TRANSPARENT = YES - -# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see -# http://www.mathjax.org) which uses client side Javascript for the rendering -# instead of using prerendered bitmaps. Use this if you do not have LaTeX -# installed or if you want to formulas look prettier in the HTML output. When -# enabled you may also need to install MathJax separately and configure the path -# to it using the MATHJAX_RELPATH option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -USE_MATHJAX = NO - -# When MathJax is enabled you can set the default output format to be used for -# the MathJax output. See the MathJax site (see: -# http://docs.mathjax.org/en/latest/output.html) for more details. -# Possible values are: HTML-CSS (which is slower, but has the best -# compatibility), NativeMML (i.e. MathML) and SVG. -# The default value is: HTML-CSS. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_FORMAT = HTML-CSS - -# When MathJax is enabled you need to specify the location relative to the HTML -# output directory using the MATHJAX_RELPATH option. The destination directory -# should contain the MathJax.js script. For instance, if the mathjax directory -# is located at the same level as the HTML output directory, then -# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax -# Content Delivery Network so you can quickly see the result without installing -# MathJax. However, it is strongly recommended to install a local copy of -# MathJax from http://www.mathjax.org before deployment. -# The default value is: http://cdn.mathjax.org/mathjax/latest. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest - -# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax -# extension names that should be enabled during MathJax rendering. For example -# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_EXTENSIONS = - -# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces -# of code that will be used on startup of the MathJax code. See the MathJax site -# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an -# example see the documentation. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_CODEFILE = - -# When the SEARCHENGINE tag is enabled doxygen will generate a search box for -# the HTML output. The underlying search engine uses javascript and DHTML and -# should work on any modern browser. Note that when using HTML help -# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) -# there is already a search function so this one should typically be disabled. -# For large projects the javascript based search engine can be slow, then -# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to -# search using the keyboard; to jump to the search box use + S -# (what the is depends on the OS and browser, but it is typically -# , /