Merge remote-tracking branch 'origin/master' into oxidize_cucumber

This commit is contained in:
Dennis 2024-07-12 17:41:30 +02:00
commit 2596a9354f
No known key found for this signature in database
GPG Key ID: 6937EAEA33A3FA5D
757 changed files with 50988 additions and 100292 deletions

1
.gitignore vendored
View File

@ -46,7 +46,6 @@ Thumbs.db
/example/build/
/test/data/monaco.osrm*
/test/data/ch
/test/data/corech
/test/data/mld
/cmake/postinst
/target

View File

@ -24,6 +24,8 @@
- 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)

View File

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

View File

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

View File

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

View File

@ -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)? <input.osrm> \[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)? <input.osrm> \[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)? <input.osrm> \[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

View File

@ -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)? <input.osrm> \[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)? <input.osrm> \[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)? <input.osrm> \[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

View File

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

View File

@ -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)? <input.osm/.osm.bz2/.osm.pbf> \[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)? <input.osm/.osm.bz2/.osm.pbf> \[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)? <input.osm/.osm.bz2/.osm.pbf> \[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

View File

@ -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)? <input.osrm> \[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)? <input.osrm> \[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)? <input.osrm> \[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

View File

@ -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)? <base.osrm> \[<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 "--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)? <base.osrm> \[<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 "--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)? <base.osrm> \[<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 "--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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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<const ::flatbuffers::String *>(VT_CODE);
}
const ::flatbuffers::String *message() const {
return GetPointer<const ::flatbuffers::String *>(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<Error> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = ::flatbuffers::Offset<Error>(end);
return o;
}
};
inline ::flatbuffers::Offset<Error> 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<Error> 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<uint8_t>(VT_ERROR, 0) != 0;
}
const osrm::engine::api::fbresult::Error *code() const {
return GetPointer<const osrm::engine::api::fbresult::Error *>(VT_CODE);
}
const ::flatbuffers::String *data_version() const {
return GetPointer<const ::flatbuffers::String *>(VT_DATA_VERSION);
}
const ::flatbuffers::Vector<::flatbuffers::Offset<osrm::engine::api::fbresult::Waypoint>> *waypoints() const {
return GetPointer<const ::flatbuffers::Vector<::flatbuffers::Offset<osrm::engine::api::fbresult::Waypoint>> *>(VT_WAYPOINTS);
}
const ::flatbuffers::Vector<::flatbuffers::Offset<osrm::engine::api::fbresult::RouteObject>> *routes() const {
return GetPointer<const ::flatbuffers::Vector<::flatbuffers::Offset<osrm::engine::api::fbresult::RouteObject>> *>(VT_ROUTES);
}
const osrm::engine::api::fbresult::TableResult *table() const {
return GetPointer<const osrm::engine::api::fbresult::TableResult *>(VT_TABLE);
}
bool Verify(::flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<uint8_t>(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<uint8_t>(FBResult::VT_ERROR, static_cast<uint8_t>(error), 0);
}
void add_code(::flatbuffers::Offset<osrm::engine::api::fbresult::Error> 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<osrm::engine::api::fbresult::Waypoint>>> waypoints) {
fbb_.AddOffset(FBResult::VT_WAYPOINTS, waypoints);
}
void add_routes(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<osrm::engine::api::fbresult::RouteObject>>> routes) {
fbb_.AddOffset(FBResult::VT_ROUTES, routes);
}
void add_table(::flatbuffers::Offset<osrm::engine::api::fbresult::TableResult> table) {
fbb_.AddOffset(FBResult::VT_TABLE, table);
}
explicit FBResultBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
::flatbuffers::Offset<FBResult> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = ::flatbuffers::Offset<FBResult>(end);
return o;
}
};
inline ::flatbuffers::Offset<FBResult> CreateFBResult(
::flatbuffers::FlatBufferBuilder &_fbb,
bool error = false,
::flatbuffers::Offset<osrm::engine::api::fbresult::Error> code = 0,
::flatbuffers::Offset<::flatbuffers::String> data_version = 0,
::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<osrm::engine::api::fbresult::Waypoint>>> waypoints = 0,
::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<osrm::engine::api::fbresult::RouteObject>>> routes = 0,
::flatbuffers::Offset<osrm::engine::api::fbresult::TableResult> 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<FBResult> CreateFBResultDirect(
::flatbuffers::FlatBufferBuilder &_fbb,
bool error = false,
::flatbuffers::Offset<osrm::engine::api::fbresult::Error> code = 0,
const char *data_version = nullptr,
const std::vector<::flatbuffers::Offset<osrm::engine::api::fbresult::Waypoint>> *waypoints = nullptr,
const std::vector<::flatbuffers::Offset<osrm::engine::api::fbresult::RouteObject>> *routes = nullptr,
::flatbuffers::Offset<osrm::engine::api::fbresult::TableResult> table = 0) {
auto data_version__ = data_version ? _fbb.CreateString(data_version) : 0;
auto waypoints__ = waypoints ? _fbb.CreateVector<::flatbuffers::Offset<osrm::engine::api::fbresult::Waypoint>>(*waypoints) : 0;
auto routes__ = routes ? _fbb.CreateVector<::flatbuffers::Offset<osrm::engine::api::fbresult::RouteObject>>(*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<osrm::engine::api::fbresult::FBResult>(buf);
}
inline const osrm::engine::api::fbresult::FBResult *GetSizePrefixedFBResult(const void *buf) {
return ::flatbuffers::GetSizePrefixedRoot<osrm::engine::api::fbresult::FBResult>(buf);
}
inline bool VerifyFBResultBuffer(
::flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<osrm::engine::api::fbresult::FBResult>(nullptr);
}
inline bool VerifySizePrefixedFBResultBuffer(
::flatbuffers::Verifier &verifier) {
return verifier.VerifySizePrefixedBuffer<osrm::engine::api::fbresult::FBResult>(nullptr);
}
inline void FinishFBResultBuffer(
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<osrm::engine::api::fbresult::FBResult> root) {
fbb.Finish(root);
}
inline void FinishSizePrefixedFBResultBuffer(
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<osrm::engine::api::fbresult::FBResult> root) {
fbb.FinishSizePrefixed(root);
}
} // namespace fbresult
} // namespace api
} // namespace engine
} // namespace osrm
#endif // FLATBUFFERS_GENERATED_FBRESULT_OSRM_ENGINE_API_FBRESULT_H_

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
include "waypoint.fbs";
namespace osrm.engine.api.fbresult;
table Table {
table TableResult {
durations: [float];
rows: ushort;
cols: ushort;

View File

@ -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<float> *durations() const {
return GetPointer<const ::flatbuffers::Vector<float> *>(VT_DURATIONS);
}
uint16_t rows() const {
return GetField<uint16_t>(VT_ROWS, 0);
}
uint16_t cols() const {
return GetField<uint16_t>(VT_COLS, 0);
}
const ::flatbuffers::Vector<float> *distances() const {
return GetPointer<const ::flatbuffers::Vector<float> *>(VT_DISTANCES);
}
const ::flatbuffers::Vector<::flatbuffers::Offset<osrm::engine::api::fbresult::Waypoint>> *destinations() const {
return GetPointer<const ::flatbuffers::Vector<::flatbuffers::Offset<osrm::engine::api::fbresult::Waypoint>> *>(VT_DESTINATIONS);
}
const ::flatbuffers::Vector<uint32_t> *fallback_speed_cells() const {
return GetPointer<const ::flatbuffers::Vector<uint32_t> *>(VT_FALLBACK_SPEED_CELLS);
}
bool Verify(::flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_DURATIONS) &&
verifier.VerifyVector(durations()) &&
VerifyField<uint16_t>(verifier, VT_ROWS, 2) &&
VerifyField<uint16_t>(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<float>> durations) {
fbb_.AddOffset(TableResult::VT_DURATIONS, durations);
}
void add_rows(uint16_t rows) {
fbb_.AddElement<uint16_t>(TableResult::VT_ROWS, rows, 0);
}
void add_cols(uint16_t cols) {
fbb_.AddElement<uint16_t>(TableResult::VT_COLS, cols, 0);
}
void add_distances(::flatbuffers::Offset<::flatbuffers::Vector<float>> distances) {
fbb_.AddOffset(TableResult::VT_DISTANCES, distances);
}
void add_destinations(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<osrm::engine::api::fbresult::Waypoint>>> destinations) {
fbb_.AddOffset(TableResult::VT_DESTINATIONS, destinations);
}
void add_fallback_speed_cells(::flatbuffers::Offset<::flatbuffers::Vector<uint32_t>> 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<TableResult> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = ::flatbuffers::Offset<TableResult>(end);
return o;
}
};
inline ::flatbuffers::Offset<TableResult> CreateTableResult(
::flatbuffers::FlatBufferBuilder &_fbb,
::flatbuffers::Offset<::flatbuffers::Vector<float>> durations = 0,
uint16_t rows = 0,
uint16_t cols = 0,
::flatbuffers::Offset<::flatbuffers::Vector<float>> distances = 0,
::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<osrm::engine::api::fbresult::Waypoint>>> destinations = 0,
::flatbuffers::Offset<::flatbuffers::Vector<uint32_t>> 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<TableResult> CreateTableResultDirect(
::flatbuffers::FlatBufferBuilder &_fbb,
const std::vector<float> *durations = nullptr,
uint16_t rows = 0,
uint16_t cols = 0,
const std::vector<float> *distances = nullptr,
const std::vector<::flatbuffers::Offset<osrm::engine::api::fbresult::Waypoint>> *destinations = nullptr,
const std::vector<uint32_t> *fallback_speed_cells = nullptr) {
auto durations__ = durations ? _fbb.CreateVector<float>(*durations) : 0;
auto distances__ = distances ? _fbb.CreateVector<float>(*distances) : 0;
auto destinations__ = destinations ? _fbb.CreateVector<::flatbuffers::Offset<osrm::engine::api::fbresult::Waypoint>>(*destinations) : 0;
auto fallback_speed_cells__ = fallback_speed_cells ? _fbb.CreateVector<uint32_t>(*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_

View File

@ -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<const ::flatbuffers::String *>(VT_HINT);
}
float distance() const {
return GetField<float>(VT_DISTANCE, 0.0f);
}
const ::flatbuffers::String *name() const {
return GetPointer<const ::flatbuffers::String *>(VT_NAME);
}
const osrm::engine::api::fbresult::Position *location() const {
return GetStruct<const osrm::engine::api::fbresult::Position *>(VT_LOCATION);
}
const osrm::engine::api::fbresult::Uint64Pair *nodes() const {
return GetStruct<const osrm::engine::api::fbresult::Uint64Pair *>(VT_NODES);
}
uint32_t matchings_index() const {
return GetField<uint32_t>(VT_MATCHINGS_INDEX, 0);
}
uint32_t waypoint_index() const {
return GetField<uint32_t>(VT_WAYPOINT_INDEX, 0);
}
uint32_t alternatives_count() const {
return GetField<uint32_t>(VT_ALTERNATIVES_COUNT, 0);
}
uint32_t trips_index() const {
return GetField<uint32_t>(VT_TRIPS_INDEX, 0);
}
bool Verify(::flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_HINT) &&
verifier.VerifyString(hint()) &&
VerifyField<float>(verifier, VT_DISTANCE, 4) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyField<osrm::engine::api::fbresult::Position>(verifier, VT_LOCATION, 4) &&
VerifyField<osrm::engine::api::fbresult::Uint64Pair>(verifier, VT_NODES, 8) &&
VerifyField<uint32_t>(verifier, VT_MATCHINGS_INDEX, 4) &&
VerifyField<uint32_t>(verifier, VT_WAYPOINT_INDEX, 4) &&
VerifyField<uint32_t>(verifier, VT_ALTERNATIVES_COUNT, 4) &&
VerifyField<uint32_t>(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<float>(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<uint32_t>(Waypoint::VT_MATCHINGS_INDEX, matchings_index, 0);
}
void add_waypoint_index(uint32_t waypoint_index) {
fbb_.AddElement<uint32_t>(Waypoint::VT_WAYPOINT_INDEX, waypoint_index, 0);
}
void add_alternatives_count(uint32_t alternatives_count) {
fbb_.AddElement<uint32_t>(Waypoint::VT_ALTERNATIVES_COUNT, alternatives_count, 0);
}
void add_trips_index(uint32_t trips_index) {
fbb_.AddElement<uint32_t>(Waypoint::VT_TRIPS_INDEX, trips_index, 0);
}
explicit WaypointBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
::flatbuffers::Offset<Waypoint> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = ::flatbuffers::Offset<Waypoint>(end);
return o;
}
};
inline ::flatbuffers::Offset<Waypoint> 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<Waypoint> 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_

File diff suppressed because it is too large Load Diff

View File

@ -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);

View File

@ -5,8 +5,6 @@
#include "util/query_heap.hpp"
#include "util/typedefs.hpp"
#include <boost/thread/tss.hpp>
namespace osrm::engine
{
@ -45,19 +43,19 @@ template <> struct SearchEngineData<routing_algorithms::ch::Algorithm>
ManyToManyHeapData,
util::UnorderedMapStorage<NodeID, int>>;
using SearchEngineHeapPtr = boost::thread_specific_ptr<QueryHeap>;
using SearchEngineHeapPtr = std::unique_ptr<QueryHeap>;
using ManyToManyHeapPtr = boost::thread_specific_ptr<ManyToManyQueryHeap>;
using ManyToManyHeapPtr = std::unique_ptr<ManyToManyQueryHeap>;
static SearchEngineHeapPtr forward_heap_1;
static SearchEngineHeapPtr reverse_heap_1;
static SearchEngineHeapPtr forward_heap_2;
static SearchEngineHeapPtr reverse_heap_2;
static SearchEngineHeapPtr forward_heap_3;
static SearchEngineHeapPtr reverse_heap_3;
static ManyToManyHeapPtr many_to_many_heap;
static SearchEngineHeapPtr map_matching_forward_heap_1;
static SearchEngineHeapPtr map_matching_reverse_heap_1;
static thread_local SearchEngineHeapPtr forward_heap_1;
static thread_local SearchEngineHeapPtr reverse_heap_1;
static thread_local SearchEngineHeapPtr forward_heap_2;
static thread_local SearchEngineHeapPtr reverse_heap_2;
static thread_local SearchEngineHeapPtr forward_heap_3;
static thread_local SearchEngineHeapPtr reverse_heap_3;
static thread_local ManyToManyHeapPtr many_to_many_heap;
static thread_local SearchEngineHeapPtr map_matching_forward_heap_1;
static thread_local SearchEngineHeapPtr map_matching_reverse_heap_1;
void InitializeOrClearMapMatchingThreadLocalStorage(unsigned number_of_nodes);
@ -127,16 +125,16 @@ template <> struct SearchEngineData<routing_algorithms::mld::Algorithm>
MapMatchingMultiLayerDijkstraHeapData,
util::TwoLevelStorage<NodeID, int>>;
using SearchEngineHeapPtr = boost::thread_specific_ptr<QueryHeap>;
using ManyToManyHeapPtr = boost::thread_specific_ptr<ManyToManyQueryHeap>;
using MapMatchingHeapPtr = boost::thread_specific_ptr<MapMatchingQueryHeap>;
using SearchEngineHeapPtr = std::unique_ptr<QueryHeap>;
using ManyToManyHeapPtr = std::unique_ptr<ManyToManyQueryHeap>;
using MapMatchingHeapPtr = std::unique_ptr<MapMatchingQueryHeap>;
static SearchEngineHeapPtr forward_heap_1;
static SearchEngineHeapPtr reverse_heap_1;
static MapMatchingHeapPtr map_matching_forward_heap_1;
static MapMatchingHeapPtr map_matching_reverse_heap_1;
static thread_local SearchEngineHeapPtr forward_heap_1;
static thread_local SearchEngineHeapPtr reverse_heap_1;
static thread_local MapMatchingHeapPtr map_matching_forward_heap_1;
static thread_local MapMatchingHeapPtr map_matching_reverse_heap_1;
static ManyToManyHeapPtr many_to_many_heap;
static thread_local ManyToManyHeapPtr many_to_many_heap;
void InitializeOrClearFirstThreadLocalStorage(unsigned number_of_nodes,
unsigned number_of_boundary_nodes);
@ -148,4 +146,4 @@ template <> struct SearchEngineData<routing_algorithms::mld::Algorithm>
};
} // namespace osrm::engine
#endif // SEARCH_ENGINE_DATA_HPP
#endif // SEARCH_ENGINE_DATA_HPP

View File

@ -15,48 +15,6 @@
namespace osrm::util
{
template <typename NodeID, typename Key> 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<Key>::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<GenerationCounter> generations;
std::vector<Key> positions;
};
template <typename NodeID, typename Key> class ArrayStorage
{
public:
@ -72,29 +30,6 @@ template <typename NodeID, typename Key> class ArrayStorage
std::vector<Key> positions;
};
template <typename NodeID, typename Key> 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<Key>::max();
}
private:
std::map<NodeID, Key> nodes;
};
template <typename NodeID, typename Key> class UnorderedMapStorage
{
public:

View File

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

View File

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

View File

@ -5,16 +5,18 @@ namespace osrm::engine
// CH heaps
using CH = routing_algorithms::ch::Algorithm;
SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::forward_heap_1;
SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::reverse_heap_1;
SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::forward_heap_2;
SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::reverse_heap_2;
SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::forward_heap_3;
SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::reverse_heap_3;
SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::map_matching_forward_heap_1;
SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::map_matching_reverse_heap_1;
thread_local SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::forward_heap_1;
thread_local SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::reverse_heap_1;
thread_local SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::forward_heap_2;
thread_local SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::reverse_heap_2;
thread_local SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::forward_heap_3;
thread_local SearchEngineData<CH>::SearchEngineHeapPtr SearchEngineData<CH>::reverse_heap_3;
thread_local SearchEngineData<CH>::SearchEngineHeapPtr
SearchEngineData<CH>::map_matching_forward_heap_1;
thread_local SearchEngineData<CH>::SearchEngineHeapPtr
SearchEngineData<CH>::map_matching_reverse_heap_1;
SearchEngineData<CH>::ManyToManyHeapPtr SearchEngineData<CH>::many_to_many_heap;
thread_local SearchEngineData<CH>::ManyToManyHeapPtr SearchEngineData<CH>::many_to_many_heap;
void SearchEngineData<CH>::InitializeOrClearMapMatchingThreadLocalStorage(unsigned number_of_nodes)
{
@ -114,11 +116,13 @@ void SearchEngineData<CH>::InitializeOrClearManyToManyThreadLocalStorage(unsigne
// MLD
using MLD = routing_algorithms::mld::Algorithm;
SearchEngineData<MLD>::SearchEngineHeapPtr SearchEngineData<MLD>::forward_heap_1;
SearchEngineData<MLD>::SearchEngineHeapPtr SearchEngineData<MLD>::reverse_heap_1;
SearchEngineData<MLD>::MapMatchingHeapPtr SearchEngineData<MLD>::map_matching_forward_heap_1;
SearchEngineData<MLD>::MapMatchingHeapPtr SearchEngineData<MLD>::map_matching_reverse_heap_1;
SearchEngineData<MLD>::ManyToManyHeapPtr SearchEngineData<MLD>::many_to_many_heap;
thread_local SearchEngineData<MLD>::SearchEngineHeapPtr SearchEngineData<MLD>::forward_heap_1;
thread_local SearchEngineData<MLD>::SearchEngineHeapPtr SearchEngineData<MLD>::reverse_heap_1;
thread_local SearchEngineData<MLD>::MapMatchingHeapPtr
SearchEngineData<MLD>::map_matching_forward_heap_1;
thread_local SearchEngineData<MLD>::MapMatchingHeapPtr
SearchEngineData<MLD>::map_matching_reverse_heap_1;
thread_local SearchEngineData<MLD>::ManyToManyHeapPtr SearchEngineData<MLD>::many_to_many_heap;
void SearchEngineData<MLD>::InitializeOrClearMapMatchingThreadLocalStorage(
unsigned number_of_nodes, unsigned number_of_boundary_nodes)
@ -178,4 +182,4 @@ void SearchEngineData<MLD>::InitializeOrClearManyToManyThreadLocalStorage(
many_to_many_heap.reset(new ManyToManyQueryHeap(number_of_nodes, number_of_boundary_nodes));
}
}
} // namespace osrm::engine
} // namespace osrm::engine

View File

@ -46,25 +46,16 @@ return_code parseArguments(int argc,
boost::program_options::value<unsigned int>(&contractor_config.requested_num_threads)
->default_value(std::thread::hardware_concurrency()),
"Number of threads to use")(
"core,k",
boost::program_options::value<double>(&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<std::vector<std::string>>(
&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<std::vector<std::string>>(
&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<std::vector<std::string>>(
&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<double>(
&contractor_config.updater_config.log_edge_updates_factor)

View File

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

View File

@ -1,18 +1,38 @@
---
buildifier: latest
bazel: 6.4.0
platforms:
ubuntu1604:
build_targets:
- "..."
test_targets:
- "..."
ubuntu1804:
environment:
CC: clang
SWIFT_VERSION: "5.5.3"
SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION"
PATH: "$PATH:$SWIFT_HOME/usr/bin"
shell_commands:
- "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME"
- "mkdir $SWIFT_HOME"
- "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu1804/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu18.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME"
build_targets:
- "..."
- "//..."
test_targets:
- "..."
- "//..."
ubuntu2004:
environment:
CC: clang
SWIFT_VERSION: "5.5.3"
SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION"
PATH: "$PATH:$SWIFT_HOME/usr/bin"
shell_commands:
- "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME"
- "mkdir $SWIFT_HOME"
- "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2004/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu20.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME"
build_targets:
- "//..."
test_targets:
- "//..."
macos:
xcode_version: "14.2"
build_targets:
- "..."
- "//..."
test_targets:
- "..."
- "//..."

1
third_party/flatbuffers/.bazelignore vendored Normal file
View File

@ -0,0 +1 @@
node_modules

4
third_party/flatbuffers/.bazelrc vendored Normal file
View File

@ -0,0 +1,4 @@
# We cannot use "common" here because the "version" command doesn't support
# --deleted_packages. We need to specify it for both build and query instead.
build --deleted_packages=tests/ts/bazel_repository_test_dir
query --deleted_packages=tests/ts/bazel_repository_test_dir

347
third_party/flatbuffers/.clang-tidy vendored Normal file
View File

@ -0,0 +1,347 @@
---
FormatStyle: "file"
WarningsAsErrors: "*"
HeaderFilterRegex: ".*"
Checks: "google-build-explicit-make-pair,
google-build-namespaces,
google-build-using-namespace,
google-default-arguments,
google-explicit-constructor,
google-global-names-in-headers,
google-objc-avoid-nsobject-new,
google-objc-avoid-throwing-exception,
google-objc-function-naming,
google-objc-global-variable-declaration,
google-readability-avoid-underscore-in-googletest-name,
google-readability-braces-around-statements,
google-readability-casting,
google-readability-function-size,
google-readability-namespace-comments,
google-runtime-int,
google-runtime-operator,
google-upgrade-googletest-case,
clang-analyzer-apiModeling.StdCLibraryFunctions,
clang-analyzer-apiModeling.TrustNonnull,
clang-analyzer-apiModeling.google.GTest,
clang-analyzer-apiModeling.llvm.CastValue,
clang-analyzer-apiModeling.llvm.ReturnValue,
clang-analyzer-core.CallAndMessage,
clang-analyzer-core.CallAndMessageModeling,
clang-analyzer-core.DivideZero,
clang-analyzer-core.DynamicTypePropagation,
clang-analyzer-core.NonNullParamChecker,
clang-analyzer-core.NonnilStringConstants,
clang-analyzer-core.NullDereference,
clang-analyzer-core.StackAddrEscapeBase,
clang-analyzer-core.StackAddressEscape,
clang-analyzer-core.UndefinedBinaryOperatorResult,
clang-analyzer-core.VLASize,
clang-analyzer-core.builtin.BuiltinFunctions,
clang-analyzer-core.builtin.NoReturnFunctions,
clang-analyzer-core.uninitialized.ArraySubscript,
clang-analyzer-core.uninitialized.Assign,
clang-analyzer-core.uninitialized.Branch,
clang-analyzer-core.uninitialized.CapturedBlockVariable,
clang-analyzer-core.uninitialized.UndefReturn,
clang-analyzer-cplusplus.InnerPointer,
clang-analyzer-cplusplus.Move,
clang-analyzer-cplusplus.NewDelete,
clang-analyzer-cplusplus.NewDeleteLeaks,
clang-analyzer-cplusplus.PlacementNew,
clang-analyzer-cplusplus.PureVirtualCall,
clang-analyzer-cplusplus.SelfAssignment,
clang-analyzer-cplusplus.SmartPtrModeling,
clang-analyzer-cplusplus.StringChecker,
clang-analyzer-cplusplus.VirtualCallModeling,
clang-analyzer-deadcode.DeadStores,
clang-analyzer-fuchsia.HandleChecker,
clang-analyzer-nullability.NullPassedToNonnull,
clang-analyzer-nullability.NullReturnedFromNonnull,
clang-analyzer-nullability.NullabilityBase,
clang-analyzer-nullability.NullableDereferenced,
clang-analyzer-nullability.NullablePassedToNonnull,
clang-analyzer-nullability.NullableReturnedFromNonnull,
clang-analyzer-optin.cplusplus.UninitializedObject,
clang-analyzer-optin.cplusplus.VirtualCall,
clang-analyzer-optin.mpi.MPI-Checker,
clang-analyzer-optin.osx.OSObjectCStyleCast,
clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker,
clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker,
clang-analyzer-optin.performance.GCDAntipattern,
clang-analyzer-optin.performance.Padding,
clang-analyzer-optin.portability.UnixAPI,
clang-analyzer-osx.API,
clang-analyzer-osx.MIG,
clang-analyzer-osx.NSOrCFErrorDerefChecker,
clang-analyzer-osx.NumberObjectConversion,
clang-analyzer-osx.OSObjectRetainCount,
clang-analyzer-osx.ObjCProperty,
clang-analyzer-osx.SecKeychainAPI,
clang-analyzer-osx.cocoa.AtSync,
clang-analyzer-osx.cocoa.AutoreleaseWrite,
clang-analyzer-osx.cocoa.ClassRelease,
clang-analyzer-osx.cocoa.Dealloc,
clang-analyzer-osx.cocoa.IncompatibleMethodTypes,
clang-analyzer-osx.cocoa.Loops,
clang-analyzer-osx.cocoa.MissingSuperCall,
clang-analyzer-osx.cocoa.NSAutoreleasePool,
clang-analyzer-osx.cocoa.NSError,
clang-analyzer-osx.cocoa.NilArg,
clang-analyzer-osx.cocoa.NonNilReturnValue,
clang-analyzer-osx.cocoa.ObjCGenerics,
clang-analyzer-osx.cocoa.RetainCount,
clang-analyzer-osx.cocoa.RetainCountBase,
clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak,
clang-analyzer-osx.cocoa.SelfInit,
clang-analyzer-osx.cocoa.SuperDealloc,
clang-analyzer-osx.cocoa.UnusedIvars,
clang-analyzer-osx.cocoa.VariadicMethodTypes,
clang-analyzer-osx.coreFoundation.CFError,
clang-analyzer-osx.coreFoundation.CFNumber,
clang-analyzer-osx.coreFoundation.CFRetainRelease,
clang-analyzer-osx.coreFoundation.containers.OutOfBounds,
clang-analyzer-osx.coreFoundation.containers.PointerSizedValues,
clang-analyzer-security.FloatLoopCounter,
clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling,
clang-analyzer-security.insecureAPI.SecuritySyntaxChecker,
clang-analyzer-security.insecureAPI.UncheckedReturn,
clang-analyzer-security.insecureAPI.bcmp,
clang-analyzer-security.insecureAPI.bcopy,
clang-analyzer-security.insecureAPI.bzero,
clang-analyzer-security.insecureAPI.decodeValueOfObjCType,
clang-analyzer-security.insecureAPI.getpw,
clang-analyzer-security.insecureAPI.gets,
clang-analyzer-security.insecureAPI.mkstemp,
clang-analyzer-security.insecureAPI.mktemp,
clang-analyzer-security.insecureAPI.rand,
clang-analyzer-security.insecureAPI.strcpy,
clang-analyzer-security.insecureAPI.vfork,
clang-analyzer-unix.API,
clang-analyzer-unix.DynamicMemoryModeling,
clang-analyzer-unix.Malloc,
clang-analyzer-unix.MallocSizeof,
clang-analyzer-unix.MismatchedDeallocator,
clang-analyzer-unix.Vfork,
clang-analyzer-unix.cstring.BadSizeArg,
clang-analyzer-unix.cstring.CStringModeling,
clang-analyzer-unix.cstring.NullArg,
clang-analyzer-valist.CopyToSelf,
clang-analyzer-valist.Uninitialized,
clang-analyzer-valist.Unterminated,
clang-analyzer-valist.ValistBase,
clang-analyzer-webkit.NoUncountedMemberChecker,
clang-analyzer-webkit.RefCntblBaseVirtualDtor,
clang-analyzer-webkit.UncountedLambdaCapturesChecker,
################################################ Optional checks ################################################
#google-readability-todo,
#bugprone-argument-comment,
#bugprone-assert-side-effect,
#bugprone-bad-signal-to-kill-thread,
#bugprone-bool-pointer-implicit-conversion,
#bugprone-branch-clone,
#bugprone-copy-constructor-init,
#bugprone-dangling-handle,
#bugprone-dynamic-static-initializers,
#bugprone-easily-swappable-parameters,
#bugprone-exception-escape,
#bugprone-fold-init-type,
#bugprone-forward-declaration-namespace,
#bugprone-forwarding-reference-overload,
#bugprone-implicit-widening-of-multiplication-result,
#bugprone-inaccurate-erase,
#bugprone-incorrect-roundings,
#bugprone-infinite-loop,
#bugprone-integer-division,
#bugprone-lambda-function-name,
#bugprone-macro-parentheses,
#bugprone-macro-repeated-side-effects,
#bugprone-misplaced-operator-in-strlen-in-alloc,
#bugprone-misplaced-pointer-arithmetic-in-alloc,
#bugprone-misplaced-widening-cast,
#bugprone-move-forwarding-reference,
#bugprone-multiple-statement-macro,
#bugprone-narrowing-conversions,
#bugprone-no-escape,
#bugprone-not-null-terminated-result,
#bugprone-parent-virtual-call,
#bugprone-posix-return,
#bugprone-redundant-branch-condition,
#bugprone-reserved-identifier,
#bugprone-signal-handler,
#bugprone-signed-char-misuse,
#bugprone-sizeof-container,
#bugprone-sizeof-expression,
#bugprone-spuriously-wake-up-functions,
#bugprone-string-constructor,
#bugprone-string-integer-assignment,
#bugprone-string-literal-with-embedded-nul,
#bugprone-stringview-nullptr,
#bugprone-suspicious-enum-usage,
#bugprone-suspicious-include,
#bugprone-suspicious-memory-comparison,
#bugprone-suspicious-memset-usage,
#bugprone-suspicious-missing-comma,
#bugprone-suspicious-semicolon,
#bugprone-suspicious-string-compare,
#bugprone-swapped-arguments,
#bugprone-terminating-continue,
#bugprone-throw-keyword-missing,
#bugprone-too-small-loop-variable,
#bugprone-undefined-memory-manipulation,
#bugprone-undelegated-constructor,
#bugprone-unhandled-exception-at-new,
#bugprone-unhandled-self-assignment,
#bugprone-unused-raii,
#bugprone-unused-return-value,
#bugprone-use-after-move,
#bugprone-virtual-near-miss,
#cppcoreguidelines-avoid-c-arrays,
#cppcoreguidelines-avoid-goto,
#cppcoreguidelines-avoid-magic-numbers,
#cppcoreguidelines-avoid-non-const-global-variables,
#cppcoreguidelines-c-copy-assignment-signature,
#cppcoreguidelines-explicit-virtual-functions,
#cppcoreguidelines-init-variables,
#cppcoreguidelines-interfaces-global-init,
#cppcoreguidelines-macro-usage,
#cppcoreguidelines-narrowing-conversions,
#cppcoreguidelines-no-malloc,
#cppcoreguidelines-non-private-member-variables-in-classes,
#cppcoreguidelines-owning-memory,
#cppcoreguidelines-prefer-member-initializer,
#cppcoreguidelines-pro-bounds-array-to-pointer-decay,
#cppcoreguidelines-pro-bounds-constant-array-index,
#cppcoreguidelines-pro-bounds-pointer-arithmetic,
#cppcoreguidelines-pro-type-const-cast,
#cppcoreguidelines-pro-type-cstyle-cast,
#cppcoreguidelines-pro-type-member-init,
#cppcoreguidelines-pro-type-reinterpret-cast,
#cppcoreguidelines-pro-type-static-cast-downcast,
#cppcoreguidelines-pro-type-union-access,
#cppcoreguidelines-pro-type-vararg,
#cppcoreguidelines-slicing,
#cppcoreguidelines-special-member-functions,
#cppcoreguidelines-virtual-class-destructor,
#hicpp-avoid-c-arrays,
#hicpp-avoid-goto,
#hicpp-braces-around-statements,
#hicpp-deprecated-headers,
#hicpp-exception-baseclass,
#hicpp-explicit-conversions,
#hicpp-function-size,
#hicpp-invalid-access-moved,
#hicpp-member-init,
#hicpp-move-const-arg,
#hicpp-multiway-paths-covered,
#hicpp-named-parameter,
#hicpp-new-delete-operators,
#hicpp-no-array-decay,
#hicpp-no-assembler,
#hicpp-no-malloc,
#hicpp-noexcept-move,
#hicpp-signed-bitwise,
#hicpp-special-member-functions,
#hicpp-static-assert,
#hicpp-undelegated-constructor,
#hicpp-uppercase-literal-suffix,
#hicpp-use-auto,
#hicpp-use-emplace,
#hicpp-use-equals-default,
#hicpp-use-equals-delete,
#hicpp-use-noexcept,
#hicpp-use-nullptr,
#hicpp-use-override,
#hicpp-vararg,
#modernize-avoid-bind,
#modernize-avoid-c-arrays,
#modernize-concat-nested-namespaces,
#modernize-deprecated-headers,
#modernize-deprecated-ios-base-aliases,
#modernize-loop-convert,
#modernize-make-shared,
#modernize-make-unique,
#modernize-pass-by-value,
#modernize-raw-string-literal,
#modernize-redundant-void-arg,
#modernize-replace-auto-ptr,
#modernize-replace-disallow-copy-and-assign-macro,
#modernize-replace-random-shuffle,
#modernize-return-braced-init-list,
#modernize-shrink-to-fit,
#modernize-unary-static-assert,
#modernize-use-auto,
#modernize-use-bool-literals,
#modernize-use-default-member-init,
#modernize-use-emplace,
#modernize-use-equals-default,
#modernize-use-equals-delete,
#modernize-use-nodiscard,
#modernize-use-noexcept,
#modernize-use-nullptr,
#modernize-use-override,
#modernize-use-trailing-return-type,
#modernize-use-transparent-functors,
#modernize-use-uncaught-exceptions,
#modernize-use-using,
#performance-faster-string-find,
#performance-for-range-copy,
#performance-implicit-conversion-in-loop,
#performance-inefficient-algorithm,
#performance-inefficient-string-concatenation,
#performance-inefficient-vector-operation,
#performance-move-const-arg,
#performance-move-constructor-init,
#performance-no-automatic-move,
#performance-no-int-to-ptr,
#performance-noexcept-move-constructor,
#performance-trivially-destructible,
#performance-type-promotion-in-math-fn,
#performance-unnecessary-copy-initialization,
#performance-unnecessary-value-param,
#portability-restrict-system-includes,
#portability-simd-intrinsics,
#readability-avoid-const-params-in-decls,
#readability-braces-around-statements,
#readability-const-return-type,
#readability-container-contains,
#readability-container-data-pointer,
#readability-container-size-empty,
#readability-convert-member-functions-to-static,
#readability-delete-null-pointer,
#readability-duplicate-include,
#readability-else-after-return,
#readability-function-cognitive-complexity,
#readability-function-size,
#readability-identifier-length,
#readability-identifier-naming,
#readability-implicit-bool-conversion,
#readability-inconsistent-declaration-parameter-name,
#readability-isolate-declaration,
#readability-magic-numbers,
#readability-make-member-function-const,
#readability-misleading-indentation,
#readability-misplaced-array-index,
#readability-named-parameter,
#readability-non-const-parameter,
#readability-qualified-auto,
#readability-redundant-access-specifiers,
#readability-redundant-control-flow,
#readability-redundant-declaration,
#readability-redundant-function-ptr-dereference,
#readability-redundant-member-init,
#readability-redundant-preprocessor,
#readability-redundant-smartptr-get,
#readability-redundant-string-cstr,
#readability-redundant-string-init,
#readability-simplify-boolean-expr,
#readability-simplify-subscript-expr,
#readability-static-accessed-through-instance,
#readability-static-definition-in-anonymous-namespace,
#readability-string-compare,
#readability-suspicious-call-argument,
#readability-uniqueptr-delete-release,
#readability-uppercase-literal-suffix,
#readability-use-anyofallof
"

View File

@ -5,3 +5,4 @@ root = true
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

13
third_party/flatbuffers/.eslintrc.js vendored Normal file
View File

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

View File

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

View File

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

View File

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

View File

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

1
third_party/flatbuffers/.npmrc vendored Normal file
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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" ],
)

139
third_party/flatbuffers/BUILD.bazel vendored Normal file
View File

@ -0,0 +1,139 @@
load("@aspect_rules_js//npm:defs.bzl", "npm_link_package")
load("@npm//:defs.bzl", "npm_link_all_packages")
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
licenses(["notice"])
package(
default_visibility = ["//visibility:public"],
)
npm_link_all_packages(name = "node_modules")
npm_link_package(
name = "node_modules/flatbuffers",
src = "//ts:flatbuffers",
)
exports_files([
"LICENSE",
"tsconfig.json",
])
config_setting(
name = "platform_freebsd",
constraint_values = [
"@platforms//os:freebsd",
],
)
config_setting(
name = "platform_openbsd",
constraint_values = [
"@platforms//os:openbsd",
],
)
filegroup(
name = "distribution",
srcs = [
"BUILD.bazel",
"WORKSPACE",
"build_defs.bzl",
"typescript.bzl",
"//grpc/src/compiler:distribution",
"//reflection:distribution",
"//src:distribution",
"//ts:distribution",
] + glob([
"include/flatbuffers/*.h",
]),
visibility = ["//visibility:public"],
)
# Public flatc library to compile flatbuffer files at runtime.
cc_library(
name = "flatbuffers",
hdrs = ["//:public_headers"],
linkstatic = 1,
strip_include_prefix = "/include",
deps = ["//src:flatbuffers"],
)
# Public C++ headers for the Flatbuffers library.
filegroup(
name = "public_headers",
srcs = [
"include/flatbuffers/allocator.h",
"include/flatbuffers/array.h",
"include/flatbuffers/base.h",
"include/flatbuffers/buffer.h",
"include/flatbuffers/buffer_ref.h",
"include/flatbuffers/code_generator.h",
"include/flatbuffers/code_generators.h",
"include/flatbuffers/default_allocator.h",
"include/flatbuffers/detached_buffer.h",
"include/flatbuffers/file_manager.h",
"include/flatbuffers/flatbuffer_builder.h",
"include/flatbuffers/flatbuffers.h",
"include/flatbuffers/flex_flat_util.h",
"include/flatbuffers/flexbuffers.h",
"include/flatbuffers/grpc.h",
"include/flatbuffers/hash.h",
"include/flatbuffers/idl.h",
"include/flatbuffers/minireflect.h",
"include/flatbuffers/reflection.h",
"include/flatbuffers/reflection_generated.h",
"include/flatbuffers/registry.h",
"include/flatbuffers/stl_emulation.h",
"include/flatbuffers/string.h",
"include/flatbuffers/struct.h",
"include/flatbuffers/table.h",
"include/flatbuffers/util.h",
"include/flatbuffers/vector.h",
"include/flatbuffers/vector_downward.h",
"include/flatbuffers/verifier.h",
],
)
# Public flatc compiler library.
cc_library(
name = "flatc_library",
linkstatic = 1,
deps = [
"//src:flatc_library",
],
)
# Public flatc compiler.
cc_binary(
name = "flatc",
data = ["//reflection:reflection_fbs_schema"],
deps = [
"//src:flatc",
],
)
filegroup(
name = "flatc_headers",
srcs = [
"include/flatbuffers/flatc.h",
],
visibility = ["//:__subpackages__"],
)
# Library used by flatbuffer_cc_library rules.
cc_library(
name = "runtime_cc",
hdrs = [
"include/flatbuffers/base.h",
"include/flatbuffers/flatbuffers.h",
"include/flatbuffers/flexbuffers.h",
"include/flatbuffers/stl_emulation.h",
"include/flatbuffers/util.h",
"include/flatbuffers/vector.h",
"include/flatbuffers/verifier.h",
],
linkstatic = 1,
strip_include_prefix = "/include",
)

168
third_party/flatbuffers/CHANGELOG.md vendored Normal file
View File

@ -0,0 +1,168 @@
# Flatbuffers Change Log
All major or breaking changes will be documented in this file, as well as any
new features that should be highlighted. Minor fixes or improvements are not
necessarily listed.
## [24.3.25] (March 25 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.25)
* Fixed license metadata parsing (#8253)
* [C++] Allow string_view in `LookUpByKey` in addition to null-terminated c-style strings (#8203)
## [24.3.7] (March 7 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.7)
* Just to fix some of the CI build issues from the 24.3.6 release.
## [24.3.6] (March 6 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.6)
* Fix typescript object API to allow 0 values for null-default scalars (#7864)
## [23.5.26 (May 26 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.26)
* Mostly bug fixing for 64-bit support
* Adds support for specifying underling type of unions in C++ and TS/JS (#7954)
## [23.5.9 (May 9 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.9)
* 64-bit support for C++ (#7935)
## [23.5.8 (May 8 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.8)
* add key_field to compiled tests
* Add golden language directory
* Rework cmake flatc codegeneration (#7938)
* remove defining generated files in test srcs
* Add binary schema reflection (#7932)
* Migrate from rules_nodejs to rules_js/rules_ts (take 2) (#7928)
* `flat_buffers.dart`: mark const variable finals for internal Dart linters
* fixed some windows warnings (#7929)
* inject no long for FBS generation to remove logs in flattests (#7926)
* Revert "Migrate from rules_nodejs to rules_js/rules_ts (#7923)" (#7927)
* Migrate from rules_nodejs to rules_js/rules_ts (#7923)
* Only generate @kotlin.ExperimentalUnsigned annotation on create*Vector methods having an unsigned array type parameter. (#7881)
* additional check for absl::string_view availability (#7897)
* Optionally generate Python type annotations (#7858)
* Replace deprecated command with environment file (#7921)
* drop glibc from runtime dependencies (#7906)
* Make JSON supporting advanced union features (#7869)
* Allow to use functions from `BuildFlatBuffers.cmake` from a flatbuffers installation installed with CMake. (#7912)
* TS/JS: Use TypeError instead of Error when appropriate (#7910)
* Go: make generated code more compliant to "go fmt" (#7907)
* Support file_identifier in Go (#7904)
* Optionally generate type prefixes and suffixes for python code (#7857)
* Go: add test for FinishWithFileIdentifier (#7905)
* Fix go_sample.sh (#7903)
* [TS/JS] Upgrade dependencies (#7889)
* Add a FileWriter interface (#7821)
* TS/JS: Use minvalue from enum if not found (#7888)
* [CS] Verifier (#7850)
* README.md: PyPI case typo (#7880)
* Update go documentation link to point to root module (#7879)
* use Bool for flatbuffers bool instead of Byte (#7876)
* fix using null string in vector (#7872)
* Add `flatbuffers-64` branch to CI for pushes
* made changes to the rust docs so they would compile. new_with_capacity is deprecated should use with_capacity, get_root_as_monster should be root_as_monster (#7871)
* Adding comment for code clarification (#7856)
* ToCamelCase() when kLowerCamel now converts first char to lower. (#7838)
* Fix help output for --java-checkerframework (#7854)
* Update filename to README.md and improve formatting (#7855)
* Update stale.yml
* Updated remaining usages of LICENSE.txt
## [23.3.3 (Mar 3 2023)](https://github.com/google/flatbuffers/releases/tag/v23.3.3)
* Refactoring of `flatc` generators to use an interface (#7797).
* Removed legacy cmake support and set min to 3.8 (#7801).
## [23.1.21 (Jan 21 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.20)
* Reworked entry points for Typescript/Javascript and compatibility for single
file build (#7510)
## [23.1.20 (Jan 20 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.20)
* Removed go.mod files after some versioning issues were being report (#7780).
## [23.1.4 (Jan 4 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.4)
* Major release! Just kidding, we are continuing the
[versioning scheme](https://github.com/google/flatbuffers/wiki/Versioning) of
using a date to signify releases. This results in the first release of the new
year to bump the tradition major version field.
* Go minimum version is now 1.19 (#7720) with the addition of Go modules.
* Added CI support for Big Endian regression testing (#7707).
* Fixed `getFullyQualifiedName` in typescript to return name delimited by '.'
instead of '_' (#7730).
* Fixed the versioning scheme to not include leading zeros which are not
consistently handled by every package manager. Only the last release
(12.12.06) should have suffered from this.
## [22.12.06 (Dec 06 2022)](https://github.com/google/flatbuffers/releases/tag/v22.12.06)
* Bug fixing release, no major changes.
## [22.10.25 (Oct 25 2022)](https://github.com/google/flatbuffers/releases/tag/v22.10.25)
* Added Nim language support with generator and runtime libraries (#7534).
## [22.9.29 (Sept 29 2022)](https://github.com/google/flatbuffers/releases/tag/v22.9.29)
* Rust soundness fixes to avoid the crate from bing labelled unsafe (#7518).
## [22.9.24 (Sept 24 2022)](https://github.com/google/flatbuffers/releases/tag/v22.9.24)
* 20 Major releases in a row? Nope, we switched to a new
[versioning scheme](https://github.com/google/flatbuffers/wiki/Versioning)
that is based on date.
* Python supports fixed size arrays now (#7529).
* Behavior change in how C++ object API uses `UnPackTo`. The original intent of
this was to reduce allocations by reusing an existing object to pack data
into. At some point, this logic started to merge the states of the two objects
instead of clearing the state of the packee. This change goes back to the
original intention, the packed object is cleared when getting data packed into
it (#7527).
* Fixed a bug in C++ alignment that was using `sizeof()` instead of the intended
`AlignOf()` for structs (#7520).
* C# has an
[official Nuget package](https://www.nuget.org/packages/Google.FlatBuffers)
now (#7496).
## 2.0.8 (Aug 29 2022)
* Fix for `--keep-prefix` the was generating the wrong include statements for
C++ (#7469). The bug was introduced in 2.0.7.
* Added the `Verifier::Options` option struct to allow specifying runtime
configuration settings for the verifier (#7489). This allows to skip verifying
nested flatbuffers, a on-by-default change that was introduced in 2.0.7. This
deprecates the existing `Verifier` constructor, which may be removed in a
future version.
* Refactor of `tests/test.cpp` that lead to ~10% speedup in compilation of the
entire project (#7487).
## 2.0.7 (Aug 22 2022)
* This is the first version with an explicit change log, so all the previous
features will not be listed.
* Verifier now checks that buffers are at least the minimum size required to be
a flatbuffers (12 bytes). This includes nested flatbuffers, which previously
could be declared valid at size 0.
* Annotated binaries. Given a flatbuffer binary and a schema (or binary schema)
one can generate an annotated flatbuffer (.afb) to describe each byte in the
binary with schema metadata and value.
* First binary schema generator (Lua) to generate Lua code via a .bfbs file.
This is mostly an implementation detail of flatc internals, but will be slowly
applied to the other language generators.

View File

@ -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_<TARGET>.
#
# Arguments:
# TARGET: The name of the target to generate.
# SCHEMAS: The list of schema files to generate code for.
# BINARY_SCHEMAS_DIR: Optional. The directory in which to generate binary
# schemas. Binary schemas will only be generated if a path is provided.
# INCLUDE: Optional. Search for includes in the specified paths. (Use this
# instead of "-I <path>" and the FLAGS option so that CMake is aware of
# the directories that need to be searched).
# INCLUDE_PREFIX: Optional. The directory in which to place the generated
# files. Use this instead of the --include-prefix option.
# FLAGS: Optional. A list of any additional flags that you would like to pass
# to flatc.
#
# Example:
#
# flatbuffers_generate_headers(
# TARGET my_generated_headers_target
# INCLUDE_PREFIX ${MY_INCLUDE_PREFIX}"
# SCHEMAS ${MY_SCHEMA_FILES}
# BINARY_SCHEMAS_DIR "${MY_BINARY_SCHEMA_DIRECTORY}"
# FLAGS --gen-object-api)
#
# target_link_libraries(MyExecutableTarget
# PRIVATE my_generated_headers_target
# )
#
# Optional (only needed within different directory):
# add_dependencies(app GENERATE_my_generated_headers_target)
function(flatbuffers_generate_headers)
# Parse function arguments.
set(options)
set(one_value_args
"TARGET"
"INCLUDE_PREFIX"
"BINARY_SCHEMAS_DIR")
set(multi_value_args
"SCHEMAS"
"INCLUDE"
"FLAGS")
cmake_parse_arguments(
PARSE_ARGV 0
FLATBUFFERS_GENERATE_HEADERS
"${options}"
"${one_value_args}"
"${multi_value_args}")
# Test if including from FindFlatBuffers
if(FLATBUFFERS_FLATC_EXECUTABLE)
set(FLATC_TARGET "")
set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE})
elseif(TARGET flatbuffers::flatc)
set(FLATC_TARGET flatbuffers::flatc)
set(FLATC flatbuffers::flatc)
else()
set(FLATC_TARGET flatc)
set(FLATC flatc)
endif()
set(working_dir "${CMAKE_CURRENT_SOURCE_DIR}")
# Generate the include files parameters.
set(include_params "")
foreach (include_dir ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE})
set(include_params -I ${include_dir} ${include_params})
endforeach()
# Create a directory to place the generated code.
set(generated_target_dir "${CMAKE_CURRENT_BINARY_DIR}/${FLATBUFFERS_GENERATE_HEADERS_TARGET}")
set(generated_include_dir "${generated_target_dir}")
if (NOT ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX} STREQUAL "")
set(generated_include_dir "${generated_include_dir}/${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX}")
list(APPEND FLATBUFFERS_GENERATE_HEADERS_FLAGS
"--include-prefix" ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX})
endif()
set(generated_custom_commands)
# Create rules to generate the code for each schema.
foreach(schema ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
get_filename_component(filename ${schema} NAME_WE)
set(generated_include "${generated_include_dir}/${filename}_generated.h")
# Generate files for grpc if needed
set(generated_source_file)
if("${FLATBUFFERS_GENERATE_HEADERS_FLAGS}" MATCHES "--grpc")
# Check if schema file contain a rpc_service definition
file(STRINGS ${schema} has_grpc REGEX "rpc_service")
if(has_grpc)
list(APPEND generated_include "${generated_include_dir}/${filename}.grpc.fb.h")
set(generated_source_file "${generated_include_dir}/${filename}.grpc.fb.cc")
endif()
endif()
add_custom_command(
OUTPUT ${generated_include} ${generated_source_file}
COMMAND ${FLATC} ${FLATC_ARGS}
-o ${generated_include_dir}
${include_params}
-c ${schema}
${FLATBUFFERS_GENERATE_HEADERS_FLAGS}
DEPENDS ${FLATC_TARGET} ${schema}
WORKING_DIRECTORY "${working_dir}"
COMMENT "Building ${schema} flatbuffers...")
list(APPEND all_generated_header_files ${generated_include})
list(APPEND all_generated_source_files ${generated_source_file})
list(APPEND generated_custom_commands "${generated_include}" "${generated_source_file}")
# Geneate the binary flatbuffers schemas if instructed to.
if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "")
set(binary_schema
"${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR}/${filename}.bfbs")
add_custom_command(
OUTPUT ${binary_schema}
COMMAND ${FLATC} -b --schema
-o ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR}
${include_params}
${schema}
DEPENDS ${FLATC_TARGET} ${schema}
WORKING_DIRECTORY "${working_dir}")
list(APPEND generated_custom_commands "${binary_schema}")
list(APPEND all_generated_binary_files ${binary_schema})
endif()
endforeach()
# Create an additional target as add_custom_command scope is only within same directory (CMakeFile.txt)
set(generate_target GENERATE_${FLATBUFFERS_GENERATE_HEADERS_TARGET})
add_custom_target(${generate_target} ALL
DEPENDS ${generated_custom_commands}
COMMENT "Generating flatbuffer target ${FLATBUFFERS_GENERATE_HEADERS_TARGET}")
# Set up interface library
add_library(${FLATBUFFERS_GENERATE_HEADERS_TARGET} INTERFACE)
target_sources(
${FLATBUFFERS_GENERATE_HEADERS_TARGET}
INTERFACE
${all_generated_header_files}
${all_generated_binary_files}
${all_generated_source_files}
${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
add_dependencies(
${FLATBUFFERS_GENERATE_HEADERS_TARGET}
${FLATC}
${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
target_include_directories(
${FLATBUFFERS_GENERATE_HEADERS_TARGET}
INTERFACE ${generated_target_dir})
# Organize file layout for IDEs.
source_group(
TREE "${generated_target_dir}"
PREFIX "Flatbuffers/Generated/Headers Files"
FILES ${all_generated_header_files})
source_group(
TREE "${generated_target_dir}"
PREFIX "Flatbuffers/Generated/Source Files"
FILES ${all_generated_source_files})
source_group(
TREE ${working_dir}
PREFIX "Flatbuffers/Schemas"
FILES ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "")
source_group(
TREE "${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR}"
PREFIX "Flatbuffers/Generated/Binary Schemas"
FILES ${all_generated_binary_files})
endif()
endfunction()
# Creates a target that can be linked against that generates flatbuffer binaries
# from json files.
#
# This function takes a target name and a list of schemas and Json files. You
# can also specify other flagc flags and options to change the behavior of the
# flatc compiler.
#
# Adding this target to your executable ensurses that the flatbuffer binaries
# are compiled before your executable is run.
#
# Arguments:
# TARGET: The name of the target to generate.
# JSON_FILES: The list of json files to compile to flatbuffers binaries.
# SCHEMA: The flatbuffers schema of the Json files to be compiled.
# INCLUDE: Optional. Search for includes in the specified paths. (Use this
# instead of "-I <path>" and the FLAGS option so that CMake is aware of
# the directories that need to be searched).
# OUTPUT_DIR: The directly where the generated flatbuffers binaries should be
# placed.
# FLAGS: Optional. A list of any additional flags that you would like to pass
# to flatc.
#
# Example:
#
# flatbuffers_generate_binary_files(
# TARGET my_binary_data
# SCHEMA "${MY_SCHEMA_DIR}/my_example_schema.fbs"
# JSON_FILES ${MY_JSON_FILES}
# OUTPUT_DIR "${MY_BINARY_DATA_DIRECTORY}"
# FLAGS --strict-json)
#
# target_link_libraries(MyExecutableTarget
# PRIVATE my_binary_data
# )
function(flatbuffers_generate_binary_files)
# Parse function arguments.
set(options)
set(one_value_args
"TARGET"
"SCHEMA"
"OUTPUT_DIR")
set(multi_value_args
"JSON_FILES"
"INCLUDE"
"FLAGS")
cmake_parse_arguments(
PARSE_ARGV 0
FLATBUFFERS_GENERATE_BINARY_FILES
"${options}"
"${one_value_args}"
"${multi_value_args}")
# Test if including from FindFlatBuffers
if(FLATBUFFERS_FLATC_EXECUTABLE)
set(FLATC_TARGET "")
set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE})
elseif(TARGET flatbuffers::flatc)
set(FLATC_TARGET flatbuffers::flatc)
set(FLATC flatbuffers::flatc)
else()
set(FLATC_TARGET flatc)
set(FLATC flatc)
endif()
set(working_dir "${CMAKE_CURRENT_SOURCE_DIR}")
# Generate the include files parameters.
set(include_params "")
foreach (include_dir ${FLATBUFFERS_GENERATE_BINARY_FILES_INCLUDE})
set(include_params -I ${include_dir} ${include_params})
endforeach()
# Create rules to generate the flatbuffers binary for each json file.
foreach(json_file ${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES})
get_filename_component(filename ${json_file} NAME_WE)
set(generated_binary_file "${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR}/${filename}.bin")
add_custom_command(
OUTPUT ${generated_binary_file}
COMMAND ${FLATC} ${FLATC_ARGS}
-o ${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR}
${include_params}
-b ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA} ${json_file}
${FLATBUFFERS_GENERATE_BINARY_FILES_FLAGS}
DEPENDS ${FLATC_TARGET} ${json_file}
WORKING_DIRECTORY "${working_dir}"
COMMENT "Building ${json_file} binary flatbuffers...")
list(APPEND all_generated_binary_files ${generated_binary_file})
endforeach()
# Set up interface library
add_library(${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET} INTERFACE)
target_sources(
${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET}
INTERFACE
${all_generated_binary_files}
${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES}
${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA})
add_dependencies(
${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET}
${FLATC})
# Organize file layout for IDEs.
source_group(
TREE ${working_dir}
PREFIX "Flatbuffers/JSON Files"
FILES ${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES})
source_group(
TREE ${working_dir}
PREFIX "Flatbuffers/Schemas"
FILES ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA})
source_group(
TREE ${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR}
PREFIX "Flatbuffers/Generated/Binary Files"
FILES ${all_generated_binary_files})
endfunction()

View File

@ -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")
include("${FLATBUFFERS_CMAKE_DIR}/BuildFlatBuffers.cmake")

View File

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

View File

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

View File

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

View File

@ -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<major>.<minor>.<patch>*"
if(GIT_DESCRIBE_DIRTY MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+.*")
string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" VERSION_MAJOR "${GIT_DESCRIBE_DIRTY}")
string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*" "\\1" VERSION_MINOR "${GIT_DESCRIBE_DIRTY}")
string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" VERSION_PATCH "${GIT_DESCRIBE_DIRTY}")
string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.[0-9]+\\-([0-9]+).*" "\\1" VERSION_COMMIT "${GIT_DESCRIBE_DIRTY}")
# If the tag points to the commit, then only the tag is shown in "git describe"
if(VERSION_COMMIT STREQUAL GIT_DESCRIBE_DIRTY)
set(VERSION_COMMIT 0)
endif()
else()
message(WARNING "\"${GIT_DESCRIBE_DIRTY}\" does not match pattern v<major>.<minor>.<patch>-<commit>")
endif()
else()
message(WARNING "git describe failed with exit code: ${GIT_DESCRIBE_RESULT}\nMake sure you cloned with tags or run 'git fetch --tags'.")
endif()
else()
message(WARNING "git is not found")
endif()
endif()
message(STATUS "Proceeding with version: ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_COMMIT}")

View File

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

View File

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

View File

@ -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=$<BOOL:${FLATBUFFERS_LOCALE_INDEPENDENT}>)
if(NOT WIN32)
check_symbol_exists(realpath "stdlib.h" HAVE_REALPATH)
if(NOT HAVE_REALPATH)
add_definitions(-DFLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION)
endif()
endif()
set(FlatBuffers_Library_SRCS
include/flatbuffers/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")
endif()
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -Wunused-result -Werror=unused-result -Wunused-parameter -Werror=unused-parameter")
endif()
# Certain platforms such as ARM do not use signed chars by default
# which causes issues with certain bounds checks.
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -fsigned-char")
elseif(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
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")
endif()
endif()
# Certain platforms such as ARM do not use signed chars by default
# which causes issues with certain bounds checks.
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -fsigned-char")
elseif(MSVC)
# Visual Studio pedantic build settings
# warning C4512: assignment operator could not be generated
# warning C4316: object allocated on the heap may not be aligned
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /WX /wd4512 /wd4316")
endif()
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")
# 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)
# FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer.
# List of sanitizer is string starts with '=': "=address,undefined,thread,memory".
if((${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") OR
((${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9"))
)
set(_sanitizer_flags "=address,undefined")
if(_sanitizer MATCHES "=.*")
# override default by user-defined sanitizer list
set(_sanitizer_flags ${_sanitizer})
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()
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()
if(BIICODE)
include(biicode/cmake/biicode.cmake)
return()
endif()
function(add_pch_to_target _target _pch_header)
# the command is available since cmake 3.16
if(COMMAND target_precompile_headers)
target_precompile_headers(${_target} PRIVATE ${_pch_header})
if(NOT MSVC)
set_source_files_properties(src/util.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS ON)
endif()
endif()
endfunction()
include_directories(include)
include_directories(grpc)
# Creates an interface library that stores the configuration settings that each
# target links too. This is a compromise between setting configuration globally
# with add_compile_options() and the more targetted target_compile_options().
# This way each target in this file can share settings and override them if
# needed.
add_library(ProjectConfig INTERFACE)
target_compile_features(ProjectConfig
INTERFACE
cxx_std_${FLATBUFFERS_CPP_STD}
)
# Force the standard to be met.
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# We shouldn't rely on any compiler-extensions to make things work.
set(CMAKE_CXX_EXTENSIONS OFF)
if(MSVC_LIKE)
target_compile_options(ProjectConfig
INTERFACE
/W4
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
/WX # Treat all compiler warnings as errors
>
/wd4512 # C4512: assignment operator could not be generated
/wd4316 # C4316: object allocated on the heap may not be aligned
/wd4456 # C4456: hides previous local declaration
$<$<CXX_COMPILER_ID:Clang>:
/D_CRT_SECURE_NO_WARNINGS
>
)
else()
target_compile_options(ProjectConfig
INTERFACE
-Wall
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror # Treat all compiler warnings as errors
-fno-rtti # Disable runtime type information
$<$<CXX_COMPILER_ID:GNU>:
# False positive string overflow
# https://github.com/google/flatbuffers/issues/7366
-Wno-error=stringop-overflow
>
>
-pedantic
-Wextra
-Wno-unused-parameter
-Wold-style-cast
-fsigned-char
-Wnon-virtual-dtor
# This isn't working for some reason: $<$<CXX_COMPILER_ID:CLANG>:
$<$<BOOL:${IS_CLANG}>:
-Wnewline-eof
-Wno-unknown-warning-option
-Wmissing-declarations
-Wzero-as-null-pointer-constant
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,3.8>:
-Wimplicit-fallthrough
-Wextra-semi
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror=unused-private-field
>
>
>
$<$<CXX_COMPILER_ID:GNU>:
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,4.4>:
-Wunused-result
-Wunused-parameter
-Werror=unused-parameter
-Wmissing-declarations
>
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,4.7>:
-Wzero-as-null-pointer-constant
>
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,7.0>:
-faligned-new
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror=implicit-fallthrough=2
>
>
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,8.0>:
-Wextra-semi
>
>
$<$<BOOL:${FLATBUFFERS_CODE_COVERAGE}>:
-g
-fprofile-arcs
-ftest-coverage
>
)
if(FLATBUFFERS_CODE_COVERAGE)
target_link_options(ProjectConfig
INTERFACE
-fprofile-arcs
-ftest-coverage
)
endif()
endif()
if(FLATBUFFERS_BUILD_FLATLIB)
add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
# CMake > 2.8.11: Attach header directory for when build via add_subdirectory().
target_include_directories(flatbuffers INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
target_compile_options(flatbuffers PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
# Attach header directory for when build via add_subdirectory().
target_include_directories(flatbuffers
INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
)
target_link_libraries(flatbuffers PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
if(FLATBUFFERS_ENABLE_PCH)
add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h)
endif()
endif()
if(FLATBUFFERS_BUILD_FLATC)
add_executable(flatc ${FlatBuffers_Compiler_SRCS})
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 $<BUILD_INTERFACE:ProjectConfig>)
target_compile_options(flatc
PRIVATE
$<$<AND:$<BOOL:${MSVC_LIKE}>,$<CONFIG:Release>>:
/MT
>
)
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
add_fsanitize_to_target(flatc ${FLATBUFFERS_CODE_SANITIZE})
endif()
if(NOT FLATBUFFERS_FLATC_EXECUTABLE)
set(FLATBUFFERS_FLATC_EXECUTABLE $<TARGET_FILE:flatc>)
endif()
if(MSVC)
# Make flatc.exe not depend on runtime dlls for easy distribution.
target_compile_options(flatc PUBLIC $<$<CONFIG:Release>:/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 $<BUILD_INTERFACE:ProjectConfig>)
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 $<BUILD_INTERFACE:ProjectConfig>)
# FlatBuffers use calendar-based versioning and do not provide any ABI
# stability guarantees. Therefore, always use the full version as SOVERSION
# in order to avoid breaking reverse dependencies on upgrades.
set(FlatBuffers_Library_SONAME_FULL "${PROJECT_VERSION}")
set_target_properties(flatbuffers_shared PROPERTIES
OUTPUT_NAME flatbuffers
SOVERSION "${FlatBuffers_Library_SONAME_FULL}"
VERSION "${FlatBuffers_Library_SONAME_FULL}")
if(FLATBUFFERS_ENABLE_PCH)
add_pch_to_target(flatbuffers_shared include/flatbuffers/pch/pch.h)
endif()
endif()
function(compile_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)
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()
endif()
target_link_libraries(flattests PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_include_directories(flattests PUBLIC
# Ideally everything is fully qualified from the root directories
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
# TODO(derekbailey): update includes to fully qualify src/ and tests/
src
tests
${CMAKE_CURRENT_BINARY_DIR}/tests
)
compile_flatbuffers_schema_to_cpp(samples/monster.fbs)
# Have tests load data from the source directory, not the build directory.
add_definitions(-DFLATBUFFERS_TEST_PATH_PREFIX=${CMAKE_CURRENT_SOURCE_DIR}/)
# The flattest target needs some generated files
SET(FLATC_OPT --cpp --gen-mutable --gen-object-api --reflect-names)
SET(FLATC_OPT_COMP ${FLATC_OPT};--gen-compare)
SET(FLATC_OPT_SCOPED_ENUMS ${FLATC_OPT_COMP};--scoped-enums)
compile_schema_for_test(tests/alignment_test.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/arrays_test.fbs "${FLATC_OPT_SCOPED_ENUMS}")
compile_schema_for_test(tests/native_inline_table_test.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/native_type_test.fbs "${FLATC_OPT}")
compile_schema_for_test(tests/key_field/key_field_sample.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/64bit/test_64bit.fbs "${FLATC_OPT_COMP};--bfbs-gen-embed")
compile_schema_for_test(tests/64bit/evolution/v1.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/64bit/evolution/v2.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/union_underlying_type_test.fbs "${FLATC_OPT_SCOPED_ENUMS}")
if(FLATBUFFERS_CODE_SANITIZE)
add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE})
endif()
include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
# Add a library so there is a single target that the generated samples can
# link too.
if(MSVC OR ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.20.0")
add_library(flatsample INTERFACE)
else()
add_library(flatsample STATIC)
endif()
# Since flatsample has no sources, we have to explicitly set the linker lang.
set_target_properties(flatsample PROPERTIES LINKER_LANGUAGE CXX)
compile_schema_for_samples(samples/monster.fbs "${FLATC_OPT_COMP}")
target_link_libraries(flatsamplebinary PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
target_link_libraries(flatsampletext PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
target_link_libraries(flatsamplebfbs PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
if(FLATBUFFERS_BUILD_CPP17)
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
target_link_libraries(flattests_cpp17 PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_include_directories(flattests_cpp17 PUBLIC src tests)
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17) # requires cmake 3.8
if(FLATBUFFERS_CODE_SANITIZE)
add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE})
endif()
endif(FLATBUFFERS_BUILD_CPP17)
endif()
if(FLATBUFFERS_BUILD_GRPCTEST)
if(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
$<BUILD_INTERFACE:ProjectConfig>
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 $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/include>)

View File

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

22
third_party/flatbuffers/Formatters.md vendored Normal file
View File

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

View File

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

View File

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

36
third_party/flatbuffers/Package.swift vendored Normal file
View File

@ -0,0 +1,36 @@
// swift-tools-version:5.6
/*
* Copyright 2020 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import PackageDescription
let package = Package(
name: "FlatBuffers",
platforms: [
.iOS(.v11),
.macOS(.v10_14),
],
products: [
.library(
name: "FlatBuffers",
targets: ["FlatBuffers"]),
],
targets: [
.target(
name: "FlatBuffers",
dependencies: [],
path: "swift/Sources"),
])

View File

@ -0,0 +1,37 @@
// swift-tools-version:5.5
/*
* Copyright 2020 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import PackageDescription
let package = Package(
name: "FlatBuffers",
platforms: [
.iOS(.v11),
.macOS(.v10_14),
],
products: [
.library(
name: "FlatBuffers",
targets: ["FlatBuffers"]),
],
targets: [
.target(
name: "FlatBuffers",
dependencies: [],
path: "swift/Sources"),
])

118
third_party/flatbuffers/README.md vendored Normal file
View File

@ -0,0 +1,118 @@
![logo](http://google.github.io/flatbuffers/fpl_logo_small.png) FlatBuffers
===========
![Build status](https://github.com/google/flatbuffers/actions/workflows/build.yml/badge.svg?branch=master)
[![BuildKite status](https://badge.buildkite.com/7979d93bc6279aa539971f271253c65d5e8fe2fe43c90bbb25.svg)](https://buildkite.com/bazel/flatbuffers)
[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/flatbuffers.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:flatbuffers)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers/badge)](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers)
[![Join the chat at https://gitter.im/google/flatbuffers](https://badges.gitter.im/google/flatbuffers.svg)](https://gitter.im/google/flatbuffers?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Discord Chat](https://img.shields.io/discord/656202785926152206.svg)](https:///discord.gg/6qgKs3R)
[![Twitter Follow](https://img.shields.io/twitter/follow/wvo.svg?style=social)](https://twitter.com/wvo)
[![Twitter Follow](https://img.shields.io/twitter/follow/dbaileychess.svg?style=social)](https://twitter.com/dbaileychess)
**FlatBuffers** is a cross platform serialization library architected for
maximum memory efficiency. It allows you to directly access serialized data without parsing/unpacking it first, while still having great forwards/backwards compatibility.
## Quick Start
1. Build the compiler for flatbuffers (`flatc`)
Use `cmake` to create the build files for your platform and then perform the compliation (Linux example).
```
cmake -G "Unix Makefiles"
make -j
```
2. Define your flatbuffer schema (`.fbs`)
Write the [schema](https://flatbuffers.dev/flatbuffers_guide_writing_schema.html) to define the data you want to serialize. See [monster.fbs](https://github.com/google/flatbuffers/blob/master/samples/monster.fbs) for an example.
3. Generate code for your language(s)
Use the `flatc` compiler to take your schema and generate language-specific code:
```
./flatc --cpp --rust monster.fbs
```
Which generates `monster_generated.h` and `monster_generated.rs` files.
4. Serialize data
Use the generated code, as well as the `FlatBufferBuilder` to construct your serialized buffer. ([`C++` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp#L24-L56))
5. Transmit/store/save Buffer
Use your serialized buffer however you want. Send it to someone, save it for later, etc...
6. Read the data
Use the generated accessors to read the data from the serialized buffer.
It doesn't need to be the same language/schema version, FlatBuffers ensures the data is readable across languages and schema versions. See the [`Rust` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs#L92-L106) reading the data written by `C++`.
## Documentation
**Go to our [landing page][] to browse our documentation.**
## Supported operating systems
- Windows
- macOS
- Linux
- Android
- And any others with a recent C++ compiler (C++ 11 and newer)
## Supported programming languages
Code generation and runtime libraries for many popular languages.
1. C
1. C++ - [snapcraft.io](https://snapcraft.io/flatbuffers)
1. C# - [nuget.org](https://www.nuget.org/packages/Google.FlatBuffers)
1. Dart - [pub.dev](https://pub.dev/packages/flat_buffers)
1. Go - [go.dev](https://pkg.go.dev/github.com/google/flatbuffers)
1. Java - [Maven](https://search.maven.org/artifact/com.google.flatbuffers/flatbuffers-java)
1. JavaScript - [NPM](https://www.npmjs.com/package/flatbuffers)
1. Kotlin
1. Lobster
1. Lua
1. PHP
1. Python - [PyPI](https://pypi.org/project/flatbuffers/)
1. Rust - [crates.io](https://crates.io/crates/flatbuffers)
1. Swift - [swiftpackageindex](https://swiftpackageindex.com/google/flatbuffers)
1. TypeScript - [NPM](https://www.npmjs.com/package/flatbuffers)
1. Nim
## Versioning
FlatBuffers does not follow traditional SemVer versioning (see [rationale](https://github.com/google/flatbuffers/wiki/Versioning)) but rather uses a format of the date of the release.
## Contribution
* [FlatBuffers Issues Tracker][] to submit an issue.
* [stackoverflow.com][] with [`flatbuffers` tag][] for any questions regarding FlatBuffers.
*To contribute to this project,* see [CONTRIBUTING][].
## Community
* [Discord Server](https:///discord.gg/6qgKs3R)
## Security
Please see our [Security Policy](SECURITY.md) for reporting vulnerabilities.
## Licensing
*Flatbuffers* is licensed under the Apache License, Version 2.0. See [LICENSE][] for the full license text.
<br>
[CONTRIBUTING]: http://github.com/google/flatbuffers/blob/master/CONTRIBUTING.md
[`flatbuffers` tag]: https://stackoverflow.com/questions/tagged/flatbuffers
[FlatBuffers Google Group]: https://groups.google.com/forum/#!forum/flatbuffers
[FlatBuffers Issues Tracker]: http://github.com/google/flatbuffers/issues
[stackoverflow.com]: http://stackoverflow.com/search?q=flatbuffers
[landing page]: https://google.github.io/flatbuffers
[LICENSE]: https://github.com/google/flatbuffers/blob/master/LICENSE

11
third_party/flatbuffers/SECURITY.md vendored Normal file
View File

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

View File

@ -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",
],
)

View File

@ -1,45 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2013 Google, Inc.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
-->
<!-- BEGIN_INCLUDE(manifest) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.FlatBufferTest">
<uses-feature android:glEsVersion="0x00020000"></uses-feature>
<!-- This .apk has no Java code itself, so set hasCode to false. -->
<application android:label="@string/app_name"
android:hasCode="false"
android:allowBackup="false">
<!-- Our activity is the built-in NativeActivity framework class.
This will take care of integrating with our NDK code. -->
<activity android:name="android.app.NativeActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="landscape">
<!-- Tell NativeActivity the name of or .so -->
<meta-data android:name="android.app.lib_name"
android:value="FlatBufferTest" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<!-- END_INCLUDE(manifest) -->

View File

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

View File

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

View File

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

View File

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

View File

@ -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)/../..)

View File

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

View File

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

View File

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

View File

@ -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())

View File

@ -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())

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 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.
-->
<resources>
<string name="app_name">FlatBufferTest</string>
</resources>

View File

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

View File

@ -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),
)
native.Fileset(
name = reflection_name,
out = "%s_out" % reflection_name,
entries = [
native.FilesetEntry(files = reflection_outs),
],
visibility = reflection_visibility,
)
native.filegroup(
name = "%s_out" % reflection_name,
srcs = reflection_outs,
visibility = reflection_visibility,
compatible_with = compatible_with,
restricted_to = restricted_to,
)
def flatbuffer_cc_library(
name,
srcs,
srcs_filegroup_name = "",
outs = [],
out_prefix = "",
deps = [],
includes = [],
include_paths = 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,
)

View File

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

View File

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

View File

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

View File

@ -6,16 +6,6 @@ import subprocess
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 @@ if __name__ == "__main__":
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,

View File

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

View File

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

View File

@ -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 @@ class FlatbuffersConan(ConanFile):
"""
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")

View File

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

View File

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

View File

@ -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<int> 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<int> 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;
}

View File

@ -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<Color> reader = const _ColorReader();
@override
String toString() {
return 'Color{value: $value}';
}
}
class _ColorReader extends fb.Reader<Color> {
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<EquipmentTypeId> reader = const _EquipmentTypeIdReader();
@override
String toString() {
return 'EquipmentTypeId{value: $value}';
}
}
class _EquipmentTypeIdReader extends fb.Reader<EquipmentTypeId> {
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<Vec3> 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<Vec3> {
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<int> bytes) {
fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
static const fb.Reader<Monster> 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<int> get inventory => const fb.ListReader<int>(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 14, null);
Color get color => new Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2));
List<Weapon> get weapons => const fb.ListReader<Weapon>(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<Vec3> get path => const fb.ListReader<Vec3>(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<Monster> {
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<int> _inventory;
final Color _color;
final List<WeaponObjectBuilder> _weapons;
final EquipmentTypeId _equippedType;
final dynamic _equipped;
final List<Vec3ObjectBuilder> _path;
MonsterObjectBuilder({
Vec3ObjectBuilder pos,
int mana,
int hp,
String name,
List<int> inventory,
Color color,
List<WeaponObjectBuilder> weapons,
EquipmentTypeId equippedType,
dynamic equipped,
List<Vec3ObjectBuilder> 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<int> bytes) {
fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
static const fb.Reader<Weapon> 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<Weapon> {
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);
}
}

File diff suppressed because it is too large Load Diff

View File

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

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