Use the Google Style for clang-format without exceptions (#8706)
This reduces the friction when merging from github and google repos by
using the exact same clang style guide.
MARKDOWN=true
diff --git a/.clang-format b/.clang-format
index 7da2b43..bb2e344 100644
--- a/.clang-format
+++ b/.clang-format
@@ -1,13 +1,5 @@
---
Language: Cpp
BasedOnStyle: Google
-DerivePointerAlignment: false
-PointerAlignment: Right
-IndentPPDirectives: AfterHash
-Cpp11BracedListStyle: false
-AlwaysBreakTemplateDeclarations: false
-AllowShortCaseLabelsOnASingleLine: true
-SpaceAfterTemplateKeyword: false
-AllowShortBlocksOnASingleLine: true
...
diff --git a/goldens/swift/basic_generated.swift b/goldens/swift/basic_generated.swift
index 16ef663..b4cb234 100644
--- a/goldens/swift/basic_generated.swift
+++ b/goldens/swift/basic_generated.swift
@@ -2,6 +2,10 @@
// swiftlint:disable all
// swiftformat:disable all
+#if canImport(Common)
+import Common
+#endif
+
import FlatBuffers
public struct flatbuffers_goldens_Galaxy: FlatBufferObject, Verifiable {
diff --git a/grpc/src/compiler/schema_interface.h b/grpc/src/compiler/schema_interface.h
index f89288d..483d5ac 100644
--- a/grpc/src/compiler/schema_interface.h
+++ b/grpc/src/compiler/schema_interface.h
@@ -24,8 +24,8 @@
#include <vector>
#ifndef GRPC_CUSTOM_STRING
-# include <string>
-# define GRPC_CUSTOM_STRING std::string
+#include <string>
+#define GRPC_CUSTOM_STRING std::string
#endif
namespace grpc {
@@ -55,10 +55,10 @@
virtual grpc::string output_type_name() const = 0;
virtual bool get_module_and_message_path_input(
- grpc::string *str, grpc::string generator_file_name,
+ grpc::string* str, grpc::string generator_file_name,
bool generate_in_pb2_grpc, grpc::string import_prefix) const = 0;
virtual bool get_module_and_message_path_output(
- grpc::string *str, grpc::string generator_file_name,
+ grpc::string* str, grpc::string generator_file_name,
bool generate_in_pb2_grpc, grpc::string import_prefix) const = 0;
virtual std::vector<grpc::string> get_input_namespace_parts() const = 0;
@@ -89,9 +89,9 @@
struct Printer {
virtual ~Printer() {}
- virtual void Print(const std::map<grpc::string, grpc::string> &vars,
- const char *template_string) = 0;
- virtual void Print(const char *string) = 0;
+ virtual void Print(const std::map<grpc::string, grpc::string>& vars,
+ const char* template_string) = 0;
+ virtual void Print(const char* string) = 0;
virtual void SetIndentationSize(const size_t size) = 0;
virtual void Indent() = 0;
virtual void Outdent() = 0;
@@ -112,7 +112,7 @@
virtual std::unique_ptr<const Service> service(int i) const = 0;
virtual std::unique_ptr<Printer> CreatePrinter(
- grpc::string *str, const char indentation_type = ' ') const = 0;
+ grpc::string* str, const char indentation_type = ' ') const = 0;
};
} // namespace grpc_generator
diff --git a/grpc/tests/grpctest.cpp b/grpc/tests/grpctest.cpp
index 6991b7e..f4798c9 100644
--- a/grpc/tests/grpctest.cpp
+++ b/grpc/tests/grpctest.cpp
@@ -33,9 +33,9 @@
// code. It implements all rpcs specified in the FlatBuffers schema.
class ServiceImpl final : public MyGame::Example::MonsterStorage::Service {
virtual ::grpc::Status Store(
- ::grpc::ServerContext *context,
- const flatbuffers::grpc::Message<Monster> *request,
- flatbuffers::grpc::Message<Stat> *response) override {
+ ::grpc::ServerContext* context,
+ const flatbuffers::grpc::Message<Monster>* request,
+ flatbuffers::grpc::Message<Stat>* response) override {
// Create a response from the incoming request name.
fbb_.Clear();
auto stat_offset = CreateStat(
@@ -46,9 +46,9 @@
return grpc::Status::OK;
}
virtual ::grpc::Status Retrieve(
- ::grpc::ServerContext *context,
- const flatbuffers::grpc::Message<Stat> *request,
- ::grpc::ServerWriter<flatbuffers::grpc::Message<Monster>> *writer)
+ ::grpc::ServerContext* context,
+ const flatbuffers::grpc::Message<Stat>* request,
+ ::grpc::ServerWriter<flatbuffers::grpc::Message<Monster>>* writer)
override {
for (int i = 0; i < 5; i++) {
fbb_.Clear();
@@ -73,7 +73,7 @@
};
// Track the server instance, so we can terminate it later.
-grpc::Server *server_instance = nullptr;
+grpc::Server* server_instance = nullptr;
// Mutex to protec this variable.
std::mutex wait_for_server;
std::condition_variable server_instance_cv;
@@ -98,7 +98,8 @@
server_instance->Wait();
}
-template<class Builder> void StoreRPC(MonsterStorage::Stub *stub) {
+template <class Builder>
+void StoreRPC(MonsterStorage::Stub* stub) {
Builder fbb;
grpc::ClientContext context;
// Build a request with the name set.
@@ -119,7 +120,8 @@
}
}
-template<class Builder> void RetrieveRPC(MonsterStorage::Stub *stub) {
+template <class Builder>
+void RetrieveRPC(MonsterStorage::Stub* stub) {
Builder fbb;
grpc::ClientContext context;
fbb.Clear();
@@ -179,7 +181,7 @@
return 0;
}
-int main(int /*argc*/, const char * /*argv*/[]) {
+int main(int /*argc*/, const char* /*argv*/[]) {
message_builder_tests();
grpc_server_test();
diff --git a/grpc/tests/grpctest_callback_client_compile.cpp b/grpc/tests/grpctest_callback_client_compile.cpp
index 8057cc5..b3947ee 100644
--- a/grpc/tests/grpctest_callback_client_compile.cpp
+++ b/grpc/tests/grpctest_callback_client_compile.cpp
@@ -15,44 +15,43 @@
// Unary async overloads
static_assert(std::is_member_function_pointer<
decltype(static_cast<void (Stub::*)(
- ::grpc::ClientContext *,
- const flatbuffers::grpc::Message<Monster> &,
- flatbuffers::grpc::Message<Stat> *,
+ ::grpc::ClientContext*,
+ const flatbuffers::grpc::Message<Monster>&,
+ flatbuffers::grpc::Message<Stat>*,
std::function<void(::grpc::Status)>)>(
&Stub::async_Store))>::value,
"Function-form unary async_Store missing");
-static_assert(std::is_member_function_pointer<
- decltype(static_cast<void (Stub::*)(
- ::grpc::ClientContext *,
- const flatbuffers::grpc::Message<Monster> &,
- flatbuffers::grpc::Message<Stat> *,
- ::grpc::ClientUnaryReactor *)>(
- &Stub::async_Store))>::value,
- "Reactor-form unary async_Store missing");
+static_assert(
+ std::is_member_function_pointer<
+ decltype(static_cast<void (Stub::*)(
+ ::grpc::ClientContext*,
+ const flatbuffers::grpc::Message<Monster>&,
+ flatbuffers::grpc::Message<Stat>*,
+ ::grpc::ClientUnaryReactor*)>(&Stub::async_Store))>::value,
+ "Reactor-form unary async_Store missing");
// Streaming reactor entry points
static_assert(
std::is_member_function_pointer<
decltype(static_cast<void (Stub::*)(
- ::grpc::ClientContext *,
- const flatbuffers::grpc::Message<Stat> &,
+ ::grpc::ClientContext*,
+ const flatbuffers::grpc::Message<Stat>&,
::grpc::ClientReadReactor<flatbuffers::grpc::Message<
- Monster> > *)>(&Stub::async_Retrieve))>::value,
+ Monster> >*)>(&Stub::async_Retrieve))>::value,
"Server streaming reactor async_Retrieve missing");
static_assert(
std::is_member_function_pointer<
decltype(static_cast<void (Stub::*)(
- ::grpc::ClientContext *,
- flatbuffers::grpc::Message<Stat> *,
+ ::grpc::ClientContext*, flatbuffers::grpc::Message<Stat>*,
::grpc::ClientWriteReactor<flatbuffers::grpc::Message<
- Monster> > *)>(&Stub::async_GetMaxHitPoint))>::value,
+ Monster> >*)>(&Stub::async_GetMaxHitPoint))>::value,
"Client streaming reactor async_GetMaxHitPoint missing");
static_assert(std::is_member_function_pointer<
decltype(static_cast<void (Stub::*)(
- ::grpc::ClientContext *,
+ ::grpc::ClientContext*,
::grpc::ClientBidiReactor<
flatbuffers::grpc::Message<Monster>,
- flatbuffers::grpc::Message<Stat> > *)>(
+ flatbuffers::grpc::Message<Stat> >*)>(
&Stub::async_GetMinMaxHitPoints))>::value,
"Bidi streaming reactor async_GetMinMaxHitPoints missing");
#endif // FLATBUFFERS_GENERATED_GRPC_CALLBACK_API &&
diff --git a/grpc/tests/message_builder_test.cpp b/grpc/tests/message_builder_test.cpp
index 8af0c21..cdaf7cb 100644
--- a/grpc/tests/message_builder_test.cpp
+++ b/grpc/tests/message_builder_test.cpp
@@ -7,9 +7,9 @@
using MyGame::Example::CreateStat;
using MyGame::Example::Vec3;
-bool verify(flatbuffers::grpc::Message<Monster> &msg,
- const std::string &expected_name, Color expected_color) {
- const Monster *monster = msg.GetRoot();
+bool verify(flatbuffers::grpc::Message<Monster>& msg,
+ const std::string& expected_name, Color expected_color) {
+ const Monster* monster = msg.GetRoot();
const auto name = monster->name()->str();
const auto color = monster->color();
TEST_EQ(name, expected_name);
@@ -17,8 +17,8 @@
return (name == expected_name) && (color == expected_color);
}
-bool release_n_verify(flatbuffers::grpc::MessageBuilder &mbb,
- const std::string &expected_name, Color expected_color) {
+bool release_n_verify(flatbuffers::grpc::MessageBuilder& mbb,
+ const std::string& expected_name, Color expected_color) {
flatbuffers::grpc::Message<Monster> msg = mbb.ReleaseMessage<Monster>();
return verify(msg, expected_name, expected_color);
}
@@ -41,11 +41,13 @@
TEST_EQ(src.GetSize(), 0);
}
-template<class SrcBuilder>
+template <class SrcBuilder>
struct BuilderReuseTests<flatbuffers::grpc::MessageBuilder, SrcBuilder> {
static void builder_reusable_after_release_message_test(
TestSelector selector) {
- if (!selector.count(REUSABLE_AFTER_RELEASE_MESSAGE)) { return; }
+ if (!selector.count(REUSABLE_AFTER_RELEASE_MESSAGE)) {
+ return;
+ }
flatbuffers::grpc::MessageBuilder mb;
std::vector<flatbuffers::grpc::Message<Monster>> buffers;
@@ -58,7 +60,9 @@
}
static void builder_reusable_after_release_test(TestSelector selector) {
- if (!selector.count(REUSABLE_AFTER_RELEASE)) { return; }
+ if (!selector.count(REUSABLE_AFTER_RELEASE)) {
+ return;
+ }
// FIXME: Populate-Release loop fails assert(GRPC_SLICE_IS_EMPTY(slice_)) in
// SliceAllocator::allocate in the second iteration.
@@ -74,7 +78,9 @@
}
static void builder_reusable_after_releaseraw_test(TestSelector selector) {
- if (!selector.count(REUSABLE_AFTER_RELEASE_RAW)) { return; }
+ if (!selector.count(REUSABLE_AFTER_RELEASE_RAW)) {
+ return;
+ }
flatbuffers::grpc::MessageBuilder mb;
for (int i = 0; i < 5; ++i) {
@@ -82,14 +88,16 @@
mb.Finish(root_offset1);
size_t size, offset;
::grpc::Slice slice;
- const uint8_t *buf = mb.ReleaseRaw(size, offset, slice);
+ const uint8_t* buf = mb.ReleaseRaw(size, offset, slice);
TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color()));
}
}
static void builder_reusable_after_release_and_move_assign_test(
TestSelector selector) {
- if (!selector.count(REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN)) { return; }
+ if (!selector.count(REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN)) {
+ return;
+ }
// FIXME: Release-move_assign loop fails assert(p ==
// GRPC_SLICE_START_PTR(slice_)) in DetachedBuffer destructor after all the
@@ -137,7 +145,9 @@
static void builder_reusable_after_releaseraw_and_move_assign_test(
TestSelector selector) {
- if (!selector.count(REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN)) { return; }
+ if (!selector.count(REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN)) {
+ return;
+ }
flatbuffers::grpc::MessageBuilder dst;
for (int i = 0; i < 5; ++i) {
@@ -145,7 +155,7 @@
dst.Finish(root_offset1);
size_t size, offset;
::grpc::Slice slice;
- const uint8_t *buf = dst.ReleaseRaw(size, offset, slice);
+ const uint8_t* buf = dst.ReleaseRaw(size, offset, slice);
TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color()));
SrcBuilder src;
@@ -170,7 +180,7 @@
{
size_t size = 2048;
flatbuffers::grpc::SliceAllocator sa1;
- uint8_t *buf = sa1.allocate(size);
+ uint8_t* buf = sa1.allocate(size);
TEST_ASSERT_FUNC(buf != 0);
buf[0] = 100;
buf[size - 1] = 200;
@@ -184,7 +194,7 @@
// move-assign test
{
flatbuffers::grpc::SliceAllocator sa1, sa2;
- uint8_t *buf = sa1.allocate(2048);
+ uint8_t* buf = sa1.allocate(2048);
sa1 = std::move(sa2);
// sa1 deletes previously allocated memory in move-assign.
// So buf is no longer usable here.
@@ -194,7 +204,7 @@
/// This function does not populate exactly the first half of the table. But it
/// could.
-void populate_first_half(MyGame::Example::MonsterBuilder &wrapper,
+void populate_first_half(MyGame::Example::MonsterBuilder& wrapper,
flatbuffers::Offset<flatbuffers::String> name_offset) {
wrapper.add_name(name_offset);
wrapper.add_color(m1_color());
@@ -202,7 +212,7 @@
/// This function does not populate exactly the second half of the table. But it
/// could.
-void populate_second_half(MyGame::Example::MonsterBuilder &wrapper) {
+void populate_second_half(MyGame::Example::MonsterBuilder& wrapper) {
wrapper.add_hp(77);
wrapper.add_mana(88);
Vec3 vec3;
@@ -216,9 +226,9 @@
/// between FlatBufferBuilders. If MonsterBuilder had a fbb_ pointer, this hack
/// would be unnecessary. That involves a code-generator change though.
void test_only_hack_update_fbb_reference(
- MyGame::Example::MonsterBuilder &monsterBuilder,
- flatbuffers::grpc::MessageBuilder &mb) {
- *reinterpret_cast<flatbuffers::FlatBufferBuilder **>(&monsterBuilder) = &mb;
+ MyGame::Example::MonsterBuilder& monsterBuilder,
+ flatbuffers::grpc::MessageBuilder& mb) {
+ *reinterpret_cast<flatbuffers::FlatBufferBuilder**>(&monsterBuilder) = &mb;
}
/// This test validates correctness of move conversion of FlatBufferBuilder to a
@@ -351,15 +361,14 @@
BuilderTests<MessageBuilder, FlatBufferBuilder>::all_tests();
BuilderReuseTestSelector tests[6] = {
- // REUSABLE_AFTER_RELEASE, // Assertion failed:
- // (GRPC_SLICE_IS_EMPTY(slice_))
- // REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN, // Assertion failed: (p ==
- // GRPC_SLICE_START_PTR(slice_)
+ // REUSABLE_AFTER_RELEASE, // Assertion failed:
+ // (GRPC_SLICE_IS_EMPTY(slice_))
+ // REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN, // Assertion failed: (p ==
+ // GRPC_SLICE_START_PTR(slice_)
- REUSABLE_AFTER_RELEASE_RAW, REUSABLE_AFTER_RELEASE_MESSAGE,
- REUSABLE_AFTER_RELEASE_MESSAGE_AND_MOVE_ASSIGN,
- REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN
- };
+ REUSABLE_AFTER_RELEASE_RAW, REUSABLE_AFTER_RELEASE_MESSAGE,
+ REUSABLE_AFTER_RELEASE_MESSAGE_AND_MOVE_ASSIGN,
+ REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN};
BuilderReuseTests<MessageBuilder, MessageBuilder>::run_tests(
TestSelector(tests, tests + 6));
diff --git a/include/flatbuffers/allocator.h b/include/flatbuffers/allocator.h
index 3042719..d451818 100644
--- a/include/flatbuffers/allocator.h
+++ b/include/flatbuffers/allocator.h
@@ -28,21 +28,21 @@
virtual ~Allocator() {}
// Allocate `size` bytes of memory.
- virtual uint8_t *allocate(size_t size) = 0;
+ virtual uint8_t* allocate(size_t size) = 0;
// Deallocate `size` bytes of memory at `p` allocated by this allocator.
- virtual void deallocate(uint8_t *p, size_t size) = 0;
+ virtual void deallocate(uint8_t* p, size_t size) = 0;
// Reallocate `new_size` bytes of memory, replacing the old region of size
// `old_size` at `p`. In contrast to a normal realloc, this grows downwards,
// and is intended specifcally for `vector_downward` use.
// `in_use_back` and `in_use_front` indicate how much of `old_size` is
// actually in use at each end, and needs to be copied.
- virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size,
+ virtual uint8_t* reallocate_downward(uint8_t* old_p, size_t old_size,
size_t new_size, size_t in_use_back,
size_t in_use_front) {
FLATBUFFERS_ASSERT(new_size > old_size); // vector_downward only grows
- uint8_t *new_p = allocate(new_size);
+ uint8_t* new_p = allocate(new_size);
memcpy_downward(old_p, old_size, new_p, new_size, in_use_back,
in_use_front);
deallocate(old_p, old_size);
@@ -54,7 +54,7 @@
// to `new_p` of `new_size`. Only memory of size `in_use_front` and
// `in_use_back` will be copied from the front and back of the old memory
// allocation.
- void memcpy_downward(uint8_t *old_p, size_t old_size, uint8_t *new_p,
+ void memcpy_downward(uint8_t* old_p, size_t old_size, uint8_t* new_p,
size_t new_size, size_t in_use_back,
size_t in_use_front) {
memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back,
diff --git a/include/flatbuffers/array.h b/include/flatbuffers/array.h
index 68c245d..914f479 100644
--- a/include/flatbuffers/array.h
+++ b/include/flatbuffers/array.h
@@ -27,7 +27,8 @@
namespace flatbuffers {
// This is used as a helper type for accessing arrays.
-template<typename T, uint16_t length> class Array {
+template <typename T, uint16_t length>
+class Array {
// Array<T> can carry only POD data types (scalars or structs).
typedef typename flatbuffers::bool_constant<flatbuffers::is_scalar<T>::value>
scalar_tag;
@@ -55,7 +56,8 @@
// If this is a Vector of enums, T will be its storage type, not the enum
// type. This function makes it convenient to retrieve value with enum
// type E.
- template<typename E> E GetEnum(uoffset_t i) const {
+ template <typename E>
+ E GetEnum(uoffset_t i) const {
return static_cast<E>(Get(i));
}
@@ -80,28 +82,28 @@
// operation. For primitive types use @p Mutate directly.
// @warning Assignments and reads to/from the dereferenced pointer are not
// automatically converted to the correct endianness.
- typename flatbuffers::conditional<scalar_tag::value, void, T *>::type
+ typename flatbuffers::conditional<scalar_tag::value, void, T*>::type
GetMutablePointer(uoffset_t i) const {
FLATBUFFERS_ASSERT(i < size());
- return const_cast<T *>(&data()[i]);
+ return const_cast<T*>(&data()[i]);
}
// Change elements if you have a non-const pointer to this object.
- void Mutate(uoffset_t i, const T &val) { MutateImpl(scalar_tag(), i, val); }
+ void Mutate(uoffset_t i, const T& val) { MutateImpl(scalar_tag(), i, val); }
// The raw data in little endian format. Use with care.
- const uint8_t *Data() const { return data_; }
+ const uint8_t* Data() const { return data_; }
- uint8_t *Data() { return data_; }
+ uint8_t* Data() { return data_; }
// Similarly, but typed, much like std::vector::data
- const T *data() const { return reinterpret_cast<const T *>(Data()); }
- T *data() { return reinterpret_cast<T *>(Data()); }
+ const T* data() const { return reinterpret_cast<const T*>(Data()); }
+ T* data() { return reinterpret_cast<T*>(Data()); }
// Copy data from a span with endian conversion.
// If this Array and the span overlap, the behavior is undefined.
void CopyFromSpan(flatbuffers::span<const T, length> src) {
- const auto p1 = reinterpret_cast<const uint8_t *>(src.data());
+ const auto p1 = reinterpret_cast<const uint8_t*>(src.data());
const auto p2 = Data();
FLATBUFFERS_ASSERT(!(p1 >= p2 && p1 < (p2 + length)) &&
!(p2 >= p1 && p2 < (p1 + length)));
@@ -111,12 +113,12 @@
}
protected:
- void MutateImpl(flatbuffers::true_type, uoffset_t i, const T &val) {
+ void MutateImpl(flatbuffers::true_type, uoffset_t i, const T& val) {
FLATBUFFERS_ASSERT(i < size());
WriteScalar(data() + i, val);
}
- void MutateImpl(flatbuffers::false_type, uoffset_t i, const T &val) {
+ void MutateImpl(flatbuffers::false_type, uoffset_t i, const T& val) {
*(GetMutablePointer(i)) = val;
}
@@ -131,7 +133,9 @@
// Copy data from flatbuffers::span with endian conversion.
void CopyFromSpanImpl(flatbuffers::false_type,
flatbuffers::span<const T, length> src) {
- for (size_type k = 0; k < length; k++) { Mutate(k, src[k]); }
+ for (size_type k = 0; k < length; k++) {
+ Mutate(k, src[k]);
+ }
}
// This class is only used to access pre-existing data. Don't ever
@@ -150,21 +154,21 @@
private:
// This class is a pointer. Copying will therefore create an invalid object.
// Private and unimplemented copy constructor.
- Array(const Array &);
- Array &operator=(const Array &);
+ Array(const Array&);
+ Array& operator=(const Array&);
};
// Specialization for Array[struct] with access using Offset<void> pointer.
// This specialization used by idl_gen_text.cpp.
-template<typename T, uint16_t length, template<typename> class OffsetT>
+template <typename T, uint16_t length, template <typename> class OffsetT>
class Array<OffsetT<T>, length> {
static_assert(flatbuffers::is_same<T, void>::value, "unexpected type T");
public:
- typedef const void *return_type;
+ typedef const void* return_type;
typedef uint16_t size_type;
- const uint8_t *Data() const { return data_; }
+ const uint8_t* Data() const { return data_; }
// Make idl_gen_text.cpp::PrintContainer happy.
return_type operator[](uoffset_t) const {
@@ -175,14 +179,14 @@
private:
// This class is only used to access pre-existing data.
Array();
- Array(const Array &);
- Array &operator=(const Array &);
+ Array(const Array&);
+ Array& operator=(const Array&);
uint8_t data_[1];
};
-template<class U, uint16_t N>
-FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U, N> make_span(Array<U, N> &arr)
+template <class U, uint16_t N>
+FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U, N> make_span(Array<U, N>& arr)
FLATBUFFERS_NOEXCEPT {
static_assert(
Array<U, N>::is_span_observable,
@@ -190,26 +194,26 @@
return span<U, N>(arr.data(), N);
}
-template<class U, uint16_t N>
+template <class U, uint16_t N>
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const U, N> make_span(
- const Array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
+ const Array<U, N>& arr) FLATBUFFERS_NOEXCEPT {
static_assert(
Array<U, N>::is_span_observable,
"wrong type U, only plain struct, LE-scalar, or byte types are allowed");
return span<const U, N>(arr.data(), N);
}
-template<class U, uint16_t N>
+template <class U, uint16_t N>
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<uint8_t, sizeof(U) * N>
-make_bytes_span(Array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
+make_bytes_span(Array<U, N>& arr) FLATBUFFERS_NOEXCEPT {
static_assert(Array<U, N>::is_span_observable,
"internal error, Array<T> might hold only scalars or structs");
return span<uint8_t, sizeof(U) * N>(arr.Data(), sizeof(U) * N);
}
-template<class U, uint16_t N>
+template <class U, uint16_t N>
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const uint8_t, sizeof(U) * N>
-make_bytes_span(const Array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
+make_bytes_span(const Array<U, N>& arr) FLATBUFFERS_NOEXCEPT {
static_assert(Array<U, N>::is_span_observable,
"internal error, Array<T> might hold only scalars or structs");
return span<const uint8_t, sizeof(U) * N>(arr.Data(), sizeof(U) * N);
@@ -218,31 +222,31 @@
// Cast a raw T[length] to a raw flatbuffers::Array<T, length>
// without endian conversion. Use with care.
// TODO: move these Cast-methods to `internal` namespace.
-template<typename T, uint16_t length>
-Array<T, length> &CastToArray(T (&arr)[length]) {
- return *reinterpret_cast<Array<T, length> *>(arr);
+template <typename T, uint16_t length>
+Array<T, length>& CastToArray(T (&arr)[length]) {
+ return *reinterpret_cast<Array<T, length>*>(arr);
}
-template<typename T, uint16_t length>
-const Array<T, length> &CastToArray(const T (&arr)[length]) {
- return *reinterpret_cast<const Array<T, length> *>(arr);
+template <typename T, uint16_t length>
+const Array<T, length>& CastToArray(const T (&arr)[length]) {
+ return *reinterpret_cast<const Array<T, length>*>(arr);
}
-template<typename E, typename T, uint16_t length>
-Array<E, length> &CastToArrayOfEnum(T (&arr)[length]) {
+template <typename E, typename T, uint16_t length>
+Array<E, length>& CastToArrayOfEnum(T (&arr)[length]) {
static_assert(sizeof(E) == sizeof(T), "invalid enum type E");
- return *reinterpret_cast<Array<E, length> *>(arr);
+ return *reinterpret_cast<Array<E, length>*>(arr);
}
-template<typename E, typename T, uint16_t length>
-const Array<E, length> &CastToArrayOfEnum(const T (&arr)[length]) {
+template <typename E, typename T, uint16_t length>
+const Array<E, length>& CastToArrayOfEnum(const T (&arr)[length]) {
static_assert(sizeof(E) == sizeof(T), "invalid enum type E");
- return *reinterpret_cast<const Array<E, length> *>(arr);
+ return *reinterpret_cast<const Array<E, length>*>(arr);
}
-template<typename T, uint16_t length>
-bool operator==(const Array<T, length> &lhs,
- const Array<T, length> &rhs) noexcept {
+template <typename T, uint16_t length>
+bool operator==(const Array<T, length>& lhs,
+ const Array<T, length>& rhs) noexcept {
return std::addressof(lhs) == std::addressof(rhs) ||
(lhs.size() == rhs.size() &&
std::memcmp(lhs.Data(), rhs.Data(), rhs.size() * sizeof(T)) == 0);
diff --git a/include/flatbuffers/buffer.h b/include/flatbuffers/buffer.h
index 00c07c7..154d187 100644
--- a/include/flatbuffers/buffer.h
+++ b/include/flatbuffers/buffer.h
@@ -26,7 +26,8 @@
// Wrapper for uoffset_t to allow safe template specialization.
// Value is allowed to be 0 to indicate a null object (see e.g. AddOffset).
-template<typename T = void> struct Offset {
+template <typename T = void>
+struct Offset {
// The type of offset to use.
typedef uoffset_t offset_type;
@@ -37,12 +38,14 @@
bool IsNull() const { return !o; }
};
-template<typename T> struct is_specialisation_of_Offset : false_type {};
-template<typename T>
+template <typename T>
+struct is_specialisation_of_Offset : false_type {};
+template <typename T>
struct is_specialisation_of_Offset<Offset<T>> : true_type {};
// Wrapper for uoffset64_t Offsets.
-template<typename T = void> struct Offset64 {
+template <typename T = void>
+struct Offset64 {
// The type of offset to use.
typedef uoffset64_t offset_type;
@@ -53,8 +56,9 @@
bool IsNull() const { return !o; }
};
-template<typename T> struct is_specialisation_of_Offset64 : false_type {};
-template<typename T>
+template <typename T>
+struct is_specialisation_of_Offset64 : false_type {};
+template <typename T>
struct is_specialisation_of_Offset64<Offset64<T>> : true_type {};
// Litmus check for ensuring the Offsets are the expected size.
@@ -64,12 +68,13 @@
inline void EndianCheck() {
int endiantest = 1;
// If this fails, see FLATBUFFERS_LITTLEENDIAN above.
- FLATBUFFERS_ASSERT(*reinterpret_cast<char *>(&endiantest) ==
+ FLATBUFFERS_ASSERT(*reinterpret_cast<char*>(&endiantest) ==
FLATBUFFERS_LITTLEENDIAN);
(void)endiantest;
}
-template<typename T> FLATBUFFERS_CONSTEXPR size_t AlignOf() {
+template <typename T>
+FLATBUFFERS_CONSTEXPR size_t AlignOf() {
// clang-format off
#ifdef _MSC_VER
return __alignof(T);
@@ -85,8 +90,8 @@
// Lexicographically compare two strings (possibly containing nulls), and
// return true if the first is less than the second.
-static inline bool StringLessThan(const char *a_data, uoffset_t a_size,
- const char *b_data, uoffset_t b_size) {
+static inline bool StringLessThan(const char* a_data, uoffset_t a_size,
+ const char* b_data, uoffset_t b_size) {
const auto cmp = memcmp(a_data, b_data, (std::min)(a_size, b_size));
return cmp == 0 ? a_size < b_size : cmp < 0;
}
@@ -99,42 +104,43 @@
// return type like this.
// The typedef is for the convenience of callers of this function
// (avoiding the need for a trailing return decltype)
-template<typename T, typename Enable = void> struct IndirectHelper {
+template <typename T, typename Enable = void>
+struct IndirectHelper {
typedef T return_type;
typedef T mutable_return_type;
static const size_t element_stride = sizeof(T);
- static return_type Read(const uint8_t *p, const size_t i) {
- return EndianScalar((reinterpret_cast<const T *>(p))[i]);
+ static return_type Read(const uint8_t* p, const size_t i) {
+ return EndianScalar((reinterpret_cast<const T*>(p))[i]);
}
- static mutable_return_type Read(uint8_t *p, const size_t i) {
+ static mutable_return_type Read(uint8_t* p, const size_t i) {
return reinterpret_cast<mutable_return_type>(
- Read(const_cast<const uint8_t *>(p), i));
+ Read(const_cast<const uint8_t*>(p), i));
}
};
// For vector of Offsets.
-template<typename T, template<typename> class OffsetT>
+template <typename T, template <typename> class OffsetT>
struct IndirectHelper<OffsetT<T>> {
- typedef const T *return_type;
- typedef T *mutable_return_type;
+ typedef const T* return_type;
+ typedef T* mutable_return_type;
typedef typename OffsetT<T>::offset_type offset_type;
static const offset_type element_stride = sizeof(offset_type);
- static return_type Read(const uint8_t *const p, const offset_type i) {
+ static return_type Read(const uint8_t* const p, const offset_type i) {
// Offsets are relative to themselves, so first update the pointer to
// point to the offset location.
- const uint8_t *const offset_location = p + i * element_stride;
+ const uint8_t* const offset_location = p + i * element_stride;
// Then read the scalar value of the offset (which may be 32 or 64-bits) and
// then determine the relative location from the offset location.
return reinterpret_cast<return_type>(
offset_location + ReadScalar<offset_type>(offset_location));
}
- static mutable_return_type Read(uint8_t *const p, const offset_type i) {
+ static mutable_return_type Read(uint8_t* const p, const offset_type i) {
// Offsets are relative to themselves, so first update the pointer to
// point to the offset location.
- uint8_t *const offset_location = p + i * element_stride;
+ uint8_t* const offset_location = p + i * element_stride;
// Then read the scalar value of the offset (which may be 32 or 64-bits) and
// then determine the relative location from the offset location.
@@ -144,7 +150,7 @@
};
// For vector of structs.
-template<typename T>
+template <typename T>
struct IndirectHelper<
T, typename std::enable_if<
!std::is_scalar<typename std::remove_pointer<T>::type>::value &&
@@ -155,15 +161,15 @@
pointee_type;
public:
- typedef const pointee_type *return_type;
- typedef pointee_type *mutable_return_type;
+ typedef const pointee_type* return_type;
+ typedef pointee_type* mutable_return_type;
static const size_t element_stride = sizeof(pointee_type);
- static return_type Read(const uint8_t *const p, const size_t i) {
+ static return_type Read(const uint8_t* const p, const size_t i) {
// Structs are stored inline, relative to the first struct pointer.
return reinterpret_cast<return_type>(p + i * element_stride);
}
- static mutable_return_type Read(uint8_t *const p, const size_t i) {
+ static mutable_return_type Read(uint8_t* const p, const size_t i) {
// Structs are stored inline, relative to the first struct pointer.
return reinterpret_cast<mutable_return_type>(p + i * element_stride);
}
@@ -176,14 +182,14 @@
/// This function is UNDEFINED for FlatBuffers whose schema does not include
/// a file_identifier (likely points at padding or the start of a the root
/// vtable).
-inline const char *GetBufferIdentifier(const void *buf,
+inline const char* GetBufferIdentifier(const void* buf,
bool size_prefixed = false) {
- return reinterpret_cast<const char *>(buf) +
+ return reinterpret_cast<const char*>(buf) +
((size_prefixed) ? 2 * sizeof(uoffset_t) : sizeof(uoffset_t));
}
// Helper to see if the identifier in a buffer has the expected value.
-inline bool BufferHasIdentifier(const void *buf, const char *identifier,
+inline bool BufferHasIdentifier(const void* buf, const char* identifier,
bool size_prefixed = false) {
return strncmp(GetBufferIdentifier(buf, size_prefixed), identifier,
flatbuffers::kFileIdentifierLength) == 0;
@@ -191,26 +197,27 @@
/// @cond FLATBUFFERS_INTERNAL
// Helpers to get a typed pointer to the root object contained in the buffer.
-template<typename T> T *GetMutableRoot(void *buf) {
+template <typename T>
+T* GetMutableRoot(void* buf) {
if (!buf) return nullptr;
EndianCheck();
- return reinterpret_cast<T *>(
- reinterpret_cast<uint8_t *>(buf) +
- EndianScalar(*reinterpret_cast<uoffset_t *>(buf)));
+ return reinterpret_cast<T*>(reinterpret_cast<uint8_t*>(buf) +
+ EndianScalar(*reinterpret_cast<uoffset_t*>(buf)));
}
-template<typename T, typename SizeT = uoffset_t>
-T *GetMutableSizePrefixedRoot(void *buf) {
- return GetMutableRoot<T>(reinterpret_cast<uint8_t *>(buf) + sizeof(SizeT));
+template <typename T, typename SizeT = uoffset_t>
+T* GetMutableSizePrefixedRoot(void* buf) {
+ return GetMutableRoot<T>(reinterpret_cast<uint8_t*>(buf) + sizeof(SizeT));
}
-template<typename T> const T *GetRoot(const void *buf) {
- return GetMutableRoot<T>(const_cast<void *>(buf));
+template <typename T>
+const T* GetRoot(const void* buf) {
+ return GetMutableRoot<T>(const_cast<void*>(buf));
}
-template<typename T, typename SizeT = uoffset_t>
-const T *GetSizePrefixedRoot(const void *buf) {
- return GetRoot<T>(reinterpret_cast<const uint8_t *>(buf) + sizeof(SizeT));
+template <typename T, typename SizeT = uoffset_t>
+const T* GetSizePrefixedRoot(const void* buf) {
+ return GetRoot<T>(reinterpret_cast<const uint8_t*>(buf) + sizeof(SizeT));
}
} // namespace flatbuffers
diff --git a/include/flatbuffers/buffer_ref.h b/include/flatbuffers/buffer_ref.h
index f70941f..746903e 100644
--- a/include/flatbuffers/buffer_ref.h
+++ b/include/flatbuffers/buffer_ref.h
@@ -27,23 +27,24 @@
// A BufferRef does not own its buffer.
struct BufferRefBase {}; // for std::is_base_of
-template<typename T> struct BufferRef : BufferRefBase {
+template <typename T>
+struct BufferRef : BufferRefBase {
BufferRef() : buf(nullptr), len(0), must_free(false) {}
- BufferRef(uint8_t *_buf, uoffset_t _len)
+ BufferRef(uint8_t* _buf, uoffset_t _len)
: buf(_buf), len(_len), must_free(false) {}
~BufferRef() {
if (must_free) free(buf);
}
- const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); }
+ const T* GetRoot() const { return flatbuffers::GetRoot<T>(buf); }
bool Verify() {
Verifier verifier(buf, len);
return verifier.VerifyBuffer<T>(nullptr);
}
- uint8_t *buf;
+ uint8_t* buf;
uoffset_t len;
bool must_free;
};
diff --git a/include/flatbuffers/code_generator.h b/include/flatbuffers/code_generator.h
index 2971e55..cc4df7f 100644
--- a/include/flatbuffers/code_generator.h
+++ b/include/flatbuffers/code_generator.h
@@ -45,13 +45,13 @@
// Generate code from the provided `parser`.
//
// DEPRECATED: prefer using the other overload of GenerateCode for bfbs.
- virtual Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) = 0;
+ virtual Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) = 0;
// Generate code from the provided `parser` and place it in the output.
- virtual Status GenerateCodeString(const Parser &parser,
- const std::string &filename,
- std::string &output) {
+ virtual Status GenerateCodeString(const Parser& parser,
+ const std::string& filename,
+ std::string& output) {
(void)parser;
(void)filename;
(void)output;
@@ -60,18 +60,18 @@
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
- virtual Status GenerateCode(const uint8_t *buffer, int64_t length,
- const CodeGenOptions &options) = 0;
+ virtual Status GenerateCode(const uint8_t* buffer, int64_t length,
+ const CodeGenOptions& options) = 0;
- virtual Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) = 0;
+ virtual Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) = 0;
- virtual Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) = 0;
+ virtual Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) = 0;
- virtual Status GenerateRootFile(const Parser &parser,
- const std::string &path) = 0;
+ virtual Status GenerateRootFile(const Parser& parser,
+ const std::string& path) = 0;
virtual bool IsSchemaOnly() const = 0;
@@ -88,8 +88,8 @@
private:
// Copying is not supported.
- CodeGenerator(const CodeGenerator &) = delete;
- CodeGenerator &operator=(const CodeGenerator &) = delete;
+ CodeGenerator(const CodeGenerator&) = delete;
+ CodeGenerator& operator=(const CodeGenerator&) = delete;
};
} // namespace flatbuffers
diff --git a/include/flatbuffers/code_generators.h b/include/flatbuffers/code_generators.h
index fc030d4..d284ac5 100644
--- a/include/flatbuffers/code_generators.h
+++ b/include/flatbuffers/code_generators.h
@@ -51,11 +51,11 @@
// Associates a key with a value. All subsequent calls to operator+=, where
// the specified key is contained in {{ and }} delimiters will be replaced by
// the given value.
- void SetValue(const std::string &key, const std::string &value) {
+ void SetValue(const std::string& key, const std::string& value) {
value_map_[key] = value;
}
- std::string GetValue(const std::string &key) const {
+ std::string GetValue(const std::string& key) const {
const auto it = value_map_.find(key);
return it == value_map_.end() ? "" : it->second;
}
@@ -76,7 +76,7 @@
if (cur_ident_lvl_) cur_ident_lvl_--;
}
- void SetPadding(const std::string &padding) { pad_ = padding; }
+ void SetPadding(const std::string& padding) { pad_ = padding; }
private:
std::map<std::string, std::string> value_map_;
@@ -86,24 +86,24 @@
bool ignore_ident_;
// Add ident padding (tab or space) based on ident level
- void AppendIdent(std::stringstream &stream);
+ void AppendIdent(std::stringstream& stream);
};
class BaseGenerator {
public:
virtual bool generate() = 0;
- static std::string NamespaceDir(const Parser &parser, const std::string &path,
- const Namespace &ns,
+ static std::string NamespaceDir(const Parser& parser, const std::string& path,
+ const Namespace& ns,
const bool dasherize = false);
- std::string GeneratedFileName(const std::string &path,
- const std::string &file_name,
- const IDLOptions &options) const;
+ std::string GeneratedFileName(const std::string& path,
+ const std::string& file_name,
+ const IDLOptions& options) const;
protected:
- BaseGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name, std::string qualifying_start,
+ BaseGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name, std::string qualifying_start,
std::string qualifying_separator, std::string default_extension)
: parser_(parser),
path_(path),
@@ -114,84 +114,84 @@
virtual ~BaseGenerator() {}
// No copy/assign.
- BaseGenerator &operator=(const BaseGenerator &);
- BaseGenerator(const BaseGenerator &);
+ BaseGenerator& operator=(const BaseGenerator&);
+ BaseGenerator(const BaseGenerator&);
- std::string NamespaceDir(const Namespace &ns,
+ std::string NamespaceDir(const Namespace& ns,
const bool dasherize = false) const;
- static const char *FlatBuffersGeneratedWarning();
+ static const char* FlatBuffersGeneratedWarning();
- static std::string FullNamespace(const char *separator, const Namespace &ns);
+ static std::string FullNamespace(const char* separator, const Namespace& ns);
- static std::string LastNamespacePart(const Namespace &ns);
+ static std::string LastNamespacePart(const Namespace& ns);
// tracks the current namespace for early exit in WrapInNameSpace
// c++, java and csharp returns a different namespace from
// the following default (no early exit, always fully qualify),
// which works for js and php
- virtual const Namespace *CurrentNameSpace() const { return nullptr; }
+ virtual const Namespace* CurrentNameSpace() const { return nullptr; }
// Ensure that a type is prefixed with its namespace even within
// its own namespace to avoid conflict between generated method
// names and similarly named classes or structs
- std::string WrapInNameSpace(const Namespace *ns,
- const std::string &name) const;
+ std::string WrapInNameSpace(const Namespace* ns,
+ const std::string& name) const;
- std::string WrapInNameSpace(const Definition &def,
- const std::string &suffix = "") const;
+ std::string WrapInNameSpace(const Definition& def,
+ const std::string& suffix = "") const;
- std::string GetNameSpace(const Definition &def) const;
+ std::string GetNameSpace(const Definition& def) const;
- const Parser &parser_;
- const std::string &path_;
- const std::string &file_name_;
+ const Parser& parser_;
+ const std::string& path_;
+ const std::string& file_name_;
const std::string qualifying_start_;
const std::string qualifying_separator_;
const std::string default_extension_;
};
struct CommentConfig {
- const char *first_line;
- const char *content_line_prefix;
- const char *last_line;
+ const char* first_line;
+ const char* content_line_prefix;
+ const char* last_line;
};
-extern void GenComment(const std::vector<std::string> &dc,
- std::string *code_ptr, const CommentConfig *config,
- const char *prefix = "");
+extern void GenComment(const std::vector<std::string>& dc,
+ std::string* code_ptr, const CommentConfig* config,
+ const char* prefix = "");
class FloatConstantGenerator {
public:
virtual ~FloatConstantGenerator() {}
- std::string GenFloatConstant(const FieldDef &field) const;
+ std::string GenFloatConstant(const FieldDef& field) const;
private:
- virtual std::string Value(double v, const std::string &src) const = 0;
+ virtual std::string Value(double v, const std::string& src) const = 0;
virtual std::string Inf(double v) const = 0;
virtual std::string NaN(double v) const = 0;
- virtual std::string Value(float v, const std::string &src) const = 0;
+ virtual std::string Value(float v, const std::string& src) const = 0;
virtual std::string Inf(float v) const = 0;
virtual std::string NaN(float v) const = 0;
- template<typename T>
- std::string GenFloatConstantImpl(const FieldDef &field) const;
+ template <typename T>
+ std::string GenFloatConstantImpl(const FieldDef& field) const;
};
class SimpleFloatConstantGenerator : public FloatConstantGenerator {
public:
- SimpleFloatConstantGenerator(const char *nan_number,
- const char *pos_inf_number,
- const char *neg_inf_number);
+ SimpleFloatConstantGenerator(const char* nan_number,
+ const char* pos_inf_number,
+ const char* neg_inf_number);
private:
std::string Value(double v,
- const std::string &src) const FLATBUFFERS_OVERRIDE;
+ const std::string& src) const FLATBUFFERS_OVERRIDE;
std::string Inf(double v) const FLATBUFFERS_OVERRIDE;
std::string NaN(double v) const FLATBUFFERS_OVERRIDE;
- std::string Value(float v, const std::string &src) const FLATBUFFERS_OVERRIDE;
+ std::string Value(float v, const std::string& src) const FLATBUFFERS_OVERRIDE;
std::string Inf(float v) const FLATBUFFERS_OVERRIDE;
std::string NaN(float v) const FLATBUFFERS_OVERRIDE;
@@ -203,24 +203,24 @@
// C++, C#, Java like generator.
class TypedFloatConstantGenerator : public FloatConstantGenerator {
public:
- TypedFloatConstantGenerator(const char *double_prefix,
- const char *single_prefix, const char *nan_number,
- const char *pos_inf_number,
- const char *neg_inf_number = "");
+ TypedFloatConstantGenerator(const char* double_prefix,
+ const char* single_prefix, const char* nan_number,
+ const char* pos_inf_number,
+ const char* neg_inf_number = "");
private:
std::string Value(double v,
- const std::string &src) const FLATBUFFERS_OVERRIDE;
+ const std::string& src) const FLATBUFFERS_OVERRIDE;
std::string Inf(double v) const FLATBUFFERS_OVERRIDE;
std::string NaN(double v) const FLATBUFFERS_OVERRIDE;
- std::string Value(float v, const std::string &src) const FLATBUFFERS_OVERRIDE;
+ std::string Value(float v, const std::string& src) const FLATBUFFERS_OVERRIDE;
std::string Inf(float v) const FLATBUFFERS_OVERRIDE;
std::string NaN(float v) const FLATBUFFERS_OVERRIDE;
- std::string MakeNaN(const std::string &prefix) const;
- std::string MakeInf(bool neg, const std::string &prefix) const;
+ std::string MakeNaN(const std::string& prefix) const;
+ std::string MakeInf(bool neg, const std::string& prefix) const;
const std::string double_prefix_;
const std::string single_prefix_;
@@ -229,9 +229,9 @@
const std::string neg_inf_number_;
};
-std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
- const std::string &path,
- const std::string &file_name);
+std::string JavaCSharpMakeRule(const bool java, const Parser& parser,
+ const std::string& path,
+ const std::string& file_name);
} // namespace flatbuffers
diff --git a/include/flatbuffers/default_allocator.h b/include/flatbuffers/default_allocator.h
index d472412..d1cab08 100644
--- a/include/flatbuffers/default_allocator.h
+++ b/include/flatbuffers/default_allocator.h
@@ -25,32 +25,32 @@
// DefaultAllocator uses new/delete to allocate memory regions
class DefaultAllocator : public Allocator {
public:
- uint8_t *allocate(size_t size) FLATBUFFERS_OVERRIDE {
+ uint8_t* allocate(size_t size) FLATBUFFERS_OVERRIDE {
return new uint8_t[size];
}
- void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; }
+ void deallocate(uint8_t* p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; }
- static void dealloc(void *p, size_t) { delete[] static_cast<uint8_t *>(p); }
+ static void dealloc(void* p, size_t) { delete[] static_cast<uint8_t*>(p); }
};
// These functions allow for a null allocator to mean use the default allocator,
// as used by DetachedBuffer and vector_downward below.
// This is to avoid having a statically or dynamically allocated default
// allocator, or having to move it between the classes that may own it.
-inline uint8_t *Allocate(Allocator *allocator, size_t size) {
+inline uint8_t* Allocate(Allocator* allocator, size_t size) {
return allocator ? allocator->allocate(size)
: DefaultAllocator().allocate(size);
}
-inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) {
+inline void Deallocate(Allocator* allocator, uint8_t* p, size_t size) {
if (allocator)
allocator->deallocate(p, size);
else
DefaultAllocator().deallocate(p, size);
}
-inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p,
+inline uint8_t* ReallocateDownward(Allocator* allocator, uint8_t* old_p,
size_t old_size, size_t new_size,
size_t in_use_back, size_t in_use_front) {
return allocator ? allocator->reallocate_downward(old_p, old_size, new_size,
diff --git a/include/flatbuffers/detached_buffer.h b/include/flatbuffers/detached_buffer.h
index 36d3f6d..0577a42 100644
--- a/include/flatbuffers/detached_buffer.h
+++ b/include/flatbuffers/detached_buffer.h
@@ -36,8 +36,8 @@
cur_(nullptr),
size_(0) {}
- DetachedBuffer(Allocator *allocator, bool own_allocator, uint8_t *buf,
- size_t reserved, uint8_t *cur, size_t sz)
+ DetachedBuffer(Allocator* allocator, bool own_allocator, uint8_t* buf,
+ size_t reserved, uint8_t* cur, size_t sz)
: allocator_(allocator),
own_allocator_(own_allocator),
buf_(buf),
@@ -45,7 +45,7 @@
cur_(cur),
size_(sz) {}
- DetachedBuffer(DetachedBuffer &&other) noexcept
+ DetachedBuffer(DetachedBuffer&& other) noexcept
: allocator_(other.allocator_),
own_allocator_(other.own_allocator_),
buf_(other.buf_),
@@ -55,7 +55,7 @@
other.reset();
}
- DetachedBuffer &operator=(DetachedBuffer &&other) noexcept {
+ DetachedBuffer& operator=(DetachedBuffer&& other) noexcept {
if (this == &other) return *this;
destroy();
@@ -74,33 +74,35 @@
~DetachedBuffer() { destroy(); }
- const uint8_t *data() const { return cur_; }
+ const uint8_t* data() const { return cur_; }
- uint8_t *data() { return cur_; }
+ uint8_t* data() { return cur_; }
size_t size() const { return size_; }
- uint8_t *begin() { return data(); }
- const uint8_t *begin() const { return data(); }
- uint8_t *end() { return data() + size(); }
- const uint8_t *end() const { return data() + size(); }
+ uint8_t* begin() { return data(); }
+ const uint8_t* begin() const { return data(); }
+ uint8_t* end() { return data() + size(); }
+ const uint8_t* end() const { return data() + size(); }
// These may change access mode, leave these at end of public section
- FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer &other));
+ FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer& other));
FLATBUFFERS_DELETE_FUNC(
- DetachedBuffer &operator=(const DetachedBuffer &other));
+ DetachedBuffer& operator=(const DetachedBuffer& other));
protected:
- Allocator *allocator_;
+ Allocator* allocator_;
bool own_allocator_;
- uint8_t *buf_;
+ uint8_t* buf_;
size_t reserved_;
- uint8_t *cur_;
+ uint8_t* cur_;
size_t size_;
inline void destroy() {
if (buf_) Deallocate(allocator_, buf_, reserved_);
- if (own_allocator_ && allocator_) { delete allocator_; }
+ if (own_allocator_ && allocator_) {
+ delete allocator_;
+ }
reset();
}
diff --git a/include/flatbuffers/file_manager.h b/include/flatbuffers/file_manager.h
index 069df5b..0941fae 100644
--- a/include/flatbuffers/file_manager.h
+++ b/include/flatbuffers/file_manager.h
@@ -31,16 +31,16 @@
FileManager() = default;
virtual ~FileManager() = default;
- virtual bool SaveFile(const std::string &absolute_file_name,
- const std::string &content) = 0;
+ virtual bool SaveFile(const std::string& absolute_file_name,
+ const std::string& content) = 0;
- virtual bool LoadFile(const std::string &absolute_file_name,
- std::string *buf) = 0;
+ virtual bool LoadFile(const std::string& absolute_file_name,
+ std::string* buf) = 0;
private:
// Copying is not supported.
- FileManager(const FileManager &) = delete;
- FileManager &operator=(const FileManager &) = delete;
+ FileManager(const FileManager&) = delete;
+ FileManager& operator=(const FileManager&) = delete;
};
} // namespace flatbuffers
diff --git a/include/flatbuffers/flatbuffer_builder.h b/include/flatbuffers/flatbuffer_builder.h
index 9ceca82..9eea6ba 100644
--- a/include/flatbuffers/flatbuffer_builder.h
+++ b/include/flatbuffers/flatbuffer_builder.h
@@ -50,19 +50,19 @@
return static_cast<voffset_t>(offset);
}
-template<typename T, typename Alloc = std::allocator<T>>
-const T *data(const std::vector<T, Alloc> &v) {
+template <typename T, typename Alloc = std::allocator<T>>
+const T* data(const std::vector<T, Alloc>& v) {
// Eventually the returned pointer gets passed down to memcpy, so
// we need it to be non-null to avoid undefined behavior.
static uint8_t t;
- return v.empty() ? reinterpret_cast<const T *>(&t) : &v.front();
+ return v.empty() ? reinterpret_cast<const T*>(&t) : &v.front();
}
-template<typename T, typename Alloc = std::allocator<T>>
-T *data(std::vector<T, Alloc> &v) {
+template <typename T, typename Alloc = std::allocator<T>>
+T* data(std::vector<T, Alloc>& v) {
// Eventually the returned pointer gets passed down to memcpy, so
// we need it to be non-null to avoid undefined behavior.
static uint8_t t;
- return v.empty() ? reinterpret_cast<T *>(&t) : &v.front();
+ return v.empty() ? reinterpret_cast<T*>(&t) : &v.front();
}
/// @addtogroup flatbuffers_cpp_api
@@ -74,7 +74,8 @@
/// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/
/// `CreateVector` functions. Do this is depth-first order to build up a tree to
/// the root. `Finish()` wraps up the buffer ready for transport.
-template<bool Is64Aware = false> class FlatBufferBuilderImpl {
+template <bool Is64Aware = false>
+class FlatBufferBuilderImpl {
public:
// This switches the size type of the builder, based on if its 64-bit aware
// (uoffset64_t) or not (uoffset_t).
@@ -93,7 +94,7 @@
/// types with custom alignment AND you wish to read the buffer in-place
/// directly after creation.
explicit FlatBufferBuilderImpl(
- size_t initial_size = 1024, Allocator *allocator = nullptr,
+ size_t initial_size = 1024, Allocator* allocator = nullptr,
bool own_allocator = false,
size_t buffer_minalign = AlignOf<largest_scalar_t>())
: buf_(initial_size, allocator, own_allocator, buffer_minalign,
@@ -112,7 +113,7 @@
}
/// @brief Move constructor for FlatBufferBuilder.
- FlatBufferBuilderImpl(FlatBufferBuilderImpl &&other) noexcept
+ FlatBufferBuilderImpl(FlatBufferBuilderImpl&& other) noexcept
: buf_(1024, nullptr, false, AlignOf<largest_scalar_t>(),
static_cast<SizeT>(Is64Aware ? FLATBUFFERS_MAX_64_BUFFER_SIZE
: FLATBUFFERS_MAX_BUFFER_SIZE)),
@@ -133,14 +134,14 @@
}
/// @brief Move assignment operator for FlatBufferBuilder.
- FlatBufferBuilderImpl &operator=(FlatBufferBuilderImpl &&other) noexcept {
+ FlatBufferBuilderImpl& operator=(FlatBufferBuilderImpl&& other) noexcept {
// Move construct a temporary and swap idiom
FlatBufferBuilderImpl temp(std::move(other));
Swap(temp);
return *this;
}
- void Swap(FlatBufferBuilderImpl &other) {
+ void Swap(FlatBufferBuilderImpl& other) {
using std::swap;
buf_.swap(other.buf_);
swap(num_field_loc, other.num_field_loc);
@@ -182,7 +183,7 @@
/// @brief The current size of the serialized buffer relative to the end of
/// the 32-bit region.
/// @return Returns an `uoffset_t` with the current size of the buffer.
- template<bool is_64 = Is64Aware>
+ template <bool is_64 = Is64Aware>
// Only enable this method for the 64-bit builder, as only that builder is
// concerned with the 32/64-bit boundary, and should be the one to bare any
// run time costs.
@@ -195,7 +196,7 @@
return static_cast<uoffset_t>(GetSize() - length_of_64_bit_region_);
}
- template<bool is_64 = Is64Aware>
+ template <bool is_64 = Is64Aware>
// Only enable this method for the 32-bit builder.
typename std::enable_if<!is_64, uoffset_t>::type GetSizeRelative32BitRegion()
const {
@@ -205,7 +206,7 @@
/// @brief Get the serialized buffer (after you call `Finish()`).
/// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the
/// buffer.
- uint8_t *GetBufferPointer() const {
+ uint8_t* GetBufferPointer() const {
Finished();
return buf_.data();
}
@@ -220,7 +221,7 @@
/// @brief Get a pointer to an unfinished buffer.
/// @return Returns a `uint8_t` pointer to the unfinished buffer.
- uint8_t *GetCurrentBufferPointer() const { return buf_.data(); }
+ uint8_t* GetCurrentBufferPointer() const { return buf_.data(); }
/// @brief Get the released DetachedBuffer.
/// @return A `DetachedBuffer` that owns the buffer and its allocator.
@@ -240,9 +241,9 @@
/// the serialized `FlatBuffer`.
/// @remark If the allocator is owned, it gets deleted when the destructor is
/// called.
- uint8_t *ReleaseRaw(size_t &size, size_t &offset) {
+ uint8_t* ReleaseRaw(size_t& size, size_t& offset) {
Finished();
- uint8_t *raw = buf_.release_raw(size, offset);
+ uint8_t* raw = buf_.release_raw(size, offset);
Clear();
return raw;
}
@@ -291,22 +292,23 @@
buf_.fill(PaddingBytes(buf_.size(), elem_size));
}
- void PushFlatBuffer(const uint8_t *bytes, size_t size) {
+ void PushFlatBuffer(const uint8_t* bytes, size_t size) {
PushBytes(bytes, size);
finished = true;
}
- void PushBytes(const uint8_t *bytes, size_t size) { buf_.push(bytes, size); }
+ void PushBytes(const uint8_t* bytes, size_t size) { buf_.push(bytes, size); }
void PopBytes(size_t amount) { buf_.pop(amount); }
- template<typename T> void AssertScalarT() {
+ template <typename T>
+ void AssertScalarT() {
// The code assumes power of 2 sizes and endian-swap-ability.
static_assert(flatbuffers::is_scalar<T>::value, "T must be a scalar type");
}
// Write a single aligned scalar to the buffer
- template<typename T, typename ReturnT = uoffset_t>
+ template <typename T, typename ReturnT = uoffset_t>
ReturnT PushElement(T element) {
AssertScalarT<T>();
Align(sizeof(T));
@@ -314,7 +316,7 @@
return CalculateOffset<ReturnT>();
}
- template<typename T, template<typename> class OffsetT = Offset>
+ template <typename T, template <typename> class OffsetT = Offset>
uoffset_t PushElement(OffsetT<T> off) {
// Special case for offsets: see ReferTo below.
return PushElement(ReferTo(off.o));
@@ -323,34 +325,41 @@
// When writing fields, we track where they are, so we can create correct
// vtables later.
void TrackField(voffset_t field, uoffset_t off) {
- FieldLoc fl = { off, field };
+ FieldLoc fl = {off, field};
buf_.scratch_push_small(fl);
num_field_loc++;
- if (field > max_voffset_) { max_voffset_ = field; }
+ if (field > max_voffset_) {
+ max_voffset_ = field;
+ }
}
// Like PushElement, but additionally tracks the field this represents.
- template<typename T> void AddElement(voffset_t field, T e, T def) {
+ template <typename T>
+ void AddElement(voffset_t field, T e, T def) {
// We don't serialize values equal to the default.
if (IsTheSameAs(e, def) && !force_defaults_) return;
TrackField(field, PushElement(e));
}
- template<typename T> void AddElement(voffset_t field, T e) {
+ template <typename T>
+ void AddElement(voffset_t field, T e) {
TrackField(field, PushElement(e));
}
- template<typename T> void AddOffset(voffset_t field, Offset<T> off) {
+ template <typename T>
+ void AddOffset(voffset_t field, Offset<T> off) {
if (off.IsNull()) return; // Don't store.
AddElement(field, ReferTo(off.o), static_cast<uoffset_t>(0));
}
- template<typename T> void AddOffset(voffset_t field, Offset64<T> off) {
+ template <typename T>
+ void AddOffset(voffset_t field, Offset64<T> off) {
if (off.IsNull()) return; // Don't store.
AddElement(field, ReferTo(off.o), static_cast<uoffset64_t>(0));
}
- template<typename T> void AddStruct(voffset_t field, const T *structptr) {
+ template <typename T>
+ void AddStruct(voffset_t field, const T* structptr) {
if (!structptr) return; // Default, don't store.
Align(AlignOf<T>());
buf_.push_small(*structptr);
@@ -380,12 +389,14 @@
return ReferTo(off, GetSize());
}
- template<typename T, typename T2> T ReferTo(const T off, const T2 size) {
+ template <typename T, typename T2>
+ T ReferTo(const T off, const T2 size) {
FLATBUFFERS_ASSERT(off && off <= size);
return size - off + static_cast<T>(sizeof(T));
}
- template<typename T> T ReferTo(const T off, const T size) {
+ template <typename T>
+ T ReferTo(const T off, const T size) {
FLATBUFFERS_ASSERT(off && off <= size);
return size - off + static_cast<T>(sizeof(T));
}
@@ -441,7 +452,7 @@
// Write the offsets into the table
for (auto it = buf_.scratch_end() - num_field_loc * sizeof(FieldLoc);
it < buf_.scratch_end(); it += sizeof(FieldLoc)) {
- auto field_location = reinterpret_cast<FieldLoc *>(it);
+ auto field_location = reinterpret_cast<FieldLoc*>(it);
const voffset_t pos =
static_cast<voffset_t>(vtable_offset_loc - field_location->off);
// If this asserts, it means you've set a field twice.
@@ -450,7 +461,7 @@
WriteScalar<voffset_t>(buf_.data() + field_location->id, pos);
}
ClearOffsets();
- auto vt1 = reinterpret_cast<voffset_t *>(buf_.data());
+ auto vt1 = reinterpret_cast<voffset_t*>(buf_.data());
auto vt1_size = ReadScalar<voffset_t>(vt1);
auto vt_use = GetSizeRelative32BitRegion();
// See if we already have generated a vtable with this exact same
@@ -458,8 +469,8 @@
if (dedup_vtables_) {
for (auto it = buf_.scratch_data(); it < buf_.scratch_end();
it += sizeof(uoffset_t)) {
- auto vt_offset_ptr = reinterpret_cast<uoffset_t *>(it);
- auto vt2 = reinterpret_cast<voffset_t *>(buf_.data_at(*vt_offset_ptr));
+ auto vt_offset_ptr = reinterpret_cast<uoffset_t*>(it);
+ auto vt2 = reinterpret_cast<voffset_t*>(buf_.data_at(*vt_offset_ptr));
auto vt2_size = ReadScalar<voffset_t>(vt2);
if (vt1_size != vt2_size || 0 != memcmp(vt2, vt1, vt1_size)) continue;
vt_use = *vt_offset_ptr;
@@ -490,8 +501,9 @@
// This checks a required field has been set in a given table that has
// just been constructed.
- template<typename T> void Required(Offset<T> table, voffset_t field) {
- auto table_ptr = reinterpret_cast<const Table *>(buf_.data_at(table.o));
+ template <typename T>
+ void Required(Offset<T> table, voffset_t field) {
+ auto table_ptr = reinterpret_cast<const Table*>(buf_.data_at(table.o));
bool ok = table_ptr->GetOptionalFieldOffset(field) != 0;
// If this fails, the caller will show what field needs to be set.
FLATBUFFERS_ASSERT(ok);
@@ -521,7 +533,8 @@
// Aligns such than when "len" bytes are written, an object of type `AlignT`
// can be written after it (forward in the buffer) without padding.
- template<typename AlignT> void PreAlign(size_t len) {
+ template <typename AlignT>
+ void PreAlign(size_t len) {
AssertScalarT<AlignT>();
PreAlign(len, AlignOf<AlignT>());
}
@@ -531,8 +544,8 @@
/// @param[in] str A const char pointer to the data to be stored as a string.
/// @param[in] len The number of bytes that should be stored from `str`.
/// @return Returns the offset in the buffer where the string starts.
- template<template<typename> class OffsetT = Offset>
- OffsetT<String> CreateString(const char *str, size_t len) {
+ template <template <typename> class OffsetT = Offset>
+ OffsetT<String> CreateString(const char* str, size_t len) {
CreateStringImpl(str, len);
return OffsetT<String>(
CalculateOffset<typename OffsetT<String>::offset_type>());
@@ -541,24 +554,24 @@
/// @brief Store a string in the buffer, which is null-terminated.
/// @param[in] str A const char pointer to a C-string to add to the buffer.
/// @return Returns the offset in the buffer where the string starts.
- template<template<typename> class OffsetT = Offset>
- OffsetT<String> CreateString(const char *str) {
+ template <template <typename> class OffsetT = Offset>
+ OffsetT<String> CreateString(const char* str) {
return CreateString<OffsetT>(str, strlen(str));
}
/// @brief Store a string in the buffer, which is null-terminated.
/// @param[in] str A char pointer to a C-string to add to the buffer.
/// @return Returns the offset in the buffer where the string starts.
- template<template<typename> class OffsetT = Offset>
- OffsetT<String> CreateString(char *str) {
+ template <template <typename> class OffsetT = Offset>
+ OffsetT<String> CreateString(char* str) {
return CreateString<OffsetT>(str, strlen(str));
}
/// @brief Store a string in the buffer, which can contain any binary data.
/// @param[in] str A const reference to a std::string to store in the buffer.
/// @return Returns the offset in the buffer where the string starts.
- template<template<typename> class OffsetT = Offset>
- OffsetT<String> CreateString(const std::string &str) {
+ template <template <typename> class OffsetT = Offset>
+ OffsetT<String> CreateString(const std::string& str) {
return CreateString<OffsetT>(str.c_str(), str.length());
}
@@ -577,8 +590,8 @@
/// @brief Store a string in the buffer, which can contain any binary data.
/// @param[in] str A const pointer to a `String` struct to add to the buffer.
/// @return Returns the offset in the buffer where the string starts
- template<template<typename> class OffsetT = Offset>
- OffsetT<String> CreateString(const String *str) {
+ template <template <typename> class OffsetT = Offset>
+ OffsetT<String> CreateString(const String* str) {
return str ? CreateString<OffsetT>(str->c_str(), str->size()) : 0;
}
@@ -586,11 +599,11 @@
/// @param[in] str A const reference to a std::string like type with support
/// of T::data() and T::length() to store in the buffer.
/// @return Returns the offset in the buffer where the string starts.
- template<template<typename> class OffsetT = Offset,
- // No need to explicitly declare the T type, let the compiler deduce
- // it.
- int &...ExplicitArgumentBarrier, typename T>
- OffsetT<String> CreateString(const T &str) {
+ template <template <typename> class OffsetT = Offset,
+ // No need to explicitly declare the T type, let the compiler deduce
+ // it.
+ int&... ExplicitArgumentBarrier, typename T>
+ OffsetT<String> CreateString(const T& str) {
return CreateString<OffsetT>(str.data(), str.length());
}
@@ -601,7 +614,7 @@
/// @param[in] str A const char pointer to the data to be stored as a string.
/// @param[in] len The number of bytes that should be stored from `str`.
/// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateSharedString(const char *str, size_t len) {
+ Offset<String> CreateSharedString(const char* str, size_t len) {
FLATBUFFERS_ASSERT(FLATBUFFERS_GENERAL_HEAP_ALLOC_OK);
if (!string_pool) {
string_pool = new StringOffsetMap(StringOffsetCompare(buf_));
@@ -640,7 +653,7 @@
/// stored on the heap, but only stores the numerical offsets.
/// @param[in] str A const char pointer to a C-string to add to the buffer.
/// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateSharedString(const char *str) {
+ Offset<String> CreateSharedString(const char* str) {
return CreateSharedString(str, strlen(str));
}
@@ -650,7 +663,7 @@
/// stored on the heap, but only stores the numerical offsets.
/// @param[in] str A const reference to a std::string to store in the buffer.
/// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateSharedString(const std::string &str) {
+ Offset<String> CreateSharedString(const std::string& str) {
return CreateSharedString(str.c_str(), str.length());
}
#endif
@@ -661,19 +674,20 @@
/// stored on the heap, but only stores the numerical offsets.
/// @param[in] str A const pointer to a `String` struct to add to the buffer.
/// @return Returns the offset in the buffer where the string starts
- Offset<String> CreateSharedString(const String *str) {
+ Offset<String> CreateSharedString(const String* str) {
return str ? CreateSharedString(str->c_str(), str->size()) : 0;
}
/// @cond FLATBUFFERS_INTERNAL
- template<typename LenT = uoffset_t, typename ReturnT = uoffset_t>
+ template <typename LenT = uoffset_t, typename ReturnT = uoffset_t>
ReturnT EndVector(size_t len) {
FLATBUFFERS_ASSERT(nested); // Hit if no corresponding StartVector.
nested = false;
return PushElement<LenT, ReturnT>(static_cast<LenT>(len));
}
- template<template<typename> class OffsetT = Offset, typename LenT = uint32_t>
+ template <template <typename> class OffsetT = Offset,
+ typename LenT = uint32_t>
void StartVector(size_t len, size_t elemsize, size_t alignment) {
NotNested();
nested = true;
@@ -683,8 +697,8 @@
PreAlign(len * elemsize, alignment); // Just in case elemsize > uoffset_t.
}
- template<typename T, template<typename> class OffsetT = Offset,
- typename LenT = uint32_t>
+ template <typename T, template <typename> class OffsetT = Offset,
+ typename LenT = uint32_t>
void StartVector(size_t len) {
return StartVector<OffsetT, LenT>(len, sizeof(T), AlignOf<T>());
}
@@ -701,7 +715,7 @@
PreAlign(len * elemsize, alignment);
}
- template<bool is_64 = Is64Aware>
+ template <bool is_64 = Is64Aware>
typename std::enable_if<is_64, void>::type ForceVectorAlignment64(
const size_t len, const size_t elemsize, const size_t alignment) {
// If you hit this assertion, you are trying to force alignment on a
@@ -733,9 +747,9 @@
/// @param[in] len The number of elements to serialize.
/// @return Returns a typed `TOffset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, template<typename...> class OffsetT = Offset,
- template<typename...> class VectorT = Vector>
- OffsetT<VectorT<T>> CreateVector(const T *v, size_t len) {
+ template <typename T, template <typename...> class OffsetT = Offset,
+ template <typename...> class VectorT = Vector>
+ OffsetT<VectorT<T>> CreateVector(const T* v, size_t len) {
// The type of the length field in the vector.
typedef typename VectorT<T>::size_type LenT;
typedef typename OffsetT<VectorT<T>>::offset_type offset_type;
@@ -768,7 +782,8 @@
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, class C> Offset<Vector<T>> CreateVector(const C &array) {
+ template <typename T, class C>
+ Offset<Vector<T>> CreateVector(const C& array) {
return CreateVector(array.data(), array.size());
}
@@ -777,15 +792,17 @@
/// @param[in] v The value of the initializer list.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T>
+ template <typename T>
Offset<Vector<T>> CreateVector(std::initializer_list<T> v) {
return CreateVector(v.begin(), v.size());
}
- template<typename T>
- Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
+ template <typename T>
+ Offset<Vector<Offset<T>>> CreateVector(const Offset<T>* v, size_t len) {
StartVector<Offset<T>>(len);
- for (auto i = len; i > 0;) { PushElement(v[--i]); }
+ for (auto i = len; i > 0;) {
+ PushElement(v[--i]);
+ }
return Offset<Vector<Offset<T>>>(EndVector(len));
}
@@ -795,21 +812,21 @@
/// buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, typename Alloc = std::allocator<T>>
- Offset<Vector<T>> CreateVector(const std::vector<T, Alloc> &v) {
+ template <typename T, typename Alloc = std::allocator<T>>
+ Offset<Vector<T>> CreateVector(const std::vector<T, Alloc>& v) {
return CreateVector(data(v), v.size());
}
- template<template<typename...> class VectorT = Vector64,
- int &...ExplicitArgumentBarrier, typename T>
- Offset64<VectorT<T>> CreateVector64(const std::vector<T> &v) {
+ template <template <typename...> class VectorT = Vector64,
+ int&... ExplicitArgumentBarrier, typename T>
+ Offset64<VectorT<T>> CreateVector64(const std::vector<T>& v) {
return CreateVector<T, Offset64, VectorT>(data(v), v.size());
}
// vector<bool> may be implemented using a bit-set, so we can't access it as
// an array. Instead, read elements manually.
// Background: https://isocpp.org/blog/2012/11/on-vectorbool
- Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) {
+ Offset<Vector<uint8_t>> CreateVector(const std::vector<bool>& v) {
StartVector<uint8_t>(v.size());
for (auto i = v.size(); i > 0;) {
PushElement(static_cast<uint8_t>(v[--i]));
@@ -824,9 +841,9 @@
/// returns any type that you can construct a FlatBuffers vector out of.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T>
+ template <typename T>
Offset<Vector<T>> CreateVector(size_t vector_size,
- const std::function<T(size_t i)> &f) {
+ const std::function<T(size_t i)>& f) {
FLATBUFFERS_ASSERT(FLATBUFFERS_GENERAL_HEAP_ALLOC_OK);
std::vector<T> elems(vector_size);
for (size_t i = 0; i < vector_size; i++) elems[i] = f(i);
@@ -844,8 +861,8 @@
/// @param state State passed to f.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, typename F, typename S>
- Offset<Vector<T>> CreateVector(size_t vector_size, F f, S *state) {
+ template <typename T, typename F, typename S>
+ Offset<Vector<T>> CreateVector(size_t vector_size, F f, S* state) {
FLATBUFFERS_ASSERT(FLATBUFFERS_GENERAL_HEAP_ALLOC_OK);
std::vector<T> elems(vector_size);
for (size_t i = 0; i < vector_size; i++) elems[i] = f(i, state);
@@ -860,10 +877,10 @@
/// buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename StringType = std::string,
- typename Alloc = std::allocator<StringType>>
+ template <typename StringType = std::string,
+ typename Alloc = std::allocator<StringType>>
Offset<Vector<Offset<String>>> CreateVectorOfStrings(
- const std::vector<StringType, Alloc> &v) {
+ const std::vector<StringType, Alloc>& v) {
return CreateVectorOfStrings(v.cbegin(), v.cend());
}
@@ -873,7 +890,7 @@
/// @param end The ending iterator of the collection
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<class It>
+ template <class It>
Offset<Vector<Offset<String>>> CreateVectorOfStrings(It begin, It end) {
auto distance = std::distance(begin, end);
FLATBUFFERS_ASSERT(distance >= 0);
@@ -890,7 +907,7 @@
for (size_t i = 1; i <= size; i++) {
// Note we re-evaluate the buf location each iteration to account for any
// underlying buffer resizing that may occur.
- PushElement(*reinterpret_cast<Offset<String> *>(
+ PushElement(*reinterpret_cast<Offset<String>*>(
buf_.scratch_end() - i * sizeof(Offset<String>)));
}
buf_.scratch_pop(scratch_buffer_usage);
@@ -904,18 +921,18 @@
/// @param[in] len The number of elements to serialize.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, template<typename...> class OffsetT = Offset,
- template<typename...> class VectorT = Vector>
- OffsetT<VectorT<const T *>> CreateVectorOfStructs(const T *v, size_t len) {
+ template <typename T, template <typename...> class OffsetT = Offset,
+ template <typename...> class VectorT = Vector>
+ OffsetT<VectorT<const T*>> CreateVectorOfStructs(const T* v, size_t len) {
// The type of the length field in the vector.
typedef typename VectorT<T>::size_type LenT;
- typedef typename OffsetT<VectorT<const T *>>::offset_type offset_type;
+ typedef typename OffsetT<VectorT<const T*>>::offset_type offset_type;
StartVector<OffsetT, LenT>(len, sizeof(T), AlignOf<T>());
if (len > 0) {
- PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
+ PushBytes(reinterpret_cast<const uint8_t*>(v), sizeof(T) * len);
}
- return OffsetT<VectorT<const T *>>(EndVector<LenT, offset_type>(len));
+ return OffsetT<VectorT<const T*>>(EndVector<LenT, offset_type>(len));
}
/// @brief Serialize an array of structs into a FlatBuffer `vector`.
@@ -926,10 +943,10 @@
/// where the vector is stored.
/// This is mostly useful when flatbuffers are generated with mutation
/// accessors.
- template<typename T>
- Offset<Vector<const T *>> CreateVectorOfStructs(
- size_t vector_size, const std::function<void(size_t i, T *)> &filler) {
- T *structs = StartVectorOfStructs<T>(vector_size);
+ template <typename T>
+ Offset<Vector<const T*>> CreateVectorOfStructs(
+ size_t vector_size, const std::function<void(size_t i, T*)>& filler) {
+ T* structs = StartVectorOfStructs<T>(vector_size);
for (size_t i = 0; i < vector_size; i++) {
filler(i, structs);
structs++;
@@ -946,10 +963,10 @@
/// where the vector is stored.
/// This is mostly useful when flatbuffers are generated with mutation
/// accessors.
- template<typename T, typename F, typename S>
- Offset<Vector<const T *>> CreateVectorOfStructs(size_t vector_size, F f,
- S *state) {
- T *structs = StartVectorOfStructs<T>(vector_size);
+ template <typename T, typename F, typename S>
+ Offset<Vector<const T*>> CreateVectorOfStructs(size_t vector_size, F f,
+ S* state) {
+ T* structs = StartVectorOfStructs<T>(vector_size);
for (size_t i = 0; i < vector_size; i++) {
f(i, structs, state);
structs++;
@@ -963,17 +980,17 @@
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, template<typename...> class OffsetT = Offset,
- template<typename...> class VectorT = Vector,
- typename Alloc = std::allocator<T>>
- OffsetT<VectorT<const T *>> CreateVectorOfStructs(
- const std::vector<T, Alloc> &v) {
+ template <typename T, template <typename...> class OffsetT = Offset,
+ template <typename...> class VectorT = Vector,
+ typename Alloc = std::allocator<T>>
+ OffsetT<VectorT<const T*>> CreateVectorOfStructs(
+ const std::vector<T, Alloc>& v) {
return CreateVectorOfStructs<T, OffsetT, VectorT>(data(v), v.size());
}
- template<template<typename...> class VectorT = Vector64, int &..., typename T>
- Offset64<VectorT<const T *>> CreateVectorOfStructs64(
- const std::vector<T> &v) {
+ template <template <typename...> class VectorT = Vector64, int&...,
+ typename T>
+ Offset64<VectorT<const T*>> CreateVectorOfStructs64(const std::vector<T>& v) {
return CreateVectorOfStructs<T, Offset64, VectorT>(data(v), v.size());
}
@@ -987,12 +1004,14 @@
/// to the FlatBuffer struct.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, typename S>
- Offset<Vector<const T *>> CreateVectorOfNativeStructs(
- const S *v, size_t len, T (*const pack_func)(const S &)) {
+ template <typename T, typename S>
+ Offset<Vector<const T*>> CreateVectorOfNativeStructs(
+ const S* v, size_t len, T (*const pack_func)(const S&)) {
FLATBUFFERS_ASSERT(pack_func);
auto structs = StartVectorOfStructs<T>(len);
- for (size_t i = 0; i < len; i++) { structs[i] = pack_func(v[i]); }
+ for (size_t i = 0; i < len; i++) {
+ structs[i] = pack_func(v[i]);
+ }
return EndVectorOfStructs<T>(len);
}
@@ -1004,10 +1023,9 @@
/// @param[in] len The number of elements to serialize.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, typename S>
- Offset<Vector<const T *>> CreateVectorOfNativeStructs(const S *v,
- size_t len) {
- extern T Pack(const S &);
+ template <typename T, typename S>
+ Offset<Vector<const T*>> CreateVectorOfNativeStructs(const S* v, size_t len) {
+ extern T Pack(const S&);
return CreateVectorOfNativeStructs(v, len, Pack);
}
@@ -1021,9 +1039,9 @@
/// to the FlatBuffer struct.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, typename S, typename Alloc = std::allocator<T>>
- Offset<Vector<const T *>> CreateVectorOfNativeStructs(
- const std::vector<S, Alloc> &v, T (*const pack_func)(const S &)) {
+ template <typename T, typename S, typename Alloc = std::allocator<T>>
+ Offset<Vector<const T*>> CreateVectorOfNativeStructs(
+ const std::vector<S, Alloc>& v, T (*const pack_func)(const S&)) {
return CreateVectorOfNativeStructs<T, S>(data(v), v.size(), pack_func);
}
@@ -1035,15 +1053,16 @@
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, typename S, typename Alloc = std::allocator<S>>
- Offset<Vector<const T *>> CreateVectorOfNativeStructs(
- const std::vector<S, Alloc> &v) {
+ template <typename T, typename S, typename Alloc = std::allocator<S>>
+ Offset<Vector<const T*>> CreateVectorOfNativeStructs(
+ const std::vector<S, Alloc>& v) {
return CreateVectorOfNativeStructs<T, S>(data(v), v.size());
}
/// @cond FLATBUFFERS_INTERNAL
- template<typename T> struct StructKeyComparator {
- bool operator()(const T &a, const T &b) const {
+ template <typename T>
+ struct StructKeyComparator {
+ bool operator()(const T& a, const T& b) const {
return a.KeyCompareLessThan(&b);
}
};
@@ -1056,9 +1075,9 @@
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, typename Alloc = std::allocator<T>>
- Offset<Vector<const T *>> CreateVectorOfSortedStructs(
- std::vector<T, Alloc> *v) {
+ template <typename T, typename Alloc = std::allocator<T>>
+ Offset<Vector<const T*>> CreateVectorOfSortedStructs(
+ std::vector<T, Alloc>* v) {
return CreateVectorOfSortedStructs(data(*v), v->size());
}
@@ -1070,9 +1089,9 @@
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, typename S, typename Alloc = std::allocator<T>>
- Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(
- std::vector<S, Alloc> *v) {
+ template <typename T, typename S, typename Alloc = std::allocator<T>>
+ Offset<Vector<const T*>> CreateVectorOfSortedNativeStructs(
+ std::vector<S, Alloc>* v) {
return CreateVectorOfSortedNativeStructs<T, S>(data(*v), v->size());
}
@@ -1084,8 +1103,8 @@
/// @param[in] len The number of elements to serialize.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T>
- Offset<Vector<const T *>> CreateVectorOfSortedStructs(T *v, size_t len) {
+ template <typename T>
+ Offset<Vector<const T*>> CreateVectorOfSortedStructs(T* v, size_t len) {
std::stable_sort(v, v + len, StructKeyComparator<T>());
return CreateVectorOfStructs(v, len);
}
@@ -1099,30 +1118,32 @@
/// @param[in] len The number of elements to serialize.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, typename S>
- Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(S *v,
- size_t len) {
- extern T Pack(const S &);
+ template <typename T, typename S>
+ Offset<Vector<const T*>> CreateVectorOfSortedNativeStructs(S* v, size_t len) {
+ extern T Pack(const S&);
auto structs = StartVectorOfStructs<T>(len);
- for (size_t i = 0; i < len; i++) { structs[i] = Pack(v[i]); }
+ for (size_t i = 0; i < len; i++) {
+ structs[i] = Pack(v[i]);
+ }
std::stable_sort(structs, structs + len, StructKeyComparator<T>());
return EndVectorOfStructs<T>(len);
}
/// @cond FLATBUFFERS_INTERNAL
- template<typename T> struct TableKeyComparator {
- explicit TableKeyComparator(vector_downward<SizeT> &buf) : buf_(buf) {}
- TableKeyComparator(const TableKeyComparator &other) : buf_(other.buf_) {}
- bool operator()(const Offset<T> &a, const Offset<T> &b) const {
- auto table_a = reinterpret_cast<T *>(buf_.data_at(a.o));
- auto table_b = reinterpret_cast<T *>(buf_.data_at(b.o));
+ template <typename T>
+ struct TableKeyComparator {
+ explicit TableKeyComparator(vector_downward<SizeT>& buf) : buf_(buf) {}
+ TableKeyComparator(const TableKeyComparator& other) : buf_(other.buf_) {}
+ bool operator()(const Offset<T>& a, const Offset<T>& b) const {
+ auto table_a = reinterpret_cast<T*>(buf_.data_at(a.o));
+ auto table_b = reinterpret_cast<T*>(buf_.data_at(b.o));
return table_a->KeyCompareLessThan(table_b);
}
- vector_downward<SizeT> &buf_;
+ vector_downward<SizeT>& buf_;
private:
FLATBUFFERS_DELETE_FUNC(
- TableKeyComparator &operator=(const TableKeyComparator &other));
+ TableKeyComparator& operator=(const TableKeyComparator& other));
};
/// @endcond
@@ -1134,8 +1155,8 @@
/// @param[in] len The number of elements to store in the `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T>
- Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(Offset<T> *v,
+ template <typename T>
+ Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(Offset<T>* v,
size_t len) {
std::stable_sort(v, v + len, TableKeyComparator<T>(buf_));
return CreateVector(v, len);
@@ -1148,9 +1169,9 @@
/// offsets to store in the buffer in sorted order.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
- template<typename T, typename Alloc = std::allocator<T>>
+ template <typename T, typename Alloc = std::allocator<T>>
Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
- std::vector<Offset<T>, Alloc> *v) {
+ std::vector<Offset<T>, Alloc>* v) {
return CreateVectorOfSortedTables(data(*v), v->size());
}
@@ -1162,7 +1183,7 @@
/// written to at a later time to serialize the data into a `vector`
/// in the buffer.
uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
- size_t alignment, uint8_t **buf) {
+ size_t alignment, uint8_t** buf) {
NotNested();
StartVector(len, elemsize, alignment);
buf_.make_space(len * elemsize);
@@ -1174,7 +1195,7 @@
FLATBUFFERS_ATTRIBUTE([[deprecated("call the version above instead")]])
uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
- uint8_t **buf) {
+ uint8_t** buf) {
return CreateUninitializedVector(len, elemsize, elemsize, buf);
}
@@ -1186,46 +1207,49 @@
/// @param[out] buf A pointer to a pointer of type `T` that can be
/// written to at a later time to serialize the data into a `vector`
/// in the buffer.
- template<typename T>
- Offset<Vector<T>> CreateUninitializedVector(size_t len, T **buf) {
+ template <typename T>
+ Offset<Vector<T>> CreateUninitializedVector(size_t len, T** buf) {
AssertScalarT<T>();
return CreateUninitializedVector(len, sizeof(T), AlignOf<T>(),
- reinterpret_cast<uint8_t **>(buf));
+ reinterpret_cast<uint8_t**>(buf));
}
- template<typename T>
- Offset<Vector<const T *>> CreateUninitializedVectorOfStructs(size_t len,
- T **buf) {
+ template <typename T>
+ Offset<Vector<const T*>> CreateUninitializedVectorOfStructs(size_t len,
+ T** buf) {
return CreateUninitializedVector(len, sizeof(T), AlignOf<T>(),
- reinterpret_cast<uint8_t **>(buf));
+ reinterpret_cast<uint8_t**>(buf));
}
// @brief Create a vector of scalar type T given as input a vector of scalar
// type U, useful with e.g. pre "enum class" enums, or any existing scalar
// data of the wrong type.
- template<typename T, typename U>
- Offset<Vector<T>> CreateVectorScalarCast(const U *v, size_t len) {
+ template <typename T, typename U>
+ Offset<Vector<T>> CreateVectorScalarCast(const U* v, size_t len) {
AssertScalarT<T>();
AssertScalarT<U>();
StartVector<T>(len);
- for (auto i = len; i > 0;) { PushElement(static_cast<T>(v[--i])); }
+ for (auto i = len; i > 0;) {
+ PushElement(static_cast<T>(v[--i]));
+ }
return Offset<Vector<T>>(EndVector(len));
}
/// @brief Write a struct by itself, typically to be part of a union.
- template<typename T> Offset<const T *> CreateStruct(const T &structobj) {
+ template <typename T>
+ Offset<const T*> CreateStruct(const T& structobj) {
NotNested();
Align(AlignOf<T>());
buf_.push_small(structobj);
- return Offset<const T *>(
- CalculateOffset<typename Offset<const T *>::offset_type>());
+ return Offset<const T*>(
+ CalculateOffset<typename Offset<const T*>::offset_type>());
}
/// @brief Finish serializing a buffer by writing the root offset.
/// @param[in] file_identifier If a `file_identifier` is given, the buffer
/// will be prefixed with a standard FlatBuffers file header.
- template<typename T>
- void Finish(Offset<T> root, const char *file_identifier = nullptr) {
+ template <typename T>
+ void Finish(Offset<T> root, const char* file_identifier = nullptr) {
Finish(root.o, file_identifier, false);
}
@@ -1236,13 +1260,13 @@
/// All >32 bit quantities in this buffer will be aligned when the whole
/// size pre-fixed buffer is aligned.
/// These kinds of buffers are useful for creating a stream of FlatBuffers.
- template<typename T>
+ template <typename T>
void FinishSizePrefixed(Offset<T> root,
- const char *file_identifier = nullptr) {
+ const char* file_identifier = nullptr) {
Finish(root.o, file_identifier, true);
}
- void SwapBufAllocator(FlatBufferBuilderImpl &other) {
+ void SwapBufAllocator(FlatBufferBuilderImpl& other) {
buf_.swap_allocator(other.buf_);
}
@@ -1252,10 +1276,10 @@
protected:
// You shouldn't really be copying instances of this class.
- FlatBufferBuilderImpl(const FlatBufferBuilderImpl &);
- FlatBufferBuilderImpl &operator=(const FlatBufferBuilderImpl &);
+ FlatBufferBuilderImpl(const FlatBufferBuilderImpl&);
+ FlatBufferBuilderImpl& operator=(const FlatBufferBuilderImpl&);
- void Finish(uoffset_t root, const char *file_identifier, bool size_prefix) {
+ void Finish(uoffset_t root, const char* file_identifier, bool size_prefix) {
// A buffer can only be finished once. To reuse a builder use `clear()`.
FLATBUFFERS_ASSERT(!finished);
@@ -1274,11 +1298,13 @@
if (file_identifier) {
FLATBUFFERS_ASSERT(strlen(file_identifier) == kFileIdentifierLength);
- PushBytes(reinterpret_cast<const uint8_t *>(file_identifier),
+ PushBytes(reinterpret_cast<const uint8_t*>(file_identifier),
kFileIdentifierLength);
}
PushElement(ReferTo(root)); // Location of root.
- if (size_prefix) { PushElement(GetSize()); }
+ if (size_prefix) {
+ PushElement(GetSize());
+ }
finished = true;
}
@@ -1329,20 +1355,20 @@
bool dedup_vtables_;
struct StringOffsetCompare {
- explicit StringOffsetCompare(const vector_downward<SizeT> &buf)
+ explicit StringOffsetCompare(const vector_downward<SizeT>& buf)
: buf_(&buf) {}
- bool operator()(const Offset<String> &a, const Offset<String> &b) const {
- auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o));
- auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o));
+ bool operator()(const Offset<String>& a, const Offset<String>& b) const {
+ auto stra = reinterpret_cast<const String*>(buf_->data_at(a.o));
+ auto strb = reinterpret_cast<const String*>(buf_->data_at(b.o));
return StringLessThan(stra->data(), stra->size(), strb->data(),
strb->size());
}
- const vector_downward<SizeT> *buf_;
+ const vector_downward<SizeT>* buf_;
};
// For use with CreateSharedString. Instantiated on first use only.
typedef std::set<Offset<String>, StringOffsetCompare> StringOffsetMap;
- StringOffsetMap *string_pool;
+ StringOffsetMap* string_pool;
private:
void CanAddOffset64() {
@@ -1372,33 +1398,33 @@
/// @param[in] str A const char pointer to the data to be stored as a string.
/// @param[in] len The number of bytes that should be stored from `str`.
/// @return Returns the offset in the buffer where the string starts.
- void CreateStringImpl(const char *str, size_t len) {
+ void CreateStringImpl(const char* str, size_t len) {
NotNested();
PreAlign<uoffset_t>(len + 1); // Always 0-terminated.
buf_.fill(1);
- PushBytes(reinterpret_cast<const uint8_t *>(str), len);
+ PushBytes(reinterpret_cast<const uint8_t*>(str), len);
PushElement(static_cast<uoffset_t>(len));
}
// Allocates space for a vector of structures.
// Must be completed with EndVectorOfStructs().
- template<typename T, template<typename> class OffsetT = Offset>
- T *StartVectorOfStructs(size_t vector_size) {
+ template <typename T, template <typename> class OffsetT = Offset>
+ T* StartVectorOfStructs(size_t vector_size) {
StartVector<OffsetT>(vector_size, sizeof(T), AlignOf<T>());
- return reinterpret_cast<T *>(buf_.make_space(vector_size * sizeof(T)));
+ return reinterpret_cast<T*>(buf_.make_space(vector_size * sizeof(T)));
}
// End the vector of structures in the flatbuffers.
// Vector should have previously be started with StartVectorOfStructs().
- template<typename T, template<typename> class OffsetT = Offset>
- OffsetT<Vector<const T *>> EndVectorOfStructs(size_t vector_size) {
- return OffsetT<Vector<const T *>>(
- EndVector<typename Vector<const T *>::size_type,
- typename OffsetT<Vector<const T *>>::offset_type>(
+ template <typename T, template <typename> class OffsetT = Offset>
+ OffsetT<Vector<const T*>> EndVectorOfStructs(size_t vector_size) {
+ return OffsetT<Vector<const T*>>(
+ EndVector<typename Vector<const T*>::size_type,
+ typename OffsetT<Vector<const T*>>::offset_type>(
vector_size));
}
- template<typename T>
+ template <typename T>
typename std::enable_if<std::is_same<T, uoffset_t>::value, T>::type
CalculateOffset() {
// Default to the end of the 32-bit region. This may or may not be the end
@@ -1408,7 +1434,7 @@
// Specializations to handle the 64-bit CalculateOffset, which is relative to
// end of the buffer.
- template<typename T>
+ template <typename T>
typename std::enable_if<std::is_same<T, uoffset64_t>::value, T>::type
CalculateOffset() {
// This should never be compiled in when not using a 64-bit builder.
@@ -1430,9 +1456,9 @@
// These are external due to GCC not allowing them in the class.
// See: https://stackoverflow.com/q/8061456/868247
-template<>
-template<>
-inline Offset64<String> FlatBufferBuilder64::CreateString(const char *str,
+template <>
+template <>
+inline Offset64<String> FlatBufferBuilder64::CreateString(const char* str,
size_t len) {
CanAddOffset64();
CreateStringImpl(str, len);
@@ -1441,19 +1467,20 @@
}
// Used to distinguish from real Offsets.
-template<typename T = void> struct EmptyOffset {};
+template <typename T = void>
+struct EmptyOffset {};
// TODO(derekbailey): it would be nice to combine these two methods.
-template<>
-template<>
+template <>
+template <>
inline void FlatBufferBuilder64::StartVector<Offset64, uint32_t>(
size_t len, size_t elemsize, size_t alignment) {
CanAddOffset64();
StartVector<EmptyOffset, uint32_t>(len, elemsize, alignment);
}
-template<>
-template<>
+template <>
+template <>
inline void FlatBufferBuilder64::StartVector<Offset64, uint64_t>(
size_t len, size_t elemsize, size_t alignment) {
CanAddOffset64();
@@ -1463,16 +1490,16 @@
/// Helpers to get a typed pointer to objects that are currently being built.
/// @warning Creating new objects will lead to reallocations and invalidates
/// the pointer!
-template<typename T>
-T *GetMutableTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
- return reinterpret_cast<T *>(fbb.GetCurrentBufferPointer() + fbb.GetSize() -
- offset.o);
+template <typename T>
+T* GetMutableTemporaryPointer(FlatBufferBuilder& fbb, Offset<T> offset) {
+ return reinterpret_cast<T*>(fbb.GetCurrentBufferPointer() + fbb.GetSize() -
+ offset.o);
}
-template<typename T>
-const T *GetTemporaryPointer(const FlatBufferBuilder &fbb, Offset<T> offset) {
- return reinterpret_cast<const T *>(fbb.GetCurrentBufferPointer() +
- fbb.GetSize() - offset.o);
+template <typename T>
+const T* GetTemporaryPointer(const FlatBufferBuilder& fbb, Offset<T> offset) {
+ return reinterpret_cast<const T*>(fbb.GetCurrentBufferPointer() +
+ fbb.GetSize() - offset.o);
}
} // namespace flatbuffers
diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h
index cbb0c53..87b271e 100644
--- a/include/flatbuffers/flatbuffers.h
+++ b/include/flatbuffers/flatbuffers.h
@@ -41,14 +41,14 @@
/// it is the opposite transformation of GetRoot().
/// This may be useful if you want to pass on a root and have the recipient
/// delete the buffer afterwards.
-inline const uint8_t *GetBufferStartFromRootPointer(const void *root) {
- auto table = reinterpret_cast<const Table *>(root);
+inline const uint8_t* GetBufferStartFromRootPointer(const void* root) {
+ auto table = reinterpret_cast<const Table*>(root);
auto vtable = table->GetVTable();
// Either the vtable is before the root or after the root.
- auto start = (std::min)(vtable, reinterpret_cast<const uint8_t *>(root));
+ auto start = (std::min)(vtable, reinterpret_cast<const uint8_t*>(root));
// Align to at least sizeof(uoffset_t).
- start = reinterpret_cast<const uint8_t *>(reinterpret_cast<uintptr_t>(start) &
- ~(sizeof(uoffset_t) - 1));
+ start = reinterpret_cast<const uint8_t*>(reinterpret_cast<uintptr_t>(start) &
+ ~(sizeof(uoffset_t) - 1));
// Additionally, there may be a file_identifier in the buffer, and the root
// offset. The buffer may have been aligned to any size between
// sizeof(uoffset_t) and FLATBUFFERS_MAX_ALIGNMENT (see "force_align").
@@ -64,7 +64,7 @@
possible_roots; possible_roots--) {
start -= sizeof(uoffset_t);
if (ReadScalar<uoffset_t>(start) + start ==
- reinterpret_cast<const uint8_t *>(root))
+ reinterpret_cast<const uint8_t*>(root))
return start;
}
// We didn't find the root, either the "root" passed isn't really a root,
@@ -76,8 +76,8 @@
}
/// @brief This return the prefixed size of a FlatBuffer.
-template<typename SizeT = uoffset_t>
-inline SizeT GetPrefixedSize(const uint8_t *buf) {
+template <typename SizeT = uoffset_t>
+inline SizeT GetPrefixedSize(const uint8_t* buf) {
return ReadScalar<SizeT>(buf);
}
@@ -87,8 +87,8 @@
//
// [size prefix][flatbuffer]
// |---------length--------|
-template<typename SizeT = uoffset_t>
-inline SizeT GetSizePrefixedBufferLength(const uint8_t *const buf) {
+template <typename SizeT = uoffset_t>
+inline SizeT GetSizePrefixedBufferLength(const uint8_t* const buf) {
return ReadScalar<SizeT>(buf) + sizeof(SizeT);
}
@@ -106,9 +106,9 @@
/// if you wish. The resolver does the opposite lookup, for when the object
/// is being serialized again.
typedef uint64_t hash_value_t;
-typedef std::function<void(void **pointer_adr, hash_value_t hash)>
+typedef std::function<void(void** pointer_adr, hash_value_t hash)>
resolver_function_t;
-typedef std::function<hash_value_t(void *pointer)> rehasher_function_t;
+typedef std::function<hash_value_t(void* pointer)> rehasher_function_t;
// Helper function to test if a field is present, using any of the field
// enums in the generated code.
@@ -117,18 +117,18 @@
// Note: this function will return false for fields equal to the default
// value, since they're not stored in the buffer (unless force_defaults was
// used).
-template<typename T>
-bool IsFieldPresent(const T *table, typename T::FlatBuffersVTableOffset field) {
+template <typename T>
+bool IsFieldPresent(const T* table, typename T::FlatBuffersVTableOffset field) {
// Cast, since Table is a private baseclass of any table types.
- return reinterpret_cast<const Table *>(table)->CheckField(
+ return reinterpret_cast<const Table*>(table)->CheckField(
static_cast<voffset_t>(field));
}
// Utility function for reverse lookups on the EnumNames*() functions
// (in the generated C++ code)
// names must be NULL terminated.
-inline int LookupEnum(const char **names, const char *name) {
- for (const char **p = names; *p; p++)
+inline int LookupEnum(const char** names, const char* name) {
+ for (const char** p = names; *p; p++)
if (!strcmp(*p, name)) return static_cast<int>(p - names);
return -1;
}
@@ -227,20 +227,20 @@
struct TypeTable;
// Signature of the static method present in each type.
-typedef const TypeTable *(*TypeFunction)();
+typedef const TypeTable* (*TypeFunction)();
struct TypeTable {
SequenceType st;
size_t num_elems; // of type_codes, values, names (but not type_refs).
- const TypeCode *type_codes; // num_elems count
- const TypeFunction *type_refs; // less than num_elems entries (see TypeCode).
- const int16_t *array_sizes; // less than num_elems entries (see TypeCode).
- const int64_t *values; // Only set for non-consecutive enum/union or structs.
- const char *const *names; // Only set if compiled with --reflect-names.
+ const TypeCode* type_codes; // num_elems count
+ const TypeFunction* type_refs; // less than num_elems entries (see TypeCode).
+ const int16_t* array_sizes; // less than num_elems entries (see TypeCode).
+ const int64_t* values; // Only set for non-consecutive enum/union or structs.
+ const char* const* names; // Only set if compiled with --reflect-names.
};
// String which identifies the current version of FlatBuffers.
-inline const char *flatbuffers_version_string() {
+inline const char* flatbuffers_version_string() {
return "FlatBuffers " FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
diff --git a/include/flatbuffers/flatc.h b/include/flatbuffers/flatc.h
index e98eb80..da24762 100644
--- a/include/flatbuffers/flatc.h
+++ b/include/flatbuffers/flatc.h
@@ -30,8 +30,8 @@
namespace flatbuffers {
-extern void LogCompilerWarn(const std::string &warn);
-extern void LogCompilerError(const std::string &err);
+extern void LogCompilerWarn(const std::string& warn);
+extern void LogCompilerError(const std::string& err);
struct FlatCOptions {
IDLOptions opts;
@@ -43,8 +43,8 @@
std::vector<std::string> filenames;
std::list<std::string> include_directories_storage;
- std::vector<const char *> include_directories;
- std::vector<const char *> conform_include_directories;
+ std::vector<const char*> include_directories;
+ std::vector<const char*> conform_include_directories;
std::vector<bool> generator_enabled;
size_t binary_files_from = std::numeric_limits<size_t>::max();
std::string conform_to_schema;
@@ -70,10 +70,10 @@
class FlatCompiler {
public:
- typedef void (*WarnFn)(const FlatCompiler *flatc, const std::string &warn,
+ typedef void (*WarnFn)(const FlatCompiler* flatc, const std::string& warn,
bool show_exe_name);
- typedef void (*ErrorFn)(const FlatCompiler *flatc, const std::string &err,
+ typedef void (*ErrorFn)(const FlatCompiler* flatc, const std::string& err,
bool usage, bool show_exe_name);
// Parameters required to initialize the FlatCompiler.
@@ -84,42 +84,42 @@
ErrorFn error_fn;
};
- explicit FlatCompiler(const InitParams ¶ms) : params_(params) {}
+ explicit FlatCompiler(const InitParams& params) : params_(params) {}
- bool RegisterCodeGenerator(const FlatCOption &option,
+ bool RegisterCodeGenerator(const FlatCOption& option,
std::shared_ptr<CodeGenerator> code_generator);
- int Compile(const FlatCOptions &options);
+ int Compile(const FlatCOptions& options);
- std::string GetShortUsageString(const std::string &program_name) const;
- std::string GetUsageString(const std::string &program_name) const;
+ std::string GetShortUsageString(const std::string& program_name) const;
+ std::string GetUsageString(const std::string& program_name) const;
// Parse the FlatC options from command line arguments.
- FlatCOptions ParseFromCommandLineArguments(int argc, const char **argv);
+ FlatCOptions ParseFromCommandLineArguments(int argc, const char** argv);
private:
- void ParseFile(flatbuffers::Parser &parser, const std::string &filename,
- const std::string &contents,
- const std::vector<const char *> &include_directories) const;
+ void ParseFile(flatbuffers::Parser& parser, const std::string& filename,
+ const std::string& contents,
+ const std::vector<const char*>& include_directories) const;
- void LoadBinarySchema(Parser &parser, const std::string &filename,
- const std::string &contents);
+ void LoadBinarySchema(Parser& parser, const std::string& filename,
+ const std::string& contents);
- void Warn(const std::string &warn, bool show_exe_name = true) const;
+ void Warn(const std::string& warn, bool show_exe_name = true) const;
- void Error(const std::string &err, bool usage = true,
+ void Error(const std::string& err, bool usage = true,
bool show_exe_name = true) const;
- void AnnotateBinaries(const uint8_t *binary_schema,
+ void AnnotateBinaries(const uint8_t* binary_schema,
uint64_t binary_schema_size,
- const FlatCOptions &options);
+ const FlatCOptions& options);
- void ValidateOptions(const FlatCOptions &options);
+ void ValidateOptions(const FlatCOptions& options);
- Parser GetConformParser(const FlatCOptions &options);
+ Parser GetConformParser(const FlatCOptions& options);
- std::unique_ptr<Parser> GenerateCode(const FlatCOptions &options,
- Parser &conform_parser);
+ std::unique_ptr<Parser> GenerateCode(const FlatCOptions& options,
+ Parser& conform_parser);
std::map<std::string, std::shared_ptr<CodeGenerator>> code_generators_;
diff --git a/include/flatbuffers/flex_flat_util.h b/include/flatbuffers/flex_flat_util.h
index 020957e..c02e90f 100644
--- a/include/flatbuffers/flex_flat_util.h
+++ b/include/flatbuffers/flex_flat_util.h
@@ -24,8 +24,8 @@
// Verifies the `nested` flexbuffer within a flatbuffer vector is valid.
inline bool VerifyNestedFlexBuffer(
- const flatbuffers::Vector<uint8_t> *const nested,
- flatbuffers::Verifier &verifier) {
+ const flatbuffers::Vector<uint8_t>* const nested,
+ flatbuffers::Verifier& verifier) {
if (!nested) return true;
return verifier.Check(flexbuffers::VerifyBuffer(
nested->data(), nested->size(), verifier.GetFlexReuseTracker()));
diff --git a/include/flatbuffers/flexbuffers.h b/include/flatbuffers/flexbuffers.h
index c4bbbbc..2784daf 100644
--- a/include/flatbuffers/flexbuffers.h
+++ b/include/flatbuffers/flexbuffers.h
@@ -25,12 +25,12 @@
#include "flatbuffers/util.h"
#ifdef _MSC_VER
-# include <intrin.h>
+#include <intrin.h>
#endif
#if defined(_MSC_VER)
-# pragma warning(push)
-# pragma warning(disable : 4127) // C4127: conditional expression is constant
+#pragma warning(push)
+#pragma warning(disable : 4127) // C4127: conditional expression is constant
#endif
namespace flexbuffers {
@@ -104,11 +104,17 @@
inline Type ToTypedVector(Type t, size_t fixed_len = 0) {
FLATBUFFERS_ASSERT(IsTypedVectorElementType(t));
switch (fixed_len) {
- case 0: return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT);
- case 2: return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT2);
- case 3: return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT3);
- case 4: return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT4);
- default: FLATBUFFERS_ASSERT(0); return FBT_NULL;
+ case 0:
+ return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT);
+ case 2:
+ return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT2);
+ case 3:
+ return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT3);
+ case 4:
+ return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT4);
+ default:
+ FLATBUFFERS_ASSERT(0);
+ return FBT_NULL;
}
}
@@ -117,7 +123,7 @@
return static_cast<Type>(t - FBT_VECTOR_INT + FBT_INT);
}
-inline Type ToFixedTypedVectorElementType(Type t, uint8_t *len) {
+inline Type ToFixedTypedVectorElementType(Type t, uint8_t* len) {
FLATBUFFERS_ASSERT(IsFixedTypedVector(t));
auto fixed_type = t - FBT_VECTOR_INT2;
*len = static_cast<uint8_t>(fixed_type / 3 +
@@ -135,8 +141,8 @@
// decently quick, but it is the most frequently executed function.
// We could do an (unaligned) 64-bit read if we ifdef out the platforms for
// which that doesn't work (or where we'd read into un-owned memory).
-template<typename R, typename T1, typename T2, typename T4, typename T8>
-R ReadSizedScalar(const uint8_t *data, uint8_t byte_width) {
+template <typename R, typename T1, typename T2, typename T4, typename T8>
+R ReadSizedScalar(const uint8_t* data, uint8_t byte_width) {
return byte_width < 4
? (byte_width < 2
? static_cast<R>(flatbuffers::ReadScalar<T1>(data))
@@ -146,12 +152,12 @@
: static_cast<R>(flatbuffers::ReadScalar<T8>(data)));
}
-inline int64_t ReadInt64(const uint8_t *data, uint8_t byte_width) {
+inline int64_t ReadInt64(const uint8_t* data, uint8_t byte_width) {
return ReadSizedScalar<int64_t, int8_t, int16_t, int32_t, int64_t>(
data, byte_width);
}
-inline uint64_t ReadUInt64(const uint8_t *data, uint8_t byte_width) {
+inline uint64_t ReadUInt64(const uint8_t* data, uint8_t byte_width) {
// This is the "hottest" function (all offset lookups use this), so worth
// optimizing if possible.
// TODO: GCC apparently replaces memcpy by a rep movsb, but only if count is a
@@ -172,16 +178,17 @@
// clang-format on
}
-inline double ReadDouble(const uint8_t *data, uint8_t byte_width) {
+inline double ReadDouble(const uint8_t* data, uint8_t byte_width) {
return ReadSizedScalar<double, quarter, half, float, double>(data,
byte_width);
}
-inline const uint8_t *Indirect(const uint8_t *offset, uint8_t byte_width) {
+inline const uint8_t* Indirect(const uint8_t* offset, uint8_t byte_width) {
return offset - ReadUInt64(offset, byte_width);
}
-template<typename T> const uint8_t *Indirect(const uint8_t *offset) {
+template <typename T>
+const uint8_t* Indirect(const uint8_t* offset) {
return offset - flatbuffers::ReadScalar<T>(offset);
}
@@ -211,11 +218,11 @@
// Points into the data buffer and allows access to one type.
class Object {
public:
- Object(const uint8_t *data, uint8_t byte_width)
+ Object(const uint8_t* data, uint8_t byte_width)
: data_(data), byte_width_(byte_width) {}
protected:
- const uint8_t *data_;
+ const uint8_t* data_;
uint8_t byte_width_;
};
@@ -223,10 +230,10 @@
class Sized : public Object {
public:
// Size prefix.
- Sized(const uint8_t *data, uint8_t byte_width)
+ Sized(const uint8_t* data, uint8_t byte_width)
: Object(data, byte_width), size_(read_size()) {}
// Manual size.
- Sized(const uint8_t *data, uint8_t byte_width, size_t sz)
+ Sized(const uint8_t* data, uint8_t byte_width, size_t sz)
: Object(data, byte_width), size_(sz) {}
size_t size() const { return size_; }
// Access size stored in `byte_width_` bytes before data_ pointer.
@@ -241,43 +248,43 @@
class String : public Sized {
public:
// Size prefix.
- String(const uint8_t *data, uint8_t byte_width) : Sized(data, byte_width) {}
+ String(const uint8_t* data, uint8_t byte_width) : Sized(data, byte_width) {}
// Manual size.
- String(const uint8_t *data, uint8_t byte_width, size_t sz)
+ String(const uint8_t* data, uint8_t byte_width, size_t sz)
: Sized(data, byte_width, sz) {}
size_t length() const { return size(); }
- const char *c_str() const { return reinterpret_cast<const char *>(data_); }
+ const char* c_str() const { return reinterpret_cast<const char*>(data_); }
std::string str() const { return std::string(c_str(), size()); }
static String EmptyString() {
- static const char *empty_string = "";
- return String(reinterpret_cast<const uint8_t *>(empty_string), 1, 0);
+ static const char* empty_string = "";
+ return String(reinterpret_cast<const uint8_t*>(empty_string), 1, 0);
}
bool IsTheEmptyString() const { return data_ == EmptyString().data_; }
};
class Blob : public Sized {
public:
- Blob(const uint8_t *data_buf, uint8_t byte_width)
+ Blob(const uint8_t* data_buf, uint8_t byte_width)
: Sized(data_buf, byte_width) {}
static Blob EmptyBlob() {
- static const uint8_t empty_blob[] = { 0 /*len*/ };
+ static const uint8_t empty_blob[] = {0 /*len*/};
return Blob(empty_blob + 1, 1);
}
bool IsTheEmptyBlob() const { return data_ == EmptyBlob().data_; }
- const uint8_t *data() const { return data_; }
+ const uint8_t* data() const { return data_; }
};
class Vector : public Sized {
public:
- Vector(const uint8_t *data, uint8_t byte_width) : Sized(data, byte_width) {}
+ Vector(const uint8_t* data, uint8_t byte_width) : Sized(data, byte_width) {}
Reference operator[](size_t i) const;
static Vector EmptyVector() {
- static const uint8_t empty_vector[] = { 0 /*len*/ };
+ static const uint8_t empty_vector[] = {0 /*len*/};
return Vector(empty_vector + 1, 1);
}
bool IsTheEmptyVector() const { return data_ == EmptyVector().data_; }
@@ -285,13 +292,13 @@
class TypedVector : public Sized {
public:
- TypedVector(const uint8_t *data, uint8_t byte_width, Type element_type)
+ TypedVector(const uint8_t* data, uint8_t byte_width, Type element_type)
: Sized(data, byte_width), type_(element_type) {}
Reference operator[](size_t i) const;
static TypedVector EmptyTypedVector() {
- static const uint8_t empty_typed_vector[] = { 0 /*len*/ };
+ static const uint8_t empty_typed_vector[] = {0 /*len*/};
return TypedVector(empty_typed_vector + 1, 1, FBT_INT);
}
bool IsTheEmptyVector() const {
@@ -310,14 +317,14 @@
class FixedTypedVector : public Object {
public:
- FixedTypedVector(const uint8_t *data, uint8_t byte_width, Type element_type,
+ FixedTypedVector(const uint8_t* data, uint8_t byte_width, Type element_type,
uint8_t len)
: Object(data, byte_width), type_(element_type), len_(len) {}
Reference operator[](size_t i) const;
static FixedTypedVector EmptyFixedTypedVector() {
- static const uint8_t fixed_empty_vector[] = { 0 /* unused */ };
+ static const uint8_t fixed_empty_vector[] = {0 /* unused */};
return FixedTypedVector(fixed_empty_vector, 1, FBT_INT, 0);
}
bool IsTheEmptyFixedTypedVector() const {
@@ -334,10 +341,10 @@
class Map : public Vector {
public:
- Map(const uint8_t *data, uint8_t byte_width) : Vector(data, byte_width) {}
+ Map(const uint8_t* data, uint8_t byte_width) : Vector(data, byte_width) {}
- Reference operator[](const char *key) const;
- Reference operator[](const std::string &key) const;
+ Reference operator[](const char* key) const;
+ Reference operator[](const std::string& key) const;
Vector Values() const { return Vector(data_, byte_width_); }
@@ -352,7 +359,7 @@
static Map EmptyMap() {
static const uint8_t empty_map[] = {
- 0 /*keys_len*/, 0 /*keys_offset*/, 1 /*keys_width*/, 0 /*len*/
+ 0 /*keys_len*/, 0 /*keys_offset*/, 1 /*keys_width*/, 0 /*len*/
};
return Map(empty_map + 4, 1);
}
@@ -360,14 +367,14 @@
bool IsTheEmptyMap() const { return data_ == EmptyMap().data_; }
};
-inline void IndentString(std::string &s, int indent,
- const char *indent_string) {
+inline void IndentString(std::string& s, int indent,
+ const char* indent_string) {
for (int i = 0; i < indent; i++) s += indent_string;
}
-template<typename T>
-void AppendToString(std::string &s, T &&v, bool keys_quoted, bool indented,
- int cur_indent, const char *indent_string,
+template <typename T>
+void AppendToString(std::string& s, T&& v, bool keys_quoted, bool indented,
+ int cur_indent, const char* indent_string,
bool natural_utf8) {
s += "[";
s += indented ? "\n" : " ";
@@ -377,8 +384,8 @@
s += indented ? "\n" : " ";
}
if (indented) IndentString(s, cur_indent, indent_string);
- v[i].ToString(true, keys_quoted, s, indented, cur_indent,
- indent_string, natural_utf8);
+ v[i].ToString(true, keys_quoted, s, indented, cur_indent, indent_string,
+ natural_utf8);
}
if (indented) {
s += "\n";
@@ -389,25 +396,24 @@
s += "]";
}
-template<typename T>
-void AppendToString(std::string &s, T &&v, bool keys_quoted) {
+template <typename T>
+void AppendToString(std::string& s, T&& v, bool keys_quoted) {
AppendToString(s, v, keys_quoted);
}
-
class Reference {
public:
Reference()
: data_(nullptr), parent_width_(0), byte_width_(0), type_(FBT_NULL) {}
- Reference(const uint8_t *data, uint8_t parent_width, uint8_t byte_width,
+ Reference(const uint8_t* data, uint8_t parent_width, uint8_t byte_width,
Type type)
: data_(data),
parent_width_(parent_width),
byte_width_(byte_width),
type_(type) {}
- Reference(const uint8_t *data, uint8_t parent_width, uint8_t packed_type)
+ Reference(const uint8_t* data, uint8_t parent_width, uint8_t packed_type)
: data_(data),
parent_width_(parent_width),
byte_width_(static_cast<uint8_t>(1 << (packed_type & 3))),
@@ -453,17 +459,24 @@
return ReadInt64(data_, parent_width_);
} else
switch (type_) {
- case FBT_INDIRECT_INT: return ReadInt64(Indirect(), byte_width_);
- case FBT_UINT: return ReadUInt64(data_, parent_width_);
- case FBT_INDIRECT_UINT: return ReadUInt64(Indirect(), byte_width_);
+ case FBT_INDIRECT_INT:
+ return ReadInt64(Indirect(), byte_width_);
+ case FBT_UINT:
+ return ReadUInt64(data_, parent_width_);
+ case FBT_INDIRECT_UINT:
+ return ReadUInt64(Indirect(), byte_width_);
case FBT_FLOAT:
return static_cast<int64_t>(ReadDouble(data_, parent_width_));
case FBT_INDIRECT_FLOAT:
return static_cast<int64_t>(ReadDouble(Indirect(), byte_width_));
- case FBT_NULL: return 0;
- case FBT_STRING: return flatbuffers::StringToInt(AsString().c_str());
- case FBT_VECTOR: return static_cast<int64_t>(AsVector().size());
- case FBT_BOOL: return ReadInt64(data_, parent_width_);
+ case FBT_NULL:
+ return 0;
+ case FBT_STRING:
+ return flatbuffers::StringToInt(AsString().c_str());
+ case FBT_VECTOR:
+ return static_cast<int64_t>(AsVector().size());
+ case FBT_BOOL:
+ return ReadInt64(data_, parent_width_);
default:
// Convert other things to int.
return 0;
@@ -482,17 +495,24 @@
return ReadUInt64(data_, parent_width_);
} else
switch (type_) {
- case FBT_INDIRECT_UINT: return ReadUInt64(Indirect(), byte_width_);
- case FBT_INT: return ReadInt64(data_, parent_width_);
- case FBT_INDIRECT_INT: return ReadInt64(Indirect(), byte_width_);
+ case FBT_INDIRECT_UINT:
+ return ReadUInt64(Indirect(), byte_width_);
+ case FBT_INT:
+ return ReadInt64(data_, parent_width_);
+ case FBT_INDIRECT_INT:
+ return ReadInt64(Indirect(), byte_width_);
case FBT_FLOAT:
return static_cast<uint64_t>(ReadDouble(data_, parent_width_));
case FBT_INDIRECT_FLOAT:
return static_cast<uint64_t>(ReadDouble(Indirect(), byte_width_));
- case FBT_NULL: return 0;
- case FBT_STRING: return flatbuffers::StringToUInt(AsString().c_str());
- case FBT_VECTOR: return static_cast<uint64_t>(AsVector().size());
- case FBT_BOOL: return ReadUInt64(data_, parent_width_);
+ case FBT_NULL:
+ return 0;
+ case FBT_STRING:
+ return flatbuffers::StringToUInt(AsString().c_str());
+ case FBT_VECTOR:
+ return static_cast<uint64_t>(AsVector().size());
+ case FBT_BOOL:
+ return ReadUInt64(data_, parent_width_);
default:
// Convert other things to uint.
return 0;
@@ -509,7 +529,8 @@
return ReadDouble(data_, parent_width_);
} else
switch (type_) {
- case FBT_INDIRECT_FLOAT: return ReadDouble(Indirect(), byte_width_);
+ case FBT_INDIRECT_FLOAT:
+ return ReadDouble(Indirect(), byte_width_);
case FBT_INT:
return static_cast<double>(ReadInt64(data_, parent_width_));
case FBT_UINT:
@@ -518,13 +539,15 @@
return static_cast<double>(ReadInt64(Indirect(), byte_width_));
case FBT_INDIRECT_UINT:
return static_cast<double>(ReadUInt64(Indirect(), byte_width_));
- case FBT_NULL: return 0.0;
+ case FBT_NULL:
+ return 0.0;
case FBT_STRING: {
double d;
flatbuffers::StringToNumber(AsString().c_str(), &d);
return d;
}
- case FBT_VECTOR: return static_cast<double>(AsVector().size());
+ case FBT_VECTOR:
+ return static_cast<double>(AsVector().size());
case FBT_BOOL:
return static_cast<double>(ReadUInt64(data_, parent_width_));
default:
@@ -535,9 +558,9 @@
float AsFloat() const { return static_cast<float>(AsDouble()); }
- const char *AsKey() const {
+ const char* AsKey() const {
if (type_ == FBT_KEY || type_ == FBT_STRING) {
- return reinterpret_cast<const char *>(Indirect());
+ return reinterpret_cast<const char*>(Indirect());
} else {
return "";
}
@@ -551,7 +574,7 @@
} else if (type_ == FBT_KEY) {
auto key = Indirect();
return String(key, byte_width_,
- strlen(reinterpret_cast<const char *>(key)));
+ strlen(reinterpret_cast<const char*>(key)));
} else {
return String::EmptyString();
}
@@ -567,18 +590,19 @@
// Convert any type to a JSON-like string. strings_quoted determines if
// string values at the top level receive "" quotes (inside other values
// they always do). keys_quoted determines if keys are quoted, at any level.
- void ToString(bool strings_quoted, bool keys_quoted, std::string &s) const {
+ void ToString(bool strings_quoted, bool keys_quoted, std::string& s) const {
ToString(strings_quoted, keys_quoted, s, false, 0, "", false);
}
// This version additionally allow you to specify if you want indentation.
- void ToString(bool strings_quoted, bool keys_quoted, std::string &s,
- bool indented, int cur_indent, const char *indent_string,
+ void ToString(bool strings_quoted, bool keys_quoted, std::string& s,
+ bool indented, int cur_indent, const char* indent_string,
bool natural_utf8 = false) const {
if (type_ == FBT_STRING) {
String str(Indirect(), byte_width_);
if (strings_quoted) {
- flatbuffers::EscapeString(str.c_str(), str.length(), &s, true, natural_utf8);
+ flatbuffers::EscapeString(str.c_str(), str.length(), &s, true,
+ natural_utf8);
} else {
s.append(str.c_str(), str.length());
}
@@ -610,7 +634,7 @@
if (!kq) {
// FlexBuffers keys may contain arbitrary characters, only allow
// unquoted if it looks like an "identifier":
- const char *p = keys[i].AsKey();
+ const char* p = keys[i].AsKey();
if (!flatbuffers::is_alpha(*p) && *p != '_') {
kq = true;
} else {
@@ -625,8 +649,8 @@
if (indented) IndentString(s, cur_indent + 1, indent_string);
keys[i].ToString(true, kq, s);
s += ": ";
- vals[i].ToString(true, keys_quoted, s, indented, cur_indent + 1, indent_string,
- natural_utf8);
+ vals[i].ToString(true, keys_quoted, s, indented, cur_indent + 1,
+ indent_string, natural_utf8);
if (i < keys.size() - 1) {
s += ",";
if (!indented) s += " ";
@@ -641,15 +665,14 @@
cur_indent + 1, indent_string, natural_utf8);
} else if (IsTypedVector()) {
AppendToString<TypedVector>(s, AsTypedVector(), keys_quoted, indented,
- cur_indent + 1, indent_string,
- natural_utf8);
+ cur_indent + 1, indent_string, natural_utf8);
} else if (IsFixedTypedVector()) {
AppendToString<FixedTypedVector>(s, AsFixedTypedVector(), keys_quoted,
indented, cur_indent + 1, indent_string,
natural_utf8);
} else if (IsBlob()) {
auto blob = AsBlob();
- flatbuffers::EscapeString(reinterpret_cast<const char *>(blob.data()),
+ flatbuffers::EscapeString(reinterpret_cast<const char*>(blob.data()),
blob.size(), &s, true, false);
} else {
s += "(?)";
@@ -713,7 +736,8 @@
}
}
- template<typename T> T As() const;
+ template <typename T>
+ T As() const;
// Experimental: Mutation functions.
// These allow scalars in an already created buffer to be updated in-place.
@@ -777,39 +801,39 @@
}
}
- bool MutateString(const char *str, size_t len) {
+ bool MutateString(const char* str, size_t len) {
auto s = AsString();
if (s.IsTheEmptyString()) return false;
// This is very strict, could allow shorter strings, but that creates
// garbage.
if (s.length() != len) return false;
- memcpy(const_cast<char *>(s.c_str()), str, len);
+ memcpy(const_cast<char*>(s.c_str()), str, len);
return true;
}
- bool MutateString(const char *str) { return MutateString(str, strlen(str)); }
- bool MutateString(const std::string &str) {
+ bool MutateString(const char* str) { return MutateString(str, strlen(str)); }
+ bool MutateString(const std::string& str) {
return MutateString(str.data(), str.length());
}
private:
- const uint8_t *Indirect() const {
+ const uint8_t* Indirect() const {
return flexbuffers::Indirect(data_, parent_width_);
}
- template<typename T>
- bool Mutate(const uint8_t *dest, T t, size_t byte_width,
+ template <typename T>
+ bool Mutate(const uint8_t* dest, T t, size_t byte_width,
BitWidth value_width) {
auto fits = static_cast<size_t>(static_cast<size_t>(1U) << value_width) <=
byte_width;
if (fits) {
t = flatbuffers::EndianScalar(t);
- memcpy(const_cast<uint8_t *>(dest), &t, byte_width);
+ memcpy(const_cast<uint8_t*>(dest), &t, byte_width);
}
return fits;
}
- template<typename T>
- bool MutateF(const uint8_t *dest, T t, size_t byte_width,
+ template <typename T>
+ bool MutateF(const uint8_t* dest, T t, size_t byte_width,
BitWidth value_width) {
if (byte_width == sizeof(double))
return Mutate(dest, static_cast<double>(t), byte_width, value_width);
@@ -821,48 +845,90 @@
friend class Verifier;
- const uint8_t *data_;
+ const uint8_t* data_;
uint8_t parent_width_;
uint8_t byte_width_;
Type type_;
};
// Template specialization for As().
-template<> inline bool Reference::As<bool>() const { return AsBool(); }
+template <>
+inline bool Reference::As<bool>() const {
+ return AsBool();
+}
-template<> inline int8_t Reference::As<int8_t>() const { return AsInt8(); }
-template<> inline int16_t Reference::As<int16_t>() const { return AsInt16(); }
-template<> inline int32_t Reference::As<int32_t>() const { return AsInt32(); }
-template<> inline int64_t Reference::As<int64_t>() const { return AsInt64(); }
+template <>
+inline int8_t Reference::As<int8_t>() const {
+ return AsInt8();
+}
+template <>
+inline int16_t Reference::As<int16_t>() const {
+ return AsInt16();
+}
+template <>
+inline int32_t Reference::As<int32_t>() const {
+ return AsInt32();
+}
+template <>
+inline int64_t Reference::As<int64_t>() const {
+ return AsInt64();
+}
-template<> inline uint8_t Reference::As<uint8_t>() const { return AsUInt8(); }
-template<> inline uint16_t Reference::As<uint16_t>() const {
+template <>
+inline uint8_t Reference::As<uint8_t>() const {
+ return AsUInt8();
+}
+template <>
+inline uint16_t Reference::As<uint16_t>() const {
return AsUInt16();
}
-template<> inline uint32_t Reference::As<uint32_t>() const {
+template <>
+inline uint32_t Reference::As<uint32_t>() const {
return AsUInt32();
}
-template<> inline uint64_t Reference::As<uint64_t>() const {
+template <>
+inline uint64_t Reference::As<uint64_t>() const {
return AsUInt64();
}
-template<> inline double Reference::As<double>() const { return AsDouble(); }
-template<> inline float Reference::As<float>() const { return AsFloat(); }
+template <>
+inline double Reference::As<double>() const {
+ return AsDouble();
+}
+template <>
+inline float Reference::As<float>() const {
+ return AsFloat();
+}
-template<> inline String Reference::As<String>() const { return AsString(); }
-template<> inline std::string Reference::As<std::string>() const {
+template <>
+inline String Reference::As<String>() const {
+ return AsString();
+}
+template <>
+inline std::string Reference::As<std::string>() const {
return AsString().str();
}
-template<> inline Blob Reference::As<Blob>() const { return AsBlob(); }
-template<> inline Vector Reference::As<Vector>() const { return AsVector(); }
-template<> inline TypedVector Reference::As<TypedVector>() const {
+template <>
+inline Blob Reference::As<Blob>() const {
+ return AsBlob();
+}
+template <>
+inline Vector Reference::As<Vector>() const {
+ return AsVector();
+}
+template <>
+inline TypedVector Reference::As<TypedVector>() const {
return AsTypedVector();
}
-template<> inline FixedTypedVector Reference::As<FixedTypedVector>() const {
+template <>
+inline FixedTypedVector Reference::As<FixedTypedVector>() const {
return AsFixedTypedVector();
}
-template<> inline Map Reference::As<Map>() const { return AsMap(); }
+template <>
+inline Map Reference::As<Map>() const {
+ return AsMap();
+}
inline uint8_t PackedType(BitWidth bit_width, Type type) {
return static_cast<uint8_t>(bit_width | (type << 2));
@@ -898,36 +964,47 @@
return Reference(elem, byte_width_, 1, type_);
}
-template<typename T> int KeyCompare(const void *key, const void *elem) {
- auto str_elem = reinterpret_cast<const char *>(
- Indirect<T>(reinterpret_cast<const uint8_t *>(elem)));
- auto skey = reinterpret_cast<const char *>(key);
+template <typename T>
+int KeyCompare(const void* key, const void* elem) {
+ auto str_elem = reinterpret_cast<const char*>(
+ Indirect<T>(reinterpret_cast<const uint8_t*>(elem)));
+ auto skey = reinterpret_cast<const char*>(key);
return strcmp(skey, str_elem);
}
-inline Reference Map::operator[](const char *key) const {
+inline Reference Map::operator[](const char* key) const {
auto keys = Keys();
// We can't pass keys.byte_width_ to the comparison function, so we have
// to pick the right one ahead of time.
- int (*comp)(const void *, const void *) = nullptr;
+ int (*comp)(const void*, const void*) = nullptr;
switch (keys.byte_width_) {
- case 1: comp = KeyCompare<uint8_t>; break;
- case 2: comp = KeyCompare<uint16_t>; break;
- case 4: comp = KeyCompare<uint32_t>; break;
- case 8: comp = KeyCompare<uint64_t>; break;
- default: FLATBUFFERS_ASSERT(false); return Reference();
+ case 1:
+ comp = KeyCompare<uint8_t>;
+ break;
+ case 2:
+ comp = KeyCompare<uint16_t>;
+ break;
+ case 4:
+ comp = KeyCompare<uint32_t>;
+ break;
+ case 8:
+ comp = KeyCompare<uint64_t>;
+ break;
+ default:
+ FLATBUFFERS_ASSERT(false);
+ return Reference();
}
auto res = std::bsearch(key, keys.data_, keys.size(), keys.byte_width_, comp);
if (!res) return Reference(nullptr, 1, NullPackedType());
- auto i = (reinterpret_cast<uint8_t *>(res) - keys.data_) / keys.byte_width_;
- return (*static_cast<const Vector *>(this))[i];
+ auto i = (reinterpret_cast<uint8_t*>(res) - keys.data_) / keys.byte_width_;
+ return (*static_cast<const Vector*>(this))[i];
}
-inline Reference Map::operator[](const std::string &key) const {
+inline Reference Map::operator[](const std::string& key) const {
return (*this)[key.c_str()];
}
-inline Reference GetRoot(const uint8_t *buffer, size_t size) {
+inline Reference GetRoot(const uint8_t* buffer, size_t size) {
// See Finish() below for the serialization counterpart of this.
// The root starts at the end of the buffer, so we parse backwards from there.
auto end = buffer + size;
@@ -937,7 +1014,7 @@
return Reference(end, byte_width, packed_type);
}
-inline Reference GetRoot(const std::vector<uint8_t> &buffer) {
+inline Reference GetRoot(const std::vector<uint8_t>& buffer) {
return GetRoot(buffer.data(), buffer.size());
}
@@ -975,13 +1052,13 @@
}
#ifdef FLATBUFFERS_DEFAULT_DECLARATION
- Builder(Builder &&) = default;
- Builder &operator=(Builder &&) = default;
+ Builder(Builder&&) = default;
+ Builder& operator=(Builder&&) = default;
#endif
/// @brief Get the serialized buffer (after you call `Finish()`).
/// @return Returns a vector owned by this class.
- const std::vector<uint8_t> &GetBuffer() const {
+ const std::vector<uint8_t>& GetBuffer() const {
Finished();
return buf_;
}
@@ -1005,43 +1082,43 @@
// vectors and elsewhere).
void Null() { stack_.push_back(Value()); }
- void Null(const char *key) {
+ void Null(const char* key) {
Key(key);
Null();
}
void Int(int64_t i) { stack_.push_back(Value(i, FBT_INT, WidthI(i))); }
- void Int(const char *key, int64_t i) {
+ void Int(const char* key, int64_t i) {
Key(key);
Int(i);
}
void UInt(uint64_t u) { stack_.push_back(Value(u, FBT_UINT, WidthU(u))); }
- void UInt(const char *key, uint64_t u) {
+ void UInt(const char* key, uint64_t u) {
Key(key);
UInt(u);
}
void Float(float f) { stack_.push_back(Value(f)); }
- void Float(const char *key, float f) {
+ void Float(const char* key, float f) {
Key(key);
Float(f);
}
void Double(double f) { stack_.push_back(Value(f)); }
- void Double(const char *key, double d) {
+ void Double(const char* key, double d) {
Key(key);
Double(d);
}
void Bool(bool b) { stack_.push_back(Value(b)); }
- void Bool(const char *key, bool b) {
+ void Bool(const char* key, bool b) {
Key(key);
Bool(b);
}
void IndirectInt(int64_t i) { PushIndirect(i, FBT_INDIRECT_INT, WidthI(i)); }
- void IndirectInt(const char *key, int64_t i) {
+ void IndirectInt(const char* key, int64_t i) {
Key(key);
IndirectInt(i);
}
@@ -1049,7 +1126,7 @@
void IndirectUInt(uint64_t u) {
PushIndirect(u, FBT_INDIRECT_UINT, WidthU(u));
}
- void IndirectUInt(const char *key, uint64_t u) {
+ void IndirectUInt(const char* key, uint64_t u) {
Key(key);
IndirectUInt(u);
}
@@ -1057,7 +1134,7 @@
void IndirectFloat(float f) {
PushIndirect(f, FBT_INDIRECT_FLOAT, BIT_WIDTH_32);
}
- void IndirectFloat(const char *key, float f) {
+ void IndirectFloat(const char* key, float f) {
Key(key);
IndirectFloat(f);
}
@@ -1065,12 +1142,12 @@
void IndirectDouble(double f) {
PushIndirect(f, FBT_INDIRECT_FLOAT, WidthF(f));
}
- void IndirectDouble(const char *key, double d) {
+ void IndirectDouble(const char* key, double d) {
Key(key);
IndirectDouble(d);
}
- size_t Key(const char *str, size_t len) {
+ size_t Key(const char* str, size_t len) {
auto sloc = buf_.size();
WriteBytes(str, len + 1);
if (flags_ & BUILDER_FLAG_SHARE_KEYS) {
@@ -1088,10 +1165,10 @@
return sloc;
}
- size_t Key(const char *str) { return Key(str, strlen(str)); }
- size_t Key(const std::string &str) { return Key(str.c_str(), str.size()); }
+ size_t Key(const char* str) { return Key(str, strlen(str)); }
+ size_t Key(const std::string& str) { return Key(str.c_str(), str.size()); }
- size_t String(const char *str, size_t len) {
+ size_t String(const char* str, size_t len) {
auto reset_to = buf_.size();
auto sloc = CreateBlob(str, len, 1, FBT_STRING);
if (flags_ & BUILDER_FLAG_SHARE_STRINGS) {
@@ -1109,39 +1186,39 @@
}
return sloc;
}
- size_t String(const char *str) { return String(str, strlen(str)); }
- size_t String(const std::string &str) {
+ size_t String(const char* str) { return String(str, strlen(str)); }
+ size_t String(const std::string& str) {
return String(str.c_str(), str.size());
}
- void String(const flexbuffers::String &str) {
+ void String(const flexbuffers::String& str) {
String(str.c_str(), str.length());
}
- void String(const char *key, const char *str) {
+ void String(const char* key, const char* str) {
Key(key);
String(str);
}
- void String(const char *key, const std::string &str) {
+ void String(const char* key, const std::string& str) {
Key(key);
String(str);
}
- void String(const char *key, const flexbuffers::String &str) {
+ void String(const char* key, const flexbuffers::String& str) {
Key(key);
String(str);
}
- size_t Blob(const void *data, size_t len) {
+ size_t Blob(const void* data, size_t len) {
return CreateBlob(data, len, 0, FBT_BLOB);
}
- size_t Blob(const std::vector<uint8_t> &v) {
+ size_t Blob(const std::vector<uint8_t>& v) {
return CreateBlob(v.data(), v.size(), 0, FBT_BLOB);
}
- void Blob(const char *key, const void *data, size_t len) {
+ void Blob(const char* key, const void* data, size_t len) {
Key(key);
Blob(data, len);
}
- void Blob(const char *key, const std::vector<uint8_t> &v) {
+ void Blob(const char* key, const std::vector<uint8_t>& v) {
Key(key);
Blob(v);
}
@@ -1151,12 +1228,12 @@
// Also some FlatBuffers types?
size_t StartVector() { return stack_.size(); }
- size_t StartVector(const char *key) {
+ size_t StartVector(const char* key) {
Key(key);
return stack_.size();
}
size_t StartMap() { return stack_.size(); }
- size_t StartMap(const char *key) {
+ size_t StartMap(const char* key) {
Key(key);
return stack_.size();
}
@@ -1193,24 +1270,24 @@
// step automatically when appliccable, and encourage people to write in
// sorted fashion.
// std::sort is typically already a lot faster on sorted data though.
- auto dict = reinterpret_cast<TwoValue *>(stack_.data() + start);
- std::sort(
- dict, dict + len, [&](const TwoValue &a, const TwoValue &b) -> bool {
- auto as = reinterpret_cast<const char *>(buf_.data() + a.key.u_);
- auto bs = reinterpret_cast<const char *>(buf_.data() + b.key.u_);
- auto comp = strcmp(as, bs);
- // We want to disallow duplicate keys, since this results in a
- // map where values cannot be found.
- // But we can't assert here (since we don't want to fail on
- // random JSON input) or have an error mechanism.
- // Instead, we set has_duplicate_keys_ in the builder to
- // signal this.
- // TODO: Have to check for pointer equality, as some sort
- // implementation apparently call this function with the same
- // element?? Why?
- if (!comp && &a != &b) has_duplicate_keys_ = true;
- return comp < 0;
- });
+ auto dict = reinterpret_cast<TwoValue*>(stack_.data() + start);
+ std::sort(dict, dict + len,
+ [&](const TwoValue& a, const TwoValue& b) -> bool {
+ auto as = reinterpret_cast<const char*>(buf_.data() + a.key.u_);
+ auto bs = reinterpret_cast<const char*>(buf_.data() + b.key.u_);
+ auto comp = strcmp(as, bs);
+ // We want to disallow duplicate keys, since this results in a
+ // map where values cannot be found.
+ // But we can't assert here (since we don't want to fail on
+ // random JSON input) or have an error mechanism.
+ // Instead, we set has_duplicate_keys_ in the builder to
+ // signal this.
+ // TODO: Have to check for pointer equality, as some sort
+ // implementation apparently call this function with the same
+ // element?? Why?
+ if (!comp && &a != &b) has_duplicate_keys_ = true;
+ return comp < 0;
+ });
// First create a vector out of all keys.
// TODO(wvo): if kBuilderFlagShareKeyVectors is true, see if we can share
// the first vector.
@@ -1226,29 +1303,33 @@
// Any map with such keys won't be able to retrieve all values.
bool HasDuplicateKeys() const { return has_duplicate_keys_; }
- template<typename F> size_t Vector(F f) {
+ template <typename F>
+ size_t Vector(F f) {
auto start = StartVector();
f();
return EndVector(start, false, false);
}
- template<typename F, typename T> size_t Vector(F f, T &state) {
+ template <typename F, typename T>
+ size_t Vector(F f, T& state) {
auto start = StartVector();
f(state);
return EndVector(start, false, false);
}
- template<typename F> size_t Vector(const char *key, F f) {
+ template <typename F>
+ size_t Vector(const char* key, F f) {
auto start = StartVector(key);
f();
return EndVector(start, false, false);
}
- template<typename F, typename T>
- size_t Vector(const char *key, F f, T &state) {
+ template <typename F, typename T>
+ size_t Vector(const char* key, F f, T& state) {
auto start = StartVector(key);
f(state);
return EndVector(start, false, false);
}
- template<typename T> void Vector(const T *elems, size_t len) {
+ template <typename T>
+ void Vector(const T* elems, size_t len) {
if (flatbuffers::is_scalar<T>::value) {
// This path should be a lot quicker and use less space.
ScalarVector(elems, len, false);
@@ -1258,38 +1339,43 @@
EndVector(start, false, false);
}
}
- template<typename T>
- void Vector(const char *key, const T *elems, size_t len) {
+ template <typename T>
+ void Vector(const char* key, const T* elems, size_t len) {
Key(key);
Vector(elems, len);
}
- template<typename T> void Vector(const std::vector<T> &vec) {
+ template <typename T>
+ void Vector(const std::vector<T>& vec) {
Vector(vec.data(), vec.size());
}
- template<typename F> size_t TypedVector(F f) {
+ template <typename F>
+ size_t TypedVector(F f) {
auto start = StartVector();
f();
return EndVector(start, true, false);
}
- template<typename F, typename T> size_t TypedVector(F f, T &state) {
+ template <typename F, typename T>
+ size_t TypedVector(F f, T& state) {
auto start = StartVector();
f(state);
return EndVector(start, true, false);
}
- template<typename F> size_t TypedVector(const char *key, F f) {
+ template <typename F>
+ size_t TypedVector(const char* key, F f) {
auto start = StartVector(key);
f();
return EndVector(start, true, false);
}
- template<typename F, typename T>
- size_t TypedVector(const char *key, F f, T &state) {
+ template <typename F, typename T>
+ size_t TypedVector(const char* key, F f, T& state) {
auto start = StartVector(key);
f(state);
return EndVector(start, true, false);
}
- template<typename T> size_t FixedTypedVector(const T *elems, size_t len) {
+ template <typename T>
+ size_t FixedTypedVector(const T* elems, size_t len) {
// We only support a few fixed vector lengths. Anything bigger use a
// regular typed vector.
FLATBUFFERS_ASSERT(len >= 2 && len <= 4);
@@ -1298,33 +1384,38 @@
return ScalarVector(elems, len, true);
}
- template<typename T>
- size_t FixedTypedVector(const char *key, const T *elems, size_t len) {
+ template <typename T>
+ size_t FixedTypedVector(const char* key, const T* elems, size_t len) {
Key(key);
return FixedTypedVector(elems, len);
}
- template<typename F> size_t Map(F f) {
+ template <typename F>
+ size_t Map(F f) {
auto start = StartMap();
f();
return EndMap(start);
}
- template<typename F, typename T> size_t Map(F f, T &state) {
+ template <typename F, typename T>
+ size_t Map(F f, T& state) {
auto start = StartMap();
f(state);
return EndMap(start);
}
- template<typename F> size_t Map(const char *key, F f) {
+ template <typename F>
+ size_t Map(const char* key, F f) {
auto start = StartMap(key);
f();
return EndMap(start);
}
- template<typename F, typename T> size_t Map(const char *key, F f, T &state) {
+ template <typename F, typename T>
+ size_t Map(const char* key, F f, T& state) {
auto start = StartMap(key);
f(state);
return EndMap(start);
}
- template<typename T> void Map(const std::map<std::string, T> &map) {
+ template <typename T>
+ void Map(const std::map<std::string, T>& map) {
auto start = StartMap();
for (auto it = map.begin(); it != map.end(); ++it)
Add(it->first.c_str(), it->second);
@@ -1352,16 +1443,14 @@
struct Value;
Value LastValue() { return stack_.back(); }
void ReuseValue(Value v) { stack_.push_back(v); }
- void ReuseValue(const char *key, Value v) {
+ void ReuseValue(const char* key, Value v) {
Key(key);
ReuseValue(v);
}
// Undo the last element serialized. Call once for a value and once for a
// key.
- void Undo() {
- stack_.pop_back();
- }
+ void Undo() { stack_.pop_back(); }
// Overloaded Add that tries to call the correct function above.
void Add(int8_t i) { Int(i); }
@@ -1375,22 +1464,30 @@
void Add(float f) { Float(f); }
void Add(double d) { Double(d); }
void Add(bool b) { Bool(b); }
- void Add(const char *str) { String(str); }
- void Add(const std::string &str) { String(str); }
- void Add(const flexbuffers::String &str) { String(str); }
+ void Add(const char* str) { String(str); }
+ void Add(const std::string& str) { String(str); }
+ void Add(const flexbuffers::String& str) { String(str); }
- template<typename T> void Add(const std::vector<T> &vec) { Vector(vec); }
+ template <typename T>
+ void Add(const std::vector<T>& vec) {
+ Vector(vec);
+ }
- template<typename T> void Add(const char *key, const T &t) {
+ template <typename T>
+ void Add(const char* key, const T& t) {
Key(key);
Add(t);
}
- template<typename T> void Add(const std::map<std::string, T> &map) {
+ template <typename T>
+ void Add(const std::map<std::string, T>& map) {
Map(map);
}
- template<typename T> void operator+=(const T &t) { Add(t); }
+ template <typename T>
+ void operator+=(const T& t) {
+ Add(t);
+ }
// This function is useful in combination with the Mutate* functions above.
// It forces elements of vectors and maps to have a minimum size, such that
@@ -1434,12 +1531,13 @@
return static_cast<uint8_t>(byte_width);
}
- void WriteBytes(const void *val, size_t size) {
- buf_.insert(buf_.end(), reinterpret_cast<const uint8_t *>(val),
- reinterpret_cast<const uint8_t *>(val) + size);
+ void WriteBytes(const void* val, size_t size) {
+ buf_.insert(buf_.end(), reinterpret_cast<const uint8_t*>(val),
+ reinterpret_cast<const uint8_t*>(val) + size);
}
- template<typename T> void Write(T val, size_t byte_width) {
+ template <typename T>
+ void Write(T val, size_t byte_width) {
FLATBUFFERS_ASSERT(sizeof(T) >= byte_width);
val = flatbuffers::EndianScalar(val);
WriteBytes(&val, byte_width);
@@ -1447,11 +1545,16 @@
void WriteDouble(double f, uint8_t byte_width) {
switch (byte_width) {
- case 8: Write(f, byte_width); break;
- case 4: Write(static_cast<float>(f), byte_width); break;
+ case 8:
+ Write(f, byte_width);
+ break;
+ case 4:
+ Write(static_cast<float>(f), byte_width);
+ break;
// case 2: Write(static_cast<half>(f), byte_width); break;
// case 1: Write(static_cast<quarter>(f), byte_width); break;
- default: FLATBUFFERS_ASSERT(0);
+ default:
+ FLATBUFFERS_ASSERT(0);
}
}
@@ -1461,7 +1564,8 @@
Write(reloff, byte_width);
}
- template<typename T> void PushIndirect(T val, Type type, BitWidth bit_width) {
+ template <typename T>
+ void PushIndirect(T val, Type type, BitWidth bit_width) {
auto byte_width = Align(bit_width);
auto iloc = buf_.size();
Write(val, byte_width);
@@ -1470,15 +1574,22 @@
static BitWidth WidthB(size_t byte_width) {
switch (byte_width) {
- case 1: return BIT_WIDTH_8;
- case 2: return BIT_WIDTH_16;
- case 4: return BIT_WIDTH_32;
- case 8: return BIT_WIDTH_64;
- default: FLATBUFFERS_ASSERT(false); return BIT_WIDTH_64;
+ case 1:
+ return BIT_WIDTH_8;
+ case 2:
+ return BIT_WIDTH_16;
+ case 4:
+ return BIT_WIDTH_32;
+ case 8:
+ return BIT_WIDTH_64;
+ default:
+ FLATBUFFERS_ASSERT(false);
+ return BIT_WIDTH_64;
}
}
- template<typename T> static Type GetScalarType() {
+ template <typename T>
+ static Type GetScalarType() {
static_assert(flatbuffers::is_scalar<T>::value, "Unrelated types");
return flatbuffers::is_floating_point<T>::value ? FBT_FLOAT
: flatbuffers::is_same<T, bool>::value
@@ -1561,18 +1672,26 @@
};
private:
- void WriteAny(const Value &val, uint8_t byte_width) {
+ void WriteAny(const Value& val, uint8_t byte_width) {
switch (val.type_) {
case FBT_NULL:
- case FBT_INT: Write(val.i_, byte_width); break;
+ case FBT_INT:
+ Write(val.i_, byte_width);
+ break;
case FBT_BOOL:
- case FBT_UINT: Write(val.u_, byte_width); break;
- case FBT_FLOAT: WriteDouble(val.f_, byte_width); break;
- default: WriteOffset(val.u_, byte_width); break;
+ case FBT_UINT:
+ Write(val.u_, byte_width);
+ break;
+ case FBT_FLOAT:
+ WriteDouble(val.f_, byte_width);
+ break;
+ default:
+ WriteOffset(val.u_, byte_width);
+ break;
}
}
- size_t CreateBlob(const void *data, size_t len, size_t trailing, Type type) {
+ size_t CreateBlob(const void* data, size_t len, size_t trailing, Type type) {
auto bit_width = WidthU(len);
auto byte_width = Align(bit_width);
Write<uint64_t>(len, byte_width);
@@ -1582,8 +1701,8 @@
return sloc;
}
- template<typename T>
- size_t ScalarVector(const T *elems, size_t len, bool fixed) {
+ template <typename T>
+ size_t ScalarVector(const T* elems, size_t len, bool fixed) {
auto vector_type = GetScalarType<T>();
auto byte_width = sizeof(T);
auto bit_width = WidthB(byte_width);
@@ -1604,7 +1723,7 @@
}
Value CreateVector(size_t start, size_t vec_len, size_t step, bool typed,
- bool fixed, const Value *keys = nullptr) {
+ bool fixed, const Value* keys = nullptr) {
FLATBUFFERS_ASSERT(
!fixed ||
typed); // typed=false, fixed=true combination is not supported.
@@ -1662,8 +1781,8 @@
}
// You shouldn't really be copying instances of this class.
- Builder(const Builder &);
- Builder &operator=(const Builder &);
+ Builder(const Builder&);
+ Builder& operator=(const Builder&);
std::vector<uint8_t> buf_;
std::vector<Value> stack_;
@@ -1676,26 +1795,26 @@
BitWidth force_min_bit_width_;
struct KeyOffsetCompare {
- explicit KeyOffsetCompare(const std::vector<uint8_t> &buf) : buf_(&buf) {}
+ explicit KeyOffsetCompare(const std::vector<uint8_t>& buf) : buf_(&buf) {}
bool operator()(size_t a, size_t b) const {
- auto stra = reinterpret_cast<const char *>(buf_->data() + a);
- auto strb = reinterpret_cast<const char *>(buf_->data() + b);
+ auto stra = reinterpret_cast<const char*>(buf_->data() + a);
+ auto strb = reinterpret_cast<const char*>(buf_->data() + b);
return strcmp(stra, strb) < 0;
}
- const std::vector<uint8_t> *buf_;
+ const std::vector<uint8_t>* buf_;
};
typedef std::pair<size_t, size_t> StringOffset;
struct StringOffsetCompare {
- explicit StringOffsetCompare(const std::vector<uint8_t> &buf)
+ explicit StringOffsetCompare(const std::vector<uint8_t>& buf)
: buf_(&buf) {}
- bool operator()(const StringOffset &a, const StringOffset &b) const {
+ bool operator()(const StringOffset& a, const StringOffset& b) const {
auto stra = buf_->data() + a.first;
auto strb = buf_->data() + b.first;
auto cr = memcmp(stra, strb, (std::min)(a.second, b.second) + 1);
return cr < 0 || (cr == 0 && a.second < b.second);
}
- const std::vector<uint8_t> *buf_;
+ const std::vector<uint8_t>* buf_;
};
typedef std::set<size_t, KeyOffsetCompare> KeyOffsetMap;
@@ -1710,12 +1829,12 @@
// Helper class to verify the integrity of a FlexBuffer
class Verifier FLATBUFFERS_FINAL_CLASS {
public:
- Verifier(const uint8_t *buf, size_t buf_len,
+ Verifier(const uint8_t* buf, size_t buf_len,
// Supplying this vector likely results in faster verification
// of larger buffers with many shared keys/strings, but
// comes at the cost of using additional memory the same size of
// the buffer being verified, so it is by default off.
- std::vector<uint8_t> *reuse_tracker = nullptr,
+ std::vector<uint8_t>* reuse_tracker = nullptr,
bool _check_alignment = true, size_t max_depth = 64)
: buf_(buf),
size_(buf_len),
@@ -1725,7 +1844,8 @@
max_vectors_(buf_len),
check_alignment_(_check_alignment),
reuse_tracker_(reuse_tracker) {
- FLATBUFFERS_ASSERT(static_cast<int32_t>(size_) < FLATBUFFERS_MAX_BUFFER_SIZE);
+ FLATBUFFERS_ASSERT(static_cast<int32_t>(size_) <
+ FLATBUFFERS_MAX_BUFFER_SIZE);
if (reuse_tracker_) {
reuse_tracker_->clear();
reuse_tracker_->resize(size_, PackedType(BIT_WIDTH_8, FBT_NULL));
@@ -1751,11 +1871,11 @@
return Check(elem_len <= elem);
}
- bool VerifyFromPointer(const uint8_t *p, size_t len) {
+ bool VerifyFromPointer(const uint8_t* p, size_t len) {
auto o = static_cast<size_t>(p - buf_);
return VerifyFrom(o, len);
}
- bool VerifyBeforePointer(const uint8_t *p, size_t len) {
+ bool VerifyBeforePointer(const uint8_t* p, size_t len) {
auto o = static_cast<size_t>(p - buf_);
return VerifyBefore(o, len);
}
@@ -1766,12 +1886,12 @@
bool VerifyType(int type) { return Check(type >= 0 && type < FBT_MAX_TYPE); }
- bool VerifyOffset(uint64_t off, const uint8_t *p) {
+ bool VerifyOffset(uint64_t off, const uint8_t* p) {
return Check(off <= static_cast<uint64_t>(size_)) &&
off <= static_cast<uint64_t>(p - buf_);
}
- bool VerifyAlignment(const uint8_t *p, size_t size) const {
+ bool VerifyAlignment(const uint8_t* p, size_t size) const {
auto o = static_cast<size_t>(p - buf_);
return Check((o & (size - 1)) == 0 || !check_alignment_);
}
@@ -1787,7 +1907,7 @@
(*reuse_tracker_)[P - buf_] = packed_type; \
}
- bool VerifyVector(Reference r, const uint8_t *p, Type elem_type) {
+ bool VerifyVector(Reference r, const uint8_t* p, Type elem_type) {
// Any kind of nesting goes thru this function, so guard against that
// here, both with simple nesting checks, and the reuse tracker if on.
depth_++;
@@ -1825,7 +1945,7 @@
return true;
}
- bool VerifyKeys(const uint8_t *p, uint8_t byte_width) {
+ bool VerifyKeys(const uint8_t* p, uint8_t byte_width) {
// The vector part of the map has already been verified.
const size_t num_prefixed_fields = 3;
if (!VerifyBeforePointer(p, byte_width * num_prefixed_fields)) return false;
@@ -1839,7 +1959,7 @@
p - off, FBT_KEY);
}
- bool VerifyKey(const uint8_t *p) {
+ bool VerifyKey(const uint8_t* p) {
FLEX_CHECK_VERIFIED(p, PackedType(BIT_WIDTH_8, FBT_KEY));
while (p < buf_ + size_)
if (*p++) return true;
@@ -1848,8 +1968,8 @@
#undef FLEX_CHECK_VERIFIED
- bool VerifyTerminator(const String &s) {
- return VerifyFromPointer(reinterpret_cast<const uint8_t *>(s.c_str()),
+ bool VerifyTerminator(const String& s) {
+ return VerifyFromPointer(reinterpret_cast<const uint8_t*>(s.c_str()),
s.size() + 1);
}
@@ -1870,20 +1990,28 @@
switch (r.type_) {
case FBT_INDIRECT_INT:
case FBT_INDIRECT_UINT:
- case FBT_INDIRECT_FLOAT: return VerifyFromPointer(p, r.byte_width_);
- case FBT_KEY: return VerifyKey(p);
+ case FBT_INDIRECT_FLOAT:
+ return VerifyFromPointer(p, r.byte_width_);
+ case FBT_KEY:
+ return VerifyKey(p);
case FBT_MAP:
return VerifyVector(r, p, FBT_NULL) && VerifyKeys(p, r.byte_width_);
- case FBT_VECTOR: return VerifyVector(r, p, FBT_NULL);
- case FBT_VECTOR_INT: return VerifyVector(r, p, FBT_INT);
+ case FBT_VECTOR:
+ return VerifyVector(r, p, FBT_NULL);
+ case FBT_VECTOR_INT:
+ return VerifyVector(r, p, FBT_INT);
case FBT_VECTOR_BOOL:
- case FBT_VECTOR_UINT: return VerifyVector(r, p, FBT_UINT);
- case FBT_VECTOR_FLOAT: return VerifyVector(r, p, FBT_FLOAT);
- case FBT_VECTOR_KEY: return VerifyVector(r, p, FBT_KEY);
+ case FBT_VECTOR_UINT:
+ return VerifyVector(r, p, FBT_UINT);
+ case FBT_VECTOR_FLOAT:
+ return VerifyVector(r, p, FBT_FLOAT);
+ case FBT_VECTOR_KEY:
+ return VerifyVector(r, p, FBT_KEY);
case FBT_VECTOR_STRING_DEPRECATED:
// Use of FBT_KEY here intentional, see elsewhere.
return VerifyVector(r, p, FBT_KEY);
- case FBT_BLOB: return VerifyVector(r, p, FBT_UINT);
+ case FBT_BLOB:
+ return VerifyVector(r, p, FBT_UINT);
case FBT_STRING:
return VerifyVector(r, p, FBT_UINT) &&
VerifyTerminator(String(p, r.byte_width_));
@@ -1901,7 +2029,8 @@
if (!VerifyType(vtype)) return false;
return VerifyFromPointer(p, static_cast<size_t>(r.byte_width_) * len);
}
- default: return false;
+ default:
+ return false;
}
}
@@ -1916,20 +2045,20 @@
}
private:
- const uint8_t *buf_;
+ const uint8_t* buf_;
size_t size_;
size_t depth_;
const size_t max_depth_;
size_t num_vectors_;
const size_t max_vectors_;
bool check_alignment_;
- std::vector<uint8_t> *reuse_tracker_;
+ std::vector<uint8_t>* reuse_tracker_;
};
// Utility function that constructs the Verifier for you, see above for
// parameters.
-inline bool VerifyBuffer(const uint8_t *buf, size_t buf_len,
- std::vector<uint8_t> *reuse_tracker = nullptr) {
+inline bool VerifyBuffer(const uint8_t* buf, size_t buf_len,
+ std::vector<uint8_t>* reuse_tracker = nullptr) {
Verifier verifier(buf, buf_len, reuse_tracker);
return verifier.VerifyBuffer();
}
@@ -1937,7 +2066,7 @@
} // namespace flexbuffers
#if defined(_MSC_VER)
-# pragma warning(pop)
+#pragma warning(pop)
#endif
#endif // FLATBUFFERS_FLEXBUFFERS_H_
diff --git a/include/flatbuffers/grpc.h b/include/flatbuffers/grpc.h
index 500df84..74633fd 100644
--- a/include/flatbuffers/grpc.h
+++ b/include/flatbuffers/grpc.h
@@ -30,23 +30,24 @@
// `grpc_slice` and also provides flatbuffers-specific helpers such as `Verify`
// and `GetRoot`. Since it is backed by a `grpc_slice`, the underlying buffer
// is refcounted and ownership is be managed automatically.
-template<class T> class Message {
+template <class T>
+class Message {
public:
Message() {}
Message(::grpc::Slice slice) : slice_(slice) {}
- Message &operator=(const Message &other) = delete;
+ Message& operator=(const Message& other) = delete;
- Message(Message &&other) = default;
+ Message(Message&& other) = default;
- Message(const Message &other) = delete;
+ Message(const Message& other) = delete;
- Message &operator=(Message &&other) = default;
+ Message& operator=(Message&& other) = default;
- const uint8_t *mutable_data() const { return slice_.begin(); }
+ const uint8_t* mutable_data() const { return slice_.begin(); }
- const uint8_t *data() const { return slice_.begin(); }
+ const uint8_t* data() const { return slice_.begin(); }
size_t size() const { return slice_.size(); }
@@ -55,12 +56,12 @@
return verifier.VerifyBuffer<T>(nullptr);
}
- T *GetMutableRoot() { return flatbuffers::GetMutableRoot<T>(mutable_data()); }
+ T* GetMutableRoot() { return flatbuffers::GetMutableRoot<T>(mutable_data()); }
- const T *GetRoot() const { return flatbuffers::GetRoot<T>(data()); }
+ const T* GetRoot() const { return flatbuffers::GetRoot<T>(data()); }
// This is only intended for serializer use, or if you know what you're doing
- const ::grpc::Slice &BorrowSlice() const { return slice_; }
+ const ::grpc::Slice& BorrowSlice() const { return slice_; }
private:
::grpc::Slice slice_;
@@ -75,41 +76,41 @@
public:
SliceAllocator() {}
- SliceAllocator(const SliceAllocator &other) = delete;
- SliceAllocator &operator=(const SliceAllocator &other) = delete;
+ SliceAllocator(const SliceAllocator& other) = delete;
+ SliceAllocator& operator=(const SliceAllocator& other) = delete;
- SliceAllocator(SliceAllocator &&other) {
+ SliceAllocator(SliceAllocator&& other) {
// default-construct and swap idiom
swap(other);
}
- SliceAllocator &operator=(SliceAllocator &&other) {
+ SliceAllocator& operator=(SliceAllocator&& other) {
// move-construct and swap idiom
SliceAllocator temp(std::move(other));
swap(temp);
return *this;
}
- void swap(SliceAllocator &other) {
+ void swap(SliceAllocator& other) {
using std::swap;
swap(slice_, other.slice_);
}
virtual ~SliceAllocator() {}
- virtual uint8_t *allocate(size_t size) override {
+ virtual uint8_t* allocate(size_t size) override {
FLATBUFFERS_ASSERT(slice_.size() == 0);
slice_ = ::grpc::Slice(size);
- return const_cast<uint8_t *>(slice_.begin());
+ return const_cast<uint8_t*>(slice_.begin());
}
- virtual void deallocate(uint8_t *p, size_t size) override {
+ virtual void deallocate(uint8_t* p, size_t size) override {
FLATBUFFERS_ASSERT(p == slice_.begin());
FLATBUFFERS_ASSERT(size == slice_.size());
slice_ = ::grpc::Slice();
}
- virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size,
+ virtual uint8_t* reallocate_downward(uint8_t* old_p, size_t old_size,
size_t new_size, size_t in_use_back,
size_t in_use_front) override {
FLATBUFFERS_ASSERT(old_p == slice_.begin());
@@ -117,15 +118,15 @@
FLATBUFFERS_ASSERT(new_size > old_size);
::grpc::Slice old_slice = slice_;
::grpc::Slice new_slice = ::grpc::Slice(new_size);
- uint8_t *new_p = const_cast<uint8_t *>(new_slice.begin());
+ uint8_t* new_p = const_cast<uint8_t*>(new_slice.begin());
memcpy_downward(old_p, old_size, new_p, new_size, in_use_back,
in_use_front);
slice_ = new_slice;
- return const_cast<uint8_t *>(slice_.begin());
+ return const_cast<uint8_t*>(slice_.begin());
}
private:
- ::grpc::Slice &get_slice(uint8_t *p, size_t size) {
+ ::grpc::Slice& get_slice(uint8_t* p, size_t size) {
FLATBUFFERS_ASSERT(p == slice_.begin());
FLATBUFFERS_ASSERT(size == slice_.size());
return slice_;
@@ -153,24 +154,24 @@
explicit MessageBuilder(uoffset_t initial_size = 1024)
: FlatBufferBuilder(initial_size, &slice_allocator_, false) {}
- MessageBuilder(const MessageBuilder &other) = delete;
- MessageBuilder &operator=(const MessageBuilder &other) = delete;
+ MessageBuilder(const MessageBuilder& other) = delete;
+ MessageBuilder& operator=(const MessageBuilder& other) = delete;
- MessageBuilder(MessageBuilder &&other)
+ MessageBuilder(MessageBuilder&& other)
: FlatBufferBuilder(1024, &slice_allocator_, false) {
// Default construct and swap idiom.
Swap(other);
}
/// Create a MessageBuilder from a FlatBufferBuilder.
- explicit MessageBuilder(FlatBufferBuilder &&src,
- void (*dealloc)(void *,
+ explicit MessageBuilder(FlatBufferBuilder&& src,
+ void (*dealloc)(void*,
size_t) = &DefaultAllocator::dealloc)
: FlatBufferBuilder(1024, &slice_allocator_, false) {
src.Swap(*this);
src.SwapBufAllocator(*this);
if (buf_.capacity()) {
- uint8_t *buf = buf_.scratch_data(); // pointer to memory
+ uint8_t* buf = buf_.scratch_data(); // pointer to memory
size_t capacity = buf_.capacity(); // size of memory
slice_allocator_.slice_ = ::grpc::Slice(buf, capacity, dealloc);
} else {
@@ -181,21 +182,21 @@
/// Move-assign a FlatBufferBuilder to a MessageBuilder.
/// Only FlatBufferBuilder with default allocator (basically, nullptr) is
/// supported.
- MessageBuilder &operator=(FlatBufferBuilder &&src) {
+ MessageBuilder& operator=(FlatBufferBuilder&& src) {
// Move construct a temporary and swap
MessageBuilder temp(std::move(src));
Swap(temp);
return *this;
}
- MessageBuilder &operator=(MessageBuilder &&other) {
+ MessageBuilder& operator=(MessageBuilder&& other) {
// Move construct a temporary and swap
MessageBuilder temp(std::move(other));
Swap(temp);
return *this;
}
- void Swap(MessageBuilder &other) {
+ void Swap(MessageBuilder& other) {
slice_allocator_.swap(other.slice_allocator_);
FlatBufferBuilder::Swap(other);
// After swapping the FlatBufferBuilder, we swap back the allocator, which
@@ -209,8 +210,8 @@
// Releases the ownership of the buffer pointer.
// Returns the size, offset, and the original grpc_slice that
// allocated the buffer. Also see grpc_slice_unref().
- uint8_t *ReleaseRaw(size_t &size, size_t &offset, ::grpc::Slice &slice) {
- uint8_t *buf = FlatBufferBuilder::ReleaseRaw(size, offset);
+ uint8_t* ReleaseRaw(size_t& size, size_t& offset, ::grpc::Slice& slice) {
+ uint8_t* buf = FlatBufferBuilder::ReleaseRaw(size, offset);
slice = slice_allocator_.slice_;
slice_allocator_.slice_ = ::grpc::Slice();
return buf;
@@ -221,7 +222,8 @@
// GetMessage extracts the subslice of the buffer corresponding to the
// flatbuffers-encoded region and wraps it in a `Message<T>` to handle buffer
// ownership.
- template<class T> Message<T> GetMessage() {
+ template <class T>
+ Message<T> GetMessage() {
auto buf_data = buf_.scratch_data(); // pointer to memory
auto buf_size = buf_.capacity(); // size of memory
auto msg_data = buf_.data(); // pointer to msg
@@ -243,7 +245,8 @@
return msg;
}
- template<class T> Message<T> ReleaseMessage() {
+ template <class T>
+ Message<T> ReleaseMessage() {
Message<T> msg = GetMessage<T>();
Reset();
return msg;
@@ -258,10 +261,11 @@
namespace grpc {
-template<class T> class SerializationTraits<flatbuffers::grpc::Message<T>> {
+template <class T>
+class SerializationTraits<flatbuffers::grpc::Message<T>> {
public:
- static grpc::Status Serialize(const flatbuffers::grpc::Message<T> &msg,
- ByteBuffer *buffer, bool *own_buffer) {
+ static grpc::Status Serialize(const flatbuffers::grpc::Message<T>& msg,
+ ByteBuffer* buffer, bool* own_buffer) {
// Package the single slice into a `ByteBuffer`,
// incrementing the refcount in the process.
*buffer = ByteBuffer(&msg.BorrowSlice(), 1);
@@ -270,8 +274,8 @@
}
// Deserialize by pulling the
- static grpc::Status Deserialize(ByteBuffer *buf,
- flatbuffers::grpc::Message<T> *msg) {
+ static grpc::Status Deserialize(ByteBuffer* buf,
+ flatbuffers::grpc::Message<T>* msg) {
Slice slice;
if (!buf->TrySingleSlice(&slice).ok()) {
if (!buf->DumpToSingleSlice(&slice).ok()) {
diff --git a/include/flatbuffers/hash.h b/include/flatbuffers/hash.h
index aebf071..2e92c09 100644
--- a/include/flatbuffers/hash.h
+++ b/include/flatbuffers/hash.h
@@ -24,73 +24,81 @@
namespace flatbuffers {
-template<typename T> struct FnvTraits {
+template <typename T>
+struct FnvTraits {
static const T kFnvPrime;
static const T kOffsetBasis;
};
-template<> struct FnvTraits<uint32_t> {
+template <>
+struct FnvTraits<uint32_t> {
static const uint32_t kFnvPrime = 0x01000193;
static const uint32_t kOffsetBasis = 0x811C9DC5;
};
-template<> struct FnvTraits<uint64_t> {
+template <>
+struct FnvTraits<uint64_t> {
static const uint64_t kFnvPrime = 0x00000100000001b3ULL;
static const uint64_t kOffsetBasis = 0xcbf29ce484222645ULL;
};
-template<typename T> T HashFnv1(const char *input) {
+template <typename T>
+T HashFnv1(const char* input) {
T hash = FnvTraits<T>::kOffsetBasis;
- for (const char *c = input; *c; ++c) {
+ for (const char* c = input; *c; ++c) {
hash *= FnvTraits<T>::kFnvPrime;
hash ^= static_cast<unsigned char>(*c);
}
return hash;
}
-template<typename T> T HashFnv1a(const char *input) {
+template <typename T>
+T HashFnv1a(const char* input) {
T hash = FnvTraits<T>::kOffsetBasis;
- for (const char *c = input; *c; ++c) {
+ for (const char* c = input; *c; ++c) {
hash ^= static_cast<unsigned char>(*c);
hash *= FnvTraits<T>::kFnvPrime;
}
return hash;
}
-template<> inline uint16_t HashFnv1<uint16_t>(const char *input) {
+template <>
+inline uint16_t HashFnv1<uint16_t>(const char* input) {
uint32_t hash = HashFnv1<uint32_t>(input);
return (hash >> 16) ^ (hash & 0xffff);
}
-template<> inline uint16_t HashFnv1a<uint16_t>(const char *input) {
+template <>
+inline uint16_t HashFnv1a<uint16_t>(const char* input) {
uint32_t hash = HashFnv1a<uint32_t>(input);
return (hash >> 16) ^ (hash & 0xffff);
}
-template<typename T> struct NamedHashFunction {
- const char *name;
+template <typename T>
+struct NamedHashFunction {
+ const char* name;
- typedef T (*HashFunction)(const char *);
+ typedef T (*HashFunction)(const char*);
HashFunction function;
};
const NamedHashFunction<uint16_t> kHashFunctions16[] = {
- { "fnv1_16", HashFnv1<uint16_t> },
- { "fnv1a_16", HashFnv1a<uint16_t> },
+ {"fnv1_16", HashFnv1<uint16_t>},
+ {"fnv1a_16", HashFnv1a<uint16_t>},
};
const NamedHashFunction<uint32_t> kHashFunctions32[] = {
- { "fnv1_32", HashFnv1<uint32_t> },
- { "fnv1a_32", HashFnv1a<uint32_t> },
+ {"fnv1_32", HashFnv1<uint32_t>},
+ {"fnv1a_32", HashFnv1a<uint32_t>},
};
const NamedHashFunction<uint64_t> kHashFunctions64[] = {
- { "fnv1_64", HashFnv1<uint64_t> },
- { "fnv1a_64", HashFnv1a<uint64_t> },
+ {"fnv1_64", HashFnv1<uint64_t>},
+ {"fnv1a_64", HashFnv1a<uint64_t>},
};
inline NamedHashFunction<uint16_t>::HashFunction FindHashFunction16(
- const char *name) {
+ const char* name) {
std::size_t size = sizeof(kHashFunctions16) / sizeof(kHashFunctions16[0]);
for (std::size_t i = 0; i < size; ++i) {
if (std::strcmp(name, kHashFunctions16[i].name) == 0) {
@@ -101,7 +109,7 @@
}
inline NamedHashFunction<uint32_t>::HashFunction FindHashFunction32(
- const char *name) {
+ const char* name) {
std::size_t size = sizeof(kHashFunctions32) / sizeof(kHashFunctions32[0]);
for (std::size_t i = 0; i < size; ++i) {
if (std::strcmp(name, kHashFunctions32[i].name) == 0) {
@@ -112,7 +120,7 @@
}
inline NamedHashFunction<uint64_t>::HashFunction FindHashFunction64(
- const char *name) {
+ const char* name) {
std::size_t size = sizeof(kHashFunctions64) / sizeof(kHashFunctions64[0]);
for (std::size_t i = 0; i < size; ++i) {
if (std::strcmp(name, kHashFunctions64[i].name) == 0) {
diff --git a/include/flatbuffers/idl.h b/include/flatbuffers/idl.h
index b6b669c..1c551e9 100644
--- a/include/flatbuffers/idl.h
+++ b/include/flatbuffers/idl.h
@@ -36,7 +36,7 @@
// Limits maximum depth of nested objects.
// Prevents stack overflow while parse scheme, or json, or flexbuffer.
#if !defined(FLATBUFFERS_MAX_PARSING_DEPTH)
-# define FLATBUFFERS_MAX_PARSING_DEPTH 64
+#define FLATBUFFERS_MAX_PARSING_DEPTH 64
#endif
namespace flatbuffers {
@@ -192,15 +192,15 @@
// Represents any type in the IDL, which is a combination of the BaseType
// and additional information for vectors/structs_.
struct Type {
- explicit Type(BaseType _base_type = BASE_TYPE_NONE, StructDef *_sd = nullptr,
- EnumDef *_ed = nullptr, uint16_t _fixed_length = 0)
+ explicit Type(BaseType _base_type = BASE_TYPE_NONE, StructDef* _sd = nullptr,
+ EnumDef* _ed = nullptr, uint16_t _fixed_length = 0)
: base_type(_base_type),
element(BASE_TYPE_NONE),
struct_def(_sd),
enum_def(_ed),
fixed_length(_fixed_length) {}
- bool operator==(const Type &o) const {
+ bool operator==(const Type& o) const {
return base_type == o.base_type && element == o.element &&
struct_def == o.struct_def && enum_def == o.enum_def;
}
@@ -209,15 +209,15 @@
return Type(element, struct_def, enum_def, fixed_length);
}
- Offset<reflection::Type> Serialize(FlatBufferBuilder *builder) const;
+ Offset<reflection::Type> Serialize(FlatBufferBuilder* builder) const;
- bool Deserialize(const Parser &parser, const reflection::Type *type);
+ bool Deserialize(const Parser& parser, const reflection::Type* type);
BaseType base_type;
BaseType element; // only set if t == BASE_TYPE_VECTOR or
// BASE_TYPE_VECTOR64
- StructDef *struct_def; // only set if t or element == BASE_TYPE_STRUCT
- EnumDef *enum_def; // set if t == BASE_TYPE_UNION / BASE_TYPE_UTYPE,
+ StructDef* struct_def; // only set if t or element == BASE_TYPE_STRUCT
+ EnumDef* enum_def; // set if t == BASE_TYPE_UNION / BASE_TYPE_UTYPE,
// or for an integral type derived from an enum.
uint16_t fixed_length; // only set if t == BASE_TYPE_ARRAY
};
@@ -234,13 +234,16 @@
// Helper class that retains the original order of a set of identifiers and
// also provides quick lookup.
-template<typename T> class SymbolTable {
+template <typename T>
+class SymbolTable {
public:
~SymbolTable() {
- for (auto it = vec.begin(); it != vec.end(); ++it) { delete *it; }
+ for (auto it = vec.begin(); it != vec.end(); ++it) {
+ delete *it;
+ }
}
- bool Add(const std::string &name, T *e) {
+ bool Add(const std::string& name, T* e) {
vec.emplace_back(e);
auto it = dict.find(name);
if (it != dict.end()) return true;
@@ -248,7 +251,7 @@
return false;
}
- void Move(const std::string &oldname, const std::string &newname) {
+ void Move(const std::string& oldname, const std::string& newname) {
auto it = dict.find(oldname);
if (it != dict.end()) {
auto obj = it->second;
@@ -259,14 +262,14 @@
}
}
- T *Lookup(const std::string &name) const {
+ T* Lookup(const std::string& name) const {
auto it = dict.find(name);
return it == dict.end() ? nullptr : it->second;
}
public:
- std::map<std::string, T *> dict; // quick lookup
- std::vector<T *> vec; // Used to iterate in order of insertion
+ std::map<std::string, T*> dict; // quick lookup
+ std::vector<T*> vec; // Used to iterate in order of insertion
};
// A name space, as set in the schema.
@@ -277,14 +280,14 @@
// which has a full namespaced descriptor.
// With max_components you can request less than the number of components
// the current namespace has.
- std::string GetFullyQualifiedName(const std::string &name,
+ std::string GetFullyQualifiedName(const std::string& name,
size_t max_components = 1000) const;
std::vector<std::string> components;
size_t from_table; // Part of the namespace corresponds to a message/table.
};
-inline bool operator<(const Namespace &a, const Namespace &b) {
+inline bool operator<(const Namespace& a, const Namespace& b) {
size_t min_size = std::min(a.components.size(), b.components.size());
for (size_t i = 0; i < min_size; ++i) {
if (a.components[i] != b.components[i])
@@ -305,23 +308,23 @@
flatbuffers::Offset<
flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
- SerializeAttributes(FlatBufferBuilder *builder, const Parser &parser) const;
+ SerializeAttributes(FlatBufferBuilder* builder, const Parser& parser) const;
- bool DeserializeAttributes(Parser &parser,
- const Vector<Offset<reflection::KeyValue>> *attrs);
+ bool DeserializeAttributes(Parser& parser,
+ const Vector<Offset<reflection::KeyValue>>* attrs);
std::string name;
std::string file;
std::vector<std::string> doc_comment;
SymbolTable<Value> attributes;
bool generated; // did we already output code for this definition?
- Namespace *defined_namespace; // Where it was defined.
+ Namespace* defined_namespace; // Where it was defined.
// For use with Serialize()
uoffset_t serialized_location;
int index; // Inside the vector it is stored.
int refcount;
- const std::string *declaration_file;
+ const std::string* declaration_file;
};
struct FieldDef : public Definition {
@@ -337,17 +340,14 @@
padding(0),
sibling_union_field(nullptr) {}
- Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id,
- const Parser &parser) const;
+ Offset<reflection::Field> Serialize(FlatBufferBuilder* builder, uint16_t id,
+ const Parser& parser) const;
- bool Deserialize(Parser &parser, const reflection::Field *field);
+ bool Deserialize(Parser& parser, const reflection::Field* field);
-
- bool IsScalarOptional() const {
- return IsScalar() && IsOptional();
- }
+ bool IsScalarOptional() const { return IsScalar() && IsOptional(); }
bool IsScalar() const {
- return ::flatbuffers::IsScalar(value.type.base_type);
+ return ::flatbuffers::IsScalar(value.type.base_type);
}
bool IsOptional() const { return presence == kOptional; }
bool IsRequired() const { return presence == kRequired; }
@@ -383,14 +383,14 @@
}
Presence presence;
- StructDef *nested_flatbuffer; // This field contains nested FlatBuffer data.
+ StructDef* nested_flatbuffer; // This field contains nested FlatBuffer data.
size_t padding; // Bytes to always pad after this field.
// sibling_union_field is always set to nullptr. The only exception is
// when FieldDef is a union field or an union type field. Therefore,
// sibling_union_field on a union field points to the union type field
// and vice-versa.
- FieldDef *sibling_union_field;
+ FieldDef* sibling_union_field;
};
struct StructDef : public Definition {
@@ -408,10 +408,10 @@
if (fields.vec.size()) fields.vec.back()->padding = padding;
}
- Offset<reflection::Object> Serialize(FlatBufferBuilder *builder,
- const Parser &parser) const;
+ Offset<reflection::Object> Serialize(FlatBufferBuilder* builder,
+ const Parser& parser) const;
- bool Deserialize(Parser &parser, const reflection::Object *object);
+ bool Deserialize(Parser& parser, const reflection::Object* object);
SymbolTable<FieldDef> fields;
@@ -430,17 +430,17 @@
struct EnumValBuilder;
struct EnumVal {
- Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder,
- const Parser &parser) const;
+ Offset<reflection::EnumVal> Serialize(FlatBufferBuilder* builder,
+ const Parser& parser) const;
- bool Deserialize(Parser &parser, const reflection::EnumVal *val);
+ bool Deserialize(Parser& parser, const reflection::EnumVal* val);
flatbuffers::Offset<
flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
- SerializeAttributes(FlatBufferBuilder *builder, const Parser &parser) const;
+ SerializeAttributes(FlatBufferBuilder* builder, const Parser& parser) const;
- bool DeserializeAttributes(Parser &parser,
- const Vector<Offset<reflection::KeyValue>> *attrs);
+ bool DeserializeAttributes(Parser& parser,
+ const Vector<Offset<reflection::KeyValue>>* attrs);
uint64_t GetAsUInt64() const { return static_cast<uint64_t>(value); }
int64_t GetAsInt64() const { return value; }
@@ -455,9 +455,9 @@
private:
friend EnumDef;
friend EnumValBuilder;
- friend bool operator==(const EnumVal &lhs, const EnumVal &rhs);
+ friend bool operator==(const EnumVal& lhs, const EnumVal& rhs);
- EnumVal(const std::string &_name, int64_t _val) : name(_name), value(_val) {}
+ EnumVal(const std::string& _name, int64_t _val) : name(_name), value(_val) {}
EnumVal() : value(0) {}
int64_t value;
@@ -466,37 +466,38 @@
struct EnumDef : public Definition {
EnumDef() : is_union(false), uses_multiple_type_instances(false) {}
- Offset<reflection::Enum> Serialize(FlatBufferBuilder *builder,
- const Parser &parser) const;
+ Offset<reflection::Enum> Serialize(FlatBufferBuilder* builder,
+ const Parser& parser) const;
- bool Deserialize(Parser &parser, const reflection::Enum *values);
+ bool Deserialize(Parser& parser, const reflection::Enum* values);
- template<typename T> void ChangeEnumValue(EnumVal *ev, T new_val);
+ template <typename T>
+ void ChangeEnumValue(EnumVal* ev, T new_val);
void SortByValue();
void RemoveDuplicates();
std::string AllFlags() const;
- const EnumVal *MinValue() const;
- const EnumVal *MaxValue() const;
+ const EnumVal* MinValue() const;
+ const EnumVal* MaxValue() const;
// Returns the number of integer steps from v1 to v2.
- uint64_t Distance(const EnumVal *v1, const EnumVal *v2) const;
+ uint64_t Distance(const EnumVal* v1, const EnumVal* v2) const;
// Returns the number of integer steps from Min to Max.
uint64_t Distance() const { return Distance(MinValue(), MaxValue()); }
- EnumVal *ReverseLookup(int64_t enum_idx,
+ EnumVal* ReverseLookup(int64_t enum_idx,
bool skip_union_default = false) const;
- EnumVal *FindByValue(const std::string &constant) const;
+ EnumVal* FindByValue(const std::string& constant) const;
- std::string ToString(const EnumVal &ev) const {
+ std::string ToString(const EnumVal& ev) const {
return IsUInt64() ? NumToString(ev.GetAsUInt64())
: NumToString(ev.GetAsInt64());
}
size_t size() const { return vals.vec.size(); }
- const std::vector<EnumVal *> &Vals() const { return vals.vec; }
+ const std::vector<EnumVal*>& Vals() const { return vals.vec; }
- const EnumVal *Lookup(const std::string &enum_name) const {
+ const EnumVal* Lookup(const std::string& enum_name) const {
return vals.Lookup(enum_name);
}
@@ -515,53 +516,53 @@
SymbolTable<EnumVal> vals;
};
-inline bool IsString(const Type &type) {
+inline bool IsString(const Type& type) {
return type.base_type == BASE_TYPE_STRING;
}
-inline bool IsStruct(const Type &type) {
+inline bool IsStruct(const Type& type) {
return type.base_type == BASE_TYPE_STRUCT && type.struct_def->fixed;
}
-inline bool IsIncompleteStruct(const Type &type) {
+inline bool IsIncompleteStruct(const Type& type) {
return type.base_type == BASE_TYPE_STRUCT && type.struct_def->predecl;
}
-inline bool IsTable(const Type &type) {
+inline bool IsTable(const Type& type) {
return type.base_type == BASE_TYPE_STRUCT && !type.struct_def->fixed;
}
-inline bool IsUnion(const Type &type) {
+inline bool IsUnion(const Type& type) {
return type.enum_def != nullptr && type.enum_def->is_union;
}
-inline bool IsUnionType(const Type &type) {
+inline bool IsUnionType(const Type& type) {
return IsUnion(type) && IsInteger(type.base_type);
}
-inline bool IsVector(const Type &type) { return IsVector(type.base_type); }
+inline bool IsVector(const Type& type) { return IsVector(type.base_type); }
-inline bool IsVectorOfStruct(const Type &type) {
+inline bool IsVectorOfStruct(const Type& type) {
return IsVector(type) && IsStruct(type.VectorType());
}
-inline bool IsVectorOfTable(const Type &type) {
+inline bool IsVectorOfTable(const Type& type) {
return IsVector(type) && IsTable(type.VectorType());
}
-inline bool IsArray(const Type &type) {
+inline bool IsArray(const Type& type) {
return type.base_type == BASE_TYPE_ARRAY;
}
-inline bool IsSeries(const Type &type) {
+inline bool IsSeries(const Type& type) {
return IsVector(type) || IsArray(type);
}
-inline bool IsEnum(const Type &type) {
+inline bool IsEnum(const Type& type) {
return type.enum_def != nullptr && IsInteger(type.base_type);
}
-inline size_t InlineSize(const Type &type) {
+inline size_t InlineSize(const Type& type) {
return IsStruct(type)
? type.struct_def->bytesize
: (IsArray(type)
@@ -569,7 +570,7 @@
: SizeOf(type.base_type));
}
-inline size_t InlineAlignment(const Type &type) {
+inline size_t InlineAlignment(const Type& type) {
if (IsStruct(type)) {
return type.struct_def->minalign;
} else if (IsArray(type)) {
@@ -579,14 +580,14 @@
return SizeOf(type.base_type);
}
}
-inline bool operator==(const EnumVal &lhs, const EnumVal &rhs) {
+inline bool operator==(const EnumVal& lhs, const EnumVal& rhs) {
return lhs.value == rhs.value;
}
-inline bool operator!=(const EnumVal &lhs, const EnumVal &rhs) {
+inline bool operator!=(const EnumVal& lhs, const EnumVal& rhs) {
return !(lhs == rhs);
}
-inline bool EqualByName(const Type &a, const Type &b) {
+inline bool EqualByName(const Type& a, const Type& b) {
return a.base_type == b.base_type && a.element == b.element &&
(a.struct_def == b.struct_def ||
(a.struct_def != nullptr && b.struct_def != nullptr &&
@@ -597,18 +598,18 @@
}
struct RPCCall : public Definition {
- Offset<reflection::RPCCall> Serialize(FlatBufferBuilder *builder,
- const Parser &parser) const;
+ Offset<reflection::RPCCall> Serialize(FlatBufferBuilder* builder,
+ const Parser& parser) const;
- bool Deserialize(Parser &parser, const reflection::RPCCall *call);
+ bool Deserialize(Parser& parser, const reflection::RPCCall* call);
StructDef *request, *response;
};
struct ServiceDef : public Definition {
- Offset<reflection::Service> Serialize(FlatBufferBuilder *builder,
- const Parser &parser) const;
- bool Deserialize(Parser &parser, const reflection::Service *service);
+ Offset<reflection::Service> Serialize(FlatBufferBuilder* builder,
+ const Parser& parser) const;
+ bool Deserialize(Parser& parser, const reflection::Service* service);
SymbolTable<RPCCall> calls;
};
@@ -627,7 +628,7 @@
};
// Since IncludedFile is contained within a std::set, need to provide ordering.
-inline bool operator<(const IncludedFile &a, const IncludedFile &b) {
+inline bool operator<(const IncludedFile& a, const IncludedFile& b) {
return a.filename < b.filename;
}
@@ -711,7 +712,7 @@
/********************************** Python **********************************/
bool python_no_type_prefix_suffix;
bool python_typing;
- bool python_decode_obj_api_strings=false;
+ bool python_decode_obj_api_strings = false;
// The target Python version. Can be one of the following:
// - "0"
@@ -881,7 +882,7 @@
attr_is_trivial_ascii_string_(true) {}
protected:
- void ResetState(const char *source) {
+ void ResetState(const char* source) {
prev_cursor_ = source;
cursor_ = source;
line_ = 0;
@@ -898,9 +899,9 @@
return static_cast<int64_t>(cursor_ - line_start_);
}
- const char *prev_cursor_;
- const char *cursor_;
- const char *line_start_;
+ const char* prev_cursor_;
+ const char* cursor_;
+ const char* line_start_;
int line_; // the current line being parsed
int token_;
@@ -924,14 +925,14 @@
explicit CheckedError(bool error)
: is_error_(error), has_been_checked_(false) {}
- CheckedError &operator=(const CheckedError &other) {
+ CheckedError& operator=(const CheckedError& other) {
is_error_ = other.is_error_;
has_been_checked_ = false;
other.has_been_checked_ = true;
return *this;
}
- CheckedError(const CheckedError &other) {
+ CheckedError(const CheckedError& other) {
*this = other; // Use assignment operator.
}
@@ -960,7 +961,7 @@
class Parser : public ParserState {
public:
- explicit Parser(const IDLOptions &options = IDLOptions())
+ explicit Parser(const IDLOptions& options = IDLOptions())
: current_namespace_(nullptr),
empty_namespace_(nullptr),
flex_builder_(256, flexbuffers::BUILDER_FLAG_SHARE_ALL),
@@ -972,7 +973,9 @@
source_(nullptr),
anonymous_counter_(0),
parse_depth_counter_(0) {
- if (opts.force_defaults) { builder_.ForceDefaults(true); }
+ if (opts.force_defaults) {
+ builder_.ForceDefaults(true);
+ }
// Start out with the empty namespace being current.
empty_namespace_ = new Namespace();
namespaces_.push_back(empty_namespace_);
@@ -1012,11 +1015,11 @@
}
// Copying is not allowed
- Parser(const Parser &) = delete;
- Parser &operator=(const Parser &) = delete;
+ Parser(const Parser&) = delete;
+ Parser& operator=(const Parser&) = delete;
- Parser(Parser &&) = default;
- Parser &operator=(Parser &&) = default;
+ Parser(Parser&&) = default;
+ Parser& operator=(Parser&&) = default;
~Parser() {
for (auto it = namespaces_.begin(); it != namespaces_.end(); ++it) {
@@ -1035,16 +1038,16 @@
// supply its name in source_filename.
// All paths specified in this call must be in posix format, if you accept
// paths from user input, please call PosixPath on them first.
- bool Parse(const char *_source, const char **include_paths = nullptr,
- const char *source_filename = nullptr);
+ bool Parse(const char* _source, const char** include_paths = nullptr,
+ const char* source_filename = nullptr);
- bool ParseJson(const char *json, const char *json_filename = nullptr);
+ bool ParseJson(const char* json, const char* json_filename = nullptr);
// Returns the number of characters were consumed when parsing a JSON string.
std::ptrdiff_t BytesConsumed() const;
// Set the root type. May override the one set in the schema.
- bool SetRootType(const char *name);
+ bool SetRootType(const char* name);
// Mark all definitions as already having code generated.
void MarkGenerated();
@@ -1052,41 +1055,41 @@
// Get the files recursively included by the given file. The returned
// container will have at least the given file.
std::set<std::string> GetIncludedFilesRecursive(
- const std::string &file_name) const;
+ const std::string& file_name) const;
// Fills builder_ with a binary version of the schema parsed.
// See reflection/reflection.fbs
void Serialize();
// Deserialize a schema buffer
- bool Deserialize(const uint8_t *buf, const size_t size);
+ bool Deserialize(const uint8_t* buf, const size_t size);
// Fills internal structure as if the schema passed had been loaded by parsing
// with Parse except that included filenames will not be populated.
- bool Deserialize(const reflection::Schema *schema);
+ bool Deserialize(const reflection::Schema* schema);
- Type *DeserializeType(const reflection::Type *type);
+ Type* DeserializeType(const reflection::Type* type);
// Checks that the schema represented by this parser is a safe evolution
// of the schema provided. Returns non-empty error on any problems.
- std::string ConformTo(const Parser &base);
+ std::string ConformTo(const Parser& base);
// Similar to Parse(), but now only accepts JSON to be parsed into a
// FlexBuffer.
- bool ParseFlexBuffer(const char *source, const char *source_filename,
- flexbuffers::Builder *builder);
+ bool ParseFlexBuffer(const char* source, const char* source_filename,
+ flexbuffers::Builder* builder);
- StructDef *LookupStruct(const std::string &id) const;
- StructDef *LookupStructThruParentNamespaces(const std::string &id) const;
+ StructDef* LookupStruct(const std::string& id) const;
+ StructDef* LookupStructThruParentNamespaces(const std::string& id) const;
- std::string UnqualifiedName(const std::string &fullQualifiedName);
+ std::string UnqualifiedName(const std::string& fullQualifiedName);
- FLATBUFFERS_CHECKED_ERROR Error(const std::string &msg);
+ FLATBUFFERS_CHECKED_ERROR Error(const std::string& msg);
// @brief Verify that any of 'opts.lang_to_generate' supports Optional scalars
// in a schema.
// @param opts Options used to parce a schema and generate code.
- static bool SupportsOptionalScalars(const flatbuffers::IDLOptions &opts);
+ static bool SupportsOptionalScalars(const flatbuffers::IDLOptions& opts);
// Get the set of included files that are directly referenced by the file
// being parsed. This does not include files that are transitively included by
@@ -1096,101 +1099,101 @@
private:
class ParseDepthGuard;
- void Message(const std::string &msg);
- void Warning(const std::string &msg);
- FLATBUFFERS_CHECKED_ERROR ParseHexNum(int nibbles, uint64_t *val);
+ void Message(const std::string& msg);
+ void Warning(const std::string& msg);
+ FLATBUFFERS_CHECKED_ERROR ParseHexNum(int nibbles, uint64_t* val);
FLATBUFFERS_CHECKED_ERROR Next();
FLATBUFFERS_CHECKED_ERROR SkipByteOrderMark();
bool Is(int t) const;
- bool IsIdent(const char *id) const;
+ bool IsIdent(const char* id) const;
FLATBUFFERS_CHECKED_ERROR Expect(int t);
std::string TokenToStringId(int t) const;
- EnumDef *LookupEnum(const std::string &id);
- FLATBUFFERS_CHECKED_ERROR ParseNamespacing(std::string *id,
- std::string *last);
- FLATBUFFERS_CHECKED_ERROR ParseTypeIdent(Type &type);
- FLATBUFFERS_CHECKED_ERROR ParseType(Type &type);
- FLATBUFFERS_CHECKED_ERROR AddField(StructDef &struct_def,
- const std::string &name, const Type &type,
- FieldDef **dest);
- FLATBUFFERS_CHECKED_ERROR ParseField(StructDef &struct_def);
- FLATBUFFERS_CHECKED_ERROR ParseString(Value &val, bool use_string_pooling);
+ EnumDef* LookupEnum(const std::string& id);
+ FLATBUFFERS_CHECKED_ERROR ParseNamespacing(std::string* id,
+ std::string* last);
+ FLATBUFFERS_CHECKED_ERROR ParseTypeIdent(Type& type);
+ FLATBUFFERS_CHECKED_ERROR ParseType(Type& type);
+ FLATBUFFERS_CHECKED_ERROR AddField(StructDef& struct_def,
+ const std::string& name, const Type& type,
+ FieldDef** dest);
+ FLATBUFFERS_CHECKED_ERROR ParseField(StructDef& struct_def);
+ FLATBUFFERS_CHECKED_ERROR ParseString(Value& val, bool use_string_pooling);
FLATBUFFERS_CHECKED_ERROR ParseComma();
- FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value &val, FieldDef *field,
+ FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value& val, FieldDef* field,
size_t parent_fieldn,
- const StructDef *parent_struct_def,
+ const StructDef* parent_struct_def,
size_t count,
bool inside_vector = false);
- template<typename F>
- FLATBUFFERS_CHECKED_ERROR ParseTableDelimiters(size_t &fieldn,
- const StructDef *struct_def,
+ template <typename F>
+ FLATBUFFERS_CHECKED_ERROR ParseTableDelimiters(size_t& fieldn,
+ const StructDef* struct_def,
F body);
- FLATBUFFERS_CHECKED_ERROR ParseTable(const StructDef &struct_def,
- std::string *value, uoffset_t *ovalue);
- void SerializeStruct(const StructDef &struct_def, const Value &val);
- void SerializeStruct(FlatBufferBuilder &builder, const StructDef &struct_def,
- const Value &val);
- template<typename F>
- FLATBUFFERS_CHECKED_ERROR ParseVectorDelimiters(size_t &count, F body);
- FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue,
- FieldDef *field, size_t fieldn);
- FLATBUFFERS_CHECKED_ERROR ParseArray(Value &array);
+ FLATBUFFERS_CHECKED_ERROR ParseTable(const StructDef& struct_def,
+ std::string* value, uoffset_t* ovalue);
+ void SerializeStruct(const StructDef& struct_def, const Value& val);
+ void SerializeStruct(FlatBufferBuilder& builder, const StructDef& struct_def,
+ const Value& val);
+ template <typename F>
+ FLATBUFFERS_CHECKED_ERROR ParseVectorDelimiters(size_t& count, F body);
+ FLATBUFFERS_CHECKED_ERROR ParseVector(const Type& type, uoffset_t* ovalue,
+ FieldDef* field, size_t fieldn);
+ FLATBUFFERS_CHECKED_ERROR ParseArray(Value& array);
FLATBUFFERS_CHECKED_ERROR ParseNestedFlatbuffer(
- Value &val, FieldDef *field, size_t fieldn,
- const StructDef *parent_struct_def);
- FLATBUFFERS_CHECKED_ERROR ParseMetaData(SymbolTable<Value> *attributes);
- FLATBUFFERS_CHECKED_ERROR TryTypedValue(const std::string *name, int dtoken,
- bool check, Value &e, BaseType req,
- bool *destmatch);
- FLATBUFFERS_CHECKED_ERROR ParseHash(Value &e, FieldDef *field);
+ Value& val, FieldDef* field, size_t fieldn,
+ const StructDef* parent_struct_def);
+ FLATBUFFERS_CHECKED_ERROR ParseMetaData(SymbolTable<Value>* attributes);
+ FLATBUFFERS_CHECKED_ERROR TryTypedValue(const std::string* name, int dtoken,
+ bool check, Value& e, BaseType req,
+ bool* destmatch);
+ FLATBUFFERS_CHECKED_ERROR ParseHash(Value& e, FieldDef* field);
FLATBUFFERS_CHECKED_ERROR TokenError();
- FLATBUFFERS_CHECKED_ERROR ParseSingleValue(const std::string *name, Value &e,
+ FLATBUFFERS_CHECKED_ERROR ParseSingleValue(const std::string* name, Value& e,
bool check_now);
- FLATBUFFERS_CHECKED_ERROR ParseFunction(const std::string *name, Value &e);
- FLATBUFFERS_CHECKED_ERROR ParseEnumFromString(const Type &type,
- std::string *result);
- StructDef *LookupCreateStruct(const std::string &name,
+ FLATBUFFERS_CHECKED_ERROR ParseFunction(const std::string* name, Value& e);
+ FLATBUFFERS_CHECKED_ERROR ParseEnumFromString(const Type& type,
+ std::string* result);
+ StructDef* LookupCreateStruct(const std::string& name,
bool create_if_new = true,
bool definition = false);
- FLATBUFFERS_CHECKED_ERROR ParseEnum(bool is_union, EnumDef **dest,
- const char *filename);
+ FLATBUFFERS_CHECKED_ERROR ParseEnum(bool is_union, EnumDef** dest,
+ const char* filename);
FLATBUFFERS_CHECKED_ERROR ParseNamespace();
- FLATBUFFERS_CHECKED_ERROR StartStruct(const std::string &name,
- StructDef **dest);
- FLATBUFFERS_CHECKED_ERROR StartEnum(const std::string &name, bool is_union,
- EnumDef **dest);
- FLATBUFFERS_CHECKED_ERROR ParseDecl(const char *filename);
- FLATBUFFERS_CHECKED_ERROR ParseService(const char *filename);
- FLATBUFFERS_CHECKED_ERROR ParseProtoFields(StructDef *struct_def,
+ FLATBUFFERS_CHECKED_ERROR StartStruct(const std::string& name,
+ StructDef** dest);
+ FLATBUFFERS_CHECKED_ERROR StartEnum(const std::string& name, bool is_union,
+ EnumDef** dest);
+ FLATBUFFERS_CHECKED_ERROR ParseDecl(const char* filename);
+ FLATBUFFERS_CHECKED_ERROR ParseService(const char* filename);
+ FLATBUFFERS_CHECKED_ERROR ParseProtoFields(StructDef* struct_def,
bool isextend, bool inside_oneof);
- FLATBUFFERS_CHECKED_ERROR ParseProtoMapField(StructDef *struct_def);
+ FLATBUFFERS_CHECKED_ERROR ParseProtoMapField(StructDef* struct_def);
FLATBUFFERS_CHECKED_ERROR ParseProtoOption();
FLATBUFFERS_CHECKED_ERROR ParseProtoKey();
FLATBUFFERS_CHECKED_ERROR ParseProtoDecl();
FLATBUFFERS_CHECKED_ERROR ParseProtoCurliesOrIdent();
- FLATBUFFERS_CHECKED_ERROR ParseTypeFromProtoType(Type *type);
+ FLATBUFFERS_CHECKED_ERROR ParseTypeFromProtoType(Type* type);
FLATBUFFERS_CHECKED_ERROR SkipAnyJsonValue();
FLATBUFFERS_CHECKED_ERROR ParseFlexBufferNumericConstant(
- flexbuffers::Builder *builder);
- FLATBUFFERS_CHECKED_ERROR ParseFlexBufferValue(flexbuffers::Builder *builder);
- FLATBUFFERS_CHECKED_ERROR StartParseFile(const char *source,
- const char *source_filename);
- FLATBUFFERS_CHECKED_ERROR ParseRoot(const char *_source,
- const char **include_paths,
- const char *source_filename);
+ flexbuffers::Builder* builder);
+ FLATBUFFERS_CHECKED_ERROR ParseFlexBufferValue(flexbuffers::Builder* builder);
+ FLATBUFFERS_CHECKED_ERROR StartParseFile(const char* source,
+ const char* source_filename);
+ FLATBUFFERS_CHECKED_ERROR ParseRoot(const char* _source,
+ const char** include_paths,
+ const char* source_filename);
FLATBUFFERS_CHECKED_ERROR CheckPrivateLeak();
FLATBUFFERS_CHECKED_ERROR CheckPrivatelyLeakedFields(
- const Definition &def, const Definition &value_type);
- FLATBUFFERS_CHECKED_ERROR DoParse(const char *_source,
- const char **include_paths,
- const char *source_filename,
- const char *include_filename);
+ const Definition& def, const Definition& value_type);
+ FLATBUFFERS_CHECKED_ERROR DoParse(const char* _source,
+ const char** include_paths,
+ const char* source_filename,
+ const char* include_filename);
FLATBUFFERS_CHECKED_ERROR DoParseJson();
- FLATBUFFERS_CHECKED_ERROR CheckClash(std::vector<FieldDef *> &fields,
- StructDef *struct_def,
- const char *suffix, BaseType baseType);
+ FLATBUFFERS_CHECKED_ERROR CheckClash(std::vector<FieldDef*>& fields,
+ StructDef* struct_def,
+ const char* suffix, BaseType baseType);
FLATBUFFERS_CHECKED_ERROR ParseAlignAttribute(
- const std::string &align_constant, size_t min_align, size_t *align);
+ const std::string& align_constant, size_t min_align, size_t* align);
bool SupportsAdvancedUnionFeatures() const;
bool SupportsAdvancedArrayFeatures() const;
@@ -1198,27 +1201,28 @@
bool SupportsDefaultVectorsAndStrings() const;
bool Supports64BitOffsets() const;
bool SupportsUnionUnderlyingType() const;
- Namespace *UniqueNamespace(Namespace *ns);
+ Namespace* UniqueNamespace(Namespace* ns);
FLATBUFFERS_CHECKED_ERROR RecurseError();
- template<typename F> CheckedError Recurse(F f);
+ template <typename F>
+ CheckedError Recurse(F f);
- const std::string &GetPooledString(const std::string &s) const;
+ const std::string& GetPooledString(const std::string& s) const;
public:
SymbolTable<Type> types_;
SymbolTable<StructDef> structs_;
SymbolTable<EnumDef> enums_;
SymbolTable<ServiceDef> services_;
- std::vector<Namespace *> namespaces_;
- Namespace *current_namespace_;
- Namespace *empty_namespace_;
+ std::vector<Namespace*> namespaces_;
+ Namespace* current_namespace_;
+ Namespace* empty_namespace_;
std::string error_; // User readable error_ if Parse() == false
FlatBufferBuilder builder_; // any data contained in the file
flexbuffers::Builder flex_builder_;
flexbuffers::Reference flex_root_;
- StructDef *root_struct_def_;
+ StructDef* root_struct_def_;
std::string file_identifier_;
std::string file_extension_;
@@ -1237,9 +1241,9 @@
std::string file_being_parsed_;
private:
- const char *source_;
+ const char* source_;
- std::vector<std::pair<Value, FieldDef *>> field_stack_;
+ std::vector<std::pair<Value, FieldDef*>> field_stack_;
// TODO(cneo): Refactor parser to use string_cache more often to save
// on memory usage.
@@ -1260,51 +1264,50 @@
// These functions return nullptr on success, or an error string,
// which may happen if the flatbuffer cannot be encoded in JSON (e.g.,
// it contains non-UTF-8 byte arrays in String values).
-extern bool GenerateTextFromTable(const Parser &parser,
- const void *table,
- const std::string &tablename,
- std::string *text);
-extern const char *GenerateText(const Parser &parser, const void *flatbuffer,
- std::string *text);
-extern const char *GenerateTextFile(const Parser &parser,
- const std::string &path,
- const std::string &file_name);
+extern bool GenerateTextFromTable(const Parser& parser, const void* table,
+ const std::string& tablename,
+ std::string* text);
+extern const char* GenerateText(const Parser& parser, const void* flatbuffer,
+ std::string* text);
+extern const char* GenerateTextFile(const Parser& parser,
+ const std::string& path,
+ const std::string& file_name);
-extern const char *GenTextFromTable(const Parser &parser, const void *table,
- const std::string &tablename,
- std::string *text);
-extern const char *GenText(const Parser &parser, const void *flatbuffer,
- std::string *text);
-extern const char *GenTextFile(const Parser &parser, const std::string &path,
- const std::string &file_name);
+extern const char* GenTextFromTable(const Parser& parser, const void* table,
+ const std::string& tablename,
+ std::string* text);
+extern const char* GenText(const Parser& parser, const void* flatbuffer,
+ std::string* text);
+extern const char* GenTextFile(const Parser& parser, const std::string& path,
+ const std::string& file_name);
// Generate GRPC Cpp interfaces.
// See idl_gen_grpc.cpp.
-bool GenerateCppGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name);
+bool GenerateCppGRPC(const Parser& parser, const std::string& path,
+ const std::string& file_name);
// Generate GRPC Go interfaces.
// See idl_gen_grpc.cpp.
-bool GenerateGoGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name);
+bool GenerateGoGRPC(const Parser& parser, const std::string& path,
+ const std::string& file_name);
// Generate GRPC Java classes.
// See idl_gen_grpc.cpp
-bool GenerateJavaGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name);
+bool GenerateJavaGRPC(const Parser& parser, const std::string& path,
+ const std::string& file_name);
// Generate GRPC Python interfaces.
// See idl_gen_grpc.cpp.
-bool GeneratePythonGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name);
+bool GeneratePythonGRPC(const Parser& parser, const std::string& path,
+ const std::string& file_name);
// Generate GRPC Swift interfaces.
// See idl_gen_grpc.cpp.
-extern bool GenerateSwiftGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name);
+extern bool GenerateSwiftGRPC(const Parser& parser, const std::string& path,
+ const std::string& file_name);
-extern bool GenerateTSGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name);
+extern bool GenerateTSGRPC(const Parser& parser, const std::string& path,
+ const std::string& file_name);
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_H_
diff --git a/include/flatbuffers/minireflect.h b/include/flatbuffers/minireflect.h
index 09ff66c..77be516 100644
--- a/include/flatbuffers/minireflect.h
+++ b/include/flatbuffers/minireflect.h
@@ -42,61 +42,70 @@
// If not present, val == nullptr. set_idx is the index of all set fields.
virtual void Field(size_t /*field_idx*/, size_t /*set_idx*/,
ElementaryType /*type*/, bool /*is_vector*/,
- const TypeTable * /*type_table*/, const char * /*name*/,
- const uint8_t * /*val*/) {}
+ const TypeTable* /*type_table*/, const char* /*name*/,
+ const uint8_t* /*val*/) {}
// Called for a value that is actually present, after a field, or as part
// of a vector.
- virtual void UType(uint8_t, const char *) {}
+ virtual void UType(uint8_t, const char*) {}
virtual void Bool(bool) {}
- virtual void Char(int8_t, const char *) {}
- virtual void UChar(uint8_t, const char *) {}
- virtual void Short(int16_t, const char *) {}
- virtual void UShort(uint16_t, const char *) {}
- virtual void Int(int32_t, const char *) {}
- virtual void UInt(uint32_t, const char *) {}
+ virtual void Char(int8_t, const char*) {}
+ virtual void UChar(uint8_t, const char*) {}
+ virtual void Short(int16_t, const char*) {}
+ virtual void UShort(uint16_t, const char*) {}
+ virtual void Int(int32_t, const char*) {}
+ virtual void UInt(uint32_t, const char*) {}
virtual void Long(int64_t) {}
virtual void ULong(uint64_t) {}
virtual void Float(float) {}
virtual void Double(double) {}
- virtual void String(const String *) {}
- virtual void Unknown(const uint8_t *) {} // From a future version.
+ virtual void String(const String*) {}
+ virtual void Unknown(const uint8_t*) {} // From a future version.
// These mark the scope of a vector.
virtual void StartVector() {}
virtual void EndVector() {}
virtual void Element(size_t /*i*/, ElementaryType /*type*/,
- const TypeTable * /*type_table*/,
- const uint8_t * /*val*/) {}
+ const TypeTable* /*type_table*/,
+ const uint8_t* /*val*/) {}
virtual ~IterationVisitor() {}
};
-inline size_t InlineSize(ElementaryType type, const TypeTable *type_table) {
+inline size_t InlineSize(ElementaryType type, const TypeTable* type_table) {
switch (type) {
case ET_UTYPE:
case ET_BOOL:
case ET_CHAR:
- case ET_UCHAR: return 1;
+ case ET_UCHAR:
+ return 1;
case ET_SHORT:
- case ET_USHORT: return 2;
+ case ET_USHORT:
+ return 2;
case ET_INT:
case ET_UINT:
case ET_FLOAT:
- case ET_STRING: return 4;
+ case ET_STRING:
+ return 4;
case ET_LONG:
case ET_ULONG:
- case ET_DOUBLE: return 8;
+ case ET_DOUBLE:
+ return 8;
case ET_SEQUENCE:
switch (type_table->st) {
case ST_TABLE:
- case ST_UNION: return 4;
+ case ST_UNION:
+ return 4;
case ST_STRUCT:
return static_cast<size_t>(type_table->values[type_table->num_elems]);
- default: FLATBUFFERS_ASSERT(false); return 1;
+ default:
+ FLATBUFFERS_ASSERT(false);
+ return 1;
}
- default: FLATBUFFERS_ASSERT(false); return 1;
+ default:
+ FLATBUFFERS_ASSERT(false);
+ return 1;
}
}
-inline int64_t LookupEnum(int64_t enum_val, const int64_t *values,
+inline int64_t LookupEnum(int64_t enum_val, const int64_t* values,
size_t num_values) {
if (!values) return enum_val;
for (size_t i = 0; i < num_values; i++) {
@@ -105,7 +114,8 @@
return -1; // Unknown enum value.
}
-template<typename T> const char *EnumName(T tval, const TypeTable *type_table) {
+template <typename T>
+const char* EnumName(T tval, const TypeTable* type_table) {
if (!type_table || !type_table->names) return nullptr;
auto i = LookupEnum(static_cast<int64_t>(tval), type_table->values,
type_table->num_elems);
@@ -115,12 +125,12 @@
return nullptr;
}
-void IterateObject(const uint8_t *obj, const TypeTable *type_table,
- IterationVisitor *visitor);
+void IterateObject(const uint8_t* obj, const TypeTable* type_table,
+ IterationVisitor* visitor);
-inline void IterateValue(ElementaryType type, const uint8_t *val,
- const TypeTable *type_table, const uint8_t *prev_val,
- soffset_t vector_index, IterationVisitor *visitor) {
+inline void IterateValue(ElementaryType type, const uint8_t* val,
+ const TypeTable* type_table, const uint8_t* prev_val,
+ soffset_t vector_index, IterationVisitor* visitor) {
switch (type) {
case ET_UTYPE: {
auto tval = ReadScalar<uint8_t>(val);
@@ -179,7 +189,7 @@
}
case ET_STRING: {
val += ReadScalar<uoffset_t>(val);
- visitor->String(reinterpret_cast<const String *>(val));
+ visitor->String(reinterpret_cast<const String*>(val));
break;
}
case ET_SEQUENCE: {
@@ -188,13 +198,15 @@
val += ReadScalar<uoffset_t>(val);
IterateObject(val, type_table, visitor);
break;
- case ST_STRUCT: IterateObject(val, type_table, visitor); break;
+ case ST_STRUCT:
+ IterateObject(val, type_table, visitor);
+ break;
case ST_UNION: {
val += ReadScalar<uoffset_t>(val);
FLATBUFFERS_ASSERT(prev_val);
auto union_type = *prev_val; // Always a uint8_t.
if (vector_index >= 0) {
- auto type_vec = reinterpret_cast<const Vector<uint8_t> *>(prev_val);
+ auto type_vec = reinterpret_cast<const Vector<uint8_t>*>(prev_val);
union_type = type_vec->Get(static_cast<uoffset_t>(vector_index));
}
auto type_code_idx =
@@ -209,16 +221,19 @@
break;
}
case ET_STRING:
- visitor->String(reinterpret_cast<const String *>(val));
+ visitor->String(reinterpret_cast<const String*>(val));
break;
- default: visitor->Unknown(val);
+ default:
+ visitor->Unknown(val);
}
} else {
visitor->Unknown(val);
}
break;
}
- case ST_ENUM: FLATBUFFERS_ASSERT(false); break;
+ case ST_ENUM:
+ FLATBUFFERS_ASSERT(false);
+ break;
}
break;
}
@@ -229,10 +244,10 @@
}
}
-inline void IterateObject(const uint8_t *obj, const TypeTable *type_table,
- IterationVisitor *visitor) {
+inline void IterateObject(const uint8_t* obj, const TypeTable* type_table,
+ IterationVisitor* visitor) {
visitor->StartSequence();
- const uint8_t *prev_val = nullptr;
+ const uint8_t* prev_val = nullptr;
size_t set_idx = 0;
size_t array_idx = 0;
for (size_t i = 0; i < type_table->num_elems; i++) {
@@ -240,12 +255,14 @@
auto type = static_cast<ElementaryType>(type_code.base_type);
auto is_repeating = type_code.is_repeating != 0;
auto ref_idx = type_code.sequence_ref;
- const TypeTable *ref = nullptr;
- if (ref_idx >= 0) { ref = type_table->type_refs[ref_idx](); }
+ const TypeTable* ref = nullptr;
+ if (ref_idx >= 0) {
+ ref = type_table->type_refs[ref_idx]();
+ }
auto name = type_table->names ? type_table->names[i] : nullptr;
- const uint8_t *val = nullptr;
+ const uint8_t* val = nullptr;
if (type_table->st == ST_TABLE) {
- val = reinterpret_cast<const Table *>(obj)->GetAddressOf(
+ val = reinterpret_cast<const Table*>(obj)->GetAddressOf(
FieldIndexToOffset(static_cast<voffset_t>(i)));
} else {
val = obj + type_table->values[i];
@@ -259,7 +276,7 @@
if (type_table->st == ST_TABLE) {
// variable length vector
val += ReadScalar<uoffset_t>(val);
- auto vec = reinterpret_cast<const Vector<uint8_t> *>(val);
+ auto vec = reinterpret_cast<const Vector<uint8_t>*>(val);
elem_ptr = vec->Data();
size = vec->size();
} else {
@@ -284,9 +301,9 @@
visitor->EndSequence();
}
-inline void IterateFlatBuffer(const uint8_t *buffer,
- const TypeTable *type_table,
- IterationVisitor *callback) {
+inline void IterateFlatBuffer(const uint8_t* buffer,
+ const TypeTable* type_table,
+ IterationVisitor* callback) {
IterateObject(GetRoot<uint8_t>(buffer), type_table, callback);
}
@@ -315,7 +332,9 @@
vector_delimited(true) {}
void append_indent() {
- for (size_t i = 0; i < indent_level; i++) { s += in; }
+ for (size_t i = 0; i < indent_level; i++) {
+ s += in;
+ }
}
void StartSequence() {
@@ -330,8 +349,8 @@
s += "}";
}
void Field(size_t /*field_idx*/, size_t set_idx, ElementaryType /*type*/,
- bool /*is_vector*/, const TypeTable * /*type_table*/,
- const char *name, const uint8_t *val) {
+ bool /*is_vector*/, const TypeTable* /*type_table*/,
+ const char* name, const uint8_t* val) {
if (!val) return;
if (set_idx) {
s += ",";
@@ -345,7 +364,8 @@
s += ": ";
}
}
- template<typename T> void Named(T x, const char *name) {
+ template <typename T>
+ void Named(T x, const char* name) {
if (name) {
if (q) s += "\"";
s += name;
@@ -354,22 +374,22 @@
s += NumToString(x);
}
}
- void UType(uint8_t x, const char *name) { Named(x, name); }
+ void UType(uint8_t x, const char* name) { Named(x, name); }
void Bool(bool x) { s += x ? "true" : "false"; }
- void Char(int8_t x, const char *name) { Named(x, name); }
- void UChar(uint8_t x, const char *name) { Named(x, name); }
- void Short(int16_t x, const char *name) { Named(x, name); }
- void UShort(uint16_t x, const char *name) { Named(x, name); }
- void Int(int32_t x, const char *name) { Named(x, name); }
- void UInt(uint32_t x, const char *name) { Named(x, name); }
+ void Char(int8_t x, const char* name) { Named(x, name); }
+ void UChar(uint8_t x, const char* name) { Named(x, name); }
+ void Short(int16_t x, const char* name) { Named(x, name); }
+ void UShort(uint16_t x, const char* name) { Named(x, name); }
+ void Int(int32_t x, const char* name) { Named(x, name); }
+ void UInt(uint32_t x, const char* name) { Named(x, name); }
void Long(int64_t x) { s += NumToString(x); }
void ULong(uint64_t x) { s += NumToString(x); }
void Float(float x) { s += NumToString(x); }
void Double(double x) { s += NumToString(x); }
- void String(const struct String *str) {
+ void String(const struct String* str) {
EscapeString(str->c_str(), str->size(), &s, true, false);
}
- void Unknown(const uint8_t *) { s += "(?)"; }
+ void Unknown(const uint8_t*) { s += "(?)"; }
void StartVector() {
s += "[";
if (vector_delimited) {
@@ -391,7 +411,7 @@
s += "]";
}
void Element(size_t i, ElementaryType /*type*/,
- const TypeTable * /*type_table*/, const uint8_t * /*val*/) {
+ const TypeTable* /*type_table*/, const uint8_t* /*val*/) {
if (i) {
s += ",";
if (vector_delimited) {
@@ -404,11 +424,11 @@
}
};
-inline std::string FlatBufferToString(const uint8_t *buffer,
- const TypeTable *type_table,
+inline std::string FlatBufferToString(const uint8_t* buffer,
+ const TypeTable* type_table,
bool multi_line = false,
bool vector_delimited = true,
- const std::string &indent = "",
+ const std::string& indent = "",
bool quotes = false) {
ToStringVisitor tostring_visitor(multi_line ? "\n" : " ", quotes, indent,
vector_delimited);
diff --git a/include/flatbuffers/reflection.h b/include/flatbuffers/reflection.h
index faf647c..371df72 100644
--- a/include/flatbuffers/reflection.h
+++ b/include/flatbuffers/reflection.h
@@ -47,28 +47,28 @@
inline size_t GetTypeSize(reflection::BaseType base_type) {
// This needs to correspond to the BaseType enum.
static size_t sizes[] = {
- 0, // None
- 1, // UType
- 1, // Bool
- 1, // Byte
- 1, // UByte
- 2, // Short
- 2, // UShort
- 4, // Int
- 4, // UInt
- 8, // Long
- 8, // ULong
- 4, // Float
- 8, // Double
- 4, // String
- 4, // Vector
- 4, // Obj
- 4, // Union
- 0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds
- // errors.
- 8, // Vector64
+ 0, // None
+ 1, // UType
+ 1, // Bool
+ 1, // Byte
+ 1, // UByte
+ 2, // Short
+ 2, // UShort
+ 4, // Int
+ 4, // UInt
+ 8, // Long
+ 8, // ULong
+ 4, // Float
+ 8, // Double
+ 4, // String
+ 4, // Vector
+ 4, // Obj
+ 4, // Union
+ 0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds
+ // errors.
+ 8, // Vector64
- 0 // MaxBaseType. This must be kept the last entry in this array.
+ 0 // MaxBaseType. This must be kept the last entry in this array.
};
static_assert(sizeof(sizes) / sizeof(size_t) == reflection::MaxBaseType + 1,
"Size of sizes[] array does not match the count of BaseType "
@@ -79,7 +79,7 @@
// Same as above, but now correctly returns the size of a struct if
// the field (or vector element) is a struct.
inline size_t GetTypeSizeInline(reflection::BaseType base_type, int type_index,
- const reflection::Schema &schema) {
+ const reflection::Schema& schema) {
if (base_type == reflection::Obj &&
schema.objects()->Get(type_index)->is_struct()) {
return schema.objects()->Get(type_index)->bytesize();
@@ -89,119 +89,121 @@
}
// Get the root, regardless of what type it is.
-inline Table *GetAnyRoot(uint8_t *const flatbuf) {
+inline Table* GetAnyRoot(uint8_t* const flatbuf) {
return GetMutableRoot<Table>(flatbuf);
}
-inline const Table *GetAnyRoot(const uint8_t *const flatbuf) {
+inline const Table* GetAnyRoot(const uint8_t* const flatbuf) {
return GetRoot<Table>(flatbuf);
}
-inline Table *GetAnySizePrefixedRoot(uint8_t *const flatbuf) {
+inline Table* GetAnySizePrefixedRoot(uint8_t* const flatbuf) {
return GetMutableSizePrefixedRoot<Table>(flatbuf);
}
-inline const Table *GetAnySizePrefixedRoot(const uint8_t *const flatbuf) {
+inline const Table* GetAnySizePrefixedRoot(const uint8_t* const flatbuf) {
return GetSizePrefixedRoot<Table>(flatbuf);
}
// Get a field's default, if you know it's an integer, and its exact type.
-template<typename T> T GetFieldDefaultI(const reflection::Field &field) {
+template <typename T>
+T GetFieldDefaultI(const reflection::Field& field) {
FLATBUFFERS_ASSERT(sizeof(T) == GetTypeSize(field.type()->base_type()));
return static_cast<T>(field.default_integer());
}
// Get a field's default, if you know it's floating point and its exact type.
-template<typename T> T GetFieldDefaultF(const reflection::Field &field) {
+template <typename T>
+T GetFieldDefaultF(const reflection::Field& field) {
FLATBUFFERS_ASSERT(sizeof(T) == GetTypeSize(field.type()->base_type()));
return static_cast<T>(field.default_real());
}
// Get a field, if you know it's an integer, and its exact type.
-template<typename T>
-T GetFieldI(const Table &table, const reflection::Field &field) {
+template <typename T>
+T GetFieldI(const Table& table, const reflection::Field& field) {
FLATBUFFERS_ASSERT(sizeof(T) == GetTypeSize(field.type()->base_type()));
return table.GetField<T>(field.offset(),
static_cast<T>(field.default_integer()));
}
// Get a field, if you know it's floating point and its exact type.
-template<typename T>
-T GetFieldF(const Table &table, const reflection::Field &field) {
+template <typename T>
+T GetFieldF(const Table& table, const reflection::Field& field) {
FLATBUFFERS_ASSERT(sizeof(T) == GetTypeSize(field.type()->base_type()));
return table.GetField<T>(field.offset(),
static_cast<T>(field.default_real()));
}
// Get a field, if you know it's a string.
-inline const String *GetFieldS(const Table &table,
- const reflection::Field &field) {
+inline const String* GetFieldS(const Table& table,
+ const reflection::Field& field) {
FLATBUFFERS_ASSERT(field.type()->base_type() == reflection::String);
- return table.GetPointer<const String *>(field.offset());
+ return table.GetPointer<const String*>(field.offset());
}
// Get a field, if you know it's a vector.
-template<typename T>
-Vector<T> *GetFieldV(const Table &table, const reflection::Field &field) {
+template <typename T>
+Vector<T>* GetFieldV(const Table& table, const reflection::Field& field) {
FLATBUFFERS_ASSERT(field.type()->base_type() == reflection::Vector &&
sizeof(T) == GetTypeSize(field.type()->element()));
- return table.GetPointer<Vector<T> *>(field.offset());
+ return table.GetPointer<Vector<T>*>(field.offset());
}
// Get a field, if you know it's a vector, generically.
// To actually access elements, use the return value together with
// field.type()->element() in any of GetAnyVectorElemI below etc.
-inline VectorOfAny *GetFieldAnyV(const Table &table,
- const reflection::Field &field) {
- return table.GetPointer<VectorOfAny *>(field.offset());
+inline VectorOfAny* GetFieldAnyV(const Table& table,
+ const reflection::Field& field) {
+ return table.GetPointer<VectorOfAny*>(field.offset());
}
// Get a field, if you know it's a table.
-inline Table *GetFieldT(const Table &table, const reflection::Field &field) {
+inline Table* GetFieldT(const Table& table, const reflection::Field& field) {
FLATBUFFERS_ASSERT(field.type()->base_type() == reflection::Obj ||
field.type()->base_type() == reflection::Union);
- return table.GetPointer<Table *>(field.offset());
+ return table.GetPointer<Table*>(field.offset());
}
// Get a field, if you know it's a struct.
-inline const Struct *GetFieldStruct(const Table &table,
- const reflection::Field &field) {
+inline const Struct* GetFieldStruct(const Table& table,
+ const reflection::Field& field) {
// TODO: This does NOT check if the field is a table or struct, but we'd need
// access to the schema to check the is_struct flag.
FLATBUFFERS_ASSERT(field.type()->base_type() == reflection::Obj);
- return table.GetStruct<const Struct *>(field.offset());
+ return table.GetStruct<const Struct*>(field.offset());
}
// Get a structure's field, if you know it's a struct.
-inline const Struct *GetFieldStruct(const Struct &structure,
- const reflection::Field &field) {
+inline const Struct* GetFieldStruct(const Struct& structure,
+ const reflection::Field& field) {
FLATBUFFERS_ASSERT(field.type()->base_type() == reflection::Obj);
- return structure.GetStruct<const Struct *>(field.offset());
+ return structure.GetStruct<const Struct*>(field.offset());
}
// Raw helper functions used below: get any value in memory as a 64bit int, a
// double or a string.
// All scalars get static_cast to an int64_t, strings use strtoull, every other
// data type returns 0.
-int64_t GetAnyValueI(reflection::BaseType type, const uint8_t *data);
+int64_t GetAnyValueI(reflection::BaseType type, const uint8_t* data);
// All scalars static cast to double, strings use strtod, every other data
// type is 0.0.
-double GetAnyValueF(reflection::BaseType type, const uint8_t *data);
+double GetAnyValueF(reflection::BaseType type, const uint8_t* data);
// All scalars converted using stringstream, strings as-is, and all other
// data types provide some level of debug-pretty-printing.
-std::string GetAnyValueS(reflection::BaseType type, const uint8_t *data,
- const reflection::Schema *schema, int type_index);
+std::string GetAnyValueS(reflection::BaseType type, const uint8_t* data,
+ const reflection::Schema* schema, int type_index);
// Get any table field as a 64bit int, regardless of what type it is.
-inline int64_t GetAnyFieldI(const Table &table,
- const reflection::Field &field) {
+inline int64_t GetAnyFieldI(const Table& table,
+ const reflection::Field& field) {
auto field_ptr = table.GetAddressOf(field.offset());
return field_ptr ? GetAnyValueI(field.type()->base_type(), field_ptr)
: field.default_integer();
}
// Get any table field as a double, regardless of what type it is.
-inline double GetAnyFieldF(const Table &table, const reflection::Field &field) {
+inline double GetAnyFieldF(const Table& table, const reflection::Field& field) {
auto field_ptr = table.GetAddressOf(field.offset());
return field_ptr ? GetAnyValueF(field.type()->base_type(), field_ptr)
: field.default_real();
@@ -210,9 +212,9 @@
// Get any table field as a string, regardless of what type it is.
// You may pass nullptr for the schema if you don't care to have fields that
// are of table type pretty-printed.
-inline std::string GetAnyFieldS(const Table &table,
- const reflection::Field &field,
- const reflection::Schema *schema) {
+inline std::string GetAnyFieldS(const Table& table,
+ const reflection::Field& field,
+ const reflection::Schema* schema) {
auto field_ptr = table.GetAddressOf(field.offset());
return field_ptr ? GetAnyValueS(field.type()->base_type(), field_ptr, schema,
field.type()->index())
@@ -220,38 +222,38 @@
}
// Get any struct field as a 64bit int, regardless of what type it is.
-inline int64_t GetAnyFieldI(const Struct &st, const reflection::Field &field) {
+inline int64_t GetAnyFieldI(const Struct& st, const reflection::Field& field) {
return GetAnyValueI(field.type()->base_type(),
st.GetAddressOf(field.offset()));
}
// Get any struct field as a double, regardless of what type it is.
-inline double GetAnyFieldF(const Struct &st, const reflection::Field &field) {
+inline double GetAnyFieldF(const Struct& st, const reflection::Field& field) {
return GetAnyValueF(field.type()->base_type(),
st.GetAddressOf(field.offset()));
}
// Get any struct field as a string, regardless of what type it is.
-inline std::string GetAnyFieldS(const Struct &st,
- const reflection::Field &field) {
+inline std::string GetAnyFieldS(const Struct& st,
+ const reflection::Field& field) {
return GetAnyValueS(field.type()->base_type(),
st.GetAddressOf(field.offset()), nullptr, -1);
}
// Get any vector element as a 64bit int, regardless of what type it is.
-inline int64_t GetAnyVectorElemI(const VectorOfAny *vec,
+inline int64_t GetAnyVectorElemI(const VectorOfAny* vec,
reflection::BaseType elem_type, size_t i) {
return GetAnyValueI(elem_type, vec->Data() + GetTypeSize(elem_type) * i);
}
// Get any vector element as a double, regardless of what type it is.
-inline double GetAnyVectorElemF(const VectorOfAny *vec,
+inline double GetAnyVectorElemF(const VectorOfAny* vec,
reflection::BaseType elem_type, size_t i) {
return GetAnyValueF(elem_type, vec->Data() + GetTypeSize(elem_type) * i);
}
// Get any vector element as a string, regardless of what type it is.
-inline std::string GetAnyVectorElemS(const VectorOfAny *vec,
+inline std::string GetAnyVectorElemS(const VectorOfAny* vec,
reflection::BaseType elem_type, size_t i) {
return GetAnyValueS(elem_type, vec->Data() + GetTypeSize(elem_type) * i,
nullptr, -1);
@@ -260,10 +262,10 @@
// Get a vector element that's a table/string/vector from a generic vector.
// Pass Table/String/VectorOfAny as template parameter.
// Warning: does no typechecking.
-template<typename T>
-T *GetAnyVectorElemPointer(const VectorOfAny *vec, size_t i) {
+template <typename T>
+T* GetAnyVectorElemPointer(const VectorOfAny* vec, size_t i) {
auto elem_ptr = vec->Data() + sizeof(uoffset_t) * i;
- return reinterpret_cast<T *>(elem_ptr + ReadScalar<uoffset_t>(elem_ptr));
+ return reinterpret_cast<T*>(elem_ptr + ReadScalar<uoffset_t>(elem_ptr));
}
// Get the inline-address of a vector element. Useful for Structs (pass Struct
@@ -271,37 +273,39 @@
// Get elem_size from GetTypeSizeInline().
// Note: little-endian data on all platforms, use EndianScalar() instead of
// raw pointer access with scalars).
-template<typename T>
-T *GetAnyVectorElemAddressOf(const VectorOfAny *vec, size_t i,
+template <typename T>
+T* GetAnyVectorElemAddressOf(const VectorOfAny* vec, size_t i,
size_t elem_size) {
- return reinterpret_cast<T *>(vec->Data() + elem_size * i);
+ return reinterpret_cast<T*>(vec->Data() + elem_size * i);
}
// Similarly, for elements of tables.
-template<typename T>
-T *GetAnyFieldAddressOf(const Table &table, const reflection::Field &field) {
- return reinterpret_cast<T *>(table.GetAddressOf(field.offset()));
+template <typename T>
+T* GetAnyFieldAddressOf(const Table& table, const reflection::Field& field) {
+ return reinterpret_cast<T*>(table.GetAddressOf(field.offset()));
}
// Similarly, for elements of structs.
-template<typename T>
-T *GetAnyFieldAddressOf(const Struct &st, const reflection::Field &field) {
- return reinterpret_cast<T *>(st.GetAddressOf(field.offset()));
+template <typename T>
+T* GetAnyFieldAddressOf(const Struct& st, const reflection::Field& field) {
+ return reinterpret_cast<T*>(st.GetAddressOf(field.offset()));
}
// Loop over all the fields of the provided `object` and call `func` on each one
// in increasing order by their field->id(). If `reverse` is true, `func` is
// called in descending order
-void ForAllFields(const reflection::Object *object, bool reverse,
- std::function<void(const reflection::Field *)> func);
+void ForAllFields(const reflection::Object* object, bool reverse,
+ std::function<void(const reflection::Field*)> func);
// ------------------------- SETTERS -------------------------
// Set any scalar field, if you know its exact type.
-template<typename T>
-bool SetField(Table *table, const reflection::Field &field, T val) {
+template <typename T>
+bool SetField(Table* table, const reflection::Field& field, T val) {
reflection::BaseType type = field.type()->base_type();
- if (!IsScalar(type)) { return false; }
+ if (!IsScalar(type)) {
+ return false;
+ }
FLATBUFFERS_ASSERT(sizeof(T) == GetTypeSize(type));
T def;
if (IsInteger(type)) {
@@ -317,12 +321,12 @@
// double or a string.
// These work for all scalar values, but do nothing for other data types.
// To set a string, see SetString below.
-void SetAnyValueI(reflection::BaseType type, uint8_t *data, int64_t val);
-void SetAnyValueF(reflection::BaseType type, uint8_t *data, double val);
-void SetAnyValueS(reflection::BaseType type, uint8_t *data, const char *val);
+void SetAnyValueI(reflection::BaseType type, uint8_t* data, int64_t val);
+void SetAnyValueF(reflection::BaseType type, uint8_t* data, double val);
+void SetAnyValueS(reflection::BaseType type, uint8_t* data, const char* val);
// Set any table field as a 64bit int, regardless of type what it is.
-inline bool SetAnyFieldI(Table *table, const reflection::Field &field,
+inline bool SetAnyFieldI(Table* table, const reflection::Field& field,
int64_t val) {
auto field_ptr = table->GetAddressOf(field.offset());
if (!field_ptr) return val == GetFieldDefaultI<int64_t>(field);
@@ -331,7 +335,7 @@
}
// Set any table field as a double, regardless of what type it is.
-inline bool SetAnyFieldF(Table *table, const reflection::Field &field,
+inline bool SetAnyFieldF(Table* table, const reflection::Field& field,
double val) {
auto field_ptr = table->GetAddressOf(field.offset());
if (!field_ptr) return val == GetFieldDefaultF<double>(field);
@@ -340,8 +344,8 @@
}
// Set any table field as a string, regardless of what type it is.
-inline bool SetAnyFieldS(Table *table, const reflection::Field &field,
- const char *val) {
+inline bool SetAnyFieldS(Table* table, const reflection::Field& field,
+ const char* val) {
auto field_ptr = table->GetAddressOf(field.offset());
if (!field_ptr) return false;
SetAnyValueS(field.type()->base_type(), field_ptr, val);
@@ -349,41 +353,41 @@
}
// Set any struct field as a 64bit int, regardless of type what it is.
-inline void SetAnyFieldI(Struct *st, const reflection::Field &field,
+inline void SetAnyFieldI(Struct* st, const reflection::Field& field,
int64_t val) {
SetAnyValueI(field.type()->base_type(), st->GetAddressOf(field.offset()),
val);
}
// Set any struct field as a double, regardless of type what it is.
-inline void SetAnyFieldF(Struct *st, const reflection::Field &field,
+inline void SetAnyFieldF(Struct* st, const reflection::Field& field,
double val) {
SetAnyValueF(field.type()->base_type(), st->GetAddressOf(field.offset()),
val);
}
// Set any struct field as a string, regardless of type what it is.
-inline void SetAnyFieldS(Struct *st, const reflection::Field &field,
- const char *val) {
+inline void SetAnyFieldS(Struct* st, const reflection::Field& field,
+ const char* val) {
SetAnyValueS(field.type()->base_type(), st->GetAddressOf(field.offset()),
val);
}
// Set any vector element as a 64bit int, regardless of type what it is.
-inline void SetAnyVectorElemI(VectorOfAny *vec, reflection::BaseType elem_type,
+inline void SetAnyVectorElemI(VectorOfAny* vec, reflection::BaseType elem_type,
size_t i, int64_t val) {
SetAnyValueI(elem_type, vec->Data() + GetTypeSize(elem_type) * i, val);
}
// Set any vector element as a double, regardless of type what it is.
-inline void SetAnyVectorElemF(VectorOfAny *vec, reflection::BaseType elem_type,
+inline void SetAnyVectorElemF(VectorOfAny* vec, reflection::BaseType elem_type,
size_t i, double val) {
SetAnyValueF(elem_type, vec->Data() + GetTypeSize(elem_type) * i, val);
}
// Set any vector element as a string, regardless of type what it is.
-inline void SetAnyVectorElemS(VectorOfAny *vec, reflection::BaseType elem_type,
- size_t i, const char *val) {
+inline void SetAnyVectorElemS(VectorOfAny* vec, reflection::BaseType elem_type,
+ size_t i, const char* val) {
SetAnyValueS(elem_type, vec->Data() + GetTypeSize(elem_type) * i, val);
}
@@ -391,36 +395,37 @@
// "smart" pointer for use with resizing vectors: turns a pointer inside
// a vector into a relative offset, such that it is not affected by resizes.
-template<typename T, typename U> class pointer_inside_vector {
+template <typename T, typename U>
+class pointer_inside_vector {
public:
- pointer_inside_vector(T *ptr, std::vector<U> &vec)
- : offset_(reinterpret_cast<uint8_t *>(ptr) -
- reinterpret_cast<uint8_t *>(vec.data())),
+ pointer_inside_vector(T* ptr, std::vector<U>& vec)
+ : offset_(reinterpret_cast<uint8_t*>(ptr) -
+ reinterpret_cast<uint8_t*>(vec.data())),
vec_(vec) {}
- T *operator*() const {
- return reinterpret_cast<T *>(reinterpret_cast<uint8_t *>(vec_.data()) +
- offset_);
+ T* operator*() const {
+ return reinterpret_cast<T*>(reinterpret_cast<uint8_t*>(vec_.data()) +
+ offset_);
}
- T *operator->() const { return operator*(); }
+ T* operator->() const { return operator*(); }
private:
size_t offset_;
- std::vector<U> &vec_;
+ std::vector<U>& vec_;
};
// Helper to create the above easily without specifying template args.
-template<typename T, typename U>
-pointer_inside_vector<T, U> piv(T *ptr, std::vector<U> &vec) {
+template <typename T, typename U>
+pointer_inside_vector<T, U> piv(T* ptr, std::vector<U>& vec) {
return pointer_inside_vector<T, U>(ptr, vec);
}
-inline const char *UnionTypeFieldSuffix() { return "_type"; }
+inline const char* UnionTypeFieldSuffix() { return "_type"; }
// Helper to figure out the actual table type a union refers to.
-inline const reflection::Object &GetUnionType(
- const reflection::Schema &schema, const reflection::Object &parent,
- const reflection::Field &unionfield, const Table &table) {
+inline const reflection::Object& GetUnionType(
+ const reflection::Schema& schema, const reflection::Object& parent,
+ const reflection::Field& unionfield, const Table& table) {
auto enumdef = schema.enums()->Get(unionfield.type()->index());
// TODO: this is clumsy and slow, but no other way to find it?
auto type_field = parent.fields()->LookupByKey(
@@ -436,27 +441,27 @@
// "str" must live inside "flatbuf" and may be invalidated after this call.
// If your FlatBuffer's root table is not the schema's root table, you should
// pass in your root_table type as well.
-void SetString(const reflection::Schema &schema, const std::string &val,
- const String *str, std::vector<uint8_t> *flatbuf,
- const reflection::Object *root_table = nullptr);
+void SetString(const reflection::Schema& schema, const std::string& val,
+ const String* str, std::vector<uint8_t>* flatbuf,
+ const reflection::Object* root_table = nullptr);
// Resizes a flatbuffers::Vector inside a FlatBuffer. FlatBuffer must
// live inside a std::vector so we can resize the buffer if needed.
// "vec" must live inside "flatbuf" and may be invalidated after this call.
// If your FlatBuffer's root table is not the schema's root table, you should
// pass in your root_table type as well.
-uint8_t *ResizeAnyVector(const reflection::Schema &schema, uoffset_t newsize,
- const VectorOfAny *vec, uoffset_t num_elems,
- uoffset_t elem_size, std::vector<uint8_t> *flatbuf,
- const reflection::Object *root_table = nullptr);
+uint8_t* ResizeAnyVector(const reflection::Schema& schema, uoffset_t newsize,
+ const VectorOfAny* vec, uoffset_t num_elems,
+ uoffset_t elem_size, std::vector<uint8_t>* flatbuf,
+ const reflection::Object* root_table = nullptr);
-template<typename T>
-void ResizeVector(const reflection::Schema &schema, uoffset_t newsize, T val,
- const Vector<T> *vec, std::vector<uint8_t> *flatbuf,
- const reflection::Object *root_table = nullptr) {
+template <typename T>
+void ResizeVector(const reflection::Schema& schema, uoffset_t newsize, T val,
+ const Vector<T>* vec, std::vector<uint8_t>* flatbuf,
+ const reflection::Object* root_table = nullptr) {
auto delta_elem = static_cast<int>(newsize) - static_cast<int>(vec->size());
auto newelems = ResizeAnyVector(
- schema, newsize, reinterpret_cast<const VectorOfAny *>(vec), vec->size(),
+ schema, newsize, reinterpret_cast<const VectorOfAny*>(vec), vec->size(),
static_cast<uoffset_t>(sizeof(T)), flatbuf, root_table);
// Set new elements to "val".
for (int i = 0; i < delta_elem; i++) {
@@ -465,7 +470,7 @@
if (is_scalar) {
WriteScalar(loc, val);
} else { // struct
- *reinterpret_cast<T *>(loc) = val;
+ *reinterpret_cast<T*>(loc) = val;
}
}
}
@@ -478,11 +483,11 @@
// existing one.
// The return value can now be set using Vector::MutateOffset or SetFieldT
// below.
-const uint8_t *AddFlatBuffer(std::vector<uint8_t> &flatbuf,
- const uint8_t *newbuf, size_t newlen);
+const uint8_t* AddFlatBuffer(std::vector<uint8_t>& flatbuf,
+ const uint8_t* newbuf, size_t newlen);
-inline bool SetFieldT(Table *table, const reflection::Field &field,
- const uint8_t *val) {
+inline bool SetFieldT(Table* table, const reflection::Field& field,
+ const uint8_t* val) {
FLATBUFFERS_ASSERT(sizeof(uoffset_t) ==
GetTypeSize(field.type()->base_type()));
return table->SetPointer(field.offset(), val);
@@ -499,22 +504,22 @@
// DAG, the copy will be a tree instead (with duplicates). Strings can be
// shared however, by passing true for use_string_pooling.
-Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
- const reflection::Schema &schema,
- const reflection::Object &objectdef,
- const Table &table,
- bool use_string_pooling = false);
+Offset<const Table*> CopyTable(FlatBufferBuilder& fbb,
+ const reflection::Schema& schema,
+ const reflection::Object& objectdef,
+ const Table& table,
+ bool use_string_pooling = false);
// Verifies the provided flatbuffer using reflection.
// root should point to the root type for this flatbuffer.
// buf should point to the start of flatbuffer data.
// length specifies the size of the flatbuffer data.
-bool Verify(const reflection::Schema &schema, const reflection::Object &root,
- const uint8_t *buf, size_t length, uoffset_t max_depth = 64,
+bool Verify(const reflection::Schema& schema, const reflection::Object& root,
+ const uint8_t* buf, size_t length, uoffset_t max_depth = 64,
uoffset_t max_tables = 1000000);
-bool VerifySizePrefixed(const reflection::Schema &schema,
- const reflection::Object &root, const uint8_t *buf,
+bool VerifySizePrefixed(const reflection::Schema& schema,
+ const reflection::Object& root, const uint8_t* buf,
size_t length, uoffset_t max_depth = 64,
uoffset_t max_tables = 1000000);
diff --git a/include/flatbuffers/registry.h b/include/flatbuffers/registry.h
index f59aa64..e70cfc3 100644
--- a/include/flatbuffers/registry.h
+++ b/include/flatbuffers/registry.h
@@ -30,7 +30,7 @@
public:
// Call this for all schemas that may be in use. The identifier has
// a function in the generated code, e.g. MonsterIdentifier().
- void Register(const char *file_identifier, const char *schema_path) {
+ void Register(const char* file_identifier, const char* schema_path) {
Schema schema;
schema.path_ = schema_path;
schemas_[file_identifier] = schema;
@@ -38,7 +38,7 @@
// Generate text from an arbitrary FlatBuffer by looking up its
// file_identifier in the registry.
- bool FlatBufferToText(const uint8_t *flatbuf, size_t len, std::string *dest) {
+ bool FlatBufferToText(const uint8_t* flatbuf, size_t len, std::string* dest) {
// Get the identifier out of the buffer.
// If the buffer is truncated, exit.
if (len < sizeof(uoffset_t) + kFileIdentifierLength) {
@@ -46,7 +46,7 @@
return false;
}
std::string ident(
- reinterpret_cast<const char *>(flatbuf) + sizeof(uoffset_t),
+ reinterpret_cast<const char*>(flatbuf) + sizeof(uoffset_t),
kFileIdentifierLength);
// Load and parse the schema.
Parser parser;
@@ -64,8 +64,8 @@
// Converts a binary buffer to text using one of the schemas in the registry,
// use the file_identifier to indicate which.
// If DetachedBuffer::data() is null then parsing failed.
- DetachedBuffer TextToFlatBuffer(const char *text,
- const char *file_identifier) {
+ DetachedBuffer TextToFlatBuffer(const char* text,
+ const char* file_identifier) {
// Load and parse the schema.
Parser parser;
if (!LoadSchema(file_identifier, &parser)) return DetachedBuffer();
@@ -79,17 +79,17 @@
}
// Modify any parsing / output options used by the other functions.
- void SetOptions(const IDLOptions &opts) { opts_ = opts; }
+ void SetOptions(const IDLOptions& opts) { opts_ = opts; }
// If schemas used contain include statements, call this function for every
// directory the parser should search them for.
- void AddIncludeDirectory(const char *path) { include_paths_.push_back(path); }
+ void AddIncludeDirectory(const char* path) { include_paths_.push_back(path); }
// Returns a human readable error if any of the above functions fail.
- const std::string &GetLastError() { return lasterror_; }
+ const std::string& GetLastError() { return lasterror_; }
private:
- bool LoadSchema(const std::string &ident, Parser *parser) {
+ bool LoadSchema(const std::string& ident, Parser* parser) {
// Find the schema, if not, exit.
auto it = schemas_.find(ident);
if (it == schemas_.end()) {
@@ -97,7 +97,7 @@
lasterror_ = "identifier for this buffer not in the registry";
return false;
}
- auto &schema = it->second;
+ auto& schema = it->second;
// Load the schema from disk. If not, exit.
std::string schematext;
if (!LoadFile(schema.path_.c_str(), false, &schematext)) {
@@ -121,7 +121,7 @@
std::string lasterror_;
IDLOptions opts_;
- std::vector<const char *> include_paths_;
+ std::vector<const char*> include_paths_;
std::map<std::string, Schema> schemas_;
};
diff --git a/include/flatbuffers/string.h b/include/flatbuffers/string.h
index 00cc18c..d9c62f9 100644
--- a/include/flatbuffers/string.h
+++ b/include/flatbuffers/string.h
@@ -23,7 +23,7 @@
namespace flatbuffers {
struct String : public Vector<char> {
- const char *c_str() const { return reinterpret_cast<const char *>(Data()); }
+ const char* c_str() const { return reinterpret_cast<const char*>(Data()); }
std::string str() const { return std::string(c_str(), size()); }
// clang-format off
@@ -39,27 +39,27 @@
#endif // FLATBUFFERS_HAS_STRING_VIEW
// clang-format on
- bool operator<(const String &o) const {
+ bool operator<(const String& o) const {
return StringLessThan(this->data(), this->size(), o.data(), o.size());
}
};
// Convenience function to get std::string from a String returning an empty
// string on null pointer.
-static inline std::string GetString(const String *str) {
+static inline std::string GetString(const String* str) {
return str ? str->str() : "";
}
// Convenience function to get char* from a String returning an empty string on
// null pointer.
-static inline const char *GetCstring(const String *str) {
+static inline const char* GetCstring(const String* str) {
return str ? str->c_str() : "";
}
#ifdef FLATBUFFERS_HAS_STRING_VIEW
// Convenience function to get string_view from a String returning an empty
// string_view on null pointer.
-static inline flatbuffers::string_view GetStringView(const String *str) {
+static inline flatbuffers::string_view GetStringView(const String* str) {
return str ? str->string_view() : flatbuffers::string_view();
}
#endif // FLATBUFFERS_HAS_STRING_VIEW
diff --git a/include/flatbuffers/struct.h b/include/flatbuffers/struct.h
index abacc8a..3aa434c 100644
--- a/include/flatbuffers/struct.h
+++ b/include/flatbuffers/struct.h
@@ -27,23 +27,25 @@
class Struct FLATBUFFERS_FINAL_CLASS {
public:
- template<typename T> T GetField(uoffset_t o) const {
+ template <typename T>
+ T GetField(uoffset_t o) const {
return ReadScalar<T>(&data_[o]);
}
- template<typename T> T GetStruct(uoffset_t o) const {
+ template <typename T>
+ T GetStruct(uoffset_t o) const {
return reinterpret_cast<T>(&data_[o]);
}
- const uint8_t *GetAddressOf(uoffset_t o) const { return &data_[o]; }
- uint8_t *GetAddressOf(uoffset_t o) { return &data_[o]; }
+ const uint8_t* GetAddressOf(uoffset_t o) const { return &data_[o]; }
+ uint8_t* GetAddressOf(uoffset_t o) { return &data_[o]; }
private:
// private constructor & copy constructor: you obtain instances of this
// class by pointing to existing data only
Struct();
- Struct(const Struct &);
- Struct &operator=(const Struct &);
+ Struct(const Struct&);
+ Struct& operator=(const Struct&);
uint8_t data_[1];
};
diff --git a/include/flatbuffers/table.h b/include/flatbuffers/table.h
index e92d8ae..defe084 100644
--- a/include/flatbuffers/table.h
+++ b/include/flatbuffers/table.h
@@ -26,7 +26,7 @@
// omitted and added at will, but uses an extra indirection to read.
class Table {
public:
- const uint8_t *GetVTable() const {
+ const uint8_t* GetVTable() const {
return data_ - ReadScalar<soffset_t>(data_);
}
@@ -42,38 +42,42 @@
return field < vtsize ? ReadScalar<voffset_t>(vtable + field) : 0;
}
- template<typename T> T GetField(voffset_t field, T defaultval) const {
+ template <typename T>
+ T GetField(voffset_t field, T defaultval) const {
auto field_offset = GetOptionalFieldOffset(field);
return field_offset ? ReadScalar<T>(data_ + field_offset) : defaultval;
}
- template<typename P, typename OffsetSize = uoffset_t>
+ template <typename P, typename OffsetSize = uoffset_t>
P GetPointer(voffset_t field) {
auto field_offset = GetOptionalFieldOffset(field);
auto p = data_ + field_offset;
return field_offset ? reinterpret_cast<P>(p + ReadScalar<OffsetSize>(p))
: nullptr;
}
- template<typename P, typename OffsetSize = uoffset_t>
+ template <typename P, typename OffsetSize = uoffset_t>
P GetPointer(voffset_t field) const {
- return const_cast<Table *>(this)->GetPointer<P, OffsetSize>(field);
+ return const_cast<Table*>(this)->GetPointer<P, OffsetSize>(field);
}
- template<typename P> P GetPointer64(voffset_t field) {
+ template <typename P>
+ P GetPointer64(voffset_t field) {
return GetPointer<P, uoffset64_t>(field);
}
- template<typename P> P GetPointer64(voffset_t field) const {
+ template <typename P>
+ P GetPointer64(voffset_t field) const {
return GetPointer<P, uoffset64_t>(field);
}
- template<typename P> P GetStruct(voffset_t field) const {
+ template <typename P>
+ P GetStruct(voffset_t field) const {
auto field_offset = GetOptionalFieldOffset(field);
- auto p = const_cast<uint8_t *>(data_ + field_offset);
+ auto p = const_cast<uint8_t*>(data_ + field_offset);
return field_offset ? reinterpret_cast<P>(p) : nullptr;
}
- template<typename Raw, typename Face>
+ template <typename Raw, typename Face>
flatbuffers::Optional<Face> GetOptional(voffset_t field) const {
auto field_offset = GetOptionalFieldOffset(field);
auto p = data_ + field_offset;
@@ -81,20 +85,22 @@
: Optional<Face>();
}
- template<typename T> bool SetField(voffset_t field, T val, T def) {
+ template <typename T>
+ bool SetField(voffset_t field, T val, T def) {
auto field_offset = GetOptionalFieldOffset(field);
if (!field_offset) return IsTheSameAs(val, def);
WriteScalar(data_ + field_offset, val);
return true;
}
- template<typename T> bool SetField(voffset_t field, T val) {
+ template <typename T>
+ bool SetField(voffset_t field, T val) {
auto field_offset = GetOptionalFieldOffset(field);
if (!field_offset) return false;
WriteScalar(data_ + field_offset, val);
return true;
}
- bool SetPointer(voffset_t field, const uint8_t *val) {
+ bool SetPointer(voffset_t field, const uint8_t* val) {
auto field_offset = GetOptionalFieldOffset(field);
if (!field_offset) return false;
WriteScalar(data_ + field_offset,
@@ -102,12 +108,12 @@
return true;
}
- uint8_t *GetAddressOf(voffset_t field) {
+ uint8_t* GetAddressOf(voffset_t field) {
auto field_offset = GetOptionalFieldOffset(field);
return field_offset ? data_ + field_offset : nullptr;
}
- const uint8_t *GetAddressOf(voffset_t field) const {
- return const_cast<Table *>(this)->GetAddressOf(field);
+ const uint8_t* GetAddressOf(voffset_t field) const {
+ return const_cast<Table*>(this)->GetAddressOf(field);
}
bool CheckField(voffset_t field) const {
@@ -116,13 +122,13 @@
// Verify the vtable of this table.
// Call this once per table, followed by VerifyField once per field.
- bool VerifyTableStart(Verifier &verifier) const {
+ bool VerifyTableStart(Verifier& verifier) const {
return verifier.VerifyTableStart(data_);
}
// Verify a particular field.
- template<typename T>
- bool VerifyField(const Verifier &verifier, voffset_t field,
+ template <typename T>
+ bool VerifyField(const Verifier& verifier, voffset_t field,
size_t align) const {
// Calling GetOptionalFieldOffset should be safe now thanks to
// VerifyTable().
@@ -132,8 +138,8 @@
}
// VerifyField for required fields.
- template<typename T>
- bool VerifyFieldRequired(const Verifier &verifier, voffset_t field,
+ template <typename T>
+ bool VerifyFieldRequired(const Verifier& verifier, voffset_t field,
size_t align) const {
auto field_offset = GetOptionalFieldOffset(field);
return verifier.Check(field_offset != 0) &&
@@ -141,24 +147,24 @@
}
// Versions for offsets.
- template<typename OffsetT = uoffset_t>
- bool VerifyOffset(const Verifier &verifier, voffset_t field) const {
+ template <typename OffsetT = uoffset_t>
+ bool VerifyOffset(const Verifier& verifier, voffset_t field) const {
auto field_offset = GetOptionalFieldOffset(field);
return !field_offset || verifier.VerifyOffset<OffsetT>(data_, field_offset);
}
- template<typename OffsetT = uoffset_t>
- bool VerifyOffsetRequired(const Verifier &verifier, voffset_t field) const {
+ template <typename OffsetT = uoffset_t>
+ bool VerifyOffsetRequired(const Verifier& verifier, voffset_t field) const {
auto field_offset = GetOptionalFieldOffset(field);
return verifier.Check(field_offset != 0) &&
verifier.VerifyOffset<OffsetT>(data_, field_offset);
}
- bool VerifyOffset64(const Verifier &verifier, voffset_t field) const {
+ bool VerifyOffset64(const Verifier& verifier, voffset_t field) const {
return VerifyOffset<uoffset64_t>(verifier, field);
}
- bool VerifyOffset64Required(const Verifier &verifier, voffset_t field) const {
+ bool VerifyOffset64Required(const Verifier& verifier, voffset_t field) const {
return VerifyOffsetRequired<uoffset64_t>(verifier, field);
}
@@ -166,15 +172,15 @@
// private constructor & copy constructor: you obtain instances of this
// class by pointing to existing data only
Table();
- Table(const Table &other);
- Table &operator=(const Table &);
+ Table(const Table& other);
+ Table& operator=(const Table&);
uint8_t data_[1];
};
// This specialization allows avoiding warnings like:
// MSVC C4800: type: forcing value to bool 'true' or 'false'.
-template<>
+template <>
inline flatbuffers::Optional<bool> Table::GetOptional<uint8_t, bool>(
voffset_t field) const {
auto field_offset = GetOptionalFieldOffset(field);
diff --git a/include/flatbuffers/util.h b/include/flatbuffers/util.h
index 82b37fb..0313e74 100644
--- a/include/flatbuffers/util.h
+++ b/include/flatbuffers/util.h
@@ -24,11 +24,11 @@
#include "flatbuffers/stl_emulation.h"
#ifndef FLATBUFFERS_PREFER_PRINTF
-# include <iomanip>
-# include <sstream>
+#include <iomanip>
+#include <sstream>
#else // FLATBUFFERS_PREFER_PRINTF
-# include <float.h>
-# include <stdio.h>
+#include <float.h>
+#include <stdio.h>
#endif // FLATBUFFERS_PREFER_PRINTF
#include <cmath>
@@ -90,7 +90,8 @@
// @end-locale-independent functions for ASCII character set
#ifdef FLATBUFFERS_PREFER_PRINTF
-template<typename T> size_t IntToDigitCount(T t) {
+template <typename T>
+size_t IntToDigitCount(T t) {
size_t digit_count = 0;
// Count the sign for negative numbers
if (t < 0) digit_count++;
@@ -105,19 +106,20 @@
return digit_count;
}
-template<typename T> size_t NumToStringWidth(T t, int precision = 0) {
+template <typename T>
+size_t NumToStringWidth(T t, int precision = 0) {
size_t string_width = IntToDigitCount(t);
// Count the dot for floating point numbers
if (precision) string_width += (precision + 1);
return string_width;
}
-template<typename T>
-std::string NumToStringImplWrapper(T t, const char *fmt, int precision = 0) {
+template <typename T>
+std::string NumToStringImplWrapper(T t, const char* fmt, int precision = 0) {
size_t string_width = NumToStringWidth(t, precision);
std::string s(string_width, 0x00);
// Allow snprintf to use std::string trailing null to detect buffer overflow
- snprintf(const_cast<char *>(s.data()), (s.size() + 1), fmt, string_width, t);
+ snprintf(const_cast<char*>(s.data()), (s.size() + 1), fmt, string_width, t);
return s;
}
#endif // FLATBUFFERS_PREFER_PRINTF
@@ -125,7 +127,8 @@
// Convert an integer or floating point value to a string.
// In contrast to std::stringstream, "char" values are
// converted to a string of digits, and we don't use scientific notation.
-template<typename T> std::string NumToString(T t) {
+template <typename T>
+std::string NumToString(T t) {
// clang-format off
#ifndef FLATBUFFERS_PREFER_PRINTF
@@ -139,18 +142,22 @@
// clang-format on
}
// Avoid char types used as character data.
-template<> inline std::string NumToString<signed char>(signed char t) {
+template <>
+inline std::string NumToString<signed char>(signed char t) {
return NumToString(static_cast<int>(t));
}
-template<> inline std::string NumToString<unsigned char>(unsigned char t) {
+template <>
+inline std::string NumToString<unsigned char>(unsigned char t) {
return NumToString(static_cast<int>(t));
}
-template<> inline std::string NumToString<char>(char t) {
+template <>
+inline std::string NumToString<char>(char t) {
return NumToString(static_cast<int>(t));
}
// Special versions for floats/doubles.
-template<typename T> std::string FloatToString(T t, int precision) {
+template <typename T>
+std::string FloatToString(T t, int precision) {
// clang-format off
#ifndef FLATBUFFERS_PREFER_PRINTF
@@ -177,10 +184,12 @@
return s;
}
-template<> inline std::string NumToString<double>(double t) {
+template <>
+inline std::string NumToString<double>(double t) {
return FloatToString(t, 12);
}
-template<> inline std::string NumToString<float>(float t) {
+template <>
+inline std::string NumToString<float>(float t) {
return FloatToString(t, 6);
}
@@ -279,8 +288,8 @@
// - If full string conversion can't be performed, 0 is returned.
// - If the converted value falls out of range of corresponding return type, a
// range error occurs. In this case value MAX(T)/MIN(T) is returned.
-template<typename T>
-inline bool StringToIntegerImpl(T *val, const char *const str,
+template <typename T>
+inline bool StringToIntegerImpl(T* val, const char* const str,
const int base = 0,
const bool check_errno = true) {
// T is int64_t or uint64_T
@@ -295,7 +304,7 @@
} else {
if (check_errno) errno = 0; // clear thread-local errno
auto endptr = str;
- strtoval_impl(val, str, const_cast<char **>(&endptr), base);
+ strtoval_impl(val, str, const_cast<char**>(&endptr), base);
if ((*endptr != '\0') || (endptr == str)) {
*val = 0; // erase partial result
return false; // invalid string
@@ -306,15 +315,17 @@
}
}
-template<typename T>
-inline bool StringToFloatImpl(T *val, const char *const str) {
+template <typename T>
+inline bool StringToFloatImpl(T* val, const char* const str) {
// Type T must be either float or double.
FLATBUFFERS_ASSERT(str && val);
auto end = str;
- strtoval_impl(val, str, const_cast<char **>(&end));
+ strtoval_impl(val, str, const_cast<char**>(&end));
auto done = (end != str) && (*end == '\0');
if (!done) *val = 0; // erase partial result
- if (done && std::isnan(*val)) { *val = std::numeric_limits<T>::quiet_NaN(); }
+ if (done && std::isnan(*val)) {
+ *val = std::numeric_limits<T>::quiet_NaN();
+ }
return done;
}
@@ -324,7 +335,8 @@
// - If full string conversion can't be performed, 0 is returned.
// - If the converted value falls out of range of corresponding return type, a
// range error occurs. In this case value MAX(T)/MIN(T) is returned.
-template<typename T> inline bool StringToNumber(const char *s, T *val) {
+template <typename T>
+inline bool StringToNumber(const char* s, T* val) {
// Assert on `unsigned long` and `signed long` on LP64.
// If it is necessary, it could be solved with flatbuffers::enable_if<B,T>.
static_assert(sizeof(T) < sizeof(int64_t), "unexpected type T");
@@ -351,12 +363,13 @@
return false;
}
-template<> inline bool StringToNumber<int64_t>(const char *str, int64_t *val) {
+template <>
+inline bool StringToNumber<int64_t>(const char* str, int64_t* val) {
return StringToIntegerImpl(val, str);
}
-template<>
-inline bool StringToNumber<uint64_t>(const char *str, uint64_t *val) {
+template <>
+inline bool StringToNumber<uint64_t>(const char* str, uint64_t* val) {
if (!StringToIntegerImpl(val, str)) return false;
// The strtoull accepts negative numbers:
// If the minus sign was part of the input sequence, the numeric value
@@ -377,39 +390,41 @@
return true;
}
-template<> inline bool StringToNumber(const char *s, float *val) {
+template <>
+inline bool StringToNumber(const char* s, float* val) {
return StringToFloatImpl(val, s);
}
-template<> inline bool StringToNumber(const char *s, double *val) {
+template <>
+inline bool StringToNumber(const char* s, double* val) {
return StringToFloatImpl(val, s);
}
-inline int64_t StringToInt(const char *s, int base = 10) {
+inline int64_t StringToInt(const char* s, int base = 10) {
int64_t val;
return StringToIntegerImpl(&val, s, base) ? val : 0;
}
-inline uint64_t StringToUInt(const char *s, int base = 10) {
+inline uint64_t StringToUInt(const char* s, int base = 10) {
uint64_t val;
return StringToIntegerImpl(&val, s, base) ? val : 0;
}
-inline bool StringIsFlatbufferNan(const std::string &s) {
+inline bool StringIsFlatbufferNan(const std::string& s) {
return s == "nan" || s == "+nan" || s == "-nan";
}
-inline bool StringIsFlatbufferPositiveInfinity(const std::string &s) {
+inline bool StringIsFlatbufferPositiveInfinity(const std::string& s) {
return s == "inf" || s == "+inf" || s == "infinity" || s == "+infinity";
}
-inline bool StringIsFlatbufferNegativeInfinity(const std::string &s) {
+inline bool StringIsFlatbufferNegativeInfinity(const std::string& s) {
return s == "-inf" || s == "-infinity";
}
-typedef bool (*LoadFileFunction)(const char *filename, bool binary,
- std::string *dest);
-typedef bool (*FileExistsFunction)(const char *filename);
+typedef bool (*LoadFileFunction)(const char* filename, bool binary,
+ std::string* dest);
+typedef bool (*FileExistsFunction)(const char* filename);
LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function);
@@ -417,29 +432,29 @@
FileExistsFunction file_exists_function);
// Check if file "name" exists.
-bool FileExists(const char *name);
+bool FileExists(const char* name);
// Check if "name" exists and it is also a directory.
-bool DirExists(const char *name);
+bool DirExists(const char* name);
// Load file "name" into "buf" returning true if successful
// false otherwise. If "binary" is false data is read
// using ifstream's text mode, otherwise data is read with
// no transcoding.
-bool LoadFile(const char *name, bool binary, std::string *buf);
+bool LoadFile(const char* name, bool binary, std::string* buf);
// Save data "buf" of length "len" bytes into a file
// "name" returning true if successful, false otherwise.
// If "binary" is false data is written using ifstream's
// text mode, otherwise data is written with no
// transcoding.
-bool SaveFile(const char *name, const char *buf, size_t len, bool binary);
+bool SaveFile(const char* name, const char* buf, size_t len, bool binary);
// Save data "buf" into file "name" returning true if
// successful, false otherwise. If "binary" is false
// data is written using ifstream's text mode, otherwise
// data is written with no transcoding.
-inline bool SaveFile(const char *name, const std::string &buf, bool binary) {
+inline bool SaveFile(const char* name, const std::string& buf, bool binary) {
return SaveFile(name, buf.c_str(), buf.size(), binary);
}
@@ -452,51 +467,50 @@
FLATBUFFERS_CONSTEXPR char kPathSeparator = '/';
// Returns the path with the extension, if any, removed.
-std::string StripExtension(const std::string &filepath);
+std::string StripExtension(const std::string& filepath);
// Returns the extension, if any.
-std::string GetExtension(const std::string &filepath);
+std::string GetExtension(const std::string& filepath);
// Return the last component of the path, after the last separator.
-std::string StripPath(const std::string &filepath);
+std::string StripPath(const std::string& filepath);
// Strip the last component of the path + separator.
-std::string StripFileName(const std::string &filepath);
+std::string StripFileName(const std::string& filepath);
-std::string StripPrefix(const std::string &filepath,
- const std::string &prefix_to_remove);
+std::string StripPrefix(const std::string& filepath,
+ const std::string& prefix_to_remove);
// Concatenates a path with a filename, regardless of whether the path
// ends in a separator or not.
-std::string ConCatPathFileName(const std::string &path,
- const std::string &filename);
+std::string ConCatPathFileName(const std::string& path,
+ const std::string& filename);
// Replaces any '\\' separators with '/'
-std::string PosixPath(const char *path);
-std::string PosixPath(const std::string &path);
+std::string PosixPath(const char* path);
+std::string PosixPath(const std::string& path);
// This function ensure a directory exists, by recursively
// creating dirs for any parts of the path that don't exist yet.
-void EnsureDirExists(const std::string &filepath);
+void EnsureDirExists(const std::string& filepath);
// Obtains the relative or absolute path.
-std::string FilePath(const std::string &project,
- const std::string &filePath,
+std::string FilePath(const std::string& project, const std::string& filePath,
bool absolute);
// Obtains the absolute path from any other path.
// Returns the input path if the absolute path couldn't be resolved.
-std::string AbsolutePath(const std::string &filepath);
+std::string AbsolutePath(const std::string& filepath);
// Returns files relative to the --project_root path, prefixed with `//`.
-std::string RelativeToRootPath(const std::string &project,
- const std::string &filepath);
+std::string RelativeToRootPath(const std::string& project,
+ const std::string& filepath);
// To and from UTF-8 unicode conversion functions
// Convert a unicode code point into a UTF-8 representation by appending it
// to a string. Returns the number of bytes generated.
-inline int ToUTF8(uint32_t ucc, std::string *out) {
+inline int ToUTF8(uint32_t ucc, std::string* out) {
FLATBUFFERS_ASSERT(!(ucc & 0x80000000)); // Top bit can't be set.
// 6 possible encodings: http://en.wikipedia.org/wiki/UTF-8
for (int i = 0; i < 6; i++) {
@@ -524,7 +538,7 @@
// advanced past all bytes parsed.
// returns -1 upon corrupt UTF-8 encoding (ignore the incoming pointer in
// this case).
-inline int FromUTF8(const char **in) {
+inline int FromUTF8(const char** in) {
int len = 0;
// Count leading 1 bits.
for (int mask = 0x80; mask >= 0x04; mask >>= 1) {
@@ -538,7 +552,9 @@
return -1; // Bit after leading 1's must be 0.
if (!len) return *(*in)++;
// UTF-8 encoded values with a length are between 2 and 4 bytes.
- if (len < 2 || len > 4) { return -1; }
+ if (len < 2 || len > 4) {
+ return -1;
+ }
// Grab initial bits of the code.
int ucc = *(*in)++ & ((1 << (7 - len)) - 1);
for (int i = 0; i < len - 1; i++) {
@@ -548,20 +564,28 @@
}
// UTF-8 cannot encode values between 0xD800 and 0xDFFF (reserved for
// UTF-16 surrogate pairs).
- if (ucc >= 0xD800 && ucc <= 0xDFFF) { return -1; }
+ if (ucc >= 0xD800 && ucc <= 0xDFFF) {
+ return -1;
+ }
// UTF-8 must represent code points in their shortest possible encoding.
switch (len) {
case 2:
// Two bytes of UTF-8 can represent code points from U+0080 to U+07FF.
- if (ucc < 0x0080 || ucc > 0x07FF) { return -1; }
+ if (ucc < 0x0080 || ucc > 0x07FF) {
+ return -1;
+ }
break;
case 3:
// Three bytes of UTF-8 can represent code points from U+0800 to U+FFFF.
- if (ucc < 0x0800 || ucc > 0xFFFF) { return -1; }
+ if (ucc < 0x0800 || ucc > 0xFFFF) {
+ return -1;
+ }
break;
case 4:
// Four bytes of UTF-8 can represent code points from U+10000 to U+10FFFF.
- if (ucc < 0x10000 || ucc > 0x10FFFF) { return -1; }
+ if (ucc < 0x10000 || ucc > 0x10FFFF) {
+ return -1;
+ }
break;
}
return ucc;
@@ -596,26 +620,40 @@
}
#endif // !FLATBUFFERS_PREFER_PRINTF
-inline bool EscapeString(const char *s, size_t length, std::string *_text,
+inline bool EscapeString(const char* s, size_t length, std::string* _text,
bool allow_non_utf8, bool natural_utf8) {
- std::string &text = *_text;
+ std::string& text = *_text;
text += "\"";
for (uoffset_t i = 0; i < length; i++) {
char c = s[i];
switch (c) {
- case '\n': text += "\\n"; break;
- case '\t': text += "\\t"; break;
- case '\r': text += "\\r"; break;
- case '\b': text += "\\b"; break;
- case '\f': text += "\\f"; break;
- case '\"': text += "\\\""; break;
- case '\\': text += "\\\\"; break;
+ case '\n':
+ text += "\\n";
+ break;
+ case '\t':
+ text += "\\t";
+ break;
+ case '\r':
+ text += "\\r";
+ break;
+ case '\b':
+ text += "\\b";
+ break;
+ case '\f':
+ text += "\\f";
+ break;
+ case '\"':
+ text += "\\\"";
+ break;
+ case '\\':
+ text += "\\\\";
+ break;
default:
if (c >= ' ' && c <= '~') {
text += c;
} else {
// Not printable ASCII data. Let's see if it's valid UTF-8 first:
- const char *utf8 = s + i;
+ const char* utf8 = s + i;
int ucc = FromUTF8(&utf8);
if (ucc < 0) {
if (allow_non_utf8) {
@@ -666,19 +704,21 @@
return true;
}
-inline std::string BufferToHexText(const void *buffer, size_t buffer_size,
+inline std::string BufferToHexText(const void* buffer, size_t buffer_size,
size_t max_length,
- const std::string &wrapped_line_prefix,
- const std::string &wrapped_line_suffix) {
+ const std::string& wrapped_line_prefix,
+ const std::string& wrapped_line_suffix) {
std::string text = wrapped_line_prefix;
size_t start_offset = 0;
- const char *s = reinterpret_cast<const char *>(buffer);
+ const char* s = reinterpret_cast<const char*>(buffer);
for (size_t i = 0; s && i < buffer_size; i++) {
// Last iteration or do we have more?
bool have_more = i + 1 < buffer_size;
text += "0x";
text += IntToStringHex(static_cast<uint8_t>(s[i]), 2);
- if (have_more) { text += ','; }
+ if (have_more) {
+ text += ',';
+ }
// If we have more to process and we reached max_length
if (have_more &&
text.size() + wrapped_line_suffix.size() >= start_offset + max_length) {
@@ -693,17 +733,17 @@
}
// Remove paired quotes in a string: "text"|'text' -> text.
-std::string RemoveStringQuotes(const std::string &s);
+std::string RemoveStringQuotes(const std::string& s);
// Change th global C-locale to locale with name <locale_name>.
// Returns an actual locale name in <_value>, useful if locale_name is "" or
// null.
-bool SetGlobalTestLocale(const char *locale_name,
- std::string *_value = nullptr);
+bool SetGlobalTestLocale(const char* locale_name,
+ std::string* _value = nullptr);
// Read (or test) a value of environment variable.
-bool ReadEnvironmentVariable(const char *var_name,
- std::string *_value = nullptr);
+bool ReadEnvironmentVariable(const char* var_name,
+ std::string* _value = nullptr);
enum class Case {
kUnknown = 0,
@@ -729,7 +769,7 @@
// Convert the `input` string of case `input_case` to the specified
// `output_case`.
-std::string ConvertCase(const std::string &input, Case output_case,
+std::string ConvertCase(const std::string& input, Case output_case,
Case input_case = Case::kSnake);
} // namespace flatbuffers
diff --git a/include/flatbuffers/vector.h b/include/flatbuffers/vector.h
index 021b3c3..e967e53 100644
--- a/include/flatbuffers/vector.h
+++ b/include/flatbuffers/vector.h
@@ -27,56 +27,56 @@
// An STL compatible iterator implementation for Vector below, effectively
// calling Get() for every element.
-template<typename T, typename IT, typename Data = uint8_t *,
- typename SizeT = uoffset_t>
+template <typename T, typename IT, typename Data = uint8_t*,
+ typename SizeT = uoffset_t>
struct VectorIterator {
typedef std::random_access_iterator_tag iterator_category;
typedef IT value_type;
typedef ptrdiff_t difference_type;
- typedef IT *pointer;
- typedef IT &reference;
+ typedef IT* pointer;
+ typedef IT& reference;
static const SizeT element_stride = IndirectHelper<T>::element_stride;
VectorIterator(Data data, SizeT i) : data_(data + element_stride * i) {}
- VectorIterator(const VectorIterator &other) : data_(other.data_) {}
+ VectorIterator(const VectorIterator& other) : data_(other.data_) {}
VectorIterator() : data_(nullptr) {}
- VectorIterator &operator=(const VectorIterator &other) {
+ VectorIterator& operator=(const VectorIterator& other) {
data_ = other.data_;
return *this;
}
- VectorIterator &operator=(VectorIterator &&other) {
+ VectorIterator& operator=(VectorIterator&& other) {
data_ = other.data_;
return *this;
}
- bool operator==(const VectorIterator &other) const {
+ bool operator==(const VectorIterator& other) const {
return data_ == other.data_;
}
- bool operator!=(const VectorIterator &other) const {
+ bool operator!=(const VectorIterator& other) const {
return data_ != other.data_;
}
- bool operator<(const VectorIterator &other) const {
+ bool operator<(const VectorIterator& other) const {
return data_ < other.data_;
}
- bool operator>(const VectorIterator &other) const {
+ bool operator>(const VectorIterator& other) const {
return data_ > other.data_;
}
- bool operator<=(const VectorIterator &other) const {
+ bool operator<=(const VectorIterator& other) const {
return !(data_ > other.data_);
}
- bool operator>=(const VectorIterator &other) const {
+ bool operator>=(const VectorIterator& other) const {
return !(data_ < other.data_);
}
- difference_type operator-(const VectorIterator &other) const {
+ difference_type operator-(const VectorIterator& other) const {
return (data_ - other.data_) / element_stride;
}
@@ -88,7 +88,7 @@
// `pointer operator->()`.
IT operator->() const { return IndirectHelper<T>::Read(data_, 0); }
- VectorIterator &operator++() {
+ VectorIterator& operator++() {
data_ += element_stride;
return *this;
}
@@ -99,16 +99,16 @@
return temp;
}
- VectorIterator operator+(const SizeT &offset) const {
+ VectorIterator operator+(const SizeT& offset) const {
return VectorIterator(data_ + offset * element_stride, 0);
}
- VectorIterator &operator+=(const SizeT &offset) {
+ VectorIterator& operator+=(const SizeT& offset) {
data_ += offset * element_stride;
return *this;
}
- VectorIterator &operator--() {
+ VectorIterator& operator--() {
data_ -= element_stride;
return *this;
}
@@ -119,11 +119,11 @@
return temp;
}
- VectorIterator operator-(const SizeT &offset) const {
+ VectorIterator operator-(const SizeT& offset) const {
return VectorIterator(data_ - offset * element_stride, 0);
}
- VectorIterator &operator-=(const SizeT &offset) {
+ VectorIterator& operator-=(const SizeT& offset) {
data_ -= offset * element_stride;
return *this;
}
@@ -132,10 +132,10 @@
Data data_;
};
-template<typename T, typename IT, typename SizeT = uoffset_t>
-using VectorConstIterator = VectorIterator<T, IT, const uint8_t *, SizeT>;
+template <typename T, typename IT, typename SizeT = uoffset_t>
+using VectorConstIterator = VectorIterator<T, IT, const uint8_t*, SizeT>;
-template<typename Iterator>
+template <typename Iterator>
struct VectorReverseIterator : public std::reverse_iterator<Iterator> {
explicit VectorReverseIterator(Iterator iter)
: std::reverse_iterator<Iterator>(iter) {}
@@ -157,10 +157,11 @@
// This is used as a helper type for accessing vectors.
// Vector::data() assumes the vector elements start after the length field.
-template<typename T, typename SizeT = uoffset_t> class Vector {
+template <typename T, typename SizeT = uoffset_t>
+class Vector {
public:
typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type,
- uint8_t *, SizeT>
+ uint8_t*, SizeT>
iterator;
typedef VectorConstIterator<T, typename IndirectHelper<T>::return_type, SizeT>
const_iterator;
@@ -199,24 +200,26 @@
// If this is a Vector of enums, T will be its storage type, not the enum
// type. This function makes it convenient to retrieve value with enum
// type E.
- template<typename E> E GetEnum(SizeT i) const {
+ template <typename E>
+ E GetEnum(SizeT i) const {
return static_cast<E>(Get(i));
}
// If this a vector of unions, this does the cast for you. There's no check
// to make sure this is the right type!
- template<typename U> const U *GetAs(SizeT i) const {
- return reinterpret_cast<const U *>(Get(i));
+ template <typename U>
+ const U* GetAs(SizeT i) const {
+ return reinterpret_cast<const U*>(Get(i));
}
// If this a vector of unions, this does the cast for you. There's no check
// to make sure this is actually a string!
- const String *GetAsString(SizeT i) const {
- return reinterpret_cast<const String *>(Get(i));
+ const String* GetAsString(SizeT i) const {
+ return reinterpret_cast<const String*>(Get(i));
}
- const void *GetStructFromOffset(size_t o) const {
- return reinterpret_cast<const void *>(Data() + o);
+ const void* GetStructFromOffset(size_t o) const {
+ return reinterpret_cast<const void*>(Data() + o);
}
iterator begin() { return iterator(Data(), 0); }
@@ -245,7 +248,7 @@
// Change elements if you have a non-const pointer to this object.
// Scalars only. See reflection.h, and the documentation.
- void Mutate(SizeT i, const T &val) {
+ void Mutate(SizeT i, const T& val) {
FLATBUFFERS_ASSERT(i < size());
WriteScalar(data() + i, val);
}
@@ -253,7 +256,7 @@
// Change an element of a vector of tables (or strings).
// "val" points to the new table/string, as you can obtain from
// e.g. reflection::AddFlatBuffer().
- void MutateOffset(SizeT i, const uint8_t *val) {
+ void MutateOffset(SizeT i, const uint8_t* val) {
FLATBUFFERS_ASSERT(i < size());
static_assert(sizeof(T) == sizeof(SizeT), "Unrelated types");
WriteScalar(data() + i,
@@ -267,30 +270,32 @@
}
// The raw data in little endian format. Use with care.
- const uint8_t *Data() const {
- return reinterpret_cast<const uint8_t *>(&length_ + 1);
+ const uint8_t* Data() const {
+ return reinterpret_cast<const uint8_t*>(&length_ + 1);
}
- uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); }
+ uint8_t* Data() { return reinterpret_cast<uint8_t*>(&length_ + 1); }
// Similarly, but typed, much like std::vector::data
- const T *data() const { return reinterpret_cast<const T *>(Data()); }
- T *data() { return reinterpret_cast<T *>(Data()); }
+ const T* data() const { return reinterpret_cast<const T*>(Data()); }
+ T* data() { return reinterpret_cast<T*>(Data()); }
- template<typename K> return_type LookupByKey(K key) const {
- void *search_result = std::bsearch(
+ template <typename K>
+ return_type LookupByKey(K key) const {
+ void* search_result = std::bsearch(
&key, Data(), size(), IndirectHelper<T>::element_stride, KeyCompare<K>);
if (!search_result) {
return nullptr; // Key not found.
}
- const uint8_t *element = reinterpret_cast<const uint8_t *>(search_result);
+ const uint8_t* element = reinterpret_cast<const uint8_t*>(search_result);
return IndirectHelper<T>::Read(element, 0);
}
- template<typename K> mutable_return_type MutableLookupByKey(K key) {
+ template <typename K>
+ mutable_return_type MutableLookupByKey(K key) {
return const_cast<mutable_return_type>(LookupByKey(key));
}
@@ -304,12 +309,13 @@
private:
// This class is a pointer. Copying will therefore create an invalid object.
// Private and unimplemented copy constructor.
- Vector(const Vector &);
- Vector &operator=(const Vector &);
+ Vector(const Vector&);
+ Vector& operator=(const Vector&);
- template<typename K> static int KeyCompare(const void *ap, const void *bp) {
- const K *key = reinterpret_cast<const K *>(ap);
- const uint8_t *data = reinterpret_cast<const uint8_t *>(bp);
+ template <typename K>
+ static int KeyCompare(const void* ap, const void* bp) {
+ const K* key = reinterpret_cast<const K*>(ap);
+ const uint8_t* data = reinterpret_cast<const uint8_t*>(bp);
auto table = IndirectHelper<T>::Read(data, 0);
// std::bsearch compares with the operands transposed, so we negate the
@@ -318,35 +324,36 @@
}
};
-template<typename T> using Vector64 = Vector<T, uoffset64_t>;
+template <typename T>
+using Vector64 = Vector<T, uoffset64_t>;
-template<class U>
-FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U> make_span(Vector<U> &vec)
+template <class U>
+FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U> make_span(Vector<U>& vec)
FLATBUFFERS_NOEXCEPT {
static_assert(Vector<U>::is_span_observable,
"wrong type U, only LE-scalar, or byte types are allowed");
return span<U>(vec.data(), vec.size());
}
-template<class U>
+template <class U>
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const U> make_span(
- const Vector<U> &vec) FLATBUFFERS_NOEXCEPT {
+ const Vector<U>& vec) FLATBUFFERS_NOEXCEPT {
static_assert(Vector<U>::is_span_observable,
"wrong type U, only LE-scalar, or byte types are allowed");
return span<const U>(vec.data(), vec.size());
}
-template<class U>
+template <class U>
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<uint8_t> make_bytes_span(
- Vector<U> &vec) FLATBUFFERS_NOEXCEPT {
+ Vector<U>& vec) FLATBUFFERS_NOEXCEPT {
static_assert(Vector<U>::scalar_tag::value,
"wrong type U, only LE-scalar, or byte types are allowed");
return span<uint8_t>(vec.Data(), vec.size() * sizeof(U));
}
-template<class U>
+template <class U>
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const uint8_t> make_bytes_span(
- const Vector<U> &vec) FLATBUFFERS_NOEXCEPT {
+ const Vector<U>& vec) FLATBUFFERS_NOEXCEPT {
static_assert(Vector<U>::scalar_tag::value,
"wrong type U, only LE-scalar, or byte types are allowed");
return span<const uint8_t>(vec.Data(), vec.size() * sizeof(U));
@@ -354,17 +361,17 @@
// Convenient helper functions to get a span of any vector, regardless
// of whether it is null or not (the field is not set).
-template<class U>
-FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U> make_span(Vector<U> *ptr)
+template <class U>
+FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U> make_span(Vector<U>* ptr)
FLATBUFFERS_NOEXCEPT {
static_assert(Vector<U>::is_span_observable,
"wrong type U, only LE-scalar, or byte types are allowed");
return ptr ? make_span(*ptr) : span<U>();
}
-template<class U>
+template <class U>
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const U> make_span(
- const Vector<U> *ptr) FLATBUFFERS_NOEXCEPT {
+ const Vector<U>* ptr) FLATBUFFERS_NOEXCEPT {
static_assert(Vector<U>::is_span_observable,
"wrong type U, only LE-scalar, or byte types are allowed");
return ptr ? make_span(*ptr) : span<const U>();
@@ -376,10 +383,10 @@
public:
uoffset_t size() const { return EndianScalar(length_); }
- const uint8_t *Data() const {
- return reinterpret_cast<const uint8_t *>(&length_ + 1);
+ const uint8_t* Data() const {
+ return reinterpret_cast<const uint8_t*>(&length_ + 1);
}
- uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); }
+ uint8_t* Data() { return reinterpret_cast<uint8_t*>(&length_ + 1); }
protected:
VectorOfAny();
@@ -387,25 +394,26 @@
uoffset_t length_;
private:
- VectorOfAny(const VectorOfAny &);
- VectorOfAny &operator=(const VectorOfAny &);
+ VectorOfAny(const VectorOfAny&);
+ VectorOfAny& operator=(const VectorOfAny&);
};
-template<typename T, typename U>
-Vector<Offset<T>> *VectorCast(Vector<Offset<U>> *ptr) {
+template <typename T, typename U>
+Vector<Offset<T>>* VectorCast(Vector<Offset<U>>* ptr) {
static_assert(std::is_base_of<T, U>::value, "Unrelated types");
- return reinterpret_cast<Vector<Offset<T>> *>(ptr);
+ return reinterpret_cast<Vector<Offset<T>>*>(ptr);
}
-template<typename T, typename U>
-const Vector<Offset<T>> *VectorCast(const Vector<Offset<U>> *ptr) {
+template <typename T, typename U>
+const Vector<Offset<T>>* VectorCast(const Vector<Offset<U>>* ptr) {
static_assert(std::is_base_of<T, U>::value, "Unrelated types");
- return reinterpret_cast<const Vector<Offset<T>> *>(ptr);
+ return reinterpret_cast<const Vector<Offset<T>>*>(ptr);
}
// Convenient helper function to get the length of any vector, regardless
// of whether it is null or not (the field is not set).
-template<typename T> static inline size_t VectorLength(const Vector<T> *v) {
+template <typename T>
+static inline size_t VectorLength(const Vector<T>* v) {
return v ? v->size() : 0;
}
diff --git a/include/flatbuffers/vector_downward.h b/include/flatbuffers/vector_downward.h
index 2b5a92c..3e6da8e 100644
--- a/include/flatbuffers/vector_downward.h
+++ b/include/flatbuffers/vector_downward.h
@@ -32,9 +32,10 @@
// Since this vector leaves the lower part unused, we support a "scratch-pad"
// that can be stored there for temporary data, to share the allocated space.
// Essentially, this supports 2 std::vectors in a single buffer.
-template<typename SizeT = uoffset_t> class vector_downward {
+template <typename SizeT = uoffset_t>
+class vector_downward {
public:
- explicit vector_downward(size_t initial_size, Allocator *allocator,
+ explicit vector_downward(size_t initial_size, Allocator* allocator,
bool own_allocator, size_t buffer_minalign,
const SizeT max_size = FLATBUFFERS_MAX_BUFFER_SIZE)
: allocator_(allocator),
@@ -48,7 +49,7 @@
cur_(nullptr),
scratch_(nullptr) {}
- vector_downward(vector_downward &&other) noexcept
+ vector_downward(vector_downward&& other) noexcept
// clang-format on
: allocator_(other.allocator_),
own_allocator_(other.own_allocator_),
@@ -70,7 +71,7 @@
other.scratch_ = nullptr;
}
- vector_downward &operator=(vector_downward &&other) noexcept {
+ vector_downward& operator=(vector_downward&& other) noexcept {
// Move construct a temporary and swap idiom
vector_downward temp(std::move(other));
swap(temp);
@@ -101,7 +102,9 @@
void clear_scratch() { scratch_ = buf_; }
void clear_allocator() {
- if (own_allocator_ && allocator_) { delete allocator_; }
+ if (own_allocator_ && allocator_) {
+ delete allocator_;
+ }
allocator_ = nullptr;
own_allocator_ = false;
}
@@ -112,8 +115,8 @@
}
// Relinquish the pointer to the caller.
- uint8_t *release_raw(size_t &allocated_bytes, size_t &offset) {
- auto *buf = buf_;
+ uint8_t* release_raw(size_t& allocated_bytes, size_t& offset) {
+ auto* buf = buf_;
allocated_bytes = reserved_;
offset = vector_downward::offset();
@@ -142,12 +145,14 @@
FLATBUFFERS_ASSERT(cur_ >= scratch_ && scratch_ >= buf_);
// If the length is larger than the unused part of the buffer, we need to
// grow.
- if (len > unused_buffer_size()) { reallocate(len); }
+ if (len > unused_buffer_size()) {
+ reallocate(len);
+ }
FLATBUFFERS_ASSERT(size() < max_size_);
return len;
}
- inline uint8_t *make_space(size_t len) {
+ inline uint8_t* make_space(size_t len) {
if (len) {
ensure_space(len);
cur_ -= len;
@@ -157,7 +162,7 @@
}
// Returns nullptr if using the DefaultAllocator.
- Allocator *get_custom_allocator() { return allocator_; }
+ Allocator* get_custom_allocator() { return allocator_; }
// The current offset into the buffer.
size_t offset() const { return cur_ - buf_; }
@@ -175,36 +180,40 @@
size_t capacity() const { return reserved_; }
- uint8_t *data() const {
+ uint8_t* data() const {
FLATBUFFERS_ASSERT(cur_);
return cur_;
}
- uint8_t *scratch_data() const {
+ uint8_t* scratch_data() const {
FLATBUFFERS_ASSERT(buf_);
return buf_;
}
- uint8_t *scratch_end() const {
+ uint8_t* scratch_end() const {
FLATBUFFERS_ASSERT(scratch_);
return scratch_;
}
- uint8_t *data_at(size_t offset) const { return buf_ + reserved_ - offset; }
+ uint8_t* data_at(size_t offset) const { return buf_ + reserved_ - offset; }
- void push(const uint8_t *bytes, size_t num) {
- if (num > 0) { memcpy(make_space(num), bytes, num); }
+ void push(const uint8_t* bytes, size_t num) {
+ if (num > 0) {
+ memcpy(make_space(num), bytes, num);
+ }
}
// Specialized version of push() that avoids memcpy call for small data.
- template<typename T> void push_small(const T &little_endian_t) {
+ template <typename T>
+ void push_small(const T& little_endian_t) {
make_space(sizeof(T));
- *reinterpret_cast<T *>(cur_) = little_endian_t;
+ *reinterpret_cast<T*>(cur_) = little_endian_t;
}
- template<typename T> void scratch_push_small(const T &t) {
+ template <typename T>
+ void scratch_push_small(const T& t) {
ensure_space(sizeof(T));
- *reinterpret_cast<T *>(scratch_) = t;
+ *reinterpret_cast<T*>(scratch_) = t;
scratch_ += sizeof(T);
}
@@ -228,7 +237,7 @@
void scratch_pop(size_t bytes_to_remove) { scratch_ -= bytes_to_remove; }
- void swap(vector_downward &other) {
+ void swap(vector_downward& other) {
using std::swap;
swap(allocator_, other.allocator_);
swap(own_allocator_, other.own_allocator_);
@@ -242,7 +251,7 @@
swap(scratch_, other.scratch_);
}
- void swap_allocator(vector_downward &other) {
+ void swap_allocator(vector_downward& other) {
using std::swap;
swap(allocator_, other.allocator_);
swap(own_allocator_, other.own_allocator_);
@@ -250,10 +259,10 @@
private:
// You shouldn't really be copying instances of this class.
- FLATBUFFERS_DELETE_FUNC(vector_downward(const vector_downward &));
- FLATBUFFERS_DELETE_FUNC(vector_downward &operator=(const vector_downward &));
+ FLATBUFFERS_DELETE_FUNC(vector_downward(const vector_downward&));
+ FLATBUFFERS_DELETE_FUNC(vector_downward& operator=(const vector_downward&));
- Allocator *allocator_;
+ Allocator* allocator_;
bool own_allocator_;
size_t initial_size_;
@@ -262,9 +271,9 @@
size_t buffer_minalign_;
size_t reserved_;
SizeT size_;
- uint8_t *buf_;
- uint8_t *cur_; // Points at location between empty (below) and used (above).
- uint8_t *scratch_; // Points to the end of the scratchpad in use.
+ uint8_t* buf_;
+ uint8_t* cur_; // Points at location between empty (below) and used (above).
+ uint8_t* scratch_; // Points to the end of the scratchpad in use.
void reallocate(size_t len) {
auto old_reserved = reserved_;
diff --git a/include/flatbuffers/verifier.h b/include/flatbuffers/verifier.h
index 6df923b..a0b7935 100644
--- a/include/flatbuffers/verifier.h
+++ b/include/flatbuffers/verifier.h
@@ -41,14 +41,14 @@
bool assert = false;
};
- explicit VerifierTemplate(const uint8_t *const buf, const size_t buf_len,
- const Options &opts)
+ explicit VerifierTemplate(const uint8_t* const buf, const size_t buf_len,
+ const Options& opts)
: buf_(buf), size_(buf_len), opts_(opts) {
FLATBUFFERS_ASSERT(size_ < opts.max_size);
}
// Deprecated API, please construct with VerifierTemplate::Options.
- VerifierTemplate(const uint8_t *const buf, const size_t buf_len,
+ VerifierTemplate(const uint8_t* const buf, const size_t buf_len,
const uoffset_t max_depth = 64,
const uoffset_t max_tables = 1000000,
const bool check_alignment = true)
@@ -80,7 +80,7 @@
if (TrackVerifierBufferSize) {
auto upper_bound = elem + elem_len;
if (upper_bound_ < upper_bound) {
- upper_bound_ = upper_bound;
+ upper_bound_ = upper_bound;
}
}
return Check(elem_len < size_ && elem <= size_ - elem_len);
@@ -91,59 +91,61 @@
}
// Verify a range indicated by sizeof(T).
- template<typename T> bool Verify(const size_t elem) const {
+ template <typename T>
+ bool Verify(const size_t elem) const {
return VerifyAlignment(elem, sizeof(T)) && Verify(elem, sizeof(T));
}
- bool VerifyFromPointer(const uint8_t *const p, const size_t len) {
+ bool VerifyFromPointer(const uint8_t* const p, const size_t len) {
return Verify(static_cast<size_t>(p - buf_), len);
}
// Verify relative to a known-good base pointer.
- bool VerifyFieldStruct(const uint8_t *const base, const voffset_t elem_off,
+ bool VerifyFieldStruct(const uint8_t* const base, const voffset_t elem_off,
const size_t elem_len, const size_t align) const {
const auto f = static_cast<size_t>(base - buf_) + elem_off;
return VerifyAlignment(f, align) && Verify(f, elem_len);
}
- template<typename T>
- bool VerifyField(const uint8_t *const base, const voffset_t elem_off,
+ template <typename T>
+ bool VerifyField(const uint8_t* const base, const voffset_t elem_off,
const size_t align) const {
const auto f = static_cast<size_t>(base - buf_) + elem_off;
return VerifyAlignment(f, align) && Verify(f, sizeof(T));
}
// Verify a pointer (may be NULL) of a table type.
- template<typename T> bool VerifyTable(const T *const table) {
+ template <typename T>
+ bool VerifyTable(const T* const table) {
return !table || table->Verify(*this);
}
// Verify a pointer (may be NULL) of any vector type.
- template<int &..., typename T, typename LenT>
- bool VerifyVector(const Vector<T, LenT> *const vec) const {
+ template <int&..., typename T, typename LenT>
+ bool VerifyVector(const Vector<T, LenT>* const vec) const {
return !vec || VerifyVectorOrString<LenT>(
- reinterpret_cast<const uint8_t *>(vec), sizeof(T));
+ reinterpret_cast<const uint8_t*>(vec), sizeof(T));
}
// Verify a pointer (may be NULL) of a vector to struct.
- template<int &..., typename T, typename LenT>
- bool VerifyVector(const Vector<const T *, LenT> *const vec) const {
- return VerifyVector(reinterpret_cast<const Vector<T, LenT> *>(vec));
+ template <int&..., typename T, typename LenT>
+ bool VerifyVector(const Vector<const T*, LenT>* const vec) const {
+ return VerifyVector(reinterpret_cast<const Vector<T, LenT>*>(vec));
}
// Verify a pointer (may be NULL) to string.
- bool VerifyString(const String *const str) const {
+ bool VerifyString(const String* const str) const {
size_t end;
return !str || (VerifyVectorOrString<uoffset_t>(
- reinterpret_cast<const uint8_t *>(str), 1, &end) &&
+ reinterpret_cast<const uint8_t*>(str), 1, &end) &&
Verify(end, 1) && // Must have terminator
Check(buf_[end] == '\0')); // Terminating byte must be 0.
}
// Common code between vectors and strings.
- template<typename LenT = uoffset_t>
- bool VerifyVectorOrString(const uint8_t *const vec, const size_t elem_size,
- size_t *const end = nullptr) const {
+ template <typename LenT = uoffset_t>
+ bool VerifyVectorOrString(const uint8_t* const vec, const size_t elem_size,
+ size_t* const end = nullptr) const {
const auto vec_offset = static_cast<size_t>(vec - buf_);
// Check we can read the size field.
if (!Verify<LenT>(vec_offset)) return false;
@@ -159,7 +161,7 @@
}
// Special case for string contents, after the above has been called.
- bool VerifyVectorOfStrings(const Vector<Offset<String>> *const vec) const {
+ bool VerifyVectorOfStrings(const Vector<Offset<String>>* const vec) const {
if (vec) {
for (uoffset_t i = 0; i < vec->size(); i++) {
if (!VerifyString(vec->Get(i))) return false;
@@ -169,8 +171,8 @@
}
// Special case for table contents, after the above has been called.
- template<typename T>
- bool VerifyVectorOfTables(const Vector<Offset<T>> *const vec) {
+ template <typename T>
+ bool VerifyVectorOfTables(const Vector<Offset<T>>* const vec) {
if (vec) {
for (uoffset_t i = 0; i < vec->size(); i++) {
if (!vec->Get(i)->Verify(*this)) return false;
@@ -180,7 +182,7 @@
}
FLATBUFFERS_SUPPRESS_UBSAN("unsigned-integer-overflow")
- bool VerifyTableStart(const uint8_t *const table) {
+ bool VerifyTableStart(const uint8_t* const table) {
// Check the vtable offset.
const auto tableo = static_cast<size_t>(table - buf_);
if (!Verify<soffset_t>(tableo)) return false;
@@ -197,8 +199,8 @@
return Check((vsize & 1) == 0) && Verify(vtableo, vsize);
}
- template<typename T>
- bool VerifyBufferFromStart(const char *const identifier, const size_t start) {
+ template <typename T>
+ bool VerifyBufferFromStart(const char* const identifier, const size_t start) {
// Buffers have to be of some size to be valid. The reason it is a runtime
// check instead of static_assert, is that nested flatbuffers go through
// this call and their size is determined at runtime.
@@ -213,7 +215,7 @@
// Call T::Verify, which must be in the generated code for this type.
const auto o = VerifyOffset<uoffset_t>(start);
if (!Check(o != 0)) return false;
- if (!(reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this))) {
+ if (!(reinterpret_cast<const T*>(buf_ + start + o)->Verify(*this))) {
return false;
}
if (TrackVerifierBufferSize) {
@@ -222,9 +224,9 @@
return true;
}
- template<typename T, int &..., typename SizeT>
- bool VerifyNestedFlatBuffer(const Vector<uint8_t, SizeT> *const buf,
- const char *const identifier) {
+ template <typename T, int&..., typename SizeT>
+ bool VerifyNestedFlatBuffer(const Vector<uint8_t, SizeT>* const buf,
+ const char* const identifier) {
// Caller opted out of this.
if (!opts_.check_nested_flatbuffers) return true;
@@ -240,14 +242,18 @@
}
// Verify this whole buffer, starting with root type T.
- template<typename T> bool VerifyBuffer() { return VerifyBuffer<T>(nullptr); }
+ template <typename T>
+ bool VerifyBuffer() {
+ return VerifyBuffer<T>(nullptr);
+ }
- template<typename T> bool VerifyBuffer(const char *const identifier) {
+ template <typename T>
+ bool VerifyBuffer(const char* const identifier) {
return VerifyBufferFromStart<T>(identifier, 0);
}
- template<typename T, typename SizeT = uoffset_t>
- bool VerifySizePrefixedBuffer(const char *const identifier) {
+ template <typename T, typename SizeT = uoffset_t>
+ bool VerifySizePrefixedBuffer(const char* const identifier) {
return Verify<SizeT>(0U) &&
// Ensure the prefixed size is within the bounds of the provided
// length.
@@ -255,7 +261,7 @@
VerifyBufferFromStart<T>(identifier, sizeof(SizeT));
}
- template<typename OffsetT = uoffset_t, typename SOffsetT = soffset_t>
+ template <typename OffsetT = uoffset_t, typename SOffsetT = soffset_t>
size_t VerifyOffset(const size_t start) const {
if (!Verify<OffsetT>(start)) return 0;
const auto o = ReadScalar<OffsetT>(buf_ + start);
@@ -269,8 +275,8 @@
return o;
}
- template<typename OffsetT = uoffset_t>
- size_t VerifyOffset(const uint8_t *const base, const voffset_t start) const {
+ template <typename OffsetT = uoffset_t>
+ size_t VerifyOffset(const uint8_t* const base, const voffset_t start) const {
return VerifyOffset<OffsetT>(static_cast<size_t>(base - buf_) + start);
}
@@ -303,7 +309,7 @@
uintptr_t size = upper_bound_;
// Align the size to uoffset_t
size = (size - 1 + sizeof(uoffset_t)) & ~(sizeof(uoffset_t) - 1);
- return (size > size_) ? 0 : size;
+ return (size > size_) ? 0 : size;
}
// Must use SizeVerifier, or (deprecated) turn on
// FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE, for this to work.
@@ -312,14 +318,14 @@
return 0;
}
- std::vector<uint8_t> *GetFlexReuseTracker() { return flex_reuse_tracker_; }
+ std::vector<uint8_t>* GetFlexReuseTracker() { return flex_reuse_tracker_; }
- void SetFlexReuseTracker(std::vector<uint8_t> *const rt) {
+ void SetFlexReuseTracker(std::vector<uint8_t>* const rt) {
flex_reuse_tracker_ = rt;
}
private:
- const uint8_t *buf_;
+ const uint8_t* buf_;
const size_t size_;
const Options opts_;
@@ -327,18 +333,18 @@
uoffset_t depth_ = 0;
uoffset_t num_tables_ = 0;
- std::vector<uint8_t> *flex_reuse_tracker_ = nullptr;
+ std::vector<uint8_t>* flex_reuse_tracker_ = nullptr;
};
// Specialization for 64-bit offsets.
-template<>
-template<>
+template <>
+template <>
inline size_t VerifierTemplate<false>::VerifyOffset<uoffset64_t>(
const size_t start) const {
return VerifyOffset<uoffset64_t, soffset64_t>(start);
}
-template<>
-template<>
+template <>
+template <>
inline size_t VerifierTemplate<true>::VerifyOffset<uoffset64_t>(
const size_t start) const {
return VerifyOffset<uoffset64_t, soffset64_t>(start);
diff --git a/samples/sample_bfbs.cpp b/samples/sample_bfbs.cpp
index 1178b0e..d8d5b86 100644
--- a/samples/sample_bfbs.cpp
+++ b/samples/sample_bfbs.cpp
@@ -22,7 +22,7 @@
// This is an example of parsing text straight into a buffer and then
// generating flatbuffer (JSON) text from the buffer.
-int main(int /*argc*/, const char * /*argv*/[]) {
+int main(int /*argc*/, const char* /*argv*/[]) {
// load FlatBuffer schema (.fbs) and JSON from disk
std::string schema_file;
std::string json_file;
@@ -37,8 +37,8 @@
return 1;
}
- const char *include_directories[] = { "samples", "tests",
- "tests/include_test", nullptr };
+ const char* include_directories[] = {"samples", "tests", "tests/include_test",
+ nullptr};
// parse fbs schema
flatbuffers::Parser parser1;
ok = parser1.Parse(schema_file.c_str(), include_directories);
@@ -46,7 +46,7 @@
// inizialize parser by deserializing bfbs schema
flatbuffers::Parser parser2;
- ok = parser2.Deserialize(reinterpret_cast<const uint8_t *>(bfbs_file.c_str()),
+ ok = parser2.Deserialize(reinterpret_cast<const uint8_t*>(bfbs_file.c_str()),
bfbs_file.length());
assert(ok);
diff --git a/samples/sample_binary.cpp b/samples/sample_binary.cpp
index b8f4f1f..25f8135 100644
--- a/samples/sample_binary.cpp
+++ b/samples/sample_binary.cpp
@@ -20,7 +20,7 @@
// Example how to use FlatBuffers to create and read binary buffers.
-int main(int /*argc*/, const char * /*argv*/[]) {
+int main(int /*argc*/, const char* /*argv*/[]) {
// Build up a serialized buffer algorithmically:
flatbuffers::FlatBufferBuilder builder;
@@ -46,7 +46,7 @@
auto name = builder.CreateString("MyMonster");
- unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
+ unsigned char inv_data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto inventory = builder.CreateVector(inv_data, 10);
// Shortcut for creating monster with all fields set:
@@ -83,8 +83,8 @@
(void)inv;
// Get and test the `weapons` FlatBuffers's `vector`.
- std::string expected_weapon_names[] = { "Sword", "Axe" };
- short expected_weapon_damages[] = { 3, 5 };
+ std::string expected_weapon_names[] = {"Sword", "Axe"};
+ short expected_weapon_damages[] = {3, 5};
auto weps = monster->weapons();
for (unsigned int i = 0; i < weps->size(); i++) {
assert(weps->Get(i)->name()->str() == expected_weapon_names[i]);
@@ -95,7 +95,7 @@
// Get and test the `Equipment` union (`equipped` field).
assert(monster->equipped_type() == Equipment_Weapon);
- auto equipped = static_cast<const Weapon *>(monster->equipped());
+ auto equipped = static_cast<const Weapon*>(monster->equipped());
assert(equipped->name()->str() == "Axe");
assert(equipped->damage() == 5);
(void)equipped;
diff --git a/samples/sample_text.cpp b/samples/sample_text.cpp
index fb42563..df642e5 100644
--- a/samples/sample_text.cpp
+++ b/samples/sample_text.cpp
@@ -22,7 +22,7 @@
// This is an example of parsing text straight into a buffer and then
// generating flatbuffer (JSON) text from the buffer.
-int main(int /*argc*/, const char * /*argv*/[]) {
+int main(int /*argc*/, const char* /*argv*/[]) {
// load FlatBuffer schema (.fbs) and JSON from disk
std::string schemafile;
std::string jsonfile;
@@ -35,7 +35,7 @@
// parse schema first, so we can use it to parse the data after
flatbuffers::Parser parser;
- const char *include_directories[] = { "samples", nullptr };
+ const char* include_directories[] = {"samples", nullptr};
ok = parser.Parse(schemafile.c_str(), include_directories) &&
parser.Parse(jsonfile.c_str(), include_directories);
assert(ok);
diff --git a/src/annotated_binary_text_gen.cpp b/src/annotated_binary_text_gen.cpp
index 87ab231..4c7cda5 100644
--- a/src/annotated_binary_text_gen.cpp
+++ b/src/annotated_binary_text_gen.cpp
@@ -30,18 +30,30 @@
static std::string ToString(const BinarySectionType type) {
switch (type) {
- case BinarySectionType::Header: return "header";
- case BinarySectionType::Table: return "table";
- case BinarySectionType::RootTable: return "root_table";
- case BinarySectionType::VTable: return "vtable";
- case BinarySectionType::Struct: return "struct";
- case BinarySectionType::String: return "string";
- case BinarySectionType::Vector: return "vector";
- case BinarySectionType::Vector64: return "vector64";
- case BinarySectionType::Unknown: return "unknown";
- case BinarySectionType::Union: return "union";
- case BinarySectionType::Padding: return "padding";
- default: return "todo";
+ case BinarySectionType::Header:
+ return "header";
+ case BinarySectionType::Table:
+ return "table";
+ case BinarySectionType::RootTable:
+ return "root_table";
+ case BinarySectionType::VTable:
+ return "vtable";
+ case BinarySectionType::Struct:
+ return "struct";
+ case BinarySectionType::String:
+ return "string";
+ case BinarySectionType::Vector:
+ return "vector";
+ case BinarySectionType::Vector64:
+ return "vector64";
+ case BinarySectionType::Unknown:
+ return "unknown";
+ case BinarySectionType::Union:
+ return "union";
+ case BinarySectionType::Padding:
+ return "padding";
+ default:
+ return "todo";
}
}
@@ -51,7 +63,8 @@
type == BinaryRegionType::UOffset64;
}
-template<typename T> std::string ToString(T value) {
+template <typename T>
+std::string ToString(T value) {
if (std::is_floating_point<T>::value) {
std::stringstream ss;
ss << value;
@@ -61,8 +74,8 @@
}
}
-template<typename T>
-std::string ToValueString(const BinaryRegion ®ion, const uint8_t *binary) {
+template <typename T>
+std::string ToValueString(const BinaryRegion& region, const uint8_t* binary) {
std::string s;
s += "0x";
const T val = ReadScalar<T>(binary + region.offset);
@@ -76,16 +89,16 @@
return s;
}
-template<>
-std::string ToValueString<std::string>(const BinaryRegion ®ion,
- const uint8_t *binary) {
- return std::string(reinterpret_cast<const char *>(binary + region.offset),
+template <>
+std::string ToValueString<std::string>(const BinaryRegion& region,
+ const uint8_t* binary) {
+ return std::string(reinterpret_cast<const char*>(binary + region.offset),
static_cast<size_t>(region.array_length));
}
-static std::string ToValueString(const BinaryRegion ®ion,
- const uint8_t *binary,
- const OutputConfig &output_config) {
+static std::string ToValueString(const BinaryRegion& region,
+ const uint8_t* binary,
+ const OutputConfig& output_config) {
std::string s;
if (region.array_length) {
@@ -106,21 +119,31 @@
switch (region.type) {
case BinaryRegionType::Uint32:
return ToValueString<uint32_t>(region, binary);
- case BinaryRegionType::Int32: return ToValueString<int32_t>(region, binary);
+ case BinaryRegionType::Int32:
+ return ToValueString<int32_t>(region, binary);
case BinaryRegionType::Uint16:
return ToValueString<uint16_t>(region, binary);
- case BinaryRegionType::Int16: return ToValueString<int16_t>(region, binary);
- case BinaryRegionType::Bool: return ToValueString<bool>(region, binary);
- case BinaryRegionType::Uint8: return ToValueString<uint8_t>(region, binary);
- case BinaryRegionType::Char: return ToValueString<char>(region, binary);
+ case BinaryRegionType::Int16:
+ return ToValueString<int16_t>(region, binary);
+ case BinaryRegionType::Bool:
+ return ToValueString<bool>(region, binary);
+ case BinaryRegionType::Uint8:
+ return ToValueString<uint8_t>(region, binary);
+ case BinaryRegionType::Char:
+ return ToValueString<char>(region, binary);
case BinaryRegionType::Byte:
- case BinaryRegionType::Int8: return ToValueString<int8_t>(region, binary);
- case BinaryRegionType::Int64: return ToValueString<int64_t>(region, binary);
+ case BinaryRegionType::Int8:
+ return ToValueString<int8_t>(region, binary);
+ case BinaryRegionType::Int64:
+ return ToValueString<int64_t>(region, binary);
case BinaryRegionType::Uint64:
return ToValueString<uint64_t>(region, binary);
- case BinaryRegionType::Double: return ToValueString<double>(region, binary);
- case BinaryRegionType::Float: return ToValueString<float>(region, binary);
- case BinaryRegionType::UType: return ToValueString<uint8_t>(region, binary);
+ case BinaryRegionType::Double:
+ return ToValueString<double>(region, binary);
+ case BinaryRegionType::Float:
+ return ToValueString<float>(region, binary);
+ case BinaryRegionType::UType:
+ return ToValueString<uint8_t>(region, binary);
// Handle Offsets separately, incase they add additional details.
case BinaryRegionType::UOffset64:
@@ -136,7 +159,8 @@
s += ToValueString<uint16_t>(region, binary);
break;
- default: break;
+ default:
+ break;
}
// If this is an offset type, include the calculated offset location in the
// value.
@@ -156,26 +180,36 @@
std::string value;
};
-static std::string GenerateTypeString(const BinaryRegion ®ion) {
+static std::string GenerateTypeString(const BinaryRegion& region) {
return ToString(region.type) +
((region.array_length)
? "[" + std::to_string(region.array_length) + "]"
: "");
}
-static std::string GenerateComment(const BinaryRegionComment &comment,
- const BinarySection &) {
+static std::string GenerateComment(const BinaryRegionComment& comment,
+ const BinarySection&) {
std::string s;
switch (comment.type) {
- case BinaryRegionCommentType::Unknown: s = "unknown"; break;
- case BinaryRegionCommentType::SizePrefix: s = "size prefix"; break;
+ case BinaryRegionCommentType::Unknown:
+ s = "unknown";
+ break;
+ case BinaryRegionCommentType::SizePrefix:
+ s = "size prefix";
+ break;
case BinaryRegionCommentType::RootTableOffset:
s = "offset to root table `" + comment.name + "`";
break;
// TODO(dbaileychess): make this lowercase to follow the convention.
- case BinaryRegionCommentType::FileIdentifier: s = "File Identifier"; break;
- case BinaryRegionCommentType::Padding: s = "padding"; break;
- case BinaryRegionCommentType::VTableSize: s = "size of this vtable"; break;
+ case BinaryRegionCommentType::FileIdentifier:
+ s = "File Identifier";
+ break;
+ case BinaryRegionCommentType::Padding:
+ s = "padding";
+ break;
+ case BinaryRegionCommentType::VTableSize:
+ s = "size of this vtable";
+ break;
case BinaryRegionCommentType::VTableRefferingTableLength:
s = "size of referring table";
break;
@@ -192,7 +226,9 @@
case BinaryRegionCommentType::TableField:
s = "table field `" + comment.name;
break;
- case BinaryRegionCommentType::TableUnknownField: s = "unknown field"; break;
+ case BinaryRegionCommentType::TableUnknownField:
+ s = "unknown field";
+ break;
case BinaryRegionCommentType::TableOffsetField:
s = "offset to field `" + comment.name + "`";
break;
@@ -203,8 +239,12 @@
s = "array field `" + comment.name + "`[" +
std::to_string(comment.index) + "]";
break;
- case BinaryRegionCommentType::StringLength: s = "length of string"; break;
- case BinaryRegionCommentType::StringValue: s = "string literal"; break;
+ case BinaryRegionCommentType::StringLength:
+ s = "length of string";
+ break;
+ case BinaryRegionCommentType::StringValue:
+ s = "string literal";
+ break;
case BinaryRegionCommentType::StringTerminator:
s = "string terminator";
break;
@@ -224,13 +264,19 @@
s = "offset to union[" + std::to_string(comment.index) + "]";
break;
- default: break;
+ default:
+ break;
}
- if (!comment.default_value.empty()) { s += " " + comment.default_value; }
+ if (!comment.default_value.empty()) {
+ s += " " + comment.default_value;
+ }
switch (comment.status) {
- case BinaryRegionStatus::OK: break; // no-op
- case BinaryRegionStatus::WARN: s = "WARN: " + s; break;
+ case BinaryRegionStatus::OK:
+ break; // no-op
+ case BinaryRegionStatus::WARN:
+ s = "WARN: " + s;
+ break;
case BinaryRegionStatus::WARN_NO_REFERENCES:
s = "WARN: nothing refers to this section.";
break;
@@ -240,7 +286,9 @@
case BinaryRegionStatus::WARN_PADDING_LENGTH:
s = "WARN: padding is longer than expected.";
break;
- case BinaryRegionStatus::ERROR: s = "ERROR: " + s; break;
+ case BinaryRegionStatus::ERROR:
+ s = "ERROR: " + s;
+ break;
case BinaryRegionStatus::ERROR_OFFSET_OUT_OF_BINARY:
s = "ERROR: " + s + ". Invalid offset, points outside the binary.";
break;
@@ -268,11 +316,11 @@
return s;
}
-static void GenerateDocumentation(std::ostream &os, const BinaryRegion ®ion,
- const BinarySection §ion,
- const uint8_t *binary,
- DocContinuation &continuation,
- const OutputConfig &output_config) {
+static void GenerateDocumentation(std::ostream& os, const BinaryRegion& region,
+ const BinarySection& section,
+ const uint8_t* binary,
+ DocContinuation& continuation,
+ const OutputConfig& output_config) {
// Check if there is a doc continuation that should be prioritized.
if (continuation.value_start_column) {
os << std::string(continuation.value_start_column - 2, ' ');
@@ -321,9 +369,9 @@
os << GenerateComment(region.comment, section);
}
-static void GenerateRegion(std::ostream &os, const BinaryRegion ®ion,
- const BinarySection §ion, const uint8_t *binary,
- const OutputConfig &output_config) {
+static void GenerateRegion(std::ostream& os, const BinaryRegion& region,
+ const BinarySection& section, const uint8_t* binary,
+ const OutputConfig& output_config) {
bool doc_generated = false;
DocContinuation doc_continuation;
for (uint64_t i = 0; i < region.length; ++i) {
@@ -364,12 +412,14 @@
}
}
-static void GenerateSection(std::ostream &os, const BinarySection §ion,
- const uint8_t *binary,
- const OutputConfig &output_config) {
+static void GenerateSection(std::ostream& os, const BinarySection& section,
+ const uint8_t* binary,
+ const OutputConfig& output_config) {
os << std::endl;
os << ToString(section.type);
- if (!section.name.empty()) { os << " (" + section.name + ")"; }
+ if (!section.name.empty()) {
+ os << " (" + section.name + ")";
+ }
os << ":";
// As a space saving measure, skip generating every vector element, just put
@@ -394,7 +444,7 @@
return;
}
- for (const BinaryRegion ®ion : section.regions) {
+ for (const BinaryRegion& region : section.regions) {
GenerateRegion(os, region, section, binary, output_config);
}
os << std::endl;
@@ -402,8 +452,8 @@
} // namespace
bool AnnotatedBinaryTextGenerator::Generate(
- const std::string &filename, const std::string &schema_filename,
- const std::string &output_filename) {
+ const std::string& filename, const std::string& schema_filename,
+ const std::string& output_filename) {
OutputConfig output_config;
output_config.max_bytes_per_line = options_.max_bytes_per_line;
output_config.include_vector_contents = options_.include_vector_contents;
@@ -419,8 +469,8 @@
// Find the largest type string of all the regions in this file, so we can
// align the output nicely.
output_config.largest_type_string = 0;
- for (const auto §ion : annotations_) {
- for (const auto ®ion : section.second.regions) {
+ for (const auto& section : annotations_) {
+ for (const auto& region : section.second.regions) {
std::string s = GenerateTypeString(region);
if (s.size() > output_config.largest_type_string) {
output_config.largest_type_string = s.size();
@@ -456,7 +506,7 @@
ofs << "// Binary file: " << filename << std::endl;
// Generate each of the binary sections
- for (const auto §ion : annotations_) {
+ for (const auto& section : annotations_) {
GenerateSection(ofs, section.second, binary_, output_config);
}
diff --git a/src/bfbs_gen_lua.cpp b/src/bfbs_gen_lua.cpp
index 185e859..7e1e372 100644
--- a/src/bfbs_gen_lua.cpp
+++ b/src/bfbs_gen_lua.cpp
@@ -39,38 +39,38 @@
namespace r = ::reflection;
std::set<std::string> LuaKeywords() {
- return { "and", "break", "do", "else", "elseif", "end",
- "false", "for", "function", "goto", "if", "in",
- "local", "nil", "not", "or", "repeat", "return",
- "then", "true", "until", "while" };
+ return {"and", "break", "do", "else", "elseif", "end",
+ "false", "for", "function", "goto", "if", "in",
+ "local", "nil", "not", "or", "repeat", "return",
+ "then", "true", "until", "while"};
}
Namer::Config LuaDefaultConfig() {
- return { /*types=*/Case::kUpperCamel,
- /*constants=*/Case::kUnknown,
- /*methods=*/Case::kUpperCamel,
- /*functions=*/Case::kUpperCamel,
- /*fields=*/Case::kUpperCamel,
- /*variables=*/Case::kLowerCamel,
- /*variants=*/Case::kKeep,
- /*enum_variant_seperator=*/"",
- /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
- /*namespaces=*/Case::kKeep,
- /*namespace_seperator=*/"__",
- /*object_prefix=*/"",
- /*object_suffix=*/"",
- /*keyword_prefix=*/"",
- /*keyword_suffix=*/"_",
- /*filenames=*/Case::kKeep,
- /*directories=*/Case::kKeep,
- /*output_path=*/"",
- /*filename_suffix=*/"",
- /*filename_extension=*/".lua" };
+ return {/*types=*/Case::kUpperCamel,
+ /*constants=*/Case::kUnknown,
+ /*methods=*/Case::kUpperCamel,
+ /*functions=*/Case::kUpperCamel,
+ /*fields=*/Case::kUpperCamel,
+ /*variables=*/Case::kLowerCamel,
+ /*variants=*/Case::kKeep,
+ /*enum_variant_seperator=*/"",
+ /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
+ /*namespaces=*/Case::kKeep,
+ /*namespace_seperator=*/"__",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kKeep,
+ /*directories=*/Case::kKeep,
+ /*output_path=*/"",
+ /*filename_suffix=*/"",
+ /*filename_extension=*/".lua"};
}
class LuaBfbsGenerator : public BaseBfbsGenerator {
public:
- explicit LuaBfbsGenerator(const std::string &flatc_version)
+ explicit LuaBfbsGenerator(const std::string& flatc_version)
: BaseBfbsGenerator(),
keywords_(),
requires_(),
@@ -79,11 +79,13 @@
flatc_version_(flatc_version),
namer_(LuaDefaultConfig(), LuaKeywords()) {}
- Status GenerateFromSchema(const r::Schema *schema,
- const CodeGenOptions &options)
+ Status GenerateFromSchema(const r::Schema* schema,
+ const CodeGenOptions& options)
FLATBUFFERS_OVERRIDE {
options_ = options;
- if (!GenerateEnums(schema->enums())) { return ERROR; }
+ if (!GenerateEnums(schema->enums())) {
+ return ERROR;
+ }
if (!GenerateObjects(schema->objects(), schema->root_table())) {
return ERROR;
}
@@ -92,14 +94,14 @@
using BaseBfbsGenerator::GenerateCode;
- Status GenerateCode(const Parser &, const std::string &,
- const std::string &) override {
+ Status GenerateCode(const Parser&, const std::string&,
+ const std::string&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -107,16 +109,16 @@
return Status::NOT_IMPLEMENTED;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
@@ -138,8 +140,8 @@
protected:
bool GenerateEnums(
- const flatbuffers::Vector<flatbuffers::Offset<r::Enum>> *enums) {
- ForAllEnums(enums, [&](const r::Enum *enum_def) {
+ const flatbuffers::Vector<flatbuffers::Offset<r::Enum>>* enums) {
+ ForAllEnums(enums, [&](const r::Enum* enum_def) {
std::string code;
StartCodeBlock(enum_def);
@@ -151,7 +153,7 @@
GenerateDocumentation(enum_def->documentation(), "", code);
code += "local " + enum_name + " = {\n";
- ForAllEnumValues(enum_def, [&](const reflection::EnumVal *enum_val) {
+ ForAllEnumValues(enum_def, [&](const reflection::EnumVal* enum_val) {
GenerateDocumentation(enum_val->documentation(), " ", code);
code += " " + namer_.Variant(enum_val->name()->str()) + " = " +
NumToString(enum_val->value()) + ",\n";
@@ -165,9 +167,9 @@
}
bool GenerateObjects(
- const flatbuffers::Vector<flatbuffers::Offset<r::Object>> *objects,
- const r::Object *root_object) {
- ForAllObjects(objects, [&](const r::Object *object) {
+ const flatbuffers::Vector<flatbuffers::Offset<r::Object>>* objects,
+ const r::Object* root_object) {
+ ForAllObjects(objects, [&](const r::Object* object) {
std::string code;
StartCodeBlock(object);
@@ -215,9 +217,11 @@
code += "\n";
// Create all the field accessors.
- ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
+ ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
// Skip writing deprecated fields altogether.
- if (field->deprecated()) { return; }
+ if (field->deprecated()) {
+ return;
+ }
const std::string field_name = namer_.Field(*field);
const r::BaseType base_type = field->type()->base_type();
@@ -247,7 +251,9 @@
std::string getter =
GenerateGetter(field->type()) + "self.view.pos + o)";
- if (IsBool(base_type)) { getter = "(" + getter + " ~=0)"; }
+ if (IsBool(base_type)) {
+ getter = "(" + getter + " ~=0)";
+ }
code += " return " + getter + "\n";
code += " end\n";
code += " return " + DefaultValue(field) + "\n";
@@ -280,7 +286,7 @@
code += " " + offset_prefix;
code += " " + offset_prefix_2;
- const r::Object *field_object = GetObject(field->type());
+ const r::Object* field_object = GetObject(field->type());
if (!field_object) {
// TODO(derekbailey): this is an error condition. we
// should report it better.
@@ -333,7 +339,7 @@
} else {
// Vector of structs are inline, so we need to query the
// size of the struct.
- const reflection::Object *obj =
+ const reflection::Object* obj =
GetObjectByIndex(field->type()->index());
element_size = obj->bytesize();
}
@@ -408,8 +414,10 @@
code += "end\n";
code += "\n";
- ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
- if (field->deprecated()) { return; }
+ ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
+ if (field->deprecated()) {
+ return;
+ }
const std::string field_name = namer_.Field(*field);
const std::string variable_name = namer_.Variable(*field);
@@ -455,21 +463,21 @@
private:
void GenerateDocumentation(
- const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>
- *documentation,
- std::string indent, std::string &code) const {
+ const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>*
+ documentation,
+ std::string indent, std::string& code) const {
flatbuffers::ForAllDocumentation(
- documentation, [&](const flatbuffers::String *str) {
+ documentation, [&](const flatbuffers::String* str) {
code += indent + "--" + str->str() + "\n";
});
}
- std::string GenerateStructBuilderArgs(const r::Object *object,
+ std::string GenerateStructBuilderArgs(const r::Object* object,
std::string prefix = "") const {
std::string signature;
- ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
+ ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
if (IsStructOrTable(field->type()->base_type())) {
- const r::Object *field_object = GetObject(field->type());
+ const r::Object* field_object = GetObject(field->type());
signature += GenerateStructBuilderArgs(
field_object, prefix + namer_.Variable(*field) + "_");
} else {
@@ -479,7 +487,7 @@
return signature;
}
- std::string AppendStructBuilderBody(const r::Object *object,
+ std::string AppendStructBuilderBody(const r::Object* object,
std::string prefix = "") const {
std::string code;
code += " builder:Prep(" + NumToString(object->minalign()) + ", " +
@@ -487,13 +495,13 @@
// We need to reverse the order we iterate over, since we build the
// buffer backwards.
- ForAllFields(object, /*reverse=*/true, [&](const r::Field *field) {
+ ForAllFields(object, /*reverse=*/true, [&](const r::Field* field) {
const int32_t num_padding_bytes = field->padding();
if (num_padding_bytes) {
code += " builder:Pad(" + NumToString(num_padding_bytes) + ")\n";
}
if (IsStructOrTable(field->type()->base_type())) {
- const r::Object *field_object = GetObject(field->type());
+ const r::Object* field_object = GetObject(field->type());
code += AppendStructBuilderBody(field_object,
prefix + namer_.Variable(*field) + "_");
} else {
@@ -505,36 +513,49 @@
return code;
}
- std::string GenerateMethod(const r::Field *field) const {
+ std::string GenerateMethod(const r::Field* field) const {
const r::BaseType base_type = field->type()->base_type();
- if (IsScalar(base_type)) { return namer_.Type(GenerateType(base_type)); }
- if (IsStructOrTable(base_type)) { return "Struct"; }
+ if (IsScalar(base_type)) {
+ return namer_.Type(GenerateType(base_type));
+ }
+ if (IsStructOrTable(base_type)) {
+ return "Struct";
+ }
return "UOffsetTRelative";
}
- std::string GenerateGetter(const r::Type *type,
+ std::string GenerateGetter(const r::Type* type,
bool element_type = false) const {
switch (element_type ? type->element() : type->base_type()) {
- case r::String: return "self.view:String(";
- case r::Union: return "self.view:Union(";
- case r::Vector: return GenerateGetter(type, true);
+ case r::String:
+ return "self.view:String(";
+ case r::Union:
+ return "self.view:Union(";
+ case r::Vector:
+ return GenerateGetter(type, true);
default:
return "self.view:Get(flatbuffers.N." +
namer_.Type(GenerateType(type, element_type)) + ", ";
}
}
- std::string GenerateType(const r::Type *type,
+ std::string GenerateType(const r::Type* type,
bool element_type = false) const {
const r::BaseType base_type =
element_type ? type->element() : type->base_type();
- if (IsScalar(base_type)) { return GenerateType(base_type); }
+ if (IsScalar(base_type)) {
+ return GenerateType(base_type);
+ }
switch (base_type) {
- case r::String: return "string";
- case r::Vector: return GenerateGetter(type, true);
- case r::Obj: return namer_.Type(namer_.Denamespace(GetObject(type)));
+ case r::String:
+ return "string";
+ case r::Vector:
+ return GenerateGetter(type, true);
+ case r::Obj:
+ return namer_.Type(namer_.Denamespace(GetObject(type)));
- default: return "*flatbuffers.Table";
+ default:
+ return "*flatbuffers.Table";
}
}
@@ -542,23 +563,36 @@
// Need to override the default naming to match the Lua runtime libraries.
// TODO(derekbailey): make overloads in the runtime libraries to avoid this.
switch (base_type) {
- case r::None: return "uint8";
- case r::UType: return "uint8";
- case r::Byte: return "int8";
- case r::UByte: return "uint8";
- case r::Short: return "int16";
- case r::UShort: return "uint16";
- case r::Int: return "int32";
- case r::UInt: return "uint32";
- case r::Long: return "int64";
- case r::ULong: return "uint64";
- case r::Float: return "Float32";
- case r::Double: return "Float64";
- default: return r::EnumNameBaseType(base_type);
+ case r::None:
+ return "uint8";
+ case r::UType:
+ return "uint8";
+ case r::Byte:
+ return "int8";
+ case r::UByte:
+ return "uint8";
+ case r::Short:
+ return "int16";
+ case r::UShort:
+ return "uint16";
+ case r::Int:
+ return "int32";
+ case r::UInt:
+ return "uint32";
+ case r::Long:
+ return "int64";
+ case r::ULong:
+ return "uint64";
+ case r::Float:
+ return "Float32";
+ case r::Double:
+ return "Float64";
+ default:
+ return r::EnumNameBaseType(base_type);
}
}
- std::string DefaultValue(const r::Field *field) const {
+ std::string DefaultValue(const r::Field* field) const {
const r::BaseType base_type = field->type()->base_type();
if (IsFloatingPoint(base_type)) {
return NumToString(field->default_real());
@@ -566,24 +600,26 @@
if (IsBool(base_type)) {
return field->default_integer() ? "true" : "false";
}
- if (IsScalar(base_type)) { return NumToString((field->default_integer())); }
+ if (IsScalar(base_type)) {
+ return NumToString((field->default_integer()));
+ }
// represents offsets
return "0";
}
- void StartCodeBlock(const reflection::Enum *enum_def) {
+ void StartCodeBlock(const reflection::Enum* enum_def) {
current_enum_ = enum_def;
current_obj_ = nullptr;
requires_.clear();
}
- void StartCodeBlock(const reflection::Object *object) {
+ void StartCodeBlock(const reflection::Object* object) {
current_obj_ = object;
current_enum_ = nullptr;
requires_.clear();
}
- std::string RegisterRequires(const r::Field *field,
+ std::string RegisterRequires(const r::Field* field,
bool use_element = false) {
std::string type_name;
@@ -591,12 +627,16 @@
use_element ? field->type()->element() : field->type()->base_type();
if (IsStructOrTable(type)) {
- const r::Object *object = GetObjectByIndex(field->type()->index());
- if (object == current_obj_) { return namer_.Denamespace(object); }
+ const r::Object* object = GetObjectByIndex(field->type()->index());
+ if (object == current_obj_) {
+ return namer_.Denamespace(object);
+ }
type_name = object->name()->str();
} else {
- const r::Enum *enum_def = GetEnumByIndex(field->type()->index());
- if (enum_def == current_enum_) { return namer_.Denamespace(enum_def); }
+ const r::Enum* enum_def = GetEnumByIndex(field->type()->index());
+ if (enum_def == current_enum_) {
+ return namer_.Denamespace(enum_def);
+ }
type_name = enum_def->name()->str();
}
@@ -609,15 +649,15 @@
return RegisterRequires(name, type_name);
}
- std::string RegisterRequires(const std::string &local_name,
- const std::string &requires_name) {
+ std::string RegisterRequires(const std::string& local_name,
+ const std::string& requires_name) {
requires_[local_name] = requires_name;
return local_name;
}
- void EmitCodeBlock(const std::string &code_block, const std::string &name,
- const std::string &ns,
- const std::string &declaring_file) const {
+ void EmitCodeBlock(const std::string& code_block, const std::string& name,
+ const std::string& ns,
+ const std::string& declaring_file) const {
const std::string root_type = schema_->root_table()->name()->str();
const std::string root_file =
schema_->root_table()->declaration_file()->str();
@@ -665,15 +705,15 @@
std::map<std::string, std::string> requires_;
CodeGenOptions options_;
- const r::Object *current_obj_;
- const r::Enum *current_enum_;
+ const r::Object* current_obj_;
+ const r::Enum* current_enum_;
const std::string flatc_version_;
const BfbsNamer namer_;
};
} // namespace
std::unique_ptr<CodeGenerator> NewLuaBfbsGenerator(
- const std::string &flatc_version) {
+ const std::string& flatc_version) {
return std::unique_ptr<LuaBfbsGenerator>(new LuaBfbsGenerator(flatc_version));
}
diff --git a/src/bfbs_gen_nim.cpp b/src/bfbs_gen_nim.cpp
index 25da044..ec72930 100644
--- a/src/bfbs_gen_nim.cpp
+++ b/src/bfbs_gen_nim.cpp
@@ -40,53 +40,52 @@
std::set<std::string> NimKeywords() {
return {
- "addr", "and", "as", "asm", "bind", "block",
- "break", "case", "cast", "concept", "const", "continue",
- "converter", "defer", "discard", "distinct", "div", "do",
- "elif", "else", "end", "enum", "except", "export",
- "finally", "for", "from", "func", "if", "import",
- "in", "include", "interface", "is", "isnot", "iterator",
- "let", "macro", "method", "mixin", "mod", "nil",
- "not", "notin", "object", "of", "or", "out",
- "proc", "ptr", "raise", "ref", "return", "shl",
- "shr", "static", "template", "try", "tuple", "type",
- "using", "var", "when", "while", "xor", "yield",
+ "addr", "and", "as", "asm", "bind", "block",
+ "break", "case", "cast", "concept", "const", "continue",
+ "converter", "defer", "discard", "distinct", "div", "do",
+ "elif", "else", "end", "enum", "except", "export",
+ "finally", "for", "from", "func", "if", "import",
+ "in", "include", "interface", "is", "isnot", "iterator",
+ "let", "macro", "method", "mixin", "mod", "nil",
+ "not", "notin", "object", "of", "or", "out",
+ "proc", "ptr", "raise", "ref", "return", "shl",
+ "shr", "static", "template", "try", "tuple", "type",
+ "using", "var", "when", "while", "xor", "yield",
};
}
Namer::Config NimDefaultConfig() {
- return { /*types=*/Case::kUpperCamel,
- /*constants=*/Case::kUpperCamel,
- /*methods=*/Case::kLowerCamel,
- /*functions=*/Case::kUpperCamel,
- /*fields=*/Case::kLowerCamel,
- /*variable=*/Case::kLowerCamel,
- /*variants=*/Case::kUpperCamel,
- /*enum_variant_seperator=*/".",
- /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
- /*namespaces=*/Case::kKeep,
- /*namespace_seperator=*/"/",
- /*object_prefix=*/"",
- /*object_suffix=*/"T",
- /*keyword_prefix=*/"",
- /*keyword_suffix=*/"_",
- /*filenames=*/Case::kKeep,
- /*directories=*/Case::kKeep,
- /*output_path=*/"",
- /*filename_suffix=*/"",
- /*filename_extension=*/".nim" };
+ return {/*types=*/Case::kUpperCamel,
+ /*constants=*/Case::kUpperCamel,
+ /*methods=*/Case::kLowerCamel,
+ /*functions=*/Case::kUpperCamel,
+ /*fields=*/Case::kLowerCamel,
+ /*variable=*/Case::kLowerCamel,
+ /*variants=*/Case::kUpperCamel,
+ /*enum_variant_seperator=*/".",
+ /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
+ /*namespaces=*/Case::kKeep,
+ /*namespace_seperator=*/"/",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kKeep,
+ /*directories=*/Case::kKeep,
+ /*output_path=*/"",
+ /*filename_suffix=*/"",
+ /*filename_extension=*/".nim"};
}
const std::string Export = "*";
const std::set<std::string> builtin_types = {
- "uint8", "uint8", "bool", "int8", "uint8", "int16",
- "uint16", "int32", "uint32", "int64", "uint64", "float32",
- "float64", "string", "int", "uint", "uoffset", "Builder"
-};
+ "uint8", "uint8", "bool", "int8", "uint8", "int16",
+ "uint16", "int32", "uint32", "int64", "uint64", "float32",
+ "float64", "string", "int", "uint", "uoffset", "Builder"};
class NimBfbsGenerator : public BaseBfbsGenerator {
public:
- explicit NimBfbsGenerator(const std::string &flatc_version)
+ explicit NimBfbsGenerator(const std::string& flatc_version)
: BaseBfbsGenerator(),
keywords_(),
imports_(),
@@ -95,15 +94,15 @@
flatc_version_(flatc_version),
namer_(NimDefaultConfig(), NimKeywords()) {}
- Status GenerateFromSchema(const r::Schema *schema,
- const CodeGenOptions &options)
+ Status GenerateFromSchema(const r::Schema* schema,
+ const CodeGenOptions& options)
FLATBUFFERS_OVERRIDE {
options_ = options;
- ForAllEnums(schema->enums(), [&](const r::Enum *enum_def) {
+ ForAllEnums(schema->enums(), [&](const r::Enum* enum_def) {
StartCodeBlock(enum_def);
GenerateEnum(enum_def);
});
- ForAllObjects(schema->objects(), [&](const r::Object *object) {
+ ForAllObjects(schema->objects(), [&](const r::Object* object) {
StartCodeBlock(object);
GenerateObject(object);
});
@@ -112,17 +111,17 @@
using BaseBfbsGenerator::GenerateCode;
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -130,16 +129,16 @@
return NOT_IMPLEMENTED;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return NOT_IMPLEMENTED;
@@ -161,7 +160,7 @@
}
protected:
- void GenerateEnum(const r::Enum *enum_def) {
+ void GenerateEnum(const r::Enum* enum_def) {
std::string code;
std::string ns;
@@ -172,7 +171,7 @@
GenerateDocumentation(enum_def->documentation(), "", code);
code += "type " + enum_name + Export + "{.pure.} = enum\n";
- ForAllEnumValues(enum_def, [&](const reflection::EnumVal *enum_val) {
+ ForAllEnumValues(enum_def, [&](const reflection::EnumVal* enum_val) {
GenerateDocumentation(enum_val->documentation(), " ", code);
code += " " + namer_.Variant(enum_val->name()->str()) + " = " +
NumToString(enum_val->value()) + "." + enum_type + ",\n";
@@ -181,7 +180,7 @@
EmitCodeBlock(code, enum_name, ns, enum_def->declaration_file()->str());
}
- void GenerateObject(const r::Object *object) {
+ void GenerateObject(const r::Object* object) {
// Register the main flatbuffers module.
RegisterImports("flatbuffers", "");
std::string code;
@@ -193,9 +192,11 @@
code += "type " + object_name + "* = object of FlatObj\n";
// Create all the field accessors.
- ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
+ ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
// Skip writing deprecated fields altogether.
- if (field->deprecated()) { return; }
+ if (field->deprecated()) {
+ return;
+ }
const std::string field_name = namer_.Field(*field);
const r::BaseType base_type = field->type()->base_type();
@@ -256,7 +257,9 @@
}
}
code += getter_signature + getter_code;
- if (IsScalar(base_type)) { code += setter_signature + setter_code; }
+ if (IsScalar(base_type)) {
+ code += setter_signature + setter_code;
+ }
} else if (base_type == r::Array || base_type == r::Vector) {
const r::BaseType vector_base_type = field->type()->element();
uint32_t element_size = field->type()->element_size();
@@ -309,8 +312,10 @@
code += " builder.StartObject(" + NumToString(object->fields()->size()) +
")\n";
- ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
- if (field->deprecated()) { return; }
+ ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
+ if (field->deprecated()) {
+ return;
+ }
const std::string field_name = namer_.Field(*field);
const std::string variable_name = namer_.Variable(*field);
@@ -348,21 +353,21 @@
private:
void GenerateDocumentation(
- const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>
- *documentation,
- std::string indent, std::string &code) const {
+ const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>*
+ documentation,
+ std::string indent, std::string& code) const {
flatbuffers::ForAllDocumentation(
- documentation, [&](const flatbuffers::String *str) {
+ documentation, [&](const flatbuffers::String* str) {
code += indent + "# " + str->str() + "\n";
});
}
- std::string GenerateStructBuilderArgs(const r::Object *object,
+ std::string GenerateStructBuilderArgs(const r::Object* object,
std::string prefix = "") const {
std::string signature;
- ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
+ ForAllFields(object, /*reverse=*/false, [&](const r::Field* field) {
if (IsStructOrTable(field->type()->base_type())) {
- const r::Object *field_object = GetObject(field->type());
+ const r::Object* field_object = GetObject(field->type());
signature += GenerateStructBuilderArgs(
field_object, prefix + namer_.Variable(*field) + "_");
} else {
@@ -373,7 +378,7 @@
return signature;
}
- std::string AppendStructBuilderBody(const r::Object *object,
+ std::string AppendStructBuilderBody(const r::Object* object,
std::string prefix = "") const {
std::string code;
code += " self.Prep(" + NumToString(object->minalign()) + ", " +
@@ -381,13 +386,13 @@
// We need to reverse the order we iterate over, since we build the
// buffer backwards.
- ForAllFields(object, /*reverse=*/true, [&](const r::Field *field) {
+ ForAllFields(object, /*reverse=*/true, [&](const r::Field* field) {
const int32_t num_padding_bytes = field->padding();
if (num_padding_bytes) {
code += " self.Pad(" + NumToString(num_padding_bytes) + ")\n";
}
if (IsStructOrTable(field->type()->base_type())) {
- const r::Object *field_object = GetObject(field->type());
+ const r::Object* field_object = GetObject(field->type());
code += AppendStructBuilderBody(field_object,
prefix + namer_.Variable(*field) + "_");
} else {
@@ -398,28 +403,35 @@
return code;
}
- std::string GenerateMethod(const r::Field *field) const {
+ std::string GenerateMethod(const r::Field* field) const {
const r::BaseType base_type = field->type()->base_type();
- if (IsStructOrTable(base_type)) { return "Struct"; }
+ if (IsStructOrTable(base_type)) {
+ return "Struct";
+ }
return "";
}
- std::string GenerateGetter(const r::Type *type, const std::string &offsetval,
+ std::string GenerateGetter(const r::Type* type, const std::string& offsetval,
bool element_type = false) const {
const r::BaseType base_type =
element_type ? type->element() : type->base_type();
std::string offset = offsetval;
- if (!element_type) { offset = "self.tab.Pos + " + offset; }
+ if (!element_type) {
+ offset = "self.tab.Pos + " + offset;
+ }
switch (base_type) {
- case r::String: return "self.tab.String(" + offset + ")";
- case r::Union: return "self.tab.Union(" + offsetval + ")";
+ case r::String:
+ return "self.tab.String(" + offset + ")";
+ case r::Union:
+ return "self.tab.Union(" + offsetval + ")";
case r::Obj: {
return GenerateType(type, element_type) +
"(tab: Vtable(Bytes: self.tab.Bytes, Pos: " + offset + "))";
}
- case r::Vector: return GenerateGetter(type, offsetval, true);
+ case r::Vector:
+ return GenerateGetter(type, offsetval, true);
default:
- const r::Enum *type_enum = GetEnum(type, element_type);
+ const r::Enum* type_enum = GetEnum(type, element_type);
if (type_enum != nullptr) {
return GenerateType(type, element_type) + "(" + "Get[" +
GenerateType(base_type) + "](self.tab, " + offset + ")" + ")";
@@ -430,46 +442,52 @@
}
}
- std::string Denamespace(const std::string &s, std::string &importns,
- std::string &ns) const {
- if (builtin_types.find(s) != builtin_types.end()) { return s; }
+ std::string Denamespace(const std::string& s, std::string& importns,
+ std::string& ns) const {
+ if (builtin_types.find(s) != builtin_types.end()) {
+ return s;
+ }
std::string type = namer_.Type(namer_.Denamespace(s, ns));
importns = ns.empty() ? type : ns + "." + type;
std::replace(importns.begin(), importns.end(), '.', '_');
return type;
}
- std::string Denamespace(const std::string &s, std::string &importns) const {
+ std::string Denamespace(const std::string& s, std::string& importns) const {
std::string ns;
return Denamespace(s, importns, ns);
}
- std::string Denamespace(const std::string &s) const {
+ std::string Denamespace(const std::string& s) const {
std::string importns;
return Denamespace(s, importns);
}
- std::string GenerateType(const r::Type *type, bool element_type = false,
+ std::string GenerateType(const r::Type* type, bool element_type = false,
bool enum_inner = false) const {
const r::BaseType base_type =
element_type ? type->element() : type->base_type();
if (IsScalar(base_type) && !enum_inner) {
- const r::Enum *type_enum = GetEnum(type, element_type);
+ const r::Enum* type_enum = GetEnum(type, element_type);
if (type_enum != nullptr) {
std::string importns;
std::string type_name = Denamespace(type_enum->name()->str(), importns);
return importns + "." + type_name;
}
}
- if (IsScalar(base_type)) { return Denamespace(GenerateType(base_type)); }
+ if (IsScalar(base_type)) {
+ return Denamespace(GenerateType(base_type));
+ }
switch (base_type) {
- case r::String: return "string";
+ case r::String:
+ return "string";
case r::Vector: {
return "seq[" + GenerateType(type, true) + "]";
}
- case r::Union: return "Vtable";
+ case r::Union:
+ return "Vtable";
case r::Obj: {
- const r::Object *type_obj = GetObject(type, element_type);
+ const r::Object* type_obj = GetObject(type, element_type);
std::string importns;
std::string type_name = Denamespace(type_obj->name()->str(), importns);
if (type_obj == current_obj_) {
@@ -478,11 +496,12 @@
return importns + "." + type_name;
}
}
- default: return "uoffset";
+ default:
+ return "uoffset";
}
}
- std::string GenerateTypeBasic(const r::Type *type,
+ std::string GenerateTypeBasic(const r::Type* type,
bool element_type = false) const {
const r::BaseType base_type =
element_type ? type->element() : type->base_type();
@@ -495,25 +514,40 @@
std::string GenerateType(const r::BaseType base_type) const {
switch (base_type) {
- case r::None: return "uint8";
- case r::UType: return "uint8";
- case r::Bool: return "bool";
- case r::Byte: return "int8";
- case r::UByte: return "uint8";
- case r::Short: return "int16";
- case r::UShort: return "uint16";
- case r::Int: return "int32";
- case r::UInt: return "uint32";
- case r::Long: return "int64";
- case r::ULong: return "uint64";
- case r::Float: return "float32";
- case r::Double: return "float64";
- case r::String: return "string";
- default: return r::EnumNameBaseType(base_type);
+ case r::None:
+ return "uint8";
+ case r::UType:
+ return "uint8";
+ case r::Bool:
+ return "bool";
+ case r::Byte:
+ return "int8";
+ case r::UByte:
+ return "uint8";
+ case r::Short:
+ return "int16";
+ case r::UShort:
+ return "uint16";
+ case r::Int:
+ return "int32";
+ case r::UInt:
+ return "uint32";
+ case r::Long:
+ return "int64";
+ case r::ULong:
+ return "uint64";
+ case r::Float:
+ return "float32";
+ case r::Double:
+ return "float64";
+ case r::String:
+ return "string";
+ default:
+ return r::EnumNameBaseType(base_type);
}
}
- std::string DefaultValue(const r::Field *field) const {
+ std::string DefaultValue(const r::Field* field) const {
const r::BaseType base_type = field->type()->base_type();
if (IsFloatingPoint(base_type)) {
if (field->default_real() != field->default_real()) {
@@ -531,24 +565,26 @@
return field->default_integer() ? "true" : "false";
}
if (IsScalar(base_type)) {
- const r::Enum *type_enum = GetEnum(field->type());
+ const r::Enum* type_enum = GetEnum(field->type());
if (type_enum != nullptr) {
return "type(result)(" + NumToString((field->default_integer())) + ")";
}
return NumToString((field->default_integer()));
}
- if (base_type == r::String) { return "\"\""; }
+ if (base_type == r::String) {
+ return "\"\"";
+ }
// represents offsets
return "0";
}
- void StartCodeBlock(const reflection::Enum *enum_def) {
+ void StartCodeBlock(const reflection::Enum* enum_def) {
current_enum_ = enum_def;
current_obj_ = nullptr;
imports_.clear();
}
- void StartCodeBlock(const reflection::Object *object) {
+ void StartCodeBlock(const reflection::Object* object) {
current_enum_ = nullptr;
current_obj_ = object;
imports_.clear();
@@ -572,8 +608,8 @@
return result;
}
- std::string GetRelativePathFromNamespace(const std::string &relative_to,
- const std::string &str2) {
+ std::string GetRelativePathFromNamespace(const std::string& relative_to,
+ const std::string& str2) {
std::vector<std::string> relative_to_vec = StringSplit(relative_to, ".");
std::vector<std::string> str2_vec = StringSplit(str2, ".");
while (relative_to_vec.size() > 0 && str2_vec.size() > 0) {
@@ -592,12 +628,14 @@
std::string new_path;
for (size_t i = 0; i < str2_vec.size(); ++i) {
new_path += str2_vec[i];
- if (i != str2_vec.size() - 1) { new_path += "/"; }
+ if (i != str2_vec.size() - 1) {
+ new_path += "/";
+ }
}
return new_path;
}
- void RegisterImports(const r::Object *object, const r::Field *field,
+ void RegisterImports(const r::Object* object, const r::Field* field,
bool use_element = false) {
std::string importns;
std::string type_name;
@@ -606,14 +644,18 @@
use_element ? field->type()->element() : field->type()->base_type();
if (IsStructOrTable(type)) {
- const r::Object *object_def = GetObjectByIndex(field->type()->index());
- if (object_def == current_obj_) { return; }
+ const r::Object* object_def = GetObjectByIndex(field->type()->index());
+ if (object_def == current_obj_) {
+ return;
+ }
std::string ns;
type_name = Denamespace(object_def->name()->str(), importns, ns);
type_name = ns.empty() ? type_name : ns + "." + type_name;
} else {
- const r::Enum *enum_def = GetEnumByIndex(field->type()->index());
- if (enum_def == current_enum_) { return; }
+ const r::Enum* enum_def = GetEnumByIndex(field->type()->index());
+ if (enum_def == current_enum_) {
+ return;
+ }
std::string ns;
type_name = Denamespace(enum_def->name()->str(), importns, ns);
type_name = ns.empty() ? type_name : ns + "." + type_name;
@@ -625,13 +667,13 @@
RegisterImports(import_path, importns);
}
- void RegisterImports(const std::string &local_name,
- const std::string &imports_name) {
+ void RegisterImports(const std::string& local_name,
+ const std::string& imports_name) {
imports_[local_name] = imports_name;
}
- void EmitCodeBlock(const std::string &code_block, const std::string &name,
- const std::string &ns, const std::string &declaring_file) {
+ void EmitCodeBlock(const std::string& code_block, const std::string& name,
+ const std::string& ns, const std::string& declaring_file) {
const std::string full_qualified_name = ns.empty() ? name : ns + "." + name;
std::string code = "#[ " + full_qualified_name + "\n";
@@ -683,15 +725,15 @@
std::map<std::string, std::string> imports_;
CodeGenOptions options_;
- const r::Object *current_obj_;
- const r::Enum *current_enum_;
+ const r::Object* current_obj_;
+ const r::Enum* current_enum_;
const std::string flatc_version_;
const BfbsNamer namer_;
};
} // namespace
std::unique_ptr<CodeGenerator> NewNimBfbsGenerator(
- const std::string &flatc_version) {
+ const std::string& flatc_version) {
return std::unique_ptr<NimBfbsGenerator>(new NimBfbsGenerator(flatc_version));
}
diff --git a/src/binary_annotator.cpp b/src/binary_annotator.cpp
index 6612b10..1e1668c 100644
--- a/src/binary_annotator.cpp
+++ b/src/binary_annotator.cpp
@@ -15,11 +15,11 @@
namespace flatbuffers {
namespace {
-static bool BinaryRegionSort(const BinaryRegion &a, const BinaryRegion &b) {
+static bool BinaryRegionSort(const BinaryRegion& a, const BinaryRegion& b) {
return a.offset < b.offset;
}
-static void SetError(BinaryRegionComment &comment, BinaryRegionStatus status,
+static void SetError(BinaryRegionComment& comment, BinaryRegionStatus status,
std::string message = "") {
comment.status = status;
comment.status_message = message;
@@ -40,7 +40,7 @@
return region;
}
-static BinarySection MakeBinarySection(const std::string &name,
+static BinarySection MakeBinarySection(const std::string& name,
const BinarySectionType type,
std::vector<BinaryRegion> regions) {
BinarySection section;
@@ -50,33 +50,37 @@
return section;
}
-static BinarySection MakeSingleRegionBinarySection(const std::string &name,
+static BinarySection MakeSingleRegionBinarySection(const std::string& name,
const BinarySectionType type,
- const BinaryRegion ®ion) {
+ const BinaryRegion& region) {
std::vector<BinaryRegion> regions;
regions.push_back(region);
return MakeBinarySection(name, type, std::move(regions));
}
static bool IsNonZeroRegion(const uint64_t offset, const uint64_t length,
- const uint8_t *const binary) {
+ const uint8_t* const binary) {
for (uint64_t i = offset; i < offset + length; ++i) {
- if (binary[i] != 0) { return true; }
+ if (binary[i] != 0) {
+ return true;
+ }
}
return false;
}
static bool IsPrintableRegion(const uint64_t offset, const uint64_t length,
- const uint8_t *const binary) {
+ const uint8_t* const binary) {
for (uint64_t i = offset; i < offset + length; ++i) {
- if (!isprint(binary[i])) { return false; }
+ if (!isprint(binary[i])) {
+ return false;
+ }
}
return true;
}
static BinarySection GenerateMissingSection(const uint64_t offset,
const uint64_t length,
- const uint8_t *const binary) {
+ const uint8_t* const binary) {
std::vector<BinaryRegion> regions;
// Check if the region is all zeros or not, as that can tell us if it is
@@ -130,7 +134,9 @@
}
// The binary is too short to read as a flatbuffers.
- if (binary_length_ < FLATBUFFERS_MIN_BUFFER_SIZE) { return {}; }
+ if (binary_length_ < FLATBUFFERS_MIN_BUFFER_SIZE) {
+ return {};
+ }
// Make sure we start with a clean slate.
vtables_.clear();
@@ -234,20 +240,24 @@
return root_table_loc;
}
-BinaryAnnotator::VTable *BinaryAnnotator::GetOrBuildVTable(
- const uint64_t vtable_offset, const reflection::Object *const table,
+BinaryAnnotator::VTable* BinaryAnnotator::GetOrBuildVTable(
+ const uint64_t vtable_offset, const reflection::Object* const table,
const uint64_t offset_of_referring_table) {
// Get a list of vtables (if any) already defined at this offset.
- std::list<VTable> &vtables = vtables_[vtable_offset];
+ std::list<VTable>& vtables = vtables_[vtable_offset];
// See if this vtable for the table type has been generated before.
- for (VTable &vtable : vtables) {
- if (vtable.referring_table == table) { return &vtable; }
+ for (VTable& vtable : vtables) {
+ if (vtable.referring_table == table) {
+ return &vtable;
+ }
}
// If we are trying to make a new vtable and it is already encompassed by
// another binary section, something is corrupted.
- if (vtables.empty() && ContainsSection(vtable_offset)) { return nullptr; }
+ if (vtables.empty() && ContainsSection(vtable_offset)) {
+ return nullptr;
+ }
const std::string referring_table_name = table->name()->str();
@@ -352,7 +362,7 @@
uint16_t fields_processed = 0;
// Loop over all the fields.
- ForAllFields(table, /*reverse=*/false, [&](const reflection::Field *field) {
+ ForAllFields(table, /*reverse=*/false, [&](const reflection::Field* field) {
const uint64_t field_offset = offset_start + field->id() * sizeof(uint16_t);
if (field_offset >= vtable_offset + vtable_size) {
@@ -497,8 +507,10 @@
void BinaryAnnotator::BuildTable(const uint64_t table_offset,
const BinarySectionType type,
- const reflection::Object *const table) {
- if (ContainsSection(table_offset)) { return; }
+ const reflection::Object* const table) {
+ if (ContainsSection(table_offset)) {
+ return;
+ }
BinaryRegionComment vtable_offset_comment;
vtable_offset_comment.type = BinaryRegionCommentType::TableVTableOffset;
@@ -548,7 +560,7 @@
// Parse the vtable first so we know what the rest of the fields in the table
// are.
- const VTable *const vtable =
+ const VTable* const vtable =
GetOrBuildVTable(vtable_offset, table, table_offset);
if (vtable == nullptr) {
@@ -571,18 +583,18 @@
// not by their IDs. So copy them over to another vector that we can sort on
// the offset_from_table property.
std::vector<VTable::Entry> fields;
- for (const auto &vtable_field : vtable->fields) {
+ for (const auto& vtable_field : vtable->fields) {
fields.push_back(vtable_field.second);
}
std::stable_sort(fields.begin(), fields.end(),
- [](const VTable::Entry &a, const VTable::Entry &b) {
+ [](const VTable::Entry& a, const VTable::Entry& b) {
return a.offset_from_table < b.offset_from_table;
});
// Iterate over all the fields by order of their offset.
for (size_t i = 0; i < fields.size(); ++i) {
- const reflection::Field *field = fields[i].field;
+ const reflection::Field* field = fields[i].field;
const uint16_t offset_from_table = fields[i].offset_from_table;
if (offset_from_table == 0) {
@@ -610,7 +622,9 @@
: table_end_offset) -
field_offset;
- if (unknown_field_length == 0) { continue; }
+ if (unknown_field_length == 0) {
+ continue;
+ }
std::string hint;
@@ -741,7 +755,7 @@
switch (field->type()->base_type()) {
case reflection::BaseType::Obj: {
- const reflection::Object *next_object =
+ const reflection::Object* next_object =
schema_->objects()->Get(field->type()->index());
if (next_object->is_struct()) {
@@ -830,7 +844,8 @@
} break;
- default: break;
+ default:
+ break;
}
}
@@ -855,14 +870,16 @@
}
uint64_t BinaryAnnotator::BuildStruct(const uint64_t struct_offset,
- std::vector<BinaryRegion> ®ions,
+ std::vector<BinaryRegion>& regions,
const std::string referring_field_name,
- const reflection::Object *const object) {
- if (!object->is_struct()) { return struct_offset; }
+ const reflection::Object* const object) {
+ if (!object->is_struct()) {
+ return struct_offset;
+ }
uint64_t offset = struct_offset;
// Loop over all the fields in increasing order
- ForAllFields(object, /*reverse=*/false, [&](const reflection::Field *field) {
+ ForAllFields(object, /*reverse=*/false, [&](const reflection::Field* field) {
if (IsScalar(field->type()->base_type())) {
// Structure Field value
const uint64_t type_size = GetTypeSize(field->type()->base_type());
@@ -971,11 +988,13 @@
}
void BinaryAnnotator::BuildString(const uint64_t string_offset,
- const reflection::Object *const table,
- const reflection::Field *const field) {
+ const reflection::Object* const table,
+ const reflection::Field* const field) {
// Check if we have already generated this string section, and this is a
// shared string instance.
- if (ContainsSection(string_offset)) { return; }
+ if (ContainsSection(string_offset)) {
+ return;
+ }
std::vector<BinaryRegion> regions;
const auto string_length = ReadScalar<uint32_t>(string_offset);
@@ -1034,10 +1053,12 @@
}
void BinaryAnnotator::BuildVector(
- const uint64_t vector_offset, const reflection::Object *const table,
- const reflection::Field *const field, const uint64_t parent_table_offset,
+ const uint64_t vector_offset, const reflection::Object* const table,
+ const reflection::Field* const field, const uint64_t parent_table_offset,
const std::map<uint16_t, VTable::Entry> vtable_fields) {
- if (ContainsSection(vector_offset)) { return; }
+ if (ContainsSection(vector_offset)) {
+ return;
+ }
BinaryRegionComment vector_length_comment;
vector_length_comment.type = BinaryRegionCommentType::VectorLength;
@@ -1052,13 +1073,17 @@
if (is_64_bit_vector) {
auto v = ReadScalar<uint64_t>(vector_offset);
- if (v.has_value()) { vector_length = v.value(); }
+ if (v.has_value()) {
+ vector_length = v.value();
+ }
vector_length_size_type = sizeof(uint64_t);
region_type = BinaryRegionType::Uint64;
section_type = BinarySectionType::Vector64;
} else {
auto v = ReadScalar<uint32_t>(vector_offset);
- if (v.has_value()) { vector_length = v.value(); }
+ if (v.has_value()) {
+ vector_length = v.value();
+ }
vector_length_size_type = sizeof(uint32_t);
region_type = BinaryRegionType::Uint32;
section_type = BinarySectionType::Vector;
@@ -1108,7 +1133,7 @@
switch (field->type()->element()) {
case reflection::BaseType::Obj: {
- const reflection::Object *object =
+ const reflection::Object* object =
schema_->objects()->Get(field->type()->index());
if (object->is_struct()) {
@@ -1117,7 +1142,9 @@
// Structs are inline to the vector.
const uint64_t next_offset =
BuildStruct(offset, regions, "[" + NumToString(i) + "]", object);
- if (next_offset == offset) { break; }
+ if (next_offset == offset) {
+ break;
+ }
offset = next_offset;
}
} else {
@@ -1382,18 +1409,20 @@
std::string BinaryAnnotator::BuildUnion(const uint64_t union_offset,
const uint8_t realized_type,
- const reflection::Field *const field) {
- const reflection::Enum *next_enum =
+ const reflection::Field* const field) {
+ const reflection::Enum* next_enum =
schema_->enums()->Get(field->type()->index());
- const reflection::EnumVal *enum_val = next_enum->values()->Get(realized_type);
+ const reflection::EnumVal* enum_val = next_enum->values()->Get(realized_type);
- if (ContainsSection(union_offset)) { return enum_val->name()->c_str(); }
+ if (ContainsSection(union_offset)) {
+ return enum_val->name()->c_str();
+ }
- const reflection::Type *union_type = enum_val->union_type();
+ const reflection::Type* union_type = enum_val->union_type();
if (union_type->base_type() == reflection::BaseType::Obj) {
- const reflection::Object *object =
+ const reflection::Object* object =
schema_->objects()->Get(union_type->index());
if (object->is_struct()) {
@@ -1418,8 +1447,8 @@
void BinaryAnnotator::FixMissingRegions() {
std::vector<BinaryRegion> regions_to_insert;
- for (auto ¤t_section : sections_) {
- BinarySection §ion = current_section.second;
+ for (auto& current_section : sections_) {
+ BinarySection& section = current_section.second;
if (section.regions.empty()) {
// TODO(dbaileychess): is this possible?
continue;
@@ -1427,7 +1456,7 @@
uint64_t offset = section.regions[0].offset + section.regions[0].length;
for (size_t i = 1; i < section.regions.size(); ++i) {
- BinaryRegion ®ion = section.regions[i];
+ BinaryRegion& region = section.regions[i];
const uint64_t next_offset = region.offset;
if (!IsValidOffset(next_offset)) {
@@ -1470,8 +1499,8 @@
std::vector<BinarySection> sections_to_insert;
- for (auto ¤t_section : sections_) {
- BinarySection §ion = current_section.second;
+ for (auto& current_section : sections_) {
+ BinarySection& section = current_section.second;
const uint64_t section_start_offset = current_section.first;
const uint64_t section_end_offset =
section.regions.back().offset + section.regions.back().length;
@@ -1494,7 +1523,7 @@
GenerateMissingSection(offset - 1, pad_bytes, binary_));
}
- for (const BinarySection §ion_to_insert : sections_to_insert) {
+ for (const BinarySection& section_to_insert : sections_to_insert) {
AddSection(section_to_insert.regions[0].offset, section_to_insert);
}
}
@@ -1502,11 +1531,15 @@
bool BinaryAnnotator::ContainsSection(const uint64_t offset) {
auto it = sections_.lower_bound(offset);
// If the section is found, check that it is exactly equal its offset.
- if (it != sections_.end() && it->first == offset) { return true; }
+ if (it != sections_.end() && it->first == offset) {
+ return true;
+ }
// If this was the first section, there are no other previous sections to
// check.
- if (it == sections_.begin()) { return false; }
+ if (it == sections_.begin()) {
+ return false;
+ }
// Go back one section.
--it;
@@ -1516,7 +1549,7 @@
it->second.regions.back().length;
}
-const reflection::Object *BinaryAnnotator::RootTable() const {
+const reflection::Object* BinaryAnnotator::RootTable() const {
if (!root_table_.empty()) {
return schema_->objects()->LookupByKey(root_table_);
}
diff --git a/src/code_generators.cpp b/src/code_generators.cpp
index 6a54210..b7860e1 100644
--- a/src/code_generators.cpp
+++ b/src/code_generators.cpp
@@ -24,21 +24,21 @@
#include "flatbuffers/util.h"
#if defined(_MSC_VER)
-# pragma warning(push)
-# pragma warning(disable : 4127) // C4127: conditional expression is constant
+#pragma warning(push)
+#pragma warning(disable : 4127) // C4127: conditional expression is constant
#endif
namespace flatbuffers {
-std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
- const std::string &path,
- const std::string &file_name) {
+std::string JavaCSharpMakeRule(const bool java, const Parser& parser,
+ const std::string& path,
+ const std::string& file_name) {
const std::string file_extension = java ? ".java" : ".cs";
std::string make_rule;
for (auto it = parser.enums_.vec.begin(); it != parser.enums_.vec.end();
++it) {
- auto &enum_def = **it;
+ auto& enum_def = **it;
if (!make_rule.empty()) make_rule += " ";
std::string directory =
BaseGenerator::NamespaceDir(parser, path, *enum_def.defined_namespace);
@@ -47,7 +47,7 @@
for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
++it) {
- auto &struct_def = **it;
+ auto& struct_def = **it;
if (!make_rule.empty()) make_rule += " ";
std::string directory = BaseGenerator::NamespaceDir(
parser, path, *struct_def.defined_namespace);
@@ -67,10 +67,14 @@
while (true) {
auto begin = text.find("{{");
- if (begin == std::string::npos) { break; }
+ if (begin == std::string::npos) {
+ break;
+ }
auto end = text.find("}}");
- if (end == std::string::npos || end < begin) { break; }
+ if (end == std::string::npos || end < begin) {
+ break;
+ }
// Write all the text before the first {{ into the stream.
stream_.write(text.c_str(), begin);
@@ -82,7 +86,7 @@
// value into the stream, otherwise write the key itself into the stream.
auto iter = value_map_.find(key);
if (iter != value_map_.end()) {
- const std::string &value = iter->second;
+ const std::string& value = iter->second;
stream_ << value;
} else {
FLATBUFFERS_ASSERT(false && "could not find key");
@@ -102,26 +106,26 @@
}
}
-void CodeWriter::AppendIdent(std::stringstream &stream) {
+void CodeWriter::AppendIdent(std::stringstream& stream) {
int lvl = cur_ident_lvl_;
while (lvl--) {
stream.write(pad_.c_str(), static_cast<std::streamsize>(pad_.size()));
}
}
-const char *BaseGenerator::FlatBuffersGeneratedWarning() {
+const char* BaseGenerator::FlatBuffersGeneratedWarning() {
return "automatically generated by the FlatBuffers compiler,"
" do not modify";
}
-std::string BaseGenerator::NamespaceDir(const Parser &parser,
- const std::string &path,
- const Namespace &ns,
+std::string BaseGenerator::NamespaceDir(const Parser& parser,
+ const std::string& path,
+ const Namespace& ns,
const bool dasherize) {
EnsureDirExists(path);
if (parser.opts.one_file) return path;
std::string namespace_dir = path; // Either empty or ends in separator.
- auto &namespaces = ns.components;
+ auto& namespaces = ns.components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
namespace_dir +=
!dasherize ? *it : ConvertCase(*it, Case::kDasher, Case::kUpperCamel);
@@ -131,15 +135,15 @@
return namespace_dir;
}
-std::string BaseGenerator::NamespaceDir(const Namespace &ns,
+std::string BaseGenerator::NamespaceDir(const Namespace& ns,
const bool dasherize) const {
return BaseGenerator::NamespaceDir(parser_, path_, ns, dasherize);
}
-std::string BaseGenerator::FullNamespace(const char *separator,
- const Namespace &ns) {
+std::string BaseGenerator::FullNamespace(const char* separator,
+ const Namespace& ns) {
std::string namespace_name;
- auto &namespaces = ns.components;
+ auto& namespaces = ns.components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
if (namespace_name.length()) namespace_name += separator;
namespace_name += *it;
@@ -147,7 +151,7 @@
return namespace_name;
}
-std::string BaseGenerator::LastNamespacePart(const Namespace &ns) {
+std::string BaseGenerator::LastNamespacePart(const Namespace& ns) {
if (!ns.components.empty())
return ns.components.back();
else
@@ -155,21 +159,21 @@
}
// Ensure that a type is prefixed with its namespace.
-std::string BaseGenerator::WrapInNameSpace(const Namespace *ns,
- const std::string &name) const {
+std::string BaseGenerator::WrapInNameSpace(const Namespace* ns,
+ const std::string& name) const {
std::string qualified_name = qualifying_start_;
for (auto it = ns->components.begin(); it != ns->components.end(); ++it)
qualified_name += *it + qualifying_separator_;
return qualified_name + name;
}
-std::string BaseGenerator::WrapInNameSpace(const Definition &def,
- const std::string &suffix) const {
+std::string BaseGenerator::WrapInNameSpace(const Definition& def,
+ const std::string& suffix) const {
return WrapInNameSpace(def.defined_namespace, def.name + suffix);
}
-std::string BaseGenerator::GetNameSpace(const Definition &def) const {
- const Namespace *ns = def.defined_namespace;
+std::string BaseGenerator::GetNameSpace(const Definition& def) const {
+ const Namespace* ns = def.defined_namespace;
if (CurrentNameSpace() == ns) return "";
std::string qualified_name = qualifying_start_;
for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
@@ -182,23 +186,23 @@
return qualified_name;
}
-std::string BaseGenerator::GeneratedFileName(const std::string &path,
- const std::string &file_name,
- const IDLOptions &options) const {
+std::string BaseGenerator::GeneratedFileName(const std::string& path,
+ const std::string& file_name,
+ const IDLOptions& options) const {
return path + file_name + options.filename_suffix + "." +
(options.filename_extension.empty() ? default_extension_
: options.filename_extension);
}
// Generate a documentation comment, if available.
-void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
- const CommentConfig *config, const char *prefix) {
+void GenComment(const std::vector<std::string>& dc, std::string* code_ptr,
+ const CommentConfig* config, const char* prefix) {
if (dc.begin() == dc.end()) {
// Don't output empty comment blocks with 0 lines of comment content.
return;
}
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
if (config != nullptr && config->first_line != nullptr) {
code += std::string(prefix) + std::string(config->first_line) + "\n";
}
@@ -215,10 +219,10 @@
}
}
-template<typename T>
+template <typename T>
std::string FloatConstantGenerator::GenFloatConstantImpl(
- const FieldDef &field) const {
- const auto &constant = field.value.constant;
+ const FieldDef& field) const {
+ const auto& constant = field.value.constant;
T v;
auto done = StringToNumber(constant.c_str(), &v);
FLATBUFFERS_ASSERT(done);
@@ -233,10 +237,12 @@
}
std::string FloatConstantGenerator::GenFloatConstant(
- const FieldDef &field) const {
+ const FieldDef& field) const {
switch (field.value.type.base_type) {
- case BASE_TYPE_FLOAT: return GenFloatConstantImpl<float>(field);
- case BASE_TYPE_DOUBLE: return GenFloatConstantImpl<double>(field);
+ case BASE_TYPE_FLOAT:
+ return GenFloatConstantImpl<float>(field);
+ case BASE_TYPE_DOUBLE:
+ return GenFloatConstantImpl<double>(field);
default: {
FLATBUFFERS_ASSERT(false);
return "INVALID_BASE_TYPE";
@@ -245,9 +251,9 @@
}
TypedFloatConstantGenerator::TypedFloatConstantGenerator(
- const char *double_prefix, const char *single_prefix,
- const char *nan_number, const char *pos_inf_number,
- const char *neg_inf_number)
+ const char* double_prefix, const char* single_prefix,
+ const char* nan_number, const char* pos_inf_number,
+ const char* neg_inf_number)
: double_prefix_(double_prefix),
single_prefix_(single_prefix),
nan_number_(nan_number),
@@ -255,11 +261,11 @@
neg_inf_number_(neg_inf_number) {}
std::string TypedFloatConstantGenerator::MakeNaN(
- const std::string &prefix) const {
+ const std::string& prefix) const {
return prefix + nan_number_;
}
std::string TypedFloatConstantGenerator::MakeInf(
- bool neg, const std::string &prefix) const {
+ bool neg, const std::string& prefix) const {
if (neg)
return !neg_inf_number_.empty() ? (prefix + neg_inf_number_)
: ("-" + prefix + pos_inf_number_);
@@ -268,7 +274,7 @@
}
std::string TypedFloatConstantGenerator::Value(double v,
- const std::string &src) const {
+ const std::string& src) const {
(void)v;
return src;
}
@@ -283,7 +289,7 @@
}
std::string TypedFloatConstantGenerator::Value(float v,
- const std::string &src) const {
+ const std::string& src) const {
(void)v;
return src + "f";
}
@@ -298,14 +304,14 @@
}
SimpleFloatConstantGenerator::SimpleFloatConstantGenerator(
- const char *nan_number, const char *pos_inf_number,
- const char *neg_inf_number)
+ const char* nan_number, const char* pos_inf_number,
+ const char* neg_inf_number)
: nan_number_(nan_number),
pos_inf_number_(pos_inf_number),
neg_inf_number_(neg_inf_number) {}
std::string SimpleFloatConstantGenerator::Value(double v,
- const std::string &src) const {
+ const std::string& src) const {
(void)v;
return src;
}
@@ -320,7 +326,7 @@
}
std::string SimpleFloatConstantGenerator::Value(float v,
- const std::string &src) const {
+ const std::string& src) const {
return this->Value(static_cast<double>(v), src);
}
@@ -335,5 +341,5 @@
} // namespace flatbuffers
#if defined(_MSC_VER)
-# pragma warning(pop)
+#pragma warning(pop)
#endif
diff --git a/src/file_binary_writer.cpp b/src/file_binary_writer.cpp
index 69d83e7..6fc762f 100644
--- a/src/file_binary_writer.cpp
+++ b/src/file_binary_writer.cpp
@@ -24,15 +24,15 @@
class FileBinaryWriter : public FileManager {
public:
- bool SaveFile(const std::string &absolute_file_name,
- const std::string &content) override {
+ bool SaveFile(const std::string& absolute_file_name,
+ const std::string& content) override {
std::ofstream ofs(absolute_file_name, std::ofstream::binary);
if (!ofs.is_open()) return false;
ofs.write(content.c_str(), content.size());
return !ofs.bad();
}
- bool Loadfile(const std::string &absolute_file_name, std::string *output) {
+ bool Loadfile(const std::string& absolute_file_name, std::string* output) {
if (DirExists(absolute_file_name.c_str())) return false;
std::ifstream ifs(absolute_file_name, std::ifstream::binary);
if (!ifs.is_open()) return false;
diff --git a/src/file_name_saving_file_manager.cpp b/src/file_name_saving_file_manager.cpp
index b43c7b6..f0a356c 100644
--- a/src/file_name_saving_file_manager.cpp
+++ b/src/file_name_saving_file_manager.cpp
@@ -27,8 +27,8 @@
FileNameSavingFileManager(std::set<std::string> file_names)
: file_names_(file_names) {}
- bool SaveFile(const std::string &absolute_file_name,
- const std::string &content) override {
+ bool SaveFile(const std::string& absolute_file_name,
+ const std::string& content) override {
(void)content;
auto pair = file_names_.insert(absolute_file_name);
// pair.second indicates whether the insertion is
@@ -36,7 +36,7 @@
return pair.second;
}
- bool Loadfile(const std::string &absolute_file_name, std::string *content) {
+ bool Loadfile(const std::string& absolute_file_name, std::string* content) {
(void)absolute_file_name;
(void)content;
return false;
diff --git a/src/file_writer.cpp b/src/file_writer.cpp
index bd34545..5cba285 100644
--- a/src/file_writer.cpp
+++ b/src/file_writer.cpp
@@ -24,15 +24,15 @@
class FileWriter : public FileManager {
public:
- bool SaveFile(const std::string &absolute_file_name,
- const std::string &content) override {
+ bool SaveFile(const std::string& absolute_file_name,
+ const std::string& content) override {
std::ofstream ofs(absolute_file_name, std::ofstream::out);
if (!ofs.is_open()) return false;
ofs.write(content.c_str(), content.size());
return !ofs.bad();
}
- bool Loadfile(const std::string &absolute_file_name, std::string *output) {
+ bool Loadfile(const std::string& absolute_file_name, std::string* output) {
if (DirExists(absolute_file_name.c_str())) return false;
std::ifstream ifs(absolute_file_name, std::ifstream::in);
if (!ifs.is_open()) return false;
diff --git a/src/flatc.cpp b/src/flatc.cpp
index f469a3e..612f797 100644
--- a/src/flatc.cpp
+++ b/src/flatc.cpp
@@ -31,15 +31,15 @@
namespace flatbuffers {
-static const char *FLATC_VERSION() { return FLATBUFFERS_VERSION(); }
+static const char* FLATC_VERSION() { return FLATBUFFERS_VERSION(); }
void FlatCompiler::ParseFile(
- flatbuffers::Parser &parser, const std::string &filename,
- const std::string &contents,
- const std::vector<const char *> &include_directories) const {
+ flatbuffers::Parser& parser, const std::string& filename,
+ const std::string& contents,
+ const std::vector<const char*>& include_directories) const {
auto local_include_directory = flatbuffers::StripFileName(filename);
- std::vector<const char *> inc_directories;
+ std::vector<const char*> inc_directories;
inc_directories.insert(inc_directories.end(), include_directories.begin(),
include_directories.end());
inc_directories.push_back(local_include_directory.c_str());
@@ -48,238 +48,246 @@
if (!parser.Parse(contents.c_str(), &inc_directories[0], filename.c_str())) {
Error(parser.error_, false, false);
}
- if (!parser.error_.empty()) { Warn(parser.error_, false); }
+ if (!parser.error_.empty()) {
+ Warn(parser.error_, false);
+ }
}
-void FlatCompiler::LoadBinarySchema(flatbuffers::Parser &parser,
- const std::string &filename,
- const std::string &contents) {
- if (!parser.Deserialize(reinterpret_cast<const uint8_t *>(contents.c_str()),
+void FlatCompiler::LoadBinarySchema(flatbuffers::Parser& parser,
+ const std::string& filename,
+ const std::string& contents) {
+ if (!parser.Deserialize(reinterpret_cast<const uint8_t*>(contents.c_str()),
contents.size())) {
Error("failed to load binary schema: " + filename, false, false);
}
}
-void FlatCompiler::Warn(const std::string &warn, bool show_exe_name) const {
+void FlatCompiler::Warn(const std::string& warn, bool show_exe_name) const {
params_.warn_fn(this, warn, show_exe_name);
}
-void FlatCompiler::Error(const std::string &err, bool usage,
+void FlatCompiler::Error(const std::string& err, bool usage,
bool show_exe_name) const {
params_.error_fn(this, err, usage, show_exe_name);
}
const static FlatCOption flatc_options[] = {
- { "o", "", "PATH", "Prefix PATH to all generated files." },
- { "I", "", "PATH", "Search for includes in the specified path." },
- { "M", "", "", "Print make rules for generated files." },
- { "", "version", "", "Print the version number of flatc and exit." },
- { "h", "help", "", "Prints this help text and exit." },
- { "", "strict-json", "",
- "Strict JSON: field names must be / will be quoted, no trailing commas in "
- "tables/vectors." },
- { "", "allow-non-utf8", "",
- "Pass non-UTF-8 input through parser and emit nonstandard \\x escapes in "
- "JSON. (Default is to raise parse error on non-UTF-8 input.)" },
- { "", "natural-utf8", "",
- "Output strings with UTF-8 as human-readable strings. By default, UTF-8 "
- "characters are printed as \\uXXXX escapes." },
- { "", "defaults-json", "",
- "Output fields whose value is the default when writing JSON" },
- { "", "unknown-json", "",
- "Allow fields in JSON that are not defined in the schema. These fields "
- "will be discarded when generating binaries." },
- { "", "no-prefix", "",
- "Don't prefix enum values with the enum type in C++." },
- { "", "scoped-enums", "",
- "Use C++11 style scoped and strongly typed enums. Also implies "
- "--no-prefix." },
- { "", "no-emit-min-max-enum-values", "",
- "Disable generation of MIN and MAX enumerated values for scoped enums "
- "and prefixed enums." },
- { "", "swift-implementation-only", "",
- "Adds a @_implementationOnly to swift imports" },
- { "", "gen-includes", "",
- "(deprecated), this is the default behavior. If the original behavior is "
- "required (no include statements) use --no-includes." },
- { "", "no-includes", "",
- "Don't generate include statements for included schemas the generated "
- "file depends on (C++, Python, Proto-to-Fbs)." },
- { "", "gen-mutable", "",
- "Generate accessors that can mutate buffers in-place." },
- { "", "gen-onefile", "",
- "Generate a single output file for C#, Go, Java, Kotlin and Python. "
- "Implies --no-include." },
- { "", "gen-name-strings", "",
- "Generate type name functions for C++ and Rust." },
- { "", "gen-object-api", "", "Generate an additional object-based API." },
- { "", "gen-compare", "", "Generate operator== for object-based API types." },
- { "", "gen-nullable", "",
- "Add Clang _Nullable for C++ pointer. or @Nullable for Java" },
- { "", "java-package-prefix", "",
- "Add a prefix to the generated package name for Java." },
- { "", "java-checkerframework", "", "Add @Pure for Java." },
- { "", "gen-generated", "", "Add @Generated annotation for Java." },
- { "", "gen-jvmstatic", "",
- "Add @JvmStatic annotation for Kotlin methods in companion object for "
- "interop from Java to Kotlin." },
- { "", "gen-all", "",
- "Generate not just code for the current schema files, but for all files it "
- "includes as well. If the language uses a single file for output (by "
- "default the case for C++ and JS), all code will end up in this one "
- "file." },
- { "", "gen-json-emit", "",
- "Generates encoding code which emits Flatbuffers into JSON" },
- { "", "cpp-include", "", "Adds an #include in generated file." },
- { "", "cpp-ptr-type", "T",
- "Set object API pointer type (default std::unique_ptr)." },
- { "", "cpp-str-type", "T",
- "Set object API string type (default std::string). T::c_str(), T::length() "
- "and T::empty() must be supported. The custom type also needs to be "
- "constructible from std::string (see the --cpp-str-flex-ctor option to "
- "change this behavior)" },
- { "", "cpp-str-flex-ctor", "",
- "Don't construct custom string types by passing std::string from "
- "Flatbuffers, but (char* + length)." },
- { "", "cpp-field-case-style", "STYLE",
- "Generate C++ fields using selected case style. Supported STYLE values: * "
- "'unchanged' - leave unchanged (default) * 'upper' - schema snake_case "
- "emits UpperCamel; * 'lower' - schema snake_case emits lowerCamel." },
- { "", "cpp-std", "CPP_STD",
- "Generate a C++ code using features of selected C++ standard. Supported "
- "CPP_STD values: * 'c++0x' - generate code compatible with old compilers; "
- "'c++11' - use C++11 code generator (default); * 'c++17' - use C++17 "
- "features in generated code (experimental)." },
- { "", "cpp-static-reflection", "",
- "When using C++17, generate extra code to provide compile-time (static) "
- "reflection of Flatbuffers types. Requires --cpp-std to be \"c++17\" or "
- "higher." },
- { "", "object-prefix", "PREFIX",
- "Customize class prefix for C++ object-based API." },
- { "", "object-suffix", "SUFFIX",
- "Customize class suffix for C++ object-based API. Default Value is "
- "\"T\"." },
- { "", "go-namespace", "", "Generate the overriding namespace in Golang." },
- { "", "go-import", "IMPORT",
- "Generate the overriding import for flatbuffers in Golang (default is "
- "\"github.com/google/flatbuffers/go\")." },
- { "", "go-module-name", "",
- "Prefix local import paths of generated go code with the module name" },
- { "", "raw-binary", "",
- "Allow binaries without file_identifier to be read. This may crash flatc "
- "given a mismatched schema." },
- { "", "size-prefixed", "", "Input binaries are size prefixed buffers." },
- { "", "proto-namespace-suffix", "SUFFIX",
- "Add this namespace to any flatbuffers generated from protobufs." },
- { "", "oneof-union", "", "Translate .proto oneofs to flatbuffer unions." },
- { "", "keep-proto-id", "", "Keep protobuf field ids in generated fbs file." },
- { "", "proto-id-gap", "",
- "Action that should be taken when a gap between protobuf ids found. "
- "Supported values: * "
- "'nop' - do not care about gap * 'warn' - A warning message will be shown "
- "about the gap in protobuf ids"
- "(default) "
- "* 'error' - An error message will be shown and the fbs generation will be "
- "interrupted." },
- { "", "grpc", "", "Generate GRPC interfaces for the specified languages." },
- { "", "schema", "", "Serialize schemas instead of JSON (use with -b)." },
- { "", "bfbs-filenames", "PATH",
- "Sets the root path where reflection filenames in reflection.fbs are "
- "relative to. The 'root' is denoted with `//`. E.g. if PATH=/a/b/c "
- "then /a/d/e.fbs will be serialized as //../d/e.fbs. (PATH defaults to the "
- "directory of the first provided schema file." },
- { "", "bfbs-absolute-paths", "", "Uses absolute paths instead of relative paths in the BFBS output." },
- { "", "bfbs-comments", "", "Add doc comments to the binary schema files." },
- { "", "bfbs-builtins", "",
- "Add builtin attributes to the binary schema files." },
- { "", "bfbs-gen-embed", "",
- "Generate code to embed the bfbs schema to the source." },
- { "", "conform", "FILE",
- "Specify a schema the following schemas should be an evolution of. Gives "
- "errors if not." },
- { "", "conform-includes", "PATH",
- "Include path for the schema given with --conform PATH" },
- { "", "filename-suffix", "SUFFIX",
- "The suffix appended to the generated file names (Default is "
- "'_generated')." },
- { "", "filename-ext", "EXT",
- "The extension appended to the generated file names. Default is "
- "language-specific (e.g., '.h' for C++)" },
- { "", "include-prefix", "PATH",
- "Prefix this PATH to any generated include statements." },
- { "", "keep-prefix", "",
- "Keep original prefix of schema include statement." },
- { "", "reflect-types", "",
- "Add minimal type reflection to code generation." },
- { "", "reflect-names", "", "Add minimal type/name reflection." },
- { "", "rust-serialize", "",
- "Implement serde::Serialize on generated Rust types." },
- { "", "rust-module-root-file", "",
- "Generate rust code in individual files with a module root file." },
- { "", "root-type", "T", "Select or override the default root_type." },
- { "", "require-explicit-ids", "",
- "When parsing schemas, require explicit ids (id: x)." },
- { "", "force-defaults", "",
- "Emit default values in binary output from JSON" },
- { "", "force-empty", "",
- "When serializing from object API representation, force strings and "
- "vectors to empty rather than null." },
- { "", "force-empty-vectors", "",
- "When serializing from object API representation, force vectors to empty "
- "rather than null." },
- { "", "flexbuffers", "",
- "Used with \"binary\" and \"json\" options, it generates data using "
- "schema-less FlexBuffers." },
- { "", "no-warnings", "", "Inhibit all warnings messages." },
- { "", "warnings-as-errors", "", "Treat all warnings as errors." },
- { "", "cs-global-alias", "",
- "Prepend \"global::\" to all user generated csharp classes and "
- "structs." },
- { "", "cs-gen-json-serializer", "",
- "Allows (de)serialization of JSON text in the Object API. (requires "
- "--gen-object-api)." },
- { "", "json-nested-bytes", "",
- "Allow a nested_flatbuffer field to be parsed as a vector of bytes "
- "in JSON, which is unsafe unless checked by a verifier afterwards." },
- { "", "ts-flat-files", "",
- "Generate a single typescript file per .fbs file. Implies "
- "ts_entry_points." },
- { "", "ts-entry-points", "",
- "Generate entry point typescript per namespace. Implies gen-all." },
- { "", "annotate-sparse-vectors", "", "Don't annotate every vector element." },
- { "", "annotate", "SCHEMA",
- "Annotate the provided BINARY_FILE with the specified SCHEMA file." },
- { "", "no-leak-private-annotation", "",
- "Prevents multiple type of annotations within a Fbs SCHEMA file. "
- "Currently this is required to generate private types in Rust" },
- { "", "python-no-type-prefix-suffix", "",
- "Skip emission of Python functions that are prefixed with typenames" },
- { "", "python-typing", "", "Generate Python type annotations" },
- { "", "python-version", "", "Generate code for the given Python version." },
- { "", "python-decode-obj-api-strings", "", "Decode bytes to strings for the Python Object API"},
- { "", "python-gen-numpy", "", "Whether to generate numpy helpers." },
- { "", "ts-omit-entrypoint", "",
- "Omit emission of namespace entrypoint file" },
- { "", "file-names-only", "",
- "Print out generated file names without writing to the files" },
- { "", "grpc-filename-suffix", "SUFFIX",
- "The suffix for the generated file names (Default is '.fb')." },
- { "", "grpc-additional-header", "",
- "Additional headers to prepend to the generated files." },
- { "", "grpc-use-system-headers", "",
- "Use <> for headers included from the generated code." },
- { "", "grpc-search-path", "PATH", "Prefix to any gRPC includes." },
- { "", "grpc-python-typed-handlers", "",
- "The handlers will use the generated classes rather than raw bytes." },
- { "", "grpc-callback-api", "",
- "Generate gRPC code using the callback (reactor) API instead of legacy "
- "sync/async." },
+ {"o", "", "PATH", "Prefix PATH to all generated files."},
+ {"I", "", "PATH", "Search for includes in the specified path."},
+ {"M", "", "", "Print make rules for generated files."},
+ {"", "version", "", "Print the version number of flatc and exit."},
+ {"h", "help", "", "Prints this help text and exit."},
+ {"", "strict-json", "",
+ "Strict JSON: field names must be / will be quoted, no trailing commas in "
+ "tables/vectors."},
+ {"", "allow-non-utf8", "",
+ "Pass non-UTF-8 input through parser and emit nonstandard \\x escapes in "
+ "JSON. (Default is to raise parse error on non-UTF-8 input.)"},
+ {"", "natural-utf8", "",
+ "Output strings with UTF-8 as human-readable strings. By default, UTF-8 "
+ "characters are printed as \\uXXXX escapes."},
+ {"", "defaults-json", "",
+ "Output fields whose value is the default when writing JSON"},
+ {"", "unknown-json", "",
+ "Allow fields in JSON that are not defined in the schema. These fields "
+ "will be discarded when generating binaries."},
+ {"", "no-prefix", "",
+ "Don't prefix enum values with the enum type in C++."},
+ {"", "scoped-enums", "",
+ "Use C++11 style scoped and strongly typed enums. Also implies "
+ "--no-prefix."},
+ {"", "no-emit-min-max-enum-values", "",
+ "Disable generation of MIN and MAX enumerated values for scoped enums "
+ "and prefixed enums."},
+ {"", "swift-implementation-only", "",
+ "Adds a @_implementationOnly to swift imports"},
+ {"", "gen-includes", "",
+ "(deprecated), this is the default behavior. If the original behavior is "
+ "required (no include statements) use --no-includes."},
+ {"", "no-includes", "",
+ "Don't generate include statements for included schemas the generated "
+ "file depends on (C++, Python, Proto-to-Fbs)."},
+ {"", "gen-mutable", "",
+ "Generate accessors that can mutate buffers in-place."},
+ {"", "gen-onefile", "",
+ "Generate a single output file for C#, Go, Java, Kotlin and Python. "
+ "Implies --no-include."},
+ {"", "gen-name-strings", "",
+ "Generate type name functions for C++ and Rust."},
+ {"", "gen-object-api", "", "Generate an additional object-based API."},
+ {"", "gen-compare", "", "Generate operator== for object-based API types."},
+ {"", "gen-nullable", "",
+ "Add Clang _Nullable for C++ pointer. or @Nullable for Java"},
+ {"", "java-package-prefix", "",
+ "Add a prefix to the generated package name for Java."},
+ {"", "java-checkerframework", "", "Add @Pure for Java."},
+ {"", "gen-generated", "", "Add @Generated annotation for Java."},
+ {"", "gen-jvmstatic", "",
+ "Add @JvmStatic annotation for Kotlin methods in companion object for "
+ "interop from Java to Kotlin."},
+ {"", "gen-all", "",
+ "Generate not just code for the current schema files, but for all files "
+ "it "
+ "includes as well. If the language uses a single file for output (by "
+ "default the case for C++ and JS), all code will end up in this one "
+ "file."},
+ {"", "gen-json-emit", "",
+ "Generates encoding code which emits Flatbuffers into JSON"},
+ {"", "cpp-include", "", "Adds an #include in generated file."},
+ {"", "cpp-ptr-type", "T",
+ "Set object API pointer type (default std::unique_ptr)."},
+ {"", "cpp-str-type", "T",
+ "Set object API string type (default std::string). T::c_str(), "
+ "T::length() "
+ "and T::empty() must be supported. The custom type also needs to be "
+ "constructible from std::string (see the --cpp-str-flex-ctor option to "
+ "change this behavior)"},
+ {"", "cpp-str-flex-ctor", "",
+ "Don't construct custom string types by passing std::string from "
+ "Flatbuffers, but (char* + length)."},
+ {"", "cpp-field-case-style", "STYLE",
+ "Generate C++ fields using selected case style. Supported STYLE values: * "
+ "'unchanged' - leave unchanged (default) * 'upper' - schema snake_case "
+ "emits UpperCamel; * 'lower' - schema snake_case emits lowerCamel."},
+ {"", "cpp-std", "CPP_STD",
+ "Generate a C++ code using features of selected C++ standard. Supported "
+ "CPP_STD values: * 'c++0x' - generate code compatible with old compilers; "
+ "'c++11' - use C++11 code generator (default); * 'c++17' - use C++17 "
+ "features in generated code (experimental)."},
+ {"", "cpp-static-reflection", "",
+ "When using C++17, generate extra code to provide compile-time (static) "
+ "reflection of Flatbuffers types. Requires --cpp-std to be \"c++17\" or "
+ "higher."},
+ {"", "object-prefix", "PREFIX",
+ "Customize class prefix for C++ object-based API."},
+ {"", "object-suffix", "SUFFIX",
+ "Customize class suffix for C++ object-based API. Default Value is "
+ "\"T\"."},
+ {"", "go-namespace", "", "Generate the overriding namespace in Golang."},
+ {"", "go-import", "IMPORT",
+ "Generate the overriding import for flatbuffers in Golang (default is "
+ "\"github.com/google/flatbuffers/go\")."},
+ {"", "go-module-name", "",
+ "Prefix local import paths of generated go code with the module name"},
+ {"", "raw-binary", "",
+ "Allow binaries without file_identifier to be read. This may crash flatc "
+ "given a mismatched schema."},
+ {"", "size-prefixed", "", "Input binaries are size prefixed buffers."},
+ {"", "proto-namespace-suffix", "SUFFIX",
+ "Add this namespace to any flatbuffers generated from protobufs."},
+ {"", "oneof-union", "", "Translate .proto oneofs to flatbuffer unions."},
+ {"", "keep-proto-id", "", "Keep protobuf field ids in generated fbs file."},
+ {"", "proto-id-gap", "",
+ "Action that should be taken when a gap between protobuf ids found. "
+ "Supported values: * "
+ "'nop' - do not care about gap * 'warn' - A warning message will be shown "
+ "about the gap in protobuf ids"
+ "(default) "
+ "* 'error' - An error message will be shown and the fbs generation will "
+ "be "
+ "interrupted."},
+ {"", "grpc", "", "Generate GRPC interfaces for the specified languages."},
+ {"", "schema", "", "Serialize schemas instead of JSON (use with -b)."},
+ {"", "bfbs-filenames", "PATH",
+ "Sets the root path where reflection filenames in reflection.fbs are "
+ "relative to. The 'root' is denoted with `//`. E.g. if PATH=/a/b/c "
+ "then /a/d/e.fbs will be serialized as //../d/e.fbs. (PATH defaults to "
+ "the "
+ "directory of the first provided schema file."},
+ {"", "bfbs-absolute-paths", "",
+ "Uses absolute paths instead of relative paths in the BFBS output."},
+ {"", "bfbs-comments", "", "Add doc comments to the binary schema files."},
+ {"", "bfbs-builtins", "",
+ "Add builtin attributes to the binary schema files."},
+ {"", "bfbs-gen-embed", "",
+ "Generate code to embed the bfbs schema to the source."},
+ {"", "conform", "FILE",
+ "Specify a schema the following schemas should be an evolution of. Gives "
+ "errors if not."},
+ {"", "conform-includes", "PATH",
+ "Include path for the schema given with --conform PATH"},
+ {"", "filename-suffix", "SUFFIX",
+ "The suffix appended to the generated file names (Default is "
+ "'_generated')."},
+ {"", "filename-ext", "EXT",
+ "The extension appended to the generated file names. Default is "
+ "language-specific (e.g., '.h' for C++)"},
+ {"", "include-prefix", "PATH",
+ "Prefix this PATH to any generated include statements."},
+ {"", "keep-prefix", "",
+ "Keep original prefix of schema include statement."},
+ {"", "reflect-types", "",
+ "Add minimal type reflection to code generation."},
+ {"", "reflect-names", "", "Add minimal type/name reflection."},
+ {"", "rust-serialize", "",
+ "Implement serde::Serialize on generated Rust types."},
+ {"", "rust-module-root-file", "",
+ "Generate rust code in individual files with a module root file."},
+ {"", "root-type", "T", "Select or override the default root_type."},
+ {"", "require-explicit-ids", "",
+ "When parsing schemas, require explicit ids (id: x)."},
+ {"", "force-defaults", "",
+ "Emit default values in binary output from JSON"},
+ {"", "force-empty", "",
+ "When serializing from object API representation, force strings and "
+ "vectors to empty rather than null."},
+ {"", "force-empty-vectors", "",
+ "When serializing from object API representation, force vectors to empty "
+ "rather than null."},
+ {"", "flexbuffers", "",
+ "Used with \"binary\" and \"json\" options, it generates data using "
+ "schema-less FlexBuffers."},
+ {"", "no-warnings", "", "Inhibit all warnings messages."},
+ {"", "warnings-as-errors", "", "Treat all warnings as errors."},
+ {"", "cs-global-alias", "",
+ "Prepend \"global::\" to all user generated csharp classes and "
+ "structs."},
+ {"", "cs-gen-json-serializer", "",
+ "Allows (de)serialization of JSON text in the Object API. (requires "
+ "--gen-object-api)."},
+ {"", "json-nested-bytes", "",
+ "Allow a nested_flatbuffer field to be parsed as a vector of bytes "
+ "in JSON, which is unsafe unless checked by a verifier afterwards."},
+ {"", "ts-flat-files", "",
+ "Generate a single typescript file per .fbs file. Implies "
+ "ts_entry_points."},
+ {"", "ts-entry-points", "",
+ "Generate entry point typescript per namespace. Implies gen-all."},
+ {"", "annotate-sparse-vectors", "", "Don't annotate every vector element."},
+ {"", "annotate", "SCHEMA",
+ "Annotate the provided BINARY_FILE with the specified SCHEMA file."},
+ {"", "no-leak-private-annotation", "",
+ "Prevents multiple type of annotations within a Fbs SCHEMA file. "
+ "Currently this is required to generate private types in Rust"},
+ {"", "python-no-type-prefix-suffix", "",
+ "Skip emission of Python functions that are prefixed with typenames"},
+ {"", "python-typing", "", "Generate Python type annotations"},
+ {"", "python-version", "", "Generate code for the given Python version."},
+ {"", "python-decode-obj-api-strings", "",
+ "Decode bytes to strings for the Python Object API"},
+ {"", "python-gen-numpy", "", "Whether to generate numpy helpers."},
+ {"", "ts-omit-entrypoint", "",
+ "Omit emission of namespace entrypoint file"},
+ {"", "file-names-only", "",
+ "Print out generated file names without writing to the files"},
+ {"", "grpc-filename-suffix", "SUFFIX",
+ "The suffix for the generated file names (Default is '.fb')."},
+ {"", "grpc-additional-header", "",
+ "Additional headers to prepend to the generated files."},
+ {"", "grpc-use-system-headers", "",
+ "Use <> for headers included from the generated code."},
+ {"", "grpc-search-path", "PATH", "Prefix to any gRPC includes."},
+ {"", "grpc-python-typed-handlers", "",
+ "The handlers will use the generated classes rather than raw bytes."},
+ {"", "grpc-callback-api", "",
+ "Generate gRPC code using the callback (reactor) API instead of legacy "
+ "sync/async."},
};
auto cmp = [](FlatCOption a, FlatCOption b) { return a.long_opt < b.long_opt; };
static std::set<FlatCOption, decltype(cmp)> language_options(cmp);
-static void AppendTextWrappedString(std::stringstream &ss, std::string &text,
+static void AppendTextWrappedString(std::stringstream& ss, std::string& text,
size_t max_col, size_t start_col) {
size_t max_line_length = max_col - start_col;
@@ -298,7 +306,7 @@
}
}
-static void AppendOption(std::stringstream &ss, const FlatCOption &option,
+static void AppendOption(std::stringstream& ss, const FlatCOption& option,
size_t max_col, size_t min_col_for_description) {
size_t chars = 2;
ss << " ";
@@ -337,26 +345,30 @@
ss << "\n";
}
-static void AppendShortOption(std::stringstream &ss,
- const FlatCOption &option) {
+static void AppendShortOption(std::stringstream& ss,
+ const FlatCOption& option) {
if (!option.short_opt.empty()) {
ss << "-" << option.short_opt;
- if (!option.long_opt.empty()) { ss << "|"; }
+ if (!option.long_opt.empty()) {
+ ss << "|";
+ }
}
- if (!option.long_opt.empty()) { ss << "--" << option.long_opt; }
+ if (!option.long_opt.empty()) {
+ ss << "--" << option.long_opt;
+ }
}
std::string FlatCompiler::GetShortUsageString(
- const std::string &program_name) const {
+ const std::string& program_name) const {
std::stringstream ss;
ss << "Usage: " << program_name << " [";
- for (const FlatCOption &option : language_options) {
+ for (const FlatCOption& option : language_options) {
AppendShortOption(ss, option);
ss << ", ";
}
- for (const FlatCOption &option : flatc_options) {
+ for (const FlatCOption& option : flatc_options) {
AppendShortOption(ss, option);
ss << ", ";
}
@@ -370,17 +382,17 @@
}
std::string FlatCompiler::GetUsageString(
- const std::string &program_name) const {
+ const std::string& program_name) const {
std::stringstream ss;
ss << "Usage: " << program_name
<< " [OPTION]... FILE... [-- BINARY_FILE...]\n";
- for (const FlatCOption &option : language_options) {
+ for (const FlatCOption& option : language_options) {
AppendOption(ss, option, 80, 25);
}
ss << "\n";
- for (const FlatCOption &option : flatc_options) {
+ for (const FlatCOption& option : flatc_options) {
AppendOption(ss, option, 80, 25);
}
ss << "\n";
@@ -397,20 +409,20 @@
return ss.str();
}
-void FlatCompiler::AnnotateBinaries(const uint8_t *binary_schema,
+void FlatCompiler::AnnotateBinaries(const uint8_t* binary_schema,
const uint64_t binary_schema_size,
- const FlatCOptions &options) {
- const std::string &schema_filename = options.annotate_schema;
+ const FlatCOptions& options) {
+ const std::string& schema_filename = options.annotate_schema;
- for (const std::string &filename : options.filenames) {
+ for (const std::string& filename : options.filenames) {
std::string binary_contents;
if (!flatbuffers::LoadFile(filename.c_str(), true, &binary_contents)) {
Warn("unable to load binary file: " + filename);
continue;
}
- const uint8_t *binary =
- reinterpret_cast<const uint8_t *>(binary_contents.c_str());
+ const uint8_t* binary =
+ reinterpret_cast<const uint8_t*>(binary_contents.c_str());
const size_t binary_size = binary_contents.size();
const bool is_size_prefixed = options.opts.size_prefixed;
@@ -436,14 +448,16 @@
}
FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc,
- const char **argv) {
- if (argc <= 1) { Error("Need to provide at least one argument."); }
+ const char** argv) {
+ if (argc <= 1) {
+ Error("Need to provide at least one argument.");
+ }
FlatCOptions options;
options.program_name = std::string(argv[0]);
- IDLOptions &opts = options.opts;
+ IDLOptions& opts = options.opts;
for (int argi = 1; argi < argc; argi++) {
std::string arg = argv[argi];
@@ -741,7 +755,9 @@
arg == "--grpc-callback-api=false") {
opts.grpc_callback_api = false;
} else {
- if (arg == "--proto") { opts.proto_mode = true; }
+ if (arg == "--proto") {
+ opts.proto_mode = true;
+ }
auto code_generator_it = code_generators_.find(arg);
if (code_generator_it == code_generators_.end()) {
@@ -772,8 +788,8 @@
return options;
}
-void FlatCompiler::ValidateOptions(const FlatCOptions &options) {
- const IDLOptions &opts = options.opts;
+void FlatCompiler::ValidateOptions(const FlatCOptions& options) {
+ const IDLOptions& opts = options.opts;
if (!options.filenames.size()) Error("missing input files", false, true);
@@ -792,7 +808,7 @@
}
flatbuffers::Parser FlatCompiler::GetConformParser(
- const FlatCOptions &options) {
+ const FlatCOptions& options) {
flatbuffers::Parser conform_parser;
// conform parser should check advanced options,
@@ -817,8 +833,8 @@
return conform_parser;
}
-std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
- Parser &conform_parser) {
+std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions& options,
+ Parser& conform_parser) {
std::unique_ptr<Parser> parser =
std::unique_ptr<Parser>(new Parser(options.opts));
@@ -826,7 +842,7 @@
file_it != options.filenames.end(); ++file_it) {
IDLOptions opts = options.opts;
- auto &filename = *file_it;
+ auto& filename = *file_it;
std::string contents;
if (!flatbuffers::LoadFile(filename.c_str(), true, &contents))
Error("unable to load file: " + filename);
@@ -842,7 +858,7 @@
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
- reinterpret_cast<const uint8_t *>(contents.c_str()),
+ reinterpret_cast<const uint8_t*>(contents.c_str()),
contents.length());
if (!options.raw_binary) {
// Generally reading binaries that do not correspond to the schema
@@ -882,7 +898,7 @@
LoadBinarySchema(*parser, filename, contents);
} else if (opts.use_flexbuffers) {
if (opts.lang_to_generate == IDLOptions::kJson) {
- auto data = reinterpret_cast<const uint8_t *>(contents.c_str());
+ auto data = reinterpret_cast<const uint8_t*>(contents.c_str());
auto size = contents.size();
std::vector<uint8_t> reuse_tracker;
if (!flexbuffers::VerifyBuffer(data, size, &reuse_tracker))
@@ -919,7 +935,7 @@
// If one of the generators uses bfbs, serialize the parser and get
// the serialized buffer and length.
- const uint8_t *bfbs_buffer = nullptr;
+ const uint8_t* bfbs_buffer = nullptr;
int64_t bfbs_length = 0;
if (options.requires_bfbs) {
parser->Serialize();
@@ -927,7 +943,7 @@
bfbs_length = parser->builder_.GetSize();
}
- for (const std::shared_ptr<CodeGenerator> &code_generator :
+ for (const std::shared_ptr<CodeGenerator>& code_generator :
options.generators) {
if (options.print_make_rules) {
std::string make_rule;
@@ -996,7 +1012,7 @@
return parser;
}
-int FlatCompiler::Compile(const FlatCOptions &options) {
+int FlatCompiler::Compile(const FlatCOptions& options) {
// TODO(derekbailey): change to std::optional<Parser>
Parser conform_parser = GetConformParser(options);
@@ -1016,7 +1032,7 @@
Error("unable to load schema: " + options.annotate_schema);
}
- const uint8_t *binary_schema = nullptr;
+ const uint8_t* binary_schema = nullptr;
uint64_t binary_schema_size = 0;
IDLOptions binary_opts;
@@ -1024,8 +1040,7 @@
Parser parser(binary_opts);
if (is_binary_schema) {
- binary_schema =
- reinterpret_cast<const uint8_t *>(schema_contents.c_str());
+ binary_schema = reinterpret_cast<const uint8_t*>(schema_contents.c_str());
binary_schema_size = schema_contents.size();
} else {
// If we need to generate the .bfbs file from the provided schema file
@@ -1057,7 +1072,7 @@
std::unique_ptr<Parser> parser = GenerateCode(options, conform_parser);
- for (const auto &code_generator : options.generators) {
+ for (const auto& code_generator : options.generators) {
if (code_generator->SupportsRootFileGeneration()) {
code_generator->GenerateRootFile(*parser, options.output_path);
}
@@ -1067,7 +1082,7 @@
}
bool FlatCompiler::RegisterCodeGenerator(
- const FlatCOption &option, std::shared_ptr<CodeGenerator> code_generator) {
+ const FlatCOption& option, std::shared_ptr<CodeGenerator> code_generator) {
if (!option.short_opt.empty() &&
code_generators_.find("-" + option.short_opt) != code_generators_.end()) {
Error("multiple generators registered under: -" + option.short_opt, false,
diff --git a/src/flatc_main.cpp b/src/flatc_main.cpp
index 45f95a0..bcbb55d 100644
--- a/src/flatc_main.cpp
+++ b/src/flatc_main.cpp
@@ -40,18 +40,22 @@
#include "idl_gen_text.h"
#include "idl_gen_ts.h"
-static const char *g_program_name = nullptr;
+static const char* g_program_name = nullptr;
-static void Warn(const flatbuffers::FlatCompiler *flatc,
- const std::string &warn, bool show_exe_name) {
+static void Warn(const flatbuffers::FlatCompiler* flatc,
+ const std::string& warn, bool show_exe_name) {
(void)flatc;
- if (show_exe_name) { printf("%s: ", g_program_name); }
+ if (show_exe_name) {
+ printf("%s: ", g_program_name);
+ }
fprintf(stderr, "\nwarning:\n %s\n\n", warn.c_str());
}
-static void Error(const flatbuffers::FlatCompiler *flatc,
- const std::string &err, bool usage, bool show_exe_name) {
- if (show_exe_name) { printf("%s: ", g_program_name); }
+static void Error(const flatbuffers::FlatCompiler* flatc,
+ const std::string& err, bool usage, bool show_exe_name) {
+ if (show_exe_name) {
+ printf("%s: ", g_program_name);
+ }
if (usage && flatc) {
fprintf(stderr, "%s\n", flatc->GetShortUsageString(g_program_name).c_str());
}
@@ -60,16 +64,16 @@
}
namespace flatbuffers {
-void LogCompilerWarn(const std::string &warn) {
- Warn(static_cast<const flatbuffers::FlatCompiler *>(nullptr), warn, true);
+void LogCompilerWarn(const std::string& warn) {
+ Warn(static_cast<const flatbuffers::FlatCompiler*>(nullptr), warn, true);
}
-void LogCompilerError(const std::string &err) {
- Error(static_cast<const flatbuffers::FlatCompiler *>(nullptr), err, false,
+void LogCompilerError(const std::string& err) {
+ Error(static_cast<const flatbuffers::FlatCompiler*>(nullptr), err, false,
true);
}
} // namespace flatbuffers
-int main(int argc, const char *argv[]) {
+int main(int argc, const char* argv[]) {
const std::string flatbuffers_version(flatbuffers::FLATBUFFERS_VERSION());
g_program_name = argv[0];
@@ -83,100 +87,101 @@
flatc.RegisterCodeGenerator(
flatbuffers::FlatCOption{
"b", "binary", "",
- "Generate wire format binaries for any data definitions" },
+ "Generate wire format binaries for any data definitions"},
flatbuffers::NewBinaryCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "c", "cpp", "",
- "Generate C++ headers for tables/structs" },
+ flatbuffers::FlatCOption{"c", "cpp", "",
+ "Generate C++ headers for tables/structs"},
flatbuffers::NewCppCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "n", "csharp", "",
- "Generate C# classes for tables/structs" },
+ flatbuffers::FlatCOption{"n", "csharp", "",
+ "Generate C# classes for tables/structs"},
flatbuffers::NewCSharpCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "d", "dart", "",
- "Generate Dart classes for tables/structs" },
+ flatbuffers::FlatCOption{"d", "dart", "",
+ "Generate Dart classes for tables/structs"},
flatbuffers::NewDartCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "", "proto", "",
- "Input is a .proto, translate to .fbs" },
+ flatbuffers::FlatCOption{"", "proto", "",
+ "Input is a .proto, translate to .fbs"},
flatbuffers::NewFBSCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "g", "go", "",
- "Generate Go files for tables/structs" },
+ flatbuffers::FlatCOption{"g", "go", "",
+ "Generate Go files for tables/structs"},
flatbuffers::NewGoCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "j", "java", "",
- "Generate Java classes for tables/structs" },
+ flatbuffers::FlatCOption{"j", "java", "",
+ "Generate Java classes for tables/structs"},
flatbuffers::NewJavaCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "", "jsonschema", "", "Generate Json schema" },
+ flatbuffers::FlatCOption{"", "jsonschema", "", "Generate Json schema"},
flatbuffers::NewJsonSchemaCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "", "kotlin", "",
- "Generate Kotlin classes for tables/structs" },
+ flatbuffers::FlatCOption{"", "kotlin", "",
+ "Generate Kotlin classes for tables/structs"},
flatbuffers::NewKotlinCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "", "kotlin-kmp", "",
- "Generate Kotlin multiplatform classes for tables/structs" },
+ flatbuffers::FlatCOption{
+ "", "kotlin-kmp", "",
+ "Generate Kotlin multiplatform classes for tables/structs"},
flatbuffers::NewKotlinKMPCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "", "lobster", "",
- "Generate Lobster files for tables/structs" },
+ flatbuffers::FlatCOption{"", "lobster", "",
+ "Generate Lobster files for tables/structs"},
flatbuffers::NewLobsterCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "l", "lua", "",
- "Generate Lua files for tables/structs" },
+ flatbuffers::FlatCOption{"l", "lua", "",
+ "Generate Lua files for tables/structs"},
flatbuffers::NewLuaBfbsGenerator(flatbuffers_version));
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "", "nim", "",
- "Generate Nim files for tables/structs" },
+ flatbuffers::FlatCOption{"", "nim", "",
+ "Generate Nim files for tables/structs"},
flatbuffers::NewNimBfbsGenerator(flatbuffers_version));
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "p", "python", "",
- "Generate Python files for tables/structs" },
+ flatbuffers::FlatCOption{"p", "python", "",
+ "Generate Python files for tables/structs"},
flatbuffers::NewPythonCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "", "php", "",
- "Generate PHP files for tables/structs" },
+ flatbuffers::FlatCOption{"", "php", "",
+ "Generate PHP files for tables/structs"},
flatbuffers::NewPhpCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "r", "rust", "",
- "Generate Rust files for tables/structs" },
+ flatbuffers::FlatCOption{"r", "rust", "",
+ "Generate Rust files for tables/structs"},
flatbuffers::NewRustCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{
- "t", "json", "", "Generate text output for any data definitions" },
+ flatbuffers::FlatCOption{"t", "json", "",
+ "Generate text output for any data definitions"},
flatbuffers::NewTextCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "", "swift", "",
- "Generate Swift files for tables/structs" },
+ flatbuffers::FlatCOption{"", "swift", "",
+ "Generate Swift files for tables/structs"},
flatbuffers::NewSwiftCodeGenerator());
flatc.RegisterCodeGenerator(
- flatbuffers::FlatCOption{ "T", "ts", "",
- "Generate TypeScript code for tables/structs" },
+ flatbuffers::FlatCOption{"T", "ts", "",
+ "Generate TypeScript code for tables/structs"},
flatbuffers::NewTsCodeGenerator());
// Create the FlatC options by parsing the command line arguments.
- const flatbuffers::FlatCOptions &options =
+ const flatbuffers::FlatCOptions& options =
flatc.ParseFromCommandLineArguments(argc, argv);
// Compile with the extracted FlatC options.
diff --git a/src/flathash.cpp b/src/flathash.cpp
index 1264f82..170afeb 100644
--- a/src/flathash.cpp
+++ b/src/flathash.cpp
@@ -24,8 +24,8 @@
enum OutputFormat { kDecimal, kHexadecimal, kHexadecimal0x };
-int main(int argc, char *argv[]) {
- const char *name = argv[0];
+int main(int argc, char* argv[]) {
+ const char* name = argv[0];
if (argc <= 1) {
printf("%s HASH [OPTION]... [--] STRING...\n", name);
printf("Available hashing algorithms:\n");
@@ -55,7 +55,7 @@
return 1;
}
- const char *hash_algorithm = argv[1];
+ const char* hash_algorithm = argv[1];
flatbuffers::NamedHashFunction<uint16_t>::HashFunction hash_function16 =
flatbuffers::FindHashFunction16(hash_algorithm);
@@ -73,7 +73,7 @@
bool annotate = false;
bool escape_dash = false;
for (int i = 2; i < argc; i++) {
- const char *arg = argv[i];
+ const char* arg = argv[i];
if (!escape_dash && arg[0] == '-') {
std::string opt = arg;
if (opt == "-d")
diff --git a/src/idl_gen_binary.cpp b/src/idl_gen_binary.cpp
index 7ed0a99..a028055 100644
--- a/src/idl_gen_binary.cpp
+++ b/src/idl_gen_binary.cpp
@@ -33,17 +33,17 @@
namespace flatbuffers {
namespace {
-static std::string BinaryFileName(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static std::string BinaryFileName(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
return path + file_name + "." + ext;
}
-static bool GenerateBinary(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateBinary(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
if (parser.opts.use_flexbuffers) {
auto data_vec = parser.flex_builder_.GetBuffer();
- auto data_ptr = reinterpret_cast<char *>(data(data_vec));
+ auto data_ptr = reinterpret_cast<char*>(data(data_vec));
return !parser.flex_builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(), data_ptr,
@@ -52,12 +52,12 @@
return !parser.builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(),
- reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
+ reinterpret_cast<char*>(parser.builder_.GetBufferPointer()),
parser.builder_.GetSize(), true);
}
-static std::string BinaryMakeRule(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static std::string BinaryMakeRule(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
if (!parser.builder_.GetSize()) return "";
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
@@ -73,36 +73,37 @@
class BinaryCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateBinary(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateBinary(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
output = BinaryMakeRule(parser, path, filename);
return Status::OK;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_cpp.cpp b/src/idl_gen_cpp.cpp
index 1fa0665..38f68b7 100644
--- a/src/idl_gen_cpp.cpp
+++ b/src/idl_gen_cpp.cpp
@@ -40,19 +40,21 @@
switch (type) {
case BASE_TYPE_INT:
return (val != "-2147483648") ? val : ("(-2147483647 - 1)");
- case BASE_TYPE_ULONG: return (val == "0") ? val : (val + "ULL");
+ case BASE_TYPE_ULONG:
+ return (val == "0") ? val : (val + "ULL");
case BASE_TYPE_LONG:
if (val == "-9223372036854775808")
return "(-9223372036854775807LL - 1LL)";
else
return (val == "0") ? val : (val + "LL");
- default: return val;
+ default:
+ return val;
}
}
-static std::string GenIncludeGuard(const std::string &file_name,
- const Namespace &name_space,
- const std::string &postfix = "") {
+static std::string GenIncludeGuard(const std::string& file_name,
+ const Namespace& name_space,
+ const std::string& postfix = "") {
// Generate include guard.
std::string guard = file_name;
// Remove any non-alpha-numeric characters that may appear in a filename.
@@ -64,24 +66,26 @@
guard = "FLATBUFFERS_GENERATED_" + guard;
guard += "_";
// For further uniqueness, also add the namespace.
- for (const std::string &component : name_space.components) {
+ for (const std::string& component : name_space.components) {
guard += component + "_";
}
// Anything extra to add to the guard?
- if (!postfix.empty()) { guard += postfix + "_"; }
+ if (!postfix.empty()) {
+ guard += postfix + "_";
+ }
guard += "H_";
std::transform(guard.begin(), guard.end(), guard.begin(), CharToUpper);
return guard;
}
-static bool IsVectorOfPointers(const FieldDef &field) {
- const auto &type = field.value.type;
- const auto &vector_type = type.VectorType();
+static bool IsVectorOfPointers(const FieldDef& field) {
+ const auto& type = field.value.type;
+ const auto& vector_type = type.VectorType();
return IsVector(type) && vector_type.base_type == BASE_TYPE_STRUCT &&
!vector_type.struct_def->fixed && !field.native_inline;
}
-static bool IsPointer(const FieldDef &field) {
+static bool IsPointer(const FieldDef& field) {
return field.value.type.base_type == BASE_TYPE_STRUCT &&
!IsStruct(field.value.type);
}
@@ -102,132 +106,136 @@
CppStandard g_cpp_std; // Base version of C++ standard.
bool g_only_fixed_enums; // Generate underlaying type for all enums.
- IDLOptionsCpp(const IDLOptions &opts)
+ IDLOptionsCpp(const IDLOptions& opts)
: IDLOptions(opts), g_cpp_std(CPP_STD_11), g_only_fixed_enums(true) {}
};
// Iterates over all the fields of the object first by Offset type (Offset64
// before Offset32) and then by definition order.
static void ForAllFieldsOrderedByOffset(
- const StructDef &object, std::function<void(const FieldDef *field)> func) {
+ const StructDef& object, std::function<void(const FieldDef* field)> func) {
// Loop over all the fields and call the func on all offset64 fields.
- for (const FieldDef *field_def : object.fields.vec) {
- if (field_def->offset64) { func(field_def); }
+ for (const FieldDef* field_def : object.fields.vec) {
+ if (field_def->offset64) {
+ func(field_def);
+ }
}
// Loop over all the fields a second time and call the func on all offset
// fields.
- for (const FieldDef *field_def : object.fields.vec) {
- if (!field_def->offset64) { func(field_def); }
+ for (const FieldDef* field_def : object.fields.vec) {
+ if (!field_def->offset64) {
+ func(field_def);
+ }
}
}
class CppGenerator : public BaseGenerator {
public:
- CppGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name, IDLOptionsCpp opts)
+ CppGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name, IDLOptionsCpp opts)
: BaseGenerator(parser, path, file_name, "", "::", "h"),
cur_name_space_(nullptr),
opts_(opts),
float_const_gen_("std::numeric_limits<double>::",
"std::numeric_limits<float>::", "quiet_NaN()",
"infinity()") {
- static const char *const keywords[] = {
- "alignas",
- "alignof",
- "and",
- "and_eq",
- "asm",
- "atomic_cancel",
- "atomic_commit",
- "atomic_noexcept",
- "auto",
- "bitand",
- "bitor",
- "bool",
- "break",
- "case",
- "catch",
- "char",
- "char16_t",
- "char32_t",
- "class",
- "compl",
- "concept",
- "const",
- "constexpr",
- "const_cast",
- "continue",
- "co_await",
- "co_return",
- "co_yield",
- "decltype",
- "default",
- "delete",
- "do",
- "double",
- "dynamic_cast",
- "else",
- "enum",
- "explicit",
- "export",
- "extern",
- "false",
- "float",
- "for",
- "friend",
- "goto",
- "if",
- "import",
- "inline",
- "int",
- "long",
- "module",
- "mutable",
- "namespace",
- "new",
- "noexcept",
- "not",
- "not_eq",
- "nullptr",
- "operator",
- "or",
- "or_eq",
- "private",
- "protected",
- "public",
- "register",
- "reinterpret_cast",
- "requires",
- "return",
- "short",
- "signed",
- "sizeof",
- "static",
- "static_assert",
- "static_cast",
- "struct",
- "switch",
- "synchronized",
- "template",
- "this",
- "thread_local",
- "throw",
- "true",
- "try",
- "typedef",
- "typeid",
- "typename",
- "union",
- "unsigned",
- "using",
- "virtual",
- "void",
- "volatile",
- "wchar_t",
- "while",
- "xor",
- "xor_eq",
- nullptr,
+ static const char* const keywords[] = {
+ "alignas",
+ "alignof",
+ "and",
+ "and_eq",
+ "asm",
+ "atomic_cancel",
+ "atomic_commit",
+ "atomic_noexcept",
+ "auto",
+ "bitand",
+ "bitor",
+ "bool",
+ "break",
+ "case",
+ "catch",
+ "char",
+ "char16_t",
+ "char32_t",
+ "class",
+ "compl",
+ "concept",
+ "const",
+ "constexpr",
+ "const_cast",
+ "continue",
+ "co_await",
+ "co_return",
+ "co_yield",
+ "decltype",
+ "default",
+ "delete",
+ "do",
+ "double",
+ "dynamic_cast",
+ "else",
+ "enum",
+ "explicit",
+ "export",
+ "extern",
+ "false",
+ "float",
+ "for",
+ "friend",
+ "goto",
+ "if",
+ "import",
+ "inline",
+ "int",
+ "long",
+ "module",
+ "mutable",
+ "namespace",
+ "new",
+ "noexcept",
+ "not",
+ "not_eq",
+ "nullptr",
+ "operator",
+ "or",
+ "or_eq",
+ "private",
+ "protected",
+ "public",
+ "register",
+ "reinterpret_cast",
+ "requires",
+ "return",
+ "short",
+ "signed",
+ "sizeof",
+ "static",
+ "static_assert",
+ "static_cast",
+ "struct",
+ "switch",
+ "synchronized",
+ "template",
+ "this",
+ "thread_local",
+ "throw",
+ "true",
+ "try",
+ "typedef",
+ "typeid",
+ "typename",
+ "union",
+ "unsigned",
+ "using",
+ "virtual",
+ "void",
+ "volatile",
+ "wchar_t",
+ "while",
+ "xor",
+ "xor_eq",
+ nullptr,
};
for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
}
@@ -253,7 +261,7 @@
void GenIncludeDependencies() {
if (opts_.generate_object_based_api) {
- for (const std::string &native_included_file :
+ for (const std::string& native_included_file :
parser_.native_included_files_) {
code_ += "#include \"" + native_included_file + "\"";
}
@@ -266,7 +274,7 @@
// interdependence between them.
std::stable_sort(included_files.begin(), included_files.end());
- for (const IncludedFile &included_file : included_files) {
+ for (const IncludedFile& included_file : included_files) {
// Get the name of the included file as defined by the schema, and strip
// the .fbs extension.
const std::string name_without_ext =
@@ -288,7 +296,9 @@
}
void MarkIf64BitBuilderIsNeeded() {
- if (needs_64_bit_builder_) { return; }
+ if (needs_64_bit_builder_) {
+ return;
+ }
for (auto t : parser_.structs_.vec) {
if (t == nullptr) continue;
for (auto f : t->fields.vec) {
@@ -307,10 +317,12 @@
}
void GenExtraIncludes() {
- for (const std::string &cpp_include : opts_.cpp_includes) {
+ for (const std::string& cpp_include : opts_.cpp_includes) {
code_ += "#include \"" + cpp_include + "\"";
}
- if (!opts_.cpp_includes.empty()) { code_ += ""; }
+ if (!opts_.cpp_includes.empty()) {
+ code_ += "";
+ }
}
void GenEmbeddedIncludes() {
@@ -323,11 +335,11 @@
}
}
- std::string EscapeKeyword(const std::string &name) const {
+ std::string EscapeKeyword(const std::string& name) const {
return keywords_.find(name) == keywords_.end() ? name : name + "_";
}
- std::string Name(const FieldDef &field) const {
+ std::string Name(const FieldDef& field) const {
// the union type field suffix is immutable.
static size_t union_suffix_len = strlen(UnionTypeFieldSuffix());
const bool is_union_type = field.value.type.base_type == BASE_TYPE_UTYPE;
@@ -351,11 +363,11 @@
return EscapeKeyword(name);
}
- std::string Name(const Definition &def) const {
+ std::string Name(const Definition& def) const {
return EscapeKeyword(def.name);
}
- std::string Name(const EnumVal &ev) const { return EscapeKeyword(ev.name); }
+ std::string Name(const EnumVal& ev) const { return EscapeKeyword(ev.name); }
bool generate_bfbs_embed() {
code_.Clear();
@@ -366,7 +378,7 @@
// put a comment in the output why there is no code generated.
code_ += "// Binary schema not generated, no root struct found";
} else {
- auto &struct_def = *parser_.root_struct_def_;
+ auto& struct_def = *parser_.root_struct_def_;
const auto include_guard =
GenIncludeGuard(file_name_, *struct_def.defined_namespace, "bfbs");
@@ -439,7 +451,9 @@
code_ += "#define " + include_guard;
code_ += "";
- if (opts_.gen_nullable) { code_ += "#pragma clang system_header\n\n"; }
+ if (opts_.gen_nullable) {
+ code_ += "#pragma clang system_header\n\n";
+ }
code_ += "#include \"flatbuffers/flatbuffers.h\"";
if (parser_.uses_flexbuffers_) {
@@ -450,7 +464,9 @@
GenFlatbuffersVersionCheck();
code_ += "";
- if (opts_.include_dependence_headers) { GenIncludeDependencies(); }
+ if (opts_.include_dependence_headers) {
+ GenIncludeDependencies();
+ }
GenExtraIncludes();
GenEmbeddedIncludes();
@@ -458,7 +474,7 @@
// Generate forward declarations for all structs/tables, since they may
// have circular references.
- for (const auto &struct_def : parser_.structs_.vec) {
+ for (const auto& struct_def : parser_.structs_.vec) {
if (!struct_def->generated) {
SetNameSpace(struct_def->defined_namespace);
code_ += "struct " + Name(*struct_def) + ";";
@@ -469,7 +485,7 @@
auto nativeName = NativeName(Name(*struct_def), struct_def, opts_);
// Check that nativeName doesn't collide the name of another struct.
- for (const auto &other_struct_def : parser_.structs_.vec) {
+ for (const auto& other_struct_def : parser_.structs_.vec) {
if (other_struct_def == struct_def ||
other_struct_def->defined_namespace !=
struct_def->defined_namespace) {
@@ -485,7 +501,9 @@
}
}
- if (!struct_def->fixed) { code_ += "struct " + nativeName + ";"; }
+ if (!struct_def->fixed) {
+ code_ += "struct " + nativeName + ";";
+ }
}
code_ += "";
}
@@ -493,7 +511,7 @@
// Generate forward declarations for all equal operators
if (opts_.generate_object_based_api && opts_.gen_compare) {
- for (const auto &struct_def : parser_.structs_.vec) {
+ for (const auto& struct_def : parser_.structs_.vec) {
if (!struct_def->generated) {
SetNameSpace(struct_def->defined_namespace);
auto nativeName = NativeName(Name(*struct_def), struct_def, opts_);
@@ -509,7 +527,7 @@
// Generate preablmle code for mini reflection.
if (opts_.mini_reflect != IDLOptions::kNone) {
// To break cyclic dependencies, first pre-declare all tables/structs.
- for (const auto &struct_def : parser_.structs_.vec) {
+ for (const auto& struct_def : parser_.structs_.vec) {
if (!struct_def->generated) {
SetNameSpace(struct_def->defined_namespace);
GenMiniReflectPre(struct_def);
@@ -518,7 +536,7 @@
}
// Generate code for all the enum declarations.
- for (const auto &enum_def : parser_.enums_.vec) {
+ for (const auto& enum_def : parser_.enums_.vec) {
if (!enum_def->generated) {
SetNameSpace(enum_def->defined_namespace);
GenEnum(*enum_def);
@@ -526,19 +544,19 @@
}
// Generate code for all structs, then all tables.
- for (const auto &struct_def : parser_.structs_.vec) {
+ for (const auto& struct_def : parser_.structs_.vec) {
if (struct_def->fixed && !struct_def->generated) {
SetNameSpace(struct_def->defined_namespace);
GenStruct(*struct_def);
}
}
- for (const auto &struct_def : parser_.structs_.vec) {
+ for (const auto& struct_def : parser_.structs_.vec) {
if (!struct_def->fixed && !struct_def->generated) {
SetNameSpace(struct_def->defined_namespace);
GenTable(*struct_def);
}
}
- for (const auto &struct_def : parser_.structs_.vec) {
+ for (const auto& struct_def : parser_.structs_.vec) {
if (!struct_def->fixed && !struct_def->generated) {
SetNameSpace(struct_def->defined_namespace);
GenTablePost(*struct_def);
@@ -546,7 +564,7 @@
}
// Generate code for union verifiers.
- for (const auto &enum_def : parser_.enums_.vec) {
+ for (const auto& enum_def : parser_.enums_.vec) {
if (enum_def->is_union && !enum_def->generated) {
SetNameSpace(enum_def->defined_namespace);
GenUnionPost(*enum_def);
@@ -556,14 +574,14 @@
// Generate code for mini reflection.
if (opts_.mini_reflect != IDLOptions::kNone) {
// Then the unions/enums that may refer to them.
- for (const auto &enum_def : parser_.enums_.vec) {
+ for (const auto& enum_def : parser_.enums_.vec) {
if (!enum_def->generated) {
SetNameSpace(enum_def->defined_namespace);
GenMiniReflect(nullptr, enum_def);
}
}
// Then the full tables/structs.
- for (const auto &struct_def : parser_.structs_.vec) {
+ for (const auto& struct_def : parser_.structs_.vec) {
if (!struct_def->generated) {
SetNameSpace(struct_def->defined_namespace);
GenMiniReflect(struct_def, nullptr);
@@ -573,7 +591,7 @@
// Generate convenient global helper functions:
if (parser_.root_struct_def_) {
- auto &struct_def = *parser_.root_struct_def_;
+ auto& struct_def = *parser_.root_struct_def_;
SetNameSpace(struct_def.defined_namespace);
auto name = Name(struct_def);
auto qualified_name = cur_name_space_->GetFullyQualifiedName(name);
@@ -749,17 +767,17 @@
std::unordered_set<std::string> keywords_;
// This tracks the current namespace so we can insert namespace declarations.
- const Namespace *cur_name_space_;
+ const Namespace* cur_name_space_;
const IDLOptionsCpp opts_;
const TypedFloatConstantGenerator float_const_gen_;
bool needs_64_bit_builder_ = false;
- const Namespace *CurrentNameSpace() const { return cur_name_space_; }
+ const Namespace* CurrentNameSpace() const { return cur_name_space_; }
// Translates a qualified name in flatbuffer text format to the same name in
// the equivalent C++ namespace.
- static std::string TranslateNameSpace(const std::string &qualified_name) {
+ static std::string TranslateNameSpace(const std::string& qualified_name) {
std::string cpp_qualified_name = qualified_name;
size_t start_pos = 0;
while ((start_pos = cpp_qualified_name.find('.', start_pos)) !=
@@ -769,28 +787,32 @@
return cpp_qualified_name;
}
- bool TypeHasKey(const Type &type) {
- if (type.base_type != BASE_TYPE_STRUCT) { return false; }
- for (auto &field : type.struct_def->fields.vec) {
- if (field->key) { return true; }
+ bool TypeHasKey(const Type& type) {
+ if (type.base_type != BASE_TYPE_STRUCT) {
+ return false;
+ }
+ for (auto& field : type.struct_def->fields.vec) {
+ if (field->key) {
+ return true;
+ }
}
return false;
}
- bool VectorElementUserFacing(const Type &type) const {
+ bool VectorElementUserFacing(const Type& type) const {
return (opts_.scoped_enums && IsEnum(type)) ||
(opts_.g_cpp_std >= cpp::CPP_STD_17 && opts_.g_only_fixed_enums &&
IsEnum(type));
}
- void GenComment(const std::vector<std::string> &dc, const char *prefix = "") {
+ void GenComment(const std::vector<std::string>& dc, const char* prefix = "") {
std::string text;
::flatbuffers::GenComment(dc, &text, nullptr, prefix);
code_ += text + "\\";
}
// Return a C++ type from the table in idl.h
- std::string GenTypeBasic(const Type &type, bool user_facing_type) const {
+ std::string GenTypeBasic(const Type& type, bool user_facing_type) const {
if (user_facing_type) {
if (type.enum_def) return WrapInNameSpace(*type.enum_def);
if (type.base_type == BASE_TYPE_BOOL) return "bool";
@@ -805,7 +827,7 @@
// Return a C++ pointer type, specialized to the actual struct/table types,
// and vector element types.
- std::string GenTypePointer(const Type &type) const {
+ std::string GenTypePointer(const Type& type) const {
switch (type.base_type) {
case BASE_TYPE_STRING: {
return "::flatbuffers::String";
@@ -832,7 +854,7 @@
// Return a C++ type for any type (scalar/pointer) specifically for
// building a flatbuffer.
- std::string GenTypeWire(const Type &type, const char *postfix,
+ std::string GenTypeWire(const Type& type, const char* postfix,
bool user_facing_type,
bool _64_bit_offset = false) const {
if (IsScalar(type.base_type)) {
@@ -847,7 +869,7 @@
// Return a C++ type for any type (scalar/pointer) that reflects its
// serialized size.
- std::string GenTypeSize(const Type &type) const {
+ std::string GenTypeSize(const Type& type) const {
if (IsScalar(type.base_type)) {
return GenTypeBasic(type, false);
} else if (IsStruct(type)) {
@@ -861,31 +883,33 @@
return opts_.gen_nullable ? " _Nullable " : "";
}
- static std::string NativeName(const std::string &name, const StructDef *sd,
- const IDLOptions &opts) {
+ static std::string NativeName(const std::string& name, const StructDef* sd,
+ const IDLOptions& opts) {
return sd && !sd->fixed ? opts.object_prefix + name + opts.object_suffix
: name;
}
- std::string WrapNativeNameInNameSpace(const StructDef &struct_def,
- const IDLOptions &opts) {
+ std::string WrapNativeNameInNameSpace(const StructDef& struct_def,
+ const IDLOptions& opts) {
return WrapInNameSpace(struct_def.defined_namespace,
NativeName(Name(struct_def), &struct_def, opts));
}
- const std::string &PtrType(const FieldDef *field) {
+ const std::string& PtrType(const FieldDef* field) {
auto attr = field ? field->attributes.Lookup("cpp_ptr_type") : nullptr;
return attr ? attr->constant : opts_.cpp_object_api_pointer_type;
}
- const std::string NativeString(const FieldDef *field) {
+ const std::string NativeString(const FieldDef* field) {
auto attr = field ? field->attributes.Lookup("cpp_str_type") : nullptr;
- auto &ret = attr ? attr->constant : opts_.cpp_object_api_string_type;
- if (ret.empty()) { return "std::string"; }
+ auto& ret = attr ? attr->constant : opts_.cpp_object_api_string_type;
+ if (ret.empty()) {
+ return "std::string";
+ }
return ret;
}
- bool FlexibleStringConstructor(const FieldDef *field) {
+ bool FlexibleStringConstructor(const FieldDef* field) {
auto attr = field != nullptr &&
(field->attributes.Lookup("cpp_str_flex_ctor") != nullptr);
auto ret = attr ? attr : opts_.cpp_object_api_string_flexible_constructor;
@@ -893,9 +917,9 @@
"std::string"; // Only for custom string types.
}
- std::string GenTypeNativePtr(const std::string &type, const FieldDef *field,
+ std::string GenTypeNativePtr(const std::string& type, const FieldDef* field,
bool is_constructor) {
- auto &ptr_type = PtrType(field);
+ auto& ptr_type = PtrType(field);
if (ptr_type != "naked") {
return (ptr_type != "default_ptr_type"
? ptr_type
@@ -908,21 +932,21 @@
}
}
- std::string GenPtrGet(const FieldDef &field) {
+ std::string GenPtrGet(const FieldDef& field) {
auto cpp_ptr_type_get = field.attributes.Lookup("cpp_ptr_type_get");
if (cpp_ptr_type_get) return cpp_ptr_type_get->constant;
- auto &ptr_type = PtrType(&field);
+ auto& ptr_type = PtrType(&field);
return ptr_type == "naked" ? "" : ".get()";
}
std::string GenOptionalNull() { return "::flatbuffers::nullopt"; }
- std::string GenOptionalDecl(const Type &type) {
+ std::string GenOptionalDecl(const Type& type) {
return "::flatbuffers::Optional<" + GenTypeBasic(type, true) + ">";
}
- std::string GenTypeNative(const Type &type, bool invector,
- const FieldDef &field, bool forcopy = false) {
+ std::string GenTypeNative(const Type& type, bool invector,
+ const FieldDef& field, bool forcopy = false) {
switch (type.base_type) {
case BASE_TYPE_STRING: {
return NativeString(&field);
@@ -944,7 +968,9 @@
auto type_name = WrapInNameSpace(*type.struct_def);
if (IsStruct(type)) {
auto native_type = type.struct_def->attributes.Lookup("native_type");
- if (native_type) { type_name = native_type->constant; }
+ if (native_type) {
+ type_name = native_type->constant;
+ }
if (invector || field.native_inline || forcopy) {
return type_name;
} else {
@@ -970,8 +996,8 @@
// Return a C++ type for any type (scalar/pointer) specifically for
// using a flatbuffer.
- std::string GenTypeGet(const Type &type, const char *afterbasic,
- const char *beforeptr, const char *afterptr,
+ std::string GenTypeGet(const Type& type, const char* afterbasic,
+ const char* beforeptr, const char* afterptr,
bool user_facing_type) {
if (IsScalar(type.base_type)) {
return GenTypeBasic(type, user_facing_type) + afterbasic;
@@ -993,7 +1019,7 @@
}
}
- std::string GenTypeSpan(const Type &type, bool immutable, size_t extent) {
+ std::string GenTypeSpan(const Type& type, bool immutable, size_t extent) {
// Generate "::flatbuffers::span<const U, extent>".
FLATBUFFERS_ASSERT(IsSeries(type) && "unexpected type");
auto element_type = type.VectorType();
@@ -1025,13 +1051,13 @@
return text;
}
- std::string GenEnumValDecl(const EnumDef &enum_def,
- const std::string &enum_val) const {
+ std::string GenEnumValDecl(const EnumDef& enum_def,
+ const std::string& enum_val) const {
return opts_.prefixed_enums ? Name(enum_def) + "_" + enum_val : enum_val;
}
- std::string GetEnumValUse(const EnumDef &enum_def,
- const EnumVal &enum_val) const {
+ std::string GetEnumValUse(const EnumDef& enum_def,
+ const EnumVal& enum_val) const {
if (opts_.scoped_enums) {
return Name(enum_def) + "::" + Name(enum_val);
} else if (opts_.prefixed_enums) {
@@ -1041,12 +1067,12 @@
}
}
- std::string StripUnionType(const std::string &name) {
+ std::string StripUnionType(const std::string& name) {
return name.substr(0, name.size() - strlen(UnionTypeFieldSuffix()));
}
- std::string GetUnionElement(const EnumVal &ev, bool native_type,
- const IDLOptions &opts) {
+ std::string GetUnionElement(const EnumVal& ev, bool native_type,
+ const IDLOptions& opts) {
if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
std::string name = ev.union_type.struct_def->name;
if (native_type) {
@@ -1061,15 +1087,15 @@
}
}
- std::string UnionVerifySignature(const EnumDef &enum_def) {
+ std::string UnionVerifySignature(const EnumDef& enum_def) {
return "bool Verify" + Name(enum_def) +
"(::flatbuffers::Verifier &verifier, const void *obj, " +
Name(enum_def) + " type)";
}
- std::string UnionVectorVerifySignature(const EnumDef &enum_def) {
+ std::string UnionVectorVerifySignature(const EnumDef& enum_def) {
const std::string name = Name(enum_def);
- const std::string &type =
+ const std::string& type =
opts_.scoped_enums ? name
: GenTypeBasic(enum_def.underlying_type, false);
return "bool Verify" + name + "Vector" +
@@ -1079,14 +1105,14 @@
"const ::flatbuffers::Vector<" + type + "> *types)";
}
- std::string UnionUnPackSignature(const EnumDef &enum_def, bool inclass) {
+ std::string UnionUnPackSignature(const EnumDef& enum_def, bool inclass) {
return (inclass ? "static " : "") + std::string("void *") +
(inclass ? "" : Name(enum_def) + "Union::") +
"UnPack(const void *obj, " + Name(enum_def) +
" type, const ::flatbuffers::resolver_function_t *resolver)";
}
- std::string UnionPackSignature(const EnumDef &enum_def, bool inclass) {
+ std::string UnionPackSignature(const EnumDef& enum_def, bool inclass) {
return "::flatbuffers::Offset<void> " +
(inclass ? "" : Name(enum_def) + "Union::") + "Pack(" +
GetBuilder() + " &_fbb, " +
@@ -1094,8 +1120,8 @@
(inclass ? " = nullptr" : "") + ") const";
}
- std::string TableCreateSignature(const StructDef &struct_def, bool predecl,
- const IDLOptions &opts) {
+ std::string TableCreateSignature(const StructDef& struct_def, bool predecl,
+ const IDLOptions& opts) {
return "::flatbuffers::Offset<" + Name(struct_def) + "> Create" +
Name(struct_def) + "(" + GetBuilder() + " &_fbb, const " +
NativeName(Name(struct_def), &struct_def, opts) +
@@ -1103,8 +1129,8 @@
(predecl ? " = nullptr" : "") + ")";
}
- std::string TablePackSignature(const StructDef &struct_def, bool inclass,
- const IDLOptions &opts) {
+ std::string TablePackSignature(const StructDef& struct_def, bool inclass,
+ const IDLOptions& opts) {
return std::string(inclass ? "static " : "") + "::flatbuffers::Offset<" +
Name(struct_def) + "> " + (inclass ? "" : Name(struct_def) + "::") +
"Pack(" + GetBuilder() + " &_fbb, " + "const " +
@@ -1113,29 +1139,29 @@
(inclass ? " = nullptr" : "") + ")";
}
- std::string TableUnPackSignature(const StructDef &struct_def, bool inclass,
- const IDLOptions &opts) {
+ std::string TableUnPackSignature(const StructDef& struct_def, bool inclass,
+ const IDLOptions& opts) {
return NativeName(Name(struct_def), &struct_def, opts) + " *" +
(inclass ? "" : Name(struct_def) + "::") +
"UnPack(const ::flatbuffers::resolver_function_t *_resolver" +
(inclass ? " = nullptr" : "") + ") const";
}
- std::string TableUnPackToSignature(const StructDef &struct_def, bool inclass,
- const IDLOptions &opts) {
+ std::string TableUnPackToSignature(const StructDef& struct_def, bool inclass,
+ const IDLOptions& opts) {
return "void " + (inclass ? "" : Name(struct_def) + "::") + "UnPackTo(" +
NativeName(Name(struct_def), &struct_def, opts) + " *" +
"_o, const ::flatbuffers::resolver_function_t *_resolver" +
(inclass ? " = nullptr" : "") + ") const";
}
- void GenMiniReflectPre(const StructDef *struct_def) {
+ void GenMiniReflectPre(const StructDef* struct_def) {
code_.SetValue("NAME", struct_def->name);
code_ += "inline const ::flatbuffers::TypeTable *{{NAME}}TypeTable();";
code_ += "";
}
- void GenMiniReflect(const StructDef *struct_def, const EnumDef *enum_def) {
+ void GenMiniReflect(const StructDef* struct_def, const EnumDef* enum_def) {
code_.SetValue("NAME", struct_def ? struct_def->name : enum_def->name);
code_.SetValue("SEQ_TYPE",
struct_def ? (struct_def->fixed ? "ST_STRUCT" : "ST_TABLE")
@@ -1147,14 +1173,14 @@
std::vector<Type> types;
if (struct_def) {
- for (const auto &field : struct_def->fields.vec) {
+ for (const auto& field : struct_def->fields.vec) {
names.push_back(Name(*field));
types.push_back(field->value.type);
}
} else {
for (auto it = enum_def->Vals().begin(); it != enum_def->Vals().end();
++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
names.push_back(Name(ev));
types.push_back(enum_def->is_union ? ev.union_type
: Type(enum_def->underlying_type));
@@ -1163,7 +1189,7 @@
std::string ts;
std::vector<std::string> type_refs;
std::vector<uint16_t> array_sizes;
- for (auto &type : types) {
+ for (auto& type : types) {
if (!ts.empty()) ts += ",\n ";
auto is_vector = IsVector(type);
auto is_array = IsArray(type);
@@ -1188,23 +1214,25 @@
type_refs.push_back(ref_name);
}
}
- if (is_array) { array_sizes.push_back(type.fixed_length); }
+ if (is_array) {
+ array_sizes.push_back(type.fixed_length);
+ }
ts += "{ ::flatbuffers::" + std::string(ElementaryTypeNames()[et]) +
", " + NumToString(is_vector || is_array) + ", " +
NumToString(ref_idx) + " }";
}
std::string rs;
- for (auto &type_ref : type_refs) {
+ for (auto& type_ref : type_refs) {
if (!rs.empty()) rs += ",\n ";
rs += type_ref + "TypeTable";
}
std::string as;
- for (auto &array_size : array_sizes) {
+ for (auto& array_size : array_sizes) {
as += NumToString(array_size);
as += ", ";
}
std::string ns;
- for (auto &name : names) {
+ for (auto& name : names) {
if (!ns.empty()) ns += ",\n ";
ns += "\"" + name + "\"";
}
@@ -1215,7 +1243,7 @@
if (enum_def && !consecutive_enum_from_zero) {
for (auto it = enum_def->Vals().begin(); it != enum_def->Vals().end();
++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
if (!vs.empty()) vs += ", ";
vs += NumToStringCpp(enum_def->ToString(ev),
enum_def->underlying_type.base_type);
@@ -1274,14 +1302,16 @@
// an enum string lookup table,
// and an enum array of values
- void GenEnum(const EnumDef &enum_def) {
+ void GenEnum(const EnumDef& enum_def) {
code_.SetValue("ENUM_NAME", Name(enum_def));
code_.SetValue("BASE_TYPE", GenTypeBasic(enum_def.underlying_type, false));
GenComment(enum_def.doc_comment);
code_ +=
(opts_.scoped_enums ? "enum class " : "enum ") + Name(enum_def) + "\\";
- if (opts_.g_only_fixed_enums) { code_ += " : {{BASE_TYPE}}\\"; }
+ if (opts_.g_only_fixed_enums) {
+ code_ += " : {{BASE_TYPE}}\\";
+ }
code_ += " {";
code_.SetValue("SEP", ",");
@@ -1301,8 +1331,8 @@
code_ += "};";
return;
}
- const EnumVal *minv = enum_def.MinValue();
- const EnumVal *maxv = enum_def.MaxValue();
+ const EnumVal* minv = enum_def.MinValue();
+ const EnumVal* maxv = enum_def.MaxValue();
if (opts_.scoped_enums || opts_.prefixed_enums) {
FLATBUFFERS_ASSERT(minv && maxv);
@@ -1345,7 +1375,7 @@
if (enum_def.is_union && !enum_def.uses_multiple_type_instances) {
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
if (it == enum_def.Vals().begin()) {
code_ += "template<typename T> struct {{ENUM_NAME}}Traits {";
@@ -1371,8 +1401,10 @@
}
// Generate a union type and a trait type for it.
- void GenEnumObjectBasedAPI(const EnumDef &enum_def) {
- if (!(opts_.generate_object_based_api && enum_def.is_union)) { return; }
+ void GenEnumObjectBasedAPI(const EnumDef& enum_def) {
+ if (!(opts_.generate_object_based_api && enum_def.is_union)) {
+ return;
+ }
code_.SetValue("NAME", Name(enum_def));
FLATBUFFERS_ASSERT(enum_def.Lookup("NONE"));
code_.SetValue("NONE", GetEnumValUse(enum_def, *enum_def.Lookup("NONE")));
@@ -1380,7 +1412,7 @@
if (!enum_def.uses_multiple_type_instances) {
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
if (it == enum_def.Vals().begin()) {
code_ += "template<typename T> struct {{NAME}}UnionTraits {";
@@ -1435,7 +1467,9 @@
code_ += "";
for (const auto ev : enum_def.Vals()) {
- if (ev->IsZero()) { continue; }
+ if (ev->IsZero()) {
+ continue;
+ }
const auto native_type = GetUnionElement(*ev, true, opts_);
code_.SetValue("NATIVE_TYPE", native_type);
@@ -1459,7 +1493,7 @@
GenEnumEquals(enum_def);
}
- void GenEnumEquals(const EnumDef &enum_def) {
+ void GenEnumEquals(const EnumDef& enum_def) {
if (opts_.gen_compare) {
code_ += "";
code_ +=
@@ -1468,7 +1502,7 @@
code_ += " if (lhs.type != rhs.type) return false;";
code_ += " switch (lhs.type) {";
- for (const auto &ev : enum_def.Vals()) {
+ for (const auto& ev : enum_def.Vals()) {
code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, *ev));
if (ev->IsNonZero()) {
const auto native_type = GetUnionElement(*ev, true, opts_);
@@ -1504,13 +1538,13 @@
}
// Generate an array of all enumeration values
- void GenEnumArray(const EnumDef &enum_def) {
+ void GenEnumArray(const EnumDef& enum_def) {
auto num_fields = NumToString(enum_def.size());
code_ += "inline const {{ENUM_NAME}} (&EnumValues{{ENUM_NAME}}())[" +
num_fields + "] {";
code_ += " static const {{ENUM_NAME}} values[] = {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
auto value = GetEnumValUse(enum_def, ev);
auto suffix = *it != enum_def.Vals().back() ? "," : "";
code_ += " " + value + suffix;
@@ -1525,7 +1559,7 @@
// Problem is, if values are very sparse that could generate huge tables.
// Ideally in that case we generate a map lookup instead, but for the moment
// we simply don't output a table at all.
- void GenEnumStringTable(const EnumDef &enum_def) {
+ void GenEnumStringTable(const EnumDef& enum_def) {
auto range = enum_def.Distance();
// Average distance between values above which we consider a table
// "too sparse". Change at will.
@@ -1536,7 +1570,7 @@
NumToString(range + 1 + 1) + "] = {";
auto val = enum_def.Vals().front();
- for (const auto &enum_value : enum_def.Vals()) {
+ for (const auto& enum_value : enum_def.Vals()) {
for (auto k = enum_def.Distance(val, enum_value); k > 1; --k) {
code_ += " \"\",";
}
@@ -1570,7 +1604,7 @@
} else {
code_ += "inline const char *EnumName{{ENUM_NAME}}({{ENUM_NAME}} e) {";
code_ += " switch (e) {";
- for (const auto &ev : enum_def.Vals()) {
+ for (const auto& ev : enum_def.Vals()) {
code_ += " case " + GetEnumValUse(enum_def, *ev) + ": return \"" +
Name(*ev) + "\";";
}
@@ -1581,7 +1615,7 @@
}
}
- void GenUnionPost(const EnumDef &enum_def) {
+ void GenUnionPost(const EnumDef& enum_def) {
// Generate a verifier function for this union that can be called by the
// table verifier functions. It uses a switch case to select a specific
// verifier function to call, this should be safe even if the union type
@@ -1592,7 +1626,7 @@
code_ += "inline " + UnionVerifySignature(enum_def) + " {";
code_ += " switch (type) {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
if (ev.IsNonZero()) {
@@ -1651,8 +1685,10 @@
code_ += " switch (type) {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
- const auto &ev = **it;
- if (ev.IsZero()) { continue; }
+ const auto& ev = **it;
+ if (ev.IsZero()) {
+ continue;
+ }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
code_.SetValue("TYPE", GetUnionElement(ev, false, opts_));
@@ -1682,8 +1718,10 @@
code_ += " switch (type) {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
- auto &ev = **it;
- if (ev.IsZero()) { continue; }
+ auto& ev = **it;
+ if (ev.IsZero()) {
+ continue;
+ }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
code_.SetValue("TYPE", GetUnionElement(ev, true, opts_));
@@ -1714,8 +1752,10 @@
"inline {{ENUM_NAME}}Union::{{ENUM_NAME}}Union(const "
"{{ENUM_NAME}}Union &u) : type(u.type), value(nullptr) {";
code_ += " switch (type) {";
- for (const auto &ev : enum_def.Vals()) {
- if (ev->IsZero()) { continue; }
+ for (const auto& ev : enum_def.Vals()) {
+ if (ev->IsZero()) {
+ continue;
+ }
code_.SetValue("LABEL", GetEnumValUse(enum_def, *ev));
code_.SetValue("TYPE", GetUnionElement(*ev, true, opts_));
code_ += " case {{LABEL}}: {";
@@ -1725,7 +1765,7 @@
!ev->union_type.struct_def->fixed) {
// Don't generate code to copy if table is not copyable.
// TODO(wvo): make tables copyable instead.
- for (const auto &field : ev->union_type.struct_def->fields.vec) {
+ for (const auto& field : ev->union_type.struct_def->fields.vec) {
if (!field->deprecated && field->value.type.struct_def &&
!field->native_inline) {
copyable = false;
@@ -1758,8 +1798,10 @@
code_ += " switch (type) {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
- const auto &ev = **it;
- if (ev.IsZero()) { continue; }
+ const auto& ev = **it;
+ if (ev.IsZero()) {
+ continue;
+ }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
code_.SetValue("TYPE", GetUnionElement(ev, true, opts_));
code_ += " case {{LABEL}}: {";
@@ -1781,8 +1823,8 @@
// different underlying type from its interface type (currently only the
// case for enums. "from" specify the direction, true meaning from the
// underlying type to the interface type.
- std::string GenUnderlyingCast(const FieldDef &field, bool from,
- const std::string &val) {
+ std::string GenUnderlyingCast(const FieldDef& field, bool from,
+ const std::string& val) {
if (from && field.value.type.base_type == BASE_TYPE_BOOL) {
return val + " != 0";
} else if ((field.value.type.enum_def &&
@@ -1795,15 +1837,17 @@
}
}
- std::string GenFieldOffsetName(const FieldDef &field) {
+ std::string GenFieldOffsetName(const FieldDef& field) {
std::string uname = Name(field);
std::transform(uname.begin(), uname.end(), uname.begin(), CharToUpper);
return "VT_" + uname;
}
- void GenFullyQualifiedNameGetter(const StructDef &struct_def,
- const std::string &name) {
- if (!opts_.generate_name_strings) { return; }
+ void GenFullyQualifiedNameGetter(const StructDef& struct_def,
+ const std::string& name) {
+ if (!opts_.generate_name_strings) {
+ return;
+ }
auto fullname = struct_def.defined_namespace->GetFullyQualifiedName(name);
code_.SetValue("NAME", fullname);
code_.SetValue("CONSTEXPR", "FLATBUFFERS_CONSTEXPR_CPP11");
@@ -1812,15 +1856,15 @@
code_ += " }";
}
- std::string GenDefaultConstant(const FieldDef &field) {
+ std::string GenDefaultConstant(const FieldDef& field) {
if (IsFloat(field.value.type.base_type))
return float_const_gen_.GenFloatConstant(field);
else
return NumToStringCpp(field.value.constant, field.value.type.base_type);
}
- std::string GetDefaultScalarValue(const FieldDef &field, bool is_ctor) {
- const auto &type = field.value.type;
+ std::string GetDefaultScalarValue(const FieldDef& field, bool is_ctor) {
+ const auto& type = field.value.type;
if (field.IsScalarOptional()) {
return GenOptionalNull();
} else if (type.enum_def && IsScalar(type.base_type)) {
@@ -1851,7 +1895,7 @@
}
}
- void GenParam(const FieldDef &field, bool direct, const char *prefix) {
+ void GenParam(const FieldDef& field, bool direct, const char* prefix) {
code_.SetValue("PRE", prefix);
code_.SetValue("PARAM_NAME", Name(field));
if (direct && IsString(field.value.type)) {
@@ -1873,7 +1917,7 @@
}
code_.SetValue("PARAM_VALUE", "nullptr");
} else {
- const auto &type = field.value.type;
+ const auto& type = field.value.type;
code_.SetValue("PARAM_VALUE", GetDefaultScalarValue(field, false));
if (field.IsScalarOptional())
code_.SetValue("PARAM_TYPE", GenOptionalDecl(type) + " ");
@@ -1885,14 +1929,14 @@
}
// Generate a member, including a default value for scalars and raw pointers.
- void GenMember(const FieldDef &field) {
+ void GenMember(const FieldDef& field) {
if (!field.deprecated && // Deprecated fields won't be accessible.
field.value.type.base_type != BASE_TYPE_UTYPE &&
(!IsVector(field.value.type) ||
field.value.type.element != BASE_TYPE_UTYPE)) {
auto type = GenTypeNative(field.value.type, false, field);
auto cpp_type = field.attributes.Lookup("cpp_type");
- const std::string &full_type =
+ const std::string& full_type =
(cpp_type
? (IsVector(field.value.type)
? "std::vector<" +
@@ -1927,16 +1971,18 @@
// Returns true if `struct_def` needs a copy constructor and assignment
// operator because it has one or more table members, struct members with a
// custom cpp_type and non-naked pointer type, or vector members of those.
- bool NeedsCopyCtorAssignOp(const StructDef &struct_def) {
- for (const auto &field : struct_def.fields.vec) {
- const auto &type = field->value.type;
+ bool NeedsCopyCtorAssignOp(const StructDef& struct_def) {
+ for (const auto& field : struct_def.fields.vec) {
+ const auto& type = field->value.type;
if (field->deprecated) continue;
if (type.base_type == BASE_TYPE_STRUCT) {
const auto cpp_type = field->attributes.Lookup("cpp_type");
const auto cpp_ptr_type = field->attributes.Lookup("cpp_ptr_type");
const bool is_ptr = !(IsStruct(type) && field->native_inline) ||
(cpp_type && cpp_ptr_type->constant != "naked");
- if (is_ptr) { return true; }
+ if (is_ptr) {
+ return true;
+ }
} else if (IsVector(type)) {
const auto vec_type = type.VectorType();
if (vec_type.base_type == BASE_TYPE_UTYPE) continue;
@@ -1944,7 +1990,9 @@
const auto cpp_ptr_type = field->attributes.Lookup("cpp_ptr_type");
const bool is_ptr = IsVectorOfPointers(*field) ||
(cpp_type && cpp_ptr_type->constant != "naked");
- if (is_ptr) { return true; }
+ if (is_ptr) {
+ return true;
+ }
}
}
return false;
@@ -1952,7 +2000,7 @@
// Generate the default constructor for this struct. Properly initialize all
// scalar members with default values.
- void GenDefaultConstructor(const StructDef &struct_def) {
+ void GenDefaultConstructor(const StructDef& struct_def) {
code_.SetValue("NATIVE_NAME",
NativeName(Name(struct_def), &struct_def, opts_));
// In >= C++11, default member initializers are generated. To allow for
@@ -1968,14 +2016,16 @@
std::string initializer_list;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (!field.deprecated && // Deprecated fields won't be accessible.
field.value.type.base_type != BASE_TYPE_UTYPE) {
auto cpp_type = field.attributes.Lookup("cpp_type");
auto native_default = field.attributes.Lookup("native_default");
// Scalar types get parsed defaults, raw pointers get nullptrs.
if (IsScalar(field.value.type.base_type)) {
- if (!initializer_list.empty()) { initializer_list += ",\n "; }
+ if (!initializer_list.empty()) {
+ initializer_list += ",\n ";
+ }
initializer_list += Name(field);
initializer_list +=
"(" +
@@ -1993,7 +2043,9 @@
}
}
} else if (cpp_type && !IsVector(field.value.type)) {
- if (!initializer_list.empty()) { initializer_list += ",\n "; }
+ if (!initializer_list.empty()) {
+ initializer_list += ",\n ";
+ }
initializer_list += Name(field) + "(0)";
}
}
@@ -2012,7 +2064,7 @@
// declarations if required. Tables that are default-copyable do not get
// user-provided copy/move constructors and assignment operators so they
// remain aggregates.
- void GenCopyMoveCtorAndAssigOpDecls(const StructDef &struct_def) {
+ void GenCopyMoveCtorAndAssigOpDecls(const StructDef& struct_def) {
if (opts_.g_cpp_std < cpp::CPP_STD_11) return;
if (!NeedsCopyCtorAssignOp(struct_def)) return;
code_.SetValue("NATIVE_NAME",
@@ -2026,20 +2078,22 @@
}
// Generate the >= C++11 copy constructor and assignment operator definitions.
- void GenCopyCtorAssignOpDefs(const StructDef &struct_def) {
+ void GenCopyCtorAssignOpDefs(const StructDef& struct_def) {
if (opts_.g_cpp_std < cpp::CPP_STD_11) return;
if (!NeedsCopyCtorAssignOp(struct_def)) return;
std::string initializer_list;
std::string vector_copies;
std::string swaps;
- for (const auto &field : struct_def.fields.vec) {
- const auto &type = field->value.type;
+ for (const auto& field : struct_def.fields.vec) {
+ const auto& type = field->value.type;
if (field->deprecated || type.base_type == BASE_TYPE_UTYPE) continue;
if (type.base_type == BASE_TYPE_STRUCT) {
- if (!initializer_list.empty()) { initializer_list += ",\n "; }
+ if (!initializer_list.empty()) {
+ initializer_list += ",\n ";
+ }
const auto cpp_type = field->attributes.Lookup("cpp_type");
const auto cpp_ptr_type = field->attributes.Lookup("cpp_ptr_type");
- const std::string &type_name =
+ const std::string& type_name =
(cpp_type) ? cpp_type->constant
: GenTypeNative(type, /*invector*/ false, *field,
/*forcopy*/ true);
@@ -2062,7 +2116,7 @@
if (vec_type.base_type == BASE_TYPE_UTYPE) continue;
const auto cpp_type = field->attributes.Lookup("cpp_type");
const auto cpp_ptr_type = field->attributes.Lookup("cpp_ptr_type");
- const std::string &type_name =
+ const std::string& type_name =
(cpp_type) ? cpp_type->constant
: GenTypeNative(vec_type, /*invector*/ true, *field,
/*forcopy*/ true);
@@ -2085,19 +2139,25 @@
// For non-pointer elements, use std::vector's copy constructor in the
// initializer list. This will yield better performance than an insert
// range loop for trivially-copyable element types.
- if (!initializer_list.empty()) { initializer_list += ",\n "; }
+ if (!initializer_list.empty()) {
+ initializer_list += ",\n ";
+ }
cw += "{{FIELD}}(o.{{FIELD}})\\";
initializer_list += cw.ToString();
}
} else {
- if (!initializer_list.empty()) { initializer_list += ",\n "; }
+ if (!initializer_list.empty()) {
+ initializer_list += ",\n ";
+ }
CodeWriter cw;
cw.SetValue("FIELD", Name(*field));
cw += "{{FIELD}}(o.{{FIELD}})\\";
initializer_list += cw.ToString();
}
{
- if (!swaps.empty()) { swaps += "\n "; }
+ if (!swaps.empty()) {
+ swaps += "\n ";
+ }
CodeWriter cw;
cw.SetValue("FIELD", Name(*field));
cw += "std::swap({{FIELD}}, o.{{FIELD}});\\";
@@ -2107,7 +2167,9 @@
if (!initializer_list.empty()) {
initializer_list = "\n : " + initializer_list;
}
- if (!swaps.empty()) { swaps = " " + swaps; }
+ if (!swaps.empty()) {
+ swaps = " " + swaps;
+ }
code_.SetValue("NATIVE_NAME",
NativeName(Name(struct_def), &struct_def, opts_));
@@ -2126,12 +2188,12 @@
code_ += " return *this;\n}\n";
}
- void GenCompareOperator(const StructDef &struct_def,
- const std::string &accessSuffix = "") {
+ void GenCompareOperator(const StructDef& struct_def,
+ const std::string& accessSuffix = "") {
std::string compare_op;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
const auto accessor = Name(field) + accessSuffix;
const auto lhs_accessor = "lhs." + accessor;
const auto rhs_accessor = "rhs." + accessor;
@@ -2139,7 +2201,9 @@
field.value.type.base_type != BASE_TYPE_UTYPE &&
(!IsVector(field.value.type) ||
field.value.type.element != BASE_TYPE_UTYPE)) {
- if (!compare_op.empty()) { compare_op += " &&\n "; }
+ if (!compare_op.empty()) {
+ compare_op += " &&\n ";
+ }
if (struct_def.fixed || field.native_inline ||
field.value.type.base_type != BASE_TYPE_STRUCT) {
// If the field is a vector of tables, the table need to be compared
@@ -2205,7 +2269,7 @@
code_ += "";
}
- void GenOperatorNewDelete(const StructDef &struct_def) {
+ void GenOperatorNewDelete(const StructDef& struct_def) {
if (auto native_custom_alloc =
struct_def.attributes.Lookup("native_custom_alloc")) {
code_ += " inline void *operator new (std::size_t count) {";
@@ -2220,7 +2284,7 @@
}
}
- void GenNativeTable(const StructDef &struct_def) {
+ void GenNativeTable(const StructDef& struct_def) {
const auto native_name = NativeName(Name(struct_def), &struct_def, opts_);
code_.SetValue("STRUCT_NAME", Name(struct_def));
code_.SetValue("NATIVE_NAME", native_name);
@@ -2229,7 +2293,9 @@
code_ += "struct {{NATIVE_NAME}} : public ::flatbuffers::NativeTable {";
code_ += " typedef {{STRUCT_NAME}} TableType;";
GenFullyQualifiedNameGetter(struct_def, native_name);
- for (const auto field : struct_def.fields.vec) { GenMember(*field); }
+ for (const auto field : struct_def.fields.vec) {
+ GenMember(*field);
+ }
GenOperatorNewDelete(struct_def);
GenDefaultConstructor(struct_def);
GenCopyMoveCtorAndAssigOpDecls(struct_def);
@@ -2239,14 +2305,14 @@
// Adds a typedef to the binary schema type so one could get the bfbs based
// on the type at runtime.
- void GenBinarySchemaTypeDef(const StructDef *struct_def) {
+ void GenBinarySchemaTypeDef(const StructDef* struct_def) {
if (struct_def && opts_.binary_schema_gen_embed) {
code_ += " typedef " + WrapInNameSpace(*struct_def) +
"BinarySchema BinarySchema;";
}
}
- void GenNativeTablePost(const StructDef &struct_def) {
+ void GenNativeTablePost(const StructDef& struct_def) {
if (opts_.gen_compare) {
const auto native_name = NativeName(Name(struct_def), &struct_def, opts_);
code_.SetValue("STRUCT_NAME", Name(struct_def));
@@ -2257,7 +2323,7 @@
}
// Generate the code to call the appropriate Verify function(s) for a field.
- void GenVerifyCall(const FieldDef &field, const char *prefix) {
+ void GenVerifyCall(const FieldDef& field, const char* prefix) {
code_.SetValue("PRE", prefix);
code_.SetValue("NAME", Name(field));
code_.SetValue("REQUIRED", field.IsRequired() ? "Required" : "");
@@ -2316,7 +2382,8 @@
"{{NAME}}_type())\\";
break;
}
- default: break;
+ default:
+ break;
}
auto nfn = GetNestedFlatBufferName(field);
@@ -2339,13 +2406,13 @@
}
}
- void GenComparatorForStruct(const StructDef &struct_def, size_t space_size,
+ void GenComparatorForStruct(const StructDef& struct_def, size_t space_size,
const std::string lhs_struct_literal,
const std::string rhs_struct_literal) {
code_.SetValue("LHS_PREFIX", lhs_struct_literal);
code_.SetValue("RHS_PREFIX", rhs_struct_literal);
std::string space(space_size, ' ');
- for (const auto &curr_field : struct_def.fields.vec) {
+ for (const auto& curr_field : struct_def.fields.vec) {
const auto curr_field_name = Name(*curr_field);
code_.SetValue("CURR_FIELD_NAME", curr_field_name);
code_.SetValue("LHS", lhs_struct_literal + "_" + curr_field_name);
@@ -2378,7 +2445,7 @@
" return static_cast<int>({{LHS}} > {{RHS}}) - "
"static_cast<int>({{LHS}} < {{RHS}});";
} else if (is_array) {
- const auto &elem_type = curr_field->value.type.VectorType();
+ const auto& elem_type = curr_field->value.type.VectorType();
code_ +=
space +
"for (::flatbuffers::uoffset_t i = 0; i < {{LHS}}->size(); i++) {";
@@ -2415,7 +2482,7 @@
}
// Generate CompareWithValue method for a key field.
- void GenKeyFieldMethods(const FieldDef &field) {
+ void GenKeyFieldMethods(const FieldDef& field) {
FLATBUFFERS_ASSERT(field.key);
const bool is_string = IsString(field.value.type);
const bool is_array = IsArray(field.value.type);
@@ -2450,7 +2517,7 @@
code_ += " if (_{{FIELD_NAME}} < {{FIELD_NAME}}()->c_str()) return 1;";
code_ += " return 0;";
} else if (is_array) {
- const auto &elem_type = field.value.type.VectorType();
+ const auto& elem_type = field.value.type.VectorType();
std::string input_type = "::flatbuffers::Array<" +
GenTypeGet(elem_type, "", "", "", false) + ", " +
NumToString(elem_type.fixed_length) + ">";
@@ -2485,7 +2552,7 @@
code_ += " }";
code_ += " return 0;";
} else if (is_struct) {
- const auto *struct_def = field.value.type.struct_def;
+ const auto* struct_def = field.value.type.struct_def;
code_.SetValue("INPUT_TYPE",
GenTypeGet(field.value.type, "", "", "", false));
code_ +=
@@ -2516,8 +2583,8 @@
code_ += " }";
}
- void GenTableUnionAsGetters(const FieldDef &field) {
- const auto &type = field.value.type;
+ void GenTableUnionAsGetters(const FieldDef& field) {
+ const auto& type = field.value.type;
auto u = type.enum_def;
if (!type.enum_def->uses_multiple_type_instances)
@@ -2526,8 +2593,10 @@
"const T *{{NULLABLE_EXT}}{{FIELD_NAME}}_as() const;";
for (auto u_it = u->Vals().begin(); u_it != u->Vals().end(); ++u_it) {
- auto &ev = **u_it;
- if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ auto& ev = **u_it;
+ if (ev.union_type.base_type == BASE_TYPE_NONE) {
+ continue;
+ }
auto full_struct_name = GetUnionElement(ev, false, opts_);
// @TODO: Mby make this decisions more universal? How?
@@ -2549,8 +2618,8 @@
}
}
- void GenTableFieldGetter(const FieldDef &field) {
- const auto &type = field.value.type;
+ void GenTableFieldGetter(const FieldDef& field) {
+ const auto& type = field.value.type;
const auto offset_str = GenFieldOffsetName(field);
GenComment(field.doc_comment, " ");
@@ -2573,7 +2642,9 @@
auto offset_type = GenTypeGet(type, "", "const ", " *", false);
auto call = accessor + offset_type + ">(" + offset_str;
// Default value as second arg for non-pointer types.
- if (is_scalar) { call += ", " + GenDefaultConstant(field); }
+ if (is_scalar) {
+ call += ", " + GenDefaultConstant(field);
+ }
call += ")";
std::string afterptr = " *" + NullableExtension();
@@ -2595,11 +2666,13 @@
code_ += " }";
}
- if (type.base_type == BASE_TYPE_UNION) { GenTableUnionAsGetters(field); }
+ if (type.base_type == BASE_TYPE_UNION) {
+ GenTableUnionAsGetters(field);
+ }
}
- void GenTableFieldType(const FieldDef &field) {
- const auto &type = field.value.type;
+ void GenTableFieldType(const FieldDef& field) {
+ const auto& type = field.value.type;
const auto offset_str = GenFieldOffsetName(field);
if (!field.IsScalarOptional()) {
std::string afterptr = " *" + NullableExtension();
@@ -2612,7 +2685,7 @@
}
}
- void GenStructFieldType(const FieldDef &field) {
+ void GenStructFieldType(const FieldDef& field) {
const auto is_array = IsArray(field.value.type);
std::string field_type =
GenTypeGet(field.value.type, "", is_array ? "" : "const ",
@@ -2621,22 +2694,26 @@
code_ += " {{FIELD_TYPE}}\\";
}
- void GenFieldTypeHelper(const StructDef &struct_def) {
- if (struct_def.fields.vec.empty()) { return; }
+ void GenFieldTypeHelper(const StructDef& struct_def) {
+ if (struct_def.fields.vec.empty()) {
+ return;
+ }
code_ += " template<size_t Index>";
code_ += " using FieldType = \\";
code_ += "decltype(std::declval<type>().get_field<Index>());";
}
- void GenIndexBasedFieldGetter(const StructDef &struct_def) {
- if (struct_def.fields.vec.empty()) { return; }
+ void GenIndexBasedFieldGetter(const StructDef& struct_def) {
+ if (struct_def.fields.vec.empty()) {
+ return;
+ }
code_ += " template<size_t Index>";
code_ += " auto get_field() const {";
size_t index = 0;
bool need_else = false;
// Generate one index-based getter for each field.
- for (const auto &field : struct_def.fields.vec) {
+ for (const auto& field : struct_def.fields.vec) {
if (field->deprecated) {
// Deprecated fields won't be accessible.
continue;
@@ -2665,7 +2742,7 @@
// "z"
// };
//
- void GenFieldNames(const StructDef &struct_def) {
+ void GenFieldNames(const StructDef& struct_def) {
code_ += " static constexpr std::array<\\";
code_ += "const char *, fields_number> field_names = {\\";
if (struct_def.fields.vec.empty()) {
@@ -2676,29 +2753,31 @@
// Generate the field_names elements.
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) {
// Deprecated fields won't be accessible.
continue;
}
code_.SetValue("FIELD_NAME", Name(field));
code_ += R"( "{{FIELD_NAME}}"\)";
- if (it + 1 != struct_def.fields.vec.end()) { code_ += ","; }
+ if (it + 1 != struct_def.fields.vec.end()) {
+ code_ += ",";
+ }
}
code_ += "\n };";
}
- void GenFieldsNumber(const StructDef &struct_def) {
+ void GenFieldsNumber(const StructDef& struct_def) {
const auto non_deprecated_field_count = std::count_if(
struct_def.fields.vec.begin(), struct_def.fields.vec.end(),
- [](const FieldDef *field) { return !field->deprecated; });
+ [](const FieldDef* field) { return !field->deprecated; });
code_.SetValue(
"FIELD_COUNT",
std::to_string(static_cast<long long>(non_deprecated_field_count)));
code_ += " static constexpr size_t fields_number = {{FIELD_COUNT}};";
}
- void GenTraitsStruct(const StructDef &struct_def) {
+ void GenTraitsStruct(const StructDef& struct_def) {
code_.SetValue(
"FULLY_QUALIFIED_NAME",
struct_def.defined_namespace->GetFullyQualifiedName(Name(struct_def)));
@@ -2721,8 +2800,8 @@
code_ += "";
}
- void GenTableFieldSetter(const FieldDef &field) {
- const auto &type = field.value.type;
+ void GenTableFieldSetter(const FieldDef& field) {
+ const auto& type = field.value.type;
const bool is_scalar = IsScalar(type.base_type);
if (is_scalar && IsUnion(type))
return; // changing of a union's type is forbidden
@@ -2762,8 +2841,12 @@
auto postptr = " *" + NullableExtension();
auto wire_type = GenTypeGet(type, " ", "", postptr.c_str(), true);
const std::string accessor = [&]() {
- if (IsStruct(type)) { return "GetStruct<"; }
- if (field.offset64) { return "GetPointer64<"; }
+ if (IsStruct(type)) {
+ return "GetStruct<";
+ }
+ if (field.offset64) {
+ return "GetPointer64<";
+ }
return "GetPointer<";
}();
auto underlying = accessor + wire_type + ">(" + offset_str + ")";
@@ -2776,7 +2859,7 @@
}
}
- std::string GetNestedFlatBufferName(const FieldDef &field) {
+ std::string GetNestedFlatBufferName(const FieldDef& field) {
auto nested = field.attributes.Lookup("nested_flatbuffer");
if (!nested) return "";
std::string qualified_name = nested->constant;
@@ -2792,8 +2875,10 @@
}
// Generate an accessor struct, builder structs & function for a table.
- void GenTable(const StructDef &struct_def) {
- if (opts_.generate_object_based_api) { GenNativeTable(struct_def); }
+ void GenTable(const StructDef& struct_def) {
+ if (opts_.generate_object_based_api) {
+ GenNativeTable(struct_def);
+ }
// Generate an accessor struct, with methods of the form:
// type name() const { return GetField<type>(offset, defaultval); }
@@ -2809,7 +2894,9 @@
code_ += " typedef {{STRUCT_NAME}}Builder Builder;";
GenBinarySchemaTypeDef(parser_.root_struct_def_);
- if (opts_.g_cpp_std >= cpp::CPP_STD_17) { code_ += " struct Traits;"; }
+ if (opts_.g_cpp_std >= cpp::CPP_STD_17) {
+ code_ += " struct Traits;";
+ }
if (opts_.mini_reflect != IDLOptions::kNone) {
code_ +=
" static const ::flatbuffers::TypeTable *MiniReflectTypeTable() {";
@@ -2826,7 +2913,7 @@
code_.SetValue("SEP", "");
code_ +=
" enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {";
- for (const auto &field : struct_def.fields.vec) {
+ for (const auto& field : struct_def.fields.vec) {
if (field->deprecated) {
// Deprecated fields won't be accessible.
continue;
@@ -2842,7 +2929,7 @@
}
// Generate the accessors.
- for (const auto &field : struct_def.fields.vec) {
+ for (const auto& field : struct_def.fields.vec) {
if (field->deprecated) {
// Deprecated fields won't be accessible.
continue;
@@ -2850,7 +2937,9 @@
code_.SetValue("FIELD_NAME", Name(*field));
GenTableFieldGetter(*field);
- if (opts_.mutable_buffer) { GenTableFieldSetter(*field); }
+ if (opts_.mutable_buffer) {
+ GenTableFieldSetter(*field);
+ }
auto nfn = GetNestedFlatBufferName(*field);
if (!nfn.empty()) {
@@ -2876,17 +2965,23 @@
}
// Generate a comparison function for this field if it is a key.
- if (field->key) { GenKeyFieldMethods(*field); }
+ if (field->key) {
+ GenKeyFieldMethods(*field);
+ }
}
- if (opts_.cpp_static_reflection) { GenIndexBasedFieldGetter(struct_def); }
+ if (opts_.cpp_static_reflection) {
+ GenIndexBasedFieldGetter(struct_def);
+ }
// Generate a verifier function that can check a buffer from an untrusted
// source will never cause reads outside the buffer.
code_ += " bool Verify(::flatbuffers::Verifier &verifier) const {";
code_ += " return VerifyTableStart(verifier)\\";
- for (const auto &field : struct_def.fields.vec) {
- if (field->deprecated) { continue; }
+ for (const auto& field : struct_def.fields.vec) {
+ if (field->deprecated) {
+ continue;
+ }
GenVerifyCall(*field, " &&\n ");
}
@@ -2904,7 +2999,7 @@
code_ += "";
// Explicit specializations for union accessors
- for (const auto &field : struct_def.fields.vec) {
+ for (const auto& field : struct_def.fields.vec) {
if (field->deprecated || field->value.type.base_type != BASE_TYPE_UNION) {
continue;
}
@@ -2915,8 +3010,10 @@
code_.SetValue("FIELD_NAME", Name(*field));
for (auto u_it = u->Vals().begin(); u_it != u->Vals().end(); ++u_it) {
- auto &ev = **u_it;
- if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ auto& ev = **u_it;
+ if (ev.union_type.base_type == BASE_TYPE_NONE) {
+ continue;
+ }
auto full_struct_name = GetUnionElement(ev, false, opts_);
@@ -2950,16 +3047,16 @@
// Generate code to force vector alignment. Return empty string for vector
// that doesn't need alignment code.
- std::string GenVectorForceAlign(const FieldDef &field,
- const std::string &field_size) {
+ std::string GenVectorForceAlign(const FieldDef& field,
+ const std::string& field_size) {
FLATBUFFERS_ASSERT(IsVector(field.value.type));
// Get the value of the force_align attribute.
- const auto *force_align = field.attributes.Lookup("force_align");
+ const auto* force_align = field.attributes.Lookup("force_align");
const int align = force_align ? atoi(force_align->constant.c_str()) : 1;
// Generate code to do force_align for the vector.
if (align > 1) {
const auto vtype = field.value.type.VectorType();
- const std::string &type =
+ const std::string& type =
IsStruct(vtype) ? WrapInNameSpace(*vtype.struct_def)
: GenTypeWire(vtype, "", false, field.offset64);
return std::string("_fbb.ForceVectorAlignment") +
@@ -2970,7 +3067,7 @@
return "";
}
- void GenBuilders(const StructDef &struct_def) {
+ void GenBuilders(const StructDef& struct_def) {
code_.SetValue("STRUCT_NAME", Name(struct_def));
// Generate a builder struct:
@@ -2982,13 +3079,15 @@
bool has_string_or_vector_fields = false;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
const bool is_scalar = IsScalar(field.value.type.base_type);
const bool is_default_scalar = is_scalar && !field.IsScalarOptional();
const bool is_string = IsString(field.value.type);
const bool is_vector = IsVector(field.value.type);
- if (is_string || is_vector) { has_string_or_vector_fields = true; }
+ if (is_string || is_vector) {
+ has_string_or_vector_fields = true;
+ }
std::string offset = GenFieldOffsetName(field);
std::string name = GenUnderlyingCast(field, false, Name(field));
@@ -3037,7 +3136,7 @@
code_ += " const auto end = fbb_.EndTable(start_);";
code_ += " auto o = ::flatbuffers::Offset<{{STRUCT_NAME}}>(end);";
- for (const auto &field : struct_def.fields.vec) {
+ for (const auto& field : struct_def.fields.vec) {
if (!field->deprecated && field->IsRequired()) {
code_.SetValue("FIELD_NAME", Name(*field));
code_.SetValue("OFFSET_NAME", GenFieldOffsetName(*field));
@@ -3055,8 +3154,10 @@
"inline ::flatbuffers::Offset<{{STRUCT_NAME}}> "
"Create{{STRUCT_NAME}}(";
code_ += " " + GetBuilder() + " &_fbb\\";
- for (const auto &field : struct_def.fields.vec) {
- if (!field->deprecated) { GenParam(*field, false, ",\n "); }
+ for (const auto& field : struct_def.fields.vec) {
+ if (!field->deprecated) {
+ GenParam(*field, false, ",\n ");
+ }
}
code_ += ") {";
@@ -3065,7 +3166,7 @@
size; size /= 2) {
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (!field.deprecated && (!struct_def.sortbysize ||
size == SizeOf(field.value.type.base_type))) {
code_.SetValue("FIELD_NAME", Name(field));
@@ -3085,7 +3186,9 @@
// Definition for type traits for this table type. This allows querying var-
// ious compile-time traits of the table.
- if (opts_.g_cpp_std >= cpp::CPP_STD_17) { GenTraitsStruct(struct_def); }
+ if (opts_.g_cpp_std >= cpp::CPP_STD_17) {
+ GenTraitsStruct(struct_def);
+ }
// Generate a CreateXDirect function with vector types as parameters
if (opts_.cpp_direct_copy && has_string_or_vector_fields) {
@@ -3093,8 +3196,10 @@
"inline ::flatbuffers::Offset<{{STRUCT_NAME}}> "
"Create{{STRUCT_NAME}}Direct(";
code_ += " " + GetBuilder() + " &_fbb\\";
- for (const auto &field : struct_def.fields.vec) {
- if (!field->deprecated) { GenParam(*field, true, ",\n "); }
+ for (const auto& field : struct_def.fields.vec) {
+ if (!field->deprecated) {
+ GenParam(*field, true, ",\n ");
+ }
}
// Need to call "Create" with the struct namespace.
const auto qualified_create_name =
@@ -3108,8 +3213,10 @@
// TODO(derekbailey): maybe optimize for the case where there is no
// 64offsets in the whole schema?
- ForAllFieldsOrderedByOffset(struct_def, [&](const FieldDef *field) {
- if (field->deprecated) { return; }
+ ForAllFieldsOrderedByOffset(struct_def, [&](const FieldDef* field) {
+ if (field->deprecated) {
+ return;
+ }
code_.SetValue("FIELD_NAME", Name(*field));
if (IsString(field->value.type)) {
if (!field->shared) {
@@ -3174,8 +3281,10 @@
});
code_ += " return {{CREATE_NAME}}{{STRUCT_NAME}}(";
code_ += " _fbb\\";
- for (const auto &field : struct_def.fields.vec) {
- if (field->deprecated) { continue; }
+ for (const auto& field : struct_def.fields.vec) {
+ if (field->deprecated) {
+ continue;
+ }
code_.SetValue("FIELD_NAME", Name(*field));
code_ += ",\n {{FIELD_NAME}}\\";
if (IsString(field->value.type) || IsVector(field->value.type)) {
@@ -3188,17 +3297,17 @@
}
}
- std::string GenUnionUnpackVal(const FieldDef &afield,
- const char *vec_elem_access,
- const char *vec_type_access) {
+ std::string GenUnionUnpackVal(const FieldDef& afield,
+ const char* vec_elem_access,
+ const char* vec_type_access) {
auto type_name = WrapInNameSpace(*afield.value.type.enum_def);
return type_name + "Union::UnPack(" + "_e" + vec_elem_access + ", " +
EscapeKeyword(Name(afield) + UnionTypeFieldSuffix()) + "()" +
vec_type_access + ", _resolver)";
}
- std::string GenUnpackVal(const Type &type, const std::string &val,
- bool invector, const FieldDef &afield) {
+ std::string GenUnpackVal(const Type& type, const std::string& val,
+ bool invector, const FieldDef& afield) {
switch (type.base_type) {
case BASE_TYPE_STRING: {
if (FlexibleStringConstructor(&afield)) {
@@ -3210,12 +3319,14 @@
}
case BASE_TYPE_STRUCT: {
if (IsStruct(type)) {
- const auto &struct_attrs = type.struct_def->attributes;
+ const auto& struct_attrs = type.struct_def->attributes;
const auto native_type = struct_attrs.Lookup("native_type");
if (native_type) {
std::string unpack_call = "::flatbuffers::UnPack";
const auto pack_name = struct_attrs.Lookup("native_type_pack_name");
- if (pack_name) { unpack_call += pack_name->constant; }
+ if (pack_name) {
+ unpack_call += pack_name->constant;
+ }
unpack_call += "(*" + val + ")";
if (invector || afield.native_inline) {
return unpack_call;
@@ -3252,8 +3363,8 @@
}
}
- std::string GenUnpackFieldStatement(const FieldDef &field,
- const FieldDef *union_field) {
+ std::string GenUnpackFieldStatement(const FieldDef& field,
+ const FieldDef* union_field) {
std::string code;
switch (field.value.type.base_type) {
case BASE_TYPE_VECTOR64:
@@ -3280,7 +3391,9 @@
WrapInNameSpace(*field.value.type.enum_def) + ">(";
}
indexing += "_e->Get(_i)";
- if (field.value.type.enum_def) { indexing += ")"; }
+ if (field.value.type.enum_def) {
+ indexing += ")";
+ }
if (field.value.type.element == BASE_TYPE_BOOL) {
indexing += " != 0";
}
@@ -3334,7 +3447,9 @@
code += GenUnpackVal(field.value.type.VectorType(), indexing, true,
field);
code += "; ";
- if (is_pointer) { code += "} "; }
+ if (is_pointer) {
+ code += "} ";
+ }
}
code += "} } else { " + vector_field + ".resize(0); }";
}
@@ -3403,7 +3518,7 @@
return code;
}
- std::string GenCreateParam(const FieldDef &field) {
+ std::string GenCreateParam(const FieldDef& field) {
std::string value = "_o->";
if (field.value.type.base_type == BASE_TYPE_UTYPE) {
value += StripUnionType(Name(field));
@@ -3481,7 +3596,7 @@
}
case BASE_TYPE_STRUCT: {
if (IsStruct(vector_type)) {
- const auto &struct_attrs =
+ const auto& struct_attrs =
field.value.type.struct_def->attributes;
const auto native_type = struct_attrs.Lookup("native_type");
if (native_type) {
@@ -3541,7 +3656,7 @@
case BASE_TYPE_UTYPE: {
value = StripUnionType(value);
auto underlying_type = GenTypeBasic(vector_type, false);
- const std::string &type = opts_.scoped_enums
+ const std::string& type = opts_.scoped_enums
? Name(*field.value.type.enum_def)
: underlying_type;
auto enum_value = "__va->_" + value + "[i].type";
@@ -3605,13 +3720,15 @@
}
case BASE_TYPE_STRUCT: {
if (IsStruct(field.value.type)) {
- const auto &struct_attribs = field.value.type.struct_def->attributes;
+ const auto& struct_attribs = field.value.type.struct_def->attributes;
const auto native_type = struct_attribs.Lookup("native_type");
if (native_type && field.native_inline) {
code += "::flatbuffers::Pack";
const auto pack_name =
struct_attribs.Lookup("native_type_pack_name");
- if (pack_name) { code += pack_name->constant; }
+ if (pack_name) {
+ code += pack_name->constant;
+ }
code += "(" + value + ")";
} else if (native_type && !field.native_inline) {
code += WrapInNameSpace(*field.value.type.struct_def) + "{};";
@@ -3624,7 +3741,7 @@
}
} else {
// _o->field ? CreateT(_fbb, _o->field.get(), _rehasher);
- const std::string &type = field.value.type.struct_def->name;
+ const std::string& type = field.value.type.struct_def->name;
code += value + " ? Create" + type;
code += "(_fbb, " + value;
if (!field.native_inline) code += GenPtrGet(field);
@@ -3641,8 +3758,10 @@
}
// Generate code for tables that needs to come after the regular definition.
- void GenTablePost(const StructDef &struct_def) {
- if (opts_.generate_object_based_api) { GenNativeTablePost(struct_def); }
+ void GenTablePost(const StructDef& struct_def) {
+ if (opts_.generate_object_based_api) {
+ GenNativeTablePost(struct_def);
+ }
code_.SetValue("STRUCT_NAME", Name(struct_def));
code_.SetValue("NATIVE_NAME",
@@ -3680,8 +3799,10 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (field.deprecated) { continue; }
+ const auto& field = **it;
+ if (field.deprecated) {
+ continue;
+ }
// Assign a value from |this| to |_o|. Values from |this| are stored
// in a variable |_e| by calling this->field_type(). The value is then
@@ -3725,12 +3846,16 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (field.deprecated) { continue; }
+ auto& field = **it;
+ if (field.deprecated) {
+ continue;
+ }
if (IsVector(field.value.type)) {
const std::string force_align_code =
GenVectorForceAlign(field, "_o->" + Name(field) + ".size()");
- if (!force_align_code.empty()) { code_ += " " + force_align_code; }
+ if (!force_align_code.empty()) {
+ code_ += " " + force_align_code;
+ }
}
code_ += " auto _" + Name(field) + " = " + GenCreateParam(field) + ";";
}
@@ -3741,8 +3866,10 @@
code_ += " return {{CREATE_NAME}}{{STRUCT_NAME}}(";
code_ += " _fbb\\";
- for (const auto &field : struct_def.fields.vec) {
- if (field->deprecated) { continue; }
+ for (const auto& field : struct_def.fields.vec) {
+ if (field->deprecated) {
+ continue;
+ }
bool pass_by_address = false;
bool check_ptr = false;
@@ -3751,8 +3878,12 @@
auto native_type =
field->value.type.struct_def->attributes.Lookup("native_type");
auto native_inline = field->attributes.Lookup("native_inline");
- if (native_type) { pass_by_address = true; }
- if (native_type && !native_inline) { check_ptr = true; }
+ if (native_type) {
+ pass_by_address = true;
+ }
+ if (native_type && !native_inline) {
+ check_ptr = true;
+ }
}
}
@@ -3773,8 +3904,8 @@
}
static void GenPadding(
- const FieldDef &field, std::string *code_ptr, int *id,
- const std::function<void(int bits, std::string *code_ptr, int *id)> &f) {
+ const FieldDef& field, std::string* code_ptr, int* id,
+ const std::function<void(int bits, std::string* code_ptr, int* id)>& f) {
if (field.padding) {
for (int i = 0; i < 4; i++) {
if (static_cast<int>(field.padding) & (1 << i)) {
@@ -3785,30 +3916,30 @@
}
}
- static void PaddingDefinition(int bits, std::string *code_ptr, int *id) {
+ static void PaddingDefinition(int bits, std::string* code_ptr, int* id) {
*code_ptr += " int" + NumToString(bits) + "_t padding" +
NumToString((*id)++) + "__;";
}
- static void PaddingInitializer(int bits, std::string *code_ptr, int *id) {
+ static void PaddingInitializer(int bits, std::string* code_ptr, int* id) {
(void)bits;
if (!code_ptr->empty()) *code_ptr += ",\n ";
*code_ptr += "padding" + NumToString((*id)++) + "__(0)";
}
- static void PaddingNoop(int bits, std::string *code_ptr, int *id) {
+ static void PaddingNoop(int bits, std::string* code_ptr, int* id) {
(void)bits;
if (!code_ptr->empty()) *code_ptr += '\n';
*code_ptr += " (void)padding" + NumToString((*id)++) + "__;";
}
- void GenStructDefaultConstructor(const StructDef &struct_def) {
+ void GenStructDefaultConstructor(const StructDef& struct_def) {
std::string init_list;
std::string body;
bool first_in_init_list = true;
int padding_initializer_id = 0;
int padding_body_id = 0;
- for (const auto &field : struct_def.fields.vec) {
+ for (const auto& field : struct_def.fields.vec) {
const auto field_name = Name(*field) + "_";
if (first_in_init_list) {
@@ -3844,12 +3975,14 @@
code_.SetValue("INIT_LIST", init_list);
code_ += " {{STRUCT_NAME}}()";
code_ += " : {{INIT_LIST}} {";
- if (!body.empty()) { code_ += body; }
+ if (!body.empty()) {
+ code_ += body;
+ }
code_ += " }";
}
}
- void GenStructConstructor(const StructDef &struct_def,
+ void GenStructConstructor(const StructDef& struct_def,
GenArrayArgMode array_mode) {
std::string arg_list;
std::string init_list;
@@ -3859,19 +3992,23 @@
const auto init_arrays = (array_mode != kArrayArgModeNone);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- const auto &type = field.value.type;
+ const auto& field = **it;
+ const auto& type = field.value.type;
const auto is_array = IsArray(type);
const auto arg_name = "_" + Name(field);
if (!is_array || init_arrays) {
- if (it != first && !arg_list.empty()) { arg_list += ", "; }
+ if (it != first && !arg_list.empty()) {
+ arg_list += ", ";
+ }
arg_list += !is_array ? GenTypeGet(type, " ", "const ", " &", true)
: GenTypeSpan(type, true, type.fixed_length);
arg_list += arg_name;
}
// skip an array with initialization from span
if (false == (is_array && init_arrays)) {
- if (it != first && !init_list.empty()) { init_list += ",\n "; }
+ if (it != first && !init_list.empty()) {
+ init_list += ",\n ";
+ }
init_list += Name(field) + "_";
if (IsScalar(type.base_type)) {
auto scalar_type = GenUnderlyingCast(field, false, arg_name);
@@ -3898,10 +4035,10 @@
code_ += " {{STRUCT_NAME}}({{ARG_LIST}}) {";
}
padding_id = 0;
- for (const auto &field : struct_def.fields.vec) {
- const auto &type = field->value.type;
+ for (const auto& field : struct_def.fields.vec) {
+ const auto& type = field->value.type;
if (IsArray(type) && init_arrays) {
- const auto &element_type = type.VectorType();
+ const auto& element_type = type.VectorType();
const auto is_enum = IsEnum(element_type);
FLATBUFFERS_ASSERT(
(IsScalar(element_type.base_type) || IsStruct(element_type)) &&
@@ -3924,7 +4061,7 @@
}
}
- void GenArrayAccessor(const Type &type, bool mutable_accessor) {
+ void GenArrayAccessor(const Type& type, bool mutable_accessor) {
FLATBUFFERS_ASSERT(IsArray(type));
const auto is_enum = IsEnum(type.VectorType());
// The Array<bool,N> is a tricky case, like std::vector<bool>.
@@ -3945,7 +4082,7 @@
}
// Generate an accessor struct with constructor for a flatbuffers struct.
- void GenStruct(const StructDef &struct_def) {
+ void GenStruct(const StructDef& struct_def) {
// Generate an accessor struct, with private variables of the form:
// type name_;
// Generates manual padding and alignment.
@@ -3961,8 +4098,8 @@
code_ += " private:";
int padding_id = 0;
- for (const auto &field : struct_def.fields.vec) {
- const auto &field_type = field->value.type;
+ for (const auto& field : struct_def.fields.vec) {
+ const auto& field_type = field->value.type;
code_.SetValue("FIELD_TYPE", GenTypeGet(field_type, " ", "", " ", false));
code_.SetValue("FIELD_NAME", Name(*field));
code_.SetValue("ARRAY",
@@ -3982,7 +4119,9 @@
code_ += "";
code_ += " public:";
- if (opts_.g_cpp_std >= cpp::CPP_STD_17) { code_ += " struct Traits;"; }
+ if (opts_.g_cpp_std >= cpp::CPP_STD_17) {
+ code_ += " struct Traits;";
+ }
// Make TypeTable accessible via the generated struct.
if (opts_.mini_reflect != IDLOptions::kNone) {
@@ -4003,22 +4142,22 @@
auto arrays_num = std::count_if(
struct_def.fields.vec.begin(), struct_def.fields.vec.end(),
- [](const FieldDef *fd) { return IsArray(fd->value.type); });
+ [](const FieldDef* fd) { return IsArray(fd->value.type); });
if (arrays_num > 0) {
GenStructConstructor(struct_def, kArrayArgModeSpanStatic);
}
// Generate accessor methods of the form:
// type name() const { return ::flatbuffers::EndianScalar(name_); }
- for (const auto &field : struct_def.fields.vec) {
- const auto &type = field->value.type;
+ for (const auto& field : struct_def.fields.vec) {
+ const auto& type = field->value.type;
const auto is_scalar = IsScalar(type.base_type);
const auto is_array = IsArray(type);
const auto field_type = GenTypeGet(type, " ", is_array ? "" : "const ",
is_array ? "" : " &", true);
auto member = Name(*field) + "_";
- const std::string &value =
+ const std::string& value =
is_scalar ? "::flatbuffers::EndianScalar(" + member + ")" : member;
code_.SetValue("FIELD_NAME", Name(*field));
@@ -4061,12 +4200,16 @@
}
// Generate a comparison function for this field if it is a key.
- if (field->key) { GenKeyFieldMethods(*field); }
+ if (field->key) {
+ GenKeyFieldMethods(*field);
+ }
}
code_.SetValue("NATIVE_NAME", Name(struct_def));
GenOperatorNewDelete(struct_def);
- if (opts_.cpp_static_reflection) { GenIndexBasedFieldGetter(struct_def); }
+ if (opts_.cpp_static_reflection) {
+ GenIndexBasedFieldGetter(struct_def);
+ }
code_ += "};";
@@ -4077,7 +4220,9 @@
// Definition for type traits for this table type. This allows querying var-
// ious compile-time traits of the table.
- if (opts_.g_cpp_std >= cpp::CPP_STD_17) { GenTraitsStruct(struct_def); }
+ if (opts_.g_cpp_std >= cpp::CPP_STD_17) {
+ GenTraitsStruct(struct_def);
+ }
}
// Set up the correct namespace. Only open a namespace if the existing one is
@@ -4085,8 +4230,10 @@
//
// The file must start and end with an empty (or null) namespace so that
// namespaces are properly opened and closed.
- void SetNameSpace(const Namespace *ns) {
- if (cur_name_space_ == ns) { return; }
+ void SetNameSpace(const Namespace* ns) {
+ if (cur_name_space_ == ns) {
+ return;
+ }
// Compute the size of the longest common namespace prefix.
// If cur_name_space is A::B::C::D and ns is A::B::E::F::G,
@@ -4107,14 +4254,18 @@
for (size_t j = old_size; j > common_prefix_size; --j) {
code_ += "} // namespace " + cur_name_space_->components[j - 1];
}
- if (old_size != common_prefix_size) { code_ += ""; }
+ if (old_size != common_prefix_size) {
+ code_ += "";
+ }
// open namespace parts to reach the ns namespace
// in the previous example, E, then F, then G are opened
for (auto j = common_prefix_size; j != new_size; ++j) {
code_ += "namespace " + ns->components[j] + " {";
}
- if (new_size != common_prefix_size) { code_ += ""; }
+ if (new_size != common_prefix_size) {
+ code_ += "";
+ }
cur_name_space_ = ns;
}
@@ -4122,8 +4273,8 @@
} // namespace cpp
-static bool GenerateCPP(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateCPP(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
cpp::IDLOptionsCpp opts(parser.opts);
// The '--cpp_std' argument could be extended (like ASAN):
// Example: "flatc --cpp_std c++17:option1:option2".
@@ -4161,14 +4312,14 @@
return generator.generate();
}
-static std::string CPPMakeRule(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static std::string CPPMakeRule(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
const auto filebase = StripPath(StripExtension(file_name));
cpp::CppGenerator geneartor(parser, path, file_name, parser.opts);
const auto included_files = parser.GetIncludedFilesRecursive(file_name);
std::string make_rule =
geneartor.GeneratedFileName(path, filebase, parser.opts) + ": ";
- for (const std::string &included_file : included_files) {
+ for (const std::string& included_file : included_files) {
make_rule += " " + included_file;
}
return make_rule;
@@ -4178,34 +4329,37 @@
class CppCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateCPP(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateCPP(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
output = CPPMakeRule(parser, path, filename);
return Status::OK;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateCppGRPC(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateCppGRPC(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_csharp.cpp b/src/idl_gen_csharp.cpp
index 9988523..5a2d648 100644
--- a/src/idl_gen_csharp.cpp
+++ b/src/idl_gen_csharp.cpp
@@ -31,9 +31,9 @@
"PositiveInfinity",
"NegativeInfinity");
static CommentConfig comment_config = {
- nullptr,
- "///",
- nullptr,
+ nullptr,
+ "///",
+ nullptr,
};
namespace csharp {
@@ -44,8 +44,8 @@
};
public:
- CSharpGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ CSharpGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name,
parser.opts.cs_global_alias ? "global::" : "", ".", "cs"),
cur_name_space_(nullptr) {
@@ -135,13 +135,13 @@
"volatile",
"while",
nullptr,
- // clang-format on
+ // clang-format on
};
for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
}
- CSharpGenerator &operator=(const CSharpGenerator &);
+ CSharpGenerator& operator=(const CSharpGenerator&);
bool generate() {
std::string one_file_code;
@@ -150,7 +150,7 @@
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
std::string enumcode;
- auto &enum_def = **it;
+ auto& enum_def = **it;
if (!parser_.opts.one_file) cur_name_space_ = enum_def.defined_namespace;
GenEnum(enum_def, &enumcode, parser_.opts);
if (parser_.opts.one_file) {
@@ -165,7 +165,7 @@
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
std::string declcode;
- auto &struct_def = **it;
+ auto& struct_def = **it;
if (!parser_.opts.one_file)
cur_name_space_ = struct_def.defined_namespace;
GenStruct(struct_def, &declcode, parser_.opts);
@@ -189,30 +189,30 @@
private:
std::unordered_set<std::string> keywords_;
- std::string EscapeKeyword(const std::string &name) const {
+ std::string EscapeKeyword(const std::string& name) const {
return keywords_.find(name) == keywords_.end() ? name : "@" + name;
}
- std::string Name(const FieldDef &field) const {
+ std::string Name(const FieldDef& field) const {
std::string name = ConvertCase(field.name, Case::kUpperCamel);
return EscapeKeyword(name);
}
- std::string Name(const Definition &def) const {
+ std::string Name(const Definition& def) const {
return EscapeKeyword(def.name);
}
- std::string NamespacedName(const Definition &def) const {
+ std::string NamespacedName(const Definition& def) const {
return WrapInNameSpace(def.defined_namespace, Name(def));
}
- std::string Name(const EnumVal &ev) const { return EscapeKeyword(ev.name); }
+ std::string Name(const EnumVal& ev) const { return EscapeKeyword(ev.name); }
// Save out the generated code for a single class while adding
// declaration boilerplate.
- bool SaveType(const std::string &defname, const Namespace &ns,
- const std::string &classcode, bool needs_includes,
- const IDLOptions &options) const {
+ bool SaveType(const std::string& defname, const Namespace& ns,
+ const std::string& classcode, bool needs_includes,
+ const IDLOptions& options) const {
if (!classcode.length()) return true;
std::string code =
@@ -232,17 +232,21 @@
code += "using global::Google.FlatBuffers;\n\n";
}
code += classcode;
- if (!namespace_name.empty()) { code += "\n}\n"; }
+ if (!namespace_name.empty()) {
+ code += "\n}\n";
+ }
auto filename = NamespaceDir(ns) + defname;
- if (options.one_file) { filename += options.filename_suffix; }
+ if (options.one_file) {
+ filename += options.filename_suffix;
+ }
filename +=
options.filename_extension.empty() ? ".cs" : options.filename_extension;
return SaveFile(filename.c_str(), code, false);
}
- const Namespace *CurrentNameSpace() const { return cur_name_space_; }
+ const Namespace* CurrentNameSpace() const { return cur_name_space_; }
- std::string GenTypeBasic(const Type &type, bool enableLangOverrides) const {
+ std::string GenTypeBasic(const Type& type, bool enableLangOverrides) const {
// clang-format off
static const char * const csharp_typename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, ...) \
@@ -262,39 +266,44 @@
return csharp_typename[type.base_type];
}
- inline std::string GenTypeBasic(const Type &type) const {
+ inline std::string GenTypeBasic(const Type& type) const {
return GenTypeBasic(type, true);
}
- std::string GenTypePointer(const Type &type) const {
+ std::string GenTypePointer(const Type& type) const {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "string";
- case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
- case BASE_TYPE_STRUCT: return NamespacedName(*type.struct_def);
- case BASE_TYPE_UNION: return "TTable";
- default: return "Table";
+ case BASE_TYPE_STRING:
+ return "string";
+ case BASE_TYPE_VECTOR:
+ return GenTypeGet(type.VectorType());
+ case BASE_TYPE_STRUCT:
+ return NamespacedName(*type.struct_def);
+ case BASE_TYPE_UNION:
+ return "TTable";
+ default:
+ return "Table";
}
}
- std::string GenTypeGet(const Type &type) const {
+ std::string GenTypeGet(const Type& type) const {
return IsScalar(type.base_type)
? GenTypeBasic(type)
: (IsArray(type) ? GenTypeGet(type.VectorType())
: GenTypePointer(type));
}
- std::string GenOffsetType(const StructDef &struct_def) const {
+ std::string GenOffsetType(const StructDef& struct_def) const {
return "Offset<" + NamespacedName(struct_def) + ">";
}
- std::string GenOffsetConstruct(const StructDef &struct_def,
- const std::string &variable_name) const {
+ std::string GenOffsetConstruct(const StructDef& struct_def,
+ const std::string& variable_name) const {
return "new Offset<" + NamespacedName(struct_def) + ">(" + variable_name +
")";
}
// Casts necessary to correctly read serialized data
- std::string DestinationCast(const Type &type) const {
+ std::string DestinationCast(const Type& type) const {
if (IsSeries(type)) {
return DestinationCast(type.VectorType());
} else {
@@ -309,7 +318,7 @@
// would be cast down to int before being put onto the buffer. In C#, one cast
// directly cast an Enum to its underlying type, which is essential before
// putting it onto the buffer.
- std::string SourceCast(const Type &type,
+ std::string SourceCast(const Type& type,
const bool isOptional = false) const {
if (IsSeries(type)) {
return SourceCast(type.VectorType());
@@ -320,25 +329,27 @@
return "";
}
- std::string SourceCastBasic(const Type &type, const bool isOptional) const {
+ std::string SourceCastBasic(const Type& type, const bool isOptional) const {
return IsScalar(type.base_type) ? SourceCast(type, isOptional) : "";
}
- std::string GenEnumDefaultValue(const FieldDef &field) const {
- auto &value = field.value;
+ std::string GenEnumDefaultValue(const FieldDef& field) const {
+ auto& value = field.value;
FLATBUFFERS_ASSERT(value.type.enum_def);
- auto &enum_def = *value.type.enum_def;
+ auto& enum_def = *value.type.enum_def;
auto enum_val = enum_def.FindByValue(value.constant);
return enum_val ? (NamespacedName(enum_def) + "." + Name(*enum_val))
: value.constant;
}
- std::string GenDefaultValue(const FieldDef &field,
+ std::string GenDefaultValue(const FieldDef& field,
bool enableLangOverrides) const {
// If it is an optional scalar field, the default is null
- if (field.IsScalarOptional()) { return "null"; }
+ if (field.IsScalarOptional()) {
+ return "null";
+ }
- auto &value = field.value;
+ auto& value = field.value;
if (enableLangOverrides) {
// handles both enum case and vector of enum case
if (value.type.enum_def != nullptr &&
@@ -349,10 +360,13 @@
auto longSuffix = "";
switch (value.type.base_type) {
- case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
- case BASE_TYPE_ULONG: return value.constant;
+ case BASE_TYPE_BOOL:
+ return value.constant == "0" ? "false" : "true";
+ case BASE_TYPE_ULONG:
+ return value.constant;
case BASE_TYPE_UINT:
- case BASE_TYPE_LONG: return value.constant + longSuffix;
+ case BASE_TYPE_LONG:
+ return value.constant + longSuffix;
default:
if (IsFloat(value.type.base_type))
return CSharpFloatGen.GenFloatConstant(field);
@@ -361,22 +375,25 @@
}
}
- std::string GenDefaultValue(const FieldDef &field) const {
+ std::string GenDefaultValue(const FieldDef& field) const {
return GenDefaultValue(field, true);
}
- std::string GenDefaultValueBasic(const FieldDef &field,
+ std::string GenDefaultValueBasic(const FieldDef& field,
bool enableLangOverrides) const {
- auto &value = field.value;
+ auto& value = field.value;
if (!IsScalar(value.type.base_type)) {
if (enableLangOverrides) {
switch (value.type.base_type) {
- case BASE_TYPE_STRING: return "default(StringOffset)";
+ case BASE_TYPE_STRING:
+ return "default(StringOffset)";
case BASE_TYPE_STRUCT:
return "default(Offset<" + NamespacedName(*value.type.struct_def) +
">)";
- case BASE_TYPE_VECTOR: return "default(VectorOffset)";
- default: break;
+ case BASE_TYPE_VECTOR:
+ return "default(VectorOffset)";
+ default:
+ break;
}
}
return "0";
@@ -384,13 +401,13 @@
return GenDefaultValue(field, enableLangOverrides);
}
- std::string GenDefaultValueBasic(const FieldDef &field) const {
+ std::string GenDefaultValueBasic(const FieldDef& field) const {
return GenDefaultValueBasic(field, true);
}
- void GenEnum(EnumDef &enum_def, std::string *code_ptr,
- const IDLOptions &opts) const {
- std::string &code = *code_ptr;
+ void GenEnum(EnumDef& enum_def, std::string* code_ptr,
+ const IDLOptions& opts) const {
+ std::string& code = *code_ptr;
if (enum_def.generated) return;
// Generate enum definitions of the form:
@@ -418,7 +435,7 @@
code += " : " + GenTypeBasic(enum_def.underlying_type, false);
code += "\n{\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
GenComment(ev.doc_comment, code_ptr, &comment_config, " ");
code += " ";
code += Name(ev) + " = ";
@@ -437,23 +454,30 @@
}
}
- bool HasUnionStringValue(const EnumDef &enum_def) const {
+ bool HasUnionStringValue(const EnumDef& enum_def) const {
if (!enum_def.is_union) return false;
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &val = **it;
- if (IsString(val.union_type)) { return true; }
+ auto& val = **it;
+ if (IsString(val.union_type)) {
+ return true;
+ }
}
return false;
}
// Returns the function name that is able to read a value of the given type.
- std::string GenGetter(const Type &type) const {
+ std::string GenGetter(const Type& type) const {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "__p.__string";
- case BASE_TYPE_STRUCT: return "__p.__struct";
- case BASE_TYPE_UNION: return "__p.__union";
- case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
- case BASE_TYPE_ARRAY: return GenGetter(type.VectorType());
+ case BASE_TYPE_STRING:
+ return "__p.__string";
+ case BASE_TYPE_STRUCT:
+ return "__p.__struct";
+ case BASE_TYPE_UNION:
+ return "__p.__union";
+ case BASE_TYPE_VECTOR:
+ return GenGetter(type.VectorType());
+ case BASE_TYPE_ARRAY:
+ return GenGetter(type.VectorType());
default: {
std::string getter = "__p.bb.Get";
if (type.base_type == BASE_TYPE_BOOL) {
@@ -466,9 +490,9 @@
}
}
- std::string GetObjectConstructor(flatbuffers::StructDef &struct_def,
- const std::string &data_buffer,
- const std::string &offset) const {
+ std::string GetObjectConstructor(flatbuffers::StructDef& struct_def,
+ const std::string& data_buffer,
+ const std::string& offset) const {
// Use the generated type directly, to properly handle default values that
// might not be written to the buffer.
return "new " + Name(struct_def) + "().__assign(" + offset + ", " +
@@ -476,20 +500,22 @@
}
// Returns the function name that is able to read a value of the given type.
- std::string GenGetterForLookupByKey(flatbuffers::StructDef &struct_def,
- flatbuffers::FieldDef *key_field,
- const std::string &data_buffer,
- const std::string &offset) const {
+ std::string GenGetterForLookupByKey(flatbuffers::StructDef& struct_def,
+ flatbuffers::FieldDef* key_field,
+ const std::string& data_buffer,
+ const std::string& offset) const {
// Use the generated type directly, to properly handle default values that
// might not be written to the buffer.
auto name = Name(*key_field);
- if (name == struct_def.name) { name += "_"; }
+ if (name == struct_def.name) {
+ name += "_";
+ }
return GetObjectConstructor(struct_def, data_buffer, offset) + "." + name;
}
// Direct mutation is only allowed for scalar fields.
// Hence a setter method will only be generated for such fields.
- std::string GenSetter(const Type &type) const {
+ std::string GenSetter(const Type& type) const {
if (IsScalar(type.base_type)) {
std::string setter = "__p.bb.Put";
if (GenTypeBasic(type, false) != "byte" &&
@@ -503,7 +529,7 @@
}
// Returns the method name for use with add/put calls.
- std::string GenMethod(const Type &type) const {
+ std::string GenMethod(const Type& type) const {
return IsScalar(type.base_type)
? ConvertCase(GenTypeBasic(type, false), Case::kUpperCamel)
: (IsStruct(type) ? "Struct" : "Offset");
@@ -511,15 +537,15 @@
// Recursively generate arguments for a constructor, to deal with nested
// structs.
- void GenStructArgs(const StructDef &struct_def, std::string *code_ptr,
- const char *nameprefix, size_t array_count = 0) const {
- std::string &code = *code_ptr;
+ void GenStructArgs(const StructDef& struct_def, std::string* code_ptr,
+ const char* nameprefix, size_t array_count = 0) const {
+ std::string& code = *code_ptr;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- const auto &field_type = field.value.type;
+ auto& field = **it;
+ const auto& field_type = field.value.type;
const auto array_field = IsArray(field_type);
- const auto &type = array_field ? field_type.VectorType() : field_type;
+ const auto& type = array_field ? field_type.VectorType() : field_type;
const auto array_cnt = array_field ? (array_count + 1) : array_count;
if (IsStruct(type)) {
// Generate arguments for a struct inside a struct. To ensure names
@@ -531,7 +557,9 @@
} else {
code += ", ";
code += GenTypeBasic(type);
- if (field.IsScalarOptional()) { code += "?"; }
+ if (field.IsScalarOptional()) {
+ code += "?";
+ }
if (array_cnt > 0) {
code += "[";
for (size_t i = 1; i < array_cnt; i++) code += ",";
@@ -547,18 +575,18 @@
// Recusively generate struct construction statements of the form:
// builder.putType(name);
// and insert manual padding.
- void GenStructBody(const StructDef &struct_def, std::string *code_ptr,
- const char *nameprefix, size_t index = 0,
+ void GenStructBody(const StructDef& struct_def, std::string* code_ptr,
+ const char* nameprefix, size_t index = 0,
bool in_array = false) const {
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
std::string indent((index + 1) * 2, ' ');
code += indent + " builder.Prep(";
code += NumToString(struct_def.minalign) + ", ";
code += NumToString(struct_def.bytesize) + ");\n";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
- auto &field = **it;
- const auto &field_type = field.value.type;
+ auto& field = **it;
+ const auto& field_type = field.value.type;
if (field.padding) {
code += indent + " builder.Pad(";
code += NumToString(field.padding) + ");\n";
@@ -568,7 +596,7 @@
(nameprefix + (field.name + "_")).c_str(), index,
in_array);
} else {
- const auto &type =
+ const auto& type =
IsArray(field_type) ? field_type.VectorType() : field_type;
const auto index_var = "_idx" + NumToString(index);
if (IsArray(field_type)) {
@@ -599,12 +627,14 @@
}
code += ");\n";
}
- if (IsArray(field_type)) { code += indent + " }\n"; }
+ if (IsArray(field_type)) {
+ code += indent + " }\n";
+ }
}
}
}
- std::string GenOffsetGetter(flatbuffers::FieldDef *key_field,
- const char *num = nullptr) const {
+ std::string GenOffsetGetter(flatbuffers::FieldDef* key_field,
+ const char* num = nullptr) const {
std::string key_offset =
"Table.__offset(" + NumToString(key_field->value.offset) + ", ";
if (num) {
@@ -617,8 +647,8 @@
return key_offset;
}
- std::string GenKeyGetter(flatbuffers::StructDef &struct_def,
- flatbuffers::FieldDef *key_field) const {
+ std::string GenKeyGetter(flatbuffers::StructDef& struct_def,
+ flatbuffers::FieldDef* key_field) const {
// Get the getter for the key of the struct.
return GenGetterForLookupByKey(struct_def, key_field, "builder.DataBuffer",
"builder.DataBuffer.Length - o1.Value") +
@@ -629,9 +659,9 @@
}
// Get the value of a table verification function start
- void GetStartOfTableVerifier(const StructDef &struct_def,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetStartOfTableVerifier(const StructDef& struct_def,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "\n";
code += "static public class " + struct_def.name + "Verify\n";
code += "{\n";
@@ -642,14 +672,14 @@
}
// Get the value of a table verification function end
- void GetEndOfTableVerifier(std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetEndOfTableVerifier(std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += " && verifier.VerifyTableEnd(tablePos);\n";
code += " }\n";
code += "}\n";
}
- std::string GetNestedFlatBufferName(const FieldDef &field) {
+ std::string GetNestedFlatBufferName(const FieldDef& field) {
std::string name;
if (field.nested_flatbuffer) {
name = NamespacedName(*field.nested_flatbuffer);
@@ -660,8 +690,8 @@
}
// Generate the code to call the appropriate Verify function(s) for a field.
- void GenVerifyCall(CodeWriter &code_, const FieldDef &field,
- const char *prefix) {
+ void GenVerifyCall(CodeWriter& code_, const FieldDef& field,
+ const char* prefix) {
code_.SetValue("PRE", prefix);
code_.SetValue("NAME", ConvertCase(field.name, Case::kUpperCamel));
code_.SetValue("REQUIRED", field.IsRequired() ? "Required" : "");
@@ -780,7 +810,7 @@
}
// Generate table constructors, conditioned on its members' types.
- void GenTableVerifier(const StructDef &struct_def, std::string *code_ptr) {
+ void GenTableVerifier(const StructDef& struct_def, std::string* code_ptr) {
CodeWriter code_;
GetStartOfTableVerifier(struct_def, code_ptr);
@@ -788,7 +818,7 @@
// Generate struct fields accessors
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
GenVerifyCall(code_, field, "");
@@ -800,7 +830,7 @@
}
// Generate struct or table methods.
- void GenStructVerifier(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStructVerifier(const StructDef& struct_def, std::string* code_ptr) {
if (struct_def.generated) return;
// cur_name_space_ = struct_def.defined_namespace;
@@ -815,10 +845,10 @@
}
}
- void GenStruct(StructDef &struct_def, std::string *code_ptr,
- const IDLOptions &opts) const {
+ void GenStruct(StructDef& struct_def, std::string* code_ptr,
+ const IDLOptions& opts) const {
if (struct_def.generated) return;
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
// Generate a struct accessor class, with methods of the form:
// public type name() { return bb.getType(i + offset); }
@@ -907,7 +937,7 @@
code += "{ __init(_i, _bb); return this; }\n\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
GenComment(field.doc_comment, code_ptr, &comment_config, " ");
std::string type_name = GenTypeGet(field.value.type);
@@ -923,12 +953,16 @@
optional = "?";
conditional_cast = "(" + type_name_dest + optional + ")";
}
- if (field.IsScalarOptional()) { optional = "?"; }
+ if (field.IsScalarOptional()) {
+ optional = "?";
+ }
std::string dest_mask = "";
std::string dest_cast = DestinationCast(field.value.type);
std::string src_cast = SourceCast(field.value.type);
std::string field_name_camel = Name(field);
- if (field_name_camel == struct_def.name) { field_name_camel += "_"; }
+ if (field_name_camel == struct_def.name) {
+ field_name_camel += "_";
+ }
std::string method_start =
" public " + type_name_dest + optional + " " + field_name_camel;
std::string obj = "(new " + type_name + "())";
@@ -1008,7 +1042,8 @@
code += offset_prefix + getter + "(o + " + "__p.";
code += "bb_pos) : null";
break;
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
if (vectortype.base_type == BASE_TYPE_UNION) {
@@ -1078,7 +1113,9 @@
for (auto uit = field.value.type.enum_def->Vals().begin();
uit != field.value.type.enum_def->Vals().end(); ++uit) {
auto val = *uit;
- if (val->union_type.base_type == BASE_TYPE_NONE) { continue; }
+ if (val->union_type.base_type == BASE_TYPE_NONE) {
+ continue;
+ }
auto union_field_type_name = GenTypeGet(val->union_type);
code += member_suffix + "}\n";
if (val->union_type.base_type == BASE_TYPE_STRUCT &&
@@ -1097,14 +1134,17 @@
}
}
break;
- default: FLATBUFFERS_ASSERT(0);
+ default:
+ FLATBUFFERS_ASSERT(0);
}
}
code += member_suffix;
code += "}\n";
if (IsVector(field.value.type)) {
auto camel_name = Name(field);
- if (camel_name == struct_def.name) { camel_name += "_"; }
+ if (camel_name == struct_def.name) {
+ camel_name += "_";
+ }
code += " public int " + camel_name;
code += "Length";
code += " { get";
@@ -1115,10 +1155,10 @@
// See if we should generate a by-key accessor.
if (field.value.type.element == BASE_TYPE_STRUCT &&
!field.value.type.struct_def->fixed) {
- auto &sd = *field.value.type.struct_def;
- auto &fields = sd.fields.vec;
+ auto& sd = *field.value.type.struct_def;
+ auto& fields = sd.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
- auto &key_field = **kit;
+ auto& key_field = **kit;
if (key_field.key) {
auto qualified_name = NamespacedName(sd);
code += " public " + qualified_name + "? ";
@@ -1210,7 +1250,7 @@
// Generate mutators for scalar fields or vectors of scalars.
if (parser_.opts.mutable_buffer) {
auto is_series = (IsSeries(field.value.type));
- const auto &underlying_type =
+ const auto& underlying_type =
is_series ? field.value.type.VectorType() : field.value.type;
// Boolean parameters have to be explicitly converted to byte
// representation.
@@ -1264,8 +1304,8 @@
}
code += "\n";
auto struct_has_create = false;
- std::set<flatbuffers::FieldDef *> field_has_create_set;
- flatbuffers::FieldDef *key_field = nullptr;
+ std::set<flatbuffers::FieldDef*> field_has_create_set;
+ flatbuffers::FieldDef* key_field = nullptr;
if (struct_def.fixed) {
struct_has_create = true;
// create a struct constructor function
@@ -1286,7 +1326,7 @@
int num_fields = 0;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
if (IsStruct(field.value.type)) {
has_no_struct_fields = false;
@@ -1306,7 +1346,7 @@
code += "(FlatBufferBuilder builder";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
code += ",\n ";
if (IsStruct(field.value.type) && opts.generate_object_based_api) {
@@ -1318,7 +1358,9 @@
code += " = null";
} else {
code += GenTypeBasic(field.value.type);
- if (field.IsScalarOptional()) { code += "?"; }
+ if (field.IsScalarOptional()) {
+ code += "?";
+ }
code += " ";
code += EscapeKeyword(field.name);
if (!IsScalar(field.value.type.base_type)) code += "Offset";
@@ -1334,7 +1376,7 @@
size; size /= 2) {
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (!field.deprecated &&
(!struct_def.sortbysize ||
size == SizeOf(field.value.type.base_type))) {
@@ -1370,7 +1412,7 @@
code += NumToString(struct_def.fields.vec.size()) + "); }\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
if (field.key) key_field = &field;
code += " public static void Add";
@@ -1379,7 +1421,9 @@
code += GenTypeBasic(field.value.type);
auto argname = ConvertCase(field.name, Case::kLowerCamel);
if (!IsScalar(field.value.type.base_type)) argname += "Offset";
- if (field.IsScalarOptional()) { code += "?"; }
+ if (field.IsScalarOptional()) {
+ code += "?";
+ }
code += " " + EscapeKeyword(argname) + ") { builder.Add";
code += GenMethod(field.value.type) + "(";
code += NumToString(it - struct_def.fields.vec.begin()) + ", ";
@@ -1479,7 +1523,7 @@
code += "EndTable();\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (!field.deprecated && field.IsRequired()) {
code += " builder.Required(o, ";
code += NumToString(field.value.offset);
@@ -1488,7 +1532,7 @@
}
code += " return " + GenOffsetConstruct(struct_def, "o") + ";\n }\n";
if (parser_.root_struct_def_ == &struct_def) {
- std::string size_prefix[] = { "", "SizePrefixed" };
+ std::string size_prefix[] = {"", "SizePrefixed"};
for (int i = 0; i < 2; ++i) {
code += " public static void ";
code += "Finish" + size_prefix[i] + struct_def.name;
@@ -1509,7 +1553,9 @@
if (struct_def.has_key && !struct_def.fixed) {
FLATBUFFERS_ASSERT(key_field);
auto name = Name(*key_field);
- if (name == struct_def.name) { name += "_"; }
+ if (name == struct_def.name) {
+ name += "_";
+ }
code += "\n public static VectorOffset ";
code += "CreateSortedVectorOf" + struct_def.name;
code += "(FlatBufferBuilder builder, ";
@@ -1564,9 +1610,9 @@
}
}
- void GenVectorAccessObject(StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenVectorAccessObject(StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
// Generate a vector of structs accessor class.
code += "\n";
code += " ";
@@ -1592,9 +1638,9 @@
code += ", __p.bb); }\n";
// See if we should generate a by-key accessor.
if (!struct_def.fixed) {
- auto &fields = struct_def.fields.vec;
+ auto& fields = struct_def.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
- auto &key_field = **kit;
+ auto& key_field = **kit;
if (key_field.key) {
auto nullable_annotation =
parser_.opts.gen_nullable ? "@Nullable " : "";
@@ -1622,9 +1668,9 @@
code += " }\n";
}
- std::string GenUnionVerify(const Type &union_type) const {
+ std::string GenUnionVerify(const Type& union_type) const {
if (union_type.enum_def) {
- const auto &enum_def = *union_type.enum_def;
+ const auto& enum_def = *union_type.enum_def;
auto ret = "\n\nstatic public class " + enum_def.name + "Verify\n";
ret += "{\n";
@@ -1640,8 +1686,10 @@
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
- const auto &ev = **it;
- if (ev.IsZero()) { continue; }
+ const auto& ev = **it;
+ if (ev.IsZero()) {
+ continue;
+ }
ret += " case " + Name(enum_def) + "." + Name(ev) + ":\n";
@@ -1683,9 +1731,9 @@
return "";
}
- void GenEnum_ObjectAPI(EnumDef &enum_def, std::string *code_ptr,
- const IDLOptions &opts) const {
- auto &code = *code_ptr;
+ void GenEnum_ObjectAPI(EnumDef& enum_def, std::string* code_ptr,
+ const IDLOptions& opts) const {
+ auto& code = *code_ptr;
if (enum_def.generated) return;
if (!enum_def.is_union) return;
if (enum_def.attributes.Lookup("private")) {
@@ -1695,7 +1743,9 @@
}
auto union_name = enum_def.name + "Union";
auto class_member = std::string("Value");
- if (class_member == enum_def.name) { class_member += "_"; };
+ if (class_member == enum_def.name) {
+ class_member += "_";
+ };
code += "class " + union_name + " {\n";
// Type
code += " public " + enum_def.name + " Type { get; set; }\n";
@@ -1713,7 +1763,7 @@
" as T; }\n";
// As, From
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
if (ev.union_type.base_type == BASE_TYPE_NONE) continue;
auto type_name = GenTypeGet_ObjectAPI(ev.union_type, opts);
std::string accessibility =
@@ -1742,7 +1792,7 @@
union_name + " _o) {\n";
code += " switch (_o.Type) {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
if (ev.union_type.base_type == BASE_TYPE_NONE) {
code += " default: return 0;\n";
} else {
@@ -1827,7 +1877,7 @@
code += " switch (_o.Type) {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
- auto &ev = **it;
+ auto& ev = **it;
if (ev.union_type.base_type == BASE_TYPE_NONE) {
code += " default: break;\n";
} else {
@@ -1844,16 +1894,16 @@
}
}
- std::string GenTypeName_ObjectAPI(const std::string &name,
- const IDLOptions &opts) const {
+ std::string GenTypeName_ObjectAPI(const std::string& name,
+ const IDLOptions& opts) const {
return opts.object_prefix + name + opts.object_suffix;
}
- void GenUnionUnPack_ObjectAPI(const EnumDef &enum_def, std::string *code_ptr,
- const std::string &camel_name,
- const std::string &camel_name_short,
+ void GenUnionUnPack_ObjectAPI(const EnumDef& enum_def, std::string* code_ptr,
+ const std::string& camel_name,
+ const std::string& camel_name_short,
bool is_vector) const {
- auto &code = *code_ptr;
+ auto& code = *code_ptr;
std::string varialbe_name = "_o." + camel_name;
std::string class_member = "Value";
if (class_member == enum_def.name) class_member += "_";
@@ -1878,7 +1928,7 @@
") {\n";
for (auto eit = enum_def.Vals().begin(); eit != enum_def.Vals().end();
++eit) {
- auto &ev = **eit;
+ auto& ev = **eit;
if (ev.union_type.base_type == BASE_TYPE_NONE) {
code += indent + " default: break;\n";
} else {
@@ -1904,10 +1954,10 @@
}
void GenPackUnPack_ObjectAPI(
- StructDef &struct_def, std::string *code_ptr, const IDLOptions &opts,
+ StructDef& struct_def, std::string* code_ptr, const IDLOptions& opts,
bool struct_has_create,
- const std::set<FieldDef *> &field_has_create) const {
- auto &code = *code_ptr;
+ const std::set<FieldDef*>& field_has_create) const {
+ auto& code = *code_ptr;
auto struct_name = GenTypeName_ObjectAPI(struct_def.name, opts);
// UnPack()
code += " public " + struct_name + " UnPack() {\n";
@@ -1919,10 +1969,12 @@
code += " public void UnPackTo(" + struct_name + " _o) {\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
auto camel_name = Name(field);
- if (camel_name == struct_def.name) { camel_name += "_"; }
+ if (camel_name == struct_def.name) {
+ camel_name += "_";
+ }
auto camel_name_short = Name(field);
auto start = " _o." + camel_name + " = ";
switch (field.value.type.base_type) {
@@ -1975,7 +2027,8 @@
code += ");}\n";
}
break;
- case BASE_TYPE_UTYPE: break;
+ case BASE_TYPE_UTYPE:
+ break;
case BASE_TYPE_UNION: {
GenUnionUnPack_ObjectAPI(*field.value.type.enum_def, code_ptr,
camel_name, camel_name_short, false);
@@ -1995,10 +2048,12 @@
");\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
auto camel_name = Name(field);
- if (camel_name == struct_def.name) { camel_name += "_"; }
+ if (camel_name == struct_def.name) {
+ camel_name += "_";
+ }
auto camel_name_short = Name(field);
// pre
switch (field.value.type.base_type) {
@@ -2012,8 +2067,8 @@
} else if (struct_def.fixed && struct_has_create) {
std::vector<FieldArrayLength> array_lengths;
FieldArrayLength tmp_array_length = {
- field.name,
- field.value.type.fixed_length,
+ field.name,
+ field.value.type.fixed_length,
};
array_lengths.push_back(tmp_array_length);
GenStructPackDecl_ObjectAPI(*field.value.type.struct_def, code_ptr,
@@ -2061,7 +2116,9 @@
to_array = NamespacedName(*field.value.type.enum_def) +
"Union.Pack(builder, _o." + property_name + "[_j])";
break;
- default: gen_for_loop = false; break;
+ default:
+ gen_for_loop = false;
+ break;
}
code += " var _" + field.name + " = default(VectorOffset);\n";
code += " if (_o." + property_name + " != null) {\n";
@@ -2100,8 +2157,8 @@
if (field.value.type.struct_def != nullptr) {
std::vector<FieldArrayLength> array_lengths;
FieldArrayLength tmp_array_length = {
- field.name,
- field.value.type.fixed_length,
+ field.name,
+ field.value.type.fixed_length,
};
array_lengths.push_back(tmp_array_length);
GenStructPackDecl_ObjectAPI(*field.value.type.struct_def, code_ptr,
@@ -2121,7 +2178,8 @@
".Pack(builder, _o." + camel_name + ");\n";
break;
}
- default: break;
+ default:
+ break;
}
}
if (struct_has_create) {
@@ -2130,10 +2188,12 @@
code += " builder";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
auto camel_name = Name(field);
- if (camel_name == struct_def.name) { camel_name += "_"; }
+ if (camel_name == struct_def.name) {
+ camel_name += "_";
+ }
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
if (struct_def.fixed) {
@@ -2165,9 +2225,12 @@
}
break;
}
- case BASE_TYPE_UNION: FLATBUFFERS_FALLTHROUGH(); // fall thru
- case BASE_TYPE_UTYPE: FLATBUFFERS_FALLTHROUGH(); // fall thru
- case BASE_TYPE_STRING: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_UNION:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_UTYPE:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_STRING:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
code += ",\n";
code += " _" + field.name;
@@ -2185,7 +2248,7 @@
code += " Start" + struct_def.name + "(builder);\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
auto camel_name = Name(field);
switch (field.value.type.base_type) {
@@ -2200,14 +2263,17 @@
}
break;
}
- case BASE_TYPE_STRING: FLATBUFFERS_FALLTHROUGH(); // fall thru
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_STRING:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
code +=
" Add" + camel_name + "(builder, _" + field.name + ");\n";
break;
}
- case BASE_TYPE_UTYPE: break;
+ case BASE_TYPE_UTYPE:
+ break;
case BASE_TYPE_UNION: {
code += " Add" + camel_name + "Type(builder, _" + field.name +
"_type);\n";
@@ -2229,18 +2295,18 @@
}
void GenStructPackDecl_ObjectAPI(
- const StructDef &struct_def, std::string *code_ptr,
- std::vector<FieldArrayLength> &array_lengths) const {
- auto &code = *code_ptr;
+ const StructDef& struct_def, std::string* code_ptr,
+ std::vector<FieldArrayLength>& array_lengths) const {
+ auto& code = *code_ptr;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
auto is_array = IsArray(field.value.type);
- const auto &field_type =
+ const auto& field_type =
is_array ? field.value.type.VectorType() : field.value.type;
FieldArrayLength tmp_array_length = {
- field.name,
- field_type.fixed_length,
+ field.name,
+ field_type.fixed_length,
};
array_lengths.push_back(tmp_array_length);
if (field_type.struct_def != nullptr) {
@@ -2261,7 +2327,9 @@
if (array_only_lengths.size() > 0) {
code += "new " + GenTypeBasic(field_type) + "[";
for (size_t i = 0; i < array_only_lengths.size(); ++i) {
- if (i != 0) { code += ","; }
+ if (i != 0) {
+ code += ",";
+ }
code += NumToString(array_only_lengths[i].length);
}
code += "];\n";
@@ -2304,14 +2372,14 @@
}
}
- void GenStructPackCall_ObjectAPI(const StructDef &struct_def,
- std::string *code_ptr,
+ void GenStructPackCall_ObjectAPI(const StructDef& struct_def,
+ std::string* code_ptr,
std::string prefix) const {
- auto &code = *code_ptr;
+ auto& code = *code_ptr;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- const auto &field_type = field.value.type;
+ auto& field = **it;
+ const auto& field_type = field.value.type;
if (field_type.struct_def != nullptr) {
GenStructPackCall_ObjectAPI(*field_type.struct_def, code_ptr,
prefix + field.name + "_");
@@ -2323,12 +2391,14 @@
}
std::string GenTypeGet_ObjectAPI(flatbuffers::Type type,
- const IDLOptions &opts) const {
+ const IDLOptions& opts) const {
auto type_name = GenTypeGet(type);
// Replace to ObjectBaseAPI Type Name
switch (type.base_type) {
- case BASE_TYPE_STRUCT: FLATBUFFERS_FALLTHROUGH(); // fall thru
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_STRUCT:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
if (type.struct_def != nullptr) {
auto type_name_length = type.struct_def->name.length();
@@ -2346,7 +2416,8 @@
type_name = NamespacedName(*type.enum_def) + "Union";
break;
}
- default: break;
+ default:
+ break;
}
switch (type.base_type) {
@@ -2358,14 +2429,15 @@
type_name = "List<" + type_name + ">";
break;
}
- default: break;
+ default:
+ break;
}
return type_name;
}
- void GenStruct_ObjectAPI(StructDef &struct_def, std::string *code_ptr,
- const IDLOptions &opts) const {
- auto &code = *code_ptr;
+ void GenStruct_ObjectAPI(StructDef& struct_def, std::string* code_ptr,
+ const IDLOptions& opts) const {
+ auto& code = *code_ptr;
if (struct_def.attributes.Lookup("private")) {
code += "internal ";
} else {
@@ -2381,14 +2453,16 @@
// Generate Properties
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
if (field.value.type.element == BASE_TYPE_UTYPE) continue;
auto type_name = GenTypeGet_ObjectAPI(field.value.type, opts);
if (field.IsScalarOptional()) type_name += "?";
auto camel_name = Name(field);
- if (camel_name == struct_def.name) { camel_name += "_"; }
+ if (camel_name == struct_def.name) {
+ camel_name += "_";
+ }
if (opts.cs_gen_json_serializer) {
if (IsUnion(field.value.type)) {
auto utype_name = NamespacedName(*field.value.type.enum_def);
@@ -2450,12 +2524,14 @@
code += " public " + class_name + "() {\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
if (field.value.type.element == BASE_TYPE_UTYPE) continue;
auto camel_name = Name(field);
- if (camel_name == struct_def.name) { camel_name += "_"; }
+ if (camel_name == struct_def.name) {
+ camel_name += "_";
+ }
code += " this." + camel_name + " = ";
auto type_name = GenTypeGet_ObjectAPI(field.value.type, opts);
if (IsScalar(field.value.type.base_type)) {
@@ -2516,12 +2592,12 @@
// This tracks the current namespace used to determine if a type need to be
// prefixed by its namespace
- const Namespace *cur_name_space_;
+ const Namespace* cur_name_space_;
};
} // namespace csharp
-static bool GenerateCSharp(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateCSharp(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
csharp::CSharpGenerator generator(parser, path, file_name);
return generator.generate();
}
@@ -2530,34 +2606,35 @@
class CSharpCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateCSharp(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateCSharp(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
output = JavaCSharpMakeRule(false, parser, path, filename);
return Status::OK;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_dart.cpp b/src/idl_gen_dart.cpp
index f0df15d..52fc877 100644
--- a/src/idl_gen_dart.cpp
+++ b/src/idl_gen_dart.cpp
@@ -33,43 +33,45 @@
namespace {
static Namer::Config DartDefaultConfig() {
- return { /*types=*/Case::kUpperCamel,
- /*constants=*/Case::kScreamingSnake,
- /*methods=*/Case::kLowerCamel,
- /*functions=*/Case::kUnknown, // unused.
- /*fields=*/Case::kLowerCamel,
- /*variables=*/Case::kLowerCamel,
- /*variants=*/Case::kKeep,
- /*enum_variant_seperator=*/".",
- /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
- /*namespaces=*/Case::kSnake2,
- /*namespace_seperator=*/".",
- /*object_prefix=*/"",
- /*object_suffix=*/"T",
- /*keyword_prefix=*/"$",
- /*keyword_suffix=*/"",
- /*filenames=*/Case::kKeep,
- /*directories=*/Case::kKeep,
- /*output_path=*/"",
- /*filename_suffix=*/"_generated",
- /*filename_extension=*/".dart" };
+ return {/*types=*/Case::kUpperCamel,
+ /*constants=*/Case::kScreamingSnake,
+ /*methods=*/Case::kLowerCamel,
+ /*functions=*/Case::kUnknown, // unused.
+ /*fields=*/Case::kLowerCamel,
+ /*variables=*/Case::kLowerCamel,
+ /*variants=*/Case::kKeep,
+ /*enum_variant_seperator=*/".",
+ /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
+ /*namespaces=*/Case::kSnake2,
+ /*namespace_seperator=*/".",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"$",
+ /*keyword_suffix=*/"",
+ /*filenames=*/Case::kKeep,
+ /*directories=*/Case::kKeep,
+ /*output_path=*/"",
+ /*filename_suffix=*/"_generated",
+ /*filename_extension=*/".dart"};
}
static std::set<std::string> DartKeywords() {
// see https://www.dartlang.org/guides/language/language-tour#keywords
// yield*, async*, and sync* shouldn't be proble
return {
- "abstract", "else", "import", "show", "as", "enum",
- "in", "static", "assert", "export", "interface", "super",
- "async", "extends", "is", "switch", "await", "extension",
- "late", "sync", "break", "external", "library", "this",
- "case", "factory", "mixin", "throw", "catch", "false",
- "new", "true", "class", "final", "null", "try",
- "const", "finally", "on", "typedef", "continue", "for",
- "operator", "var", "covariant", "Function", "part", "void",
- "default", "get", "required", "while", "deferred", "hide",
- "rethrow", "with", "do", "if", "return", "yield",
- "dynamic", "implements", "set",
+ "abstract", "else", "import", "show", "as",
+ "enum", "in", "static", "assert", "export",
+ "interface", "super", "async", "extends", "is",
+ "switch", "await", "extension", "late", "sync",
+ "break", "external", "library", "this", "case",
+ "factory", "mixin", "throw", "catch", "false",
+ "new", "true", "class", "final", "null",
+ "try", "const", "finally", "on", "typedef",
+ "continue", "for", "operator", "var", "covariant",
+ "Function", "part", "void", "default", "get",
+ "required", "while", "deferred", "hide", "rethrow",
+ "with", "do", "if", "return", "yield",
+ "dynamic", "implements", "set",
};
}
} // namespace
@@ -82,17 +84,17 @@
public:
typedef std::map<std::string, std::string> namespace_code_map;
- DartGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ DartGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", ".", "dart"),
namer_(WithFlagOptions(DartDefaultConfig(), parser.opts, path),
DartKeywords()) {}
- template<typename T>
- void import_generator(const std::vector<T *> &definitions,
- const std::string &included,
- std::set<std::string> &imports) {
- for (const auto &item : definitions) {
+ template <typename T>
+ void import_generator(const std::vector<T*>& definitions,
+ const std::string& included,
+ std::set<std::string>& imports) {
+ for (const auto& item : definitions) {
if (item->file == included) {
std::string component = namer_.Namespace(*item->defined_namespace);
std::string filebase =
@@ -118,7 +120,7 @@
std::set<std::string> imports;
- for (const auto &included_file : parser_.GetIncludedFiles()) {
+ for (const auto& included_file : parser_.GetIncludedFiles()) {
if (included_file.filename == parser_.file_being_parsed_) continue;
import_generator(parser_.structs_.vec, included_file.filename, imports);
@@ -126,7 +128,9 @@
}
std::string import_code = "";
- for (const auto &file : imports) { import_code += file; }
+ for (const auto& file : imports) {
+ import_code += file;
+ }
import_code += import_code.empty() ? "" : "\n";
@@ -137,7 +141,9 @@
"// ignore_for_file: unused_import, unused_field, unused_element, "
"unused_local_variable, constant_identifier_names\n\n";
- if (!kv->first.empty()) { code += "library " + kv->first + ";\n\n"; }
+ if (!kv->first.empty()) {
+ code += "library " + kv->first + ";\n\n";
+ }
code += "import 'dart:typed_data' show Uint8List;\n";
code += "import 'package:flat_buffers/flat_buffers.dart' as " + _kFb +
@@ -156,18 +162,20 @@
code += kv->second;
- if (!SaveFile(Filename(kv->first).c_str(), code, false)) { return false; }
+ if (!SaveFile(Filename(kv->first).c_str(), code, false)) {
+ return false;
+ }
}
return true;
}
- std::string Filename(const std::string &suffix, bool path = true) const {
+ std::string Filename(const std::string& suffix, bool path = true) const {
return (path ? path_ : "") +
namer_.File(file_name_ + (suffix.empty() ? "" : "_" + suffix));
}
private:
- static std::string ImportAliasName(const std::string &ns) {
+ static std::string ImportAliasName(const std::string& ns) {
std::string ret;
ret.assign(ns);
size_t pos = ret.find('.');
@@ -179,25 +187,25 @@
return ret;
}
- void GenerateEnums(namespace_code_map &namespace_code) {
+ void GenerateEnums(namespace_code_map& namespace_code) {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
- auto &enum_def = **it;
+ auto& enum_def = **it;
GenEnum(enum_def, namespace_code);
}
}
- void GenerateStructs(namespace_code_map &namespace_code) {
+ void GenerateStructs(namespace_code_map& namespace_code) {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
- auto &struct_def = **it;
+ auto& struct_def = **it;
GenStruct(struct_def, namespace_code);
}
}
// Generate a documentation comment, if available.
- static void GenDocComment(const std::vector<std::string> &dc,
- const char *indent, std::string &code) {
+ static void GenDocComment(const std::vector<std::string>& dc,
+ const char* indent, std::string& code) {
for (auto it = dc.begin(); it != dc.end(); ++it) {
if (indent) code += indent;
code += "/// " + *it + "\n";
@@ -205,9 +213,9 @@
}
// Generate an enum declaration and an enum string lookup table.
- void GenEnum(EnumDef &enum_def, namespace_code_map &namespace_code) {
+ void GenEnum(EnumDef& enum_def, namespace_code_map& namespace_code) {
if (enum_def.generated) return;
- std::string &code =
+ std::string& code =
namespace_code[namer_.Namespace(*enum_def.defined_namespace)];
GenDocComment(enum_def.doc_comment, "", code);
@@ -222,12 +230,14 @@
code += "enum " + enum_type + " {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
const auto enum_var = namer_.Variant(ev);
if (it != enum_def.Vals().begin()) code += ",\n";
code += " " + enum_var + "(" + enum_def.ToString(ev) + ")";
}
- if (auto_default) { code += ",\n _default(0)"; }
+ if (auto_default) {
+ code += ",\n _default(0)";
+ }
code += ";\n\n";
code += " final int value;\n";
@@ -235,7 +245,7 @@
code += " factory " + enum_type + ".fromValue(int value) {\n";
code += " switch (value) {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
const auto enum_var = namer_.Variant(ev);
code += " case " + enum_def.ToString(ev) + ":";
code += " return " + enum_type + "." + enum_var + ";\n";
@@ -268,8 +278,8 @@
GenEnumReader(enum_def, enum_type, code);
}
- void GenEnumReader(EnumDef &enum_def, const std::string &enum_type,
- std::string &code) {
+ void GenEnumReader(EnumDef& enum_def, const std::string& enum_type,
+ std::string& code) {
code += "class _" + enum_type + "Reader extends " + _kFb + ".Reader<" +
enum_type + "> {\n";
code += " const _" + enum_type + "Reader();\n\n";
@@ -283,48 +293,69 @@
code += "}\n\n";
}
- std::string GenType(const Type &type) {
+ std::string GenType(const Type& type) {
switch (type.base_type) {
- case BASE_TYPE_BOOL: return "Bool";
- case BASE_TYPE_CHAR: return "Int8";
+ case BASE_TYPE_BOOL:
+ return "Bool";
+ case BASE_TYPE_CHAR:
+ return "Int8";
case BASE_TYPE_UTYPE:
- case BASE_TYPE_UCHAR: return "Uint8";
- case BASE_TYPE_SHORT: return "Int16";
- case BASE_TYPE_USHORT: return "Uint16";
- case BASE_TYPE_INT: return "Int32";
- case BASE_TYPE_UINT: return "Uint32";
- case BASE_TYPE_LONG: return "Int64";
- case BASE_TYPE_ULONG: return "Uint64";
- case BASE_TYPE_FLOAT: return "Float32";
- case BASE_TYPE_DOUBLE: return "Float64";
- case BASE_TYPE_STRING: return "String";
- case BASE_TYPE_VECTOR: return GenType(type.VectorType());
- case BASE_TYPE_STRUCT: return namer_.Type(*type.struct_def);
- case BASE_TYPE_UNION: return namer_.Type(*type.enum_def) + "TypeId";
- default: return "Table";
+ case BASE_TYPE_UCHAR:
+ return "Uint8";
+ case BASE_TYPE_SHORT:
+ return "Int16";
+ case BASE_TYPE_USHORT:
+ return "Uint16";
+ case BASE_TYPE_INT:
+ return "Int32";
+ case BASE_TYPE_UINT:
+ return "Uint32";
+ case BASE_TYPE_LONG:
+ return "Int64";
+ case BASE_TYPE_ULONG:
+ return "Uint64";
+ case BASE_TYPE_FLOAT:
+ return "Float32";
+ case BASE_TYPE_DOUBLE:
+ return "Float64";
+ case BASE_TYPE_STRING:
+ return "String";
+ case BASE_TYPE_VECTOR:
+ return GenType(type.VectorType());
+ case BASE_TYPE_STRUCT:
+ return namer_.Type(*type.struct_def);
+ case BASE_TYPE_UNION:
+ return namer_.Type(*type.enum_def) + "TypeId";
+ default:
+ return "Table";
}
}
- static std::string EnumSize(const Type &type) {
+ static std::string EnumSize(const Type& type) {
switch (type.base_type) {
case BASE_TYPE_BOOL:
case BASE_TYPE_CHAR:
case BASE_TYPE_UTYPE:
- case BASE_TYPE_UCHAR: return "1";
+ case BASE_TYPE_UCHAR:
+ return "1";
case BASE_TYPE_SHORT:
- case BASE_TYPE_USHORT: return "2";
+ case BASE_TYPE_USHORT:
+ return "2";
case BASE_TYPE_INT:
case BASE_TYPE_UINT:
- case BASE_TYPE_FLOAT: return "4";
+ case BASE_TYPE_FLOAT:
+ return "4";
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG:
- case BASE_TYPE_DOUBLE: return "8";
- default: return "1";
+ case BASE_TYPE_DOUBLE:
+ return "8";
+ default:
+ return "1";
}
}
- std::string GenReaderTypeName(const Type &type, Namespace *current_namespace,
- const FieldDef &def,
+ std::string GenReaderTypeName(const Type& type, Namespace* current_namespace,
+ const FieldDef& def,
bool parent_is_vector = false, bool lazy = true,
bool constConstruct = true) {
std::string prefix = (constConstruct ? "const " : "") + _kFb;
@@ -357,8 +388,8 @@
}
}
- std::string GenDartTypeName(const Type &type, Namespace *current_namespace,
- const FieldDef &def,
+ std::string GenDartTypeName(const Type& type, Namespace* current_namespace,
+ const FieldDef& def,
std::string struct_type_suffix = "") {
if (type.enum_def) {
if (type.enum_def->is_union && type.base_type != BASE_TYPE_UNION) {
@@ -371,7 +402,8 @@
}
switch (type.base_type) {
- case BASE_TYPE_BOOL: return "bool";
+ case BASE_TYPE_BOOL:
+ return "bool";
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG:
case BASE_TYPE_INT:
@@ -379,10 +411,13 @@
case BASE_TYPE_SHORT:
case BASE_TYPE_USHORT:
case BASE_TYPE_CHAR:
- case BASE_TYPE_UCHAR: return "int";
+ case BASE_TYPE_UCHAR:
+ return "int";
case BASE_TYPE_FLOAT:
- case BASE_TYPE_DOUBLE: return "double";
- case BASE_TYPE_STRING: return "String";
+ case BASE_TYPE_DOUBLE:
+ return "double";
+ case BASE_TYPE_STRING:
+ return "String";
case BASE_TYPE_STRUCT:
return MaybeWrapNamespace(
namer_.Type(*type.struct_def) + struct_type_suffix,
@@ -392,12 +427,14 @@
GenDartTypeName(type.VectorType(), current_namespace, def,
struct_type_suffix) +
">";
- default: assert(0); return "dynamic";
+ default:
+ assert(0);
+ return "dynamic";
}
}
- std::string GenDartTypeName(const Type &type, Namespace *current_namespace,
- const FieldDef &def, bool nullable,
+ std::string GenDartTypeName(const Type& type, Namespace* current_namespace,
+ const FieldDef& def, bool nullable,
std::string struct_type_suffix) {
std::string typeName =
GenDartTypeName(type, current_namespace, def, struct_type_suffix);
@@ -405,9 +442,9 @@
return typeName;
}
- std::string MaybeWrapNamespace(const std::string &type_name,
- Namespace *current_ns,
- const FieldDef &field) const {
+ std::string MaybeWrapNamespace(const std::string& type_name,
+ Namespace* current_ns,
+ const FieldDef& field) const {
const std::string current_namespace = namer_.Namespace(*current_ns);
const std::string field_namespace =
field.value.type.struct_def
@@ -424,14 +461,14 @@
}
// Generate an accessor struct with constructor for a flatbuffers struct.
- void GenStruct(const StructDef &struct_def,
- namespace_code_map &namespace_code) {
+ void GenStruct(const StructDef& struct_def,
+ namespace_code_map& namespace_code) {
if (struct_def.generated) return;
- std::string &code =
+ std::string& code =
namespace_code[namer_.Namespace(*struct_def.defined_namespace)];
- const auto &struct_type = namer_.Type(struct_def);
+ const auto& struct_type = namer_.Type(struct_def);
// Emit constructor
@@ -461,10 +498,10 @@
code += " final " + _kFb + ".BufferContext _bc;\n";
code += " final int _bcOffset;\n\n";
- std::vector<std::pair<int, FieldDef *>> non_deprecated_fields;
+ std::vector<std::pair<int, FieldDef*>> non_deprecated_fields;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- FieldDef &field = **it;
+ FieldDef& field = **it;
if (field.deprecated) continue;
auto offset = static_cast<int>(it - struct_def.fields.vec.begin());
non_deprecated_fields.push_back(std::make_pair(offset, &field));
@@ -500,8 +537,8 @@
// Generate an accessor struct with constructor for a flatbuffers struct.
std::string GenStructObjectAPI(
- const StructDef &struct_def,
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
+ const StructDef& struct_def,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields) {
std::string code;
GenDocComment(struct_def.doc_comment, "", code);
@@ -511,7 +548,7 @@
std::string constructor_args;
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
- const FieldDef &field = *it->second;
+ const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
const std::string defaultValue = getDefaultValue(field.value);
@@ -528,7 +565,7 @@
constructor_args += "this." + field_name;
if (!struct_def.fixed && !defaultValue.empty()) {
if (IsEnum(field.value.type)) {
- auto &enum_def = *field.value.type.enum_def;
+ auto& enum_def = *field.value.type.enum_def;
if (auto val = enum_def.FindByValue(defaultValue)) {
constructor_args += " = " + namer_.EnumVariant(enum_def, *val);
} else {
@@ -554,18 +591,18 @@
// Generate function `StructNameT unpack()`
std::string GenStructObjectAPIUnpack(
- const StructDef &struct_def,
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
+ const StructDef& struct_def,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields) {
std::string constructor_args;
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
- const FieldDef &field = *it->second;
+ const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
if (!constructor_args.empty()) constructor_args += ",\n";
constructor_args += " " + field_name + ": ";
- const Type &type = field.value.type;
+ const Type& type = field.value.type;
std::string defaultValue = getDefaultValue(field.value);
bool isNullable = defaultValue.empty() && !struct_def.fixed;
std::string nullableValueAccessOperator = isNullable ? "?" : "";
@@ -601,8 +638,8 @@
// Generate function `StructNameT pack()`
std::string GenStructObjectAPIPack(
- const StructDef &struct_def,
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
+ const StructDef& struct_def,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields) {
std::string code;
code += " @override\n";
@@ -613,8 +650,8 @@
return code;
}
- std::string NamespaceAliasFromUnionType(Namespace *root_namespace,
- const Type &type) {
+ std::string NamespaceAliasFromUnionType(Namespace* root_namespace,
+ const Type& type) {
const std::vector<std::string> qualified_name_parts =
type.struct_def->defined_namespace->components;
if (std::equal(root_namespace->components.begin(),
@@ -627,7 +664,7 @@
for (auto it = qualified_name_parts.begin();
it != qualified_name_parts.end(); ++it) {
- auto &part = *it;
+ auto& part = *it;
for (size_t i = 0; i < part.length(); i++) {
if (i && !isdigit(part[i]) && part[i] == CharToUpper(part[i])) {
@@ -637,19 +674,21 @@
ns += CharToLower(part[i]);
}
}
- if (it != qualified_name_parts.end() - 1) { ns += "_"; }
+ if (it != qualified_name_parts.end() - 1) {
+ ns += "_";
+ }
}
return ns + "." + namer_.Type(*type.struct_def);
}
void GenImplementationGetters(
- const StructDef &struct_def,
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
- std::string &code) {
+ const StructDef& struct_def,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
+ std::string& code) {
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
- const FieldDef &field = *it->second;
+ const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
const std::string defaultValue = getDefaultValue(field.value);
@@ -664,10 +703,10 @@
if (field.value.type.base_type == BASE_TYPE_UNION) {
code += " {\n";
code += " switch (" + field_name + "Type?.value) {\n";
- const auto &enum_def = *field.value.type.enum_def;
+ const auto& enum_def = *field.value.type.enum_def;
for (auto en_it = enum_def.Vals().begin() + 1;
en_it != enum_def.Vals().end(); ++en_it) {
- const auto &ev = **en_it;
+ const auto& ev = **en_it;
const auto enum_name = NamespaceAliasFromUnionType(
enum_def.defined_namespace, ev.union_type);
code += " case " + enum_def.ToString(ev) + ": return " +
@@ -713,8 +752,8 @@
}
std::string GenToString(
- const std::string &object_name,
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
+ const std::string& object_name,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields) {
std::string code;
code += " @override\n";
code += " String toString() {\n";
@@ -730,16 +769,20 @@
escaped_field.push_back(field[i]);
}
code += escaped_field + ": ${" + field + "}";
- if (it != non_deprecated_fields.end() - 1) { code += ", "; }
+ if (it != non_deprecated_fields.end() - 1) {
+ code += ", ";
+ }
}
code += "}';\n";
code += " }\n";
return code;
}
- std::string getDefaultValue(const Value &value) const {
+ std::string getDefaultValue(const Value& value) const {
if (!value.constant.empty() && value.constant != "0") {
- if (IsBool(value.type.base_type)) { return "true"; }
+ if (IsBool(value.type.base_type)) {
+ return "true";
+ }
if (IsScalar(value.type.base_type)) {
if (StringIsFlatbufferNan(value.constant)) {
return "double.nan";
@@ -759,8 +802,8 @@
}
}
- void GenReader(const StructDef &struct_def, const std::string &reader_name,
- std::string &code) {
+ void GenReader(const StructDef& struct_def, const std::string& reader_name,
+ std::string& code) {
const auto struct_type = namer_.Type(struct_def);
code += "class " + reader_name + " extends " + _kFb;
@@ -784,10 +827,12 @@
}
void GenBuilder(
- const StructDef &struct_def,
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
- const std::string &builder_name, std::string &code) {
- if (non_deprecated_fields.size() == 0) { return; }
+ const StructDef& struct_def,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
+ const std::string& builder_name, std::string& code) {
+ if (non_deprecated_fields.size() == 0) {
+ return;
+ }
code += "class " + builder_name + " {\n";
code += " " + builder_name + "(this.fbBuilder);\n\n";
@@ -803,13 +848,13 @@
}
void StructBuilderBody(
- const StructDef &struct_def,
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
- std::string &code) {
+ const StructDef& struct_def,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
+ std::string& code) {
code += " int finish(";
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
- const FieldDef &field = *it->second;
+ const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
if (IsStruct(field.value.type)) {
@@ -819,13 +864,15 @@
field);
}
code += " " + field_name;
- if (it != non_deprecated_fields.end() - 1) { code += ", "; }
+ if (it != non_deprecated_fields.end() - 1) {
+ code += ", ";
+ }
}
code += ") {\n";
for (auto it = non_deprecated_fields.rbegin();
it != non_deprecated_fields.rend(); ++it) {
- const FieldDef &field = *it->second;
+ const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
if (field.padding) {
@@ -837,7 +884,9 @@
} else {
code += " fbBuilder.put" + GenType(field.value.type) + "(";
code += field_name;
- if (field.value.type.enum_def) { code += ".value"; }
+ if (field.value.type.enum_def) {
+ code += ".value";
+ }
code += ");\n";
}
}
@@ -846,9 +895,9 @@
}
void TableBuilderBody(
- const StructDef &struct_def,
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
- std::string &code) {
+ const StructDef& struct_def,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
+ std::string& code) {
code += " void begin() {\n";
code += " fbBuilder.startTable(" +
NumToString(struct_def.fields.vec.size()) + ");\n";
@@ -856,7 +905,7 @@
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
- const auto &field = *it->second;
+ const auto& field = *it->second;
const auto offset = it->first;
const std::string add_field = namer_.Method("add", field);
const std::string field_var = namer_.Variable(field);
@@ -869,7 +918,9 @@
code += " fbBuilder.add" + GenType(field.value.type) + "(" +
NumToString(offset) + ", ";
code += field_var;
- if (field.value.type.enum_def) { code += "?.value"; }
+ if (field.value.type.enum_def) {
+ code += "?.value";
+ }
code += ");\n";
} else if (IsStruct(field.value.type)) {
code += " int " + add_field + "(int offset) {\n";
@@ -891,13 +942,13 @@
}
void GenObjectBuilder(
- const StructDef &struct_def,
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
- const std::string &builder_name, std::string &code) {
+ const StructDef& struct_def,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
+ const std::string& builder_name, std::string& code) {
code += "class " + builder_name + " extends " + _kFb + ".ObjectBuilder {\n";
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
- const FieldDef &field = *it->second;
+ const FieldDef& field = *it->second;
code += " final " +
GenDartTypeName(field.value.type, struct_def.defined_namespace,
@@ -911,7 +962,7 @@
code += "{\n";
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
- const FieldDef &field = *it->second;
+ const FieldDef& field = *it->second;
code += " ";
code += (struct_def.fixed ? "required " : "") +
@@ -923,7 +974,7 @@
code += " : ";
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
- const FieldDef &field = *it->second;
+ const FieldDef& field = *it->second;
code += "_" + namer_.Variable(field) + " = " + namer_.Variable(field);
if (it == non_deprecated_fields.end() - 1) {
@@ -954,13 +1005,13 @@
}
std::string GenObjectBuilderImplementation(
- const StructDef &struct_def,
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
+ const StructDef& struct_def,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
bool prependUnderscore = true, bool pack = false) {
std::string code;
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
- const FieldDef &field = *it->second;
+ const FieldDef& field = *it->second;
if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type))
continue;
@@ -1029,13 +1080,13 @@
}
std::string StructObjectBuilderBody(
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
bool prependUnderscore = true, bool pack = false) {
std::string code;
for (auto it = non_deprecated_fields.rbegin();
it != non_deprecated_fields.rend(); ++it) {
- const FieldDef &field = *it->second;
+ const FieldDef& field = *it->second;
const std::string field_name = namer_.Field(field);
if (field.padding) {
@@ -1044,13 +1095,19 @@
if (IsStruct(field.value.type)) {
code += " ";
- if (prependUnderscore) { code += "_"; }
+ if (prependUnderscore) {
+ code += "_";
+ }
code += field_name + (pack ? ".pack" : ".finish") + "(fbBuilder);\n";
} else {
code += " fbBuilder.put" + GenType(field.value.type) + "(";
- if (prependUnderscore) { code += "_"; }
+ if (prependUnderscore) {
+ code += "_";
+ }
code += field_name;
- if (field.value.type.enum_def) { code += ".value"; }
+ if (field.value.type.enum_def) {
+ code += ".value";
+ }
code += ");\n";
}
}
@@ -1060,8 +1117,8 @@
}
std::string TableObjectBuilderBody(
- const StructDef &struct_def,
- const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
+ const StructDef& struct_def,
+ const std::vector<std::pair<int, FieldDef*>>& non_deprecated_fields,
bool prependUnderscore = true, bool pack = false) {
std::string code;
code += " fbBuilder.startTable(" +
@@ -1069,7 +1126,7 @@
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
- const FieldDef &field = *it->second;
+ const FieldDef& field = *it->second;
auto offset = it->first;
std::string field_var =
@@ -1101,14 +1158,14 @@
};
} // namespace dart
-static bool GenerateDart(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateDart(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
dart::DartGenerator generator(parser, path, file_name);
return generator.generate();
}
-static std::string DartMakeRule(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static std::string DartMakeRule(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
auto filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
dart::DartGenerator generator(parser, path, file_name);
@@ -1125,34 +1182,35 @@
class DartCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateDart(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateDart(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
output = DartMakeRule(parser, path, filename);
return Status::OK;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_fbs.cpp b/src/idl_gen_fbs.cpp
index f984485..1d7fd9a 100644
--- a/src/idl_gen_fbs.cpp
+++ b/src/idl_gen_fbs.cpp
@@ -30,12 +30,13 @@
namespace flatbuffers {
namespace {
-static std::string GenType(const Type &type, bool underlying = false) {
+static std::string GenType(const Type& type, bool underlying = false) {
switch (type.base_type) {
case BASE_TYPE_STRUCT:
return type.struct_def->defined_namespace->GetFullyQualifiedName(
type.struct_def->name);
- case BASE_TYPE_VECTOR: return "[" + GenType(type.VectorType()) + "]";
+ case BASE_TYPE_VECTOR:
+ return "[" + GenType(type.VectorType()) + "]";
default:
if (type.enum_def && !underlying) {
return type.enum_def->defined_namespace->GetFullyQualifiedName(
@@ -46,11 +47,11 @@
}
}
-static bool HasFieldWithId(const std::vector<FieldDef *> &fields) {
+static bool HasFieldWithId(const std::vector<FieldDef*>& fields) {
static const std::string ID = "id";
- for (const auto *field : fields) {
- const auto *id_attribute = field->attributes.Lookup(ID);
+ for (const auto* field : fields) {
+ const auto* id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
return true;
}
@@ -58,81 +59,93 @@
return false;
}
-static bool HasNonPositiveFieldId(const std::vector<FieldDef *> &fields) {
+static bool HasNonPositiveFieldId(const std::vector<FieldDef*>& fields) {
static const std::string ID = "id";
- for (const auto *field : fields) {
- const auto *id_attribute = field->attributes.Lookup(ID);
+ for (const auto* field : fields) {
+ const auto* id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
voffset_t proto_id = 0;
bool done = StringToNumber(id_attribute->constant.c_str(), &proto_id);
- if (!done) { return true; }
+ if (!done) {
+ return true;
+ }
}
}
return false;
}
static bool HasFieldIdFromReservedIds(
- const std::vector<FieldDef *> &fields,
- const std::vector<voffset_t> &reserved_ids) {
+ const std::vector<FieldDef*>& fields,
+ const std::vector<voffset_t>& reserved_ids) {
static const std::string ID = "id";
- for (const auto *field : fields) {
- const auto *id_attribute = field->attributes.Lookup(ID);
+ for (const auto* field : fields) {
+ const auto* id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
voffset_t proto_id = 0;
bool done = StringToNumber(id_attribute->constant.c_str(), &proto_id);
- if (!done) { return true; }
+ if (!done) {
+ return true;
+ }
auto id_it =
std::find(std::begin(reserved_ids), std::end(reserved_ids), proto_id);
- if (id_it != reserved_ids.end()) { return true; }
+ if (id_it != reserved_ids.end()) {
+ return true;
+ }
}
}
return false;
}
static std::vector<voffset_t> ExtractProtobufIds(
- const std::vector<FieldDef *> &fields) {
+ const std::vector<FieldDef*>& fields) {
static const std::string ID = "id";
std::vector<voffset_t> used_proto_ids;
- for (const auto *field : fields) {
- const auto *id_attribute = field->attributes.Lookup(ID);
+ for (const auto* field : fields) {
+ const auto* id_attribute = field->attributes.Lookup(ID);
if (id_attribute != nullptr && !id_attribute->constant.empty()) {
voffset_t proto_id = 0;
bool done = StringToNumber(id_attribute->constant.c_str(), &proto_id);
- if (done) { used_proto_ids.push_back(proto_id); }
+ if (done) {
+ used_proto_ids.push_back(proto_id);
+ }
}
}
return used_proto_ids;
}
-static bool HasTwiceUsedId(const std::vector<FieldDef *> &fields) {
+static bool HasTwiceUsedId(const std::vector<FieldDef*>& fields) {
std::vector<voffset_t> used_proto_ids = ExtractProtobufIds(fields);
std::sort(std::begin(used_proto_ids), std::end(used_proto_ids));
for (auto it = std::next(std::begin(used_proto_ids));
it != std::end(used_proto_ids); it++) {
- if (*it == *std::prev(it)) { return true; }
+ if (*it == *std::prev(it)) {
+ return true;
+ }
}
return false;
}
-static bool HasGapInProtoId(const std::vector<FieldDef *> &fields) {
+static bool HasGapInProtoId(const std::vector<FieldDef*>& fields) {
std::vector<voffset_t> used_proto_ids = ExtractProtobufIds(fields);
std::sort(std::begin(used_proto_ids), std::end(used_proto_ids));
for (auto it = std::next(std::begin(used_proto_ids));
it != std::end(used_proto_ids); it++) {
- if (*it != *std::prev(it) + 1) { return true; }
+ if (*it != *std::prev(it) + 1) {
+ return true;
+ }
}
return false;
}
-static bool ProtobufIdSanityCheck(const StructDef &struct_def,
+static bool ProtobufIdSanityCheck(const StructDef& struct_def,
IDLOptions::ProtoIdGapAction gap_action,
bool no_log = false) {
- const auto &fields = struct_def.fields.vec;
+ const auto& fields = struct_def.fields.vec;
if (HasNonPositiveFieldId(fields)) {
// TODO: Use LogCompilerWarn
if (!no_log) {
@@ -167,7 +180,9 @@
fprintf(stderr, "Fields in struct %s have gap between ids\n",
struct_def.name.c_str());
}
- if (gap_action == IDLOptions::ProtoIdGapAction::ERROR) { return false; }
+ if (gap_action == IDLOptions::ProtoIdGapAction::ERROR) {
+ return false;
+ }
}
}
@@ -184,9 +199,9 @@
};
static ProtobufToFbsIdMap MapProtoIdsToFieldsId(
- const StructDef &struct_def, IDLOptions::ProtoIdGapAction gap_action,
+ const StructDef& struct_def, IDLOptions::ProtoIdGapAction gap_action,
bool no_log) {
- const auto &fields = struct_def.fields.vec;
+ const auto& fields = struct_def.fields.vec;
if (!HasFieldWithId(fields)) {
ProtobufToFbsIdMap result;
@@ -194,14 +209,16 @@
return result;
}
- if (!ProtobufIdSanityCheck(struct_def, gap_action, no_log)) { return {}; }
+ if (!ProtobufIdSanityCheck(struct_def, gap_action, no_log)) {
+ return {};
+ }
static constexpr int UNION_ID = -1;
using ProtoIdFieldNamePair = std::pair<int, std::string>;
std::vector<ProtoIdFieldNamePair> proto_ids;
- for (const auto *field : fields) {
- const auto *id_attribute = field->attributes.Lookup("id");
+ for (const auto* field : fields) {
+ const auto* id_attribute = field->attributes.Lookup("id");
if (id_attribute != nullptr) {
// When we have union but do not use union flag to keep them
if (id_attribute->constant.empty() &&
@@ -224,25 +241,27 @@
std::sort(
std::begin(proto_ids), std::end(proto_ids),
- [](const ProtoIdFieldNamePair &rhs, const ProtoIdFieldNamePair &lhs) {
+ [](const ProtoIdFieldNamePair& rhs, const ProtoIdFieldNamePair& lhs) {
return rhs.first < lhs.first;
});
struct ProtobufToFbsIdMap proto_to_fbs;
voffset_t id = 0;
- for (const auto &element : proto_ids) {
- if (element.first == UNION_ID) { id++; }
+ for (const auto& element : proto_ids) {
+ if (element.first == UNION_ID) {
+ id++;
+ }
proto_to_fbs.field_to_id.emplace(element.second, id++);
}
proto_to_fbs.successful = true;
return proto_to_fbs;
}
-static void GenNameSpace(const Namespace &name_space, std::string *_schema,
- const Namespace **last_namespace) {
+static void GenNameSpace(const Namespace& name_space, std::string* _schema,
+ const Namespace** last_namespace) {
if (*last_namespace == &name_space) return;
*last_namespace = &name_space;
- auto &schema = *_schema;
+ auto& schema = *_schema;
schema += "namespace ";
for (auto it = name_space.components.begin();
it != name_space.components.end(); ++it) {
@@ -253,14 +272,14 @@
}
// Generate a flatbuffer schema from the Parser's internal representation.
-static std::string GenerateFBS(const Parser &parser,
- const std::string &file_name,
+static std::string GenerateFBS(const Parser& parser,
+ const std::string& file_name,
bool no_log = false) {
// Proto namespaces may clash with table names, escape the ones that were
// generated from a table:
for (auto it = parser.namespaces_.begin(); it != parser.namespaces_.end();
++it) {
- auto &ns = **it;
+ auto& ns = **it;
for (size_t i = 0; i < ns.from_table; i++) {
ns.components[ns.components.size() - 1 - i] += "_";
}
@@ -298,10 +317,10 @@
}
// Generate code for all the enum declarations.
- const Namespace *last_namespace = nullptr;
+ const Namespace* last_namespace = nullptr;
for (auto enum_def_it = parser.enums_.vec.begin();
enum_def_it != parser.enums_.vec.end(); ++enum_def_it) {
- EnumDef &enum_def = **enum_def_it;
+ EnumDef& enum_def = **enum_def_it;
if (parser.opts.include_dependence_headers && enum_def.generated) {
continue;
}
@@ -316,7 +335,7 @@
schema += GenType(enum_def.underlying_type, true) + " {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
GenComment(ev.doc_comment, &schema, nullptr, " ");
if (enum_def.is_union) {
schema += " " + GenType(ev.union_type) + ",\n";
@@ -329,10 +348,12 @@
// Generate code for all structs/tables.
for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
++it) {
- StructDef &struct_def = **it;
+ StructDef& struct_def = **it;
const auto proto_fbs_ids = MapProtoIdsToFieldsId(
struct_def, parser.opts.proto_id_gap_action, no_log);
- if (!proto_fbs_ids.successful) { return {}; }
+ if (!proto_fbs_ids.successful) {
+ return {};
+ }
if (parser.opts.include_dependence_headers && struct_def.generated) {
continue;
@@ -343,7 +364,7 @@
schema += "table " + struct_def.name + " {\n";
for (auto field_it = struct_def.fields.vec.begin();
field_it != struct_def.fields.vec.end(); ++field_it) {
- auto &field = **field_it;
+ auto& field = **field_it;
if (field.value.type.base_type != BASE_TYPE_UTYPE) {
GenComment(field.doc_comment, &schema, nullptr, " ");
schema += " " + field.name + ":" + GenType(field.value.type);
@@ -361,7 +382,7 @@
if (!attributes.empty()) {
schema += " (";
- for (const auto &attribute : attributes) {
+ for (const auto& attribute : attributes) {
schema += attribute + ",";
}
schema.pop_back();
@@ -376,10 +397,12 @@
return schema;
}
-static bool GenerateFBS(const Parser &parser, const std::string &path,
- const std::string &file_name, bool no_log = false) {
+static bool GenerateFBS(const Parser& parser, const std::string& path,
+ const std::string& file_name, bool no_log = false) {
const std::string fbs = GenerateFBS(parser, file_name, no_log);
- if (fbs.empty()) { return false; }
+ if (fbs.empty()) {
+ return false;
+ }
// TODO: Use LogCompilerWarn
if (!no_log) {
fprintf(stderr,
@@ -393,28 +416,29 @@
public:
explicit FBSCodeGenerator(const bool no_log) : no_log_(no_log) {}
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateFBS(parser, path, filename, no_log_)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateFBS(parser, path, filename, no_log_)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCodeString(const Parser &parser, const std::string &filename,
- std::string &output) override {
+ Status GenerateCodeString(const Parser& parser, const std::string& filename,
+ std::string& output) override {
output = GenerateFBS(parser, filename, no_log_);
return Status::OK;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -422,16 +446,16 @@
return Status::NOT_IMPLEMENTED;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_go.cpp b/src/idl_gen_go.cpp
index 6bbc5dc..f4a03ce 100644
--- a/src/idl_gen_go.cpp
+++ b/src/idl_gen_go.cpp
@@ -31,12 +31,12 @@
#include "idl_namer.h"
#ifdef _WIN32
-# include <direct.h>
-# define PATH_SEPARATOR "\\"
-# define mkdir(n, m) _mkdir(n)
+#include <direct.h>
+#define PATH_SEPARATOR "\\"
+#define mkdir(n, m) _mkdir(n)
#else
-# include <sys/stat.h>
-# define PATH_SEPARATOR "/"
+#include <sys/stat.h>
+#define PATH_SEPARATOR "/"
#endif
namespace flatbuffers {
@@ -48,11 +48,11 @@
// see https://golang.org/ref/spec#Keywords
static std::set<std::string> GoKeywords() {
return {
- "break", "default", "func", "interface", "select",
- "case", "defer", "go", "map", "struct",
- "chan", "else", "goto", "package", "switch",
- "const", "fallthrough", "if", "range", "type",
- "continue", "for", "import", "return", "var",
+ "break", "default", "func", "interface", "select",
+ "case", "defer", "go", "map", "struct",
+ "chan", "else", "goto", "package", "switch",
+ "const", "fallthrough", "if", "range", "type",
+ "continue", "for", "import", "return", "var",
};
}
@@ -60,34 +60,34 @@
// Note that the functions with user defined types in the name use
// upper camel case for all but the user defined type itself, which is keep
// cased. Despite being a function, we interpret it as a Type.
- return { /*types=*/Case::kKeep,
- /*constants=*/Case::kUnknown,
- /*methods=*/Case::kUpperCamel,
- /*functions=*/Case::kUpperCamel,
- /*fields=*/Case::kUpperCamel,
- /*variables=*/Case::kLowerCamel,
- /*variants=*/Case::kKeep,
- /*enum_variant_seperator=*/"", // I.e. Concatenate.
- /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
- /*namespaces=*/Case::kKeep,
- /*namespace_seperator=*/"__",
- /*object_prefix=*/"",
- /*object_suffix=*/"T",
- /*keyword_prefix=*/"",
- /*keyword_suffix=*/"_",
- /*filenames=*/Case::kKeep,
- /*directories=*/Case::kKeep,
- /*output_path=*/"",
- /*filename_suffix=*/"",
- /*filename_extension=*/".go" };
+ return {/*types=*/Case::kKeep,
+ /*constants=*/Case::kUnknown,
+ /*methods=*/Case::kUpperCamel,
+ /*functions=*/Case::kUpperCamel,
+ /*fields=*/Case::kUpperCamel,
+ /*variables=*/Case::kLowerCamel,
+ /*variants=*/Case::kKeep,
+ /*enum_variant_seperator=*/"", // I.e. Concatenate.
+ /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
+ /*namespaces=*/Case::kKeep,
+ /*namespace_seperator=*/"__",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kKeep,
+ /*directories=*/Case::kKeep,
+ /*output_path=*/"",
+ /*filename_suffix=*/"",
+ /*filename_extension=*/".go"};
}
} // namespace
class GoGenerator : public BaseGenerator {
public:
- GoGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name, const std::string &go_namespace)
+ GoGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name, const std::string& go_namespace)
: BaseGenerator(parser, path, file_name, "" /* not used*/,
"" /* not used */, "go"),
cur_name_space_(nullptr),
@@ -120,7 +120,7 @@
}
private:
- bool generateEnums(std::string *one_file_code) {
+ bool generateEnums(std::string* one_file_code) {
bool needs_imports = false;
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
@@ -128,7 +128,7 @@
needs_imports = false;
ResetImports();
}
- auto &enum_def = **it;
+ auto& enum_def = **it;
std::string enumcode;
GenEnum(enum_def, &enumcode);
if (enum_def.is_union && parser_.opts.generate_object_based_api) {
@@ -144,7 +144,7 @@
return true;
}
- void GenNativeUnionCreator(const EnumDef &enum_def, std::string *code_ptr) {
+ void GenNativeUnionCreator(const EnumDef& enum_def, std::string* code_ptr) {
if (enum_def.generated) return;
GenNativeUnion(enum_def, code_ptr);
@@ -152,12 +152,14 @@
GenNativeUnionUnPack(enum_def, code_ptr);
}
- bool generateStructs(std::string *one_file_code) {
+ bool generateStructs(std::string* one_file_code) {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
- if (!parser_.opts.one_file) { ResetImports(); }
+ if (!parser_.opts.one_file) {
+ ResetImports();
+ }
std::string declcode;
- auto &struct_def = **it;
+ auto& struct_def = **it;
GenStruct(struct_def, &declcode);
if (parser_.opts.one_file) {
*one_file_code += declcode;
@@ -169,28 +171,28 @@
}
Namespace go_namespace_;
- Namespace *cur_name_space_;
+ Namespace* cur_name_space_;
const IdlNamer namer_;
struct NamespacePtrLess {
- bool operator()(const Definition *a, const Definition *b) const {
+ bool operator()(const Definition* a, const Definition* b) const {
return *a->defined_namespace < *b->defined_namespace;
}
};
- std::set<const Definition *, NamespacePtrLess> tracked_imported_namespaces_;
+ std::set<const Definition*, NamespacePtrLess> tracked_imported_namespaces_;
bool needs_math_import_ = false;
bool needs_bytes_import_ = false;
// Most field accessors need to retrieve and test the field offset first,
// this is the prefix code for that.
- std::string OffsetPrefix(const FieldDef &field) {
+ std::string OffsetPrefix(const FieldDef& field) {
return "{\n\to := flatbuffers.UOffsetT(rcv._tab.Offset(" +
NumToString(field.value.offset) + "))\n\tif o != 0 {\n";
}
// Begin a class declaration.
- void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void BeginClass(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "type " + namer_.Type(struct_def) + " struct {\n\t";
@@ -202,27 +204,27 @@
}
// Construct the name of the type for this enum.
- std::string GetEnumTypeName(const EnumDef &enum_def) {
+ std::string GetEnumTypeName(const EnumDef& enum_def) {
return WrapInNameSpaceAndTrack(&enum_def, namer_.Type(enum_def));
}
// Create a type for the enum values.
- void GenEnumType(const EnumDef &enum_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GenEnumType(const EnumDef& enum_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "type " + GetEnumTypeName(enum_def) + " ";
code += GenTypeBasic(enum_def.underlying_type) + "\n\n";
}
// Begin enum code with a class declaration.
- void BeginEnum(std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void BeginEnum(std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "const (\n";
}
// A single enum member.
- void EnumMember(const EnumDef &enum_def, const EnumVal &ev,
- size_t max_name_length, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void EnumMember(const EnumDef& enum_def, const EnumVal& ev,
+ size_t max_name_length, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "\t";
code += namer_.EnumVariant(enum_def, ev);
code += " ";
@@ -233,23 +235,23 @@
}
// End enum code.
- void EndEnum(std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void EndEnum(std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += ")\n\n";
}
// Begin enum name map.
- void BeginEnumNames(const EnumDef &enum_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void BeginEnumNames(const EnumDef& enum_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "var EnumNames";
code += enum_def.name;
code += " = map[" + GetEnumTypeName(enum_def) + "]string{\n";
}
// A single enum name member.
- void EnumNameMember(const EnumDef &enum_def, const EnumVal &ev,
- size_t max_name_length, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void EnumNameMember(const EnumDef& enum_def, const EnumVal& ev,
+ size_t max_name_length, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "\t";
code += namer_.EnumVariant(enum_def, ev);
code += ": ";
@@ -260,14 +262,14 @@
}
// End enum name map.
- void EndEnumNames(std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void EndEnumNames(std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "}\n\n";
}
// Generate String() method on enum type.
- void EnumStringer(const EnumDef &enum_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void EnumStringer(const EnumDef& enum_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
const std::string enum_type = namer_.Type(enum_def);
code += "func (v " + enum_type + ") String() string {\n";
code += "\tif s, ok := EnumNames" + enum_type + "[v]; ok {\n";
@@ -279,17 +281,17 @@
}
// Begin enum value map.
- void BeginEnumValues(const EnumDef &enum_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void BeginEnumValues(const EnumDef& enum_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "var EnumValues";
code += namer_.Type(enum_def);
code += " = map[string]" + GetEnumTypeName(enum_def) + "{\n";
}
// A single enum value member.
- void EnumValueMember(const EnumDef &enum_def, const EnumVal &ev,
- size_t max_name_length, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void EnumValueMember(const EnumDef& enum_def, const EnumVal& ev,
+ size_t max_name_length, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "\t\"";
code += ev.name;
code += "\": ";
@@ -299,16 +301,16 @@
}
// End enum value map.
- void EndEnumValues(std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void EndEnumValues(std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "}\n\n";
}
// Initialize a new struct or table from existing data.
- void NewRootTypeFromBuffer(const StructDef &struct_def,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
- const std::string size_prefix[] = { "", "SizePrefixed" };
+ void NewRootTypeFromBuffer(const StructDef& struct_def,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
+ const std::string size_prefix[] = {"", "SizePrefixed"};
const std::string struct_type = namer_.Type(struct_def);
bool has_file_identifier = (parser_.root_struct_def_ == &struct_def) &&
@@ -363,8 +365,8 @@
}
// Initialize an existing object with other data, to avoid an allocation.
- void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void InitializeExisting(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += " Init(buf []byte, i flatbuffers.UOffsetT) ";
@@ -375,8 +377,8 @@
}
// Implement the table accessor
- void GenTableAccessor(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GenTableAccessor(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += " Table() flatbuffers.Table ";
@@ -391,9 +393,9 @@
}
// Get the length of a vector.
- void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetVectorLen(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += " " + namer_.Function(field) + "Length(";
@@ -403,9 +405,9 @@
}
// Get a [ubyte] vector as a byte slice.
- void GetUByteSlice(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetUByteSlice(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += " " + namer_.Function(field) + "Bytes(";
@@ -415,9 +417,9 @@
}
// Get the value of a struct's scalar.
- void GetScalarFieldOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetScalarFieldOfStruct(const StructDef& struct_def,
+ const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
code += " " + namer_.Function(field);
@@ -430,9 +432,9 @@
}
// Get the value of a table's scalar.
- void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetScalarFieldOfTable(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
code += " " + namer_.Function(field);
@@ -444,7 +446,9 @@
code += "\t\treturn ";
}
code += CastToEnum(field.value.type, getter + "(o + rcv._tab.Pos)");
- if (field.IsScalarOptional()) { code += "\n\t\treturn &v"; }
+ if (field.IsScalarOptional()) {
+ code += "\n\t\treturn &v";
+ }
code += "\n\t}\n";
code += "\treturn " + GenConstant(field) + "\n";
code += "}\n\n";
@@ -452,9 +456,9 @@
// Get a struct by initializing an existing struct.
// Specific to Struct.
- void GetStructFieldOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetStructFieldOfStruct(const StructDef& struct_def,
+ const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += " " + namer_.Function(field);
code += "(obj *" + TypeName(field);
@@ -471,9 +475,9 @@
// Get a struct by initializing an existing struct.
// Specific to Table.
- void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetStructFieldOfTable(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += " " + namer_.Function(field);
code += "(obj *";
@@ -493,9 +497,9 @@
}
// Get the value of a string.
- void GetStringField(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetStringField(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += " " + namer_.Function(field);
code += "() " + TypeName(field) + " ";
@@ -505,9 +509,9 @@
}
// Get the value of a union from an object.
- void GetUnionField(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetUnionField(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += " " + namer_.Function(field) + "(";
code += "obj " + GenTypePointer(field.value.type) + ") bool ";
@@ -519,9 +523,9 @@
}
// Get the value of a vector's struct member.
- void GetMemberOfVectorOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetMemberOfVectorOfStruct(const StructDef& struct_def,
+ const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
@@ -540,21 +544,21 @@
code += "}\n\n";
}
- void GetMemberOfVectorOfStructByKey(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetMemberOfVectorOfStructByKey(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
FLATBUFFERS_ASSERT(vectortype.struct_def->has_key);
- auto &vector_struct_fields = vectortype.struct_def->fields.vec;
+ auto& vector_struct_fields = vectortype.struct_def->fields.vec;
auto kit =
std::find_if(vector_struct_fields.begin(), vector_struct_fields.end(),
- [&](FieldDef *vector_struct_field) {
+ [&](FieldDef* vector_struct_field) {
return vector_struct_field->key;
});
- auto &key_field = **kit;
+ auto& key_field = **kit;
FLATBUFFERS_ASSERT(key_field.key);
GenReceiver(struct_def, code_ptr);
@@ -571,10 +575,10 @@
}
// Get the value of a vector's non-struct member.
- void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetMemberOfVectorOfNonStruct(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
@@ -599,8 +603,8 @@
}
// Begin the creator function signature.
- void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void BeginBuilderArgs(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
if (code.substr(code.length() - 2) != "\n\n") {
// a previous mutate has not put an extra new line
@@ -612,11 +616,11 @@
// Recursively generate arguments for a constructor, to deal with nested
// structs.
- void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix,
- std::string *code_ptr) {
+ void StructBuilderArgs(const StructDef& struct_def, const char* nameprefix,
+ std::string* code_ptr) {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (IsStruct(field.value.type)) {
// Generate arguments for a struct inside a struct. To ensure names
// don't clash, and to make it obvious these arguments are constructing
@@ -624,7 +628,7 @@
StructBuilderArgs(*field.value.type.struct_def,
(nameprefix + (field.name + "_")).c_str(), code_ptr);
} else {
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
code += std::string(", ") + nameprefix;
code += namer_.Variable(field);
code += " " + TypeName(field);
@@ -633,21 +637,21 @@
}
// End the creator function signature.
- void EndBuilderArgs(std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void EndBuilderArgs(std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += ") flatbuffers.UOffsetT {\n";
}
// Recursively generate struct construction statements and instert manual
// padding.
- void StructBuilderBody(const StructDef &struct_def, const char *nameprefix,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void StructBuilderBody(const StructDef& struct_def, const char* nameprefix,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "\tbuilder.Prep(" + NumToString(struct_def.minalign) + ", ";
code += NumToString(struct_def.bytesize) + ")\n";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.padding)
code += "\tbuilder.Pad(" + NumToString(field.padding) + ")\n";
if (IsStruct(field.value.type)) {
@@ -662,15 +666,15 @@
}
}
- void EndBuilderBody(std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void EndBuilderBody(std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "\treturn builder.Offset()\n";
code += "}\n";
}
// Get the value of a table's starting offset.
- void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetStartOfTable(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "func " + namer_.Type(struct_def) + "Start";
code += "(builder *flatbuffers.Builder) {\n";
code += "\tbuilder.StartObject(";
@@ -679,9 +683,9 @@
}
// Set the value of a table's field.
- void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- const size_t offset, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void BuildFieldOfTable(const StructDef& struct_def, const FieldDef& field,
+ const size_t offset, std::string* code_ptr) {
+ std::string& code = *code_ptr;
const std::string field_var = namer_.Variable(field);
code += "func " + namer_.Type(struct_def) + "Add" + namer_.Function(field);
code += "(builder *flatbuffers.Builder, ";
@@ -716,9 +720,9 @@
}
// Set the value of one of the members of a table's vector.
- void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void BuildVectorOfTable(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "func " + namer_.Type(struct_def) + "Start";
code += namer_.Function(field);
code += "Vector(builder *flatbuffers.Builder, numElems int) ";
@@ -732,22 +736,22 @@
}
// Get the offset of the end of a table.
- void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetEndOffsetOnTable(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "func " + namer_.Type(struct_def) + "End";
code += "(builder *flatbuffers.Builder) flatbuffers.UOffsetT ";
code += "{\n\treturn builder.EndObject()\n}\n";
}
// Generate the receiver for function signatures.
- void GenReceiver(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GenReceiver(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "func (rcv *" + namer_.Type(struct_def) + ")";
}
// Generate a struct field getter, conditioned on its child type(s).
- void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ void GenStructAccessor(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
GenComment(field.doc_comment, code_ptr, nullptr, "");
if (IsScalar(field.value.type.base_type)) {
if (struct_def.fixed) {
@@ -782,8 +786,11 @@
}
break;
}
- case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr); break;
- default: FLATBUFFERS_ASSERT(0);
+ case BASE_TYPE_UNION:
+ GetUnionField(struct_def, field, code_ptr);
+ break;
+ default:
+ FLATBUFFERS_ASSERT(0);
}
}
if (IsVector(field.value.type)) {
@@ -795,9 +802,9 @@
}
// Mutate the value of a struct's scalar.
- void MutateScalarFieldOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void MutateScalarFieldOfStruct(const StructDef& struct_def,
+ const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
std::string setter =
"rcv._tab.Mutate" + namer_.Method(GenTypeBasic(field.value.type));
GenReceiver(struct_def, code_ptr);
@@ -810,9 +817,9 @@
}
// Mutate the value of a table's scalar.
- void MutateScalarFieldOfTable(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void MutateScalarFieldOfTable(const StructDef& struct_def,
+ const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
std::string setter = "rcv._tab.Mutate" +
namer_.Method(GenTypeBasic(field.value.type)) + "Slot";
GenReceiver(struct_def, code_ptr);
@@ -824,10 +831,10 @@
}
// Mutate an element of a vector of scalars.
- void MutateElementOfVectorOfNonStruct(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void MutateElementOfVectorOfNonStruct(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
std::string setter =
"rcv._tab.Mutate" + namer_.Method(GenTypeBasic(vectortype));
@@ -846,8 +853,8 @@
}
// Generate a struct field setter, conditioned on its child type(s).
- void GenStructMutator(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ void GenStructMutator(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
GenComment(field.doc_comment, code_ptr, nullptr, "");
if (IsScalar(field.value.type.base_type)) {
if (struct_def.fixed) {
@@ -863,12 +870,12 @@
}
// Generate table constructors, conditioned on its members' types.
- void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
+ void GenTableBuilders(const StructDef& struct_def, std::string* code_ptr) {
GetStartOfTable(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
auto offset = it - struct_def.fields.vec.begin();
@@ -882,7 +889,7 @@
}
// Generate struct or table methods.
- void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStruct(const StructDef& struct_def, std::string* code_ptr) {
if (struct_def.generated) return;
cur_name_space_ = struct_def.defined_namespace;
@@ -906,7 +913,7 @@
// Generate struct fields accessors
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
GenStructAccessor(struct_def, field, code_ptr);
@@ -929,11 +936,11 @@
}
}
- void GenKeyCompare(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ void GenKeyCompare(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
FLATBUFFERS_ASSERT(struct_def.has_key);
FLATBUFFERS_ASSERT(field.key);
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
code += "func " + namer_.Type(struct_def) + "KeyCompare(";
code += "o1, o2 flatbuffers.UOffsetT, buf []byte) bool {\n";
@@ -951,11 +958,11 @@
code += "}\n\n";
}
- void GenLookupByKey(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ void GenLookupByKey(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
FLATBUFFERS_ASSERT(struct_def.has_key);
FLATBUFFERS_ASSERT(field.key);
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += " LookupByKey(";
@@ -964,7 +971,9 @@
code += "buf []byte) bool {\n";
code += "\tspan := flatbuffers.GetUOffsetT(buf[vectorLocation-4:])\n";
code += "\tstart := flatbuffers.UOffsetT(0)\n";
- if (IsString(field.value.type)) { code += "\tbKey := []byte(key)\n"; }
+ if (IsString(field.value.type)) {
+ code += "\tbKey := []byte(key)\n";
+ }
code += "\tfor span != 0 {\n";
code += "\t\tmiddle := span / 2\n";
code += "\t\ttableOffset := flatbuffers.GetIndirectOffset(buf, ";
@@ -1002,20 +1011,22 @@
code += "}\n\n";
}
- void GenNativeStruct(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GenNativeStruct(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "type " + NativeName(struct_def) + " struct {\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const FieldDef &field = **it;
+ const FieldDef& field = **it;
if (field.deprecated) continue;
if (IsScalar(field.value.type.base_type) &&
field.value.type.enum_def != nullptr &&
field.value.type.enum_def->is_union)
continue;
code += "\t" + namer_.Field(field) + " ";
- if (field.IsScalarOptional()) { code += "*"; }
+ if (field.IsScalarOptional()) {
+ code += "*";
+ }
code += NativeType(field.value.type) + " `json:\"" + field.name + "\"`" +
"\n";
}
@@ -1030,20 +1041,20 @@
}
}
- void GenNativeUnion(const EnumDef &enum_def, std::string *code_ptr) {
+ void GenNativeUnion(const EnumDef& enum_def, std::string* code_ptr) {
if (enum_def.generated) return;
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
code += "type " + NativeName(enum_def) + " struct {\n";
code += "\tType " + namer_.Type(enum_def) + "\n";
code += "\tValue interface{}\n";
code += "}\n\n";
}
- void GenNativeUnionPack(const EnumDef &enum_def, std::string *code_ptr) {
+ void GenNativeUnionPack(const EnumDef& enum_def, std::string* code_ptr) {
if (enum_def.generated) return;
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
code += "func (t *" + NativeName(enum_def) +
") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
code += "\tif t == nil {\n\t\treturn 0\n\t}\n";
@@ -1051,7 +1062,7 @@
code += "\tswitch t.Type {\n";
for (auto it2 = enum_def.Vals().begin(); it2 != enum_def.Vals().end();
++it2) {
- const EnumVal &ev = **it2;
+ const EnumVal& ev = **it2;
if (ev.IsZero()) continue;
code += "\tcase " + namer_.EnumVariant(enum_def, ev) + ":\n";
code += "\t\treturn t.Value.(" + NativeType(ev.union_type) +
@@ -1062,10 +1073,10 @@
code += "}\n\n";
}
- void GenNativeUnionUnPack(const EnumDef &enum_def, std::string *code_ptr) {
+ void GenNativeUnionUnPack(const EnumDef& enum_def, std::string* code_ptr) {
if (enum_def.generated) return;
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
code += "func (rcv " + namer_.Type(enum_def) +
") UnPack(table flatbuffers.Table) *" + NativeName(enum_def) +
@@ -1074,7 +1085,7 @@
for (auto it2 = enum_def.Vals().begin(); it2 != enum_def.Vals().end();
++it2) {
- const EnumVal &ev = **it2;
+ const EnumVal& ev = **it2;
if (ev.IsZero()) continue;
code += "\tcase " + namer_.EnumVariant(enum_def, ev) + ":\n";
code += "\t\tvar x " +
@@ -1093,8 +1104,8 @@
code += "}\n\n";
}
- void GenNativeTablePack(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GenNativeTablePack(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
const std::string struct_type = namer_.Type(struct_def);
code += "func (t *" + NativeName(struct_def) +
@@ -1102,7 +1113,7 @@
code += "\tif t == nil {\n\t\treturn 0\n\t}\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const FieldDef &field = **it;
+ const FieldDef& field = **it;
if (field.deprecated) continue;
if (IsScalar(field.value.type.base_type)) continue;
@@ -1177,7 +1188,7 @@
code += "\t" + struct_type + "Start(builder)\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const FieldDef &field = **it;
+ const FieldDef& field = **it;
if (field.deprecated) continue;
const std::string field_field = namer_.Field(field);
const std::string field_fn = namer_.Function(field);
@@ -1194,7 +1205,9 @@
code += "\t" + struct_type + "Add" + field_fn + "(builder, " +
prefix + "t." + field_field + ")\n";
}
- if (field.IsScalarOptional()) { code += "\t}\n"; }
+ if (field.IsScalarOptional()) {
+ code += "\t}\n";
+ }
} else {
if (field.value.type.base_type == BASE_TYPE_STRUCT &&
field.value.type.struct_def->fixed) {
@@ -1215,16 +1228,16 @@
code += "}\n\n";
}
- void GenNativeTableUnPack(const StructDef &struct_def,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GenNativeTableUnPack(const StructDef& struct_def,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
const std::string struct_type = namer_.Type(struct_def);
code += "func (rcv *" + struct_type + ") UnPackTo(t *" +
NativeName(struct_def) + ") {\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const FieldDef &field = **it;
+ const FieldDef& field = **it;
if (field.deprecated) continue;
const std::string field_field = namer_.Field(field);
const std::string field_var = namer_.Variable(field);
@@ -1292,8 +1305,8 @@
code += "}\n\n";
}
- void GenNativeStructPack(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GenNativeStructPack(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "func (t *" + NativeName(struct_def) +
") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
@@ -1304,12 +1317,12 @@
code += "}\n";
}
- void StructPackArgs(const StructDef &struct_def, const char *nameprefix,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void StructPackArgs(const StructDef& struct_def, const char* nameprefix,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const FieldDef &field = **it;
+ const FieldDef& field = **it;
if (field.value.type.base_type == BASE_TYPE_STRUCT) {
StructPackArgs(*field.value.type.struct_def,
(nameprefix + namer_.Field(field) + ".").c_str(),
@@ -1320,15 +1333,15 @@
}
}
- void GenNativeStructUnPack(const StructDef &struct_def,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GenNativeStructUnPack(const StructDef& struct_def,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "func (rcv *" + namer_.Type(struct_def) + ") UnPackTo(t *" +
NativeName(struct_def) + ") {\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const FieldDef &field = **it;
+ const FieldDef& field = **it;
if (field.value.type.base_type == BASE_TYPE_STRUCT) {
code += "\tt." + namer_.Field(field) + " = rcv." +
namer_.Method(field) + "(nil).UnPack()\n";
@@ -1349,7 +1362,7 @@
}
// Generate enum declarations.
- void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
+ void GenEnum(const EnumDef& enum_def, std::string* code_ptr) {
if (enum_def.generated) return;
auto max_name_length = MaxNameLength(enum_def);
@@ -1359,7 +1372,7 @@
GenEnumType(enum_def, code_ptr);
BeginEnum(code_ptr);
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- const EnumVal &ev = **it;
+ const EnumVal& ev = **it;
GenComment(ev.doc_comment, code_ptr, nullptr, "\t");
EnumMember(enum_def, ev, max_name_length, code_ptr);
}
@@ -1367,14 +1380,14 @@
BeginEnumNames(enum_def, code_ptr);
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- const EnumVal &ev = **it;
+ const EnumVal& ev = **it;
EnumNameMember(enum_def, ev, max_name_length, code_ptr);
}
EndEnumNames(code_ptr);
BeginEnumValues(enum_def, code_ptr);
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
EnumValueMember(enum_def, ev, max_name_length, code_ptr);
}
EndEnumValues(code_ptr);
@@ -1383,23 +1396,27 @@
}
// Returns the function name that is able to read a value of the given type.
- std::string GenGetter(const Type &type) {
+ std::string GenGetter(const Type& type) {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "rcv._tab.ByteVector";
- case BASE_TYPE_UNION: return "rcv._tab.Union";
- case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
- default: return "rcv._tab.Get" + namer_.Function(GenTypeBasic(type));
+ case BASE_TYPE_STRING:
+ return "rcv._tab.ByteVector";
+ case BASE_TYPE_UNION:
+ return "rcv._tab.Union";
+ case BASE_TYPE_VECTOR:
+ return GenGetter(type.VectorType());
+ default:
+ return "rcv._tab.Get" + namer_.Function(GenTypeBasic(type));
}
}
// Returns the method name for use with add/put calls.
- std::string GenMethod(const FieldDef &field) {
+ std::string GenMethod(const FieldDef& field) {
return IsScalar(field.value.type.base_type)
? namer_.Method(GenTypeBasic(field.value.type))
: (IsStruct(field.value.type) ? "Struct" : "UOffsetT");
}
- std::string GenTypeBasic(const Type &type) {
+ std::string GenTypeBasic(const Type& type) {
// clang-format off
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, ...) \
@@ -1411,32 +1428,39 @@
return ctypename[type.base_type];
}
- std::string GenTypePointer(const Type &type) {
+ std::string GenTypePointer(const Type& type) {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "[]byte";
- case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
+ case BASE_TYPE_STRING:
+ return "[]byte";
+ case BASE_TYPE_VECTOR:
+ return GenTypeGet(type.VectorType());
case BASE_TYPE_STRUCT:
return WrapInNameSpaceAndTrack(type.struct_def, type.struct_def->name);
case BASE_TYPE_UNION:
// fall through
- default: return "*flatbuffers.Table";
+ default:
+ return "*flatbuffers.Table";
}
}
- std::string GenTypeGet(const Type &type) {
- if (type.enum_def != nullptr) { return GetEnumTypeName(*type.enum_def); }
+ std::string GenTypeGet(const Type& type) {
+ if (type.enum_def != nullptr) {
+ return GetEnumTypeName(*type.enum_def);
+ }
return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
}
- std::string TypeName(const FieldDef &field) {
+ std::string TypeName(const FieldDef& field) {
std::string prefix;
- if (field.IsScalarOptional()) { prefix = "*"; }
+ if (field.IsScalarOptional()) {
+ prefix = "*";
+ }
return prefix + GenTypeGet(field.value.type);
}
// If type is an enum, returns value with a cast to the enum type, otherwise
// returns value as-is.
- std::string CastToEnum(const Type &type, std::string value) {
+ std::string CastToEnum(const Type& type, std::string value) {
if (type.enum_def == nullptr) {
return value;
} else {
@@ -1446,7 +1470,7 @@
// If type is an enum, returns value with a cast to the enum base type,
// otherwise returns value as-is.
- std::string CastToBaseType(const Type &type, std::string value) {
+ std::string CastToBaseType(const Type& type, std::string value) {
if (type.enum_def == nullptr) {
return value;
} else {
@@ -1454,8 +1478,10 @@
}
}
- std::string GenConstant(const FieldDef &field) {
- if (field.IsScalarOptional()) { return "nil"; }
+ std::string GenConstant(const FieldDef& field) {
+ if (field.IsScalarOptional()) {
+ return "nil";
+ }
switch (field.value.type.base_type) {
case BASE_TYPE_BOOL:
return field.value.constant == "0" ? "false" : "true";
@@ -1476,19 +1502,20 @@
}
return field.value.constant;
}
- default: return field.value.constant;
+ default:
+ return field.value.constant;
}
}
- std::string NativeName(const StructDef &struct_def) const {
+ std::string NativeName(const StructDef& struct_def) const {
return namer_.ObjectType(struct_def);
}
- std::string NativeName(const EnumDef &enum_def) const {
+ std::string NativeName(const EnumDef& enum_def) const {
return namer_.ObjectType(enum_def);
}
- std::string NativeType(const Type &type) {
+ std::string NativeType(const Type& type) {
if (IsScalar(type.base_type)) {
if (type.enum_def == nullptr) {
return GenTypeBasic(type);
@@ -1511,7 +1538,7 @@
}
// Create a struct with a builder and the struct's arguments.
- void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStructBuilder(const StructDef& struct_def, std::string* code_ptr) {
BeginBuilderArgs(struct_def, code_ptr);
StructBuilderArgs(struct_def, "", code_ptr);
EndBuilderArgs(code_ptr);
@@ -1521,9 +1548,9 @@
}
// Begin by declaring namespace and imports.
- void BeginFile(const std::string &name_space_name, const bool needs_imports,
- const bool is_enum, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void BeginFile(const std::string& name_space_name, const bool needs_imports,
+ const bool is_enum, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code = code +
"// Code generated by the FlatBuffers compiler. DO NOT EDIT.\n\n";
code += "package " + name_space_name + "\n\n";
@@ -1537,8 +1564,12 @@
code += "\tflatbuffers \"github.com/google/flatbuffers/go\"\n";
}
// math is needed to support non-finite scalar default values.
- if (needs_math_import_) { code += "\t\"math\"\n"; }
- if (is_enum) { code += "\t\"strconv\"\n"; }
+ if (needs_math_import_) {
+ code += "\t\"math\"\n";
+ }
+ if (is_enum) {
+ code += "\t\"strconv\"\n";
+ }
if (tracked_imported_namespaces_.size() > 0) {
code += "\n";
@@ -1555,7 +1586,9 @@
}
code += ")\n\n";
} else {
- if (is_enum) { code += "import \"strconv\"\n\n"; }
+ if (is_enum) {
+ code += "import \"strconv\"\n\n";
+ }
if (needs_math_import_) {
// math is needed to support non-finite scalar default values.
code += "import \"math\"\n\n";
@@ -1571,11 +1604,11 @@
}
// Save out the generated code for a Go Table type.
- bool SaveType(const Definition &def, const std::string &classcode,
+ bool SaveType(const Definition& def, const std::string& classcode,
const bool needs_imports, const bool is_enum) {
if (!classcode.length()) return true;
- Namespace &ns = go_namespace_.components.empty() ? *def.defined_namespace
+ Namespace& ns = go_namespace_.components.empty() ? *def.defined_namespace
: go_namespace_;
std::string code = "";
BeginFile(ns.components.empty() ? def.name : LastNamespacePart(ns),
@@ -1593,12 +1626,12 @@
}
// Create the full name of the imported namespace (format: A__B__C).
- std::string NamespaceImportName(const Namespace *ns) const {
+ std::string NamespaceImportName(const Namespace* ns) const {
return namer_.Namespace(*ns);
}
// Create the full path for the imported namespace (format: A/B/C).
- std::string NamespaceImportPath(const Namespace *ns) const {
+ std::string NamespaceImportPath(const Namespace* ns) const {
std::string path =
namer_.Directories(*ns, SkipDir::OutputPathAndTrailingPathSeparator);
if (!parser_.opts.go_module_name.empty()) {
@@ -1609,8 +1642,8 @@
// Ensure that a type is prefixed with its go package import name if it is
// used outside of its namespace.
- std::string WrapInNameSpaceAndTrack(const Definition *def,
- const std::string &name) {
+ std::string WrapInNameSpaceAndTrack(const Definition* def,
+ const std::string& name) {
if (CurrentNameSpace() == def->defined_namespace) return name;
tracked_imported_namespaces_.insert(def);
if (def->defined_namespace->components.empty())
@@ -1619,9 +1652,9 @@
return NamespaceImportName(def->defined_namespace) + "." + name;
}
- const Namespace *CurrentNameSpace() const { return cur_name_space_; }
+ const Namespace* CurrentNameSpace() const { return cur_name_space_; }
- static size_t MaxNameLength(const EnumDef &enum_def) {
+ static size_t MaxNameLength(const EnumDef& enum_def) {
size_t max = 0;
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
max = std::max((*it)->name.length(), max);
@@ -1631,8 +1664,8 @@
};
} // namespace go
-static bool GenerateGo(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateGo(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
go::GoGenerator generator(parser, path, file_name, parser.opts.go_namespace);
return generator.generate();
}
@@ -1641,20 +1674,21 @@
class GoCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateGo(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateGo(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -1662,14 +1696,16 @@
return Status::NOT_IMPLEMENTED;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateGoGRPC(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateGoGRPC(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_grpc.cpp b/src/idl_gen_grpc.cpp
index 9951b86..dc5bed3 100644
--- a/src/idl_gen_grpc.cpp
+++ b/src/idl_gen_grpc.cpp
@@ -30,8 +30,8 @@
#include "src/compiler/ts_generator.h"
#if defined(_MSC_VER)
-# pragma warning(push)
-# pragma warning(disable : 4512) // C4512: 'class' : assignment operator could
+#pragma warning(push)
+#pragma warning(disable : 4512) // C4512: 'class' : assignment operator could
// not be generated
#endif
@@ -41,7 +41,7 @@
public:
enum Streaming { kNone, kClient, kServer, kBiDi };
- FlatBufMethod(const RPCCall *method) : method_(method) {
+ FlatBufMethod(const RPCCall* method) : method_(method) {
streaming_ = kNone;
auto val = method_->attributes.Lookup("streaming");
if (val) {
@@ -63,7 +63,7 @@
// TODO: This method need to incorporate namespace for C++ side. Other
// language bindings simply don't use this method.
- std::string GRPCType(const StructDef &sd) const {
+ std::string GRPCType(const StructDef& sd) const {
return "flatbuffers::grpc::Message<" + sd.name + ">";
}
@@ -79,7 +79,7 @@
std::string get_output_type_name() const { return (*method_->response).name; }
- bool get_module_and_message_path_input(grpc::string * /*str*/,
+ bool get_module_and_message_path_input(grpc::string* /*str*/,
grpc::string /*generator_file_name*/,
bool /*generate_in_pb2_grpc*/,
grpc::string /*import_prefix*/) const {
@@ -87,7 +87,7 @@
}
bool get_module_and_message_path_output(
- grpc::string * /*str*/, grpc::string /*generator_file_name*/,
+ grpc::string* /*str*/, grpc::string /*generator_file_name*/,
bool /*generate_in_pb2_grpc*/, grpc::string /*import_prefix*/) const {
return true;
}
@@ -107,13 +107,13 @@
bool BidiStreaming() const { return streaming_ == kBiDi; }
private:
- const RPCCall *method_;
+ const RPCCall* method_;
Streaming streaming_;
};
class FlatBufService : public grpc_generator::Service {
public:
- FlatBufService(const ServiceDef *service) : service_(service) {}
+ FlatBufService(const ServiceDef* service) : service_(service) {}
grpc::string GetLeadingComments(const grpc::string) const { return ""; }
@@ -142,20 +142,20 @@
}
private:
- const ServiceDef *service_;
+ const ServiceDef* service_;
};
class FlatBufPrinter : public grpc_generator::Printer {
public:
- FlatBufPrinter(std::string *str, const char indentation_type)
+ FlatBufPrinter(std::string* str, const char indentation_type)
: str_(str),
escape_char_('$'),
indent_(0),
indentation_size_(2),
indentation_type_(indentation_type) {}
- void Print(const std::map<std::string, std::string> &vars,
- const char *string_template) {
+ void Print(const std::map<std::string, std::string>& vars,
+ const char* string_template) {
std::string s = string_template;
// Replace any occurrences of strings in "vars" that are surrounded
// by the escape character by what they're mapped to.
@@ -174,14 +174,16 @@
Print(s.c_str());
}
- void Print(const char *s) {
- if (s == nullptr || *s == '\0') { return; }
+ void Print(const char* s) {
+ if (s == nullptr || *s == '\0') {
+ return;
+ }
// Add this string, but for each part separated by \n, add indentation.
for (;;) {
// Current indentation.
str_->insert(str_->end(), indent_ * indentation_size_, indentation_type_);
// See if this contains more than one line.
- const char *lf = strchr(s, '\n');
+ const char* lf = strchr(s, '\n');
if (lf) {
(*str_) += std::string(s, lf + 1);
s = lf + 1;
@@ -206,7 +208,7 @@
}
private:
- std::string *str_;
+ std::string* str_;
char escape_char_;
size_t indent_;
size_t indentation_size_;
@@ -224,11 +226,11 @@
kLanguageTS
};
- FlatBufFile(const Parser &parser, const std::string &file_name,
+ FlatBufFile(const Parser& parser, const std::string& file_name,
Language language)
: parser_(parser), file_name_(file_name), language_(language) {}
- FlatBufFile &operator=(const FlatBufFile &);
+ FlatBufFile& operator=(const FlatBufFile&);
grpc::string GetLeadingComments(const grpc::string) const { return ""; }
@@ -257,7 +259,7 @@
case kLanguageCpp: {
if (!parser_.opts.grpc_additional_headers.empty()) {
std::string result = "";
- for (const std::string &header :
+ for (const std::string& header :
parser_.opts.grpc_additional_headers) {
if (!result.empty()) result += "\n";
result += "#include \"" + header + "\"";
@@ -295,21 +297,21 @@
}
std::unique_ptr<grpc_generator::Printer> CreatePrinter(
- std::string *str, const char indentation_type = ' ') const {
+ std::string* str, const char indentation_type = ' ') const {
return std::unique_ptr<grpc_generator::Printer>(
new FlatBufPrinter(str, indentation_type));
}
private:
- const Parser &parser_;
- const std::string &file_name_;
+ const Parser& parser_;
+ const std::string& file_name_;
const Language language_;
};
class GoGRPCGenerator : public flatbuffers::BaseGenerator {
public:
- GoGRPCGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ GoGRPCGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", "" /*Unused*/, "go"),
parser_(parser),
path_(path),
@@ -321,7 +323,7 @@
p.custom_method_io_type = "flatbuffers.Builder";
for (int i = 0; i < file.service_count(); i++) {
auto service = file.service(i);
- const Definition *def = parser_.services_.vec[i];
+ const Definition* def = parser_.services_.vec[i];
p.package_name = LastNamespacePart(*(def->defined_namespace));
p.service_prefix =
def->defined_namespace->GetFullyQualifiedName(""); // file.package();
@@ -335,12 +337,12 @@
}
protected:
- const Parser &parser_;
+ const Parser& parser_;
const std::string &path_, &file_name_;
};
-bool GenerateGoGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+bool GenerateGoGRPC(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -350,9 +352,9 @@
return GoGRPCGenerator(parser, path, file_name).generate();
}
-bool GenerateCppGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name) {
- const auto &opts = parser.opts;
+bool GenerateCppGRPC(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
+ const auto& opts = parser.opts;
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -403,8 +405,8 @@
class JavaGRPCGenerator : public flatbuffers::BaseGenerator {
public:
- JavaGRPCGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ JavaGRPCGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", "." /*separator*/, "java") {}
bool generate() {
@@ -412,7 +414,7 @@
grpc_java_generator::Parameters p;
for (int i = 0; i < file.service_count(); i++) {
auto service = file.service(i);
- const Definition *def = parser_.services_.vec[i];
+ const Definition* def = parser_.services_.vec[i];
p.package_name =
def->defined_namespace->GetFullyQualifiedName(""); // file.package();
std::string output =
@@ -425,8 +427,8 @@
}
};
-bool GenerateJavaGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+bool GenerateJavaGRPC(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -436,8 +438,8 @@
return JavaGRPCGenerator(parser, path, file_name).generate();
}
-bool GeneratePythonGRPC(const Parser &parser, const std::string &path,
- const std::string & /*file_name*/) {
+bool GeneratePythonGRPC(const Parser& parser, const std::string& path,
+ const std::string& /*file_name*/) {
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -462,8 +464,8 @@
CodeWriter code_;
public:
- SwiftGRPCGenerator(const Parser &parser, const std::string &path,
- const std::string &filename)
+ SwiftGRPCGenerator(const Parser& parser, const std::string& path,
+ const std::string& filename)
: BaseGenerator(parser, path, filename, "", "" /*Unused*/, "swift") {}
bool generate() {
@@ -480,14 +482,14 @@
return SaveFile(filename.c_str(), final_code, false);
}
- static std::string GeneratedFileName(const std::string &path,
- const std::string &file_name) {
+ static std::string GeneratedFileName(const std::string& path,
+ const std::string& file_name) {
return path + file_name + ".grpc.swift";
}
};
-bool GenerateSwiftGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+bool GenerateSwiftGRPC(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -502,8 +504,8 @@
CodeWriter code_;
public:
- TSGRPCGenerator(const Parser &parser, const std::string &path,
- const std::string &filename)
+ TSGRPCGenerator(const Parser& parser, const std::string& path,
+ const std::string& filename)
: BaseGenerator(parser, path, filename, "", "" /*Unused*/, "ts") {}
bool generate() {
@@ -526,16 +528,16 @@
return true;
}
- static std::string GeneratedFileName(const std::string &path,
- const std::string &file_name,
+ static std::string GeneratedFileName(const std::string& path,
+ const std::string& file_name,
const bool is_interface = false) {
if (is_interface) return path + file_name + "_grpc.d.ts";
return path + file_name + "_grpc.js";
}
};
-bool GenerateTSGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+bool GenerateTSGRPC(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
int nservices = 0;
for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
++it) {
@@ -548,5 +550,5 @@
} // namespace flatbuffers
#if defined(_MSC_VER)
-# pragma warning(pop)
+#pragma warning(pop)
#endif
diff --git a/src/idl_gen_java.cpp b/src/idl_gen_java.cpp
index 51c388d..2979230 100644
--- a/src/idl_gen_java.cpp
+++ b/src/idl_gen_java.cpp
@@ -31,41 +31,41 @@
static Namer::Config JavaDefaultConfig() {
return {
- /*types=*/Case::kKeep,
- /*constants=*/Case::kScreamingSnake,
- /*methods=*/Case::kLowerCamel,
- /*functions=*/Case::kLowerCamel,
- /*fields=*/Case::kLowerCamel,
- /*variables=*/Case::kLowerCamel,
- /*variants=*/Case::kKeep,
- /*enum_variant_seperator=*/".",
- /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
- /*namespaces=*/Case::kKeep,
- /*namespace_seperator=*/".",
- /*object_prefix=*/"",
- /*object_suffix=*/"T",
- /*keyword_prefix=*/"",
- /*keyword_suffix=*/"_",
- /*filenames=*/Case::kKeep,
- /*directories=*/Case::kKeep,
- /*output_path=*/"",
- /*filename_suffix=*/"_generated",
- /*filename_extension=*/".java",
+ /*types=*/Case::kKeep,
+ /*constants=*/Case::kScreamingSnake,
+ /*methods=*/Case::kLowerCamel,
+ /*functions=*/Case::kLowerCamel,
+ /*fields=*/Case::kLowerCamel,
+ /*variables=*/Case::kLowerCamel,
+ /*variants=*/Case::kKeep,
+ /*enum_variant_seperator=*/".",
+ /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
+ /*namespaces=*/Case::kKeep,
+ /*namespace_seperator=*/".",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kKeep,
+ /*directories=*/Case::kKeep,
+ /*output_path=*/"",
+ /*filename_suffix=*/"_generated",
+ /*filename_extension=*/".java",
};
}
static std::set<std::string> JavaKeywords() {
return {
- "abstract", "continue", "for", "new", "switch",
- "assert", "default", "goto", "package", "synchronized",
- "boolean", "do", "if", "private", "this",
- "break", "double", "implements", "protected", "throw",
- "byte", "else", "import", "public", "throws",
- "case", "enum", "instanceof", "return", "transient",
- "catch", "extends", "int", "short", "try",
- "char", "final", "interface", "static", "void",
- "class", "finally", "long", "strictfp", "volatile",
- "const", "float", "native", "super", "while",
+ "abstract", "continue", "for", "new", "switch",
+ "assert", "default", "goto", "package", "synchronized",
+ "boolean", "do", "if", "private", "this",
+ "break", "double", "implements", "protected", "throw",
+ "byte", "else", "import", "public", "throws",
+ "case", "enum", "instanceof", "return", "transient",
+ "catch", "extends", "int", "short", "try",
+ "char", "final", "interface", "static", "void",
+ "class", "finally", "long", "strictfp", "volatile",
+ "const", "float", "native", "super", "while",
};
}
@@ -75,9 +75,9 @@
"NEGATIVE_INFINITY");
static const CommentConfig comment_config = {
- "/**",
- " *",
- " */",
+ "/**",
+ " *",
+ " */",
};
} // namespace
@@ -89,8 +89,8 @@
};
public:
- JavaGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name, const std::string &package_prefix)
+ JavaGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name, const std::string& package_prefix)
: BaseGenerator(parser, path, file_name, "", ".", "java"),
cur_name_space_(nullptr),
namer_(WithFlagOptions(JavaDefaultConfig(), parser.opts, path),
@@ -105,7 +105,7 @@
}
}
- JavaGenerator &operator=(const JavaGenerator &);
+ JavaGenerator& operator=(const JavaGenerator&);
bool generate() {
std::string one_file_code;
cur_name_space_ = parser_.current_namespace_;
@@ -113,7 +113,7 @@
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
std::string enumcode;
- auto &enum_def = **it;
+ auto& enum_def = **it;
if (!parser_.opts.one_file) cur_name_space_ = enum_def.defined_namespace;
GenEnum(enum_def, enumcode);
if (parser_.opts.one_file) {
@@ -141,7 +141,7 @@
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
std::string declcode;
- auto &struct_def = **it;
+ auto& struct_def = **it;
if (!parser_.opts.one_file)
cur_name_space_ = struct_def.defined_namespace;
GenStruct(struct_def, declcode, parser_.opts);
@@ -176,8 +176,8 @@
// Save out the generated code for a single class while adding
// declaration boilerplate.
- bool SaveType(const std::string &defname, const Namespace &ns,
- const std::string &classcode, bool needs_includes) const {
+ bool SaveType(const std::string& defname, const Namespace& ns,
+ const std::string& classcode, bool needs_includes) const {
if (!classcode.length()) return true;
std::string code;
@@ -228,9 +228,9 @@
return SaveFile(filename.c_str(), code, false);
}
- const Namespace *CurrentNameSpace() const { return cur_name_space_; }
+ const Namespace* CurrentNameSpace() const { return cur_name_space_; }
- std::string GenNullableAnnotation(const Type &t) const {
+ std::string GenNullableAnnotation(const Type& t) const {
return parser_.opts.gen_nullable &&
!IsScalar(DestinationType(t, true).base_type) &&
t.base_type != BASE_TYPE_VECTOR
@@ -238,14 +238,14 @@
: "";
}
- std::string GenPureAnnotation(const Type &t) const {
+ std::string GenPureAnnotation(const Type& t) const {
return parser_.opts.java_checkerframework &&
!IsScalar(DestinationType(t, true).base_type)
? " @Pure "
: "";
}
- std::string GenTypeBasic(const Type &type) const {
+ std::string GenTypeBasic(const Type& type) const {
// clang-format off
static const char * const java_typename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, ...) \
@@ -257,18 +257,22 @@
return java_typename[type.base_type];
}
- std::string GenTypePointer(const Type &type) const {
+ std::string GenTypePointer(const Type& type) const {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "String";
- case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
+ case BASE_TYPE_STRING:
+ return "String";
+ case BASE_TYPE_VECTOR:
+ return GenTypeGet(type.VectorType());
case BASE_TYPE_STRUCT:
return Prefixed(namer_.NamespacedType(*type.struct_def));
- case BASE_TYPE_UNION: FLATBUFFERS_FALLTHROUGH(); // else fall thru
- default: return "Table";
+ case BASE_TYPE_UNION:
+ FLATBUFFERS_FALLTHROUGH(); // else fall thru
+ default:
+ return "Table";
}
}
- std::string GenTypeGet(const Type &type) const {
+ std::string GenTypeGet(const Type& type) const {
return IsScalar(type.base_type)
? GenTypeBasic(type)
: (IsArray(type) ? GenTypeGet(type.VectorType())
@@ -277,49 +281,57 @@
// Find the destination type the user wants to receive the value in (e.g.
// one size higher signed types for unsigned serialized values in Java).
- Type DestinationType(const Type &type, bool vectorelem) const {
+ Type DestinationType(const Type& type, bool vectorelem) const {
switch (type.base_type) {
// We use int for both uchar/ushort, since that generally means less
// casting than using short for uchar.
- case BASE_TYPE_UCHAR: return Type(BASE_TYPE_INT);
- case BASE_TYPE_USHORT: return Type(BASE_TYPE_INT);
- case BASE_TYPE_UINT: return Type(BASE_TYPE_LONG);
+ case BASE_TYPE_UCHAR:
+ return Type(BASE_TYPE_INT);
+ case BASE_TYPE_USHORT:
+ return Type(BASE_TYPE_INT);
+ case BASE_TYPE_UINT:
+ return Type(BASE_TYPE_LONG);
case BASE_TYPE_ARRAY:
case BASE_TYPE_VECTOR:
if (vectorelem) return DestinationType(type.VectorType(), vectorelem);
FLATBUFFERS_FALLTHROUGH(); // else fall thru
- default: return type;
+ default:
+ return type;
}
}
std::string GenOffsetType() const { return "int"; }
- std::string GenOffsetConstruct(const std::string &variable_name) const {
+ std::string GenOffsetConstruct(const std::string& variable_name) const {
return variable_name;
}
std::string GenVectorOffsetType() const { return "int"; }
// Generate destination type name
- std::string GenTypeNameDest(const Type &type) const {
+ std::string GenTypeNameDest(const Type& type) const {
return GenTypeGet(DestinationType(type, true));
}
// Mask to turn serialized value into destination type value.
- std::string DestinationMask(const Type &type, bool vectorelem) const {
+ std::string DestinationMask(const Type& type, bool vectorelem) const {
switch (type.base_type) {
- case BASE_TYPE_UCHAR: return " & 0xFF";
- case BASE_TYPE_USHORT: return " & 0xFFFF";
- case BASE_TYPE_UINT: return " & 0xFFFFFFFFL";
+ case BASE_TYPE_UCHAR:
+ return " & 0xFF";
+ case BASE_TYPE_USHORT:
+ return " & 0xFFFF";
+ case BASE_TYPE_UINT:
+ return " & 0xFFFFFFFFL";
case BASE_TYPE_VECTOR:
if (vectorelem) return DestinationMask(type.VectorType(), vectorelem);
FLATBUFFERS_FALLTHROUGH(); // else fall thru
- default: return "";
+ default:
+ return "";
}
}
// Casts necessary to correctly read serialized data
- std::string DestinationCast(const Type &type) const {
+ std::string DestinationCast(const Type& type) const {
if (IsSeries(type)) {
return DestinationCast(type.VectorType());
} else {
@@ -333,7 +345,7 @@
// In Java, parameters representing unsigned numbers need to be cast down to
// their respective type. For example, a long holding an unsigned int value
// would be cast down to int before being put onto the buffer.
- std::string SourceCast(const Type &type, bool castFromDest) const {
+ std::string SourceCast(const Type& type, bool castFromDest) const {
if (IsSeries(type)) {
return SourceCast(type.VectorType(), castFromDest);
} else {
@@ -349,41 +361,43 @@
return "";
}
- std::string SourceCast(const Type &type) const {
+ std::string SourceCast(const Type& type) const {
return SourceCast(type, true);
}
- std::string SourceCastBasic(const Type &type, bool castFromDest) const {
+ std::string SourceCastBasic(const Type& type, bool castFromDest) const {
return IsScalar(type.base_type) ? SourceCast(type, castFromDest) : "";
}
- std::string SourceCastBasic(const Type &type) const {
+ std::string SourceCastBasic(const Type& type) const {
return SourceCastBasic(type, true);
}
- std::string GenEnumDefaultValue(const FieldDef &field) const {
- auto &value = field.value;
+ std::string GenEnumDefaultValue(const FieldDef& field) const {
+ auto& value = field.value;
FLATBUFFERS_ASSERT(value.type.enum_def);
- auto &enum_def = *value.type.enum_def;
+ auto& enum_def = *value.type.enum_def;
auto enum_val = enum_def.FindByValue(value.constant);
return enum_val
? Prefixed(namer_.NamespacedEnumVariant(enum_def, *enum_val))
: value.constant;
}
- std::string GenDefaultValue(const FieldDef &field) const {
- auto &value = field.value;
+ std::string GenDefaultValue(const FieldDef& field) const {
+ auto& value = field.value;
auto constant = field.IsScalarOptional() ? "0" : value.constant;
auto longSuffix = "L";
switch (value.type.base_type) {
- case BASE_TYPE_BOOL: return constant == "0" ? "false" : "true";
+ case BASE_TYPE_BOOL:
+ return constant == "0" ? "false" : "true";
case BASE_TYPE_ULONG: {
// Converts the ulong into its bits signed equivalent
uint64_t defaultValue = StringToUInt(constant.c_str());
return NumToString(static_cast<int64_t>(defaultValue)) + longSuffix;
}
case BASE_TYPE_UINT:
- case BASE_TYPE_LONG: return constant + longSuffix;
+ case BASE_TYPE_LONG:
+ return constant + longSuffix;
default:
if (IsFloat(value.type.base_type)) {
if (field.IsScalarOptional()) {
@@ -396,13 +410,15 @@
}
}
- std::string GenDefaultValueBasic(const FieldDef &field) const {
- auto &value = field.value;
- if (!IsScalar(value.type.base_type)) { return "0"; }
+ std::string GenDefaultValueBasic(const FieldDef& field) const {
+ auto& value = field.value;
+ if (!IsScalar(value.type.base_type)) {
+ return "0";
+ }
return GenDefaultValue(field);
}
- void GenEnum(EnumDef &enum_def, std::string &code) const {
+ void GenEnum(EnumDef& enum_def, std::string& code) const {
if (enum_def.generated) return;
// Generate enum definitions of the form:
@@ -422,7 +438,7 @@
code += " {\n";
code += " private " + namer_.Type(enum_def) + "() { }\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
GenComment(ev.doc_comment, &code, &comment_config, " ");
code += " public static final ";
code += GenTypeBasic(DestinationType(enum_def.underlying_type, false));
@@ -449,10 +465,10 @@
"long") {
code += "\n public static final String";
code += "[] names = { ";
- const EnumVal *prev = enum_def.Vals().front();
+ const EnumVal* prev = enum_def.Vals().front();
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
- const EnumVal &ev = **it;
+ const EnumVal& ev = **it;
for (auto k = enum_def.Distance(prev, &ev); k > 1; --k)
code += "\"\", ";
prev = &ev;
@@ -473,13 +489,18 @@
}
// Returns the function name that is able to read a value of the given type.
- std::string GenGetter(const Type &type) const {
+ std::string GenGetter(const Type& type) const {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "__string";
- case BASE_TYPE_STRUCT: return "__struct";
- case BASE_TYPE_UNION: return "__union";
- case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
- case BASE_TYPE_ARRAY: return GenGetter(type.VectorType());
+ case BASE_TYPE_STRING:
+ return "__string";
+ case BASE_TYPE_STRUCT:
+ return "__struct";
+ case BASE_TYPE_UNION:
+ return "__union";
+ case BASE_TYPE_VECTOR:
+ return GenGetter(type.VectorType());
+ case BASE_TYPE_ARRAY:
+ return GenGetter(type.VectorType());
default: {
std::string getter = "bb.get";
if (type.base_type == BASE_TYPE_BOOL) {
@@ -493,9 +514,9 @@
}
// Returns the function name that is able to read a value of the given type.
- std::string GenGetterForLookupByKey(flatbuffers::FieldDef *key_field,
- const std::string &data_buffer,
- const char *num = nullptr) const {
+ std::string GenGetterForLookupByKey(flatbuffers::FieldDef* key_field,
+ const std::string& data_buffer,
+ const char* num = nullptr) const {
auto type = key_field->value.type;
auto dest_mask = DestinationMask(type, true);
auto dest_cast = DestinationCast(type);
@@ -510,7 +531,7 @@
// Direct mutation is only allowed for scalar fields.
// Hence a setter method will only be generated for such fields.
- std::string GenSetter(const Type &type) const {
+ std::string GenSetter(const Type& type) const {
if (IsScalar(type.base_type)) {
std::string setter = "bb.put";
if (GenTypeBasic(type) != "byte" && type.base_type != BASE_TYPE_BOOL) {
@@ -523,7 +544,7 @@
}
// Returns the method name for use with add/put calls.
- std::string GenMethod(const Type &type) const {
+ std::string GenMethod(const Type& type) const {
return IsScalar(type.base_type)
? ConvertCase(GenTypeBasic(type), Case::kUpperCamel)
: (IsStruct(type) ? "Struct" : "Offset");
@@ -531,14 +552,14 @@
// Recursively generate arguments for a constructor, to deal with nested
// structs.
- void GenStructArgs(const StructDef &struct_def, std::string &code,
- const char *nameprefix, size_t array_count = 0) const {
+ void GenStructArgs(const StructDef& struct_def, std::string& code,
+ const char* nameprefix, size_t array_count = 0) const {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- const auto &field_type = field.value.type;
+ auto& field = **it;
+ const auto& field_type = field.value.type;
const auto array_field = IsArray(field_type);
- const auto &type = array_field ? field_type.VectorType()
+ const auto& type = array_field ? field_type.VectorType()
: DestinationType(field_type, false);
const auto array_cnt = array_field ? (array_count + 1) : array_count;
if (IsStruct(type)) {
@@ -561,8 +582,8 @@
// Recusively generate struct construction statements of the form:
// builder.putType(name);
// and insert manual padding.
- void GenStructBody(const StructDef &struct_def, std::string &code,
- const char *nameprefix, size_t index = 0,
+ void GenStructBody(const StructDef& struct_def, std::string& code,
+ const char* nameprefix, size_t index = 0,
bool in_array = false) const {
std::string indent((index + 1) * 2, ' ');
code += indent + " builder.prep(";
@@ -570,8 +591,8 @@
code += NumToString(struct_def.bytesize) + ");\n";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
- auto &field = **it;
- const auto &field_type = field.value.type;
+ auto& field = **it;
+ const auto& field_type = field.value.type;
if (field.padding) {
code += indent + " builder.pad(";
code += NumToString(field.padding) + ");\n";
@@ -581,7 +602,7 @@
(nameprefix + (field.name + "_")).c_str(), index,
in_array);
} else {
- const auto &type =
+ const auto& type =
IsArray(field_type) ? field_type.VectorType() : field_type;
const auto index_var = "_idx" + NumToString(index);
if (IsArray(field_type)) {
@@ -607,13 +628,15 @@
}
code += ");\n";
}
- if (IsArray(field_type)) { code += indent + " }\n"; }
+ if (IsArray(field_type)) {
+ code += indent + " }\n";
+ }
}
}
}
- std::string GenOffsetGetter(flatbuffers::FieldDef *key_field,
- const char *num = nullptr) const {
+ std::string GenOffsetGetter(flatbuffers::FieldDef* key_field,
+ const char* num = nullptr) const {
std::string key_offset = "";
key_offset += "__offset(" + NumToString(key_field->value.offset) + ", ";
if (num) {
@@ -626,7 +649,7 @@
return key_offset;
}
- std::string GenLookupKeyGetter(flatbuffers::FieldDef *key_field) const {
+ std::string GenLookupKeyGetter(flatbuffers::FieldDef* key_field) const {
std::string key_getter = " ";
key_getter += "int tableOffset = ";
key_getter += "__indirect(vectorLocation + 4 * (start + middle)";
@@ -645,7 +668,7 @@
return key_getter;
}
- std::string GenKeyGetter(flatbuffers::FieldDef *key_field) const {
+ std::string GenKeyGetter(flatbuffers::FieldDef* key_field) const {
std::string key_getter = "";
auto data_buffer = "_bb";
if (IsString(key_field->value.type)) {
@@ -669,8 +692,8 @@
return key_getter;
}
- void GenStruct(StructDef &struct_def, std::string &code,
- const IDLOptions &opts) const {
+ void GenStruct(StructDef& struct_def, std::string& code,
+ const IDLOptions& opts) const {
if (struct_def.generated) return;
// Generate a struct accessor class, with methods of the form:
@@ -749,7 +772,7 @@
code += "{ __init(_i, _bb); return this; }\n\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
GenComment(field.doc_comment, &code, &comment_config, " ");
const std::string type_name = GenTypeGet(field.value.type);
@@ -787,7 +810,9 @@
code += "(new " + type_name + "(), j); }\n";
}
- if (field.IsScalarOptional()) { code += GenOptionalScalarCheck(field); }
+ if (field.IsScalarOptional()) {
+ code += GenOptionalScalarCheck(field);
+ }
std::string getter = dest_cast + GenGetter(field.value.type);
code += method_start;
std::string member_suffix = "; ";
@@ -828,7 +853,8 @@
code += offset_prefix + getter + "(o + ";
code += "bb_pos) : null";
break;
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
code += "(";
@@ -874,7 +900,8 @@
code += "(" + type_name + " obj)" + offset_prefix + getter;
code += "(obj, o + bb_pos) : null";
break;
- default: FLATBUFFERS_ASSERT(0);
+ default:
+ FLATBUFFERS_ASSERT(0);
}
}
code += member_suffix;
@@ -890,10 +917,10 @@
// See if we should generate a by-key accessor.
if (field.value.type.element == BASE_TYPE_STRUCT &&
!field.value.type.struct_def->fixed) {
- auto &sd = *field.value.type.struct_def;
- auto &fields = sd.fields.vec;
+ auto& sd = *field.value.type.struct_def;
+ auto& fields = sd.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
- auto &key_field = **kit;
+ auto& key_field = **kit;
if (key_field.key) {
auto qualified_name = Prefixed(namer_.NamespacedType(sd));
code += " public " + qualified_name + " ";
@@ -922,7 +949,7 @@
// Generate the accessors for vector of structs with vector access object
if (IsVector(field.value.type)) {
std::string vector_type_name;
- const auto &element_base_type = field.value.type.VectorType().base_type;
+ const auto& element_base_type = field.value.type.VectorType().base_type;
if (IsScalar(element_base_type)) {
vector_type_name =
ConvertCase(type_name, Case::kUpperCamel) + "Vector";
@@ -995,7 +1022,7 @@
// Generate mutators for scalar fields or vectors of scalars.
if (parser_.opts.mutable_buffer) {
auto is_series = (IsSeries(field.value.type));
- const auto &underlying_type =
+ const auto& underlying_type =
is_series ? field.value.type.VectorType() : field.value.type;
// Boolean parameters have to be explicitly converted to byte
// representation.
@@ -1045,8 +1072,8 @@
}
code += "\n";
auto struct_has_create = false;
- std::set<flatbuffers::FieldDef *> field_has_create_set;
- flatbuffers::FieldDef *key_field = nullptr;
+ std::set<flatbuffers::FieldDef*> field_has_create_set;
+ flatbuffers::FieldDef* key_field = nullptr;
if (struct_def.fixed) {
struct_has_create = true;
// create a struct constructor function
@@ -1067,7 +1094,7 @@
int num_fields = 0;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
if (IsStruct(field.value.type)) {
has_no_struct_fields = false;
@@ -1086,7 +1113,7 @@
code += "(FlatBufferBuilder builder";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
auto field_name = namer_.Field(field);
if (field.deprecated) continue;
code += ",\n ";
@@ -1102,7 +1129,7 @@
size; size /= 2) {
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
- auto &field = **it;
+ auto& field = **it;
auto field_name = namer_.Field(field);
if (!field.deprecated &&
(!struct_def.sortbysize ||
@@ -1130,7 +1157,7 @@
code += NumToString(struct_def.fields.vec.size()) + "); }\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
code += " public static void " + namer_.Method("add", field);
@@ -1216,7 +1243,7 @@
code += "endTable();\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (!field.deprecated && field.IsRequired()) {
code += " builder.required(o, ";
code += NumToString(field.value.offset);
@@ -1225,7 +1252,7 @@
}
code += " return " + GenOffsetConstruct("o") + ";\n }\n";
if (parser_.root_struct_def_ == &struct_def) {
- std::string size_prefix[] = { "", "SizePrefixed" };
+ std::string size_prefix[] = {"", "SizePrefixed"};
for (int i = 0; i < 2; ++i) {
code += " public static void ";
code += namer_.LegacyJavaMethod2("finish" + size_prefix[i],
@@ -1287,14 +1314,14 @@
code += "}\n\n";
}
- std::string GenOptionalScalarCheck(FieldDef &field) const {
+ std::string GenOptionalScalarCheck(FieldDef& field) const {
if (!field.IsScalarOptional()) return "";
return " public boolean " + namer_.Method("has", field) +
"() { return 0 != __offset(" + NumToString(field.value.offset) +
"); }\n";
}
- void GenVectorAccessObject(StructDef &struct_def, std::string &code) const {
+ void GenVectorAccessObject(StructDef& struct_def, std::string& code) const {
// Generate a vector of structs accessor class.
code += "\n";
code += " ";
@@ -1323,9 +1350,9 @@
code += ", bb); }\n";
// See if we should generate a by-key accessor.
if (!struct_def.fixed) {
- auto &fields = struct_def.fields.vec;
+ auto& fields = struct_def.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
- auto &key_field = **kit;
+ auto& key_field = **kit;
if (key_field.key) {
auto nullable_annotation =
parser_.opts.gen_nullable ? "@Nullable " : "";
@@ -1353,11 +1380,13 @@
code += " }\n";
}
- void GenEnum_ObjectAPI(EnumDef &enum_def, std::string &code) const {
+ void GenEnum_ObjectAPI(EnumDef& enum_def, std::string& code) const {
if (enum_def.generated) return;
code += "import com.google.flatbuffers.FlatBufferBuilder;\n\n";
- if (!enum_def.attributes.Lookup("private")) { code += "public "; }
+ if (!enum_def.attributes.Lookup("private")) {
+ code += "public ";
+ }
auto union_name = namer_.Type(enum_def) + "Union";
auto union_type =
GenTypeBasic(DestinationType(enum_def.underlying_type, false));
@@ -1382,7 +1411,7 @@
code += " }\n\n";
// As
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
if (ev.union_type.base_type == BASE_TYPE_NONE) continue;
auto type_name = GenTypeGet_ObjectAPI(ev.union_type, false, true);
if (ev.union_type.base_type == BASE_TYPE_STRUCT &&
@@ -1400,7 +1429,7 @@
union_name + " _o) {\n";
code += " switch (_o.type) {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
if (ev.union_type.base_type == BASE_TYPE_NONE) {
continue;
} else {
@@ -1419,9 +1448,9 @@
code += "}\n\n";
}
- void GenUnionUnPack_ObjectAPI(const EnumDef &enum_def, std::string &code,
- const std::string &type_name,
- const std::string &field_name,
+ void GenUnionUnPack_ObjectAPI(const EnumDef& enum_def, std::string& code,
+ const std::string& type_name,
+ const std::string& field_name,
bool is_vector) const {
const std::string variable_type =
is_vector ? type_name.substr(0, type_name.length() - 2) : type_name;
@@ -1442,7 +1471,7 @@
code += indent + "switch (" + variable_name + "Type) {\n";
for (auto eit = enum_def.Vals().begin(); eit != enum_def.Vals().end();
++eit) {
- auto &ev = **eit;
+ auto& ev = **eit;
if (ev.union_type.base_type == BASE_TYPE_NONE) {
continue;
} else {
@@ -1473,9 +1502,9 @@
}
void GenPackUnPack_ObjectAPI(
- StructDef &struct_def, std::string &code, const IDLOptions &opts,
+ StructDef& struct_def, std::string& code, const IDLOptions& opts,
bool struct_has_create,
- const std::set<FieldDef *> &field_has_create) const {
+ const std::set<FieldDef*>& field_has_create) const {
auto struct_name = namer_.ObjectType(struct_def);
// unpack()
code += " public " + struct_name + " unpack() {\n";
@@ -1487,7 +1516,7 @@
code += " public void unpackTo(" + struct_name + " _o) {\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
if (field.value.type.element == BASE_TYPE_UTYPE) continue;
@@ -1560,7 +1589,8 @@
code += ";}\n";
}
break;
- case BASE_TYPE_UTYPE: break;
+ case BASE_TYPE_UTYPE:
+ break;
case BASE_TYPE_UNION: {
GenUnionUnPack_ObjectAPI(*field.value.type.enum_def, code, type_name,
accessor, false);
@@ -1587,7 +1617,7 @@
code += " if (_o == null) return 0;\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
const auto field_name = namer_.Field(field);
const auto variable = "_" + namer_.Variable("o", field);
@@ -1603,8 +1633,8 @@
} else if (struct_def.fixed && struct_has_create) {
std::vector<FieldArrayLength> array_lengths;
FieldArrayLength tmp_array_length = {
- field.name,
- field.value.type.fixed_length,
+ field.name,
+ field.value.type.fixed_length,
};
array_lengths.push_back(tmp_array_length);
GenStructPackDecl_ObjectAPI(*field.value.type.struct_def,
@@ -1719,8 +1749,8 @@
if (field.value.type.struct_def != nullptr) {
std::vector<FieldArrayLength> array_lengths;
FieldArrayLength tmp_array_length = {
- field.name,
- field.value.type.fixed_length,
+ field.name,
+ field.value.type.fixed_length,
};
array_lengths.push_back(tmp_array_length);
GenStructPackDecl_ObjectAPI(*field.value.type.struct_def,
@@ -1746,7 +1776,8 @@
"Union.pack(builder, _o." + get_field + "());\n";
break;
}
- default: break;
+ default:
+ break;
}
}
if (struct_has_create) {
@@ -1756,7 +1787,7 @@
code += " builder";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
const auto field_name = namer_.Field(field);
const auto get_field = namer_.Method("get", field);
@@ -1790,9 +1821,12 @@
}
break;
}
- case BASE_TYPE_UNION: FLATBUFFERS_FALLTHROUGH(); // fall thru
- case BASE_TYPE_UTYPE: FLATBUFFERS_FALLTHROUGH(); // fall thru
- case BASE_TYPE_STRING: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_UNION:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_UTYPE:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_STRING:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
code += ",\n";
code += " _" + field_name;
@@ -1811,7 +1845,7 @@
"(builder);\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
const auto arg = "_" + namer_.Variable(field);
const auto get_field = namer_.Method("get", field);
@@ -1828,13 +1862,16 @@
}
break;
}
- case BASE_TYPE_STRING: FLATBUFFERS_FALLTHROUGH(); // fall thru
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_STRING:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
code += " " + add_field + "(builder, " + arg + ");\n";
break;
}
- case BASE_TYPE_UTYPE: break;
+ case BASE_TYPE_UTYPE:
+ break;
case BASE_TYPE_UNION: {
code += " " + add_field + "Type(builder, " + arg + "Type);\n";
code += " " + add_field + "(builder, " + arg + ");\n";
@@ -1859,18 +1896,18 @@
code += " }\n";
}
- void GenStructPackDecl_ObjectAPI(const StructDef &struct_def,
- std::vector<FieldArrayLength> &array_lengths,
- std::string &code) const {
+ void GenStructPackDecl_ObjectAPI(const StructDef& struct_def,
+ std::vector<FieldArrayLength>& array_lengths,
+ std::string& code) const {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const FieldDef &field = **it;
+ const FieldDef& field = **it;
const bool is_array = IsArray(field.value.type);
- const Type &field_type =
+ const Type& field_type =
is_array ? field.value.type.VectorType() : field.value.type;
FieldArrayLength tmp_array_length = {
- field.name,
- field_type.fixed_length,
+ field.name,
+ field_type.fixed_length,
};
array_lengths.push_back(tmp_array_length);
if (field_type.struct_def != nullptr) {
@@ -1895,7 +1932,9 @@
code += " " + name + " = ";
code += "new " + GenTypeBasic(field_type) + "[";
for (size_t i = 0; i < array_only_lengths.size(); ++i) {
- if (i != 0) { code += "]["; }
+ if (i != 0) {
+ code += "][";
+ }
code += NumToString(array_only_lengths[i].length);
}
code += "];\n";
@@ -1940,13 +1979,13 @@
}
}
- void GenStructPackCall_ObjectAPI(const StructDef &struct_def,
- std::string &code,
+ void GenStructPackCall_ObjectAPI(const StructDef& struct_def,
+ std::string& code,
std::string prefix) const {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- const auto &field_type = field.value.type;
+ auto& field = **it;
+ const auto& field_type = field.value.type;
if (field_type.struct_def != nullptr) {
GenStructPackCall_ObjectAPI(*field_type.struct_def, code,
prefix + namer_.Field(field) + "_");
@@ -1958,7 +1997,7 @@
}
std::string ConvertPrimitiveTypeToObjectWrapper_ObjectAPI(
- const std::string &type_name) const {
+ const std::string& type_name) const {
if (type_name == "boolean")
return "Boolean";
else if (type_name == "byte")
@@ -1978,14 +2017,16 @@
return type_name;
}
- std::string GenTypeGet_ObjectAPI(const flatbuffers::Type &type,
+ std::string GenTypeGet_ObjectAPI(const flatbuffers::Type& type,
bool vectorelem,
bool wrap_in_namespace) const {
auto type_name = GenTypeNameDest(type);
// Replace to ObjectBaseAPI Type Name
switch (type.base_type) {
- case BASE_TYPE_STRUCT: FLATBUFFERS_FALLTHROUGH(); // fall thru
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_STRUCT:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
if (type.struct_def != nullptr) {
auto type_name_length = type.struct_def->name.length();
@@ -2011,27 +2052,34 @@
}
break;
}
- default: break;
+ default:
+ break;
}
- if (vectorelem) { return type_name; }
+ if (vectorelem) {
+ return type_name;
+ }
switch (type.base_type) {
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
type_name = type_name + "[]";
break;
}
- default: break;
+ default:
+ break;
}
return type_name;
}
std::string GenConcreteTypeGet_ObjectAPI(
- const flatbuffers::Type &type) const {
+ const flatbuffers::Type& type) const {
auto type_name = GenTypeNameDest(type);
// Replace to ObjectBaseAPI Type Name
switch (type.base_type) {
- case BASE_TYPE_STRUCT: FLATBUFFERS_FALLTHROUGH(); // fall thru
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_STRUCT:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
if (type.struct_def != nullptr) {
auto type_name_length = type.struct_def->name.length();
@@ -2048,22 +2096,25 @@
type_name = Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
break;
}
- default: break;
+ default:
+ break;
}
switch (type.base_type) {
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
type_name = type_name + "[]";
break;
}
- default: break;
+ default:
+ break;
}
return type_name;
}
- void GenStruct_ObjectAPI(const StructDef &struct_def,
- std::string &code) const {
+ void GenStruct_ObjectAPI(const StructDef& struct_def,
+ std::string& code) const {
if (struct_def.generated) return;
if (struct_def.attributes.Lookup("private")) {
// For Java, we leave the enum unmarked to indicate package-private
@@ -2077,7 +2128,7 @@
// Generate Properties
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
if (field.value.type.element == BASE_TYPE_UTYPE) continue;
@@ -2091,7 +2142,7 @@
code += "\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
if (field.value.type.element == BASE_TYPE_UTYPE) continue;
@@ -2118,7 +2169,7 @@
code += " public " + class_name + "() {\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
if (field.value.type.element == BASE_TYPE_UTYPE) continue;
@@ -2177,11 +2228,11 @@
// This tracks the current namespace used to determine if a type need to be
// prefixed by its namespace
- const Namespace *cur_name_space_;
+ const Namespace* cur_name_space_;
const IdlNamer namer_;
private:
- std::string Prefixed(const std::string &str) const {
+ std::string Prefixed(const std::string& str) const {
return package_prefix_ + str;
}
@@ -2190,8 +2241,8 @@
};
} // namespace java
-static bool GenerateJava(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateJava(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
java::JavaGenerator generator(parser, path, file_name,
parser.opts.java_package_prefix);
return generator.generate();
@@ -2201,32 +2252,35 @@
class JavaCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateJava(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateJava(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
output = JavaCSharpMakeRule(true, parser, path, filename);
return Status::OK;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateJavaGRPC(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateJavaGRPC(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_json_schema.cpp b/src/idl_gen_json_schema.cpp
index ed891ab..9ab2905 100644
--- a/src/idl_gen_json_schema.cpp
+++ b/src/idl_gen_json_schema.cpp
@@ -30,9 +30,10 @@
namespace {
-template<class T> static std::string GenFullName(const T *enum_def) {
+template <class T>
+static std::string GenFullName(const T* enum_def) {
std::string full_name;
- const auto &name_spaces = enum_def->defined_namespace->components;
+ const auto& name_spaces = enum_def->defined_namespace->components;
for (auto ns = name_spaces.cbegin(); ns != name_spaces.cend(); ++ns) {
full_name.append(*ns + "_");
}
@@ -40,17 +41,19 @@
return full_name;
}
-template<class T> static std::string GenTypeRef(const T *enum_def) {
+template <class T>
+static std::string GenTypeRef(const T* enum_def) {
return "\"$ref\" : \"#/definitions/" + GenFullName(enum_def) + "\"";
}
-static std::string GenType(const std::string &name) {
+static std::string GenType(const std::string& name) {
return "\"type\" : \"" + name + "\"";
}
static std::string GenType(BaseType type) {
switch (type) {
- case BASE_TYPE_BOOL: return "\"type\" : \"boolean\"";
+ case BASE_TYPE_BOOL:
+ return "\"type\" : \"boolean\"";
case BASE_TYPE_CHAR:
return "\"type\" : \"integer\", \"minimum\" : " +
NumToString(std::numeric_limits<int8_t>::min()) +
@@ -84,19 +87,26 @@
return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" : " +
NumToString(std::numeric_limits<uint64_t>::max());
case BASE_TYPE_FLOAT:
- case BASE_TYPE_DOUBLE: return "\"type\" : \"number\"";
- case BASE_TYPE_STRING: return "\"type\" : \"string\"";
- default: return "";
+ case BASE_TYPE_DOUBLE:
+ return "\"type\" : \"number\"";
+ case BASE_TYPE_STRING:
+ return "\"type\" : \"string\"";
+ default:
+ return "";
}
}
-static std::string GenBaseType(const Type &type) {
- if (type.struct_def != nullptr) { return GenTypeRef(type.struct_def); }
- if (type.enum_def != nullptr) { return GenTypeRef(type.enum_def); }
+static std::string GenBaseType(const Type& type) {
+ if (type.struct_def != nullptr) {
+ return GenTypeRef(type.struct_def);
+ }
+ if (type.enum_def != nullptr) {
+ return GenTypeRef(type.enum_def);
+ }
return GenType(type.base_type);
}
-static std::string GenArrayType(const Type &type) {
+static std::string GenArrayType(const Type& type) {
std::string element_type;
if (type.struct_def != nullptr) {
element_type = GenTypeRef(type.struct_def);
@@ -109,9 +119,10 @@
return "\"type\" : \"array\", \"items\" : {" + element_type + "}";
}
-static std::string GenType(const Type &type) {
+static std::string GenType(const Type& type) {
switch (type.base_type) {
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BASE_TYPE_VECTOR: {
return GenArrayType(type);
}
@@ -120,10 +131,12 @@
}
case BASE_TYPE_UNION: {
std::string union_type_string("\"anyOf\": [");
- const auto &union_types = type.enum_def->Vals();
+ const auto& union_types = type.enum_def->Vals();
for (auto ut = union_types.cbegin(); ut < union_types.cend(); ++ut) {
- const auto &union_type = *ut;
- if (union_type->union_type.base_type == BASE_TYPE_NONE) { continue; }
+ const auto& union_type = *ut;
+ if (union_type->union_type.base_type == BASE_TYPE_NONE) {
+ continue;
+ }
if (union_type->union_type.base_type == BASE_TYPE_STRUCT) {
union_type_string.append(
"{ " + GenTypeRef(union_type->union_type.struct_def) + " }");
@@ -135,7 +148,8 @@
union_type_string.append("]");
return union_type_string;
}
- case BASE_TYPE_UTYPE: return GenTypeRef(type.enum_def);
+ case BASE_TYPE_UTYPE:
+ return GenTypeRef(type.enum_def);
default: {
return GenBaseType(type);
}
@@ -149,16 +163,16 @@
std::string code_;
public:
- JsonSchemaGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ JsonSchemaGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", "", "json") {}
- explicit JsonSchemaGenerator(const BaseGenerator &base_generator)
+ explicit JsonSchemaGenerator(const BaseGenerator& base_generator)
: BaseGenerator(base_generator) {}
- std::string GeneratedFileName(const std::string &path,
- const std::string &file_name,
- const IDLOptions &options /* unused */) const {
+ std::string GeneratedFileName(const std::string& path,
+ const std::string& file_name,
+ const IDLOptions& options /* unused */) const {
(void)options;
return path + file_name + ".schema.json";
}
@@ -175,11 +189,11 @@
}
std::string PrepareDescription(
- const std::vector<std::string> &comment_lines) {
+ const std::vector<std::string>& comment_lines) {
std::string comment;
for (auto line_iterator = comment_lines.cbegin();
line_iterator != comment_lines.cend(); ++line_iterator) {
- const auto &comment_line = *line_iterator;
+ const auto& comment_line = *line_iterator;
// remove leading and trailing spaces from comment line
const auto start = std::find_if(comment_line.begin(), comment_line.end(),
@@ -226,7 +240,9 @@
for (auto enum_value = (*e)->Vals().begin();
enum_value != (*e)->Vals().end(); ++enum_value) {
enumdef.append("\"" + (*enum_value)->name + "\"");
- if (*enum_value != (*e)->Vals().back()) { enumdef.append(", "); }
+ if (*enum_value != (*e)->Vals().back()) {
+ enumdef.append(", ");
+ }
}
enumdef.append("]");
code_ += enumdef + NewLine();
@@ -234,10 +250,10 @@
}
for (auto s = parser_.structs_.vec.cbegin();
s != parser_.structs_.vec.cend(); ++s) {
- const auto &structure = *s;
+ const auto& structure = *s;
code_ += Indent(2) + "\"" + GenFullName(structure) + "\" : {" + NewLine();
code_ += Indent(3) + GenType("object") + "," + NewLine();
- const auto &comment_lines = structure->doc_comment;
+ const auto& comment_lines = structure->doc_comment;
auto comment = PrepareDescription(comment_lines);
if (comment != "") {
code_ += Indent(3) + "\"description\" : " + comment + "," + NewLine();
@@ -245,9 +261,9 @@
code_ += Indent(3) + "\"properties\" : {" + NewLine();
- const auto &properties = structure->fields.vec;
+ const auto& properties = structure->fields.vec;
for (auto prop = properties.cbegin(); prop != properties.cend(); ++prop) {
- const auto &property = *prop;
+ const auto& property = *prop;
std::string arrayInfo = "";
if (IsArray(property->value.type)) {
arrayInfo = "," + NewLine() + Indent(8) + "\"minItems\": " +
@@ -272,15 +288,17 @@
}
typeLine += NewLine() + Indent(7) + "}";
- if (property != properties.back()) { typeLine.append(","); }
+ if (property != properties.back()) {
+ typeLine.append(",");
+ }
code_ += typeLine + NewLine();
}
code_ += Indent(3) + "}," + NewLine(); // close properties
- std::vector<FieldDef *> requiredProperties;
+ std::vector<FieldDef*> requiredProperties;
std::copy_if(properties.begin(), properties.end(),
back_inserter(requiredProperties),
- [](FieldDef const *prop) { return prop->IsRequired(); });
+ [](FieldDef const* prop) { return prop->IsRequired(); });
if (!requiredProperties.empty()) {
auto required_string(Indent(3) + "\"required\" : [");
for (auto req_prop = requiredProperties.cbegin();
@@ -295,7 +313,9 @@
}
code_ += Indent(3) + "\"additionalProperties\" : false" + NewLine();
auto closeType(Indent(2) + "}");
- if (*s != parser_.structs_.vec.back()) { closeType.append(","); }
+ if (*s != parser_.structs_.vec.back()) {
+ closeType.append(",");
+ }
code_ += closeType + NewLine(); // close type
}
code_ += Indent(1) + "}," + NewLine(); // close definitions
@@ -317,10 +337,12 @@
};
} // namespace jsons
-static bool GenerateJsonSchema(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateJsonSchema(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
jsons::JsonSchemaGenerator generator(parser, path, file_name);
- if (!generator.generate()) { return false; }
+ if (!generator.generate()) {
+ return false;
+ }
return generator.save();
}
@@ -328,20 +350,21 @@
class JsonSchemaCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateJsonSchema(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateJsonSchema(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -349,16 +372,16 @@
return Status::NOT_IMPLEMENTED;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_kotlin.cpp b/src/idl_gen_kotlin.cpp
index 7b95f96..e917615 100644
--- a/src/idl_gen_kotlin.cpp
+++ b/src/idl_gen_kotlin.cpp
@@ -38,56 +38,56 @@
"POSITIVE_INFINITY",
"NEGATIVE_INFINITY");
-static const CommentConfig comment_config = { "/**", " *", " */" };
+static const CommentConfig comment_config = {"/**", " *", " */"};
static const std::string ident_pad = " ";
static std::set<std::string> KotlinKeywords() {
- return { "package", "as", "typealias", "class", "this", "super",
- "val", "var", "fun", "for", "null", "true",
- "false", "is", "in", "throw", "return", "break",
- "continue", "object", "if", "try", "else", "while",
- "do", "when", "interface", "typeof", "Any", "Character" };
+ return {"package", "as", "typealias", "class", "this", "super",
+ "val", "var", "fun", "for", "null", "true",
+ "false", "is", "in", "throw", "return", "break",
+ "continue", "object", "if", "try", "else", "while",
+ "do", "when", "interface", "typeof", "Any", "Character"};
}
static Namer::Config KotlinDefaultConfig() {
- return { /*types=*/Case::kKeep,
- /*constants=*/Case::kKeep,
- /*methods=*/Case::kLowerCamel,
- /*functions=*/Case::kKeep,
- /*fields=*/Case::kLowerCamel,
- /*variables=*/Case::kLowerCamel,
- /*variants=*/Case::kKeep,
- /*enum_variant_seperator=*/"", // I.e. Concatenate.
- /*escape_keywords=*/Namer::Config::Escape::BeforeConvertingCase,
- /*namespaces=*/Case::kKeep,
- /*namespace_seperator=*/"__",
- /*object_prefix=*/"",
- /*object_suffix=*/"T",
- /*keyword_prefix=*/"",
- /*keyword_suffix=*/"_",
- /*filenames=*/Case::kKeep,
- /*directories=*/Case::kKeep,
- /*output_path=*/"",
- /*filename_suffix=*/"",
- /*filename_extension=*/".kt" };
+ return {/*types=*/Case::kKeep,
+ /*constants=*/Case::kKeep,
+ /*methods=*/Case::kLowerCamel,
+ /*functions=*/Case::kKeep,
+ /*fields=*/Case::kLowerCamel,
+ /*variables=*/Case::kLowerCamel,
+ /*variants=*/Case::kKeep,
+ /*enum_variant_seperator=*/"", // I.e. Concatenate.
+ /*escape_keywords=*/Namer::Config::Escape::BeforeConvertingCase,
+ /*namespaces=*/Case::kKeep,
+ /*namespace_seperator=*/"__",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kKeep,
+ /*directories=*/Case::kKeep,
+ /*output_path=*/"",
+ /*filename_suffix=*/"",
+ /*filename_extension=*/".kt"};
}
} // namespace
class KotlinGenerator : public BaseGenerator {
public:
- KotlinGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ KotlinGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", ".", "kt"),
namer_(WithFlagOptions(KotlinDefaultConfig(), parser.opts, path),
KotlinKeywords()) {}
- KotlinGenerator &operator=(const KotlinGenerator &);
+ KotlinGenerator& operator=(const KotlinGenerator&);
bool generate() FLATBUFFERS_OVERRIDE {
std::string one_file_code;
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
CodeWriter enumWriter(ident_pad);
- auto &enum_def = **it;
+ auto& enum_def = **it;
GenEnum(enum_def, enumWriter);
if (parser_.opts.one_file) {
one_file_code += enumWriter.ToString();
@@ -101,7 +101,7 @@
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
CodeWriter structWriter(ident_pad);
- auto &struct_def = **it;
+ auto& struct_def = **it;
GenStruct(struct_def, structWriter, parser_.opts);
if (parser_.opts.one_file) {
one_file_code += structWriter.ToString();
@@ -121,8 +121,8 @@
// Save out the generated code for a single class while adding
// declaration boilerplate.
- bool SaveType(const std::string &defname, const Namespace &ns,
- const std::string &classcode, bool needs_includes) const {
+ bool SaveType(const std::string& defname, const Namespace& ns,
+ const std::string& classcode, bool needs_includes) const {
if (!classcode.length()) return true;
std::string code =
@@ -159,11 +159,11 @@
return SaveFile(filename.c_str(), code, false);
}
- static bool IsEnum(const Type &type) {
+ static bool IsEnum(const Type& type) {
return type.enum_def != nullptr && IsInteger(type.base_type);
}
- static std::string GenTypeBasic(const BaseType &type) {
+ static std::string GenTypeBasic(const BaseType& type) {
// clang-format off
static const char * const kotlin_typename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
@@ -176,18 +176,22 @@
return kotlin_typename[type];
}
- std::string GenTypePointer(const Type &type) const {
+ std::string GenTypePointer(const Type& type) const {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "String";
- case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
- case BASE_TYPE_STRUCT: return WrapInNameSpace(*type.struct_def);
- default: return "Table";
+ case BASE_TYPE_STRING:
+ return "String";
+ case BASE_TYPE_VECTOR:
+ return GenTypeGet(type.VectorType());
+ case BASE_TYPE_STRUCT:
+ return WrapInNameSpace(*type.struct_def);
+ default:
+ return "Table";
}
}
// with the addition of optional scalar types,
// we are adding the nullable '?' operator to return type of a field.
- std::string GetterReturnType(const FieldDef &field) const {
+ std::string GetterReturnType(const FieldDef& field) const {
auto base_type = field.value.type.base_type;
auto r_type = GenTypeGet(field.value.type);
@@ -204,15 +208,15 @@
return r_type;
}
- std::string GenTypeGet(const Type &type) const {
+ std::string GenTypeGet(const Type& type) const {
return IsScalar(type.base_type) ? GenTypeBasic(type.base_type)
: GenTypePointer(type);
}
- std::string GenEnumDefaultValue(const FieldDef &field) const {
- auto &value = field.value;
+ std::string GenEnumDefaultValue(const FieldDef& field) const {
+ auto& value = field.value;
FLATBUFFERS_ASSERT(value.type.enum_def);
- auto &enum_def = *value.type.enum_def;
+ auto& enum_def = *value.type.enum_def;
auto enum_val = enum_def.FindByValue(value.constant);
return enum_val ? (WrapInNameSpace(enum_def) + "." + enum_val->name)
: value.constant;
@@ -223,7 +227,7 @@
// Main differences are:
// - Floats are upcasted to doubles
// - Unsigned are casted to signed
- std::string GenFBBDefaultValue(const FieldDef &field) const {
+ std::string GenFBBDefaultValue(const FieldDef& field) const {
if (field.IsScalarOptional()) {
// although default value is null, java API forces us to present a real
// default value for scalars, while adding a field to the buffer. This is
@@ -231,9 +235,12 @@
// calling builder.addMyField()
switch (field.value.type.base_type) {
case BASE_TYPE_DOUBLE:
- case BASE_TYPE_FLOAT: return "0.0";
- case BASE_TYPE_BOOL: return "false";
- default: return "0";
+ case BASE_TYPE_FLOAT:
+ return "0.0";
+ case BASE_TYPE_BOOL:
+ return "false";
+ default:
+ return "0";
}
}
auto out = GenDefaultValue(field, true);
@@ -250,19 +257,21 @@
// FlatBufferBuilder only store signed types, so this function
// returns a cast for unsigned values
- std::string GenFBBValueCast(const FieldDef &field) const {
+ std::string GenFBBValueCast(const FieldDef& field) const {
if (IsUnsigned(field.value.type.base_type)) {
return CastToSigned(field.value.type);
}
return "";
}
- std::string GenDefaultValue(const FieldDef &field,
+ std::string GenDefaultValue(const FieldDef& field,
bool force_signed = false) const {
- auto &value = field.value;
+ auto& value = field.value;
auto base_type = field.value.type.base_type;
- if (field.IsScalarOptional()) { return "null"; }
+ if (field.IsScalarOptional()) {
+ return "null";
+ }
if (IsFloat(base_type)) {
auto val = KotlinFloatGen.GenFloatConstant(field);
if (base_type == BASE_TYPE_DOUBLE && val.back() == 'f') {
@@ -283,7 +292,7 @@
return value.constant + suffix;
}
- void GenEnum(EnumDef &enum_def, CodeWriter &writer) const {
+ void GenEnum(EnumDef& enum_def, CodeWriter& writer) const {
if (enum_def.generated) return;
GenerateComment(enum_def.doc_comment, writer, &comment_config);
@@ -296,7 +305,7 @@
// Write all properties
auto vals = enum_def.Vals();
for (auto it = vals.begin(); it != vals.end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
auto field_type = GenTypeBasic(enum_def.underlying_type.base_type);
auto val = enum_def.ToString(ev);
auto suffix = LiteralSuffix(enum_def.underlying_type.base_type);
@@ -328,7 +337,9 @@
writer += "\"\", \\";
val = ev;
writer += "\"" + (*it)->name + "\"\\";
- if (it + 1 != vals.end()) { writer += ", \\"; }
+ if (it + 1 != vals.end()) {
+ writer += ", \\";
+ }
}
writer += ")";
});
@@ -348,49 +359,65 @@
}
// Returns the function name that is able to read a value of the given type.
- std::string ByteBufferGetter(const Type &type,
+ std::string ByteBufferGetter(const Type& type,
std::string bb_var_name) const {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "__string";
- case BASE_TYPE_STRUCT: return "__struct";
- case BASE_TYPE_UNION: return "__union";
+ case BASE_TYPE_STRING:
+ return "__string";
+ case BASE_TYPE_STRUCT:
+ return "__struct";
+ case BASE_TYPE_UNION:
+ return "__union";
case BASE_TYPE_VECTOR:
return ByteBufferGetter(type.VectorType(), bb_var_name);
case BASE_TYPE_INT:
- case BASE_TYPE_UINT: return bb_var_name + ".getInt";
+ case BASE_TYPE_UINT:
+ return bb_var_name + ".getInt";
case BASE_TYPE_SHORT:
- case BASE_TYPE_USHORT: return bb_var_name + ".getShort";
+ case BASE_TYPE_USHORT:
+ return bb_var_name + ".getShort";
case BASE_TYPE_ULONG:
- case BASE_TYPE_LONG: return bb_var_name + ".getLong";
- case BASE_TYPE_FLOAT: return bb_var_name + ".getFloat";
- case BASE_TYPE_DOUBLE: return bb_var_name + ".getDouble";
+ case BASE_TYPE_LONG:
+ return bb_var_name + ".getLong";
+ case BASE_TYPE_FLOAT:
+ return bb_var_name + ".getFloat";
+ case BASE_TYPE_DOUBLE:
+ return bb_var_name + ".getDouble";
case BASE_TYPE_CHAR:
case BASE_TYPE_UCHAR:
case BASE_TYPE_NONE:
- case BASE_TYPE_UTYPE: return bb_var_name + ".get";
- case BASE_TYPE_BOOL: return "0.toByte() != " + bb_var_name + ".get";
+ case BASE_TYPE_UTYPE:
+ return bb_var_name + ".get";
+ case BASE_TYPE_BOOL:
+ return "0.toByte() != " + bb_var_name + ".get";
default:
return bb_var_name + "." +
namer_.Method("get", GenTypeBasic(type.base_type));
}
}
- std::string ByteBufferSetter(const Type &type) const {
+ std::string ByteBufferSetter(const Type& type) const {
if (IsScalar(type.base_type)) {
switch (type.base_type) {
case BASE_TYPE_INT:
- case BASE_TYPE_UINT: return "bb.putInt";
+ case BASE_TYPE_UINT:
+ return "bb.putInt";
case BASE_TYPE_SHORT:
- case BASE_TYPE_USHORT: return "bb.putShort";
+ case BASE_TYPE_USHORT:
+ return "bb.putShort";
case BASE_TYPE_ULONG:
- case BASE_TYPE_LONG: return "bb.putLong";
- case BASE_TYPE_FLOAT: return "bb.putFloat";
- case BASE_TYPE_DOUBLE: return "bb.putDouble";
+ case BASE_TYPE_LONG:
+ return "bb.putLong";
+ case BASE_TYPE_FLOAT:
+ return "bb.putFloat";
+ case BASE_TYPE_DOUBLE:
+ return "bb.putDouble";
case BASE_TYPE_CHAR:
case BASE_TYPE_UCHAR:
case BASE_TYPE_BOOL:
case BASE_TYPE_NONE:
- case BASE_TYPE_UTYPE: return "bb.put";
+ case BASE_TYPE_UTYPE:
+ return "bb.put";
default:
return "bb." + namer_.Method("put", GenTypeBasic(type.base_type));
}
@@ -399,27 +426,27 @@
}
// Returns the function name that is able to read a value of the given type.
- std::string GenLookupByKey(flatbuffers::FieldDef *key_field,
- const std::string &bb_var_name,
- const char *num = nullptr) const {
+ std::string GenLookupByKey(flatbuffers::FieldDef* key_field,
+ const std::string& bb_var_name,
+ const char* num = nullptr) const {
auto type = key_field->value.type;
return ByteBufferGetter(type, bb_var_name) + "(" +
GenOffsetGetter(key_field, num) + ")";
}
// Returns the method name for use with add/put calls.
- static std::string GenMethod(const Type &type) {
+ static std::string GenMethod(const Type& type) {
return IsScalar(type.base_type) ? ToSignedType(type)
: (IsStruct(type) ? "Struct" : "Offset");
}
// Recursively generate arguments for a constructor, to deal with nested
// structs.
- void GenStructArgs(const StructDef &struct_def, CodeWriter &writer,
- const char *nameprefix) const {
+ void GenStructArgs(const StructDef& struct_def, CodeWriter& writer,
+ const char* nameprefix) const {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (IsStruct(field.value.type)) {
// Generate arguments for a struct inside a struct. To ensure
// names don't clash, and to make it obvious these arguments are
@@ -438,14 +465,14 @@
// Recusively generate struct construction statements of the form:
// builder.putType(name);
// and insert manual padding.
- void GenStructBody(const StructDef &struct_def, CodeWriter &writer,
- const char *nameprefix) const {
+ void GenStructBody(const StructDef& struct_def, CodeWriter& writer,
+ const char* nameprefix) const {
writer.SetValue("align", NumToString(struct_def.minalign));
writer.SetValue("size", NumToString(struct_def.bytesize));
writer += "builder.prep({{align}}, {{size}})";
auto fields_vec = struct_def.fields.vec;
for (auto it = fields_vec.rbegin(); it != fields_vec.rend(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.padding) {
writer.SetValue("pad", NumToString(field.padding));
@@ -463,14 +490,14 @@
}
}
- std::string GenByteBufferLength(const char *bb_name) const {
+ std::string GenByteBufferLength(const char* bb_name) const {
std::string bb_len = bb_name;
bb_len += ".capacity()";
return bb_len;
}
- std::string GenOffsetGetter(flatbuffers::FieldDef *key_field,
- const char *num = nullptr) const {
+ std::string GenOffsetGetter(flatbuffers::FieldDef* key_field,
+ const char* num = nullptr) const {
std::string key_offset =
"__offset(" + NumToString(key_field->value.offset) + ", ";
if (num) {
@@ -483,7 +510,7 @@
return key_offset;
}
- void GenStruct(StructDef &struct_def, CodeWriter &writer,
+ void GenStruct(StructDef& struct_def, CodeWriter& writer,
IDLOptions options) const {
if (struct_def.generated) return;
@@ -517,7 +544,7 @@
// Generate Static Fields
GenerateCompanionObject(writer, [&]() {
if (!struct_def.fixed) {
- FieldDef *key_field = nullptr;
+ FieldDef* key_field = nullptr;
// Generate version check method.
// Force compile time error if not using the same version
@@ -537,7 +564,7 @@
auto fields = struct_def.fields.vec;
int field_pos = -1;
for (auto it = fields.begin(); it != fields.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
field_pos++;
if (field.deprecated) continue;
if (field.key) key_field = &field;
@@ -576,8 +603,8 @@
}
// TODO: move key_field to reference instead of pointer
- void GenerateLookupByKey(FieldDef *key_field, StructDef &struct_def,
- CodeWriter &writer, const IDLOptions options) const {
+ void GenerateLookupByKey(FieldDef* key_field, StructDef& struct_def,
+ CodeWriter& writer, const IDLOptions options) const {
std::stringstream params;
params << "obj: " << namer_.Type(struct_def) << "?"
<< ", ";
@@ -637,9 +664,9 @@
options.gen_jvmstatic);
}
- void GenerateFinishSizePrefixed(StructDef &struct_def,
- const std::string &identifier,
- CodeWriter &writer,
+ void GenerateFinishSizePrefixed(StructDef& struct_def,
+ const std::string& identifier,
+ CodeWriter& writer,
const IDLOptions options) const {
auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : "";
auto params = "builder: FlatBufferBuilder, offset: Int";
@@ -650,9 +677,9 @@
[&]() { writer += "builder.finishSizePrefixed(offset" + id + ")"; },
options.gen_jvmstatic);
}
- void GenerateFinishStructBuffer(StructDef &struct_def,
- const std::string &identifier,
- CodeWriter &writer,
+ void GenerateFinishStructBuffer(StructDef& struct_def,
+ const std::string& identifier,
+ CodeWriter& writer,
const IDLOptions options) const {
auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : "";
auto params = "builder: FlatBufferBuilder, offset: Int";
@@ -664,7 +691,7 @@
options.gen_jvmstatic);
}
- void GenerateEndStructMethod(StructDef &struct_def, CodeWriter &writer,
+ void GenerateEndStructMethod(StructDef& struct_def, CodeWriter& writer,
const IDLOptions options) const {
// Generate end{{TableName}}(builder: FlatBufferBuilder) method
auto name = namer_.LegacyJavaMethod2("end", struct_def, "");
@@ -678,8 +705,10 @@
writer += "val o = builder.endTable()";
writer.IncrementIdentLevel();
for (auto it = field_vec.begin(); it != field_vec.end(); ++it) {
- auto &field = **it;
- if (field.deprecated || !field.IsRequired()) { continue; }
+ auto& field = **it;
+ if (field.deprecated || !field.IsRequired()) {
+ continue;
+ }
writer.SetValue("offset", NumToString(field.value.offset));
writer += "builder.required(o, {{offset}})";
}
@@ -690,7 +719,7 @@
}
// Generate a method to create a vector from a Kotlin array.
- void GenerateCreateVectorField(FieldDef &field, CodeWriter &writer,
+ void GenerateCreateVectorField(FieldDef& field, CodeWriter& writer,
const IDLOptions options) const {
auto vector_type = field.value.type.VectorType();
auto method_name = namer_.Method("create", field, "vector");
@@ -718,7 +747,7 @@
options.gen_jvmstatic);
}
- void GenerateStartVectorField(FieldDef &field, CodeWriter &writer,
+ void GenerateStartVectorField(FieldDef& field, CodeWriter& writer,
const IDLOptions options) const {
// Generate a method to start a vector, data to be added manually
// after.
@@ -735,8 +764,8 @@
options.gen_jvmstatic);
}
- void GenerateAddField(std::string field_pos, FieldDef &field,
- CodeWriter &writer, const IDLOptions options) const {
+ void GenerateAddField(std::string field_pos, FieldDef& field,
+ CodeWriter& writer, const IDLOptions options) const {
auto field_type = GenTypeBasic(field.value.type.base_type);
auto secondArg = namer_.Variable(field.name) + ": " + field_type;
@@ -770,21 +799,27 @@
}
}
- static std::string ToSignedType(const Type &type) {
+ static std::string ToSignedType(const Type& type) {
switch (type.base_type) {
- case BASE_TYPE_UINT: return GenTypeBasic(BASE_TYPE_INT);
- case BASE_TYPE_ULONG: return GenTypeBasic(BASE_TYPE_LONG);
+ case BASE_TYPE_UINT:
+ return GenTypeBasic(BASE_TYPE_INT);
+ case BASE_TYPE_ULONG:
+ return GenTypeBasic(BASE_TYPE_LONG);
case BASE_TYPE_UCHAR:
case BASE_TYPE_NONE:
- case BASE_TYPE_UTYPE: return GenTypeBasic(BASE_TYPE_CHAR);
- case BASE_TYPE_USHORT: return GenTypeBasic(BASE_TYPE_SHORT);
- case BASE_TYPE_VECTOR: return ToSignedType(type.VectorType());
- default: return GenTypeBasic(type.base_type);
+ case BASE_TYPE_UTYPE:
+ return GenTypeBasic(BASE_TYPE_CHAR);
+ case BASE_TYPE_USHORT:
+ return GenTypeBasic(BASE_TYPE_SHORT);
+ case BASE_TYPE_VECTOR:
+ return ToSignedType(type.VectorType());
+ default:
+ return GenTypeBasic(type.base_type);
}
}
- static std::string FlexBufferBuilderCast(const std::string &method,
- FieldDef &field, bool isFirst) {
+ static std::string FlexBufferBuilderCast(const std::string& method,
+ FieldDef& field, bool isFirst) {
auto field_type = GenTypeBasic(field.value.type.base_type);
std::string to_type;
if (method == "Boolean")
@@ -808,7 +843,7 @@
}
// fun startMonster(builder: FlatBufferBuilder) = builder.startTable(11)
- void GenerateStartStructMethod(StructDef &struct_def, CodeWriter &code,
+ void GenerateStartStructMethod(StructDef& struct_def, CodeWriter& code,
const IDLOptions options) const {
GenerateFunOneLine(
code, namer_.LegacyJavaMethod2("start", struct_def, ""),
@@ -820,7 +855,7 @@
options.gen_jvmstatic);
}
- void GenerateTableCreator(StructDef &struct_def, CodeWriter &writer,
+ void GenerateTableCreator(StructDef& struct_def, CodeWriter& writer,
const IDLOptions options) const {
// Generate a method that creates a table in one go. This is only possible
// when the table has no struct fields, since those have to be created
@@ -830,7 +865,7 @@
auto fields_vec = struct_def.fields.vec;
for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
if (IsStruct(field.value.type)) {
has_no_struct_fields = false;
@@ -848,7 +883,7 @@
std::stringstream params;
params << "builder: FlatBufferBuilder";
for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
params << ", " << namer_.Variable(field);
if (!IsScalar(field.value.type.base_type)) {
@@ -872,7 +907,7 @@
for (size_t size = largest; size; size /= 2) {
for (auto it = fields_vec.rbegin(); it != fields_vec.rend();
++it) {
- auto &field = **it;
+ auto& field = **it;
auto base_type_size = SizeOf(field.value.type.base_type);
if (!field.deprecated &&
(!sortbysize || size == base_type_size)) {
@@ -898,7 +933,7 @@
options.gen_jvmstatic);
}
}
- void GenerateBufferHasIdentifier(StructDef &struct_def, CodeWriter &writer,
+ void GenerateBufferHasIdentifier(StructDef& struct_def, CodeWriter& writer,
IDLOptions options) const {
auto file_identifier = parser_.file_identifier_;
// Check if a buffer has the identifier.
@@ -913,11 +948,11 @@
options.gen_jvmstatic);
}
- void GenerateStructGetters(StructDef &struct_def, CodeWriter &writer) const {
+ void GenerateStructGetters(StructDef& struct_def, CodeWriter& writer) const {
auto fields_vec = struct_def.fields.vec;
- FieldDef *key_field = nullptr;
+ FieldDef* key_field = nullptr;
for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
if (field.key) key_field = &field;
@@ -1090,7 +1125,8 @@
case BASE_TYPE_UNION:
found = "{{bbgetter}}(obj, {{index}}){{ucast}}";
break;
- default: found = "{{bbgetter}}({{index}}){{ucast}}";
+ default:
+ found = "{{bbgetter}}({{index}}){{ucast}}";
}
OffsetWrapper(
writer, offset_val, [&]() { writer += found; },
@@ -1105,7 +1141,8 @@
offset_val, bbgetter + "(obj, o + bb_pos)", "null");
});
break;
- default: FLATBUFFERS_ASSERT(0);
+ default:
+ FLATBUFFERS_ASSERT(0);
}
}
@@ -1118,10 +1155,10 @@
// See if we should generate a by-key accessor.
if (field.value.type.element == BASE_TYPE_STRUCT &&
!field.value.type.struct_def->fixed) {
- auto &sd = *field.value.type.struct_def;
- auto &fields = sd.fields.vec;
+ auto& sd = *field.value.type.struct_def;
+ auto& fields = sd.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
- auto &kfield = **kit;
+ auto& kfield = **kit;
if (kfield.key) {
auto qualified_name = WrapInNameSpace(sd);
auto name = namer_.Method(field, "ByKey");
@@ -1286,35 +1323,47 @@
}
}
- static std::string CastToUsigned(const FieldDef &field) {
+ static std::string CastToUsigned(const FieldDef& field) {
return CastToUsigned(field.value.type);
}
static std::string CastToUsigned(const Type type) {
switch (type.base_type) {
- case BASE_TYPE_UINT: return ".toUInt()";
+ case BASE_TYPE_UINT:
+ return ".toUInt()";
case BASE_TYPE_UCHAR:
- case BASE_TYPE_UTYPE: return ".toUByte()";
- case BASE_TYPE_USHORT: return ".toUShort()";
- case BASE_TYPE_ULONG: return ".toULong()";
- case BASE_TYPE_VECTOR: return CastToUsigned(type.VectorType());
- default: return "";
+ case BASE_TYPE_UTYPE:
+ return ".toUByte()";
+ case BASE_TYPE_USHORT:
+ return ".toUShort()";
+ case BASE_TYPE_ULONG:
+ return ".toULong()";
+ case BASE_TYPE_VECTOR:
+ return CastToUsigned(type.VectorType());
+ default:
+ return "";
}
}
- static std::string CastToSigned(const FieldDef &field) {
+ static std::string CastToSigned(const FieldDef& field) {
return CastToSigned(field.value.type);
}
static std::string CastToSigned(const Type type) {
switch (type.base_type) {
- case BASE_TYPE_UINT: return ".toInt()";
+ case BASE_TYPE_UINT:
+ return ".toInt()";
case BASE_TYPE_UCHAR:
- case BASE_TYPE_UTYPE: return ".toByte()";
- case BASE_TYPE_USHORT: return ".toShort()";
- case BASE_TYPE_ULONG: return ".toLong()";
- case BASE_TYPE_VECTOR: return CastToSigned(type.VectorType());
- default: return "";
+ case BASE_TYPE_UTYPE:
+ return ".toByte()";
+ case BASE_TYPE_USHORT:
+ return ".toShort()";
+ case BASE_TYPE_ULONG:
+ return ".toLong()";
+ case BASE_TYPE_VECTOR:
+ return CastToSigned(type.VectorType());
+ default:
+ return "";
}
}
@@ -1323,15 +1372,19 @@
case BASE_TYPE_UINT:
case BASE_TYPE_UCHAR:
case BASE_TYPE_UTYPE:
- case BASE_TYPE_USHORT: return "u";
- case BASE_TYPE_ULONG: return "UL";
- case BASE_TYPE_LONG: return "L";
- default: return "";
+ case BASE_TYPE_USHORT:
+ return "u";
+ case BASE_TYPE_ULONG:
+ return "UL";
+ case BASE_TYPE_LONG:
+ return "L";
+ default:
+ return "";
}
}
- void GenerateCompanionObject(CodeWriter &code,
- const std::function<void()> &callback) const {
+ void GenerateCompanionObject(CodeWriter& code,
+ const std::function<void()>& callback) const {
code += "companion object {";
code.IncrementIdentLevel();
callback();
@@ -1340,8 +1393,8 @@
}
// Generate a documentation comment, if available.
- void GenerateComment(const std::vector<std::string> &dc, CodeWriter &writer,
- const CommentConfig *config) const {
+ void GenerateComment(const std::vector<std::string>& dc, CodeWriter& writer,
+ const CommentConfig* config) const {
if (dc.begin() == dc.end()) {
// Don't output empty comment blocks with 0 lines of comment content.
return;
@@ -1362,8 +1415,8 @@
}
}
- void GenerateGetRootAsAccessors(const std::string &struct_name,
- CodeWriter &writer,
+ void GenerateGetRootAsAccessors(const std::string& struct_name,
+ CodeWriter& writer,
IDLOptions options) const {
// Generate a special accessor for the table that when used as the root
// ex: fun getRootAsMonster(_bb: ByteBuffer): Monster {...}
@@ -1390,7 +1443,7 @@
writer += "}";
}
- void GenerateStaticConstructor(const StructDef &struct_def, CodeWriter &code,
+ void GenerateStaticConstructor(const StructDef& struct_def, CodeWriter& code,
const IDLOptions options) const {
// create a struct constructor function
auto params = StructConstructorParams(struct_def);
@@ -1403,14 +1456,16 @@
options.gen_jvmstatic);
}
- std::string StructConstructorParams(const StructDef &struct_def,
- const std::string &prefix = "") const {
+ std::string StructConstructorParams(const StructDef& struct_def,
+ const std::string& prefix = "") const {
// builder: FlatBufferBuilder
std::stringstream out;
auto field_vec = struct_def.fields.vec;
- if (prefix.empty()) { out << "builder: FlatBufferBuilder"; }
+ if (prefix.empty()) {
+ out << "builder: FlatBufferBuilder";
+ }
for (auto it = field_vec.begin(); it != field_vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (IsStruct(field.value.type)) {
// Generate arguments for a struct inside a struct. To ensure
// names don't clash, and to make it obvious these arguments are
@@ -1426,10 +1481,10 @@
return out.str();
}
- static void GeneratePropertyOneLine(CodeWriter &writer,
- const std::string &name,
- const std::string &type,
- const std::function<void()> &body) {
+ static void GeneratePropertyOneLine(CodeWriter& writer,
+ const std::string& name,
+ const std::string& type,
+ const std::function<void()>& body) {
// Generates Kotlin getter for properties
// e.g.:
// val prop: Mytype = x
@@ -1438,9 +1493,9 @@
writer += "val {{_name}} : {{_type}} = \\";
body();
}
- static void GenerateGetterOneLine(CodeWriter &writer, const std::string &name,
- const std::string &type,
- const std::function<void()> &body) {
+ static void GenerateGetterOneLine(CodeWriter& writer, const std::string& name,
+ const std::string& type,
+ const std::function<void()>& body) {
// Generates Kotlin getter for properties
// e.g.:
// val prop: Mytype get() = x
@@ -1450,9 +1505,9 @@
body();
}
- static void GenerateGetter(CodeWriter &writer, const std::string &name,
- const std::string &type,
- const std::function<void()> &body) {
+ static void GenerateGetter(CodeWriter& writer, const std::string& name,
+ const std::string& type,
+ const std::function<void()>& body) {
// Generates Kotlin getter for properties
// e.g.:
// val prop: Mytype
@@ -1471,10 +1526,10 @@
writer.DecrementIdentLevel();
}
- static void GenerateFun(CodeWriter &writer, const std::string &name,
- const std::string ¶ms,
- const std::string &returnType,
- const std::function<void()> &body,
+ static void GenerateFun(CodeWriter& writer, const std::string& name,
+ const std::string& params,
+ const std::string& returnType,
+ const std::function<void()>& body,
bool gen_jvmstatic = false) {
// Generates Kotlin function
// e.g.:
@@ -1493,10 +1548,10 @@
writer += "}";
}
- static void GenerateFunOneLine(CodeWriter &writer, const std::string &name,
- const std::string ¶ms,
- const std::string &returnType,
- const std::function<void()> &body,
+ static void GenerateFunOneLine(CodeWriter& writer, const std::string& name,
+ const std::string& params,
+ const std::string& returnType,
+ const std::function<void()>& body,
bool gen_jvmstatic = false) {
// Generates Kotlin function
// e.g.:
@@ -1510,10 +1565,10 @@
body();
}
- static void GenerateOverrideFun(CodeWriter &writer, const std::string &name,
- const std::string ¶ms,
- const std::string &returnType,
- const std::function<void()> &body) {
+ static void GenerateOverrideFun(CodeWriter& writer, const std::string& name,
+ const std::string& params,
+ const std::string& returnType,
+ const std::function<void()>& body) {
// Generates Kotlin function
// e.g.:
// override fun path(j: Int): Vec3 = return path(Vec3(), j)
@@ -1521,11 +1576,11 @@
GenerateFun(writer, name, params, returnType, body);
}
- static void GenerateOverrideFunOneLine(CodeWriter &writer,
- const std::string &name,
- const std::string ¶ms,
- const std::string &returnType,
- const std::string &statement) {
+ static void GenerateOverrideFunOneLine(CodeWriter& writer,
+ const std::string& name,
+ const std::string& params,
+ const std::string& returnType,
+ const std::string& statement) {
// Generates Kotlin function
// e.g.:
// override fun path(j: Int): Vec3 = return path(Vec3(), j)
@@ -1537,16 +1592,16 @@
writer += statement;
}
- static std::string OffsetWrapperOneLine(const std::string &offset,
- const std::string &found,
- const std::string ¬_found) {
+ static std::string OffsetWrapperOneLine(const std::string& offset,
+ const std::string& found,
+ const std::string& not_found) {
return "val o = __offset(" + offset + "); return if (o != 0) " + found +
" else " + not_found;
}
- static void OffsetWrapper(CodeWriter &code, const std::string &offset,
- const std::function<void()> &found,
- const std::function<void()> ¬_found) {
+ static void OffsetWrapper(CodeWriter& code, const std::string& offset,
+ const std::function<void()>& found,
+ const std::function<void()>& not_found) {
code += "val o = __offset(" + offset + ")";
code += "return if (o != 0) {";
code.IncrementIdentLevel();
@@ -1559,7 +1614,7 @@
code += "}";
}
- static std::string Indirect(const std::string &index, bool fixed) {
+ static std::string Indirect(const std::string& index, bool fixed) {
// We apply __indirect() and struct is not fixed.
if (!fixed) return "__indirect(" + index + ")";
return index;
@@ -1567,34 +1622,43 @@
static std::string NotFoundReturn(BaseType el) {
switch (el) {
- case BASE_TYPE_FLOAT: return "0.0f";
- case BASE_TYPE_DOUBLE: return "0.0";
- case BASE_TYPE_BOOL: return "false";
+ case BASE_TYPE_FLOAT:
+ return "0.0f";
+ case BASE_TYPE_DOUBLE:
+ return "0.0";
+ case BASE_TYPE_BOOL:
+ return "false";
case BASE_TYPE_LONG:
case BASE_TYPE_INT:
case BASE_TYPE_CHAR:
- case BASE_TYPE_SHORT: return "0";
+ case BASE_TYPE_SHORT:
+ return "0";
case BASE_TYPE_UINT:
case BASE_TYPE_UCHAR:
case BASE_TYPE_USHORT:
- case BASE_TYPE_UTYPE: return "0u";
- case BASE_TYPE_ULONG: return "0uL";
- default: return "null";
+ case BASE_TYPE_UTYPE:
+ return "0u";
+ case BASE_TYPE_ULONG:
+ return "0uL";
+ default:
+ return "null";
}
}
// Prepend @JvmStatic to methods in companion object.
- static void GenerateJvmStaticAnnotation(CodeWriter &code,
+ static void GenerateJvmStaticAnnotation(CodeWriter& code,
bool gen_jvmstatic) {
- if (gen_jvmstatic) { code += "@JvmStatic"; }
+ if (gen_jvmstatic) {
+ code += "@JvmStatic";
+ }
}
const IdlNamer namer_;
};
} // namespace kotlin
-static bool GenerateKotlin(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateKotlin(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
kotlin::KotlinGenerator generator(parser, path, file_name);
return generator.generate();
}
@@ -1603,20 +1667,21 @@
class KotlinCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateKotlin(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateKotlin(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -1624,16 +1689,16 @@
return Status::NOT_IMPLEMENTED;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_kotlin_kmp.cpp b/src/idl_gen_kotlin_kmp.cpp
index 2dba494..89bee94 100644
--- a/src/idl_gen_kotlin_kmp.cpp
+++ b/src/idl_gen_kotlin_kmp.cpp
@@ -36,56 +36,56 @@
"POSITIVE_INFINITY",
"NEGATIVE_INFINITY");
-static const CommentConfig comment_config = { "/**", " *", " */" };
+static const CommentConfig comment_config = {"/**", " *", " */"};
static const std::string ident_pad = " ";
static std::set<std::string> KotlinKeywords() {
- return { "package", "as", "typealias", "class", "this", "super",
- "val", "var", "fun", "for", "null", "true",
- "false", "is", "in", "throw", "return", "break",
- "continue", "object", "if", "try", "else", "while",
- "do", "when", "interface", "typeof", "Any", "Character" };
+ return {"package", "as", "typealias", "class", "this", "super",
+ "val", "var", "fun", "for", "null", "true",
+ "false", "is", "in", "throw", "return", "break",
+ "continue", "object", "if", "try", "else", "while",
+ "do", "when", "interface", "typeof", "Any", "Character"};
}
static Namer::Config KotlinDefaultConfig() {
- return { /*types=*/Case::kKeep,
- /*constants=*/Case::kUpperCamel,
- /*methods=*/Case::kLowerCamel,
- /*functions=*/Case::kKeep,
- /*fields=*/Case::kLowerCamel,
- /*variables=*/Case::kLowerCamel,
- /*variants=*/Case::kUpperCamel,
- /*enum_variant_seperator=*/"", // I.e. Concatenate.
- /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
- /*namespaces=*/Case::kLowerCamel,
- /*namespace_seperator=*/".",
- /*object_prefix=*/"",
- /*object_suffix=*/"T",
- /*keyword_prefix=*/"",
- /*keyword_suffix=*/"E",
- /*filenames=*/Case::kUpperCamel,
- /*directories=*/Case::kLowerCamel,
- /*output_path=*/"",
- /*filename_suffix=*/"",
- /*filename_extension=*/".kt" };
+ return {/*types=*/Case::kKeep,
+ /*constants=*/Case::kUpperCamel,
+ /*methods=*/Case::kLowerCamel,
+ /*functions=*/Case::kKeep,
+ /*fields=*/Case::kLowerCamel,
+ /*variables=*/Case::kLowerCamel,
+ /*variants=*/Case::kUpperCamel,
+ /*enum_variant_seperator=*/"", // I.e. Concatenate.
+ /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
+ /*namespaces=*/Case::kLowerCamel,
+ /*namespace_seperator=*/".",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"E",
+ /*filenames=*/Case::kUpperCamel,
+ /*directories=*/Case::kLowerCamel,
+ /*output_path=*/"",
+ /*filename_suffix=*/"",
+ /*filename_extension=*/".kt"};
}
} // namespace
class KotlinKMPGenerator : public BaseGenerator {
public:
- KotlinKMPGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ KotlinKMPGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", ".", "kt"),
namer_(WithFlagOptions(KotlinDefaultConfig(), parser.opts, path),
KotlinKeywords()) {}
- KotlinKMPGenerator &operator=(const KotlinKMPGenerator &);
+ KotlinKMPGenerator& operator=(const KotlinKMPGenerator&);
bool generate() FLATBUFFERS_OVERRIDE {
std::string one_file_code;
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
CodeWriter enumWriter(ident_pad);
- auto &enum_def = **it;
+ auto& enum_def = **it;
GenEnum(enum_def, enumWriter);
enumWriter += "";
@@ -103,7 +103,7 @@
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
CodeWriter structWriter(ident_pad);
- auto &struct_def = **it;
+ auto& struct_def = **it;
GenStruct(struct_def, structWriter, parser_.opts);
structWriter += "";
@@ -126,21 +126,21 @@
return true;
}
- std::string TypeInNameSpace(const Namespace *ns,
- const std::string &name = "") const {
+ std::string TypeInNameSpace(const Namespace* ns,
+ const std::string& name = "") const {
auto qualified = namer_.Namespace(*ns);
return qualified.empty() ? name : qualified + qualifying_separator_ + name;
}
- std::string TypeInNameSpace(const Definition &def,
- const std::string &suffix = "") const {
+ std::string TypeInNameSpace(const Definition& def,
+ const std::string& suffix = "") const {
return TypeInNameSpace(def.defined_namespace, def.name + suffix);
}
// Save out the generated code for a single class while adding
// declaration boilerplate.
- bool SaveType(const std::string &defname, const Namespace &ns,
- const std::string &classcode, bool needs_includes) const {
+ bool SaveType(const std::string& defname, const Namespace& ns,
+ const std::string& classcode, bool needs_includes) const {
if (!classcode.length()) return true;
std::string code =
@@ -151,7 +151,9 @@
code += "package " + namespace_name;
code += "\n\n";
}
- if (needs_includes) { code += "import com.google.flatbuffers.kotlin.*\n"; }
+ if (needs_includes) {
+ code += "import com.google.flatbuffers.kotlin.*\n";
+ }
code += "import kotlin.jvm.JvmInline\n";
code += classcode;
const std::string dirs =
@@ -162,12 +164,14 @@
return SaveFile(filename.c_str(), code, false);
}
- static bool IsEnum(const Type &type) {
+ static bool IsEnum(const Type& type) {
return type.enum_def != nullptr && IsInteger(type.base_type);
}
- std::string GenerateKotlinPrimiteArray(const Type &type) const {
- if (IsScalar(type.base_type) && !IsEnum(type)) { return GenType(type); }
+ std::string GenerateKotlinPrimiteArray(const Type& type) const {
+ if (IsScalar(type.base_type) && !IsEnum(type)) {
+ return GenType(type);
+ }
if (IsEnum(type) || type.base_type == BASE_TYPE_UTYPE) {
return TypeInNameSpace(type.enum_def->defined_namespace,
@@ -176,14 +180,18 @@
switch (type.base_type) {
case BASE_TYPE_STRUCT:
return "Offset<" + TypeInNameSpace(*type.struct_def) + ">";
- case BASE_TYPE_UNION: return "UnionOffset";
- case BASE_TYPE_STRING: return "Offset<String>";
- case BASE_TYPE_UTYPE: return "Offset<UByte>";
- default: return "Offset<" + GenTypeBasic(type.element) + ">";
+ case BASE_TYPE_UNION:
+ return "UnionOffset";
+ case BASE_TYPE_STRING:
+ return "Offset<String>";
+ case BASE_TYPE_UTYPE:
+ return "Offset<UByte>";
+ default:
+ return "Offset<" + GenTypeBasic(type.element) + ">";
}
}
- std::string GenerateKotlinOffsetArray(const Type &type) const {
+ std::string GenerateKotlinOffsetArray(const Type& type) const {
if (IsScalar(type.base_type) && !IsEnum(type)) {
return GenType(type) + "Array";
}
@@ -195,40 +203,60 @@
switch (type.base_type) {
case BASE_TYPE_STRUCT:
return TypeInNameSpace(*type.struct_def) + "OffsetArray";
- case BASE_TYPE_UNION: return "UnionOffsetArray";
- case BASE_TYPE_STRING: return "StringOffsetArray";
- case BASE_TYPE_UTYPE: return "UByteArray";
- default: return GenTypeBasic(type.element) + "OffsetArray";
+ case BASE_TYPE_UNION:
+ return "UnionOffsetArray";
+ case BASE_TYPE_STRING:
+ return "StringOffsetArray";
+ case BASE_TYPE_UTYPE:
+ return "UByteArray";
+ default:
+ return GenTypeBasic(type.element) + "OffsetArray";
}
}
- std::string GenTypeBasic(const BaseType &type) const {
+ std::string GenTypeBasic(const BaseType& type) const {
switch (type) {
case BASE_TYPE_NONE:
- case BASE_TYPE_UTYPE: return "UByte";
- case BASE_TYPE_BOOL: return "Boolean";
- case BASE_TYPE_CHAR: return "Byte";
- case BASE_TYPE_UCHAR: return "UByte";
- case BASE_TYPE_SHORT: return "Short";
- case BASE_TYPE_USHORT: return "UShort";
- case BASE_TYPE_INT: return "Int";
- case BASE_TYPE_UINT: return "UInt";
- case BASE_TYPE_LONG: return "Long";
- case BASE_TYPE_ULONG: return "ULong";
- case BASE_TYPE_FLOAT: return "Float";
- case BASE_TYPE_DOUBLE: return "Double";
+ case BASE_TYPE_UTYPE:
+ return "UByte";
+ case BASE_TYPE_BOOL:
+ return "Boolean";
+ case BASE_TYPE_CHAR:
+ return "Byte";
+ case BASE_TYPE_UCHAR:
+ return "UByte";
+ case BASE_TYPE_SHORT:
+ return "Short";
+ case BASE_TYPE_USHORT:
+ return "UShort";
+ case BASE_TYPE_INT:
+ return "Int";
+ case BASE_TYPE_UINT:
+ return "UInt";
+ case BASE_TYPE_LONG:
+ return "Long";
+ case BASE_TYPE_ULONG:
+ return "ULong";
+ case BASE_TYPE_FLOAT:
+ return "Float";
+ case BASE_TYPE_DOUBLE:
+ return "Double";
case BASE_TYPE_STRING:
- case BASE_TYPE_STRUCT: return "Offset";
- case BASE_TYPE_UNION: return "UnionOffset";
+ case BASE_TYPE_STRUCT:
+ return "Offset";
+ case BASE_TYPE_UNION:
+ return "UnionOffset";
case BASE_TYPE_VECTOR:
- case BASE_TYPE_ARRAY: return "VectorOffset";
+ case BASE_TYPE_ARRAY:
+ return "VectorOffset";
// VECTOR64 not supported
- case BASE_TYPE_VECTOR64: FLATBUFFERS_ASSERT(0);
+ case BASE_TYPE_VECTOR64:
+ FLATBUFFERS_ASSERT(0);
}
return "Int";
}
- std::string GenType(const Type &type) const {
+ std::string GenType(const Type& type) const {
auto base_type = GenTypeBasic(type.base_type);
if (IsEnum(type) || type.base_type == BASE_TYPE_UTYPE) {
@@ -243,32 +271,42 @@
return base_type + "<" + TypeInNameSpace(*type.struct_def) + ">";
case BASE_TYPE_UNION:
return base_type + "<" + GenTypeBasic(type.element) + ">";
- case BASE_TYPE_STRING: return base_type + "<String>";
- case BASE_TYPE_UTYPE: return base_type + "<UByte>";
- default: return base_type + "<" + GenTypeBasic(type.element) + ">";
+ case BASE_TYPE_STRING:
+ return base_type + "<String>";
+ case BASE_TYPE_UTYPE:
+ return base_type + "<UByte>";
+ default:
+ return base_type + "<" + GenTypeBasic(type.element) + ">";
}
}
case BASE_TYPE_STRUCT:
return base_type + "<" + TypeInNameSpace(*type.struct_def) + ">";
- case BASE_TYPE_STRING: return base_type + "<String>";
- case BASE_TYPE_UNION: return base_type;
- default: return base_type;
+ case BASE_TYPE_STRING:
+ return base_type + "<String>";
+ case BASE_TYPE_UNION:
+ return base_type;
+ default:
+ return base_type;
}
// clang-format on
}
- std::string GenTypePointer(const Type &type) const {
+ std::string GenTypePointer(const Type& type) const {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "String";
- case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
- case BASE_TYPE_STRUCT: return TypeInNameSpace(*type.struct_def);
- default: return "Table";
+ case BASE_TYPE_STRING:
+ return "String";
+ case BASE_TYPE_VECTOR:
+ return GenTypeGet(type.VectorType());
+ case BASE_TYPE_STRUCT:
+ return TypeInNameSpace(*type.struct_def);
+ default:
+ return "Table";
}
}
// with the addition of optional scalar types,
// we are adding the nullable '?' operator to return type of a field.
- std::string GetterReturnType(const FieldDef &field) const {
+ std::string GetterReturnType(const FieldDef& field) const {
auto base_type = field.value.type.base_type;
auto r_type = GenTypeGet(field.value.type);
@@ -284,14 +322,14 @@
return r_type;
}
- std::string GenTypeGet(const Type &type) const {
+ std::string GenTypeGet(const Type& type) const {
return IsScalar(type.base_type) ? GenType(type) : GenTypePointer(type);
}
- std::string GenEnumDefaultValue(const FieldDef &field) const {
- auto &value = field.value;
+ std::string GenEnumDefaultValue(const FieldDef& field) const {
+ auto& value = field.value;
FLATBUFFERS_ASSERT(value.type.enum_def);
- auto &enum_def = *value.type.enum_def;
+ auto& enum_def = *value.type.enum_def;
auto enum_val = enum_def.FindByValue(value.constant);
return enum_val ? (TypeInNameSpace(enum_def) + "." + enum_val->name)
: value.constant;
@@ -299,12 +337,14 @@
// differently from GenDefaultValue, the default values are meant
// to be inserted in the buffer as the object is building.
- std::string GenDefaultBufferValue(const FieldDef &field) const {
- auto &value = field.value;
+ std::string GenDefaultBufferValue(const FieldDef& field) const {
+ auto& value = field.value;
auto base_type = value.type.base_type;
auto field_name = field.name;
std::string suffix = IsScalar(base_type) ? LiteralSuffix(value.type) : "";
- if (field.IsScalarOptional()) { return "null"; }
+ if (field.IsScalarOptional()) {
+ return "null";
+ }
if (IsFloat(base_type)) {
auto val = KotlinFloatGen.GenFloatConstant(field);
if (base_type == BASE_TYPE_DOUBLE && val.back() == 'f') {
@@ -329,12 +369,14 @@
}
}
- std::string GenDefaultValue(const FieldDef &field) const {
- auto &value = field.value;
+ std::string GenDefaultValue(const FieldDef& field) const {
+ auto& value = field.value;
auto base_type = value.type.base_type;
auto field_name = field.name;
std::string suffix = LiteralSuffix(value.type);
- if (field.IsScalarOptional()) { return "null"; }
+ if (field.IsScalarOptional()) {
+ return "null";
+ }
if (IsFloat(base_type)) {
auto val = KotlinFloatGen.GenFloatConstant(field);
if (base_type == BASE_TYPE_DOUBLE && val.back() == 'f') {
@@ -365,19 +407,23 @@
value.constant + suffix + ")";
case BASE_TYPE_UNION:
case BASE_TYPE_STRUCT:
- case BASE_TYPE_STRING: return "null";
- case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
- case BASE_TYPE_FLOAT: return value.constant + "f";
+ case BASE_TYPE_STRING:
+ return "null";
+ case BASE_TYPE_BOOL:
+ return value.constant == "0" ? "false" : "true";
+ case BASE_TYPE_FLOAT:
+ return value.constant + "f";
case BASE_TYPE_DOUBLE: {
return value.constant + ".toDouble()";
}
- default: return value.constant + suffix;
+ default:
+ return value.constant + suffix;
}
}
return value.constant + suffix;
}
- void GenEnum(EnumDef &enum_def, CodeWriter &writer) const {
+ void GenEnum(EnumDef& enum_def, CodeWriter& writer) const {
if (enum_def.generated) return;
GenerateComment(enum_def.doc_comment, writer, &comment_config);
@@ -393,7 +439,7 @@
auto vals = enum_def.Vals();
for (auto it = vals.begin(); it != vals.end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
auto val = enum_def.ToString(ev);
auto suffix = LiteralSuffix(enum_def.underlying_type);
writer.SetValue("name", namer_.Variant(ev));
@@ -421,7 +467,9 @@
writer += "\"\", \\";
val = ev;
writer += "\"" + (*it)->name + "\"\\";
- if (it + 1 != vals.end()) { writer += ", \\"; }
+ if (it + 1 != vals.end()) {
+ writer += ", \\";
+ }
}
writer += ")";
});
@@ -443,52 +491,67 @@
}
// Returns the function name that is able to read a value of the given type.
- std::string ByteBufferGetter(const Type &type,
+ std::string ByteBufferGetter(const Type& type,
std::string bb_var_name) const {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "string";
- case BASE_TYPE_STRUCT: return "__struct";
- case BASE_TYPE_UNION: return "union";
+ case BASE_TYPE_STRING:
+ return "string";
+ case BASE_TYPE_STRUCT:
+ return "__struct";
+ case BASE_TYPE_UNION:
+ return "union";
case BASE_TYPE_VECTOR:
return ByteBufferGetter(type.VectorType(), bb_var_name);
- case BASE_TYPE_INT: return bb_var_name + ".getInt";
- case BASE_TYPE_UINT: return bb_var_name + ".getUInt";
- case BASE_TYPE_SHORT: return bb_var_name + ".getShort";
- case BASE_TYPE_USHORT: return bb_var_name + ".getUShort";
- case BASE_TYPE_ULONG: return bb_var_name + ".getULong";
- case BASE_TYPE_LONG: return bb_var_name + ".getLong";
- case BASE_TYPE_FLOAT: return bb_var_name + ".getFloat";
- case BASE_TYPE_DOUBLE: return bb_var_name + ".getDouble";
+ case BASE_TYPE_INT:
+ return bb_var_name + ".getInt";
+ case BASE_TYPE_UINT:
+ return bb_var_name + ".getUInt";
+ case BASE_TYPE_SHORT:
+ return bb_var_name + ".getShort";
+ case BASE_TYPE_USHORT:
+ return bb_var_name + ".getUShort";
+ case BASE_TYPE_ULONG:
+ return bb_var_name + ".getULong";
+ case BASE_TYPE_LONG:
+ return bb_var_name + ".getLong";
+ case BASE_TYPE_FLOAT:
+ return bb_var_name + ".getFloat";
+ case BASE_TYPE_DOUBLE:
+ return bb_var_name + ".getDouble";
case BASE_TYPE_UTYPE:
- case BASE_TYPE_UCHAR: return bb_var_name + ".getUByte";
+ case BASE_TYPE_UCHAR:
+ return bb_var_name + ".getUByte";
case BASE_TYPE_CHAR:
- case BASE_TYPE_NONE: return bb_var_name + ".get";
- case BASE_TYPE_BOOL: return "0.toByte() != " + bb_var_name + ".get";
- default: return bb_var_name + "." + namer_.Method("get", GenType(type));
+ case BASE_TYPE_NONE:
+ return bb_var_name + ".get";
+ case BASE_TYPE_BOOL:
+ return "0.toByte() != " + bb_var_name + ".get";
+ default:
+ return bb_var_name + "." + namer_.Method("get", GenType(type));
}
}
// Returns the function name that is able to read a value of the given type.
- std::string GenLookupByKey(flatbuffers::FieldDef *key_field,
- const std::string &bb_var_name,
- const char *num = nullptr) const {
+ std::string GenLookupByKey(flatbuffers::FieldDef* key_field,
+ const std::string& bb_var_name,
+ const char* num = nullptr) const {
auto type = key_field->value.type;
return ByteBufferGetter(type, bb_var_name) + "(" +
GenOffsetGetter(key_field, num) + ")";
}
// Returns the method name for use with add/put calls.
- static std::string GenMethod(const Type &type) {
+ static std::string GenMethod(const Type& type) {
return IsStruct(type) ? "Struct" : "";
}
// Recursively generate arguments for a constructor, to deal with nested
// structs.
- void GenStructArgs(const StructDef &struct_def, CodeWriter &writer,
- const char *nameprefix) const {
+ void GenStructArgs(const StructDef& struct_def, CodeWriter& writer,
+ const char* nameprefix) const {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (IsStruct(field.value.type)) {
// Generate arguments for a struct inside a struct. To ensure
// names don't clash, and to make it obvious these arguments are
@@ -507,14 +570,14 @@
// Recusively generate struct construction statements of the form:
// builder.putType(name);
// and insert manual padding.
- void GenStructBody(const StructDef &struct_def, CodeWriter &writer,
- const char *nameprefix) const {
+ void GenStructBody(const StructDef& struct_def, CodeWriter& writer,
+ const char* nameprefix) const {
writer.SetValue("align", NumToString(struct_def.minalign));
writer.SetValue("size", NumToString(struct_def.bytesize));
writer += "builder.prep({{align}}, {{size}})";
auto fields_vec = struct_def.fields.vec;
for (auto it = fields_vec.rbegin(); it != fields_vec.rend(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.padding) {
writer.SetValue("pad", NumToString(field.padding));
@@ -533,8 +596,8 @@
}
}
- std::string GenOffsetGetter(flatbuffers::FieldDef *key_field,
- const char *num = nullptr) const {
+ std::string GenOffsetGetter(flatbuffers::FieldDef* key_field,
+ const char* num = nullptr) const {
std::string key_offset =
"offset(" + NumToString(key_field->value.offset) + ", ";
if (num) {
@@ -546,11 +609,13 @@
return key_offset;
}
- bool StructHasUnsignedField(StructDef &struct_def) {
+ bool StructHasUnsignedField(StructDef& struct_def) {
auto vec = struct_def.fields.vec;
for (auto it = vec.begin(); it != vec.end(); ++it) {
- auto &field = **it;
- if (IsUnsigned(field.value.type.base_type)) { return true; }
+ auto& field = **it;
+ if (IsUnsigned(field.value.type.base_type)) {
+ return true;
+ }
}
return false;
}
@@ -561,7 +626,7 @@
// Array<Offset<Monster>> generates boxing.
// So we creates a new type to avoid it:
// typealias MonterOffsetArray = IntArray
- void GenStructOffsetAlias(StructDef &struct_def, CodeWriter &writer) const {
+ void GenStructOffsetAlias(StructDef& struct_def, CodeWriter& writer) const {
if (struct_def.generated) return;
auto name = namer_.Type(struct_def);
// This assumes offset as Ints always.
@@ -585,7 +650,7 @@
// Array<Offset<Monster>> generates boxing.
// So we creates a new type to avoid it:
// typealias MonterOffsetArray = IntArray
- void GenEnumOffsetAlias(EnumDef &enum_def, CodeWriter &writer) const {
+ void GenEnumOffsetAlias(EnumDef& enum_def, CodeWriter& writer) const {
if (enum_def.generated) return;
// This assumes offset as Ints always.
writer += "typealias " + namer_.Type(enum_def) +
@@ -593,7 +658,7 @@
"Array";
}
- void GenStruct(StructDef &struct_def, CodeWriter &writer,
+ void GenStruct(StructDef& struct_def, CodeWriter& writer,
IDLOptions options) const {
if (struct_def.generated) return;
@@ -622,7 +687,7 @@
// Generate Static Fields
GenerateCompanionObject(writer, [&]() {
if (!struct_def.fixed) {
- FieldDef *key_field = nullptr;
+ FieldDef* key_field = nullptr;
// Generate version check method.
// Force compile time error if not using the same version
@@ -646,7 +711,7 @@
auto fields = struct_def.fields.vec;
int field_pos = -1;
for (auto it = fields.begin(); it != fields.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
field_pos++;
if (field.deprecated) continue;
if (field.key) key_field = &field;
@@ -692,8 +757,8 @@
}
// TODO: move key_field to reference instead of pointer
- void GenerateLookupByKey(FieldDef *key_field, StructDef &struct_def,
- CodeWriter &writer, const IDLOptions options) const {
+ void GenerateLookupByKey(FieldDef* key_field, StructDef& struct_def,
+ CodeWriter& writer, const IDLOptions options) const {
std::stringstream params;
params << "obj: " << namer_.Type(struct_def) << "?"
<< ", ";
@@ -750,9 +815,9 @@
options.gen_jvmstatic);
}
- void GenerateFinishSizePrefixed(StructDef &struct_def,
- const std::string &identifier,
- CodeWriter &writer,
+ void GenerateFinishSizePrefixed(StructDef& struct_def,
+ const std::string& identifier,
+ CodeWriter& writer,
const IDLOptions options) const {
auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : "";
auto gen_type = "Offset<" + namer_.Type(struct_def.name) + ">";
@@ -764,9 +829,9 @@
[&]() { writer += "builder.finishSizePrefixed(offset" + id + ")"; },
options.gen_jvmstatic);
}
- void GenerateFinishStructBuffer(StructDef &struct_def,
- const std::string &identifier,
- CodeWriter &writer,
+ void GenerateFinishStructBuffer(StructDef& struct_def,
+ const std::string& identifier,
+ CodeWriter& writer,
const IDLOptions options) const {
auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : "";
auto gen_type = "Offset<" + namer_.Type(struct_def.name) + ">";
@@ -779,7 +844,7 @@
options.gen_jvmstatic);
}
- void GenerateEndStructMethod(StructDef &struct_def, CodeWriter &writer,
+ void GenerateEndStructMethod(StructDef& struct_def, CodeWriter& writer,
const IDLOptions options) const {
// Generate end{{TableName}}(builder: FlatBufferBuilder) method
auto name = namer_.Method("end", struct_def.name);
@@ -793,8 +858,10 @@
writer += "val o: " + returns + " = builder.endTable()";
writer.IncrementIdentLevel();
for (auto it = field_vec.begin(); it != field_vec.end(); ++it) {
- auto &field = **it;
- if (field.deprecated || !field.IsRequired()) { continue; }
+ auto& field = **it;
+ if (field.deprecated || !field.IsRequired()) {
+ continue;
+ }
writer.SetValue("offset", NumToString(field.value.offset));
writer.SetValue("field_name", field.name);
writer += "builder.required(o, {{offset}}, \"{{field_name}}\")";
@@ -806,7 +873,7 @@
}
// Generate a method to create a vector from a Kotlin array.
- void GenerateCreateVectorField(FieldDef &field, CodeWriter &writer,
+ void GenerateCreateVectorField(FieldDef& field, CodeWriter& writer,
const IDLOptions options) const {
auto vector_type = field.value.type.VectorType();
auto method_name = namer_.Method("create", field, "vector");
@@ -831,7 +898,7 @@
options.gen_jvmstatic);
}
- void GenerateStartVectorField(FieldDef &field, CodeWriter &writer,
+ void GenerateStartVectorField(FieldDef& field, CodeWriter& writer,
const IDLOptions options) const {
// Generate a method to start a vector, data to be added manually
// after.
@@ -848,8 +915,8 @@
options.gen_jvmstatic);
}
- void GenerateAddField(std::string field_pos, FieldDef &field,
- CodeWriter &writer, const IDLOptions options) const {
+ void GenerateAddField(std::string field_pos, FieldDef& field,
+ CodeWriter& writer, const IDLOptions options) const {
auto field_type = GenType(field.value.type);
auto secondArg = namer_.Variable(field.name) + ": " + field_type;
@@ -891,7 +958,7 @@
}
// fun startMonster(builder: FlatBufferBuilder) = builder.startTable(11)
- void GenerateStartStructMethod(StructDef &struct_def, CodeWriter &code,
+ void GenerateStartStructMethod(StructDef& struct_def, CodeWriter& code,
const IDLOptions options) const {
GenerateFunOneLine(
code, namer_.LegacyJavaMethod2("start", struct_def, ""),
@@ -903,7 +970,7 @@
options.gen_jvmstatic);
}
- void GenerateTableCreator(StructDef &struct_def, CodeWriter &writer,
+ void GenerateTableCreator(StructDef& struct_def, CodeWriter& writer,
const IDLOptions options) const {
// Generate a method that creates a table in one go. This is only possible
// when the table has no struct fields, since those have to be created
@@ -913,7 +980,7 @@
auto fields_vec = struct_def.fields.vec;
for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
if (IsStruct(field.value.type)) {
has_no_struct_fields = false;
@@ -931,7 +998,7 @@
std::stringstream params;
params << "builder: FlatBufferBuilder";
for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
params << ", " << namer_.Variable(field);
if (!IsScalar(field.value.type.base_type)) {
@@ -956,7 +1023,7 @@
for (size_t size = largest; size; size /= 2) {
for (auto it = fields_vec.rbegin(); it != fields_vec.rend();
++it) {
- auto &field = **it;
+ auto& field = **it;
auto base_type_size = SizeOf(field.value.type.base_type);
if (!field.deprecated &&
(!sortbysize || size == base_type_size)) {
@@ -982,7 +1049,7 @@
options.gen_jvmstatic);
}
}
- void GenerateBufferHasIdentifier(StructDef &struct_def, CodeWriter &writer,
+ void GenerateBufferHasIdentifier(StructDef& struct_def, CodeWriter& writer,
IDLOptions options) const {
auto file_identifier = parser_.file_identifier_;
// Check if a buffer has the identifier.
@@ -998,11 +1065,11 @@
options.gen_jvmstatic);
}
- void GenerateStructGetters(StructDef &struct_def, CodeWriter &writer) const {
+ void GenerateStructGetters(StructDef& struct_def, CodeWriter& writer) const {
auto fields_vec = struct_def.fields.vec;
- FieldDef *key_field = nullptr;
+ FieldDef* key_field = nullptr;
for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
if (field.key) key_field = &field;
@@ -1067,9 +1134,8 @@
// fun pos(obj: Vec3) : Vec3? = obj.init(bufferPos + 4, bb)
// ? adds nullability annotation
GenerateFunOneLine(
- writer, field_name, "obj: " + field_type, return_type, [&]() {
- writer += "obj.init(bufferPos + {{offset}}, bb)";
- });
+ writer, field_name, "obj: " + field_type, return_type,
+ [&]() { writer += "obj.init(bufferPos + {{offset}}, bb)"; });
} else {
// create getter with object reuse
// ex:
@@ -1147,7 +1213,8 @@
case BASE_TYPE_UTYPE:
found = "{{field_type}}({{bbgetter}}({{index}}))";
break;
- default: found = "{{bbgetter}}({{index}})";
+ default:
+ found = "{{bbgetter}}({{index}})";
}
}
writer +=
@@ -1162,7 +1229,8 @@
offset_val, bbgetter + "(obj, it + bufferPos)", "null");
});
break;
- default: FLATBUFFERS_ASSERT(0);
+ default:
+ FLATBUFFERS_ASSERT(0);
}
}
@@ -1175,10 +1243,10 @@
// See if we should generate a by-key accessor.
if (field.value.type.element == BASE_TYPE_STRUCT &&
!field.value.type.struct_def->fixed) {
- auto &sd = *field.value.type.struct_def;
- auto &fields = sd.fields.vec;
+ auto& sd = *field.value.type.struct_def;
+ auto& fields = sd.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
- auto &kfield = **kit;
+ auto& kfield = **kit;
if (kfield.key) {
auto qualified_name = TypeInNameSpace(sd);
auto name = namer_.Method(field, "ByKey");
@@ -1272,29 +1340,35 @@
}
}
- static std::string LiteralSuffix(const Type &type) {
+ static std::string LiteralSuffix(const Type& type) {
auto base = IsVector(type) ? type.element : type.base_type;
switch (base) {
case BASE_TYPE_UINT:
case BASE_TYPE_UCHAR:
case BASE_TYPE_UTYPE:
- case BASE_TYPE_USHORT: return "u";
- case BASE_TYPE_ULONG: return "UL";
- case BASE_TYPE_LONG: return "L";
- default: return "";
+ case BASE_TYPE_USHORT:
+ return "u";
+ case BASE_TYPE_ULONG:
+ return "UL";
+ case BASE_TYPE_LONG:
+ return "L";
+ default:
+ return "";
}
}
- std::string WrapEnumValue(const Type &type, const std::string value) const {
- if (IsEnum(type)) { return GenType(type) + "(" + value + ")"; }
+ std::string WrapEnumValue(const Type& type, const std::string value) const {
+ if (IsEnum(type)) {
+ return GenType(type) + "(" + value + ")";
+ }
if (IsVector(type) && IsEnum(type.VectorType())) {
return GenType(type.VectorType()) + "(" + value + ")";
}
return value;
}
- void GenerateCompanionObject(CodeWriter &code,
- const std::function<void()> &callback) const {
+ void GenerateCompanionObject(CodeWriter& code,
+ const std::function<void()>& callback) const {
code += "companion object {";
code.IncrementIdentLevel();
callback();
@@ -1303,8 +1377,8 @@
}
// Generate a documentation comment, if available.
- void GenerateComment(const std::vector<std::string> &dc, CodeWriter &writer,
- const CommentConfig *config) const {
+ void GenerateComment(const std::vector<std::string>& dc, CodeWriter& writer,
+ const CommentConfig* config) const {
if (dc.begin() == dc.end()) {
// Don't output empty comment blocks with 0 lines of comment content.
return;
@@ -1325,8 +1399,8 @@
}
}
- void GenerateGetRootAsAccessors(const std::string &struct_name,
- CodeWriter &writer,
+ void GenerateGetRootAsAccessors(const std::string& struct_name,
+ CodeWriter& writer,
IDLOptions options) const {
// Generate a special accessor for the table that when used as the root
// ex: fun getRootAsMonster(buffer: ByteBuffer): Monster {...}
@@ -1348,7 +1422,7 @@
});
}
- void GenerateStaticConstructor(const StructDef &struct_def, CodeWriter &code,
+ void GenerateStaticConstructor(const StructDef& struct_def, CodeWriter& code,
const IDLOptions options) const {
// create a struct constructor function
auto params = StructConstructorParams(struct_def);
@@ -1362,14 +1436,16 @@
options.gen_jvmstatic);
}
- std::string StructConstructorParams(const StructDef &struct_def,
- const std::string &prefix = "") const {
+ std::string StructConstructorParams(const StructDef& struct_def,
+ const std::string& prefix = "") const {
// builder: FlatBufferBuilder
std::stringstream out;
auto field_vec = struct_def.fields.vec;
- if (prefix.empty()) { out << "builder: FlatBufferBuilder"; }
+ if (prefix.empty()) {
+ out << "builder: FlatBufferBuilder";
+ }
for (auto it = field_vec.begin(); it != field_vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (IsStruct(field.value.type)) {
// Generate arguments for a struct inside a struct. To ensure
// names don't clash, and to make it obvious these arguments are
@@ -1385,11 +1461,11 @@
return out.str();
}
- static void GenerateVarGetterSetterOneLine(CodeWriter &writer,
- const std::string &name,
- const std::string &type,
- const std::string &getter,
- const std::string &setter) {
+ static void GenerateVarGetterSetterOneLine(CodeWriter& writer,
+ const std::string& name,
+ const std::string& type,
+ const std::string& getter,
+ const std::string& setter) {
// Generates Kotlin getter for properties
// e.g.:
// val prop: Mytype
@@ -1405,10 +1481,10 @@
writer.DecrementIdentLevel();
}
- static void GeneratePropertyOneLine(CodeWriter &writer,
- const std::string &name,
- const std::string &type,
- const std::function<void()> &body) {
+ static void GeneratePropertyOneLine(CodeWriter& writer,
+ const std::string& name,
+ const std::string& type,
+ const std::function<void()>& body) {
// Generates Kotlin getter for properties
// e.g.:
// val prop: Mytype = x
@@ -1417,9 +1493,9 @@
writer += "val {{_name}} : {{_type}} = \\";
body();
}
- static void GenerateGetterOneLine(CodeWriter &writer, const std::string &name,
- const std::string &type,
- const std::function<void()> &body) {
+ static void GenerateGetterOneLine(CodeWriter& writer, const std::string& name,
+ const std::string& type,
+ const std::function<void()>& body) {
// Generates Kotlin getter for properties
// e.g.:
// val prop: Mytype get() = x
@@ -1429,9 +1505,9 @@
body();
}
- static void GenerateGetter(CodeWriter &writer, const std::string &name,
- const std::string &type,
- const std::function<void()> &body) {
+ static void GenerateGetter(CodeWriter& writer, const std::string& name,
+ const std::string& type,
+ const std::function<void()>& body) {
// Generates Kotlin getter for properties
// e.g.:
// val prop: Mytype
@@ -1450,10 +1526,10 @@
writer.DecrementIdentLevel();
}
- static void GenerateFun(CodeWriter &writer, const std::string &name,
- const std::string ¶ms,
- const std::string &returnType,
- const std::function<void()> &body,
+ static void GenerateFun(CodeWriter& writer, const std::string& name,
+ const std::string& params,
+ const std::string& returnType,
+ const std::function<void()>& body,
bool gen_jvmstatic = false) {
// Generates Kotlin function
// e.g.:
@@ -1472,10 +1548,10 @@
writer += "}";
}
- static void GenerateFunOneLine(CodeWriter &writer, const std::string &name,
- const std::string ¶ms,
- const std::string &returnType,
- const std::function<void()> &body,
+ static void GenerateFunOneLine(CodeWriter& writer, const std::string& name,
+ const std::string& params,
+ const std::string& returnType,
+ const std::function<void()>& body,
bool gen_jvmstatic = false) {
// Generates Kotlin function
// e.g.:
@@ -1486,10 +1562,10 @@
body();
}
- static void GenerateOverrideFun(CodeWriter &writer, const std::string &name,
- const std::string ¶ms,
- const std::string &returnType,
- const std::function<void()> &body) {
+ static void GenerateOverrideFun(CodeWriter& writer, const std::string& name,
+ const std::string& params,
+ const std::string& returnType,
+ const std::function<void()>& body) {
// Generates Kotlin function
// e.g.:
// override fun path(j: Int): Vec3 = return path(Vec3(), j)
@@ -1497,11 +1573,11 @@
GenerateFun(writer, name, params, returnType, body);
}
- static void GenerateOverrideFunOneLine(CodeWriter &writer,
- const std::string &name,
- const std::string ¶ms,
- const std::string &returnType,
- const std::string &statement) {
+ static void GenerateOverrideFunOneLine(CodeWriter& writer,
+ const std::string& name,
+ const std::string& params,
+ const std::string& returnType,
+ const std::string& statement) {
// Generates Kotlin function
// e.g.:
// override fun path(j: Int): Vec3 = return path(Vec3(), j)
@@ -1513,13 +1589,13 @@
writer += statement;
}
- static std::string LookupFieldOneLine(const std::string &offset,
- const std::string &found,
- const std::string ¬_found) {
+ static std::string LookupFieldOneLine(const std::string& offset,
+ const std::string& found,
+ const std::string& not_found) {
return "lookupField(" + offset + ", " + not_found + " ) { " + found + " }";
}
- static std::string Indirect(const std::string &index, bool fixed) {
+ static std::string Indirect(const std::string& index, bool fixed) {
// We apply indirect() and struct is not fixed.
if (!fixed) return "indirect(" + index + ")";
return index;
@@ -1527,34 +1603,43 @@
static std::string NotFoundReturn(BaseType el) {
switch (el) {
- case BASE_TYPE_FLOAT: return "0.0f";
- case BASE_TYPE_DOUBLE: return "0.0";
- case BASE_TYPE_BOOL: return "false";
+ case BASE_TYPE_FLOAT:
+ return "0.0f";
+ case BASE_TYPE_DOUBLE:
+ return "0.0";
+ case BASE_TYPE_BOOL:
+ return "false";
case BASE_TYPE_LONG:
case BASE_TYPE_INT:
case BASE_TYPE_CHAR:
- case BASE_TYPE_SHORT: return "0";
+ case BASE_TYPE_SHORT:
+ return "0";
case BASE_TYPE_UINT:
case BASE_TYPE_UCHAR:
case BASE_TYPE_USHORT:
- case BASE_TYPE_UTYPE: return "0u";
- case BASE_TYPE_ULONG: return "0uL";
- default: return "null";
+ case BASE_TYPE_UTYPE:
+ return "0u";
+ case BASE_TYPE_ULONG:
+ return "0uL";
+ default:
+ return "null";
}
}
// Prepend @JvmStatic to methods in companion object.
- static void GenerateJvmStaticAnnotation(CodeWriter &code,
+ static void GenerateJvmStaticAnnotation(CodeWriter& code,
bool gen_jvmstatic) {
- if (gen_jvmstatic) { code += "@JvmStatic"; }
+ if (gen_jvmstatic) {
+ code += "@JvmStatic";
+ }
}
const IdlNamer namer_;
};
} // namespace kotlin
-static bool GenerateKotlinKMP(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateKotlinKMP(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
kotlin::KotlinKMPGenerator generator(parser, path, file_name);
return generator.generate();
}
@@ -1563,20 +1648,21 @@
class KotlinKMPCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateKotlinKMP(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateKotlinKMP(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -1584,16 +1670,16 @@
return Status::NOT_IMPLEMENTED;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_lobster.cpp b/src/idl_gen_lobster.cpp
index de4e152..33c1071 100644
--- a/src/idl_gen_lobster.cpp
+++ b/src/idl_gen_lobster.cpp
@@ -29,38 +29,38 @@
class LobsterGenerator : public BaseGenerator {
public:
- LobsterGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ LobsterGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name, "" /* not used */, ".",
"lobster") {
- static const char *const keywords[] = {
- "nil", "true", "false", "return", "struct", "class",
- "import", "int", "float", "string", "any", "def",
- "is", "from", "program", "private", "coroutine", "resource",
- "enum", "typeof", "var", "let", "pakfile", "switch",
- "case", "default", "namespace", "not", "and", "or",
- "bool",
+ static const char* const keywords[] = {
+ "nil", "true", "false", "return", "struct", "class",
+ "import", "int", "float", "string", "any", "def",
+ "is", "from", "program", "private", "coroutine", "resource",
+ "enum", "typeof", "var", "let", "pakfile", "switch",
+ "case", "default", "namespace", "not", "and", "or",
+ "bool",
};
keywords_.insert(std::begin(keywords), std::end(keywords));
}
- std::string EscapeKeyword(const std::string &name) const {
+ std::string EscapeKeyword(const std::string& name) const {
return keywords_.find(name) == keywords_.end() ? name : name + "_";
}
- std::string NormalizedName(const Definition &definition) const {
+ std::string NormalizedName(const Definition& definition) const {
return EscapeKeyword(definition.name);
}
- std::string NormalizedName(const EnumVal &ev) const {
+ std::string NormalizedName(const EnumVal& ev) const {
return EscapeKeyword(ev.name);
}
- std::string NamespacedName(const Definition &def) {
+ std::string NamespacedName(const Definition& def) {
return WrapInNameSpace(def.defined_namespace, NormalizedName(def));
}
- std::string GenTypeName(const Type &type) {
+ std::string GenTypeName(const Type& type) {
auto bits = NumToString(SizeOf(type.base_type) * 8);
if (IsInteger(type.base_type)) {
if (IsUnsigned(type.base_type))
@@ -74,7 +74,7 @@
return "none";
}
- std::string LobsterType(const Type &type) {
+ std::string LobsterType(const Type& type) {
if (IsFloat(type.base_type)) return "float";
if (IsBool(type.base_type)) return "bool";
if (IsScalar(type.base_type) && type.enum_def)
@@ -85,14 +85,14 @@
}
// Returns the method name for use with add/put calls.
- std::string GenMethod(const Type &type) {
+ std::string GenMethod(const Type& type) {
return IsScalar(type.base_type)
? ConvertCase(GenTypeBasic(type), Case::kUpperCamel)
: (IsStruct(type) ? "Struct" : "UOffsetTRelative");
}
// This uses Python names for now..
- std::string GenTypeBasic(const Type &type) {
+ std::string GenTypeBasic(const Type& type) {
// clang-format off
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
@@ -106,10 +106,10 @@
}
// Generate a struct field, conditioned on its child type(s).
- void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ void GenStructAccessor(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
GenComment(field.doc_comment, code_ptr, nullptr, " ");
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
auto offsets = NumToString(field.value.offset);
auto def = " def " + NormalizedName(field);
if (IsScalar(field.value.type.base_type)) {
@@ -195,7 +195,7 @@
case BASE_TYPE_UNION: {
for (auto it = field.value.type.enum_def->Vals().begin();
it != field.value.type.enum_def->Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
if (ev.IsNonZero()) {
code += def + "_as_" + ev.name + "():\n return " +
NamespacedName(*ev.union_type.struct_def) +
@@ -205,7 +205,8 @@
}
break;
}
- default: FLATBUFFERS_ASSERT(0);
+ default:
+ FLATBUFFERS_ASSERT(0);
}
if (IsVector(field.value.type)) {
code += def +
@@ -216,8 +217,8 @@
}
// Generate table constructors, conditioned on its members' types.
- void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GenTableBuilders(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "struct " + NormalizedName(struct_def) +
"Builder:\n b_:flatbuffers.builder\n";
code += " def start():\n b_.StartObject(" +
@@ -225,7 +226,7 @@
")\n return this\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
auto offset = it - struct_def.fields.vec.begin();
code += " def add_" + NormalizedName(field) + "(" +
@@ -239,7 +240,7 @@
code += " def end():\n return b_.EndObject()\n\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
if (IsVector(field.value.type)) {
code += "def " + NormalizedName(struct_def) + "Start" +
@@ -266,23 +267,23 @@
}
}
- void GenStructPreDecl(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStructPreDecl(const StructDef& struct_def, std::string* code_ptr) {
if (struct_def.generated) return;
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
CheckNameSpace(struct_def, &code);
code += "class " + NormalizedName(struct_def) + "\n\n";
}
// Generate struct or table methods.
- void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStruct(const StructDef& struct_def, std::string* code_ptr) {
if (struct_def.generated) return;
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
CheckNameSpace(struct_def, &code);
GenComment(struct_def.doc_comment, code_ptr, nullptr, "");
code += "class " + NormalizedName(struct_def) + " : flatbuffers.handle\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
GenStructAccessor(struct_def, field, code_ptr);
}
@@ -304,14 +305,14 @@
}
// Generate enum declarations.
- void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
+ void GenEnum(const EnumDef& enum_def, std::string* code_ptr) {
if (enum_def.generated) return;
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
CheckNameSpace(enum_def, &code);
GenComment(enum_def.doc_comment, code_ptr, nullptr, "");
code += "enum " + NormalizedName(enum_def) + ":\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
GenComment(ev.doc_comment, code_ptr, nullptr, " ");
code += " " + enum_def.name + "_" + NormalizedName(ev) + " = " +
enum_def.ToString(ev) + "\n";
@@ -321,11 +322,11 @@
// Recursively generate arguments for a constructor, to deal with nested
// structs.
- void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix,
- std::string *code_ptr) {
+ void StructBuilderArgs(const StructDef& struct_def, const char* nameprefix,
+ std::string* code_ptr) {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (IsStruct(field.value.type)) {
// Generate arguments for a struct inside a struct. To ensure names
// don't clash, and to make it obvious these arguments are constructing
@@ -334,7 +335,7 @@
(nameprefix + (NormalizedName(field) + "_")).c_str(),
code_ptr);
} else {
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
code += ", " + (nameprefix + NormalizedName(field)) + ":" +
LobsterType(field.value.type);
}
@@ -343,14 +344,14 @@
// Recursively generate struct construction statements and instert manual
// padding.
- void StructBuilderBody(const StructDef &struct_def, const char *nameprefix,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void StructBuilderBody(const StructDef& struct_def, const char* nameprefix,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += " b_.Prep(" + NumToString(struct_def.minalign) + ", " +
NumToString(struct_def.bytesize) + ")\n";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.padding)
code += " b_.Pad(" + NumToString(field.padding) + ")\n";
if (IsStruct(field.value.type)) {
@@ -365,8 +366,8 @@
}
// Create a struct with a builder and the struct's arguments.
- void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GenStructBuilder(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code +=
"def Create" + NormalizedName(struct_def) + "(b_:flatbuffers.builder";
StructBuilderArgs(struct_def, "", code_ptr);
@@ -375,11 +376,11 @@
code += " return b_.Offset()\n\n";
}
- void CheckNameSpace(const Definition &def, std::string *code_ptr) {
+ void CheckNameSpace(const Definition& def, std::string* code_ptr) {
auto ns = GetNameSpace(def);
if (ns == current_namespace_) return;
current_namespace_ = ns;
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
code += "namespace " + ns + "\n\n";
}
@@ -389,17 +390,17 @@
"\nimport flatbuffers\n\n";
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
- auto &enum_def = **it;
+ auto& enum_def = **it;
GenEnum(enum_def, &code);
}
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
- auto &struct_def = **it;
+ auto& struct_def = **it;
GenStructPreDecl(struct_def, &code);
}
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
- auto &struct_def = **it;
+ auto& struct_def = **it;
GenStruct(struct_def, &code);
}
return SaveFile(GeneratedFileName(path_, file_name_, parser_.opts).c_str(),
@@ -413,8 +414,8 @@
} // namespace lobster
-static bool GenerateLobster(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateLobster(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
lobster::LobsterGenerator generator(parser, path, file_name);
return generator.generate();
}
@@ -423,20 +424,21 @@
class LobsterCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateLobster(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateLobster(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -444,16 +446,16 @@
return Status::NOT_IMPLEMENTED;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_php.cpp b/src/idl_gen_php.cpp
index 16ba338..48de73c 100644
--- a/src/idl_gen_php.cpp
+++ b/src/idl_gen_php.cpp
@@ -31,8 +31,8 @@
const std::string Indent = " ";
class PhpGenerator : public BaseGenerator {
public:
- PhpGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ PhpGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name, "\\", "\\", "php") {}
bool generate() {
if (!GenerateEnums()) return false;
@@ -44,7 +44,7 @@
bool GenerateEnums() {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
- auto &enum_def = **it;
+ auto& enum_def = **it;
std::string enumcode;
GenEnum(enum_def, &enumcode);
if (!SaveType(enum_def, enumcode, false)) return false;
@@ -55,7 +55,7 @@
bool GenerateStructs() {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
- auto &struct_def = **it;
+ auto& struct_def = **it;
std::string declcode;
GenStruct(struct_def, &declcode);
if (!SaveType(struct_def, declcode, true)) return false;
@@ -64,9 +64,9 @@
}
// Begin by declaring namespace and imports.
- void BeginFile(const std::string &name_space_name, const bool needs_imports,
- std::string *code_ptr) {
- auto &code = *code_ptr;
+ void BeginFile(const std::string& name_space_name, const bool needs_imports,
+ std::string* code_ptr) {
+ auto& code = *code_ptr;
code += "<?php\n";
code = code + "// " + FlatBuffersGeneratedWarning() + "\n\n";
@@ -84,7 +84,7 @@
}
// Save out the generated code for a Php Table type.
- bool SaveType(const Definition &def, const std::string &classcode,
+ bool SaveType(const Definition& def, const std::string& classcode,
bool needs_imports) {
if (!classcode.length()) return true;
@@ -99,8 +99,8 @@
}
// Begin a class declaration.
- static void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void BeginClass(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
if (struct_def.fixed) {
code += "class " + struct_def.name + " extends Struct\n";
} else {
@@ -109,21 +109,21 @@
code += "{\n";
}
- static void EndClass(std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void EndClass(std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "}\n";
}
// Begin enum code with a class declaration.
- static void BeginEnum(const std::string &class_name, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void BeginEnum(const std::string& class_name, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "class " + class_name + "\n{\n";
}
// A single enum member.
- static void EnumMember(const EnumDef &enum_def, const EnumVal &ev,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void EnumMember(const EnumDef& enum_def, const EnumVal& ev,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "const ";
code += ev.name;
code += " = ";
@@ -131,15 +131,15 @@
}
// End enum code.
- static void EndEnum(std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void EndEnum(std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "}\n";
}
// Initialize a new struct or table from existing data.
- static void NewRootTypeFromBuffer(const StructDef &struct_def,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void NewRootTypeFromBuffer(const StructDef& struct_def,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @param ByteBuffer $bb\n";
@@ -158,9 +158,9 @@
}
// Initialize an existing object with other data, to avoid an allocation.
- static void InitializeExisting(const StructDef &struct_def,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void InitializeExisting(const StructDef& struct_def,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @param int $_i offset\n";
@@ -176,8 +176,8 @@
}
// Get the length of a vector.
- static void GetVectorLen(const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void GetVectorLen(const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @return int\n";
@@ -193,8 +193,8 @@
}
// Get a [ubyte] vector as a byte array.
- static void GetUByte(const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void GetUByte(const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @return string\n";
@@ -208,9 +208,9 @@
}
// Get the value of a struct's scalar.
- static void GetScalarFieldOfStruct(const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void GetScalarFieldOfStruct(const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
std::string getter = GenGetter(field.value.type);
code += Indent + "/**\n";
@@ -232,8 +232,8 @@
}
// Get the value of a table's scalar.
- void GetScalarFieldOfTable(const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetScalarFieldOfTable(const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
@@ -254,8 +254,8 @@
// Get a struct by initializing an existing struct.
// Specific to Struct.
- void GetStructFieldOfStruct(const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetStructFieldOfStruct(const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
@@ -273,8 +273,8 @@
// Get a struct by initializing an existing struct.
// Specific to Table.
- void GetStructFieldOfTable(const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetStructFieldOfTable(const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "public function get";
code += ConvertCase(field.name, Case::kUpperCamel);
@@ -297,8 +297,8 @@
}
// Get the value of a string.
- void GetStringField(const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetStringField(const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "public function get";
code += ConvertCase(field.name, Case::kUpperCamel);
code += "()\n";
@@ -312,8 +312,8 @@
}
// Get the value of a union from an object.
- void GetUnionField(const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetUnionField(const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @return" + GenTypeBasic(field.value.type) + "\n";
@@ -329,9 +329,9 @@
}
// Get the value of a vector's struct member.
- void GetMemberOfVectorOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetMemberOfVectorOfStruct(const StructDef& struct_def,
+ const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
code += Indent + "/**\n";
@@ -382,7 +382,8 @@
code += Indent + Indent + "return $o != 0 ? $this->";
code += GenGetter(field.value.type) + "($obj, $o); null;\n";
break;
- default: break;
+ default:
+ break;
}
code += Indent + "}\n\n";
@@ -390,9 +391,9 @@
// Get the value of a vector's non-struct member. Uses a named return
// argument to conveniently set the zero value for the result.
- void GetMemberOfVectorOfNonStruct(const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetMemberOfVectorOfNonStruct(const FieldDef& field,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
code += Indent + "/**\n";
@@ -423,8 +424,8 @@
// Get the value of a vector's union member. Uses a named return
// argument to conveniently set the zero value for the result.
- void GetMemberOfVectorOfUnion(const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetMemberOfVectorOfUnion(const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
code += Indent + "/**\n";
@@ -445,11 +446,11 @@
// Recursively generate arguments for a constructor, to deal with nested
// structs.
- static void StructBuilderArgs(const StructDef &struct_def,
- const char *nameprefix, std::string *code_ptr) {
+ static void StructBuilderArgs(const StructDef& struct_def,
+ const char* nameprefix, std::string* code_ptr) {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (IsStruct(field.value.type)) {
// Generate arguments for a struct inside a struct. To ensure names
// don't clash, and to make it obvious
@@ -458,7 +459,7 @@
StructBuilderArgs(*field.value.type.struct_def,
(nameprefix + (field.name + "_")).c_str(), code_ptr);
} else {
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
code += std::string(", $") + nameprefix;
code += ConvertCase(field.name, Case::kLowerCamel);
}
@@ -467,15 +468,15 @@
// Recursively generate struct construction statements and instert manual
// padding.
- static void StructBuilderBody(const StructDef &struct_def,
- const char *nameprefix, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void StructBuilderBody(const StructDef& struct_def,
+ const char* nameprefix, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + Indent + "$builder->prep(";
code += NumToString(struct_def.minalign) + ", ";
code += NumToString(struct_def.bytesize) + ");\n";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.padding) {
code += Indent + Indent + "$builder->pad(";
code += NumToString(field.padding) + ");\n";
@@ -492,9 +493,9 @@
}
// Get the value of a table's starting offset.
- static void GetStartOfTable(const StructDef &struct_def,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void GetStartOfTable(const StructDef& struct_def,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @param FlatBufferBuilder $builder\n";
@@ -517,10 +518,12 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
- if (it != struct_def.fields.vec.begin()) { code += ", "; }
+ if (it != struct_def.fields.vec.begin()) {
+ code += ", ";
+ }
code += "$" + field.name;
}
code += ")\n";
@@ -530,7 +533,7 @@
code += ");\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
code += Indent + Indent + "self::add";
@@ -542,7 +545,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (!field.deprecated && field.IsRequired()) {
code += Indent + Indent + "$builder->required($o, ";
code += NumToString(field.value.offset);
@@ -554,9 +557,9 @@
}
// Set the value of a table's field.
- static void BuildFieldOfTable(const FieldDef &field, const size_t offset,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void BuildFieldOfTable(const FieldDef& field, const size_t offset,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @param FlatBufferBuilder $builder\n";
@@ -586,8 +589,8 @@
}
// Set the value of one of the members of a table's vector.
- static void BuildVectorOfTable(const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void BuildVectorOfTable(const FieldDef& field, std::string* code_ptr) {
+ std::string& code = *code_ptr;
auto vector_type = field.value.type.VectorType();
auto alignment = InlineAlignment(vector_type);
@@ -638,8 +641,8 @@
}
// Get the offset of the end of a table.
- void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
+ void GetEndOffsetOnTable(const StructDef& struct_def, std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += Indent + "/**\n";
code += Indent + " * @param FlatBufferBuilder $builder\n";
@@ -652,7 +655,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (!field.deprecated && field.IsRequired()) {
code += Indent + Indent + "$builder->required($o, ";
code += NumToString(field.value.offset);
@@ -678,8 +681,8 @@
}
// Generate a struct field, conditioned on its child type(s).
- void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ void GenStructAccessor(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) {
GenComment(field.doc_comment, code_ptr, nullptr, Indent.c_str());
if (IsScalar(field.value.type.base_type)) {
@@ -697,7 +700,9 @@
GetStructFieldOfTable(field, code_ptr);
}
break;
- case BASE_TYPE_STRING: GetStringField(field, code_ptr); break;
+ case BASE_TYPE_STRING:
+ GetStringField(field, code_ptr);
+ break;
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
if (vectortype.base_type == BASE_TYPE_UNION) {
@@ -709,8 +714,11 @@
}
break;
}
- case BASE_TYPE_UNION: GetUnionField(field, code_ptr); break;
- default: FLATBUFFERS_ASSERT(0);
+ case BASE_TYPE_UNION:
+ GetUnionField(field, code_ptr);
+ break;
+ default:
+ FLATBUFFERS_ASSERT(0);
}
}
if (IsVector(field.value.type)) {
@@ -722,17 +730,17 @@
}
// Generate table constructors, conditioned on its members' types.
- void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
+ void GenTableBuilders(const StructDef& struct_def, std::string* code_ptr) {
GetStartOfTable(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
auto offset = it - struct_def.fields.vec.begin();
if (field.value.type.base_type == BASE_TYPE_UNION) {
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
code += Indent + "public static function add";
code += ConvertCase(field.name, Case::kUpperCamel);
code += "(FlatBufferBuilder $builder, $offset)\n";
@@ -743,14 +751,16 @@
} else {
BuildFieldOfTable(field, offset, code_ptr);
}
- if (IsVector(field.value.type)) { BuildVectorOfTable(field, code_ptr); }
+ if (IsVector(field.value.type)) {
+ BuildVectorOfTable(field, code_ptr);
+ }
}
GetEndOffsetOnTable(struct_def, code_ptr);
}
// Generate struct or table methods.
- void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStruct(const StructDef& struct_def, std::string* code_ptr) {
if (struct_def.generated) return;
GenComment(struct_def.doc_comment, code_ptr, nullptr);
@@ -762,7 +772,7 @@
NewRootTypeFromBuffer(struct_def, code_ptr);
}
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
if (!struct_def.fixed) {
if (parser_.file_identifier_.length()) {
// Return the identifier
@@ -799,7 +809,7 @@
InitializeExisting(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
GenStructAccessor(struct_def, field, code_ptr);
@@ -816,22 +826,22 @@
}
// Generate enum declarations.
- static void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
+ static void GenEnum(const EnumDef& enum_def, std::string* code_ptr) {
if (enum_def.generated) return;
GenComment(enum_def.doc_comment, code_ptr, nullptr);
BeginEnum(enum_def.name, code_ptr);
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
GenComment(ev.doc_comment, code_ptr, nullptr, Indent.c_str());
EnumMember(enum_def, ev, code_ptr);
}
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
code += "\n";
code += Indent + "private static $names = array(\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
code += Indent + Indent + enum_def.name + "::" + ev.name + "=>" + "\"" +
ev.name + "\",\n";
}
@@ -848,24 +858,29 @@
}
// Returns the function name that is able to read a value of the given type.
- static std::string GenGetter(const Type &type) {
+ static std::string GenGetter(const Type& type) {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "__string";
- case BASE_TYPE_STRUCT: return "__struct";
- case BASE_TYPE_UNION: return "__union";
- case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
- default: return "Get";
+ case BASE_TYPE_STRING:
+ return "__string";
+ case BASE_TYPE_STRUCT:
+ return "__struct";
+ case BASE_TYPE_UNION:
+ return "__union";
+ case BASE_TYPE_VECTOR:
+ return GenGetter(type.VectorType());
+ default:
+ return "Get";
}
}
// Returns the method name for use with add/put calls.
- static std::string GenMethod(const FieldDef &field) {
+ static std::string GenMethod(const FieldDef& field) {
return IsScalar(field.value.type.base_type)
? ConvertCase(GenTypeBasic(field.value.type), Case::kUpperCamel)
: (IsStruct(field.value.type) ? "Struct" : "Offset");
}
- static std::string GenTypeBasic(const Type &type) {
+ static std::string GenTypeBasic(const Type& type) {
// clang-format off
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
@@ -878,7 +893,7 @@
return ctypename[type.base_type];
}
- std::string GenDefaultValue(const Value &value) {
+ std::string GenDefaultValue(const Value& value) {
if (value.type.enum_def) {
if (auto val = value.type.enum_def->FindByValue(value.constant)) {
return WrapInNameSpace(*value.type.enum_def) + "::" + val->name;
@@ -886,9 +901,11 @@
}
switch (value.type.base_type) {
- case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
+ case BASE_TYPE_BOOL:
+ return value.constant == "0" ? "false" : "true";
- case BASE_TYPE_STRING: return "null";
+ case BASE_TYPE_STRING:
+ return "null";
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG:
@@ -898,29 +915,34 @@
}
return "0";
- default: return value.constant;
+ default:
+ return value.constant;
}
}
- static std::string GenTypePointer(const Type &type) {
+ static std::string GenTypePointer(const Type& type) {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "string";
- case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
- case BASE_TYPE_STRUCT: return type.struct_def->name;
+ case BASE_TYPE_STRING:
+ return "string";
+ case BASE_TYPE_VECTOR:
+ return GenTypeGet(type.VectorType());
+ case BASE_TYPE_STRUCT:
+ return type.struct_def->name;
case BASE_TYPE_UNION:
// fall through
- default: return "Table";
+ default:
+ return "Table";
}
}
- static std::string GenTypeGet(const Type &type) {
+ static std::string GenTypeGet(const Type& type) {
return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
}
// Create a struct with a builder and the struct's arguments.
- static void GenStructBuilder(const StructDef &struct_def,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
+ static void GenStructBuilder(const StructDef& struct_def,
+ std::string* code_ptr) {
+ std::string& code = *code_ptr;
code += "\n";
code += Indent + "/**\n";
code += Indent + " * @return int offset\n";
@@ -939,8 +961,8 @@
};
} // namespace php
-static bool GeneratePhp(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GeneratePhp(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
php::PhpGenerator generator(parser, path, file_name);
return generator.generate();
}
@@ -949,20 +971,21 @@
class PhpCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GeneratePhp(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GeneratePhp(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -970,16 +993,16 @@
return Status::NOT_IMPLEMENTED;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_python.cpp b/src/idl_gen_python.cpp
index c9c289b..4c48b21 100644
--- a/src/idl_gen_python.cpp
+++ b/src/idl_gen_python.cpp
@@ -45,16 +45,16 @@
typedef std::set<ImportMapEntry> ImportMap;
// Hardcode spaces per indentation.
-static const CommentConfig def_comment = { nullptr, "#", nullptr };
+static const CommentConfig def_comment = {nullptr, "#", nullptr};
static const std::string Indent = " ";
class PythonStubGenerator {
public:
- PythonStubGenerator(const Parser &parser, const std::string &path,
- const Version &version)
- : parser_{ parser },
- namer_{ WithFlagOptions(kStubConfig, parser.opts, path),
- Keywords(version) },
+ PythonStubGenerator(const Parser& parser, const std::string& path,
+ const Version& version)
+ : parser_{parser},
+ namer_{WithFlagOptions(kStubConfig, parser.opts, path),
+ Keywords(version)},
version_(version) {}
bool Generate() {
@@ -63,11 +63,11 @@
std::stringstream stub;
DeclareUOffset(stub, &imports);
- for (const EnumDef *def : parser_.enums_.vec) {
+ for (const EnumDef* def : parser_.enums_.vec) {
if (def->generated) continue;
GenerateEnumStub(stub, def, &imports);
}
- for (const StructDef *def : parser_.structs_.vec) {
+ for (const StructDef* def : parser_.structs_.vec) {
if (def->generated) continue;
GenerateStructStub(stub, def, &imports);
}
@@ -80,7 +80,7 @@
return SaveFile(filename, imports, stub);
}
- for (const EnumDef *def : parser_.enums_.vec) {
+ for (const EnumDef* def : parser_.enums_.vec) {
if (def->generated) continue;
Imports imports;
@@ -94,7 +94,7 @@
if (!SaveFile(filename, imports, stub)) return false;
}
- for (const StructDef *def : parser_.structs_.vec) {
+ for (const StructDef* def : parser_.structs_.vec) {
if (def->generated) continue;
Imports imports;
@@ -112,8 +112,8 @@
}
private:
- bool SaveFile(const std::string &filename, const Imports &imports,
- const std::stringstream &content) {
+ bool SaveFile(const std::string& filename, const Imports& imports,
+ const std::stringstream& content) {
std::stringstream ss;
GenerateImports(ss, imports);
ss << '\n';
@@ -123,7 +123,7 @@
return flatbuffers::SaveFile(filename.c_str(), ss.str(), false);
}
- static void DeclareUOffset(std::stringstream &stub, Imports *imports) {
+ static void DeclareUOffset(std::stringstream& stub, Imports* imports) {
imports->Import("flatbuffers");
imports->Import("typing");
stub << "uoffset: typing.TypeAlias = "
@@ -131,7 +131,7 @@
<< '\n';
}
- std::string ModuleForFile(const std::string &file) const {
+ std::string ModuleForFile(const std::string& file) const {
if (parser_.file_being_parsed_ == file) return ".";
std::string module = parser_.opts.include_prefix + StripExtension(file) +
@@ -140,16 +140,17 @@
return module;
}
- template<typename T> std::string ModuleFor(const T *def) const {
+ template <typename T>
+ std::string ModuleFor(const T* def) const {
if (parser_.opts.one_file) return ModuleForFile(def->file);
return namer_.NamespacedType(*def);
}
- const StructDef *GetNestedStruct(const FieldDef *field) const {
- const Value *nested = field->attributes.Lookup("nested_flatbuffer");
+ const StructDef* GetNestedStruct(const FieldDef* field) const {
+ const Value* nested = field->attributes.Lookup("nested_flatbuffer");
if (nested == nullptr) return nullptr;
- StructDef *nested_def = parser_.LookupStruct(nested->constant);
+ StructDef* nested_def = parser_.LookupStruct(nested->constant);
if (nested_def != nullptr) return nested_def;
return parser_.LookupStruct(namer_.NamespacedType(
@@ -164,13 +165,13 @@
return "None";
}
- template<typename F>
- std::string UnionType(const EnumDef &enum_def, Imports *imports,
+ template <typename F>
+ std::string UnionType(const EnumDef& enum_def, Imports* imports,
F type) const {
imports->Import("typing");
std::string result = "";
- for (const EnumVal *val : enum_def.Vals()) {
+ for (const EnumVal* val : enum_def.Vals()) {
if (!result.empty()) result += ", ";
switch (val->union_type.base_type) {
@@ -180,65 +181,74 @@
result += import.name;
break;
}
- case BASE_TYPE_STRING: result += "str"; break;
- case BASE_TYPE_NONE: result += "None"; break;
- default: break;
+ case BASE_TYPE_STRING:
+ result += "str";
+ break;
+ case BASE_TYPE_NONE:
+ result += "None";
+ break;
+ default:
+ break;
}
}
return "typing.Union[" + result + "]";
}
- std::string UnionObjectType(const EnumDef &enum_def, Imports *imports) const {
- return UnionType(enum_def, imports, [this](const StructDef &struct_def) {
+ std::string UnionObjectType(const EnumDef& enum_def, Imports* imports) const {
+ return UnionType(enum_def, imports, [this](const StructDef& struct_def) {
return namer_.ObjectType(struct_def);
});
}
- std::string UnionType(const EnumDef &enum_def, Imports *imports) const {
- return UnionType(enum_def, imports, [this](const StructDef &struct_def) {
+ std::string UnionType(const EnumDef& enum_def, Imports* imports) const {
+ return UnionType(enum_def, imports, [this](const StructDef& struct_def) {
return namer_.Type(struct_def);
});
}
- std::string EnumType(const EnumDef &enum_def, Imports *imports) const {
+ std::string EnumType(const EnumDef& enum_def, Imports* imports) const {
imports->Import("typing");
- const Import &import =
+ const Import& import =
imports->Import(ModuleFor(&enum_def), namer_.Type(enum_def));
std::string result = "";
- for (const EnumVal *val : enum_def.Vals()) {
+ for (const EnumVal* val : enum_def.Vals()) {
if (!result.empty()) result += ", ";
result += import.name + "." + namer_.Variant(*val);
}
return "typing.Literal[" + result + "]";
}
- std::string TypeOf(const Type &type, Imports *imports) const {
+ std::string TypeOf(const Type& type, Imports* imports) const {
if (type.enum_def != nullptr) return EnumType(*type.enum_def, imports);
if (IsScalar(type.base_type)) return ScalarType(type.base_type);
switch (type.base_type) {
case BASE_TYPE_STRUCT: {
- const Import &import = imports->Import(ModuleFor(type.struct_def),
+ const Import& import = imports->Import(ModuleFor(type.struct_def),
namer_.Type(*type.struct_def));
return import.name;
}
- case BASE_TYPE_STRING: return "str";
+ case BASE_TYPE_STRING:
+ return "str";
case BASE_TYPE_ARRAY:
case BASE_TYPE_VECTOR: {
imports->Import("typing");
return "typing.List[" + TypeOf(type.VectorType(), imports) + "]";
}
- case BASE_TYPE_UNION: return UnionType(*type.enum_def, imports);
- default: FLATBUFFERS_ASSERT(0); return "";
+ case BASE_TYPE_UNION:
+ return UnionType(*type.enum_def, imports);
+ default:
+ FLATBUFFERS_ASSERT(0);
+ return "";
}
}
- std::string GenerateObjectFieldStub(const FieldDef *field,
- Imports *imports) const {
+ std::string GenerateObjectFieldStub(const FieldDef* field,
+ Imports* imports) const {
std::string field_name = namer_.Field(*field);
- const Type &field_type = field->value.type;
+ const Type& field_type = field->value.type;
if (IsScalar(field_type.base_type)) {
std::string result = field_name + ": " + TypeOf(field_type, imports);
if (field->IsOptional()) result += " | None";
@@ -252,7 +262,8 @@
namer_.ObjectType(*field_type.struct_def));
return field_name + ": " + import.name + " | None";
}
- case BASE_TYPE_STRING: return field_name + ": str | None";
+ case BASE_TYPE_STRING:
+ return field_name + ": str | None";
case BASE_TYPE_ARRAY:
case BASE_TYPE_VECTOR: {
imports->Import("typing");
@@ -271,26 +282,29 @@
case BASE_TYPE_UNION:
return field_name + ": " +
UnionObjectType(*field->value.type.enum_def, imports);
- default: return field_name;
+ default:
+ return field_name;
}
}
- void GenerateObjectInitializerStub(std::stringstream &stub,
- const StructDef *struct_def,
- Imports *imports) const {
+ void GenerateObjectInitializerStub(std::stringstream& stub,
+ const StructDef* struct_def,
+ Imports* imports) const {
stub << " def __init__(\n";
stub << " self,\n";
- for (const FieldDef *field : struct_def->fields.vec) {
+ for (const FieldDef* field : struct_def->fields.vec) {
if (field->deprecated) continue;
std::string field_name = namer_.Field(*field);
std::string field_type;
- const Type &type = field->value.type;
+ const Type& type = field->value.type;
if (IsScalar(type.base_type)) {
field_type = TypeOf(type, imports);
- if (field->IsOptional()) { field_type += " | None"; }
+ if (field->IsOptional()) {
+ field_type += " | None";
+ }
} else {
switch (type.base_type) {
case BASE_TYPE_STRUCT: {
@@ -300,7 +314,9 @@
field_type = "'" + import_.name + "' | None";
break;
}
- case BASE_TYPE_STRING: field_type = "str | None"; break;
+ case BASE_TYPE_STRING:
+ field_type = "str | None";
+ break;
case BASE_TYPE_ARRAY:
case BASE_TYPE_VECTOR: {
imports->Import("typing");
@@ -320,7 +336,9 @@
case BASE_TYPE_UNION:
field_type = UnionObjectType(*type.enum_def, imports);
break;
- default: field_type = "typing.Any"; break;
+ default:
+ field_type = "typing.Any";
+ break;
}
}
stub << " " << field_name << ": " << field_type << " = ...,\n";
@@ -328,15 +346,15 @@
stub << " ) -> None: ...\n";
}
- void GenerateObjectStub(std::stringstream &stub, const StructDef *struct_def,
- Imports *imports) const {
+ void GenerateObjectStub(std::stringstream& stub, const StructDef* struct_def,
+ Imports* imports) const {
std::string name = namer_.ObjectType(*struct_def);
imports->Export(ModuleFor(struct_def), namer_.Type(*struct_def));
stub << "class " << name;
if (version_.major != 3) stub << "(object)";
stub << ":\n";
- for (const FieldDef *field : struct_def->fields.vec) {
+ for (const FieldDef* field : struct_def->fields.vec) {
if (field->deprecated) continue;
stub << " " << GenerateObjectFieldStub(field, imports) << "\n";
}
@@ -351,7 +369,7 @@
stub << " def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> " << name
<< ": ...\n";
- const Import &import =
+ const Import& import =
imports->Import(ModuleFor(struct_def), namer_.Type(*struct_def));
stub << " @classmethod\n";
@@ -368,8 +386,8 @@
}
}
- void GenerateStructStub(std::stringstream &stub, const StructDef *struct_def,
- Imports *imports) const {
+ void GenerateStructStub(std::stringstream& stub, const StructDef* struct_def,
+ Imports* imports) const {
std::string type = namer_.Type(*struct_def);
imports->Export(ModuleFor(struct_def), namer_.Type(*struct_def));
@@ -399,12 +417,12 @@
stub << " def Init(self, buf: bytes, pos: int) -> None: ...\n";
- for (const FieldDef *field : struct_def->fields.vec) {
+ for (const FieldDef* field : struct_def->fields.vec) {
if (field->deprecated) continue;
std::string name = namer_.Method(*field);
- const Type &field_type = field->value.type;
+ const Type& field_type = field->value.type;
if (IsScalar(field_type.base_type)) {
stub << " def " << name << "(self) -> " << TypeOf(field_type, imports);
if (field->IsOptional()) stub << " | None";
@@ -412,7 +430,7 @@
} else {
switch (field_type.base_type) {
case BASE_TYPE_STRUCT: {
- const Import &import =
+ const Import& import =
imports->Import(ModuleFor(field_type.struct_def),
namer_.Type(*field_type.struct_def));
if (struct_def->fixed) {
@@ -431,7 +449,7 @@
case BASE_TYPE_VECTOR: {
switch (field_type.element) {
case BASE_TYPE_STRUCT: {
- const Import &import =
+ const Import& import =
imports->Import(ModuleFor(field_type.struct_def),
namer_.Type(*field_type.struct_def));
stub << " def " << name << "(self, i: int) -> " << import.name
@@ -450,9 +468,9 @@
<< "AsNumpy(self) -> np.ndarray: ...\n";
}
- const StructDef *nested_def = GetNestedStruct(field);
+ const StructDef* nested_def = GetNestedStruct(field);
if (nested_def != nullptr) {
- const Import &import = imports->Import(
+ const Import& import = imports->Import(
ModuleFor(nested_def), namer_.Type(*nested_def));
stub << " def " << name + "NestedRoot(self) -> "
@@ -469,7 +487,8 @@
stub << " def " << name << "(self) -> table.Table | None: ...\n";
break;
}
- default: break;
+ default:
+ break;
}
}
}
@@ -485,10 +504,10 @@
}
}
- void StructBuilderArgs(const StructDef &struct_def, const std::string prefix,
- Imports *imports,
- std::vector<std::string> *args) const {
- for (const FieldDef *field : struct_def.fields.vec) {
+ void StructBuilderArgs(const StructDef& struct_def, const std::string prefix,
+ Imports* imports,
+ std::vector<std::string>* args) const {
+ for (const FieldDef* field : struct_def.fields.vec) {
const Type type = IsArray(field->value.type)
? field->value.type.VectorType()
: field->value.type;
@@ -502,9 +521,9 @@
}
}
- void GenerateStructBuilderStub(std::stringstream &stub,
- const StructDef *struct_def,
- Imports *imports) const {
+ void GenerateStructBuilderStub(std::stringstream& stub,
+ const StructDef* struct_def,
+ Imports* imports) const {
imports->Import("flatbuffers");
std::vector<std::string> args;
@@ -513,13 +532,15 @@
stub << '\n';
stub << "def Create" + namer_.Type(*struct_def)
<< "(builder: flatbuffers.Builder";
- for (const std::string &arg : args) { stub << ", " << arg; }
+ for (const std::string& arg : args) {
+ stub << ", " << arg;
+ }
stub << ") -> uoffset: ...\n";
}
- void GenerateTableBuilderStub(std::stringstream &stub,
- const StructDef *struct_def,
- Imports *imports) const {
+ void GenerateTableBuilderStub(std::stringstream& stub,
+ const StructDef* struct_def,
+ Imports* imports) const {
std::string type = namer_.Type(*struct_def);
/**************************** def TableStart ****************************/
@@ -531,7 +552,7 @@
}
/************************** def TableAddField ***************************/
- for (const FieldDef *field : struct_def->fields.vec) {
+ for (const FieldDef* field : struct_def->fields.vec) {
if (field->deprecated) continue;
stub << "def ";
@@ -584,8 +605,8 @@
}
}
- void GenerateEnumStub(std::stringstream &stub, const EnumDef *enum_def,
- Imports *imports) const {
+ void GenerateEnumStub(std::stringstream& stub, const EnumDef* enum_def,
+ Imports* imports) const {
stub << "class " << namer_.Type(*enum_def);
imports->Export(ModuleFor(enum_def), namer_.Type(*enum_def));
@@ -599,7 +620,7 @@
}
stub << ":\n";
- for (const EnumVal *val : enum_def->Vals()) {
+ for (const EnumVal* val : enum_def->Vals()) {
stub << " " << namer_.Variant(*val) << " = cast("
<< ScalarType(enum_def->underlying_type.base_type) << ", ...)\n";
}
@@ -613,16 +634,18 @@
}
}
- void GenerateImports(std::stringstream &ss, const Imports &imports) {
+ void GenerateImports(std::stringstream& ss, const Imports& imports) {
ss << "from __future__ import annotations\n";
ss << '\n';
ss << "import flatbuffers\n";
- if (parser_.opts.python_gen_numpy) { ss << "import numpy as np\n"; }
+ if (parser_.opts.python_gen_numpy) {
+ ss << "import numpy as np\n";
+ }
ss << '\n';
std::set<std::string> modules;
std::map<std::string, std::set<std::string>> names_by_module;
- for (const Import &import : imports.imports) {
+ for (const Import& import : imports.imports) {
if (import.IsLocal()) continue; // skip all local imports
if (import.module == "flatbuffers" && import.name == "")
continue; // skip double include hardcoded flatbuffers
@@ -634,7 +657,7 @@
}
// Remove imports from exports
- for (const Import &import : imports.exports) {
+ for (const Import& import : imports.exports) {
if (import.name == "") {
modules.erase(import.module);
} else {
@@ -645,14 +668,14 @@
}
}
- for (const std::string &module : modules) {
+ for (const std::string& module : modules) {
ss << "import " << module << '\n';
}
- for (const auto &import : names_by_module) {
+ for (const auto& import : names_by_module) {
if (!import.second.empty()) {
ss << "from " << import.first << " import ";
size_t i = 0;
- for (const std::string &name : import.second) {
+ for (const std::string& name : import.second) {
if (i > 0) ss << ", ";
ss << name;
++i;
@@ -662,7 +685,7 @@
}
}
- const Parser &parser_;
+ const Parser& parser_;
const IdlNamer namer_;
const Version version_;
};
@@ -670,8 +693,8 @@
class PythonGenerator : public BaseGenerator {
public:
- PythonGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name, const Version &version)
+ PythonGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name, const Version& version)
: BaseGenerator(parser, path, file_name, "" /* not used */,
"" /* not used */, "py"),
float_const_gen_("float('nan')", "float('inf')", "float('-inf')"),
@@ -680,7 +703,7 @@
// Most field accessors need to retrieve and test the field offset first,
// this is the prefix code for that.
- std::string OffsetPrefix(const FieldDef &field, bool new_line = true) const {
+ std::string OffsetPrefix(const FieldDef& field, bool new_line = true) const {
return "\n" + Indent + Indent +
"o = flatbuffers.number_types.UOffsetTFlags.py_type" +
"(self._tab.Offset(" + NumToString(field.value.offset) + "))\n" +
@@ -688,16 +711,16 @@
}
// Begin a class declaration.
- void BeginClass(const StructDef &struct_def, std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void BeginClass(const StructDef& struct_def, std::string* code_ptr) const {
+ auto& code = *code_ptr;
code += "class " + namer_.Type(struct_def) + "(object):\n";
code += Indent + "__slots__ = ['_tab']";
code += "\n\n";
}
// Begin enum code with a class declaration.
- void BeginEnum(const EnumDef &enum_def, std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void BeginEnum(const EnumDef& enum_def, std::string* code_ptr) const {
+ auto& code = *code_ptr;
code += "class " + namer_.Type(enum_def) + "(object):\n";
}
@@ -707,9 +730,9 @@
}
// A single enum member.
- void EnumMember(const EnumDef &enum_def, const EnumVal &ev,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void EnumMember(const EnumDef& enum_def, const EnumVal& ev,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
code += Indent;
code += namer_.Variant(ev);
code += " = ";
@@ -717,9 +740,9 @@
}
// Initialize a new struct or table from existing data.
- void NewRootTypeFromBuffer(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void NewRootTypeFromBuffer(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const std::string struct_type = namer_.Type(struct_def);
code += Indent + "@classmethod\n";
@@ -751,9 +774,9 @@
}
// Initialize an existing object with other data, to avoid an allocation.
- void InitializeExisting(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void InitializeExisting(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
if (parser_.opts.python_typing) {
@@ -766,13 +789,15 @@
}
// Get the length of a vector.
- void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GetVectorLen(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field) + "Length(self)";
- if (parser_.opts.python_typing) { code += " -> int"; }
+ if (parser_.opts.python_typing) {
+ code += " -> int";
+ }
code += ":";
if (!IsArray(field.value.type)) {
code += OffsetPrefix(field, false);
@@ -785,13 +810,15 @@
}
// Determines whether a vector is none or not.
- void GetVectorIsNone(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GetVectorIsNone(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field) + "IsNone(self)";
- if (parser_.opts.python_typing) { code += " -> bool"; }
+ if (parser_.opts.python_typing) {
+ code += " -> bool";
+ }
code += ":";
if (!IsArray(field.value.type)) {
code += GenIndents(2) +
@@ -806,10 +833,10 @@
}
// Get the value of a struct's scalar.
- void GetScalarFieldOfStruct(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GetScalarFieldOfStruct(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field);
@@ -819,9 +846,9 @@
}
// Get the value of a table's scalar.
- void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GetScalarFieldOfTable(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field);
@@ -829,7 +856,9 @@
code += OffsetPrefix(field);
getter += "o + self._tab.Pos)";
auto is_bool = IsBool(field.value.type.base_type);
- if (is_bool) { getter = "bool(" + getter + ")"; }
+ if (is_bool) {
+ getter = "bool(" + getter + ")";
+ }
code += Indent + Indent + Indent + "return " + getter + "\n";
std::string default_value;
if (field.IsScalarOptional()) {
@@ -846,10 +875,10 @@
// Get a struct by initializing an existing struct.
// Specific to Struct.
- void GetStructFieldOfStruct(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GetStructFieldOfStruct(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field);
code += "(self, obj):\n";
@@ -859,15 +888,15 @@
}
// Get the value of a fixed size array.
- void GetArrayOfStruct(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr, ImportMap &imports) const {
- auto &code = *code_ptr;
+ void GetArrayOfStruct(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr, ImportMap& imports) const {
+ auto& code = *code_ptr;
const auto vec_type = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field);
- const ImportMapEntry import_entry = { GenPackageReference(field.value.type),
- TypeName(field) };
+ const ImportMapEntry import_entry = {GenPackageReference(field.value.type),
+ TypeName(field)};
if (parser_.opts.python_typing) {
const std::string return_type = ReturnType(struct_def, field);
@@ -895,9 +924,9 @@
// Get the value of a vector's non-struct member. Uses a named return
// argument to conveniently set the zero value for the result.
- void GetArrayOfNonStruct(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GetArrayOfNonStruct(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field);
code += "(self, j = None):";
@@ -921,19 +950,19 @@
// Get a struct by initializing an existing struct.
// Specific to Table.
- void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr, ImportMap &imports) const {
- auto &code = *code_ptr;
+ void GetStructFieldOfTable(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr, ImportMap& imports) const {
+ auto& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field) + "(self)";
- const ImportMapEntry import_entry = { GenPackageReference(field.value.type),
- TypeName(field) };
+ const ImportMapEntry import_entry = {GenPackageReference(field.value.type),
+ TypeName(field)};
if (parser_.opts.python_typing) {
const std::string return_type = ReturnType(struct_def, field);
code += " -> Optional[" + return_type + "]";
- imports.insert(ImportMapEntry{ "typing", "Optional" });
+ imports.insert(ImportMapEntry{"typing", "Optional"});
imports.insert(import_entry);
}
code += ":";
@@ -958,15 +987,15 @@
}
// Get the value of a string.
- void GetStringField(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr, ImportMap &imports) const {
- auto &code = *code_ptr;
+ void GetStringField(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr, ImportMap& imports) const {
+ auto& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field);
if (parser_.opts.python_typing) {
code += "(self) -> Optional[str]:";
- imports.insert(ImportMapEntry{ "typing", "Optional" });
+ imports.insert(ImportMapEntry{"typing", "Optional"});
} else {
code += "(self):";
}
@@ -978,26 +1007,26 @@
}
// Get the value of a union from an object.
- void GetUnionField(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr, ImportMap &imports) const {
- auto &code = *code_ptr;
+ void GetUnionField(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr, ImportMap& imports) const {
+ auto& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
std::string return_ty = "flatbuffers.table.Table";
bool is_native_table = TypeName(field) == "*flatbuffers.Table";
ImportMapEntry import_entry;
if (is_native_table) {
- import_entry = ImportMapEntry{ "flatbuffers.table", "Table" };
+ import_entry = ImportMapEntry{"flatbuffers.table", "Table"};
} else {
return_ty = TypeName(field);
- import_entry = ImportMapEntry{ GenPackageReference(field.value.type),
- TypeName(field) };
+ import_entry = ImportMapEntry{GenPackageReference(field.value.type),
+ TypeName(field)};
}
code += namer_.Method(field) + "(self)";
if (parser_.opts.python_typing) {
code += " -> Optional[" + return_ty + "]";
- imports.insert(ImportMapEntry{ "typing", "Optional" });
+ imports.insert(ImportMapEntry{"typing", "Optional"});
imports.insert(import_entry);
}
code += ":";
@@ -1014,8 +1043,11 @@
code += Indent + Indent + "return None\n\n";
}
- template<typename T> std::string ModuleFor(const T *def) const {
- if (!parser_.opts.one_file) { return namer_.NamespacedType(*def); }
+ template <typename T>
+ std::string ModuleFor(const T* def) const {
+ if (!parser_.opts.one_file) {
+ return namer_.NamespacedType(*def);
+ }
std::string filename =
StripExtension(def->file) + parser_.opts.filename_suffix;
@@ -1030,28 +1062,28 @@
// Generate the package reference when importing a struct or enum from its
// module.
- std::string GenPackageReference(const Type &type) const {
+ std::string GenPackageReference(const Type& type) const {
if (type.struct_def) return ModuleFor(type.struct_def);
if (type.enum_def) return ModuleFor(type.enum_def);
return "." + GenTypeGet(type);
}
// Get the value of a vector's struct member.
- void GetMemberOfVectorOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr,
- ImportMap &imports) const {
- auto &code = *code_ptr;
+ void GetMemberOfVectorOfStruct(const StructDef& struct_def,
+ const FieldDef& field, std::string* code_ptr,
+ ImportMap& imports) const {
+ auto& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field);
- const ImportMapEntry import_entry = { GenPackageReference(field.value.type),
- TypeName(field) };
+ const ImportMapEntry import_entry = {GenPackageReference(field.value.type),
+ TypeName(field)};
if (parser_.opts.python_typing) {
const std::string return_type = ReturnType(struct_def, field);
code += "(self, j: int) -> Optional[" + return_type + "]";
- imports.insert(ImportMapEntry{ "typing", "Optional" });
+ imports.insert(ImportMapEntry{"typing", "Optional"});
imports.insert(import_entry);
} else {
code += "(self, j)";
@@ -1078,10 +1110,10 @@
// Get the value of a vector's non-struct member. Uses a named return
// argument to conveniently set the zero value for the result.
- void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GetMemberOfVectorOfNonStruct(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
@@ -1108,15 +1140,17 @@
// Returns a non-struct vector as a numpy array. Much faster
// than iterating over the vector element by element.
- void GetVectorOfNonStructAsNumpy(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GetVectorOfNonStructAsNumpy(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
auto vectortype = field.value.type.VectorType();
// Currently, we only support accessing as numpy array if
// the vector type is a scalar.
- if (!(IsScalar(vectortype.base_type))) { return; }
+ if (!(IsScalar(vectortype.base_type))) {
+ return;
+ }
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field) + "AsNumpy(self):";
@@ -1146,7 +1180,7 @@
}
std::string NestedFlatbufferType(std::string unqualified_name) const {
- StructDef *nested_root = parser_.LookupStruct(unqualified_name);
+ StructDef* nested_root = parser_.LookupStruct(unqualified_name);
std::string qualified_name;
if (nested_root == nullptr) {
qualified_name = namer_.NamespacedType(
@@ -1159,24 +1193,28 @@
}
// Returns a nested flatbuffer as itself.
- void GetVectorAsNestedFlatbuffer(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr,
- ImportMap &imports) const {
+ void GetVectorAsNestedFlatbuffer(const StructDef& struct_def,
+ const FieldDef& field, std::string* code_ptr,
+ ImportMap& imports) const {
auto nested = field.attributes.Lookup("nested_flatbuffer");
- if (!nested) { return; } // There is no nested flatbuffer.
+ if (!nested) {
+ return;
+ } // There is no nested flatbuffer.
const std::string unqualified_name = nested->constant;
std::string qualified_name = NestedFlatbufferType(unqualified_name);
- if (qualified_name.empty()) { qualified_name = nested->constant; }
+ if (qualified_name.empty()) {
+ qualified_name = nested->constant;
+ }
- const ImportMapEntry import_entry = { qualified_name, unqualified_name };
+ const ImportMapEntry import_entry = {qualified_name, unqualified_name};
- auto &code = *code_ptr;
+ auto& code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += namer_.Method(field) + "NestedRoot(self)";
if (parser_.opts.python_typing) {
code += " -> Union[" + unqualified_name + ", int]";
- imports.insert(ImportMapEntry{ "typing", "Union" });
+ imports.insert(ImportMapEntry{"typing", "Union"});
imports.insert(import_entry);
}
code += ":";
@@ -1196,9 +1234,9 @@
}
// Begin the creator function signature.
- void BeginBuilderArgs(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void BeginBuilderArgs(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
code += "\n";
code += "def Create" + namer_.Type(struct_def);
@@ -1207,16 +1245,16 @@
// Recursively generate arguments for a constructor, to deal with nested
// structs.
- void StructBuilderArgs(const StructDef &struct_def,
+ void StructBuilderArgs(const StructDef& struct_def,
const std::string nameprefix,
const std::string namesuffix, bool has_field_name,
const std::string fieldname_suffix,
- std::string *code_ptr) const {
+ std::string* code_ptr) const {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- const auto &field_type = field.value.type;
- const auto &type =
+ auto& field = **it;
+ const auto& field_type = field.value.type;
+ const auto& type =
IsArray(field_type) ? field_type.VectorType() : field_type;
if (IsStruct(type)) {
// Generate arguments for a struct inside a struct. To ensure names
@@ -1229,35 +1267,37 @@
StructBuilderArgs(*field.value.type.struct_def, subprefix, namesuffix,
has_field_name, fieldname_suffix, code_ptr);
} else {
- auto &code = *code_ptr;
+ auto& code = *code_ptr;
code += std::string(", ") + nameprefix;
- if (has_field_name) { code += namer_.Field(field); }
+ if (has_field_name) {
+ code += namer_.Field(field);
+ }
code += namesuffix;
}
}
}
// End the creator function signature.
- void EndBuilderArgs(std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void EndBuilderArgs(std::string* code_ptr) const {
+ auto& code = *code_ptr;
code += "):\n";
}
// Recursively generate struct construction statements and instert manual
// padding.
- void StructBuilderBody(const StructDef &struct_def, const char *nameprefix,
- std::string *code_ptr, size_t index = 0,
+ void StructBuilderBody(const StructDef& struct_def, const char* nameprefix,
+ std::string* code_ptr, size_t index = 0,
bool in_array = false) const {
- auto &code = *code_ptr;
+ auto& code = *code_ptr;
std::string indent(index * 4, ' ');
code +=
indent + " builder.Prep(" + NumToString(struct_def.minalign) + ", ";
code += NumToString(struct_def.bytesize) + ")\n";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
- auto &field = **it;
- const auto &field_type = field.value.type;
- const auto &type =
+ auto& field = **it;
+ const auto& field_type = field.value.type;
+ const auto& type =
IsArray(field_type) ? field_type.VectorType() : field_type;
if (field.padding)
code +=
@@ -1292,15 +1332,15 @@
}
}
- void EndBuilderBody(std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void EndBuilderBody(std::string* code_ptr) const {
+ auto& code = *code_ptr;
code += " return builder.Offset()\n";
}
// Get the value of a table's starting offset.
- void GetStartOfTable(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GetStartOfTable(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto struct_type = namer_.Type(struct_def);
// Generate method with struct name.
@@ -1331,9 +1371,9 @@
}
// Set the value of a table's field.
- void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- const size_t offset, std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void BuildFieldOfTable(const StructDef& struct_def, const FieldDef& field,
+ const size_t offset, std::string* code_ptr) const {
+ auto& code = *code_ptr;
const std::string field_var = namer_.Variable(field);
const std::string field_method = namer_.Method(field);
const std::string field_ty = GenFieldTy(field);
@@ -1386,9 +1426,9 @@
}
// Set the value of one of the members of a table's vector.
- void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void BuildVectorOfTable(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const std::string struct_type = namer_.Type(struct_def);
const std::string field_method = namer_.Method(field);
@@ -1427,13 +1467,15 @@
// Set the value of one of the members of a table's vector and fills in the
// elements from a bytearray. This is for simplifying the use of nested
// flatbuffers.
- void BuildVectorOfTableFromBytes(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) const {
+ void BuildVectorOfTableFromBytes(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr) const {
auto nested = field.attributes.Lookup("nested_flatbuffer");
- if (!nested) { return; } // There is no nested flatbuffer.
+ if (!nested) {
+ return;
+ } // There is no nested flatbuffer.
- auto &code = *code_ptr;
+ auto& code = *code_ptr;
const std::string field_method = namer_.Method(field);
const std::string struct_type = namer_.Type(struct_def);
@@ -1461,9 +1503,9 @@
}
// Get the offset of the end of a table.
- void GetEndOffsetOnTable(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GetEndOffsetOnTable(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto name = parser_.opts.python_no_type_prefix_suffix
? "End"
@@ -1489,15 +1531,15 @@
}
// Generate the receiver for function signatures.
- void GenReceiver(const StructDef &struct_def, std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenReceiver(const StructDef& struct_def, std::string* code_ptr) const {
+ auto& code = *code_ptr;
code += Indent + "# " + namer_.Type(struct_def) + "\n";
code += Indent + "def ";
}
// Generate a struct field, conditioned on its child type(s).
- void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr, ImportMap &imports) const {
+ void GenStructAccessor(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr, ImportMap& imports) const {
GenComment(field.doc_comment, code_ptr, &def_comment, Indent.c_str());
if (IsScalar(field.value.type.base_type)) {
if (struct_def.fixed) {
@@ -1546,7 +1588,8 @@
case BASE_TYPE_UNION:
GetUnionField(struct_def, field, code_ptr, imports);
break;
- default: FLATBUFFERS_ASSERT(0);
+ default:
+ FLATBUFFERS_ASSERT(0);
}
}
if (IsVector(field.value.type) || IsArray(field.value.type)) {
@@ -1556,9 +1599,9 @@
}
// Generate struct sizeof.
- void GenStructSizeOf(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenStructSizeOf(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
code += Indent + "@classmethod\n";
if (parser_.opts.python_typing) {
code += Indent + "def SizeOf(cls) -> int:\n";
@@ -1571,13 +1614,13 @@
}
// Generate table constructors, conditioned on its members' types.
- void GenTableBuilders(const StructDef &struct_def,
- std::string *code_ptr) const {
+ void GenTableBuilders(const StructDef& struct_def,
+ std::string* code_ptr) const {
GetStartOfTable(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
auto offset = it - struct_def.fields.vec.begin();
@@ -1592,9 +1635,9 @@
}
// Generate function to check for proper file identifier
- void GenHasFileIdentifier(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenHasFileIdentifier(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
std::string escapedID;
// In the event any of file_identifier characters are special(NULL, \, etc),
// problems occur. To prevent this, convert all chars to their hex-escaped
@@ -1616,8 +1659,8 @@
}
// Generates struct or table methods.
- void GenStruct(const StructDef &struct_def, std::string *code_ptr,
- ImportMap &imports) const {
+ void GenStruct(const StructDef& struct_def, std::string* code_ptr,
+ ImportMap& imports) const {
if (struct_def.generated) return;
GenComment(struct_def.doc_comment, code_ptr, &def_comment);
@@ -1639,7 +1682,7 @@
InitializeExisting(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
GenStructAccessor(struct_def, field, code_ptr, imports);
@@ -1654,16 +1697,16 @@
}
}
- void GenReceiverForObjectAPI(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenReceiverForObjectAPI(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
code += GenIndents(1) + "# " + namer_.ObjectType(struct_def);
code += GenIndents(1) + "def ";
}
- void BeginClassForObjectAPI(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void BeginClassForObjectAPI(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
code += "\n";
code += "class " + namer_.ObjectType(struct_def) + "(object):";
code += "\n";
@@ -1672,7 +1715,7 @@
// Gets the accoresponding python builtin type of a BaseType for scalars and
// string.
std::string GetBasePythonTypeForScalarAndString(
- const BaseType &base_type) const {
+ const BaseType& base_type) const {
if (IsBool(base_type)) {
return "bool";
} else if (IsFloat(base_type)) {
@@ -1687,7 +1730,7 @@
}
}
- std::string GetDefaultValue(const FieldDef &field) const {
+ std::string GetDefaultValue(const FieldDef& field) const {
BaseType base_type = field.value.type.base_type;
if (field.IsScalarOptional()) {
return "None";
@@ -1703,19 +1746,19 @@
}
}
- void GenUnionInit(const FieldDef &field, std::string *field_types_ptr,
- std::set<std::string> *import_list,
- std::set<std::string> *import_typing_list) const {
+ void GenUnionInit(const FieldDef& field, std::string* field_types_ptr,
+ std::set<std::string>* import_list,
+ std::set<std::string>* import_typing_list) const {
// Gets all possible types in the union.
import_typing_list->insert("Union");
- auto &field_types = *field_types_ptr;
+ auto& field_types = *field_types_ptr;
field_types = "Union[";
std::string separator_string = ", ";
auto enum_def = field.value.type.enum_def;
for (auto it = enum_def->Vals().begin(); it != enum_def->Vals().end();
++it) {
- auto &ev = **it;
+ auto& ev = **it;
// Union only supports string and table.
std::string field_type;
switch (ev.union_type.base_type) {
@@ -1728,9 +1771,14 @@
}
field_type = "'" + field_type + "'";
break;
- case BASE_TYPE_STRING: field_type += "str"; break;
- case BASE_TYPE_NONE: field_type += "None"; break;
- default: break;
+ case BASE_TYPE_STRING:
+ field_type += "str";
+ break;
+ case BASE_TYPE_NONE:
+ field_type += "None";
+ break;
+ default:
+ break;
}
field_types += field_type + separator_string;
}
@@ -1746,12 +1794,12 @@
}
}
- void GenStructInit(const FieldDef &field, std::string *out_ptr,
- std::set<std::string> *import_list,
- std::set<std::string> *import_typing_list) const {
+ void GenStructInit(const FieldDef& field, std::string* out_ptr,
+ std::set<std::string>* import_list,
+ std::set<std::string>* import_typing_list) const {
import_typing_list->insert("Optional");
- auto &output = *out_ptr;
- const Type &type = field.value.type;
+ auto& output = *out_ptr;
+ const Type& type = field.value.type;
const std::string object_type = namer_.ObjectType(*type.struct_def);
if (parser_.opts.include_dependence_headers) {
auto package_reference = GenPackageReference(type);
@@ -1763,12 +1811,12 @@
output = "Optional[" + output;
}
- void GenVectorInit(const FieldDef &field, std::string *field_type_ptr,
- std::set<std::string> *import_list,
- std::set<std::string> *import_typing_list) const {
+ void GenVectorInit(const FieldDef& field, std::string* field_type_ptr,
+ std::set<std::string>* import_list,
+ std::set<std::string>* import_typing_list) const {
import_typing_list->insert("List");
- auto &field_type = *field_type_ptr;
- const Type &vector_type = field.value.type.VectorType();
+ auto& field_type = *field_type_ptr;
+ const Type& vector_type = field.value.type.VectorType();
const BaseType base_type = vector_type.base_type;
if (base_type == BASE_TYPE_STRUCT) {
const std::string object_type =
@@ -1786,8 +1834,8 @@
}
}
- void GenInitialize(const StructDef &struct_def, std::string *code_ptr,
- std::set<std::string> *import_list) const {
+ void GenInitialize(const StructDef& struct_def, std::string* code_ptr,
+ std::set<std::string>* import_list) const {
std::string signature_params;
std::string init_body;
std::set<std::string> import_typing_list;
@@ -1796,7 +1844,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
// Determines field type, default value, and typing imports.
@@ -1840,7 +1888,7 @@
}
// Writes __init__ method.
- auto &code_base = *code_ptr;
+ auto& code_base = *code_ptr;
GenReceiverForObjectAPI(struct_def, code_ptr);
code_base += "__init__(" + signature_params + GenIndents(1) + "):";
if (init_body.empty()) {
@@ -1858,7 +1906,7 @@
std::string separator_string = ", ";
for (auto it = import_typing_list.begin(); it != import_typing_list.end();
++it) {
- const std::string &im = *it;
+ const std::string& im = *it;
typing_imports += im + separator_string;
}
// Removes the last separator_string.
@@ -1876,9 +1924,9 @@
import_list->erase(struct_import);
}
- void InitializeFromBuf(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void InitializeFromBuf(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto struct_var = namer_.Variable(struct_def);
const auto struct_type = namer_.Type(struct_def);
@@ -1890,9 +1938,9 @@
code += "\n";
}
- void InitializeFromPackedBuf(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void InitializeFromPackedBuf(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto struct_var = namer_.Variable(struct_def);
const auto struct_type = namer_.Type(struct_def);
@@ -1904,9 +1952,9 @@
code += "\n";
}
- void InitializeFromObjForObject(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void InitializeFromObjForObject(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto struct_var = namer_.Variable(struct_def);
const auto struct_object = namer_.ObjectType(struct_def);
@@ -1918,14 +1966,14 @@
code += "\n";
}
- void GenCompareOperator(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenCompareOperator(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
code += GenIndents(1) + "def __eq__(self, other):";
code += GenIndents(2) + "return type(self) == type(other)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
// Writes the comparison statement for this field.
@@ -1942,9 +1990,9 @@
code += "\n";
}
- void GenUnPackForStruct(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenUnPackForStruct(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto struct_var = namer_.Variable(struct_def);
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
@@ -1971,13 +2019,13 @@
code += "))";
}
- void GenUnPackForUnion(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenUnPackForUnion(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
const auto struct_var = namer_.Variable(struct_def);
- const EnumDef &enum_def = *field.value.type.enum_def;
+ const EnumDef& enum_def = *field.value.type.enum_def;
auto union_type = namer_.Type(enum_def);
if (parser_.opts.include_dependence_headers) {
@@ -1988,10 +2036,10 @@
field_method + "())";
}
- void GenUnPackForStructVector(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenUnPackForStructVector(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
const auto struct_var = namer_.Variable(struct_def);
@@ -2020,10 +2068,10 @@
GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")";
}
- void GenUnpackForTableVector(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenUnpackForTableVector(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
const auto struct_var = namer_.Variable(struct_def);
@@ -2052,11 +2100,11 @@
GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")";
}
- void GenUnpackforScalarVectorHelper(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr,
+ void GenUnpackforScalarVectorHelper(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr,
int indents) const {
- auto &code = *code_ptr;
+ auto& code = *code_ptr;
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
const auto struct_var = namer_.Variable(struct_def);
@@ -2068,10 +2116,10 @@
struct_var + "." + field_method + "(i))";
}
- void GenUnPackForScalarVector(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenUnPackForScalarVector(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
const auto struct_var = namer_.Variable(struct_def);
@@ -2098,9 +2146,9 @@
}
}
- void GenUnPackForString(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenUnPackForString(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
const auto struct_var = namer_.Variable(struct_def);
@@ -2112,9 +2160,9 @@
".decode('utf-8')";
}
- void GenUnPackForScalar(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenUnPackForScalar(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
const auto struct_var = namer_.Variable(struct_def);
@@ -2124,14 +2172,14 @@
}
// Generates the UnPack method for the object class.
- void GenUnPack(const StructDef &struct_def, std::string *code_ptr) const {
+ void GenUnPack(const StructDef& struct_def, std::string* code_ptr) const {
std::string code;
// Items that needs to be imported. No duplicate modules will be imported.
std::set<std::string> import_list;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
switch (field.value.type.base_type) {
@@ -2161,12 +2209,13 @@
}
break;
}
- default: GenUnPackForScalar(struct_def, field, &code);
+ default:
+ GenUnPackForScalar(struct_def, field, &code);
}
}
// Writes import statements and code into the generated file.
- auto &code_base = *code_ptr;
+ auto& code_base = *code_ptr;
const auto struct_var = namer_.Variable(struct_def);
GenReceiverForObjectAPI(struct_def, code_ptr);
@@ -2185,9 +2234,9 @@
code_base += "\n";
}
- void GenPackForStruct(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenPackForStruct(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto struct_fn = namer_.Function(struct_def);
GenReceiverForObjectAPI(struct_def, code_ptr);
@@ -2202,12 +2251,12 @@
code += ")\n";
}
- void GenPackForStructVectorField(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_prefix_ptr,
- std::string *code_ptr) const {
- auto &code_prefix = *code_prefix_ptr;
- auto &code = *code_ptr;
+ void GenPackForStructVectorField(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_prefix_ptr,
+ std::string* code_ptr) const {
+ auto& code_prefix = *code_prefix_ptr;
+ auto& code = *code_ptr;
const auto field_field = namer_.Field(field);
const auto struct_type = namer_.Type(struct_def);
const auto field_method = namer_.Method(field);
@@ -2246,11 +2295,11 @@
field_field + ")";
}
- void GenPackForScalarVectorFieldHelper(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr,
+ void GenPackForScalarVectorFieldHelper(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_ptr,
int indents) const {
- auto &code = *code_ptr;
+ auto& code = *code_ptr;
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
const auto struct_type = namer_.Type(struct_def);
@@ -2264,29 +2313,55 @@
std::string type_name;
switch (vectortype.base_type) {
- case BASE_TYPE_BOOL: type_name = "Bool"; break;
- case BASE_TYPE_CHAR: type_name = "Byte"; break;
- case BASE_TYPE_UCHAR: type_name = "Uint8"; break;
- case BASE_TYPE_SHORT: type_name = "Int16"; break;
- case BASE_TYPE_USHORT: type_name = "Uint16"; break;
- case BASE_TYPE_INT: type_name = "Int32"; break;
- case BASE_TYPE_UINT: type_name = "Uint32"; break;
- case BASE_TYPE_LONG: type_name = "Int64"; break;
- case BASE_TYPE_ULONG: type_name = "Uint64"; break;
- case BASE_TYPE_FLOAT: type_name = "Float32"; break;
- case BASE_TYPE_DOUBLE: type_name = "Float64"; break;
- case BASE_TYPE_STRING: type_name = "UOffsetTRelative"; break;
- default: type_name = "VOffsetT"; break;
+ case BASE_TYPE_BOOL:
+ type_name = "Bool";
+ break;
+ case BASE_TYPE_CHAR:
+ type_name = "Byte";
+ break;
+ case BASE_TYPE_UCHAR:
+ type_name = "Uint8";
+ break;
+ case BASE_TYPE_SHORT:
+ type_name = "Int16";
+ break;
+ case BASE_TYPE_USHORT:
+ type_name = "Uint16";
+ break;
+ case BASE_TYPE_INT:
+ type_name = "Int32";
+ break;
+ case BASE_TYPE_UINT:
+ type_name = "Uint32";
+ break;
+ case BASE_TYPE_LONG:
+ type_name = "Int64";
+ break;
+ case BASE_TYPE_ULONG:
+ type_name = "Uint64";
+ break;
+ case BASE_TYPE_FLOAT:
+ type_name = "Float32";
+ break;
+ case BASE_TYPE_DOUBLE:
+ type_name = "Float64";
+ break;
+ case BASE_TYPE_STRING:
+ type_name = "UOffsetTRelative";
+ break;
+ default:
+ type_name = "VOffsetT";
+ break;
}
code += type_name;
}
- void GenPackForScalarVectorField(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_prefix_ptr,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
- auto &code_prefix = *code_prefix_ptr;
+ void GenPackForScalarVectorField(const StructDef& struct_def,
+ const FieldDef& field,
+ std::string* code_prefix_ptr,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
+ auto& code_prefix = *code_prefix_ptr;
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
const auto struct_type = namer_.Type(struct_def);
@@ -2331,11 +2406,11 @@
}
}
- void GenPackForStructField(const StructDef &struct_def, const FieldDef &field,
- std::string *code_prefix_ptr,
- std::string *code_ptr) const {
- auto &code_prefix = *code_prefix_ptr;
- auto &code = *code_ptr;
+ void GenPackForStructField(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_prefix_ptr,
+ std::string* code_ptr) const {
+ auto& code_prefix = *code_prefix_ptr;
+ auto& code = *code_ptr;
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
const auto struct_type = namer_.Type(struct_def);
@@ -2358,11 +2433,11 @@
field_field + ")";
}
- void GenPackForUnionField(const StructDef &struct_def, const FieldDef &field,
- std::string *code_prefix_ptr,
- std::string *code_ptr) const {
- auto &code_prefix = *code_prefix_ptr;
- auto &code = *code_ptr;
+ void GenPackForUnionField(const StructDef& struct_def, const FieldDef& field,
+ std::string* code_prefix_ptr,
+ std::string* code_ptr) const {
+ auto& code_prefix = *code_prefix_ptr;
+ auto& code = *code_ptr;
const auto field_field = namer_.Field(field);
const auto field_method = namer_.Method(field);
const auto struct_type = namer_.Type(struct_def);
@@ -2376,9 +2451,9 @@
field_field + ")";
}
- void GenPackForTable(const StructDef &struct_def,
- std::string *code_ptr) const {
- auto &code_base = *code_ptr;
+ void GenPackForTable(const StructDef& struct_def,
+ std::string* code_ptr) const {
+ auto& code_base = *code_ptr;
std::string code, code_prefix;
const auto struct_var = namer_.Variable(struct_def);
const auto struct_type = namer_.Type(struct_def);
@@ -2388,7 +2463,7 @@
code += GenIndents(2) + struct_type + "Start(builder)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
const auto field_method = namer_.Method(field);
@@ -2440,8 +2515,8 @@
code_base += "\n";
}
- void GenStructForObjectAPI(const StructDef &struct_def,
- std::string *code_ptr) const {
+ void GenStructForObjectAPI(const StructDef& struct_def,
+ std::string* code_ptr) const {
if (struct_def.generated) return;
std::set<std::string> import_list;
@@ -2458,7 +2533,9 @@
InitializeFromObjForObject(struct_def, &code);
- if (parser_.opts.gen_compare) { GenCompareOperator(struct_def, &code); }
+ if (parser_.opts.gen_compare) {
+ GenCompareOperator(struct_def, &code);
+ }
GenUnPack(struct_def, &code);
@@ -2469,7 +2546,7 @@
}
// Adds the imports at top.
- auto &code_base = *code_ptr;
+ auto& code_base = *code_ptr;
code_base += "\n";
for (auto it = import_list.begin(); it != import_list.end(); it++) {
auto im = *it;
@@ -2478,9 +2555,9 @@
code_base += code;
}
- void GenUnionCreatorForStruct(const EnumDef &enum_def, const EnumVal &ev,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenUnionCreatorForStruct(const EnumDef& enum_def, const EnumVal& ev,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto union_type = namer_.Type(enum_def);
const auto variant = namer_.Variant(ev);
auto field_type = namer_.ObjectType(*ev.union_type.struct_def);
@@ -2496,9 +2573,9 @@
".InitFromBuf(table.Bytes, table.Pos)";
}
- void GenUnionCreatorForString(const EnumDef &enum_def, const EnumVal &ev,
- std::string *code_ptr) const {
- auto &code = *code_ptr;
+ void GenUnionCreatorForString(const EnumDef& enum_def, const EnumVal& ev,
+ std::string* code_ptr) const {
+ auto& code = *code_ptr;
const auto union_type = namer_.Type(enum_def);
const auto variant = namer_.Variant(ev);
@@ -2510,10 +2587,10 @@
}
// Creates an union object based on union type.
- void GenUnionCreator(const EnumDef &enum_def, std::string *code_ptr) const {
+ void GenUnionCreator(const EnumDef& enum_def, std::string* code_ptr) const {
if (enum_def.generated) return;
- auto &code = *code_ptr;
+ auto& code = *code_ptr;
const auto enum_fn = namer_.Function(enum_def);
code += "\n";
@@ -2523,7 +2600,7 @@
code += GenIndents(2) + "return None";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
// Union only supports string and table.
switch (ev.union_type.base_type) {
case BASE_TYPE_STRUCT:
@@ -2532,7 +2609,8 @@
case BASE_TYPE_STRING:
GenUnionCreatorForString(enum_def, ev, &code);
break;
- default: break;
+ default:
+ break;
}
}
code += GenIndents(1) + "return None";
@@ -2540,38 +2618,47 @@
}
// Generate enum declarations.
- void GenEnum(const EnumDef &enum_def, std::string *code_ptr) const {
+ void GenEnum(const EnumDef& enum_def, std::string* code_ptr) const {
if (enum_def.generated) return;
GenComment(enum_def.doc_comment, code_ptr, &def_comment);
BeginEnum(enum_def, code_ptr);
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
GenComment(ev.doc_comment, code_ptr, &def_comment, Indent.c_str());
EnumMember(enum_def, ev, code_ptr);
}
}
// Returns the function name that is able to read a value of the given type.
- std::string GenGetter(const Type &type) const {
+ std::string GenGetter(const Type& type) const {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "self._tab.String(";
- case BASE_TYPE_UNION: return "self._tab.Union(";
- case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
+ case BASE_TYPE_STRING:
+ return "self._tab.String(";
+ case BASE_TYPE_UNION:
+ return "self._tab.Union(";
+ case BASE_TYPE_VECTOR:
+ return GenGetter(type.VectorType());
default:
return "self._tab.Get(flatbuffers.number_types." +
namer_.Method(GenTypeGet(type)) + "Flags, ";
}
}
- std::string GenFieldTy(const FieldDef &field) const {
+ std::string GenFieldTy(const FieldDef& field) const {
if (IsScalar(field.value.type.base_type) || IsArray(field.value.type)) {
const std::string ty = GenTypeBasic(field.value.type);
- if (ty.find("int") != std::string::npos) { return "int"; }
+ if (ty.find("int") != std::string::npos) {
+ return "int";
+ }
- if (ty.find("float") != std::string::npos) { return "float"; }
+ if (ty.find("float") != std::string::npos) {
+ return "float";
+ }
- if (ty == "bool") { return "bool"; }
+ if (ty == "bool") {
+ return "bool";
+ }
return "Any";
} else {
@@ -2584,13 +2671,13 @@
}
// Returns the method name for use with add/put calls.
- std::string GenMethod(const FieldDef &field) const {
+ std::string GenMethod(const FieldDef& field) const {
return (IsScalar(field.value.type.base_type) || IsArray(field.value.type))
? namer_.Method(GenTypeBasic(field.value.type))
: (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative");
}
- std::string GenTypeBasic(const Type &type) const {
+ std::string GenTypeBasic(const Type& type) const {
// clang-format off
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
@@ -2604,29 +2691,33 @@
: type.base_type];
}
- std::string GenTypePointer(const Type &type) const {
+ std::string GenTypePointer(const Type& type) const {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "string";
+ case BASE_TYPE_STRING:
+ return "string";
case BASE_TYPE_VECTOR:
// fall through
- case BASE_TYPE_ARRAY: return GenTypeGet(type.VectorType());
- case BASE_TYPE_STRUCT: return type.struct_def->name;
+ case BASE_TYPE_ARRAY:
+ return GenTypeGet(type.VectorType());
+ case BASE_TYPE_STRUCT:
+ return type.struct_def->name;
case BASE_TYPE_UNION:
// fall through
- default: return "*flatbuffers.Table";
+ default:
+ return "*flatbuffers.Table";
}
}
- std::string GenTypeGet(const Type &type) const {
+ std::string GenTypeGet(const Type& type) const {
return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
}
- std::string TypeName(const FieldDef &field) const {
+ std::string TypeName(const FieldDef& field) const {
return GenTypeGet(field.value.type);
}
- std::string ReturnType(const StructDef &struct_def,
- const FieldDef &field) const {
+ std::string ReturnType(const StructDef& struct_def,
+ const FieldDef& field) const {
// If we have a class member that returns an instance of the same class,
// for example:
// class Field(object):
@@ -2645,14 +2736,16 @@
const std::string self_type = struct_def.name;
std::string field_type = TypeName(field);
- if (self_type == field_type) { field_type = "'" + field_type + "'"; }
+ if (self_type == field_type) {
+ field_type = "'" + field_type + "'";
+ }
return field_type;
}
// Create a struct with a builder and the struct's arguments.
- void GenStructBuilder(const StructDef &struct_def,
- std::string *code_ptr) const {
+ void GenStructBuilder(const StructDef& struct_def,
+ std::string* code_ptr) const {
BeginBuilderArgs(struct_def, code_ptr);
StructBuilderArgs(struct_def,
/* nameprefix = */ "",
@@ -2683,10 +2776,10 @@
}
private:
- bool generateEnums(std::string *one_file_code) const {
+ bool generateEnums(std::string* one_file_code) const {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
- auto &enum_def = **it;
+ auto& enum_def = **it;
std::string enumcode;
GenEnum(enum_def, &enumcode);
if (parser_.opts.generate_object_based_api & enum_def.is_union) {
@@ -2709,11 +2802,11 @@
return true;
}
- bool generateStructs(std::string *one_file_code,
- ImportMap &one_file_imports) const {
+ bool generateStructs(std::string* one_file_code,
+ ImportMap& one_file_imports) const {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
- auto &struct_def = **it;
+ auto& struct_def = **it;
std::string declcode;
ImportMap imports;
GenStruct(struct_def, &declcode, imports);
@@ -2722,9 +2815,13 @@
}
if (parser_.opts.one_file) {
- if (!declcode.empty()) { *one_file_code += declcode + "\n\n"; }
+ if (!declcode.empty()) {
+ *one_file_code += declcode + "\n\n";
+ }
- for (auto import_str : imports) { one_file_imports.insert(import_str); }
+ for (auto import_str : imports) {
+ one_file_imports.insert(import_str);
+ }
} else {
const std::string mod =
namer_.File(struct_def, SkipFile::SuffixAndExtension);
@@ -2738,10 +2835,10 @@
}
// Begin by declaring namespace and imports.
- void BeginFile(const std::string &name_space_name, const bool needs_imports,
- std::string *code_ptr, const std::string &mod,
- const ImportMap &imports) const {
- auto &code = *code_ptr;
+ void BeginFile(const std::string& name_space_name, const bool needs_imports,
+ std::string* code_ptr, const std::string& mod,
+ const ImportMap& imports) const {
+ auto& code = *code_ptr;
code = code + "# " + FlatBuffersGeneratedWarning() + "\n\n";
code += "# namespace: " + name_space_name + "\n\n";
@@ -2767,14 +2864,16 @@
}
}
}
- if (parser_.opts.python_gen_numpy) { code += "np = import_numpy()\n\n"; }
+ if (parser_.opts.python_gen_numpy) {
+ code += "np = import_numpy()\n\n";
+ }
}
}
// Save out the generated code for a Python Table type.
- bool SaveType(const std::string &defname, const Namespace &ns,
- const std::string &classcode, const ImportMap &imports,
- const std::string &mod, bool needs_imports) const {
+ bool SaveType(const std::string& defname, const Namespace& ns,
+ const std::string& classcode, const ImportMap& imports,
+ const std::string& mod, bool needs_imports) const {
if (classcode.empty()) return true;
std::string code = "";
@@ -2803,9 +2902,9 @@
} // namespace python
-static bool GeneratePython(const Parser &parser, const std::string &path,
- const std::string &file_name) {
- python::Version version{ parser.opts.python_version };
+static bool GeneratePython(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
+ python::Version version{parser.opts.python_version};
if (!version.IsValid()) return false;
python::PythonGenerator generator(parser, path, file_name, version);
@@ -2822,20 +2921,21 @@
class PythonCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GeneratePython(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GeneratePython(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -2843,14 +2943,16 @@
return Status::NOT_IMPLEMENTED;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GeneratePythonGRPC(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GeneratePythonGRPC(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_rust.cpp b/src/idl_gen_rust.cpp
index 6087a6a..09dbcdf 100644
--- a/src/idl_gen_rust.cpp
+++ b/src/idl_gen_rust.cpp
@@ -34,108 +34,108 @@
// implementation, presumably because Flatbuffers schema style and Rust style
// roughly align. We are not going to enforce proper casing since its an
// unnecessary breaking change.
- return { /*types=*/Case::kKeep,
- /*constants=*/Case::kScreamingSnake,
- /*methods=*/Case::kSnake,
- /*functions=*/Case::kSnake,
- /*fields=*/Case::kKeep,
- /*variables=*/Case::kUnknown, // Unused.
- /*variants=*/Case::kKeep,
- /*enum_variant_seperator=*/"::",
- /*escape_keywords=*/Namer::Config::Escape::BeforeConvertingCase,
- /*namespaces=*/Case::kSnake,
- /*namespace_seperator=*/"::",
- /*object_prefix=*/"",
- /*object_suffix=*/"T",
- /*keyword_prefix=*/"",
- /*keyword_suffix=*/"_",
- /*filenames=*/Case::kSnake,
- /*directories=*/Case::kSnake,
- /*output_path=*/"",
- /*filename_suffix=*/"_generated",
- /*filename_extension=*/".rs" };
+ return {/*types=*/Case::kKeep,
+ /*constants=*/Case::kScreamingSnake,
+ /*methods=*/Case::kSnake,
+ /*functions=*/Case::kSnake,
+ /*fields=*/Case::kKeep,
+ /*variables=*/Case::kUnknown, // Unused.
+ /*variants=*/Case::kKeep,
+ /*enum_variant_seperator=*/"::",
+ /*escape_keywords=*/Namer::Config::Escape::BeforeConvertingCase,
+ /*namespaces=*/Case::kSnake,
+ /*namespace_seperator=*/"::",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kSnake,
+ /*directories=*/Case::kSnake,
+ /*output_path=*/"",
+ /*filename_suffix=*/"_generated",
+ /*filename_extension=*/".rs"};
}
static std::set<std::string> RustKeywords() {
return {
- // https://doc.rust-lang.org/book/second-edition/appendix-01-keywords.html
- "as",
- "break",
- "const",
- "continue",
- "crate",
- "else",
- "enum",
- "extern",
- "false",
- "fn",
- "for",
- "if",
- "impl",
- "in",
- "let",
- "loop",
- "match",
- "mod",
- "move",
- "mut",
- "pub",
- "ref",
- "return",
- "Self",
- "self",
- "static",
- "struct",
- "super",
- "trait",
- "true",
- "type",
- "unsafe",
- "use",
- "where",
- "while",
- // future possible keywords
- "abstract",
- "alignof",
- "become",
- "box",
- "do",
- "final",
- "macro",
- "offsetof",
- "override",
- "priv",
- "proc",
- "pure",
- "sizeof",
- "typeof",
- "unsized",
- "virtual",
- "yield",
- // other rust terms we should not use
- "std",
- "usize",
- "isize",
- "u8",
- "i8",
- "u16",
- "i16",
- "u32",
- "i32",
- "u64",
- "i64",
- "u128",
- "i128",
- "f32",
- "f64",
- // Terms that we use ourselves
- "follow",
- "push",
- "to_little_endian",
- "from_little_endian",
- "ENUM_MAX",
- "ENUM_MIN",
- "ENUM_VALUES",
+ // https://doc.rust-lang.org/book/second-edition/appendix-01-keywords.html
+ "as",
+ "break",
+ "const",
+ "continue",
+ "crate",
+ "else",
+ "enum",
+ "extern",
+ "false",
+ "fn",
+ "for",
+ "if",
+ "impl",
+ "in",
+ "let",
+ "loop",
+ "match",
+ "mod",
+ "move",
+ "mut",
+ "pub",
+ "ref",
+ "return",
+ "Self",
+ "self",
+ "static",
+ "struct",
+ "super",
+ "trait",
+ "true",
+ "type",
+ "unsafe",
+ "use",
+ "where",
+ "while",
+ // future possible keywords
+ "abstract",
+ "alignof",
+ "become",
+ "box",
+ "do",
+ "final",
+ "macro",
+ "offsetof",
+ "override",
+ "priv",
+ "proc",
+ "pure",
+ "sizeof",
+ "typeof",
+ "unsized",
+ "virtual",
+ "yield",
+ // other rust terms we should not use
+ "std",
+ "usize",
+ "isize",
+ "u8",
+ "i8",
+ "u16",
+ "i16",
+ "u32",
+ "i32",
+ "u64",
+ "i64",
+ "u128",
+ "i128",
+ "f32",
+ "f64",
+ // Terms that we use ourselves
+ "follow",
+ "push",
+ "to_little_endian",
+ "from_little_endian",
+ "ENUM_MAX",
+ "ENUM_MIN",
+ "ENUM_VALUES",
};
}
@@ -176,7 +176,7 @@
};
// Convert a Type to a FullType (exhaustive).
-static FullType GetFullType(const Type &type) {
+static FullType GetFullType(const Type& type) {
// N.B. The order of these conditionals matters for some types.
if (IsString(type)) {
@@ -266,19 +266,19 @@
return ftBool;
}
-static bool IsBitFlagsEnum(const EnumDef &enum_def) {
+static bool IsBitFlagsEnum(const EnumDef& enum_def) {
return enum_def.attributes.Lookup("bit_flags") != nullptr;
}
// TableArgs make required non-scalars "Option<_>".
// TODO(cneo): Rework how we do defaults and stuff.
-static bool IsOptionalToBuilder(const FieldDef &field) {
+static bool IsOptionalToBuilder(const FieldDef& field) {
return field.IsOptional() || !IsScalar(field.value.type.base_type);
}
} // namespace
-static bool GenerateRustModuleRootFile(const Parser &parser,
- const std::string &output_dir) {
+static bool GenerateRustModuleRootFile(const Parser& parser,
+ const std::string& output_dir) {
if (!parser.opts.rust_module_root_file) {
// Don't generate a root file when generating one file. This isn't an error
// so return true.
@@ -292,9 +292,9 @@
std::map<std::string, Module> sub_modules;
std::vector<std::string> generated_files;
// Add a symbol into the tree.
- void Insert(const Namer &namer, const Definition *s) {
- const Definition &symbol = *s;
- Module *current_module = this;
+ void Insert(const Namer& namer, const Definition* s) {
+ const Definition& symbol = *s;
+ Module* current_module = this;
for (auto it = symbol.defined_namespace->components.begin();
it != symbol.defined_namespace->components.end(); it++) {
std::string ns_component = namer.Namespace(*it);
@@ -304,7 +304,7 @@
namer.File(symbol.name, SkipFile::Extension));
}
// Recursively create the importer file.
- void GenerateImports(CodeWriter &code) {
+ void GenerateImports(CodeWriter& code) {
for (auto it = sub_modules.begin(); it != sub_modules.end(); it++) {
code += "pub mod " + it->first + " {";
code.IncrementIdentLevel();
@@ -346,8 +346,8 @@
class RustGenerator : public BaseGenerator {
public:
- RustGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ RustGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", "::", "rs"),
cur_name_space_(nullptr),
namer_(WithFlagOptions(RustDefaultConfig(), parser.opts, path),
@@ -364,11 +364,11 @@
}
}
- template<typename T>
- bool GenerateSymbols(const SymbolTable<T> &symbols,
- std::function<void(const T &)> gen_symbol) {
+ template <typename T>
+ bool GenerateSymbols(const SymbolTable<T>& symbols,
+ std::function<void(const T&)> gen_symbol) {
for (auto it = symbols.vec.begin(); it != symbols.vec.end(); it++) {
- const T &symbol = **it;
+ const T& symbol = **it;
if (symbol.generated) continue;
code_.Clear();
code_ += "// " + std::string(FlatBuffersGeneratedWarning());
@@ -405,9 +405,9 @@
code_.Clear();
// Don't bother with imports. Use absolute paths everywhere.
return GenerateSymbols<EnumDef>(
- parser_.enums_, [&](const EnumDef &e) { this->GenEnum(e); }) &&
+ parser_.enums_, [&](const EnumDef& e) { this->GenEnum(e); }) &&
GenerateSymbols<StructDef>(
- parser_.structs_, [&](const StructDef &s) {
+ parser_.structs_, [&](const StructDef& s) {
if (s.fixed) {
this->GenStruct(s);
} else {
@@ -445,12 +445,12 @@
// O(n**2) to O(n).
for (auto ns_it = parser_.namespaces_.begin();
ns_it != parser_.namespaces_.end(); ++ns_it) {
- const auto &ns = *ns_it;
+ const auto& ns = *ns_it;
// Generate code for all the enum declarations.
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
- const auto &enum_def = **it;
+ const auto& enum_def = **it;
if (enum_def.defined_namespace == ns && !enum_def.generated) {
SetNameSpace(enum_def.defined_namespace);
GenEnum(enum_def);
@@ -460,7 +460,7 @@
// Generate code for all structs.
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
- const auto &struct_def = **it;
+ const auto& struct_def = **it;
if (struct_def.defined_namespace == ns && struct_def.fixed &&
!struct_def.generated) {
SetNameSpace(struct_def.defined_namespace);
@@ -471,7 +471,7 @@
// Generate code for all tables.
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
- const auto &struct_def = **it;
+ const auto& struct_def = **it;
if (struct_def.defined_namespace == ns && !struct_def.fixed &&
!struct_def.generated) {
SetNameSpace(struct_def.defined_namespace);
@@ -484,8 +484,10 @@
// Generate global helper functions.
if (parser_.root_struct_def_) {
- auto &struct_def = *parser_.root_struct_def_;
- if (struct_def.defined_namespace != ns) { continue; }
+ auto& struct_def = *parser_.root_struct_def_;
+ if (struct_def.defined_namespace != ns) {
+ continue;
+ }
SetNameSpace(struct_def.defined_namespace);
GenRootTableFuncs(struct_def);
}
@@ -501,13 +503,13 @@
CodeWriter code_;
// This tracks the current namespace so we can insert namespace declarations.
- const Namespace *cur_name_space_;
+ const Namespace* cur_name_space_;
- const Namespace *CurrentNameSpace() const { return cur_name_space_; }
+ const Namespace* CurrentNameSpace() const { return cur_name_space_; }
// Determine if a Type needs a lifetime template parameter when used in the
// Rust builder args.
- bool TableBuilderTypeNeedsLifetime(const Type &type) const {
+ bool TableBuilderTypeNeedsLifetime(const Type& type) const {
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
@@ -524,33 +526,37 @@
}
// Determine if a table args rust type needs a lifetime template parameter.
- bool TableBuilderArgsNeedsLifetime(const StructDef &struct_def) const {
+ bool TableBuilderArgsNeedsLifetime(const StructDef& struct_def) const {
FLATBUFFERS_ASSERT(!struct_def.fixed);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (field.deprecated) { continue; }
+ const auto& field = **it;
+ if (field.deprecated) {
+ continue;
+ }
- if (TableBuilderTypeNeedsLifetime(field.value.type)) { return true; }
+ if (TableBuilderTypeNeedsLifetime(field.value.type)) {
+ return true;
+ }
}
return false;
}
- std::string NamespacedNativeName(const EnumDef &def) {
+ std::string NamespacedNativeName(const EnumDef& def) {
return WrapInNameSpace(def.defined_namespace, namer_.ObjectType(def));
}
- std::string NamespacedNativeName(const StructDef &def) {
+ std::string NamespacedNativeName(const StructDef& def) {
return WrapInNameSpace(def.defined_namespace, namer_.ObjectType(def));
}
- std::string WrapInNameSpace(const Definition &def) const {
+ std::string WrapInNameSpace(const Definition& def) const {
return WrapInNameSpace(def.defined_namespace,
namer_.EscapeKeyword(def.name));
}
- std::string WrapInNameSpace(const Namespace *ns,
- const std::string &name) const {
+ std::string WrapInNameSpace(const Namespace* ns,
+ const std::string& name) const {
if (CurrentNameSpace() == ns) return name;
std::string prefix = GetRelativeNamespaceTraversal(CurrentNameSpace(), ns);
return prefix + name;
@@ -561,8 +567,8 @@
// the user to have a particular file layout. (If we output absolute
// namespace paths, that may require users to organize their Rust crates in a
// particular way.)
- std::string GetRelativeNamespaceTraversal(const Namespace *src,
- const Namespace *dst) const {
+ std::string GetRelativeNamespaceTraversal(const Namespace* src,
+ const Namespace* dst) const {
// calculate the path needed to reference dst from src.
// example: f(A::B::C, A::B::C) -> (none)
// example: f(A::B::C, A::B) -> super::
@@ -588,14 +594,14 @@
}
// Generate a comment from the schema.
- void GenComment(const std::vector<std::string> &dc, const char *prefix = "") {
+ void GenComment(const std::vector<std::string>& dc, const char* prefix = "") {
for (auto it = dc.begin(); it != dc.end(); it++) {
code_ += std::string(prefix) + "///" + *it;
}
}
// Return a Rust type from the table in idl.h.
- std::string GetTypeBasic(const Type &type) const {
+ std::string GetTypeBasic(const Type& type) const {
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
@@ -619,13 +625,15 @@
};
// clang-format on
- if (type.enum_def) { return WrapInNameSpace(*type.enum_def); }
+ if (type.enum_def) {
+ return WrapInNameSpace(*type.enum_def);
+ }
return ctypename[type.base_type];
}
// Look up the native type for an enum. This will always be an integer like
// u8, i32, etc.
- std::string GetEnumTypeForDecl(const Type &type) {
+ std::string GetEnumTypeForDecl(const Type& type) {
const auto ft = GetFullType(type);
if (!(ft == ftEnumKey || ft == ftUnionKey)) {
FLATBUFFERS_ASSERT(false && "precondition failed in GetEnumTypeForDecl");
@@ -649,7 +657,7 @@
// Return a Rust type for any type (scalar, table, struct) specifically for
// using a FlatBuffer.
- std::string GetTypeGet(const Type &type) const {
+ std::string GetTypeGet(const Type& type) const {
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
@@ -676,16 +684,16 @@
}
}
- std::string GetEnumValue(const EnumDef &enum_def,
- const EnumVal &enum_val) const {
+ std::string GetEnumValue(const EnumDef& enum_def,
+ const EnumVal& enum_val) const {
return namer_.EnumVariant(enum_def, enum_val);
}
// 1 suffix since old C++ can't figure out the overload.
- void ForAllEnumValues1(const EnumDef &enum_def,
- std::function<void(const EnumVal &)> cb) {
+ void ForAllEnumValues1(const EnumDef& enum_def,
+ std::function<void(const EnumVal&)> cb) {
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
code_.SetValue("VARIANT", namer_.Variant(ev));
code_.SetValue("VALUE", enum_def.ToString(ev));
code_.IncrementIdentLevel();
@@ -693,8 +701,8 @@
code_.DecrementIdentLevel();
}
}
- void ForAllEnumValues(const EnumDef &enum_def, std::function<void()> cb) {
- std::function<void(const EnumVal &)> wrapped = [&](const EnumVal &unused) {
+ void ForAllEnumValues(const EnumDef& enum_def, std::function<void()> cb) {
+ std::function<void(const EnumVal&)> wrapped = [&](const EnumVal& unused) {
(void)unused;
cb();
};
@@ -704,7 +712,7 @@
// an enum string lookup table,
// an enum match function,
// and an enum array of values
- void GenEnum(const EnumDef &enum_def) {
+ void GenEnum(const EnumDef& enum_def) {
const bool is_private = parser_.opts.no_leak_private_annotations &&
(enum_def.attributes.Lookup("private") != nullptr);
code_.SetValue("ACCESS_TYPE", is_private ? "pub(crate)" : "pub");
@@ -712,8 +720,8 @@
code_.SetValue("BASE_TYPE", GetEnumTypeForDecl(enum_def.underlying_type));
code_.SetValue("ENUM_NAMESPACE", namer_.Namespace(enum_def.name));
code_.SetValue("ENUM_CONSTANT", namer_.Constant(enum_def.name));
- const EnumVal *minv = enum_def.MinValue();
- const EnumVal *maxv = enum_def.MaxValue();
+ const EnumVal* minv = enum_def.MinValue();
+ const EnumVal* maxv = enum_def.MaxValue();
FLATBUFFERS_ASSERT(minv && maxv);
code_.SetValue("ENUM_MIN_BASE_VALUE", enum_def.ToString(*minv));
code_.SetValue("ENUM_MAX_BASE_VALUE", enum_def.ToString(*maxv));
@@ -729,7 +737,7 @@
GenComment(enum_def.doc_comment, " ");
code_ += " #[derive(Default, Debug, Clone, Copy, PartialEq)]";
code_ += " {{ACCESS_TYPE}} struct {{ENUM_TY}}: {{BASE_TYPE}} {";
- ForAllEnumValues1(enum_def, [&](const EnumVal &ev) {
+ ForAllEnumValues1(enum_def, [&](const EnumVal& ev) {
this->GenComment(ev.doc_comment, " ");
code_ += " const {{VARIANT}} = {{VALUE}};";
});
@@ -759,7 +767,7 @@
code_ += "#[allow(non_camel_case_types)]";
code_ += "pub const ENUM_VALUES_{{ENUM_CONSTANT}}: [{{ENUM_TY}}; " +
num_fields + "] = [";
- ForAllEnumValues1(enum_def, [&](const EnumVal &ev) {
+ ForAllEnumValues1(enum_def, [&](const EnumVal& ev) {
code_ += namer_.EnumVariant(enum_def, ev) + ",";
});
code_ += "];";
@@ -776,7 +784,7 @@
code_ += "{{ACCESS_TYPE}} struct {{ENUM_TY}}(pub {{BASE_TYPE}});";
code_ += "#[allow(non_upper_case_globals)]";
code_ += "impl {{ENUM_TY}} {";
- ForAllEnumValues1(enum_def, [&](const EnumVal &ev) {
+ ForAllEnumValues1(enum_def, [&](const EnumVal& ev) {
this->GenComment(ev.doc_comment);
code_ += "pub const {{VARIANT}}: Self = Self({{VALUE}});";
});
@@ -841,7 +849,8 @@
code_ += " #[inline]";
code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
code_ +=
- " let b = unsafe { flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf, loc) };";
+ " let b = unsafe { "
+ "flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf, loc) };";
if (IsBitFlagsEnum(enum_def)) {
code_ += " Self::from_bits_retain(b)";
} else {
@@ -898,15 +907,17 @@
code_.SetValue("UNION_TYPE", namer_.Type(enum_def));
code_ += "{{ACCESS_TYPE}} struct {{UNION_TYPE}}UnionTableOffset {}";
code_ += "";
- if (parser_.opts.generate_object_based_api) { GenUnionObject(enum_def); }
+ if (parser_.opts.generate_object_based_api) {
+ GenUnionObject(enum_def);
+ }
}
}
// TODO(cneo): dedup Object versions from non object versions.
- void ForAllUnionObjectVariantsBesidesNone(const EnumDef &enum_def,
+ void ForAllUnionObjectVariantsBesidesNone(const EnumDef& enum_def,
std::function<void()> cb) {
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &enum_val = **it;
+ auto& enum_val = **it;
if (enum_val.union_type.base_type == BASE_TYPE_NONE) continue;
code_.SetValue("VARIANT_NAME", namer_.Variant(enum_val));
// For legacy reasons, enum variants are Keep case while enum native
@@ -921,7 +932,7 @@
code_.DecrementIdentLevel();
}
}
- void GenUnionObject(const EnumDef &enum_def) {
+ void GenUnionObject(const EnumDef& enum_def) {
code_.SetValue("ENUM_TY", namer_.Type(enum_def));
code_.SetValue("ENUM_FN", namer_.Function(enum_def));
code_.SetValue("ENUM_OTY", namer_.ObjectType(enum_def));
@@ -1021,7 +1032,7 @@
}
enum DefaultContext { kBuilder, kAccessor, kObject };
- std::string GetDefaultValue(const FieldDef &field,
+ std::string GetDefaultValue(const FieldDef& field,
const DefaultContext context) {
if (context == kBuilder) {
// Builders and Args structs model nonscalars "optional" even if they're
@@ -1033,7 +1044,9 @@
} else {
// This for defaults in objects.
// Unions have a NONE variant instead of using Rust's None.
- if (field.IsOptional() && !IsUnion(field.value.type)) { return "None"; }
+ if (field.IsOptional() && !IsUnion(field.value.type)) {
+ return "None";
+ }
}
switch (GetFullType(field.value.type)) {
case ftInteger: {
@@ -1116,9 +1129,9 @@
// 2) return a hardcoded value because the relevant vtable field is not in
// the vtable, or
// 3) return a hardcoded value because the vtable field value is set to zero.
- std::string TableBuilderArgsDefnType(const FieldDef &field,
- const std::string &lifetime) {
- const Type &type = field.value.type;
+ std::string TableBuilderArgsDefnType(const FieldDef& field,
+ const std::string& lifetime) {
+ const Type& type = field.value.type;
auto WrapOption = [&](std::string s) {
return IsOptionalToBuilder(field) ? "Option<" + s + ">" : s;
};
@@ -1190,8 +1203,8 @@
return "INVALID_CODE_GENERATION"; // for return analysis
}
- std::string ObjectFieldType(const FieldDef &field, bool in_a_table) {
- const Type &type = field.value.type;
+ std::string ObjectFieldType(const FieldDef& field, bool in_a_table) {
+ const Type& type = field.value.type;
std::string ty;
switch (GetFullType(type)) {
case ftInteger:
@@ -1275,9 +1288,9 @@
}
}
- std::string TableBuilderArgsAddFuncType(const FieldDef &field,
- const std::string &lifetime) {
- const Type &type = field.value.type;
+ std::string TableBuilderArgsAddFuncType(const FieldDef& field,
+ const std::string& lifetime) {
+ const Type& type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftVectorOfStruct: {
@@ -1356,8 +1369,8 @@
return "INVALID_CODE_GENERATION"; // for return analysis
}
- std::string TableBuilderArgsAddFuncBody(const FieldDef &field) {
- const Type &type = field.value.type;
+ std::string TableBuilderArgsAddFuncBody(const FieldDef& field) {
+ const Type& type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftInteger:
@@ -1408,9 +1421,9 @@
return "INVALID_CODE_GENERATION"; // for return analysis
}
- std::string GenTableAccessorFuncReturnType(const FieldDef &field,
- const std::string &lifetime) {
- const Type &type = field.value.type;
+ std::string GenTableAccessorFuncReturnType(const FieldDef& field,
+ const std::string& lifetime) {
+ const Type& type = field.value.type;
const auto WrapOption = [&](std::string s) {
return field.IsOptional() ? "Option<" + s + ">" : s;
};
@@ -1484,7 +1497,7 @@
return "INVALID_CODE_GENERATION"; // for return analysis
}
- std::string FollowType(const Type &type, const std::string &lifetime) {
+ std::string FollowType(const Type& type, const std::string& lifetime) {
// IsVector... This can be made iterative?
const auto WrapForwardsUOffset = [](std::string ty) -> std::string {
@@ -1562,8 +1575,8 @@
return "INVALID_CODE_GENERATION"; // for return analysis
}
- std::string GenTableAccessorFuncBody(const FieldDef &field,
- const std::string &lifetime) {
+ std::string GenTableAccessorFuncBody(const FieldDef& field,
+ const std::string& lifetime) {
const std::string vt_offset = namer_.LegacyRustFieldOffsetName(field);
const std::string typname = FollowType(field.value.type, lifetime);
// Default-y fields (scalars so far) are neither optional nor required.
@@ -1579,8 +1592,8 @@
}
// Generates a fully-qualified name getter for use with --gen-name-strings
- void GenFullyQualifiedNameGetter(const StructDef &struct_def,
- const std::string &name) {
+ void GenFullyQualifiedNameGetter(const StructDef& struct_def,
+ const std::string& name) {
const std::string fully_qualified_name =
struct_def.defined_namespace->GetFullyQualifiedName(name);
code_ += " pub const fn get_fully_qualified_name() -> &'static str {";
@@ -1590,13 +1603,15 @@
}
void ForAllUnionVariantsBesidesNone(
- const EnumDef &def, std::function<void(const EnumVal &ev)> cb) {
+ const EnumDef& def, std::function<void(const EnumVal& ev)> cb) {
FLATBUFFERS_ASSERT(def.is_union);
for (auto it = def.Vals().begin(); it != def.Vals().end(); ++it) {
- const EnumVal &ev = **it;
+ const EnumVal& ev = **it;
// TODO(cneo): Can variants be deprecated, should we skip them?
- if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ if (ev.union_type.base_type == BASE_TYPE_NONE) {
+ continue;
+ }
code_.SetValue(
"U_ELEMENT_ENUM_TYPE",
WrapInNameSpace(def.defined_namespace, namer_.EnumVariant(def, ev)));
@@ -1609,12 +1624,12 @@
}
}
- void ForAllTableFields(const StructDef &struct_def,
- std::function<void(const FieldDef &)> cb,
+ void ForAllTableFields(const StructDef& struct_def,
+ std::function<void(const FieldDef&)> cb,
bool reversed = false) {
// TODO(cneo): Remove `reversed` overload. It's only here to minimize the
// diff when refactoring to the `ForAllX` helper functions.
- auto go = [&](const FieldDef &field) {
+ auto go = [&](const FieldDef& field) {
if (field.deprecated) return;
code_.SetValue("OFFSET_NAME", namer_.LegacyRustFieldOffsetName(field));
code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset));
@@ -1625,7 +1640,7 @@
cb(field);
code_.DecrementIdentLevel();
};
- const auto &fields = struct_def.fields.vec;
+ const auto& fields = struct_def.fields.vec;
if (reversed) {
for (auto it = fields.rbegin(); it != fields.rend(); ++it) go(**it);
} else {
@@ -1634,7 +1649,7 @@
}
// Generate an accessor struct, builder struct, and create function for a
// table.
- void GenTable(const StructDef &struct_def) {
+ void GenTable(const StructDef& struct_def) {
const bool is_private =
parser_.opts.no_leak_private_annotations &&
(struct_def.attributes.Lookup("private") != nullptr);
@@ -1665,7 +1680,7 @@
code_ += "impl<'a> {{STRUCT_TY}}<'a> {";
// Generate field id constants.
- ForAllTableFields(struct_def, [&](const FieldDef &unused) {
+ ForAllTableFields(struct_def, [&](const FieldDef& unused) {
(void)unused;
code_ +=
"pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = "
@@ -1703,7 +1718,7 @@
size; size /= 2) {
ForAllTableFields(
struct_def,
- [&](const FieldDef &field) {
+ [&](const FieldDef& field) {
if (struct_def.sortbysize &&
size != SizeOf(field.value.type.base_type))
return;
@@ -1726,8 +1741,8 @@
// TODO(cneo): Manage indentation with IncrementIdentLevel?
code_.SetValue("STRUCT_OTY", namer_.ObjectType(struct_def));
code_ += " pub fn unpack(&self) -> {{STRUCT_OTY}} {";
- ForAllObjectTableFields(struct_def, [&](const FieldDef &field) {
- const Type &type = field.value.type;
+ ForAllObjectTableFields(struct_def, [&](const FieldDef& field) {
+ const Type& type = field.value.type;
switch (GetFullType(type)) {
case ftInteger:
case ftBool:
@@ -1736,9 +1751,10 @@
code_ += " let {{FIELD}} = self.{{FIELD}}();";
return;
}
- case ftUnionKey: return;
+ case ftUnionKey:
+ return;
case ftUnionValue: {
- const auto &enum_def = *type.enum_def;
+ const auto& enum_def = *type.enum_def;
code_.SetValue("ENUM_TY", WrapInNameSpace(enum_def));
code_.SetValue("NATIVE_ENUM_NAME", NamespacedNativeName(enum_def));
code_.SetValue("UNION_TYPE_METHOD",
@@ -1816,7 +1832,7 @@
}
});
code_ += " {{STRUCT_OTY}} {";
- ForAllObjectTableFields(struct_def, [&](const FieldDef &field) {
+ ForAllObjectTableFields(struct_def, [&](const FieldDef& field) {
if (field.value.type.base_type == BASE_TYPE_UTYPE) return;
code_ += " {{FIELD}},";
});
@@ -1837,7 +1853,7 @@
// pub fn name(&'a self) -> user_facing_type {
// self._tab.get::<internal_type>(offset, defaultval).unwrap()
// }
- ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ ForAllTableFields(struct_def, [&](const FieldDef& field) {
code_.SetValue("RETURN_TYPE",
GenTableAccessorFuncReturnType(field, "'a"));
@@ -1851,7 +1867,9 @@
code_ += "}";
// Generate a comparison function for this field if it is a key.
- if (field.key) { GenKeyFieldMethods(field); }
+ if (field.key) {
+ GenKeyFieldMethods(field);
+ }
// Generate a nested flatbuffer field, if applicable.
auto nested = field.attributes.Lookup("nested_flatbuffer");
@@ -1894,10 +1912,10 @@
});
// Explicit specializations for union accessors
- ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ ForAllTableFields(struct_def, [&](const FieldDef& field) {
if (field.value.type.base_type != BASE_TYPE_UNION) return;
ForAllUnionVariantsBesidesNone(
- *field.value.type.enum_def, [&](const EnumVal &unused) {
+ *field.value.type.enum_def, [&](const EnumVal& unused) {
(void)unused;
code_ += "#[inline]";
code_ += "#[allow(non_snake_case)]";
@@ -1958,7 +1976,7 @@
code_ += " v.visit_table(pos)?\\";
// Escape newline and insert it onthe next line so we can end the builder
// with a nice semicolon.
- ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ ForAllTableFields(struct_def, [&](const FieldDef& field) {
if (GetFullType(field.value.type) == ftUnionKey) return;
code_.SetValue("IS_REQ", field.IsRequired() ? "true" : "false");
@@ -1971,7 +1989,7 @@
return;
}
// Unions.
- const EnumDef &union_def = *field.value.type.enum_def;
+ const EnumDef& union_def = *field.value.type.enum_def;
code_.SetValue("UNION_TYPE", WrapInNameSpace(union_def));
code_.SetValue("UNION_TYPE_OFFSET_NAME",
namer_.LegacyRustUnionTypeOffsetName(field));
@@ -1983,7 +2001,7 @@
"\"{{FIELD}}\", Self::{{OFFSET_NAME}}, {{IS_REQ}}, "
"|key, v, pos| {";
code_ += " match key {";
- ForAllUnionVariantsBesidesNone(union_def, [&](const EnumVal &unused) {
+ ForAllUnionVariantsBesidesNone(union_def, [&](const EnumVal& unused) {
(void)unused;
code_ +=
" {{U_ELEMENT_ENUM_TYPE}} => v.verify_union_variant::"
@@ -2003,7 +2021,7 @@
code_.SetValue("MAYBE_LT",
TableBuilderArgsNeedsLifetime(struct_def) ? "<'a>" : "");
code_ += "{{ACCESS_TYPE}} struct {{STRUCT_TY}}Args{{MAYBE_LT}} {";
- ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ ForAllTableFields(struct_def, [&](const FieldDef& field) {
code_.SetValue("PARAM_TYPE", TableBuilderArgsDefnType(field, "'a"));
code_ += " pub {{FIELD}}: {{PARAM_TYPE}},";
});
@@ -2014,7 +2032,7 @@
code_ += " #[inline]";
code_ += " fn default() -> Self {";
code_ += " {{STRUCT_TY}}Args {";
- ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ ForAllTableFields(struct_def, [&](const FieldDef& field) {
code_ += " {{FIELD}}: {{BLDR_DEF_VAL}},\\";
code_ += field.IsRequired() ? " // required field" : "";
});
@@ -2041,11 +2059,11 @@
" let mut s = serializer.serialize_struct(\"{{STRUCT_TY}}\", "
"{{NUM_FIELDS}})?;";
}
- ForAllTableFields(struct_def, [&](const FieldDef &field) {
- const Type &type = field.value.type;
+ ForAllTableFields(struct_def, [&](const FieldDef& field) {
+ const Type& type = field.value.type;
if (IsUnion(type)) {
if (type.base_type == BASE_TYPE_UNION) {
- const auto &enum_def = *type.enum_def;
+ const auto& enum_def = *type.enum_def;
code_.SetValue("ENUM_TY", WrapInNameSpace(enum_def));
code_.SetValue("FIELD", namer_.Field(field));
code_.SetValue("UNION_TYPE_METHOD",
@@ -2107,7 +2125,7 @@
"impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> "
"{{STRUCT_TY}}Builder<'a, "
"'b, A> {";
- ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ ForAllTableFields(struct_def, [&](const FieldDef& field) {
const bool is_scalar = IsScalar(field.value.type.base_type);
std::string offset = namer_.LegacyRustFieldOffsetName(field);
// Generate functions to add data, which take one of two forms.
@@ -2158,7 +2176,7 @@
"flatbuffers::WIPOffset<{{STRUCT_TY}}<'a>> {";
code_ += " let o = self.fbb_.end_table(self.start_);";
- ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ ForAllTableFields(struct_def, [&](const FieldDef& field) {
if (!field.IsRequired()) return;
code_ +=
" self.fbb_.required(o, {{STRUCT_TY}}::{{OFFSET_NAME}},"
@@ -2174,7 +2192,7 @@
" fn fmt(&self, f: &mut core::fmt::Formatter<'_>"
") -> core::fmt::Result {";
code_ += " let mut ds = f.debug_struct(\"{{STRUCT_TY}}\");";
- ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ ForAllTableFields(struct_def, [&](const FieldDef& field) {
if (GetFullType(field.value.type) == ftUnionValue) {
// Generate a match statement to handle unions properly.
code_.SetValue("KEY_TYPE", GenTableAccessorFuncReturnType(field, ""));
@@ -2184,7 +2202,7 @@
code_ += " match self.{{DISCRIMINANT}}() {";
ForAllUnionVariantsBesidesNone(
- *field.value.type.enum_def, [&](const EnumVal &unused) {
+ *field.value.type.enum_def, [&](const EnumVal& unused) {
(void)unused;
code_ += " {{U_ELEMENT_ENUM_TYPE}} => {";
code_ +=
@@ -2212,7 +2230,7 @@
code_ += "}";
}
- void GenTableObject(const StructDef &table) {
+ void GenTableObject(const StructDef& table) {
code_.SetValue("STRUCT_OTY", namer_.ObjectType(table));
code_.SetValue("STRUCT_TY", namer_.Type(table));
@@ -2220,7 +2238,7 @@
code_ += "#[non_exhaustive]";
code_ += "#[derive(Debug, Clone, PartialEq)]";
code_ += "{{ACCESS_TYPE}} struct {{STRUCT_OTY}} {";
- ForAllObjectTableFields(table, [&](const FieldDef &field) {
+ ForAllObjectTableFields(table, [&](const FieldDef& field) {
// Union objects combine both the union discriminant and value, so we
// skip making a field for the discriminant.
if (field.value.type.base_type == BASE_TYPE_UTYPE) return;
@@ -2231,7 +2249,7 @@
code_ += "impl Default for {{STRUCT_OTY}} {";
code_ += " fn default() -> Self {";
code_ += " Self {";
- ForAllObjectTableFields(table, [&](const FieldDef &field) {
+ ForAllObjectTableFields(table, [&](const FieldDef& field) {
if (field.value.type.base_type == BASE_TYPE_UTYPE) return;
std::string default_value = GetDefaultValue(field, kObject);
code_ += " {{FIELD}}: " + default_value + ",";
@@ -2251,8 +2269,8 @@
code_ += " ) -> flatbuffers::WIPOffset<{{STRUCT_TY}}<'b>> {";
// First we generate variables for each field and then later assemble them
// using "StructArgs" to more easily manage ownership of the builder.
- ForAllObjectTableFields(table, [&](const FieldDef &field) {
- const Type &type = field.value.type;
+ ForAllObjectTableFields(table, [&](const FieldDef& field) {
+ const Type& type = field.value.type;
switch (GetFullType(type)) {
case ftInteger:
case ftBool:
@@ -2261,7 +2279,8 @@
code_ += " let {{FIELD}} = self.{{FIELD}};";
return;
}
- case ftUnionKey: return; // Generate union type with union value.
+ case ftUnionKey:
+ return; // Generate union type with union value.
case ftUnionValue: {
code_.SetValue("ENUM_METHOD",
namer_.Method(*field.value.type.enum_def));
@@ -2340,7 +2359,7 @@
}
});
code_ += " {{STRUCT_TY}}::create(_fbb, &{{STRUCT_TY}}Args{";
- ForAllObjectTableFields(table, [&](const FieldDef &field) {
+ ForAllObjectTableFields(table, [&](const FieldDef& field) {
(void)field; // Unused.
code_ += " {{FIELD}},";
});
@@ -2348,11 +2367,11 @@
code_ += " }";
code_ += "}";
}
- void ForAllObjectTableFields(const StructDef &table,
- std::function<void(const FieldDef &)> cb) {
- const std::vector<FieldDef *> &v = table.fields.vec;
+ void ForAllObjectTableFields(const StructDef& table,
+ std::function<void(const FieldDef&)> cb) {
+ const std::vector<FieldDef*>& v = table.fields.vec;
for (auto it = v.begin(); it != v.end(); it++) {
- const FieldDef &field = **it;
+ const FieldDef& field = **it;
if (field.deprecated) continue;
code_.SetValue("FIELD", namer_.Field(field));
code_.SetValue("FIELD_OTY", ObjectFieldType(field, true));
@@ -2361,7 +2380,7 @@
code_.DecrementIdentLevel();
}
}
- void MapNativeTableField(const FieldDef &field, const std::string &expr) {
+ void MapNativeTableField(const FieldDef& field, const std::string& expr) {
if (field.IsOptional()) {
code_ += " let {{FIELD}} = self.{{FIELD}}.as_ref().map(|x|{";
code_ += " " + expr;
@@ -2378,7 +2397,7 @@
// Generate functions to compare tables and structs by key. This function
// must only be called if the field key is defined.
- void GenKeyFieldMethods(const FieldDef &field) {
+ void GenKeyFieldMethods(const FieldDef& field) {
FLATBUFFERS_ASSERT(field.key);
code_.SetValue("KEY_TYPE", GenTableAccessorFuncReturnType(field, ""));
@@ -2402,7 +2421,7 @@
// Generate functions for accessing the root table object. This function
// must only be called if the root table is defined.
- void GenRootTableFuncs(const StructDef &struct_def) {
+ void GenRootTableFuncs(const StructDef& struct_def) {
FLATBUFFERS_ASSERT(parser_.root_struct_def_ && "root table not defined");
code_.SetValue("STRUCT_TY", namer_.Type(struct_def));
code_.SetValue("STRUCT_FN", namer_.Function(struct_def));
@@ -2561,8 +2580,8 @@
}
static void GenPadding(
- const FieldDef &field, std::string *code_ptr, int *id,
- const std::function<void(int bits, std::string *code_ptr, int *id)> &f) {
+ const FieldDef& field, std::string* code_ptr, int* id,
+ const std::function<void(int bits, std::string* code_ptr, int* id)>& f) {
if (field.padding) {
for (int i = 0; i < 4; i++) {
if (static_cast<int>(field.padding) & (1 << i)) {
@@ -2573,22 +2592,22 @@
}
}
- static void PaddingDefinition(int bits, std::string *code_ptr, int *id) {
+ static void PaddingDefinition(int bits, std::string* code_ptr, int* id) {
*code_ptr +=
" padding" + NumToString((*id)++) + "__: u" + NumToString(bits) + ",";
}
- static void PaddingInitializer(int bits, std::string *code_ptr, int *id) {
+ static void PaddingInitializer(int bits, std::string* code_ptr, int* id) {
(void)bits;
*code_ptr += "padding" + NumToString((*id)++) + "__: 0,";
}
- void ForAllStructFields(const StructDef &struct_def,
- std::function<void(const FieldDef &field)> cb) {
+ void ForAllStructFields(const StructDef& struct_def,
+ std::function<void(const FieldDef& field)> cb) {
size_t offset_to_field = 0;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
code_.SetValue("FIELD_TYPE", GetTypeGet(field.value.type));
code_.SetValue("FIELD_OTY", ObjectFieldType(field, false));
code_.SetValue("FIELD", namer_.Field(field));
@@ -2604,7 +2623,7 @@
}
}
// Generate an accessor struct with constructor for a flatbuffers struct.
- void GenStruct(const StructDef &struct_def) {
+ void GenStruct(const StructDef& struct_def) {
const bool is_private =
parser_.opts.no_leak_private_annotations &&
(struct_def.attributes.Lookup("private") != nullptr);
@@ -2639,7 +2658,7 @@
" fn fmt(&self, f: &mut core::fmt::Formatter"
") -> core::fmt::Result {";
code_ += " f.debug_struct(\"{{STRUCT_TY}}\")";
- ForAllStructFields(struct_def, [&](const FieldDef &unused) {
+ ForAllStructFields(struct_def, [&](const FieldDef& unused) {
(void)unused;
code_ += " .field(\"{{FIELD}}\", &self.{{FIELD}}())";
});
@@ -2663,7 +2682,9 @@
code_ += " type Inner = &'a {{STRUCT_TY}};";
code_ += " #[inline]";
code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
- code_ += " unsafe { flatbuffers::follow_cast_ref::<{{STRUCT_TY}}>(buf, loc) }";
+ code_ +=
+ " unsafe { flatbuffers::follow_cast_ref::<{{STRUCT_TY}}>(buf, loc) "
+ "}";
code_ += " }";
code_ += "}";
code_ += "impl<'b> flatbuffers::Push for {{STRUCT_TY}} {";
@@ -2671,7 +2692,8 @@
code_ += " #[inline]";
code_ += " unsafe fn push(&self, dst: &mut [u8], _written_len: usize) {";
code_ +=
- " let src = unsafe { ::core::slice::from_raw_parts(self as *const "
+ " let src = unsafe { ::core::slice::from_raw_parts(self as "
+ "*const "
"{{STRUCT_TY}} as *const u8, <Self as flatbuffers::Push>::size()) };";
code_ += " dst.copy_from_slice(src);";
code_ += " }";
@@ -2713,7 +2735,7 @@
" let mut s = serializer.serialize_struct(\"{{STRUCT_TY}}\", "
"{{NUM_FIELDS}})?;";
}
- ForAllStructFields(struct_def, [&](const FieldDef &unused) {
+ ForAllStructFields(struct_def, [&](const FieldDef& unused) {
(void)unused;
code_ +=
" s.serialize_field(\"{{FIELD}}\", "
@@ -2729,13 +2751,13 @@
code_ += "impl<'a> {{STRUCT_TY}} {";
code_ += " #[allow(clippy::too_many_arguments)]";
code_ += " pub fn new(";
- ForAllStructFields(struct_def, [&](const FieldDef &unused) {
+ ForAllStructFields(struct_def, [&](const FieldDef& unused) {
(void)unused;
code_ += " {{FIELD}}: {{REF}}{{FIELD_TYPE}},";
});
code_ += " ) -> Self {";
code_ += " let mut s = Self([0; {{STRUCT_SIZE}}]);";
- ForAllStructFields(struct_def, [&](const FieldDef &unused) {
+ ForAllStructFields(struct_def, [&](const FieldDef& unused) {
(void)unused;
code_ += " s.set_{{FIELD}}({{FIELD}});";
});
@@ -2748,7 +2770,7 @@
}
// Generate accessor methods for the struct.
- ForAllStructFields(struct_def, [&](const FieldDef &field) {
+ ForAllStructFields(struct_def, [&](const FieldDef& field) {
this->GenComment(field.doc_comment);
// Getter.
if (IsStruct(field.value.type)) {
@@ -2851,7 +2873,9 @@
code_ += "}\n";
// Generate a comparison function for this field if it is a key.
- if (field.key) { GenKeyFieldMethods(field); }
+ if (field.key) {
+ GenKeyFieldMethods(field);
+ }
});
// Generate Object API unpack method.
@@ -2859,7 +2883,7 @@
code_.SetValue("STRUCT_OTY", namer_.ObjectType(struct_def));
code_ += " pub fn unpack(&self) -> {{STRUCT_OTY}} {";
code_ += " {{STRUCT_OTY}} {";
- ForAllStructFields(struct_def, [&](const FieldDef &field) {
+ ForAllStructFields(struct_def, [&](const FieldDef& field) {
if (IsArray(field.value.type)) {
if (GetFullType(field.value.type) == ftArrayOfStruct) {
code_ +=
@@ -2886,7 +2910,7 @@
// Struct declaration
code_ += "#[derive(Debug, Clone, PartialEq, Default)]";
code_ += "{{ACCESS_TYPE}} struct {{STRUCT_OTY}} {";
- ForAllStructFields(struct_def, [&](const FieldDef &field) {
+ ForAllStructFields(struct_def, [&](const FieldDef& field) {
(void)field; // unused.
code_ += "pub {{FIELD}}: {{FIELD_OTY}},";
});
@@ -2896,7 +2920,7 @@
code_ += "impl {{STRUCT_OTY}} {";
code_ += " pub fn pack(&self) -> {{STRUCT_TY}} {";
code_ += " {{STRUCT_TY}}::new(";
- ForAllStructFields(struct_def, [&](const FieldDef &field) {
+ ForAllStructFields(struct_def, [&](const FieldDef& field) {
if (IsStruct(field.value.type)) {
code_ += " &self.{{FIELD}}.pack(),";
} else if (IsArray(field.value.type)) {
@@ -2963,8 +2987,10 @@
//
// The file must start and end with an empty (or null) namespace so that
// namespaces are properly opened and closed.
- void SetNameSpace(const Namespace *ns) {
- if (cur_name_space_ == ns) { return; }
+ void SetNameSpace(const Namespace* ns) {
+ if (cur_name_space_ == ns) {
+ return;
+ }
// Compute the size of the longest common namespace prefix.
// If cur_name_space is A::B::C::D and ns is A::B::E::F::G,
@@ -2985,7 +3011,9 @@
for (size_t j = old_size; j > common_prefix_size; --j) {
code_ += "} // pub mod " + cur_name_space_->components[j - 1];
}
- if (old_size != common_prefix_size) { code_ += ""; }
+ if (old_size != common_prefix_size) {
+ code_ += "";
+ }
// open namespace parts to reach the ns namespace
// in the previous example, E, then F, then G are opened
@@ -2995,7 +3023,9 @@
// Generate local namespace imports.
GenNamespaceImports(2);
}
- if (new_size != common_prefix_size) { code_ += ""; }
+ if (new_size != common_prefix_size) {
+ code_ += "";
+ }
cur_name_space_ = ns;
}
@@ -3006,14 +3036,14 @@
} // namespace rust
-static bool GenerateRust(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateRust(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
rust::RustGenerator generator(parser, path, file_name);
return generator.generate();
}
-static std::string RustMakeRule(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static std::string RustMakeRule(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
rust::RustGenerator generator(parser, path, file_name);
@@ -3031,35 +3061,38 @@
class RustCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateRust(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateRust(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
output = RustMakeRule(parser, path, filename);
return Status::OK;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
- if (!GenerateRustModuleRootFile(parser, path)) { return Status::ERROR; }
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
+ if (!GenerateRustModuleRootFile(parser, path)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
diff --git a/src/idl_gen_swift.cpp b/src/idl_gen_swift.cpp
index b061b30..e737ef3 100644
--- a/src/idl_gen_swift.cpp
+++ b/src/idl_gen_swift.cpp
@@ -32,117 +32,117 @@
namespace {
static Namer::Config SwiftDefaultConfig() {
- return { /*types=*/Case::kKeep,
- /*constants=*/Case::kLowerCamel,
- /*methods=*/Case::kLowerCamel,
- /*functions=*/Case::kLowerCamel,
- /*fields=*/Case::kLowerCamel,
- /*variables=*/Case::kLowerCamel,
- /*variants=*/Case::kLowerCamel,
- /*enum_variant_seperator=*/".",
- /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
- /*namespaces=*/Case::kKeep,
- /*namespace_seperator=*/"_",
- /*object_prefix=*/"",
- /*object_suffix=*/"T",
- /*keyword_prefix=*/"",
- /*keyword_suffix=*/"_",
- /*filenames=*/Case::kKeep,
- /*directories=*/Case::kKeep,
- /*output_path=*/"",
- /*filename_suffix=*/"_generated",
- /*filename_extension=*/".swift" };
+ return {/*types=*/Case::kKeep,
+ /*constants=*/Case::kLowerCamel,
+ /*methods=*/Case::kLowerCamel,
+ /*functions=*/Case::kLowerCamel,
+ /*fields=*/Case::kLowerCamel,
+ /*variables=*/Case::kLowerCamel,
+ /*variants=*/Case::kLowerCamel,
+ /*enum_variant_seperator=*/".",
+ /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
+ /*namespaces=*/Case::kKeep,
+ /*namespace_seperator=*/"_",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kKeep,
+ /*directories=*/Case::kKeep,
+ /*output_path=*/"",
+ /*filename_suffix=*/"_generated",
+ /*filename_extension=*/".swift"};
}
static std::set<std::string> SwiftKeywords() {
return {
- "associatedtype",
- "class",
- "deinit",
- "enum",
- "extension",
- "fileprivate",
- "func",
- "import",
- "init",
- "inout",
- "internal",
- "let",
- "open",
- "operator",
- "private",
- "protocol",
- "public",
- "rethrows",
- "static",
- "struct",
- "subscript",
- "typealias",
- "var",
- "break",
- "case",
- "continue",
- "default",
- "defer",
- "do",
- "else",
- "fallthrough",
- "for",
- "guard",
- "if",
- "in",
- "repeat",
- "return",
- "switch",
- "where",
- "while",
- "Any",
- "catch",
- "false",
- "is",
- "nil",
- "super",
- "self",
- "Self",
- "throw",
- "throws",
- "true",
- "try",
- "associativity",
- "convenience",
- "dynamic",
- "didSet",
- "final",
- "get",
- "infix",
- "indirect",
- "lazy",
- "left",
- "mutating",
- "none",
- "nonmutating",
- "optional",
- "override",
- "postfix",
- "precedence",
- "prefix",
- "Protocol",
- "required",
- "right",
- "set",
- "Type",
- "unowned",
- "weak",
- "willSet",
- "Void",
+ "associatedtype",
+ "class",
+ "deinit",
+ "enum",
+ "extension",
+ "fileprivate",
+ "func",
+ "import",
+ "init",
+ "inout",
+ "internal",
+ "let",
+ "open",
+ "operator",
+ "private",
+ "protocol",
+ "public",
+ "rethrows",
+ "static",
+ "struct",
+ "subscript",
+ "typealias",
+ "var",
+ "break",
+ "case",
+ "continue",
+ "default",
+ "defer",
+ "do",
+ "else",
+ "fallthrough",
+ "for",
+ "guard",
+ "if",
+ "in",
+ "repeat",
+ "return",
+ "switch",
+ "where",
+ "while",
+ "Any",
+ "catch",
+ "false",
+ "is",
+ "nil",
+ "super",
+ "self",
+ "Self",
+ "throw",
+ "throws",
+ "true",
+ "try",
+ "associativity",
+ "convenience",
+ "dynamic",
+ "didSet",
+ "final",
+ "get",
+ "infix",
+ "indirect",
+ "lazy",
+ "left",
+ "mutating",
+ "none",
+ "nonmutating",
+ "optional",
+ "override",
+ "postfix",
+ "precedence",
+ "prefix",
+ "Protocol",
+ "required",
+ "right",
+ "set",
+ "Type",
+ "unowned",
+ "weak",
+ "willSet",
+ "Void",
};
}
-static std::string GenIndirect(const std::string &reading) {
+static std::string GenIndirect(const std::string& reading) {
return "{{ACCESS}}.indirect(" + reading + ")";
}
-static std::string GenArrayMainBody(const std::string &optional) {
+static std::string GenArrayMainBody(const std::string& optional) {
return "{{ACCESS_TYPE}} func {{FIELDMETHOD}}(at index: Int32) -> "
"{{VALUETYPE}}" +
optional + " { ";
@@ -157,8 +157,8 @@
int namespace_depth;
public:
- SwiftGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ SwiftGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", "_", "swift"),
namer_(WithFlagOptions(SwiftDefaultConfig(), parser.opts, path),
SwiftKeywords()) {
@@ -174,7 +174,9 @@
code_ += "// swiftlint:disable all";
code_ += "// swiftformat:disable all\n";
if (parser_.opts.include_dependence_headers || parser_.opts.generate_all) {
- code_.SetValue("IMPLEMENTONLY", parser_.opts.swift_implementation_only ? "@_implementationOnly " : "");
+ code_.SetValue("IMPLEMENTONLY", parser_.opts.swift_implementation_only
+ ? "@_implementationOnly "
+ : "");
code_ += "#if canImport(Common)";
code_ += "{{IMPLEMENTONLY}}import Common";
code_ += "#endif";
@@ -185,13 +187,15 @@
// Generate code for all the enum declarations.
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
- const auto &enum_def = **it;
- if (!enum_def.generated) { GenEnum(enum_def); }
+ const auto& enum_def = **it;
+ if (!enum_def.generated) {
+ GenEnum(enum_def);
+ }
}
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
- const auto &struct_def = **it;
+ const auto& struct_def = **it;
if (struct_def.fixed && !struct_def.generated) {
GenStructReader(struct_def);
GenMutableStructReader(struct_def);
@@ -200,7 +204,7 @@
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
- const auto &struct_def = **it;
+ const auto& struct_def = **it;
if (!struct_def.fixed && !struct_def.generated) {
GenTable(struct_def);
if (parser_.opts.generate_object_based_api) {
@@ -214,7 +218,7 @@
return SaveFile(filename.c_str(), final_code, false);
}
- void mark(const std::string &str) {
+ void mark(const std::string& str) {
code_.SetValue("MARKVALUE", str);
code_ += "\n// MARK: - {{MARKVALUE}}\n";
}
@@ -222,7 +226,7 @@
// MARK: - Generating structs
// Generates the reader for swift
- void GenStructReader(const StructDef &struct_def) {
+ void GenStructReader(const StructDef& struct_def) {
const bool is_private_access =
parser_.opts.swift_implementation_only ||
struct_def.attributes.Lookup("private") != nullptr;
@@ -245,7 +249,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
if (!constructor.empty()) constructor += ", ";
@@ -269,7 +273,9 @@
accessing_value);
base_constructor.push_back("_" + field_var + " = " + base_value);
- if (field.padding) { GenPadding(field, &padding_id); }
+ if (field.padding) {
+ GenPadding(field, &padding_id);
+ }
constructor += field_var + ": " + type;
}
code_ += "";
@@ -282,7 +288,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
code_.SetValue("FIELDVAR", namer_.Variable(field));
code_.SetValue("VALUETYPE", GenType(field.value.type));
@@ -309,13 +315,13 @@
if (parser_.opts.gen_json_coders) GenerateJSONEncodingAPIs(struct_def);
}
- void BuildStructConstructor(const StructDef &struct_def) {
+ void BuildStructConstructor(const StructDef& struct_def) {
code_ += "{{ACCESS_TYPE}} init(_ bb: ByteBuffer, o: Int32) {";
Indent();
code_ += "let {{ACCESS}} = Struct(bb: bb, position: o)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
const auto type = field.value.type;
code_.SetValue("FIELDVAR", namer_.Variable(field));
@@ -337,12 +343,12 @@
code_ += "}\n";
}
- void GenMutableStructReader(const StructDef &struct_def) {
+ void GenMutableStructReader(const StructDef& struct_def) {
GenObjectHeader(struct_def);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
const auto offset = NumToString(field.value.offset);
const auto type = GenType(field.value.type);
@@ -379,17 +385,17 @@
code_ += "}\n";
}
- void GenerateStructArgs(const StructDef &struct_def, std::string *code_ptr,
- const std::string &nameprefix,
- const std::string &object_name,
- const std::string &obj_api_named = "",
+ void GenerateStructArgs(const StructDef& struct_def, std::string* code_ptr,
+ const std::string& nameprefix,
+ const std::string& object_name,
+ const std::string& obj_api_named = "",
bool is_obj_api = false) {
- auto &code = *code_ptr;
+ auto& code = *code_ptr;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
- const auto &field_type = field.value.type;
+ const auto& field_type = field.value.type;
if (IsStruct(field.value.type)) {
GenerateStructArgs(
*field_type.struct_def, code_ptr, (nameprefix + field.name),
@@ -417,7 +423,7 @@
// MARK: - Table Generator
// Generates the reader for swift
- void GenTable(const StructDef &struct_def) {
+ void GenTable(const StructDef& struct_def) {
const bool is_private_access =
parser_.opts.swift_implementation_only ||
struct_def.attributes.Lookup("private") != nullptr;
@@ -436,15 +442,17 @@
}
// Generates the reader for swift
- void GenTableAccessors(const StructDef &struct_def) {
+ void GenTableAccessors(const StructDef& struct_def) {
// Generate field id constants.
if (struct_def.fields.vec.size() > 0) {
code_ += "private enum {{TABLEOFFSET}}: VOffset {";
Indent();
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (field.deprecated) { continue; }
+ const auto& field = **it;
+ if (field.deprecated) {
+ continue;
+ }
code_.SetValue("OFFSET_NAME", namer_.Variable(field));
code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset));
code_ += "case {{OFFSET_NAME}} = {{OFFSET_VALUE}}";
@@ -457,7 +465,7 @@
}
}
- void GenObjectHeader(const StructDef &struct_def) {
+ void GenObjectHeader(const StructDef& struct_def) {
GenComment(struct_def.doc_comment);
code_.SetValue("SHORT_STRUCTNAME", namer_.Type(struct_def));
@@ -495,8 +503,8 @@
code_ += "";
}
- void GenTableWriter(const StructDef &struct_def) {
- flatbuffers::FieldDef *key_field = nullptr;
+ void GenTableWriter(const StructDef& struct_def) {
+ flatbuffers::FieldDef* key_field = nullptr;
std::vector<std::string> require_fields;
std::vector<std::string> create_func_body;
std::vector<std::string> create_func_header;
@@ -510,7 +518,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
if (field.key) key_field = &field;
if (field.IsRequired())
@@ -568,11 +576,10 @@
"_ fbb: inout FlatBufferBuilder) -> Offset {";
Indent();
code_ += spacing + "var off = offsets";
- code_ +=
- spacing +
- "off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: "
- "{{VOFFSET}}, fbb: &fbb), Table.offset(Int32($0.o), vOffset: "
- "{{VOFFSET}}, fbb: &fbb), fbb: &fbb) < 0 } ";
+ code_ += spacing +
+ "off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: "
+ "{{VOFFSET}}, fbb: &fbb), Table.offset(Int32($0.o), vOffset: "
+ "{{VOFFSET}}, fbb: &fbb), fbb: &fbb) < 0 } ";
code_ += spacing + "return fbb.createVector(ofOffsets: off)";
Outdent();
code_ += "}";
@@ -580,12 +587,12 @@
}
}
- void GenTableWriterFields(const FieldDef &field,
- std::vector<std::string> *create_body,
- std::vector<std::string> *create_header) {
+ void GenTableWriterFields(const FieldDef& field,
+ std::vector<std::string>* create_body,
+ std::vector<std::string>* create_header) {
std::string builder_string = ", _ fbb: inout FlatBufferBuilder) { ";
- auto &create_func_body = *create_body;
- auto &create_func_header = *create_header;
+ auto& create_func_body = *create_body;
+ auto& create_func_header = *create_header;
const auto field_field = namer_.Field(field);
const auto field_var = namer_.Variable(field);
const auto type = GenType(field.value.type);
@@ -687,16 +694,16 @@
}
}
- void GenTableReader(const StructDef &struct_def) {
+ void GenTableReader(const StructDef& struct_def) {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
GenTableReaderFields(field);
}
}
- void GenTableReaderFields(const FieldDef &field) {
+ void GenTableReaderFields(const FieldDef& field) {
const auto offset = NumToString(field.value.offset);
const auto field_field = namer_.Field(field);
const auto type = GenType(field.value.type);
@@ -780,8 +787,11 @@
"{{ACCESS}}.getVector(at: {{TABLEOFFSET}}.{{OFFSET}}.v) }";
break;
}
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
- case BASE_TYPE_VECTOR: GenTableReaderVectorFields(field); break;
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_VECTOR:
+ GenTableReaderVectorFields(field);
+ break;
case BASE_TYPE_UNION:
code_.SetValue("CONSTANT", "nil");
code_ +=
@@ -791,11 +801,12 @@
is_required + " { " + GenOffset() + required_reader +
"{{ACCESS}}.union(o) }";
break;
- default: FLATBUFFERS_ASSERT(0);
+ default:
+ FLATBUFFERS_ASSERT(0);
}
}
- void GenTableReaderVectorFields(const FieldDef &field) {
+ void GenTableReaderVectorFields(const FieldDef& field) {
std::string const_string = "return o == 0 ? {{CONSTANT}} : ";
const auto vectortype = field.value.type.VectorType();
code_.SetValue("SIZE", NumToString(InlineSize(vectortype)));
@@ -879,10 +890,10 @@
code_ += GenConstructor(
"{{ACCESS}}.indirect({{ACCESS}}.vector(at: o) + index * "
"{{SIZE}})");
- const auto &sd = *field.value.type.struct_def;
- const auto &fields = sd.fields.vec;
+ const auto& sd = *field.value.type.struct_def;
+ const auto& fields = sd.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
- const auto &key_field = **kit;
+ const auto& key_field = **kit;
if (key_field.key) {
GenByKeyFunctions(key_field);
break;
@@ -891,7 +902,7 @@
}
}
- void GenUnsafeBufferPointer(const FieldDef &field) {
+ void GenUnsafeBufferPointer(const FieldDef& field) {
code_.SetValue("functionName",
namer_.Variable("withUnsafePointerTo", field));
code_ +=
@@ -901,12 +912,12 @@
"body: body) }";
}
- void GenerateCodingKeys(const StructDef &struct_def) {
+ void GenerateCodingKeys(const StructDef& struct_def) {
code_ += "enum CodingKeys: String, CodingKey {";
Indent();
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
code_.SetValue("RAWVALUENAME", field.name);
@@ -917,8 +928,8 @@
code_ += "}";
}
- void GenerateEncoderUnionBody(const FieldDef &field) {
- EnumDef &union_def = *field.value.type.enum_def;
+ void GenerateEncoderUnionBody(const FieldDef& field) {
+ EnumDef& union_def = *field.value.type.enum_def;
const auto is_vector = field.value.type.base_type == BASE_TYPE_VECTOR ||
field.value.type.base_type == BASE_TYPE_ARRAY;
if (field.value.type.base_type == BASE_TYPE_UTYPE ||
@@ -939,11 +950,13 @@
code_ += "switch type {";
for (auto it = union_def.Vals().begin(); it != union_def.Vals().end();
++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
const auto type = GenType(ev.union_type);
code_.SetValue("KEY", namer_.LegacySwiftVariant(ev));
code_.SetValue("VALUETYPE", type);
- if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ if (ev.union_type.base_type == BASE_TYPE_NONE) {
+ continue;
+ }
code_ += "case .{{KEY}}:";
Indent();
code_ += "let _v = {{FIELDVAR}}(at: index, type: {{VALUETYPE}}.self)";
@@ -960,11 +973,13 @@
code_ += "switch {{FIELDVAR}}Type {";
for (auto it = union_def.Vals().begin(); it != union_def.Vals().end();
++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
const auto type = GenType(ev.union_type);
code_.SetValue("KEY", namer_.LegacySwiftVariant(ev));
code_.SetValue("VALUETYPE", type);
- if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ if (ev.union_type.base_type == BASE_TYPE_NONE) {
+ continue;
+ }
code_ += "case .{{KEY}}:";
Indent();
code_ += "let _v = {{FIELDVAR}}(type: {{VALUETYPE}}.self)";
@@ -975,11 +990,11 @@
code_ += "}";
}
- void GenerateEncoderBody(const StructDef &struct_def) {
+ void GenerateEncoderBody(const StructDef& struct_def) {
code_ += "var container = encoder.container(keyedBy: CodingKeys.self)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
const auto type = field.value.type;
@@ -1038,7 +1053,7 @@
}
}
- void GenerateJSONEncodingAPIs(const StructDef &struct_def) {
+ void GenerateJSONEncodingAPIs(const StructDef& struct_def) {
code_ += "extension {{STRUCTNAME}}: Encodable {";
Indent();
code_ += "";
@@ -1054,7 +1069,7 @@
code_ += "";
}
- void GenerateVerifier(const StructDef &struct_def) {
+ void GenerateVerifier(const StructDef& struct_def) {
code_ +=
"{{ACCESS_TYPE}} static func verify<T>(_ verifier: inout Verifier, at "
"position: "
@@ -1063,7 +1078,7 @@
code_ += "var _v = try verifier.visitTable(at: position)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
const auto offset = NumToString(field.value.offset);
@@ -1087,14 +1102,14 @@
code_ += "}";
}
- void GenerateUnionTypeVerifier(const FieldDef &field) {
+ void GenerateUnionTypeVerifier(const FieldDef& field) {
const auto is_vector =
IsVector(field.value.type) || IsArray(field.value.type);
if (field.value.type.base_type == BASE_TYPE_UTYPE ||
(is_vector &&
field.value.type.VectorType().base_type == BASE_TYPE_UTYPE))
return;
- EnumDef &union_def = *field.value.type.enum_def;
+ EnumDef& union_def = *field.value.type.enum_def;
code_.SetValue("VALUETYPE", namer_.NamespacedType(union_def));
code_.SetValue("FUNCTION_NAME", is_vector ? "visitUnionVector" : "visit");
code_ +=
@@ -1106,7 +1121,7 @@
code_ += "switch key {";
for (auto it = union_def.Vals().begin(); it != union_def.Vals().end();
++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
const auto type = GenType(ev.union_type);
code_.SetValue("KEY", namer_.LegacySwiftVariant(ev));
code_.SetValue("VALUETYPE", type);
@@ -1133,7 +1148,7 @@
code_ += "})";
}
- std::string GenerateVerifierType(const FieldDef &field) {
+ std::string GenerateVerifierType(const FieldDef& field) {
const auto type = field.value.type;
const auto is_vector = IsVector(type) || IsArray(type);
@@ -1147,19 +1162,25 @@
return GenerateNestedVerifierTypes(field.value.type);
}
- std::string GenerateNestedVerifierTypes(const Type &type) {
+ std::string GenerateNestedVerifierTypes(const Type& type) {
const auto string_type = GenType(type);
- if (IsScalar(type.base_type)) { return string_type; }
+ if (IsScalar(type.base_type)) {
+ return string_type;
+ }
- if (IsString(type)) { return "ForwardOffset<" + string_type + ">"; }
+ if (IsString(type)) {
+ return "ForwardOffset<" + string_type + ">";
+ }
- if (type.struct_def && type.struct_def->fixed) { return string_type; }
+ if (type.struct_def && type.struct_def->fixed) {
+ return string_type;
+ }
return "ForwardOffset<" + string_type + ">";
}
- void GenByKeyFunctions(const FieldDef &key_field) {
+ void GenByKeyFunctions(const FieldDef& key_field) {
code_.SetValue("TYPE", GenType(key_field.value.type));
code_ +=
"{{ACCESS_TYPE}} func {{FIELDVAR}}By(key: {{TYPE}}) -> {{VALUETYPE}}? "
@@ -1169,7 +1190,7 @@
"{{ACCESS}}.vector(at: o), key: key, fbb: {{ACCESS}}.bb) }";
}
- void GenEnum(const EnumDef &enum_def) {
+ void GenEnum(const EnumDef& enum_def) {
if (enum_def.generated) return;
const bool is_private_access =
parser_.opts.swift_implementation_only ||
@@ -1199,7 +1220,7 @@
code_ +=
"{{ACCESS_TYPE}} var value: {{BASE_TYPE}} { return self.rawValue }";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
code_.SetValue("KEY", namer_.LegacySwiftVariant(ev));
code_.SetValue("VALUE", enum_def.ToString(ev));
GenComment(ev.doc_comment);
@@ -1238,7 +1259,7 @@
}
}
- void EnumEncoder(const EnumDef &enum_def) {
+ void EnumEncoder(const EnumDef& enum_def) {
code_ += "extension {{ENUM_NAME}}: Encodable {";
Indent();
code_ += "{{ACCESS_TYPE}} func encode(to encoder: Encoder) throws {";
@@ -1246,7 +1267,7 @@
code_ += "var container = encoder.singleValueContainer()";
code_ += "switch self {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- const auto &ev = **it;
+ const auto& ev = **it;
code_.SetValue("KEY", namer_.LegacySwiftVariant(ev));
code_.SetValue("RAWKEY", ev.name);
code_ += "case .{{KEY}}: try container.encode(\"{{RAWKEY}}\")";
@@ -1286,13 +1307,13 @@
Indent();
}
- void GenerateObjectAPIStructConstructor(const StructDef &struct_def) {
+ void GenerateObjectAPIStructConstructor(const StructDef& struct_def) {
code_ +=
"{{ACCESS_TYPE}} init(_ _t: inout {{STRUCTNAME}}" + Mutable() + ") {";
Indent();
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
const auto type = GenType(field.value.type);
@@ -1309,7 +1330,7 @@
code_ += "}\n";
}
- void GenObjectAPI(const StructDef &struct_def) {
+ void GenObjectAPI(const StructDef& struct_def) {
code_ += "{{ACCESS_TYPE}} class " +
namer_.NamespacedObjectType(struct_def) + ": NativeObject {\n";
std::vector<std::string> buffer_constructor;
@@ -1317,7 +1338,7 @@
Indent();
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
BuildObjectAPIConstructorBody(field, struct_def.fixed, buffer_constructor,
base_constructor);
@@ -1335,13 +1356,13 @@
code_ += "}";
}
- void GenerateObjectAPITableExtension(const StructDef &struct_def) {
+ void GenerateObjectAPITableExtension(const StructDef& struct_def) {
GenerateObjectAPIExtensionHeader(namer_.NamespacedObjectType(struct_def));
std::vector<std::string> unpack_body;
std::string builder = ", &builder)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
const auto field_var = namer_.Variable(field);
const auto field_field = namer_.Field(field);
@@ -1353,7 +1374,8 @@
: "(";
std::string body = "add" + check_if_vector + field_method + ": ";
switch (field.value.type.base_type) {
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH();
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH();
case BASE_TYPE_VECTOR: {
GenerateVectorObjectAPITableExtension(field);
unpack_body.push_back("{{STRUCTNAME}}." + body + "__" + field_var +
@@ -1401,7 +1423,8 @@
}
break;
}
- case BASE_TYPE_UTYPE: break;
+ case BASE_TYPE_UTYPE:
+ break;
default:
unpack_body.push_back("{{STRUCTNAME}}." + body + "obj." +
field_field + builder);
@@ -1417,8 +1440,8 @@
code_ += "}";
}
- void GenerateVectorObjectAPITableExtension(const FieldDef &field_def) {
- const Type &field_type = field_def.value.type;
+ void GenerateVectorObjectAPITableExtension(const FieldDef& field_def) {
+ const Type& field_type = field_def.value.type;
const auto type = GenType(field_type);
const auto var = namer_.Variable(field_def);
const auto field = namer_.Field(field_def);
@@ -1439,7 +1462,8 @@
".compactMap { $0?.type })";
break;
}
- case BASE_TYPE_UTYPE: break;
+ case BASE_TYPE_UTYPE:
+ break;
case BASE_TYPE_STRUCT: {
if (field_type.struct_def && !field_type.struct_def->fixed) {
code_ += "var __" + var + "__: [Offset] = []";
@@ -1480,8 +1504,8 @@
}
}
- void BuildingOptionalObjects(const std::string &var,
- const std::string &body_front) {
+ void BuildingOptionalObjects(const std::string& var,
+ const std::string& body_front) {
code_ += "let __" + var + ": Offset";
code_ += "if let s = obj." + var + " {";
Indent();
@@ -1495,8 +1519,8 @@
code_ += "";
}
- void BuildObjectConstructor(const std::vector<std::string> &body,
- const std::string &header = "") {
+ void BuildObjectConstructor(const std::vector<std::string>& body,
+ const std::string& header = "") {
code_.SetValue("HEADER", header);
code_ += "{{ACCESS_TYPE}} init({{HEADER}}) {";
Indent();
@@ -1506,9 +1530,9 @@
}
void BuildObjectAPIConstructorBody(
- const FieldDef &field, bool is_fixed,
- std::vector<std::string> &buffer_constructor,
- std::vector<std::string> &base_constructor) {
+ const FieldDef& field, bool is_fixed,
+ std::vector<std::string>& buffer_constructor,
+ std::vector<std::string>& base_constructor) {
const auto field_field = namer_.Field(field);
const auto field_var = namer_.Variable(field);
const auto type = GenType(field.value.type);
@@ -1540,7 +1564,8 @@
}
break;
}
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH();
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH();
case BASE_TYPE_VECTOR: {
BuildObjectAPIConstructorBodyVectors(field, buffer_constructor,
base_constructor, " ");
@@ -1563,7 +1588,8 @@
}
break;
}
- case BASE_TYPE_UTYPE: break;
+ case BASE_TYPE_UTYPE:
+ break;
case BASE_TYPE_UNION: {
BuildUnionEnumSwitchCase(*field.value.type.enum_def, field_var,
buffer_constructor);
@@ -1601,9 +1627,9 @@
}
void BuildObjectAPIConstructorBodyVectors(
- const FieldDef &field, std::vector<std::string> &buffer_constructor,
- std::vector<std::string> &base_constructor,
- const std::string &indentation) {
+ const FieldDef& field, std::vector<std::string>& buffer_constructor,
+ std::vector<std::string>& base_constructor,
+ const std::string& indentation) {
const auto vectortype = field.value.type.VectorType();
const auto field_var = namer_.Field(field);
const auto field_field = namer_.Field(field);
@@ -1630,7 +1656,8 @@
}
break;
}
- case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH();
+ case BASE_TYPE_ARRAY:
+ FLATBUFFERS_FALLTHROUGH();
case BASE_TYPE_VECTOR: {
break;
}
@@ -1639,7 +1666,8 @@
buffer_constructor, indentation, true);
break;
}
- case BASE_TYPE_UTYPE: break;
+ case BASE_TYPE_UTYPE:
+ break;
default: {
code_.SetValue(
"VALUETYPE",
@@ -1663,14 +1691,16 @@
buffer_constructor.push_back("}");
}
- void BuildUnionEnumSwitchCaseWritter(const EnumDef &ed) {
+ void BuildUnionEnumSwitchCaseWritter(const EnumDef& ed) {
code_ += "switch type {";
for (auto it = ed.Vals().begin(); it < ed.Vals().end(); ++it) {
const auto ev = **it;
const auto variant = namer_.LegacySwiftVariant(ev);
const auto type = GenType(ev.union_type);
const auto is_struct = IsStruct(ev.union_type) ? type + Mutable() : type;
- if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ if (ev.union_type.base_type == BASE_TYPE_NONE) {
+ continue;
+ }
code_ += "case ." + variant + ":";
Indent();
code_ += "var __obj = value as? " + GenType(ev.union_type, true);
@@ -1681,9 +1711,9 @@
code_ += "}";
}
- void BuildUnionEnumSwitchCase(const EnumDef &ed, const std::string &field,
- std::vector<std::string> &buffer_constructor,
- const std::string &indentation = "",
+ void BuildUnionEnumSwitchCase(const EnumDef& ed, const std::string& field,
+ std::vector<std::string>& buffer_constructor,
+ const std::string& indentation = "",
const bool is_vector = false) {
const auto ns_type = namer_.NamespacedType(ed);
code_.SetValue("VALUETYPE", ns_type);
@@ -1697,7 +1727,9 @@
for (auto it = ed.Vals().begin(); it < ed.Vals().end(); ++it) {
const auto ev = **it;
const auto variant = namer_.LegacySwiftVariant(ev);
- if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ if (ev.union_type.base_type == BASE_TYPE_NONE) {
+ continue;
+ }
const auto type = IsStruct(ev.union_type)
? GenType(ev.union_type) + Mutable()
: GenType(ev.union_type);
@@ -1715,14 +1747,14 @@
buffer_constructor.push_back(indentation + "}");
}
- void AddMinOrMaxEnumValue(const std::string &str, const std::string &type) {
+ void AddMinOrMaxEnumValue(const std::string& str, const std::string& type) {
const auto current_value = str;
code_.SetValue(type, current_value);
code_ += "{{ACCESS_TYPE}} static var " + type +
": {{ENUM_NAME}} { return .{{" + type + "}} }";
}
- void GenLookup(const FieldDef &key_field, const std::string &struct_type) {
+ void GenLookup(const FieldDef& key_field, const std::string& struct_type) {
code_.SetValue("STRUCTTYPE", struct_type);
code_.SetValue("OFFSET", NumToString(key_field.value.offset));
std::string offset_reader =
@@ -1773,7 +1805,7 @@
code_ += "}";
}
- inline void GenPadding(const FieldDef &field, int *id) {
+ inline void GenPadding(const FieldDef& field, int* id) {
if (field.padding) {
for (int i = 0; i < 4; i++) {
if (static_cast<int>(field.padding) & (1 << i)) {
@@ -1786,33 +1818,35 @@
}
}
- void GenComment(const std::vector<std::string> &dc) {
+ void GenComment(const std::vector<std::string>& dc) {
if (dc.begin() == dc.end()) {
// Don't output empty comment blocks with 0 lines of comment content.
return;
}
- for (auto it = dc.begin(); it != dc.end(); ++it) { code_ += "/// " + *it; }
+ for (auto it = dc.begin(); it != dc.end(); ++it) {
+ code_ += "/// " + *it;
+ }
}
std::string GenOffset() {
return "let o = {{ACCESS}}.offset({{TABLEOFFSET}}.{{OFFSET}}.v); ";
}
- std::string GenReaderMainBody(const std::string &optional = "") {
+ std::string GenReaderMainBody(const std::string& optional = "") {
return "{{ACCESS_TYPE}} var {{FIELDVAR}}: {{VALUETYPE}}" + optional + " { ";
}
- std::string GenReader(const std::string &type,
- const std::string &at = "{{OFFSET}}") {
+ std::string GenReader(const std::string& type,
+ const std::string& at = "{{OFFSET}}") {
return "{{ACCESS}}.readBuffer(of: {{" + type + "}}.self, at: " + at + ")";
}
- std::string GenConstructor(const std::string &offset) {
+ std::string GenConstructor(const std::string& offset) {
return "{{VALUETYPE}}({{ACCESS}}.bb, o: " + offset + ") }";
}
- std::string GenMutate(const std::string &offset,
- const std::string &get_offset, bool isRaw = false) {
+ std::string GenMutate(const std::string& offset,
+ const std::string& get_offset, bool isRaw = false) {
return "@discardableResult {{ACCESS_TYPE}} func mutate({{FIELDVAR}}: "
"{{VALUETYPE}}) -> Bool {" +
get_offset + " return {{ACCESS}}.mutate({{FIELDVAR}}" +
@@ -1827,22 +1861,22 @@
"{{ACCESS}}.vector(at: o) + index * {{SIZE}}) }";
}
- std::string GenEnumDefaultValue(const FieldDef &field) {
- const auto &value = field.value;
+ std::string GenEnumDefaultValue(const FieldDef& field) {
+ const auto& value = field.value;
FLATBUFFERS_ASSERT(value.type.enum_def);
- const auto &enum_def = *value.type.enum_def;
+ const auto& enum_def = *value.type.enum_def;
// Vector of enum defaults are always "[]" which never works.
const std::string constant = IsVector(value.type) ? "0" : value.constant;
const auto enum_val = enum_def.FindByValue(constant);
if (enum_val) {
return "." + namer_.LegacySwiftVariant(*enum_val);
} else {
- const auto &ev = **enum_def.Vals().begin();
+ const auto& ev = **enum_def.Vals().begin();
return "." + namer_.LegacySwiftVariant(ev);
}
}
- std::string SwiftConstant(const FieldDef &field) {
+ std::string SwiftConstant(const FieldDef& field) {
const auto default_value =
StringIsFlatbufferNan(field.value.constant) ? ".nan"
: StringIsFlatbufferPositiveInfinity(field.value.constant) ? ".infinity"
@@ -1854,7 +1888,7 @@
return default_value;
}
- std::string GenEnumConstructor(const std::string &at) {
+ std::string GenEnumConstructor(const std::string& at) {
return "{{VALUETYPE}}(rawValue: " + GenReader("BASEVALUE", at) + ") ";
}
@@ -1862,31 +1896,34 @@
return "static func validateVersion() { FlatBuffersVersion_25_2_10() }";
}
- std::string GenType(const Type &type,
+ std::string GenType(const Type& type,
const bool should_consider_suffix = false) const {
return IsScalar(type.base_type) ? GenTypeBasic(type)
: IsArray(type) ? GenType(type.VectorType())
: GenTypePointer(type, should_consider_suffix);
}
- std::string GenTypePointer(const Type &type,
+ std::string GenTypePointer(const Type& type,
const bool should_consider_suffix) const {
switch (type.base_type) {
- case BASE_TYPE_STRING: return "String";
- case BASE_TYPE_VECTOR: return GenType(type.VectorType());
+ case BASE_TYPE_STRING:
+ return "String";
+ case BASE_TYPE_VECTOR:
+ return GenType(type.VectorType());
case BASE_TYPE_STRUCT: {
- const auto &sd = *type.struct_def;
+ const auto& sd = *type.struct_def;
if (should_consider_suffix && !sd.fixed) {
return namer_.NamespacedObjectType(sd);
}
return namer_.NamespacedType(sd);
}
case BASE_TYPE_UNION:
- default: return "FlatbuffersInitializable";
+ default:
+ return "FlatbuffersInitializable";
}
}
- std::string GenTypeBasic(const Type &type) const {
+ std::string GenTypeBasic(const Type& type) const {
return GenTypeBasic(type, true);
}
@@ -1894,7 +1931,7 @@
void Outdent() { code_.DecrementIdentLevel(); }
- std::string GenTypeBasic(const Type &type, bool can_override) const {
+ std::string GenTypeBasic(const Type& type, bool can_override) const {
// clang-format off
static const char * const swift_type[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
@@ -1917,8 +1954,8 @@
};
} // namespace swift
-static bool GenerateSwift(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateSwift(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
swift::SwiftGenerator generator(parser, path, file_name);
return generator.generate();
}
@@ -1927,26 +1964,29 @@
class SwiftCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateSwift(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateSwift(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateSwiftGRPC(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateSwiftGRPC(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
(void)parser;
(void)path;
(void)filename;
@@ -1954,8 +1994,8 @@
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_text.cpp b/src/idl_gen_text.cpp
index 895367e..ea1738c 100644
--- a/src/idl_gen_text.cpp
+++ b/src/idl_gen_text.cpp
@@ -30,10 +30,12 @@
struct PrintScalarTag {};
struct PrintPointerTag {};
-template<typename T> struct PrintTag {
+template <typename T>
+struct PrintTag {
typedef PrintScalarTag type;
};
-template<> struct PrintTag<const void *> {
+template <>
+struct PrintTag<const void*> {
typedef PrintPointerTag type;
};
@@ -49,7 +51,7 @@
int Indent() const { return std::max(opts.indent_step, 0); }
// Output an identifier with or without quotes depending on strictness.
- void OutputIdentifier(const std::string &name) {
+ void OutputIdentifier(const std::string& name) {
if (opts.strict_json) text += '\"';
text += name;
if (opts.strict_json) text += '\"';
@@ -58,15 +60,15 @@
// Print (and its template specialization below for pointers) generate text
// for a single FlatBuffer value into JSON format.
// The general case for scalars:
- template<typename T>
- void PrintScalar(T val, const Type &type, int /*indent*/) {
+ template <typename T>
+ void PrintScalar(T val, const Type& type, int /*indent*/) {
if (IsBool(type.base_type)) {
text += val != 0 ? "true" : "false";
return; // done
}
if (opts.output_enum_identifiers && type.enum_def) {
- const auto &enum_def = *type.enum_def;
+ const auto& enum_def = *type.enum_def;
if (auto ev = enum_def.ReverseLookup(static_cast<int64_t>(val))) {
text += '\"';
text += ev->name;
@@ -106,9 +108,9 @@
// Print a vector or an array of JSON values, comma seperated, wrapped in
// "[]".
- template<typename Container, typename SizeT = typename Container::size_type>
- const char *PrintContainer(PrintScalarTag, const Container &c, SizeT size,
- const Type &type, int indent, const uint8_t *) {
+ template <typename Container, typename SizeT = typename Container::size_type>
+ const char* PrintContainer(PrintScalarTag, const Container& c, SizeT size,
+ const Type& type, int indent, const uint8_t*) {
const auto elem_indent = indent + Indent();
text += '[';
AddNewLine();
@@ -128,10 +130,10 @@
// Print a vector or an array of JSON values, comma seperated, wrapped in
// "[]".
- template<typename Container, typename SizeT = typename Container::size_type>
- const char *PrintContainer(PrintPointerTag, const Container &c, SizeT size,
- const Type &type, int indent,
- const uint8_t *prev_val) {
+ template <typename Container, typename SizeT = typename Container::size_type>
+ const char* PrintContainer(PrintPointerTag, const Container& c, SizeT size,
+ const Type& type, int indent,
+ const uint8_t* prev_val) {
const auto is_struct = IsStruct(type);
const auto elem_indent = indent + Indent();
text += '[';
@@ -142,7 +144,7 @@
AddNewLine();
}
AddIndent(elem_indent);
- auto ptr = is_struct ? reinterpret_cast<const void *>(
+ auto ptr = is_struct ? reinterpret_cast<const void*>(
c.Data() + type.struct_def->bytesize * i)
: c[i];
auto err = PrintOffset(ptr, type, elem_indent, prev_val,
@@ -155,29 +157,29 @@
return nullptr;
}
- template<typename T, typename SizeT = uoffset_t>
- const char *PrintVector(const void *val, const Type &type, int indent,
- const uint8_t *prev_val) {
+ template <typename T, typename SizeT = uoffset_t>
+ const char* PrintVector(const void* val, const Type& type, int indent,
+ const uint8_t* prev_val) {
typedef Vector<T, SizeT> Container;
typedef typename PrintTag<typename Container::return_type>::type tag;
- auto &vec = *reinterpret_cast<const Container *>(val);
+ auto& vec = *reinterpret_cast<const Container*>(val);
return PrintContainer<Container>(tag(), vec, vec.size(), type, indent,
prev_val);
}
// Print an array a sequence of JSON values, comma separated, wrapped in "[]".
- template<typename T>
- const char *PrintArray(const void *val, uint16_t size, const Type &type,
+ template <typename T>
+ const char* PrintArray(const void* val, uint16_t size, const Type& type,
int indent) {
typedef Array<T, 0xFFFF> Container;
typedef typename PrintTag<typename Container::return_type>::type tag;
- auto &arr = *reinterpret_cast<const Container *>(val);
+ auto& arr = *reinterpret_cast<const Container*>(val);
return PrintContainer<Container>(tag(), arr, size, type, indent, nullptr);
}
- const char *PrintOffset(const void *val, const Type &type, int indent,
- const uint8_t *prev_val, soffset_t vector_index) {
+ const char* PrintOffset(const void* val, const Type& type, int indent,
+ const uint8_t* prev_val, soffset_t vector_index) {
switch (type.base_type) {
case BASE_TYPE_UNION: {
// If this assert hits, you have an corrupt buffer, a union type field
@@ -185,7 +187,7 @@
FLATBUFFERS_ASSERT(prev_val);
auto union_type_byte = *prev_val; // Always a uint8_t.
if (vector_index >= 0) {
- auto type_vec = reinterpret_cast<const Vector<uint8_t> *>(
+ auto type_vec = reinterpret_cast<const Vector<uint8_t>*>(
prev_val + ReadScalar<uoffset_t>(prev_val));
union_type_byte = type_vec->Get(static_cast<uoffset_t>(vector_index));
}
@@ -197,10 +199,10 @@
}
}
case BASE_TYPE_STRUCT:
- return GenStruct(*type.struct_def, reinterpret_cast<const Table *>(val),
+ return GenStruct(*type.struct_def, reinterpret_cast<const Table*>(val),
indent);
case BASE_TYPE_STRING: {
- auto s = reinterpret_cast<const String *>(val);
+ auto s = reinterpret_cast<const String*>(val);
bool ok = EscapeString(s->c_str(), s->size(), &text,
opts.allow_non_utf8, opts.natural_utf8);
return ok ? nullptr : "string contains non-utf8 bytes";
@@ -240,11 +242,14 @@
// clang-format on
return nullptr;
}
- default: FLATBUFFERS_ASSERT(0); return "unknown type";
+ default:
+ FLATBUFFERS_ASSERT(0);
+ return "unknown type";
}
}
- template<typename T> static T GetFieldDefault(const FieldDef &fd) {
+ template <typename T>
+ static T GetFieldDefault(const FieldDef& fd) {
T val{};
auto check = StringToNumber(fd.value.constant.c_str(), &val);
(void)check;
@@ -253,12 +258,12 @@
}
// Generate text for a scalar field.
- template<typename T>
- void GenField(const FieldDef &fd, const Table *table, bool fixed,
+ template <typename T>
+ void GenField(const FieldDef& fd, const Table* table, bool fixed,
int indent) {
if (fixed) {
PrintScalar(
- reinterpret_cast<const Struct *>(table)->GetField<T>(fd.value.offset),
+ reinterpret_cast<const Struct*>(table)->GetField<T>(fd.value.offset),
fd.value.type, indent);
} else if (fd.IsOptional()) {
auto opt = table->GetOptional<T, T>(fd.value.offset);
@@ -274,13 +279,13 @@
}
// Generate text for non-scalar field.
- const char *GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
- int indent, const uint8_t *prev_val) {
- const void *val = nullptr;
+ const char* GenFieldOffset(const FieldDef& fd, const Table* table, bool fixed,
+ int indent, const uint8_t* prev_val) {
+ const void* val = nullptr;
if (fixed) {
// The only non-scalar fields in structs are structs or arrays.
FLATBUFFERS_ASSERT(IsStruct(fd.value.type) || IsArray(fd.value.type));
- val = reinterpret_cast<const Struct *>(table)->GetStruct<const void *>(
+ val = reinterpret_cast<const Struct*>(table)->GetStruct<const void*>(
fd.value.offset);
} else if (fd.flexbuffer && opts.json_nested_flexbuffers) {
// We could verify this FlexBuffer before access, but since this sits
@@ -289,38 +294,40 @@
// The caller should really be verifying the whole.
// If the whole buffer is corrupt, we likely crash before we even get
// here.
- auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
+ auto vec = table->GetPointer<const Vector<uint8_t>*>(fd.value.offset);
auto root = flexbuffers::GetRoot(vec->data(), vec->size());
root.ToString(true, opts.strict_json, text);
return nullptr;
} else if (fd.nested_flatbuffer && opts.json_nested_flatbuffers) {
- auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
+ auto vec = table->GetPointer<const Vector<uint8_t>*>(fd.value.offset);
auto root = GetRoot<Table>(vec->data());
return GenStruct(*fd.nested_flatbuffer, root, indent);
} else {
val = IsStruct(fd.value.type)
- ? table->GetStruct<const void *>(fd.value.offset)
- : table->GetPointer<const void *>(fd.value.offset);
+ ? table->GetStruct<const void*>(fd.value.offset)
+ : table->GetPointer<const void*>(fd.value.offset);
}
return PrintOffset(val, fd.value.type, indent, prev_val, -1);
}
// Generate text for a struct or table, values separated by commas, indented,
// and bracketed by "{}"
- const char *GenStruct(const StructDef &struct_def, const Table *table,
+ const char* GenStruct(const StructDef& struct_def, const Table* table,
int indent) {
text += '{';
int fieldout = 0;
- const uint8_t *prev_val = nullptr;
+ const uint8_t* prev_val = nullptr;
const auto elem_indent = indent + Indent();
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- FieldDef &fd = **it;
+ FieldDef& fd = **it;
auto is_present = struct_def.fixed || table->CheckField(fd.value.offset);
auto output_anyway = (opts.output_default_scalars_in_json || fd.key) &&
IsScalar(fd.value.type.base_type) && !fd.deprecated;
if (is_present || output_anyway) {
- if (fieldout++) { AddComma(); }
+ if (fieldout++) {
+ AddComma();
+ }
AddNewLine();
AddIndent(elem_indent);
OutputIdentifier(fd.name);
@@ -352,7 +359,7 @@
// clang-format on
// Track prev val for use with union types.
if (struct_def.fixed) {
- prev_val = reinterpret_cast<const uint8_t *>(table) + fd.value.offset;
+ prev_val = reinterpret_cast<const uint8_t*>(table) + fd.value.offset;
} else {
prev_val = table->GetAddressOf(fd.value.offset);
}
@@ -364,18 +371,18 @@
return nullptr;
}
- JsonPrinter(const Parser &parser, std::string &dest)
+ JsonPrinter(const Parser& parser, std::string& dest)
: opts(parser.opts), text(dest) {
text.reserve(1024); // Reduce amount of inevitable reallocs.
}
- const IDLOptions &opts;
- std::string &text;
+ const IDLOptions& opts;
+ std::string& text;
};
-static const char *GenerateTextImpl(const Parser &parser, const Table *table,
- const StructDef &struct_def,
- std::string *_text) {
+static const char* GenerateTextImpl(const Parser& parser, const Table* table,
+ const StructDef& struct_def,
+ std::string* _text) {
JsonPrinter printer(parser, *_text);
auto err = printer.GenStruct(struct_def, table, 0);
if (err) return err;
@@ -385,49 +392,51 @@
// Generate a text representation of a flatbuffer in JSON format.
// Deprecated: please use `GenTextFromTable`
-bool GenerateTextFromTable(const Parser &parser, const void *table,
- const std::string &table_name,
- std::string *_text) {
+bool GenerateTextFromTable(const Parser& parser, const void* table,
+ const std::string& table_name, std::string* _text) {
return GenTextFromTable(parser, table, table_name, _text) != nullptr;
}
// Generate a text representation of a flatbuffer in JSON format.
-const char *GenTextFromTable(const Parser &parser, const void *table,
- const std::string &table_name, std::string *_text) {
+const char* GenTextFromTable(const Parser& parser, const void* table,
+ const std::string& table_name,
+ std::string* _text) {
auto struct_def = parser.LookupStruct(table_name);
- if (struct_def == nullptr) { return "unknown struct"; }
- auto root = static_cast<const Table *>(table);
+ if (struct_def == nullptr) {
+ return "unknown struct";
+ }
+ auto root = static_cast<const Table*>(table);
return GenerateTextImpl(parser, root, *struct_def, _text);
}
// Deprecated: please use `GenText`
-const char *GenerateText(const Parser &parser, const void *flatbuffer,
- std::string *_text) {
+const char* GenerateText(const Parser& parser, const void* flatbuffer,
+ std::string* _text) {
return GenText(parser, flatbuffer, _text);
}
// Generate a text representation of a flatbuffer in JSON format.
-const char *GenText(const Parser &parser, const void *flatbuffer,
- std::string *_text) {
+const char* GenText(const Parser& parser, const void* flatbuffer,
+ std::string* _text) {
FLATBUFFERS_ASSERT(parser.root_struct_def_); // call SetRootType()
auto root = parser.opts.size_prefixed ? GetSizePrefixedRoot<Table>(flatbuffer)
: GetRoot<Table>(flatbuffer);
return GenerateTextImpl(parser, root, *parser.root_struct_def_, _text);
}
-static std::string TextFileName(const std::string &path,
- const std::string &file_name) {
+static std::string TextFileName(const std::string& path,
+ const std::string& file_name) {
return path + file_name + ".json";
}
// Deprecated: please use `GenTextFile`
-const char *GenerateTextFile(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+const char* GenerateTextFile(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
return GenTextFile(parser, path, file_name);
}
-const char *GenTextFile(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+const char* GenTextFile(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
if (parser.opts.use_flexbuffers) {
std::string json;
parser.flex_root_.ToString(true, parser.opts.strict_json, json);
@@ -446,8 +455,8 @@
: "SaveFile failed";
}
-static std::string TextMakeRule(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static std::string TextMakeRule(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
if (!parser.builder_.GetSize() || !parser.root_struct_def_) return "";
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
@@ -464,8 +473,8 @@
class TextCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
auto err = GenTextFile(parser, path, filename);
if (err) {
status_detail = " (" + std::string(err) + ")";
@@ -476,28 +485,27 @@
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
output = TextMakeRule(parser, path, filename);
return Status::OK;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
(void)parser;
(void)path;
(void)filename;
return Status::NOT_IMPLEMENTED;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_gen_ts.cpp b/src/idl_gen_ts.cpp
index 14d42dc..83ca66e 100644
--- a/src/idl_gen_ts.cpp
+++ b/src/idl_gen_ts.cpp
@@ -39,61 +39,63 @@
std::string bare_file_path;
std::string rel_file_path;
std::string object_name;
- const Definition *dependent = nullptr;
- const Definition *dependency = nullptr;
+ const Definition* dependent = nullptr;
+ const Definition* dependency = nullptr;
};
struct NsDefinition {
std::string path;
std::string filepath;
std::string symbolic_name;
- const Namespace *ns;
- std::map<std::string, const Definition *> definitions;
+ const Namespace* ns;
+ std::map<std::string, const Definition*> definitions;
};
Namer::Config TypeScriptDefaultConfig() {
- return { /*types=*/Case::kKeep,
- /*constants=*/Case::kUnknown,
- /*methods=*/Case::kLowerCamel,
- /*functions=*/Case::kLowerCamel,
- /*fields=*/Case::kLowerCamel,
- /*variables=*/Case::kLowerCamel,
- /*variants=*/Case::kKeep,
- /*enum_variant_seperator=*/"::",
- /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
- /*namespaces=*/Case::kKeep,
- /*namespace_seperator=*/"_",
- /*object_prefix=*/"",
- /*object_suffix=*/"T",
- /*keyword_prefix=*/"",
- /*keyword_suffix=*/"_",
- /*filenames=*/Case::kDasher,
- /*directories=*/Case::kDasher,
- /*output_path=*/"",
- /*filename_suffix=*/"_generated",
- /*filename_extension=*/".ts" };
+ return {/*types=*/Case::kKeep,
+ /*constants=*/Case::kUnknown,
+ /*methods=*/Case::kLowerCamel,
+ /*functions=*/Case::kLowerCamel,
+ /*fields=*/Case::kLowerCamel,
+ /*variables=*/Case::kLowerCamel,
+ /*variants=*/Case::kKeep,
+ /*enum_variant_seperator=*/"::",
+ /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
+ /*namespaces=*/Case::kKeep,
+ /*namespace_seperator=*/"_",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kDasher,
+ /*directories=*/Case::kDasher,
+ /*output_path=*/"",
+ /*filename_suffix=*/"_generated",
+ /*filename_extension=*/".ts"};
}
std::set<std::string> TypescriptKeywords() {
// List of keywords retrieved from here:
// https://github.com/microsoft/TypeScript/issues/2536
return {
- "arguments", "break", "case", "catch", "class", "const",
- "continue", "debugger", "default", "delete", "do", "else",
- "enum", "export", "extends", "false", "finally", "for",
- "function", "if", "import", "in", "instanceof", "new",
- "null", "Object", "return", "super", "switch", "this",
- "throw", "true", "try", "typeof", "var", "void",
- "while", "with", "as", "implements", "interface", "let",
- "package", "private", "protected", "public", "static", "yield",
+ "arguments", "break", "case", "catch", "class", "const",
+ "continue", "debugger", "default", "delete", "do", "else",
+ "enum", "export", "extends", "false", "finally", "for",
+ "function", "if", "import", "in", "instanceof", "new",
+ "null", "Object", "return", "super", "switch", "this",
+ "throw", "true", "try", "typeof", "var", "void",
+ "while", "with", "as", "implements", "interface", "let",
+ "package", "private", "protected", "public", "static", "yield",
};
}
enum AnnotationType { kParam = 0, kType = 1, kReturns = 2 };
-template<typename T> struct SupportsObjectAPI : std::false_type {};
+template <typename T>
+struct SupportsObjectAPI : std::false_type {};
-template<> struct SupportsObjectAPI<StructDef> : std::true_type {};
+template <>
+struct SupportsObjectAPI<StructDef> : std::true_type {};
} // namespace
@@ -104,8 +106,8 @@
public:
typedef std::map<std::string, ImportDefinition> import_set;
- TsGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
+ TsGenerator(const Parser& parser, const std::string& path,
+ const std::string& file_name)
: BaseGenerator(parser, path, file_name, "", "_", "ts"),
namer_(WithFlagOptions(TypeScriptDefaultConfig(), parser.opts, path),
TypescriptKeywords()) {}
@@ -113,18 +115,22 @@
bool generate() {
generateEnums();
generateStructs();
- if (!parser_.opts.ts_omit_entrypoint) { generateEntry(); }
+ if (!parser_.opts.ts_omit_entrypoint) {
+ generateEntry();
+ }
if (!generateBundle()) return false;
return true;
}
- std::string GetTypeName(const EnumDef &def, const bool = false,
+ std::string GetTypeName(const EnumDef& def, const bool = false,
const bool force_ns_wrap = false) {
- if (force_ns_wrap) { return namer_.NamespacedType(def); }
+ if (force_ns_wrap) {
+ return namer_.NamespacedType(def);
+ }
return namer_.Type(def);
}
- std::string GetTypeName(const StructDef &def, const bool object_api = false,
+ std::string GetTypeName(const StructDef& def, const bool object_api = false,
const bool force_ns_wrap = false) {
if (object_api && parser_.opts.generate_object_based_api) {
if (force_ns_wrap) {
@@ -143,14 +149,16 @@
// Save out the generated code for a single class while adding
// declaration boilerplate.
- bool SaveType(const Definition &definition, const std::string &class_code,
- import_set &imports, import_set &bare_imports) {
+ bool SaveType(const Definition& definition, const std::string& class_code,
+ import_set& imports, import_set& bare_imports) {
if (!class_code.length()) return true;
std::string code;
code += "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n" +
- "/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */\n\n";
+ "/* eslint-disable @typescript-eslint/no-unused-vars, "
+ "@typescript-eslint/no-explicit-any, "
+ "@typescript-eslint/no-non-null-assertion */\n\n";
for (auto it = bare_imports.begin(); it != bare_imports.end(); it++) {
code += it->second.import_statement + "\n";
@@ -173,7 +181,7 @@
return SaveFile(basename.c_str(), code, false);
}
- void TrackNsDef(const Definition &definition, std::string type_name) {
+ void TrackNsDef(const Definition& definition, std::string type_name) {
std::string path;
std::string filepath;
std::string symbolic_name;
@@ -214,7 +222,7 @@
import_set bare_imports;
import_set imports;
std::string enumcode;
- auto &enum_def = **it;
+ auto& enum_def = **it;
GenEnum(enum_def, &enumcode, imports, false);
GenEnum(enum_def, &enumcode, imports, true);
std::string type_name = GetTypeName(enum_def);
@@ -230,7 +238,7 @@
import_set bare_imports;
import_set imports;
AddImport(bare_imports, "* as flatbuffers", "flatbuffers");
- auto &struct_def = **it;
+ auto& struct_def = **it;
std::string declcode;
GenStruct(parser_, struct_def, &declcode, imports);
std::string type_name = GetTypeName(struct_def);
@@ -254,13 +262,15 @@
ns_defs_[nsDef.path] = nsDef;
}
- for (const auto &it : ns_defs_) {
+ for (const auto& it : ns_defs_) {
code = "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n" +
- "/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */\n\n";
+ "/* eslint-disable @typescript-eslint/no-unused-vars, "
+ "@typescript-eslint/no-explicit-any, "
+ "@typescript-eslint/no-non-null-assertion */\n\n";
// export all definitions in ns entry point module
int export_counter = 0;
- for (const auto &def : it.second.definitions) {
+ for (const auto& def : it.second.definitions) {
std::vector<std::string> rel_components;
// build path for root level vs child level
if (it.second.ns->components.size() > 0) {
@@ -294,7 +304,7 @@
// re-export child namespace(s) in parent
const auto child_ns_level = it.second.ns->components.size() + 1;
- for (const auto &it2 : ns_defs_) {
+ for (const auto& it2 : ns_defs_) {
if (it2.second.ns->components.size() != child_ns_level) continue;
auto ts_file_path = it2.second.path + ".ts";
code += "export * as " + it2.second.symbolic_name + " from './";
@@ -303,7 +313,9 @@
std::copy(it2.second.ns->components.end() - count,
it2.second.ns->components.end(),
std::back_inserter(rel_path));
- code += namer_.Directories(rel_path, SkipDir::OutputPathAndTrailingPathSeparator) + ".js';\n";
+ code += namer_.Directories(
+ rel_path, SkipDir::OutputPathAndTrailingPathSeparator) +
+ ".js';\n";
export_counter++;
}
@@ -335,15 +347,15 @@
}
// Generate a documentation comment, if available.
- static void GenDocComment(const std::vector<std::string> &dc,
- std::string *code_ptr,
- const char *indent = nullptr) {
+ static void GenDocComment(const std::vector<std::string>& dc,
+ std::string* code_ptr,
+ const char* indent = nullptr) {
if (dc.empty()) {
// Don't output empty comment blocks with 0 lines of comment content.
return;
}
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
if (indent) code += indent;
code += "/**\n";
for (auto it = dc.begin(); it != dc.end(); ++it) {
@@ -354,24 +366,26 @@
code += " */\n";
}
- static void GenDocComment(std::string *code_ptr) {
+ static void GenDocComment(std::string* code_ptr) {
GenDocComment(std::vector<std::string>(), code_ptr);
}
// Generate an enum declaration and an enum string lookup table.
- void GenEnum(EnumDef &enum_def, std::string *code_ptr, import_set &imports,
+ void GenEnum(EnumDef& enum_def, std::string* code_ptr, import_set& imports,
bool reverse) {
if (enum_def.generated) return;
if (reverse) return; // FIXME.
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
GenDocComment(enum_def.doc_comment, code_ptr);
code += "export enum ";
code += GetTypeName(enum_def);
code += " {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
+ auto& ev = **it;
if (!ev.doc_comment.empty()) {
- if (it != enum_def.Vals().begin()) { code += '\n'; }
+ if (it != enum_def.Vals().begin()) {
+ code += '\n';
+ }
GenDocComment(ev.doc_comment, code_ptr, " ");
}
@@ -391,7 +405,8 @@
code += "'" + enum_def.ToString(ev) + "'";
break;
}
- default: code += enum_def.ToString(ev);
+ default:
+ code += enum_def.ToString(ev);
}
}
@@ -406,40 +421,60 @@
code += "\n";
}
- static std::string GenType(const Type &type) {
+ static std::string GenType(const Type& type) {
switch (type.base_type) {
case BASE_TYPE_BOOL:
- case BASE_TYPE_CHAR: return "Int8";
- case BASE_TYPE_UTYPE: return GenType(GetUnionUnderlyingType(type));
- case BASE_TYPE_UCHAR: return "Uint8";
- case BASE_TYPE_SHORT: return "Int16";
- case BASE_TYPE_USHORT: return "Uint16";
- case BASE_TYPE_INT: return "Int32";
- case BASE_TYPE_UINT: return "Uint32";
- case BASE_TYPE_LONG: return "Int64";
- case BASE_TYPE_ULONG: return "Uint64";
- case BASE_TYPE_FLOAT: return "Float32";
- case BASE_TYPE_DOUBLE: return "Float64";
- case BASE_TYPE_STRING: return "String";
- case BASE_TYPE_VECTOR: return GenType(type.VectorType());
- case BASE_TYPE_STRUCT: return type.struct_def->name;
- default: return "flatbuffers.Table";
+ case BASE_TYPE_CHAR:
+ return "Int8";
+ case BASE_TYPE_UTYPE:
+ return GenType(GetUnionUnderlyingType(type));
+ case BASE_TYPE_UCHAR:
+ return "Uint8";
+ case BASE_TYPE_SHORT:
+ return "Int16";
+ case BASE_TYPE_USHORT:
+ return "Uint16";
+ case BASE_TYPE_INT:
+ return "Int32";
+ case BASE_TYPE_UINT:
+ return "Uint32";
+ case BASE_TYPE_LONG:
+ return "Int64";
+ case BASE_TYPE_ULONG:
+ return "Uint64";
+ case BASE_TYPE_FLOAT:
+ return "Float32";
+ case BASE_TYPE_DOUBLE:
+ return "Float64";
+ case BASE_TYPE_STRING:
+ return "String";
+ case BASE_TYPE_VECTOR:
+ return GenType(type.VectorType());
+ case BASE_TYPE_STRUCT:
+ return type.struct_def->name;
+ default:
+ return "flatbuffers.Table";
}
}
- std::string GenGetter(const Type &type, const std::string &arguments) {
+ std::string GenGetter(const Type& type, const std::string& arguments) {
switch (type.base_type) {
- case BASE_TYPE_STRING: return GenBBAccess() + ".__string" + arguments;
- case BASE_TYPE_STRUCT: return GenBBAccess() + ".__struct" + arguments;
+ case BASE_TYPE_STRING:
+ return GenBBAccess() + ".__string" + arguments;
+ case BASE_TYPE_STRUCT:
+ return GenBBAccess() + ".__struct" + arguments;
case BASE_TYPE_UNION:
if (!UnionHasStringType(*type.enum_def)) {
return GenBBAccess() + ".__union" + arguments;
}
return GenBBAccess() + ".__union_with_string" + arguments;
- case BASE_TYPE_VECTOR: return GenGetter(type.VectorType(), arguments);
+ case BASE_TYPE_VECTOR:
+ return GenGetter(type.VectorType(), arguments);
default: {
auto getter = GenBBAccess() + "." + "read" + GenType(type) + arguments;
- if (type.base_type == BASE_TYPE_BOOL) { getter = "!!" + getter; }
+ if (type.base_type == BASE_TYPE_BOOL) {
+ getter = "!!" + getter;
+ }
return getter;
}
}
@@ -447,10 +482,12 @@
std::string GenBBAccess() const { return "this.bb!"; }
- std::string GenDefaultValue(const FieldDef &field, import_set &imports) {
- if (field.IsScalarOptional()) { return "null"; }
+ std::string GenDefaultValue(const FieldDef& field, import_set& imports) {
+ if (field.IsScalarOptional()) {
+ return "null";
+ }
- const auto &value = field.value;
+ const auto& value = field.value;
if (value.type.enum_def && value.type.base_type != BASE_TYPE_UNION &&
value.type.base_type != BASE_TYPE_VECTOR) {
switch (value.type.base_type) {
@@ -476,9 +513,9 @@
return "BigInt('" + value.constant + "')";
}
default: {
- EnumVal *val = value.type.enum_def->FindByValue(value.constant);
+ EnumVal* val = value.type.enum_def->FindByValue(value.constant);
if (val == nullptr)
- val = const_cast<EnumVal *>(value.type.enum_def->MinValue());
+ val = const_cast<EnumVal*>(value.type.enum_def->MinValue());
return AddImport(imports, *value.type.enum_def, *value.type.enum_def)
.name +
"." + namer_.Variant(*val);
@@ -487,7 +524,8 @@
}
switch (value.type.base_type) {
- case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
+ case BASE_TYPE_BOOL:
+ return value.constant == "0" ? "false" : "true";
case BASE_TYPE_STRING:
case BASE_TYPE_UNION:
@@ -496,7 +534,8 @@
}
case BASE_TYPE_ARRAY:
- case BASE_TYPE_VECTOR: return "[]";
+ case BASE_TYPE_VECTOR:
+ return "[]";
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG: {
@@ -516,8 +555,8 @@
}
}
- std::string GenTypeName(import_set &imports, const Definition &owner,
- const Type &type, bool input,
+ std::string GenTypeName(import_set& imports, const Definition& owner,
+ const Type& type, bool input,
bool allowNull = false) {
if (!input) {
if (IsString(type) || type.base_type == BASE_TYPE_STRUCT) {
@@ -532,9 +571,11 @@
}
switch (type.base_type) {
- case BASE_TYPE_BOOL: return allowNull ? "boolean|null" : "boolean";
+ case BASE_TYPE_BOOL:
+ return allowNull ? "boolean|null" : "boolean";
case BASE_TYPE_LONG:
- case BASE_TYPE_ULONG: return allowNull ? "bigint|null" : "bigint";
+ case BASE_TYPE_ULONG:
+ return allowNull ? "bigint|null" : "bigint";
case BASE_TYPE_ARRAY: {
std::string name;
if (type.element == BASE_TYPE_LONG || type.element == BASE_TYPE_ULONG) {
@@ -564,50 +605,58 @@
}
}
- static Type GetUnionUnderlyingType(const Type &type)
- {
+ static Type GetUnionUnderlyingType(const Type& type) {
if (type.enum_def != nullptr &&
type.enum_def->underlying_type.base_type != type.base_type) {
return type.enum_def->underlying_type;
} else {
- return Type(BASE_TYPE_UCHAR);
+ return Type(BASE_TYPE_UCHAR);
}
}
- static Type GetUnderlyingVectorType(const Type &vector_type)
- {
- return (vector_type.base_type == BASE_TYPE_UTYPE) ? GetUnionUnderlyingType(vector_type) : vector_type;
+ static Type GetUnderlyingVectorType(const Type& vector_type) {
+ return (vector_type.base_type == BASE_TYPE_UTYPE)
+ ? GetUnionUnderlyingType(vector_type)
+ : vector_type;
}
// Returns the method name for use with add/put calls.
- std::string GenWriteMethod(const Type &type) {
+ std::string GenWriteMethod(const Type& type) {
// Forward to signed versions since unsigned versions don't exist
switch (type.base_type) {
- case BASE_TYPE_UTYPE: return GenWriteMethod(GetUnionUnderlyingType(type));
- case BASE_TYPE_UCHAR: return GenWriteMethod(Type(BASE_TYPE_CHAR));
- case BASE_TYPE_USHORT: return GenWriteMethod(Type(BASE_TYPE_SHORT));
- case BASE_TYPE_UINT: return GenWriteMethod(Type(BASE_TYPE_INT));
- case BASE_TYPE_ULONG: return GenWriteMethod(Type(BASE_TYPE_LONG));
- default: break;
+ case BASE_TYPE_UTYPE:
+ return GenWriteMethod(GetUnionUnderlyingType(type));
+ case BASE_TYPE_UCHAR:
+ return GenWriteMethod(Type(BASE_TYPE_CHAR));
+ case BASE_TYPE_USHORT:
+ return GenWriteMethod(Type(BASE_TYPE_SHORT));
+ case BASE_TYPE_UINT:
+ return GenWriteMethod(Type(BASE_TYPE_INT));
+ case BASE_TYPE_ULONG:
+ return GenWriteMethod(Type(BASE_TYPE_LONG));
+ default:
+ break;
}
return IsScalar(type.base_type) ? namer_.Type(GenType(type))
: (IsStruct(type) ? "Struct" : "Offset");
}
- template<typename T> static std::string MaybeAdd(T value) {
+ template <typename T>
+ static std::string MaybeAdd(T value) {
return value != 0 ? " + " + NumToString(value) : "";
}
- template<typename T> static std::string MaybeScale(T value) {
+ template <typename T>
+ static std::string MaybeScale(T value) {
return value != 1 ? " * " + NumToString(value) : "";
}
- void GenStructArgs(import_set &imports, const StructDef &struct_def,
- std::string *arguments, const std::string &nameprefix) {
+ void GenStructArgs(import_set& imports, const StructDef& struct_def,
+ std::string* arguments, const std::string& nameprefix) {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (IsStruct(field.value.type)) {
// Generate arguments for a struct inside a struct. To ensure names
// don't clash, and to make it obvious these arguments are constructing
@@ -622,15 +671,15 @@
}
}
- void GenStructBody(const StructDef &struct_def, std::string *body,
- const std::string &nameprefix) {
+ void GenStructBody(const StructDef& struct_def, std::string* body,
+ const std::string& nameprefix) {
*body += " builder.prep(";
*body += NumToString(struct_def.minalign) + ", ";
*body += NumToString(struct_def.bytesize) + ");\n";
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.padding) {
*body += " builder.pad(" + NumToString(field.padding) + ");\n";
}
@@ -727,12 +776,12 @@
}
}
- std::string GenerateNewExpression(const std::string &object_name) {
+ std::string GenerateNewExpression(const std::string& object_name) {
return "new " + namer_.Type(object_name) + "()";
}
- void GenerateRootAccessor(StructDef &struct_def, std::string *code_ptr,
- std::string &code, const std::string &object_name,
+ void GenerateRootAccessor(StructDef& struct_def, std::string* code_ptr,
+ std::string& code, const std::string& object_name,
bool size_prefixed) {
if (!struct_def.fixed) {
GenDocComment(code_ptr);
@@ -752,8 +801,8 @@
}
}
- void GenerateFinisher(StructDef &struct_def, std::string *code_ptr,
- std::string &code, bool size_prefixed) {
+ void GenerateFinisher(StructDef& struct_def, std::string* code_ptr,
+ std::string& code, bool size_prefixed) {
if (parser_.root_struct_def_ == &struct_def) {
std::string sizePrefixed("SizePrefixed");
GenDocComment(code_ptr);
@@ -766,7 +815,9 @@
code += ", '" + parser_.file_identifier_ + "'";
}
if (size_prefixed) {
- if (parser_.file_identifier_.empty()) { code += ", undefined"; }
+ if (parser_.file_identifier_.empty()) {
+ code += ", undefined";
+ }
code += ", true";
}
code += ");\n";
@@ -774,14 +825,14 @@
}
}
- bool UnionHasStringType(const EnumDef &union_enum) {
+ bool UnionHasStringType(const EnumDef& union_enum) {
return std::any_of(union_enum.Vals().begin(), union_enum.Vals().end(),
- [](const EnumVal *ev) {
+ [](const EnumVal* ev) {
return !ev->IsZero() && IsString(ev->union_type);
});
}
- std::string GenUnionGenericTypeTS(const EnumDef &union_enum) {
+ std::string GenUnionGenericTypeTS(const EnumDef& union_enum) {
// TODO: make it work without any
// return std::string("T") + (UnionHasStringType(union_enum) ? "|string" :
// "");
@@ -789,14 +840,16 @@
(UnionHasStringType(union_enum) ? "|string" : "");
}
- std::string GenUnionTypeTS(const EnumDef &union_enum, import_set &imports) {
+ std::string GenUnionTypeTS(const EnumDef& union_enum, import_set& imports) {
std::string ret;
std::set<std::string> type_list;
for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
++it) {
- const auto &ev = **it;
- if (ev.IsZero()) { continue; }
+ const auto& ev = **it;
+ if (ev.IsZero()) {
+ continue;
+ }
std::string type = "";
if (IsString(ev.union_type)) {
@@ -816,20 +869,22 @@
return ret;
}
- static bool CheckIfNameClashes(const import_set &imports,
- const std::string &name) {
+ static bool CheckIfNameClashes(const import_set& imports,
+ const std::string& name) {
// TODO: this would be better as a hashset.
for (auto it = imports.begin(); it != imports.end(); it++) {
- if (it->second.name == name) { return true; }
+ if (it->second.name == name) {
+ return true;
+ }
}
return false;
}
- std::string GenSymbolExpression(const StructDef &struct_def,
+ std::string GenSymbolExpression(const StructDef& struct_def,
const bool has_name_clash,
- const std::string &import_name,
- const std::string &name,
- const std::string &object_name) {
+ const std::string& import_name,
+ const std::string& name,
+ const std::string& object_name) {
std::string symbols_expression;
if (has_name_clash) {
@@ -853,11 +908,10 @@
return symbols_expression;
}
- std::string GenSymbolExpression(const EnumDef &enum_def,
+ std::string GenSymbolExpression(const EnumDef& enum_def,
const bool has_name_clash,
- const std::string &import_name,
- const std::string &name,
- const std::string &) {
+ const std::string& import_name,
+ const std::string& name, const std::string&) {
std::string symbols_expression;
if (has_name_clash) {
symbols_expression += import_name + " as " + name;
@@ -873,16 +927,18 @@
return symbols_expression;
}
- template<typename DefinitionT>
- ImportDefinition AddImport(import_set &imports, const Definition &dependent,
- const DefinitionT &dependency) {
+ template <typename DefinitionT>
+ ImportDefinition AddImport(import_set& imports, const Definition& dependent,
+ const DefinitionT& dependency) {
// The unique name of the dependency, fully qualified in its namespace.
const std::string unique_name = GetTypeName(
dependency, /*object_api = */ false, /*force_ns_wrap=*/true);
// Look if we have already added this import and return its name if found.
const auto import_pair = imports.find(unique_name);
- if (import_pair != imports.end()) { return import_pair->second; }
+ if (import_pair != imports.end()) {
+ return import_pair->second;
+ }
// Check if this name would have a name clash with another type. Just use
// the "base" name (properly escaped) without any namespacing applied.
@@ -901,11 +957,13 @@
std::string bare_file_path;
std::string rel_file_path;
if (dependent.defined_namespace) {
- const auto &dep_comps = dependent.defined_namespace->components;
+ const auto& dep_comps = dependent.defined_namespace->components;
for (size_t i = 0; i < dep_comps.size(); i++) {
rel_file_path += i == 0 ? ".." : (kPathSeparator + std::string(".."));
}
- if (dep_comps.size() == 0) { rel_file_path += "."; }
+ if (dep_comps.size() == 0) {
+ rel_file_path += ".";
+ }
} else {
rel_file_path += "..";
}
@@ -935,7 +993,7 @@
return import;
}
- void AddImport(import_set &imports, std::string import_name,
+ void AddImport(import_set& imports, std::string import_name,
std::string fileName) {
ImportDefinition import;
import.name = import_name;
@@ -945,17 +1003,19 @@
}
// Generate a TS union type based on a union's enum
- std::string GenObjApiUnionTypeTS(import_set &imports,
- const StructDef &dependent,
- const IDLOptions &,
- const EnumDef &union_enum) {
+ std::string GenObjApiUnionTypeTS(import_set& imports,
+ const StructDef& dependent,
+ const IDLOptions&,
+ const EnumDef& union_enum) {
std::string ret = "";
std::set<std::string> type_list;
for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
++it) {
- const auto &ev = **it;
- if (ev.IsZero()) { continue; }
+ const auto& ev = **it;
+ if (ev.IsZero()) {
+ continue;
+ }
std::string type = "";
if (IsString(ev.union_type)) {
@@ -978,17 +1038,17 @@
return ret;
}
- std::string GenUnionConvFuncName(const EnumDef &enum_def) {
+ std::string GenUnionConvFuncName(const EnumDef& enum_def) {
return namer_.Function("unionTo", enum_def);
}
- std::string GenUnionListConvFuncName(const EnumDef &enum_def) {
+ std::string GenUnionListConvFuncName(const EnumDef& enum_def) {
return namer_.Function("unionListTo", enum_def);
}
- std::string GenUnionConvFunc(const Type &union_type, import_set &imports) {
+ std::string GenUnionConvFunc(const Type& union_type, import_set& imports) {
if (union_type.enum_def) {
- const auto &enum_def = *union_type.enum_def;
+ const auto& enum_def = *union_type.enum_def;
const auto valid_union_type = GenUnionTypeTS(enum_def, imports);
const auto valid_union_type_with_null = valid_union_type + "|null";
@@ -1001,14 +1061,16 @@
const auto enum_type = AddImport(imports, enum_def, enum_def).name;
- const auto union_enum_loop = [&](const std::string &accessor_str) {
+ const auto union_enum_loop = [&](const std::string& accessor_str) {
ret += " switch(" + enum_type + "[type]) {\n";
ret += " case 'NONE': return null; \n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
- const auto &ev = **it;
- if (ev.IsZero()) { continue; }
+ const auto& ev = **it;
+ if (ev.IsZero()) {
+ continue;
+ }
ret += " case '" + namer_.Variant(ev) + "': ";
@@ -1049,12 +1111,12 @@
// Used for generating a short function that returns the correct class
// based on union enum type. Assume the context is inside the non object api
// type
- std::string GenUnionValTS(import_set &imports, const StructDef &dependent,
- const std::string &field_name,
- const Type &union_type,
+ std::string GenUnionValTS(import_set& imports, const StructDef& dependent,
+ const std::string& field_name,
+ const Type& union_type,
const bool is_array = false) {
if (union_type.enum_def) {
- const auto &enum_def = *union_type.enum_def;
+ const auto& enum_def = *union_type.enum_def;
const auto enum_type = AddImport(imports, dependent, enum_def).name;
const std::string union_accessor = "this." + field_name;
@@ -1113,20 +1175,20 @@
}
static std::string GenNullCheckConditional(
- const std::string &nullCheckVar, const std::string &trueVal,
- const std::string &falseVal = "null") {
+ const std::string& nullCheckVar, const std::string& trueVal,
+ const std::string& falseVal = "null") {
return "(" + nullCheckVar + " !== null ? " + trueVal + " : " + falseVal +
")";
}
- std::string GenStructMemberValueTS(const StructDef &struct_def,
- const std::string &prefix,
- const std::string &delimiter,
+ std::string GenStructMemberValueTS(const StructDef& struct_def,
+ const std::string& prefix,
+ const std::string& delimiter,
const bool nullCheck = true) {
std::string ret;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
auto curr_member_accessor = prefix + "." + namer_.Method(field);
if (prefix != "this") {
@@ -1152,15 +1214,17 @@
}
}
- if (std::next(it) != struct_def.fields.vec.end()) { ret += delimiter; }
+ if (std::next(it) != struct_def.fields.vec.end()) {
+ ret += delimiter;
+ }
}
return ret;
}
- void GenObjApi(const Parser &parser, StructDef &struct_def,
- std::string &obj_api_unpack_func, std::string &obj_api_class,
- import_set &imports) {
+ void GenObjApi(const Parser& parser, StructDef& struct_def,
+ std::string& obj_api_unpack_func, std::string& obj_api_class,
+ import_set& imports) {
const auto class_name = GetTypeName(struct_def, /*object_api=*/true);
std::string unpack_func = "\nunpack(): " + class_name +
@@ -1201,7 +1265,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
const auto field_method = namer_.Method(field);
@@ -1243,7 +1307,7 @@
auto is_vector = false;
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
- const auto &sd = *field.value.type.struct_def;
+ const auto& sd = *field.value.type.struct_def;
field_type += AddImport(imports, struct_def, sd).object_name;
const std::string field_accessor =
@@ -1273,7 +1337,7 @@
switch (vectortype.base_type) {
case BASE_TYPE_STRUCT: {
- const auto &sd = *field.value.type.struct_def;
+ const auto& sd = *field.value.type.struct_def;
const auto field_type_name =
GetTypeName(sd, /*object_api=*/true);
field_type += field_type_name;
@@ -1362,7 +1426,7 @@
switch (vectortype.base_type) {
case BASE_TYPE_STRUCT: {
- const auto &sd = *field.value.type.struct_def;
+ const auto& sd = *field.value.type.struct_def;
const auto field_type_name =
GetTypeName(sd, /*object_api=*/true);
field_type += field_type_name;
@@ -1452,7 +1516,9 @@
break;
}
- default: FLATBUFFERS_ASSERT(0); break;
+ default:
+ FLATBUFFERS_ASSERT(0);
+ break;
}
// length 0 vector is simply empty instead of null
@@ -1463,7 +1529,9 @@
field_offset_decl =
" const " + field_field + " = " + field_offset_decl + ";";
}
- if (field_offset_val.empty()) { field_offset_val = field_field; }
+ if (field_offset_val.empty()) {
+ field_offset_val = field_field;
+ }
unpack_func += " " + field_val;
unpack_to_func += " _o." + field_field + " = " + field_val + ";";
@@ -1536,23 +1604,24 @@
obj_api_unpack_func = unpack_func + "\n\n" + unpack_to_func;
}
- static bool CanCreateFactoryMethod(const StructDef &struct_def) {
+ static bool CanCreateFactoryMethod(const StructDef& struct_def) {
// to preserve backwards compatibility, we allow the first field to be a
// struct
return struct_def.fields.vec.size() < 2 ||
- std::all_of(std::begin(struct_def.fields.vec) + 1,
- std::end(struct_def.fields.vec),
- [](const FieldDef *f) -> bool {
- FLATBUFFERS_ASSERT(f != nullptr);
- return f->value.type.base_type != BASE_TYPE_STRUCT;
- });
+ std::all_of(
+ std::begin(struct_def.fields.vec) + 1,
+ std::end(struct_def.fields.vec),
+ [](const FieldDef* f) -> bool {
+ FLATBUFFERS_ASSERT(f != nullptr);
+ return f->value.type.base_type != BASE_TYPE_STRUCT;
+ });
}
// Generate an accessor struct with constructor for a flatbuffers struct.
- void GenStruct(const Parser &parser, StructDef &struct_def,
- std::string *code_ptr, import_set &imports) {
+ void GenStruct(const Parser& parser, StructDef& struct_def,
+ std::string* code_ptr, import_set& imports) {
if (struct_def.generated) return;
- std::string &code = *code_ptr;
+ std::string& code = *code_ptr;
// Special case for the root struct, since no one will necessarily reference
// it, we have to explicitly add it to the import list.
@@ -1603,7 +1672,7 @@
// Emit field accessors
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
std::string offset_prefix = "";
@@ -1653,7 +1722,9 @@
";\n";
} else {
std::string index = "this.bb_pos + offset";
- if (is_string) { index += ", optionalEncoding"; }
+ if (is_string) {
+ index += ", optionalEncoding";
+ }
code +=
offset_prefix + GenGetter(field.value.type, "(" + index + ")");
if (field.value.type.base_type != BASE_TYPE_ARRAY) {
@@ -1701,19 +1772,26 @@
std::string ret_type;
bool is_union = false;
switch (vectortype.base_type) {
- case BASE_TYPE_STRUCT: ret_type = vectortypename; break;
- case BASE_TYPE_STRING: ret_type = vectortypename; break;
+ case BASE_TYPE_STRUCT:
+ ret_type = vectortypename;
+ break;
+ case BASE_TYPE_STRING:
+ ret_type = vectortypename;
+ break;
case BASE_TYPE_UNION:
ret_type = "?flatbuffers.Table";
is_union = true;
break;
- default: ret_type = vectortypename;
+ default:
+ ret_type = vectortypename;
}
GenDocComment(field.doc_comment, code_ptr);
std::string prefix = namer_.Method(field);
// TODO: make it work without any
// if (is_union) { prefix += "<T extends flatbuffers.Table>"; }
- if (is_union) { prefix += ""; }
+ if (is_union) {
+ prefix += "";
+ }
prefix += "(index: number";
if (is_union) {
const auto union_type =
@@ -1792,19 +1870,26 @@
std::string ret_type;
bool is_union = false;
switch (vectortype.base_type) {
- case BASE_TYPE_STRUCT: ret_type = vectortypename; break;
- case BASE_TYPE_STRING: ret_type = vectortypename; break;
+ case BASE_TYPE_STRUCT:
+ ret_type = vectortypename;
+ break;
+ case BASE_TYPE_STRING:
+ ret_type = vectortypename;
+ break;
case BASE_TYPE_UNION:
ret_type = "?flatbuffers.Table";
is_union = true;
break;
- default: ret_type = vectortypename;
+ default:
+ ret_type = vectortypename;
}
GenDocComment(field.doc_comment, code_ptr);
std::string prefix = namer_.Method(field);
// TODO: make it work without any
// if (is_union) { prefix += "<T extends flatbuffers.Table>"; }
- if (is_union) { prefix += ""; }
+ if (is_union) {
+ prefix += "";
+ }
prefix += "(index: number";
if (is_union) {
const auto union_type =
@@ -1863,7 +1948,7 @@
GenDocComment(field.doc_comment, code_ptr);
code += namer_.Method(field);
- const auto &union_enum = *(field.value.type.enum_def);
+ const auto& union_enum = *(field.value.type.enum_def);
const auto union_type = GenUnionGenericTypeTS(union_enum);
code += "<T extends flatbuffers.Table>(obj:" + union_type +
"):" + union_type +
@@ -1875,7 +1960,8 @@
" : null;\n";
break;
}
- default: FLATBUFFERS_ASSERT(0);
+ default:
+ FLATBUFFERS_ASSERT(0);
}
}
code += "}\n\n";
@@ -1908,8 +1994,10 @@
}
// special case for bools, which are treated as uint8
- if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
-
+ if (field.value.type.base_type == BASE_TYPE_BOOL) {
+ code += "+";
+ }
+
code += "value);\n";
code += " return true;\n";
code += "}\n\n";
@@ -1945,16 +2033,14 @@
// Emit the fully qualified name
if (parser_.opts.generate_name_strings) {
- const std::string fullyQualifiedName = struct_def.defined_namespace->GetFullyQualifiedName(struct_def.name);
+ const std::string fullyQualifiedName =
+ struct_def.defined_namespace->GetFullyQualifiedName(struct_def.name);
GenDocComment(code_ptr);
code += "static getFullyQualifiedName(): \"";
code += fullyQualifiedName;
code += "\" {\n";
- code +=
- " return '" +
- fullyQualifiedName +
- "';\n";
+ code += " return '" + fullyQualifiedName + "';\n";
code += "}\n\n";
}
@@ -1992,7 +2078,7 @@
// Generate a set of static methods that allow table construction
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (field.deprecated) continue;
const auto argname = GetArgName(field);
@@ -2003,14 +2089,18 @@
GetArgType(imports, struct_def, field, false) + ") {\n";
code += " builder.addField" + GenWriteMethod(field.value.type) + "(";
code += NumToString(it - struct_def.fields.vec.begin()) + ", ";
- if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
+ if (field.value.type.base_type == BASE_TYPE_BOOL) {
+ code += "+";
+ }
code += argname + ", ";
if (!IsScalar(field.value.type.base_type)) {
code += "0";
} else if (HasNullDefault(field)) {
code += "null";
} else {
- if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
+ if (field.value.type.base_type == BASE_TYPE_BOOL) {
+ code += "+";
+ }
code += GenDefaultValue(field, imports);
}
code += ");\n}\n\n";
@@ -2032,7 +2122,7 @@
std::string type =
GenTypeName(imports, struct_def, vector_type, true) + "[]";
if (type == "number[]") {
- const auto &array_type = GenType(vector_type);
+ const auto& array_type = GenType(vector_type);
// the old type should be deprecated in the future
std::string type_old = "number[]|Uint8Array";
std::string type_new = "number[]|" + array_type + "Array";
@@ -2053,7 +2143,9 @@
code += ", data.length, " + NumToString(alignment) + ");\n";
code += " for (let i = data.length - 1; i >= 0; i--) {\n";
code += " builder.add" + GenWriteMethod(vector_type) + "(";
- if (vector_type.base_type == BASE_TYPE_BOOL) { code += "+"; }
+ if (vector_type.base_type == BASE_TYPE_BOOL) {
+ code += "+";
+ }
code += "data[i]!);\n";
code += " }\n";
code += " return builder.endVector();\n";
@@ -2082,7 +2174,7 @@
code += " const offset = builder.endObject();\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ auto& field = **it;
if (!field.deprecated && field.IsRequired()) {
code += " builder.requiredField(offset, ";
code += NumToString(field.value.offset);
@@ -2102,7 +2194,7 @@
code += "(builder:flatbuffers.Builder";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
code += ", " + GetArgName(field) + ":" +
GetArgType(imports, struct_def, field, true);
@@ -2115,7 +2207,7 @@
std::string methodPrefix = object_name;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
+ const auto& field = **it;
if (field.deprecated) continue;
const auto arg_name = GetArgName(field);
@@ -2161,37 +2253,39 @@
}
}
- static bool HasNullDefault(const FieldDef &field) {
+ static bool HasNullDefault(const FieldDef& field) {
return field.IsOptional() && field.value.constant == "null";
}
- std::string GetArgType(import_set &imports, const Definition &owner,
- const FieldDef &field, bool allowNull) {
+ std::string GetArgType(import_set& imports, const Definition& owner,
+ const FieldDef& field, bool allowNull) {
return GenTypeName(imports, owner, field.value.type, true,
allowNull && field.IsOptional());
}
- std::string GetArgName(const FieldDef &field) {
+ std::string GetArgName(const FieldDef& field) {
auto argname = namer_.Variable(field);
- if (!IsScalar(field.value.type.base_type)) { argname += "Offset"; }
+ if (!IsScalar(field.value.type.base_type)) {
+ argname += "Offset";
+ }
return argname;
}
- std::string GetPrefixedName(const StructDef &struct_def,
- const char *prefix = "") {
+ std::string GetPrefixedName(const StructDef& struct_def,
+ const char* prefix = "") {
return prefix + struct_def.name;
}
}; // namespace ts
} // namespace ts
-static bool GenerateTS(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static bool GenerateTS(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
ts::TsGenerator generator(parser, path, file_name);
return generator.generate();
}
-static std::string TSMakeRule(const Parser &parser, const std::string &path,
- const std::string &file_name) {
+static std::string TSMakeRule(const Parser& parser, const std::string& path,
+ const std::string& file_name) {
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
ts::TsGenerator generator(parser, path, file_name);
@@ -2209,32 +2303,35 @@
class TsCodeGenerator : public CodeGenerator {
public:
- Status GenerateCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateTS(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateTS(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateCode(const uint8_t *, int64_t,
- const CodeGenOptions &) override {
+ Status GenerateCode(const uint8_t*, int64_t, const CodeGenOptions&) override {
return Status::NOT_IMPLEMENTED;
}
- Status GenerateMakeRule(const Parser &parser, const std::string &path,
- const std::string &filename,
- std::string &output) override {
+ Status GenerateMakeRule(const Parser& parser, const std::string& path,
+ const std::string& filename,
+ std::string& output) override {
output = TSMakeRule(parser, path, filename);
return Status::OK;
}
- Status GenerateGrpcCode(const Parser &parser, const std::string &path,
- const std::string &filename) override {
- if (!GenerateTSGRPC(parser, path, filename)) { return Status::ERROR; }
+ Status GenerateGrpcCode(const Parser& parser, const std::string& path,
+ const std::string& filename) override {
+ if (!GenerateTSGRPC(parser, path, filename)) {
+ return Status::ERROR;
+ }
return Status::OK;
}
- Status GenerateRootFile(const Parser &parser,
- const std::string &path) override {
+ Status GenerateRootFile(const Parser& parser,
+ const std::string& path) override {
(void)parser;
(void)path;
return Status::NOT_IMPLEMENTED;
diff --git a/src/idl_parser.cpp b/src/idl_parser.cpp
index d01e18e..42df4cd 100644
--- a/src/idl_parser.cpp
+++ b/src/idl_parser.cpp
@@ -30,7 +30,7 @@
namespace flatbuffers {
// Reflects the version at the compiling time of binary(lib/dll/so).
-const char *FLATBUFFERS_VERSION() {
+const char* FLATBUFFERS_VERSION() {
// clang-format off
return
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
@@ -63,16 +63,18 @@
#define NEXT() ECHECK(Next())
#define EXPECT(tok) ECHECK(Expect(tok))
-static bool ValidateUTF8(const std::string &str) {
- const char *s = &str[0];
- const char *const sEnd = s + str.length();
+static bool ValidateUTF8(const std::string& str) {
+ const char* s = &str[0];
+ const char* const sEnd = s + str.length();
while (s < sEnd) {
- if (FromUTF8(&s) < 0) { return false; }
+ if (FromUTF8(&s) < 0) {
+ return false;
+ }
}
return true;
}
-static bool IsLowerSnakeCase(const std::string &str) {
+static bool IsLowerSnakeCase(const std::string& str) {
for (size_t i = 0; i < str.length(); i++) {
char c = str[i];
if (!check_ascii_range(c, 'a', 'z') && !is_digit(c) && c != '_') {
@@ -82,8 +84,8 @@
return true;
}
-static void DeserializeDoc(std::vector<std::string> &doc,
- const Vector<Offset<String>> *documentation) {
+static void DeserializeDoc(std::vector<std::string>& doc,
+ const Vector<Offset<String>>* documentation) {
if (documentation == nullptr) return;
for (uoffset_t index = 0; index < documentation->size(); index++)
doc.push_back(documentation->Get(index)->str());
@@ -91,27 +93,28 @@
static CheckedError NoError() { return CheckedError(false); }
-template<typename T> static std::string TypeToIntervalString() {
+template <typename T>
+static std::string TypeToIntervalString() {
return "[" + NumToString((flatbuffers::numeric_limits<T>::lowest)()) + "; " +
NumToString((flatbuffers::numeric_limits<T>::max)()) + "]";
}
// atot: template version of atoi/atof: convert a string to an instance of T.
-template<typename T>
-static bool atot_scalar(const char *s, T *val, bool_constant<false>) {
+template <typename T>
+static bool atot_scalar(const char* s, T* val, bool_constant<false>) {
return StringToNumber(s, val);
}
-template<typename T>
-static bool atot_scalar(const char *s, T *val, bool_constant<true>) {
+template <typename T>
+static bool atot_scalar(const char* s, T* val, bool_constant<true>) {
// Normalize NaN parsed from fbs or json to unsigned NaN.
if (false == StringToNumber(s, val)) return false;
*val = (*val != *val) ? std::fabs(*val) : *val;
return true;
}
-template<typename T>
-static CheckedError atot(const char *s, Parser &parser, T *val) {
+template <typename T>
+static CheckedError atot(const char* s, Parser& parser, T* val) {
auto done = atot_scalar(s, val, bool_constant<is_floating_point<T>::value>());
if (done) return NoError();
if (0 == *val)
@@ -120,28 +123,28 @@
return parser.Error("invalid number: \"" + std::string(s) + "\"" +
", constant does not fit " + TypeToIntervalString<T>());
}
-template<>
-CheckedError atot<Offset<void>>(const char *s, Parser &parser,
- Offset<void> *val) {
+template <>
+CheckedError atot<Offset<void>>(const char* s, Parser& parser,
+ Offset<void>* val) {
(void)parser;
*val = Offset<void>(atoi(s));
return NoError();
}
-template<>
-CheckedError atot<Offset64<void>>(const char *s, Parser &parser,
- Offset64<void> *val) {
+template <>
+CheckedError atot<Offset64<void>>(const char* s, Parser& parser,
+ Offset64<void>* val) {
(void)parser;
*val = Offset64<void>(atoi(s));
return NoError();
}
-template<typename T>
-static T *LookupTableByName(const SymbolTable<T> &table,
- const std::string &name,
- const Namespace ¤t_namespace,
+template <typename T>
+static T* LookupTableByName(const SymbolTable<T>& table,
+ const std::string& name,
+ const Namespace& current_namespace,
size_t skip_top) {
- const auto &components = current_namespace.components;
+ const auto& components = current_namespace.components;
if (table.dict.empty()) return nullptr;
if (components.size() < skip_top) return nullptr;
const auto N = components.size() - skip_top;
@@ -201,16 +204,18 @@
static bool IsIdentifierStart(char c) { return is_alpha(c) || (c == '_'); }
-static bool CompareSerializedScalars(const uint8_t *a, const uint8_t *b,
- const FieldDef &key) {
+static bool CompareSerializedScalars(const uint8_t* a, const uint8_t* b,
+ const FieldDef& key) {
switch (key.value.type.base_type) {
-#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
- case BASE_TYPE_##ENUM: { \
- CTYPE def = static_cast<CTYPE>(0); \
- if (!a || !b) { StringToNumber(key.value.constant.c_str(), &def); } \
- const auto av = a ? ReadScalar<CTYPE>(a) : def; \
- const auto bv = b ? ReadScalar<CTYPE>(b) : def; \
- return av < bv; \
+#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
+ case BASE_TYPE_##ENUM: { \
+ CTYPE def = static_cast<CTYPE>(0); \
+ if (!a || !b) { \
+ StringToNumber(key.value.constant.c_str(), &def); \
+ } \
+ const auto av = a ? ReadScalar<CTYPE>(a) : def; \
+ const auto bv = b ? ReadScalar<CTYPE>(b) : def; \
+ return av < bv; \
}
FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
@@ -221,41 +226,41 @@
}
}
-static bool CompareTablesByScalarKey(const Offset<Table> *_a,
- const Offset<Table> *_b,
- const FieldDef &key) {
+static bool CompareTablesByScalarKey(const Offset<Table>* _a,
+ const Offset<Table>* _b,
+ const FieldDef& key) {
const voffset_t offset = key.value.offset;
// Indirect offset pointer to table pointer.
- auto a = reinterpret_cast<const uint8_t *>(_a) + ReadScalar<uoffset_t>(_a);
- auto b = reinterpret_cast<const uint8_t *>(_b) + ReadScalar<uoffset_t>(_b);
+ auto a = reinterpret_cast<const uint8_t*>(_a) + ReadScalar<uoffset_t>(_a);
+ auto b = reinterpret_cast<const uint8_t*>(_b) + ReadScalar<uoffset_t>(_b);
// Fetch field address from table.
- a = reinterpret_cast<const Table *>(a)->GetAddressOf(offset);
- b = reinterpret_cast<const Table *>(b)->GetAddressOf(offset);
+ a = reinterpret_cast<const Table*>(a)->GetAddressOf(offset);
+ b = reinterpret_cast<const Table*>(b)->GetAddressOf(offset);
return CompareSerializedScalars(a, b, key);
}
-static bool CompareTablesByStringKey(const Offset<Table> *_a,
- const Offset<Table> *_b,
- const FieldDef &key) {
+static bool CompareTablesByStringKey(const Offset<Table>* _a,
+ const Offset<Table>* _b,
+ const FieldDef& key) {
const voffset_t offset = key.value.offset;
// Indirect offset pointer to table pointer.
- auto a = reinterpret_cast<const uint8_t *>(_a) + ReadScalar<uoffset_t>(_a);
- auto b = reinterpret_cast<const uint8_t *>(_b) + ReadScalar<uoffset_t>(_b);
+ auto a = reinterpret_cast<const uint8_t*>(_a) + ReadScalar<uoffset_t>(_a);
+ auto b = reinterpret_cast<const uint8_t*>(_b) + ReadScalar<uoffset_t>(_b);
// Fetch field address from table.
- a = reinterpret_cast<const Table *>(a)->GetAddressOf(offset);
- b = reinterpret_cast<const Table *>(b)->GetAddressOf(offset);
+ a = reinterpret_cast<const Table*>(a)->GetAddressOf(offset);
+ b = reinterpret_cast<const Table*>(b)->GetAddressOf(offset);
if (a && b) {
// Indirect offset pointer to string pointer.
a += ReadScalar<uoffset_t>(a);
b += ReadScalar<uoffset_t>(b);
- return *reinterpret_cast<const String *>(a) <
- *reinterpret_cast<const String *>(b);
+ return *reinterpret_cast<const String*>(a) <
+ *reinterpret_cast<const String*>(b);
} else {
return a ? true : false;
}
}
-static void SwapSerializedTables(Offset<Table> *a, Offset<Table> *b) {
+static void SwapSerializedTables(Offset<Table>* a, Offset<Table>* b) {
// These are serialized offsets, so are relative where they are
// stored in memory, so compute the distance between these pointers:
ptrdiff_t diff = (b - a) * sizeof(Offset<Table>);
@@ -267,8 +272,8 @@
}
// See below for why we need our own sort :(
-template<typename T, typename F, typename S>
-static void SimpleQsort(T *begin, T *end, size_t width, F comparator,
+template <typename T, typename F, typename S>
+static void SimpleQsort(T* begin, T* end, size_t width, F comparator,
S swapper) {
if (end - begin <= static_cast<ptrdiff_t>(width)) return;
auto l = begin + width;
@@ -287,43 +292,49 @@
SimpleQsort(r, end, width, comparator, swapper);
}
-template<typename T> static inline void SingleValueRepack(Value &e, T val) {
+template <typename T>
+static inline void SingleValueRepack(Value& e, T val) {
// Remove leading zeros.
- if (IsInteger(e.type.base_type)) { e.constant = NumToString(val); }
+ if (IsInteger(e.type.base_type)) {
+ e.constant = NumToString(val);
+ }
}
#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
// Normalize defaults NaN to unsigned quiet-NaN(0) if value was parsed from
// hex-float literal.
-static void SingleValueRepack(Value &e, float val) {
+static void SingleValueRepack(Value& e, float val) {
if (val != val) e.constant = "nan";
}
-static void SingleValueRepack(Value &e, double val) {
+static void SingleValueRepack(Value& e, double val) {
if (val != val) e.constant = "nan";
}
#endif
-template<typename T> static uint64_t EnumDistanceImpl(T e1, T e2) {
- if (e1 < e2) { std::swap(e1, e2); } // use std for scalars
+template <typename T>
+static uint64_t EnumDistanceImpl(T e1, T e2) {
+ if (e1 < e2) {
+ std::swap(e1, e2);
+ } // use std for scalars
// Signed overflow may occur, use unsigned calculation.
// The unsigned overflow is well-defined by C++ standard (modulo 2^n).
return static_cast<uint64_t>(e1) - static_cast<uint64_t>(e2);
}
-static bool compareFieldDefs(const FieldDef *a, const FieldDef *b) {
+static bool compareFieldDefs(const FieldDef* a, const FieldDef* b) {
auto a_id = atoi(a->attributes.Lookup("id")->constant.c_str());
auto b_id = atoi(b->attributes.Lookup("id")->constant.c_str());
return a_id < b_id;
}
-static Namespace *GetNamespace(
- const std::string &qualified_name, std::vector<Namespace *> &namespaces,
- std::map<std::string, Namespace *> &namespaces_index) {
+static Namespace* GetNamespace(
+ const std::string& qualified_name, std::vector<Namespace*>& namespaces,
+ std::map<std::string, Namespace*>& namespaces_index) {
size_t dot = qualified_name.find_last_of('.');
std::string namespace_name = (dot != std::string::npos)
? std::string(qualified_name.c_str(), dot)
: "";
- Namespace *&ns = namespaces_index[namespace_name];
+ Namespace*& ns = namespaces_index[namespace_name];
if (!ns) {
ns = new Namespace();
@@ -333,7 +344,9 @@
for (;;) {
dot = qualified_name.find('.', pos);
- if (dot == std::string::npos) { break; }
+ if (dot == std::string::npos) {
+ break;
+ }
ns->components.push_back(qualified_name.substr(pos, dot - pos));
pos = dot + 1;
}
@@ -343,7 +356,7 @@
}
// Generate a unique hash for a file based on its name and contents (if any).
-static uint64_t HashFile(const char *source_filename, const char *source) {
+static uint64_t HashFile(const char* source_filename, const char* source) {
uint64_t hash = 0;
if (source_filename)
@@ -354,12 +367,14 @@
return hash;
}
-template<typename T> static bool compareName(const T *a, const T *b) {
+template <typename T>
+static bool compareName(const T* a, const T* b) {
return a->defined_namespace->GetFullyQualifiedName(a->name) <
b->defined_namespace->GetFullyQualifiedName(b->name);
}
-template<typename T> static void AssignIndices(const std::vector<T *> &defvec) {
+template <typename T>
+static void AssignIndices(const std::vector<T*>& defvec) {
// Pre-sort these vectors, such that we can set the correct indices for them.
auto vec = defvec;
std::sort(vec.begin(), vec.end(), compareName<T>);
@@ -368,7 +383,7 @@
} // namespace
-void Parser::Message(const std::string &msg) {
+void Parser::Message(const std::string& msg) {
if (!error_.empty()) error_ += "\n"; // log all warnings and errors
error_ += file_being_parsed_.length() ? AbsolutePath(file_being_parsed_) : "";
// clang-format off
@@ -384,14 +399,14 @@
error_ += ": " + msg;
}
-void Parser::Warning(const std::string &msg) {
+void Parser::Warning(const std::string& msg) {
if (!opts.no_warnings) {
Message("warning: " + msg);
has_warning_ = true; // for opts.warnings_as_errors
}
}
-CheckedError Parser::Error(const std::string &msg) {
+CheckedError Parser::Error(const std::string& msg) {
Message("error: " + msg);
return CheckedError(true);
}
@@ -401,13 +416,13 @@
" reached");
}
-const std::string &Parser::GetPooledString(const std::string &s) const {
+const std::string& Parser::GetPooledString(const std::string& s) const {
return *(string_cache_.insert(s).first);
}
class Parser::ParseDepthGuard {
public:
- explicit ParseDepthGuard(Parser *parser_not_null)
+ explicit ParseDepthGuard(Parser* parser_not_null)
: parser_(*parser_not_null), caller_depth_(parser_.parse_depth_counter_) {
FLATBUFFERS_ASSERT(caller_depth_ <= (FLATBUFFERS_MAX_PARSING_DEPTH) &&
"Check() must be called to prevent stack overflow");
@@ -422,18 +437,20 @@
: CheckedError(false);
}
- FLATBUFFERS_DELETE_FUNC(ParseDepthGuard(const ParseDepthGuard &));
- FLATBUFFERS_DELETE_FUNC(ParseDepthGuard &operator=(const ParseDepthGuard &));
+ FLATBUFFERS_DELETE_FUNC(ParseDepthGuard(const ParseDepthGuard&));
+ FLATBUFFERS_DELETE_FUNC(ParseDepthGuard& operator=(const ParseDepthGuard&));
private:
- Parser &parser_;
+ Parser& parser_;
const int caller_depth_;
};
-std::string Namespace::GetFullyQualifiedName(const std::string &name,
+std::string Namespace::GetFullyQualifiedName(const std::string& name,
size_t max_components) const {
// Early exit if we don't have a defined namespace.
- if (components.empty() || !max_components) { return name; }
+ if (components.empty() || !max_components) {
+ return name;
+ }
std::string stream_str;
for (size_t i = 0; i < std::min(components.size(), max_components); i++) {
stream_str += components[i];
@@ -452,7 +469,7 @@
}
// Parses exactly nibbles worth of hex digits into a number, or error.
-CheckedError Parser::ParseHexNum(int nibbles, uint64_t *val) {
+CheckedError Parser::ParseHexNum(int nibbles, uint64_t* val) {
FLATBUFFERS_ASSERT(nibbles > 0);
for (int i = 0; i < nibbles; i++)
if (!is_xdigit(cursor_[i]))
@@ -492,7 +509,8 @@
return NoError();
case ' ':
case '\r':
- case '\t': break;
+ case '\t':
+ break;
case '\n':
MarkNewLine();
seen_newline = true;
@@ -508,7 +526,8 @@
case ',':
case ':':
case ';':
- case '=': return NoError();
+ case '=':
+ return NoError();
case '\"':
case '\'': {
int unicode_high_surrogate = -1;
@@ -598,7 +617,8 @@
}
break;
}
- default: return Error("unknown escape code in string constant");
+ default:
+ return Error("unknown escape code in string constant");
}
} else { // printable chars + UTF-8 bytes
if (unicode_high_surrogate != -1) {
@@ -625,7 +645,7 @@
}
case '/':
if (*cursor_ == '/') {
- const char *start = ++cursor_;
+ const char* start = ++cursor_;
while (*cursor_ && *cursor_ != '\n' && *cursor_ != '\r') cursor_++;
if (*start == '/') { // documentation comment
if (!seen_newline)
@@ -649,7 +669,7 @@
default:
if (IsIdentifierStart(c)) {
// Collect all chars of an identifier:
- const char *start = cursor_ - 1;
+ const char* start = cursor_ - 1;
while (IsIdentifierStart(*cursor_) || is_digit(*cursor_)) cursor_++;
attribute_.append(start, cursor_);
token_ = kTokenIdentifier;
@@ -735,7 +755,7 @@
// Check if a given token is next.
bool Parser::Is(int t) const { return t == token_; }
-bool Parser::IsIdent(const char *id) const {
+bool Parser::IsIdent(const char* id) const {
return token_ == kTokenIdentifier && attribute_ == id;
}
@@ -749,7 +769,7 @@
return NoError();
}
-CheckedError Parser::ParseNamespacing(std::string *id, std::string *last) {
+CheckedError Parser::ParseNamespacing(std::string* id, std::string* last) {
while (Is('.')) {
NEXT();
*id += ".";
@@ -760,25 +780,25 @@
return NoError();
}
-EnumDef *Parser::LookupEnum(const std::string &id) {
+EnumDef* Parser::LookupEnum(const std::string& id) {
// Search thru parent namespaces.
return LookupTableByName(enums_, id, *current_namespace_, 0);
}
-StructDef *Parser::LookupStruct(const std::string &id) const {
+StructDef* Parser::LookupStruct(const std::string& id) const {
auto sd = structs_.Lookup(id);
if (sd) sd->refcount++;
return sd;
}
-StructDef *Parser::LookupStructThruParentNamespaces(
- const std::string &id) const {
+StructDef* Parser::LookupStructThruParentNamespaces(
+ const std::string& id) const {
auto sd = LookupTableByName(structs_, id, *current_namespace_, 1);
if (sd) sd->refcount++;
return sd;
}
-CheckedError Parser::ParseTypeIdent(Type &type) {
+CheckedError Parser::ParseTypeIdent(Type& type) {
std::string id = attribute_;
EXPECT(kTokenIdentifier);
ECHECK(ParseNamespacing(&id, nullptr));
@@ -794,7 +814,7 @@
}
// Parse any IDL type.
-CheckedError Parser::ParseType(Type &type) {
+CheckedError Parser::ParseType(Type& type) {
if (token_ == kTokenIdentifier) {
if (IsIdent("bool")) {
type.base_type = BASE_TYPE_BOOL;
@@ -872,9 +892,9 @@
return NoError();
}
-CheckedError Parser::AddField(StructDef &struct_def, const std::string &name,
- const Type &type, FieldDef **dest) {
- auto &field = *new FieldDef();
+CheckedError Parser::AddField(StructDef& struct_def, const std::string& name,
+ const Type& type, FieldDef** dest) {
+ auto& field = *new FieldDef();
field.value.offset =
FieldIndexToOffset(static_cast<voffset_t>(struct_def.fields.vec.size()));
field.name = name;
@@ -896,7 +916,7 @@
return NoError();
}
-CheckedError Parser::ParseField(StructDef &struct_def) {
+CheckedError Parser::ParseField(StructDef& struct_def) {
std::string name = attribute_;
if (LookupCreateStruct(name, false, false))
@@ -924,7 +944,7 @@
auto valid = IsScalar(type.base_type) || IsStruct(type);
if (!valid && IsArray(type)) {
- const auto &elem_type = type.VectorType();
+ const auto& elem_type = type.VectorType();
valid |= IsScalar(elem_type.base_type) || IsStruct(elem_type);
}
if (!valid)
@@ -943,16 +963,18 @@
}
}
- FieldDef *typefield = nullptr;
+ FieldDef* typefield = nullptr;
if (type.base_type == BASE_TYPE_UNION) {
// For union fields, add a second auto-generated field to hold the type,
// with a special suffix.
- // To ensure compatibility with many codes that rely on the BASE_TYPE_UTYPE value to identify union type fields.
+ // To ensure compatibility with many codes that rely on the BASE_TYPE_UTYPE
+ // value to identify union type fields.
Type union_type(type.enum_def->underlying_type);
union_type.base_type = BASE_TYPE_UTYPE;
- ECHECK(AddField(struct_def, name + UnionTypeFieldSuffix(),union_type, &typefield));
-
+ ECHECK(AddField(struct_def, name + UnionTypeFieldSuffix(), union_type,
+ &typefield));
+
} else if (IsVector(type) && type.element == BASE_TYPE_UNION) {
advanced_features_ |= reflection::AdvancedUnionFeatures;
// Only cpp, js and ts supports the union vector feature so far.
@@ -969,7 +991,7 @@
&typefield));
}
- FieldDef *field;
+ FieldDef* field;
ECHECK(AddField(struct_def, name, type, &field));
if (typefield) {
@@ -1005,7 +1027,7 @@
// Append .0 if the value has not it (skip hex and scientific floats).
// This suffix needed for generated C++ code.
if (IsFloat(type.base_type)) {
- auto &text = field->value.constant;
+ auto& text = field->value.constant;
FLATBUFFERS_ASSERT(false == text.empty());
auto s = text.c_str();
while (*s == ' ') s++;
@@ -1168,9 +1190,11 @@
if (type.enum_def) {
// Verify the enum's type and default value.
- const std::string &constant = field->value.constant;
+ const std::string& constant = field->value.constant;
if (type.base_type == BASE_TYPE_UNION) {
- if (constant != "0") { return Error("Union defaults must be NONE"); }
+ if (constant != "0") {
+ return Error("Union defaults must be NONE");
+ }
} else if (IsVector(type)) {
if (constant != "0" && constant != "[]") {
return Error("Vector defaults may only be `[]`.");
@@ -1261,7 +1285,7 @@
// the automatically added type field should have an id as well (of N - 1).
auto attr = field->attributes.Lookup("id");
if (attr) {
- const auto &id_str = attr->constant;
+ const auto& id_str = attr->constant;
voffset_t id = 0;
const auto done = !atot(id_str.c_str(), *this, &id).Check();
if (done && id > 0) {
@@ -1280,14 +1304,16 @@
}
// if this field is a union that is deprecated,
// the automatically added type field should be deprecated as well
- if (field->deprecated) { typefield->deprecated = true; }
+ if (field->deprecated) {
+ typefield->deprecated = true;
+ }
}
EXPECT(';');
return NoError();
}
-CheckedError Parser::ParseString(Value &val, bool use_string_pooling) {
+CheckedError Parser::ParseString(Value& val, bool use_string_pooling) {
auto s = attribute_;
EXPECT(kTokenStringConstant);
if (use_string_pooling) {
@@ -1303,26 +1329,26 @@
return NoError();
}
-CheckedError Parser::ParseAnyValue(Value &val, FieldDef *field,
+CheckedError Parser::ParseAnyValue(Value& val, FieldDef* field,
size_t parent_fieldn,
- const StructDef *parent_struct_def,
+ const StructDef* parent_struct_def,
size_t count, bool inside_vector) {
switch (val.type.base_type) {
case BASE_TYPE_UNION: {
FLATBUFFERS_ASSERT(field);
std::string constant;
- Vector<uint8_t> *vector_of_union_types = nullptr;
+ Vector<uint8_t>* vector_of_union_types = nullptr;
// Find corresponding type field we may have already parsed.
for (auto elem = field_stack_.rbegin() + count;
elem != field_stack_.rbegin() + parent_fieldn + count; ++elem) {
- auto &type = elem->second->value.type;
+ auto& type = elem->second->value.type;
if (type.enum_def == val.type.enum_def) {
if (inside_vector) {
if (IsVector(type) && type.element == BASE_TYPE_UTYPE) {
// Vector of union type field.
uoffset_t offset;
ECHECK(atot(elem->first.constant.c_str(), *this, &offset));
- vector_of_union_types = reinterpret_cast<Vector<uint8_t> *>(
+ vector_of_union_types = reinterpret_cast<Vector<uint8_t>*>(
builder_.GetCurrentBufferPointer() + builder_.GetSize() -
offset);
break;
@@ -1347,7 +1373,7 @@
auto type_field = parent_struct_def->fields.Lookup(type_name);
FLATBUFFERS_ASSERT(type_field); // Guaranteed by ParseField().
// Remember where we are in the source file, so we can come back here.
- auto backup = *static_cast<ParserState *>(this);
+ auto backup = *static_cast<ParserState*>(this);
ECHECK(SkipAnyJsonValue()); // The table.
ECHECK(ParseComma());
auto next_name = attribute_;
@@ -1364,7 +1390,7 @@
ECHECK(ParseAnyValue(type_val, type_field, 0, nullptr, 0));
constant = type_val.constant;
// Got the information we needed, now rewind:
- *static_cast<ParserState *>(this) = backup;
+ *static_cast<ParserState*>(this) = backup;
}
}
if (constant.empty() && !vector_of_union_types) {
@@ -1435,22 +1461,22 @@
return NoError();
}
-void Parser::SerializeStruct(const StructDef &struct_def, const Value &val) {
+void Parser::SerializeStruct(const StructDef& struct_def, const Value& val) {
SerializeStruct(builder_, struct_def, val);
}
-void Parser::SerializeStruct(FlatBufferBuilder &builder,
- const StructDef &struct_def, const Value &val) {
+void Parser::SerializeStruct(FlatBufferBuilder& builder,
+ const StructDef& struct_def, const Value& val) {
FLATBUFFERS_ASSERT(val.constant.length() == struct_def.bytesize);
builder.Align(struct_def.minalign);
- builder.PushBytes(reinterpret_cast<const uint8_t *>(val.constant.c_str()),
+ builder.PushBytes(reinterpret_cast<const uint8_t*>(val.constant.c_str()),
struct_def.bytesize);
builder.AddStructOffset(val.offset, builder.GetSize());
}
-template<typename F>
-CheckedError Parser::ParseTableDelimiters(size_t &fieldn,
- const StructDef *struct_def, F body) {
+template <typename F>
+CheckedError Parser::ParseTableDelimiters(size_t& fieldn,
+ const StructDef* struct_def, F body) {
// We allow tables both as JSON object{ .. } with field names
// or vector[..] with all fields in order
char terminator = '}';
@@ -1489,16 +1515,16 @@
return NoError();
}
-CheckedError Parser::ParseTable(const StructDef &struct_def, std::string *value,
- uoffset_t *ovalue) {
+CheckedError Parser::ParseTable(const StructDef& struct_def, std::string* value,
+ uoffset_t* ovalue) {
ParseDepthGuard depth_guard(this);
ECHECK(depth_guard.Check());
size_t fieldn_outer = 0;
auto err = ParseTableDelimiters(
fieldn_outer, &struct_def,
- [&](const std::string &name, size_t &fieldn,
- const StructDef *struct_def_inner) -> CheckedError {
+ [&](const std::string& name, size_t& fieldn,
+ const StructDef* struct_def_inner) -> CheckedError {
if (name == "$schema") {
ECHECK(Expect(kTokenStringConstant));
return NoError();
@@ -1555,7 +1581,9 @@
for (auto field_it = struct_def.fields.vec.begin();
field_it != struct_def.fields.vec.end(); ++field_it) {
auto required_field = *field_it;
- if (!required_field->IsRequired()) { continue; }
+ if (!required_field->IsRequired()) {
+ continue;
+ }
bool found = false;
for (auto pf_it = field_stack_.end() - fieldn_outer;
pf_it != field_stack_.end(); ++pf_it) {
@@ -1585,7 +1613,7 @@
// Offset64 then Offset32 fields.
for (auto it = field_stack_.rbegin();
it != field_stack_.rbegin() + fieldn_outer; ++it) {
- auto &field_value = it->first;
+ auto& field_value = it->first;
auto field = it->second;
if (!struct_def.sortbysize ||
size == SizeOf(field_value.type.base_type)) {
@@ -1655,7 +1683,7 @@
// Temporarily store this struct in the value string, since it is to
// be serialized in-place elsewhere.
value->assign(
- reinterpret_cast<const char *>(builder_.GetCurrentBufferPointer()),
+ reinterpret_cast<const char*>(builder_.GetCurrentBufferPointer()),
struct_def.bytesize);
builder_.PopBytes(struct_def.bytesize);
FLATBUFFERS_ASSERT(!ovalue);
@@ -1667,8 +1695,8 @@
return NoError();
}
-template<typename F>
-CheckedError Parser::ParseVectorDelimiters(size_t &count, F body) {
+template <typename F>
+CheckedError Parser::ParseVectorDelimiters(size_t& count, F body) {
EXPECT('[');
for (;;) {
if ((!opts.strict_json || !count) && Is(']')) break;
@@ -1681,8 +1709,8 @@
return NoError();
}
-CheckedError Parser::ParseAlignAttribute(const std::string &align_constant,
- size_t min_align, size_t *align) {
+CheckedError Parser::ParseAlignAttribute(const std::string& align_constant,
+ size_t min_align, size_t* align) {
// Use uint8_t to avoid problems with size_t==`unsigned long` on LP64.
uint8_t align_value;
if (StringToNumber(align_constant.c_str(), &align_value) &&
@@ -1698,11 +1726,11 @@
NumToString(FLATBUFFERS_MAX_ALIGNMENT));
}
-CheckedError Parser::ParseVector(const Type &vector_type, uoffset_t *ovalue,
- FieldDef *field, size_t fieldn) {
+CheckedError Parser::ParseVector(const Type& vector_type, uoffset_t* ovalue,
+ FieldDef* field, size_t fieldn) {
Type type = vector_type.VectorType();
size_t count = 0;
- auto err = ParseVectorDelimiters(count, [&](size_t &) -> CheckedError {
+ auto err = ParseVectorDelimiters(count, [&](size_t&) -> CheckedError {
Value val;
val.type = type;
ECHECK(ParseAnyValue(val, field, fieldn, nullptr, count, true));
@@ -1718,7 +1746,9 @@
if (force_align) {
size_t align;
ECHECK(ParseAlignAttribute(force_align->constant, 1, &align));
- if (align > 1) { builder_.ForceVectorAlignment(len, elemsize, align); }
+ if (align > 1) {
+ builder_.ForceVectorAlignment(len, elemsize, align);
+ }
}
// TODO Fix using element alignment as size (`elemsize`)!
@@ -1731,7 +1761,7 @@
}
for (size_t i = 0; i < count; i++) {
// start at the back, since we're building the data backwards.
- auto &val = field_stack_.back().first;
+ auto& val = field_stack_.back().first;
switch (val.type.base_type) {
// clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE,...) \
@@ -1759,7 +1789,7 @@
if (type.base_type == BASE_TYPE_STRUCT && type.struct_def->has_key) {
// We should sort this vector. Find the key first.
- const FieldDef *key = nullptr;
+ const FieldDef* key = nullptr;
for (auto it = type.struct_def->fields.vec.begin();
it != type.struct_def->fields.vec.end(); ++it) {
if ((*it)->key) {
@@ -1781,19 +1811,21 @@
const voffset_t offset = key->value.offset;
const size_t struct_size = type.struct_def->bytesize;
auto v =
- reinterpret_cast<VectorOfAny *>(builder_.GetCurrentBufferPointer());
+ reinterpret_cast<VectorOfAny*>(builder_.GetCurrentBufferPointer());
SimpleQsort<uint8_t>(
v->Data(), v->Data() + v->size() * type.struct_def->bytesize,
type.struct_def->bytesize,
- [offset, key](const uint8_t *a, const uint8_t *b) -> bool {
+ [offset, key](const uint8_t* a, const uint8_t* b) -> bool {
return CompareSerializedScalars(a + offset, b + offset, *key);
},
- [struct_size](uint8_t *a, uint8_t *b) {
+ [struct_size](uint8_t* a, uint8_t* b) {
// FIXME: faster?
- for (size_t i = 0; i < struct_size; i++) { std::swap(a[i], b[i]); }
+ for (size_t i = 0; i < struct_size; i++) {
+ std::swap(a[i], b[i]);
+ }
});
} else {
- auto v = reinterpret_cast<Vector<Offset<Table>> *>(
+ auto v = reinterpret_cast<Vector<Offset<Table>>*>(
builder_.GetCurrentBufferPointer());
// Here also can't use std::sort. We do have an iterator type for it,
// but it is non-standard as it will dereference the offsets, and thus
@@ -1801,14 +1833,14 @@
if (key->value.type.base_type == BASE_TYPE_STRING) {
SimpleQsort<Offset<Table>>(
v->data(), v->data() + v->size(), 1,
- [key](const Offset<Table> *_a, const Offset<Table> *_b) -> bool {
+ [key](const Offset<Table>* _a, const Offset<Table>* _b) -> bool {
return CompareTablesByStringKey(_a, _b, *key);
},
SwapSerializedTables);
} else {
SimpleQsort<Offset<Table>>(
v->data(), v->data() + v->size(), 1,
- [key](const Offset<Table> *_a, const Offset<Table> *_b) -> bool {
+ [key](const Offset<Table>* _a, const Offset<Table>* _b) -> bool {
return CompareTablesByScalarKey(_a, _b, *key);
},
SwapSerializedTables);
@@ -1818,15 +1850,15 @@
return NoError();
}
-CheckedError Parser::ParseArray(Value &array) {
+CheckedError Parser::ParseArray(Value& array) {
std::vector<Value> stack;
FlatBufferBuilder builder;
- const auto &type = array.type.VectorType();
+ const auto& type = array.type.VectorType();
auto length = array.type.fixed_length;
size_t count = 0;
- auto err = ParseVectorDelimiters(count, [&](size_t &) -> CheckedError {
+ auto err = ParseVectorDelimiters(count, [&](size_t&) -> CheckedError {
stack.emplace_back(Value());
- auto &val = stack.back();
+ auto& val = stack.back();
val.type = type;
if (IsStruct(type)) {
ECHECK(ParseTable(*val.type.struct_def, &val.constant, nullptr));
@@ -1839,7 +1871,7 @@
if (length != count) return Error("Fixed-length array size is incorrect.");
for (auto it = stack.rbegin(); it != stack.rend(); ++it) {
- auto &val = *it;
+ auto& val = *it;
// clang-format off
switch (val.type.base_type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
@@ -1860,14 +1892,14 @@
}
array.constant.assign(
- reinterpret_cast<const char *>(builder.GetCurrentBufferPointer()),
+ reinterpret_cast<const char*>(builder.GetCurrentBufferPointer()),
InlineSize(array.type));
return NoError();
}
-CheckedError Parser::ParseNestedFlatbuffer(Value &val, FieldDef *field,
+CheckedError Parser::ParseNestedFlatbuffer(Value& val, FieldDef* field,
size_t fieldn,
- const StructDef *parent_struct_def) {
+ const StructDef* parent_struct_def) {
if (token_ == '[') { // backwards compat for 'legacy' ubyte buffers
if (opts.json_nested_legacy_flatbuffers) {
ECHECK(ParseAnyValue(val, field, fieldn, parent_struct_def, 0));
@@ -1897,7 +1929,9 @@
nested_parser.enums_.dict.clear();
nested_parser.enums_.vec.clear();
- if (!ok) { ECHECK(Error(nested_parser.error_)); }
+ if (!ok) {
+ ECHECK(Error(nested_parser.error_));
+ }
// Force alignment for nested flatbuffer
builder_.ForceVectorAlignment(
nested_parser.builder_.GetSize(), sizeof(uint8_t),
@@ -1910,7 +1944,7 @@
return NoError();
}
-CheckedError Parser::ParseMetaData(SymbolTable<Value> *attributes) {
+CheckedError Parser::ParseMetaData(SymbolTable<Value>* attributes) {
if (Is('(')) {
NEXT();
for (;;) {
@@ -1938,8 +1972,8 @@
return NoError();
}
-CheckedError Parser::ParseEnumFromString(const Type &type,
- std::string *result) {
+CheckedError Parser::ParseEnumFromString(const Type& type,
+ std::string* result) {
const auto base_type =
type.enum_def ? type.enum_def->underlying_type.base_type : type.base_type;
if (!IsInteger(base_type)) return Error("not a valid value for this field");
@@ -1949,7 +1983,7 @@
const auto last = (std::string::npos == delim);
auto word = attribute_.substr(pos, !last ? delim - pos : std::string::npos);
pos = !last ? delim + 1 : std::string::npos;
- const EnumVal *ev = nullptr;
+ const EnumVal* ev = nullptr;
if (type.enum_def) {
ev = type.enum_def->Lookup(word);
} else {
@@ -1970,9 +2004,9 @@
return NoError();
}
-CheckedError Parser::ParseHash(Value &e, FieldDef *field) {
+CheckedError Parser::ParseHash(Value& e, FieldDef* field) {
FLATBUFFERS_ASSERT(field);
- Value *hash_name = field->attributes.Lookup("hash");
+ Value* hash_name = field->attributes.Lookup("hash");
switch (e.type.base_type) {
case BASE_TYPE_SHORT: {
auto hash = FindHashFunction16(hash_name->constant.c_str());
@@ -2010,7 +2044,8 @@
e.constant = NumToString(hashed_value);
break;
}
- default: FLATBUFFERS_ASSERT(0);
+ default:
+ FLATBUFFERS_ASSERT(0);
}
NEXT();
return NoError();
@@ -2020,7 +2055,7 @@
return Error("cannot parse value starting with: " + TokenToStringId(token_));
}
-CheckedError Parser::ParseFunction(const std::string *name, Value &e) {
+CheckedError Parser::ParseFunction(const std::string* name, Value& e) {
ParseDepthGuard depth_guard(this);
ECHECK(depth_guard.Check());
@@ -2063,9 +2098,9 @@
return NoError();
}
-CheckedError Parser::TryTypedValue(const std::string *name, int dtoken,
- bool check, Value &e, BaseType req,
- bool *destmatch) {
+CheckedError Parser::TryTypedValue(const std::string* name, int dtoken,
+ bool check, Value& e, BaseType req,
+ bool* destmatch) {
FLATBUFFERS_ASSERT(*destmatch == false && dtoken == token_);
*destmatch = true;
e.constant = attribute_;
@@ -2082,7 +2117,7 @@
// The exponent suffix of hexadecimal float-point number is mandatory.
// A hex-integer constant is forbidden as an initializer of float number.
if ((kTokenFloatConstant != dtoken) && IsFloat(e.type.base_type)) {
- const auto &s = e.constant;
+ const auto& s = e.constant;
const auto k = s.find_first_of("0123456789.");
if ((std::string::npos != k) && (s.length() > (k + 1)) &&
(s[k] == '0' && is_alpha_char(s[k + 1], 'X')) &&
@@ -2097,7 +2132,7 @@
return NoError();
}
-CheckedError Parser::ParseSingleValue(const std::string *name, Value &e,
+CheckedError Parser::ParseSingleValue(const std::string* name, Value& e,
bool check_now) {
if (token_ == '+' || token_ == '-') {
const char sign = static_cast<char>(token_);
@@ -2112,7 +2147,9 @@
const auto is_tok_string = (token_ == kTokenStringConstant);
// First see if this could be a conversion function.
- if (is_tok_ident && *cursor_ == '(') { return ParseFunction(name, e); }
+ if (is_tok_ident && *cursor_ == '(') {
+ return ParseFunction(name, e);
+ }
// clang-format off
auto match = false;
@@ -2195,7 +2232,9 @@
// Match empty vectors for default-empty-vectors.
if (!match && IsVector(e.type) && token_ == '[') {
NEXT();
- if (token_ != ']') { return Error("Expected `]` in vector default"); }
+ if (token_ != ']') {
+ return Error("Expected `]` in vector default");
+ }
NEXT();
match = true;
e.constant = "[]";
@@ -2235,7 +2274,7 @@
return NoError();
}
-StructDef *Parser::LookupCreateStruct(const std::string &name,
+StructDef* Parser::LookupCreateStruct(const std::string& name,
bool create_if_new, bool definition) {
std::string qualified_name = current_namespace_->GetFullyQualifiedName(name);
// See if it exists pre-declared by an unqualified use.
@@ -2283,14 +2322,14 @@
return struct_def;
}
-const EnumVal *EnumDef::MinValue() const {
+const EnumVal* EnumDef::MinValue() const {
return vals.vec.empty() ? nullptr : vals.vec.front();
}
-const EnumVal *EnumDef::MaxValue() const {
+const EnumVal* EnumDef::MaxValue() const {
return vals.vec.empty() ? nullptr : vals.vec.back();
}
-uint64_t EnumDef::Distance(const EnumVal *v1, const EnumVal *v2) const {
+uint64_t EnumDef::Distance(const EnumVal* v1, const EnumVal* v2) const {
return IsUInt64() ? EnumDistanceImpl(v1->GetAsUInt64(), v2->GetAsUInt64())
: EnumDistanceImpl(v1->GetAsInt64(), v2->GetAsInt64());
}
@@ -2304,16 +2343,18 @@
return IsUInt64() ? NumToString(u64) : NumToString(static_cast<int64_t>(u64));
}
-EnumVal *EnumDef::ReverseLookup(int64_t enum_idx,
+EnumVal* EnumDef::ReverseLookup(int64_t enum_idx,
bool skip_union_default) const {
auto skip_first = static_cast<int>(is_union && skip_union_default);
for (auto it = Vals().begin() + skip_first; it != Vals().end(); ++it) {
- if ((*it)->GetAsInt64() == enum_idx) { return *it; }
+ if ((*it)->GetAsInt64() == enum_idx) {
+ return *it;
+ }
}
return nullptr;
}
-EnumVal *EnumDef::FindByValue(const std::string &constant) const {
+EnumVal* EnumDef::FindByValue(const std::string& constant) const {
int64_t i64;
auto done = false;
if (IsUInt64()) {
@@ -2329,17 +2370,19 @@
}
void EnumDef::SortByValue() {
- auto &v = vals.vec;
+ auto& v = vals.vec;
if (IsUInt64())
- std::sort(v.begin(), v.end(), [](const EnumVal *e1, const EnumVal *e2) {
+ std::sort(v.begin(), v.end(), [](const EnumVal* e1, const EnumVal* e2) {
if (e1->GetAsUInt64() == e2->GetAsUInt64()) {
return e1->name < e2->name;
}
return e1->GetAsUInt64() < e2->GetAsUInt64();
});
else
- std::sort(v.begin(), v.end(), [](const EnumVal *e1, const EnumVal *e2) {
- if (e1->GetAsInt64() == e2->GetAsInt64()) { return e1->name < e2->name; }
+ std::sort(v.begin(), v.end(), [](const EnumVal* e1, const EnumVal* e2) {
+ if (e1->GetAsInt64() == e2->GetAsInt64()) {
+ return e1->name < e2->name;
+ }
return e1->GetAsInt64() < e2->GetAsInt64();
});
}
@@ -2367,21 +2410,24 @@
vals.vec.erase(++result, last);
}
-template<typename T> void EnumDef::ChangeEnumValue(EnumVal *ev, T new_value) {
+template <typename T>
+void EnumDef::ChangeEnumValue(EnumVal* ev, T new_value) {
ev->value = static_cast<int64_t>(new_value);
}
namespace EnumHelper {
-template<BaseType E> struct EnumValType {
+template <BaseType E>
+struct EnumValType {
typedef int64_t type;
};
-template<> struct EnumValType<BASE_TYPE_ULONG> {
+template <>
+struct EnumValType<BASE_TYPE_ULONG> {
typedef uint64_t type;
};
} // namespace EnumHelper
struct EnumValBuilder {
- EnumVal *CreateEnumerator(const std::string &ev_name) {
+ EnumVal* CreateEnumerator(const std::string& ev_name) {
FLATBUFFERS_ASSERT(!temp);
auto first = enum_def.vals.vec.empty();
user_value = first;
@@ -2389,14 +2435,14 @@
return temp;
}
- EnumVal *CreateEnumerator(const std::string &ev_name, int64_t val) {
+ EnumVal* CreateEnumerator(const std::string& ev_name, int64_t val) {
FLATBUFFERS_ASSERT(!temp);
user_value = true;
temp = new EnumVal(ev_name, val);
return temp;
}
- FLATBUFFERS_CHECKED_ERROR AcceptEnumerator(const std::string &name) {
+ FLATBUFFERS_CHECKED_ERROR AcceptEnumerator(const std::string& name) {
FLATBUFFERS_ASSERT(temp);
ECHECK(ValidateValue(&temp->value, false == user_value));
FLATBUFFERS_ASSERT((temp->union_type.enum_def == nullptr) ||
@@ -2411,7 +2457,7 @@
return AcceptEnumerator(temp->name);
}
- FLATBUFFERS_CHECKED_ERROR AssignEnumeratorValue(const std::string &value) {
+ FLATBUFFERS_CHECKED_ERROR AssignEnumeratorValue(const std::string& value) {
user_value = true;
auto fit = false;
if (enum_def.IsUInt64()) {
@@ -2427,8 +2473,8 @@
return NoError();
}
- template<BaseType E, typename CTYPE>
- inline FLATBUFFERS_CHECKED_ERROR ValidateImpl(int64_t *ev, int m) {
+ template <BaseType E, typename CTYPE>
+ inline FLATBUFFERS_CHECKED_ERROR ValidateImpl(int64_t* ev, int m) {
typedef typename EnumHelper::EnumValType<E>::type T; // int64_t or uint64_t
static_assert(sizeof(T) == sizeof(int64_t), "invalid EnumValType");
const auto v = static_cast<T>(*ev);
@@ -2443,7 +2489,7 @@
return NoError();
}
- FLATBUFFERS_CHECKED_ERROR ValidateValue(int64_t *ev, bool next) {
+ FLATBUFFERS_CHECKED_ERROR ValidateValue(int64_t* ev, bool next) {
// clang-format off
switch (enum_def.underlying_type.base_type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
@@ -2459,7 +2505,7 @@
return parser.Error("fatal: invalid enum underlying type");
}
- EnumValBuilder(Parser &_parser, EnumDef &_enum_def)
+ EnumValBuilder(Parser& _parser, EnumDef& _enum_def)
: parser(_parser),
enum_def(_enum_def),
temp(nullptr),
@@ -2467,23 +2513,23 @@
~EnumValBuilder() { delete temp; }
- Parser &parser;
- EnumDef &enum_def;
- EnumVal *temp;
+ Parser& parser;
+ EnumDef& enum_def;
+ EnumVal* temp;
bool user_value;
};
-CheckedError Parser::ParseEnum(const bool is_union, EnumDef **dest,
- const char *filename) {
+CheckedError Parser::ParseEnum(const bool is_union, EnumDef** dest,
+ const char* filename) {
std::vector<std::string> enum_comment = doc_comment_;
NEXT();
std::string enum_name = attribute_;
EXPECT(kTokenIdentifier);
- EnumDef *enum_def;
+ EnumDef* enum_def;
ECHECK(StartEnum(enum_name, is_union, &enum_def));
if (filename != nullptr && !opts.project_root.empty()) {
- enum_def->declaration_file =
- &GetPooledString(FilePath(opts.project_root, filename, opts.binary_schema_absolute_paths));
+ enum_def->declaration_file = &GetPooledString(FilePath(
+ opts.project_root, filename, opts.binary_schema_absolute_paths));
}
enum_def->doc_comment = enum_comment;
if (!opts.proto_mode) {
@@ -2511,14 +2557,15 @@
if (explicit_underlying_type) {
// Specify the integer type underlying this enum.
ECHECK(ParseType(enum_def->underlying_type));
- if (!IsInteger(enum_def->underlying_type.base_type) || IsBool(enum_def->underlying_type.base_type)) {
- return Error("underlying " + std::string(is_union ? "union" : "enum") + "type must be integral");
+ if (!IsInteger(enum_def->underlying_type.base_type) ||
+ IsBool(enum_def->underlying_type.base_type)) {
+ return Error("underlying " + std::string(is_union ? "union" : "enum") +
+ "type must be integral");
}
-
+
// Make this type refer back to the enum it was derived from.
enum_def->underlying_type.enum_def = enum_def;
}
-
}
ECHECK(ParseMetaData(&enum_def->attributes));
const auto underlying_type = enum_def->underlying_type.base_type;
@@ -2537,12 +2584,12 @@
evb.CreateEnumerator("NONE");
ECHECK(evb.AcceptEnumerator());
}
- std::set<std::pair<BaseType, StructDef *>> union_types;
+ std::set<std::pair<BaseType, StructDef*>> union_types;
while (!Is('}')) {
if (opts.proto_mode && attribute_ == "option") {
ECHECK(ParseProtoOption());
} else {
- auto &ev = *evb.CreateEnumerator(attribute_);
+ auto& ev = *evb.CreateEnumerator(attribute_);
auto full_name = ev.name;
ev.doc_comment = doc_comment_;
EXPECT(kTokenIdentifier);
@@ -2633,8 +2680,8 @@
return NoError();
}
-CheckedError Parser::StartStruct(const std::string &name, StructDef **dest) {
- auto &struct_def = *LookupCreateStruct(name, true, true);
+CheckedError Parser::StartStruct(const std::string& name, StructDef** dest) {
+ auto& struct_def = *LookupCreateStruct(name, true, true);
if (!struct_def.predecl)
return Error("datatype already exists: " +
current_namespace_->GetFullyQualifiedName(name));
@@ -2649,12 +2696,12 @@
return NoError();
}
-CheckedError Parser::CheckClash(std::vector<FieldDef *> &fields,
- StructDef *struct_def, const char *suffix,
+CheckedError Parser::CheckClash(std::vector<FieldDef*>& fields,
+ StructDef* struct_def, const char* suffix,
BaseType basetype) {
auto len = strlen(suffix);
for (auto it = fields.begin(); it != fields.end(); ++it) {
- auto &fname = (*it)->name;
+ auto& fname = (*it)->name;
if (fname.length() > len &&
fname.compare(fname.length() - len, len, suffix) == 0 &&
(*it)->value.type.base_type != BASE_TYPE_UTYPE) {
@@ -2671,19 +2718,20 @@
std::vector<IncludedFile> Parser::GetIncludedFiles() const {
const auto it = files_included_per_file_.find(file_being_parsed_);
- if (it == files_included_per_file_.end()) { return {}; }
+ if (it == files_included_per_file_.end()) {
+ return {};
+ }
- return { it->second.cbegin(), it->second.cend() };
+ return {it->second.cbegin(), it->second.cend()};
}
-bool Parser::SupportsOptionalScalars(const flatbuffers::IDLOptions &opts) {
+bool Parser::SupportsOptionalScalars(const flatbuffers::IDLOptions& opts) {
static FLATBUFFERS_CONSTEXPR unsigned long supported_langs =
IDLOptions::kRust | IDLOptions::kSwift | IDLOptions::kLobster |
IDLOptions::kKotlin | IDLOptions::kKotlinKmp | IDLOptions::kCpp |
IDLOptions::kJava | IDLOptions::kCSharp | IDLOptions::kTs |
IDLOptions::kBinary | IDLOptions::kGo | IDLOptions::kPython |
- IDLOptions::kJson |
- IDLOptions::kNim;
+ IDLOptions::kJson | IDLOptions::kNim;
unsigned long langs = opts.lang_to_generate;
return (langs > 0 && langs < IDLOptions::kMAX) && !(langs & ~supported_langs);
}
@@ -2719,11 +2767,11 @@
}
bool Parser::SupportsUnionUnderlyingType() const {
- return (opts.lang_to_generate & ~(IDLOptions::kCpp | IDLOptions::kTs |
- IDLOptions::kBinary)) == 0;
+ return (opts.lang_to_generate &
+ ~(IDLOptions::kCpp | IDLOptions::kTs | IDLOptions::kBinary)) == 0;
}
-Namespace *Parser::UniqueNamespace(Namespace *ns) {
+Namespace* Parser::UniqueNamespace(Namespace* ns) {
for (auto it = namespaces_.begin(); it != namespaces_.end(); ++it) {
if (ns->components == (*it)->components) {
delete ns;
@@ -2734,8 +2782,8 @@
return ns;
}
-std::string Parser::UnqualifiedName(const std::string &full_qualified_name) {
- Namespace *ns = new Namespace();
+std::string Parser::UnqualifiedName(const std::string& full_qualified_name) {
+ Namespace* ns = new Namespace();
std::size_t current, previous = 0;
current = full_qualified_name.find('.');
@@ -2749,20 +2797,20 @@
return full_qualified_name.substr(previous, current - previous);
}
-CheckedError Parser::ParseDecl(const char *filename) {
+CheckedError Parser::ParseDecl(const char* filename) {
std::vector<std::string> dc = doc_comment_;
bool fixed = IsIdent("struct");
if (!fixed && !IsIdent("table")) return Error("declaration expected");
NEXT();
std::string name = attribute_;
EXPECT(kTokenIdentifier);
- StructDef *struct_def;
+ StructDef* struct_def;
ECHECK(StartStruct(name, &struct_def));
struct_def->doc_comment = dc;
struct_def->fixed = fixed;
if (filename && !opts.project_root.empty()) {
- struct_def->declaration_file =
- &GetPooledString(FilePath(opts.project_root, filename, opts.binary_schema_absolute_paths));
+ struct_def->declaration_file = &GetPooledString(FilePath(
+ opts.project_root, filename, opts.binary_schema_absolute_paths));
}
ECHECK(ParseMetaData(&struct_def->attributes));
struct_def->sortbysize =
@@ -2781,7 +2829,7 @@
}
struct_def->PadLastField(struct_def->minalign);
// Check if this is a table that has manual id assignments
- auto &fields = struct_def->fields.vec;
+ auto& fields = struct_def->fields.vec;
if (!fixed && fields.size()) {
size_t num_id_fields = 0;
for (auto it = fields.begin(); it != fields.end(); ++it) {
@@ -2807,8 +2855,8 @@
FLATBUFFERS_ASSERT(fields.size() <=
flatbuffers::numeric_limits<voffset_t>::max());
for (voffset_t i = 0; i < static_cast<voffset_t>(fields.size()); i++) {
- auto &field = *fields[i];
- const auto &id_str = field.attributes.Lookup("id")->constant;
+ auto& field = *fields[i];
+ const auto& id_str = field.attributes.Lookup("id")->constant;
// Metadata values have a dynamic type, they can be `float`, 'int', or
// 'string`.
@@ -2844,19 +2892,19 @@
return NoError();
}
-CheckedError Parser::ParseService(const char *filename) {
+CheckedError Parser::ParseService(const char* filename) {
std::vector<std::string> service_comment = doc_comment_;
NEXT();
auto service_name = attribute_;
EXPECT(kTokenIdentifier);
- auto &service_def = *new ServiceDef();
+ auto& service_def = *new ServiceDef();
service_def.name = service_name;
service_def.file = file_being_parsed_;
service_def.doc_comment = service_comment;
service_def.defined_namespace = current_namespace_;
if (filename != nullptr && !opts.project_root.empty()) {
- service_def.declaration_file =
- &GetPooledString(FilePath(opts.project_root, filename, opts.binary_schema_absolute_paths));
+ service_def.declaration_file = &GetPooledString(FilePath(
+ opts.project_root, filename, opts.binary_schema_absolute_paths));
}
if (services_.Add(current_namespace_->GetFullyQualifiedName(service_name),
&service_def))
@@ -2876,7 +2924,7 @@
if (reqtype.base_type != BASE_TYPE_STRUCT || reqtype.struct_def->fixed ||
resptype.base_type != BASE_TYPE_STRUCT || resptype.struct_def->fixed)
return Error("rpc request and response types must be tables");
- auto &rpc = *new RPCCall();
+ auto& rpc = *new RPCCall();
rpc.name = rpc_name;
rpc.request = reqtype.struct_def;
rpc.response = resptype.struct_def;
@@ -2890,7 +2938,7 @@
return NoError();
}
-bool Parser::SetRootType(const char *name) {
+bool Parser::SetRootType(const char* name) {
root_struct_def_ = LookupStruct(name);
if (!root_struct_def_)
root_struct_def_ =
@@ -2906,7 +2954,9 @@
(*it)->generated = true;
}
for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) {
- if (!(*it)->predecl) { (*it)->generated = true; }
+ if (!(*it)->predecl) {
+ (*it)->generated = true;
+ }
}
for (auto it = services_.vec.begin(); it != services_.vec.end(); ++it) {
(*it)->generated = true;
@@ -2942,8 +2992,8 @@
} else if (IsIdent("message") || isextend) {
std::vector<std::string> struct_comment = doc_comment_;
NEXT();
- StructDef *struct_def = nullptr;
- Namespace *parent_namespace = nullptr;
+ StructDef* struct_def = nullptr;
+ Namespace* parent_namespace = nullptr;
if (isextend) {
if (Is('.')) NEXT(); // qualified names may start with a . ?
auto id = attribute_;
@@ -2968,11 +3018,13 @@
}
struct_def->doc_comment = struct_comment;
ECHECK(ParseProtoFields(struct_def, isextend, false));
- if (!isextend) { current_namespace_ = parent_namespace; }
+ if (!isextend) {
+ current_namespace_ = parent_namespace;
+ }
if (Is(';')) NEXT();
} else if (IsIdent("enum")) {
// These are almost the same, just with different terminator:
- EnumDef *enum_def;
+ EnumDef* enum_def;
ECHECK(ParseEnum(false, &enum_def, nullptr));
if (Is(';')) NEXT();
// Temp: remove any duplicates, as .fbs files can't handle them.
@@ -2996,9 +3048,9 @@
return NoError();
}
-CheckedError Parser::StartEnum(const std::string &name, bool is_union,
- EnumDef **dest) {
- auto &enum_def = *new EnumDef();
+CheckedError Parser::StartEnum(const std::string& name, bool is_union,
+ EnumDef** dest) {
+ auto& enum_def = *new EnumDef();
enum_def.name = name;
enum_def.file = file_being_parsed_;
enum_def.doc_comment = doc_comment_;
@@ -3014,7 +3066,7 @@
return NoError();
}
-CheckedError Parser::ParseProtoFields(StructDef *struct_def, bool isextend,
+CheckedError Parser::ParseProtoFields(StructDef* struct_def, bool isextend,
bool inside_oneof) {
EXPECT('{');
while (token_ != '}') {
@@ -3093,8 +3145,8 @@
// can't error, proto3 allows decls without any of the above.
}
}
- StructDef *anonymous_struct = nullptr;
- EnumDef *oneof_union = nullptr;
+ StructDef* anonymous_struct = nullptr;
+ EnumDef* oneof_union = nullptr;
Type type;
if (IsIdent("group") || oneof) {
if (!oneof) NEXT();
@@ -3133,7 +3185,7 @@
proto_field_id = attribute_;
EXPECT(kTokenIntegerConstant);
}
- FieldDef *field = nullptr;
+ FieldDef* field = nullptr;
if (isextend) {
// We allow a field to be re-defined when extending.
// TODO: are there situations where that is problematic?
@@ -3189,8 +3241,8 @@
if (Is(';')) NEXT();
for (auto field_it = oneof_struct.fields.vec.begin();
field_it != oneof_struct.fields.vec.end(); ++field_it) {
- const auto &oneof_field = **field_it;
- const auto &oneof_type = oneof_field.value.type;
+ const auto& oneof_field = **field_it;
+ const auto& oneof_type = oneof_field.value.type;
if (oneof_type.base_type != BASE_TYPE_STRUCT ||
!oneof_type.struct_def || oneof_type.struct_def->fixed)
return Error("oneof '" + name +
@@ -3211,7 +3263,7 @@
return NoError();
}
-CheckedError Parser::ParseProtoMapField(StructDef *struct_def) {
+CheckedError Parser::ParseProtoMapField(StructDef* struct_def) {
NEXT();
EXPECT('<');
Type key_type;
@@ -3228,20 +3280,20 @@
EXPECT(';');
auto entry_table_name = ConvertCase(field_name, Case::kUpperCamel) + "Entry";
- StructDef *entry_table;
+ StructDef* entry_table;
ECHECK(StartStruct(entry_table_name, &entry_table));
entry_table->has_key = true;
- FieldDef *key_field;
+ FieldDef* key_field;
ECHECK(AddField(*entry_table, "key", key_type, &key_field));
key_field->key = true;
- FieldDef *value_field;
+ FieldDef* value_field;
ECHECK(AddField(*entry_table, "value", value_type, &value_field));
Type field_type;
field_type.base_type = BASE_TYPE_VECTOR;
field_type.element = BASE_TYPE_STRUCT;
field_type.struct_def = entry_table;
- FieldDef *field;
+ FieldDef* field;
ECHECK(AddField(*struct_def, field_name, field_type, &field));
if (!proto_field_id.empty()) {
auto val = new Value();
@@ -3293,29 +3345,27 @@
}
// Parse a protobuf type, and map it to the corresponding FlatBuffer one.
-CheckedError Parser::ParseTypeFromProtoType(Type *type) {
+CheckedError Parser::ParseTypeFromProtoType(Type* type) {
struct type_lookup {
- const char *proto_type;
+ const char* proto_type;
BaseType fb_type, element;
};
- static type_lookup lookup[] = {
- { "float", BASE_TYPE_FLOAT, BASE_TYPE_NONE },
- { "double", BASE_TYPE_DOUBLE, BASE_TYPE_NONE },
- { "int32", BASE_TYPE_INT, BASE_TYPE_NONE },
- { "int64", BASE_TYPE_LONG, BASE_TYPE_NONE },
- { "uint32", BASE_TYPE_UINT, BASE_TYPE_NONE },
- { "uint64", BASE_TYPE_ULONG, BASE_TYPE_NONE },
- { "sint32", BASE_TYPE_INT, BASE_TYPE_NONE },
- { "sint64", BASE_TYPE_LONG, BASE_TYPE_NONE },
- { "fixed32", BASE_TYPE_UINT, BASE_TYPE_NONE },
- { "fixed64", BASE_TYPE_ULONG, BASE_TYPE_NONE },
- { "sfixed32", BASE_TYPE_INT, BASE_TYPE_NONE },
- { "sfixed64", BASE_TYPE_LONG, BASE_TYPE_NONE },
- { "bool", BASE_TYPE_BOOL, BASE_TYPE_NONE },
- { "string", BASE_TYPE_STRING, BASE_TYPE_NONE },
- { "bytes", BASE_TYPE_VECTOR, BASE_TYPE_UCHAR },
- { nullptr, BASE_TYPE_NONE, BASE_TYPE_NONE }
- };
+ static type_lookup lookup[] = {{"float", BASE_TYPE_FLOAT, BASE_TYPE_NONE},
+ {"double", BASE_TYPE_DOUBLE, BASE_TYPE_NONE},
+ {"int32", BASE_TYPE_INT, BASE_TYPE_NONE},
+ {"int64", BASE_TYPE_LONG, BASE_TYPE_NONE},
+ {"uint32", BASE_TYPE_UINT, BASE_TYPE_NONE},
+ {"uint64", BASE_TYPE_ULONG, BASE_TYPE_NONE},
+ {"sint32", BASE_TYPE_INT, BASE_TYPE_NONE},
+ {"sint64", BASE_TYPE_LONG, BASE_TYPE_NONE},
+ {"fixed32", BASE_TYPE_UINT, BASE_TYPE_NONE},
+ {"fixed64", BASE_TYPE_ULONG, BASE_TYPE_NONE},
+ {"sfixed32", BASE_TYPE_INT, BASE_TYPE_NONE},
+ {"sfixed64", BASE_TYPE_LONG, BASE_TYPE_NONE},
+ {"bool", BASE_TYPE_BOOL, BASE_TYPE_NONE},
+ {"string", BASE_TYPE_STRING, BASE_TYPE_NONE},
+ {"bytes", BASE_TYPE_VECTOR, BASE_TYPE_UCHAR},
+ {nullptr, BASE_TYPE_NONE, BASE_TYPE_NONE}};
for (auto tl = lookup; tl->proto_type; tl++) {
if (attribute_ == tl->proto_type) {
type->base_type = tl->fb_type;
@@ -3337,8 +3387,8 @@
case '{': {
size_t fieldn_outer = 0;
return ParseTableDelimiters(fieldn_outer, nullptr,
- [&](const std::string &, size_t &fieldn,
- const StructDef *) -> CheckedError {
+ [&](const std::string&, size_t& fieldn,
+ const StructDef*) -> CheckedError {
ECHECK(SkipAnyJsonValue());
fieldn++;
return NoError();
@@ -3347,11 +3397,13 @@
case '[': {
size_t count = 0;
return ParseVectorDelimiters(
- count, [&](size_t &) -> CheckedError { return SkipAnyJsonValue(); });
+ count, [&](size_t&) -> CheckedError { return SkipAnyJsonValue(); });
}
case kTokenStringConstant:
case kTokenIntegerConstant:
- case kTokenFloatConstant: NEXT(); break;
+ case kTokenFloatConstant:
+ NEXT();
+ break;
default:
if (IsIdent("true") || IsIdent("false") || IsIdent("null") ||
IsIdent("inf")) {
@@ -3363,7 +3415,7 @@
}
CheckedError Parser::ParseFlexBufferNumericConstant(
- flexbuffers::Builder *builder) {
+ flexbuffers::Builder* builder) {
double d;
if (!StringToNumber(attribute_.c_str(), &d))
return Error("unexpected floating-point constant: " + attribute_);
@@ -3371,7 +3423,7 @@
return NoError();
}
-CheckedError Parser::ParseFlexBufferValue(flexbuffers::Builder *builder) {
+CheckedError Parser::ParseFlexBufferValue(flexbuffers::Builder* builder) {
ParseDepthGuard depth_guard(this);
ECHECK(depth_guard.Check());
@@ -3381,8 +3433,8 @@
size_t fieldn_outer = 0;
auto err =
ParseTableDelimiters(fieldn_outer, nullptr,
- [&](const std::string &name, size_t &fieldn,
- const StructDef *) -> CheckedError {
+ [&](const std::string& name, size_t& fieldn,
+ const StructDef*) -> CheckedError {
builder->Key(name);
ECHECK(ParseFlexBufferValue(builder));
fieldn++;
@@ -3397,7 +3449,7 @@
case '[': {
auto start = builder->StartVector();
size_t count = 0;
- ECHECK(ParseVectorDelimiters(count, [&](size_t &) -> CheckedError {
+ ECHECK(ParseVectorDelimiters(count, [&](size_t&) -> CheckedError {
return ParseFlexBufferValue(builder);
}));
builder->EndVector(start, false, false);
@@ -3449,8 +3501,8 @@
return NoError();
}
-bool Parser::ParseFlexBuffer(const char *source, const char *source_filename,
- flexbuffers::Builder *builder) {
+bool Parser::ParseFlexBuffer(const char* source, const char* source_filename,
+ flexbuffers::Builder* builder) {
const auto initial_depth = parse_depth_counter_;
(void)initial_depth;
auto ok = !StartParseFile(source, source_filename).Check() &&
@@ -3460,8 +3512,8 @@
return ok;
}
-bool Parser::Parse(const char *source, const char **include_paths,
- const char *source_filename) {
+bool Parser::Parse(const char* source, const char** include_paths,
+ const char* source_filename) {
const auto initial_depth = parse_depth_counter_;
(void)initial_depth;
bool r;
@@ -3475,7 +3527,7 @@
return r;
}
-bool Parser::ParseJson(const char *json, const char *json_filename) {
+bool Parser::ParseJson(const char* json, const char* json_filename) {
const auto initial_depth = parse_depth_counter_;
(void)initial_depth;
builder_.Clear();
@@ -3489,8 +3541,8 @@
return std::distance(source_, prev_cursor_);
}
-CheckedError Parser::StartParseFile(const char *source,
- const char *source_filename) {
+CheckedError Parser::StartParseFile(const char* source,
+ const char* source_filename) {
file_being_parsed_ = source_filename ? source_filename : "";
source_ = source;
ResetState(source_);
@@ -3501,18 +3553,18 @@
return NoError();
}
-CheckedError Parser::ParseRoot(const char *source, const char **include_paths,
- const char *source_filename) {
+CheckedError Parser::ParseRoot(const char* source, const char** include_paths,
+ const char* source_filename) {
ECHECK(DoParse(source, include_paths, source_filename, nullptr));
// Check that all types were defined.
for (auto it = structs_.vec.begin(); it != structs_.vec.end();) {
- auto &struct_def = **it;
+ auto& struct_def = **it;
if (struct_def.predecl) {
if (opts.proto_mode) {
// Protos allow enums to be used before declaration, so check if that
// is the case here.
- EnumDef *enum_def = nullptr;
+ EnumDef* enum_def = nullptr;
for (size_t components =
struct_def.defined_namespace->components.size() + 1;
components && !enum_def; components--) {
@@ -3526,14 +3578,14 @@
auto initial_count = struct_def.refcount;
for (auto struct_it = structs_.vec.begin();
struct_it != structs_.vec.end(); ++struct_it) {
- auto &sd = **struct_it;
+ auto& sd = **struct_it;
for (auto field_it = sd.fields.vec.begin();
field_it != sd.fields.vec.end(); ++field_it) {
- auto &field = **field_it;
+ auto& field = **field_it;
if (field.value.type.struct_def == &struct_def) {
field.value.type.struct_def = nullptr;
field.value.type.enum_def = enum_def;
- auto &bt = IsVector(field.value.type)
+ auto& bt = IsVector(field.value.type)
? field.value.type.element
: field.value.type.base_type;
FLATBUFFERS_ASSERT(bt == BASE_TYPE_STRUCT);
@@ -3566,11 +3618,11 @@
// This check has to happen here and not earlier, because only now do we
// know for sure what the type of these are.
for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
- auto &enum_def = **it;
+ auto& enum_def = **it;
if (enum_def.is_union) {
for (auto val_it = enum_def.Vals().begin();
val_it != enum_def.Vals().end(); ++val_it) {
- auto &val = **val_it;
+ auto& val = **val_it;
if (!(opts.lang_to_generate != 0 && SupportsAdvancedUnionFeatures()) &&
(IsStruct(val.union_type) || IsString(val.union_type)))
@@ -3586,7 +3638,9 @@
if (err.Check()) return err;
// Parse JSON object only if the scheme has been parsed.
- if (token_ == '{') { ECHECK(DoParseJson()); }
+ if (token_ == '{') {
+ ECHECK(DoParseJson());
+ }
return NoError();
}
@@ -3595,34 +3649,40 @@
// Iterate over all structs/tables to validate we arent leaking
// any private (structs/tables/enums)
for (auto it = structs_.vec.begin(); it != structs_.vec.end(); it++) {
- auto &struct_def = **it;
+ auto& struct_def = **it;
for (auto fld_it = struct_def.fields.vec.begin();
fld_it != struct_def.fields.vec.end(); ++fld_it) {
- auto &field = **fld_it;
+ auto& field = **fld_it;
if (field.value.type.enum_def) {
auto err =
CheckPrivatelyLeakedFields(struct_def, *field.value.type.enum_def);
- if (err.Check()) { return err; }
+ if (err.Check()) {
+ return err;
+ }
} else if (field.value.type.struct_def) {
auto err = CheckPrivatelyLeakedFields(struct_def,
*field.value.type.struct_def);
- if (err.Check()) { return err; }
+ if (err.Check()) {
+ return err;
+ }
}
}
}
// Iterate over all enums to validate we arent leaking
// any private (structs/tables)
for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
- auto &enum_def = **it;
+ auto& enum_def = **it;
if (enum_def.is_union) {
for (auto val_it = enum_def.Vals().begin();
val_it != enum_def.Vals().end(); ++val_it) {
- auto &val = **val_it;
+ auto& val = **val_it;
if (val.union_type.struct_def) {
auto err =
CheckPrivatelyLeakedFields(enum_def, *val.union_type.struct_def);
- if (err.Check()) { return err; }
+ if (err.Check()) {
+ return err;
+ }
}
}
}
@@ -3630,8 +3690,8 @@
return NoError();
}
-CheckedError Parser::CheckPrivatelyLeakedFields(const Definition &def,
- const Definition &value_type) {
+CheckedError Parser::CheckPrivatelyLeakedFields(const Definition& def,
+ const Definition& value_type) {
if (!opts.no_leak_private_annotations) return NoError();
const auto is_private = def.attributes.Lookup("private");
const auto is_field_private = value_type.attributes.Lookup("private");
@@ -3643,9 +3703,9 @@
return NoError();
}
-CheckedError Parser::DoParse(const char *source, const char **include_paths,
- const char *source_filename,
- const char *include_filename) {
+CheckedError Parser::DoParse(const char* source, const char** include_paths,
+ const char* source_filename,
+ const char* include_filename) {
uint64_t source_hash = 0;
if (source_filename) {
// If the file is in-memory, don't include its contents in the hash as we
@@ -3663,7 +3723,7 @@
}
}
if (!include_paths) {
- static const char *current_directory[] = { "", nullptr };
+ static const char* current_directory[] = {"", nullptr};
include_paths = current_directory;
}
field_stack_.clear();
@@ -3835,7 +3895,7 @@
}
std::set<std::string> Parser::GetIncludedFilesRecursive(
- const std::string &file_name) const {
+ const std::string& file_name) const {
std::set<std::string> included_files;
std::list<std::string> to_process;
@@ -3848,8 +3908,8 @@
included_files.insert(current);
// Workaround the lack of const accessor in C++98 maps.
- auto &new_files =
- (*const_cast<std::map<std::string, std::set<IncludedFile>> *>(
+ auto& new_files =
+ (*const_cast<std::map<std::string, std::set<IncludedFile>>*>(
&files_included_per_file_))[current];
for (auto it = new_files.begin(); it != new_files.end(); ++it) {
if (included_files.find(it->filename) == included_files.end())
@@ -3864,8 +3924,8 @@
static flatbuffers::Offset<
flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
-SerializeAttributesCommon(const SymbolTable<Value> &attributes,
- FlatBufferBuilder *builder, const Parser &parser) {
+SerializeAttributesCommon(const SymbolTable<Value>& attributes,
+ FlatBufferBuilder* builder, const Parser& parser) {
std::vector<flatbuffers::Offset<reflection::KeyValue>> attrs;
for (auto kv = attributes.dict.begin(); kv != attributes.dict.end(); ++kv) {
auto it = parser.known_attributes_.find(kv->first);
@@ -3884,13 +3944,15 @@
}
static bool DeserializeAttributesCommon(
- SymbolTable<Value> &attributes, Parser &parser,
- const Vector<Offset<reflection::KeyValue>> *attrs) {
+ SymbolTable<Value>& attributes, Parser& parser,
+ const Vector<Offset<reflection::KeyValue>>* attrs) {
if (attrs == nullptr) return true;
for (uoffset_t i = 0; i < attrs->size(); ++i) {
auto kv = attrs->Get(i);
auto value = new Value();
- if (kv->value()) { value->constant = kv->value()->str(); }
+ if (kv->value()) {
+ value->constant = kv->value()->str();
+ }
if (attributes.Add(kv->key()->str(), value)) {
delete value;
return false;
@@ -3910,21 +3972,21 @@
auto offset = (*it)->Serialize(&builder_, *this);
object_offsets.push_back(offset);
(*it)->serialized_location = offset.o;
- const std::string *file = (*it)->declaration_file;
+ const std::string* file = (*it)->declaration_file;
if (file) files.insert(*file);
}
std::vector<Offset<reflection::Enum>> enum_offsets;
for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
auto offset = (*it)->Serialize(&builder_, *this);
enum_offsets.push_back(offset);
- const std::string *file = (*it)->declaration_file;
+ const std::string* file = (*it)->declaration_file;
if (file) files.insert(*file);
}
std::vector<Offset<reflection::Service>> service_offsets;
for (auto it = services_.vec.begin(); it != services_.vec.end(); ++it) {
auto offset = (*it)->Serialize(&builder_, *this);
service_offsets.push_back(offset);
- const std::string *file = (*it)->declaration_file;
+ const std::string* file = (*it)->declaration_file;
if (file) files.insert(*file);
}
@@ -3937,12 +3999,12 @@
std::vector<Offset<flatbuffers::String>> included_files;
for (auto f = files_included_per_file_.begin();
f != files_included_per_file_.end(); f++) {
-
const auto filename__ = builder_.CreateSharedString(FilePath(
opts.project_root, f->first, opts.binary_schema_absolute_paths));
for (auto i = f->second.begin(); i != f->second.end(); i++) {
included_files.push_back(builder_.CreateSharedString(
- FilePath(opts.project_root, i->filename, opts.binary_schema_absolute_paths)));
+ FilePath(opts.project_root, i->filename,
+ opts.binary_schema_absolute_paths)));
}
const auto included_files__ = builder_.CreateVector(included_files);
included_files.clear();
@@ -3970,8 +4032,8 @@
}
}
-Offset<reflection::Object> StructDef::Serialize(FlatBufferBuilder *builder,
- const Parser &parser) const {
+Offset<reflection::Object> StructDef::Serialize(FlatBufferBuilder* builder,
+ const Parser& parser) const {
std::vector<Offset<reflection::Field>> field_offsets;
for (auto it = fields.vec.begin(); it != fields.vec.end(); ++it) {
field_offsets.push_back((*it)->Serialize(
@@ -3991,13 +4053,13 @@
static_cast<int>(bytesize), attr__, docs__, file__);
}
-bool StructDef::Deserialize(Parser &parser, const reflection::Object *object) {
+bool StructDef::Deserialize(Parser& parser, const reflection::Object* object) {
if (!DeserializeAttributes(parser, object->attributes())) return false;
DeserializeDoc(doc_comment, object->documentation());
name = parser.UnqualifiedName(object->name()->str());
predecl = false;
sortbysize = attributes.Lookup("original_order") == nullptr && !fixed;
- const auto &of = *(object->fields());
+ const auto& of = *(object->fields());
auto indexes = std::vector<uoffset_t>(of.size());
for (uoffset_t i = 0; i < of.size(); i++) indexes[of.Get(i)->id()] = i;
size_t tmp_struct_size = 0;
@@ -4033,9 +4095,9 @@
return true;
}
-Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder,
+Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder* builder,
uint16_t id,
- const Parser &parser) const {
+ const Parser& parser) const {
auto name__ = builder->CreateString(name);
auto type__ = value.type.Serialize(builder);
auto attr__ = SerializeAttributes(builder, parser);
@@ -4055,7 +4117,7 @@
// space by sharing it. Same for common values of value.type.
}
-bool FieldDef::Deserialize(Parser &parser, const reflection::Field *field) {
+bool FieldDef::Deserialize(Parser& parser, const reflection::Field* field) {
name = field->name()->str();
defined_namespace = parser.current_namespace_;
if (!value.type.Deserialize(parser, field->type())) return false;
@@ -4089,8 +4151,8 @@
return true;
}
-Offset<reflection::RPCCall> RPCCall::Serialize(FlatBufferBuilder *builder,
- const Parser &parser) const {
+Offset<reflection::RPCCall> RPCCall::Serialize(FlatBufferBuilder* builder,
+ const Parser& parser) const {
auto name__ = builder->CreateString(name);
auto attr__ = SerializeAttributes(builder, parser);
auto docs__ = parser.opts.binary_schema_comments && !doc_comment.empty()
@@ -4101,18 +4163,20 @@
response->serialized_location, attr__, docs__);
}
-bool RPCCall::Deserialize(Parser &parser, const reflection::RPCCall *call) {
+bool RPCCall::Deserialize(Parser& parser, const reflection::RPCCall* call) {
name = call->name()->str();
if (!DeserializeAttributes(parser, call->attributes())) return false;
DeserializeDoc(doc_comment, call->documentation());
request = parser.structs_.Lookup(call->request()->name()->str());
response = parser.structs_.Lookup(call->response()->name()->str());
- if (!request || !response) { return false; }
+ if (!request || !response) {
+ return false;
+ }
return true;
}
-Offset<reflection::Service> ServiceDef::Serialize(FlatBufferBuilder *builder,
- const Parser &parser) const {
+Offset<reflection::Service> ServiceDef::Serialize(FlatBufferBuilder* builder,
+ const Parser& parser) const {
std::vector<Offset<reflection::RPCCall>> servicecall_offsets;
for (auto it = calls.vec.begin(); it != calls.vec.end(); ++it) {
servicecall_offsets.push_back((*it)->Serialize(builder, parser));
@@ -4130,8 +4194,8 @@
file__);
}
-bool ServiceDef::Deserialize(Parser &parser,
- const reflection::Service *service) {
+bool ServiceDef::Deserialize(Parser& parser,
+ const reflection::Service* service) {
name = parser.UnqualifiedName(service->name()->str());
if (service->calls()) {
for (uoffset_t i = 0; i < service->calls()->size(); ++i) {
@@ -4148,8 +4212,8 @@
return true;
}
-Offset<reflection::Enum> EnumDef::Serialize(FlatBufferBuilder *builder,
- const Parser &parser) const {
+Offset<reflection::Enum> EnumDef::Serialize(FlatBufferBuilder* builder,
+ const Parser& parser) const {
std::vector<Offset<reflection::EnumVal>> enumval_offsets;
for (auto it = vals.vec.begin(); it != vals.vec.end(); ++it) {
enumval_offsets.push_back((*it)->Serialize(builder, parser));
@@ -4168,7 +4232,7 @@
attr__, docs__, file__);
}
-bool EnumDef::Deserialize(Parser &parser, const reflection::Enum *_enum) {
+bool EnumDef::Deserialize(Parser& parser, const reflection::Enum* _enum) {
name = parser.UnqualifiedName(_enum->name()->str());
for (uoffset_t i = 0; i < _enum->values()->size(); ++i) {
auto val = new EnumVal();
@@ -4189,18 +4253,18 @@
flatbuffers::Offset<
flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
-EnumVal::SerializeAttributes(FlatBufferBuilder *builder,
- const Parser &parser) const {
+EnumVal::SerializeAttributes(FlatBufferBuilder* builder,
+ const Parser& parser) const {
return SerializeAttributesCommon(attributes, builder, parser);
}
bool EnumVal::DeserializeAttributes(
- Parser &parser, const Vector<Offset<reflection::KeyValue>> *attrs) {
+ Parser& parser, const Vector<Offset<reflection::KeyValue>>* attrs) {
return DeserializeAttributesCommon(attributes, parser, attrs);
}
-Offset<reflection::EnumVal> EnumVal::Serialize(FlatBufferBuilder *builder,
- const Parser &parser) const {
+Offset<reflection::EnumVal> EnumVal::Serialize(FlatBufferBuilder* builder,
+ const Parser& parser) const {
const auto name__ = builder->CreateString(name);
const auto type__ = union_type.Serialize(builder);
const auto attr__ = SerializeAttributes(builder, parser);
@@ -4211,7 +4275,7 @@
attr__);
}
-bool EnumVal::Deserialize(Parser &parser, const reflection::EnumVal *val) {
+bool EnumVal::Deserialize(Parser& parser, const reflection::EnumVal* val) {
name = val->name()->str();
value = val->value();
if (!union_type.Deserialize(parser, val->union_type())) return false;
@@ -4220,7 +4284,7 @@
return true;
}
-Offset<reflection::Type> Type::Serialize(FlatBufferBuilder *builder) const {
+Offset<reflection::Type> Type::Serialize(FlatBufferBuilder* builder) const {
size_t element_size = SizeOf(element);
if (base_type == BASE_TYPE_VECTOR && element == BASE_TYPE_STRUCT &&
struct_def->bytesize != 0) {
@@ -4235,7 +4299,7 @@
static_cast<uint32_t>(element_size));
}
-bool Type::Deserialize(const Parser &parser, const reflection::Type *type) {
+bool Type::Deserialize(const Parser& parser, const reflection::Type* type) {
if (type == nullptr) return true;
base_type = static_cast<BaseType>(type->base_type());
element = static_cast<BaseType>(type->element());
@@ -4264,21 +4328,21 @@
flatbuffers::Offset<
flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
-Definition::SerializeAttributes(FlatBufferBuilder *builder,
- const Parser &parser) const {
+Definition::SerializeAttributes(FlatBufferBuilder* builder,
+ const Parser& parser) const {
return SerializeAttributesCommon(attributes, builder, parser);
}
bool Definition::DeserializeAttributes(
- Parser &parser, const Vector<Offset<reflection::KeyValue>> *attrs) {
+ Parser& parser, const Vector<Offset<reflection::KeyValue>>* attrs) {
return DeserializeAttributesCommon(attributes, parser, attrs);
}
/************************************************************************/
/* DESERIALIZATION */
/************************************************************************/
-bool Parser::Deserialize(const uint8_t *buf, const size_t size) {
- flatbuffers::Verifier verifier(reinterpret_cast<const uint8_t *>(buf), size);
+bool Parser::Deserialize(const uint8_t* buf, const size_t size) {
+ flatbuffers::Verifier verifier(reinterpret_cast<const uint8_t*>(buf), size);
bool size_prefixed = false;
if (!reflection::SchemaBufferHasIdentifier(buf)) {
if (!flatbuffers::BufferHasIdentifier(buf, reflection::SchemaIdentifier(),
@@ -4289,16 +4353,18 @@
}
auto verify_fn = size_prefixed ? &reflection::VerifySizePrefixedSchemaBuffer
: &reflection::VerifySchemaBuffer;
- if (!verify_fn(verifier)) { return false; }
+ if (!verify_fn(verifier)) {
+ return false;
+ }
auto schema = size_prefixed ? reflection::GetSizePrefixedSchema(buf)
: reflection::GetSchema(buf);
return Deserialize(schema);
}
-bool Parser::Deserialize(const reflection::Schema *schema) {
+bool Parser::Deserialize(const reflection::Schema* schema) {
file_identifier_ = schema->file_ident() ? schema->file_ident()->str() : "";
file_extension_ = schema->file_ext() ? schema->file_ext()->str() : "";
- std::map<std::string, Namespace *> namespaces_index;
+ std::map<std::string, Namespace*> namespaces_index;
// Create defs without deserializing so references from fields to structs and
// enums can be resolved.
@@ -4338,15 +4404,21 @@
auto struct_def = structs_.Lookup(qualified_name);
struct_def->defined_namespace =
GetNamespace(qualified_name, namespaces_, namespaces_index);
- if (!struct_def->Deserialize(*this, *it)) { return false; }
- if (schema->root_table() == *it) { root_struct_def_ = struct_def; }
+ if (!struct_def->Deserialize(*this, *it)) {
+ return false;
+ }
+ if (schema->root_table() == *it) {
+ root_struct_def_ = struct_def;
+ }
}
for (auto it = schema->enums()->begin(); it != schema->enums()->end(); ++it) {
std::string qualified_name = it->name()->str();
auto enum_def = enums_.Lookup(qualified_name);
enum_def->defined_namespace =
GetNamespace(qualified_name, namespaces_, namespaces_index);
- if (!enum_def->Deserialize(*this, *it)) { return false; }
+ if (!enum_def->Deserialize(*this, *it)) {
+ return false;
+ }
}
if (schema->services()) {
@@ -4379,17 +4451,17 @@
return true;
}
-std::string Parser::ConformTo(const Parser &base) {
+std::string Parser::ConformTo(const Parser& base) {
for (auto sit = structs_.vec.begin(); sit != structs_.vec.end(); ++sit) {
- auto &struct_def = **sit;
+ auto& struct_def = **sit;
auto qualified_name =
struct_def.defined_namespace->GetFullyQualifiedName(struct_def.name);
auto struct_def_base = base.LookupStruct(qualified_name);
if (!struct_def_base) continue;
- std::set<FieldDef *> renamed_fields;
+ std::set<FieldDef*> renamed_fields;
for (auto fit = struct_def.fields.vec.begin();
fit != struct_def.fields.vec.end(); ++fit) {
- auto &field = **fit;
+ auto& field = **fit;
auto field_base = struct_def_base->fields.Lookup(field.name);
const auto qualified_field_name = qualified_name + "." + field.name;
if (field_base) {
@@ -4429,7 +4501,7 @@
// deletion of trailing fields are not allowed
for (auto fit = struct_def_base->fields.vec.begin();
fit != struct_def_base->fields.vec.end(); ++fit) {
- auto &field_base = **fit;
+ auto& field_base = **fit;
// not a renamed field
if (renamed_fields.find(&field_base) == renamed_fields.end()) {
auto field = struct_def.fields.Lookup(field_base.name);
@@ -4441,14 +4513,14 @@
}
for (auto eit = enums_.vec.begin(); eit != enums_.vec.end(); ++eit) {
- auto &enum_def = **eit;
+ auto& enum_def = **eit;
auto qualified_name =
enum_def.defined_namespace->GetFullyQualifiedName(enum_def.name);
auto enum_def_base = base.enums_.Lookup(qualified_name);
if (!enum_def_base) continue;
for (auto evit = enum_def.Vals().begin(); evit != enum_def.Vals().end();
++evit) {
- auto &enum_val = **evit;
+ auto& enum_val = **evit;
auto enum_val_base = enum_def_base->Lookup(enum_val.name);
if (enum_val_base) {
if (enum_val != *enum_val_base)
@@ -4456,8 +4528,11 @@
}
}
// Check underlying type changes
- if (enum_def_base->underlying_type.base_type != enum_def.underlying_type.base_type) {
- return "underlying type differ for " + std::string(enum_def.is_union ? "union: " : "enum: ") + qualified_name;
+ if (enum_def_base->underlying_type.base_type !=
+ enum_def.underlying_type.base_type) {
+ return "underlying type differ for " +
+ std::string(enum_def.is_union ? "union: " : "enum: ") +
+ qualified_name;
}
}
return "";
diff --git a/src/reflection.cpp b/src/reflection.cpp
index f064c1c..e42baa2 100644
--- a/src/reflection.cpp
+++ b/src/reflection.cpp
@@ -24,47 +24,51 @@
namespace {
-static void CopyInline(FlatBufferBuilder &fbb,
- const reflection::Field &fielddef, const Table &table,
+static void CopyInline(FlatBufferBuilder& fbb,
+ const reflection::Field& fielddef, const Table& table,
size_t align, size_t size) {
fbb.Align(align);
- fbb.PushBytes(table.GetStruct<const uint8_t *>(fielddef.offset()), size);
+ fbb.PushBytes(table.GetStruct<const uint8_t*>(fielddef.offset()), size);
fbb.TrackField(fielddef.offset(), fbb.GetSize());
}
-static bool VerifyStruct(flatbuffers::Verifier &v,
- const flatbuffers::Table &parent_table,
- voffset_t field_offset, const reflection::Object &obj,
+static bool VerifyStruct(flatbuffers::Verifier& v,
+ const flatbuffers::Table& parent_table,
+ voffset_t field_offset, const reflection::Object& obj,
bool required) {
auto offset = parent_table.GetOptionalFieldOffset(field_offset);
- if (required && !offset) { return false; }
+ if (required && !offset) {
+ return false;
+ }
return !offset ||
- v.VerifyFieldStruct(reinterpret_cast<const uint8_t *>(&parent_table),
+ v.VerifyFieldStruct(reinterpret_cast<const uint8_t*>(&parent_table),
offset, obj.bytesize(), obj.minalign());
}
-static bool VerifyVectorOfStructs(flatbuffers::Verifier &v,
- const flatbuffers::Table &parent_table,
+static bool VerifyVectorOfStructs(flatbuffers::Verifier& v,
+ const flatbuffers::Table& parent_table,
voffset_t field_offset,
- const reflection::Object &obj,
+ const reflection::Object& obj,
bool required) {
- auto p = parent_table.GetPointer<const uint8_t *>(field_offset);
- if (required && !p) { return false; }
+ auto p = parent_table.GetPointer<const uint8_t*>(field_offset);
+ if (required && !p) {
+ return false;
+ }
return !p || v.VerifyVectorOrString(p, obj.bytesize());
}
// forward declare to resolve cyclic deps between VerifyObject and VerifyVector
-static bool VerifyObject(flatbuffers::Verifier &v,
- const reflection::Schema &schema,
- const reflection::Object &obj,
- const flatbuffers::Table *table, bool required);
+static bool VerifyObject(flatbuffers::Verifier& v,
+ const reflection::Schema& schema,
+ const reflection::Object& obj,
+ const flatbuffers::Table* table, bool required);
-static bool VerifyUnion(flatbuffers::Verifier &v,
- const reflection::Schema &schema, uint8_t utype,
- const uint8_t *elem,
- const reflection::Field &union_field) {
+static bool VerifyUnion(flatbuffers::Verifier& v,
+ const reflection::Schema& schema, uint8_t utype,
+ const uint8_t* elem,
+ const reflection::Field& union_field) {
if (!utype) return true; // Not present.
auto fb_enum = schema.enums()->Get(union_field.type()->index());
if (utype >= fb_enum->values()->size()) return false;
@@ -76,21 +80,21 @@
return v.VerifyFromPointer(elem, elem_obj->bytesize());
} else {
return VerifyObject(v, schema, *elem_obj,
- reinterpret_cast<const flatbuffers::Table *>(elem),
+ reinterpret_cast<const flatbuffers::Table*>(elem),
true);
}
}
case reflection::String:
- return v.VerifyString(
- reinterpret_cast<const flatbuffers::String *>(elem));
- default: return false;
+ return v.VerifyString(reinterpret_cast<const flatbuffers::String*>(elem));
+ default:
+ return false;
}
}
-static bool VerifyVector(flatbuffers::Verifier &v,
- const reflection::Schema &schema,
- const flatbuffers::Table &table,
- const reflection::Field &vec_field) {
+static bool VerifyVector(flatbuffers::Verifier& v,
+ const reflection::Schema& schema,
+ const flatbuffers::Table& table,
+ const reflection::Field& vec_field) {
FLATBUFFERS_ASSERT(vec_field.type()->base_type() == reflection::Vector);
if (!table.VerifyField<uoffset_t>(v, vec_field.offset(), sizeof(uoffset_t)))
return false;
@@ -149,8 +153,8 @@
table, vec_field);
if (!v.VerifyVector(vec)) return false;
if (!vec) return true;
- auto type_vec = table.GetPointer<Vector<uint8_t> *>(vec_field.offset() -
- sizeof(voffset_t));
+ auto type_vec = table.GetPointer<Vector<uint8_t>*>(vec_field.offset() -
+ sizeof(voffset_t));
if (!v.VerifyVector(type_vec)) return false;
for (uoffset_t j = 0; j < vec->size(); j++) {
// get union type from the prev field
@@ -162,20 +166,24 @@
}
case reflection::Vector:
case reflection::None:
- default: FLATBUFFERS_ASSERT(false); return false;
+ default:
+ FLATBUFFERS_ASSERT(false);
+ return false;
}
}
-static bool VerifyObject(flatbuffers::Verifier &v,
- const reflection::Schema &schema,
- const reflection::Object &obj,
- const flatbuffers::Table *table, bool required) {
+static bool VerifyObject(flatbuffers::Verifier& v,
+ const reflection::Schema& schema,
+ const reflection::Object& obj,
+ const flatbuffers::Table* table, bool required) {
if (!table) return !required;
if (!table->VerifyTableStart(v)) return false;
for (uoffset_t i = 0; i < obj.fields()->size(); i++) {
auto field_def = obj.fields()->Get(i);
switch (field_def->type()->base_type()) {
- case reflection::None: FLATBUFFERS_ASSERT(false); break;
+ case reflection::None:
+ FLATBUFFERS_ASSERT(false);
+ break;
case reflection::UType:
if (!table->VerifyField<uint8_t>(v, field_def->offset(),
sizeof(uint8_t)))
@@ -243,12 +251,16 @@
// get union type from the prev field
voffset_t utype_offset = field_def->offset() - sizeof(voffset_t);
auto utype = table->GetField<uint8_t>(utype_offset, 0);
- auto uval = reinterpret_cast<const uint8_t *>(
+ auto uval = reinterpret_cast<const uint8_t*>(
flatbuffers::GetFieldT(*table, *field_def));
- if (!VerifyUnion(v, schema, utype, uval, *field_def)) { return false; }
+ if (!VerifyUnion(v, schema, utype, uval, *field_def)) {
+ return false;
+ }
break;
}
- default: FLATBUFFERS_ASSERT(false); break;
+ default:
+ FLATBUFFERS_ASSERT(false);
+ break;
}
}
@@ -259,7 +271,7 @@
} // namespace
-int64_t GetAnyValueI(reflection::BaseType type, const uint8_t *data) {
+int64_t GetAnyValueI(reflection::BaseType type, const uint8_t* data) {
// clang-format off
#define FLATBUFFERS_GET(T) static_cast<int64_t>(ReadScalar<T>(data))
switch (type) {
@@ -286,13 +298,15 @@
// clang-format on
}
-double GetAnyValueF(reflection::BaseType type, const uint8_t *data) {
+double GetAnyValueF(reflection::BaseType type, const uint8_t* data) {
switch (type) {
- case reflection::Float: return static_cast<double>(ReadScalar<float>(data));
- case reflection::Double: return ReadScalar<double>(data);
+ case reflection::Float:
+ return static_cast<double>(ReadScalar<float>(data));
+ case reflection::Double:
+ return ReadScalar<double>(data);
case reflection::String: {
auto s =
- reinterpret_cast<const String *>(ReadScalar<uoffset_t>(data) + data);
+ reinterpret_cast<const String*>(ReadScalar<uoffset_t>(data) + data);
if (s) {
double d;
StringToNumber(s->c_str(), &d);
@@ -301,18 +315,20 @@
return 0.0;
}
}
- default: return static_cast<double>(GetAnyValueI(type, data));
+ default:
+ return static_cast<double>(GetAnyValueI(type, data));
}
}
-std::string GetAnyValueS(reflection::BaseType type, const uint8_t *data,
- const reflection::Schema *schema, int type_index) {
+std::string GetAnyValueS(reflection::BaseType type, const uint8_t* data,
+ const reflection::Schema* schema, int type_index) {
switch (type) {
case reflection::Float:
- case reflection::Double: return NumToString(GetAnyValueF(type, data));
+ case reflection::Double:
+ return NumToString(GetAnyValueF(type, data));
case reflection::String: {
auto s =
- reinterpret_cast<const String *>(ReadScalar<uoffset_t>(data) + data);
+ reinterpret_cast<const String*>(ReadScalar<uoffset_t>(data) + data);
return s ? s->c_str() : "";
}
case reflection::Obj:
@@ -320,17 +336,17 @@
// Convert the table to a string. This is mostly for debugging purposes,
// and does NOT promise to be JSON compliant.
// Also prefixes the type.
- auto &objectdef = *schema->objects()->Get(type_index);
+ auto& objectdef = *schema->objects()->Get(type_index);
auto s = objectdef.name()->str();
if (objectdef.is_struct()) {
s += "(struct)"; // TODO: implement this as well.
} else {
- auto table_field = reinterpret_cast<const Table *>(
+ auto table_field = reinterpret_cast<const Table*>(
ReadScalar<uoffset_t>(data) + data);
s += " { ";
auto fielddefs = objectdef.fields();
for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
- auto &fielddef = **it;
+ auto& fielddef = **it;
if (!table_field->CheckField(fielddef.offset())) continue;
auto val = GetAnyFieldS(*table_field, fielddef, schema);
if (fielddef.type()->base_type() == reflection::String) {
@@ -351,14 +367,16 @@
return "(table)";
}
case reflection::Vector:
- return "[(elements)]"; // TODO: implement this as well.
- case reflection::Union: return "(union)"; // TODO: implement this as well.
- default: return NumToString(GetAnyValueI(type, data));
+ return "[(elements)]"; // TODO: implement this as well.
+ case reflection::Union:
+ return "(union)"; // TODO: implement this as well.
+ default:
+ return NumToString(GetAnyValueI(type, data));
}
}
-void ForAllFields(const reflection::Object *object, bool reverse,
- std::function<void(const reflection::Field *)> func) {
+void ForAllFields(const reflection::Object* object, bool reverse,
+ std::function<void(const reflection::Field*)> func) {
std::vector<uint32_t> field_to_id_map;
field_to_id_map.resize(object->fields()->size());
@@ -374,7 +392,7 @@
}
}
-void SetAnyValueI(reflection::BaseType type, uint8_t *data, int64_t val) {
+void SetAnyValueI(reflection::BaseType type, uint8_t* data, int64_t val) {
// clang-format off
#define FLATBUFFERS_SET(T) WriteScalar(data, static_cast<T>(val))
switch (type) {
@@ -397,16 +415,22 @@
// clang-format on
}
-void SetAnyValueF(reflection::BaseType type, uint8_t *data, double val) {
+void SetAnyValueF(reflection::BaseType type, uint8_t* data, double val) {
switch (type) {
- case reflection::Float: WriteScalar(data, static_cast<float>(val)); break;
- case reflection::Double: WriteScalar(data, val); break;
+ case reflection::Float:
+ WriteScalar(data, static_cast<float>(val));
+ break;
+ case reflection::Double:
+ WriteScalar(data, val);
+ break;
// TODO: support strings.
- default: SetAnyValueI(type, data, static_cast<int64_t>(val)); break;
+ default:
+ SetAnyValueI(type, data, static_cast<int64_t>(val));
+ break;
}
}
-void SetAnyValueS(reflection::BaseType type, uint8_t *data, const char *val) {
+void SetAnyValueS(reflection::BaseType type, uint8_t* data, const char* val) {
switch (type) {
case reflection::Float:
case reflection::Double: {
@@ -416,7 +440,9 @@
break;
}
// TODO: support strings.
- default: SetAnyValueI(type, data, StringToInt(val)); break;
+ default:
+ SetAnyValueI(type, data, StringToInt(val));
+ break;
}
}
@@ -430,9 +456,9 @@
// pass in your root_table type as well.
class ResizeContext {
public:
- ResizeContext(const reflection::Schema &schema, uoffset_t start, int delta,
- std::vector<uint8_t> *flatbuf,
- const reflection::Object *root_table = nullptr)
+ ResizeContext(const reflection::Schema& schema, uoffset_t start, int delta,
+ std::vector<uint8_t>* flatbuf,
+ const reflection::Object* root_table = nullptr)
: schema_(schema),
startptr_(flatbuf->data() + start),
delta_(delta),
@@ -455,8 +481,8 @@
// Check if the range between first (lower address) and second straddles
// the insertion point. If it does, change the offset at offsetloc (of
// type T, with direction D).
- template<typename T, int D>
- void Straddle(const void *first, const void *second, void *offsetloc) {
+ template <typename T, int D>
+ void Straddle(const void* first, const void* second, void* offsetloc) {
if (first <= startptr_ && second >= startptr_) {
WriteScalar<T>(offsetloc, ReadScalar<T>(offsetloc) + delta_ * D);
DagCheck(offsetloc) = true;
@@ -469,18 +495,18 @@
// resize actually happens.
// This must be checked for every offset, since we can't know which offsets
// will straddle and which won't.
- uint8_t &DagCheck(const void *offsetloc) {
- auto dag_idx = reinterpret_cast<const uoffset_t *>(offsetloc) -
- reinterpret_cast<const uoffset_t *>(buf_.data());
+ uint8_t& DagCheck(const void* offsetloc) {
+ auto dag_idx = reinterpret_cast<const uoffset_t*>(offsetloc) -
+ reinterpret_cast<const uoffset_t*>(buf_.data());
return dag_check_[dag_idx];
}
- void ResizeTable(const reflection::Object &objectdef, Table *table) {
+ void ResizeTable(const reflection::Object& objectdef, Table* table) {
if (DagCheck(table)) return; // Table already visited.
auto vtable = table->GetVTable();
// Early out: since all fields inside the table must point forwards in
// memory, if the insertion point is before the table we can stop here.
- auto tableloc = reinterpret_cast<uint8_t *>(table);
+ auto tableloc = reinterpret_cast<uint8_t*>(table);
if (startptr_ <= tableloc) {
// Check if insertion point is between the table and a vtable that
// precedes it. This can't happen in current construction code, but check
@@ -490,7 +516,7 @@
// Check each field.
auto fielddefs = objectdef.fields();
for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
- auto &fielddef = **it;
+ auto& fielddef = **it;
auto base_type = fielddef.type()->base_type();
// Ignore scalars.
if (base_type <= reflection::Double) continue;
@@ -512,7 +538,7 @@
switch (base_type) {
case reflection::Obj: {
if (subobjectdef) {
- ResizeTable(*subobjectdef, reinterpret_cast<Table *>(ref));
+ ResizeTable(*subobjectdef, reinterpret_cast<Table*>(ref));
}
break;
}
@@ -520,7 +546,7 @@
auto elem_type = fielddef.type()->element();
if (elem_type != reflection::Obj && elem_type != reflection::String)
break;
- auto vec = reinterpret_cast<Vector<uoffset_t> *>(ref);
+ auto vec = reinterpret_cast<Vector<uoffset_t>*>(ref);
auto elemobjectdef =
elem_type == reflection::Obj
? schema_.objects()->Get(fielddef.type()->index())
@@ -532,17 +558,19 @@
auto dest = loc + vec->Get(i);
Straddle<uoffset_t, 1>(loc, dest, loc);
if (elemobjectdef)
- ResizeTable(*elemobjectdef, reinterpret_cast<Table *>(dest));
+ ResizeTable(*elemobjectdef, reinterpret_cast<Table*>(dest));
}
break;
}
case reflection::Union: {
ResizeTable(GetUnionType(schema_, objectdef, fielddef, *table),
- reinterpret_cast<Table *>(ref));
+ reinterpret_cast<Table*>(ref));
break;
}
- case reflection::String: break;
- default: FLATBUFFERS_ASSERT(false);
+ case reflection::String:
+ break;
+ default:
+ FLATBUFFERS_ASSERT(false);
}
}
// Check if the vtable offset points beyond the insertion point.
@@ -553,19 +581,19 @@
}
private:
- const reflection::Schema &schema_;
- uint8_t *startptr_;
+ const reflection::Schema& schema_;
+ uint8_t* startptr_;
int delta_;
- std::vector<uint8_t> &buf_;
+ std::vector<uint8_t>& buf_;
std::vector<uint8_t> dag_check_;
};
-void SetString(const reflection::Schema &schema, const std::string &val,
- const String *str, std::vector<uint8_t> *flatbuf,
- const reflection::Object *root_table) {
+void SetString(const reflection::Schema& schema, const std::string& val,
+ const String* str, std::vector<uint8_t>* flatbuf,
+ const reflection::Object* root_table) {
auto delta = static_cast<int>(val.size()) - static_cast<int>(str->size());
auto str_start = static_cast<uoffset_t>(
- reinterpret_cast<const uint8_t *>(str) - flatbuf->data());
+ reinterpret_cast<const uint8_t*>(str) - flatbuf->data());
auto start = str_start + static_cast<uoffset_t>(sizeof(uoffset_t));
if (delta) {
// Clear the old string, since we don't want parts of it remaining.
@@ -580,13 +608,13 @@
memcpy(flatbuf->data() + start, val.c_str(), val.size() + 1);
}
-uint8_t *ResizeAnyVector(const reflection::Schema &schema, uoffset_t newsize,
- const VectorOfAny *vec, uoffset_t num_elems,
- uoffset_t elem_size, std::vector<uint8_t> *flatbuf,
- const reflection::Object *root_table) {
+uint8_t* ResizeAnyVector(const reflection::Schema& schema, uoffset_t newsize,
+ const VectorOfAny* vec, uoffset_t num_elems,
+ uoffset_t elem_size, std::vector<uint8_t>* flatbuf,
+ const reflection::Object* root_table) {
auto delta_elem = static_cast<int>(newsize) - static_cast<int>(num_elems);
auto delta_bytes = delta_elem * static_cast<int>(elem_size);
- auto vec_start = reinterpret_cast<const uint8_t *>(vec) - flatbuf->data();
+ auto vec_start = reinterpret_cast<const uint8_t*>(vec) - flatbuf->data();
auto start = static_cast<uoffset_t>(vec_start) +
static_cast<uoffset_t>(sizeof(uoffset_t)) +
elem_size * num_elems;
@@ -608,8 +636,8 @@
return flatbuf->data() + start;
}
-const uint8_t *AddFlatBuffer(std::vector<uint8_t> &flatbuf,
- const uint8_t *newbuf, size_t newlen) {
+const uint8_t* AddFlatBuffer(std::vector<uint8_t>& flatbuf,
+ const uint8_t* newbuf, size_t newlen) {
// Align to sizeof(uoffset_t) past sizeof(largest_scalar_t) since we're
// going to chop off the root offset.
while ((flatbuf.size() & (sizeof(uoffset_t) - 1)) ||
@@ -623,16 +651,16 @@
return flatbuf.data() + insertion_point + root_offset;
}
-Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
- const reflection::Schema &schema,
- const reflection::Object &objectdef,
- const Table &table, bool use_string_pooling) {
+Offset<const Table*> CopyTable(FlatBufferBuilder& fbb,
+ const reflection::Schema& schema,
+ const reflection::Object& objectdef,
+ const Table& table, bool use_string_pooling) {
// Before we can construct the table, we have to first generate any
// subobjects, and collect their offsets.
std::vector<uoffset_t> offsets;
auto fielddefs = objectdef.fields();
for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
- auto &fielddef = **it;
+ auto& fielddef = **it;
// Skip if field is not present in the source.
if (!table.CheckField(fielddef.offset())) continue;
uoffset_t offset = 0;
@@ -644,7 +672,7 @@
break;
}
case reflection::Obj: {
- auto &subobjectdef = *schema.objects()->Get(fielddef.type()->index());
+ auto& subobjectdef = *schema.objects()->Get(fielddef.type()->index());
if (!subobjectdef.is_struct()) {
offset = CopyTable(fbb, schema, subobjectdef,
*GetFieldT(table, fielddef), use_string_pooling)
@@ -653,7 +681,7 @@
break;
}
case reflection::Union: {
- auto &subobjectdef = GetUnionType(schema, objectdef, fielddef, table);
+ auto& subobjectdef = GetUnionType(schema, objectdef, fielddef, table);
offset = CopyTable(fbb, schema, subobjectdef,
*GetFieldT(table, fielddef), use_string_pooling)
.o;
@@ -661,7 +689,7 @@
}
case reflection::Vector: {
auto vec =
- table.GetPointer<const Vector<Offset<Table>> *>(fielddef.offset());
+ table.GetPointer<const Vector<Offset<Table>>*>(fielddef.offset());
auto element_base_type = fielddef.type()->element();
auto elemobjectdef =
element_base_type == reflection::Obj
@@ -669,8 +697,8 @@
: nullptr;
switch (element_base_type) {
case reflection::String: {
- std::vector<Offset<const String *>> elements(vec->size());
- auto vec_s = reinterpret_cast<const Vector<Offset<String>> *>(vec);
+ std::vector<Offset<const String*>> elements(vec->size());
+ auto vec_s = reinterpret_cast<const Vector<Offset<String>>*>(vec);
for (uoffset_t i = 0; i < vec_s->size(); i++) {
elements[i] = use_string_pooling
? fbb.CreateSharedString(vec_s->Get(i)).o
@@ -681,7 +709,7 @@
}
case reflection::Obj: {
if (!elemobjectdef->is_struct()) {
- std::vector<Offset<const Table *>> elements(vec->size());
+ std::vector<Offset<const Table*>> elements(vec->size());
for (uoffset_t i = 0; i < vec->size(); i++) {
elements[i] = CopyTable(fbb, schema, *elemobjectdef,
*vec->Get(i), use_string_pooling);
@@ -707,19 +735,21 @@
default: // Scalars.
break;
}
- if (offset) { offsets.push_back(offset); }
+ if (offset) {
+ offsets.push_back(offset);
+ }
}
// Now we can build the actual table from either offsets or scalar data.
auto start = objectdef.is_struct() ? fbb.StartStruct(objectdef.minalign())
: fbb.StartTable();
size_t offset_idx = 0;
for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
- auto &fielddef = **it;
+ auto& fielddef = **it;
if (!table.CheckField(fielddef.offset())) continue;
auto base_type = fielddef.type()->base_type();
switch (base_type) {
case reflection::Obj: {
- auto &subobjectdef = *schema.objects()->Get(fielddef.type()->index());
+ auto& subobjectdef = *schema.objects()->Get(fielddef.type()->index());
if (subobjectdef.is_struct()) {
CopyInline(fbb, fielddef, table, subobjectdef.minalign(),
subobjectdef.bytesize());
@@ -748,17 +778,17 @@
}
}
-bool Verify(const reflection::Schema &schema, const reflection::Object &root,
- const uint8_t *const buf, const size_t length,
+bool Verify(const reflection::Schema& schema, const reflection::Object& root,
+ const uint8_t* const buf, const size_t length,
const uoffset_t max_depth, const uoffset_t max_tables) {
Verifier v(buf, length, max_depth, max_tables);
return VerifyObject(v, schema, root, flatbuffers::GetAnyRoot(buf),
/*required=*/true);
}
-bool VerifySizePrefixed(const reflection::Schema &schema,
- const reflection::Object &root,
- const uint8_t *const buf, const size_t length,
+bool VerifySizePrefixed(const reflection::Schema& schema,
+ const reflection::Object& root,
+ const uint8_t* const buf, const size_t length,
const uoffset_t max_depth, const uoffset_t max_tables) {
Verifier v(buf, length, max_depth, max_tables);
return VerifyObject(v, schema, root, flatbuffers::GetAnySizePrefixedRoot(buf),
diff --git a/src/util.cpp b/src/util.cpp
index 2d45ee7..de6b68c 100644
--- a/src/util.cpp
+++ b/src/util.cpp
@@ -58,12 +58,12 @@
namespace {
-static bool FileExistsRaw(const char *name) {
+static bool FileExistsRaw(const char* name) {
std::ifstream ifs(name);
return ifs.good();
}
-static bool LoadFileRaw(const char *name, bool binary, std::string *buf) {
+static bool LoadFileRaw(const char* name, bool binary, std::string* buf) {
if (DirExists(name)) return false;
std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
if (!ifs.is_open()) return false;
@@ -86,7 +86,7 @@
LoadFileFunction g_load_file_function = LoadFileRaw;
FileExistsFunction g_file_exists_function = FileExistsRaw;
-static std::string ToCamelCase(const std::string &input, bool is_upper) {
+static std::string ToCamelCase(const std::string& input, bool is_upper) {
std::string s;
for (size_t i = 0; i < input.length(); i++) {
if (!i && input[i] == '_') {
@@ -105,7 +105,7 @@
return s;
}
-static std::string ToSnakeCase(const std::string &input, bool screaming) {
+static std::string ToSnakeCase(const std::string& input, bool screaming) {
std::string s;
for (size_t i = 0; i < input.length(); i++) {
if (i == 0) {
@@ -127,14 +127,16 @@
return s;
}
-std::string ToAll(const std::string &input,
+std::string ToAll(const std::string& input,
std::function<char(const char)> transform) {
std::string s;
- for (size_t i = 0; i < input.length(); i++) { s += transform(input[i]); }
+ for (size_t i = 0; i < input.length(); i++) {
+ s += transform(input[i]);
+ }
return s;
}
-std::string CamelToSnake(const std::string &input) {
+std::string CamelToSnake(const std::string& input) {
std::string s;
for (size_t i = 0; i < input.length(); i++) {
if (i == 0) {
@@ -156,7 +158,7 @@
return s;
}
-std::string DasherToSnake(const std::string &input) {
+std::string DasherToSnake(const std::string& input) {
std::string s;
for (size_t i = 0; i < input.length(); i++) {
if (input[i] == '-') {
@@ -168,11 +170,11 @@
return s;
}
-std::string ToDasher(const std::string &input) {
+std::string ToDasher(const std::string& input) {
std::string s;
char p = 0;
for (size_t i = 0; i < input.length(); i++) {
- char const &c = input[i];
+ char const& c = input[i];
if (c == '_') {
if (i > 0 && p != kPathSeparator &&
// The following is a special case to ignore digits after a _. This is
@@ -190,7 +192,7 @@
}
// Converts foo_bar_123baz_456 to foo_bar123_baz456
-std::string SnakeToSnake2(const std::string &s) {
+std::string SnakeToSnake2(const std::string& s) {
if (s.length() <= 1) return s;
std::string result;
result.reserve(s.size());
@@ -212,17 +214,17 @@
} // namespace
-bool LoadFile(const char *name, bool binary, std::string *buf) {
+bool LoadFile(const char* name, bool binary, std::string* buf) {
FLATBUFFERS_ASSERT(g_load_file_function);
return g_load_file_function(name, binary, buf);
}
-bool FileExists(const char *name) {
+bool FileExists(const char* name) {
FLATBUFFERS_ASSERT(g_file_exists_function);
return g_file_exists_function(name);
}
-bool DirExists(const char *name) {
+bool DirExists(const char* name) {
// clang-format off
#ifdef _WIN32
@@ -252,7 +254,7 @@
return previous_function;
}
-bool SaveFile(const char *name, const char *buf, size_t len, bool binary) {
+bool SaveFile(const char* name, const char* buf, size_t len, bool binary) {
std::ofstream ofs(name, binary ? std::ofstream::binary : std::ofstream::out);
if (!ofs.is_open()) return false;
ofs.write(buf, len);
@@ -264,30 +266,30 @@
// on Windows when paths are string-compared.
static const char kPathSeparatorWindows = '\\';
-static const char *PathSeparatorSet = "\\/"; // Intentionally no ':'
+static const char* PathSeparatorSet = "\\/"; // Intentionally no ':'
-std::string StripExtension(const std::string &filepath) {
+std::string StripExtension(const std::string& filepath) {
size_t i = filepath.find_last_of('.');
return i != std::string::npos ? filepath.substr(0, i) : filepath;
}
-std::string GetExtension(const std::string &filepath) {
+std::string GetExtension(const std::string& filepath) {
size_t i = filepath.find_last_of('.');
return i != std::string::npos ? filepath.substr(i + 1) : "";
}
-std::string StripPath(const std::string &filepath) {
+std::string StripPath(const std::string& filepath) {
size_t i = filepath.find_last_of(PathSeparatorSet);
return i != std::string::npos ? filepath.substr(i + 1) : filepath;
}
-std::string StripFileName(const std::string &filepath) {
+std::string StripFileName(const std::string& filepath) {
size_t i = filepath.find_last_of(PathSeparatorSet);
return i != std::string::npos ? filepath.substr(0, i) : "";
}
-std::string StripPrefix(const std::string &filepath,
- const std::string &prefix_to_remove) {
+std::string StripPrefix(const std::string& filepath,
+ const std::string& prefix_to_remove) {
if (!strncmp(filepath.c_str(), prefix_to_remove.c_str(),
prefix_to_remove.size())) {
return filepath.substr(prefix_to_remove.size());
@@ -295,11 +297,11 @@
return filepath;
}
-std::string ConCatPathFileName(const std::string &path,
- const std::string &filename) {
+std::string ConCatPathFileName(const std::string& path,
+ const std::string& filename) {
std::string filepath = path;
if (filepath.length()) {
- char &filepath_last_character = filepath.back();
+ char& filepath_last_character = filepath.back();
if (filepath_last_character == kPathSeparatorWindows) {
filepath_last_character = kPathSeparator;
} else if (filepath_last_character != kPathSeparator) {
@@ -314,19 +316,19 @@
return filepath;
}
-std::string PosixPath(const char *path) {
+std::string PosixPath(const char* path) {
std::string p = path;
std::replace(p.begin(), p.end(), '\\', '/');
return p;
}
-std::string PosixPath(const std::string &path) {
+std::string PosixPath(const std::string& path) {
return PosixPath(path.c_str());
}
-void EnsureDirExists(const std::string &filepath) {
+void EnsureDirExists(const std::string& filepath) {
auto parent = StripFileName(filepath);
if (parent.length()) EnsureDirExists(parent);
- // clang-format off
+ // clang-format off
#ifdef _WIN32
(void)_mkdir(filepath.c_str());
@@ -336,11 +338,13 @@
// clang-format on
}
-std::string FilePath(const std::string& project, const std::string& filePath, bool absolute) {
- return (absolute) ? AbsolutePath(filePath) : RelativeToRootPath(project, filePath);
+std::string FilePath(const std::string& project, const std::string& filePath,
+ bool absolute) {
+ return (absolute) ? AbsolutePath(filePath)
+ : RelativeToRootPath(project, filePath);
}
-std::string AbsolutePath(const std::string &filepath) {
+std::string AbsolutePath(const std::string& filepath) {
// clang-format off
#ifdef FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
@@ -365,16 +369,16 @@
// clang-format on
}
-std::string RelativeToRootPath(const std::string &project,
- const std::string &filepath) {
+std::string RelativeToRootPath(const std::string& project,
+ const std::string& filepath) {
std::string absolute_project = PosixPath(AbsolutePath(project));
if (absolute_project.back() != '/') absolute_project += "/";
std::string absolute_filepath = PosixPath(AbsolutePath(filepath));
// Find the first character where they disagree.
// The previous directory is the lowest common ancestor;
- const char *a = absolute_project.c_str();
- const char *b = absolute_filepath.c_str();
+ const char* a = absolute_project.c_str();
+ const char* b = absolute_filepath.c_str();
size_t common_prefix_len = 0;
while (*a != '\0' && *b != '\0' && *a == *b) {
if (*a == '/') common_prefix_len = a - absolute_project.c_str();
@@ -383,7 +387,7 @@
}
// the number of ../ to prepend to b depends on the number of remaining
// directories in A.
- const char *suffix = absolute_project.c_str() + common_prefix_len;
+ const char* suffix = absolute_project.c_str() + common_prefix_len;
size_t num_up = 0;
while (*suffix != '\0')
if (*suffix++ == '/') num_up++;
@@ -416,21 +420,21 @@
#endif // !FLATBUFFERS_LOCALE_INDEPENDENT
-std::string RemoveStringQuotes(const std::string &s) {
+std::string RemoveStringQuotes(const std::string& s) {
auto ch = *s.c_str();
return ((s.size() >= 2) && (ch == '\"' || ch == '\'') && (ch == s.back()))
? s.substr(1, s.length() - 2)
: s;
}
-bool SetGlobalTestLocale(const char *locale_name, std::string *_value) {
+bool SetGlobalTestLocale(const char* locale_name, std::string* _value) {
const auto the_locale = setlocale(LC_ALL, locale_name);
if (!the_locale) return false;
if (_value) *_value = std::string(the_locale);
return true;
}
-bool ReadEnvironmentVariable(const char *var_name, std::string *_value) {
+bool ReadEnvironmentVariable(const char* var_name, std::string* _value) {
#ifdef _MSC_VER
__pragma(warning(disable : 4996)); // _CRT_SECURE_NO_WARNINGS
#endif
@@ -440,7 +444,7 @@
return true;
}
-std::string ConvertCase(const std::string &input, Case output_case,
+std::string ConvertCase(const std::string& input, Case output_case,
Case input_case) {
if (output_case == Case::kKeep) return input;
// The output cases expect snake_case inputs, so if we don't have that input
@@ -449,26 +453,39 @@
case Case::kLowerCamel:
case Case::kUpperCamel:
return ConvertCase(CamelToSnake(input), output_case);
- case Case::kDasher: return ConvertCase(DasherToSnake(input), output_case);
- case Case::kKeep: printf("WARNING: Converting from kKeep case.\n"); break;
+ case Case::kDasher:
+ return ConvertCase(DasherToSnake(input), output_case);
+ case Case::kKeep:
+ printf("WARNING: Converting from kKeep case.\n");
+ break;
default:
case Case::kSnake:
case Case::kScreamingSnake:
case Case::kAllLower:
- case Case::kAllUpper: break;
+ case Case::kAllUpper:
+ break;
}
switch (output_case) {
- case Case::kUpperCamel: return ToCamelCase(input, true);
- case Case::kLowerCamel: return ToCamelCase(input, false);
- case Case::kSnake: return input;
- case Case::kScreamingSnake: return ToSnakeCase(input, true);
- case Case::kAllUpper: return ToAll(input, CharToUpper);
- case Case::kAllLower: return ToAll(input, CharToLower);
- case Case::kDasher: return ToDasher(input);
- case Case::kSnake2: return SnakeToSnake2(input);
+ case Case::kUpperCamel:
+ return ToCamelCase(input, true);
+ case Case::kLowerCamel:
+ return ToCamelCase(input, false);
+ case Case::kSnake:
+ return input;
+ case Case::kScreamingSnake:
+ return ToSnakeCase(input, true);
+ case Case::kAllUpper:
+ return ToAll(input, CharToUpper);
+ case Case::kAllLower:
+ return ToAll(input, CharToLower);
+ case Case::kDasher:
+ return ToDasher(input);
+ case Case::kSnake2:
+ return SnakeToSnake2(input);
default:
- case Case::kUnknown: return input;
+ case Case::kUnknown:
+ return input;
}
}
diff --git a/tests/alignment_test.cpp b/tests/alignment_test.cpp
index 2641a31..cff0d0f 100644
--- a/tests/alignment_test.cpp
+++ b/tests/alignment_test.cpp
@@ -1,9 +1,9 @@
#include "alignment_test.h"
-#include "tests/alignment_test_generated.h"
#include "flatbuffers/flatbuffer_builder.h"
#include "flatbuffers/util.h"
#include "test_assert.h"
+#include "tests/alignment_test_generated.h"
namespace flatbuffers {
namespace tests {
@@ -14,8 +14,8 @@
BadAlignmentLarge large;
Offset<OuterLarge> outer_large = CreateOuterLarge(builder, &large);
- BadAlignmentSmall *small;
- Offset<Vector<const BadAlignmentSmall *>> small_offset =
+ BadAlignmentSmall* small;
+ Offset<Vector<const BadAlignmentSmall*>> small_offset =
builder.CreateUninitializedVectorOfStructs(9, &small);
(void)small; // We do not have to write data to trigger the test failure
@@ -27,22 +27,19 @@
Verifier verifier(builder.GetBufferPointer(), builder.GetSize());
TEST_ASSERT(verifier.VerifyBuffer<BadAlignmentRoot>(nullptr));
-
// ============= Test Small Structs Vector misalignment ========
builder.Clear();
// creating 5 structs with 2 bytes each
// 10 bytes in total for Vector data is needed
- std::vector<EvenSmallStruct> even_vector = { { 2, 1 }, { 3, 1 }, { 4, 1 } };
- std::vector<OddSmallStruct> odd_vector = { { 6, 5, 4 },
- { 9, 8, 7 },
- { 1, 2, 3 } };
+ std::vector<EvenSmallStruct> even_vector = {{2, 1}, {3, 1}, {4, 1}};
+ std::vector<OddSmallStruct> odd_vector = {{6, 5, 4}, {9, 8, 7}, {1, 2, 3}};
// CreateVectorOfStructs is used in the generated CreateSmallStructsDirect()
// method, but we test it directly
- Offset<Vector<const EvenSmallStruct *>> even_structs_offset =
+ Offset<Vector<const EvenSmallStruct*>> even_structs_offset =
builder.CreateVectorOfStructs<EvenSmallStruct>(even_vector);
- Offset<Vector<const OddSmallStruct *>> odd_structs_offset =
+ Offset<Vector<const OddSmallStruct*>> odd_structs_offset =
builder.CreateVectorOfStructs<OddSmallStruct>(odd_vector);
Offset<SmallStructs> small_structs_root =
CreateSmallStructs(builder, even_structs_offset, odd_structs_offset);
diff --git a/tests/evolution_test.cpp b/tests/evolution_test.cpp
index 51c2e81..7899278 100644
--- a/tests/evolution_test.cpp
+++ b/tests/evolution_test.cpp
@@ -8,7 +8,7 @@
namespace flatbuffers {
namespace tests {
-void EvolutionTest(const std::string &tests_data_path) {
+void EvolutionTest(const std::string& tests_data_path) {
// VS10 does not support typed enums, exclude from tests
#if !defined(_MSC_VER) || _MSC_VER >= 1700
const int NUM_VERSIONS = 2;
@@ -83,8 +83,8 @@
void ConformTest() {
const char ref[] = "table T { A:int; } enum E:byte { A }";
- auto test_conform = [](const char *ref, const char *test,
- const char *expected_err) {
+ auto test_conform = [](const char* ref, const char* test,
+ const char* expected_err) {
flatbuffers::Parser parser1;
TEST_EQ(parser1.Parse(ref), true);
flatbuffers::Parser parser2;
@@ -112,11 +112,13 @@
"field renamed to different type: T2.df (renamed from T2.f)");
// Check enum underlying type changes.
- test_conform("enum E:int32 {A}", "enum E: byte {A}", "underlying type differ for enum: E");
-
+ test_conform("enum E:int32 {A}", "enum E: byte {A}",
+ "underlying type differ for enum: E");
+
// Check union underlying type changes.
const char ref3[] = "table A {} table B {} union C {A, B}";
- test_conform(ref3, "table A {} table B {} union C:int32 {A, B}", "underlying type differ for union: C");
+ test_conform(ref3, "table A {} table B {} union C:int32 {A, B}",
+ "underlying type differ for union: C");
// Check conformity for Offset64-related changes.
{
@@ -151,7 +153,7 @@
}
}
-void UnionDeprecationTest(const std::string &tests_data_path) {
+void UnionDeprecationTest(const std::string& tests_data_path) {
const int NUM_VERSIONS = 2;
std::string schemas[NUM_VERSIONS];
std::string jsonfiles[NUM_VERSIONS];
diff --git a/tests/flexbuffers_test.cpp b/tests/flexbuffers_test.cpp
index 0c7d04e..3c87f8c 100644
--- a/tests/flexbuffers_test.cpp
+++ b/tests/flexbuffers_test.cpp
@@ -28,15 +28,15 @@
slb += "Fred";
slb.IndirectFloat(4.0f);
auto i_f = slb.LastValue();
- uint8_t blob[] = { 77 };
+ uint8_t blob[] = {77};
slb.Blob(blob, 1);
slb += false;
slb.ReuseValue(i_f);
});
- int ints[] = { 1, 2, 3 };
+ int ints[] = {1, 2, 3};
slb.Vector("bar", ints, 3);
slb.FixedTypedVector("bar3", ints, 3);
- bool bools[] = { true, false, true, false };
+ bool bools[] = {true, false, true, false};
slb.Vector("bools", bools, 4);
slb.Bool("bool", true);
slb.Double("foo", 100);
@@ -136,7 +136,8 @@
std::string jsonback_indented;
jroot.ToString(true, false, jsonback_indented, true, 0, " ");
auto jsontest_indented =
- "{\n a: [\n 123,\n 456.0\n ],\n b: \"hello\",\n c: true,\n d: false\n}";
+ "{\n a: [\n 123,\n 456.0\n ],\n b: \"hello\",\n c: true,\n d: "
+ "false\n}";
TEST_EQ_STR(jsontest_indented, jsonback_indented.c_str());
slb.Clear();
diff --git a/tests/fuzz_test.cpp b/tests/fuzz_test.cpp
index 1c9adbc..72cd991 100644
--- a/tests/fuzz_test.cpp
+++ b/tests/fuzz_test.cpp
@@ -20,8 +20,8 @@
}
void lcg_reset() { lcg_seed = 48271; }
-template<typename T>
-static void CompareTableFieldValue(flatbuffers::Table *table,
+template <typename T>
+static void CompareTableFieldValue(flatbuffers::Table* table,
flatbuffers::voffset_t voffset, T val) {
T read = table->GetField(voffset, static_cast<T>(0));
TEST_EQ(read, val);
@@ -64,17 +64,39 @@
int choice = lcg_rand() % test_values_max;
auto off = flatbuffers::FieldIndexToOffset(f);
switch (choice) {
- case 0: builder.AddElement<uint8_t>(off, bool_val, 0); break;
- case 1: builder.AddElement<int8_t>(off, char_val, 0); break;
- case 2: builder.AddElement<uint8_t>(off, uchar_val, 0); break;
- case 3: builder.AddElement<int16_t>(off, short_val, 0); break;
- case 4: builder.AddElement<uint16_t>(off, ushort_val, 0); break;
- case 5: builder.AddElement<int32_t>(off, int_val, 0); break;
- case 6: builder.AddElement<uint32_t>(off, uint_val, 0); break;
- case 7: builder.AddElement<int64_t>(off, long_val, 0); break;
- case 8: builder.AddElement<uint64_t>(off, ulong_val, 0); break;
- case 9: builder.AddElement<float>(off, float_val, 0); break;
- case 10: builder.AddElement<double>(off, double_val, 0); break;
+ case 0:
+ builder.AddElement<uint8_t>(off, bool_val, 0);
+ break;
+ case 1:
+ builder.AddElement<int8_t>(off, char_val, 0);
+ break;
+ case 2:
+ builder.AddElement<uint8_t>(off, uchar_val, 0);
+ break;
+ case 3:
+ builder.AddElement<int16_t>(off, short_val, 0);
+ break;
+ case 4:
+ builder.AddElement<uint16_t>(off, ushort_val, 0);
+ break;
+ case 5:
+ builder.AddElement<int32_t>(off, int_val, 0);
+ break;
+ case 6:
+ builder.AddElement<uint32_t>(off, uint_val, 0);
+ break;
+ case 7:
+ builder.AddElement<int64_t>(off, long_val, 0);
+ break;
+ case 8:
+ builder.AddElement<uint64_t>(off, ulong_val, 0);
+ break;
+ case 9:
+ builder.AddElement<float>(off, float_val, 0);
+ break;
+ case 10:
+ builder.AddElement<double>(off, double_val, 0);
+ break;
}
}
objects[i] = builder.EndTable(start);
@@ -83,28 +105,50 @@
lcg_reset(); // Reset.
- uint8_t *eob = builder.GetCurrentBufferPointer() + builder.GetSize();
+ uint8_t* eob = builder.GetCurrentBufferPointer() + builder.GetSize();
// Test that all objects we generated are readable and return the
// expected values. We generate random objects in the same order
// so this is deterministic.
for (int i = 0; i < num_fuzz_objects; i++) {
- auto table = reinterpret_cast<flatbuffers::Table *>(eob - objects[i]);
+ auto table = reinterpret_cast<flatbuffers::Table*>(eob - objects[i]);
for (flatbuffers::voffset_t f = 0; f < fields_per_object; f++) {
int choice = lcg_rand() % test_values_max;
flatbuffers::voffset_t off = flatbuffers::FieldIndexToOffset(f);
switch (choice) {
- case 0: CompareTableFieldValue(table, off, bool_val); break;
- case 1: CompareTableFieldValue(table, off, char_val); break;
- case 2: CompareTableFieldValue(table, off, uchar_val); break;
- case 3: CompareTableFieldValue(table, off, short_val); break;
- case 4: CompareTableFieldValue(table, off, ushort_val); break;
- case 5: CompareTableFieldValue(table, off, int_val); break;
- case 6: CompareTableFieldValue(table, off, uint_val); break;
- case 7: CompareTableFieldValue(table, off, long_val); break;
- case 8: CompareTableFieldValue(table, off, ulong_val); break;
- case 9: CompareTableFieldValue(table, off, float_val); break;
- case 10: CompareTableFieldValue(table, off, double_val); break;
+ case 0:
+ CompareTableFieldValue(table, off, bool_val);
+ break;
+ case 1:
+ CompareTableFieldValue(table, off, char_val);
+ break;
+ case 2:
+ CompareTableFieldValue(table, off, uchar_val);
+ break;
+ case 3:
+ CompareTableFieldValue(table, off, short_val);
+ break;
+ case 4:
+ CompareTableFieldValue(table, off, ushort_val);
+ break;
+ case 5:
+ CompareTableFieldValue(table, off, int_val);
+ break;
+ case 6:
+ CompareTableFieldValue(table, off, uint_val);
+ break;
+ case 7:
+ CompareTableFieldValue(table, off, long_val);
+ break;
+ case 8:
+ CompareTableFieldValue(table, off, ulong_val);
+ break;
+ case 9:
+ CompareTableFieldValue(table, off, float_val);
+ break;
+ case 10:
+ CompareTableFieldValue(table, off, double_val);
+ break;
}
}
}
@@ -131,8 +175,8 @@
// Since we're generating schema and corresponding data in tandem,
// this convenience function adds strings to both at once.
static void Add(RndDef (&definitions_l)[num_definitions],
- std::string &schema_l, const int instances_per_definition_l,
- const char *schema_add, const char *instance_add,
+ std::string& schema_l, const int instances_per_definition_l,
+ const char* schema_add, const char* instance_add,
int definition) {
schema_l += schema_add;
for (int i = 0; i < instances_per_definition_l; i++)
@@ -266,7 +310,7 @@
// from the binary and compare against the original.
TEST_EQ(parser.Parse(schema.c_str()), true);
- const std::string &json =
+ const std::string& json =
definitions[num_definitions - 1].instances[0] + "\n";
TEST_EQ(parser.Parse(json.c_str()), true);
diff --git a/tests/json_test.cpp b/tests/json_test.cpp
index 2a32863..c6499dd 100644
--- a/tests/json_test.cpp
+++ b/tests/json_test.cpp
@@ -13,7 +13,7 @@
using namespace MyGame::Example;
// Check stringify of an default enum value to json
-void JsonDefaultTest(const std::string &tests_data_path) {
+void JsonDefaultTest(const std::string& tests_data_path) {
// load FlatBuffer schema (.fbs) from disk
std::string schemafile;
TEST_EQ(flatbuffers::LoadFile((tests_data_path + "monster_test.fbs").c_str(),
@@ -23,8 +23,8 @@
flatbuffers::Parser parser;
auto include_test_path =
flatbuffers::ConCatPathFileName(tests_data_path, "include_test");
- const char *include_directories[] = { tests_data_path.c_str(),
- include_test_path.c_str(), nullptr };
+ const char* include_directories[] = {tests_data_path.c_str(),
+ include_test_path.c_str(), nullptr};
TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
// create incomplete monster and store to json
@@ -44,7 +44,7 @@
TEST_EQ(std::string::npos != jsongen.find("testf: 3.14159"), true);
}
-void JsonEnumsTest(const std::string &tests_data_path) {
+void JsonEnumsTest(const std::string& tests_data_path) {
// load FlatBuffer schema (.fbs) from disk
std::string schemafile;
TEST_EQ(flatbuffers::LoadFile((tests_data_path + "monster_test.fbs").c_str(),
@@ -54,8 +54,8 @@
flatbuffers::Parser parser;
auto include_test_path =
flatbuffers::ConCatPathFileName(tests_data_path, "include_test");
- const char *include_directories[] = { tests_data_path.c_str(),
- include_test_path.c_str(), nullptr };
+ const char* include_directories[] = {tests_data_path.c_str(),
+ include_test_path.c_str(), nullptr};
parser.opts.output_enum_identifiers = true;
TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
flatbuffers::FlatBufferBuilder builder;
@@ -83,7 +83,7 @@
TEST_EQ(std::string::npos != future_json.find("color: 13"), true);
}
-void JsonOptionalTest(const std::string &tests_data_path,
+void JsonOptionalTest(const std::string& tests_data_path,
bool default_scalars) {
// load FlatBuffer schema (.fbs) and JSON from disk
std::string schemafile;
@@ -100,8 +100,8 @@
auto include_test_path =
flatbuffers::ConCatPathFileName(tests_data_path, "include_test");
- const char *include_directories[] = { tests_data_path.c_str(),
- include_test_path.c_str(), nullptr };
+ const char* include_directories[] = {tests_data_path.c_str(),
+ include_test_path.c_str(), nullptr};
// parse schema first, so we can use it to parse the data after
flatbuffers::Parser parser;
@@ -124,17 +124,17 @@
TEST_EQ_STR(jsongen.c_str(), jsonfile.c_str());
}
-void ParseIncorrectMonsterJsonTest(const std::string &tests_data_path) {
+void ParseIncorrectMonsterJsonTest(const std::string& tests_data_path) {
std::string schemafile;
TEST_EQ(flatbuffers::LoadFile((tests_data_path + "monster_test.bfbs").c_str(),
true, &schemafile),
true);
flatbuffers::Parser parser;
flatbuffers::Verifier verifier(
- reinterpret_cast<const uint8_t *>(schemafile.c_str()), schemafile.size());
+ reinterpret_cast<const uint8_t*>(schemafile.c_str()), schemafile.size());
TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
TEST_EQ(
- parser.Deserialize(reinterpret_cast<const uint8_t *>(schemafile.c_str()),
+ parser.Deserialize(reinterpret_cast<const uint8_t*>(schemafile.c_str()),
schemafile.size()),
true);
TEST_EQ(parser.ParseJson("{name:\"monster\"}"), true);
diff --git a/tests/key_field_test.cpp b/tests/key_field_test.cpp
index 20eb209..db5a0d5 100644
--- a/tests/key_field_test.cpp
+++ b/tests/key_field_test.cpp
@@ -15,10 +15,10 @@
void FixedSizedScalarKeyInStructTest() {
flatbuffers::FlatBufferBuilder fbb;
std::vector<Baz> bazs;
- uint8_t test_array1[4] = { 8, 2, 3, 0 };
- uint8_t test_array2[4] = { 1, 2, 3, 4 };
- uint8_t test_array3[4] = { 2, 2, 3, 4 };
- uint8_t test_array4[4] = { 3, 2, 3, 4 };
+ uint8_t test_array1[4] = {8, 2, 3, 0};
+ uint8_t test_array2[4] = {1, 2, 3, 4};
+ uint8_t test_array3[4] = {2, 2, 3, 4};
+ uint8_t test_array4[4] = {3, 2, 3, 4};
bazs.push_back(Baz(flatbuffers::make_span(test_array1), 4));
bazs.push_back(Baz(flatbuffers::make_span(test_array2), 1));
bazs.push_back(Baz(flatbuffers::make_span(test_array3), 2));
@@ -27,10 +27,10 @@
auto test_string = fbb.CreateString("TEST");
- float test_float_array1[3] = { 1.5, 2.5, 0 };
- float test_float_array2[3] = { 7.5, 2.5, 0 };
- float test_float_array3[3] = { 1.5, 2.5, -1 };
- float test_float_array4[3] = { -1.5, 2.5, 0 };
+ float test_float_array1[3] = {1.5, 2.5, 0};
+ float test_float_array2[3] = {7.5, 2.5, 0};
+ float test_float_array3[3] = {1.5, 2.5, -1};
+ float test_float_array4[3] = {-1.5, 2.5, 0};
std::vector<Bar> bars;
bars.push_back(Bar(flatbuffers::make_span(test_float_array1), 3));
bars.push_back(Bar(flatbuffers::make_span(test_float_array2), 4));
@@ -42,7 +42,7 @@
fbb.Finish(t);
- uint8_t *buf = fbb.GetBufferPointer();
+ uint8_t* buf = fbb.GetBufferPointer();
auto foo_table = GetFooTable(buf);
auto sorted_baz_vec = foo_table->d();
@@ -50,37 +50,37 @@
TEST_EQ(sorted_baz_vec->Get(3)->b(), 4);
uint8_t test_array[4];
- auto *key_array = &flatbuffers::CastToArray(test_array);
+ auto* key_array = &flatbuffers::CastToArray(test_array);
key_array->CopyFromSpan(flatbuffers::make_span(test_array1));
TEST_NOTNULL(sorted_baz_vec->LookupByKey(key_array));
TEST_EQ(sorted_baz_vec->LookupByKey(key_array)->b(), 4);
- uint8_t array_int[4] = { 7, 2, 3, 0 };
+ uint8_t array_int[4] = {7, 2, 3, 0};
key_array->CopyFromSpan(flatbuffers::make_span(array_int));
TEST_EQ(sorted_baz_vec->LookupByKey(key_array),
- static_cast<const Baz *>(nullptr));
+ static_cast<const Baz*>(nullptr));
auto sorted_bar_vec = foo_table->e();
TEST_EQ(sorted_bar_vec->Get(0)->b(), 1);
TEST_EQ(sorted_bar_vec->Get(3)->b(), 4);
float test_float_array[3];
- auto *key_float_array = &flatbuffers::CastToArray(test_float_array);
+ auto* key_float_array = &flatbuffers::CastToArray(test_float_array);
key_float_array->CopyFromSpan(flatbuffers::make_span(test_float_array1));
TEST_NOTNULL(sorted_bar_vec->LookupByKey(key_float_array));
TEST_EQ(sorted_bar_vec->LookupByKey(key_float_array)->b(), 3);
- float array_float[3] = { -1, -2, -3 };
+ float array_float[3] = {-1, -2, -3};
key_float_array->CopyFromSpan(flatbuffers::make_span(array_float));
TEST_EQ(sorted_bar_vec->LookupByKey(key_float_array),
- static_cast<const Bar *>(nullptr));
+ static_cast<const Bar*>(nullptr));
}
void StructKeyInStructTest() {
flatbuffers::FlatBufferBuilder fbb;
std::vector<Apple> apples;
- float test_float_array1[3] = { 1.5, 2.5, 0 };
- float test_float_array2[3] = { 7.5, 2.5, 0 };
- float test_float_array3[3] = { 1.5, 2.5, -1 };
+ float test_float_array1[3] = {1.5, 2.5, 0};
+ float test_float_array2[3] = {7.5, 2.5, 0};
+ float test_float_array3[3] = {1.5, 2.5, -1};
apples.push_back(
Apple(2, Color(flatbuffers::make_span(test_float_array1), 3)));
apples.push_back(
@@ -100,7 +100,7 @@
auto orc = foo_builder.Finish();
fbb.Finish(orc);
- uint8_t *buf = fbb.GetBufferPointer();
+ uint8_t* buf = fbb.GetBufferPointer();
auto foo_table = GetFooTable(buf);
auto sorted_apple_vec = foo_table->f();
@@ -113,15 +113,15 @@
2);
TEST_EQ(sorted_apple_vec->LookupByKey(
Color(flatbuffers::make_span(test_float_array1), 0)),
- static_cast<const Apple *>(nullptr));
+ static_cast<const Apple*>(nullptr));
}
void NestedStructKeyInStructTest() {
flatbuffers::FlatBufferBuilder fbb;
std::vector<Fruit> fruits;
- float test_float_array1[3] = { 1.5, 2.5, 0 };
- float test_float_array2[3] = { 1.5, 2.5, 0 };
- float test_float_array3[3] = { 1.5, 2.5, -1 };
+ float test_float_array1[3] = {1.5, 2.5, 0};
+ float test_float_array2[3] = {1.5, 2.5, 0};
+ float test_float_array3[3] = {1.5, 2.5, -1};
fruits.push_back(
Fruit(Apple(2, Color(flatbuffers::make_span(test_float_array1), 2)), 2));
@@ -140,7 +140,7 @@
auto orc = foo_builder.Finish();
fbb.Finish(orc);
- uint8_t *buf = fbb.GetBufferPointer();
+ uint8_t* buf = fbb.GetBufferPointer();
auto foo_table = GetFooTable(buf);
auto sorted_fruit_vec = foo_table->g();
@@ -154,34 +154,31 @@
1);
TEST_EQ(sorted_fruit_vec->LookupByKey(
Apple(1, Color(flatbuffers::make_span(test_float_array2), 1))),
- static_cast<const Fruit *>(nullptr));
+ static_cast<const Fruit*>(nullptr));
}
void FixedSizedStructArrayKeyInStructTest() {
flatbuffers::FlatBufferBuilder fbb;
std::vector<Grain> grains;
- uint8_t test_char_array1[3] = { 'u', 's', 'a' };
- uint8_t test_char_array2[3] = { 'c', 'h', 'n' };
- uint8_t test_char_array3[3] = { 'c', 'h', 'l' };
- uint8_t test_char_array4[3] = { 'f', 'r', 'a' };
- uint8_t test_char_array5[3] = { 'i', 'n', 'd' };
- uint8_t test_char_array6[3] = { 'i', 't', 'a' };
+ uint8_t test_char_array1[3] = {'u', 's', 'a'};
+ uint8_t test_char_array2[3] = {'c', 'h', 'n'};
+ uint8_t test_char_array3[3] = {'c', 'h', 'l'};
+ uint8_t test_char_array4[3] = {'f', 'r', 'a'};
+ uint8_t test_char_array5[3] = {'i', 'n', 'd'};
+ uint8_t test_char_array6[3] = {'i', 't', 'a'};
Rice test_rice_array1[3] = {
- Rice(flatbuffers::make_span(test_char_array1), 2),
- Rice(flatbuffers::make_span(test_char_array2), 1),
- Rice(flatbuffers::make_span(test_char_array3), 2)
- };
+ Rice(flatbuffers::make_span(test_char_array1), 2),
+ Rice(flatbuffers::make_span(test_char_array2), 1),
+ Rice(flatbuffers::make_span(test_char_array3), 2)};
Rice test_rice_array2[3] = {
- Rice(flatbuffers::make_span(test_char_array4), 2),
- Rice(flatbuffers::make_span(test_char_array5), 1),
- Rice(flatbuffers::make_span(test_char_array6), 2)
- };
+ Rice(flatbuffers::make_span(test_char_array4), 2),
+ Rice(flatbuffers::make_span(test_char_array5), 1),
+ Rice(flatbuffers::make_span(test_char_array6), 2)};
Rice test_rice_array3[3] = {
- Rice(flatbuffers::make_span(test_char_array4), 2),
- Rice(flatbuffers::make_span(test_char_array6), 1),
- Rice(flatbuffers::make_span(test_char_array1), 2)
- };
+ Rice(flatbuffers::make_span(test_char_array4), 2),
+ Rice(flatbuffers::make_span(test_char_array6), 1),
+ Rice(flatbuffers::make_span(test_char_array1), 2)};
grains.push_back(Grain(flatbuffers::make_span(test_rice_array1), 3));
grains.push_back(Grain(flatbuffers::make_span(test_rice_array2), 1));
@@ -196,7 +193,7 @@
auto orc = foo_builder.Finish();
fbb.Finish(orc);
- uint8_t *buf = fbb.GetBufferPointer();
+ uint8_t* buf = fbb.GetBufferPointer();
auto foo_table = GetFooTable(buf);
auto sorted_grain_vec = foo_table->h();
@@ -207,13 +204,12 @@
sorted_grain_vec->LookupByKey(&flatbuffers::CastToArray(test_rice_array1))
->tag(),
3);
- Rice test_rice_array[3] = { Rice(flatbuffers::make_span(test_char_array3), 2),
- Rice(flatbuffers::make_span(test_char_array2), 1),
- Rice(flatbuffers::make_span(test_char_array1),
- 2) };
+ Rice test_rice_array[3] = {Rice(flatbuffers::make_span(test_char_array3), 2),
+ Rice(flatbuffers::make_span(test_char_array2), 1),
+ Rice(flatbuffers::make_span(test_char_array1), 2)};
TEST_EQ(
sorted_grain_vec->LookupByKey(&flatbuffers::CastToArray(test_rice_array)),
- static_cast<const Grain *>(nullptr));
+ static_cast<const Grain*>(nullptr));
TEST_EQ(
sorted_grain_vec->LookupByKey(&flatbuffers::CastToArray(test_rice_array1))
->tag(),
diff --git a/tests/monster_test.cpp b/tests/monster_test.cpp
index b546d20..9b188af 100644
--- a/tests/monster_test.cpp
+++ b/tests/monster_test.cpp
@@ -24,7 +24,7 @@
using namespace MyGame::Example;
// example of how to build up a serialized buffer algorithmically:
-flatbuffers::DetachedBuffer CreateFlatBufferTest(std::string &buffer) {
+flatbuffers::DetachedBuffer CreateFlatBufferTest(std::string& buffer) {
flatbuffers::FlatBufferBuilder builder;
auto vec = Vec3(1, 2, 3, 0, Color_Red, Test(10, 20));
@@ -33,7 +33,7 @@
// Use the initializer_list specialization of CreateVector.
auto inventory =
- builder.CreateVector<uint8_t>({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
+ builder.CreateVector<uint8_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
// Alternatively, create the vector first, and fill in data later:
// unsigned char *inv_buf = nullptr;
@@ -41,12 +41,12 @@
// 10, &inv_buf);
// memcpy(inv_buf, inv_data, 10);
- Test tests[] = { Test(10, 20), Test(30, 40) };
+ Test tests[] = {Test(10, 20), Test(30, 40)};
auto testv = builder.CreateVectorOfStructs(tests, 2);
// Create a vector of structures from a lambda.
auto testv2 = builder.CreateVectorOfStructs<Test>(
- 2, [&](size_t i, Test *s) -> void { *s = tests[i]; });
+ 2, [&](size_t i, Test* s) -> void { *s = tests[i]; });
// create monster with very few fields set:
// (same functionality as CreateMonster below, but sets fields manually)
@@ -69,9 +69,9 @@
auto vecofstrings =
builder.CreateVector<flatbuffers::Offset<flatbuffers::String>>(
4,
- [](size_t i, flatbuffers::FlatBufferBuilder *b)
+ [](size_t i, flatbuffers::FlatBufferBuilder* b)
-> flatbuffers::Offset<flatbuffers::String> {
- static const char *names[] = { "bob", "fred", "bob", "fred" };
+ static const char* names[] = {"bob", "fred", "bob", "fred"};
return b->CreateSharedString(names[i]);
},
&builder);
@@ -83,7 +83,7 @@
auto vecofstrings2 = builder.CreateVectorOfStrings(names2);
// Creating vectors from types that are different from std::string
- std::vector<const char *> names3;
+ std::vector<const char*> names3;
names3.push_back("foo");
names3.push_back("bar");
builder.CreateVectorOfStrings(names3); // Also an accepted type
@@ -96,11 +96,13 @@
#endif
// Make sure the template deduces an initializer as std::vector<std::string>
- builder.CreateVectorOfStrings({ "hello", "world" });
+ builder.CreateVectorOfStrings({"hello", "world"});
// Create many vectors of strings
std::vector<std::string> manyNames;
- for (auto i = 0; i < 100; i++) { manyNames.push_back("john_doe"); }
+ for (auto i = 0; i < 100; i++) {
+ manyNames.push_back("john_doe");
+ }
auto manyNamesVec = builder.CreateVectorOfStrings(manyNames);
TEST_EQ(false, manyNamesVec.IsNull());
auto manyNamesVec2 =
@@ -155,7 +157,7 @@
flexbuild.Finish();
auto flex = builder.CreateVector(flexbuild.GetBuffer());
// Test vector of enums.
- Color colors[] = { Color_Blue, Color_Green };
+ Color colors[] = {Color_Blue, Color_Green};
// We use this special creation function because we have an array of
// pre-C++11 (enum class) enums whose size likely is int, yet its declared
// type in the schema is byte.
@@ -184,14 +186,14 @@
// return the buffer for the caller to use.
auto bufferpointer =
- reinterpret_cast<const char *>(builder.GetBufferPointer());
+ reinterpret_cast<const char*>(builder.GetBufferPointer());
buffer.assign(bufferpointer, bufferpointer + builder.GetSize());
return builder.Release();
}
// example of accessing a buffer loaded in memory:
-void AccessFlatBufferTest(const uint8_t *flatbuf, size_t length, bool pooled) {
+void AccessFlatBufferTest(const uint8_t* flatbuf, size_t length, bool pooled) {
// First, verify the buffers integrity (optional)
flatbuffers::Verifier verifier(flatbuf, length);
std::vector<uint8_t> flex_reuse_tracker;
@@ -238,7 +240,7 @@
auto inventory = monster->inventory();
TEST_EQ(VectorLength(inventory), 10UL); // Works even if inventory is null.
TEST_NOTNULL(inventory);
- unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
+ unsigned char inv_data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// Check compatibilty of iterators with STL.
std::vector<unsigned char> inv_vec(inventory->begin(), inventory->end());
size_t n = 0;
@@ -277,7 +279,7 @@
// Example of accessing a union:
TEST_EQ(monster->test_type(), Any_Monster); // First make sure which it is.
- auto monster2 = reinterpret_cast<const Monster *>(monster->test());
+ auto monster2 = reinterpret_cast<const Monster*>(monster->test());
TEST_NOTNULL(monster2);
TEST_EQ_STR(monster2->name()->c_str(), "Fred");
@@ -350,8 +352,7 @@
}
TEST_NOTNULL(vecofstructs->LookupByKey(0)); // test default value
TEST_NOTNULL(vecofstructs->LookupByKey(3));
- TEST_EQ(static_cast<const Ability *>(nullptr),
- vecofstructs->LookupByKey(5));
+ TEST_EQ(static_cast<const Ability*>(nullptr), vecofstructs->LookupByKey(5));
}
if (auto vec_of_stat = monster->scalar_key_sorted_tables()) {
@@ -394,9 +395,9 @@
TEST_EQ(flatbuffers::AlignOf<Test>(), 2UL);
TEST_EQ(sizeof(Test), 4UL);
- const flatbuffers::Vector<const Test *> *tests_array[] = {
- monster->test4(),
- monster->test5(),
+ const flatbuffers::Vector<const Test*>* tests_array[] = {
+ monster->test4(),
+ monster->test5(),
};
for (size_t i = 0; i < sizeof(tests_array) / sizeof(tests_array[0]); ++i) {
auto tests = tests_array[i];
@@ -421,7 +422,7 @@
}
// Change a FlatBuffer in-place, after it has been constructed.
-void MutateFlatBuffersTest(uint8_t *flatbuf, std::size_t length) {
+void MutateFlatBuffersTest(uint8_t* flatbuf, std::size_t length) {
// Get non-const pointer to root.
auto monster = GetMutableMonster(flatbuf);
@@ -451,7 +452,7 @@
// Mutate structs.
auto pos = monster->mutable_pos();
- auto &test3 = pos->mutable_test3(); // Struct inside a struct.
+ auto& test3 = pos->mutable_test3(); // Struct inside a struct.
test3.mutate_a(50); // Struct fields never fail.
TEST_EQ(test3.a(), 50);
test3.mutate_a(10);
@@ -480,7 +481,7 @@
// Mutate via LookupByKey
TEST_NOTNULL(tables->MutableLookupByKey("Barney"));
- TEST_EQ(static_cast<Monster *>(nullptr),
+ TEST_EQ(static_cast<Monster*>(nullptr),
tables->MutableLookupByKey("DoesntExist"));
TEST_EQ(tables->MutableLookupByKey("Barney")->hp(), 1000);
TEST_EQ(tables->MutableLookupByKey("Barney")->mutate_hp(0), true);
@@ -493,18 +494,18 @@
}
// Unpack a FlatBuffer into objects.
-void ObjectFlatBuffersTest(uint8_t *flatbuf) {
+void ObjectFlatBuffersTest(uint8_t* flatbuf) {
// Optional: we can specify resolver and rehasher functions to turn hashed
// strings into object pointers and back, to implement remote references
// and such.
auto resolver = flatbuffers::resolver_function_t(
- [](void **pointer_adr, flatbuffers::hash_value_t hash) {
+ [](void** pointer_adr, flatbuffers::hash_value_t hash) {
(void)pointer_adr;
(void)hash;
// Don't actually do anything, leave variable null.
});
auto rehasher = flatbuffers::rehasher_function_t(
- [](void *pointer) -> flatbuffers::hash_value_t {
+ [](void* pointer) -> flatbuffers::hash_value_t {
(void)pointer;
return 0;
});
@@ -549,20 +550,20 @@
}
// Utility function to check a Monster object.
-void CheckMonsterObject(MonsterT *monster2) {
+void CheckMonsterObject(MonsterT* monster2) {
TEST_EQ(monster2->hp, 80);
TEST_EQ(monster2->mana, 150); // default
TEST_EQ_STR(monster2->name.c_str(), "MyMonster");
- auto &pos = monster2->pos;
+ auto& pos = monster2->pos;
TEST_NOTNULL(pos);
TEST_EQ(pos->z(), 3);
TEST_EQ(pos->test3().a(), 10);
TEST_EQ(pos->test3().b(), 20);
- auto &inventory = monster2->inventory;
+ auto& inventory = monster2->inventory;
TEST_EQ(inventory.size(), 10UL);
- unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
+ unsigned char inv_data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (auto it = inventory.begin(); it != inventory.end(); ++it)
TEST_EQ(*it, inv_data[it - inventory.begin()]);
@@ -572,24 +573,24 @@
TEST_NOTNULL(monster3);
TEST_EQ_STR(monster3->name.c_str(), "Fred");
- auto &vecofstrings = monster2->testarrayofstring;
+ auto& vecofstrings = monster2->testarrayofstring;
TEST_EQ(vecofstrings.size(), 4U);
TEST_EQ_STR(vecofstrings[0].c_str(), "bob");
TEST_EQ_STR(vecofstrings[1].c_str(), "fred");
- auto &vecofstrings2 = monster2->testarrayofstring2;
+ auto& vecofstrings2 = monster2->testarrayofstring2;
TEST_EQ(vecofstrings2.size(), 2U);
TEST_EQ_STR(vecofstrings2[0].c_str(), "jane");
TEST_EQ_STR(vecofstrings2[1].c_str(), "mary");
- auto &vecoftables = monster2->testarrayoftables;
+ auto& vecoftables = monster2->testarrayoftables;
TEST_EQ(vecoftables.size(), 3U);
TEST_EQ_STR(vecoftables[0]->name.c_str(), "Barney");
TEST_EQ(vecoftables[0]->hp, 1000);
TEST_EQ_STR(vecoftables[1]->name.c_str(), "Fred");
TEST_EQ_STR(vecoftables[2]->name.c_str(), "Wilma");
- auto &tests = monster2->test4;
+ auto& tests = monster2->test4;
TEST_EQ(tests[0].a(), 10);
TEST_EQ(tests[0].b(), 20);
TEST_EQ(tests[1].a(), 30);
@@ -634,7 +635,7 @@
}
}
-void TestMonsterExtraFloats(const std::string &tests_data_path) {
+void TestMonsterExtraFloats(const std::string& tests_data_path) {
#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
TEST_EQ(is_quiet_nan(1.0), false);
TEST_EQ(is_quiet_nan(infinity_d), false);
@@ -652,8 +653,8 @@
// Parse schema first, so we can use it to parse the data after.
Parser parser;
auto include_test_path = ConCatPathFileName(tests_data_path, "include_test");
- const char *include_directories[] = { tests_data_path.c_str(),
- include_test_path.c_str(), nullptr };
+ const char* include_directories[] = {tests_data_path.c_str(),
+ include_test_path.c_str(), nullptr};
TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
// Create empty extra and store to json.
parser.opts.output_default_scalars_in_json = true;
@@ -774,7 +775,7 @@
// example of parsing text straight into a buffer, and generating
// text back from it:
-void ParseAndGenerateTextTest(const std::string &tests_data_path, bool binary) {
+void ParseAndGenerateTextTest(const std::string& tests_data_path, bool binary) {
// load FlatBuffer schema (.fbs) and JSON from disk
std::string schemafile;
std::string jsonfile;
@@ -790,21 +791,21 @@
auto include_test_path =
flatbuffers::ConCatPathFileName(tests_data_path, "include_test");
- const char *include_directories[] = { tests_data_path.c_str(),
- include_test_path.c_str(), nullptr };
+ const char* include_directories[] = {tests_data_path.c_str(),
+ include_test_path.c_str(), nullptr};
// parse schema first, so we can use it to parse the data after
flatbuffers::Parser parser;
if (binary) {
flatbuffers::Verifier verifier(
- reinterpret_cast<const uint8_t *>(schemafile.c_str()),
+ reinterpret_cast<const uint8_t*>(schemafile.c_str()),
schemafile.size());
TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
// auto schema = reflection::GetSchema(schemafile.c_str());
- TEST_EQ(parser.Deserialize(
- reinterpret_cast<const uint8_t *>(schemafile.c_str()),
- schemafile.size()),
- true);
+ TEST_EQ(
+ parser.Deserialize(reinterpret_cast<const uint8_t*>(schemafile.c_str()),
+ schemafile.size()),
+ true);
} else {
TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
}
@@ -866,14 +867,14 @@
TEST_EQ_STR(jsongen_utf8.c_str(), jsonfile_utf8.c_str());
}
-void UnPackTo(const uint8_t *flatbuf) {
+void UnPackTo(const uint8_t* flatbuf) {
// Get a monster that has a name and no enemy
auto orig_monster = GetMonster(flatbuf);
TEST_EQ_STR(orig_monster->name()->c_str(), "MyMonster");
TEST_ASSERT(orig_monster->enemy() == nullptr);
// Create an enemy
- MonsterT *enemy = new MonsterT();
+ MonsterT* enemy = new MonsterT();
enemy->name = "Enemy";
// And create another monster owning the enemy,
diff --git a/tests/native_type_test_impl.cpp b/tests/native_type_test_impl.cpp
index b5b595b..5c54025 100644
--- a/tests/native_type_test_impl.cpp
+++ b/tests/native_type_test_impl.cpp
@@ -3,19 +3,19 @@
#include "native_type_test_generated.h"
namespace flatbuffers {
-Geometry::Vector3D Pack(const Native::Vector3D &obj) {
+Geometry::Vector3D Pack(const Native::Vector3D& obj) {
return Geometry::Vector3D(obj.x, obj.y, obj.z);
}
-const Native::Vector3D UnPack(const Geometry::Vector3D &obj) {
+const Native::Vector3D UnPack(const Geometry::Vector3D& obj) {
return Native::Vector3D(obj.x(), obj.y(), obj.z());
}
-Geometry::Vector3DAlt PackVector3DAlt(const Native::Vector3D &obj) {
+Geometry::Vector3DAlt PackVector3DAlt(const Native::Vector3D& obj) {
return Geometry::Vector3DAlt(obj.x, obj.y, obj.z);
}
-const Native::Vector3D UnPackVector3DAlt(const Geometry::Vector3DAlt &obj) {
+const Native::Vector3D UnPackVector3DAlt(const Geometry::Vector3DAlt& obj) {
return Native::Vector3D(obj.a(), obj.b(), obj.c());
}
} // namespace flatbuffers
diff --git a/tests/optional_scalars_test.cpp b/tests/optional_scalars_test.cpp
index 7713eb5..0e1fae3 100644
--- a/tests/optional_scalars_test.cpp
+++ b/tests/optional_scalars_test.cpp
@@ -43,7 +43,7 @@
const bool has_null = schema->find("null") != std::string::npos;
flatbuffers::Parser parser;
TEST_ASSERT(parser.Parse(schema->c_str()));
- const auto *mana = parser.structs_.Lookup("Monster")->fields.Lookup("mana");
+ const auto* mana = parser.structs_.Lookup("Monster")->fields.Lookup("mana");
TEST_EQ(mana->IsOptional(), has_null);
}
diff --git a/tests/parser_test.cpp b/tests/parser_test.cpp
index 33b1d6e..e03fd96 100644
--- a/tests/parser_test.cpp
+++ b/tests/parser_test.cpp
@@ -16,9 +16,9 @@
static const auto infinity_d = std::numeric_limits<double>::infinity();
// Test that parser errors are actually generated.
-static void TestError_(const char *src, const char *error_substr,
- bool strict_json, const char *file, int line,
- const char *func) {
+static void TestError_(const char* src, const char* error_substr,
+ bool strict_json, const char* file, int line,
+ const char* func) {
flatbuffers::IDLOptions opts;
opts.strict_json = strict_json;
flatbuffers::Parser parser(opts);
@@ -33,17 +33,17 @@
}
}
-static void TestError_(const char *src, const char *error_substr,
- const char *file, int line, const char *func) {
+static void TestError_(const char* src, const char* error_substr,
+ const char* file, int line, const char* func) {
TestError_(src, error_substr, false, file, line, func);
}
#ifdef _WIN32
-# define TestError(src, ...) \
- TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
+#define TestError(src, ...) \
+ TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
#else
-# define TestError(src, ...) \
- TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __PRETTY_FUNCTION__)
+#define TestError(src, ...) \
+ TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __PRETTY_FUNCTION__)
#endif
static bool FloatCompare(float a, float b) { return fabs(a - b) < 0.001; }
@@ -462,13 +462,15 @@
TestError(locale_ident.c_str(), "");
}
-template<typename T>
-T TestValue(const char *json, const char *type_name,
- const char *decls = nullptr) {
+template <typename T>
+T TestValue(const char* json, const char* type_name,
+ const char* decls = nullptr) {
flatbuffers::Parser parser;
parser.builder_.ForceDefaults(true); // return defaults
auto check_default = json ? false : true;
- if (check_default) { parser.opts.output_default_scalars_in_json = true; }
+ if (check_default) {
+ parser.opts.output_default_scalars_in_json = true;
+ }
// Simple schema.
std::string schema = std::string(decls ? decls : "") + "\n" +
"table X { y:" + std::string(type_name) +
@@ -486,7 +488,9 @@
parser.opts.indent_step = -1;
TEST_NULL(GenText(parser, parser.builder_.GetBufferPointer(), &print_back));
// restore value from its default
- if (check_default) { TEST_EQ(parser.Parse(print_back.c_str()), true); }
+ if (check_default) {
+ TEST_EQ(parser.Parse(print_back.c_str()), true);
+ }
auto root = flatbuffers::GetRoot<flatbuffers::Table>(
parser.builder_.GetBufferPointer());
@@ -796,7 +800,7 @@
true);
auto root = flatbuffers::GetRoot<flatbuffers::Table>(
parser.builder_.GetBufferPointer());
- auto string = root->GetPointer<flatbuffers::String *>(
+ auto string = root->GetPointer<flatbuffers::String*>(
flatbuffers::FieldIndexToOffset(0));
TEST_EQ_STR(string->c_str(), "\xF0\x9F\x92\xA9");
}
@@ -843,11 +847,14 @@
true);
// Test union underlying type
- const char *source = "table A {} table B {} union U : int {A, B} table C {test_union: U; test_vector_of_union: [U];}";
+ const char* source =
+ "table A {} table B {} union U : int {A, B} table C {test_union: U; "
+ "test_vector_of_union: [U];}";
flatbuffers::Parser parser3;
- parser3.opts.lang_to_generate = flatbuffers::IDLOptions::kCpp | flatbuffers::IDLOptions::kTs;
+ parser3.opts.lang_to_generate =
+ flatbuffers::IDLOptions::kCpp | flatbuffers::IDLOptions::kTs;
TEST_EQ(parser3.Parse(source), true);
-
+
parser3.opts.lang_to_generate &= flatbuffers::IDLOptions::kJava;
TEST_EQ(parser3.Parse(source), false);
}
@@ -898,7 +905,7 @@
for (auto s = schemas.begin(); s < schemas.end(); s++) {
flatbuffers::Parser parser;
TEST_ASSERT(parser.Parse(s->c_str()));
- const auto *mana = parser.structs_.Lookup("Monster")->fields.Lookup("mana");
+ const auto* mana = parser.structs_.Lookup("Monster")->fields.Lookup("mana");
TEST_EQ(mana->IsDefault(), true);
}
}
diff --git a/tests/proto_test.cpp b/tests/proto_test.cpp
index 90c70bd..7a6f163 100644
--- a/tests/proto_test.cpp
+++ b/tests/proto_test.cpp
@@ -7,10 +7,10 @@
namespace flatbuffers {
namespace tests {
-void RunTest(const flatbuffers::IDLOptions &opts, const std::string &proto_path,
- const std::string &proto_file, const std::string &golden_file,
+void RunTest(const flatbuffers::IDLOptions& opts, const std::string& proto_path,
+ const std::string& proto_file, const std::string& golden_file,
const std::string import_proto_file) {
- const char *include_directories[] = { proto_path.c_str(), nullptr };
+ const char* include_directories[] = {proto_path.c_str(), nullptr};
// Parse proto.
flatbuffers::Parser parser(opts);
@@ -48,7 +48,7 @@
TEST_EQ_STR(fbs.c_str(), golden_file.c_str());
}
-void proto_test(const std::string &proto_path, const std::string &proto_file) {
+void proto_test(const std::string& proto_path, const std::string& proto_file) {
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = false;
opts.proto_mode = true;
@@ -63,8 +63,8 @@
RunTest(opts, proto_path, proto_file, golden_file);
}
-void proto_test_id(const std::string &proto_path,
- const std::string &proto_file) {
+void proto_test_id(const std::string& proto_path,
+ const std::string& proto_file) {
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = false;
opts.proto_mode = true;
@@ -80,8 +80,8 @@
RunTest(opts, proto_path, proto_file, golden_file);
}
-void proto_test_union(const std::string &proto_path,
- const std::string &proto_file) {
+void proto_test_union(const std::string& proto_path,
+ const std::string& proto_file) {
// Parse proto with --oneof-union option.
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = false;
@@ -96,8 +96,8 @@
RunTest(opts, proto_path, proto_file, golden_file);
}
-void proto_test_union_id(const std::string &proto_path,
- const std::string &proto_file) {
+void proto_test_union_id(const std::string& proto_path,
+ const std::string& proto_file) {
// Parse proto with --oneof-union option.
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = false;
@@ -114,8 +114,8 @@
RunTest(opts, proto_path, proto_file, golden_file);
}
-void proto_test_union_suffix(const std::string &proto_path,
- const std::string &proto_file) {
+void proto_test_union_suffix(const std::string& proto_path,
+ const std::string& proto_file) {
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = false;
opts.proto_mode = true;
@@ -131,8 +131,8 @@
RunTest(opts, proto_path, proto_file, golden_file);
}
-void proto_test_union_suffix_id(const std::string &proto_path,
- const std::string &proto_file) {
+void proto_test_union_suffix_id(const std::string& proto_path,
+ const std::string& proto_file) {
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = false;
opts.proto_mode = true;
@@ -149,9 +149,9 @@
RunTest(opts, proto_path, proto_file, golden_file);
}
-void proto_test_include(const std::string &proto_path,
- const std::string &proto_file,
- const std::string &import_proto_file) {
+void proto_test_include(const std::string& proto_path,
+ const std::string& proto_file,
+ const std::string& import_proto_file) {
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = true;
opts.proto_mode = true;
@@ -166,9 +166,9 @@
RunTest(opts, proto_path, proto_file, golden_file, import_proto_file);
}
-void proto_test_include_id(const std::string &proto_path,
- const std::string &proto_file,
- const std::string &import_proto_file) {
+void proto_test_include_id(const std::string& proto_path,
+ const std::string& proto_file,
+ const std::string& import_proto_file) {
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = true;
opts.proto_mode = true;
@@ -184,9 +184,9 @@
RunTest(opts, proto_path, proto_file, golden_file, import_proto_file);
}
-void proto_test_include_union(const std::string &proto_path,
- const std::string &proto_file,
- const std::string &import_proto_file) {
+void proto_test_include_union(const std::string& proto_path,
+ const std::string& proto_file,
+ const std::string& import_proto_file) {
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = true;
opts.proto_mode = true;
@@ -202,9 +202,9 @@
RunTest(opts, proto_path, proto_file, golden_file, import_proto_file);
}
-void proto_test_include_union_id(const std::string &proto_path,
- const std::string &proto_file,
- const std::string &import_proto_file) {
+void proto_test_include_union_id(const std::string& proto_path,
+ const std::string& proto_file,
+ const std::string& import_proto_file) {
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = true;
opts.proto_mode = true;
@@ -221,8 +221,8 @@
RunTest(opts, proto_path, proto_file, golden_file, import_proto_file);
}
-void ParseCorruptedProto(const std::string &proto_path) {
- const char *include_directories[] = { proto_path.c_str(), nullptr };
+void ParseCorruptedProto(const std::string& proto_path) {
+ const char* include_directories[] = {proto_path.c_str(), nullptr};
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = true;
@@ -282,7 +282,7 @@
}
// Parse a .proto schema, output as .fbs
-void ParseProtoTest(const std::string &tests_data_path) {
+void ParseProtoTest(const std::string& tests_data_path) {
auto proto_path = tests_data_path + "prototest/";
std::string proto_file;
TEST_EQ(
@@ -325,8 +325,7 @@
// Similarly, in text output, it should omit these.
std::string text;
auto err =
- flatbuffers::GenText(
- parser, parser.builder_.GetBufferPointer(), &text);
+ flatbuffers::GenText(parser, parser.builder_.GetBufferPointer(), &text);
TEST_NULL(err);
TEST_EQ_STR(text.c_str(),
"{\n A [\n 1\n 2\n ]\n C {\n B: 2\n }\n}\n");
diff --git a/tests/reflection_test.cpp b/tests/reflection_test.cpp
index 880f137..1c48918 100644
--- a/tests/reflection_test.cpp
+++ b/tests/reflection_test.cpp
@@ -1,6 +1,5 @@
#include "reflection_test.h"
-#include "tests/arrays_test_generated.h"
#include "flatbuffers/minireflect.h"
#include "flatbuffers/reflection.h"
#include "flatbuffers/reflection_generated.h"
@@ -8,13 +7,14 @@
#include "monster_test.h"
#include "monster_test_generated.h"
#include "test_assert.h"
+#include "tests/arrays_test_generated.h"
namespace flatbuffers {
namespace tests {
using namespace MyGame::Example;
-void ReflectionTest(const std::string &tests_data_path, uint8_t *flatbuf,
+void ReflectionTest(const std::string& tests_data_path, uint8_t* flatbuf,
size_t length) {
// Load a binary schema.
std::string bfbsfile;
@@ -24,11 +24,11 @@
// Verify it, just in case:
flatbuffers::Verifier verifier(
- reinterpret_cast<const uint8_t *>(bfbsfile.c_str()), bfbsfile.length());
+ reinterpret_cast<const uint8_t*>(bfbsfile.c_str()), bfbsfile.length());
TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
// Make sure the schema is what we expect it to be.
- auto &schema = *reflection::GetSchema(bfbsfile.c_str());
+ auto& schema = *reflection::GetSchema(bfbsfile.c_str());
auto root_table = schema.root_table();
// Check the declaration files.
@@ -83,7 +83,7 @@
auto fields = root_table->fields();
auto hp_field_ptr = fields->LookupByKey("hp");
TEST_NOTNULL(hp_field_ptr);
- auto &hp_field = *hp_field_ptr;
+ auto& hp_field = *hp_field_ptr;
TEST_EQ_STR(hp_field.name()->c_str(), "hp");
TEST_EQ(hp_field.id(), 2);
TEST_EQ(hp_field.type()->base_type(), reflection::Short);
@@ -108,7 +108,7 @@
TEST_EQ(fields->LookupByKey("name")->optional(), false);
// Now use it to dynamically access a buffer.
- auto &root = *flatbuffers::GetAnyRoot(flatbuf);
+ auto& root = *flatbuffers::GetAnyRoot(flatbuf);
// Verify the buffer first using reflection based verification
TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), flatbuf, length),
@@ -169,7 +169,7 @@
// First we put the FlatBuffer inside an std::vector.
std::vector<uint8_t> resizingbuf(flatbuf, flatbuf + length);
// Find the field we want to modify.
- auto &name_field = *fields->LookupByKey("name");
+ auto& name_field = *fields->LookupByKey("name");
// Get the root.
// This time we wrap the result from GetAnyRoot in a smartpointer that
// will keep rroot valid as resizingbuf resizes.
@@ -180,7 +180,7 @@
// Here resizingbuf has changed, but rroot is still valid.
TEST_EQ_STR(GetFieldS(**rroot, name_field)->c_str(), "totally new string");
// Now lets extend a vector by 100 elements (10 -> 110).
- auto &inventory_field = *fields->LookupByKey("inventory");
+ auto& inventory_field = *fields->LookupByKey("inventory");
auto rinventory = flatbuffers::piv(
flatbuffers::GetFieldV<uint8_t>(**rroot, inventory_field), resizingbuf);
flatbuffers::ResizeVector<uint8_t>(schema, 110, 50, *rinventory,
@@ -193,7 +193,7 @@
// FlatBuffer of its own, then add that to an existing FlatBuffer:
// As an example, let's add a string to an array of strings.
// First, find our field:
- auto &testarrayofstring_field = *fields->LookupByKey("testarrayofstring");
+ auto& testarrayofstring_field = *fields->LookupByKey("testarrayofstring");
// Find the vector value:
auto rtestarrayofstring = flatbuffers::piv(
flatbuffers::GetFieldV<flatbuffers::Offset<flatbuffers::String>>(
@@ -218,8 +218,7 @@
TEST_EQ_STR(rtestarrayofstring->Get(2)->c_str(), "hank");
// Test integrity of all resize operations above.
flatbuffers::Verifier resize_verifier(
- reinterpret_cast<const uint8_t *>(resizingbuf.data()),
- resizingbuf.size());
+ reinterpret_cast<const uint8_t*>(resizingbuf.data()), resizingbuf.size());
TEST_EQ(VerifyMonsterBuffer(resize_verifier), true);
// Test buffer is valid using reflection as well
@@ -249,7 +248,7 @@
true);
}
-void MiniReflectFlatBuffersTest(uint8_t *flatbuf) {
+void MiniReflectFlatBuffersTest(uint8_t* flatbuf) {
auto s =
flatbuffers::FlatBufferToString(flatbuf, Monster::MiniReflectTypeTable());
TEST_EQ_STR(
diff --git a/tests/test.cpp b/tests/test.cpp
index 1564fa7..c499ece 100644
--- a/tests/test.cpp
+++ b/tests/test.cpp
@@ -47,7 +47,7 @@
#include "tests/union_vector/union_vector_generated.h"
#include "union_underlying_type_test_generated.h"
#if !defined(_MSC_VER) || _MSC_VER >= 1700
-# include "tests/arrays_test_generated.h"
+#include "tests/arrays_test_generated.h"
#endif
#if INCLUDE_64_BIT_TESTS
#include "tests/64bit/offset64_test.h"
@@ -97,7 +97,7 @@
// Guard against -Wunused-function on platforms without file tests.
#ifndef FLATBUFFERS_NO_FILE_TESTS
-void GenerateTableTextTest(const std::string &tests_data_path) {
+void GenerateTableTextTest(const std::string& tests_data_path) {
std::string schemafile;
std::string jsonfile;
bool ok =
@@ -108,8 +108,8 @@
TEST_EQ(ok, true);
auto include_test_path =
flatbuffers::ConCatPathFileName(tests_data_path, "include_test");
- const char *include_directories[] = { tests_data_path.c_str(),
- include_test_path.c_str(), nullptr };
+ const char* include_directories[] = {tests_data_path.c_str(),
+ include_test_path.c_str(), nullptr};
flatbuffers::IDLOptions opt;
opt.indent_step = -1;
flatbuffers::Parser parser(opt);
@@ -117,7 +117,7 @@
parser.Parse(jsonfile.c_str(), include_directories);
TEST_EQ(ok, true);
// Test root table
- const Monster *monster = GetMonster(parser.builder_.GetBufferPointer());
+ const Monster* monster = GetMonster(parser.builder_.GetBufferPointer());
const auto abilities = monster->testarrayofsortedstruct();
TEST_EQ(abilities->size(), 3);
TEST_EQ(abilities->Get(0)->id(), 0);
@@ -128,35 +128,33 @@
TEST_EQ(abilities->Get(2)->distance(), 12);
std::string jsongen;
- auto result = GenTextFromTable(parser, monster, "MyGame.Example.Monster",
- &jsongen);
+ auto result =
+ GenTextFromTable(parser, monster, "MyGame.Example.Monster", &jsongen);
TEST_NULL(result);
// Test sub table
- const Vec3 *pos = monster->pos();
+ const Vec3* pos = monster->pos();
jsongen.clear();
result = GenTextFromTable(parser, pos, "MyGame.Example.Vec3", &jsongen);
TEST_NULL(result);
TEST_EQ_STR(
jsongen.c_str(),
"{x: 1.0,y: 2.0,z: 3.0,test1: 3.0,test2: \"Green\",test3: {a: 5,b: 6}}");
- const Test &test3 = pos->test3();
+ const Test& test3 = pos->test3();
jsongen.clear();
- result =
- GenTextFromTable(parser, &test3, "MyGame.Example.Test", &jsongen);
+ result = GenTextFromTable(parser, &test3, "MyGame.Example.Test", &jsongen);
TEST_NULL(result);
TEST_EQ_STR(jsongen.c_str(), "{a: 5,b: 6}");
- const Test *test4 = monster->test4()->Get(0);
+ const Test* test4 = monster->test4()->Get(0);
jsongen.clear();
- result =
- GenTextFromTable(parser, test4, "MyGame.Example.Test", &jsongen);
+ result = GenTextFromTable(parser, test4, "MyGame.Example.Test", &jsongen);
TEST_NULL(result);
TEST_EQ_STR(jsongen.c_str(), "{a: 10,b: 20}");
}
-void MultiFileNameClashTest(const std::string &tests_data_path) {
+void MultiFileNameClashTest(const std::string& tests_data_path) {
const auto name_clash_path =
flatbuffers::ConCatPathFileName(tests_data_path, "name_clash_test");
- const char *include_directories[] = { name_clash_path.c_str() };
+ const char* include_directories[] = {name_clash_path.c_str()};
// Load valid 2 file Flatbuffer schema
const auto valid_path =
@@ -182,7 +180,7 @@
false);
}
-void InvalidNestedFlatbufferTest(const std::string &tests_data_path) {
+void InvalidNestedFlatbufferTest(const std::string& tests_data_path) {
// First, load and parse FlatBuffer schema (.fbs)
std::string schemafile;
TEST_EQ(flatbuffers::LoadFile((tests_data_path + "monster_test.fbs").c_str(),
@@ -190,8 +188,8 @@
true);
auto include_test_path =
flatbuffers::ConCatPathFileName(tests_data_path, "include_test");
- const char *include_directories[] = { tests_data_path.c_str(),
- include_test_path.c_str(), nullptr };
+ const char* include_directories[] = {tests_data_path.c_str(),
+ include_test_path.c_str(), nullptr};
flatbuffers::Parser parser1;
TEST_EQ(parser1.Parse(schemafile.c_str(), include_directories), true);
@@ -201,7 +199,7 @@
false);
}
-void UnionVectorTest(const std::string &tests_data_path) {
+void UnionVectorTest(const std::string& tests_data_path) {
// load FlatBuffer fbs schema and json.
std::string schemafile, jsonfile;
TEST_EQ(flatbuffers::LoadFile(
@@ -249,7 +247,7 @@
auto flat_movie = GetMovie(fbb.GetBufferPointer());
- auto TestMovie = [](const Movie *movie) {
+ auto TestMovie = [](const Movie* movie) {
TEST_EQ(movie->main_character_type() == Character_Rapunzel, true);
auto cts = movie->characters_type();
@@ -405,7 +403,7 @@
void UninitializedVectorTest() {
flatbuffers::FlatBufferBuilder builder;
- Test *buf = nullptr;
+ Test* buf = nullptr;
auto vector_offset =
builder.CreateUninitializedVectorOfStructs<Test>(2, &buf);
TEST_NOTNULL(buf);
@@ -550,8 +548,8 @@
TEST_EQ(onetwo.o != two.o, true);
// Support for embedded nulls
- const char chars_b[] = { 'a', '\0', 'b' };
- const char chars_c[] = { 'a', '\0', 'c' };
+ const char chars_b[] = {'a', '\0', 'b'};
+ const char chars_c[] = {'a', '\0', 'c'};
const auto null_b1 = builder.CreateSharedString(chars_b, sizeof(chars_b));
const auto null_c = builder.CreateSharedString(chars_c, sizeof(chars_c));
const auto null_b2 = builder.CreateSharedString(chars_b, sizeof(chars_b));
@@ -560,8 +558,7 @@
// Put the strings into an array for round trip verification.
std::array<flatbuffers::Offset<flatbuffers::String>, 7> array = {
- one1, two, one2, onetwo, null_b1, null_c, null_b2
- };
+ one1, two, one2, onetwo, null_b1, null_c, null_b2};
const auto vector_offset =
builder.CreateVector<flatbuffers::Offset<flatbuffers::String>>(array);
MonsterBuilder monster_builder(builder);
@@ -570,12 +567,12 @@
builder.Finish(monster_builder.Finish());
// Read the Monster back.
- const auto *monster =
+ const auto* monster =
flatbuffers::GetRoot<Monster>(builder.GetBufferPointer());
TEST_EQ_STR(monster->name()->c_str(), "two");
- const auto *testarrayofstring = monster->testarrayofstring();
+ const auto* testarrayofstring = monster->testarrayofstring();
TEST_EQ(testarrayofstring->size(), flatbuffers::uoffset_t(7));
- const auto &a = *testarrayofstring;
+ const auto& a = *testarrayofstring;
TEST_EQ_STR(a[0]->c_str(), "one");
TEST_EQ_STR(a[1]->c_str(), "two");
TEST_EQ_STR(a[2]->c_str(), "one");
@@ -617,7 +614,7 @@
TEST_EQ(c3.size(), 0);
TEST_ASSERT(c1.empty() && c2.empty() && c3.empty());
- int i_data7[7] = { 0, 1, 2, 3, 4, 5, 6 };
+ int i_data7[7] = {0, 1, 2, 3, 4, 5, 6};
span<int, 7> i1(&i_data7[0], 7);
span<int> i2(i1); // make dynamic from static
TEST_EQ(i1.size(), 7);
@@ -634,7 +631,7 @@
span<const int> i7(i_data7);
TEST_EQ(i7.size(), 7);
// Check construction from a const array.
- const int i_cdata5[5] = { 4, 3, 2, 1, 0 };
+ const int i_cdata5[5] = {4, 3, 2, 1, 0};
span<const int, 5> i8(i_cdata5);
span<const int> i9(i_cdata5);
TEST_EQ(i9.size(), 5);
@@ -646,32 +643,32 @@
span<const int> i13(i_cdata5, 5);
TEST_EQ(i13.size(), 5);
// Construction from std::array.
- std::array<int, 6> i_arr6 = { { 0, 1, 2, 3, 4, 5 } };
+ std::array<int, 6> i_arr6 = {{0, 1, 2, 3, 4, 5}};
span<int, 6> i14(i_arr6);
span<const int, 6> i15(i_arr6);
span<int> i16(i_arr6);
span<const int> i17(i_arr6);
TEST_EQ(i17.size(), 6);
- const std::array<int, 8> i_carr8 = { { 0, 1, 2, 3, 4, 5, 6, 7 } };
+ const std::array<int, 8> i_carr8 = {{0, 1, 2, 3, 4, 5, 6, 7}};
span<const int, 8> i18(i_carr8);
span<const int> i19(i_carr8);
TEST_EQ(i18.size(), 8);
TEST_EQ(i19.size(), 8);
TEST_EQ(i19[7], 7);
// Check compatibility with flatbuffers::Array.
- int fbs_int3_underlaying[3] = { 0 };
- int fbs_int3_data[3] = { 1, 2, 3 };
- auto &fbs_int3 = flatbuffers::CastToArray(fbs_int3_underlaying);
+ int fbs_int3_underlaying[3] = {0};
+ int fbs_int3_data[3] = {1, 2, 3};
+ auto& fbs_int3 = flatbuffers::CastToArray(fbs_int3_underlaying);
fbs_int3.CopyFromSpan(fbs_int3_data);
TEST_EQ(fbs_int3.Get(1), 2);
- const int fbs_cint3_data[3] = { 2, 3, 4 };
+ const int fbs_cint3_data[3] = {2, 3, 4};
fbs_int3.CopyFromSpan(fbs_cint3_data);
TEST_EQ(fbs_int3.Get(1), 3);
// Check with Array<Enum, N>
enum class Dummy : uint16_t { Zero = 0, One, Two };
Dummy fbs_dummy3_underlaying[3] = {};
- Dummy fbs_dummy3_data[3] = { Dummy::One, Dummy::Two, Dummy::Two };
- auto &fbs_dummy3 = flatbuffers::CastToArray(fbs_dummy3_underlaying);
+ Dummy fbs_dummy3_data[3] = {Dummy::One, Dummy::Two, Dummy::Two};
+ auto& fbs_dummy3 = flatbuffers::CastToArray(fbs_dummy3_underlaying);
fbs_dummy3.CopyFromSpan(fbs_dummy3_data);
TEST_EQ(fbs_dummy3.Get(1), Dummy::Two);
}
@@ -771,18 +768,20 @@
const size_t arr_size = sizeof(MyGame::Example::ArrayStruct);
char non_zero_memory[arr_size];
// set memory chunk of size ArrayStruct to 1's
- std::memset(static_cast<void *>(non_zero_memory), 1, arr_size);
+ std::memset(static_cast<void*>(non_zero_memory), 1, arr_size);
// after placement-new it should be all 0's
-# if defined(_MSC_VER) && defined(_DEBUG)
-# undef new
-# endif
- MyGame::Example::ArrayStruct *ap =
+#if defined(_MSC_VER) && defined(_DEBUG)
+#undef new
+#endif
+ MyGame::Example::ArrayStruct* ap =
new (non_zero_memory) MyGame::Example::ArrayStruct;
-# if defined(_MSC_VER) && defined(_DEBUG)
-# define new DEBUG_NEW
-# endif
+#if defined(_MSC_VER) && defined(_DEBUG)
+#define new DEBUG_NEW
+#endif
(void)ap;
- for (size_t i = 0; i < arr_size; ++i) { TEST_EQ(non_zero_memory[i], 0); }
+ for (size_t i = 0; i < arr_size; ++i) {
+ TEST_EQ(non_zero_memory[i], 0);
+ }
}
#else
void FixedLengthArrayTest() {}
@@ -791,30 +790,29 @@
#if !defined(FLATBUFFERS_SPAN_MINIMAL) && \
(!defined(_MSC_VER) || _MSC_VER >= 1700)
void FixedLengthArrayConstructorTest() {
- const int32_t nested_a[2] = { 1, 2 };
- MyGame::Example::TestEnum nested_c[2] = { MyGame::Example::TestEnum::A,
- MyGame::Example::TestEnum::B };
- const int64_t int64_2[2] = { -2, -1 };
+ const int32_t nested_a[2] = {1, 2};
+ MyGame::Example::TestEnum nested_c[2] = {MyGame::Example::TestEnum::A,
+ MyGame::Example::TestEnum::B};
+ const int64_t int64_2[2] = {-2, -1};
std::array<MyGame::Example::NestedStruct, 2> init_d = {
- { MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::B,
- nested_c, int64_2),
- MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::A,
- nested_c,
- std::array<int64_t, 2>{ { 12, 13 } }) }
- };
+ {MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::B,
+ nested_c, int64_2),
+ MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::A,
+ nested_c,
+ std::array<int64_t, 2>{{12, 13}})}};
MyGame::Example::ArrayStruct arr_struct(
8.125,
std::array<int32_t, 0xF>{
- { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } },
+ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}},
-17, init_d, 10, int64_2);
TEST_EQ(arr_struct.a(), 8.125);
TEST_EQ(arr_struct.b()->Get(2), 3);
TEST_EQ(arr_struct.c(), -17);
TEST_NOTNULL(arr_struct.d());
- const auto &arr_d_0 = *arr_struct.d()->Get(0);
+ const auto& arr_d_0 = *arr_struct.d()->Get(0);
TEST_EQ(arr_d_0.a()->Get(0), 1);
TEST_EQ(arr_d_0.a()->Get(1), 2);
TEST_EQ(arr_d_0.b(), MyGame::Example::TestEnum::B);
@@ -822,7 +820,7 @@
TEST_EQ(arr_d_0.c()->Get(1), MyGame::Example::TestEnum::B);
TEST_EQ(arr_d_0.d()->Get(0), -2);
TEST_EQ(arr_d_0.d()->Get(1), -1);
- const auto &arr_d_1 = *arr_struct.d()->Get(1);
+ const auto& arr_d_1 = *arr_struct.d()->Get(1);
TEST_EQ(arr_d_1.a()->Get(0), 1);
TEST_EQ(arr_d_1.a()->Get(1), 2);
TEST_EQ(arr_d_1.b(), MyGame::Example::TestEnum::A);
@@ -858,48 +856,46 @@
#endif
void FixedLengthArrayOperatorEqualTest() {
- const int32_t nested_a[2] = { 1, 2 };
- MyGame::Example::TestEnum nested_c[2] = { MyGame::Example::TestEnum::A,
- MyGame::Example::TestEnum::B };
+ const int32_t nested_a[2] = {1, 2};
+ MyGame::Example::TestEnum nested_c[2] = {MyGame::Example::TestEnum::A,
+ MyGame::Example::TestEnum::B};
- MyGame::Example::TestEnum nested_cc[2] = { MyGame::Example::TestEnum::A,
- MyGame::Example::TestEnum::C };
- const int64_t int64_2[2] = { -2, -1 };
+ MyGame::Example::TestEnum nested_cc[2] = {MyGame::Example::TestEnum::A,
+ MyGame::Example::TestEnum::C};
+ const int64_t int64_2[2] = {-2, -1};
std::array<MyGame::Example::NestedStruct, 2> init_d = {
- { MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::B,
- nested_c, int64_2),
- MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::B,
- nested_c,
- std::array<int64_t, 2>{ { -2, -1 } }) }
- };
+ {MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::B,
+ nested_c, int64_2),
+ MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::B,
+ nested_c,
+ std::array<int64_t, 2>{{-2, -1}})}};
auto different = MyGame::Example::NestedStruct(
nested_a, MyGame::Example::TestEnum::B, nested_cc,
- std::array<int64_t, 2>{ { -2, -1 } });
+ std::array<int64_t, 2>{{-2, -1}});
TEST_ASSERT(init_d[0] == init_d[1]);
TEST_ASSERT(init_d[0] != different);
std::array<MyGame::Example::ArrayStruct, 3> arr_struct = {
- MyGame::Example::ArrayStruct(
- 8.125,
- std::array<int32_t, 0xF>{
- { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } },
- -17, init_d, 10, int64_2),
+ MyGame::Example::ArrayStruct(
+ 8.125,
+ std::array<int32_t, 0xF>{
+ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}},
+ -17, init_d, 10, int64_2),
- MyGame::Example::ArrayStruct(
- 8.125,
- std::array<int32_t, 0xF>{
- { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } },
- -17, init_d, 10, int64_2),
+ MyGame::Example::ArrayStruct(
+ 8.125,
+ std::array<int32_t, 0xF>{
+ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}},
+ -17, init_d, 10, int64_2),
- MyGame::Example::ArrayStruct(
- 8.125,
- std::array<int32_t, 0xF>{
- { 1000, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } },
- -17, init_d, 10, int64_2)
- };
+ MyGame::Example::ArrayStruct(
+ 8.125,
+ std::array<int32_t, 0xF>{
+ {1000, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}},
+ -17, init_d, 10, int64_2)};
TEST_ASSERT(arr_struct[0] == arr_struct[1]);
TEST_ASSERT(arr_struct[1] != arr_struct[2]);
@@ -935,12 +931,12 @@
TEST_EQ(dstDataT->position_inline.z, 6.0f);
for (int i = 0; i < N; ++i) {
- const Native::Vector3D &v = dstDataT->vectors[i];
+ const Native::Vector3D& v = dstDataT->vectors[i];
TEST_EQ(v.x, 10 * i + 0.1f);
TEST_EQ(v.y, 10 * i + 0.2f);
TEST_EQ(v.z, 10 * i + 0.3f);
- const Native::Vector3D &v2 = dstDataT->vectors_alt[i];
+ const Native::Vector3D& v2 = dstDataT->vectors_alt[i];
TEST_EQ(v2.x, 20 * i + 0.1f);
TEST_EQ(v2.y, 20 * i + 0.2f);
TEST_EQ(v2.z, 20 * i + 0.3f);
@@ -950,8 +946,8 @@
// Guard against -Wunused-function on platforms without file tests.
#ifndef FLATBUFFERS_NO_FILE_TESTS
// VS10 does not support typed enums, exclude from tests
-# if !defined(_MSC_VER) || _MSC_VER >= 1700
-void FixedLengthArrayJsonTest(const std::string &tests_data_path, bool binary) {
+#if !defined(_MSC_VER) || _MSC_VER >= 1700
+void FixedLengthArrayJsonTest(const std::string& tests_data_path, bool binary) {
// load FlatBuffer schema (.fbs) and JSON from disk
std::string schemafile;
std::string jsonfile;
@@ -969,15 +965,15 @@
flatbuffers::Parser parserOrg, parserGen;
if (binary) {
flatbuffers::Verifier verifier(
- reinterpret_cast<const uint8_t *>(schemafile.c_str()),
+ reinterpret_cast<const uint8_t*>(schemafile.c_str()),
schemafile.size());
TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
TEST_EQ(parserOrg.Deserialize(
- reinterpret_cast<const uint8_t *>(schemafile.c_str()),
+ reinterpret_cast<const uint8_t*>(schemafile.c_str()),
schemafile.size()),
true);
TEST_EQ(parserGen.Deserialize(
- reinterpret_cast<const uint8_t *>(schemafile.c_str()),
+ reinterpret_cast<const uint8_t*>(schemafile.c_str()),
schemafile.size()),
true);
} else {
@@ -1012,7 +1008,7 @@
0);
}
-void FixedLengthArraySpanTest(const std::string &tests_data_path) {
+void FixedLengthArraySpanTest(const std::string& tests_data_path) {
// load FlatBuffer schema (.fbs) and JSON from disk
std::string schemafile;
std::string jsonfile;
@@ -1028,7 +1024,7 @@
flatbuffers::Parser parser;
TEST_EQ(parser.Parse(schemafile.c_str()), true);
TEST_EQ(parser.Parse(jsonfile.c_str()), true);
- auto &fbb = parser.builder_;
+ auto& fbb = parser.builder_;
auto verifier = flatbuffers::Verifier(fbb.GetBufferPointer(), fbb.GetSize());
TEST_EQ(true, VerifyArrayTableBuffer(verifier));
@@ -1048,8 +1044,8 @@
TEST_ASSERT(const_d[1] == mutable_d[1]);
mutable_d[0] = const_d[0]; // mutate
// test scalars
- auto &const_nested = const_d[0];
- auto &mutable_nested = mutable_d[0];
+ auto& const_nested = const_d[0];
+ auto& mutable_nested = mutable_d[0];
static_assert(sizeof(MyGame::Example::TestEnum) == sizeof(uint8_t),
"TestEnum's underlaying type must by byte");
TEST_NOTNULL(const_nested.d());
@@ -1069,7 +1065,7 @@
std::equal(const_d_c.begin(), const_d_c.end(), mutable_d_c.begin()));
}
// test little endian array of int32
-# if FLATBUFFERS_LITTLEENDIAN
+#if FLATBUFFERS_LITTLEENDIAN
{
flatbuffers::span<const int32_t, 2> const_d_a =
flatbuffers::make_span(*const_nested.a());
@@ -1084,14 +1080,14 @@
TEST_ASSERT(
std::equal(const_d_a.begin(), const_d_a.end(), mutable_d_a.begin()));
}
-# endif
+#endif
}
-# else
+#else
void FixedLengthArrayJsonTest(bool /*binary*/) {}
void FixedLengthArraySpanTest() {}
-# endif
+#endif
-void TestEmbeddedBinarySchema(const std::string &tests_data_path) {
+void TestEmbeddedBinarySchema(const std::string& tests_data_path) {
// load JSON from disk
std::string jsonfile;
TEST_EQ(flatbuffers::LoadFile(
@@ -1139,7 +1135,8 @@
}
#endif
-template<typename T> void EmbeddedSchemaAccessByType() {
+template <typename T>
+void EmbeddedSchemaAccessByType() {
// Get the binary schema from the Type itself.
// Verify the schema is OK.
flatbuffers::Verifier verifierEmbeddedSchema(
@@ -1240,7 +1237,7 @@
// Purposely invalidate the nested flatbuffer setting its length to 0, an
// invalid length.
- uint8_t *invalid_nested_buffer = nullptr;
+ uint8_t* invalid_nested_buffer = nullptr;
auto nested_monster_bytes = builder.CreateVector(invalid_nested_buffer, 0);
auto name = builder.CreateString("OuterMonster");
@@ -1257,8 +1254,8 @@
}
}
-template<class T, class Container>
-void TestIterators(const std::vector<T> &expected, const Container &tested) {
+template <class T, class Container>
+void TestIterators(const std::vector<T>& expected, const Container& tested) {
TEST_ASSERT(tested.rbegin().base() == tested.end());
TEST_ASSERT(tested.crbegin().base() == tested.cend());
TEST_ASSERT(tested.rend().base() == tested.begin());
@@ -1266,14 +1263,14 @@
size_t k = 0;
for (auto it = tested.begin(); it != tested.end(); ++it, ++k) {
- const auto &e = expected.at(k);
+ const auto& e = expected.at(k);
TEST_EQ(*it, e);
}
TEST_EQ(k, expected.size());
k = expected.size();
for (auto it = tested.rbegin(); it != tested.rend(); ++it, --k) {
- const auto &e = expected.at(k - 1);
+ const auto& e = expected.at(k - 1);
TEST_EQ(*it, e);
}
TEST_EQ(k, 0);
@@ -1282,19 +1279,19 @@
void FlatbuffersIteratorsTest() {
{
flatbuffers::FlatBufferBuilder fbb;
- const std::vector<unsigned char> inv_data = { 1, 2, 3 };
+ const std::vector<unsigned char> inv_data = {1, 2, 3};
{
auto mon_name = fbb.CreateString("MyMonster"); // key, mandatory
auto inv_vec = fbb.CreateVector(inv_data);
auto empty_i64_vec =
- fbb.CreateVector(static_cast<const int64_t *>(nullptr), 0);
+ fbb.CreateVector(static_cast<const int64_t*>(nullptr), 0);
MonsterBuilder mb(fbb);
mb.add_name(mon_name);
mb.add_inventory(inv_vec);
mb.add_vector_of_longs(empty_i64_vec);
FinishMonsterBuffer(fbb, mb.Finish());
}
- const auto &mon = *flatbuffers::GetRoot<Monster>(fbb.GetBufferPointer());
+ const auto& mon = *flatbuffers::GetRoot<Monster>(fbb.GetBufferPointer());
TEST_EQ_STR("MyMonster", mon.name()->c_str());
TEST_ASSERT(mon.inventory());
@@ -1308,10 +1305,10 @@
MyGame::Example::ArrayStruct aStruct;
MyGame::Example::FinishArrayTableBuffer(
fbb, MyGame::Example::CreateArrayTable(fbb, &aStruct));
- const auto &array_table =
+ const auto& array_table =
*flatbuffers::GetRoot<ArrayTable>(fbb.GetBufferPointer());
TEST_ASSERT(array_table.a());
- auto &int_15 = *array_table.a()->b();
+ auto& int_15 = *array_table.a()->b();
TestIterators(std::vector<int>(15, 0), int_15);
}
}
@@ -1444,7 +1441,7 @@
auto mloc = CreateMonster(
builder, nullptr, 0, 0, builder.CreateString("Monster"),
- builder.CreateVector<uint8_t>({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }));
+ builder.CreateVector<uint8_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
FinishMonsterBuffer(builder, mloc);
@@ -1522,34 +1519,36 @@
auto offset = TestNativeInlineTable::Pack(fbb, &test);
fbb.Finish(offset);
- auto *root =
+ auto* root =
flatbuffers::GetRoot<TestNativeInlineTable>(fbb.GetBufferPointer());
TestNativeInlineTableT unpacked;
root->UnPackTo(&unpacked);
- for (int i = 0; i < 10; ++i) { TEST_ASSERT(unpacked.t[i] == test.t[i]); }
+ for (int i = 0; i < 10; ++i) {
+ TEST_ASSERT(unpacked.t[i] == test.t[i]);
+ }
TEST_ASSERT(unpacked.t == test.t);
}
// Guard against -Wunused-function on platforms without file tests.
#ifndef FLATBUFFERS_NO_FILE_TESTS
-void DoNotRequireEofTest(const std::string &tests_data_path) {
+void DoNotRequireEofTest(const std::string& tests_data_path) {
std::string schemafile;
bool ok = flatbuffers::LoadFile(
(tests_data_path + "monster_test.fbs").c_str(), false, &schemafile);
TEST_EQ(ok, true);
auto include_test_path =
flatbuffers::ConCatPathFileName(tests_data_path, "include_test");
- const char *include_directories[] = { tests_data_path.c_str(),
- include_test_path.c_str(), nullptr };
+ const char* include_directories[] = {tests_data_path.c_str(),
+ include_test_path.c_str(), nullptr};
flatbuffers::IDLOptions opt;
opt.require_json_eof = false;
flatbuffers::Parser parser(opt);
ok = parser.Parse(schemafile.c_str(), include_directories);
TEST_EQ(ok, true);
- const char *str = R"(Some text at the beginning. {
+ const char* str = R"(Some text at the beginning. {
"name": "Blob",
"hp": 5
}{
@@ -1558,11 +1557,11 @@
}
Some extra text at the end too.
)";
- const char *tableStart = std::strchr(str, '{');
+ const char* tableStart = std::strchr(str, '{');
ok = parser.ParseJson(tableStart);
TEST_EQ(ok, true);
- const Monster *monster = GetMonster(parser.builder_.GetBufferPointer());
+ const Monster* monster = GetMonster(parser.builder_.GetBufferPointer());
TEST_EQ_STR(monster->name()->c_str(), "Blob");
TEST_EQ(monster->hp(), 5);
@@ -1578,38 +1577,36 @@
#endif
void UnionUnderlyingTypeTest() {
- using namespace UnionUnderlyingType;
- TEST_ASSERT(sizeof(ABC) == sizeof(uint32_t));
- TEST_ASSERT(static_cast<int32_t>(ABC::A) == 555);
- TEST_ASSERT(static_cast<int32_t>(ABC::B) == 666);
- TEST_ASSERT(static_cast<int32_t>(ABC::C) == 777);
+ using namespace UnionUnderlyingType;
+ TEST_ASSERT(sizeof(ABC) == sizeof(uint32_t));
+ TEST_ASSERT(static_cast<int32_t>(ABC::A) == 555);
+ TEST_ASSERT(static_cast<int32_t>(ABC::B) == 666);
+ TEST_ASSERT(static_cast<int32_t>(ABC::C) == 777);
- DT buffer;
- AT a;
- a.a = 42;
- BT b;
- b.b = "foo";
- CT c;
- c.c = true;
- buffer.test_union = ABCUnion();
- buffer.test_union.Set(a);
- buffer.test_vector_of_union.resize(3);
- buffer.test_vector_of_union[0].Set(a);
- buffer.test_vector_of_union[1].Set(b);
- buffer.test_vector_of_union[2].Set(c);
+ DT buffer;
+ AT a;
+ a.a = 42;
+ BT b;
+ b.b = "foo";
+ CT c;
+ c.c = true;
+ buffer.test_union = ABCUnion();
+ buffer.test_union.Set(a);
+ buffer.test_vector_of_union.resize(3);
+ buffer.test_vector_of_union[0].Set(a);
+ buffer.test_vector_of_union[1].Set(b);
+ buffer.test_vector_of_union[2].Set(c);
- flatbuffers::FlatBufferBuilder fbb;
- auto offset = D::Pack(fbb, &buffer);
- fbb.Finish(offset);
+ flatbuffers::FlatBufferBuilder fbb;
+ auto offset = D::Pack(fbb, &buffer);
+ fbb.Finish(offset);
- auto *root =
- flatbuffers::GetRoot<D>(fbb.GetBufferPointer());
- DT unpacked;
- root->UnPackTo(&unpacked);
+ auto* root = flatbuffers::GetRoot<D>(fbb.GetBufferPointer());
+ DT unpacked;
+ root->UnPackTo(&unpacked);
- TEST_ASSERT(unpacked.test_union == buffer.test_union);
- TEST_ASSERT(unpacked.test_vector_of_union == buffer.test_vector_of_union);
-
+ TEST_ASSERT(unpacked.test_union == buffer.test_union);
+ TEST_ASSERT(unpacked.test_vector_of_union == buffer.test_vector_of_union);
}
static void Offset64Tests() {
@@ -1626,14 +1623,14 @@
#endif
}
-int FlatBufferTests(const std::string &tests_data_path) {
+int FlatBufferTests(const std::string& tests_data_path) {
// Run our various test suites:
std::string rawbuf;
auto flatbuf1 = CreateFlatBufferTest(rawbuf);
auto flatbuf = std::move(flatbuf1); // Test move assignment.
- AccessFlatBufferTest(reinterpret_cast<const uint8_t *>(rawbuf.c_str()),
+ AccessFlatBufferTest(reinterpret_cast<const uint8_t*>(rawbuf.c_str()),
rawbuf.length());
AccessFlatBufferTest(flatbuf.data(), flatbuf.size());
@@ -1745,7 +1742,7 @@
} // namespace tests
} // namespace flatbuffers
-int main(int argc, const char *argv[]) {
+int main(int argc, const char* argv[]) {
std::string tests_data_path = "tests/";
for (int argi = 1; argi < argc; argi++) {
diff --git a/tests/test_assert.cpp b/tests/test_assert.cpp
index 32dece9..090ce60 100644
--- a/tests/test_assert.cpp
+++ b/tests/test_assert.cpp
@@ -3,15 +3,15 @@
#include <assert.h>
#ifdef _MSC_VER
-# include <crtdbg.h>
-# include <windows.h>
+#include <crtdbg.h>
+#include <windows.h>
#endif
int testing_fails = 0;
static TestFailEventListener fail_listener_ = nullptr;
-void TestFail(const char *expval, const char *val, const char *exp,
- const char *file, int line, const char *func) {
+void TestFail(const char* expval, const char* val, const char* exp,
+ const char* file, int line, const char* func) {
TEST_OUTPUT_LINE("EXPECTED: \"%s\"", expval);
TEST_OUTPUT_LINE("VALUE: \"%s\"", val);
TEST_OUTPUT_LINE("TEST FAILED: %s:%d, %s in %s", file, line, exp,
@@ -24,8 +24,8 @@
assert(0); // ignored in Release if NDEBUG defined
}
-void TestEqStr(const char *expval, const char *val, const char *exp,
- const char *file, int line, const char *func) {
+void TestEqStr(const char* expval, const char* val, const char* exp,
+ const char* file, int line, const char* func) {
if (strcmp(expval, val) != 0) {
TestFail(expval, val, exp, file, line, func);
}
@@ -33,7 +33,7 @@
#if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && defined(_MSC_VER) && \
defined(_DEBUG)
-# define FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC
+#define FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC
#endif
void InitTestEngine(TestFailEventListener listener) {
diff --git a/tests/test_builder.cpp b/tests/test_builder.cpp
index 8b14a92..c782c81 100644
--- a/tests/test_builder.cpp
+++ b/tests/test_builder.cpp
@@ -11,16 +11,16 @@
class TestHeapBuilder : public FlatBufferBuilder {
private:
- TestHeapBuilder(const TestHeapBuilder &);
- TestHeapBuilder &operator=(const TestHeapBuilder &);
+ TestHeapBuilder(const TestHeapBuilder&);
+ TestHeapBuilder& operator=(const TestHeapBuilder&);
public:
TestHeapBuilder() : FlatBufferBuilder(2048, new OwnedAllocator(), true) {}
- TestHeapBuilder(TestHeapBuilder &&other)
+ TestHeapBuilder(TestHeapBuilder&& other)
: FlatBufferBuilder(std::move(other)) {}
- TestHeapBuilder &operator=(TestHeapBuilder &&other) {
+ TestHeapBuilder& operator=(TestHeapBuilder&& other) {
FlatBufferBuilder::operator=(std::move(other));
return *this;
}
@@ -34,27 +34,27 @@
struct GrpcLikeMessageBuilder : private AllocatorMember,
public FlatBufferBuilder {
private:
- GrpcLikeMessageBuilder(const GrpcLikeMessageBuilder &);
- GrpcLikeMessageBuilder &operator=(const GrpcLikeMessageBuilder &);
+ GrpcLikeMessageBuilder(const GrpcLikeMessageBuilder&);
+ GrpcLikeMessageBuilder& operator=(const GrpcLikeMessageBuilder&);
public:
GrpcLikeMessageBuilder()
: FlatBufferBuilder(1024, &member_allocator_, false) {}
- GrpcLikeMessageBuilder(GrpcLikeMessageBuilder &&other)
+ GrpcLikeMessageBuilder(GrpcLikeMessageBuilder&& other)
: FlatBufferBuilder(1024, &member_allocator_, false) {
// Default construct and swap idiom.
Swap(other);
}
- GrpcLikeMessageBuilder &operator=(GrpcLikeMessageBuilder &&other) {
+ GrpcLikeMessageBuilder& operator=(GrpcLikeMessageBuilder&& other) {
// Construct temporary and swap idiom
GrpcLikeMessageBuilder temp(std::move(other));
Swap(temp);
return *this;
}
- void Swap(GrpcLikeMessageBuilder &other) {
+ void Swap(GrpcLikeMessageBuilder& other) {
// No need to swap member_allocator_ because it's stateless.
FlatBufferBuilder::Swap(other);
// After swapping the FlatBufferBuilder, we swap back the allocator, which
@@ -67,23 +67,23 @@
};
flatbuffers::Offset<Monster> populate1(
- flatbuffers::FlatBufferBuilder &builder) {
+ flatbuffers::FlatBufferBuilder& builder) {
auto name_offset = builder.CreateString(m1_name());
return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m1_color());
}
flatbuffers::Offset<Monster> populate2(
- flatbuffers::FlatBufferBuilder &builder) {
+ flatbuffers::FlatBufferBuilder& builder) {
auto name_offset = builder.CreateString(m2_name());
return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m2_color());
}
-uint8_t *release_raw_base(flatbuffers::FlatBufferBuilder &fbb, size_t &size,
- size_t &offset) {
+uint8_t* release_raw_base(flatbuffers::FlatBufferBuilder& fbb, size_t& size,
+ size_t& offset) {
return fbb.ReleaseRaw(size, offset);
}
-void free_raw(flatbuffers::grpc::MessageBuilder &, uint8_t *) {
+void free_raw(flatbuffers::grpc::MessageBuilder&, uint8_t*) {
// release_raw_base calls FlatBufferBuilder::ReleaseRaw on the argument
// MessageBuilder. It's semantically wrong as MessageBuilder has its own
// ReleaseRaw member function that takes three arguments. In such cases
@@ -94,26 +94,26 @@
// not occur with FlatBufferBuilder.
}
-void free_raw(flatbuffers::FlatBufferBuilder &, uint8_t *buf) {
+void free_raw(flatbuffers::FlatBufferBuilder&, uint8_t* buf) {
flatbuffers::DefaultAllocator().deallocate(buf, 0);
}
-bool verify(const flatbuffers::DetachedBuffer &buf,
- const std::string &expected_name, Color color) {
- const Monster *monster = flatbuffers::GetRoot<Monster>(buf.data());
+bool verify(const flatbuffers::DetachedBuffer& buf,
+ const std::string& expected_name, Color color) {
+ const Monster* monster = flatbuffers::GetRoot<Monster>(buf.data());
return (monster->name()->str() == expected_name) &&
(monster->color() == color);
}
-bool verify(const uint8_t *buf, size_t offset, const std::string &expected_name,
+bool verify(const uint8_t* buf, size_t offset, const std::string& expected_name,
Color color) {
- const Monster *monster = flatbuffers::GetRoot<Monster>(buf + offset);
+ const Monster* monster = flatbuffers::GetRoot<Monster>(buf + offset);
return (monster->name()->str() == expected_name) &&
(monster->color() == color);
}
-bool release_n_verify(flatbuffers::FlatBufferBuilder &fbb,
- const std::string &expected_name, Color color) {
+bool release_n_verify(flatbuffers::FlatBufferBuilder& fbb,
+ const std::string& expected_name, Color color) {
flatbuffers::DetachedBuffer buf = fbb.Release();
return verify(buf, expected_name, color);
}
@@ -129,10 +129,9 @@
BuilderTests<GrpcLikeMessageBuilder>::all_tests();
BuilderReuseTestSelector tests[4] = {
- REUSABLE_AFTER_RELEASE, REUSABLE_AFTER_RELEASE_RAW,
- REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN,
- REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN
- };
+ REUSABLE_AFTER_RELEASE, REUSABLE_AFTER_RELEASE_RAW,
+ REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN,
+ REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN};
BuilderReuseTests<FlatBufferBuilder, FlatBufferBuilder>::run_tests(
TestSelector(tests, tests + 4));
@@ -143,7 +142,7 @@
}
// forward-declared in test_builder.h
-void CheckTestGeneratedIsValid(const MyGame::Example::Color &);
+void CheckTestGeneratedIsValid(const MyGame::Example::Color&);
// Link-time check using pointer type.
-void CheckTestGeneratedIsValid(const MyGame::Example::Color &) {}
+void CheckTestGeneratedIsValid(const MyGame::Example::Color&) {}
diff --git a/tests/util_test.cpp b/tests/util_test.cpp
index 924855d..fadc0ee 100644
--- a/tests/util_test.cpp
+++ b/tests/util_test.cpp
@@ -7,8 +7,8 @@
namespace tests {
namespace {
-template<typename T>
-void NumericUtilsTestInteger(const char *lower, const char *upper) {
+template <typename T>
+void NumericUtilsTestInteger(const char* lower, const char* upper) {
T x;
TEST_EQ(flatbuffers::StringToNumber("1q", &x), false);
TEST_EQ(x, 0);
@@ -21,8 +21,8 @@
TEST_EQ(x, expval);
}
-template<typename T>
-void NumericUtilsTestFloat(const char *lower, const char *upper) {
+template <typename T>
+void NumericUtilsTestFloat(const char* lower, const char* upper) {
T f;
TEST_EQ(flatbuffers::StringToNumber("", &f), false);
TEST_EQ(flatbuffers::StringToNumber("1q", &f), false);
@@ -69,53 +69,51 @@
std::vector<TestCase> cases;
// Tests for the common cases
- cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kUpperCamel,
- "TheQuickBrownFox" });
- cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kLowerCamel,
- "theQuickBrownFox" });
- cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kSnake,
- "the_quick_brown_fox" });
- cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kScreamingSnake,
- "THE_QUICK_BROWN_FOX" });
- cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kAllLower,
- "the_quick_brown_fox" });
- cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kAllUpper,
- "THE_QUICK_BROWN_FOX" });
- cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kUnknown,
- "the_quick_brown_fox" });
- cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kKeep,
- "the_quick_brown_fox" });
- cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kSnake2,
- "the_quick_brown_fox" });
+ cases.push_back({"the_quick_brown_fox", flatbuffers::Case::kUpperCamel,
+ "TheQuickBrownFox"});
+ cases.push_back({"the_quick_brown_fox", flatbuffers::Case::kLowerCamel,
+ "theQuickBrownFox"});
+ cases.push_back({"the_quick_brown_fox", flatbuffers::Case::kSnake,
+ "the_quick_brown_fox"});
+ cases.push_back({"the_quick_brown_fox", flatbuffers::Case::kScreamingSnake,
+ "THE_QUICK_BROWN_FOX"});
+ cases.push_back({"the_quick_brown_fox", flatbuffers::Case::kAllLower,
+ "the_quick_brown_fox"});
+ cases.push_back({"the_quick_brown_fox", flatbuffers::Case::kAllUpper,
+ "THE_QUICK_BROWN_FOX"});
+ cases.push_back({"the_quick_brown_fox", flatbuffers::Case::kUnknown,
+ "the_quick_brown_fox"});
+ cases.push_back({"the_quick_brown_fox", flatbuffers::Case::kKeep,
+ "the_quick_brown_fox"});
+ cases.push_back({"the_quick_brown_fox", flatbuffers::Case::kSnake2,
+ "the_quick_brown_fox"});
// Tests for some snake_cases where the _ is oddly placed or
// missing.
- cases.push_back({ "single", flatbuffers::Case::kUpperCamel, "Single" });
- cases.push_back({ "Single", flatbuffers::Case::kUpperCamel, "Single" });
- cases.push_back({ "_leading", flatbuffers::Case::kUpperCamel, "_Leading" });
- cases.push_back(
- { "trailing_", flatbuffers::Case::kUpperCamel, "Trailing_" });
- cases.push_back({ "double__underscore", flatbuffers::Case::kUpperCamel,
- "Double_underscore" });
- cases.push_back({ "single", flatbuffers::Case::kLowerCamel, "single" });
- cases.push_back({ "Single", flatbuffers::Case::kLowerCamel, "single" });
- cases.push_back({ "_leading", flatbuffers::Case::kLowerCamel, "_Leading" });
- cases.push_back(
- { "trailing_", flatbuffers::Case::kLowerCamel, "trailing_" });
- cases.push_back({ "double__underscore", flatbuffers::Case::kLowerCamel,
- "double_underscore" });
+ cases.push_back({"single", flatbuffers::Case::kUpperCamel, "Single"});
+ cases.push_back({"Single", flatbuffers::Case::kUpperCamel, "Single"});
+ cases.push_back({"_leading", flatbuffers::Case::kUpperCamel, "_Leading"});
+ cases.push_back({"trailing_", flatbuffers::Case::kUpperCamel, "Trailing_"});
+ cases.push_back({"double__underscore", flatbuffers::Case::kUpperCamel,
+ "Double_underscore"});
+ cases.push_back({"single", flatbuffers::Case::kLowerCamel, "single"});
+ cases.push_back({"Single", flatbuffers::Case::kLowerCamel, "single"});
+ cases.push_back({"_leading", flatbuffers::Case::kLowerCamel, "_Leading"});
+ cases.push_back({"trailing_", flatbuffers::Case::kLowerCamel, "trailing_"});
+ cases.push_back({"double__underscore", flatbuffers::Case::kLowerCamel,
+ "double_underscore"});
// Tests for some output snake_cases
- cases.push_back({ "single", flatbuffers::Case::kSnake, "single" });
- cases.push_back({ "single", flatbuffers::Case::kScreamingSnake, "SINGLE" });
+ cases.push_back({"single", flatbuffers::Case::kSnake, "single"});
+ cases.push_back({"single", flatbuffers::Case::kScreamingSnake, "SINGLE"});
cases.push_back(
- { "_leading", flatbuffers::Case::kScreamingSnake, "_LEADING" });
+ {"_leading", flatbuffers::Case::kScreamingSnake, "_LEADING"});
cases.push_back(
- { "trailing_", flatbuffers::Case::kScreamingSnake, "TRAILING_" });
- cases.push_back({ "double__underscore", flatbuffers::Case::kScreamingSnake,
- "DOUBLE__UNDERSCORE" });
+ {"trailing_", flatbuffers::Case::kScreamingSnake, "TRAILING_"});
+ cases.push_back({"double__underscore", flatbuffers::Case::kScreamingSnake,
+ "DOUBLE__UNDERSCORE"});
- for (auto &test_case : cases) {
+ for (auto& test_case : cases) {
TEST_EQ(test_case.expected_output,
flatbuffers::ConvertCase(test_case.input, test_case.output_case));
}
@@ -132,38 +130,38 @@
std::vector<TestCase> cases;
- cases.push_back({ flatbuffers::Case::kUpperCamel, "TheQuickBrownFox",
- flatbuffers::Case::kSnake, "the_quick_brown_fox" });
- cases.push_back({ flatbuffers::Case::kLowerCamel, "theQuickBrownFox",
- flatbuffers::Case::kSnake, "the_quick_brown_fox" });
- cases.push_back({ flatbuffers::Case::kSnake, "the_quick_brown_fox",
- flatbuffers::Case::kSnake, "the_quick_brown_fox" });
- cases.push_back({ flatbuffers::Case::kScreamingSnake, "THE_QUICK_BROWN_FOX",
- flatbuffers::Case::kSnake, "THE_QUICK_BROWN_FOX" });
- cases.push_back({ flatbuffers::Case::kAllUpper, "SINGLE",
- flatbuffers::Case::kSnake, "SINGLE" });
- cases.push_back({ flatbuffers::Case::kAllLower, "single",
- flatbuffers::Case::kSnake, "single" });
- cases.push_back({ flatbuffers::Case::kUpperCamel, "ABCtest",
- flatbuffers::Case::kSnake, "abctest" });
- cases.push_back({ flatbuffers::Case::kUpperCamel, "tHe_qUiCk_BrOwN_fOx",
- flatbuffers::Case::kKeep, "tHe_qUiCk_BrOwN_fOx" });
- cases.push_back({ flatbuffers::Case::kLowerCamel, "theQuick12345Fox",
- flatbuffers::Case::kSnake, "the_quick_12345_fox" });
- cases.push_back({ flatbuffers::Case::kLowerCamel, "a12b34c45",
- flatbuffers::Case::kSnake, "a_12b_34c_45" });
- cases.push_back({ flatbuffers::Case::kLowerCamel, "a12b34c45",
- flatbuffers::Case::kSnake2, "a12_b34_c45" });
- cases.push_back({ flatbuffers::Case::kUpperCamel, "Int32Stamped",
- flatbuffers::Case::kSnake, "int_32_stamped" });
- cases.push_back({ flatbuffers::Case::kUpperCamel, "101DogsTest",
- flatbuffers::Case::kSnake, "101_dogs_test" });
- cases.push_back({ flatbuffers::Case::kUpperCamel, "Int32Stamped",
- flatbuffers::Case::kScreamingSnake, "INT_32_STAMPED" });
- cases.push_back({ flatbuffers::Case::kUpperCamel, "101DogsTest",
- flatbuffers::Case::kScreamingSnake, "101_DOGS_TEST" });
+ cases.push_back({flatbuffers::Case::kUpperCamel, "TheQuickBrownFox",
+ flatbuffers::Case::kSnake, "the_quick_brown_fox"});
+ cases.push_back({flatbuffers::Case::kLowerCamel, "theQuickBrownFox",
+ flatbuffers::Case::kSnake, "the_quick_brown_fox"});
+ cases.push_back({flatbuffers::Case::kSnake, "the_quick_brown_fox",
+ flatbuffers::Case::kSnake, "the_quick_brown_fox"});
+ cases.push_back({flatbuffers::Case::kScreamingSnake, "THE_QUICK_BROWN_FOX",
+ flatbuffers::Case::kSnake, "THE_QUICK_BROWN_FOX"});
+ cases.push_back({flatbuffers::Case::kAllUpper, "SINGLE",
+ flatbuffers::Case::kSnake, "SINGLE"});
+ cases.push_back({flatbuffers::Case::kAllLower, "single",
+ flatbuffers::Case::kSnake, "single"});
+ cases.push_back({flatbuffers::Case::kUpperCamel, "ABCtest",
+ flatbuffers::Case::kSnake, "abctest"});
+ cases.push_back({flatbuffers::Case::kUpperCamel, "tHe_qUiCk_BrOwN_fOx",
+ flatbuffers::Case::kKeep, "tHe_qUiCk_BrOwN_fOx"});
+ cases.push_back({flatbuffers::Case::kLowerCamel, "theQuick12345Fox",
+ flatbuffers::Case::kSnake, "the_quick_12345_fox"});
+ cases.push_back({flatbuffers::Case::kLowerCamel, "a12b34c45",
+ flatbuffers::Case::kSnake, "a_12b_34c_45"});
+ cases.push_back({flatbuffers::Case::kLowerCamel, "a12b34c45",
+ flatbuffers::Case::kSnake2, "a12_b34_c45"});
+ cases.push_back({flatbuffers::Case::kUpperCamel, "Int32Stamped",
+ flatbuffers::Case::kSnake, "int_32_stamped"});
+ cases.push_back({flatbuffers::Case::kUpperCamel, "101DogsTest",
+ flatbuffers::Case::kSnake, "101_dogs_test"});
+ cases.push_back({flatbuffers::Case::kUpperCamel, "Int32Stamped",
+ flatbuffers::Case::kScreamingSnake, "INT_32_STAMPED"});
+ cases.push_back({flatbuffers::Case::kUpperCamel, "101DogsTest",
+ flatbuffers::Case::kScreamingSnake, "101_DOGS_TEST"});
- for (auto &test_case : cases) {
+ for (auto& test_case : cases) {
TEST_EQ(test_case.expected_output,
flatbuffers::ConvertCase(test_case.input, test_case.output_case,
test_case.input_case));