Also added missing generated files.
Change-Id: Ifd22a643a08e3f2edfce92812ed57b87fc0e1875
---
-Language: Cpp
-BasedOnStyle: Google
+Language: Cpp
+BasedOnStyle: Google
DerivePointerAlignment: false
PointerAlignment: Right
+IndentPPDirectives: AfterHash
+Cpp11BracedListStyle: false
+AlwaysBreakTemplateDeclarations: false
+AllowShortCaseLabelsOnASingleLine: true
+SpaceAfterTemplateKeyword: false
+AllowShortBlocksOnASingleLine: true
...
#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 {
#include <grpc++/grpc++.h>
-#include "monster_test_generated.h"
#include "monster_test.grpc.fb.h"
+#include "monster_test_generated.h"
using namespace MyGame::Example;
// The callback implementation of our server, that derives from the generated
// code. It implements all rpcs specified in the FlatBuffers schema.
class ServiceImpl final : public MyGame::Example::MonsterStorage::Service {
- virtual ::grpc::Status Store(::grpc::ServerContext* context,
- const flatbuffers::grpc::Message<Monster> *request,
- flatbuffers::grpc::Message<Stat> *response)
- override {
+ virtual ::grpc::Status Store(
+ ::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(fbb_, fbb_.CreateString("Hello, " +
- request->GetRoot()->name()->str()));
+ auto stat_offset = CreateStat(
+ fbb_, fbb_.CreateString("Hello, " + request->GetRoot()->name()->str()));
fbb_.Finish(stat_offset);
// Transfer ownership of the message to gRPC
*response = fbb_.ReleaseMessage<Stat>();
return grpc::Status::OK;
}
- virtual ::grpc::Status Retrieve(::grpc::ServerContext *context,
- const flatbuffers::grpc::Message<Stat> *request,
- ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* writer)
- override {
-
- for (int i=0; i<10; i++) {
- fbb_.Clear();
- // Create 10 monsters for resposne.
- auto monster_offset =
- CreateMonster(fbb_, 0, 0, 0, fbb_.CreateString(
- request->GetRoot()->id()->str() + " No." + std::to_string(i)));
- fbb_.Finish(monster_offset);
-
- flatbuffers::grpc::Message<Monster> monster = fbb_.ReleaseMessage<Monster>();
-
- // Send monster to client using streaming.
- writer->Write(monster);
- }
- return grpc::Status::OK;
+ virtual ::grpc::Status Retrieve(
+ ::grpc::ServerContext *context,
+ const flatbuffers::grpc::Message<Stat> *request,
+ ::grpc::ServerWriter<flatbuffers::grpc::Message<Monster>> *writer)
+ override {
+ for (int i = 0; i < 10; i++) {
+ fbb_.Clear();
+ // Create 10 monsters for resposne.
+ auto monster_offset =
+ CreateMonster(fbb_, 0, 0, 0,
+ fbb_.CreateString(request->GetRoot()->id()->str() +
+ " No." + std::to_string(i)));
+ fbb_.Finish(monster_offset);
+
+ flatbuffers::grpc::Message<Monster> monster =
+ fbb_.ReleaseMessage<Monster>();
+
+ // Send monster to client using streaming.
+ writer->Write(monster);
+ }
+ return grpc::Status::OK;
}
private:
server_instance->Wait();
}
-int main(int /*argc*/, const char * /*argv*/[]) {
+int main(int /*argc*/, const char * /*argv*/ []) {
// Launch server.
std::thread server_thread(RunServer);
grpc::InsecureChannelCredentials());
auto stub = MyGame::Example::MonsterStorage::NewStub(channel);
-
flatbuffers::grpc::MessageBuilder fbb;
{
grpc::ClientContext context;
}
}
- #if !FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION
+#if !FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION
{
// Test that an invalid request errors out correctly
grpc::ClientContext context;
// matches the protobuf gRPC status code for an unparseable message.
assert(!status.ok());
assert(status.error_code() == ::grpc::StatusCode::INTERNAL);
- assert(strcmp(status.error_message().c_str(), "Message verification failed") == 0);
+ assert(strcmp(status.error_message().c_str(),
+ "Message verification failed") == 0);
}
- #endif
+#endif
server_instance->Shutdown();
#ifndef FLATBUFFERS_BASE_H_
#define FLATBUFFERS_BASE_H_
+// clang-format off
#if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && \
defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
// 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;
}
public:
virtual bool generate() = 0;
- static std::string NamespaceDir(const Parser &parser,
- const std::string &path,
+ static std::string NamespaceDir(const Parser &parser, const std::string &path,
const Namespace &ns);
protected:
};
extern void GenComment(const std::vector<std::string> &dc,
- std::string *code_ptr,
- const CommentConfig *config,
+ std::string *code_ptr, const CommentConfig *config,
const char *prefix = "");
} // namespace flatbuffers
}
template<typename T> FLATBUFFERS_CONSTEXPR size_t AlignOf() {
+ // clang-format off
#ifdef _MSC_VER
return __alignof(T);
#else
return alignof(T);
#endif
#endif
+ // clang-format on
}
// When we read serialized data from memory, in the case of most scalars,
// An STL compatible iterator implementation for Vector below, effectively
// calling Get() for every element.
-template<typename T, typename IT>
-struct VectorIterator {
+template<typename T, typename IT> struct VectorIterator {
typedef std::random_access_iterator_tag iterator_category;
typedef IT value_type;
typedef uoffset_t difference_type;
typedef IT *pointer;
typedef IT &reference;
- VectorIterator(const uint8_t *data, uoffset_t i) :
- data_(data + IndirectHelper<T>::element_stride * i) {}
+ VectorIterator(const uint8_t *data, uoffset_t i)
+ : data_(data + IndirectHelper<T>::element_stride * i) {}
VectorIterator(const VectorIterator &other) : data_(other.data_) {}
VectorIterator &operator=(const VectorIterator &other) {
return (data_ - other.data_) / IndirectHelper<T>::element_stride;
}
- IT operator *() const {
- return IndirectHelper<T>::Read(data_, 0);
- }
+ IT operator*() const { return IndirectHelper<T>::Read(data_, 0); }
- IT operator->() const {
- return IndirectHelper<T>::Read(data_, 0);
- }
+ IT operator->() const { return IndirectHelper<T>::Read(data_, 0); }
VectorIterator &operator++() {
data_ += IndirectHelper<T>::element_stride;
}
VectorIterator operator+(const uoffset_t &offset) const {
- return VectorIterator(data_ + offset * IndirectHelper<T>::element_stride, 0);
+ return VectorIterator(data_ + offset * IndirectHelper<T>::element_stride,
+ 0);
}
- VectorIterator& operator+=(const uoffset_t &offset) {
+ VectorIterator &operator+=(const uoffset_t &offset) {
data_ += offset * IndirectHelper<T>::element_stride;
return *this;
}
}
VectorIterator operator-(const uoffset_t &offset) {
- return VectorIterator(data_ - offset * IndirectHelper<T>::element_stride, 0);
+ return VectorIterator(data_ - offset * IndirectHelper<T>::element_stride,
+ 0);
}
- VectorIterator& operator-=(const uoffset_t &offset) {
+ VectorIterator &operator-=(const uoffset_t &offset) {
data_ -= offset * IndirectHelper<T>::element_stride;
return *this;
}
-private:
+ private:
const uint8_t *data_;
};
// This is used as a helper type for accessing vectors.
// Vector::data() assumes the vector elements start after the length field.
template<typename T> class Vector {
-public:
+ public:
typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type>
- iterator;
+ iterator;
typedef VectorIterator<T, typename IndirectHelper<T>::return_type>
- const_iterator;
+ const_iterator;
uoffset_t size() const { return EndianScalar(length_); }
// Change elements if you have a non-const pointer to this object.
// Scalars only. See reflection.h, and the documentation.
- void Mutate(uoffset_t i, const T& val) {
+ void Mutate(uoffset_t i, const T &val) {
assert(i < size());
WriteScalar(data() + i, val);
}
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()); }
template<typename K> return_type LookupByKey(K key) const {
- void *search_result = std::bsearch(&key, Data(), size(),
- IndirectHelper<T>::element_stride, KeyCompare<K>);
+ void *search_result = std::bsearch(
+ &key, Data(), size(), IndirectHelper<T>::element_stride, KeyCompare<K>);
if (!search_result) {
return nullptr; // Key not found.
return IndirectHelper<T>::Read(element, 0);
}
-protected:
+ protected:
// This class is only used to access pre-existing data. Don't ever
// try to construct these manually.
Vector();
uoffset_t length_;
-private:
+ private:
// This class is a pointer. Copying will therefore create an invalid object.
// Private and unimplemented copy constructor.
- Vector(const Vector&);
+ Vector(const Vector &);
template<typename K> static int KeyCompare(const void *ap, const void *bp) {
const K *key = reinterpret_cast<const K *>(ap);
// Represent a vector much like the template above, but in this case we
// don't know what the element types are (used with reflection.h).
class VectorOfAny {
-public:
+ public:
uoffset_t size() const { return EndianScalar(length_); }
const uint8_t *Data() const {
return reinterpret_cast<const uint8_t *>(&length_ + 1);
}
- uint8_t *Data() {
- return reinterpret_cast<uint8_t *>(&length_ + 1);
- }
-protected:
+ uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); }
+
+ protected:
VectorOfAny();
uoffset_t length_;
-private:
- VectorOfAny(const VectorOfAny&);
+ private:
+ VectorOfAny(const VectorOfAny &);
};
#ifndef FLATBUFFERS_CPP98_STL
const char *c_str() const { return reinterpret_cast<const char *>(Data()); }
std::string str() const { return std::string(c_str(), Length()); }
- bool operator <(const String &o) const {
+ bool operator<(const String &o) const {
return strcmp(c_str(), o.c_str()) < 0;
}
};
// the DetachedBuffer can manage the memory lifetime.
class DetachedBuffer {
public:
- DetachedBuffer() : allocator_(nullptr), own_allocator_(false), buf_(nullptr),
- reserved_(0), cur_(nullptr), size_(0) {}
+ DetachedBuffer()
+ : allocator_(nullptr),
+ own_allocator_(false),
+ buf_(nullptr),
+ reserved_(0),
+ cur_(nullptr),
+ size_(0) {}
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),
- reserved_(reserved), cur_(cur), size_(sz) {
+ : allocator_(allocator),
+ own_allocator_(own_allocator),
+ buf_(buf),
+ reserved_(reserved),
+ cur_(cur),
+ size_(sz) {
assert(allocator_);
}
DetachedBuffer(DetachedBuffer &&other)
- : allocator_(other.allocator_), own_allocator_(other.own_allocator_),
- buf_(other.buf_), reserved_(other.reserved_), cur_(other.cur_),
- size_(other.size_) {
+ : allocator_(other.allocator_),
+ own_allocator_(other.own_allocator_),
+ buf_(other.buf_),
+ reserved_(other.reserved_),
+ cur_(other.cur_),
+ size_(other.size_) {
other.reset();
}
return *this;
}
- ~DetachedBuffer() {
- destroy();
- }
+ ~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_;
- }
+ size_t size() const { return size_; }
-#if 0 // disabled for now due to the ordering of classes in this header
+ // clang-format off
+ #if 0 // disabled for now due to the ordering of classes in this header
template <class T>
bool Verify() const {
Verifier verifier(data(), size());
T* GetRoot() {
return flatbuffers::GetRoot<T>(data());
}
-#endif
+ #endif
+ // clang-format on
// These may change access mode, leave these at end of public section
FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer &other))
assert(allocator_);
allocator_->deallocate(buf_, reserved_);
}
- if (own_allocator_ && allocator_) {
- delete allocator_;
- }
+ if (own_allocator_ && allocator_) { delete allocator_; }
reset();
}
explicit vector_downward(size_t initial_size = 1024,
Allocator *allocator = nullptr,
bool own_allocator = false)
- : allocator_(allocator ? allocator : &DefaultAllocator::instance()),
- own_allocator_(own_allocator), initial_size_(initial_size), reserved_(0),
- buf_(nullptr), cur_(nullptr) {
+ : allocator_(allocator ? allocator : &DefaultAllocator::instance()),
+ own_allocator_(own_allocator),
+ initial_size_(initial_size),
+ reserved_(0),
+ buf_(nullptr),
+ cur_(nullptr) {
assert(allocator_);
}
assert(allocator_);
allocator_->deallocate(buf_, reserved_);
}
- if (own_allocator_ && allocator_) {
- delete allocator_;
- }
+ if (own_allocator_ && allocator_) { delete allocator_; }
}
void reset() {
uint8_t *make_space(size_t len) {
assert(cur_ >= buf_);
- if (len > static_cast<size_t>(cur_ - buf_)) {
- reallocate(len);
- }
+ if (len > static_cast<size_t>(cur_ - buf_)) { reallocate(len); }
cur_ -= len;
// Beyond this, signed offsets may not have enough range:
// (FlatBuffers > 2GB not supported).
return static_cast<uoffset_t>(reserved_ - (cur_ - buf_));
}
- size_t capacity() const {
- return reserved_;
- }
+ size_t capacity() const { return reserved_; }
uint8_t *buf() const {
assert(buf_);
}
// 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) {
auto dest = make_space(sizeof(T));
*reinterpret_cast<T *>(dest) = little_endian_t;
}
return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
}
-template <typename T, typename Alloc> const T* data(const std::vector<T, Alloc> &v) {
+template<typename T, typename Alloc>
+const T *data(const std::vector<T, Alloc> &v) {
return v.empty() ? nullptr : &v.front();
}
-template <typename T, typename Alloc> T* data(std::vector<T, Alloc> &v) {
+template<typename T, typename Alloc> T *data(std::vector<T, Alloc> &v) {
return v.empty() ? nullptr : &v.front();
}
/// `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.
-class FlatBufferBuilder
-{
+class FlatBufferBuilder {
public:
/// @brief Default constructor for FlatBufferBuilder.
/// @param[in] initial_size The initial size of the buffer, in bytes. Defaults
explicit FlatBufferBuilder(size_t initial_size = 1024,
Allocator *allocator = nullptr,
bool own_allocator = false)
- : buf_(initial_size, allocator, own_allocator), max_voffset_(0),
- nested(false), finished(false), minalign_(1), force_defaults_(false),
- dedup_vtables_(true), string_pool(nullptr) {
+ : buf_(initial_size, allocator, own_allocator),
+ max_voffset_(0),
+ nested(false),
+ finished(false),
+ minalign_(1),
+ force_defaults_(false),
+ dedup_vtables_(true),
+ string_pool(nullptr) {
offsetbuf_.reserve(16); // Avoid first few reallocs.
vtables_.reserve(16);
EndianCheck();
}
void Reset() {
- Clear(); // clear builder state
+ Clear(); // clear builder state
buf_.reset(); // deallocate buffer
}
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); }
// by the offsets themselves. In reverse:
// Include space for the last offset and ensure empty tables have a
// minimum size.
- max_voffset_ = (std::max)(static_cast<voffset_t>(max_voffset_ +
- sizeof(voffset_t)),
- FieldIndexToOffset(0));
+ max_voffset_ =
+ (std::max)(static_cast<voffset_t>(max_voffset_ + sizeof(voffset_t)),
+ FieldIndexToOffset(0));
buf_.fill_big(max_voffset_);
auto table_object_size = vtableoffsetloc - start;
assert(table_object_size < 0x10000); // Vtable use 16bit offsets.
WriteScalar<voffset_t>(buf_.data(), max_voffset_);
// Write the offsets into the table
for (auto field_location = offsetbuf_.begin();
- field_location != offsetbuf_.end();
- ++field_location) {
+ field_location != offsetbuf_.end(); ++field_location) {
auto pos = static_cast<voffset_t>(vtableoffsetloc - field_location->off);
// If this asserts, it means you've set a field twice.
assert(!ReadScalar<voffset_t>(buf_.data() + field_location->id));
}
}
// If this is a new vtable, remember it.
- if (vt_use == GetSize()) {
- vtables_.push_back(vt_use);
- }
+ if (vt_use == GetSize()) { vtables_.push_back(vt_use); }
// Fill the vtable offset we created above.
// The offset points from the beginning of the object to where the
// vtable is stored.
// flexibility (storing all vtables at the start of the file).
WriteScalar(buf_.data_at(vtableoffsetloc),
static_cast<soffset_t>(vt_use) -
- static_cast<soffset_t>(vtableoffsetloc));
+ static_cast<soffset_t>(vtableoffsetloc));
nested = false;
return vtableoffsetloc;
/// @param[in] str A const reference to a std::string like type with support
/// of T::c_str() and T::length() to store in the buffer.
/// @return Returns the offset in the buffer where the string starts.
- template<typename T>
- Offset<String> CreateString(const T &str) {
+ template<typename T> Offset<String> CreateString(const T &str) {
return CreateString(str.c_str(), str.length());
}
// causing the wrong overload to be selected, remove it.
AssertScalarT<T>();
StartVector(len, sizeof(T));
+ // clang-format off
#if FLATBUFFERS_LITTLEENDIAN
PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T));
#else
}
}
#endif
+ // clang-format on
return Offset<Vector<T>>(EndVector(len));
}
- 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(len, sizeof(Offset<T>));
- 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));
}
// Background: https://isocpp.org/blog/2012/11/on-vectorbool
Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) {
StartVector(v.size(), sizeof(uint8_t));
- for (auto i = v.size(); i > 0; ) {
+ for (auto i = v.size(); i > 0;) {
PushElement(static_cast<uint8_t>(v[--i]));
}
return Offset<Vector<uint8_t>>(EndVector(v.size()));
}
+ // clang-format off
#ifndef FLATBUFFERS_CPP98_STL
/// @brief Serialize values returned by a function into a FlatBuffer `vector`.
/// This is a convenience function that takes care of iteration for you.
return CreateVector(elems);
}
#endif
+ // clang-format on
/// @brief Serialize values returned by a function into a FlatBuffer `vector`.
/// This is a convenience function that takes care of iteration for you.
/// @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) {
std::vector<T> elems(vector_size);
for (size_t i = 0; i < vector_size; i++) elems[i] = f(i, state);
return CreateVector(elems);
/// @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 *>> CreateVectorOfStructs(
- const T *v, size_t len) {
+ template<typename T>
+ Offset<Vector<const T *>> CreateVectorOfStructs(const T *v, size_t len) {
StartVector(len * sizeof(T) / AlignOf<T>(), AlignOf<T>());
PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
return Offset<Vector<const T *>>(EndVector(len));
/// @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&);
- typedef T (*Pack_t)(const S&);
+ template<typename T, typename S>
+ Offset<Vector<const T *>> CreateVectorOfNativeStructs(const S *v,
+ size_t len) {
+ extern T Pack(const S &);
+ typedef T (*Pack_t)(const S &);
std::vector<T> vv(len);
- std::transform(v, v+len, vv.begin(), *(Pack_t)&Pack);
+ std::transform(v, v + len, vv.begin(), *(Pack_t)&Pack);
return CreateVectorOfStructs<T>(vv.data(), vv.size());
}
+ // clang-format off
#ifndef FLATBUFFERS_CPP98_STL
/// @brief Serialize an array of structs into a FlatBuffer `vector`.
/// @tparam T The data type of the struct array elements.
return EndVectorOfStructs<T>(vector_size);
}
#endif
+ // clang-format on
/// @brief Serialize an array of structs into a FlatBuffer `vector`.
/// @tparam T The data type of the struct array elements.
/// 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++;
/// 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> Offset<Vector<const T *>> CreateVectorOfStructs(
+ template<typename T, typename Alloc>
+ Offset<Vector<const T *>> CreateVectorOfStructs(
const std::vector<T, Alloc> &v) {
return CreateVectorOfStructs(data(v), v.size());
}
- /// @brief Serialize a `std::vector` of native structs into a FlatBuffer `vector`.
+ /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
+ /// `vector`.
/// @tparam T The data type of the `std::vector` struct elements.
/// @tparam S The data type of the `std::vector` native struct elements.
/// @param[in]] v A const reference to the `std::vector` of structs to
/// 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> Offset<Vector<const T *>> CreateVectorOfNativeStructs(
+ template<typename T, typename S>
+ Offset<Vector<const T *>> CreateVectorOfNativeStructs(
const std::vector<S> &v) {
return CreateVectorOfNativeStructs<T, S>(data(v), v.size());
}
-
/// @cond FLATBUFFERS_INTERNAL
- template<typename T>
- struct StructKeyComparator {
+ template<typename T> struct StructKeyComparator {
bool operator()(const T &a, const T &b) const {
return a.KeyCompareLessThan(&b);
}
- private:
- StructKeyComparator& operator= (const StructKeyComparator&);
+ private:
+ StructKeyComparator &operator=(const StructKeyComparator &);
};
/// @endcond
/// 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> Offset<Vector<const T *>> CreateVectorOfSortedStructs(
- std::vector<T> *v) {
+ template<typename T>
+ Offset<Vector<const T *>> CreateVectorOfSortedStructs(std::vector<T> *v) {
return CreateVectorOfSortedStructs(data(*v), v->size());
}
- /// @brief Serialize a `std::vector` of native structs into a FlatBuffer `vector`
- /// in sorted order.
+ /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
+ /// `vector` in sorted order.
/// @tparam T The data type of the `std::vector` struct elements.
/// @tparam S The data type of the `std::vector` native struct elements.
/// @param[in]] v A const reference to the `std::vector` of structs to
/// 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> Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(
+ template<typename T, typename S>
+ Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(
std::vector<S> *v) {
return CreateVectorOfSortedNativeStructs<T, S>(data(*v), v->size());
}
/// @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::sort(v, v + len, StructKeyComparator<T>());
return CreateVectorOfStructs(v, len);
}
- /// @brief Serialize an array of native structs into a FlatBuffer `vector` in sorted
- /// order.
+ /// @brief Serialize an array of native structs into a FlatBuffer `vector` in
+ /// sorted order.
/// @tparam T The data type of the struct array elements.
/// @tparam S The data type of the native struct array elements.
/// @param[in] v A pointer to the array of type `S` to serialize into the
/// @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&);
- typedef T (*Pack_t)(const S&);
+ template<typename T, typename S>
+ Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(S *v,
+ size_t len) {
+ extern T Pack(const S &);
+ typedef T (*Pack_t)(const S &);
std::vector<T> vv(len);
- std::transform(v, v+len, vv.begin(), *(Pack_t)&Pack);
+ std::transform(v, v + len, vv.begin(), *(Pack_t)&Pack);
return CreateVectorOfSortedStructs<T>(vv, len);
}
/// @cond FLATBUFFERS_INTERNAL
- template<typename T>
- struct TableKeyComparator {
- TableKeyComparator(vector_downward& buf) : buf_(buf) {}
+ template<typename T> struct TableKeyComparator {
+ TableKeyComparator(vector_downward &buf) : buf_(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& buf_;
+ vector_downward &buf_;
- private:
- TableKeyComparator& operator= (const TableKeyComparator&);
+ private:
+ TableKeyComparator &operator=(const TableKeyComparator &);
};
/// @endcond
/// @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, size_t len) {
+ template<typename T>
+ Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(Offset<T> *v,
+ size_t len) {
std::sort(v, v + len, TableKeyComparator<T>(buf_));
return CreateVector(v, len);
}
/// 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> Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
+ template<typename T>
+ Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
std::vector<Offset<T>> *v) {
return CreateVectorOfSortedTables(data(*v), v->size());
}
/// @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) {
return CreateUninitializedVector(len, sizeof(T),
reinterpret_cast<uint8_t **>(buf));
}
/// @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);
}
/// 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> void FinishSizePrefixed(Offset<T> root,
- const char *file_identifier = nullptr) {
+ template<typename T>
+ void FinishSizePrefixed(Offset<T> root,
+ const char *file_identifier = nullptr) {
Finish(root.o, file_identifier, true);
}
void Finish(uoffset_t root, const char *file_identifier, bool size_prefix) {
NotNested();
// This will cause the whole buffer to be aligned.
- PreAlign((size_prefix ? sizeof(uoffset_t) : 0) +
- sizeof(uoffset_t) +
- (file_identifier ? kFileIdentifierLength : 0),
+ PreAlign((size_prefix ? sizeof(uoffset_t) : 0) + sizeof(uoffset_t) +
+ (file_identifier ? kFileIdentifierLength : 0),
minalign_);
if (file_identifier) {
assert(strlen(file_identifier) == kFileIdentifierLength);
kFileIdentifierLength);
}
PushElement(ReferTo(root)); // Location of root.
- if (size_prefix) {
- PushElement(GetSize());
- }
+ if (size_prefix) { PushElement(GetSize()); }
finished = true;
}
struct StringOffsetCompare {
StringOffsetCompare(const vector_downward &buf) : buf_(&buf) {}
- bool operator() (const Offset<String> &a, const Offset<String> &b) const {
+ bool operator()(const Offset<String> &a, const Offset<String> &b) const {
auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o));
auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o));
return strncmp(stra->c_str(), strb->c_str(),
private:
// Allocates space for a vector of structures.
// Must be completed with EndVectorOfStructs().
- template<typename T> T* StartVectorOfStructs(size_t vector_size) {
+ template<typename T> T *StartVectorOfStructs(size_t vector_size) {
StartVector(vector_size * sizeof(T) / AlignOf<T>(), AlignOf<T>());
return reinterpret_cast<T *>(buf_.make_space(vector_size * sizeof(T)));
}
// End the vector of structues in the flatbuffers.
// Vector should have previously be started with StartVectorOfStructs().
- template<typename T> Offset<Vector<const T *>> EndVectorOfStructs(
- size_t vector_size) {
+ template<typename T>
+ Offset<Vector<const T *>> EndVectorOfStructs(size_t vector_size) {
return Offset<Vector<const T *>>(EndVector(vector_size));
}
};
// Helpers to get a typed pointer to the root object contained in the buffer.
template<typename T> T *GetMutableRoot(void *buf) {
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> const T *GetRoot(const void *buf) {
/// 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(FlatBufferBuilder &fbb,
- Offset<T> offset) {
+template<typename T>
+const T *GetTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
return GetMutableTemporaryPointer<T>(fbb, offset);
}
-
/// @brief Get a pointer to the the file_identifier section of the buffer.
/// @return Returns a const char pointer to the start of the file_identifier
/// characters in the buffer. The returned char * has length
// Helper to see if the identifier in a buffer has the expected value.
inline bool BufferHasIdentifier(const void *buf, const char *identifier) {
- return strncmp(GetBufferIdentifier(buf),
- identifier, FlatBufferBuilder::kFileIdentifierLength) == 0;
+ return strncmp(GetBufferIdentifier(buf), identifier,
+ FlatBufferBuilder::kFileIdentifierLength) == 0;
}
// Helper class to verify the integrity of a FlatBuffer
public:
Verifier(const uint8_t *buf, size_t buf_len, uoffset_t _max_depth = 64,
uoffset_t _max_tables = 1000000)
- : buf_(buf), end_(buf + buf_len), depth_(0), max_depth_(_max_depth),
- num_tables_(0), max_tables_(_max_tables)
+ : buf_(buf),
+ end_(buf + buf_len),
+ depth_(0),
+ max_depth_(_max_depth),
+ num_tables_(0),
+ max_tables_(_max_tables)
+ // clang-format off
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
, upper_bound_(buf)
#endif
- {}
+ // clang-format on
+ {
+ }
// Central location where any verification failures register.
bool Check(bool ok) const {
+ // clang-format off
#ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
assert(ok);
#endif
if (!ok)
upper_bound_ = buf_;
#endif
+ // clang-format on
return ok;
}
// Verify any range within the buffer.
bool Verify(const void *elem, size_t elem_len) const {
+ // clang-format off
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
auto upper_bound = reinterpret_cast<const uint8_t *>(elem) + elem_len;
if (upper_bound_ < upper_bound)
upper_bound_ = upper_bound;
#endif
- return Check(elem_len <= (size_t) (end_ - buf_) &&
- elem >= buf_ &&
+ // clang-format on
+ return Check(elem_len <= (size_t)(end_ - buf_) && elem >= buf_ &&
elem <= end_ - elem_len);
}
// Verify a pointer (may be NULL) of any vector type.
template<typename T> bool Verify(const Vector<T> *vec) const {
const uint8_t *end;
- return !vec ||
- VerifyVector(reinterpret_cast<const uint8_t *>(vec), sizeof(T),
- &end);
+ return !vec || VerifyVector(reinterpret_cast<const uint8_t *>(vec),
+ sizeof(T), &end);
}
// Verify a pointer (may be NULL) of a vector to struct.
// Special case for string contents, after the above has been called.
bool VerifyVectorOfStrings(const Vector<Offset<String>> *vec) const {
- if (vec) {
- for (uoffset_t i = 0; i < vec->size(); i++) {
- if (!Verify(vec->Get(i))) return false;
- }
+ if (vec) {
+ for (uoffset_t i = 0; i < vec->size(); i++) {
+ if (!Verify(vec->Get(i))) return false;
}
- return true;
+ }
+ return true;
}
// Special case for table contents, after the above has been called.
return true;
}
- template<typename T> bool VerifyBufferFromStart(const char *identifier,
- const uint8_t *start) {
+ template<typename T>
+ bool VerifyBufferFromStart(const char *identifier, const uint8_t *start) {
if (identifier &&
(size_t(end_ - start) < 2 * sizeof(flatbuffers::uoffset_t) ||
!BufferHasIdentifier(start, identifier))) {
// Call T::Verify, which must be in the generated code for this type.
auto o = VerifyOffset(start);
- return o &&
- reinterpret_cast<const T *>(start + o)->
- Verify(*this)
- #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
- && GetComputedSize()
- #endif
- ;
+ return o && reinterpret_cast<const T *>(start + o)->Verify(*this)
+#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
+ && GetComputedSize()
+#endif
+ ;
}
// 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 *identifier) {
return VerifyBufferFromStart<T>(identifier, buf_);
return true;
}
+ // clang-format off
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
// Returns the message size in bytes
size_t GetComputedSize() const {
return (buf_ + size > end_) ? 0 : size;
}
#endif
+ // clang-format on
private:
const uint8_t *buf_;
uoffset_t max_depth_;
uoffset_t num_tables_;
uoffset_t max_tables_;
-#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
- mutable const uint8_t *upper_bound_;
-#endif
+ // clang-format off
+ #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
+ mutable const uint8_t *upper_bound_;
+ #endif
+ // clang-format on
};
// Convenient way to bundle a buffer and its length, to pass it around
template<typename T> struct BufferRef : BufferRefBase {
BufferRef() : buf(nullptr), len(0), must_free(false) {}
BufferRef(uint8_t *_buf, uoffset_t _len)
- : buf(_buf), len(_len), must_free(false) {}
+ : buf(_buf), len(_len), must_free(false) {}
- ~BufferRef() { if (must_free) free(buf); }
+ ~BufferRef() {
+ if (must_free) free(buf);
+ }
const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); }
template<typename P> P GetPointer(voffset_t field) {
auto field_offset = GetOptionalFieldOffset(field);
auto p = data_ + field_offset;
- return field_offset
- ? reinterpret_cast<P>(p + ReadScalar<uoffset_t>(p))
- : nullptr;
+ return field_offset ? reinterpret_cast<P>(p + ReadScalar<uoffset_t>(p))
+ : nullptr;
}
template<typename P> P GetPointer(voffset_t field) const {
return const_cast<Table *>(this)->GetPointer<P>(field);
if (!verifier.Verify<soffset_t>(data_)) return false;
auto vtable = GetVTable();
// Check the vtable size field, then check vtable fits in its entirety.
- return verifier.VerifyComplexity() &&
- verifier.Verify<voffset_t>(vtable) &&
+ return verifier.VerifyComplexity() && verifier.Verify<voffset_t>(vtable) &&
(ReadScalar<voffset_t>(vtable) & (sizeof(voffset_t) - 1)) == 0 &&
verifier.Verify(vtable, ReadScalar<voffset_t>(vtable));
}
// Verify a particular field.
- template<typename T> bool VerifyField(const Verifier &verifier,
- voffset_t field) const {
+ template<typename T>
+ bool VerifyField(const Verifier &verifier, voffset_t field) const {
// Calling GetOptionalFieldOffset should be safe now thanks to
// VerifyTable().
auto field_offset = GetOptionalFieldOffset(field);
}
// VerifyField for required fields.
- template<typename T> bool VerifyFieldRequired(const Verifier &verifier,
- voffset_t field) const {
+ template<typename T>
+ bool VerifyFieldRequired(const Verifier &verifier, voffset_t field) const {
auto field_offset = GetOptionalFieldOffset(field);
return verifier.Check(field_offset != 0) &&
verifier.Verify<T>(data_ + field_offset);
// Either the vtable is before the root or after the 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").
static_assert(FlatBufferBuilder::kFileIdentifierLength == sizeof(uoffset_t),
"file_identifier is assumed to be the same size as uoffset_t");
for (auto possible_roots = FLATBUFFERS_MAX_ALIGNMENT / sizeof(uoffset_t) + 1;
- possible_roots;
- possible_roots--) {
- start -= sizeof(uoffset_t);
- if (ReadScalar<uoffset_t>(start) + start ==
- reinterpret_cast<const uint8_t *>(root)) return start;
+ possible_roots; possible_roots--) {
+ start -= sizeof(uoffset_t);
+ if (ReadScalar<uoffset_t>(start) + start ==
+ reinterpret_cast<const uint8_t *>(root))
+ return start;
}
// We didn't find the root, either the "root" passed isn't really a root,
// or the buffer is corrupt.
// Base class for native objects (FlatBuffer data de-serialized into native
// C++ data structures).
// Contains no functionality, purely documentative.
-struct NativeTable {
-};
+struct NativeTable {};
/// @brief Function types to be used with resolving hashes into objects and
/// back again. The resolver gets a pointer to a field inside an object API
/// if you wish. The resolver does the opposite lookup, for when the object
/// is being serialized again.
typedef uint64_t hash_value_t;
+// clang-format off
#ifdef FLATBUFFERS_CPP98_STL
typedef void (*resolver_function_t)(void **pointer_adr, hash_value_t hash);
typedef hash_value_t (*rehasher_function_t)(void *pointer);
resolver_function_t;
typedef std::function<hash_value_t (void *pointer)> rehasher_function_t;
#endif
+// clang-format on
// Helper function to test if a field is present, using any of the field
// enums in the generated code.
// names must be NULL terminated.
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);
+ if (!strcmp(*p, name)) return static_cast<int>(p - names);
return -1;
}
// by the force_align attribute.
// These are used in the generated code only.
+// clang-format off
#if defined(_MSC_VER)
#define MANUALLY_ALIGNED_STRUCT(alignment) \
__pragma(pack(1)); \
#else
#error Unknown compiler, please define structure alignment macros
#endif
+// clang-format on
// Minimal reflection via code generation.
// Besides full-fat reflection (see reflection.h) and parsing/printing by
enum SequenceType { ST_TABLE, ST_STRUCT, ST_UNION, ST_ENUM };
// Scalars have the same order as in idl.h
+// clang-format off
#define FLATBUFFERS_GEN_ELEMENTARY_TYPES(ET) \
ET(ET_UTYPE) \
ET(ET_BOOL) \
};
return names;
}
+// clang-format on
// Basic type info cost just 16bits per field!
struct TypeCode {
- uint16_t base_type : 4; // ElementaryType
+ uint16_t base_type : 4; // ElementaryType
uint16_t is_vector : 1;
- int16_t sequence_ref : 11; // Index into type_refs below, or -1 for none.
+ int16_t sequence_ref : 11; // Index into type_refs below, or -1 for none.
};
static_assert(sizeof(TypeCode) == 2, "TypeCode");
const TypeCode *type_codes;
const TypeFunction *type_refs;
const int32_t *values; // Only set for non-consecutive enum/union or structs.
- const char **names; // Only set if compiled with --reflect-names.
+ const char **names; // Only set if compiled with --reflect-names.
};
// String which identifies the current version of FlatBuffers.
// appreciate if you left it in.
// Weak linkage is culled by VS & doesn't work on cygwin.
+// clang-format off
#if !defined(_WIN32) && !defined(__CYGWIN__)
extern volatile __attribute__((weak)) const char *flatbuffer_version_string;
} // namespace flatbuffers
#if defined(_MSC_VER)
-#pragma warning(pop)
+ #pragma warning(pop)
#endif
+// clang-format on
#endif // FLATBUFFERS_H_
* limitations under the License.
*/
-#include "flatbuffers/flatbuffers.h"
-#include "flatbuffers/idl.h"
-#include "flatbuffers/util.h"
#include <functional>
#include <limits>
#include <string>
+#include "flatbuffers/flatbuffers.h"
+#include "flatbuffers/idl.h"
+#include "flatbuffers/util.h"
#ifndef FLATC_H_
-#define FLATC_H_
+# define FLATC_H_
namespace flatbuffers {
MakeRuleFn make_rule;
};
- 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.
warn_fn(nullptr),
error_fn(nullptr) {}
- const Generator* generators;
+ const Generator *generators;
size_t num_generators;
WarnFn warn_fn;
ErrorFn error_fn;
};
- explicit FlatCompiler(const InitParams& params) : params_(params) {}
+ explicit FlatCompiler(const InitParams ¶ms) : params_(params) {}
- int Compile(int argc, const char** argv);
+ int Compile(int argc, const char **argv);
- std::string GetUsageString(const char* program_name) const;
+ std::string GetUsageString(const char *program_name) const;
private:
- void ParseFile(flatbuffers::Parser &parser,
- const std::string &filename,
+ void ParseFile(flatbuffers::Parser &parser, const std::string &filename,
const std::string &contents,
std::vector<const char *> &include_directories) const;
InitParams params_;
};
-
} // namespace flatbuffers
#endif // FLATC_H_
#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 {
TYPE_INDIRECT_UINT = 7,
TYPE_INDIRECT_FLOAT = 8,
TYPE_MAP = 9,
- TYPE_VECTOR = 10, // Untyped.
- TYPE_VECTOR_INT = 11, // Typed any size (stores no type table).
+ TYPE_VECTOR = 10, // Untyped.
+ TYPE_VECTOR_INT = 11, // Typed any size (stores no type table).
TYPE_VECTOR_UINT = 12,
TYPE_VECTOR_FLOAT = 13,
TYPE_VECTOR_KEY = 14,
TYPE_VECTOR_STRING = 15,
- TYPE_VECTOR_INT2 = 16, // Typed tuple (no type table, no size field).
+ TYPE_VECTOR_INT2 = 16, // Typed tuple (no type table, no size field).
TYPE_VECTOR_UINT2 = 17,
TYPE_VECTOR_FLOAT2 = 18,
- TYPE_VECTOR_INT3 = 19, // Typed triple (no type table, no size field).
+ TYPE_VECTOR_INT3 = 19, // Typed triple (no type table, no size field).
TYPE_VECTOR_UINT3 = 20,
TYPE_VECTOR_FLOAT3 = 21,
- TYPE_VECTOR_INT4 = 22, // Typed quad (no type table, no size field).
+ TYPE_VECTOR_INT4 = 22, // Typed quad (no type table, no size field).
TYPE_VECTOR_UINT4 = 23,
TYPE_VECTOR_FLOAT4 = 24,
TYPE_BLOB = 25,
TYPE_BOOL = 26,
- TYPE_VECTOR_BOOL = 36, // To Allow the same type of conversion of type to vector type
+ TYPE_VECTOR_BOOL =
+ 36, // To Allow the same type of conversion of type to vector type
};
inline bool IsInline(Type t) { return t <= TYPE_FLOAT || t == TYPE_BOOL; }
}
inline bool IsTypedVector(Type t) {
- return (t >= TYPE_VECTOR_INT && t <= TYPE_VECTOR_STRING) || t == TYPE_VECTOR_BOOL;
+ return (t >= TYPE_VECTOR_INT && t <= TYPE_VECTOR_STRING) ||
+ t == TYPE_VECTOR_BOOL;
}
inline bool IsFixedTypedVector(Type t) {
inline Type ToFixedTypedVectorElementType(Type t, uint8_t *len) {
assert(IsFixedTypedVector(t));
auto fixed_type = t - TYPE_VECTOR_INT2;
- *len = static_cast<uint8_t>(fixed_type / 3 + 2); // 3 types each, starting from length 2.
+ *len = static_cast<uint8_t>(fixed_type / 3 +
+ 2); // 3 types each, starting from length 2.
return static_cast<Type>(fixed_type % 3 + TYPE_INT);
}
// 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>
+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))
- : static_cast<R>(flatbuffers::ReadScalar<T2>(data)))
- : (byte_width < 8 ? static_cast<R>(flatbuffers::ReadScalar<T4>(data))
- : static_cast<R>(flatbuffers::ReadScalar<T8>(data)));
+ ? (byte_width < 2
+ ? static_cast<R>(flatbuffers::ReadScalar<T1>(data))
+ : static_cast<R>(flatbuffers::ReadScalar<T2>(data)))
+ : (byte_width < 8
+ ? static_cast<R>(flatbuffers::ReadScalar<T4>(data))
+ : static_cast<R>(flatbuffers::ReadScalar<T8>(data)));
}
-
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);
+ 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) {
// TODO: GCC apparently replaces memcpy by a rep movsb, but only if count is a
// constant, which here it isn't. Test if memcpy is still faster than
// the conditionals in ReadSizedScalar. Can also use inline asm.
+ // clang-format off
#ifdef _MSC_VER
uint64_t u = 0;
__movsb(reinterpret_cast<uint8_t *>(&u),
return ReadSizedScalar<uint64_t, uint8_t, uint16_t, uint32_t, uint64_t>(
data, byte_width);
#endif
+ // clang-format on
}
inline double ReadDouble(const uint8_t *data, uint8_t byte_width) {
return ReadSizedScalar<double, quarter, half, float, double>(data,
- byte_width);
+ byte_width);
}
inline const uint8_t *Indirect(const uint8_t *offset, uint8_t byte_width) {
}
inline BitWidth WidthU(uint64_t u) {
- #define FLATBUFFERS_GET_FIELD_BIT_WIDTH(value, width) { \
+#define FLATBUFFERS_GET_FIELD_BIT_WIDTH(value, width) \
+ { \
if (!((u) & ~((1ULL << (width)) - 1ULL))) return BIT_WIDTH_##width; \
}
FLATBUFFERS_GET_FIELD_BIT_WIDTH(u, 8);
FLATBUFFERS_GET_FIELD_BIT_WIDTH(u, 16);
FLATBUFFERS_GET_FIELD_BIT_WIDTH(u, 32);
- #undef FLATBUFFERS_GET_FIELD_BIT_WIDTH
+#undef FLATBUFFERS_GET_FIELD_BIT_WIDTH
return BIT_WIDTH_64;
}
class Object {
public:
Object(const uint8_t *data, uint8_t byte_width)
- : data_(data), byte_width_(byte_width) {}
+ : data_(data), byte_width_(byte_width) {}
protected:
const uint8_t *data_;
class String : public Sized {
public:
- 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) {}
size_t length() const { return size(); }
const char *c_str() const { return reinterpret_cast<const char *>(data_); }
std::string str() const { return std::string(c_str(), length()); }
static String EmptyString() {
- static const uint8_t empty_string[] = { 0/*len*/, 0/*terminator*/ };
+ static const uint8_t empty_string[] = { 0 /*len*/, 0 /*terminator*/ };
return String(empty_string + 1, 1);
}
bool IsTheEmptyString() const { return data_ == EmptyString().data_; }
class Blob : public Sized {
public:
Blob(const uint8_t *data_buf, uint8_t byte_width)
- : Sized(data_buf, 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_; }
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_; }
class TypedVector : public Sized {
public:
TypedVector(const uint8_t *data, uint8_t byte_width, Type element_type)
- : Sized(data, 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, TYPE_INT);
}
bool IsTheEmptyVector() const {
public:
FixedTypedVector(const uint8_t *data, uint8_t byte_width, Type element_type,
uint8_t len)
- : Object(data, byte_width), type_(element_type), len_(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, TYPE_INT, 0);
}
bool IsTheEmptyFixedTypedVector() const {
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;
auto keys_offset = data_ - byte_width_ * num_prefixed_fields;
return TypedVector(Indirect(keys_offset, byte_width_),
static_cast<uint8_t>(
- ReadUInt64(keys_offset + byte_width_, byte_width_)),
+ ReadUInt64(keys_offset + byte_width_, byte_width_)),
TYPE_KEY);
}
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);
}
- bool IsTheEmptyMap() const {
- return data_ == EmptyMap().data_;
- }
+ bool IsTheEmptyMap() const { return data_ == EmptyMap().data_; }
};
class Reference {
public:
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) {}
+ : 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)
- : data_(data), parent_width_(parent_width) {
+ : data_(data), parent_width_(parent_width) {
byte_width_ = 1U << static_cast<BitWidth>(packed_type & 3);
type_ = static_cast<Type>(packed_type >> 2);
}
bool IsNull() const { return type_ == TYPE_NULL; }
bool IsBool() const { return type_ == TYPE_BOOL; }
- bool IsInt() const { return type_ == TYPE_INT ||
- type_ == TYPE_INDIRECT_INT; }
- bool IsUInt() const { return type_ == TYPE_UINT||
- type_ == TYPE_INDIRECT_UINT;; }
+ bool IsInt() const { return type_ == TYPE_INT || type_ == TYPE_INDIRECT_INT; }
+ bool IsUInt() const {
+ return type_ == TYPE_UINT || type_ == TYPE_INDIRECT_UINT;
+ }
bool IsIntOrUint() const { return IsInt() || IsUInt(); }
- bool IsFloat() const { return type_ == TYPE_FLOAT ||
- type_ == TYPE_INDIRECT_FLOAT; }
+ bool IsFloat() const {
+ return type_ == TYPE_FLOAT || type_ == TYPE_INDIRECT_FLOAT;
+ }
bool IsNumeric() const { return IsIntOrUint() || IsFloat(); }
bool IsString() const { return type_ == TYPE_STRING; }
bool IsKey() const { return type_ == TYPE_KEY; }
bool IsBlob() const { return type_ == TYPE_BLOB; }
bool AsBool() const {
- return (type_ == TYPE_BOOL ? ReadUInt64(data_, parent_width_) : AsUInt64()) != 0;
+ return (type_ == TYPE_BOOL ? ReadUInt64(data_, parent_width_)
+ : AsUInt64()) != 0;
}
// Reads any type as a int64_t. Never fails, does most sensible conversion.
if (type_ == TYPE_INT) {
// A fast path for the common case.
return ReadInt64(data_, parent_width_);
- } else switch (type_) {
- case TYPE_INDIRECT_INT: return ReadInt64(Indirect(), byte_width_);
- case TYPE_UINT: return ReadUInt64(data_, parent_width_);
- case TYPE_INDIRECT_UINT: return ReadUInt64(Indirect(), byte_width_);
- case TYPE_FLOAT: return static_cast<int64_t>(
- ReadDouble(data_, parent_width_));
- case TYPE_INDIRECT_FLOAT: return static_cast<int64_t>(
- ReadDouble(Indirect(), byte_width_));
- case TYPE_NULL: return 0;
- case TYPE_STRING: return flatbuffers::StringToInt(AsString().c_str());
- case TYPE_VECTOR: return static_cast<int64_t>(AsVector().size());
- case TYPE_BOOL: return ReadInt64(data_, parent_width_);
- default:
- // Convert other things to int.
- return 0;
- }
+ } else
+ switch (type_) {
+ case TYPE_INDIRECT_INT: return ReadInt64(Indirect(), byte_width_);
+ case TYPE_UINT: return ReadUInt64(data_, parent_width_);
+ case TYPE_INDIRECT_UINT: return ReadUInt64(Indirect(), byte_width_);
+ case TYPE_FLOAT:
+ return static_cast<int64_t>(ReadDouble(data_, parent_width_));
+ case TYPE_INDIRECT_FLOAT:
+ return static_cast<int64_t>(ReadDouble(Indirect(), byte_width_));
+ case TYPE_NULL: return 0;
+ case TYPE_STRING: return flatbuffers::StringToInt(AsString().c_str());
+ case TYPE_VECTOR: return static_cast<int64_t>(AsVector().size());
+ case TYPE_BOOL: return ReadInt64(data_, parent_width_);
+ default:
+ // Convert other things to int.
+ return 0;
+ }
}
// TODO: could specialize these to not use AsInt64() if that saves
// extension ops in generated code, and use a faster op than ReadInt64.
int32_t AsInt32() const { return static_cast<int32_t>(AsInt64()); }
int16_t AsInt16() const { return static_cast<int16_t>(AsInt64()); }
- int8_t AsInt8() const { return static_cast<int8_t> (AsInt64()); }
+ int8_t AsInt8() const { return static_cast<int8_t>(AsInt64()); }
uint64_t AsUInt64() const {
if (type_ == TYPE_UINT) {
// A fast path for the common case.
return ReadUInt64(data_, parent_width_);
- } else switch (type_) {
- case TYPE_INDIRECT_UINT: return ReadUInt64(Indirect(), byte_width_);
- case TYPE_INT: return ReadInt64(data_, parent_width_);
- case TYPE_INDIRECT_INT: return ReadInt64(Indirect(), byte_width_);
- case TYPE_FLOAT: return static_cast<uint64_t>(
- ReadDouble(data_, parent_width_));
- case TYPE_INDIRECT_FLOAT: return static_cast<uint64_t>(
- ReadDouble(Indirect(), byte_width_));
- case TYPE_NULL: return 0;
- case TYPE_STRING: return flatbuffers::StringToUInt(AsString().c_str());
- case TYPE_VECTOR: return static_cast<uint64_t>(AsVector().size());
- case TYPE_BOOL: return ReadUInt64(data_, parent_width_);
- default:
- // Convert other things to uint.
- return 0;
- }
+ } else
+ switch (type_) {
+ case TYPE_INDIRECT_UINT: return ReadUInt64(Indirect(), byte_width_);
+ case TYPE_INT: return ReadInt64(data_, parent_width_);
+ case TYPE_INDIRECT_INT: return ReadInt64(Indirect(), byte_width_);
+ case TYPE_FLOAT:
+ return static_cast<uint64_t>(ReadDouble(data_, parent_width_));
+ case TYPE_INDIRECT_FLOAT:
+ return static_cast<uint64_t>(ReadDouble(Indirect(), byte_width_));
+ case TYPE_NULL: return 0;
+ case TYPE_STRING: return flatbuffers::StringToUInt(AsString().c_str());
+ case TYPE_VECTOR: return static_cast<uint64_t>(AsVector().size());
+ case TYPE_BOOL: return ReadUInt64(data_, parent_width_);
+ default:
+ // Convert other things to uint.
+ return 0;
+ }
}
uint32_t AsUInt32() const { return static_cast<uint32_t>(AsUInt64()); }
uint16_t AsUInt16() const { return static_cast<uint16_t>(AsUInt64()); }
- uint8_t AsUInt8() const { return static_cast<uint8_t> (AsUInt64()); }
+ uint8_t AsUInt8() const { return static_cast<uint8_t>(AsUInt64()); }
double AsDouble() const {
if (type_ == TYPE_FLOAT) {
// A fast path for the common case.
return ReadDouble(data_, parent_width_);
- } else switch (type_) {
- case TYPE_INDIRECT_FLOAT: return ReadDouble(Indirect(), byte_width_);
- case TYPE_INT: return static_cast<double>(
- ReadInt64(data_, parent_width_));
- case TYPE_UINT: return static_cast<double>(
- ReadUInt64(data_, parent_width_));
- case TYPE_INDIRECT_INT: return static_cast<double>(
- ReadInt64(Indirect(), byte_width_));
- case TYPE_INDIRECT_UINT: return static_cast<double>(
- ReadUInt64(Indirect(), byte_width_));
- case TYPE_NULL: return 0.0;
- case TYPE_STRING: return strtod(AsString().c_str(), nullptr);
- case TYPE_VECTOR: return static_cast<double>(AsVector().size());
- case TYPE_BOOL: return static_cast<double>(
- ReadUInt64(data_, parent_width_));
- default:
- // Convert strings and other things to float.
- return 0;
- }
+ } else
+ switch (type_) {
+ case TYPE_INDIRECT_FLOAT: return ReadDouble(Indirect(), byte_width_);
+ case TYPE_INT:
+ return static_cast<double>(ReadInt64(data_, parent_width_));
+ case TYPE_UINT:
+ return static_cast<double>(ReadUInt64(data_, parent_width_));
+ case TYPE_INDIRECT_INT:
+ return static_cast<double>(ReadInt64(Indirect(), byte_width_));
+ case TYPE_INDIRECT_UINT:
+ return static_cast<double>(ReadUInt64(Indirect(), byte_width_));
+ case TYPE_NULL: return 0.0;
+ case TYPE_STRING: return strtod(AsString().c_str(), nullptr);
+ case TYPE_VECTOR: return static_cast<double>(AsVector().size());
+ case TYPE_BOOL:
+ return static_cast<double>(ReadUInt64(data_, parent_width_));
+ default:
+ // Convert strings and other things to float.
+ return 0;
+ }
}
float AsFloat() const { return static_cast<float>(AsDouble()); }
memcpy(const_cast<char *>(s.c_str()), str, len);
return true;
}
- bool MutateString(const char *str) {
- return MutateString(str, strlen(str));
- }
+ bool MutateString(const char *str) { return MutateString(str, strlen(str)); }
bool MutateString(const std::string &str) {
return MutateString(str.data(), str.length());
}
return flexbuffers::Indirect(data_, parent_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;
+ 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);
return fits;
}
- template<typename T> bool MutateF(const uint8_t *dest, T t, size_t byte_width,
- BitWidth value_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);
if (byte_width == sizeof(float))
template<> inline float Reference::As<float>() { return AsFloat(); }
template<> inline String Reference::As<String>() { return AsString(); }
-template<> inline std::string Reference::As<std::string>() { return AsString().str(); }
+template<> inline std::string Reference::As<std::string>() {
+ return AsString().str();
+}
template<> inline Blob Reference::As<Blob>() { return AsBlob(); }
template<> inline Vector Reference::As<Vector>() { return AsVector(); }
-template<> inline TypedVector Reference::As<TypedVector>() { return AsTypedVector(); }
-template<> inline FixedTypedVector Reference::As<FixedTypedVector>() { return AsFixedTypedVector(); }
+template<> inline TypedVector Reference::As<TypedVector>() {
+ return AsTypedVector();
+}
+template<> inline FixedTypedVector Reference::As<FixedTypedVector>() {
+ return AsFixedTypedVector();
+}
template<> inline Map Reference::As<Map>() { return AsMap(); }
inline uint8_t PackedType(BitWidth bit_width, Type type) {
return static_cast<uint8_t>(bit_width | (type << 2));
}
-inline uint8_t NullPackedType() {
- return PackedType(BIT_WIDTH_8, TYPE_NULL);
-}
+inline uint8_t NullPackedType() { return PackedType(BIT_WIDTH_8, TYPE_NULL); }
// Vector accessors.
// Note: if you try to access outside of bounds, you get a Null value back
// wanted 3d).
// The Null converts seamlessly into a default value for any other type.
// TODO(wvo): Could introduce an #ifdef that makes this into an assert?
-inline Reference Vector::operator[](size_t i) const {
+inline Reference Vector::operator[](size_t i) const {
auto len = size();
if (i >= len) return Reference(nullptr, 1, NullPackedType());
auto packed_type = (data_ + len * byte_width_)[i];
return Reference(elem, byte_width_, packed_type);
}
-inline Reference TypedVector::operator[](size_t i) const {
+inline Reference TypedVector::operator[](size_t i) const {
auto len = size();
if (i >= len) return Reference(nullptr, 1, NullPackedType());
auto elem = data_ + i * byte_width_;
return Reference(elem, byte_width_, 1, type_);
}
-inline Reference FixedTypedVector::operator[](size_t i) const {
+inline Reference FixedTypedVector::operator[](size_t i) const {
if (i >= len_) return Reference(nullptr, 1, NullPackedType());
auto elem = data_ + i * byte_width_;
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)));
+ Indirect<T>(reinterpret_cast<const uint8_t *>(elem)));
auto skey = reinterpret_cast<const char *>(key);
return strcmp(skey, str_elem);
}
case 8: comp = KeyCompare<uint64_t>; break;
}
auto res = std::bsearch(key, keys.data_, keys.size(), keys.byte_width_, comp);
- if (!res)
- return Reference(nullptr, 1, NullPackedType());
+ 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];
}
public:
Builder(size_t initial_size = 256,
BuilderFlag flags = BUILDER_FLAG_SHARE_KEYS)
- : buf_(initial_size), finished_(false), flags_(flags),
- force_min_bit_width_(BIT_WIDTH_8), key_pool(KeyOffsetCompare(buf_)),
+ : buf_(initial_size),
+ finished_(false),
+ flags_(flags),
+ force_min_bit_width_(BIT_WIDTH_8),
+ key_pool(KeyOffsetCompare(buf_)),
string_pool(StringOffsetCompare(buf_)) {
buf_.clear();
}
}
// Size of the buffer. Does not include unfinished values.
- size_t GetSize() const {
- return buf_.size();
- }
+ size_t GetSize() const { return buf_.size(); }
// Reset all state so we can re-use the buffer.
void Clear() {
// vectors and elsewhere).
void Null() { stack_.push_back(Value()); }
- void Null(const char *key) { Key(key); Null(); }
+ void Null(const char *key) {
+ Key(key);
+ Null();
+ }
void Int(int64_t i) { stack_.push_back(Value(i, TYPE_INT, WidthI(i))); }
- void Int(const char *key, int64_t i) { Key(key); Int(i); }
+ void Int(const char *key, int64_t i) {
+ Key(key);
+ Int(i);
+ }
void UInt(uint64_t u) { stack_.push_back(Value(u, TYPE_UINT, WidthU(u))); }
- void UInt(const char *key, uint64_t u) { Key(key); Int(u); }
+ void UInt(const char *key, uint64_t u) {
+ Key(key);
+ Int(u);
+ }
void Float(float f) { stack_.push_back(Value(f)); }
- void Float(const char *key, float f) { Key(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) { Key(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) { Key(key); Bool(b); }
-
- void IndirectInt(int64_t i) {
- PushIndirect(i, TYPE_INDIRECT_INT, WidthI(i));
+ void Bool(const char *key, bool b) {
+ Key(key);
+ Bool(b);
}
+
+ void IndirectInt(int64_t i) { PushIndirect(i, TYPE_INDIRECT_INT, WidthI(i)); }
void IndirectInt(const char *key, int64_t i) {
Key(key);
IndirectInt(i);
}
return sloc;
}
- size_t String(const char *str) {
- return String(str, strlen(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());
}
// Also some FlatBuffers types?
size_t StartVector() { return stack_.size(); }
- size_t StartVector(const char *key) { Key(key); return stack_.size(); }
+ size_t StartVector(const char *key) {
+ Key(key);
+ return stack_.size();
+ }
size_t StartMap() { return stack_.size(); }
- size_t StartMap(const char *key) { Key(key); return stack_.size(); }
+ size_t StartMap(const char *key) {
+ Key(key);
+ return stack_.size();
+ }
// TODO(wvo): allow this to specify an aligment greater than the natural
// alignment.
}
// Now sort values, so later we can do a binary seach lookup.
// We want to sort 2 array elements at a time.
- struct TwoValue { Value key; Value val; };
+ struct TwoValue {
+ Value key;
+ Value val;
+ };
// TODO(wvo): strict aliasing?
// TODO(wvo): allow the caller to indicate the data is already sorted
// for maximum efficiency? With an assert to check sortedness to make sure
// sorted fashion.
// std::sort is typically already a lot faster on sorted data though.
auto dict =
- reinterpret_cast<TwoValue *>(flatbuffers::vector_data(stack_) +
- start);
+ reinterpret_cast<TwoValue *>(flatbuffers::vector_data(stack_) + start);
std::sort(dict, dict + len,
[&](const TwoValue &a, const TwoValue &b) -> bool {
- auto as = reinterpret_cast<const char *>(
- flatbuffers::vector_data(buf_) + a.key.u_);
- auto bs = reinterpret_cast<const char *>(
- flatbuffers::vector_data(buf_) + b.key.u_);
- auto comp = strcmp(as, bs);
- // If this assertion hits, you've added two keys with the same value to
- // this map.
- // TODO: Have to check for pointer equality, as some sort implementation
- // apparently call this function with the same element?? Why?
- assert(comp || &a == &b);
- return comp < 0;
- });
+ auto as = reinterpret_cast<const char *>(
+ flatbuffers::vector_data(buf_) + a.key.u_);
+ auto bs = reinterpret_cast<const char *>(
+ flatbuffers::vector_data(buf_) + b.key.u_);
+ auto comp = strcmp(as, bs);
+ // If this assertion hits, you've added two keys with the same
+ // value to this map.
+ // TODO: Have to check for pointer equality, as some sort
+ // implementation apparently call this function with the same
+ // element?? Why?
+ assert(comp || &a == &b);
+ 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.
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);
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);
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);
}
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);
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);
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);
}
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);
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);
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) {
Key(key);
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
}
void WriteBytes(const void *val, size_t size) {
- buf_.insert(buf_.end(),
- reinterpret_cast<const uint8_t *>(val),
+ buf_.insert(buf_.end(), reinterpret_cast<const uint8_t *>(val),
reinterpret_cast<const uint8_t *>(val) + size);
}
switch (byte_width) {
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;
+ // case 2: Write(static_cast<half>(f), byte_width); break;
+ // case 1: Write(static_cast<quarter>(f), byte_width); break;
default: assert(0);
}
}
template<typename T> static Type GetScalarType() {
assert(flatbuffers::is_scalar<T>::value);
return flatbuffers::is_floating_point<T>::value
- ? TYPE_FLOAT
- : flatbuffers::is_same<T, bool>::value ? TYPE_BOOL
- : (flatbuffers::is_unsigned<T>::value ? TYPE_UINT : TYPE_INT);
+ ? TYPE_FLOAT
+ : flatbuffers::is_same<T, bool>::value
+ ? TYPE_BOOL
+ : (flatbuffers::is_unsigned<T>::value ? TYPE_UINT
+ : TYPE_INT);
}
struct Value {
Value() : i_(0), type_(TYPE_NULL), min_bit_width_(BIT_WIDTH_8) {}
- Value(bool b) : u_(static_cast<uint64_t>(b)), type_(TYPE_BOOL), min_bit_width_(BIT_WIDTH_8) {}
+ Value(bool b)
+ : u_(static_cast<uint64_t>(b)),
+ type_(TYPE_BOOL),
+ min_bit_width_(BIT_WIDTH_8) {}
Value(int64_t i, Type t, BitWidth bw)
- : i_(i), type_(t), min_bit_width_(bw) {}
+ : i_(i), type_(t), min_bit_width_(bw) {}
Value(uint64_t u, Type t, BitWidth bw)
- : u_(u), type_(t), min_bit_width_(bw) {}
+ : u_(u), type_(t), min_bit_width_(bw) {}
- Value(float f)
- : f_(f), type_(TYPE_FLOAT), min_bit_width_(BIT_WIDTH_32) {}
- Value(double f)
- : f_(f), type_(TYPE_FLOAT), min_bit_width_(WidthF(f)) {}
+ Value(float f) : f_(f), type_(TYPE_FLOAT), min_bit_width_(BIT_WIDTH_32) {}
+ Value(double f) : f_(f), type_(TYPE_FLOAT), min_bit_width_(WidthF(f)) {}
- uint8_t StoredPackedType(BitWidth parent_bit_width_= BIT_WIDTH_8) const {
+ uint8_t StoredPackedType(BitWidth parent_bit_width_ = BIT_WIDTH_8) const {
return PackedType(StoredWidth(parent_bit_width_), type_);
}
byte_width <= sizeof(flatbuffers::largest_scalar_t);
byte_width *= 2) {
// Where are we going to write this offset?
- auto offset_loc =
- buf_size +
- flatbuffers::PaddingBytes(buf_size, byte_width) +
- elem_index * byte_width;
+ auto offset_loc = buf_size +
+ flatbuffers::PaddingBytes(buf_size, byte_width) +
+ elem_index * byte_width;
// Compute relative offset.
auto offset = offset_loc - u_;
// Does it fit?
auto bit_width = WidthU(offset);
- if (static_cast<size_t>(static_cast<size_t>(1U) << bit_width) == byte_width)
+ if (static_cast<size_t>(static_cast<size_t>(1U) << bit_width) ==
+ byte_width)
return bit_width;
}
assert(false); // Must match one of the sizes above.
BitWidth StoredWidth(BitWidth parent_bit_width_ = BIT_WIDTH_8) const {
if (IsInline(type_)) {
- return (std::max)(min_bit_width_, parent_bit_width_);
+ return (std::max)(min_bit_width_, parent_bit_width_);
} else {
- return min_bit_width_;
+ return min_bit_width_;
}
}
};
void WriteAny(const Value &val, uint8_t byte_width) {
switch (val.type_) {
case TYPE_NULL:
- case TYPE_INT:
- Write(val.i_, byte_width);
- break;
+ case TYPE_INT: Write(val.i_, byte_width); break;
case TYPE_BOOL:
- case TYPE_UINT:
- Write(val.u_, byte_width);
- break;
- case TYPE_FLOAT:
- WriteDouble(val.f_, byte_width);
- break;
- default:
- WriteOffset(val.u_, byte_width);
- break;
+ case TYPE_UINT: Write(val.u_, byte_width); break;
+ case TYPE_FLOAT: WriteDouble(val.f_, byte_width); break;
+ default: WriteOffset(val.u_, byte_width); break;
}
}
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);
buf_.push_back(stack_[i].StoredPackedType(bit_width));
}
}
- return Value(static_cast<uint64_t>(vloc), keys
- ? TYPE_MAP
- : (typed
- ? ToTypedVector(vector_type, fixed ? vec_len : 0)
- : TYPE_VECTOR),
- bit_width);
+ return Value(static_cast<uint64_t>(vloc),
+ keys ? TYPE_MAP
+ : (typed ? ToTypedVector(vector_type, fixed ? vec_len : 0)
+ : TYPE_VECTOR),
+ bit_width);
}
// You shouldn't really be copying instances of this class.
struct StringOffsetCompare {
StringOffsetCompare(const std::vector<uint8_t> &buf) : buf_(&buf) {}
bool operator()(const StringOffset &a, const StringOffset &b) const {
- auto stra = reinterpret_cast<const char *>(flatbuffers::vector_data(*buf_) +
- a.first);
- auto strb = reinterpret_cast<const char *>(flatbuffers::vector_data(*buf_) +
- b.first);
+ auto stra = reinterpret_cast<const char *>(
+ flatbuffers::vector_data(*buf_) + a.first);
+ auto strb = reinterpret_cast<const char *>(
+ flatbuffers::vector_data(*buf_) + b.first);
return strncmp(stra, strb, (std::min)(a.second, b.second) + 1) < 0;
}
const std::vector<uint8_t> *buf_;
} // namespace flexbuffers
-#if defined(_MSC_VER)
-#pragma warning(pop)
-#endif
+# if defined(_MSC_VER)
+# pragma warning(pop)
+# endif
#endif // FLATBUFFERS_FLEXBUFFERS_H_
// `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() : slice_(grpc_empty_slice()) {}
Message(grpc_slice slice, bool add_ref)
- : slice_(add_ref ? grpc_slice_ref(slice) : slice) {}
+ : slice_(add_ref ? grpc_slice_ref(slice) : slice) {}
Message &operator=(const Message &other) = delete;
struct SliceAllocatorMember {
SliceAllocator slice_allocator_;
};
-}
+} // namespace detail
// MessageBuilder is a gRPC-specific FlatBufferBuilder that uses SliceAllocator
// to allocate gRPC buffers.
public FlatBufferBuilder {
public:
explicit MessageBuilder(uoffset_t initial_size = 1024)
- : FlatBufferBuilder(initial_size, &slice_allocator_, false) {}
+ : FlatBufferBuilder(initial_size, &slice_allocator_, false) {}
MessageBuilder(const MessageBuilder &other) = delete;
MessageBuilder &operator=(const MessageBuilder &other) = delete;
// 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_.buf(); // pointer to memory
auto buf_size = buf_.capacity(); // size of memory
auto msg_data = buf_.data(); // pointer to msg
return msg;
}
- template <class T>
- Message<T> ReleaseMessage() {
+ template<class T> Message<T> ReleaseMessage() {
Message<T> msg = GetMessage<T>();
Reset();
return msg;
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,
grpc_byte_buffer **buffer, bool *own_buffer) {
*msg = flatbuffers::grpc::Message<T>(slice, false);
}
grpc_byte_buffer_destroy(buffer);
- #if FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION
+#if FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION
return ::grpc::Status::OK;
- #else
+#else
if (msg->Verify()) {
return ::grpc::Status::OK;
} else {
return ::grpc::Status(::grpc::StatusCode::INTERNAL,
"Message verification failed");
}
- #endif
+#endif
}
};
-} // namespace grpc;
+} // namespace grpc
#endif // FLATBUFFERS_GRPC_H_
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) {
hash *= FnvTraits<T>::kFnvPrime;
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) {
hash ^= static_cast<unsigned char>(*c);
return hash;
}
-template <typename T>
-struct NamedHashFunction {
+template<typename T> struct NamedHashFunction {
const char *name;
- typedef T (*HashFunction)(const char*);
+ typedef T (*HashFunction)(const char *);
HashFunction function;
};
const NamedHashFunction<uint32_t> kHashFunctions32[] = {
- { "fnv1_32", HashFnv1<uint32_t> },
+ { "fnv1_32", HashFnv1<uint32_t> },
{ "fnv1a_32", HashFnv1a<uint32_t> },
};
const NamedHashFunction<uint64_t> kHashFunctions64[] = {
- { "fnv1_64", HashFnv1<uint64_t> },
+ { "fnv1_64", HashFnv1<uint64_t> },
{ "fnv1a_64", HashFnv1a<uint64_t> },
};
#define FLATBUFFERS_IDL_H_
#include <map>
-#include <stack>
#include <memory>
+#include <stack>
#include "flatbuffers/base.h"
#include "flatbuffers/flatbuffers.h"
+#include "flatbuffers/flexbuffers.h"
#include "flatbuffers/hash.h"
#include "flatbuffers/reflection.h"
-#include "flatbuffers/flexbuffers.h"
#if !defined(FLATBUFFERS_CPP98_STL)
- #include <functional>
+# include <functional>
#endif // !defined(FLATBUFFERS_CPP98_STL)
// This file defines the data types representing a parsed IDL (Interface
// The order of these matters for Is*() functions below.
// Additionally, Parser::ParseType assumes bool..string is a contiguous range
// of type tokens.
+// clang-format off
#define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
TD(NONE, "", uint8_t, byte, byte, byte, uint8) \
TD(UTYPE, "", uint8_t, byte, byte, byte, uint8) /* begin scalar/int */ \
inline bool IsLong (BaseType t) { return t == BASE_TYPE_LONG ||
t == BASE_TYPE_ULONG; }
inline bool IsBool (BaseType t) { return t == BASE_TYPE_BOOL; }
+// clang-format on
extern const char *const kTypeNames[];
extern const char kTypeSizes[];
-inline size_t SizeOf(BaseType t) {
- return kTypeSizes[t];
-}
+inline size_t SizeOf(BaseType t) { return kTypeSizes[t]; }
struct StructDef;
struct EnumDef;
// Represents any type in the IDL, which is a combination of the BaseType
// and additional information for vectors/structs_.
struct Type {
- explicit Type(BaseType _base_type = BASE_TYPE_NONE,
- StructDef *_sd = nullptr, EnumDef *_ed = nullptr)
- : base_type(_base_type),
- element(BASE_TYPE_NONE),
- struct_def(_sd),
- enum_def(_ed)
- {}
+ explicit Type(BaseType _base_type = BASE_TYPE_NONE, StructDef *_sd = nullptr,
+ EnumDef *_ed = nullptr)
+ : base_type(_base_type),
+ element(BASE_TYPE_NONE),
+ struct_def(_sd),
+ enum_def(_ed) {}
bool operator==(const Type &o) {
return base_type == o.base_type && element == o.element &&
// Represents a parsed scalar value, it's type, and field offset.
struct Value {
- Value() : constant("0"), offset(static_cast<voffset_t>(
- ~(static_cast<voffset_t>(0U)))) {}
+ Value()
+ : constant("0"),
+ offset(static_cast<voffset_t>(~(static_cast<voffset_t>(0U)))) {}
Type type;
std::string constant;
voffset_t offset;
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) {
}
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.
struct Namespace {
Namespace() : from_table(0) {}
-
// Given a (potentally unqualified) name, return the "fully qualified" name
// which has a full namespaced descriptor.
// With max_components you can request less than the number of components
// Base class for all definition types (fields, structs_, enums_).
struct Definition {
- Definition() : generated(false), defined_namespace(nullptr),
- serialized_location(0), index(-1), refcount(1) {}
+ Definition()
+ : generated(false),
+ defined_namespace(nullptr),
+ serialized_location(0),
+ index(-1),
+ refcount(1) {}
- flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<
- reflection::KeyValue>>>
- SerializeAttributes(FlatBufferBuilder *builder,
- const Parser &parser) const;
+ flatbuffers::Offset<
+ flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
+ SerializeAttributes(FlatBufferBuilder *builder, const Parser &parser) const;
std::string name;
std::string file;
};
struct FieldDef : public Definition {
- FieldDef() : deprecated(false), required(false), key(false),
- native_inline(false), flexbuffer(false), nested_flatbuffer(NULL),
- padding(0) {}
+ FieldDef()
+ : deprecated(false),
+ required(false),
+ key(false),
+ native_inline(false),
+ flexbuffer(false),
+ nested_flatbuffer(NULL),
+ padding(0) {}
Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id,
const Parser &parser) const;
Value value;
- bool deprecated; // Field is allowed to be present in old data, but can't be.
- // written in new data nor accessed in new code.
- bool required; // Field must always be present.
- bool key; // Field functions as a key for creating sorted vectors.
+ bool deprecated; // Field is allowed to be present in old data, but can't be.
+ // written in new data nor accessed in new code.
+ bool required; // Field must always be present.
+ bool key; // Field functions as a key for creating sorted vectors.
bool native_inline; // Field will be defined inline (instead of as a pointer)
// for native tables if field is a struct.
- bool flexbuffer; // This field contains FlexBuffer data.
- StructDef *nested_flatbuffer; // This field contains nested FlatBuffer data.
- size_t padding; // Bytes to always pad after this field.
+ bool flexbuffer; // This field contains FlexBuffer data.
+ StructDef *nested_flatbuffer; // This field contains nested FlatBuffer data.
+ size_t padding; // Bytes to always pad after this field.
};
struct StructDef : public Definition {
StructDef()
- : fixed(false),
- predecl(true),
- sortbysize(true),
- has_key(false),
- minalign(1),
- bytesize(0)
- {}
+ : fixed(false),
+ predecl(true),
+ sortbysize(true),
+ has_key(false),
+ minalign(1),
+ bytesize(0) {}
void PadLastField(size_t min_align) {
auto padding = PaddingBytes(bytesize, min_align);
}
struct EnumVal {
- EnumVal(const std::string &_name, int64_t _val)
- : name(_name), value(_val) {}
+ EnumVal(const std::string &_name, int64_t _val) : name(_name), value(_val) {}
Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder) const;
EnumDef() : is_union(false), uses_type_aliases(false) {}
EnumVal *ReverseLookup(int enum_idx, bool skip_union_default = true) {
- for (auto it = vals.vec.begin() + static_cast<int>(is_union &&
- skip_union_default);
- it != vals.vec.end(); ++it) {
- if ((*it)->value == enum_idx) {
- return *it;
- }
+ for (auto it = vals.vec.begin() +
+ static_cast<int>(is_union && skip_union_default);
+ it != vals.vec.end(); ++it) {
+ if ((*it)->value == enum_idx) { return *it; }
}
return nullptr;
}
return a.base_type == b.base_type && a.element == b.element &&
(a.struct_def == b.struct_def ||
a.struct_def->name == b.struct_def->name) &&
- (a.enum_def == b.enum_def ||
- a.enum_def->name == b.enum_def->name);
+ (a.enum_def == b.enum_def || a.enum_def->name == b.enum_def->name);
}
struct RPCCall {
// Possible options for the more general generator below.
enum Language {
- kJava = 1 << 0,
+ kJava = 1 << 0,
kCSharp = 1 << 1,
- kGo = 1 << 2,
- kCpp = 1 << 3,
- kJs = 1 << 4,
+ kGo = 1 << 2,
+ kCpp = 1 << 3,
+ kJs = 1 << 4,
kPython = 1 << 5,
- kPhp = 1 << 6,
- kJson = 1 << 7,
+ kPhp = 1 << 6,
+ kJson = 1 << 7,
kBinary = 1 << 8,
- kTs = 1 << 9,
+ kTs = 1 << 9,
kJsonSchema = 1 << 10,
kMAX
};
unsigned long lang_to_generate;
IDLOptions()
- : strict_json(false),
- skip_js_exports(false),
- use_goog_js_export_format(false),
- output_default_scalars_in_json(false),
- indent_step(2),
- output_enum_identifiers(true), prefixed_enums(true), scoped_enums(false),
- include_dependence_headers(true),
- mutable_buffer(false),
- one_file(false),
- proto_mode(false),
- generate_all(false),
- skip_unexpected_fields_in_json(false),
- generate_name_strings(false),
- generate_object_based_api(false),
- cpp_object_api_pointer_type("std::unique_ptr"),
- gen_nullable(false),
- object_suffix("T"),
- union_value_namespacing(true),
- allow_non_utf8(false),
- keep_include_path(false),
- binary_schema_comments(false),
- skip_flatbuffers_import(false),
- reexport_ts_modules(true),
- protobuf_ascii_alike(false),
- lang(IDLOptions::kJava),
- mini_reflect(IDLOptions::kNone),
- lang_to_generate(0) {}
+ : strict_json(false),
+ skip_js_exports(false),
+ use_goog_js_export_format(false),
+ output_default_scalars_in_json(false),
+ indent_step(2),
+ output_enum_identifiers(true),
+ prefixed_enums(true),
+ scoped_enums(false),
+ include_dependence_headers(true),
+ mutable_buffer(false),
+ one_file(false),
+ proto_mode(false),
+ generate_all(false),
+ skip_unexpected_fields_in_json(false),
+ generate_name_strings(false),
+ generate_object_based_api(false),
+ cpp_object_api_pointer_type("std::unique_ptr"),
+ gen_nullable(false),
+ object_suffix("T"),
+ union_value_namespacing(true),
+ allow_non_utf8(false),
+ keep_include_path(false),
+ binary_schema_comments(false),
+ skip_flatbuffers_import(false),
+ reexport_ts_modules(true),
+ protobuf_ascii_alike(false),
+ lang(IDLOptions::kJava),
+ mini_reflect(IDLOptions::kNone),
+ lang_to_generate(0) {}
};
// This encapsulates where the parser is in the current source file.
class CheckedError {
public:
explicit CheckedError(bool error)
- : is_error_(error), has_been_checked_(false) {}
+ : is_error_(error), has_been_checked_(false) {}
CheckedError &operator=(const CheckedError &other) {
is_error_ = other.is_error_;
~CheckedError() { assert(has_been_checked_); }
- bool Check() { has_been_checked_ = true; return is_error_; }
+ bool Check() {
+ has_been_checked_ = true;
+ return is_error_;
+ }
private:
bool is_error_;
// Additionally, in GCC we can get these errors statically, for additional
// assurance:
+// clang-format off
#ifdef __GNUC__
#define FLATBUFFERS_CHECKED_ERROR CheckedError \
__attribute__((warn_unused_result))
#else
#define FLATBUFFERS_CHECKED_ERROR CheckedError
#endif
+// clang-format on
class Parser : public ParserState {
public:
explicit Parser(const IDLOptions &options = IDLOptions())
- : current_namespace_(nullptr),
- empty_namespace_(nullptr),
- root_struct_def_(nullptr),
- opts(options),
- uses_flexbuffers_(false),
- source_(nullptr),
- anonymous_counter(0) {
+ : current_namespace_(nullptr),
+ empty_namespace_(nullptr),
+ root_struct_def_(nullptr),
+ opts(options),
+ uses_flexbuffers_(false),
+ source_(nullptr),
+ anonymous_counter(0) {
// Start out with the empty namespace being current.
empty_namespace_ = new Namespace();
namespaces_.push_back(empty_namespace_);
StructDef *LookupStruct(const std::string &id) const;
-private:
+ private:
void Message(const std::string &msg);
void Warning(const std::string &msg);
FLATBUFFERS_CHECKED_ERROR Error(const std::string &msg);
FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value &val, FieldDef *field,
size_t parent_fieldn,
const StructDef *parent_struct_def);
+ // clang-format off
#if defined(FLATBUFFERS_CPP98_STL)
typedef CheckedError (*ParseTableDelimitersBody)(
const std::string &name, size_t &fieldn, const StructDef *struct_def,
const StructDef*, void*)>
ParseTableDelimitersBody;
#endif // defined(FLATBUFFERS_CPP98_STL)
+ // clang-format on
FLATBUFFERS_CHECKED_ERROR ParseTableDelimiters(size_t &fieldn,
const StructDef *struct_def,
ParseTableDelimitersBody body,
std::string *value, uoffset_t *ovalue);
void SerializeStruct(const StructDef &struct_def, const Value &val);
void AddVector(bool sortbysize, int count);
+ // clang-format off
#if defined(FLATBUFFERS_CPP98_STL)
typedef CheckedError (*ParseVectorDelimitersBody)(size_t &count,
void *state);
typedef std::function<CheckedError(size_t&, void*)>
ParseVectorDelimitersBody;
#endif // defined(FLATBUFFERS_CPP98_STL)
+ // clang-format on
FLATBUFFERS_CHECKED_ERROR ParseVectorDelimiters(
size_t &count, ParseVectorDelimitersBody body, void *state);
FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue);
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,
virtual void EndVector() {}
virtual void Element(size_t /*i*/, ElementaryType /*type*/,
const TypeTable * /*type_table*/,
- const uint8_t * /*val*/)
- {}
+ const uint8_t * /*val*/) {}
virtual ~IterationVisitor() {}
};
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_STRUCT:
- return type_table->values[type_table->num_elems];
- default:
- assert(false);
- return 1;
+ case ST_UNION: return 4;
+ case ST_STRUCT: return type_table->values[type_table->num_elems];
+ default: assert(false); return 1;
}
- default:
- assert(false);
- return 1;
+ default: assert(false); return 1;
}
}
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<int32_t>(tval), type_table->values,
- type_table->num_elems);
+ type_table->num_elems);
if (i >= 0 && i < static_cast<int32_t>(type_table->num_elems)) {
return type_table->names[i];
}
}
void IterateObject(const uint8_t *obj, const TypeTable *type_table,
- IterationVisitor *visitor);
+ 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) {
+ const TypeTable *type_table, const uint8_t *prev_val,
+ soffset_t vector_index, IterationVisitor *visitor) {
switch (type) {
case ET_UTYPE: {
auto tval = *reinterpret_cast<const uint8_t *>(val);
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);
assert(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 = LookupEnum(union_type, type_table->values,
- type_table->num_elems);
- if (type_code_idx >= 0 && type_code_idx <
- static_cast<int32_t>(type_table->num_elems)) {
+ auto type_code_idx =
+ LookupEnum(union_type, type_table->values, type_table->num_elems);
+ if (type_code_idx >= 0 &&
+ type_code_idx < static_cast<int32_t>(type_table->num_elems)) {
auto type_code = type_table->type_codes[type_code_idx];
switch (type_code.base_type) {
case ET_SEQUENCE: {
case ET_STRING:
visitor->String(reinterpret_cast<const String *>(val));
break;
- default:
- visitor->Unknown(val);
+ default: visitor->Unknown(val);
}
} else {
visitor->Unknown(val);
}
break;
}
- case ST_ENUM:
- assert(false);
- break;
+ case ST_ENUM: assert(false); break;
}
break;
}
auto is_vector = type_code.is_vector != 0;
auto ref_idx = type_code.sequence_ref;
const TypeTable *ref = nullptr;
- if (ref_idx >= 0) {
- ref = type_table->type_refs[ref_idx]();
- }
+ 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;
if (type_table->st == ST_TABLE) {
val = reinterpret_cast<const Table *>(obj)->GetAddressOf(
- FieldIndexToOffset(static_cast<voffset_t>(i)));
+ FieldIndexToOffset(static_cast<voffset_t>(i)));
} else {
val = obj + type_table->values[i];
}
const char *name, const uint8_t *val) {
if (!val) return;
if (set_idx) s += ", ";
- if (name) { s += name; s += ": "; }
+ if (name) {
+ s += name;
+ s += ": ";
+ }
}
template<typename T> void Named(T x, const char *name) {
- if (name) s+= name;
- else s+= NumToString(x);
+ if (name)
+ s += name;
+ else
+ s += NumToString(x);
}
void UType(uint8_t x, const char *name) { Named(x, name); }
- void Bool(bool x) { s+= x ? "true" : "false"; }
+ 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 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 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) {
EscapeString(str->c_str(), str->size(), &s, true);
}
// ------------------------- GETTERS -------------------------
-inline bool IsScalar (reflection::BaseType t) { return t >= reflection::UType &&
- t <= reflection::Double; }
-inline bool IsInteger(reflection::BaseType t) { return t >= reflection::UType &&
- t <= reflection::ULong; }
-inline bool IsFloat (reflection::BaseType t) { return t == reflection::Float ||
- t == reflection::Double; }
-inline bool IsLong (reflection::BaseType t) { return t == reflection::Long ||
- t == reflection::ULong; }
+inline bool IsScalar(reflection::BaseType t) {
+ return t >= reflection::UType && t <= reflection::Double;
+}
+inline bool IsInteger(reflection::BaseType t) {
+ return t >= reflection::UType && t <= reflection::ULong;
+}
+inline bool IsFloat(reflection::BaseType t) {
+ return t == reflection::Float || t == reflection::Double;
+}
+inline bool IsLong(reflection::BaseType t) {
+ return t == reflection::Long || t == reflection::ULong;
+}
// Size of a basic type, don't use with structs.
inline size_t GetTypeSize(reflection::BaseType base_type) {
// Same as above, but now correctly returns the size of a struct if
// the field (or vector element) is a struct.
-inline size_t GetTypeSizeInline(reflection::BaseType base_type,
- int type_index,
+inline size_t GetTypeSizeInline(reflection::BaseType base_type, int type_index,
const reflection::Schema &schema) {
if (base_type == reflection::Obj &&
schema.objects()->Get(type_index)->is_struct()) {
}
// 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) {
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) {
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 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) {
assert(field.type()->base_type() == reflection::Vector &&
sizeof(T) == GetTypeSize(field.type()->element()));
return table.GetPointer<Vector<T> *>(field.offset());
}
// Get a field, if you know it's a table.
-inline Table *GetFieldT(const Table &table,
- const reflection::Field &field) {
+inline Table *GetFieldT(const Table &table, const reflection::Field &field) {
assert(field.type()->base_type() == reflection::Obj ||
field.type()->base_type() == reflection::Union);
return table.GetPointer<Table *>(field.offset());
// 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);
+ 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,
}
// 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();
}
-
// 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.
}
// 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 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 (T *)(elem_ptr + ReadScalar<uoffset_t>(elem_ptr));
}
// Get elem_size from GetTypeSizeInline().
// Note: little-endian data on all platforms, use EndianScalar() instead of
// raw pointer access with scalars).
-template<typename T> T *GetAnyVectorElemAddressOf(const VectorOfAny *vec,
- size_t i,
- size_t elem_size) {
+template<typename T>
+T *GetAnyVectorElemAddressOf(const VectorOfAny *vec, size_t i,
+ size_t elem_size) {
// C-cast to allow const conversion.
return (T *)(vec->Data() + elem_size * i);
}
// Similarly, for elements of tables.
-template<typename T> T *GetAnyFieldAddressOf(const Table &table,
- const reflection::Field &field) {
+template<typename T>
+T *GetAnyFieldAddressOf(const Table &table, const reflection::Field &field) {
return (T *)table.GetAddressOf(field.offset());
}
// Similarly, for elements of structs.
-template<typename T> T *GetAnyFieldAddressOf(const Struct &st,
- const reflection::Field &field) {
+template<typename T>
+T *GetAnyFieldAddressOf(const Struct &st, const reflection::Field &field) {
return (T *)st.GetAddressOf(field.offset());
}
// ------------------------- SETTERS -------------------------
// Set any scalar field, if you know its exact type.
-template<typename T> bool SetField(Table *table, const reflection::Field &field,
- T val) {
+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; }
assert(sizeof(T) == GetTypeSize(type));
T def;
if (IsInteger(type)) {
// 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) {
+ const char *val) {
auto field_ptr = table->GetAddressOf(field.offset());
if (!field_ptr) return false;
SetAnyValueS(field.type()->base_type(), field_ptr, val);
SetAnyValueS(elem_type, vec->Data() + GetTypeSize(elem_type) * i, val);
}
-
// ------------------------- RESIZING SETTERS -------------------------
// "smart" pointer for use with resizing vectors: turns a pointer inside
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 *>(flatbuffers::vector_data(vec))),
- vec_(vec) {}
+ : offset_(reinterpret_cast<uint8_t *>(ptr) -
+ reinterpret_cast<uint8_t *>(flatbuffers::vector_data(vec))),
+ vec_(vec) {}
T *operator*() const {
return reinterpret_cast<T *>(
- reinterpret_cast<uint8_t *>(
- flatbuffers::vector_data(vec_)) + offset_);
- }
- T *operator->() const {
- return operator*();
+ reinterpret_cast<uint8_t *>(flatbuffers::vector_data(vec_)) + offset_);
}
+ T *operator->() const { return operator*(); }
void operator=(const pointer_inside_vector &piv);
+
private:
size_t offset_;
std::vector<U> &vec_;
};
// Helper to create the above easily without specifying template args.
-template<typename T, typename U> pointer_inside_vector<T, U> piv(T *ptr,
- std::vector<U> &vec) {
+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);
}
auto enumdef = schema.enums()->Get(unionfield.type()->index());
// TODO: this is clumsy and slow, but no other way to find it?
auto type_field = parent.fields()->LookupByKey(
- (unionfield.name()->str() + UnionTypeFieldSuffix()).c_str());
+ (unionfield.name()->str() + UnionTypeFieldSuffix()).c_str());
assert(type_field);
auto union_type = GetFieldI<uint8_t>(table, *type_field);
auto enumval = enumdef->values()->LookupByKey(union_type);
uoffset_t elem_size, std::vector<uint8_t> *flatbuf,
const reflection::Object *root_table = nullptr);
-template <typename T>
+template<typename T>
void ResizeVector(const reflection::Schema &schema, uoffset_t newsize, T val,
const Vector<T> *vec, std::vector<uint8_t> *flatbuf,
const reflection::Object *root_table = nullptr) {
auto delta_elem = static_cast<int>(newsize) - static_cast<int>(vec->size());
- auto newelems = ResizeAnyVector(schema, newsize,
- reinterpret_cast<const VectorOfAny *>(vec),
- vec->size(),
- static_cast<uoffset_t>(sizeof(T)), flatbuf,
- root_table);
+ auto newelems = ResizeAnyVector(
+ schema, newsize, reinterpret_cast<const VectorOfAny *>(vec), vec->size(),
+ static_cast<uoffset_t>(sizeof(T)), flatbuf, root_table);
// Set new elements to "val".
for (int i = 0; i < delta_elem; i++) {
auto loc = newelems + i * sizeof(T);
// 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);
+bool Verify(const reflection::Schema &schema, const reflection::Object &root,
+ const uint8_t *buf, size_t length);
} // namespace flatbuffers
// 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) +
- FlatBufferBuilder::kFileIdentifierLength) {
+ if (len < sizeof(uoffset_t) + FlatBufferBuilder::kFileIdentifierLength) {
lasterror_ = "buffer truncated";
return false;
}
- std::string ident(reinterpret_cast<const char *>(flatbuf) +
- sizeof(uoffset_t),
- FlatBufferBuilder::kFileIdentifierLength);
+ std::string ident(
+ reinterpret_cast<const char *>(flatbuf) + sizeof(uoffset_t),
+ FlatBufferBuilder::kFileIdentifierLength);
// Load and parse the schema.
Parser parser;
if (!LoadSchema(ident, &parser)) return false;
// 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_; }
private:
- bool LoadSchema(const std::string &ident, Parser *parser) {
- // Find the schema, if not, exit.
- auto it = schemas_.find(ident);
- if (it == schemas_.end()) {
- // Don't attach the identifier, since it may not be human readable.
- lasterror_ = "identifier for this buffer not in the registry";
- return false;
- }
- auto &schema = it->second;
- // Load the schema from disk. If not, exit.
- std::string schematext;
- if (!LoadFile(schema.path_.c_str(), false, &schematext)) {
- lasterror_ = "could not load schema: " + schema.path_;
- return false;
- }
- // Parse schema.
- parser->opts = opts_;
- if (!parser->Parse(schematext.c_str(), vector_data(include_paths_),
- schema.path_.c_str())) {
- lasterror_ = parser->error_;
- return false;
- }
- return true;
- }
+ bool LoadSchema(const std::string &ident, Parser *parser) {
+ // Find the schema, if not, exit.
+ auto it = schemas_.find(ident);
+ if (it == schemas_.end()) {
+ // Don't attach the identifier, since it may not be human readable.
+ lasterror_ = "identifier for this buffer not in the registry";
+ return false;
+ }
+ auto &schema = it->second;
+ // Load the schema from disk. If not, exit.
+ std::string schematext;
+ if (!LoadFile(schema.path_.c_str(), false, &schematext)) {
+ lasterror_ = "could not load schema: " + schema.path_;
+ return false;
+ }
+ // Parse schema.
+ parser->opts = opts_;
+ if (!parser->Parse(schematext.c_str(), vector_data(include_paths_),
+ schema.path_.c_str())) {
+ lasterror_ = parser->error_;
+ return false;
+ }
+ return true;
+ }
struct Schema {
std::string path_;
#ifndef FLATBUFFERS_STL_EMULATION_H_
#define FLATBUFFERS_STL_EMULATION_H_
+// clang-format off
+
#include <string>
#include <type_traits>
#include <vector>
#ifndef FLATBUFFERS_UTIL_H_
#define FLATBUFFERS_UTIL_H_
+#include <assert.h>
+#include <stdint.h>
+#include <stdlib.h>
#include <fstream>
#include <iomanip>
-#include <string>
#include <sstream>
-#include <stdint.h>
-#include <stdlib.h>
-#include <assert.h>
+#include <string>
#ifdef _WIN32
-#ifndef WIN32_LEAN_AND_MEAN
- #define WIN32_LEAN_AND_MEAN
-#endif
-#ifndef NOMINMAX
- #define NOMINMAX
-#endif
-#include <windows.h>
-#include <winbase.h>
-#include <direct.h>
+# ifndef WIN32_LEAN_AND_MEAN
+# define WIN32_LEAN_AND_MEAN
+# endif
+# ifndef NOMINMAX
+# define NOMINMAX
+# endif
+# include <direct.h>
+# include <winbase.h>
+# include <windows.h>
#else
-#include <limits.h>
+# include <limits.h>
#endif
-#include <sys/types.h>
#include <sys/stat.h>
+#include <sys/types.h>
#include "flatbuffers/base.h"
-
namespace flatbuffers {
// Convert an integer or floating point value to a string.
return NumToString(static_cast<int>(t));
}
#if defined(FLATBUFFERS_CPP98_STL)
- template <> inline std::string NumToString<long long>(long long t) {
- char buf[21]; // (log((1 << 63) - 1) / log(10)) + 2
- snprintf(buf, sizeof(buf), "%lld", t);
- return std::string(buf);
- }
+template<> inline std::string NumToString<long long>(long long t) {
+ char buf[21]; // (log((1 << 63) - 1) / log(10)) + 2
+ snprintf(buf, sizeof(buf), "%lld", t);
+ return std::string(buf);
+}
- template <> inline std::string NumToString<unsigned long long>(
- unsigned long long t) {
- char buf[22]; // (log((1 << 63) - 1) / log(10)) + 1
- snprintf(buf, sizeof(buf), "%llu", t);
- return std::string(buf);
- }
+template<>
+inline std::string NumToString<unsigned long long>(unsigned long long t) {
+ char buf[22]; // (log((1 << 63) - 1) / log(10)) + 1
+ snprintf(buf, sizeof(buf), "%llu", t);
+ return std::string(buf);
+}
#endif // defined(FLATBUFFERS_CPP98_STL)
// Special versions for floats/doubles.
// For example, IntToStringHex(0x23, 8) returns the string "00000023".
inline std::string IntToStringHex(int i, int xdigits) {
std::stringstream ss;
- ss << std::setw(xdigits)
- << std::setfill('0')
- << std::hex
- << std::uppercase
+ ss << std::setw(xdigits) << std::setfill('0') << std::hex << std::uppercase
<< i;
return ss.str();
}
// Portable implementation of strtoll().
inline int64_t StringToInt(const char *str, char **endptr = nullptr,
int base = 10) {
+ // clang-format off
#ifdef _MSC_VER
return _strtoi64(str, endptr, base);
#else
return strtoll(str, endptr, base);
#endif
+ // clang-format on
}
// Portable implementation of strtoull().
inline uint64_t StringToUInt(const char *str, char **endptr = nullptr,
int base = 10) {
+ // clang-format off
#ifdef _MSC_VER
return _strtoui64(str, endptr, base);
#else
return strtoull(str, endptr, base);
#endif
+ // clang-format on
}
typedef bool (*LoadFileFunction)(const char *filename, bool binary,
LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function);
-FileExistsFunction SetFileExistsFunction(FileExistsFunction
- file_exists_function);
-
+FileExistsFunction SetFileExistsFunction(
+ FileExistsFunction file_exists_function);
// Check if file "name" exists.
bool FileExists(const char *name);
inline void EnsureDirExists(const std::string &filepath) {
auto parent = StripFileName(filepath);
if (parent.length()) EnsureDirExists(parent);
+ // clang-format off
#ifdef _WIN32
(void)_mkdir(filepath.c_str());
#else
mkdir(filepath.c_str(), S_IRWXU|S_IRGRP|S_IXGRP);
#endif
+ // clang-format on
}
// Obtains the absolute path from any other path.
// Returns the input path if the absolute path couldn't be resolved.
inline std::string AbsolutePath(const std::string &filepath) {
+ // clang-format off
#ifdef FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
return filepath;
#else
? abs_path
: filepath;
#endif // FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
+ // clang-format on
}
// To and from UTF-8 unicode conversion functions
uint32_t remain_bits = i * 6;
// Store first byte:
(*out) += static_cast<char>((0xFE << (max_bits - remain_bits)) |
- (ucc >> remain_bits));
+ (ucc >> remain_bits));
// Store remaining bytes:
for (int j = i - 1; j >= 0; j--) {
(*out) += static_cast<char>(((ucc >> (j * 6)) & 0x3F) | 0x80);
if ((**in << len) & 0x80) return -1; // Bit after leading 1's must be 0.
if (!len) return *(*in)++;
// UTF-8 encoded values with a length are between 2 and 4 bytes.
- if (len < 2 || len > 4) {
- return -1;
- }
+ 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++) {
}
// 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;
text += "\\u";
text += IntToStringHex(ucc, 4);
} else if (ucc <= 0x10FFFF) {
- // Encode Unicode SMP values to a surrogate pair using two \u escapes.
+ // Encode Unicode SMP values to a surrogate pair using two \u
+ // escapes.
uint32_t base = ucc - 0x10000;
auto high_surrogate = (base >> 10) + 0xD800;
auto low_surrogate = (base & 0x03FF) + 0xDC00;
* limitations under the License.
*/
-#include "monster_generated.h" // Already includes "flatbuffers/flatbuffers.h".
+#include "monster_generated.h" // Already includes "flatbuffers/flatbuffers.h".
using namespace MyGame::Sample;
// 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;
auto orc = CreateMonster(builder, &position, 150, 80, name, inventory,
Color_Red, weapons, Equipment_Weapon, axe.Union());
- builder.Finish(orc); // Serialize the root of the object.
+ builder.Finish(orc); // Serialize the root of the object.
// We now have a FlatBuffer we can store on disk or send over a network.
(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]);
// 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;
printf("The FlatBuffer was successfully created and verified!\n");
}
-
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#include "monster_generated.h" // Already includes "flatbuffers/flatbuffers.h".
+#include "monster_generated.h" // Already includes "flatbuffers/flatbuffers.h".
using namespace MyGame::Sample;
// 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;
--- /dev/null
+clang-format -i -style=file include/flatbuffers/* src/*.cpp tests/test.cpp samples/*.cpp grpc/src/compiler/schema_interface.h grpc/tests/*.cpp
+git checkout include/flatbuffers/reflection_generated.h
#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 {
void CodeWriter::operator+=(std::string text) {
-
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);
return qualified_name + name;
}
-
std::string BaseGenerator::WrapInNameSpace(const Definition &def) const {
return WrapInNameSpace(def.defined_namespace, def.name);
}
if (config != nullptr && config->first_line != nullptr) {
code += std::string(prefix) + std::string(config->first_line) + "\n";
}
- std::string line_prefix = std::string(prefix) +
- ((config != nullptr && config->content_line_prefix != nullptr) ?
- config->content_line_prefix : "///");
- for (auto it = dc.begin();
- it != dc.end();
- ++it) {
+ std::string line_prefix =
+ std::string(prefix) +
+ ((config != nullptr && config->content_line_prefix != nullptr)
+ ? config->content_line_prefix
+ : "///");
+ for (auto it = dc.begin(); it != dc.end(); ++it) {
code += line_prefix + *it + "\n";
}
if (config != nullptr && config->last_line != nullptr) {
} // namespace flatbuffers
#if defined(_MSC_VER)
-#pragma warning(pop)
+# pragma warning(pop)
#endif
#define FLATC_VERSION "1.8.0 (" __DATE__ " " __TIME__ ")"
-
namespace flatbuffers {
void FlatCompiler::ParseFile(
- flatbuffers::Parser &parser,
- const std::string &filename,
+ flatbuffers::Parser &parser, const std::string &filename,
const std::string &contents,
std::vector<const char *> &include_directories) const {
auto local_include_directory = flatbuffers::StripFileName(filename);
params_.error_fn(this, err, usage, show_exe_name);
}
-std::string FlatCompiler::GetUsageString(const char* program_name) const {
+std::string FlatCompiler::GetUsageString(const char *program_name) const {
std::stringstream ss;
ss << "Usage: " << program_name << " [OPTION]... FILE... [-- FILE...]\n";
for (size_t i = 0; i < params_.num_generators; ++i) {
- const Generator& g = params_.generators[i];
+ const Generator &g = params_.generators[i];
std::stringstream full_name;
full_name << std::setw(12) << std::left << g.generator_opt_long;
ss << " " << full_name.str() << " " << name << " " << help << ".\n";
}
+ // clang-format off
ss <<
- " -o PATH Prefix PATH to all generated files.\n"
- " -I PATH Search for includes in the specified path.\n"
- " -M Print make rules for generated files.\n"
- " --version Print the version number of flatc and exit.\n"
- " --strict-json Strict JSON: field names must be / will be quoted,\n"
- " no trailing commas in tables/vectors.\n"
- " --allow-non-utf8 Pass non-UTF-8 input through parser and emit nonstandard\n"
- " \\x escapes in JSON. (Default is to raise parse error on\n"
- " non-UTF-8 input.)\n"
- " --defaults-json Output fields whose value is the default when\n"
- " writing JSON\n"
- " --unknown-json Allow fields in JSON that are not defined in the\n"
- " schema. These fields will be discared when generating\n"
- " binaries.\n"
- " --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
- " --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
- " also implies --no-prefix.\n"
- " --gen-includes (deprecated), this is the default behavior.\n"
- " If the original behavior is required (no include\n"
- " statements) use --no-includes.\n"
- " --no-includes Don\'t generate include statements for included\n"
- " schemas the generated file depends on (C++).\n"
- " --gen-mutable Generate accessors that can mutate buffers in-place.\n"
- " --gen-onefile Generate single output file for C# and Go.\n"
- " --gen-name-strings Generate type name functions for C++.\n"
- " --gen-object-api Generate an additional object-based API.\n"
- " --cpp-ptr-type T Set object API pointer type (default std::unique_ptr)\n"
- " --cpp-str-type T Set object API string type (default std::string)\n"
- " T::c_str() and T::length() must be supported\n"
- " --gen-nullable Add Clang _Nullable for C++ pointer. or @Nullable for Java\n"
- " --object-prefix Customise class prefix for C++ object-based API.\n"
- " --object-suffix Customise class suffix for C++ object-based API.\n"
- " Default value is \"T\"\n"
- " --no-js-exports Removes Node.js style export lines in JS.\n"
- " --goog-js-export Uses goog.exports* for closure compiler exporting in JS.\n"
- " --go-namespace Generate the overrided namespace in Golang.\n"
- " --go-import Generate the overrided import for flatbuffers in Golang.\n"
- " (default is \"github.com/google/flatbuffers/go\")\n"
- " --raw-binary Allow binaries without file_indentifier to be read.\n"
- " This may crash flatc given a mismatched schema.\n"
- " --proto Input is a .proto, translate to .fbs.\n"
- " --grpc Generate GRPC interfaces for the specified languages\n"
- " --schema Serialize schemas instead of JSON (use with -b)\n"
- " --bfbs-comments Add doc comments to the binary schema files.\n"
- " --conform FILE Specify a schema the following schemas should be\n"
- " an evolution of. Gives errors if not.\n"
- " --conform-includes Include path for the schema given with --conform\n"
- " PATH \n"
- " --include-prefix Prefix this path to any generated include statements.\n"
- " PATH\n"
- " --keep-prefix Keep original prefix of schema include statement.\n"
- " --no-fb-import Don't include flatbuffers import statement for TypeScript.\n"
- " --no-ts-reexport Don't re-export imported dependencies for TypeScript.\n"
- " --reflect-types Add minimal type reflection to code generation.\n"
- " --reflect-names Add minimal type/name reflection.\n"
- "FILEs may be schemas (must end in .fbs), or JSON files (conforming to preceding\n"
- "schema). FILEs after the -- must be binary flatbuffer format files.\n"
- "Output files are named using the base file name of the input,\n"
- "and written to the current directory or the path given by -o.\n"
- "example: " << program_name << " -c -b schema1.fbs schema2.fbs data.json\n";
+ " -o PATH Prefix PATH to all generated files.\n"
+ " -I PATH Search for includes in the specified path.\n"
+ " -M Print make rules for generated files.\n"
+ " --version Print the version number of flatc and exit.\n"
+ " --strict-json Strict JSON: field names must be / will be quoted,\n"
+ " no trailing commas in tables/vectors.\n"
+ " --allow-non-utf8 Pass non-UTF-8 input through parser and emit nonstandard\n"
+ " \\x escapes in JSON. (Default is to raise parse error on\n"
+ " non-UTF-8 input.)\n"
+ " --defaults-json Output fields whose value is the default when\n"
+ " writing JSON\n"
+ " --unknown-json Allow fields in JSON that are not defined in the\n"
+ " schema. These fields will be discared when generating\n"
+ " binaries.\n"
+ " --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
+ " --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
+ " also implies --no-prefix.\n"
+ " --gen-includes (deprecated), this is the default behavior.\n"
+ " If the original behavior is required (no include\n"
+ " statements) use --no-includes.\n"
+ " --no-includes Don\'t generate include statements for included\n"
+ " schemas the generated file depends on (C++).\n"
+ " --gen-mutable Generate accessors that can mutate buffers in-place.\n"
+ " --gen-onefile Generate single output file for C# and Go.\n"
+ " --gen-name-strings Generate type name functions for C++.\n"
+ " --gen-object-api Generate an additional object-based API.\n"
+ " --cpp-ptr-type T Set object API pointer type (default std::unique_ptr)\n"
+ " --cpp-str-type T Set object API string type (default std::string)\n"
+ " T::c_str() and T::length() must be supported\n"
+ " --gen-nullable Add Clang _Nullable for C++ pointer. or @Nullable for Java\n"
+ " --object-prefix Customise class prefix for C++ object-based API.\n"
+ " --object-suffix Customise class suffix for C++ object-based API.\n"
+ " Default value is \"T\"\n"
+ " --no-js-exports Removes Node.js style export lines in JS.\n"
+ " --goog-js-export Uses goog.exports* for closure compiler exporting in JS.\n"
+ " --go-namespace Generate the overrided namespace in Golang.\n"
+ " --go-import Generate the overrided import for flatbuffers in Golang.\n"
+ " (default is \"github.com/google/flatbuffers/go\")\n"
+ " --raw-binary Allow binaries without file_indentifier to be read.\n"
+ " This may crash flatc given a mismatched schema.\n"
+ " --proto Input is a .proto, translate to .fbs.\n"
+ " --grpc Generate GRPC interfaces for the specified languages\n"
+ " --schema Serialize schemas instead of JSON (use with -b)\n"
+ " --bfbs-comments Add doc comments to the binary schema files.\n"
+ " --conform FILE Specify a schema the following schemas should be\n"
+ " an evolution of. Gives errors if not.\n"
+ " --conform-includes Include path for the schema given with --conform\n"
+ " PATH \n"
+ " --include-prefix Prefix this path to any generated include statements.\n"
+ " PATH\n"
+ " --keep-prefix Keep original prefix of schema include statement.\n"
+ " --no-fb-import Don't include flatbuffers import statement for TypeScript.\n"
+ " --no-ts-reexport Don't re-export imported dependencies for TypeScript.\n"
+ " --reflect-types Add minimal type reflection to code generation.\n"
+ " --reflect-names Add minimal type/name reflection.\n"
+ "FILEs may be schemas (must end in .fbs), or JSON files (conforming to preceding\n"
+ "schema). FILEs after the -- must be binary flatbuffer format files.\n"
+ "Output files are named using the base file name of the input,\n"
+ "and written to the current directory or the path given by -o.\n"
+ "example: " << program_name << " -c -b schema1.fbs schema2.fbs data.json\n";
+ // clang-format on
return ss.str();
}
-int FlatCompiler::Compile(int argc, const char** argv) {
+int FlatCompiler::Compile(int argc, const char **argv) {
if (params_.generators == nullptr || params_.num_generators == 0) {
return 0;
}
if (arg == "-o") {
if (++argi >= argc) Error("missing path following: " + arg, true);
output_path = flatbuffers::ConCatPathFileName(
- flatbuffers::PosixPath(argv[argi]), "");
- } else if(arg == "-I") {
+ flatbuffers::PosixPath(argv[argi]), "");
+ } else if (arg == "-I") {
if (++argi >= argc) Error("missing path following" + arg, true);
include_directories_storage.push_back(
- flatbuffers::PosixPath(argv[argi]));
+ flatbuffers::PosixPath(argv[argi]));
include_directories.push_back(
- include_directories_storage.back().c_str());
- } else if(arg == "--conform") {
+ include_directories_storage.back().c_str());
+ } else if (arg == "--conform") {
if (++argi >= argc) Error("missing path following" + arg, true);
conform_to_schema = flatbuffers::PosixPath(argv[argi]);
} else if (arg == "--conform-includes") {
if (++argi >= argc) Error("missing path following" + arg, true);
include_directories_storage.push_back(
- flatbuffers::PosixPath(argv[argi]));
+ flatbuffers::PosixPath(argv[argi]));
conform_include_directories.push_back(
- include_directories_storage.back().c_str());
+ include_directories_storage.back().c_str());
} else if (arg == "--include-prefix") {
if (++argi >= argc) Error("missing path following" + arg, true);
opts.include_prefix = flatbuffers::ConCatPathFileName(
- flatbuffers::PosixPath(argv[argi]), "");
- } else if(arg == "--keep-prefix") {
+ flatbuffers::PosixPath(argv[argi]), "");
+ } else if (arg == "--keep-prefix") {
opts.keep_include_path = true;
- } else if(arg == "--strict-json") {
+ } else if (arg == "--strict-json") {
opts.strict_json = true;
- } else if(arg == "--allow-non-utf8") {
+ } else if (arg == "--allow-non-utf8") {
opts.allow_non_utf8 = true;
- } else if(arg == "--no-js-exports") {
+ } else if (arg == "--no-js-exports") {
opts.skip_js_exports = true;
- } else if(arg == "--goog-js-export") {
+ } else if (arg == "--goog-js-export") {
opts.use_goog_js_export_format = true;
- } else if(arg == "--go-namespace") {
+ } else if (arg == "--go-namespace") {
if (++argi >= argc) Error("missing golang namespace" + arg, true);
opts.go_namespace = argv[argi];
- } else if(arg == "--go-import") {
+ } else if (arg == "--go-import") {
if (++argi >= argc) Error("missing golang import" + arg, true);
opts.go_import = argv[argi];
- } else if(arg == "--defaults-json") {
+ } else if (arg == "--defaults-json") {
opts.output_default_scalars_in_json = true;
} else if (arg == "--unknown-json") {
opts.skip_unexpected_fields_in_json = true;
- } else if(arg == "--no-prefix") {
+ } else if (arg == "--no-prefix") {
opts.prefixed_enums = false;
- } else if(arg == "--scoped-enums") {
+ } else if (arg == "--scoped-enums") {
opts.prefixed_enums = false;
opts.scoped_enums = true;
} else if (arg == "--no-union-value-namespacing") {
opts.union_value_namespacing = false;
- } else if(arg == "--gen-mutable") {
+ } else if (arg == "--gen-mutable") {
opts.mutable_buffer = true;
- } else if(arg == "--gen-name-strings") {
+ } else if (arg == "--gen-name-strings") {
opts.generate_name_strings = true;
- } else if(arg == "--gen-object-api") {
+ } else if (arg == "--gen-object-api") {
opts.generate_object_based_api = true;
} else if (arg == "--cpp-ptr-type") {
if (++argi >= argc) Error("missing type following" + arg, true);
} else if (arg == "--object-suffix") {
if (++argi >= argc) Error("missing suffix following" + arg, true);
opts.object_suffix = argv[argi];
- } else if(arg == "--gen-all") {
+ } else if (arg == "--gen-all") {
opts.generate_all = true;
opts.include_dependence_headers = false;
- } else if(arg == "--gen-includes") {
+ } else if (arg == "--gen-includes") {
// Deprecated, remove this option some time in the future.
printf("warning: --gen-includes is deprecated (it is now default)\n");
- } else if(arg == "--no-includes") {
+ } else if (arg == "--no-includes") {
opts.include_dependence_headers = false;
} else if (arg == "--gen-onefile") {
opts.one_file = true;
} else if (arg == "--raw-binary") {
raw_binary = true;
- } else if(arg == "--") { // Separator between text and binary inputs.
+ } else if (arg == "--") { // Separator between text and binary inputs.
binary_files_from = filenames.size();
- } else if(arg == "--proto") {
+ } else if (arg == "--proto") {
opts.proto_mode = true;
- } else if(arg == "--schema") {
+ } else if (arg == "--schema") {
schema_binary = true;
- } else if(arg == "-M") {
+ } else if (arg == "-M") {
print_make_rules = true;
- } else if(arg == "--version") {
+ } else if (arg == "--version") {
printf("flatc version %s\n", FLATC_VERSION);
exit(0);
- } else if(arg == "--grpc") {
+ } else if (arg == "--grpc") {
grpc_enabled = true;
- } else if(arg == "--bfbs-comments") {
+ } else if (arg == "--bfbs-comments") {
opts.binary_schema_comments = true;
- } else if(arg == "--no-fb-import") {
+ } else if (arg == "--no-fb-import") {
opts.skip_flatbuffers_import = true;
- } else if(arg == "--no-ts-reexport") {
+ } else if (arg == "--no-ts-reexport") {
opts.reexport_ts_modules = false;
- } else if(arg == "--reflect-types") {
+ } else if (arg == "--reflect-types") {
opts.mini_reflect = IDLOptions::kTypes;
- } else if(arg == "--reflect-names") {
+ } else if (arg == "--reflect-names") {
opts.mini_reflect = IDLOptions::kTypesAndNames;
} else {
for (size_t i = 0; i < params_.num_generators; ++i) {
}
}
Error("unknown commandline argument: " + arg, true);
- found:;
+ found:;
}
} else {
filenames.push_back(flatbuffers::PosixPath(argv[argi]));
std::unique_ptr<flatbuffers::Parser> parser(new flatbuffers::Parser(opts));
- for (auto file_it = filenames.begin();
- file_it != filenames.end();
- ++file_it) {
+ for (auto file_it = filenames.begin(); file_it != filenames.end();
+ ++file_it) {
auto &filename = *file_it;
std::string contents;
if (!flatbuffers::LoadFile(filename.c_str(), true, &contents))
Error("unable to load file: " + filename);
- bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >=
- binary_files_from;
+ bool is_binary =
+ static_cast<size_t>(file_it - filenames.begin()) >= binary_files_from;
auto ext = flatbuffers::GetExtension(filename);
auto is_schema = ext == "fbs" || ext == "proto";
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
- reinterpret_cast<const uint8_t *>(contents.c_str()),
- contents.length());
+ reinterpret_cast<const uint8_t *>(contents.c_str()),
+ contents.length());
if (!raw_binary) {
// Generally reading binaries that do not correspond to the schema
// will crash, and sadly there's no way around that when the binary
// such an identifier, so by default we require them to match.
if (!parser->file_identifier_.length()) {
Error("current schema has no file_identifier: cannot test if \"" +
- filename +
- "\" matches the schema, use --raw-binary to read this file"
- " anyway.");
- } else if (!flatbuffers::BufferHasIdentifier(contents.c_str(),
- parser->file_identifier_.c_str())) {
- Error("binary \"" +
- filename +
- "\" does not have expected file_identifier \"" +
- parser->file_identifier_ +
- "\", use --raw-binary to read this file anyway.");
+ filename +
+ "\" matches the schema, use --raw-binary to read this file"
+ " anyway.");
+ } else if (!flatbuffers::BufferHasIdentifier(
+ contents.c_str(), parser->file_identifier_.c_str())) {
+ Error("binary \"" + filename +
+ "\" does not have expected file_identifier \"" +
+ parser->file_identifier_ +
+ "\", use --raw-binary to read this file anyway.");
}
}
} else {
if (!is_schema && !parser->builder_.GetSize()) {
// If a file doesn't end in .fbs, it must be json/binary. Ensure we
// didn't just parse a schema with a different extension.
- Error("input file is neither json nor a .fbs (schema) file: " +
- filename, true);
+ Error(
+ "input file is neither json nor a .fbs (schema) file: " + filename,
+ true);
}
if (is_schema && !conform_to_schema.empty()) {
auto err = parser->ConformTo(conform_parser);
}
}
- std::string filebase = flatbuffers::StripPath(
- flatbuffers::StripExtension(filename));
+ std::string filebase =
+ flatbuffers::StripPath(flatbuffers::StripExtension(filename));
for (size_t i = 0; i < params_.num_generators; ++i) {
parser->opts.lang = params_.generators[i].lang;
if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path);
if ((!params_.generators[i].schema_only || is_schema) &&
- !params_.generators[i].generate(*parser.get(), output_path, filebase)) {
+ !params_.generators[i].generate(*parser.get(), output_path,
+ filebase)) {
Error(std::string("Unable to generate ") +
- params_.generators[i].lang_name +
- " for " +
- filebase);
+ params_.generators[i].lang_name + " for " + filebase);
}
} else {
std::string make_rule = params_.generators[i].make_rule(
*parser.get(), output_path, filename);
if (!make_rule.empty())
- printf("%s\n", flatbuffers::WordWrap(
- make_rule, 80, " ", " \\").c_str());
+ printf("%s\n",
+ flatbuffers::WordWrap(make_rule, 80, " ", " \\").c_str());
}
if (grpc_enabled) {
if (params_.generators[i].generateGRPC != nullptr) {
if (!params_.generators[i].generateGRPC(*parser.get(), output_path,
- filebase)) {
+ filebase)) {
Error(std::string("Unable to generate GRPC interface for") +
params_.generators[i].lang_name);
}
} else {
- Warn(std::string("GRPC interface generator not implemented for ")
- + params_.generators[i].lang_name);
+ Warn(std::string("GRPC interface generator not implemented for ") +
+ params_.generators[i].lang_name);
}
}
}
static const char *g_program_name = nullptr;
static void Warn(const flatbuffers::FlatCompiler *flatc,
- const std::string &warn,
- bool show_exe_name) {
+ 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); }
printf("warning: %s\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);
- }
+ const std::string &err, bool usage, bool show_exe_name) {
+ if (show_exe_name) { printf("%s: ", g_program_name); }
printf("error: %s\n", err.c_str());
- if (usage) {
- printf("%s", flatc->GetUsageString(g_program_name).c_str());
- }
+ if (usage) { printf("%s", flatc->GetUsageString(g_program_name).c_str()); }
exit(1);
}
g_program_name = argv[0];
const flatbuffers::FlatCompiler::Generator generators[] = {
- { flatbuffers::GenerateBinary, "-b", "--binary", "binary", false,
- nullptr,
+ { flatbuffers::GenerateBinary, "-b", "--binary", "binary", false, nullptr,
flatbuffers::IDLOptions::kBinary,
"Generate wire format binaries for any data definitions",
flatbuffers::BinaryMakeRule },
- { flatbuffers::GenerateTextFile, "-t", "--json", "text", false,
- nullptr,
+ { flatbuffers::GenerateTextFile, "-t", "--json", "text", false, nullptr,
flatbuffers::IDLOptions::kJson,
"Generate text output for any data definitions",
flatbuffers::TextMakeRule },
- { flatbuffers::GenerateCPP, "-c", "--cpp", "C++", true,
- flatbuffers::GenerateCppGRPC,
- flatbuffers::IDLOptions::kCpp,
- "Generate C++ headers for tables/structs",
- flatbuffers::CPPMakeRule },
- { flatbuffers::GenerateGo, "-g", "--go", "Go", true,
- flatbuffers::GenerateGoGRPC,
- flatbuffers::IDLOptions::kGo,
- "Generate Go files for tables/structs",
- flatbuffers::GeneralMakeRule },
- { flatbuffers::GenerateGeneral, "-j", "--java", "Java", true,
- flatbuffers::GenerateJavaGRPC,
- flatbuffers::IDLOptions::kJava,
+ { flatbuffers::GenerateCPP, "-c", "--cpp", "C++", true,
+ flatbuffers::GenerateCppGRPC, flatbuffers::IDLOptions::kCpp,
+ "Generate C++ headers for tables/structs", flatbuffers::CPPMakeRule },
+ { flatbuffers::GenerateGo, "-g", "--go", "Go", true,
+ flatbuffers::GenerateGoGRPC, flatbuffers::IDLOptions::kGo,
+ "Generate Go files for tables/structs", flatbuffers::GeneralMakeRule },
+ { flatbuffers::GenerateGeneral, "-j", "--java", "Java", true,
+ flatbuffers::GenerateJavaGRPC, flatbuffers::IDLOptions::kJava,
"Generate Java classes for tables/structs",
flatbuffers::GeneralMakeRule },
- { flatbuffers::GenerateJS, "-s", "--js", "JavaScript", true,
- nullptr,
+ { flatbuffers::GenerateJS, "-s", "--js", "JavaScript", true, nullptr,
flatbuffers::IDLOptions::kJs,
- "Generate JavaScript code for tables/structs",
- flatbuffers::JSMakeRule },
- { flatbuffers::GenerateJS, "-T", "--ts", "TypeScript", true,
- nullptr,
+ "Generate JavaScript code for tables/structs", flatbuffers::JSMakeRule },
+ { flatbuffers::GenerateJS, "-T", "--ts", "TypeScript", true, nullptr,
flatbuffers::IDLOptions::kTs,
- "Generate TypeScript code for tables/structs",
- flatbuffers::JSMakeRule },
- { flatbuffers::GenerateGeneral, "-n", "--csharp", "C#", true,
- nullptr,
+ "Generate TypeScript code for tables/structs", flatbuffers::JSMakeRule },
+ { flatbuffers::GenerateGeneral, "-n", "--csharp", "C#", true, nullptr,
flatbuffers::IDLOptions::kCSharp,
- "Generate C# classes for tables/structs",
- flatbuffers::GeneralMakeRule },
- { flatbuffers::GeneratePython, "-p", "--python", "Python", true,
- nullptr,
+ "Generate C# classes for tables/structs", flatbuffers::GeneralMakeRule },
+ { flatbuffers::GeneratePython, "-p", "--python", "Python", true, nullptr,
flatbuffers::IDLOptions::kPython,
"Generate Python files for tables/structs",
flatbuffers::GeneralMakeRule },
- { flatbuffers::GeneratePhp, nullptr, "--php", "PHP", true,
- nullptr,
- flatbuffers::IDLOptions::kPhp,
- "Generate PHP files for tables/structs",
- flatbuffers::GeneralMakeRule },
- { flatbuffers::GenerateJsonSchema, nullptr, "--jsonschema", "JsonSchema", true,
- nullptr,
- flatbuffers::IDLOptions::kJsonSchema,
- "Generate Json schema",
+ { flatbuffers::GeneratePhp, nullptr, "--php", "PHP", true, nullptr,
+ flatbuffers::IDLOptions::kPhp, "Generate PHP files for tables/structs",
flatbuffers::GeneralMakeRule },
+ { flatbuffers::GenerateJsonSchema, nullptr, "--jsonschema", "JsonSchema",
+ true, nullptr, flatbuffers::IDLOptions::kJsonSchema,
+ "Generate Json schema", flatbuffers::GeneralMakeRule },
};
flatbuffers::FlatCompiler::InitParams params;
* limitations under the License.
*/
+#include <stdio.h>
#include <iostream>
#include <sstream>
#include <string>
#include "flatbuffers/hash.h"
-#include <stdio.h>
-enum OutputFormat {
- kDecimal,
- kHexadecimal,
- kHexadecimal0x
-};
+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... [-- STRING...]\n", name);
printf("Available hashing algorithms:\n 32 bit:\n");
return 0;
}
- const char* hash_algorithm = argv[1];
+ const char *hash_algorithm = argv[1];
flatbuffers::NamedHashFunction<uint32_t>::HashFunction hash_function32 =
flatbuffers::FindHashFunction32(hash_algorithm);
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") output_format = kDecimal;
- else if (opt == "-x") output_format = kHexadecimal;
- else if (opt == "-0x") output_format = kHexadecimal0x;
- else if (opt == "-c") annotate = true;
- else if (opt == "--") escape_dash = true;
- else printf("Unrecognized argument: \"%s\"\n", arg);
+ if (opt == "-d")
+ output_format = kDecimal;
+ else if (opt == "-x")
+ output_format = kHexadecimal;
+ else if (opt == "-0x")
+ output_format = kHexadecimal0x;
+ else if (opt == "-c")
+ annotate = true;
+ else if (opt == "--")
+ escape_dash = true;
+ else
+ printf("Unrecognized argument: \"%s\"\n", arg);
} else {
std::stringstream ss;
if (output_format == kDecimal) {
else if (hash_function64)
ss << hash_function64(arg);
- if (annotate)
- ss << " /* \"" << arg << "\" */";
+ if (annotate) ss << " /* \"" << arg << "\" */";
ss << "\n";
}
return 0;
}
-
// independent from idl_parser, since this code is not needed for most clients
+#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#include "flatbuffers/code_generators.h"
namespace flatbuffers {
// Pedantic warning free version of toupper().
-inline char ToUpper(char c) {
- return static_cast<char>(::toupper(c));
-}
+inline char ToUpper(char c) { return static_cast<char>(::toupper(c)); }
static std::string GeneratedFileName(const std::string &path,
const std::string &file_name) {
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "", "::"),
cur_name_space_(nullptr) {
- const char *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
- };
+ const char *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);
}
}
for (auto it = parser_.included_files_.begin();
it != parser_.included_files_.end(); ++it) {
- if (it->second.empty())
- continue;
+ if (it->second.empty()) continue;
auto noext = flatbuffers::StripExtension(it->second);
auto basename = flatbuffers::StripPath(noext);
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); }
// Iterate through all definitions we haven't generate code for (enums,
// structs, and tables) and output them to a single file.
}
code_ += "";
- if (parser_.opts.include_dependence_headers) {
- GenIncludeDependencies();
- }
+ if (parser_.opts.include_dependence_headers) { GenIncludeDependencies(); }
assert(!cur_name_space_);
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);
+ auto qualified_name = cur_name_space_->GetFullyQualifiedName(name);
auto cpp_name = TranslateNameSpace(qualified_name);
code_.SetValue("STRUCT_NAME", name);
// The root datatype accessor:
code_ += "inline \\";
- code_ += "const {{CPP_NAME}} *{{NULLABLE_EXT}}Get{{STRUCT_NAME}}(const void *buf) {";
+ code_ +=
+ "const {{CPP_NAME}} *{{NULLABLE_EXT}}Get{{STRUCT_NAME}}(const void "
+ "*buf) {";
code_ += " return flatbuffers::GetRoot<{{CPP_NAME}}>(buf);";
code_ += "}";
code_ += "";
// Return a C++ type from the table in idl.h
std::string GenTypeBasic(const Type &type, bool user_facing_type) const {
static const char *ctypename[] = {
+ // clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
#CTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
+ // clang-format on
};
if (user_facing_type) {
if (type.enum_def) return WrapInNameSpace(*type.enum_def);
}
case BASE_TYPE_UNION:
// fall through
- default: {
- return "void";
- }
+ default: { return "void"; }
}
}
return parser_.opts.gen_nullable ? " _Nullable " : "";
}
- 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;
+ 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;
}
const std::string &PtrType(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 : parser_.opts.cpp_object_api_string_type;
- if (ret.empty()) {
- return "std::string";
- }
+ if (ret.empty()) { return "std::string"; }
return ret;
}
}
case BASE_TYPE_VECTOR: {
const auto type_name = GenTypeNative(type.VectorType(), true, field);
- if (type.struct_def && type.struct_def->attributes.Lookup("native_custom_alloc")) {
- auto native_custom_alloc = type.struct_def->attributes.Lookup("native_custom_alloc");
- return "std::vector<" + type_name + "," + native_custom_alloc->constant + "<" + type_name + ">>";
- } else
+ if (type.struct_def &&
+ type.struct_def->attributes.Lookup("native_custom_alloc")) {
+ auto native_custom_alloc =
+ type.struct_def->attributes.Lookup("native_custom_alloc");
+ return "std::vector<" + type_name + "," +
+ native_custom_alloc->constant + "<" + type_name + ">>";
+ } else
return "std::vector<" + type_name + ">";
}
case BASE_TYPE_STRUCT: {
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) {
return type_name;
} else {
return GenTypeNativePtr(type_name, &field, false);
}
} else {
- return GenTypeNativePtr(NativeName(type_name, type.struct_def, parser_.opts),
- &field, false);
+ return GenTypeNativePtr(
+ NativeName(type_name, type.struct_def, parser_.opts), &field,
+ false);
}
}
case BASE_TYPE_UNION: {
return type.enum_def->name + "Union";
}
- default: {
- return GenTypeBasic(type, true);
- }
+ default: { return GenTypeBasic(type, true); }
}
}
bool native_type = false) {
if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
auto name = actual_type ? ev.union_type.struct_def->name : Name(ev);
- return wrap
- ? WrapInNameSpace(ev.union_type.struct_def->defined_namespace, name)
- : name;
+ return wrap ? WrapInNameSpace(ev.union_type.struct_def->defined_namespace,
+ name)
+ : name;
} else if (ev.union_type.base_type == BASE_TYPE_STRING) {
- return actual_type
- ? (native_type ? "std::string" : "flatbuffers::String")
- : Name(ev);
+ return actual_type ? (native_type ? "std::string" : "flatbuffers::String")
+ : Name(ev);
} else {
assert(false);
return Name(ev);
"const flatbuffers::Vector<uint8_t> *types)";
}
- std::string UnionUnPackSignature(const EnumDef &enum_def,
- bool inclass) {
- return (inclass ? "static " : "") +
- std::string("void *") +
+ 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)";
(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) +
- "(flatbuffers::FlatBufferBuilder &_fbb, const " +
+ Name(struct_def) + "(flatbuffers::FlatBufferBuilder &_fbb, const " +
NativeName(Name(struct_def), &struct_def, opts) +
" *_o, const flatbuffers::rehasher_function_t *_rehasher" +
(predecl ? " = nullptr" : "") + ")";
}
- 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(flatbuffers::FlatBufferBuilder &_fbb, " +
- "const " + NativeName(Name(struct_def), &struct_def, opts) + "* _o, " +
+ 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(flatbuffers::FlatBufferBuilder &_fbb, " + "const " +
+ NativeName(Name(struct_def), &struct_def, opts) + "* _o, " +
"const flatbuffers::rehasher_function_t *_rehasher" +
(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) {
- return "void " + (inclass ? "" : Name(struct_def) + "::") +
- "UnPackTo(" + NativeName(Name(struct_def), &struct_def, 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";
}
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")
- : (enum_def->is_union ? "ST_UNION" : "ST_ENUM"));
- auto num_fields = struct_def
- ? struct_def->fields.vec.size()
- : enum_def->vals.vec.size();
+ code_.SetValue("SEQ_TYPE",
+ struct_def ? (struct_def->fixed ? "ST_STRUCT" : "ST_TABLE")
+ : (enum_def->is_union ? "ST_UNION" : "ST_ENUM"));
+ auto num_fields =
+ struct_def ? struct_def->fields.vec.size() : enum_def->vals.vec.size();
code_.SetValue("NUM_FIELDS", NumToString(num_fields));
std::vector<std::string> names;
std::vector<Type> types;
auto is_vector = type.base_type == BASE_TYPE_VECTOR;
auto bt = is_vector ? type.element : type.base_type;
auto et = IsScalar(bt) || bt == BASE_TYPE_STRING
- ? bt - BASE_TYPE_UTYPE + ET_UTYPE
- : ET_SEQUENCE;
+ ? bt - BASE_TYPE_UTYPE + ET_UTYPE
+ : ET_SEQUENCE;
int ref_idx = -1;
- std::string ref_name = type.struct_def
- ? WrapInNameSpace(*type.struct_def)
- : type.enum_def
- ? WrapInNameSpace(*type.enum_def)
- : "";
+ std::string ref_name =
+ type.struct_def
+ ? WrapInNameSpace(*type.struct_def)
+ : type.enum_def ? WrapInNameSpace(*type.enum_def) : "";
if (!ref_name.empty()) {
auto rit = type_refs.begin();
for (; rit != type_refs.end(); ++rit) {
if (!vs.empty()) {
code_ += " static const int32_t values[] = { {{VALUES}} };";
}
- auto has_names = num_fields &&
- parser_.opts.mini_reflect == IDLOptions::kTypesAndNames;
+ auto has_names =
+ num_fields && parser_.opts.mini_reflect == IDLOptions::kTypesAndNames;
if (has_names) {
code_ += " static const char *names[] = {";
code_ += " {{NAMES}}";
code_ += " static flatbuffers::TypeTable tt = {";
code_ += std::string(" flatbuffers::{{SEQ_TYPE}}, {{NUM_FIELDS}}, ") +
(num_fields ? "type_codes, " : "nullptr, ") +
- (!type_refs.empty() ? "type_refs, ": "nullptr, " ) +
+ (!type_refs.empty() ? "type_refs, " : "nullptr, ") +
(!vs.empty() ? "values, " : "nullptr, ") +
(has_names ? "names" : "nullptr");
code_ += " };";
GenComment(enum_def.doc_comment);
code_ += GenEnumDecl(enum_def) + "\\";
- if (parser_.opts.scoped_enums)
- code_ += " : {{BASE_TYPE}}\\";
+ if (parser_.opts.scoped_enums) code_ += " : {{BASE_TYPE}}\\";
code_ += " {";
int64_t anyv = 0;
code_.SetValue("VALUE", NumToString(anyv));
code_ += "{{SEP}} {{KEY}} = {{VALUE}}\\";
} else { // MIN & MAX are useless for bit_flags
- code_.SetValue("KEY",GenEnumValDecl(enum_def, "MIN"));
+ code_.SetValue("KEY", GenEnumValDecl(enum_def, "MIN"));
code_.SetValue("VALUE", GenEnumValDecl(enum_def, minv->name));
code_ += "{{SEP}} {{KEY}} = {{VALUE}}\\";
- code_.SetValue("KEY",GenEnumValDecl(enum_def, "MAX"));
+ code_.SetValue("KEY", GenEnumValDecl(enum_def, "MAX"));
code_.SetValue("VALUE", GenEnumValDecl(enum_def, maxv->name));
code_ += "{{SEP}} {{KEY}} = {{VALUE}}\\";
}
// Generate an array of all enumeration values
auto num_fields = NumToString(enum_def.vals.vec.size());
- code_ += "inline {{ENUM_NAME}} (&EnumValues{{ENUM_NAME}}())[" + num_fields + "] {";
+ code_ += "inline {{ENUM_NAME}} (&EnumValues{{ENUM_NAME}}())[" + num_fields +
+ "] {";
code_ += " static {{ENUM_NAME}} values[] = {";
for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
const auto &ev = **it;
auto value = GetEnumValUse(enum_def, ev);
auto suffix = *it != enum_def.vals.vec.back() ? "," : "";
- code_ += " " + value + suffix;
+ code_ += " " + value + suffix;
}
code_ += " };";
code_ += " return values;";
for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
const auto &ev = **it;
- while (val++ != ev.value) {
- code_ += " \"\",";
- }
+ while (val++ != ev.value) { code_ += " \"\","; }
code_ += " \"" + Name(ev) + "\",";
}
code_ += " nullptr";
// Generate type traits for unions to map from a type to union enum value.
if (enum_def.is_union && !enum_def.uses_type_aliases) {
for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
- ++it) {
+ ++it) {
const auto &ev = **it;
if (it == enum_def.vals.vec.begin()) {
code_ += "template<typename T> struct {{ENUM_NAME}}Traits {";
- }
- else {
+ } else {
auto name = GetUnionElement(ev, true, true);
code_ += "template<> struct {{ENUM_NAME}}Traits<" + name + "> {";
}
// Generate a union type
code_.SetValue("NAME", Name(enum_def));
code_.SetValue("NONE",
- GetEnumValUse(enum_def, *enum_def.vals.Lookup("NONE")));
+ GetEnumValUse(enum_def, *enum_def.vals.Lookup("NONE")));
code_ += "struct {{NAME}}Union {";
code_ += " {{NAME}} type;";
code_ += " type({{NONE}}), value(nullptr)";
code_ += " { std::swap(type, u.type); std::swap(value, u.value); }";
code_ += " {{NAME}}Union(const {{NAME}}Union &) FLATBUFFERS_NOEXCEPT;";
- code_ += " {{NAME}}Union &operator=(const {{NAME}}Union &u) FLATBUFFERS_NOEXCEPT";
- code_ += " { {{NAME}}Union t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; }";
- code_ += " {{NAME}}Union &operator=({{NAME}}Union &&u) FLATBUFFERS_NOEXCEPT";
- code_ += " { std::swap(type, u.type); std::swap(value, u.value); return *this; }";
+ code_ +=
+ " {{NAME}}Union &operator=(const {{NAME}}Union &u) "
+ "FLATBUFFERS_NOEXCEPT";
+ code_ +=
+ " { {{NAME}}Union t(u); std::swap(type, t.type); std::swap(value, "
+ "t.value); return *this; }";
+ code_ +=
+ " {{NAME}}Union &operator=({{NAME}}Union &&u) FLATBUFFERS_NOEXCEPT";
+ code_ +=
+ " { std::swap(type, u.type); std::swap(value, u.value); return "
+ "*this; }";
code_ += " ~{{NAME}}Union() { Reset(); }";
code_ += "";
code_ += " void Reset();";
code_ += " template <typename T>";
code_ += " void Set(T&& val) {";
code_ += " Reset();";
- code_ += " type = {{NAME}}Traits<typename T::TableType>::enum_value;";
+ code_ +=
+ " type = {{NAME}}Traits<typename T::TableType>::enum_value;";
code_ += " if (type != {{NONE}}) {";
code_ += " value = new T(std::forward<T>(val));";
code_ += " }";
for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
const auto &ev = **it;
- if (!ev.value) {
- continue;
- }
+ if (!ev.value) { continue; }
const auto native_type =
NativeName(GetUnionElement(ev, true, true, true),
code_ += " const {{NATIVE_TYPE}} *As{{NATIVE_NAME}}() const {";
code_ += " return type == {{NATIVE_ID}} ?";
- code_ += " reinterpret_cast<const {{NATIVE_TYPE}} *>(value) : nullptr;";
+ code_ +=
+ " reinterpret_cast<const {{NATIVE_TYPE}} *>(value) : nullptr;";
code_ += " }";
}
code_ += "};";
code_ += " if (values->size() != types->size()) return false;";
code_ += " for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {";
code_ += " if (!Verify" + Name(enum_def) + "(";
- code_ += " verifier, values->Get(i), types->GetEnum<" + Name(enum_def) + ">(i))) {";
+ code_ += " verifier, values->Get(i), types->GetEnum<" +
+ Name(enum_def) + ">(i))) {";
code_ += " return false;";
code_ += " }";
code_ += " }";
for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
const auto &ev = **it;
- if (!ev.value) {
- continue;
- }
+ if (!ev.value) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
code_.SetValue("TYPE", GetUnionElement(ev, true, true));
for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
auto &ev = **it;
- if (!ev.value) {
- continue;
- }
+ if (!ev.value) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
- code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, parser_.opts));
+ code_.SetValue("TYPE",
+ NativeName(GetUnionElement(ev, true, true, true),
+ ev.union_type.struct_def, parser_.opts));
code_.SetValue("NAME", GetUnionElement(ev, false, true));
code_ += " case {{LABEL}}: {";
code_ += " auto ptr = reinterpret_cast<const {{TYPE}} *>(value);";
code_ += "";
// Union copy constructor
- code_ += "inline {{ENUM_NAME}}Union::{{ENUM_NAME}}Union(const "
- "{{ENUM_NAME}}Union &u) FLATBUFFERS_NOEXCEPT : type(u.type), "
- "value(nullptr) {";
+ code_ +=
+ "inline {{ENUM_NAME}}Union::{{ENUM_NAME}}Union(const "
+ "{{ENUM_NAME}}Union &u) FLATBUFFERS_NOEXCEPT : type(u.type), "
+ "value(nullptr) {";
code_ += " switch (type) {";
for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
const auto &ev = **it;
- if (!ev.value) {
- continue;
- }
+ if (!ev.value) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
- code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, parser_.opts));
+ code_.SetValue("TYPE",
+ NativeName(GetUnionElement(ev, true, true, true),
+ ev.union_type.struct_def, parser_.opts));
code_ += " case {{LABEL}}: {";
bool copyable = true;
if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
}
}
if (copyable) {
- code_ += " value = new {{TYPE}}(*reinterpret_cast<{{TYPE}} *>"
- "(u.value));";
+ code_ +=
+ " value = new {{TYPE}}(*reinterpret_cast<{{TYPE}} *>"
+ "(u.value));";
} else {
code_ += " assert(false); // {{TYPE}} not copyable.";
}
// Union Reset() function.
code_.SetValue("NONE",
- GetEnumValUse(enum_def, *enum_def.vals.Lookup("NONE")));
+ GetEnumValUse(enum_def, *enum_def.vals.Lookup("NONE")));
code_ += "inline void {{ENUM_NAME}}Union::Reset() {";
code_ += " switch (type) {";
for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
const auto &ev = **it;
- if (!ev.value) {
- continue;
- }
+ if (!ev.value) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
- code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, parser_.opts));
+ code_.SetValue("TYPE",
+ NativeName(GetUnionElement(ev, true, true, true),
+ ev.union_type.struct_def, parser_.opts));
code_ += " case {{LABEL}}: {";
code_ += " auto ptr = reinterpret_cast<{{TYPE}} *>(value);";
code_ += " delete ptr;";
void GenFullyQualifiedNameGetter(const StructDef &struct_def,
const std::string &name) {
- if (!parser_.opts.generate_name_strings) {
- return;
- }
+ if (!parser_.opts.generate_name_strings) { return; }
auto fullname = struct_def.defined_namespace->GetFullyQualifiedName(name);
code_.SetValue("NAME", fullname);
code_.SetValue("CONSTEXPR", "FLATBUFFERS_CONSTEXPR");
auto ev = field.value.type.enum_def->ReverseLookup(
static_cast<int>(StringToInt(field.value.constant.c_str())), false);
if (ev) {
- return WrapInNameSpace(
- field.value.type.enum_def->defined_namespace,
- GetEnumValUse(*field.value.type.enum_def, *ev));
+ return WrapInNameSpace(field.value.type.enum_def->defined_namespace,
+ GetEnumValUse(*field.value.type.enum_def, *ev));
} else {
return GenUnderlyingCast(field, true, field.value.constant);
}
// 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) {
std::string initializer_list;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto cpp_type = field.attributes.Lookup("cpp_type");
// 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 += "(" + GetDefaultScalarValue(field) + ")";
} else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
}
}
} else if (cpp_type) {
- if (!initializer_list.empty()) {
- initializer_list += ",\n ";
- }
+ if (!initializer_list.empty()) { initializer_list += ",\n "; }
initializer_list += Name(field) + "(0)";
}
}
initializer_list = "\n : " + initializer_list;
}
- code_.SetValue("NATIVE_NAME", NativeName(Name(struct_def), &struct_def, parser_.opts));
+ code_.SetValue("NATIVE_NAME",
+ NativeName(Name(struct_def), &struct_def, parser_.opts));
code_.SetValue("INIT_LIST", initializer_list);
code_ += " {{NATIVE_NAME}}(){{INIT_LIST}} {";
code_ += " }";
}
- void GenOperatorNewDelete(const StructDef & struct_def) {
- if (auto native_custom_alloc = struct_def.attributes.Lookup("native_custom_alloc")) {
+ 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) {";
- code_ += " return " + native_custom_alloc->constant + "<{{NATIVE_NAME}}>().allocate(count / sizeof({{NATIVE_NAME}}));";
+ code_ += " return " + native_custom_alloc->constant +
+ "<{{NATIVE_NAME}}>().allocate(count / sizeof({{NATIVE_NAME}}));";
code_ += " }";
code_ += " inline void operator delete (void *ptr) {";
- code_ += " return " + native_custom_alloc->constant + "<{{NATIVE_NAME}}>().deallocate(static_cast<{{NATIVE_NAME}}*>(ptr),1);";
+ code_ += " return " + native_custom_alloc->constant +
+ "<{{NATIVE_NAME}}>().deallocate(static_cast<{{NATIVE_NAME}}*>("
+ "ptr),1);";
code_ += " }";
}
}
void GenNativeTable(const StructDef &struct_def) {
- const auto native_name = NativeName(Name(struct_def), &struct_def, parser_.opts);
+ const auto native_name =
+ NativeName(Name(struct_def), &struct_def, parser_.opts);
code_.SetValue("STRUCT_NAME", Name(struct_def));
code_.SetValue("NATIVE_NAME", native_name);
}
// 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.required ? "Required" : "");
case BASE_TYPE_UNION: {
code_.SetValue("ENUM_NAME", field.value.type.enum_def->name);
code_.SetValue("SUFFIX", UnionTypeFieldSuffix());
- code_ += "{{PRE}}Verify{{ENUM_NAME}}(verifier, {{NAME}}(), "
- "{{NAME}}{{SUFFIX}}())\\";
+ code_ +=
+ "{{PRE}}Verify{{ENUM_NAME}}(verifier, {{NAME}}(), "
+ "{{NAME}}{{SUFFIX}}())\\";
break;
}
case BASE_TYPE_STRUCT: {
}
case BASE_TYPE_UNION: {
code_.SetValue("ENUM_NAME", field.value.type.enum_def->name);
- code_ += "{{PRE}}Verify{{ENUM_NAME}}Vector(verifier, {{NAME}}(), {{NAME}}_type())\\";
+ code_ +=
+ "{{PRE}}Verify{{ENUM_NAME}}Vector(verifier, {{NAME}}(), "
+ "{{NAME}}_type())\\";
break;
}
- default:
- break;
+ default: break;
}
break;
}
- default: {
- break;
- }
+ default: { break; }
}
}
// Generate an accessor struct, builder structs & function for a table.
void GenTable(const StructDef &struct_def) {
- if (parser_.opts.generate_object_based_api) {
- GenNativeTable(struct_def);
- }
+ if (parser_.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); }
GenComment(struct_def.doc_comment);
code_.SetValue("STRUCT_NAME", Name(struct_def));
- code_ += "struct {{STRUCT_NAME}} FLATBUFFERS_FINAL_CLASS"
- " : private flatbuffers::Table {";
+ code_ +=
+ "struct {{STRUCT_NAME}} FLATBUFFERS_FINAL_CLASS"
+ " : private flatbuffers::Table {";
if (parser_.opts.generate_object_based_api) {
code_ += " typedef {{NATIVE_NAME}} NativeTableType;";
}
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();
GenComment(field.doc_comment, " ");
- code_.SetValue("FIELD_TYPE",
- GenTypeGet(field.value.type, " ", "const ", afterptr.c_str(), true));
+ code_.SetValue("FIELD_TYPE", GenTypeGet(field.value.type, " ", "const ",
+ afterptr.c_str(), true));
code_.SetValue("FIELD_VALUE", GenUnderlyingCast(field, true, call));
code_.SetValue("NULLABLE_EXT", NullableExtension());
if (field.value.type.base_type == BASE_TYPE_UNION) {
auto u = field.value.type.enum_def;
- code_ += " template<typename T> "
- "const T *{{NULLABLE_EXT}}{{FIELD_NAME}}_as() const;";
+ code_ +=
+ " template<typename T> "
+ "const T *{{NULLABLE_EXT}}{{FIELD_NAME}}_as() const;";
- for (auto u_it = u->vals.vec.begin();
- u_it != u->vals.vec.end(); ++u_it) {
+ for (auto u_it = u->vals.vec.begin(); u_it != u->vals.vec.end();
+ ++u_it) {
auto &ev = **u_it;
- if (ev.union_type.base_type == BASE_TYPE_NONE) {
- continue;
- }
+ if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
auto full_struct_name = GetUnionElement(ev, true, true);
// @TODO: Mby make this decisions more universal? How?
code_.SetValue("U_GET_TYPE", Name(field) + UnionTypeFieldSuffix());
- code_.SetValue("U_ELEMENT_TYPE", WrapInNameSpace(
- u->defined_namespace, GetEnumValUse(*u, ev)));
+ code_.SetValue(
+ "U_ELEMENT_TYPE",
+ WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev)));
code_.SetValue("U_FIELD_TYPE", "const " + full_struct_name + " *");
- code_.SetValue("U_FIELD_NAME",
- Name(field) + "_as_" + Name(ev));
+ code_.SetValue("U_FIELD_NAME", Name(field) + "_as_" + Name(ev));
code_.SetValue("U_NULLABLE", NullableExtension());
// `const Type *union_name_asType() const` accessor.
code_ += " {{U_FIELD_TYPE}}{{U_NULLABLE}}{{U_FIELD_NAME}}() const {";
- code_ += " return {{U_GET_TYPE}}() == {{U_ELEMENT_TYPE}} ? "
- "static_cast<{{U_FIELD_TYPE}}>({{FIELD_NAME}}()) "
- ": nullptr;";
+ code_ +=
+ " return {{U_GET_TYPE}}() == {{U_ELEMENT_TYPE}} ? "
+ "static_cast<{{U_FIELD_TYPE}}>({{FIELD_NAME}}()) "
+ ": nullptr;";
code_ += " }";
}
}
code_.SetValue("OFFSET_NAME", offset_str);
code_.SetValue("FIELD_TYPE", GenTypeBasic(field.value.type, true));
code_.SetValue("FIELD_VALUE",
- GenUnderlyingCast(field, false, "_" + Name(field)));
+ GenUnderlyingCast(field, false, "_" + Name(field)));
code_.SetValue("DEFAULT_VALUE", GenDefaultConstant(field));
- code_ += " bool mutate_{{FIELD_NAME}}({{FIELD_TYPE}} "
- "_{{FIELD_NAME}}) {";
- code_ += " return {{SET_FN}}({{OFFSET_NAME}}, {{FIELD_VALUE}}, {{DEFAULT_VALUE}});";
+ code_ +=
+ " bool mutate_{{FIELD_NAME}}({{FIELD_TYPE}} "
+ "_{{FIELD_NAME}}) {";
+ code_ +=
+ " return {{SET_FN}}({{OFFSET_NAME}}, {{FIELD_VALUE}}, "
+ "{{DEFAULT_VALUE}});";
code_ += " }";
} else {
auto postptr = " *" + NullableExtension();
- auto type = GenTypeGet(field.value.type, " ", "", postptr.c_str(), true);
+ auto type =
+ GenTypeGet(field.value.type, " ", "", postptr.c_str(), true);
auto underlying = accessor + type + ">(" + offset_str + ")";
code_.SetValue("FIELD_TYPE", type);
code_.SetValue("FIELD_VALUE",
- GenUnderlyingCast(field, true, underlying));
+ GenUnderlyingCast(field, true, underlying));
code_ += " {{FIELD_TYPE}}mutable_{{FIELD_NAME}}() {";
code_ += " return {{FIELD_VALUE}};";
auto nested = field.attributes.Lookup("nested_flatbuffer");
if (nested) {
std::string qualified_name =
- parser_.current_namespace_->GetFullyQualifiedName(
- nested->constant);
+ parser_.current_namespace_->GetFullyQualifiedName(nested->constant);
auto nested_root = parser_.LookupStruct(qualified_name);
assert(nested_root); // Guaranteed to exist by parser.
(void)nested_root;
}
if (field.flexbuffer) {
- code_ += " flexbuffers::Reference {{FIELD_NAME}}_flexbuffer_root()"
- " const {";
+ code_ +=
+ " flexbuffers::Reference {{FIELD_NAME}}_flexbuffer_root()"
+ " const {";
code_ += " auto v = {{FIELD_NAME}}();";
code_ += " return flexbuffers::GetRoot(v->Data(), v->size());";
code_ += " }";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
- if (field.deprecated) {
- continue;
- }
+ if (field.deprecated) { continue; }
GenVerifyCall(field, " &&\n ");
}
if (parser_.opts.generate_object_based_api) {
// Generate the UnPack() pre declaration.
- code_ += " " + TableUnPackSignature(struct_def, true, parser_.opts) + ";";
- code_ += " " + TableUnPackToSignature(struct_def, true, parser_.opts) + ";";
+ code_ +=
+ " " + TableUnPackSignature(struct_def, true, parser_.opts) + ";";
+ code_ +=
+ " " + TableUnPackToSignature(struct_def, true, parser_.opts) + ";";
code_ += " " + TablePackSignature(struct_def, true, parser_.opts) + ";";
}
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
- if (field.deprecated ||
- field.value.type.base_type != BASE_TYPE_UNION) {
+ if (field.deprecated || field.value.type.base_type != BASE_TYPE_UNION) {
continue;
}
code_.SetValue("FIELD_NAME", Name(field));
- for (auto u_it = u->vals.vec.begin();
- u_it != u->vals.vec.end(); ++u_it) {
+ for (auto u_it = u->vals.vec.begin(); u_it != u->vals.vec.end(); ++u_it) {
auto &ev = **u_it;
- if (ev.union_type.base_type == BASE_TYPE_NONE) {
- continue;
- }
+ if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
auto full_struct_name = GetUnionElement(ev, true, true);
- code_.SetValue("U_ELEMENT_TYPE", WrapInNameSpace(
- u->defined_namespace, GetEnumValUse(*u, ev)));
+ code_.SetValue(
+ "U_ELEMENT_TYPE",
+ WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev)));
code_.SetValue("U_FIELD_TYPE", "const " + full_struct_name + " *");
code_.SetValue("U_ELEMENT_NAME", full_struct_name);
- code_.SetValue("U_FIELD_NAME",
- Name(field) + "_as_" + Name(ev));
+ code_.SetValue("U_FIELD_NAME", Name(field) + "_as_" + Name(ev));
// `template<> const T *union_name_as<T>() const` accessor.
- code_ += "template<> "
- "inline {{U_FIELD_TYPE}}{{STRUCT_NAME}}::{{FIELD_NAME}}_as"
- "<{{U_ELEMENT_NAME}}>() const {";
+ code_ +=
+ "template<> "
+ "inline {{U_FIELD_TYPE}}{{STRUCT_NAME}}::{{FIELD_NAME}}_as"
+ "<{{U_ELEMENT_NAME}}>() const {";
code_ += " return {{U_FIELD_NAME}}();";
code_ += "}";
code_ += "";
const bool is_scalar = IsScalar(field.value.type.base_type);
const bool is_string = field.value.type.base_type == BASE_TYPE_STRING;
const bool is_vector = field.value.type.base_type == BASE_TYPE_VECTOR;
- 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));
}
code_ += " void add_{{FIELD_NAME}}({{FIELD_TYPE}}{{FIELD_NAME}}) {";
- code_ += " fbb_.{{ADD_FN}}(\\";
+ code_ += " fbb_.{{ADD_FN}}(\\";
if (is_scalar) {
code_ += "{{ADD_OFFSET}}, {{ADD_NAME}}, {{ADD_VALUE}});";
} else {
}
// Builder constructor
- code_ += " explicit {{STRUCT_NAME}}Builder(flatbuffers::FlatBufferBuilder &_fbb)";
+ code_ +=
+ " explicit {{STRUCT_NAME}}Builder(flatbuffers::FlatBufferBuilder "
+ "&_fbb)";
code_ += " : fbb_(_fbb) {";
code_ += " start_ = fbb_.StartTable();";
code_ += " }";
// Assignment operator;
- code_ += " {{STRUCT_NAME}}Builder &operator="
- "(const {{STRUCT_NAME}}Builder &);";
+ code_ +=
+ " {{STRUCT_NAME}}Builder &operator="
+ "(const {{STRUCT_NAME}}Builder &);";
// Finish() function.
code_ += " flatbuffers::Offset<{{STRUCT_NAME}}> Finish() {";
// Generate a convenient CreateX function that uses the above builder
// to create a table in one go.
- code_ += "inline flatbuffers::Offset<{{STRUCT_NAME}}> "
- "Create{{STRUCT_NAME}}(";
+ code_ +=
+ "inline flatbuffers::Offset<{{STRUCT_NAME}}> "
+ "Create{{STRUCT_NAME}}(";
code_ += " flatbuffers::FlatBufferBuilder &_fbb\\";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
- if (!field.deprecated) {
- GenParam(field, false, ",\n ");
- }
+ if (!field.deprecated) { GenParam(field, false, ",\n "); }
}
code_ += ") {";
// Generate a CreateXDirect function with vector types as parameters
if (has_string_or_vector_fields) {
- code_ += "inline flatbuffers::Offset<{{STRUCT_NAME}}> "
- "Create{{STRUCT_NAME}}Direct(";
+ code_ +=
+ "inline flatbuffers::Offset<{{STRUCT_NAME}}> "
+ "Create{{STRUCT_NAME}}Direct(";
code_ += " flatbuffers::FlatBufferBuilder &_fbb\\";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
- if (!field.deprecated) {
- GenParam(field, true, ",\n ");
- }
+ if (!field.deprecated) { GenParam(field, true, ",\n "); }
}
// Need to call "Create" with the struct namespace.
- const auto qualified_create_name = struct_def.defined_namespace->GetFullyQualifiedName("Create");
+ const auto qualified_create_name =
+ struct_def.defined_namespace->GetFullyQualifiedName("Create");
code_.SetValue("CREATE_NAME", TranslateNameSpace(qualified_create_name));
code_ += ") {";
code_.SetValue("FIELD_NAME", Name(field));
if (field.value.type.base_type == BASE_TYPE_STRING) {
- code_ += ",\n {{FIELD_NAME}} ? "
- "_fbb.CreateString({{FIELD_NAME}}) : 0\\";
+ code_ +=
+ ",\n {{FIELD_NAME}} ? "
+ "_fbb.CreateString({{FIELD_NAME}}) : 0\\";
} else if (field.value.type.base_type == BASE_TYPE_VECTOR) {
auto type = GenTypeWire(field.value.type.VectorType(), "", false);
- code_ += ",\n {{FIELD_NAME}} ? "
- "_fbb.CreateVector<" + type + ">(*{{FIELD_NAME}}) : 0\\";
+ code_ +=
+ ",\n {{FIELD_NAME}} ? "
+ "_fbb.CreateVector<" +
+ type + ">(*{{FIELD_NAME}}) : 0\\";
} else {
code_ += ",\n {{FIELD_NAME}}\\";
}
return ptype + "(new " + name + "(*" + val + "))";
}
} else {
- const auto ptype = GenTypeNativePtr(NativeName(name, type.struct_def, parser_.opts),
- &afield, true);
+ const auto ptype = GenTypeNativePtr(
+ NativeName(name, type.struct_def, parser_.opts), &afield, true);
return ptype + "(" + val + "->UnPack(_resolver))";
}
}
case BASE_TYPE_UNION: {
- return GenUnionUnpackVal(afield,
- invector ? "->Get(_i)" : "",
- invector ? ("->GetEnum<" +
- type.enum_def->name +
- ">(_i)").c_str() : "");
+ return GenUnionUnpackVal(
+ afield, invector ? "->Get(_i)" : "",
+ invector ? ("->GetEnum<" + type.enum_def->name + ">(_i)").c_str()
+ : "");
}
default: {
return val;
indexing += "(" + field.value.type.enum_def->name + ")";
}
indexing += "_e->Get(_i)";
- if (field.value.type.element == BASE_TYPE_BOOL) {
- indexing += " != 0";
- }
+ if (field.value.type.element == BASE_TYPE_BOOL) { indexing += " != 0"; }
// Generate code that pushes data from _e to _o in the form:
// for (uoffset_t i = 0; i < _e->size(); ++i) {
if (field.value.type.element == BASE_TYPE_UTYPE) {
name = StripUnionType(Name(field));
}
- auto access = field.value.type.element == BASE_TYPE_UTYPE
- ? ".type"
- : (field.value.type.element == BASE_TYPE_UNION
- ? ".value"
- : "");
+ auto access =
+ field.value.type.element == BASE_TYPE_UTYPE
+ ? ".type"
+ : (field.value.type.element == BASE_TYPE_UNION ? ".value" : "");
code += "{ _o->" + name + ".resize(_e->size()); ";
code += "for (flatbuffers::uoffset_t _i = 0;";
code += " _i < _e->size(); _i++) { ";
code += "_o->" + name + "[_i]" + access + " = ";
- code += GenUnpackVal(field.value.type.VectorType(),
- indexing, true, field);
+ code +=
+ GenUnpackVal(field.value.type.VectorType(), indexing, true, field);
code += "; } }";
break;
}
}
if (field.attributes.Lookup("cpp_type")) {
auto type = GenTypeBasic(field.value.type, false);
- value = "_rehasher ? "
- "static_cast<" + type + ">((*_rehasher)(" + value + ")) : 0";
+ value =
+ "_rehasher ? "
+ "static_cast<" +
+ type + ">((*_rehasher)(" + value + ")) : 0";
}
std::string code;
// For optional fields, check to see if there actually is any data
// in _o->field before attempting to access it.
- if (!field.required) {
- code = value + ".empty() ? 0 : " + code;
- }
+ if (!field.required) { code = value + ".empty() ? 0 : " + code; }
break;
}
// Vector fields come in several flavours, of the forms:
case BASE_TYPE_STRUCT: {
if (IsStruct(vector_type)) {
auto native_type =
- field.value.type.struct_def->attributes.Lookup("native_type");
+ field.value.type.struct_def->attributes.Lookup("native_type");
if (native_type) {
code += "_fbb.CreateVectorOfNativeStructs<";
code += WrapInNameSpace(*vector_type.struct_def) + ">";
break;
}
case BASE_TYPE_UNION: {
- code += "_fbb.CreateVector<flatbuffers::"
- "Offset<void>>(" + value +
- ".size(), [](size_t i, _VectorArgs *__va) { "
- "return __va->_" + value +
- "[i].Pack(*__va->__fbb, __va->__rehasher); }, &_va)";
+ code +=
+ "_fbb.CreateVector<flatbuffers::"
+ "Offset<void>>(" +
+ value +
+ ".size(), [](size_t i, _VectorArgs *__va) { "
+ "return __va->_" +
+ value + "[i].Pack(*__va->__fbb, __va->__rehasher); }, &_va)";
break;
}
case BASE_TYPE_UTYPE: {
value = StripUnionType(value);
code += "_fbb.CreateVector<uint8_t>(" + value +
".size(), [](size_t i, _VectorArgs *__va) { "
- "return static_cast<uint8_t>(__va->_" + value +
- "[i].type); }, &_va)";
+ "return static_cast<uint8_t>(__va->_" +
+ value + "[i].type); }, &_va)";
break;
}
default: {
// For optional fields, check to see if there actually is any data
// in _o->field before attempting to access it.
- if (!field.required) {
- code = value + ".size() ? " + code + " : 0";
- }
+ if (!field.required) { code = value + ".size() ? " + code + " : 0"; }
break;
}
case BASE_TYPE_UNION: {
// Generate code for tables that needs to come after the regular definition.
void GenTablePost(const StructDef &struct_def) {
code_.SetValue("STRUCT_NAME", Name(struct_def));
- code_.SetValue("NATIVE_NAME", NativeName(Name(struct_def), &struct_def, parser_.opts));
+ code_.SetValue("NATIVE_NAME",
+ NativeName(Name(struct_def), &struct_def, parser_.opts));
if (parser_.opts.generate_object_based_api) {
// Generate the X::UnPack() method.
- code_ += "inline " + TableUnPackSignature(struct_def, false, parser_.opts) + " {";
+ code_ += "inline " +
+ TableUnPackSignature(struct_def, false, parser_.opts) + " {";
code_ += " auto _o = new {{NATIVE_NAME}}();";
code_ += " UnPackTo(_o, _resolver);";
code_ += " return _o;";
code_ += "}";
code_ += "";
- code_ += "inline " + TableUnPackToSignature(struct_def, false, parser_.opts) + " {";
+ code_ += "inline " +
+ TableUnPackToSignature(struct_def, false, parser_.opts) + " {";
code_ += " (void)_o;";
code_ += " (void)_resolver;";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
- if (field.deprecated) {
- continue;
- }
+ 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
// Generate the X::Pack member function that simply calls the global
// CreateX function.
- code_ += "inline " + TablePackSignature(struct_def, false, parser_.opts) + " {";
+ code_ += "inline " + TablePackSignature(struct_def, false, parser_.opts) +
+ " {";
code_ += " return Create{{STRUCT_NAME}}(_fbb, _o, _rehasher);";
code_ += "}";
code_ += "";
// Generate a CreateX method that works with an unpacked C++ object.
- code_ += "inline " + TableCreateSignature(struct_def, false, parser_.opts) + " {";
+ code_ += "inline " +
+ TableCreateSignature(struct_def, false, parser_.opts) + " {";
code_ += " (void)_rehasher;";
code_ += " (void)_o;";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
- if (field.deprecated) {
- continue;
- }
+ if (field.deprecated) { continue; }
code_ += " auto _" + Name(field) + " = " + GenCreateParam(field) + ";";
}
// Need to call "Create" with the struct namespace.
- const auto qualified_create_name = struct_def.defined_namespace->GetFullyQualifiedName("Create");
+ const auto qualified_create_name =
+ struct_def.defined_namespace->GetFullyQualifiedName("Create");
code_.SetValue("CREATE_NAME", TranslateNameSpace(qualified_create_name));
code_ += " return {{CREATE_NAME}}{{STRUCT_NAME}}(";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
- if (field.deprecated) {
- continue;
- }
+ if (field.deprecated) { continue; }
bool pass_by_address = false;
if (field.value.type.base_type == BASE_TYPE_STRUCT) {
if (IsStruct(field.value.type)) {
auto native_type =
field.value.type.struct_def->attributes.Lookup("native_type");
- if (native_type) {
- pass_by_address = true;
- }
+ if (native_type) { pass_by_address = true; }
}
}
static void PaddingDefinition(int bits, std::string *code_ptr, int *id) {
*code_ptr += " int" + NumToString(bits) + "_t padding" +
- NumToString((*id)++) + "__;";
+ NumToString((*id)++) + "__;";
}
static void PaddingInitializer(int bits, std::string *code_ptr, int *id) {
code_.SetValue("ALIGN", NumToString(struct_def.minalign));
code_.SetValue("STRUCT_NAME", Name(struct_def));
- code_ += "MANUALLY_ALIGNED_STRUCT({{ALIGN}}) "
- "{{STRUCT_NAME}} FLATBUFFERS_FINAL_CLASS {";
+ code_ +=
+ "MANUALLY_ALIGNED_STRUCT({{ALIGN}}) "
+ "{{STRUCT_NAME}} FLATBUFFERS_FINAL_CLASS {";
code_ += " private:";
int padding_id = 0;
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
code_.SetValue("FIELD_TYPE",
- GenTypeGet(field.value.type, " ", "", " ", false));
+ GenTypeGet(field.value.type, " ", "", " ", false));
code_.SetValue("FIELD_NAME", Name(field));
code_ += " {{FIELD_TYPE}}{{FIELD_NAME}}_;";
auto field_type = GenTypeGet(field.value.type, " ", "const ", " &", true);
auto is_scalar = IsScalar(field.value.type.base_type);
auto member = Name(field) + "_";
- auto value = is_scalar ? "flatbuffers::EndianScalar(" + member + ")"
- : member;
+ auto value =
+ is_scalar ? "flatbuffers::EndianScalar(" + member + ")" : member;
code_.SetValue("FIELD_NAME", Name(field));
code_.SetValue("FIELD_TYPE", field_type);
if (is_scalar) {
code_.SetValue("ARG", GenTypeBasic(field.value.type, true));
code_.SetValue("FIELD_VALUE",
- GenUnderlyingCast(field, false, "_" + Name(field)));
+ GenUnderlyingCast(field, false, "_" + Name(field)));
code_ += " void mutate_{{FIELD_NAME}}({{ARG}} _{{FIELD_NAME}}) {";
- code_ += " flatbuffers::WriteScalar(&{{FIELD_NAME}}_, "
- "{{FIELD_VALUE}});";
+ code_ +=
+ " flatbuffers::WriteScalar(&{{FIELD_NAME}}_, "
+ "{{FIELD_VALUE}});";
code_ += " }";
} else {
code_ += " {{FIELD_TYPE}}mutable_{{FIELD_NAME}}() {";
code_.SetValue("KEY_TYPE", type);
code_ += " int KeyCompareWithValue({{KEY_TYPE}} val) const {";
code_ += " const auto key = {{FIELD_NAME}}();";
- code_ += " return static_cast<int>(key > val) - static_cast<int>(key < val);";
+ code_ +=
+ " return static_cast<int>(key > val) - static_cast<int>(key < "
+ "val);";
code_ += " }";
}
}
// 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;
- }
+ 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,
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;
}
// independent from idl_parser, since this code is not needed for most clients
+#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#include "flatbuffers/code_generators.h"
namespace flatbuffers {
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()) + "]";
+ type.struct_def->name);
+ case BASE_TYPE_VECTOR: return "[" + GenType(type.VectorType()) + "]";
default:
- if (type.enum_def && !underlying) {
- return type.enum_def->defined_namespace->GetFullyQualifiedName(
- type.enum_def->name);
- } else {
- return kTypeNames[type.base_type];
- }
+ if (type.enum_def && !underlying) {
+ return type.enum_def->defined_namespace->GetFullyQualifiedName(
+ type.enum_def->name);
+ } else {
+ return kTypeNames[type.base_type];
+ }
}
}
auto &schema = *_schema;
schema += "namespace ";
for (auto it = name_space.components.begin();
- it != name_space.components.end(); ++it) {
+ it != name_space.components.end(); ++it) {
if (it != name_space.components.begin()) schema += ".";
schema += *it;
}
std::string schema;
schema += "// Generated from " + file_name + ".proto\n\n";
if (parser.opts.include_dependence_headers) {
+ // clang-format off
#ifdef FBS_GEN_INCLUDES // TODO: currently all in one file.
int num_includes = 0;
for (auto it = parser.included_files_.begin();
}
if (num_includes) schema += "\n";
#endif
+ // clang-format on
}
// Generate code for all the enum declarations.
const Namespace *last_namespace = nullptr;
for (auto enum_def_it = parser.enums_.vec.begin();
- enum_def_it != parser.enums_.vec.end(); ++enum_def_it) {
+ enum_def_it != parser.enums_.vec.end(); ++enum_def_it) {
EnumDef &enum_def = **enum_def_it;
GenNameSpace(*enum_def.defined_namespace, &schema, &last_namespace);
GenComment(enum_def.doc_comment, &schema, nullptr);
schema += "enum " + enum_def.name + " : ";
schema += GenType(enum_def.underlying_type, true) + " {\n";
- for (auto it = enum_def.vals.vec.begin();
- it != enum_def.vals.vec.end(); ++it) {
+ for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
+ ++it) {
auto &ev = **it;
GenComment(ev.doc_comment, &schema, nullptr, " ");
schema += " " + ev.name + " = " + NumToString(ev.value) + ",\n";
schema += "}\n\n";
}
// Generate code for all structs/tables.
- for (auto it = parser.structs_.vec.begin();
- it != parser.structs_.vec.end(); ++it) {
+ for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
+ ++it) {
StructDef &struct_def = **it;
GenNameSpace(*struct_def.defined_namespace, &schema, &last_namespace);
GenComment(struct_def.doc_comment, &schema, nullptr);
schema += "table " + struct_def.name + " {\n";
for (auto field_it = struct_def.fields.vec.begin();
- field_it != struct_def.fields.vec.end(); ++field_it) {
+ field_it != struct_def.fields.vec.end(); ++field_it) {
auto &field = **field_it;
if (field.value.type.base_type != BASE_TYPE_UTYPE) {
GenComment(field.doc_comment, &schema, nullptr, " ");
return schema;
}
-bool GenerateFBS(const Parser &parser,
- const std::string &path,
+bool GenerateFBS(const Parser &parser, const std::string &path,
const std::string &file_name) {
return SaveFile((path + file_name + ".fbs").c_str(),
GenerateFBS(parser, file_name), false);
}
} // namespace flatbuffers
-
// independent from idl_parser, since this code is not needed for most clients
+#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#include "flatbuffers/code_generators.h"
#if defined(FLATBUFFERS_CPP98_STL)
- #include <cctype>
+# include <cctype>
#endif // defined(FLATBUFFERS_CPP98_STL)
namespace flatbuffers {
CommentConfig comment_config;
};
-const LanguageParameters& GetLangParams(IDLOptions::Language lang) {
+const LanguageParameters &GetLangParams(IDLOptions::Language lang) {
static LanguageParameters language_parameters[] = {
{
- IDLOptions::kJava,
- false,
- ".java",
- "String",
- "boolean ",
- " {\n",
- "class ",
- " final ",
- "final ",
- "final class ",
- ";\n",
- "()",
- "",
- " extends ",
- "package ",
- ";",
- "",
- "_bb.order(ByteOrder.LITTLE_ENDIAN); ",
- "position()",
- "offset()",
- "",
- "",
- "",
- "import java.nio.*;\nimport java.lang.*;\nimport java.util.*;\nimport com.google.flatbuffers.*;\n",
- "\n@SuppressWarnings(\"unused\")\n",
- {
- "/**",
- " *",
- " */",
- },
+ IDLOptions::kJava,
+ false,
+ ".java",
+ "String",
+ "boolean ",
+ " {\n",
+ "class ",
+ " final ",
+ "final ",
+ "final class ",
+ ";\n",
+ "()",
+ "",
+ " extends ",
+ "package ",
+ ";",
+ "",
+ "_bb.order(ByteOrder.LITTLE_ENDIAN); ",
+ "position()",
+ "offset()",
+ "",
+ "",
+ "",
+ "import java.nio.*;\nimport java.lang.*;\nimport "
+ "java.util.*;\nimport com.google.flatbuffers.*;\n",
+ "\n@SuppressWarnings(\"unused\")\n",
+ {
+ "/**",
+ " *",
+ " */",
+ },
},
{
- IDLOptions::kCSharp,
- true,
- ".cs",
- "string",
- "bool ",
- "\n{\n",
- "struct ",
- " readonly ",
- "",
- "enum ",
- ",\n",
- " { get",
- "} ",
- " : ",
- "namespace ",
- "\n{",
- "\n}\n",
- "",
- "Position",
- "Offset",
- "__p.",
- "Table.",
- "?",
- "using global::System;\nusing global::FlatBuffers;\n\n",
- "",
- {
- nullptr,
- "///",
- nullptr,
- },
+ IDLOptions::kCSharp,
+ true,
+ ".cs",
+ "string",
+ "bool ",
+ "\n{\n",
+ "struct ",
+ " readonly ",
+ "",
+ "enum ",
+ ",\n",
+ " { get",
+ "} ",
+ " : ",
+ "namespace ",
+ "\n{",
+ "\n}\n",
+ "",
+ "Position",
+ "Offset",
+ "__p.",
+ "Table.",
+ "?",
+ "using global::System;\nusing global::FlatBuffers;\n\n",
+ "",
+ {
+ nullptr,
+ "///",
+ nullptr,
+ },
},
};
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "", "."),
lang_(GetLangParams(parser_.opts.lang)),
- cur_name_space_( nullptr ) {
- }
+ cur_name_space_(nullptr) {}
GeneralGenerator &operator=(const GeneralGenerator &);
bool generate() {
++it) {
std::string enumcode;
auto &enum_def = **it;
- if (!parser_.opts.one_file)
- cur_name_space_ = enum_def.defined_namespace;
+ if (!parser_.opts.one_file) cur_name_space_ = enum_def.defined_namespace;
GenEnum(enum_def, &enumcode);
if (parser_.opts.one_file) {
one_file_code += enumcode;
} else {
- if (!SaveType(enum_def.name, *enum_def.defined_namespace,
- enumcode, false)) return false;
+ if (!SaveType(enum_def.name, *enum_def.defined_namespace, enumcode,
+ false))
+ return false;
}
}
if (parser_.opts.one_file) {
one_file_code += declcode;
} else {
- if (!SaveType(struct_def.name, *struct_def.defined_namespace,
- declcode, true)) return false;
+ if (!SaveType(struct_def.name, *struct_def.defined_namespace, declcode,
+ true))
+ return false;
}
}
if (parser_.opts.one_file) {
- return SaveType(file_name_, *parser_.current_namespace_,
- one_file_code, true);
+ return SaveType(file_name_, *parser_.current_namespace_, one_file_code,
+ true);
}
return true;
}
// 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 std::string &classcode, bool needs_includes) {
if (!classcode.length()) return true;
std::string code;
if (lang_.language == IDLOptions::kCSharp) {
- code = "// <auto-generated>\n"
- "// " + std::string(FlatBuffersGeneratedWarning()) + "\n"
- "// </auto-generated>\n\n";
+ code =
+ "// <auto-generated>\n"
+ "// " +
+ std::string(FlatBuffersGeneratedWarning()) +
+ "\n"
+ "// </auto-generated>\n\n";
} else {
code = "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
}
return std::string() + (lang_.language == IDLOptions::kJava
? static_cast<char>(tolower(upper))
: upper);
-}
+ }
-std::string GenNullableAnnotation(const Type& t) {
- return lang_.language == IDLOptions::kJava
- && parser_.opts.gen_nullable
- && !IsScalar(DestinationType(t, true).base_type) ? " @Nullable ": "";
-}
+ std::string GenNullableAnnotation(const Type &t) {
+ return lang_.language == IDLOptions::kJava && parser_.opts.gen_nullable &&
+ !IsScalar(DestinationType(t, true).base_type)
+ ? " @Nullable "
+ : "";
+ }
-static bool IsEnum(const Type& type) {
- return type.enum_def != nullptr && IsInteger(type.base_type);
-}
+ static bool IsEnum(const Type &type) {
+ return type.enum_def != nullptr && IsInteger(type.base_type);
+ }
-std::string GenTypeBasic(const Type &type, bool enableLangOverrides) {
+ std::string GenTypeBasic(const Type &type, bool enableLangOverrides) {
+ // clang-format off
static const char *java_typename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
+ // clang-format on
- if (enableLangOverrides) {
- if (lang_.language == IDLOptions::kCSharp) {
- if (IsEnum(type)) return WrapInNameSpace(*type.enum_def);
- if (type.base_type == BASE_TYPE_STRUCT) {
+ if (enableLangOverrides) {
+ if (lang_.language == IDLOptions::kCSharp) {
+ if (IsEnum(type)) return WrapInNameSpace(*type.enum_def);
+ if (type.base_type == BASE_TYPE_STRUCT) {
return "Offset<" + WrapInNameSpace(*type.struct_def) + ">";
+ }
}
}
- }
- if (lang_.language == IDLOptions::kJava) {
- return java_typename[type.base_type];
- } else {
- assert(lang_.language == IDLOptions::kCSharp);
- return csharp_typename[type.base_type];
+ if (lang_.language == IDLOptions::kJava) {
+ return java_typename[type.base_type];
+ } else {
+ assert(lang_.language == IDLOptions::kCSharp);
+ return csharp_typename[type.base_type];
+ }
}
-}
-
-std::string GenTypeBasic(const Type &type) {
- return GenTypeBasic(type, true);
-}
-std::string GenTypePointer(const Type &type) {
- switch (type.base_type) {
- case BASE_TYPE_STRING:
- return lang_.string_type;
- case BASE_TYPE_VECTOR:
- return GenTypeGet(type.VectorType());
- case BASE_TYPE_STRUCT:
- return WrapInNameSpace(*type.struct_def);
- case BASE_TYPE_UNION:
- // Unions in C# use a generic Table-derived type for better type safety
- if (lang_.language == IDLOptions::kCSharp) return "TTable";
- // fall through
- default:
- return "Table";
+ std::string GenTypeBasic(const Type &type) {
+ return GenTypeBasic(type, true);
}
-}
-std::string GenTypeGet(const Type &type) {
- return IsScalar(type.base_type)
- ? GenTypeBasic(type)
- : GenTypePointer(type);
-}
+ std::string GenTypePointer(const Type &type) {
+ switch (type.base_type) {
+ case BASE_TYPE_STRING: return lang_.string_type;
+ case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
+ case BASE_TYPE_STRUCT: return WrapInNameSpace(*type.struct_def);
+ case BASE_TYPE_UNION:
+ // Unions in C# use a generic Table-derived type for better type safety
+ if (lang_.language == IDLOptions::kCSharp) return "TTable";
+ // fall through
+ default: return "Table";
+ }
+ }
-// 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) {
- if (lang_.language != IDLOptions::kJava) return type;
- 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_VECTOR:
- if (vectorelem)
- return DestinationType(type.VectorType(), vectorelem);
- // else fall thru
- default: return type;
+ std::string GenTypeGet(const Type &type) {
+ return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
}
-}
-std::string GenOffsetType(const StructDef &struct_def) {
- if(lang_.language == IDLOptions::kCSharp) {
- return "Offset<" + WrapInNameSpace(struct_def) + ">";
- } else {
- return "int";
+ // 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) {
+ if (lang_.language != IDLOptions::kJava) return type;
+ 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_VECTOR:
+ if (vectorelem) return DestinationType(type.VectorType(), vectorelem);
+ // else fall thru
+ default: return type;
+ }
}
-}
-std::string GenOffsetConstruct(const StructDef &struct_def,
- const std::string &variable_name)
-{
- if(lang_.language == IDLOptions::kCSharp) {
- return "new Offset<" + WrapInNameSpace(struct_def) + ">(" + variable_name +
- ")";
+ std::string GenOffsetType(const StructDef &struct_def) {
+ if (lang_.language == IDLOptions::kCSharp) {
+ return "Offset<" + WrapInNameSpace(struct_def) + ">";
+ } else {
+ return "int";
+ }
}
- return variable_name;
-}
-std::string GenVectorOffsetType() {
- if(lang_.language == IDLOptions::kCSharp) {
- return "VectorOffset";
- } else {
- return "int";
+ std::string GenOffsetConstruct(const StructDef &struct_def,
+ const std::string &variable_name) {
+ if (lang_.language == IDLOptions::kCSharp) {
+ return "new Offset<" + WrapInNameSpace(struct_def) + ">(" +
+ variable_name + ")";
+ }
+ return variable_name;
}
-}
-// Generate destination type name
-std::string GenTypeNameDest(const Type &type)
-{
- return GenTypeGet(DestinationType(type, true));
-}
+ std::string GenVectorOffsetType() {
+ if (lang_.language == IDLOptions::kCSharp) {
+ return "VectorOffset";
+ } else {
+ return "int";
+ }
+ }
-// Mask to turn serialized value into destination type value.
-std::string DestinationMask(const Type &type, bool vectorelem) {
- if (lang_.language != IDLOptions::kJava) return "";
- 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_VECTOR:
- if (vectorelem)
- return DestinationMask(type.VectorType(), vectorelem);
- // else fall thru
- default: return "";
+ // Generate destination type name
+ std::string GenTypeNameDest(const Type &type) {
+ return GenTypeGet(DestinationType(type, true));
}
-}
-// Casts necessary to correctly read serialized data
-std::string DestinationCast(const Type &type) {
- if (type.base_type == BASE_TYPE_VECTOR) {
- return DestinationCast(type.VectorType());
- } else {
- switch (lang_.language) {
- case IDLOptions::kJava:
- // Cast necessary to correctly read serialized unsigned values.
- if (type.base_type == BASE_TYPE_UINT) return "(long)";
- break;
-
- case IDLOptions::kCSharp:
- // Cast from raw integral types to enum.
- if (IsEnum(type)) return "(" + WrapInNameSpace(*type.enum_def) + ")";
- break;
-
- default:
- break;
+ // Mask to turn serialized value into destination type value.
+ std::string DestinationMask(const Type &type, bool vectorelem) {
+ if (lang_.language != IDLOptions::kJava) return "";
+ 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_VECTOR:
+ if (vectorelem) return DestinationMask(type.VectorType(), vectorelem);
+ // else fall thru
+ default: return "";
}
}
- return "";
-}
-// Cast statements for mutator method parameters.
-// 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. 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, bool castFromDest) {
- if (type.base_type == BASE_TYPE_VECTOR) {
- return SourceCast(type.VectorType(), castFromDest);
- } else {
- switch (lang_.language) {
- case IDLOptions::kJava:
- if (castFromDest) {
- if (type.base_type == BASE_TYPE_UINT) return "(int)";
- else if (type.base_type == BASE_TYPE_USHORT) return "(short)";
- else if (type.base_type == BASE_TYPE_UCHAR) return "(byte)";
- }
- break;
- case IDLOptions::kCSharp:
- if (IsEnum(type)) return "(" + GenTypeBasic(type, false) + ")";
- break;
- default:
- break;
+ // Casts necessary to correctly read serialized data
+ std::string DestinationCast(const Type &type) {
+ if (type.base_type == BASE_TYPE_VECTOR) {
+ return DestinationCast(type.VectorType());
+ } else {
+ switch (lang_.language) {
+ case IDLOptions::kJava:
+ // Cast necessary to correctly read serialized unsigned values.
+ if (type.base_type == BASE_TYPE_UINT) return "(long)";
+ break;
+
+ case IDLOptions::kCSharp:
+ // Cast from raw integral types to enum.
+ if (IsEnum(type)) return "(" + WrapInNameSpace(*type.enum_def) + ")";
+ break;
+
+ default: break;
+ }
}
+ return "";
}
- return "";
-}
-std::string SourceCast(const Type &type) {
- return SourceCast(type, true);
-}
+ // Cast statements for mutator method parameters.
+ // 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. 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, bool castFromDest) {
+ if (type.base_type == BASE_TYPE_VECTOR) {
+ return SourceCast(type.VectorType(), castFromDest);
+ } else {
+ switch (lang_.language) {
+ case IDLOptions::kJava:
+ if (castFromDest) {
+ if (type.base_type == BASE_TYPE_UINT)
+ return "(int)";
+ else if (type.base_type == BASE_TYPE_USHORT)
+ return "(short)";
+ else if (type.base_type == BASE_TYPE_UCHAR)
+ return "(byte)";
+ }
+ break;
+ case IDLOptions::kCSharp:
+ if (IsEnum(type)) return "(" + GenTypeBasic(type, false) + ")";
+ break;
+ default: break;
+ }
+ }
+ return "";
+ }
-std::string SourceCastBasic(const Type &type, bool castFromDest) {
- return IsScalar(type.base_type) ? SourceCast(type, castFromDest) : "";
-}
+ std::string SourceCast(const Type &type) { return SourceCast(type, true); }
-std::string SourceCastBasic(const Type &type) {
- return SourceCastBasic(type, true);
-}
+ std::string SourceCastBasic(const Type &type, bool castFromDest) {
+ return IsScalar(type.base_type) ? SourceCast(type, castFromDest) : "";
+ }
+ std::string SourceCastBasic(const Type &type) {
+ return SourceCastBasic(type, true);
+ }
-std::string GenEnumDefaultValue(const Value &value) {
- auto enum_def = value.type.enum_def;
- auto vec = enum_def->vals.vec;
- auto default_value = StringToInt(value.constant.c_str());
+ std::string GenEnumDefaultValue(const Value &value) {
+ auto enum_def = value.type.enum_def;
+ auto vec = enum_def->vals.vec;
+ auto default_value = StringToInt(value.constant.c_str());
- auto result = value.constant;
- for (auto it = vec.begin(); it != vec.end(); ++it) {
- auto enum_val = **it;
- if (enum_val.value == default_value) {
- result = WrapInNameSpace(*enum_def) + "." + enum_val.name;
- break;
+ auto result = value.constant;
+ for (auto it = vec.begin(); it != vec.end(); ++it) {
+ auto enum_val = **it;
+ if (enum_val.value == default_value) {
+ result = WrapInNameSpace(*enum_def) + "." + enum_val.name;
+ break;
+ }
}
- }
- return result;
-}
+ return result;
+ }
-std::string GenDefaultValue(const Value &value, bool enableLangOverrides) {
- if (enableLangOverrides) {
- // handles both enum case and vector of enum case
- if (lang_.language == IDLOptions::kCSharp &&
- value.type.enum_def != nullptr &&
- value.type.base_type != BASE_TYPE_UNION) {
- return GenEnumDefaultValue(value);
+ std::string GenDefaultValue(const Value &value, bool enableLangOverrides) {
+ if (enableLangOverrides) {
+ // handles both enum case and vector of enum case
+ if (lang_.language == IDLOptions::kCSharp &&
+ value.type.enum_def != nullptr &&
+ value.type.base_type != BASE_TYPE_UNION) {
+ return GenEnumDefaultValue(value);
+ }
}
- }
- auto longSuffix = lang_.language == IDLOptions::kJava ? "L" : "";
- switch (value.type.base_type) {
- case BASE_TYPE_FLOAT: return value.constant + "f";
- case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
- case BASE_TYPE_ULONG:
- {
- if (lang_.language != IDLOptions::kJava)
- return value.constant;
- // Converts the ulong into its bits signed equivalent
- uint64_t defaultValue = StringToUInt(value.constant.c_str());
- return NumToString(static_cast<int64_t>(defaultValue)) + longSuffix;
+ auto longSuffix = lang_.language == IDLOptions::kJava ? "L" : "";
+ switch (value.type.base_type) {
+ case BASE_TYPE_FLOAT: return value.constant + "f";
+ case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
+ case BASE_TYPE_ULONG: {
+ if (lang_.language != IDLOptions::kJava) return value.constant;
+ // Converts the ulong into its bits signed equivalent
+ uint64_t defaultValue = StringToUInt(value.constant.c_str());
+ return NumToString(static_cast<int64_t>(defaultValue)) + longSuffix;
+ }
+ case BASE_TYPE_UINT:
+ case BASE_TYPE_LONG: return value.constant + longSuffix;
+ default: return value.constant;
}
- case BASE_TYPE_UINT:
- case BASE_TYPE_LONG: return value.constant + longSuffix;
- default: return value.constant;
}
-}
-std::string GenDefaultValue(const Value &value) {
- return GenDefaultValue(value, true);
-}
+ std::string GenDefaultValue(const Value &value) {
+ return GenDefaultValue(value, true);
+ }
-std::string GenDefaultValueBasic(const Value &value, bool enableLangOverrides) {
- if (!IsScalar(value.type.base_type)) {
- if (enableLangOverrides) {
- if (lang_.language == IDLOptions::kCSharp) {
- switch (value.type.base_type) {
- case BASE_TYPE_STRING:
- return "default(StringOffset)";
- case BASE_TYPE_STRUCT:
- return "default(Offset<" + WrapInNameSpace(*value.type.struct_def) +
- ">)";
- case BASE_TYPE_VECTOR:
- return "default(VectorOffset)";
- default:
- break;
+ std::string GenDefaultValueBasic(const Value &value,
+ bool enableLangOverrides) {
+ if (!IsScalar(value.type.base_type)) {
+ if (enableLangOverrides) {
+ if (lang_.language == IDLOptions::kCSharp) {
+ switch (value.type.base_type) {
+ case BASE_TYPE_STRING: return "default(StringOffset)";
+ case BASE_TYPE_STRUCT:
+ return "default(Offset<" +
+ WrapInNameSpace(*value.type.struct_def) + ">)";
+ case BASE_TYPE_VECTOR: return "default(VectorOffset)";
+ default: break;
+ }
}
}
+ return "0";
}
- return "0";
+ return GenDefaultValue(value, enableLangOverrides);
}
- return GenDefaultValue(value, enableLangOverrides);
-}
-
-std::string GenDefaultValueBasic(const Value &value) {
- return GenDefaultValueBasic(value, true);
-}
-void GenEnum(EnumDef &enum_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
- if (enum_def.generated) return;
-
- // Generate enum definitions of the form:
- // public static (final) int name = value;
- // In Java, we use ints rather than the Enum feature, because we want them
- // to map directly to how they're used in C/C++ and file formats.
- // That, and Java Enums are expensive, and not universally liked.
- GenComment(enum_def.doc_comment, code_ptr, &lang_.comment_config);
- code += std::string("public ") + lang_.enum_decl + enum_def.name;
- if (lang_.language == IDLOptions::kCSharp) {
- code += lang_.inheritance_marker +
- GenTypeBasic(enum_def.underlying_type, false);
- }
- code += lang_.open_curly;
- if (lang_.language == IDLOptions::kJava) {
- code += " private " + enum_def.name + "() { }\n";
- }
- for (auto it = enum_def.vals.vec.begin();
- it != enum_def.vals.vec.end();
- ++it) {
- auto &ev = **it;
- GenComment(ev.doc_comment, code_ptr, &lang_.comment_config, " ");
- if (lang_.language != IDLOptions::kCSharp) {
- code += " public static";
- code += lang_.const_decl;
- code += GenTypeBasic(enum_def.underlying_type, false);
- }
- code += " " + ev.name + " = ";
- code += NumToString(ev.value);
- code += lang_.enum_separator;
+ std::string GenDefaultValueBasic(const Value &value) {
+ return GenDefaultValueBasic(value, true);
}
- // Generate a generate string table for enum values.
- // We do not do that for C# where this functionality is native.
- if (lang_.language != IDLOptions::kCSharp) {
- // Problem is, if values are very sparse that could generate really big
- // tables. Ideally in that case we generate a map lookup instead, but for
- // the moment we simply don't output a table at all.
- auto range = enum_def.vals.vec.back()->value -
- enum_def.vals.vec.front()->value + 1;
- // Average distance between values above which we consider a table
- // "too sparse". Change at will.
- static const int kMaxSparseness = 5;
- if (range / static_cast<int64_t>(enum_def.vals.vec.size()) < kMaxSparseness) {
- code += "\n public static";
- code += lang_.const_decl;
- code += lang_.string_type;
- code += "[] names = { ";
- auto val = enum_def.vals.vec.front()->value;
- for (auto it = enum_def.vals.vec.begin();
- it != enum_def.vals.vec.end();
- ++it) {
- while (val++ != (*it)->value) code += "\"\", ";
- code += "\"" + (*it)->name + "\", ";
+ void GenEnum(EnumDef &enum_def, std::string *code_ptr) {
+ std::string &code = *code_ptr;
+ if (enum_def.generated) return;
+
+ // Generate enum definitions of the form:
+ // public static (final) int name = value;
+ // In Java, we use ints rather than the Enum feature, because we want them
+ // to map directly to how they're used in C/C++ and file formats.
+ // That, and Java Enums are expensive, and not universally liked.
+ GenComment(enum_def.doc_comment, code_ptr, &lang_.comment_config);
+ code += std::string("public ") + lang_.enum_decl + enum_def.name;
+ if (lang_.language == IDLOptions::kCSharp) {
+ code += lang_.inheritance_marker +
+ GenTypeBasic(enum_def.underlying_type, false);
+ }
+ code += lang_.open_curly;
+ if (lang_.language == IDLOptions::kJava) {
+ code += " private " + enum_def.name + "() { }\n";
+ }
+ for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
+ ++it) {
+ auto &ev = **it;
+ GenComment(ev.doc_comment, code_ptr, &lang_.comment_config, " ");
+ if (lang_.language != IDLOptions::kCSharp) {
+ code += " public static";
+ code += lang_.const_decl;
+ code += GenTypeBasic(enum_def.underlying_type, false);
}
- code += "};\n\n";
- code += " public static ";
- code += lang_.string_type;
- code += " " + MakeCamel("name", lang_.first_camel_upper);
- code += "(int e) { return names[e";
- if (enum_def.vals.vec.front()->value)
- code += " - " + enum_def.vals.vec.front()->name;
- code += "]; }\n";
+ code += " " + ev.name + " = ";
+ code += NumToString(ev.value);
+ code += lang_.enum_separator;
}
- }
- // Close the class
- code += "}";
- // Java does not need the closing semi-colon on class definitions.
- code += (lang_.language != IDLOptions::kJava) ? ";" : "";
- code += "\n\n";
-}
-
-// Returns the function name that is able to read a value of the given type.
-std::string GenGetter(const Type &type) {
- switch (type.base_type) {
- case BASE_TYPE_STRING: return lang_.accessor_prefix + "__string";
- case BASE_TYPE_STRUCT: return lang_.accessor_prefix + "__struct";
- case BASE_TYPE_UNION: return lang_.accessor_prefix + "__union";
- case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
- default: {
- std::string getter =
- lang_.accessor_prefix + "bb." + FunctionStart('G') + "et";
- if (type.base_type == BASE_TYPE_BOOL) {
- getter = "0!=" + getter;
- } else if (GenTypeBasic(type, false) != "byte") {
- getter += MakeCamel(GenTypeBasic(type, false));
+ // Generate a generate string table for enum values.
+ // We do not do that for C# where this functionality is native.
+ if (lang_.language != IDLOptions::kCSharp) {
+ // Problem is, if values are very sparse that could generate really big
+ // tables. Ideally in that case we generate a map lookup instead, but for
+ // the moment we simply don't output a table at all.
+ auto range = enum_def.vals.vec.back()->value -
+ enum_def.vals.vec.front()->value + 1;
+ // Average distance between values above which we consider a table
+ // "too sparse". Change at will.
+ static const int kMaxSparseness = 5;
+ if (range / static_cast<int64_t>(enum_def.vals.vec.size()) <
+ kMaxSparseness) {
+ code += "\n public static";
+ code += lang_.const_decl;
+ code += lang_.string_type;
+ code += "[] names = { ";
+ auto val = enum_def.vals.vec.front()->value;
+ for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
+ ++it) {
+ while (val++ != (*it)->value) code += "\"\", ";
+ code += "\"" + (*it)->name + "\", ";
+ }
+ code += "};\n\n";
+ code += " public static ";
+ code += lang_.string_type;
+ code += " " + MakeCamel("name", lang_.first_camel_upper);
+ code += "(int e) { return names[e";
+ if (enum_def.vals.vec.front()->value)
+ code += " - " + enum_def.vals.vec.front()->name;
+ code += "]; }\n";
}
- return getter;
}
- }
-}
-// 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) {
- auto type = key_field->value.type;
- auto dest_mask = DestinationMask(type, true);
- auto dest_cast = DestinationCast(type);
- auto getter = data_buffer + "." + FunctionStart('G') + "et";
- if (GenTypeBasic(type, false) != "byte") {
- getter += MakeCamel(GenTypeBasic(type, false));
+ // Close the class
+ code += "}";
+ // Java does not need the closing semi-colon on class definitions.
+ code += (lang_.language != IDLOptions::kJava) ? ";" : "";
+ code += "\n\n";
}
- getter = dest_cast + getter + "(" + GenOffsetGetter(key_field, num) + ")"
- + dest_mask;
- return getter;
-}
-// 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) {
- if (IsScalar(type.base_type)) {
- std::string setter =
- lang_.accessor_prefix + "bb." + FunctionStart('P') + "ut";
- if (GenTypeBasic(type, false) != "byte" &&
- type.base_type != BASE_TYPE_BOOL) {
- setter += MakeCamel(GenTypeBasic(type, false));
+ // Returns the function name that is able to read a value of the given type.
+ std::string GenGetter(const Type &type) {
+ switch (type.base_type) {
+ case BASE_TYPE_STRING: return lang_.accessor_prefix + "__string";
+ case BASE_TYPE_STRUCT: return lang_.accessor_prefix + "__struct";
+ case BASE_TYPE_UNION: return lang_.accessor_prefix + "__union";
+ case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
+ default: {
+ std::string getter =
+ lang_.accessor_prefix + "bb." + FunctionStart('G') + "et";
+ if (type.base_type == BASE_TYPE_BOOL) {
+ getter = "0!=" + getter;
+ } else if (GenTypeBasic(type, false) != "byte") {
+ getter += MakeCamel(GenTypeBasic(type, false));
+ }
+ return getter;
+ }
}
- return setter;
- } else {
- return "";
}
-}
-// Returns the method name for use with add/put calls.
-std::string GenMethod(const Type &type) {
- return IsScalar(type.base_type)
- ? MakeCamel(GenTypeBasic(type, false))
- : (IsStruct(type) ? "Struct" : "Offset");
-}
-
-// Recursively generate arguments for a constructor, to deal with nested
-// structs.
-void GenStructArgs(const StructDef &struct_def, std::string *code_ptr,
- const char *nameprefix) {
- std::string &code = *code_ptr;
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++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
- // a nested struct, prefix the name with the field name.
- GenStructArgs(*field.value.type.struct_def, code_ptr,
- (nameprefix + (field.name + "_")).c_str());
- } else {
- code += ", ";
- code += GenTypeBasic(DestinationType(field.value.type, false));
- code += " ";
- code += nameprefix;
- code += MakeCamel(field.name, lang_.first_camel_upper);
+ // 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) {
+ auto type = key_field->value.type;
+ auto dest_mask = DestinationMask(type, true);
+ auto dest_cast = DestinationCast(type);
+ auto getter = data_buffer + "." + FunctionStart('G') + "et";
+ if (GenTypeBasic(type, false) != "byte") {
+ getter += MakeCamel(GenTypeBasic(type, false));
}
+ getter = dest_cast + getter + "(" + GenOffsetGetter(key_field, num) + ")" +
+ dest_mask;
+ return getter;
}
-}
-// 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) {
- std::string &code = *code_ptr;
- code += " builder." + FunctionStart('P') + "rep(";
- 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;
- if (field.padding) {
- code += " builder." + FunctionStart('P') + "ad(";
- code += NumToString(field.padding) + ");\n";
- }
- if (IsStruct(field.value.type)) {
- GenStructBody(*field.value.type.struct_def, code_ptr,
- (nameprefix + (field.name + "_")).c_str());
+ // 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) {
+ if (IsScalar(type.base_type)) {
+ std::string setter =
+ lang_.accessor_prefix + "bb." + FunctionStart('P') + "ut";
+ if (GenTypeBasic(type, false) != "byte" &&
+ type.base_type != BASE_TYPE_BOOL) {
+ setter += MakeCamel(GenTypeBasic(type, false));
+ }
+ return setter;
} else {
- code += " builder." + FunctionStart('P') + "ut";
- code += GenMethod(field.value.type) + "(";
- code += SourceCast(field.value.type);
- auto argname = nameprefix + MakeCamel(field.name, lang_.first_camel_upper);
- code += argname;
- code += ");\n";
+ return "";
}
}
-}
-std::string GenByteBufferLength(const char *bb_name) {
- std::string bb_len = bb_name;
- if (lang_.language == IDLOptions::kCSharp) bb_len += ".Length";
- else bb_len += ".capacity()";
- return bb_len;
-}
-
-std::string GenOffsetGetter(flatbuffers::FieldDef *key_field,
- const char *num = nullptr) {
- std::string key_offset = "";
- key_offset += lang_.accessor_prefix_static + "__offset(" +
- NumToString(key_field->value.offset) + ", ";
- if (num) {
- key_offset += num;
- key_offset += (lang_.language == IDLOptions::kCSharp ?
- ".Value, builder.DataBuffer)" : ", _bb)");
- } else {
- key_offset += GenByteBufferLength("bb");
- key_offset += " - tableOffset, bb)";
+ // Returns the method name for use with add/put calls.
+ std::string GenMethod(const Type &type) {
+ return IsScalar(type.base_type) ? MakeCamel(GenTypeBasic(type, false))
+ : (IsStruct(type) ? "Struct" : "Offset");
}
- return key_offset;
-}
-std::string GenLookupKeyGetter(flatbuffers::FieldDef *key_field) {
- std::string key_getter = " ";
- key_getter += "int tableOffset = " + lang_.accessor_prefix_static;
- key_getter += "__indirect(vectorLocation + 4 * (start + middle)";
- key_getter += ", bb);\n ";
- if (key_field->value.type.base_type == BASE_TYPE_STRING) {
- key_getter += "int comp = " + lang_.accessor_prefix_static;
- key_getter += FunctionStart('C') + "ompareStrings(";
- key_getter += GenOffsetGetter(key_field);
- key_getter += ", byteKey, bb);\n";
- } else {
- auto get_val = GenGetterForLookupByKey(key_field, "bb");
- if (lang_.language == IDLOptions::kCSharp) {
- key_getter += "int comp = " + get_val + ".CompareTo(key);\n";
- } else {
- key_getter += GenTypeNameDest(key_field->value.type) + " val = ";
- key_getter += get_val + ";\n";
- key_getter += " int comp = val > key ? 1 : val < key ? -1 : 0;\n";
+ // Recursively generate arguments for a constructor, to deal with nested
+ // structs.
+ void GenStructArgs(const StructDef &struct_def, std::string *code_ptr,
+ const char *nameprefix) {
+ std::string &code = *code_ptr;
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++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
+ // a nested struct, prefix the name with the field name.
+ GenStructArgs(*field.value.type.struct_def, code_ptr,
+ (nameprefix + (field.name + "_")).c_str());
+ } else {
+ code += ", ";
+ code += GenTypeBasic(DestinationType(field.value.type, false));
+ code += " ";
+ code += nameprefix;
+ code += MakeCamel(field.name, lang_.first_camel_upper);
+ }
}
}
- return key_getter;
-}
-
-std::string GenKeyGetter(flatbuffers::FieldDef *key_field) {
- std::string key_getter = "";
- auto data_buffer = (lang_.language == IDLOptions::kCSharp) ?
- "builder.DataBuffer" : "_bb";
- if (key_field->value.type.base_type == BASE_TYPE_STRING) {
- if (lang_.language == IDLOptions::kJava)
- key_getter += " return ";
- key_getter += lang_.accessor_prefix_static;
- key_getter += FunctionStart('C') + "ompareStrings(";
- key_getter += GenOffsetGetter(key_field, "o1") + ", ";
- key_getter += GenOffsetGetter(key_field, "o2") + ", " + data_buffer + ")";
- if (lang_.language == IDLOptions::kJava)
- key_getter += ";";
- }
- else {
- auto field_getter = GenGetterForLookupByKey(key_field, data_buffer, "o1");
- if (lang_.language == IDLOptions::kCSharp) {
- key_getter += field_getter;
- field_getter = GenGetterForLookupByKey(key_field, data_buffer, "o2");
- key_getter += ".CompareTo(" + field_getter + ")";
- }
- else {
- key_getter += "\n " + GenTypeNameDest(key_field->value.type) + " val_1 = ";
- key_getter += field_getter + ";\n " + GenTypeNameDest(key_field->value.type);
- key_getter += " val_2 = ";
- field_getter = GenGetterForLookupByKey(key_field, data_buffer, "o2");
- key_getter += field_getter + ";\n";
- key_getter += " return val_1 > val_2 ? 1 : val_1 < val_2 ? -1 : 0;\n ";
+ // 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) {
+ std::string &code = *code_ptr;
+ code += " builder." + FunctionStart('P') + "rep(";
+ 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;
+ if (field.padding) {
+ code += " builder." + FunctionStart('P') + "ad(";
+ code += NumToString(field.padding) + ");\n";
+ }
+ if (IsStruct(field.value.type)) {
+ GenStructBody(*field.value.type.struct_def, code_ptr,
+ (nameprefix + (field.name + "_")).c_str());
+ } else {
+ code += " builder." + FunctionStart('P') + "ut";
+ code += GenMethod(field.value.type) + "(";
+ code += SourceCast(field.value.type);
+ auto argname =
+ nameprefix + MakeCamel(field.name, lang_.first_camel_upper);
+ code += argname;
+ code += ");\n";
+ }
}
}
- return key_getter;
-}
-void GenStruct(StructDef &struct_def, std::string *code_ptr) {
- if (struct_def.generated) return;
- std::string &code = *code_ptr;
-
- // Generate a struct accessor class, with methods of the form:
- // public type name() { return bb.getType(i + offset); }
- // or for tables of the form:
- // public type name() {
- // int o = __offset(offset); return o != 0 ? bb.getType(o + i) : default;
- // }
- GenComment(struct_def.doc_comment, code_ptr, &lang_.comment_config);
- code += "public ";
- if (lang_.language == IDLOptions::kCSharp &&
- struct_def.attributes.Lookup("csharp_partial")) {
- // generate a partial class for this C# struct/table
- code += "partial ";
- } else {
- code += lang_.unsubclassable_decl;
+ std::string GenByteBufferLength(const char *bb_name) {
+ std::string bb_len = bb_name;
+ if (lang_.language == IDLOptions::kCSharp)
+ bb_len += ".Length";
+ else
+ bb_len += ".capacity()";
+ return bb_len;
}
- code += lang_.accessor_type + struct_def.name;
- if (lang_.language == IDLOptions::kCSharp) {
- code += " : IFlatbufferObject";
- code += lang_.open_curly;
- code += " private ";
- code += struct_def.fixed ? "Struct" : "Table";
- code += " __p;\n";
- if (lang_.language == IDLOptions::kCSharp) {
- code += " public ByteBuffer ByteBuffer { get { return __p.bb; } }\n";
+ std::string GenOffsetGetter(flatbuffers::FieldDef *key_field,
+ const char *num = nullptr) {
+ std::string key_offset = "";
+ key_offset += lang_.accessor_prefix_static + "__offset(" +
+ NumToString(key_field->value.offset) + ", ";
+ if (num) {
+ key_offset += num;
+ key_offset +=
+ (lang_.language == IDLOptions::kCSharp ? ".Value, builder.DataBuffer)"
+ : ", _bb)");
+ } else {
+ key_offset += GenByteBufferLength("bb");
+ key_offset += " - tableOffset, bb)";
}
+ return key_offset;
+ }
- } else {
- code += lang_.inheritance_marker;
- code += struct_def.fixed ? "Struct" : "Table";
- code += lang_.open_curly;
+ std::string GenLookupKeyGetter(flatbuffers::FieldDef *key_field) {
+ std::string key_getter = " ";
+ key_getter += "int tableOffset = " + lang_.accessor_prefix_static;
+ key_getter += "__indirect(vectorLocation + 4 * (start + middle)";
+ key_getter += ", bb);\n ";
+ if (key_field->value.type.base_type == BASE_TYPE_STRING) {
+ key_getter += "int comp = " + lang_.accessor_prefix_static;
+ key_getter += FunctionStart('C') + "ompareStrings(";
+ key_getter += GenOffsetGetter(key_field);
+ key_getter += ", byteKey, bb);\n";
+ } else {
+ auto get_val = GenGetterForLookupByKey(key_field, "bb");
+ if (lang_.language == IDLOptions::kCSharp) {
+ key_getter += "int comp = " + get_val + ".CompareTo(key);\n";
+ } else {
+ key_getter += GenTypeNameDest(key_field->value.type) + " val = ";
+ key_getter += get_val + ";\n";
+ key_getter += " int comp = val > key ? 1 : val < key ? -1 : 0;\n";
+ }
+ }
+ return key_getter;
}
- if (!struct_def.fixed) {
- // Generate a special accessor for the table that when used as the root
- // of a FlatBuffer
- std::string method_name = FunctionStart('G') + "etRootAs" + struct_def.name;
- std::string method_signature = " public static " + struct_def.name + " " +
- method_name;
-
- // create convenience method that doesn't require an existing object
- code += method_signature + "(ByteBuffer _bb) ";
- code += "{ return " + method_name + "(_bb, new " + struct_def.name+ "()); }\n";
-
- // create method that allows object reuse
- code += method_signature + "(ByteBuffer _bb, " + struct_def.name + " obj) { ";
- code += lang_.set_bb_byteorder;
- code += "return (obj.__assign(_bb." + FunctionStart('G') + "etInt(_bb.";
- code += lang_.get_bb_position;
- code += ") + _bb.";
- code += lang_.get_bb_position;
- code += ", _bb)); }\n";
- if (parser_.root_struct_def_ == &struct_def) {
- if (parser_.file_identifier_.length()) {
- // Check if a buffer has the identifier.
- code += " public static ";
- code += lang_.bool_type + struct_def.name;
- code += "BufferHasIdentifier(ByteBuffer _bb) { return ";
- code += lang_.accessor_prefix_static + "__has_identifier(_bb, \"";
- code += parser_.file_identifier_;
- code += "\"); }\n";
+
+ std::string GenKeyGetter(flatbuffers::FieldDef *key_field) {
+ std::string key_getter = "";
+ auto data_buffer =
+ (lang_.language == IDLOptions::kCSharp) ? "builder.DataBuffer" : "_bb";
+ if (key_field->value.type.base_type == BASE_TYPE_STRING) {
+ if (lang_.language == IDLOptions::kJava) key_getter += " return ";
+ key_getter += lang_.accessor_prefix_static;
+ key_getter += FunctionStart('C') + "ompareStrings(";
+ key_getter += GenOffsetGetter(key_field, "o1") + ", ";
+ key_getter += GenOffsetGetter(key_field, "o2") + ", " + data_buffer + ")";
+ if (lang_.language == IDLOptions::kJava) key_getter += ";";
+ } else {
+ auto field_getter = GenGetterForLookupByKey(key_field, data_buffer, "o1");
+ if (lang_.language == IDLOptions::kCSharp) {
+ key_getter += field_getter;
+ field_getter = GenGetterForLookupByKey(key_field, data_buffer, "o2");
+ key_getter += ".CompareTo(" + field_getter + ")";
+ } else {
+ key_getter +=
+ "\n " + GenTypeNameDest(key_field->value.type) + " val_1 = ";
+ key_getter +=
+ field_getter + ";\n " + GenTypeNameDest(key_field->value.type);
+ key_getter += " val_2 = ";
+ field_getter = GenGetterForLookupByKey(key_field, data_buffer, "o2");
+ key_getter += field_getter + ";\n";
+ key_getter +=
+ " return val_1 > val_2 ? 1 : val_1 < val_2 ? -1 : 0;\n ";
}
}
+ return key_getter;
}
- // Generate the __init method that sets the field in a pre-existing
- // accessor object. This is to allow object reuse.
- code += " public void __init(int _i, ByteBuffer _bb) ";
- code += "{ " + lang_.accessor_prefix + "bb_pos = _i; ";
- code += lang_.accessor_prefix + "bb = _bb; }\n";
- code += " public " + struct_def.name + " __assign(int _i, ByteBuffer _bb) ";
- 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;
- if (field.deprecated) continue;
- GenComment(field.doc_comment, code_ptr, &lang_.comment_config, " ");
- std::string type_name = GenTypeGet(field.value.type);
- std::string type_name_dest = GenTypeNameDest(field.value.type);
- std::string conditional_cast = "";
- std::string optional = "";
+
+ void GenStruct(StructDef &struct_def, std::string *code_ptr) {
+ if (struct_def.generated) return;
+ std::string &code = *code_ptr;
+
+ // Generate a struct accessor class, with methods of the form:
+ // public type name() { return bb.getType(i + offset); }
+ // or for tables of the form:
+ // public type name() {
+ // int o = __offset(offset); return o != 0 ? bb.getType(o + i) : default;
+ // }
+ GenComment(struct_def.doc_comment, code_ptr, &lang_.comment_config);
+ code += "public ";
if (lang_.language == IDLOptions::kCSharp &&
- !struct_def.fixed &&
- (field.value.type.base_type == BASE_TYPE_STRUCT ||
- field.value.type.base_type == BASE_TYPE_UNION ||
- (field.value.type.base_type == BASE_TYPE_VECTOR &&
- field.value.type.element == BASE_TYPE_STRUCT))) {
- optional = lang_.optional_suffix;
- conditional_cast = "(" + type_name_dest + optional + ")";
+ struct_def.attributes.Lookup("csharp_partial")) {
+ // generate a partial class for this C# struct/table
+ code += "partial ";
+ } else {
+ code += lang_.unsubclassable_decl;
}
- std::string dest_mask = DestinationMask(field.value.type, true);
- std::string dest_cast = DestinationCast(field.value.type);
- std::string src_cast = SourceCast(field.value.type);
- std::string method_start = " public " + GenNullableAnnotation(field.value.type) +
- type_name_dest + optional + " " +
- MakeCamel(field.name, lang_.first_camel_upper);
- std::string obj = lang_.language == IDLOptions::kCSharp
- ? "(new " + type_name + "())"
- : "obj";
-
- // Most field accessors need to retrieve and test the field offset first,
- // this is the prefix code for that:
- auto offset_prefix = " { int o = " + lang_.accessor_prefix + "__offset(" +
- NumToString(field.value.offset) +
- "); return o != 0 ? ";
- // Generate the accessors that don't do object reuse.
- if (field.value.type.base_type == BASE_TYPE_STRUCT) {
- // Calls the accessor that takes an accessor object with a new object.
- if (lang_.language != IDLOptions::kCSharp) {
- code += method_start + "() { return ";
- code += MakeCamel(field.name, lang_.first_camel_upper);
- code += "(new ";
- code += type_name + "()); }\n";
- }
- } else if (field.value.type.base_type == BASE_TYPE_VECTOR &&
- field.value.type.element == BASE_TYPE_STRUCT) {
- // Accessors for vectors of structs also take accessor objects, this
- // generates a variant without that argument.
- if (lang_.language != IDLOptions::kCSharp) {
- code += method_start + "(int j) { return ";
- code += MakeCamel(field.name, lang_.first_camel_upper);
- code += "(new " + type_name + "(), j); }\n";
- }
- } else if (field.value.type.base_type == BASE_TYPE_UNION) {
+ code += lang_.accessor_type + struct_def.name;
+ if (lang_.language == IDLOptions::kCSharp) {
+ code += " : IFlatbufferObject";
+ code += lang_.open_curly;
+ code += " private ";
+ code += struct_def.fixed ? "Struct" : "Table";
+ code += " __p;\n";
+
if (lang_.language == IDLOptions::kCSharp) {
- // Union types in C# use generic Table-derived type for better type
- // safety.
- method_start += "<TTable>";
- type_name = type_name_dest;
+ code += " public ByteBuffer ByteBuffer { get { return __p.bb; } }\n";
}
+
+ } else {
+ code += lang_.inheritance_marker;
+ code += struct_def.fixed ? "Struct" : "Table";
+ code += lang_.open_curly;
}
- std::string getter = dest_cast + GenGetter(field.value.type);
- code += method_start;
- std::string default_cast = "";
- // only create default casts for c# scalars or vectors of scalars
- if (lang_.language == IDLOptions::kCSharp &&
- (IsScalar(field.value.type.base_type) ||
- (field.value.type.base_type == BASE_TYPE_VECTOR &&
- IsScalar(field.value.type.element)))) {
- // For scalars, default value will be returned by GetDefaultValue().
- // If the scalar is an enum, GetDefaultValue() returns an actual c# enum
- // that doesn't need to be casted. However, default values for enum
- // elements of vectors are integer literals ("0") and are still casted
- // for clarity.
- if (field.value.type.enum_def == nullptr ||
- field.value.type.base_type == BASE_TYPE_VECTOR) {
- default_cast = "(" + type_name_dest + ")";
+ if (!struct_def.fixed) {
+ // Generate a special accessor for the table that when used as the root
+ // of a FlatBuffer
+ std::string method_name =
+ FunctionStart('G') + "etRootAs" + struct_def.name;
+ std::string method_signature =
+ " public static " + struct_def.name + " " + method_name;
+
+ // create convenience method that doesn't require an existing object
+ code += method_signature + "(ByteBuffer _bb) ";
+ code += "{ return " + method_name + "(_bb, new " + struct_def.name +
+ "()); }\n";
+
+ // create method that allows object reuse
+ code +=
+ method_signature + "(ByteBuffer _bb, " + struct_def.name + " obj) { ";
+ code += lang_.set_bb_byteorder;
+ code += "return (obj.__assign(_bb." + FunctionStart('G') + "etInt(_bb.";
+ code += lang_.get_bb_position;
+ code += ") + _bb.";
+ code += lang_.get_bb_position;
+ code += ", _bb)); }\n";
+ if (parser_.root_struct_def_ == &struct_def) {
+ if (parser_.file_identifier_.length()) {
+ // Check if a buffer has the identifier.
+ code += " public static ";
+ code += lang_.bool_type + struct_def.name;
+ code += "BufferHasIdentifier(ByteBuffer _bb) { return ";
+ code += lang_.accessor_prefix_static + "__has_identifier(_bb, \"";
+ code += parser_.file_identifier_;
+ code += "\"); }\n";
+ }
}
}
- std::string member_suffix = "; ";
- if (IsScalar(field.value.type.base_type)) {
- code += lang_.getter_prefix;
- member_suffix += lang_.getter_suffix;
- if (struct_def.fixed) {
- code += " { return " + getter;
- code += "(" + lang_.accessor_prefix + "bb_pos + ";
- code += NumToString(field.value.offset) + ")";
- code += dest_mask;
- } else {
- code += offset_prefix + getter;
- code += "(o + " + lang_.accessor_prefix + "bb_pos)" + dest_mask;
- code += " : " + default_cast;
- code += GenDefaultValue(field.value);
+ // Generate the __init method that sets the field in a pre-existing
+ // accessor object. This is to allow object reuse.
+ code += " public void __init(int _i, ByteBuffer _bb) ";
+ code += "{ " + lang_.accessor_prefix + "bb_pos = _i; ";
+ code += lang_.accessor_prefix + "bb = _bb; }\n";
+ code +=
+ " public " + struct_def.name + " __assign(int _i, ByteBuffer _bb) ";
+ 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;
+ if (field.deprecated) continue;
+ GenComment(field.doc_comment, code_ptr, &lang_.comment_config, " ");
+ std::string type_name = GenTypeGet(field.value.type);
+ std::string type_name_dest = GenTypeNameDest(field.value.type);
+ std::string conditional_cast = "";
+ std::string optional = "";
+ if (lang_.language == IDLOptions::kCSharp && !struct_def.fixed &&
+ (field.value.type.base_type == BASE_TYPE_STRUCT ||
+ field.value.type.base_type == BASE_TYPE_UNION ||
+ (field.value.type.base_type == BASE_TYPE_VECTOR &&
+ field.value.type.element == BASE_TYPE_STRUCT))) {
+ optional = lang_.optional_suffix;
+ conditional_cast = "(" + type_name_dest + optional + ")";
}
- } else {
- switch (field.value.type.base_type) {
- case BASE_TYPE_STRUCT:
- if (lang_.language != IDLOptions::kCSharp) {
- code += "(" + type_name + " obj" + ")";
- } else {
+ std::string dest_mask = DestinationMask(field.value.type, true);
+ std::string dest_cast = DestinationCast(field.value.type);
+ std::string src_cast = SourceCast(field.value.type);
+ std::string method_start = " public " +
+ GenNullableAnnotation(field.value.type) +
+ type_name_dest + optional + " " +
+ MakeCamel(field.name, lang_.first_camel_upper);
+ std::string obj = lang_.language == IDLOptions::kCSharp
+ ? "(new " + type_name + "())"
+ : "obj";
+
+ // Most field accessors need to retrieve and test the field offset first,
+ // this is the prefix code for that:
+ auto offset_prefix = " { int o = " + lang_.accessor_prefix + "__offset(" +
+ NumToString(field.value.offset) +
+ "); return o != 0 ? ";
+ // Generate the accessors that don't do object reuse.
+ if (field.value.type.base_type == BASE_TYPE_STRUCT) {
+ // Calls the accessor that takes an accessor object with a new object.
+ if (lang_.language != IDLOptions::kCSharp) {
+ code += method_start + "() { return ";
+ code += MakeCamel(field.name, lang_.first_camel_upper);
+ code += "(new ";
+ code += type_name + "()); }\n";
+ }
+ } else if (field.value.type.base_type == BASE_TYPE_VECTOR &&
+ field.value.type.element == BASE_TYPE_STRUCT) {
+ // Accessors for vectors of structs also take accessor objects, this
+ // generates a variant without that argument.
+ if (lang_.language != IDLOptions::kCSharp) {
+ code += method_start + "(int j) { return ";
+ code += MakeCamel(field.name, lang_.first_camel_upper);
+ code += "(new " + type_name + "(), j); }\n";
+ }
+ } else if (field.value.type.base_type == BASE_TYPE_UNION) {
+ if (lang_.language == IDLOptions::kCSharp) {
+ // Union types in C# use generic Table-derived type for better type
+ // safety.
+ method_start += "<TTable>";
+ type_name = type_name_dest;
+ }
+ }
+ std::string getter = dest_cast + GenGetter(field.value.type);
+ code += method_start;
+ std::string default_cast = "";
+ // only create default casts for c# scalars or vectors of scalars
+ if (lang_.language == IDLOptions::kCSharp &&
+ (IsScalar(field.value.type.base_type) ||
+ (field.value.type.base_type == BASE_TYPE_VECTOR &&
+ IsScalar(field.value.type.element)))) {
+ // For scalars, default value will be returned by GetDefaultValue().
+ // If the scalar is an enum, GetDefaultValue() returns an actual c# enum
+ // that doesn't need to be casted. However, default values for enum
+ // elements of vectors are integer literals ("0") and are still casted
+ // for clarity.
+ if (field.value.type.enum_def == nullptr ||
+ field.value.type.base_type == BASE_TYPE_VECTOR) {
+ default_cast = "(" + type_name_dest + ")";
+ }
+ }
+ std::string member_suffix = "; ";
+ if (IsScalar(field.value.type.base_type)) {
+ code += lang_.getter_prefix;
+ member_suffix += lang_.getter_suffix;
+ if (struct_def.fixed) {
+ code += " { return " + getter;
+ code += "(" + lang_.accessor_prefix + "bb_pos + ";
+ code += NumToString(field.value.offset) + ")";
+ code += dest_mask;
+ } else {
+ code += offset_prefix + getter;
+ code += "(o + " + lang_.accessor_prefix + "bb_pos)" + dest_mask;
+ code += " : " + default_cast;
+ code += GenDefaultValue(field.value);
+ }
+ } else {
+ switch (field.value.type.base_type) {
+ case BASE_TYPE_STRUCT:
+ if (lang_.language != IDLOptions::kCSharp) {
+ code += "(" + type_name + " obj" + ")";
+ } else {
+ code += lang_.getter_prefix;
+ member_suffix += lang_.getter_suffix;
+ }
+ if (struct_def.fixed) {
+ code += " { return " + obj + ".__assign(" + lang_.accessor_prefix;
+ code += "bb_pos + " + NumToString(field.value.offset) + ", ";
+ code += lang_.accessor_prefix + "bb)";
+ } else {
+ code += offset_prefix + conditional_cast;
+ code += obj + ".__assign(";
+ code += field.value.type.struct_def->fixed
+ ? "o + " + lang_.accessor_prefix + "bb_pos"
+ : lang_.accessor_prefix + "__indirect(o + " +
+ lang_.accessor_prefix + "bb_pos)";
+ code += ", " + lang_.accessor_prefix + "bb) : null";
+ }
+ break;
+ case BASE_TYPE_STRING:
code += lang_.getter_prefix;
member_suffix += lang_.getter_suffix;
+ code += offset_prefix + getter + "(o + " + lang_.accessor_prefix;
+ code += "bb_pos) : null";
+ break;
+ case BASE_TYPE_VECTOR: {
+ auto vectortype = field.value.type.VectorType();
+ code += "(";
+ if (vectortype.base_type == BASE_TYPE_STRUCT) {
+ if (lang_.language != IDLOptions::kCSharp)
+ code += type_name + " obj, ";
+ getter = obj + ".__assign";
+ }
+ code += "int j)" + offset_prefix + conditional_cast + getter + "(";
+ auto index = lang_.accessor_prefix + "__vector(o) + j * " +
+ NumToString(InlineSize(vectortype));
+ if (vectortype.base_type == BASE_TYPE_STRUCT) {
+ code += vectortype.struct_def->fixed
+ ? index
+ : lang_.accessor_prefix + "__indirect(" + index + ")";
+ code += ", " + lang_.accessor_prefix + "bb";
+ } else {
+ code += index;
+ }
+ code += ")" + dest_mask + " : ";
+
+ code +=
+ field.value.type.element == BASE_TYPE_BOOL
+ ? "false"
+ : (IsScalar(field.value.type.element) ? default_cast + "0"
+ : "null");
+ break;
}
- if (struct_def.fixed) {
- code += " { return " + obj + ".__assign(" + lang_.accessor_prefix;
- code += "bb_pos + " + NumToString(field.value.offset) + ", ";
- code += lang_.accessor_prefix + "bb)";
- } else {
- code += offset_prefix + conditional_cast;
- code += obj + ".__assign(";
- code += field.value.type.struct_def->fixed
- ? "o + " + lang_.accessor_prefix + "bb_pos"
- : lang_.accessor_prefix + "__indirect(o + " +
- lang_.accessor_prefix + "bb_pos)";
- code += ", " + lang_.accessor_prefix + "bb) : null";
- }
- break;
- case BASE_TYPE_STRING:
- code += lang_.getter_prefix;
- member_suffix += lang_.getter_suffix;
- code += offset_prefix + getter + "(o + " + lang_.accessor_prefix;
- code += "bb_pos) : null";
- break;
- case BASE_TYPE_VECTOR: {
- auto vectortype = field.value.type.VectorType();
- code += "(";
- if (vectortype.base_type == BASE_TYPE_STRUCT) {
- if (lang_.language != IDLOptions::kCSharp)
- code += type_name + " obj, ";
- getter = obj + ".__assign";
- }
- code += "int j)" + offset_prefix + conditional_cast + getter +"(";
- auto index = lang_.accessor_prefix + "__vector(o) + j * " +
- NumToString(InlineSize(vectortype));
- if (vectortype.base_type == BASE_TYPE_STRUCT) {
- code += vectortype.struct_def->fixed
- ? index
- : lang_.accessor_prefix + "__indirect(" + index + ")";
- code += ", " + lang_.accessor_prefix + "bb";
- } else {
- code += index;
- }
- code += ")" + dest_mask + " : ";
-
- code += field.value.type.element == BASE_TYPE_BOOL ? "false" :
- (IsScalar(field.value.type.element) ? default_cast + "0" : "null");
- break;
+ case BASE_TYPE_UNION:
+ if (lang_.language == IDLOptions::kCSharp) {
+ code += "() where TTable : struct, IFlatbufferObject";
+ code += offset_prefix + "(TTable?)" + getter;
+ code += "<TTable>(o) : null";
+ } else {
+ code += "(" + type_name + " obj)" + offset_prefix + getter;
+ code += "(obj, o) : null";
+ }
+ break;
+ default: assert(0);
}
- case BASE_TYPE_UNION:
- if (lang_.language == IDLOptions::kCSharp) {
- code += "() where TTable : struct, IFlatbufferObject";
- code += offset_prefix + "(TTable?)" + getter;
- code += "<TTable>(o) : null";
- } else {
- code += "(" + type_name + " obj)" + offset_prefix + getter;
- code += "(obj, o) : null";
- }
- break;
- default:
- assert(0);
}
- }
- code += member_suffix;
- code += "}\n";
- if (field.value.type.base_type == BASE_TYPE_VECTOR) {
- code += " public int " + MakeCamel(field.name, lang_.first_camel_upper);
- code += "Length";
- code += lang_.getter_prefix;
- code += offset_prefix;
- code += lang_.accessor_prefix + "__vector_len(o) : 0; ";
- code += lang_.getter_suffix;
+ code += member_suffix;
code += "}\n";
- // 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;
- for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
- auto &key_field = **kit;
- if (key_field.key) {
- code += " public " + sd.name + lang_.optional_suffix + " ";
- code += MakeCamel(field.name, lang_.first_camel_upper) + "ByKey(";
- code += GenTypeNameDest(key_field.value.type) + " key)";
- code += offset_prefix;
- code += sd.name + ".__lookup_by_key(";
- code += lang_.accessor_prefix + "__vector(o), key, ";
- code += lang_.accessor_prefix + "bb) : null; ";
- code += "}\n";
- break;
+ if (field.value.type.base_type == BASE_TYPE_VECTOR) {
+ code +=
+ " public int " + MakeCamel(field.name, lang_.first_camel_upper);
+ code += "Length";
+ code += lang_.getter_prefix;
+ code += offset_prefix;
+ code += lang_.accessor_prefix + "__vector_len(o) : 0; ";
+ code += lang_.getter_suffix;
+ code += "}\n";
+ // 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;
+ for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
+ auto &key_field = **kit;
+ if (key_field.key) {
+ code += " public " + sd.name + lang_.optional_suffix + " ";
+ code += MakeCamel(field.name, lang_.first_camel_upper) + "ByKey(";
+ code += GenTypeNameDest(key_field.value.type) + " key)";
+ code += offset_prefix;
+ code += sd.name + ".__lookup_by_key(";
+ code += lang_.accessor_prefix + "__vector(o), key, ";
+ code += lang_.accessor_prefix + "bb) : null; ";
+ code += "}\n";
+ break;
+ }
}
}
}
- }
- // Generate a ByteBuffer accessor for strings & vectors of scalars.
- if ((field.value.type.base_type == BASE_TYPE_VECTOR &&
- IsScalar(field.value.type.VectorType().base_type)) ||
- field.value.type.base_type == BASE_TYPE_STRING) {
- switch (lang_.language) {
- case IDLOptions::kJava:
- code += " public ByteBuffer ";
- code += MakeCamel(field.name, lang_.first_camel_upper);
- code += "AsByteBuffer() { return ";
- code += lang_.accessor_prefix + "__vector_as_bytebuffer(";
- code += NumToString(field.value.offset) + ", ";
- code += NumToString(field.value.type.base_type == BASE_TYPE_STRING
- ? 1
- : InlineSize(field.value.type.VectorType()));
- code += "); }\n";
- break;
- case IDLOptions::kCSharp:
- code += " public ArraySegment<byte>? Get";
- code += MakeCamel(field.name, lang_.first_camel_upper);
- code += "Bytes() { return ";
- code += lang_.accessor_prefix + "__vector_as_arraysegment(";
- code += NumToString(field.value.offset);
- code += "); }\n";
- break;
- default:
- break;
+ // Generate a ByteBuffer accessor for strings & vectors of scalars.
+ if ((field.value.type.base_type == BASE_TYPE_VECTOR &&
+ IsScalar(field.value.type.VectorType().base_type)) ||
+ field.value.type.base_type == BASE_TYPE_STRING) {
+ switch (lang_.language) {
+ case IDLOptions::kJava:
+ code += " public ByteBuffer ";
+ code += MakeCamel(field.name, lang_.first_camel_upper);
+ code += "AsByteBuffer() { return ";
+ code += lang_.accessor_prefix + "__vector_as_bytebuffer(";
+ code += NumToString(field.value.offset) + ", ";
+ code +=
+ NumToString(field.value.type.base_type == BASE_TYPE_STRING
+ ? 1
+ : InlineSize(field.value.type.VectorType()));
+ code += "); }\n";
+ break;
+ case IDLOptions::kCSharp:
+ code += " public ArraySegment<byte>? Get";
+ code += MakeCamel(field.name, lang_.first_camel_upper);
+ code += "Bytes() { return ";
+ code += lang_.accessor_prefix + "__vector_as_arraysegment(";
+ code += NumToString(field.value.offset);
+ code += "); }\n";
+ break;
+ default: break;
+ }
}
- }
- // generate object accessors if is nested_flatbuffer
- if (field.nested_flatbuffer) {
- auto nested_type_name = WrapInNameSpace(*field.nested_flatbuffer);
- auto nested_method_name = MakeCamel(field.name, lang_.first_camel_upper)
- + "As" + nested_type_name;
- auto get_nested_method_name = nested_method_name;
- if (lang_.language == IDLOptions::kCSharp) {
- get_nested_method_name = "Get" + nested_method_name;
- conditional_cast = "(" + nested_type_name + lang_.optional_suffix + ")";
- }
- if (lang_.language != IDLOptions::kCSharp) {
- code += " public " + nested_type_name + lang_.optional_suffix + " ";
- code += nested_method_name + "() { return ";
- code += get_nested_method_name + "(new " + nested_type_name + "()); }\n";
- } else {
- obj = "(new " + nested_type_name + "())";
- }
- code += " public " + nested_type_name + lang_.optional_suffix + " ";
- code += get_nested_method_name + "(";
- if (lang_.language != IDLOptions::kCSharp)
- code += nested_type_name + " obj";
- code += ") { int o = " + lang_.accessor_prefix + "__offset(";
- code += NumToString(field.value.offset) +"); ";
- code += "return o != 0 ? " + conditional_cast + obj + ".__assign(";
- code += lang_.accessor_prefix;
- code += "__indirect(" + lang_.accessor_prefix + "__vector(o)), ";
- code += lang_.accessor_prefix + "bb) : null; }\n";
- }
- // Generate mutators for scalar fields or vectors of scalars.
- if (parser_.opts.mutable_buffer) {
- auto underlying_type = field.value.type.base_type == BASE_TYPE_VECTOR
- ? field.value.type.VectorType()
- : field.value.type;
- // Boolean parameters have to be explicitly converted to byte
- // representation.
- auto setter_parameter = underlying_type.base_type == BASE_TYPE_BOOL
- ? "(byte)(" + field.name + " ? 1 : 0)"
- : field.name;
- auto mutator_prefix = MakeCamel("mutate", lang_.first_camel_upper);
- // A vector mutator also needs the index of the vector element it should
- // mutate.
- auto mutator_params = (field.value.type.base_type == BASE_TYPE_VECTOR
- ? "(int j, "
- : "(") + GenTypeNameDest(underlying_type) + " " + field.name + ") { ";
- auto setter_index = field.value.type.base_type == BASE_TYPE_VECTOR
- ? lang_.accessor_prefix + "__vector(o) + j * " +
- NumToString(InlineSize(underlying_type))
- : (struct_def.fixed
- ? lang_.accessor_prefix + "bb_pos + " +
- NumToString(field.value.offset)
- : "o + " + lang_.accessor_prefix + "bb_pos");
- if (IsScalar(field.value.type.base_type) ||
- (field.value.type.base_type == BASE_TYPE_VECTOR &&
- IsScalar(field.value.type.VectorType().base_type))) {
- code += " public ";
- code += struct_def.fixed ? "void " : lang_.bool_type;
- code += mutator_prefix + MakeCamel(field.name, true);
- code += mutator_params;
- if (struct_def.fixed) {
- code += GenSetter(underlying_type) + "(" + setter_index + ", ";
- code += src_cast + setter_parameter + "); }\n";
+ // generate object accessors if is nested_flatbuffer
+ if (field.nested_flatbuffer) {
+ auto nested_type_name = WrapInNameSpace(*field.nested_flatbuffer);
+ auto nested_method_name =
+ MakeCamel(field.name, lang_.first_camel_upper) + "As" +
+ nested_type_name;
+ auto get_nested_method_name = nested_method_name;
+ if (lang_.language == IDLOptions::kCSharp) {
+ get_nested_method_name = "Get" + nested_method_name;
+ conditional_cast =
+ "(" + nested_type_name + lang_.optional_suffix + ")";
+ }
+ if (lang_.language != IDLOptions::kCSharp) {
+ code += " public " + nested_type_name + lang_.optional_suffix + " ";
+ code += nested_method_name + "() { return ";
+ code +=
+ get_nested_method_name + "(new " + nested_type_name + "()); }\n";
} else {
- code += "int o = " + lang_.accessor_prefix + "__offset(";
- code += NumToString(field.value.offset) + ");";
- code += " if (o != 0) { " + GenSetter(underlying_type);
- code += "(" + setter_index + ", " + src_cast + setter_parameter +
- "); return true; } else { return false; } }\n";
+ obj = "(new " + nested_type_name + "())";
}
+ code += " public " + nested_type_name + lang_.optional_suffix + " ";
+ code += get_nested_method_name + "(";
+ if (lang_.language != IDLOptions::kCSharp)
+ code += nested_type_name + " obj";
+ code += ") { int o = " + lang_.accessor_prefix + "__offset(";
+ code += NumToString(field.value.offset) + "); ";
+ code += "return o != 0 ? " + conditional_cast + obj + ".__assign(";
+ code += lang_.accessor_prefix;
+ code += "__indirect(" + lang_.accessor_prefix + "__vector(o)), ";
+ code += lang_.accessor_prefix + "bb) : null; }\n";
}
- }
- }
- code += "\n";
- flatbuffers::FieldDef *key_field = nullptr;
- if (struct_def.fixed) {
- // create a struct constructor function
- code += " public static " + GenOffsetType(struct_def) + " ";
- code += FunctionStart('C') + "reate";
- code += struct_def.name + "(FlatBufferBuilder builder";
- GenStructArgs(struct_def, code_ptr, "");
- code += ") {\n";
- GenStructBody(struct_def, code_ptr, "");
- code += " return ";
- code += GenOffsetConstruct(struct_def,
- "builder." + std::string(lang_.get_fbb_offset));
- code += ";\n }\n";
- } else {
- // 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
- // inline, and there's no way to do so in Java.
- bool has_no_struct_fields = true;
- int num_fields = 0;
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (field.deprecated) continue;
- if (IsStruct(field.value.type)) {
- has_no_struct_fields = false;
- } else {
- num_fields++;
+ // Generate mutators for scalar fields or vectors of scalars.
+ if (parser_.opts.mutable_buffer) {
+ auto underlying_type = field.value.type.base_type == BASE_TYPE_VECTOR
+ ? field.value.type.VectorType()
+ : field.value.type;
+ // Boolean parameters have to be explicitly converted to byte
+ // representation.
+ auto setter_parameter = underlying_type.base_type == BASE_TYPE_BOOL
+ ? "(byte)(" + field.name + " ? 1 : 0)"
+ : field.name;
+ auto mutator_prefix = MakeCamel("mutate", lang_.first_camel_upper);
+ // A vector mutator also needs the index of the vector element it should
+ // mutate.
+ auto mutator_params =
+ (field.value.type.base_type == BASE_TYPE_VECTOR ? "(int j, "
+ : "(") +
+ GenTypeNameDest(underlying_type) + " " + field.name + ") { ";
+ auto setter_index =
+ field.value.type.base_type == BASE_TYPE_VECTOR
+ ? lang_.accessor_prefix + "__vector(o) + j * " +
+ NumToString(InlineSize(underlying_type))
+ : (struct_def.fixed
+ ? lang_.accessor_prefix + "bb_pos + " +
+ NumToString(field.value.offset)
+ : "o + " + lang_.accessor_prefix + "bb_pos");
+ if (IsScalar(field.value.type.base_type) ||
+ (field.value.type.base_type == BASE_TYPE_VECTOR &&
+ IsScalar(field.value.type.VectorType().base_type))) {
+ code += " public ";
+ code += struct_def.fixed ? "void " : lang_.bool_type;
+ code += mutator_prefix + MakeCamel(field.name, true);
+ code += mutator_params;
+ if (struct_def.fixed) {
+ code += GenSetter(underlying_type) + "(" + setter_index + ", ";
+ code += src_cast + setter_parameter + "); }\n";
+ } else {
+ code += "int o = " + lang_.accessor_prefix + "__offset(";
+ code += NumToString(field.value.offset) + ");";
+ code += " if (o != 0) { " + GenSetter(underlying_type);
+ code += "(" + setter_index + ", " + src_cast + setter_parameter +
+ "); return true; } else { return false; } }\n";
+ }
+ }
}
}
- // JVM specifications restrict default constructor params to be < 255.
- // Longs and doubles take up 2 units, so we set the limit to be < 127.
- if (has_no_struct_fields && num_fields && num_fields < 127) {
- // Generate a table constructor of the form:
- // public static int createName(FlatBufferBuilder builder, args...)
+ code += "\n";
+ flatbuffers::FieldDef *key_field = nullptr;
+ if (struct_def.fixed) {
+ // create a struct constructor function
code += " public static " + GenOffsetType(struct_def) + " ";
- code += FunctionStart('C') + "reate" + struct_def.name;
- code += "(FlatBufferBuilder builder";
+ code += FunctionStart('C') + "reate";
+ code += struct_def.name + "(FlatBufferBuilder builder";
+ GenStructArgs(struct_def, code_ptr, "");
+ code += ") {\n";
+ GenStructBody(struct_def, code_ptr, "");
+ code += " return ";
+ code += GenOffsetConstruct(
+ struct_def, "builder." + std::string(lang_.get_fbb_offset));
+ code += ";\n }\n";
+ } else {
+ // 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
+ // inline, and there's no way to do so in Java.
+ bool has_no_struct_fields = true;
+ int num_fields = 0;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
- code += ",\n ";
- code += GenTypeBasic(DestinationType(field.value.type, false));
- code += " ";
- code += field.name;
- if (!IsScalar(field.value.type.base_type)) code += "Offset";
-
- // Java doesn't have defaults, which means this method must always
- // supply all arguments, and thus won't compile when fields are added.
- if (lang_.language != IDLOptions::kJava) {
- code += " = ";
- code += GenDefaultValueBasic(field.value);
+ if (IsStruct(field.value.type)) {
+ has_no_struct_fields = false;
+ } else {
+ num_fields++;
}
}
- code += ") {\n builder.";
- code += FunctionStart('S') + "tartObject(";
- code += NumToString(struct_def.fields.vec.size()) + ");\n";
- for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
- size;
- size /= 2) {
- for (auto it = struct_def.fields.vec.rbegin();
- it != struct_def.fields.vec.rend(); ++it) {
+ // JVM specifications restrict default constructor params to be < 255.
+ // Longs and doubles take up 2 units, so we set the limit to be < 127.
+ if (has_no_struct_fields && num_fields && num_fields < 127) {
+ // Generate a table constructor of the form:
+ // public static int createName(FlatBufferBuilder builder, args...)
+ code += " public static " + GenOffsetType(struct_def) + " ";
+ code += FunctionStart('C') + "reate" + struct_def.name;
+ code += "(FlatBufferBuilder builder";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
- if (!field.deprecated &&
- (!struct_def.sortbysize ||
- size == SizeOf(field.value.type.base_type))) {
- code += " " + struct_def.name + ".";
- code += FunctionStart('A') + "dd";
- code += MakeCamel(field.name) + "(builder, " + field.name;
- if (!IsScalar(field.value.type.base_type)) code += "Offset";
- code += ");\n";
+ if (field.deprecated) continue;
+ code += ",\n ";
+ code += GenTypeBasic(DestinationType(field.value.type, false));
+ code += " ";
+ code += field.name;
+ if (!IsScalar(field.value.type.base_type)) code += "Offset";
+
+ // Java doesn't have defaults, which means this method must always
+ // supply all arguments, and thus won't compile when fields are added.
+ if (lang_.language != IDLOptions::kJava) {
+ code += " = ";
+ code += GenDefaultValueBasic(field.value);
}
}
+ code += ") {\n builder.";
+ code += FunctionStart('S') + "tartObject(";
+ code += NumToString(struct_def.fields.vec.size()) + ");\n";
+ for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
+ size; size /= 2) {
+ for (auto it = struct_def.fields.vec.rbegin();
+ it != struct_def.fields.vec.rend(); ++it) {
+ auto &field = **it;
+ if (!field.deprecated &&
+ (!struct_def.sortbysize ||
+ size == SizeOf(field.value.type.base_type))) {
+ code += " " + struct_def.name + ".";
+ code += FunctionStart('A') + "dd";
+ code += MakeCamel(field.name) + "(builder, " + field.name;
+ if (!IsScalar(field.value.type.base_type)) code += "Offset";
+ code += ");\n";
+ }
+ }
+ }
+ code += " return " + struct_def.name + ".";
+ code += FunctionStart('E') + "nd" + struct_def.name;
+ code += "(builder);\n }\n\n";
}
- code += " return " + struct_def.name + ".";
- code += FunctionStart('E') + "nd" + struct_def.name;
- code += "(builder);\n }\n\n";
- }
- // Generate a set of static methods that allow table construction,
- // of the form:
- // public static void addName(FlatBufferBuilder builder, short name)
- // { builder.addShort(id, name, default); }
- // Unlike the Create function, these always work.
- code += " public static void " + FunctionStart('S') + "tart";
- code += struct_def.name;
- code += "(FlatBufferBuilder builder) { builder.";
- code += FunctionStart('S') + "tartObject(";
- 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;
- if (field.deprecated) continue;
- if (field.key) key_field = &field;
- code += " public static void " + FunctionStart('A') + "dd";
- code += MakeCamel(field.name);
- code += "(FlatBufferBuilder builder, ";
- code += GenTypeBasic(DestinationType(field.value.type, false));
- auto argname = MakeCamel(field.name, false);
- if (!IsScalar(field.value.type.base_type)) argname += "Offset";
- code += " " + argname + ") { builder." + FunctionStart('A') + "dd";
- code += GenMethod(field.value.type) + "(";
- code += NumToString(it - struct_def.fields.vec.begin()) + ", ";
- code += SourceCastBasic(field.value.type);
- code += argname;
- if (!IsScalar(field.value.type.base_type) &&
- field.value.type.base_type != BASE_TYPE_UNION &&
- lang_.language == IDLOptions::kCSharp) {
- code += ".Value";
- }
- code += ", ";
- if (lang_.language == IDLOptions::kJava)
- code += SourceCastBasic( field.value.type );
- code += GenDefaultValue(field.value, false);
- code += "); }\n";
- if (field.value.type.base_type == BASE_TYPE_VECTOR) {
- auto vector_type = field.value.type.VectorType();
- auto alignment = InlineAlignment(vector_type);
- auto elem_size = InlineSize(vector_type);
- if (!IsStruct(vector_type)) {
- // Generate a method to create a vector from a Java array.
- code += " public static " + GenVectorOffsetType() + " ";
- code += FunctionStart('C') + "reate";
+ // Generate a set of static methods that allow table construction,
+ // of the form:
+ // public static void addName(FlatBufferBuilder builder, short name)
+ // { builder.addShort(id, name, default); }
+ // Unlike the Create function, these always work.
+ code += " public static void " + FunctionStart('S') + "tart";
+ code += struct_def.name;
+ code += "(FlatBufferBuilder builder) { builder.";
+ code += FunctionStart('S') + "tartObject(";
+ 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;
+ if (field.deprecated) continue;
+ if (field.key) key_field = &field;
+ code += " public static void " + FunctionStart('A') + "dd";
+ code += MakeCamel(field.name);
+ code += "(FlatBufferBuilder builder, ";
+ code += GenTypeBasic(DestinationType(field.value.type, false));
+ auto argname = MakeCamel(field.name, false);
+ if (!IsScalar(field.value.type.base_type)) argname += "Offset";
+ code += " " + argname + ") { builder." + FunctionStart('A') + "dd";
+ code += GenMethod(field.value.type) + "(";
+ code += NumToString(it - struct_def.fields.vec.begin()) + ", ";
+ code += SourceCastBasic(field.value.type);
+ code += argname;
+ if (!IsScalar(field.value.type.base_type) &&
+ field.value.type.base_type != BASE_TYPE_UNION &&
+ lang_.language == IDLOptions::kCSharp) {
+ code += ".Value";
+ }
+ code += ", ";
+ if (lang_.language == IDLOptions::kJava)
+ code += SourceCastBasic(field.value.type);
+ code += GenDefaultValue(field.value, false);
+ code += "); }\n";
+ if (field.value.type.base_type == BASE_TYPE_VECTOR) {
+ auto vector_type = field.value.type.VectorType();
+ auto alignment = InlineAlignment(vector_type);
+ auto elem_size = InlineSize(vector_type);
+ if (!IsStruct(vector_type)) {
+ // Generate a method to create a vector from a Java array.
+ code += " public static " + GenVectorOffsetType() + " ";
+ code += FunctionStart('C') + "reate";
+ code += MakeCamel(field.name);
+ code += "Vector(FlatBufferBuilder builder, ";
+ code += GenTypeBasic(vector_type) + "[] data) ";
+ code += "{ builder." + FunctionStart('S') + "tartVector(";
+ code += NumToString(elem_size);
+ code += ", data." + FunctionStart('L') + "ength, ";
+ code += NumToString(alignment);
+ code += "); for (int i = data.";
+ code += FunctionStart('L') + "ength - 1; i >= 0; i--) builder.";
+ code += FunctionStart('A') + "dd";
+ code += GenMethod(vector_type);
+ code += "(";
+ code += SourceCastBasic(vector_type, false);
+ code += "data[i]";
+ if (lang_.language == IDLOptions::kCSharp &&
+ (vector_type.base_type == BASE_TYPE_STRUCT ||
+ vector_type.base_type == BASE_TYPE_STRING))
+ code += ".Value";
+ code += "); return ";
+ code += "builder." + FunctionStart('E') + "ndVector(); }\n";
+ }
+ // Generate a method to start a vector, data to be added manually
+ // after.
+ code += " public static void " + FunctionStart('S') + "tart";
code += MakeCamel(field.name);
- code += "Vector(FlatBufferBuilder builder, ";
- code += GenTypeBasic(vector_type) + "[] data) ";
+ code += "Vector(FlatBufferBuilder builder, int numElems) ";
code += "{ builder." + FunctionStart('S') + "tartVector(";
code += NumToString(elem_size);
- code += ", data." + FunctionStart('L') + "ength, ";
- code += NumToString(alignment);
- code += "); for (int i = data.";
- code += FunctionStart('L') + "ength - 1; i >= 0; i--) builder.";
- code += FunctionStart('A') + "dd";
- code += GenMethod(vector_type);
- code += "(";
- code += SourceCastBasic(vector_type, false);
- code += "data[i]";
- if (lang_.language == IDLOptions::kCSharp &&
- (vector_type.base_type == BASE_TYPE_STRUCT ||
- vector_type.base_type == BASE_TYPE_STRING))
- code += ".Value";
- code += "); return ";
- code += "builder." + FunctionStart('E') + "ndVector(); }\n";
+ code += ", numElems, " + NumToString(alignment);
+ code += "); }\n";
}
- // Generate a method to start a vector, data to be added manually after.
- code += " public static void " + FunctionStart('S') + "tart";
- code += MakeCamel(field.name);
- code += "Vector(FlatBufferBuilder builder, int numElems) ";
- code += "{ builder." + FunctionStart('S') + "tartVector(";
- code += NumToString(elem_size);
- code += ", numElems, " + NumToString(alignment);
- code += "); }\n";
}
- }
- code += " public static " + GenOffsetType(struct_def) + " ";
- code += FunctionStart('E') + "nd" + struct_def.name;
- code += "(FlatBufferBuilder builder) {\n int o = builder.";
- code += FunctionStart('E') + "ndObject();\n";
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
- auto &field = **it;
- if (!field.deprecated && field.required) {
- code += " builder." + FunctionStart('R') + "equired(o, ";
- code += NumToString(field.value.offset);
- code += "); // " + field.name + "\n";
+ code += " public static " + GenOffsetType(struct_def) + " ";
+ code += FunctionStart('E') + "nd" + struct_def.name;
+ code += "(FlatBufferBuilder builder) {\n int o = builder.";
+ code += FunctionStart('E') + "ndObject();\n";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (!field.deprecated && field.required) {
+ code += " builder." + FunctionStart('R') + "equired(o, ";
+ code += NumToString(field.value.offset);
+ code += "); // " + field.name + "\n";
+ }
}
- }
- code += " return " + GenOffsetConstruct(struct_def, "o") + ";\n }\n";
- if (parser_.root_struct_def_ == &struct_def) {
- code += " public static void ";
- code += FunctionStart('F') + "inish" + struct_def.name;
- code += "Buffer(FlatBufferBuilder builder, " + GenOffsetType(struct_def);
- code += " offset) {";
- code += " builder." + FunctionStart('F') + "inish(offset";
- if (lang_.language == IDLOptions::kCSharp) {
- code += ".Value";
+ code += " return " + GenOffsetConstruct(struct_def, "o") + ";\n }\n";
+ if (parser_.root_struct_def_ == &struct_def) {
+ code += " public static void ";
+ code += FunctionStart('F') + "inish" + struct_def.name;
+ code +=
+ "Buffer(FlatBufferBuilder builder, " + GenOffsetType(struct_def);
+ code += " offset) {";
+ code += " builder." + FunctionStart('F') + "inish(offset";
+ if (lang_.language == IDLOptions::kCSharp) { code += ".Value"; }
+
+ if (parser_.file_identifier_.length())
+ code += ", \"" + parser_.file_identifier_ + "\"";
+ code += "); }\n";
}
-
- if (parser_.file_identifier_.length())
- code += ", \"" + parser_.file_identifier_ + "\"";
- code += "); }\n";
- }
- }
- // Only generate key compare function for table,
- // because `key_field` is not set for struct
- if (struct_def.has_key && !struct_def.fixed) {
- if (lang_.language == IDLOptions::kJava) {
- code += "\n @Override\n protected int keysCompare(";
- code += "Integer o1, Integer o2, ByteBuffer _bb) {";
- code += GenKeyGetter(key_field);
- code += " }\n";
- }
- else {
- code += "\n public static VectorOffset ";
- code += "CreateSortedVectorOf" + struct_def.name;
- code += "(FlatBufferBuilder builder, ";
- code += "Offset<" + struct_def.name + ">";
- code += "[] offsets) {\n";
- code += " Array.Sort(offsets, (Offset<" + struct_def.name +
- "> o1, Offset<" + struct_def.name + "> o2) => " + GenKeyGetter(key_field);
- code += ");\n";
- code += " return builder.CreateVectorOfTables(offsets);\n }\n";
}
+ // Only generate key compare function for table,
+ // because `key_field` is not set for struct
+ if (struct_def.has_key && !struct_def.fixed) {
+ if (lang_.language == IDLOptions::kJava) {
+ code += "\n @Override\n protected int keysCompare(";
+ code += "Integer o1, Integer o2, ByteBuffer _bb) {";
+ code += GenKeyGetter(key_field);
+ code += " }\n";
+ } else {
+ code += "\n public static VectorOffset ";
+ code += "CreateSortedVectorOf" + struct_def.name;
+ code += "(FlatBufferBuilder builder, ";
+ code += "Offset<" + struct_def.name + ">";
+ code += "[] offsets) {\n";
+ code += " Array.Sort(offsets, (Offset<" + struct_def.name +
+ "> o1, Offset<" + struct_def.name + "> o2) => " +
+ GenKeyGetter(key_field);
+ code += ");\n";
+ code += " return builder.CreateVectorOfTables(offsets);\n }\n";
+ }
- code += "\n public static " + struct_def.name + lang_.optional_suffix;
- code += " __lookup_by_key(int vectorLocation, ";
- code += GenTypeNameDest(key_field->value.type);
- code += " key, ByteBuffer bb) {\n";
- if (key_field->value.type.base_type == BASE_TYPE_STRING) {
- code += " byte[] byteKey = ";
- if (lang_.language == IDLOptions::kJava)
- code += "key.getBytes(Table.UTF8_CHARSET.get());\n";
- else
- code += "System.Text.Encoding.UTF8.GetBytes(key);\n";
+ code += "\n public static " + struct_def.name + lang_.optional_suffix;
+ code += " __lookup_by_key(int vectorLocation, ";
+ code += GenTypeNameDest(key_field->value.type);
+ code += " key, ByteBuffer bb) {\n";
+ if (key_field->value.type.base_type == BASE_TYPE_STRING) {
+ code += " byte[] byteKey = ";
+ if (lang_.language == IDLOptions::kJava)
+ code += "key.getBytes(Table.UTF8_CHARSET.get());\n";
+ else
+ code += "System.Text.Encoding.UTF8.GetBytes(key);\n";
+ }
+ code += " int span = ";
+ code += "bb." + FunctionStart('G') + "etInt(vectorLocation - 4);\n";
+ code += " int start = 0;\n";
+ code += " while (span != 0) {\n";
+ code += " int middle = span / 2;\n";
+ code += GenLookupKeyGetter(key_field);
+ code += " if (comp > 0) {\n";
+ code += " span = middle;\n";
+ code += " } else if (comp < 0) {\n";
+ code += " middle++;\n";
+ code += " start += middle;\n";
+ code += " span -= middle;\n";
+ code += " } else {\n";
+ code += " return new " + struct_def.name;
+ code += "().__assign(tableOffset, bb);\n";
+ code += " }\n }\n";
+ code += " return null;\n";
+ code += " }\n";
}
- code += " int span = ";
- code += "bb." + FunctionStart('G') + "etInt(vectorLocation - 4);\n";
- code += " int start = 0;\n";
- code += " while (span != 0) {\n";
- code += " int middle = span / 2;\n";
- code += GenLookupKeyGetter(key_field);
- code += " if (comp > 0) {\n";
- code += " span = middle;\n";
- code += " } else if (comp < 0) {\n";
- code += " middle++;\n";
- code += " start += middle;\n";
- code += " span -= middle;\n";
- code += " } else {\n";
- code += " return new " + struct_def.name;
- code += "().__assign(tableOffset, bb);\n";
- code += " }\n }\n";
- code += " return null;\n";
- code += " }\n";
+ code += "}";
+ // Java does not need the closing semi-colon on class definitions.
+ code += (lang_.language != IDLOptions::kJava) ? ";" : "";
+ code += "\n\n";
}
- code += "}";
- // Java does not need the closing semi-colon on class definitions.
- code += (lang_.language != IDLOptions::kJava) ? ";" : "";
- code += "\n\n";
-}
- const LanguageParameters& lang_;
- // This tracks the current namespace used to determine if a type need to be prefixed by its namespace
- const Namespace *cur_name_space_;
+ const LanguageParameters &lang_;
+ // This tracks the current namespace used to determine if a type need to be
+ // prefixed by its namespace
+ const Namespace *cur_name_space_;
};
} // namespace general
++it) {
auto &struct_def = **it;
if (make_rule != "") make_rule += " ";
- std::string directory =
- BaseGenerator::NamespaceDir(parser, path,
- *struct_def.defined_namespace);
+ std::string directory = BaseGenerator::NamespaceDir(
+ parser, path, *struct_def.defined_namespace);
make_rule += directory + struct_def.name + lang.file_extension;
}
return make_rule;
}
-std::string BinaryFileName(const Parser &parser,
- const std::string &path,
+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;
}
-bool GenerateBinary(const Parser &parser,
- const std::string &path,
+bool GenerateBinary(const Parser &parser, const std::string &path,
const std::string &file_name) {
return !parser.builder_.GetSize() ||
flatbuffers::SaveFile(
- BinaryFileName(parser, path, file_name).c_str(),
- reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
- parser.builder_.GetSize(),
- true);
+ BinaryFileName(parser, path, file_name).c_str(),
+ reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
+ parser.builder_.GetSize(), true);
}
-std::string BinaryMakeRule(const Parser &parser,
- const std::string &path,
+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));
- std::string make_rule = BinaryFileName(parser, path, filebase) + ": " +
- file_name;
- auto included_files = parser.GetIncludedFilesRecursive(
- parser.root_struct_def_->file);
- for (auto it = included_files.begin();
- it != included_files.end(); ++it) {
+ std::string filebase =
+ flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
+ std::string make_rule =
+ BinaryFileName(parser, path, filebase) + ": " + file_name;
+ auto included_files =
+ parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
+ for (auto it = included_files.begin(); it != included_files.end(); ++it) {
make_rule += " " + *it;
}
return make_rule;
// independent from idl_parser, since this code is not needed for most clients
-#include <string>
#include <sstream>
+#include <string>
+#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#include "flatbuffers/code_generators.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 {
// see https://golang.org/ref/spec#Keywords
static const char *g_golang_keywords[] = {
- "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",
};
static std::string GenGetter(const Type &type);
static std::string GenTypeBasic(const Type &type);
static std::string GenTypeGet(const Type &type);
static std::string TypeName(const FieldDef &field);
-static std::string GoIdentity(const std::string& name) {
- for (size_t i=0; i<sizeof(g_golang_keywords)/sizeof(g_golang_keywords[0]); i++) {
- if (name == g_golang_keywords[i]) {
- return MakeCamel(name + "_", false);
- }
+static std::string GoIdentity(const std::string &name) {
+ for (size_t i = 0;
+ i < sizeof(g_golang_keywords) / sizeof(g_golang_keywords[0]); i++) {
+ if (name == g_golang_keywords[i]) { return MakeCamel(name + "_", false); }
}
return MakeCamel(name, 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) {
return "{\n\to := flatbuffers.UOffsetT(rcv._tab.Offset(" +
- NumToString(field.value.offset) +
- "))\n\tif o != 0 {\n";
+ NumToString(field.value.offset) + "))\n\tif o != 0 {\n";
}
// Begin a class declaration.
// Implement the table accessor
static void GenTableAccessor(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += "{\n";
if (struct_def.fixed) {
- code += "\treturn rcv._tab.Table\n";
+ code += "\treturn rcv._tab.Table\n";
} else {
- code += "\treturn rcv._tab\n";
+ code += "\treturn rcv._tab\n";
}
code += "}\n\n";
}
// Get the length of a vector.
-static void GetVectorLen(const StructDef &struct_def,
- const FieldDef &field,
+static void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
}
// Get a [ubyte] vector as a byte slice.
-static void GetUByteSlice(const StructDef &struct_def,
- const FieldDef &field,
+static void GetUByteSlice(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += " " + MakeCamel(field.name);
code += "() " + TypeName(field) + " {\n";
- code +="\treturn " + getter;
+ code += "\treturn " + getter;
code += "(rcv._tab.Pos + flatbuffers.UOffsetT(";
code += NumToString(field.value.offset) + "))\n}\n";
}
}
// Get the value of a string.
-static void GetStringField(const StructDef &struct_def,
- const FieldDef &field,
+static void GetStringField(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += " " + MakeCamel(field.name);
+ code += " " + MakeCamel(field.name);
code += "() " + TypeName(field) + " ";
code += OffsetPrefix(field) + "\t\treturn " + GenGetter(field.value.type);
code += "(o + rcv._tab.Pos)\n\t}\n\treturn nil\n";
}
// Get the value of a union from an object.
-static void GetUnionField(const StructDef &struct_def,
- const FieldDef &field,
+static void GetUnionField(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, 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
- code += "\n";
+ // a previous mutate has not put an extra new line
+ code += "\n";
}
code += "func Create" + struct_def.name;
code += "(builder *flatbuffers.Builder";
// 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) {
+ const char *nameprefix, std::string *code_ptr) {
for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
+ it != struct_def.fields.vec.end(); ++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
// a nested struct, prefix the name with the field name.
StructBuilderArgs(*field.value.type.struct_def,
- (nameprefix + (field.name + "_")).c_str(),
- code_ptr);
+ (nameprefix + (field.name + "_")).c_str(), code_ptr);
} else {
std::string &code = *code_ptr;
- code += (std::string)", " + nameprefix;
+ code += (std::string) ", " + nameprefix;
code += GoIdentity(field.name);
code += " " + GenTypeBasic(field.value.type);
}
// Recursively generate struct construction statements and instert manual
// padding.
static void StructBuilderBody(const StructDef &struct_def,
- const char *nameprefix,
- std::string *code_ptr) {
+ 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) {
+ it != struct_def.fields.vec.rend(); ++it) {
auto &field = **it;
if (field.padding)
code += "\tbuilder.Pad(" + NumToString(field.padding) + ")\n";
if (IsStruct(field.value.type)) {
StructBuilderBody(*field.value.type.struct_def,
- (nameprefix + (field.name + "_")).c_str(),
- code_ptr);
+ (nameprefix + (field.name + "_")).c_str(), code_ptr);
} else {
code += "\tbuilder.Prepend" + GenMethod(field) + "(";
code += nameprefix + GoIdentity(field.name) + ")\n";
// Set the value of a table's field.
static void BuildFieldOfTable(const StructDef &struct_def,
- const FieldDef &field,
- const size_t offset,
+ const FieldDef &field, const size_t offset,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "func " + struct_def.name + "Add" + MakeCamel(field.name);
// Set the value of one of the members of a table's vector.
static void BuildVectorOfTable(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) {
+ const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "func " + struct_def.name + "Start";
code += MakeCamel(field.name);
// Generate a struct field getter, conditioned on its child type(s).
static void GenStructAccessor(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) {
+ 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) {
GetStructFieldOfTable(struct_def, field, code_ptr);
}
break;
- case BASE_TYPE_STRING:
- GetStringField(struct_def, field, code_ptr);
- break;
+ case BASE_TYPE_STRING: GetStringField(struct_def, field, code_ptr); break;
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
if (vectortype.base_type == BASE_TYPE_STRUCT) {
}
break;
}
- case BASE_TYPE_UNION:
- GetUnionField(struct_def, field, code_ptr);
- break;
- default:
- assert(0);
+ case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr); break;
+ default: assert(0);
}
}
if (field.value.type.base_type == BASE_TYPE_VECTOR) {
// Mutate the value of a struct's scalar.
static void MutateScalarFieldOfStruct(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) {
std::string &code = *code_ptr;
std::string type = MakeCamel(GenTypeBasic(field.value.type));
std::string setter = "rcv._tab.Mutate" + type;
// Mutate the value of a table's scalar.
static void MutateScalarFieldOfTable(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) {
std::string &code = *code_ptr;
std::string type = MakeCamel(GenTypeBasic(field.value.type));
std::string setter = "rcv._tab.Mutate" + type + "Slot";
}
// Generate a struct field setter, conditioned on its child type(s).
-static void GenStructMutator(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) {
+static void GenStructMutator(const StructDef &struct_def, const FieldDef &field,
+ std::string *code_ptr) {
GenComment(field.doc_comment, code_ptr, nullptr, "");
if (IsScalar(field.value.type.base_type)) {
if (struct_def.fixed) {
GetStartOfTable(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
+ it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
}
// Generate struct or table methods.
-static void GenStruct(const StructDef &struct_def,
- std::string *code_ptr) {
+static void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
if (struct_def.generated) return;
GenComment(struct_def.doc_comment, code_ptr, nullptr);
// Generate struct fields accessors
for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
+ it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
GenComment(enum_def.doc_comment, code_ptr, nullptr);
BeginEnum(code_ptr);
- for (auto it = enum_def.vals.vec.begin();
- it != enum_def.vals.vec.end();
+ for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
auto &ev = **it;
GenComment(ev.doc_comment, code_ptr, nullptr, "\t");
EndEnum(code_ptr);
BeginEnumNames(enum_def, code_ptr);
- for (auto it = enum_def.vals.vec.begin();
- it != enum_def.vals.vec.end();
+ for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
auto &ev = **it;
EnumNameMember(enum_def, ev, code_ptr);
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" + MakeCamel(GenTypeGet(type));
+ default: return "rcv._tab.Get" + MakeCamel(GenTypeGet(type));
}
}
// Returns the method name for use with add/put calls.
static std::string GenMethod(const FieldDef &field) {
return IsScalar(field.value.type.base_type)
- ? MakeCamel(GenTypeBasic(field.value.type))
- : (IsStruct(field.value.type) ? "Struct" : "UOffsetT");
+ ? MakeCamel(GenTypeBasic(field.value.type))
+ : (IsStruct(field.value.type) ? "Struct" : "UOffsetT");
}
static std::string GenTypeBasic(const Type &type) {
static const char *ctypename[] = {
+ // clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
#GTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
+ // clang-format on
};
return ctypename[type.base_type];
}
static 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_STRUCT:
- return type.struct_def->name;
+ case BASE_TYPE_STRING: return "[]byte";
+ 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 "*flatbuffers.Table";
+ default: return "*flatbuffers.Table";
}
}
static std::string GenTypeGet(const Type &type) {
- return IsScalar(type.base_type)
- ? GenTypeBasic(type)
- : GenTypePointer(type);
+ return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
}
static std::string TypeName(const FieldDef &field) {
public:
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 */) {
+ : BaseGenerator(parser, path, file_name, "" /* not used*/,
+ "" /* not used */) {
std::istringstream iss(go_namespace);
std::string component;
while (std::getline(iss, component, '.')) {
if (needs_imports) {
code += "import (\n";
if (!parser_.opts.go_import.empty()) {
- code += "\tflatbuffers \"" + parser_.opts.go_import +"\"\n";
- } else{
+ code += "\tflatbuffers \"" + parser_.opts.go_import + "\"\n";
+ } else {
code += "\tflatbuffers \"github.com/google/flatbuffers/go\"\n";
}
code += ")\n\n";
bool needs_imports) {
if (!classcode.length()) return true;
- Namespace& ns = go_namespace_.components.empty() ? *def.defined_namespace : go_namespace_;
+ Namespace &ns = go_namespace_.components.empty() ? *def.defined_namespace
+ : go_namespace_;
std::string code = "";
BeginFile(LastNamespacePart(ns), needs_imports, &code);
code += classcode;
- std::string filename =
- NamespaceDir(ns) + def.name + ".go";
+ std::string filename = NamespaceDir(ns) + def.name + ".go";
return SaveFile(filename.c_str(), code, false);
}
// independent from idl_parser, since this code is not needed for most clients
+#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#include "flatbuffers/code_generators.h"
#include "src/compiler/cpp_generator.h"
#include "src/compiler/go_generator.h"
#include "src/compiler/java_generator.h"
#if defined(_MSC_VER)
-#pragma warning(push)
-#pragma warning(disable: 4512) // C4512: 'class' : assignment operator could not be generated
+# pragma warning(push)
+# pragma warning(disable : 4512) // C4512: 'class' : assignment operator could
+ // not be generated
#endif
namespace flatbuffers {
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) {
}
}
- grpc::string GetLeadingComments(const grpc::string) const {
- return "";
- }
- grpc::string GetTrailingComments(const grpc::string) const {
- return "";
- }
+ grpc::string GetLeadingComments(const grpc::string) const { return ""; }
+ grpc::string GetTrailingComments(const grpc::string) const { return ""; }
std::vector<grpc::string> GetAllComments() const {
return method_->rpc_comment;
}
return "flatbuffers::grpc::Message<" + sd.name + ">";
}
- std::string get_input_type_name() const {
- return (*method_->request).name;
- }
- std::string get_output_type_name() const {
- return (*method_->response).name;
- }
+ std::string get_input_type_name() const { return (*method_->request).name; }
+ std::string get_output_type_name() const { return (*method_->response).name; }
- 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 {
+ 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 {
return true;
}
return true;
}
- std::string input_type_name() const {
- return GRPCType(*method_->request);
- }
+ std::string input_type_name() const { return GRPCType(*method_->request); }
- std::string output_type_name() const {
- return GRPCType(*method_->response);
- }
+ std::string output_type_name() const { return GRPCType(*method_->response); }
bool NoStreaming() const { return streaming_ == kNone; }
bool ClientStreaming() const { return streaming_ == kClient; }
public:
FlatBufService(const ServiceDef *service) : service_(service) {}
- grpc::string GetLeadingComments(const grpc::string) const {
- return "";
- }
- grpc::string GetTrailingComments(const grpc::string) const {
- return "";
- }
+ grpc::string GetLeadingComments(const grpc::string) const { return ""; }
+ grpc::string GetTrailingComments(const grpc::string) const { return ""; }
std::vector<grpc::string> GetAllComments() const {
return service_->doc_comment;
}
std::unique_ptr<const grpc_generator::Method> method(int i) const {
return std::unique_ptr<const grpc_generator::Method>(
- new FlatBufMethod(service_->calls.vec[i]));
+ new FlatBufMethod(service_->calls.vec[i]));
};
private:
class FlatBufPrinter : public grpc_generator::Printer {
public:
- FlatBufPrinter(std::string *str)
- : str_(str), escape_char_('$'), indent_(0) {}
+ FlatBufPrinter(std::string *str) : str_(str), escape_char_('$'), indent_(0) {}
void Print(const std::map<std::string, std::string> &vars,
const char *string_template) {
}
void Print(const char *s) {
- if (s == nullptr || std::strlen(s) == 0) {
- return;
- }
+ if (s == nullptr || std::strlen(s) == 0) { return; }
// Add this string, but for each part separated by \n, add indentation.
for (;;) {
// Current indentation.
str_->insert(str_->end(), indent_ * 2, ' ');
// See if this contains more than one line.
- const char * lf = strchr(s, '\n');
+ const char *lf = strchr(s, '\n');
if (lf) {
(*str_) += std::string(s, lf + 1);
s = lf + 1;
}
void Indent() { indent_++; }
- void Outdent() { indent_--; assert(indent_ >= 0); }
+ void Outdent() {
+ indent_--;
+ assert(indent_ >= 0);
+ }
private:
std::string *str_;
class FlatBufFile : public grpc_generator::File {
public:
- enum Language {
- kLanguageGo,
- kLanguageCpp,
- kLanguageJava
- };
+ enum Language { kLanguageGo, kLanguageCpp, kLanguageJava };
- FlatBufFile(
- const Parser &parser, const std::string &file_name, Language language)
- : parser_(parser), file_name_(file_name), language_(language) {}
+ FlatBufFile(const Parser &parser, const std::string &file_name,
+ Language language)
+ : parser_(parser), file_name_(file_name), language_(language) {}
FlatBufFile &operator=(const FlatBufFile &);
- grpc::string GetLeadingComments(const grpc::string) const {
- return "";
- }
- grpc::string GetTrailingComments(const grpc::string) const {
- return "";
- }
+ grpc::string GetLeadingComments(const grpc::string) const { return ""; }
+ grpc::string GetTrailingComments(const grpc::string) const { return ""; }
std::vector<grpc::string> GetAllComments() const {
return std::vector<grpc::string>();
}
};
std::unique_ptr<const grpc_generator::Service> service(int i) const {
- return std::unique_ptr<const grpc_generator::Service> (
- new FlatBufService(parser_.services_.vec[i]));
+ return std::unique_ptr<const grpc_generator::Service>(
+ new FlatBufService(parser_.services_.vec[i]));
}
- std::unique_ptr<grpc_generator::Printer> CreatePrinter(std::string *str) const {
- return std::unique_ptr<grpc_generator::Printer>(
- new FlatBufPrinter(str));
+ std::unique_ptr<grpc_generator::Printer> CreatePrinter(
+ std::string *str) const {
+ return std::unique_ptr<grpc_generator::Printer>(new FlatBufPrinter(str));
}
private:
public:
GoGRPCGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
- : BaseGenerator(parser, path, file_name, "", "" /*Unused*/),
- parser_(parser), path_(path), file_name_(file_name) {}
+ : BaseGenerator(parser, path, file_name, "", "" /*Unused*/),
+ parser_(parser),
+ path_(path),
+ file_name_(file_name) {}
bool generate() {
FlatBufFile file(parser_, file_name_, FlatBufFile::kLanguageGo);
auto service = file.service(i);
const Definition *def = parser_.services_.vec[i];
p.package_name = LastNamespacePart(*(def->defined_namespace));
- std::string output = grpc_go_generator::GenerateServiceSource(&file, service.get(), &p);
- std::string filename = NamespaceDir(*def->defined_namespace) + def->name + "_grpc.go";
- if (!flatbuffers::SaveFile(filename.c_str(), output, false))
- return false;
+ std::string output =
+ grpc_go_generator::GenerateServiceSource(&file, service.get(), &p);
+ std::string filename =
+ NamespaceDir(*def->defined_namespace) + def->name + "_grpc.go";
+ if (!flatbuffers::SaveFile(filename.c_str(), output, false)) return false;
}
return true;
}
const std::string &path_, &file_name_;
};
-bool GenerateGoGRPC(const Parser &parser,
- const std::string &path,
+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) {
+ for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
+ ++it) {
if (!(*it)->generated) nservices++;
}
if (!nservices) return true;
return GoGRPCGenerator(parser, path, file_name).generate();
}
-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) {
int nservices = 0;
- for (auto it = parser.services_.vec.begin();
- it != parser.services_.vec.end(); ++it) {
+ for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end();
+ ++it) {
if (!(*it)->generated) nservices++;
}
if (!nservices) return true;
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*/),
parser_(parser),
path_(path),
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 =
}
protected:
- const Parser& parser_;
+ const Parser &parser_;
const std::string &path_, &file_name_;
};
-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) {
} // namespace flatbuffers
#if defined(_MSC_VER)
-#pragma warning(pop)
+# pragma warning(pop)
#endif
*/
// independent from idl_parser, since this code is not needed for most clients
-#include <unordered_set>
-#include <unordered_map>
#include <cassert>
+#include <unordered_map>
+#include <unordered_set>
+#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#include "flatbuffers/code_generators.h"
namespace flatbuffers {
std::string target_namespace;
};
-const JsLanguageParameters& GetJsLangParams(IDLOptions::Language lang) {
+const JsLanguageParameters &GetJsLangParams(IDLOptions::Language lang) {
static JsLanguageParameters js_language_parameters[] = {
{
- IDLOptions::kJs,
- ".js",
+ IDLOptions::kJs,
+ ".js",
},
{
- IDLOptions::kTs,
- ".ts",
+ IDLOptions::kTs,
+ ".ts",
},
};
public:
typedef std::unordered_set<std::string> imported_fileset;
typedef std::unordered_multimap<std::string, ReexportDescription>
- reexport_map;
+ reexport_map;
JsGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "", "."),
- lang_(GetJsLangParams(parser_.opts.lang))
- {
- };
+ lang_(GetJsLangParams(parser_.opts.lang)){};
// Iterate through all definitions we haven't generate code for (enums,
// structs, and tables) and output them to a single file.
bool generate() {
// Generate reexports, which might not have been explicitly imported using the
// "export import" trick
- void generateReexports(std::string *code_ptr,
- const reexport_map &reexports,
+ void generateReexports(std::string *code_ptr, const reexport_map &reexports,
imported_fileset imported_files) {
- if (!parser_.opts.reexport_ts_modules ||
- lang_.language != IDLOptions::kTs) {
- return;
- }
+ if (!parser_.opts.reexport_ts_modules ||
+ lang_.language != IDLOptions::kTs) {
+ return;
+ }
- std::string &code = *code_ptr;
- for (auto it = reexports.begin(); it != reexports.end(); ++it) {
- const auto &file = *it;
- const auto basename =
- flatbuffers::StripPath(flatbuffers::StripExtension(file.first));
- if (basename != file_name_) {
- const auto file_name = basename + kGeneratedFileNamePostfix;
-
- if (imported_files.find(file.first) == imported_files.end()) {
- code += GenPrefixedImport(file.first, file_name);
- imported_files.emplace(file.first);
- }
+ std::string &code = *code_ptr;
+ for (auto it = reexports.begin(); it != reexports.end(); ++it) {
+ const auto &file = *it;
+ const auto basename =
+ flatbuffers::StripPath(flatbuffers::StripExtension(file.first));
+ if (basename != file_name_) {
+ const auto file_name = basename + kGeneratedFileNamePostfix;
- code += "export namespace " + file.second.target_namespace + " { \n";
- code += "export import " + file.second.symbol + " = ";
- code += GenFileNamespacePrefix(file.first) + "." +
- file.second.source_namespace + "." + file.second.symbol +
- "; }\n";
+ if (imported_files.find(file.first) == imported_files.end()) {
+ code += GenPrefixedImport(file.first, file_name);
+ imported_files.emplace(file.first);
}
+
+ code += "export namespace " + file.second.target_namespace + " { \n";
+ code += "export import " + file.second.symbol + " = ";
+ code += GenFileNamespacePrefix(file.first) + "." +
+ file.second.source_namespace + "." + file.second.symbol +
+ "; }\n";
}
+ }
}
// Generate code for all enums.
- void generateEnums(std::string *enum_code_ptr,
- std::string *exports_code_ptr,
+ void generateEnums(std::string *enum_code_ptr, std::string *exports_code_ptr,
reexport_map &reexports) {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
}
}
void GenNamespaces(std::string *code_ptr, std::string *exports_ptr) {
- if (lang_.language == IDLOptions::kTs &&
- parser_.opts.skip_flatbuffers_import) {
- return;
- }
-
- std::set<std::string> namespaces;
+ if (lang_.language == IDLOptions::kTs &&
+ parser_.opts.skip_flatbuffers_import) {
+ return;
+ }
- for (auto it = parser_.namespaces_.begin();
- it != parser_.namespaces_.end(); ++it) {
- std::string namespace_so_far;
+ std::set<std::string> namespaces;
- // Gather all parent namespaces for this namespace
- for (auto component = (*it)->components.begin();
- component != (*it)->components.end(); ++component) {
- if (!namespace_so_far.empty()) {
- namespace_so_far += '.';
+ for (auto it = parser_.namespaces_.begin(); it != parser_.namespaces_.end();
+ ++it) {
+ std::string namespace_so_far;
+
+ // Gather all parent namespaces for this namespace
+ for (auto component = (*it)->components.begin();
+ component != (*it)->components.end(); ++component) {
+ if (!namespace_so_far.empty()) { namespace_so_far += '.'; }
+ namespace_so_far += *component;
+ namespaces.insert(namespace_so_far);
}
- namespace_so_far += *component;
- namespaces.insert(namespace_so_far);
}
- }
- // Make sure parent namespaces come before child namespaces
- std::vector<std::string> sorted_namespaces(
- namespaces.begin(), namespaces.end());
- std::sort(sorted_namespaces.begin(), sorted_namespaces.end());
+ // Make sure parent namespaces come before child namespaces
+ std::vector<std::string> sorted_namespaces(namespaces.begin(),
+ namespaces.end());
+ std::sort(sorted_namespaces.begin(), sorted_namespaces.end());
- // Emit namespaces in a form that Closure Compiler can optimize
- std::string &code = *code_ptr;
- std::string &exports = *exports_ptr;
- for (auto it = sorted_namespaces.begin();
- it != sorted_namespaces.end(); it++) {
- if (lang_.language == IDLOptions::kTs) {
- if (it->find('.') == std::string::npos) {
- code += "import { flatbuffers } from \"./flatbuffers\"\n";
- break;
- }
- } else {
- code += "/**\n * @const\n * @namespace\n */\n";
- if (it->find('.') == std::string::npos) {
- code += "var ";
- if(parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportSymbol('" + *it + "', " + *it + ");\n";
- } else {
- exports += "this." + *it + " = " + *it + ";\n";
+ // Emit namespaces in a form that Closure Compiler can optimize
+ std::string &code = *code_ptr;
+ std::string &exports = *exports_ptr;
+ for (auto it = sorted_namespaces.begin(); it != sorted_namespaces.end();
+ it++) {
+ if (lang_.language == IDLOptions::kTs) {
+ if (it->find('.') == std::string::npos) {
+ code += "import { flatbuffers } from \"./flatbuffers\"\n";
+ break;
}
+ } else {
+ code += "/**\n * @const\n * @namespace\n */\n";
+ if (it->find('.') == std::string::npos) {
+ code += "var ";
+ if (parser_.opts.use_goog_js_export_format) {
+ exports += "goog.exportSymbol('" + *it + "', " + *it + ");\n";
+ } else {
+ exports += "this." + *it + " = " + *it + ";\n";
+ }
+ }
+ code += *it + " = " + *it + " || {};\n\n";
}
- code += *it + " = " + *it + " || {};\n\n";
}
}
-}
-// Generate a documentation comment, if available.
-static void GenDocComment(const std::vector<std::string> &dc,
- std::string *code_ptr,
- const std::string &extra_lines,
- const char *indent = nullptr) {
- if (dc.empty() && extra_lines.empty()) {
- // Don't output empty comment blocks with 0 lines of comment content.
- return;
- }
+ // Generate a documentation comment, if available.
+ static void GenDocComment(const std::vector<std::string> &dc,
+ std::string *code_ptr,
+ const std::string &extra_lines,
+ const char *indent = nullptr) {
+ if (dc.empty() && extra_lines.empty()) {
+ // Don't output empty comment blocks with 0 lines of comment content.
+ return;
+ }
- std::string &code = *code_ptr;
- if (indent) code += indent;
- code += "/**\n";
- for (auto it = dc.begin(); it != dc.end(); ++it) {
+ std::string &code = *code_ptr;
if (indent) code += indent;
- code += " *" + *it + "\n";
- }
- if (!extra_lines.empty()) {
- if (!dc.empty()) {
+ code += "/**\n";
+ for (auto it = dc.begin(); it != dc.end(); ++it) {
if (indent) code += indent;
- code += " *\n";
+ code += " *" + *it + "\n";
}
- if (indent) code += indent;
- std::string::size_type start = 0;
- for (;;) {
- auto end = extra_lines.find('\n', start);
- if (end != std::string::npos) {
- code += " * " + extra_lines.substr(start, end - start) + "\n";
- start = end + 1;
- } else {
- code += " * " + extra_lines.substr(start) + "\n";
- break;
+ if (!extra_lines.empty()) {
+ if (!dc.empty()) {
+ if (indent) code += indent;
+ code += " *\n";
+ }
+ if (indent) code += indent;
+ std::string::size_type start = 0;
+ for (;;) {
+ auto end = extra_lines.find('\n', start);
+ if (end != std::string::npos) {
+ code += " * " + extra_lines.substr(start, end - start) + "\n";
+ start = end + 1;
+ } else {
+ code += " * " + extra_lines.substr(start) + "\n";
+ break;
+ }
}
}
+ if (indent) code += indent;
+ code += " */\n";
}
- if (indent) code += indent;
- code += " */\n";
-}
-static void GenDocComment(std::string *code_ptr,
- const std::string &extra_lines) {
- GenDocComment(std::vector<std::string>(), code_ptr, extra_lines);
-}
+ static void GenDocComment(std::string *code_ptr,
+ const std::string &extra_lines) {
+ GenDocComment(std::vector<std::string>(), code_ptr, extra_lines);
+ }
-// Generate an enum declaration and an enum string lookup table.
-void GenEnum(EnumDef &enum_def, std::string *code_ptr,
- std::string *exports_ptr, reexport_map &reexports) {
- if (enum_def.generated) return;
- std::string &code = *code_ptr;
- std::string &exports = *exports_ptr;
- GenDocComment(enum_def.doc_comment, code_ptr, "@enum");
- std::string ns = GetNameSpace(enum_def);
- if (lang_.language == IDLOptions::kTs) {
- if (!ns.empty()) {
- code += "export namespace " + ns + "{\n";
- }
- code += "export enum " + enum_def.name + "{\n";
- } else {
- if (enum_def.defined_namespace->components.empty()) {
- code += "var ";
- if(parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportSymbol('" + enum_def.name + "', " +
- enum_def.name + ");\n";
- } else {
- exports += "this." + enum_def.name + " = " + enum_def.name + ";\n";
+ // Generate an enum declaration and an enum string lookup table.
+ void GenEnum(EnumDef &enum_def, std::string *code_ptr,
+ std::string *exports_ptr, reexport_map &reexports) {
+ if (enum_def.generated) return;
+ std::string &code = *code_ptr;
+ std::string &exports = *exports_ptr;
+ GenDocComment(enum_def.doc_comment, code_ptr, "@enum");
+ std::string ns = GetNameSpace(enum_def);
+ if (lang_.language == IDLOptions::kTs) {
+ if (!ns.empty()) { code += "export namespace " + ns + "{\n"; }
+ code += "export enum " + enum_def.name + "{\n";
+ } else {
+ if (enum_def.defined_namespace->components.empty()) {
+ code += "var ";
+ if (parser_.opts.use_goog_js_export_format) {
+ exports += "goog.exportSymbol('" + enum_def.name + "', " +
+ enum_def.name + ");\n";
+ } else {
+ exports += "this." + enum_def.name + " = " + enum_def.name + ";\n";
+ }
}
+ code += WrapInNameSpace(enum_def) + " = {\n";
}
- code += WrapInNameSpace(enum_def) + " = {\n";
- }
- for (auto it = enum_def.vals.vec.begin();
- it != enum_def.vals.vec.end(); ++it) {
- auto &ev = **it;
- if (!ev.doc_comment.empty()) {
- if (it != enum_def.vals.vec.begin()) {
- code += '\n';
+ for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
+ ++it) {
+ auto &ev = **it;
+ if (!ev.doc_comment.empty()) {
+ if (it != enum_def.vals.vec.begin()) { code += '\n'; }
+ GenDocComment(ev.doc_comment, code_ptr, "", " ");
+ }
+ code += " " + ev.name;
+ code += lang_.language == IDLOptions::kTs ? "= " : ": ";
+ code += NumToString(ev.value);
+ code += (it + 1) != enum_def.vals.vec.end() ? ",\n" : "\n";
+
+ if (ev.union_type.struct_def) {
+ ReexportDescription desc = { ev.name,
+ GetNameSpace(*ev.union_type.struct_def),
+ GetNameSpace(enum_def) };
+ reexports.insert(
+ std::make_pair(ev.union_type.struct_def->file, std::move(desc)));
}
- GenDocComment(ev.doc_comment, code_ptr, "", " ");
- }
- code += " " + ev.name;
- code += lang_.language == IDLOptions::kTs ? "= " : ": ";
- code += NumToString(ev.value);
- code += (it + 1) != enum_def.vals.vec.end() ? ",\n" : "\n";
-
- if (ev.union_type.struct_def) {
- ReexportDescription desc = {
- ev.name,
- GetNameSpace(*ev.union_type.struct_def),
- GetNameSpace(enum_def)
- };
- reexports.insert(std::make_pair(ev.union_type.struct_def->file,
- std::move(desc)));
}
- }
- if (lang_.language == IDLOptions::kTs && !ns.empty()) {
- code += "}";
+ if (lang_.language == IDLOptions::kTs && !ns.empty()) { code += "}"; }
+ code += "};\n\n";
}
- code += "};\n\n";
-}
-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:
- 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 "Table";
+ 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:
+ 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 "Table";
+ }
}
-}
-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_UNION: return GenBBAccess() + ".__union" + arguments;
- case BASE_TYPE_VECTOR: return GenGetter(type.VectorType(), arguments);
- default: {
- auto getter = GenBBAccess() + ".read" + MakeCamel(GenType(type)) + arguments;
- if (type.base_type == BASE_TYPE_BOOL) {
- getter = "!!" + getter;
- }
- if (type.enum_def) {
- getter = "/** @type {" + WrapInNameSpace(*type.enum_def) + "} */ (" +
- getter + ")";
+ 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_UNION: return GenBBAccess() + ".__union" + arguments;
+ case BASE_TYPE_VECTOR: return GenGetter(type.VectorType(), arguments);
+ default: {
+ auto getter =
+ GenBBAccess() + ".read" + MakeCamel(GenType(type)) + arguments;
+ if (type.base_type == BASE_TYPE_BOOL) { getter = "!!" + getter; }
+ if (type.enum_def) {
+ getter = "/** @type {" + WrapInNameSpace(*type.enum_def) + "} */ (" +
+ getter + ")";
+ }
+ return getter;
}
- return getter;
}
}
-}
-std::string GenBBAccess() {
- return lang_.language == IDLOptions::kTs ? "this.bb!" : "this.bb";
-}
+ std::string GenBBAccess() {
+ return lang_.language == IDLOptions::kTs ? "this.bb!" : "this.bb";
+ }
-std::string GenDefaultValue(const Value &value, const std::string &context) {
- if (value.type.enum_def) {
- if (auto val = value.type.enum_def->ReverseLookup(
- atoi(value.constant.c_str()), false)) {
- if (lang_.language == IDLOptions::kTs) {
- return GenPrefixedTypeName(WrapInNameSpace(*value.type.enum_def),
- value.type.enum_def->file) + "." + val->name;
+ std::string GenDefaultValue(const Value &value, const std::string &context) {
+ if (value.type.enum_def) {
+ if (auto val = value.type.enum_def->ReverseLookup(
+ atoi(value.constant.c_str()), false)) {
+ if (lang_.language == IDLOptions::kTs) {
+ return GenPrefixedTypeName(WrapInNameSpace(*value.type.enum_def),
+ value.type.enum_def->file) +
+ "." + val->name;
+ } else {
+ return WrapInNameSpace(*value.type.enum_def) + "." + val->name;
+ }
} else {
- return WrapInNameSpace(*value.type.enum_def) + "." + val->name;
+ return "/** @type {" + WrapInNameSpace(*value.type.enum_def) +
+ "} */ (" + value.constant + ")";
}
- } else {
- return "/** @type {" + WrapInNameSpace(*value.type.enum_def) + "} */ ("
- + value.constant + ")";
}
- }
- switch (value.type.base_type) {
- case BASE_TYPE_BOOL:
- return value.constant == "0" ? "false" : "true";
+ switch (value.type.base_type) {
+ 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: {
- int64_t constant = StringToInt(value.constant.c_str());
- return context + ".createLong(" + NumToString((int32_t)constant) +
- ", " + NumToString((int32_t)(constant >> 32)) + ")";
- }
+ case BASE_TYPE_LONG:
+ case BASE_TYPE_ULONG: {
+ int64_t constant = StringToInt(value.constant.c_str());
+ return context + ".createLong(" + NumToString((int32_t)constant) +
+ ", " + NumToString((int32_t)(constant >> 32)) + ")";
+ }
- default:
- return value.constant;
+ default: return value.constant;
+ }
}
-}
-std::string GenTypeName(const Type &type, bool input, bool allowNull = false) {
- if (!input) {
- if (type.base_type == BASE_TYPE_STRING || type.base_type == BASE_TYPE_STRUCT) {
- std::string name;
- if (type.base_type == BASE_TYPE_STRING) {
- name = "string|Uint8Array";
- } else {
- name = WrapInNameSpace(*type.struct_def);
+ std::string GenTypeName(const Type &type, bool input,
+ bool allowNull = false) {
+ if (!input) {
+ if (type.base_type == BASE_TYPE_STRING ||
+ type.base_type == BASE_TYPE_STRUCT) {
+ std::string name;
+ if (type.base_type == BASE_TYPE_STRING) {
+ name = "string|Uint8Array";
+ } else {
+ name = WrapInNameSpace(*type.struct_def);
+ }
+ return (allowNull) ? (name + "|null") : (name);
}
- return (allowNull) ? (name + "|null") : (name);
}
- }
- switch (type.base_type) {
- case BASE_TYPE_BOOL: return "boolean";
- case BASE_TYPE_LONG:
- case BASE_TYPE_ULONG: return "flatbuffers.Long";
- default:
- if (IsScalar(type.base_type)) {
- if (type.enum_def) {
- return WrapInNameSpace(*type.enum_def);
+ switch (type.base_type) {
+ case BASE_TYPE_BOOL: return "boolean";
+ case BASE_TYPE_LONG:
+ case BASE_TYPE_ULONG: return "flatbuffers.Long";
+ default:
+ if (IsScalar(type.base_type)) {
+ if (type.enum_def) { return WrapInNameSpace(*type.enum_def); }
+ return "number";
}
- return "number";
- }
- return "flatbuffers.Offset";
+ return "flatbuffers.Offset";
+ }
}
-}
-// Returns the method name for use with add/put calls.
-static std::string GenWriteMethod(const Type &type) {
- // Forward to signed versions since unsigned versions don't exist
- switch (type.base_type) {
- case BASE_TYPE_UTYPE:
- 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;
- }
+ // Returns the method name for use with add/put calls.
+ static std::string GenWriteMethod(const Type &type) {
+ // Forward to signed versions since unsigned versions don't exist
+ switch (type.base_type) {
+ case BASE_TYPE_UTYPE:
+ 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)
- ? MakeCamel(GenType(type))
- : (IsStruct(type) ? "Struct" : "Offset");
-}
+ return IsScalar(type.base_type) ? MakeCamel(GenType(type))
+ : (IsStruct(type) ? "Struct" : "Offset");
+ }
-template <typename T>
-static std::string MaybeAdd(T value) {
- return value != 0 ? " + " + NumToString(value) : "";
-}
+ template<typename T> static std::string MaybeAdd(T value) {
+ return value != 0 ? " + " + NumToString(value) : "";
+ }
-template <typename T>
-static std::string MaybeScale(T value) {
- return value != 1 ? " * " + NumToString(value) : "";
-}
+ template<typename T> static std::string MaybeScale(T value) {
+ return value != 1 ? " * " + NumToString(value) : "";
+ }
-static std::string GenFileNamespacePrefix(const std::string &file) {
- return "NS" + std::to_string(
- static_cast<unsigned long long>(std::hash<std::string>()(file)));
-}
+ static std::string GenFileNamespacePrefix(const std::string &file) {
+ return "NS" + std::to_string(static_cast<unsigned long long>(
+ std::hash<std::string>()(file)));
+ }
-static std::string GenPrefixedImport(const std::string &full_file_name,
- const std::string &base_file_name) {
- return "import * as "+ GenFileNamespacePrefix(full_file_name) +
- " from \"./" + base_file_name + "\";\n";
-}
+ static std::string GenPrefixedImport(const std::string &full_file_name,
+ const std::string &base_file_name) {
+ return "import * as " + GenFileNamespacePrefix(full_file_name) +
+ " from \"./" + base_file_name + "\";\n";
+ }
-// Adds a source-dependent prefix, for of import * statements.
-std::string GenPrefixedTypeName(const std::string &typeName,
- const std::string &file) {
- const auto basename =
- flatbuffers::StripPath(flatbuffers::StripExtension(file));
- if (basename == file_name_) {
- return typeName;
+ // Adds a source-dependent prefix, for of import * statements.
+ std::string GenPrefixedTypeName(const std::string &typeName,
+ const std::string &file) {
+ const auto basename =
+ flatbuffers::StripPath(flatbuffers::StripExtension(file));
+ if (basename == file_name_) { return typeName; }
+ return GenFileNamespacePrefix(file) + "." + typeName;
}
- return GenFileNamespacePrefix(file) + "." + typeName;
-}
-void GenStructArgs(const StructDef &struct_def,
- std::string *annotations,
- 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;
- 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
- // a nested struct, prefix the name with the field name.
- GenStructArgs(*field.value.type.struct_def, annotations, arguments,
- nameprefix + field.name + "_");
- } else {
- *annotations += "@param {" + GenTypeName(field.value.type, true);
- *annotations += "} " + nameprefix + field.name + "\n";
+ void GenStructArgs(const StructDef &struct_def, std::string *annotations,
+ 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;
+ 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
+ // a nested struct, prefix the name with the field name.
+ GenStructArgs(*field.value.type.struct_def, annotations, arguments,
+ nameprefix + field.name + "_");
+ } else {
+ *annotations += "@param {" + GenTypeName(field.value.type, true);
+ *annotations += "} " + nameprefix + field.name + "\n";
- if (lang_.language == IDLOptions::kTs) {
+ if (lang_.language == IDLOptions::kTs) {
*arguments += ", " + nameprefix + field.name + ": " +
GenTypeName(field.value.type, true);
- } else {
+ } else {
*arguments += ", " + nameprefix + field.name;
+ }
}
}
}
-}
-static 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;
- if (field.padding) {
- *body += " builder.pad(" + NumToString(field.padding) + ");\n";
- }
- 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
- // a nested struct, prefix the name with the field name.
- GenStructBody(*field.value.type.struct_def, body,
- nameprefix + field.name + "_");
- } else {
- *body += " builder.write" + GenWriteMethod(field.value.type) + "(";
- if (field.value.type.base_type == BASE_TYPE_BOOL) {
- *body += "+";
+ static 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;
+ if (field.padding) {
+ *body += " builder.pad(" + NumToString(field.padding) + ");\n";
+ }
+ 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
+ // a nested struct, prefix the name with the field name.
+ GenStructBody(*field.value.type.struct_def, body,
+ nameprefix + field.name + "_");
+ } else {
+ *body += " builder.write" + GenWriteMethod(field.value.type) + "(";
+ if (field.value.type.base_type == BASE_TYPE_BOOL) { *body += "+"; }
+ *body += nameprefix + field.name + ");\n";
}
- *body += nameprefix + field.name + ");\n";
}
}
-}
-// Generate an accessor struct with constructor for a flatbuffers struct.
-void GenStruct(const Parser &parser, StructDef &struct_def,
- std::string *code_ptr, std::string *exports_ptr,
- imported_fileset &imported_files) {
- if (struct_def.generated) return;
- std::string &code = *code_ptr;
- std::string &exports = *exports_ptr;
-
- std::string object_name;
- std::string object_namespace = GetNameSpace(struct_def);
-
- // Emit constructor
- if (lang_.language == IDLOptions::kTs) {
- object_name = struct_def.name;
- GenDocComment(struct_def.doc_comment, code_ptr, "@constructor");
- if (!object_namespace.empty()) {
- code += "export namespace " + object_namespace + "{\n";
- }
- code += "export class " + struct_def.name;
- code += " {\n";
- code += " /**\n";
- code += " * @type {flatbuffers.ByteBuffer}\n";
- code += " */\n";
- code += " bb: flatbuffers.ByteBuffer|null = null;\n";
- code += "\n";
- code += " /**\n";
- code += " * @type {number}\n";
- code += " */\n";
- code += " bb_pos:number = 0;\n";
- } else {
- bool isStatement = struct_def.defined_namespace->components.empty();
- object_name = WrapInNameSpace(struct_def);
- GenDocComment(struct_def.doc_comment, code_ptr, "@constructor");
- if (isStatement) {
- if(parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportSymbol('" + struct_def.name + "', " +
- struct_def.name + ");\n";
- } else {
- exports += "this." + struct_def.name + " = " + struct_def.name + ";\n";
+ // Generate an accessor struct with constructor for a flatbuffers struct.
+ void GenStruct(const Parser &parser, StructDef &struct_def,
+ std::string *code_ptr, std::string *exports_ptr,
+ imported_fileset &imported_files) {
+ if (struct_def.generated) return;
+ std::string &code = *code_ptr;
+ std::string &exports = *exports_ptr;
+
+ std::string object_name;
+ std::string object_namespace = GetNameSpace(struct_def);
+
+ // Emit constructor
+ if (lang_.language == IDLOptions::kTs) {
+ object_name = struct_def.name;
+ GenDocComment(struct_def.doc_comment, code_ptr, "@constructor");
+ if (!object_namespace.empty()) {
+ code += "export namespace " + object_namespace + "{\n";
}
- code += "function " + object_name;
+ code += "export class " + struct_def.name;
+ code += " {\n";
+ code += " /**\n";
+ code += " * @type {flatbuffers.ByteBuffer}\n";
+ code += " */\n";
+ code += " bb: flatbuffers.ByteBuffer|null = null;\n";
+ code += "\n";
+ code += " /**\n";
+ code += " * @type {number}\n";
+ code += " */\n";
+ code += " bb_pos:number = 0;\n";
} else {
- code += object_name + " = function";
+ bool isStatement = struct_def.defined_namespace->components.empty();
+ object_name = WrapInNameSpace(struct_def);
+ GenDocComment(struct_def.doc_comment, code_ptr, "@constructor");
+ if (isStatement) {
+ if (parser_.opts.use_goog_js_export_format) {
+ exports += "goog.exportSymbol('" + struct_def.name + "', " +
+ struct_def.name + ");\n";
+ } else {
+ exports +=
+ "this." + struct_def.name + " = " + struct_def.name + ";\n";
+ }
+ code += "function " + object_name;
+ } else {
+ code += object_name + " = function";
+ }
+ code += "() {\n";
+ code += " /**\n";
+ code += " * @type {flatbuffers.ByteBuffer}\n";
+ code += " */\n";
+ code += " this.bb = null;\n";
+ code += "\n";
+ code += " /**\n";
+ code += " * @type {number}\n";
+ code += " */\n";
+ code += " this.bb_pos = 0;\n";
+ code += isStatement ? "}\n\n" : "};\n\n";
}
- code += "() {\n";
- code += " /**\n";
- code += " * @type {flatbuffers.ByteBuffer}\n";
- code += " */\n";
- code += " this.bb = null;\n";
- code += "\n";
- code += " /**\n";
- code += " * @type {number}\n";
- code += " */\n";
- code += " this.bb_pos = 0;\n";
- code += isStatement ? "}\n\n" : "};\n\n";
- }
- // Generate the __init method that sets the field in a pre-existing
- // accessor object. This is to allow object reuse.
- code += "/**\n";
- code += " * @param {number} i\n";
- code += " * @param {flatbuffers.ByteBuffer} bb\n";
- code += " * @returns {" + object_name + "}\n";
- code += " */\n";
-
- if (lang_.language == IDLOptions::kTs) {
- code += "__init(i:number, bb:flatbuffers.ByteBuffer):" + object_name +
- " {\n";
- } else {
- code += object_name + ".prototype.__init = function(i, bb) {\n";
- }
+ // Generate the __init method that sets the field in a pre-existing
+ // accessor object. This is to allow object reuse.
+ code += "/**\n";
+ code += " * @param {number} i\n";
+ code += " * @param {flatbuffers.ByteBuffer} bb\n";
+ code += " * @returns {" + object_name + "}\n";
+ code += " */\n";
- code += " this.bb_pos = i;\n";
- code += " this.bb = bb;\n";
- code += " return this;\n";
- code += "};\n\n";
-
- // Generate a special accessor for the table that when used as the root of a
- // FlatBuffer
- if (!struct_def.fixed) {
- GenDocComment(code_ptr,
- "@param {flatbuffers.ByteBuffer} bb\n"
- "@param {" + object_name + "=} obj\n"
- "@returns {" + object_name + "}");
if (lang_.language == IDLOptions::kTs) {
- code += "static getRootAs" + struct_def.name;
- code += "(bb:flatbuffers.ByteBuffer, obj?:" + object_name + "):" +
- object_name + " {\n";
+ code +=
+ "__init(i:number, bb:flatbuffers.ByteBuffer):" + object_name + " {\n";
} else {
- code += object_name + ".getRootAs" + struct_def.name;
- code += " = function(bb, obj) {\n";
+ code += object_name + ".prototype.__init = function(i, bb) {\n";
}
- code += " return (obj || new " + object_name;
- code += ").__init(bb.readInt32(bb.position()) + bb.position(), bb);\n";
+
+ code += " this.bb_pos = i;\n";
+ code += " this.bb = bb;\n";
+ code += " return this;\n";
code += "};\n\n";
- // Generate the identifier check method
- if (parser_.root_struct_def_ == &struct_def &&
- !parser_.file_identifier_.empty()) {
+ // Generate a special accessor for the table that when used as the root of a
+ // FlatBuffer
+ if (!struct_def.fixed) {
GenDocComment(code_ptr,
- "@param {flatbuffers.ByteBuffer} bb\n"
- "@returns {boolean}");
+ "@param {flatbuffers.ByteBuffer} bb\n"
+ "@param {" +
+ object_name +
+ "=} obj\n"
+ "@returns {" +
+ object_name + "}");
if (lang_.language == IDLOptions::kTs) {
- code +=
- "static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean {\n";
+ code += "static getRootAs" + struct_def.name;
+ code += "(bb:flatbuffers.ByteBuffer, obj?:" + object_name +
+ "):" + object_name + " {\n";
} else {
- code += object_name + ".bufferHasIdentifier = function(bb) {\n";
+ code += object_name + ".getRootAs" + struct_def.name;
+ code += " = function(bb, obj) {\n";
}
+ code += " return (obj || new " + object_name;
+ code += ").__init(bb.readInt32(bb.position()) + bb.position(), bb);\n";
+ code += "};\n\n";
- code += " return bb.__has_identifier('" + parser_.file_identifier_;
- code += "');\n};\n\n";
- }
- }
-
- // Emit field accessors
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (field.deprecated) continue;
- auto offset_prefix = " var offset = " + GenBBAccess() +
- ".__offset(this.bb_pos, " + NumToString(field.value.offset) +
- ");\n return offset ? ";
-
- // Emit a scalar field
- if (IsScalar(field.value.type.base_type) ||
- field.value.type.base_type == BASE_TYPE_STRING) {
- GenDocComment(field.doc_comment, code_ptr,
- std::string(field.value.type.base_type == BASE_TYPE_STRING ?
- "@param {flatbuffers.Encoding=} optionalEncoding\n" : "") +
- "@returns {" + GenTypeName(field.value.type, false, true) + "}");
- if (lang_.language == IDLOptions::kTs) {
- std::string prefix = MakeCamel(field.name, false) + "(";
- if (field.value.type.base_type == BASE_TYPE_STRING) {
- code += prefix + "):string|null\n";
- code += prefix + "optionalEncoding:flatbuffers.Encoding"+"):" +
- GenTypeName(field.value.type, false, true)+"\n";
- code += prefix + "optionalEncoding?:any";
- } else {
- code += prefix;
- }
- if (field.value.type.enum_def) {
- code += "):" +
- GenPrefixedTypeName(GenTypeName(field.value.type, false, true),
- field.value.type.enum_def->file) + " {\n";
+ // Generate the identifier check method
+ if (parser_.root_struct_def_ == &struct_def &&
+ !parser_.file_identifier_.empty()) {
+ GenDocComment(code_ptr,
+ "@param {flatbuffers.ByteBuffer} bb\n"
+ "@returns {boolean}");
+ if (lang_.language == IDLOptions::kTs) {
+ code +=
+ "static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean "
+ "{\n";
} else {
- code += "):" + GenTypeName(field.value.type, false, true) + " {\n";
- }
- } else {
- code += object_name + ".prototype." + MakeCamel(field.name, false);
- code += " = function(";
- if (field.value.type.base_type == BASE_TYPE_STRING) {
- code += "optionalEncoding";
+ code += object_name + ".bufferHasIdentifier = function(bb) {\n";
}
- code += ") {\n";
- }
- if (struct_def.fixed) {
- code += " return " + GenGetter(field.value.type, "(this.bb_pos" +
- MaybeAdd(field.value.offset) + ")") + ";\n";
- } else {
- std::string index = "this.bb_pos + offset";
- if (field.value.type.base_type == BASE_TYPE_STRING) {
- index += ", optionalEncoding";
- }
- code += offset_prefix + GenGetter(field.value.type,
- "(" + index + ")") + " : " + GenDefaultValue(field.value, GenBBAccess());
- code += ";\n";
+ code += " return bb.__has_identifier('" + parser_.file_identifier_;
+ code += "');\n};\n\n";
}
}
- // Emit an object field
- else {
- switch (field.value.type.base_type) {
- case BASE_TYPE_STRUCT: {
- auto type = WrapInNameSpace(*field.value.type.struct_def);
- GenDocComment(field.doc_comment, code_ptr,
- "@param {" + type + "=} obj\n@returns {" + type + "|null}");
- if (lang_.language == IDLOptions::kTs) {
- type = GenPrefixedTypeName(type, field.value.type.struct_def->file);
- code += MakeCamel(field.name, false);
- code += "(obj?:" + type + "):" + type + "|null {\n";
+ // Emit field accessors
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ auto offset_prefix =
+ " var offset = " + GenBBAccess() + ".__offset(this.bb_pos, " +
+ NumToString(field.value.offset) + ");\n return offset ? ";
+
+ // Emit a scalar field
+ if (IsScalar(field.value.type.base_type) ||
+ field.value.type.base_type == BASE_TYPE_STRING) {
+ GenDocComment(
+ field.doc_comment, code_ptr,
+ std::string(
+ field.value.type.base_type == BASE_TYPE_STRING
+ ? "@param {flatbuffers.Encoding=} optionalEncoding\n"
+ : "") +
+ "@returns {" + GenTypeName(field.value.type, false, true) +
+ "}");
+ if (lang_.language == IDLOptions::kTs) {
+ std::string prefix = MakeCamel(field.name, false) + "(";
+ if (field.value.type.base_type == BASE_TYPE_STRING) {
+ code += prefix + "):string|null\n";
+ code += prefix + "optionalEncoding:flatbuffers.Encoding" +
+ "):" + GenTypeName(field.value.type, false, true) + "\n";
+ code += prefix + "optionalEncoding?:any";
} else {
- code += object_name + ".prototype." + MakeCamel(field.name, false);
- code += " = function(obj) {\n";
+ code += prefix;
}
-
- if (struct_def.fixed) {
- code += " return (obj || new " + type;
- code += ").__init(this.bb_pos";
- code += MaybeAdd(field.value.offset) + ", " + GenBBAccess() + ");\n";
+ if (field.value.type.enum_def) {
+ code +=
+ "):" +
+ GenPrefixedTypeName(GenTypeName(field.value.type, false, true),
+ field.value.type.enum_def->file) +
+ " {\n";
} else {
- code += offset_prefix + "(obj || new " + type + ").__init(";
- code += field.value.type.struct_def->fixed
- ? "this.bb_pos + offset"
- : GenBBAccess() + ".__indirect(this.bb_pos + offset)";
- code += ", " + GenBBAccess() + ") : null;\n";
+ code += "):" + GenTypeName(field.value.type, false, true) + " {\n";
}
-
- if (lang_.language == IDLOptions::kTs) {
- imported_files.insert(field.value.type.struct_def->file);
+ } else {
+ code += object_name + ".prototype." + MakeCamel(field.name, false);
+ code += " = function(";
+ if (field.value.type.base_type == BASE_TYPE_STRING) {
+ code += "optionalEncoding";
}
-
- break;
+ code += ") {\n";
}
- case BASE_TYPE_VECTOR: {
- auto vectortype = field.value.type.VectorType();
- auto vectortypename = GenTypeName(vectortype, false);
- auto inline_size = InlineSize(vectortype);
- auto index = GenBBAccess() + ".__vector(this.bb_pos + offset) + index" +
- MaybeScale(inline_size);
- std::string args = "@param {number} index\n";
- std::string ret_type;
- bool is_union = false;
- switch (vectortype.base_type) {
- case BASE_TYPE_STRUCT:
- args += "@param {" + vectortypename + "=} obj\n";
- ret_type = vectortypename;
- break;
- case BASE_TYPE_STRING:
- args += "@param {flatbuffers.Encoding=} optionalEncoding\n";
- ret_type = vectortypename;
- break;
- case BASE_TYPE_UNION:
- args += "@param {flatbuffers.Table=} obj\n";
- ret_type = "?flatbuffers.Table";
- is_union = true;
- break;
- default:
- ret_type = vectortypename;
+ if (struct_def.fixed) {
+ code +=
+ " return " +
+ GenGetter(field.value.type,
+ "(this.bb_pos" + MaybeAdd(field.value.offset) + ")") +
+ ";\n";
+ } else {
+ std::string index = "this.bb_pos + offset";
+ if (field.value.type.base_type == BASE_TYPE_STRING) {
+ index += ", optionalEncoding";
}
- GenDocComment(field.doc_comment, code_ptr, args +
- "@returns {" + ret_type + "}");
- if (lang_.language == IDLOptions::kTs) {
- std::string prefix = MakeCamel(field.name, false);
- if (is_union) {
- prefix += "<T extends flatbuffers.Table>";
+ code += offset_prefix +
+ GenGetter(field.value.type, "(" + index + ")") + " : " +
+ GenDefaultValue(field.value, GenBBAccess());
+ code += ";\n";
+ }
+ }
+
+ // Emit an object field
+ else {
+ switch (field.value.type.base_type) {
+ case BASE_TYPE_STRUCT: {
+ auto type = WrapInNameSpace(*field.value.type.struct_def);
+ GenDocComment(
+ field.doc_comment, code_ptr,
+ "@param {" + type + "=} obj\n@returns {" + type + "|null}");
+ if (lang_.language == IDLOptions::kTs) {
+ type =
+ GenPrefixedTypeName(type, field.value.type.struct_def->file);
+ code += MakeCamel(field.name, false);
+ code += "(obj?:" + type + "):" + type + "|null {\n";
+ } else {
+ code +=
+ object_name + ".prototype." + MakeCamel(field.name, false);
+ code += " = function(obj) {\n";
}
- prefix += "(index: number";
- if (is_union) {
- vectortypename = "T";
- code += prefix + ", obj:T";
- } else if (vectortype.base_type == BASE_TYPE_STRUCT) {
- vectortypename = GenPrefixedTypeName(vectortypename,
- vectortype.struct_def->file);
- code += prefix + ", obj?:" + vectortypename;
- imported_files.insert(vectortype.struct_def->file);
- } else if (vectortype.base_type == BASE_TYPE_STRING) {
- code += prefix + "):string\n";
- code += prefix + ",optionalEncoding:flatbuffers.Encoding" + "):" +
- vectortypename + "\n";
- code += prefix + ",optionalEncoding?:any";
+
+ if (struct_def.fixed) {
+ code += " return (obj || new " + type;
+ code += ").__init(this.bb_pos";
+ code +=
+ MaybeAdd(field.value.offset) + ", " + GenBBAccess() + ");\n";
} else {
- code += prefix;
+ code += offset_prefix + "(obj || new " + type + ").__init(";
+ code += field.value.type.struct_def->fixed
+ ? "this.bb_pos + offset"
+ : GenBBAccess() + ".__indirect(this.bb_pos + offset)";
+ code += ", " + GenBBAccess() + ") : null;\n";
}
- code += "):" + vectortypename + "|null {\n";
- } else {
- code += object_name + ".prototype." + MakeCamel(field.name, false);
- code += " = function(index";
- if (vectortype.base_type == BASE_TYPE_STRUCT || is_union) {
- code += ", obj";
- } else if (vectortype.base_type == BASE_TYPE_STRING) {
- code += ", optionalEncoding";
+
+ if (lang_.language == IDLOptions::kTs) {
+ imported_files.insert(field.value.type.struct_def->file);
}
- code += ") {\n";
+
+ break;
}
- if (vectortype.base_type == BASE_TYPE_STRUCT) {
- code += offset_prefix + "(obj || new " + vectortypename;
- code += ").__init(";
- code += vectortype.struct_def->fixed
- ? index
- : GenBBAccess() + ".__indirect(" + index + ")";
- code += ", " + GenBBAccess() + ")";
- } else {
- if (is_union) {
- index = "obj, " + index;
- } else if (vectortype.base_type == BASE_TYPE_STRING) {
- index += ", optionalEncoding";
+ case BASE_TYPE_VECTOR: {
+ auto vectortype = field.value.type.VectorType();
+ auto vectortypename = GenTypeName(vectortype, false);
+ auto inline_size = InlineSize(vectortype);
+ auto index = GenBBAccess() +
+ ".__vector(this.bb_pos + offset) + index" +
+ MaybeScale(inline_size);
+ std::string args = "@param {number} index\n";
+ std::string ret_type;
+ bool is_union = false;
+ switch (vectortype.base_type) {
+ case BASE_TYPE_STRUCT:
+ args += "@param {" + vectortypename + "=} obj\n";
+ ret_type = vectortypename;
+ break;
+ case BASE_TYPE_STRING:
+ args += "@param {flatbuffers.Encoding=} optionalEncoding\n";
+ ret_type = vectortypename;
+ break;
+ case BASE_TYPE_UNION:
+ args += "@param {flatbuffers.Table=} obj\n";
+ ret_type = "?flatbuffers.Table";
+ is_union = true;
+ break;
+ default: ret_type = vectortypename;
}
- code += offset_prefix + GenGetter(vectortype, "(" + index + ")");
- }
- code += " : ";
- if (field.value.type.element == BASE_TYPE_BOOL) {
- code += "false";
- } else if (field.value.type.element == BASE_TYPE_LONG ||
- field.value.type.element == BASE_TYPE_ULONG) {
- code += GenBBAccess() + ".createLong(0, 0)";
- } else if (IsScalar(field.value.type.element)) {
- if (field.value.type.enum_def) {
- code += "/** @type {" +
- WrapInNameSpace(*field.value.type.enum_def) + "} */ (" +
- field.value.constant + ")";
+ GenDocComment(field.doc_comment, code_ptr,
+ args + "@returns {" + ret_type + "}");
+ if (lang_.language == IDLOptions::kTs) {
+ std::string prefix = MakeCamel(field.name, false);
+ if (is_union) { prefix += "<T extends flatbuffers.Table>"; }
+ prefix += "(index: number";
+ if (is_union) {
+ vectortypename = "T";
+ code += prefix + ", obj:T";
+ } else if (vectortype.base_type == BASE_TYPE_STRUCT) {
+ vectortypename = GenPrefixedTypeName(
+ vectortypename, vectortype.struct_def->file);
+ code += prefix + ", obj?:" + vectortypename;
+ imported_files.insert(vectortype.struct_def->file);
+ } else if (vectortype.base_type == BASE_TYPE_STRING) {
+ code += prefix + "):string\n";
+ code += prefix + ",optionalEncoding:flatbuffers.Encoding" +
+ "):" + vectortypename + "\n";
+ code += prefix + ",optionalEncoding?:any";
+ } else {
+ code += prefix;
+ }
+ code += "):" + vectortypename + "|null {\n";
} else {
- code += "0";
+ code +=
+ object_name + ".prototype." + MakeCamel(field.name, false);
+ code += " = function(index";
+ if (vectortype.base_type == BASE_TYPE_STRUCT || is_union) {
+ code += ", obj";
+ } else if (vectortype.base_type == BASE_TYPE_STRING) {
+ code += ", optionalEncoding";
+ }
+ code += ") {\n";
}
- } else {
- code += "null";
- }
- code += ";\n";
- break;
- }
- case BASE_TYPE_UNION:
- GenDocComment(field.doc_comment, code_ptr,
- "@param {flatbuffers.Table} obj\n"
- "@returns {?flatbuffers.Table}");
- if (lang_.language == IDLOptions::kTs) {
- code += MakeCamel(field.name, false);
- code += "<T extends flatbuffers.Table>(obj:T):T|null {\n";
- } else {
- code += object_name + ".prototype." + MakeCamel(field.name, false);
- code += " = function(obj) {\n";
+ if (vectortype.base_type == BASE_TYPE_STRUCT) {
+ code += offset_prefix + "(obj || new " + vectortypename;
+ code += ").__init(";
+ code += vectortype.struct_def->fixed
+ ? index
+ : GenBBAccess() + ".__indirect(" + index + ")";
+ code += ", " + GenBBAccess() + ")";
+ } else {
+ if (is_union) {
+ index = "obj, " + index;
+ } else if (vectortype.base_type == BASE_TYPE_STRING) {
+ index += ", optionalEncoding";
+ }
+ code += offset_prefix + GenGetter(vectortype, "(" + index + ")");
+ }
+ code += " : ";
+ if (field.value.type.element == BASE_TYPE_BOOL) {
+ code += "false";
+ } else if (field.value.type.element == BASE_TYPE_LONG ||
+ field.value.type.element == BASE_TYPE_ULONG) {
+ code += GenBBAccess() + ".createLong(0, 0)";
+ } else if (IsScalar(field.value.type.element)) {
+ if (field.value.type.enum_def) {
+ code += "/** @type {" +
+ WrapInNameSpace(*field.value.type.enum_def) + "} */ (" +
+ field.value.constant + ")";
+ } else {
+ code += "0";
+ }
+ } else {
+ code += "null";
+ }
+ code += ";\n";
+ break;
}
- code += offset_prefix + GenGetter(field.value.type,
- "(obj, this.bb_pos + offset)") + " : null;\n";
- break;
-
- default:
- assert(0);
- }
- }
- code += "};\n\n";
-
- if(parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportProperty(" + object_name + ".prototype, '" +
- MakeCamel(field.name, false) + "', " + object_name + ".prototype." +
- MakeCamel(field.name, false) + ");\n";
- }
+ case BASE_TYPE_UNION:
+ GenDocComment(field.doc_comment, code_ptr,
+ "@param {flatbuffers.Table} obj\n"
+ "@returns {?flatbuffers.Table}");
+ if (lang_.language == IDLOptions::kTs) {
+ code += MakeCamel(field.name, false);
+ code += "<T extends flatbuffers.Table>(obj:T):T|null {\n";
+ } else {
+ code +=
+ object_name + ".prototype." + MakeCamel(field.name, false);
+ code += " = function(obj) {\n";
+ }
- // Adds the mutable scalar value to the output
- if (IsScalar(field.value.type.base_type) && parser.opts.mutable_buffer) {
- std::string annotations =
- "@param {" + GenTypeName(field.value.type, true) + "} value\n";
- GenDocComment(code_ptr, annotations +
- "@returns {boolean}");
+ code += offset_prefix +
+ GenGetter(field.value.type, "(obj, this.bb_pos + offset)") +
+ " : null;\n";
+ break;
- if (lang_.language == IDLOptions::kTs) {
- std::string type;
- if (field.value.type.enum_def) {
- type = GenPrefixedTypeName(GenTypeName(field.value.type, true),
- field.value.type.enum_def->file);
- } else {
- type = GenTypeName(field.value.type, true);
+ default: assert(0);
}
-
- code += "mutate_" + field.name + "(value:" + type + "):boolean {\n";
- } else {
- code += object_name + ".prototype.mutate_" + field.name +
- " = function(value) {\n";
}
+ code += "};\n\n";
- code += " var offset = " + GenBBAccess() + ".__offset(this.bb_pos, " +
- NumToString(field.value.offset) + ");\n\n";
- code += " if (offset === 0) {\n";
- code += " return false;\n";
- code += " }\n\n";
-
- // special case for bools, which are treated as uint8
- code += " " + GenBBAccess() + ".write" +
- MakeCamel(GenType(field.value.type)) + "(this.bb_pos + offset, ";
- if (field.value.type.base_type == BASE_TYPE_BOOL &&
- lang_.language == IDLOptions::kTs) {
- code += "+";
+ if (parser_.opts.use_goog_js_export_format) {
+ exports += "goog.exportProperty(" + object_name + ".prototype, '" +
+ MakeCamel(field.name, false) + "', " + object_name +
+ ".prototype." + MakeCamel(field.name, false) + ");\n";
}
- code += "value);\n";
- code += " return true;\n";
- code += "};\n\n";
+ // Adds the mutable scalar value to the output
+ if (IsScalar(field.value.type.base_type) && parser.opts.mutable_buffer) {
+ std::string annotations =
+ "@param {" + GenTypeName(field.value.type, true) + "} value\n";
+ GenDocComment(code_ptr, annotations + "@returns {boolean}");
- if(parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportProperty(" + object_name +
- ".prototype, 'mutate_" + field.name + "', " + object_name +
- ".prototype.mutate_" + field.name + ");\n";
- }
- }
+ if (lang_.language == IDLOptions::kTs) {
+ std::string type;
+ if (field.value.type.enum_def) {
+ type = GenPrefixedTypeName(GenTypeName(field.value.type, true),
+ field.value.type.enum_def->file);
+ } else {
+ type = GenTypeName(field.value.type, true);
+ }
- // Emit vector helpers
- if (field.value.type.base_type == BASE_TYPE_VECTOR) {
- // Emit a length helper
- GenDocComment(code_ptr, "@returns {number}");
- if (lang_.language == IDLOptions::kTs) {
- code += MakeCamel(field.name, false);
- code += "Length():number {\n" + offset_prefix;
- } else {
- code += object_name + ".prototype." + MakeCamel(field.name, false);
- code += "Length = function() {\n" + offset_prefix;
- }
+ code += "mutate_" + field.name + "(value:" + type + "):boolean {\n";
+ } else {
+ code += object_name + ".prototype.mutate_" + field.name +
+ " = function(value) {\n";
+ }
+
+ code += " var offset = " + GenBBAccess() + ".__offset(this.bb_pos, " +
+ NumToString(field.value.offset) + ");\n\n";
+ code += " if (offset === 0) {\n";
+ code += " return false;\n";
+ code += " }\n\n";
+
+ // special case for bools, which are treated as uint8
+ code += " " + GenBBAccess() + ".write" +
+ MakeCamel(GenType(field.value.type)) +
+ "(this.bb_pos + offset, ";
+ if (field.value.type.base_type == BASE_TYPE_BOOL &&
+ lang_.language == IDLOptions::kTs) {
+ code += "+";
+ }
- code += GenBBAccess() + ".__vector_len(this.bb_pos + offset) : 0;\n};\n\n";
+ code += "value);\n";
+ code += " return true;\n";
+ code += "};\n\n";
- if(parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportProperty(" + object_name + ".prototype, '" +
- MakeCamel(field.name, false) + "Length', " + object_name +
- ".prototype." + MakeCamel(field.name, false) + "Length);\n";
+ if (parser_.opts.use_goog_js_export_format) {
+ exports += "goog.exportProperty(" + object_name +
+ ".prototype, 'mutate_" + field.name + "', " + object_name +
+ ".prototype.mutate_" + field.name + ");\n";
+ }
}
- // For scalar types, emit a typed array helper
- auto vectorType = field.value.type.VectorType();
- if (IsScalar(vectorType.base_type) && !IsLong(vectorType.base_type)) {
- GenDocComment(code_ptr, "@returns {" + GenType(vectorType) + "Array}");
-
+ // Emit vector helpers
+ if (field.value.type.base_type == BASE_TYPE_VECTOR) {
+ // Emit a length helper
+ GenDocComment(code_ptr, "@returns {number}");
if (lang_.language == IDLOptions::kTs) {
code += MakeCamel(field.name, false);
- code += "Array():" + GenType(vectorType) + "Array|null {\n" +
- offset_prefix;
+ code += "Length():number {\n" + offset_prefix;
} else {
code += object_name + ".prototype." + MakeCamel(field.name, false);
- code += "Array = function() {\n" + offset_prefix;
+ code += "Length = function() {\n" + offset_prefix;
}
- code += "new " + GenType(vectorType) + "Array(" + GenBBAccess() +
- ".bytes().buffer, " + GenBBAccess() + ".bytes().byteOffset + " +
- GenBBAccess() + ".__vector(this.bb_pos + offset), " +
- GenBBAccess() + ".__vector_len(this.bb_pos + offset)) : null;\n};\n\n";
+ code +=
+ GenBBAccess() + ".__vector_len(this.bb_pos + offset) : 0;\n};\n\n";
- if(parser_.opts.use_goog_js_export_format) {
+ if (parser_.opts.use_goog_js_export_format) {
exports += "goog.exportProperty(" + object_name + ".prototype, '" +
- MakeCamel(field.name, false) + "Array', " + object_name +
- ".prototype." + MakeCamel(field.name, false) + "Array);\n";
+ MakeCamel(field.name, false) + "Length', " + object_name +
+ ".prototype." + MakeCamel(field.name, false) +
+ "Length);\n";
}
- }
- }
- }
- // Emit a factory constructor
- if (struct_def.fixed) {
- std::string annotations = "@param {flatbuffers.Builder} builder\n";
- std::string arguments;
- GenStructArgs(struct_def, &annotations, &arguments, "");
- GenDocComment(code_ptr, annotations +
- "@returns {flatbuffers.Offset}");
-
- if (lang_.language == IDLOptions::kTs) {
- code += "static create" + struct_def.name + "(builder:flatbuffers.Builder";
- code += arguments + "):flatbuffers.Offset {\n";
- } else {
- code += object_name + ".create" + struct_def.name + " = function(builder";
- code += arguments + ") {\n";
- }
+ // For scalar types, emit a typed array helper
+ auto vectorType = field.value.type.VectorType();
+ if (IsScalar(vectorType.base_type) && !IsLong(vectorType.base_type)) {
+ GenDocComment(code_ptr,
+ "@returns {" + GenType(vectorType) + "Array}");
- GenStructBody(struct_def, &code, "");
- code += " return builder.offset();\n};\n\n";
- } else {
- // Generate a method to start building a new object
- GenDocComment(code_ptr,
- "@param {flatbuffers.Builder} builder");
+ if (lang_.language == IDLOptions::kTs) {
+ code += MakeCamel(field.name, false);
+ code += "Array():" + GenType(vectorType) + "Array|null {\n" +
+ offset_prefix;
+ } else {
+ code += object_name + ".prototype." + MakeCamel(field.name, false);
+ code += "Array = function() {\n" + offset_prefix;
+ }
- if (lang_.language == IDLOptions::kTs) {
- code += "static start" + struct_def.name;
- code += "(builder:flatbuffers.Builder) {\n";
- } else {
- code += object_name + ".start" + struct_def.name;
- code += " = function(builder) {\n";
+ code += "new " + GenType(vectorType) + "Array(" + GenBBAccess() +
+ ".bytes().buffer, " + GenBBAccess() +
+ ".bytes().byteOffset + " + GenBBAccess() +
+ ".__vector(this.bb_pos + offset), " + GenBBAccess() +
+ ".__vector_len(this.bb_pos + offset)) : null;\n};\n\n";
+
+ if (parser_.opts.use_goog_js_export_format) {
+ exports += "goog.exportProperty(" + object_name + ".prototype, '" +
+ MakeCamel(field.name, false) + "Array', " + object_name +
+ ".prototype." + MakeCamel(field.name, false) +
+ "Array);\n";
+ }
+ }
+ }
}
- code += " builder.startObject(" + NumToString(
- struct_def.fields.vec.size()) + ");\n";
- code += "};\n\n";
+ // Emit a factory constructor
+ if (struct_def.fixed) {
+ std::string annotations = "@param {flatbuffers.Builder} builder\n";
+ std::string arguments;
+ GenStructArgs(struct_def, &annotations, &arguments, "");
+ GenDocComment(code_ptr, annotations + "@returns {flatbuffers.Offset}");
- // 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;
- if (field.deprecated) continue;
- auto argname = MakeCamel(field.name, false);
- if (!IsScalar(field.value.type.base_type)) {
- argname += "Offset";
+ if (lang_.language == IDLOptions::kTs) {
+ code +=
+ "static create" + struct_def.name + "(builder:flatbuffers.Builder";
+ code += arguments + "):flatbuffers.Offset {\n";
+ } else {
+ code +=
+ object_name + ".create" + struct_def.name + " = function(builder";
+ code += arguments + ") {\n";
}
- // Generate the field insertion method
- GenDocComment(code_ptr,
- "@param {flatbuffers.Builder} builder\n"
- "@param {" + GenTypeName(field.value.type, true) + "} " +
- argname);
+ GenStructBody(struct_def, &code, "");
+ code += " return builder.offset();\n};\n\n";
+ } else {
+ // Generate a method to start building a new object
+ GenDocComment(code_ptr, "@param {flatbuffers.Builder} builder");
if (lang_.language == IDLOptions::kTs) {
- std::string argType;
- if (field.value.type.enum_def) {
- argType = GenPrefixedTypeName(GenTypeName(field.value.type, true),
- field.value.type.enum_def->file);
- } else {
- argType = GenTypeName(field.value.type, true);
- }
-
- code += "static add" + MakeCamel(field.name);
- code += "(builder:flatbuffers.Builder, " + argname + ":" + argType +
- ") {\n";
+ code += "static start" + struct_def.name;
+ code += "(builder:flatbuffers.Builder) {\n";
} else {
- code += object_name + ".add" + MakeCamel(field.name);
- code += " = function(builder, " + argname + ") {\n";
+ code += object_name + ".start" + struct_def.name;
+ code += " = function(builder) {\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 += "+";
- }
- code += argname + ", ";
- if (!IsScalar(field.value.type.base_type)) {
- code += "0";
- } else {
- if (field.value.type.base_type == BASE_TYPE_BOOL) {
- code += "+";
- }
- code += GenDefaultValue(field.value, "builder");
- }
- code += ");\n};\n\n";
+ code += " builder.startObject(" +
+ NumToString(struct_def.fields.vec.size()) + ");\n";
+ code += "};\n\n";
- if (field.value.type.base_type == BASE_TYPE_VECTOR) {
- auto vector_type = field.value.type.VectorType();
- auto alignment = InlineAlignment(vector_type);
- auto elem_size = InlineSize(vector_type);
+ // 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;
+ if (field.deprecated) continue;
+ auto argname = MakeCamel(field.name, false);
+ if (!IsScalar(field.value.type.base_type)) { argname += "Offset"; }
- // Generate a method to create a vector from a JavaScript array
- if (!IsStruct(vector_type)) {
- GenDocComment(code_ptr,
- "@param {flatbuffers.Builder} builder\n"
- "@param {Array.<" + GenTypeName(vector_type, true) +
- ">} data\n"
- "@returns {flatbuffers.Offset}");
+ // Generate the field insertion method
+ GenDocComment(code_ptr,
+ "@param {flatbuffers.Builder} builder\n"
+ "@param {" +
+ GenTypeName(field.value.type, true) + "} " + argname);
- if (lang_.language == IDLOptions::kTs) {
- code += "static create" + MakeCamel(field.name);
- std::string type = GenTypeName(vector_type, true) + "[]";
- if (type == "number[]") {
- type += " | Uint8Array";
- }
- code += "Vector(builder:flatbuffers.Builder, data:" + type +
- "):flatbuffers.Offset {\n";
+ if (lang_.language == IDLOptions::kTs) {
+ std::string argType;
+ if (field.value.type.enum_def) {
+ argType = GenPrefixedTypeName(GenTypeName(field.value.type, true),
+ field.value.type.enum_def->file);
} else {
- code += object_name + ".create" + MakeCamel(field.name);
- code += "Vector = function(builder, data) {\n";
+ argType = GenTypeName(field.value.type, true);
}
- code += " builder.startVector(" + NumToString(elem_size);
- code += ", data.length, " + NumToString(alignment) + ");\n";
- code += " for (var i = data.length - 1; i >= 0; i--) {\n";
- code += " builder.add" + GenWriteMethod(vector_type) + "(";
- if (vector_type.base_type == BASE_TYPE_BOOL) {
- code += "+";
- }
- code += "data[i]);\n";
- code += " }\n";
- code += " return builder.endVector();\n";
- code += "};\n\n";
+ code += "static add" + MakeCamel(field.name);
+ code += "(builder:flatbuffers.Builder, " + argname + ":" + argType +
+ ") {\n";
+ } else {
+ code += object_name + ".add" + MakeCamel(field.name);
+ code += " = function(builder, " + argname + ") {\n";
}
- // Generate a method to start a vector, data to be added manually after
- GenDocComment(code_ptr,
- "@param {flatbuffers.Builder} builder\n"
- "@param {number} numElems");
-
- if (lang_.language == IDLOptions::kTs) {
- code += "static start" + MakeCamel(field.name);
- code += "Vector(builder:flatbuffers.Builder, numElems:number) {\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 += "+"; }
+ code += argname + ", ";
+ if (!IsScalar(field.value.type.base_type)) {
+ code += "0";
} else {
- code += object_name + ".start" + MakeCamel(field.name);
- code += "Vector = function(builder, numElems) {\n";
+ if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
+ code += GenDefaultValue(field.value, "builder");
}
+ code += ");\n};\n\n";
+
+ if (field.value.type.base_type == BASE_TYPE_VECTOR) {
+ auto vector_type = field.value.type.VectorType();
+ auto alignment = InlineAlignment(vector_type);
+ auto elem_size = InlineSize(vector_type);
+
+ // Generate a method to create a vector from a JavaScript array
+ if (!IsStruct(vector_type)) {
+ GenDocComment(code_ptr,
+ "@param {flatbuffers.Builder} builder\n"
+ "@param {Array.<" +
+ GenTypeName(vector_type, true) +
+ ">} data\n"
+ "@returns {flatbuffers.Offset}");
+
+ if (lang_.language == IDLOptions::kTs) {
+ code += "static create" + MakeCamel(field.name);
+ std::string type = GenTypeName(vector_type, true) + "[]";
+ if (type == "number[]") { type += " | Uint8Array"; }
+ code += "Vector(builder:flatbuffers.Builder, data:" + type +
+ "):flatbuffers.Offset {\n";
+ } else {
+ code += object_name + ".create" + MakeCamel(field.name);
+ code += "Vector = function(builder, data) {\n";
+ }
- code += " builder.startVector(" + NumToString(elem_size);
- code += ", numElems, " + NumToString(alignment) + ");\n";
- code += "};\n\n";
- }
- }
+ code += " builder.startVector(" + NumToString(elem_size);
+ code += ", data.length, " + NumToString(alignment) + ");\n";
+ code += " for (var i = data.length - 1; i >= 0; i--) {\n";
+ code += " builder.add" + GenWriteMethod(vector_type) + "(";
+ if (vector_type.base_type == BASE_TYPE_BOOL) { code += "+"; }
+ code += "data[i]);\n";
+ code += " }\n";
+ code += " return builder.endVector();\n";
+ code += "};\n\n";
+ }
- // Generate a method to stop building a new object
- GenDocComment(code_ptr,
- "@param {flatbuffers.Builder} builder\n"
- "@returns {flatbuffers.Offset}");
+ // Generate a method to start a vector, data to be added manually
+ // after
+ GenDocComment(code_ptr,
+ "@param {flatbuffers.Builder} builder\n"
+ "@param {number} numElems");
- if (lang_.language == IDLOptions::kTs) {
- code += "static end" + struct_def.name;
- code += "(builder:flatbuffers.Builder):flatbuffers.Offset {\n";
- } else {
- code += object_name + ".end" + struct_def.name;
- code += " = function(builder) {\n";
- }
+ if (lang_.language == IDLOptions::kTs) {
+ code += "static start" + MakeCamel(field.name);
+ code += "Vector(builder:flatbuffers.Builder, numElems:number) {\n";
+ } else {
+ code += object_name + ".start" + MakeCamel(field.name);
+ code += "Vector = function(builder, numElems) {\n";
+ }
- code += " var offset = builder.endObject();\n";
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (!field.deprecated && field.required) {
- code += " builder.requiredField(offset, ";
- code += NumToString(field.value.offset);
- code += "); // " + field.name + "\n";
+ code += " builder.startVector(" + NumToString(elem_size);
+ code += ", numElems, " + NumToString(alignment) + ");\n";
+ code += "};\n\n";
+ }
}
- }
- code += " return offset;\n";
- code += "};\n\n";
- // Generate the method to complete buffer construction
- if (parser_.root_struct_def_ == &struct_def) {
+ // Generate a method to stop building a new object
GenDocComment(code_ptr,
- "@param {flatbuffers.Builder} builder\n"
- "@param {flatbuffers.Offset} offset");
+ "@param {flatbuffers.Builder} builder\n"
+ "@returns {flatbuffers.Offset}");
if (lang_.language == IDLOptions::kTs) {
- code += "static finish" + struct_def.name + "Buffer";
- code += "(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {\n";
+ code += "static end" + struct_def.name;
+ code += "(builder:flatbuffers.Builder):flatbuffers.Offset {\n";
} else {
- code += object_name + ".finish" + struct_def.name + "Buffer";
- code += " = function(builder, offset) {\n";
+ code += object_name + ".end" + struct_def.name;
+ code += " = function(builder) {\n";
}
- code += " builder.finish(offset";
- if (!parser_.file_identifier_.empty()) {
- code += ", '" + parser_.file_identifier_ + "'";
+ code += " var offset = builder.endObject();\n";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (!field.deprecated && field.required) {
+ code += " builder.requiredField(offset, ";
+ code += NumToString(field.value.offset);
+ code += "); // " + field.name + "\n";
+ }
}
- code += ");\n";
+ code += " return offset;\n";
code += "};\n\n";
+
+ // Generate the method to complete buffer construction
+ if (parser_.root_struct_def_ == &struct_def) {
+ GenDocComment(code_ptr,
+ "@param {flatbuffers.Builder} builder\n"
+ "@param {flatbuffers.Offset} offset");
+
+ if (lang_.language == IDLOptions::kTs) {
+ code += "static finish" + struct_def.name + "Buffer";
+ code +=
+ "(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {\n";
+ } else {
+ code += object_name + ".finish" + struct_def.name + "Buffer";
+ code += " = function(builder, offset) {\n";
+ }
+
+ code += " builder.finish(offset";
+ if (!parser_.file_identifier_.empty()) {
+ code += ", '" + parser_.file_identifier_ + "'";
+ }
+ code += ");\n";
+ code += "};\n\n";
+ }
}
- }
- if (lang_.language == IDLOptions::kTs) {
- if (!object_namespace.empty()) {
+ if (lang_.language == IDLOptions::kTs) {
+ if (!object_namespace.empty()) { code += "}\n"; }
code += "}\n";
}
- code += "}\n";
}
-}
};
} // namespace js
return generator.generate();
}
-std::string JSMakeRule(const Parser &parser,
- const std::string &path,
+std::string JSMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
assert(parser.opts.lang <= IDLOptions::kMAX);
const auto &lang = GetJsLangParams(parser.opts.lang);
- std::string filebase = flatbuffers::StripPath(
- flatbuffers::StripExtension(file_name));
+ std::string filebase =
+ flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
std::string make_rule = GeneratedFileName(path, filebase, lang) + ": ";
auto included_files = parser.GetIncludedFilesRecursive(file_name);
- for (auto it = included_files.begin();
- it != included_files.end(); ++it) {
+ for (auto it = included_files.begin(); it != included_files.end(); ++it) {
make_rule += " " + *it;
}
-return make_rule;
+ return make_rule;
}
} // namespace flatbuffers
/*
-* Copyright 2014 Google Inc. All rights reserved.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
+ * Copyright 2014 Google Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <iostream>
#include "flatbuffers/code_generators.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#include <iostream>
namespace flatbuffers {
std::string GenNativeType(BaseType type) {
switch (type) {
- case BASE_TYPE_BOOL:
- return "boolean";
+ case BASE_TYPE_BOOL: return "boolean";
case BASE_TYPE_CHAR:
case BASE_TYPE_UCHAR:
case BASE_TYPE_SHORT:
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG:
case BASE_TYPE_FLOAT:
- case BASE_TYPE_DOUBLE:
- return "number";
- case BASE_TYPE_STRING:
- return "string";
- default:
- return "";
+ case BASE_TYPE_DOUBLE: return "number";
+ case BASE_TYPE_STRING: return "string";
+ default: return "";
}
}
-template <class T> std::string GenFullName(const T *enum_def) {
+template<class T> std::string GenFullName(const T *enum_def) {
std::string full_name;
const auto &name_spaces = enum_def->defined_namespace->components;
for (auto ns = name_spaces.cbegin(); ns != name_spaces.cend(); ++ns) {
return full_name;
}
-template <class T> std::string GenTypeRef(const T *enum_def) {
+template<class T> std::string GenTypeRef(const T *enum_def) {
return "\"$ref\" : \"#/definitions/" + GenFullName(enum_def) + "\"";
}
const auto &union_types = type.enum_def->vals.vec;
for (auto ut = union_types.cbegin(); ut < union_types.cend(); ++ut) {
auto &union_type = *ut;
- if (union_type->union_type.base_type == BASE_TYPE_NONE) {
- continue;
- }
+ 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) + " }");
+ union_type_string.append(
+ "{ " + GenTypeRef(union_type->union_type.struct_def) + " }");
}
if (union_type != *type.enum_def->vals.vec.rbegin()) {
union_type_string.append(",");
union_type_string.append("]");
return union_type_string;
}
- case BASE_TYPE_UTYPE:
- return GenTypeRef(type.enum_def);
- default:
- return GenType(GenNativeType(type.base_type));
+ case BASE_TYPE_UTYPE: return GenTypeRef(type.enum_def);
+ default: return GenType(GenNativeType(type.base_type));
}
}
code_ += "{";
code_ += " \"$schema\": \"http://json-schema.org/draft-04/schema#\",";
code_ += " \"definitions\": {";
- for (auto e = parser_.enums_.vec.cbegin();
- e != parser_.enums_.vec.cend();
+ for (auto e = parser_.enums_.vec.cbegin(); e != parser_.enums_.vec.cend();
++e) {
code_ += " \"" + GenFullName(*e) + "\" : {";
code_ += " " + GenType("string") + ",";
std::string enumdef(" \"enum\": [");
- for (auto enum_value = (*e)->vals.vec.begin();
- enum_value != (*e)->vals.vec.end();
- ++enum_value) {
+ for (auto enum_value = (*e)->vals.vec.begin();
+ enum_value != (*e)->vals.vec.end(); ++enum_value) {
enumdef.append("\"" + (*enum_value)->name + "\"");
- if (*enum_value != (*e)->vals.vec.back()) {
- enumdef.append(", ");
- }
+ if (*enum_value != (*e)->vals.vec.back()) { enumdef.append(", "); }
}
enumdef.append("]");
code_ += enumdef;
code_ += " },"; // close type
}
- for (auto s = parser_.structs_.vec.cbegin();
- s != parser_.structs_.vec.cend();
- ++s) {
+ for (auto s = parser_.structs_.vec.cbegin();
+ s != parser_.structs_.vec.cend(); ++s) {
const auto &structure = *s;
code_ += " \"" + GenFullName(structure) + "\" : {";
code_ += " " + GenType("object") + ",";
std::string comment;
const auto &comment_lines = structure->doc_comment;
for (auto comment_line = comment_lines.cbegin();
- comment_line != comment_lines.cend();
- ++comment_line) {
+ comment_line != comment_lines.cend(); ++comment_line) {
comment.append(*comment_line);
}
if (comment.size() > 0) {
const auto &properties = structure->fields.vec;
for (auto prop = properties.cbegin(); prop != properties.cend(); ++prop) {
const auto &property = *prop;
- std::string typeLine(" \"" + property->name + "\" : { " + GenType(property->value.type) + " }");
- if (property != properties.back()) {
- typeLine.append(",");
- }
+ std::string typeLine(" \"" + property->name + "\" : { " +
+ GenType(property->value.type) + " }");
+ if (property != properties.back()) { typeLine.append(","); }
code_ += typeLine;
}
code_ += " },"; // close properties
if (requiredProperties.size() > 0) {
std::string required_string(" \"required\" : [");
for (auto req_prop = requiredProperties.cbegin();
- req_prop != requiredProperties.cend();
- ++req_prop) {
+ req_prop != requiredProperties.cend(); ++req_prop) {
required_string.append("\"" + (*req_prop)->name + "\"");
if (*req_prop != requiredProperties.back()) {
required_string.append(", ");
}
code_ += " \"additionalProperties\" : false";
std::string closeType(" }");
- if (*s != parser_.structs_.vec.back()) {
- closeType.append(",");
- }
+ if (*s != parser_.structs_.vec.back()) { closeType.append(","); }
code_ += closeType; // close type
}
code_ += " },"; // close definitions
/*
-* Copyright 2014 Google Inc. All rights reserved.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
+ * Copyright 2014 Google Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
// independent from idl_parser, since this code is not needed for most clients
#include <string>
+#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#include "flatbuffers/code_generators.h"
namespace flatbuffers {
namespace php {
- // Hardcode spaces per indentation.
- const std::string Indent = " ";
- class PhpGenerator : public BaseGenerator {
- public:
- PhpGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
- : BaseGenerator(parser, path, file_name, "\\", "\\"){};
- bool generate() {
- if (!generateEnums()) return false;
- if (!generateStructs()) return false;
- return true;
- }
-
- private:
- bool generateEnums() {
- for (auto it = parser_.enums_.vec.begin();
- it != parser_.enums_.vec.end(); ++it) {
- auto &enum_def = **it;
- std::string enumcode;
- GenEnum(enum_def, &enumcode);
- if (!SaveType(enum_def, enumcode, false)) return false;
- }
- return true;
- }
-
- bool generateStructs() {
- for (auto it = parser_.structs_.vec.begin();
- it != parser_.structs_.vec.end(); ++it) {
- auto &struct_def = **it;
- std::string declcode;
- GenStruct(struct_def, &declcode);
- if (!SaveType(struct_def, declcode, true)) return false;
- }
- return true;
- }
-
- // Begin by declaring namespace and imports.
- void BeginFile(const std::string name_space_name,
- const bool needs_imports, std::string *code_ptr) {
- std::string &code = *code_ptr;
- code += "<?php\n";
- code = code + "// " + FlatBuffersGeneratedWarning() + "\n\n";
-
- if (!name_space_name.empty()) {
- code += "namespace " + name_space_name + ";\n\n";
- }
-
- if (needs_imports) {
- code += "use \\Google\\FlatBuffers\\Struct;\n";
- code += "use \\Google\\FlatBuffers\\Table;\n";
- code += "use \\Google\\FlatBuffers\\ByteBuffer;\n";
- code += "use \\Google\\FlatBuffers\\FlatBufferBuilder;\n";
- code += "\n";
- }
- }
-
- // Save out the generated code for a Php Table type.
- bool SaveType(const Definition &def, const std::string &classcode,
- bool needs_imports) {
- if (!classcode.length()) return true;
-
- std::string code = "";
- BeginFile(FullNamespace("\\", *def.defined_namespace),
- needs_imports, &code);
- code += classcode;
-
- std::string filename = NamespaceDir(*def.defined_namespace) +
- def.name + ".php";
- return SaveFile(filename.c_str(), code, false);
- }
-
- // Begin a class declaration.
- static void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
- if (struct_def.fixed) {
- code += "class " + struct_def.name + " extends Struct\n";
- } else {
- code += "class " + struct_def.name + " extends Table\n";
- }
- code += "{\n";
- }
-
- 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;
- code += "class " + class_name + "\n{\n";
- }
-
- // A single enum member.
- static void EnumMember(const EnumVal ev, std::string *code_ptr) {
- std::string &code = *code_ptr;
- code += Indent + "const ";
- code += ev.name;
- code += " = ";
- code += NumToString(ev.value) + ";\n";
- }
-
- // End enum code.
- 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;
-
- code += Indent + "/**\n";
- code += Indent + " * @param ByteBuffer $bb\n";
- code += Indent + " * @return " + struct_def.name + "\n";
- code += Indent + " */\n";
- code += Indent + "public static function getRootAs";
- code += struct_def.name;
- code += "(ByteBuffer $bb)\n";
- code += Indent + "{\n";
-
- code += Indent + Indent + "$obj = new " + struct_def.name + "();\n";
- code += Indent + Indent;
- code += "return ($obj->init($bb->getInt($bb->getPosition())";
- code += " + $bb->getPosition(), $bb));\n";
- code += Indent + "}\n\n";
- }
-
- // 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;
-
- code += Indent + "/**\n";
- code += Indent + " * @param int $_i offset\n";
- code += Indent + " * @param ByteBuffer $_bb\n";
- code += Indent + " * @return " + struct_def.name + "\n";
- code += Indent + " **/\n";
- code += Indent + "public function init($_i, ByteBuffer $_bb)\n";
- code += Indent + "{\n";
- code += Indent + Indent + "$this->bb_pos = $_i;\n";
- code += Indent + Indent + "$this->bb = $_bb;\n";
- code += Indent + Indent + "return $this;\n";
- code += Indent + "}\n\n";
- }
-
- // Get the length of a vector.
- static void GetVectorLen(const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
-
- code += Indent + "/**\n";
- code += Indent + " * @return int\n";
- code += Indent + " */\n";
- code += Indent + "public function get";
- code += MakeCamel(field.name) + "Length()\n";
- code += Indent + "{\n";
- code += Indent + Indent + "$o = $this->__offset(";
- code += NumToString(field.value.offset) + ");\n";
- code += Indent + Indent;
- code += "return $o != 0 ? $this->__vector_len($o) : 0;\n";
- code += Indent + "}\n\n";
- }
-
- // Get a [ubyte] vector as a byte array.
- static void GetUByte(const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
-
- code += Indent + "/**\n";
- code += Indent + " * @return string\n";
- code += Indent + " */\n";
- code += Indent + "public function get";
- code += MakeCamel(field.name) + "Bytes()\n";
- code += Indent + "{\n";
- code += Indent + Indent + "return $this->__vector_as_bytes(";
- code += NumToString(field.value.offset) + ");\n";
- code += Indent + "}\n\n";
- }
-
- // Get the value of a struct's scalar.
- static void GetScalarFieldOfStruct(const FieldDef &field,
- std::string *code_ptr) {
- std::string &code = *code_ptr;
- std::string getter = GenGetter(field.value.type);
-
- code += Indent + "/**\n";
- code += Indent + " * @return ";
- code += GenTypeGet(field.value.type) + "\n";
- code += Indent + " */\n";
- code += Indent + "public function " + getter;
- code += MakeCamel(field.name) + "()\n";
- code += Indent + "{\n";
- code += Indent + Indent + "return ";
-
- code += "$this->bb->get";
- code += MakeCamel(GenTypeGet(field.value.type));
- code += "($this->bb_pos + ";
- code += NumToString(field.value.offset) + ")";
- code += ";\n";
-
- code += Indent + "}\n\n";
- }
-
- // Get the value of a table's scalar.
- void GetScalarFieldOfTable(const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
- std::string getter = GenGetter(field.value.type);
-
- code += Indent + "/**\n";
- code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
- code += Indent + " */\n";
- code += Indent + "public function get";
- code += MakeCamel(field.name);
- code += "()\n";
- code += Indent + "{\n";
- code += Indent + Indent +
- "$o = $this->__offset(" +
- NumToString(field.value.offset) +
- ");\n" + Indent + Indent + "return $o != 0 ? ";
- code += "$this->bb->get";
- code += MakeCamel(GenTypeGet(field.value.type)) + "($o + $this->bb_pos)";
- code += " : " + GenDefaultValue(field.value) + ";\n";
- code += Indent + "}\n\n";
- }
-
- // 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;
-
- code += Indent + "/**\n";
- code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
- code += Indent + " */\n";
- code += Indent + "public function get";
- code += MakeCamel(field.name) + "()\n";
- code += Indent + "{\n";
- code += Indent + Indent + "$obj = new ";
- code += GenTypeGet(field.value.type) + "();\n";
- code += Indent + Indent + "$obj->init($this->bb_pos + ";
- code += NumToString(field.value.offset) + ", $this->bb);";
- code += "\n" + Indent + Indent + "return $obj;\n";
- code += Indent + "}\n\n";
- }
-
- // 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;
-
- code += Indent + "public function get";
- code += MakeCamel(field.name);
- code += "()\n";
- code += Indent + "{\n";
- code += Indent + Indent + "$obj = new ";
- code += MakeCamel(GenTypeGet(field.value.type)) + "();\n";
- code += Indent + Indent +
- "$o = $this->__offset(" +
- NumToString(field.value.offset) +
- ");\n";
- code += Indent + Indent;
- code += "return $o != 0 ? $obj->init(";
- if (field.value.type.struct_def->fixed)
- {
- code += "$o + $this->bb_pos, $this->bb) : ";
- } else {
- code += "$this->__indirect($o + $this->bb_pos), $this->bb) : ";
- }
- code += GenDefaultValue(field.value) + ";\n";
- code += Indent + "}\n\n";
- }
-
- // Get the value of a string.
- void GetStringField(const FieldDef &field, std::string *code_ptr) {
- std::string &code = *code_ptr;
- code += Indent + "public function get";
- code += MakeCamel(field.name);
- code += "()\n";
- code += Indent + "{\n";
- code += Indent + Indent +
- "$o = $this->__offset(" +
- NumToString(field.value.offset) +
- ");\n";
- code += Indent + Indent;
- code += "return $o != 0 ? $this->__string($o + $this->bb_pos) : ";
- code += GenDefaultValue(field.value) + ";\n";
- code += Indent + "}\n\n";
- }
-
- // Get the value of a union from an object.
- 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";
- code += Indent + " */\n";
- code += Indent + "public function get";
- code += MakeCamel(field.name) + "($obj)\n";
- code += Indent + "{\n";
- code += Indent + Indent +
- "$o = $this->__offset(" +
- NumToString(field.value.offset) +
- ");\n";
- code += Indent + Indent;
- code += "return $o != 0 ? $this->__union($obj, $o) : null;\n";
- code += Indent + "}\n\n";
+// Hardcode spaces per indentation.
+const std::string Indent = " ";
+class PhpGenerator : public BaseGenerator {
+ public:
+ PhpGenerator(const Parser &parser, const std::string &path,
+ const std::string &file_name)
+ : BaseGenerator(parser, path, file_name, "\\", "\\"){};
+ bool generate() {
+ if (!generateEnums()) return false;
+ if (!generateStructs()) return false;
+ return true;
+ }
+
+ private:
+ bool generateEnums() {
+ for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
+ ++it) {
+ auto &enum_def = **it;
+ std::string enumcode;
+ GenEnum(enum_def, &enumcode);
+ if (!SaveType(enum_def, enumcode, false)) return false;
+ }
+ return true;
+ }
+
+ bool generateStructs() {
+ for (auto it = parser_.structs_.vec.begin();
+ it != parser_.structs_.vec.end(); ++it) {
+ auto &struct_def = **it;
+ std::string declcode;
+ GenStruct(struct_def, &declcode);
+ if (!SaveType(struct_def, declcode, true)) return false;
+ }
+ return true;
+ }
+
+ // Begin by declaring namespace and imports.
+ void BeginFile(const std::string name_space_name, const bool needs_imports,
+ std::string *code_ptr) {
+ std::string &code = *code_ptr;
+ code += "<?php\n";
+ code = code + "// " + FlatBuffersGeneratedWarning() + "\n\n";
+
+ if (!name_space_name.empty()) {
+ code += "namespace " + name_space_name + ";\n\n";
+ }
+
+ if (needs_imports) {
+ code += "use \\Google\\FlatBuffers\\Struct;\n";
+ code += "use \\Google\\FlatBuffers\\Table;\n";
+ code += "use \\Google\\FlatBuffers\\ByteBuffer;\n";
+ code += "use \\Google\\FlatBuffers\\FlatBufferBuilder;\n";
+ code += "\n";
}
-
- // 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;
- auto vectortype = field.value.type.VectorType();
-
- code += Indent + "/**\n";
- code += Indent + " * @return" + GenTypeBasic(field.value.type) + "\n";
- code += Indent + " */\n";
- code += Indent + "public function get";
- code += MakeCamel(field.name);
- code += "($j)\n";
- code += Indent + "{\n";
- code += Indent + Indent +
- "$o = $this->__offset(" +
- NumToString(field.value.offset) +
- ");\n";
- code += Indent + Indent + "$obj = new ";
- code += MakeCamel(GenTypeGet(field.value.type)) + "();\n";
-
- switch (field.value.type.base_type) {
+ }
+
+ // Save out the generated code for a Php Table type.
+ bool SaveType(const Definition &def, const std::string &classcode,
+ bool needs_imports) {
+ if (!classcode.length()) return true;
+
+ std::string code = "";
+ BeginFile(FullNamespace("\\", *def.defined_namespace), needs_imports,
+ &code);
+ code += classcode;
+
+ std::string filename =
+ NamespaceDir(*def.defined_namespace) + def.name + ".php";
+ return SaveFile(filename.c_str(), code, false);
+ }
+
+ // Begin a class declaration.
+ static void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
+ std::string &code = *code_ptr;
+ if (struct_def.fixed) {
+ code += "class " + struct_def.name + " extends Struct\n";
+ } else {
+ code += "class " + struct_def.name + " extends Table\n";
+ }
+ code += "{\n";
+ }
+
+ 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;
+ code += "class " + class_name + "\n{\n";
+ }
+
+ // A single enum member.
+ static void EnumMember(const EnumVal ev, std::string *code_ptr) {
+ std::string &code = *code_ptr;
+ code += Indent + "const ";
+ code += ev.name;
+ code += " = ";
+ code += NumToString(ev.value) + ";\n";
+ }
+
+ // End enum code.
+ 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;
+
+ code += Indent + "/**\n";
+ code += Indent + " * @param ByteBuffer $bb\n";
+ code += Indent + " * @return " + struct_def.name + "\n";
+ code += Indent + " */\n";
+ code += Indent + "public static function getRootAs";
+ code += struct_def.name;
+ code += "(ByteBuffer $bb)\n";
+ code += Indent + "{\n";
+
+ code += Indent + Indent + "$obj = new " + struct_def.name + "();\n";
+ code += Indent + Indent;
+ code += "return ($obj->init($bb->getInt($bb->getPosition())";
+ code += " + $bb->getPosition(), $bb));\n";
+ code += Indent + "}\n\n";
+ }
+
+ // 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;
+
+ code += Indent + "/**\n";
+ code += Indent + " * @param int $_i offset\n";
+ code += Indent + " * @param ByteBuffer $_bb\n";
+ code += Indent + " * @return " + struct_def.name + "\n";
+ code += Indent + " **/\n";
+ code += Indent + "public function init($_i, ByteBuffer $_bb)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$this->bb_pos = $_i;\n";
+ code += Indent + Indent + "$this->bb = $_bb;\n";
+ code += Indent + Indent + "return $this;\n";
+ code += Indent + "}\n\n";
+ }
+
+ // Get the length of a vector.
+ static void GetVectorLen(const FieldDef &field, std::string *code_ptr) {
+ std::string &code = *code_ptr;
+
+ code += Indent + "/**\n";
+ code += Indent + " * @return int\n";
+ code += Indent + " */\n";
+ code += Indent + "public function get";
+ code += MakeCamel(field.name) + "Length()\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$o = $this->__offset(";
+ code += NumToString(field.value.offset) + ");\n";
+ code += Indent + Indent;
+ code += "return $o != 0 ? $this->__vector_len($o) : 0;\n";
+ code += Indent + "}\n\n";
+ }
+
+ // Get a [ubyte] vector as a byte array.
+ static void GetUByte(const FieldDef &field, std::string *code_ptr) {
+ std::string &code = *code_ptr;
+
+ code += Indent + "/**\n";
+ code += Indent + " * @return string\n";
+ code += Indent + " */\n";
+ code += Indent + "public function get";
+ code += MakeCamel(field.name) + "Bytes()\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "return $this->__vector_as_bytes(";
+ code += NumToString(field.value.offset) + ");\n";
+ code += Indent + "}\n\n";
+ }
+
+ // Get the value of a struct's scalar.
+ static void GetScalarFieldOfStruct(const FieldDef &field,
+ std::string *code_ptr) {
+ std::string &code = *code_ptr;
+ std::string getter = GenGetter(field.value.type);
+
+ code += Indent + "/**\n";
+ code += Indent + " * @return ";
+ code += GenTypeGet(field.value.type) + "\n";
+ code += Indent + " */\n";
+ code += Indent + "public function " + getter;
+ code += MakeCamel(field.name) + "()\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "return ";
+
+ code += "$this->bb->get";
+ code += MakeCamel(GenTypeGet(field.value.type));
+ code += "($this->bb_pos + ";
+ code += NumToString(field.value.offset) + ")";
+ code += ";\n";
+
+ code += Indent + "}\n\n";
+ }
+
+ // Get the value of a table's scalar.
+ void GetScalarFieldOfTable(const FieldDef &field, std::string *code_ptr) {
+ std::string &code = *code_ptr;
+ std::string getter = GenGetter(field.value.type);
+
+ code += Indent + "/**\n";
+ code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
+ code += Indent + " */\n";
+ code += Indent + "public function get";
+ code += MakeCamel(field.name);
+ code += "()\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$o = $this->__offset(" +
+ NumToString(field.value.offset) + ");\n" + Indent + Indent +
+ "return $o != 0 ? ";
+ code += "$this->bb->get";
+ code += MakeCamel(GenTypeGet(field.value.type)) + "($o + $this->bb_pos)";
+ code += " : " + GenDefaultValue(field.value) + ";\n";
+ code += Indent + "}\n\n";
+ }
+
+ // 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;
+
+ code += Indent + "/**\n";
+ code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
+ code += Indent + " */\n";
+ code += Indent + "public function get";
+ code += MakeCamel(field.name) + "()\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$obj = new ";
+ code += GenTypeGet(field.value.type) + "();\n";
+ code += Indent + Indent + "$obj->init($this->bb_pos + ";
+ code += NumToString(field.value.offset) + ", $this->bb);";
+ code += "\n" + Indent + Indent + "return $obj;\n";
+ code += Indent + "}\n\n";
+ }
+
+ // 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;
+
+ code += Indent + "public function get";
+ code += MakeCamel(field.name);
+ code += "()\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$obj = new ";
+ code += MakeCamel(GenTypeGet(field.value.type)) + "();\n";
+ code += Indent + Indent + "$o = $this->__offset(" +
+ NumToString(field.value.offset) + ");\n";
+ code += Indent + Indent;
+ code += "return $o != 0 ? $obj->init(";
+ if (field.value.type.struct_def->fixed) {
+ code += "$o + $this->bb_pos, $this->bb) : ";
+ } else {
+ code += "$this->__indirect($o + $this->bb_pos), $this->bb) : ";
+ }
+ code += GenDefaultValue(field.value) + ";\n";
+ code += Indent + "}\n\n";
+ }
+
+ // Get the value of a string.
+ void GetStringField(const FieldDef &field, std::string *code_ptr) {
+ std::string &code = *code_ptr;
+ code += Indent + "public function get";
+ code += MakeCamel(field.name);
+ code += "()\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$o = $this->__offset(" +
+ NumToString(field.value.offset) + ");\n";
+ code += Indent + Indent;
+ code += "return $o != 0 ? $this->__string($o + $this->bb_pos) : ";
+ code += GenDefaultValue(field.value) + ";\n";
+ code += Indent + "}\n\n";
+ }
+
+ // Get the value of a union from an object.
+ 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";
+ code += Indent + " */\n";
+ code += Indent + "public function get";
+ code += MakeCamel(field.name) + "($obj)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$o = $this->__offset(" +
+ NumToString(field.value.offset) + ");\n";
+ code += Indent + Indent;
+ code += "return $o != 0 ? $this->__union($obj, $o) : null;\n";
+ code += Indent + "}\n\n";
+ }
+
+ // 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;
+ auto vectortype = field.value.type.VectorType();
+
+ code += Indent + "/**\n";
+ code += Indent + " * @return" + GenTypeBasic(field.value.type) + "\n";
+ code += Indent + " */\n";
+ code += Indent + "public function get";
+ code += MakeCamel(field.name);
+ code += "($j)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$o = $this->__offset(" +
+ NumToString(field.value.offset) + ");\n";
+ code += Indent + Indent + "$obj = new ";
+ code += MakeCamel(GenTypeGet(field.value.type)) + "();\n";
+
+ switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT:
if (struct_def.fixed) {
code += Indent + Indent;
- code += "return $o != 0 ? $obj->init($this->bb_pos +"
- + NumToString(field.value.offset) + ", $this->bb) : null;\n";
+ code += "return $o != 0 ? $obj->init($this->bb_pos +" +
+ NumToString(field.value.offset) + ", $this->bb) : null;\n";
} else {
code += Indent + Indent + "return $o != 0 ? $obj->init(";
code += field.value.type.struct_def->fixed
- ? "$o + $this->bb_pos"
- : "$this->__indirect($o + $this->bb_pos)";
+ ? "$o + $this->bb_pos"
+ : "$this->__indirect($o + $this->bb_pos)";
code += ", $this->bb) : null;\n";
}
break;
code += Indent + Indent + "return $o != 0 ? $this->";
code += GenGetter(field.value.type) + "($obj, $o); null;\n";
break;
- default:
- break;
- }
-
- code += Indent + "}\n\n";
+ default: break;
+ }
+
+ code += Indent + "}\n\n";
+ }
+
+ // 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;
+ auto vectortype = field.value.type.VectorType();
+
+ code += Indent + "/**\n";
+ code += Indent + " * @param int offset\n";
+ code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
+ code += Indent + " */\n";
+ code += Indent + "public function get";
+ code += MakeCamel(field.name);
+ code += "($j)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$o = $this->__offset(" +
+ NumToString(field.value.offset) + ");\n";
+
+ if (field.value.type.VectorType().base_type == BASE_TYPE_STRING) {
+ code += Indent + Indent;
+ code += "return $o != 0 ? $this->__string($this->__vector($o) + $j * ";
+ code += NumToString(InlineSize(vectortype)) + ") : ";
+ code += GenDefaultValue(field.value) + ";\n";
+ } else {
+ code += Indent + Indent + "return $o != 0 ? $this->bb->get";
+ code += MakeCamel(GenTypeGet(field.value.type));
+ code += "($this->__vector($o) + $j * ";
+ code += NumToString(InlineSize(vectortype)) + ") : ";
+ code += GenDefaultValue(field.value) + ";\n";
}
-
- // 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;
- auto vectortype = field.value.type.VectorType();
-
- code += Indent + "/**\n";
- code += Indent + " * @param int offset\n";
- code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
- code += Indent + " */\n";
- code += Indent + "public function get";
- code += MakeCamel(field.name);
- code += "($j)\n";
- code += Indent + "{\n";
- code += Indent + Indent +
- "$o = $this->__offset(" +
- NumToString(field.value.offset) +
- ");\n";
-
- if (field.value.type.VectorType().base_type == BASE_TYPE_STRING) {
- code += Indent + Indent;
- code += "return $o != 0 ? $this->__string($this->__vector($o) + $j * ";
- code += NumToString(InlineSize(vectortype)) + ") : ";
- code += GenDefaultValue(field.value) + ";\n";
+ code += Indent + "}\n\n";
+ }
+
+ // 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;
+ auto vectortype = field.value.type.VectorType();
+
+ code += Indent + "/**\n";
+ code += Indent + " * @param int offset\n";
+ code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
+ code += Indent + " */\n";
+ code += Indent + "public function get";
+ code += MakeCamel(field.name);
+ code += "($j, $obj)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$o = $this->__offset(" +
+ NumToString(field.value.offset) + ");\n";
+ code += Indent + Indent + "return $o != 0 ? ";
+ code += "$this->__union($obj, $this->__vector($o) + $j * ";
+ code += NumToString(InlineSize(vectortype)) + " - $this->bb_pos) : null;\n";
+ code += Indent + "}\n\n";
+ }
+
+ // 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) {
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++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
+ // a nested struct, prefix the name with the field name.
+ StructBuilderArgs(*field.value.type.struct_def,
+ (nameprefix + (field.name + "_")).c_str(), code_ptr);
} else {
- code += Indent + Indent + "return $o != 0 ? $this->bb->get";
- code += MakeCamel(GenTypeGet(field.value.type));
- code += "($this->__vector($o) + $j * ";
- code += NumToString(InlineSize(vectortype)) + ") : ";
- code += GenDefaultValue(field.value) + ";\n";
- }
- code += Indent + "}\n\n";
- }
-
- // 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;
- auto vectortype = field.value.type.VectorType();
-
- code += Indent + "/**\n";
- code += Indent + " * @param int offset\n";
- code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
- code += Indent + " */\n";
- code += Indent + "public function get";
- code += MakeCamel(field.name);
- code += "($j, $obj)\n";
- code += Indent + "{\n";
- code += Indent + Indent +
- "$o = $this->__offset(" +
- NumToString(field.value.offset) +
- ");\n";
- code += Indent + Indent + "return $o != 0 ? ";
- code += "$this->__union($obj, $this->__vector($o) + $j * ";
- code += NumToString(InlineSize(vectortype)) + " - $this->bb_pos) : null;\n";
- code += Indent + "}\n\n";
- }
-
- // 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) {
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++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
- // a nested struct, prefix the name with the field name.
- StructBuilderArgs(*field.value.type.struct_def,
- (nameprefix + (field.name + "_")).c_str(),
- code_ptr);
- } else {
- std::string &code = *code_ptr;
- code += (std::string)", $" + nameprefix;
- code += MakeCamel(field.name, false);
- }
- }
- }
-
- // 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;
- 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;
- if (field.padding) {
- code += Indent + Indent + "$builder->pad(";
- code += NumToString(field.padding) + ");\n";
- }
- if (IsStruct(field.value.type)) {
- StructBuilderBody(*field.value.type.struct_def,
- (nameprefix + (field.name + "_")).c_str(),
- code_ptr);
- } else {
- code += Indent + Indent + "$builder->put" + GenMethod(field) + "($";
- code += nameprefix + MakeCamel(field.name, false) + ");\n";
- }
+ std::string &code = *code_ptr;
+ code += (std::string) ", $" + nameprefix;
+ code += MakeCamel(field.name, false);
}
}
-
- // 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;
-
- code += Indent + "/**\n";
- code += Indent + " * @param FlatBufferBuilder $builder\n";
- code += Indent + " * @return void\n";
- code += Indent + " */\n";
- code += Indent + "public static function start" + struct_def.name;
- code += "(FlatBufferBuilder $builder)\n";
- code += Indent + "{\n";
- code += Indent + Indent + "$builder->StartObject(";
- code += NumToString(struct_def.fields.vec.size());
- code += ");\n";
- code += Indent + "}\n\n";
-
- code += Indent + "/**\n";
- code += Indent + " * @param FlatBufferBuilder $builder\n";
- code += Indent + " * @return " + struct_def.name + "\n";
- code += Indent + " */\n";
- code += Indent + "public static function create" + struct_def.name;
- code += "(FlatBufferBuilder $builder, ";
-
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
- auto &field = **it;
-
- if (field.deprecated) continue;
- code += "$" + field.name;
- if (!(it == (--struct_def.fields.vec.end()))) {
- code += ", ";
- }
+ }
+
+ // 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;
+ 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;
+ if (field.padding) {
+ code += Indent + Indent + "$builder->pad(";
+ code += NumToString(field.padding) + ");\n";
}
- code += ")\n";
- code += Indent + "{\n";
- code += Indent + Indent + "$builder->startObject(";
- code += NumToString(struct_def.fields.vec.size());
- code += ");\n";
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
- auto &field = **it;
- if (field.deprecated) continue;
-
- code += Indent + Indent + "self::add";
- code += MakeCamel(field.name) + "($builder, $" + field.name + ");\n";
- }
-
- code += Indent + Indent + "$o = $builder->endObject();\n";
-
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
- auto &field = **it;
- if (!field.deprecated && field.required) {
- code += Indent + Indent + "$builder->required($o, ";
- code += NumToString(field.value.offset);
- code += "); // " + field.name + "\n";
- }
+ if (IsStruct(field.value.type)) {
+ StructBuilderBody(*field.value.type.struct_def,
+ (nameprefix + (field.name + "_")).c_str(), code_ptr);
+ } else {
+ code += Indent + Indent + "$builder->put" + GenMethod(field) + "($";
+ code += nameprefix + MakeCamel(field.name, false) + ");\n";
}
- code += Indent + Indent + "return $o;\n";
- code += Indent + "}\n\n";
}
-
- // 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;
-
-
- code += Indent + "/**\n";
- code += Indent + " * @param FlatBufferBuilder $builder\n";
- code += Indent + " * @param " + GenTypeBasic(field.value.type) + "\n";
- code += Indent + " * @return void\n";
- code += Indent + " */\n";
- code += Indent + "public static function ";
- code += "add" + MakeCamel(field.name);
- code += "(FlatBufferBuilder $builder, ";
- code += "$" + MakeCamel(field.name, false);
- code += ")\n";
- code += Indent + "{\n";
- code += Indent + Indent + "$builder->add";
- code += GenMethod(field) + "X(";
- code += NumToString(offset) + ", ";
-
-
- code += "$" + MakeCamel(field.name, false);
- code += ", ";
-
- if (field.value.type.base_type == BASE_TYPE_BOOL) {
- code += "false";
- } else {
- code += field.value.constant;
+ }
+
+ // 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;
+
+ code += Indent + "/**\n";
+ code += Indent + " * @param FlatBufferBuilder $builder\n";
+ code += Indent + " * @return void\n";
+ code += Indent + " */\n";
+ code += Indent + "public static function start" + struct_def.name;
+ code += "(FlatBufferBuilder $builder)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$builder->StartObject(";
+ code += NumToString(struct_def.fields.vec.size());
+ code += ");\n";
+ code += Indent + "}\n\n";
+
+ code += Indent + "/**\n";
+ code += Indent + " * @param FlatBufferBuilder $builder\n";
+ code += Indent + " * @return " + struct_def.name + "\n";
+ code += Indent + " */\n";
+ code += Indent + "public static function create" + struct_def.name;
+ code += "(FlatBufferBuilder $builder, ";
+
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+
+ if (field.deprecated) continue;
+ code += "$" + field.name;
+ if (!(it == (--struct_def.fields.vec.end()))) { code += ", "; }
+ }
+ code += ")\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$builder->startObject(";
+ code += NumToString(struct_def.fields.vec.size());
+ code += ");\n";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+
+ code += Indent + Indent + "self::add";
+ code += MakeCamel(field.name) + "($builder, $" + field.name + ");\n";
+ }
+
+ code += Indent + Indent + "$o = $builder->endObject();\n";
+
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (!field.deprecated && field.required) {
+ code += Indent + Indent + "$builder->required($o, ";
+ code += NumToString(field.value.offset);
+ code += "); // " + field.name + "\n";
}
- code += ");\n";
- code += Indent + "}\n\n";
}
-
- // 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;
-
- auto vector_type = field.value.type.VectorType();
- auto alignment = InlineAlignment(vector_type);
- auto elem_size = InlineSize(vector_type);
- code += Indent + "/**\n";
- code += Indent + " * @param FlatBufferBuilder $builder\n";
- code += Indent + " * @param array offset array\n";
- code += Indent + " * @return int vector offset\n";
- code += Indent + " */\n";
- code += Indent + "public static function create";
- code += MakeCamel(field.name);
- code += "Vector(FlatBufferBuilder $builder, array $data)\n";
- code += Indent + "{\n";
- code += Indent + Indent + "$builder->startVector(";
- code += NumToString(elem_size);
- code += ", count($data), " + NumToString(alignment);
- code += ");\n";
- code += Indent + Indent;
- code += "for ($i = count($data) - 1; $i >= 0; $i--) {\n";
- if (IsScalar(field.value.type.VectorType().base_type)) {
- code += Indent + Indent + Indent;
- code += "$builder->add";
- code += MakeCamel(GenTypeBasic(field.value.type.VectorType()));
- code += "($data[$i]);\n";
- } else {
- code += Indent + Indent + Indent;
- code += "$builder->addOffset($data[$i]);\n";
+ code += Indent + Indent + "return $o;\n";
+ code += Indent + "}\n\n";
+ }
+
+ // 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;
+
+ code += Indent + "/**\n";
+ code += Indent + " * @param FlatBufferBuilder $builder\n";
+ code += Indent + " * @param " + GenTypeBasic(field.value.type) + "\n";
+ code += Indent + " * @return void\n";
+ code += Indent + " */\n";
+ code += Indent + "public static function ";
+ code += "add" + MakeCamel(field.name);
+ code += "(FlatBufferBuilder $builder, ";
+ code += "$" + MakeCamel(field.name, false);
+ code += ")\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$builder->add";
+ code += GenMethod(field) + "X(";
+ code += NumToString(offset) + ", ";
+
+ code += "$" + MakeCamel(field.name, false);
+ code += ", ";
+
+ if (field.value.type.base_type == BASE_TYPE_BOOL) {
+ code += "false";
+ } else {
+ code += field.value.constant;
+ }
+ code += ");\n";
+ code += Indent + "}\n\n";
+ }
+
+ // 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;
+
+ auto vector_type = field.value.type.VectorType();
+ auto alignment = InlineAlignment(vector_type);
+ auto elem_size = InlineSize(vector_type);
+ code += Indent + "/**\n";
+ code += Indent + " * @param FlatBufferBuilder $builder\n";
+ code += Indent + " * @param array offset array\n";
+ code += Indent + " * @return int vector offset\n";
+ code += Indent + " */\n";
+ code += Indent + "public static function create";
+ code += MakeCamel(field.name);
+ code += "Vector(FlatBufferBuilder $builder, array $data)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$builder->startVector(";
+ code += NumToString(elem_size);
+ code += ", count($data), " + NumToString(alignment);
+ code += ");\n";
+ code += Indent + Indent;
+ code += "for ($i = count($data) - 1; $i >= 0; $i--) {\n";
+ if (IsScalar(field.value.type.VectorType().base_type)) {
+ code += Indent + Indent + Indent;
+ code += "$builder->add";
+ code += MakeCamel(GenTypeBasic(field.value.type.VectorType()));
+ code += "($data[$i]);\n";
+ } else {
+ code += Indent + Indent + Indent;
+ code += "$builder->addOffset($data[$i]);\n";
+ }
+ code += Indent + Indent + "}\n";
+ code += Indent + Indent + "return $builder->endVector();\n";
+ code += Indent + "}\n\n";
+
+ code += Indent + "/**\n";
+ code += Indent + " * @param FlatBufferBuilder $builder\n";
+ code += Indent + " * @param int $numElems\n";
+ code += Indent + " * @return void\n";
+ code += Indent + " */\n";
+ code += Indent + "public static function start";
+ code += MakeCamel(field.name);
+ code += "Vector(FlatBufferBuilder $builder, $numElems)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$builder->startVector(";
+ code += NumToString(elem_size);
+ code += ", $numElems, " + NumToString(alignment);
+ code += ");\n";
+ code += Indent + "}\n\n";
+ }
+
+ // Get the offset of the end of a table.
+ void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
+ std::string &code = *code_ptr;
+
+ code += Indent + "/**\n";
+ code += Indent + " * @param FlatBufferBuilder $builder\n";
+ code += Indent + " * @return int table offset\n";
+ code += Indent + " */\n";
+ code += Indent + "public static function end" + struct_def.name;
+ code += "(FlatBufferBuilder $builder)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$o = $builder->endObject();\n";
+
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (!field.deprecated && field.required) {
+ code += Indent + Indent + "$builder->required($o, ";
+ code += NumToString(field.value.offset);
+ code += "); // " + field.name + "\n";
}
- code += Indent + Indent + "}\n";
- code += Indent + Indent + "return $builder->endVector();\n";
- code += Indent + "}\n\n";
-
-
- code += Indent + "/**\n";
- code += Indent + " * @param FlatBufferBuilder $builder\n";
- code += Indent + " * @param int $numElems\n";
- code += Indent + " * @return void\n";
- code += Indent + " */\n";
- code += Indent + "public static function start";
- code += MakeCamel(field.name);
- code += "Vector(FlatBufferBuilder $builder, $numElems)\n";
- code += Indent + "{\n";
- code += Indent + Indent + "$builder->startVector(";
- code += NumToString(elem_size);
- code += ", $numElems, " + NumToString(alignment);
- code += ");\n";
- code += Indent + "}\n\n";
}
+ code += Indent + Indent + "return $o;\n";
+ code += Indent + "}\n";
- // Get the offset of the end of a table.
- void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
- std::string &code = *code_ptr;
-
-
- code += Indent + "/**\n";
- code += Indent + " * @param FlatBufferBuilder $builder\n";
- code += Indent + " * @return int table offset\n";
- code += Indent + " */\n";
- code += Indent + "public static function end" + struct_def.name;
- code += "(FlatBufferBuilder $builder)\n";
+ if (parser_.root_struct_def_ == &struct_def) {
+ code += "\n";
+ code += Indent + "public static function finish";
+ code += struct_def.name;
+ code += "Buffer(FlatBufferBuilder $builder, $offset)\n";
code += Indent + "{\n";
- code += Indent + Indent + "$o = $builder->endObject();\n";
-
+ code += Indent + Indent + "$builder->finish($offset";
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
- auto &field = **it;
- if (!field.deprecated && field.required) {
- code += Indent + Indent + "$builder->required($o, ";
- code += NumToString(field.value.offset);
- code += "); // " + field.name + "\n";
- }
- }
- code += Indent + Indent + "return $o;\n";
+ if (parser_.file_identifier_.length())
+ code += ", \"" + parser_.file_identifier_ + "\"";
+ code += ");\n";
code += Indent + "}\n";
-
- if (parser_.root_struct_def_ == &struct_def) {
- code += "\n";
- code += Indent + "public static function finish";
- code += struct_def.name;
- code += "Buffer(FlatBufferBuilder $builder, $offset)\n";
- code += Indent + "{\n";
- code += Indent + Indent + "$builder->finish($offset";
-
- if (parser_.file_identifier_.length())
- code += ", \"" + parser_.file_identifier_ + "\"";
- code += ");\n";
- code += Indent + "}\n";
- }
}
+ }
// Generate a struct field, conditioned on its child type(s).
- void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
- GenComment(field.doc_comment, code_ptr, nullptr);
+ 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) {
- GetScalarFieldOfStruct(field, code_ptr);
- } else {
- GetScalarFieldOfTable(field, code_ptr);
- }
+ if (IsScalar(field.value.type.base_type)) {
+ if (struct_def.fixed) {
+ GetScalarFieldOfStruct(field, code_ptr);
} else {
- switch (field.value.type.base_type) {
+ GetScalarFieldOfTable(field, code_ptr);
+ }
+ } else {
+ switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT:
if (struct_def.fixed) {
GetStructFieldOfStruct(field, code_ptr);
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) {
}
break;
}
- case BASE_TYPE_UNION:
- GetUnionField(field, code_ptr);
- break;
- default:
- assert(0);
- }
- }
- if (field.value.type.base_type == BASE_TYPE_VECTOR) {
- GetVectorLen(field, code_ptr);
- if (field.value.type.element == BASE_TYPE_UCHAR) {
- GetUByte(field, code_ptr);
- }
+ case BASE_TYPE_UNION: GetUnionField(field, code_ptr); break;
+ default: assert(0);
}
}
-
- // Generate table constructors, conditioned on its members' types.
- 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;
- 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;
- code += Indent + "public static function add";
- code += MakeCamel(field.name);
- code += "(FlatBufferBuilder $builder, $offset)\n";
- code += Indent + "{\n";
- code += Indent + Indent + "$builder->addOffsetX(";
- code += NumToString(offset) + ", $offset, 0);\n";
- code += Indent + "}\n\n";
- } else {
- BuildFieldOfTable(field, offset, code_ptr);
- }
- if (field.value.type.base_type == BASE_TYPE_VECTOR) {
- BuildVectorOfTable(field, code_ptr);
- }
+ if (field.value.type.base_type == BASE_TYPE_VECTOR) {
+ GetVectorLen(field, code_ptr);
+ if (field.value.type.element == BASE_TYPE_UCHAR) {
+ GetUByte(field, code_ptr);
}
-
- GetEndOffsetOnTable(struct_def, code_ptr);
}
+ }
- // Generate struct or table methods.
- void GenStruct(const StructDef &struct_def,
- std::string *code_ptr) {
- if (struct_def.generated) return;
+ // Generate table constructors, conditioned on its members' types.
+ void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
+ GetStartOfTable(struct_def, code_ptr);
- GenComment(struct_def.doc_comment, code_ptr, nullptr);
- BeginClass(struct_def, code_ptr);
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
- if (!struct_def.fixed) {
- // Generate a special accessor for the table that has been declared as
- // the root type.
- NewRootTypeFromBuffer(struct_def, code_ptr);
+ auto offset = it - struct_def.fields.vec.begin();
+ if (field.value.type.base_type == BASE_TYPE_UNION) {
+ std::string &code = *code_ptr;
+ code += Indent + "public static function add";
+ code += MakeCamel(field.name);
+ code += "(FlatBufferBuilder $builder, $offset)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "$builder->addOffsetX(";
+ code += NumToString(offset) + ", $offset, 0);\n";
+ code += Indent + "}\n\n";
+ } else {
+ BuildFieldOfTable(field, offset, code_ptr);
}
-
- std::string &code = *code_ptr;
- if (!struct_def.fixed) {
- if (parser_.file_identifier_.length()) {
- // Return the identifier
- code += Indent + "public static function " + struct_def.name;
- code += "Identifier()\n";
- code += Indent + "{\n";
- code += Indent + Indent + "return \"";
- code += parser_.file_identifier_ + "\";\n";
- code += Indent + "}\n\n";
-
- // Check if a buffer has the identifier.
- code += Indent + "public static function " + struct_def.name;
- code += "BufferHasIdentifier(ByteBuffer $buf)\n";
- code += Indent + "{\n";
- code += Indent + Indent + "return self::";
- code += "__has_identifier($buf, self::";
- code += struct_def.name + "Identifier());\n";
- code += Indent + "}\n\n";
- }
-
- if (parser_.file_extension_.length()) {
- // Return the extension
- code += Indent + "public static function " + struct_def.name;
- code += "Extension()\n";
- code += Indent + "{\n";
- code += Indent + Indent + "return \"" + parser_.file_extension_;
- code += "\";\n";
- code += Indent + "}\n\n";
- }
+ if (field.value.type.base_type == BASE_TYPE_VECTOR) {
+ BuildVectorOfTable(field, code_ptr);
}
+ }
- // Generate the Init method that sets the field in a pre-existing
- // accessor object. This is to allow object reuse.
- InitializeExisting(struct_def, code_ptr);
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
- auto &field = **it;
- if (field.deprecated) continue;
+ GetEndOffsetOnTable(struct_def, code_ptr);
+ }
- GenStructAccessor(struct_def, field, code_ptr);
- }
+ // Generate struct or table methods.
+ void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
+ if (struct_def.generated) return;
- if (struct_def.fixed) {
- // create a struct constructor function
- GenStructBuilder(struct_def, code_ptr);
- } else {
- // Create a set of functions that allow table construction.
- GenTableBuilders(struct_def, code_ptr);
- }
- EndClass(code_ptr);
+ GenComment(struct_def.doc_comment, code_ptr, nullptr);
+ BeginClass(struct_def, code_ptr);
+
+ if (!struct_def.fixed) {
+ // Generate a special accessor for the table that has been declared as
+ // the root type.
+ NewRootTypeFromBuffer(struct_def, code_ptr);
}
- // Generate enum declarations.
- 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.vec.begin();
- it != enum_def.vals.vec.end();
- ++it) {
- auto &ev = **it;
- GenComment(ev.doc_comment, code_ptr, nullptr);
- EnumMember(ev, code_ptr);
- }
+ std::string &code = *code_ptr;
+ if (!struct_def.fixed) {
+ if (parser_.file_identifier_.length()) {
+ // Return the identifier
+ code += Indent + "public static function " + struct_def.name;
+ code += "Identifier()\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "return \"";
+ code += parser_.file_identifier_ + "\";\n";
+ code += Indent + "}\n\n";
- std::string &code = *code_ptr;
- code += "\n";
- code += Indent + "private static $names = array(\n";
- for (auto it = enum_def.vals.vec.begin();
- it != enum_def.vals.vec.end(); ++it) {
- auto &ev = **it;
- code += Indent + Indent + "\"" + ev.name + "\",\n";
+ // Check if a buffer has the identifier.
+ code += Indent + "public static function " + struct_def.name;
+ code += "BufferHasIdentifier(ByteBuffer $buf)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "return self::";
+ code += "__has_identifier($buf, self::";
+ code += struct_def.name + "Identifier());\n";
+ code += Indent + "}\n\n";
}
- code += Indent + ");\n\n";
- code += Indent + "public static function Name($e)\n";
- code += Indent + "{\n";
- code += Indent + Indent + "if (!isset(self::$names[$e])) {\n";
- code += Indent + Indent + Indent + "throw new \\Exception();\n";
- code += Indent + Indent + "}\n";
- code += Indent + Indent + "return self::$names[$e];\n";
- code += Indent + "}\n";
- EndEnum(code_ptr);
+ if (parser_.file_extension_.length()) {
+ // Return the extension
+ code += Indent + "public static function " + struct_def.name;
+ code += "Extension()\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "return \"" + parser_.file_extension_;
+ code += "\";\n";
+ code += Indent + "}\n\n";
+ }
}
- // Returns the function name that is able to read a value of the given type.
- static std::string GenGetter(const Type &type) {
- switch (type.base_type) {
+ // Generate the Init method that sets the field in a pre-existing
+ // accessor object. This is to allow object reuse.
+ InitializeExisting(struct_def, code_ptr);
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+
+ GenStructAccessor(struct_def, field, code_ptr);
+ }
+
+ if (struct_def.fixed) {
+ // create a struct constructor function
+ GenStructBuilder(struct_def, code_ptr);
+ } else {
+ // Create a set of functions that allow table construction.
+ GenTableBuilders(struct_def, code_ptr);
+ }
+ EndClass(code_ptr);
+ }
+
+ // Generate enum declarations.
+ 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.vec.begin(); it != enum_def.vals.vec.end();
+ ++it) {
+ auto &ev = **it;
+ GenComment(ev.doc_comment, code_ptr, nullptr);
+ EnumMember(ev, code_ptr);
+ }
+
+ std::string &code = *code_ptr;
+ code += "\n";
+ code += Indent + "private static $names = array(\n";
+ for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
+ ++it) {
+ auto &ev = **it;
+ code += Indent + Indent + "\"" + ev.name + "\",\n";
+ }
+
+ code += Indent + ");\n\n";
+ code += Indent + "public static function Name($e)\n";
+ code += Indent + "{\n";
+ code += Indent + Indent + "if (!isset(self::$names[$e])) {\n";
+ code += Indent + Indent + Indent + "throw new \\Exception();\n";
+ code += Indent + Indent + "}\n";
+ code += Indent + Indent + "return self::$names[$e];\n";
+ code += Indent + "}\n";
+ EndEnum(code_ptr);
+ }
+
+ // Returns the function name that is able to read a value of the given 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";
+ default: return "Get";
+ }
+ }
+
+ // Returns the method name for use with add/put calls.
+ static std::string GenMethod(const FieldDef &field) {
+ return IsScalar(field.value.type.base_type)
+ ? MakeCamel(GenTypeBasic(field.value.type))
+ : (IsStruct(field.value.type) ? "Struct" : "Offset");
+ }
+
+ static std::string GenTypeBasic(const Type &type) {
+ static const char *ctypename[] = {
+ // clang-format off
+ #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
+ CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
+ #NTYPE,
+ FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
+ #undef FLATBUFFERS_TD
+ // clang-format on
+ };
+ return ctypename[type.base_type];
+ }
+
+ std::string GenDefaultValue(const Value &value) {
+ if (value.type.enum_def) {
+ if (auto val = value.type.enum_def->ReverseLookup(
+ atoi(value.constant.c_str()), false)) {
+ return WrapInNameSpace(*value.type.enum_def) + "::" + val->name;
}
}
- // Returns the method name for use with add/put calls.
- static std::string GenMethod(const FieldDef &field) {
- return IsScalar(field.value.type.base_type)
- ? MakeCamel(GenTypeBasic(field.value.type))
- : (IsStruct(field.value.type) ? "Struct" : "Offset");
- }
+ switch (value.type.base_type) {
+ case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
- static std::string GenTypeBasic(const Type &type) {
- static const char *ctypename[] = {
-#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
- CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
- #NTYPE,
- FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
-#undef FLATBUFFERS_TD
- };
- return ctypename[type.base_type];
- }
-
- std::string GenDefaultValue(const Value &value) {
- if (value.type.enum_def) {
- if (auto val = value.type.enum_def->ReverseLookup(
- atoi(value.constant.c_str()), false)) {
- return WrapInNameSpace(*value.type.enum_def) + "::" + val->name;
- }
- }
-
- switch (value.type.base_type) {
- 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:
}
return "0";
- default:
- return value.constant;
- }
+ default: return value.constant;
}
+ }
- 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;
+ 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_UNION:
// fall through
- default:
- return "Table";
- }
- }
-
- 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;
- code += "\n";
- code += Indent + "/**\n";
- code += Indent + " * @return int offset\n";
- code += Indent + " */\n";
- code += Indent + "public static function create" + struct_def.name;
- code += "(FlatBufferBuilder $builder";
- StructBuilderArgs(struct_def, "", code_ptr);
- code += ")\n";
- code += Indent + "{\n";
-
- StructBuilderBody(struct_def, "", code_ptr);
-
- code += Indent + Indent + "return $builder->offset();\n";
- code += Indent + "}\n";
- }
-
- };
- } // namespace php
-
- bool GeneratePhp(const Parser &parser, const std::string &path,
- const std::string &file_name) {
- php::PhpGenerator generator(parser, path, file_name);
- return generator.generate();
- }
- } // namespace flatbuffers
+ default: return "Table";
+ }
+ }
+
+ 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;
+ code += "\n";
+ code += Indent + "/**\n";
+ code += Indent + " * @return int offset\n";
+ code += Indent + " */\n";
+ code += Indent + "public static function create" + struct_def.name;
+ code += "(FlatBufferBuilder $builder";
+ StructBuilderArgs(struct_def, "", code_ptr);
+ code += ")\n";
+ code += Indent + "{\n";
+
+ StructBuilderBody(struct_def, "", code_ptr);
+
+ code += Indent + Indent + "return $builder->offset();\n";
+ code += Indent + "}\n";
+ }
+};
+} // namespace php
+
+bool GeneratePhp(const Parser &parser, const std::string &path,
+ const std::string &file_name) {
+ php::PhpGenerator generator(parser, path, file_name);
+ return generator.generate();
+}
+} // namespace flatbuffers
#include <string>
+#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#include "flatbuffers/code_generators.h"
namespace flatbuffers {
namespace python {
static std::string GenTypeGet(const Type &type);
static std::string TypeName(const FieldDef &field);
-
// Hardcode spaces per indentation.
const std::string Indent = " ";
std::string OffsetPrefix(const FieldDef &field) {
return "\n" + Indent + Indent +
"o = flatbuffers.number_types.UOffsetTFlags.py_type" +
- "(self._tab.Offset(" +
- NumToString(field.value.offset) +
- "))\n" + Indent + Indent + "if o != 0:\n";
+ "(self._tab.Offset(" + NumToString(field.value.offset) + "))\n" +
+ Indent + Indent + "if o != 0:\n";
}
// Begin a class declaration.
}
// Get the length of a vector.
-static void GetVectorLen(const StructDef &struct_def,
- const FieldDef &field,
+static void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
}
// Get the value of a string.
-static void GetStringField(const StructDef &struct_def,
- const FieldDef &field,
+static void GetStringField(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
}
// Get the value of a union from an object.
-static void GetUnionField(const StructDef &struct_def,
- const FieldDef &field,
+static void GetUnionField(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
// 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 += MakeCamel(field.name) + "AsNumpy(self):";
// 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) {
+ const char *nameprefix, std::string *code_ptr) {
for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
+ it != struct_def.fields.vec.end(); ++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
// a nested struct, prefix the name with the field name.
StructBuilderArgs(*field.value.type.struct_def,
- (nameprefix + (field.name + "_")).c_str(),
- code_ptr);
+ (nameprefix + (field.name + "_")).c_str(), code_ptr);
} else {
std::string &code = *code_ptr;
- code += (std::string)", " + nameprefix;
+ code += (std::string) ", " + nameprefix;
code += MakeCamel(field.name, false);
}
}
// Recursively generate struct construction statements and instert manual
// padding.
static void StructBuilderBody(const StructDef &struct_def,
- const char *nameprefix,
- std::string *code_ptr) {
+ const char *nameprefix, std::string *code_ptr) {
std::string &code = *code_ptr;
code += " 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) {
+ it != struct_def.fields.vec.rend(); ++it) {
auto &field = **it;
if (field.padding)
code += " builder.Pad(" + NumToString(field.padding) + ")\n";
if (IsStruct(field.value.type)) {
StructBuilderBody(*field.value.type.struct_def,
- (nameprefix + (field.name + "_")).c_str(),
- code_ptr);
+ (nameprefix + (field.name + "_")).c_str(), code_ptr);
} else {
code += " builder.Prepend" + GenMethod(field) + "(";
code += nameprefix + MakeCamel(field.name, false) + ")\n";
// Set the value of a table's field.
static void BuildFieldOfTable(const StructDef &struct_def,
- const FieldDef &field,
- const size_t offset,
+ const FieldDef &field, const size_t offset,
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "def " + struct_def.name + "Add" + MakeCamel(field.name);
// Set the value of one of the members of a table's vector.
static void BuildVectorOfTable(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) {
+ const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "def " + struct_def.name + "Start";
code += MakeCamel(field.name);
// Generate a struct field, conditioned on its child type(s).
static void GenStructAccessor(const StructDef &struct_def,
- const FieldDef &field,
- std::string *code_ptr) {
+ 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) {
GetStructFieldOfTable(struct_def, field, code_ptr);
}
break;
- case BASE_TYPE_STRING:
- GetStringField(struct_def, field, code_ptr);
- break;
+ case BASE_TYPE_STRING: GetStringField(struct_def, field, code_ptr); break;
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
if (vectortype.base_type == BASE_TYPE_STRUCT) {
}
break;
}
- case BASE_TYPE_UNION:
- GetUnionField(struct_def, field, code_ptr);
- break;
- default:
- assert(0);
+ case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr); break;
+ default: assert(0);
}
}
if (field.value.type.base_type == BASE_TYPE_VECTOR) {
GetStartOfTable(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
+ it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
}
// Generate struct or table methods.
-static void GenStruct(const StructDef &struct_def,
- std::string *code_ptr) {
+static void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
if (struct_def.generated) return;
GenComment(struct_def.doc_comment, code_ptr, nullptr, "# ");
// accessor object. This is to allow object reuse.
InitializeExisting(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
+ it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
GenComment(enum_def.doc_comment, code_ptr, nullptr, "# ");
BeginEnum(enum_def.name, code_ptr);
- for (auto it = enum_def.vals.vec.begin();
- it != enum_def.vals.vec.end();
+ for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
auto &ev = **it;
GenComment(ev.doc_comment, code_ptr, nullptr, "# ");
case BASE_TYPE_UNION: return "self._tab.Union(";
case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
default:
- return "self._tab.Get(flatbuffers.number_types." + \
- MakeCamel(GenTypeGet(type)) + \
- "Flags, ";
+ return "self._tab.Get(flatbuffers.number_types." +
+ MakeCamel(GenTypeGet(type)) + "Flags, ";
}
}
// Returns the method name for use with add/put calls.
static std::string GenMethod(const FieldDef &field) {
return IsScalar(field.value.type.base_type)
- ? MakeCamel(GenTypeBasic(field.value.type))
- : (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative");
+ ? MakeCamel(GenTypeBasic(field.value.type))
+ : (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative");
}
static std::string GenTypeBasic(const Type &type) {
static const char *ctypename[] = {
+ // clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
#PTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
+ // clang-format on
};
return ctypename[type.base_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 "*flatbuffers.Table";
+ default: return "*flatbuffers.Table";
}
}
static std::string GenTypeGet(const Type &type) {
- return IsScalar(type.base_type)
- ? GenTypeBasic(type)
- : GenTypePointer(type);
+ return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
}
static std::string TypeName(const FieldDef &field) {
std::string &code = *code_ptr;
code = code + "# " + FlatBuffersGeneratedWarning() + "\n\n";
code += "# namespace: " + name_space_name + "\n\n";
- if (needs_imports) {
- code += "import flatbuffers\n\n";
- }
+ if (needs_imports) { code += "import flatbuffers\n\n"; }
}
// Save out the generated code for a Python Table type.
std::string code = "";
BeginFile(LastNamespacePart(*def.defined_namespace), needs_imports, &code);
code += classcode;
- std::string filename = NamespaceDir(*def.defined_namespace) +
- def.name + ".py";
+ std::string filename =
+ NamespaceDir(*def.defined_namespace) + def.name + ".py";
return SaveFile(filename.c_str(), code, false);
}
};
// independent from idl_parser, since this code is not needed for most clients
#include "flatbuffers/flatbuffers.h"
+#include "flatbuffers/flexbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#include "flatbuffers/flexbuffers.h"
namespace flatbuffers {
static bool GenStruct(const StructDef &struct_def, const Table *table,
- int indent, const IDLOptions &opts,
- std::string *_text);
+ int indent, const IDLOptions &opts, std::string *_text);
// If indentation is less than 0, that indicates we don't want any newlines
// either.
return opts.indent_step >= 0 ? "\n" : "";
}
-int Indent(const IDLOptions &opts) {
- return std::max(opts.indent_step, 0);
-}
+int Indent(const IDLOptions &opts) { return std::max(opts.indent_step, 0); }
// Output an identifier with or without quotes depending on strictness.
void OutputIdentifier(const std::string &name, const IDLOptions &opts,
// 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> bool Print(T val, Type type, int /*indent*/,
- Type * /*union_type*/,
- const IDLOptions &opts,
- std::string *_text) {
+template<typename T>
+bool Print(T val, Type type, int /*indent*/, Type * /*union_type*/,
+ const IDLOptions &opts, std::string *_text) {
std::string &text = *_text;
if (type.enum_def && opts.output_enum_identifiers) {
auto enum_val = type.enum_def->ReverseLookup(static_cast<int>(val));
}
// Print a vector a sequence of JSON values, comma separated, wrapped in "[]".
-template<typename T> bool PrintVector(const Vector<T> &v, Type type,
- int indent, const IDLOptions &opts,
- std::string *_text) {
+template<typename T>
+bool PrintVector(const Vector<T> &v, Type type, int indent,
+ const IDLOptions &opts, std::string *_text) {
std::string &text = *_text;
text += "[";
text += NewLine(opts);
return false;
}
} else {
- if (!Print(v[i], type, indent + Indent(opts), nullptr,
- opts, _text)) {
+ if (!Print(v[i], type, indent + Indent(opts), nullptr, opts, _text)) {
return false;
}
}
}
// Specialization of Print above for pointer types.
-template<> bool Print<const void *>(const void *val,
- Type type, int indent,
- Type *union_type,
- const IDLOptions &opts,
- std::string *_text) {
+template<>
+bool Print<const void *>(const void *val, Type type, int indent,
+ Type *union_type, const IDLOptions &opts,
+ std::string *_text) {
switch (type.base_type) {
case BASE_TYPE_UNION:
// If this assert hits, you have an corrupt buffer, a union type field
return Print<const void *>(val, *union_type, indent, nullptr, opts,
_text);
case BASE_TYPE_STRUCT:
- if (!GenStruct(*type.struct_def,
- reinterpret_cast<const Table *>(val),
- indent,
- opts,
- _text)) {
+ if (!GenStruct(*type.struct_def, reinterpret_cast<const Table *>(val),
+ indent, opts, _text)) {
return false;
}
break;
type = type.VectorType();
// Call PrintVector above specifically for each element type:
switch (type.base_type) {
+ // clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
case BASE_TYPE_ ## ENUM: \
break;
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
+ // clang-format on
}
break;
default: assert(0);
}
// Generate text for a scalar field.
-template<typename T> static bool GenField(const FieldDef &fd,
- const Table *table, bool fixed,
- const IDLOptions &opts,
- int indent,
- std::string *_text) {
- return Print(fixed ?
- reinterpret_cast<const Struct *>(table)->GetField<T>(fd.value.offset) :
- table->GetField<T>(fd.value.offset, 0), fd.value.type, indent, nullptr,
- opts, _text);
+template<typename T>
+static bool GenField(const FieldDef &fd, const Table *table, bool fixed,
+ const IDLOptions &opts, int indent, std::string *_text) {
+ return Print(fixed ? reinterpret_cast<const Struct *>(table)->GetField<T>(
+ fd.value.offset)
+ : table->GetField<T>(fd.value.offset, 0),
+ fd.value.type, indent, nullptr, opts, _text);
}
static bool GenStruct(const StructDef &struct_def, const Table *table,
- int indent, const IDLOptions &opts,
- std::string *_text);
+ int indent, const IDLOptions &opts, std::string *_text);
// Generate text for non-scalar field.
static bool GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
- int indent, Type *union_type,
- const IDLOptions &opts, std::string *_text) {
+ int indent, Type *union_type, const IDLOptions &opts,
+ std::string *_text) {
const void *val = nullptr;
if (fixed) {
// The only non-scalar fields in structs are structs.
assert(IsStruct(fd.value.type));
- val = reinterpret_cast<const Struct *>(table)->
- GetStruct<const void *>(fd.value.offset);
+ val = reinterpret_cast<const Struct *>(table)->GetStruct<const void *>(
+ fd.value.offset);
} else if (fd.flexbuffer) {
auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
auto root = flexbuffers::GetRoot(vec->data(), vec->size());
return GenStruct(*fd.nested_flatbuffer, root, indent, opts, _text);
} 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 Print(val, fd.value.type, indent, union_type, opts, _text);
}
// Generate text for a struct or table, values separated by commas, indented,
// and bracketed by "{}"
static bool GenStruct(const StructDef &struct_def, const Table *table,
- int indent, const IDLOptions &opts,
- std::string *_text) {
+ int indent, const IDLOptions &opts, std::string *_text) {
std::string &text = *_text;
text += "{";
int fieldout = 0;
Type *union_type = nullptr;
for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end();
- ++it) {
+ it != struct_def.fields.vec.end(); ++it) {
FieldDef &fd = **it;
auto is_present = struct_def.fixed || table->CheckField(fd.value.offset);
auto output_anyway = opts.output_default_scalars_in_json &&
- IsScalar(fd.value.type.base_type) &&
- !fd.deprecated;
+ IsScalar(fd.value.type.base_type) && !fd.deprecated;
if (is_present || output_anyway) {
if (fieldout++) {
if (!opts.protobuf_ascii_alike) text += ",";
OutputIdentifier(fd.name, opts, _text);
if (!opts.protobuf_ascii_alike ||
(fd.value.type.base_type != BASE_TYPE_STRUCT &&
- fd.value.type.base_type != BASE_TYPE_VECTOR)) text += ":";
+ fd.value.type.base_type != BASE_TYPE_VECTOR))
+ text += ":";
text += " ";
if (is_present) {
switch (fd.value.type.base_type) {
- #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
- CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
- case BASE_TYPE_ ## ENUM: \
- if (!GenField<CTYPE>(fd, table, struct_def.fixed, \
- opts, indent + Indent(opts), _text)) { \
- return false; \
- } \
- break;
+ // clang-format off
+ #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
+ CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
+ case BASE_TYPE_ ## ENUM: \
+ if (!GenField<CTYPE>(fd, table, struct_def.fixed, \
+ opts, indent + Indent(opts), _text)) { \
+ return false; \
+ } \
+ break;
FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
// Generate drop-thru case statements for all pointer types:
return false;
}
break;
+ // clang-format on
}
if (fd.value.type.base_type == BASE_TYPE_UTYPE) {
auto enum_val = fd.value.type.enum_def->ReverseLookup(
- table->GetField<uint8_t>(fd.value.offset, 0));
+ table->GetField<uint8_t>(fd.value.offset, 0));
assert(enum_val);
union_type = &enum_val->union_type;
}
- }
- else
- {
+ } else {
text += fd.value.constant;
}
}
std::string *_text) {
std::string &text = *_text;
assert(parser.root_struct_def_); // call SetRootType()
- text.reserve(1024); // Reduce amount of inevitable reallocs.
- if (!GenStruct(*parser.root_struct_def_,
- GetRoot<Table>(flatbuffer),
- 0,
- parser.opts,
- _text)) {
+ text.reserve(1024); // Reduce amount of inevitable reallocs.
+ if (!GenStruct(*parser.root_struct_def_, GetRoot<Table>(flatbuffer), 0,
+ parser.opts, _text)) {
return false;
}
text += NewLine(parser.opts);
return path + file_name + ".json";
}
-bool GenerateTextFile(const Parser &parser,
- const std::string &path,
+bool GenerateTextFile(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (!parser.builder_.GetSize() || !parser.root_struct_def_) return true;
std::string text;
if (!GenerateText(parser, parser.builder_.GetBufferPointer(), &text)) {
return false;
}
- return flatbuffers::SaveFile(TextFileName(path, file_name).c_str(),
- text,
+ return flatbuffers::SaveFile(TextFileName(path, file_name).c_str(), text,
false);
}
-std::string TextMakeRule(const Parser &parser,
- const std::string &path,
+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));
+ std::string filebase =
+ flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
std::string make_rule = TextFileName(path, filebase) + ": " + file_name;
- auto included_files = parser.GetIncludedFilesRecursive(
- parser.root_struct_def_->file);
- for (auto it = included_files.begin();
- it != included_files.end(); ++it) {
+ auto included_files =
+ parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
+ for (auto it = included_files.begin(); it != included_files.end(); ++it) {
make_rule += " " + *it;
}
return make_rule;
}
} // namespace flatbuffers
-
*/
#include <algorithm>
-#include <list>
#include <iostream>
+#include <list>
#include <math.h>
const double kPi = 3.14159265358979323846;
const char *const kTypeNames[] = {
+// clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
IDLTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
+ // clang-format on
nullptr
};
const char kTypeSizes[] = {
+// clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
sizeof(CTYPE),
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
+ // clang-format on
};
// The enums in the reflection schema should match the ones we use internally.
// Compare the last element to check if these go out of sync.
-static_assert(BASE_TYPE_UNION ==
- static_cast<BaseType>(reflection::Union),
+static_assert(BASE_TYPE_UNION == static_cast<BaseType>(reflection::Union),
"enums don't match");
// Any parsing calls have to be wrapped in this macro, which automates
// handling of recursive error checking a bit. It will check the received
// CheckedError object, and return straight away on error.
-#define ECHECK(call) { auto ce = (call); if (ce.Check()) return ce; }
+#define ECHECK(call) \
+ { \
+ auto ce = (call); \
+ if (ce.Check()) return ce; \
+ }
// These two functions are called hundreds of times below, so define a short
// form:
static bool ValidateUTF8(const std::string &str) {
const char *s = &str[0];
- const char * const sEnd = s + str.length();
+ const char *const sEnd = s + str.length();
while (s < sEnd) {
- if (FromUTF8(&s) < 0) {
- return false;
- }
+ if (FromUTF8(&s) < 0) { return false; }
}
return true;
}
void Parser::Message(const std::string &msg) {
error_ = file_being_parsed_.length() ? AbsolutePath(file_being_parsed_) : "";
+ // clang-format off
#ifdef _WIN32
error_ += "(" + NumToString(line_) + ")"; // MSVC alike
#else
if (file_being_parsed_.length()) error_ += ":";
error_ += NumToString(line_) + ":0"; // gcc alike
#endif
+ // clang-format on
error_ += ": " + msg;
}
-void Parser::Warning(const std::string &msg) {
- Message("warning: " + msg);
-}
+void Parser::Warning(const std::string &msg) { Message("warning: " + msg); }
CheckedError Parser::Error(const std::string &msg) {
Message("error: " + msg);
}
// atot: templated version of atoi/atof: convert a string to an instance of T.
-template<typename T> inline CheckedError atot(const char *s, Parser &parser,
- T *val) {
+template<typename T>
+inline CheckedError atot(const char *s, Parser &parser, T *val) {
int64_t i = StringToInt(s);
const int64_t min = flatbuffers::numeric_limits<T>::min();
const int64_t max = flatbuffers::numeric_limits<T>::max();
*val = (T)i;
return NoError();
}
-template<> inline CheckedError atot<uint64_t>(const char *s, Parser &parser,
- uint64_t *val) {
+template<>
+inline CheckedError atot<uint64_t>(const char *s, Parser &parser,
+ uint64_t *val) {
(void)parser;
*val = StringToUInt(s);
return NoError();
}
-template<> inline CheckedError atot<bool>(const char *s, Parser &parser,
- bool *val) {
+template<>
+inline CheckedError atot<bool>(const char *s, Parser &parser, bool *val) {
(void)parser;
*val = 0 != atoi(s);
return NoError();
}
-template<> inline CheckedError atot<float>(const char *s, Parser &parser,
- float *val) {
+template<>
+inline CheckedError atot<float>(const char *s, Parser &parser, float *val) {
(void)parser;
*val = static_cast<float>(strtod(s, nullptr));
return NoError();
}
-template<> inline CheckedError atot<double>(const char *s, Parser &parser,
- double *val) {
+template<>
+inline CheckedError atot<double>(const char *s, Parser &parser, double *val) {
(void)parser;
*val = strtod(s, nullptr);
return NoError();
}
-template<> inline CheckedError atot<Offset<void>>(const char *s, Parser &parser,
- Offset<void> *val) {
+template<>
+inline CheckedError atot<Offset<void>>(const char *s, Parser &parser,
+ Offset<void> *val) {
(void)parser;
*val = Offset<void>(atoi(s));
return NoError();
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.size() == 0 || !max_components) {
- return name;
- }
+ if (components.size() == 0 || !max_components) { return name; }
std::stringstream stream;
- for (size_t i = 0; i < std::min(components.size(), max_components);
- i++) {
- if (i) {
- stream << ".";
- }
+ for (size_t i = 0; i < std::min(components.size(), max_components); i++) {
+ if (i) { stream << "."; }
stream << components[i];
}
if (name.length()) stream << "." << name;
// Declare tokens we'll use. Single character tokens are represented by their
// ascii character code (e.g. '{'), others above 256.
+// clang-format off
#define FLATBUFFERS_GEN_TOKENS(TD) \
TD(Eof, 256, "end of file") \
TD(StringConstant, 257, "string constant") \
return tokens[t - 256];
}
}
+// clang-format on
std::string Parser::TokenToStringId(int t) {
return t == kTokenIdentifier ? attribute_ : TokenToString(t);
}
CheckedError Parser::SkipByteOrderMark() {
- if (static_cast<unsigned char>(*cursor_) != 0xef)
- return NoError();
+ if (static_cast<unsigned char>(*cursor_) != 0xef) return NoError();
cursor_++;
if (static_cast<unsigned char>(*cursor_) != 0xbb)
return Error("invalid utf-8 byte order mark");
char c = *cursor_++;
token_ = c;
switch (c) {
- case '\0': cursor_--; token_ = kTokenEof; return NoError();
- case ' ': case '\r': case '\t': break;
- case '\n': line_++; seen_newline = true; break;
- case '{': case '}': case '(': case ')': case '[': case ']':
- case ',': case ':': case ';': case '=': return NoError();
+ case '\0':
+ cursor_--;
+ token_ = kTokenEof;
+ return NoError();
+ case ' ':
+ case '\r':
+ case '\t': break;
+ case '\n':
+ line_++;
+ seen_newline = true;
+ break;
+ case '{':
+ case '}':
+ case '(':
+ case ')':
+ case '[':
+ case ']':
+ case ',':
+ case ':':
+ case ';':
+ case '=': return NoError();
case '.':
- if(!isdigit(static_cast<const unsigned char>(*cursor_))) return NoError();
+ if (!isdigit(static_cast<const unsigned char>(*cursor_)))
+ return NoError();
return Error("floating point constant can\'t start with \".\"");
case '\"':
case '\'': {
return Error("illegal character in string constant");
if (*cursor_ == '\\') {
cursor_++;
- if (unicode_high_surrogate != -1 &&
- *cursor_ != 'u') {
+ if (unicode_high_surrogate != -1 && *cursor_ != 'u') {
return Error(
- "illegal Unicode sequence (unpaired high surrogate)");
+ "illegal Unicode sequence (unpaired high surrogate)");
}
switch (*cursor_) {
- case 'n': attribute_ += '\n'; cursor_++; break;
- case 't': attribute_ += '\t'; cursor_++; break;
- case 'r': attribute_ += '\r'; cursor_++; break;
- case 'b': attribute_ += '\b'; cursor_++; break;
- case 'f': attribute_ += '\f'; cursor_++; break;
- case '\"': attribute_ += '\"'; cursor_++; break;
- case '\'': attribute_ += '\''; cursor_++; break;
- case '\\': attribute_ += '\\'; cursor_++; break;
- case '/': attribute_ += '/'; cursor_++; break;
+ case 'n':
+ attribute_ += '\n';
+ cursor_++;
+ break;
+ case 't':
+ attribute_ += '\t';
+ cursor_++;
+ break;
+ case 'r':
+ attribute_ += '\r';
+ cursor_++;
+ break;
+ case 'b':
+ attribute_ += '\b';
+ cursor_++;
+ break;
+ case 'f':
+ attribute_ += '\f';
+ cursor_++;
+ break;
+ case '\"':
+ attribute_ += '\"';
+ cursor_++;
+ break;
+ case '\'':
+ attribute_ += '\'';
+ cursor_++;
+ break;
+ case '\\':
+ attribute_ += '\\';
+ cursor_++;
+ break;
+ case '/':
+ attribute_ += '/';
+ cursor_++;
+ break;
case 'x': { // Not in the JSON standard
cursor_++;
uint64_t val;
if (val >= 0xD800 && val <= 0xDBFF) {
if (unicode_high_surrogate != -1) {
return Error(
- "illegal Unicode sequence (multiple high surrogates)");
+ "illegal Unicode sequence (multiple high surrogates)");
} else {
unicode_high_surrogate = static_cast<int>(val);
}
} else if (val >= 0xDC00 && val <= 0xDFFF) {
if (unicode_high_surrogate == -1) {
return Error(
- "illegal Unicode sequence (unpaired low surrogate)");
+ "illegal Unicode sequence (unpaired low surrogate)");
} else {
int code_point = 0x10000 +
- ((unicode_high_surrogate & 0x03FF) << 10) +
- (val & 0x03FF);
+ ((unicode_high_surrogate & 0x03FF) << 10) +
+ (val & 0x03FF);
ToUTF8(code_point, &attribute_);
unicode_high_surrogate = -1;
}
} else {
if (unicode_high_surrogate != -1) {
return Error(
- "illegal Unicode sequence (unpaired high surrogate)");
+ "illegal Unicode sequence (unpaired high surrogate)");
}
ToUTF8(static_cast<int>(val), &attribute_);
}
}
default: return Error("unknown escape code in string constant");
}
- } else { // printable chars + UTF-8 bytes
+ } else { // printable chars + UTF-8 bytes
if (unicode_high_surrogate != -1) {
return Error(
- "illegal Unicode sequence (unpaired high surrogate)");
+ "illegal Unicode sequence (unpaired high surrogate)");
}
attribute_ += *cursor_++;
}
}
if (unicode_high_surrogate != -1) {
- return Error(
- "illegal Unicode sequence (unpaired high surrogate)");
+ return Error("illegal Unicode sequence (unpaired high surrogate)");
}
cursor_++;
if (!opts.allow_non_utf8 && !ValidateUTF8(attribute_)) {
if (*start == '/') { // documentation comment
if (cursor_ != source_ && !seen_newline)
return Error(
- "a documentation comment should be on a line on its own");
+ "a documentation comment should be on a line on its own");
doc_comment_.push_back(std::string(start + 1, cursor_));
}
break;
c = '0';
}
if (c == '0' && (*cursor_ == 'x' || *cursor_ == 'X')) {
- cursor_++;
- while (isxdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
- attribute_.append(start + 2, cursor_);
- attribute_ = NumToString(static_cast<int64_t>(
- StringToUInt(attribute_.c_str(), nullptr, 16)));
- token_ = kTokenIntegerConstant;
- return NoError();
+ cursor_++;
+ while (isxdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
+ attribute_.append(start + 2, cursor_);
+ attribute_ = NumToString(static_cast<int64_t>(
+ StringToUInt(attribute_.c_str(), nullptr, 16)));
+ token_ = kTokenIntegerConstant;
+ return NoError();
}
while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
if (*cursor_ == '.' || *cursor_ == 'e' || *cursor_ == 'E') {
}
// Check if a given token is next.
-bool Parser::Is(int t) {
- return t == token_;
-}
+bool Parser::Is(int t) { return t == token_; }
bool Parser::IsIdent(const char *id) {
return token_ == kTokenIdentifier && attribute_ == id;
// Expect a given token to be next, consume it, or error if not present.
CheckedError Parser::Expect(int t) {
if (t != token_) {
- return Error("expecting: " + TokenToString(t) + " instead got: " +
- TokenToStringId(token_));
+ return Error("expecting: " + TokenToString(t) +
+ " instead got: " + TokenToStringId(token_));
}
NEXT();
return NoError();
for (int components = static_cast<int>(current_namespace_->components.size());
components >= 0; components--) {
auto ed = enums_.Lookup(
- current_namespace_->GetFullyQualifiedName(id, components));
+ current_namespace_->GetFullyQualifiedName(id, components));
if (ed) return ed;
}
return nullptr;
if (subtype.base_type == BASE_TYPE_VECTOR) {
// We could support this, but it will complicate things, and it's
// easier to work around with a struct around the inner vector.
- return Error(
- "nested vector types not supported (wrap in table first).");
+ return Error("nested vector types not supported (wrap in table first).");
}
type = Type(BASE_TYPE_VECTOR, subtype.struct_def, subtype.enum_def);
type.element = subtype.base_type;
const Type &type, FieldDef **dest) {
auto &field = *new FieldDef();
field.value.offset =
- FieldIndexToOffset(static_cast<voffset_t>(struct_def.fields.vec.size()));
+ FieldIndexToOffset(static_cast<voffset_t>(struct_def.fields.vec.size()));
field.name = name;
field.file = struct_def.file;
field.value.type = type;
type.element == BASE_TYPE_UNION) {
// Only cpp, js and ts supports the union vector feature so far.
if (!SupportsVectorOfUnions()) {
- return Error("Vectors of unions are not yet supported in all "
- "the specified programming languages.");
+ return Error(
+ "Vectors of unions are not yet supported in all "
+ "the specified programming languages.");
}
// For vector of union fields, add a second auto-generated vector field to
// hold the types, with a special suffix.
Type union_vector(BASE_TYPE_VECTOR, nullptr, type.enum_def);
union_vector.element = BASE_TYPE_UTYPE;
- ECHECK(AddField(struct_def, name + UnionTypeFieldSuffix(),
- union_vector, &typefield));
+ ECHECK(AddField(struct_def, name + UnionTypeFieldSuffix(), union_vector,
+ &typefield));
}
FieldDef *field;
field->value.constant += ".0";
}
- if (type.enum_def &&
- IsScalar(type.base_type) &&
- !struct_def.fixed &&
+ if (type.enum_def && IsScalar(type.base_type) && !struct_def.fixed &&
!type.enum_def->attributes.Lookup("bit_flags") &&
- !type.enum_def->ReverseLookup(static_cast<int>(
- StringToInt(field->value.constant.c_str()))))
+ !type.enum_def->ReverseLookup(
+ static_cast<int>(StringToInt(field->value.constant.c_str()))))
Warning("enum " + type.enum_def->name +
- " does not have a declaration for this field\'s default of " +
- field->value.constant);
+ " does not have a declaration for this field\'s default of " +
+ field->value.constant);
field->doc_comment = dc;
ECHECK(ParseMetaData(&field->attributes));
case BASE_TYPE_UINT: {
if (FindHashFunction32(hash_name->constant.c_str()) == nullptr)
return Error("Unknown hashing algorithm for 32 bit types: " +
- hash_name->constant);
+ hash_name->constant);
break;
}
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG: {
if (FindHashFunction64(hash_name->constant.c_str()) == nullptr)
return Error("Unknown hashing algorithm for 64 bit types: " +
- hash_name->constant);
+ hash_name->constant);
break;
}
default:
return Error(
- "only int, uint, long and ulong data types support hashing.");
+ "only int, uint, long and ulong data types support hashing.");
}
}
auto cpp_type = field->attributes.Lookup("cpp_type");
if (field->deprecated && struct_def.fixed)
return Error("can't deprecate fields in a struct");
field->required = field->attributes.Lookup("required") != nullptr;
- if (field->required && (struct_def.fixed ||
- IsScalar(field->value.type.base_type)))
+ if (field->required &&
+ (struct_def.fixed || IsScalar(field->value.type.base_type)))
return Error("only non-scalar fields in tables may be 'required'");
field->key = field->attributes.Lookup("key") != nullptr;
if (field->key) {
- if (struct_def.has_key)
- return Error("only one field may be set as 'key'");
+ if (struct_def.has_key) return Error("only one field may be set as 'key'");
struct_def.has_key = true;
if (!IsScalar(field->value.type.base_type)) {
field->required = true;
}
}
- auto field_native_custom_alloc = field->attributes.Lookup("native_custom_alloc");
+ auto field_native_custom_alloc =
+ field->attributes.Lookup("native_custom_alloc");
if (field_native_custom_alloc)
- return Error("native_custom_alloc can only be used with a table or struct definition");
+ return Error(
+ "native_custom_alloc can only be used with a table or struct "
+ "definition");
field->native_inline = field->attributes.Lookup("native_inline") != nullptr;
if (field->native_inline && !IsStruct(field->value.type))
if (nested) {
if (nested->type.base_type != BASE_TYPE_STRING)
return Error(
- "nested_flatbuffer attribute must be a string (the root type)");
+ "nested_flatbuffer attribute must be a string (the root type)");
if (field->value.type.base_type != BASE_TYPE_VECTOR ||
field->value.type.element != BASE_TYPE_UCHAR)
return Error(
- "nested_flatbuffer attribute may only apply to a vector of ubyte");
+ "nested_flatbuffer attribute may only apply to a vector of ubyte");
// This will cause an error if the root type of the nested flatbuffer
// wasn't defined elsewhere.
LookupCreateStruct(nested->constant);
uses_flexbuffers_ = true;
if (field->value.type.base_type != BASE_TYPE_VECTOR ||
field->value.type.element != BASE_TYPE_UCHAR)
- return Error(
- "flexbuffer attribute may only apply to a vector of ubyte");
+ return Error("flexbuffer attribute may only apply to a vector of ubyte");
}
if (typefield) {
}
break;
}
- default:
- ECHECK(ParseSingleValue(val));
- break;
+ default: ECHECK(ParseSingleValue(val)); break;
}
return NoError();
}
CheckedError Parser::ParseTable(const StructDef &struct_def, std::string *value,
uoffset_t *ovalue) {
size_t fieldn_outer = 0;
- auto err = ParseTableDelimiters(fieldn_outer, &struct_def,
- [](const std::string &name, size_t &fieldn,
- const StructDef *struct_def_inner,
- void *state) -> CheckedError {
- Parser *parser = static_cast<Parser *>(state);
- if (name == "$schema") {
- ECHECK(parser->Expect(kTokenStringConstant));
- return NoError();
- }
- auto field = struct_def_inner->fields.Lookup(name);
- if (!field) {
- if (!parser->opts.skip_unexpected_fields_in_json) {
- return parser->Error("unknown field: " + name);
- } else {
- ECHECK(parser->SkipAnyJsonValue());
- }
- } else {
- if (parser->IsIdent("null")) {
- ECHECK(parser->Next()); // Ignore this field.
- } else {
- Value val = field->value;
- if (field->flexbuffer) {
- flexbuffers::Builder builder(1024,
- flexbuffers::BUILDER_FLAG_SHARE_ALL);
- ECHECK(parser->ParseFlexBufferValue(&builder));
- builder.Finish();
- auto off = parser->builder_.CreateVector(builder.GetBuffer());
- val.constant = NumToString(off.o);
- } else if (field->nested_flatbuffer) {
- ECHECK(parser->ParseNestedFlatbuffer(val, field, fieldn, struct_def_inner));
- } else {
- ECHECK(parser->ParseAnyValue(val, field, fieldn, struct_def_inner));
+ auto err = ParseTableDelimiters(
+ fieldn_outer, &struct_def,
+ [](const std::string &name, size_t &fieldn,
+ const StructDef *struct_def_inner, void *state) -> CheckedError {
+ Parser *parser = static_cast<Parser *>(state);
+ if (name == "$schema") {
+ ECHECK(parser->Expect(kTokenStringConstant));
+ return NoError();
}
- // Hardcoded insertion-sort with error-check.
- // If fields are specified in order, then this loop exits immediately.
- auto elem = parser->field_stack_.rbegin();
- for (; elem != parser->field_stack_.rbegin() + fieldn; ++elem) {
- auto existing_field = elem->second;
- if (existing_field == field)
- return parser->Error("field set more than once: " + field->name);
- if (existing_field->value.offset < field->value.offset) break;
+ auto field = struct_def_inner->fields.Lookup(name);
+ if (!field) {
+ if (!parser->opts.skip_unexpected_fields_in_json) {
+ return parser->Error("unknown field: " + name);
+ } else {
+ ECHECK(parser->SkipAnyJsonValue());
+ }
+ } else {
+ if (parser->IsIdent("null")) {
+ ECHECK(parser->Next()); // Ignore this field.
+ } else {
+ Value val = field->value;
+ if (field->flexbuffer) {
+ flexbuffers::Builder builder(1024,
+ flexbuffers::BUILDER_FLAG_SHARE_ALL);
+ ECHECK(parser->ParseFlexBufferValue(&builder));
+ builder.Finish();
+ auto off = parser->builder_.CreateVector(builder.GetBuffer());
+ val.constant = NumToString(off.o);
+ } else if (field->nested_flatbuffer) {
+ ECHECK(parser->ParseNestedFlatbuffer(val, field, fieldn,
+ struct_def_inner));
+ } else {
+ ECHECK(
+ parser->ParseAnyValue(val, field, fieldn, struct_def_inner));
+ }
+ // Hardcoded insertion-sort with error-check.
+ // If fields are specified in order, then this loop exits
+ // immediately.
+ auto elem = parser->field_stack_.rbegin();
+ for (; elem != parser->field_stack_.rbegin() + fieldn; ++elem) {
+ auto existing_field = elem->second;
+ if (existing_field == field)
+ return parser->Error("field set more than once: " +
+ field->name);
+ if (existing_field->value.offset < field->value.offset) break;
+ }
+ // Note: elem points to before the insertion point, thus .base()
+ // points to the correct spot.
+ parser->field_stack_.insert(elem.base(),
+ std::make_pair(val, field));
+ fieldn++;
+ }
}
- // Note: elem points to before the insertion point, thus .base() points
- // to the correct spot.
- parser->field_stack_.insert(elem.base(),
- std::make_pair(val, field));
- fieldn++;
- }
- }
- return NoError();
- }, this);
+ return NoError();
+ },
+ this);
ECHECK(err);
// Check if all required fields are parsed.
for (auto field_it = struct_def.fields.vec.begin();
- field_it != struct_def.fields.vec.end();
- ++field_it) {
+ field_it != struct_def.fields.vec.end(); ++field_it) {
auto required_field = *field_it;
- if (!required_field->required) {
- continue;
- }
+ if (!required_field->required) { continue; }
bool found = false;
for (auto pf_it = field_stack_.end() - fieldn_outer;
- pf_it != field_stack_.end();
- ++pf_it) {
+ pf_it != field_stack_.end(); ++pf_it) {
auto parsed_field = pf_it->second;
if (parsed_field == required_field) {
found = true;
}
}
if (!found) {
- return Error("required field is missing: " + required_field->name + " in " + struct_def.name);
+ return Error("required field is missing: " + required_field->name +
+ " in " + struct_def.name);
}
}
if (struct_def.fixed && fieldn_outer != struct_def.fields.vec.size())
return Error("struct: wrong number of initializers: " + struct_def.name);
- auto start = struct_def.fixed
- ? builder_.StartStruct(struct_def.minalign)
- : builder_.StartTable();
+ auto start = struct_def.fixed ? builder_.StartStruct(struct_def.minalign)
+ : builder_.StartTable();
- for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
- size;
+ for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1; size;
size /= 2) {
// Go through elements in reverse, since we're building the data backwards.
- for (auto it = field_stack_.rbegin(); it != field_stack_.rbegin() +
- fieldn_outer;
- ++it) {
+ for (auto it = field_stack_.rbegin();
+ it != field_stack_.rbegin() + fieldn_outer; ++it) {
auto &field_value = it->first;
auto field = it->second;
if (!struct_def.sortbysize ||
size == SizeOf(field_value.type.base_type)) {
switch (field_value.type.base_type) {
+ // clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
case BASE_TYPE_ ## ENUM: \
break;
FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD);
#undef FLATBUFFERS_TD
+ // clang-format on
}
}
}
// 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()),
- struct_def.bytesize);
+ reinterpret_cast<const char *>(builder_.GetCurrentBufferPointer()),
+ struct_def.bytesize);
builder_.PopBytes(struct_def.bytesize);
assert(!ovalue);
} else {
CheckedError Parser::ParseVector(const Type &type, uoffset_t *ovalue) {
size_t count = 0;
std::pair<Parser *, const Type &> parser_and_type_state(this, type);
- auto err = ParseVectorDelimiters(count,
- [](size_t &, void *state) -> CheckedError {
- auto *parser_and_type =
- static_cast<std::pair<Parser *, const Type &> *>(state);
- auto *parser = parser_and_type->first;
- Value val;
- val.type = parser_and_type->second;
- ECHECK(parser->ParseAnyValue(val, nullptr, 0, nullptr));
- parser->field_stack_.push_back(std::make_pair(val, nullptr));
- return NoError();
- }, &parser_and_type_state);
+ auto err = ParseVectorDelimiters(
+ count,
+ [](size_t &, void *state) -> CheckedError {
+ auto *parser_and_type =
+ static_cast<std::pair<Parser *, const Type &> *>(state);
+ auto *parser = parser_and_type->first;
+ Value val;
+ val.type = parser_and_type->second;
+ ECHECK(parser->ParseAnyValue(val, nullptr, 0, nullptr));
+ parser->field_stack_.push_back(std::make_pair(val, nullptr));
+ return NoError();
+ },
+ &parser_and_type_state);
ECHECK(err);
builder_.StartVector(count * InlineSize(type) / InlineAlignment(type),
// start at the back, since we're building the data backwards.
auto &val = field_stack_.back().first;
switch (val.type.base_type) {
+ // clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
case BASE_TYPE_ ## ENUM: \
break;
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
+ // clang-format on
}
field_stack_.pop_back();
}
}
CheckedError Parser::ParseNestedFlatbuffer(Value &val, FieldDef *field,
- size_t fieldn,
- const StructDef *parent_struct_def) {
- if (token_ == '[') {// backwards compat for 'legacy' ubyte buffers
+ size_t fieldn,
+ const StructDef *parent_struct_def) {
+ if (token_ == '[') { // backwards compat for 'legacy' ubyte buffers
ECHECK(ParseAnyValue(val, field, fieldn, parent_struct_def));
} else {
auto cursor_at_value_begin = cursor_;
ECHECK(SkipAnyJsonValue());
- std::string substring(cursor_at_value_begin -1 , cursor_ -1);
+ std::string substring(cursor_at_value_begin - 1, cursor_ - 1);
// Create and initialize new parser
Parser nested_parser;
if (!nested_parser.Parse(substring.c_str(), nullptr, nullptr)) {
ECHECK(Error(nested_parser.error_));
}
- auto off = builder_.CreateVector(nested_parser.builder_.GetBufferPointer(), nested_parser.builder_.GetSize());
+ auto off = builder_.CreateVector(nested_parser.builder_.GetBufferPointer(),
+ nested_parser.builder_.GetSize());
val.constant = NumToString(off.o);
- // Clean nested_parser before destruction to avoid deleting the elements in the SymbolTables
+ // Clean nested_parser before destruction to avoid deleting the elements in
+ // the SymbolTables
nested_parser.enums_.dict.clear();
nested_parser.enums_.vec.clear();
}
NEXT();
ECHECK(ParseSingleValue(*e));
}
- if (Is(')')) { NEXT(); break; }
+ if (Is(')')) {
+ NEXT();
+ break;
+ }
EXPECT(',');
}
}
} else {
return Error(std::string("type mismatch: expecting: ") +
kTypeNames[e.type.base_type] +
- ", found: " +
- kTypeNames[req]);
+ ", found: " + kTypeNames[req]);
}
}
NEXT();
auto enum_val = type.enum_def->vals.Lookup(word);
if (!enum_val)
return Error("unknown enum value: " + word +
- ", for enum: " + type.enum_def->name);
+ ", for enum: " + type.enum_def->name);
*result |= enum_val->value;
} else { // No enum type, probably integral field.
if (!IsInteger(type.base_type))
if (!enum_val) return Error("unknown enum value: " + enum_val_str);
*result |= enum_val->value;
}
- } while(*next);
+ } while (*next);
return NoError();
}
-
-CheckedError Parser::ParseHash(Value &e, FieldDef* field) {
+CheckedError Parser::ParseHash(Value &e, FieldDef *field) {
assert(field);
Value *hash_name = field->attributes.Lookup("hash");
switch (e.type.base_type) {
e.constant = NumToString(hashed_value);
break;
}
- default:
- assert(0);
+ default: assert(0);
}
NEXT();
return NoError();
}
CheckedError Parser::TokenError() {
- return Error("cannot parse value starting with: " +
- TokenToStringId(token_));
+ return Error("cannot parse value starting with: " + TokenToStringId(token_));
}
CheckedError Parser::ParseSingleValue(Value &e) {
EXPECT('(');
ECHECK(ParseSingleValue(e));
EXPECT(')');
+ // clang-format off
#define FLATBUFFERS_FN_DOUBLE(name, op) \
if (functionname == name) { \
auto x = strtod(e.constant.c_str(), nullptr); \
FLATBUFFERS_FN_DOUBLE("atan", atan(x));
// TODO(wvo): add more useful conversion functions here.
#undef FLATBUFFERS_FN_DOUBLE
- // Then check if this could be a string/identifier enum value:
+ // clang-format on
+ // Then check if this could be a string/identifier enum value:
} else if (e.type.base_type != BASE_TYPE_STRING &&
- e.type.base_type != BASE_TYPE_BOOL &&
- e.type.base_type != BASE_TYPE_NONE &&
- (token_ == kTokenIdentifier || token_ == kTokenStringConstant)) {
+ e.type.base_type != BASE_TYPE_BOOL &&
+ e.type.base_type != BASE_TYPE_NONE &&
+ (token_ == kTokenIdentifier || token_ == kTokenStringConstant)) {
if (IsIdentifierStart(attribute_[0])) { // Enum value.
int64_t val;
ECHECK(ParseEnumFromString(e.type, &val));
if (IsInteger(e.type.base_type)) {
char *end;
e.constant = NumToString(StringToInt(attribute_.c_str(), &end));
- if (*end)
- return Error("invalid integer: " + attribute_);
+ if (*end) return Error("invalid integer: " + attribute_);
} else if (IsFloat(e.type.base_type)) {
char *end;
e.constant = NumToString(strtod(attribute_.c_str(), &end));
- if (*end)
- return Error("invalid float: " + attribute_);
+ if (*end) return Error("invalid float: " + attribute_);
} else {
assert(0); // Shouldn't happen, we covered all types.
e.constant = "0";
}
} else {
bool match = false;
- ECHECK(TryTypedValue(kTokenIntegerConstant,
- IsScalar(e.type.base_type),
- e,
- BASE_TYPE_INT,
- &match));
- ECHECK(TryTypedValue(kTokenFloatConstant,
- IsFloat(e.type.base_type),
- e,
- BASE_TYPE_FLOAT,
- &match));
+ ECHECK(TryTypedValue(kTokenIntegerConstant, IsScalar(e.type.base_type), e,
+ BASE_TYPE_INT, &match));
+ ECHECK(TryTypedValue(kTokenFloatConstant, IsFloat(e.type.base_type), e,
+ BASE_TYPE_FLOAT, &match));
ECHECK(TryTypedValue(kTokenStringConstant,
- e.type.base_type == BASE_TYPE_STRING,
- e,
- BASE_TYPE_STRING,
- &match));
+ e.type.base_type == BASE_TYPE_STRING, e,
+ BASE_TYPE_STRING, &match));
auto istrue = IsIdent("true");
if (istrue || IsIdent("false")) {
attribute_ = NumToString(istrue);
- ECHECK(TryTypedValue(kTokenIdentifier,
- IsBool(e.type.base_type),
- e,
- BASE_TYPE_BOOL,
- &match));
+ ECHECK(TryTypedValue(kTokenIdentifier, IsBool(e.type.base_type), e,
+ BASE_TYPE_BOOL, &match));
}
if (!match) return TokenError();
}
structs_.Add(name, struct_def);
struct_def->name = name;
struct_def->defined_namespace = current_namespace_;
- struct_def->original_location.reset(new std::string(file_being_parsed_ +
- ":" + NumToString(line_)));
+ struct_def->original_location.reset(
+ new std::string(file_being_parsed_ + ":" + NumToString(line_)));
}
}
return struct_def;
// Give specialized error message, since this type spec used to
// be optional in the first FlatBuffers release.
if (!Is(':')) {
- return Error("must specify the underlying integer type for this"
- " enum (e.g. \': short\', which was the default).");
+ return Error(
+ "must specify the underlying integer type for this"
+ " enum (e.g. \': short\', which was the default).");
} else {
NEXT();
}
}
}
auto prevsize = enum_def.vals.vec.size();
- auto value = enum_def.vals.vec.size()
- ? enum_def.vals.vec.back()->value + 1
- : 0;
+ auto value =
+ enum_def.vals.vec.size() ? enum_def.vals.vec.back()->value + 1 : 0;
auto &ev = *new EnumVal(value_name, value);
if (enum_def.vals.Add(value_name, &ev))
return Error("enum value already exists: " + value_name);
for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
if (static_cast<size_t>((*it)->value) >=
- SizeOf(enum_def.underlying_type.base_type) * 8)
+ SizeOf(enum_def.underlying_type.base_type) * 8)
return Error("bit flag out of range of underlying integral type");
(*it)->value = 1LL << (*it)->value;
}
struct_def.file = file_being_parsed_;
// Move this struct to the back of the vector just in case it was predeclared,
// to preserve declaration order.
- *std::remove(structs_.vec.begin(), structs_.vec.end(), &struct_def) = &struct_def;
+ *std::remove(structs_.vec.begin(), structs_.vec.end(), &struct_def) =
+ &struct_def;
*dest = &struct_def;
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) {
if (fname.length() > len &&
fname.compare(fname.length() - len, len, suffix) == 0 &&
(*it)->value.type.base_type != BASE_TYPE_UTYPE) {
- auto field = struct_def->fields.Lookup(
- fname.substr(0, fname.length() - len));
+ auto field =
+ struct_def->fields.Lookup(fname.substr(0, fname.length() - len));
if (field && field->value.type.base_type == basetype)
return Error("Field " + fname +
" would clash with generated functions for field " +
}
bool Parser::SupportsVectorOfUnions() const {
- return opts.lang_to_generate != 0 && (opts.lang_to_generate &
- ~(IDLOptions::kCpp | IDLOptions::kJs | IDLOptions::kTs | IDLOptions::kPhp)) == 0;
+ return opts.lang_to_generate != 0 &&
+ (opts.lang_to_generate & ~(IDLOptions::kCpp | IDLOptions::kJs |
+ IDLOptions::kTs | IDLOptions::kPhp)) == 0;
}
Namespace *Parser::UniqueNamespace(Namespace *ns) {
struct_def->fixed = fixed;
ECHECK(ParseMetaData(&struct_def->attributes));
struct_def->sortbysize =
- struct_def->attributes.Lookup("original_order") == nullptr && !fixed;
+ struct_def->attributes.Lookup("original_order") == nullptr && !fixed;
EXPECT('{');
while (token_ != '}') ECHECK(ParseField(*struct_def));
auto force_align = struct_def->attributes.Lookup("force_align");
if (fixed && force_align) {
auto align = static_cast<size_t>(atoi(force_align->constant.c_str()));
if (force_align->type.base_type != BASE_TYPE_INT ||
- align < struct_def->minalign ||
- align > FLATBUFFERS_MAX_ALIGNMENT ||
+ align < struct_def->minalign || align > FLATBUFFERS_MAX_ALIGNMENT ||
align & (align - 1))
- return Error("force_align must be a power of two integer ranging from the"
- "struct\'s natural alignment to " +
- NumToString(FLATBUFFERS_MAX_ALIGNMENT));
+ return Error(
+ "force_align must be a power of two integer ranging from the"
+ "struct\'s natural alignment to " +
+ NumToString(FLATBUFFERS_MAX_ALIGNMENT));
struct_def->minalign = align;
}
struct_def->PadLastField(struct_def->minalign);
// Then all fields must have them.
if (num_id_fields != fields.size())
return Error(
- "either all fields or no fields must have an 'id' attribute");
+ "either all fields or no fields must have an 'id' attribute");
// Simply sort by id, then the fields are the same as if no ids had
// been specified.
std::sort(fields.begin(), fields.end(), compareFieldDefs);
for (int i = 0; i < static_cast<int>(fields.size()); i++) {
if (i != atoi(fields[i]->attributes.Lookup("id")->constant.c_str()))
return Error("field id\'s must be consecutive from 0, id " +
- NumToString(i) + " missing or set twice");
+ NumToString(i) + " missing or set twice");
fields[i]->value.offset = FieldIndexToOffset(static_cast<voffset_t>(i));
}
}
}
- ECHECK(CheckClash(fields, struct_def, UnionTypeFieldSuffix(),
- BASE_TYPE_UNION));
+ ECHECK(
+ CheckClash(fields, struct_def, UnionTypeFieldSuffix(), BASE_TYPE_UNION));
ECHECK(CheckClash(fields, struct_def, "Type", BASE_TYPE_UNION));
ECHECK(CheckClash(fields, struct_def, "_length", BASE_TYPE_VECTOR));
ECHECK(CheckClash(fields, struct_def, "Length", BASE_TYPE_VECTOR));
ECHECK(ParseTypeIdent(resptype));
if (reqtype.base_type != BASE_TYPE_STRUCT || reqtype.struct_def->fixed ||
resptype.base_type != BASE_TYPE_STRUCT || resptype.struct_def->fixed)
- return Error("rpc request and response types must be tables");
+ return Error("rpc request and response types must be tables");
auto &rpc = *new RPCCall();
rpc.name = rpc_name;
rpc.request = reqtype.struct_def;
bool Parser::SetRootType(const char *name) {
root_struct_def_ = LookupStruct(name);
if (!root_struct_def_)
- root_struct_def_ = LookupStruct(
- current_namespace_->GetFullyQualifiedName(name));
+ root_struct_def_ =
+ LookupStruct(current_namespace_->GetFullyQualifiedName(name));
return root_struct_def_ != nullptr;
}
// This function marks all existing definitions as having already
// been generated, which signals no code for included files should be
// generated.
- for (auto it = enums_.vec.begin();
- it != enums_.vec.end(); ++it) {
+ for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
(*it)->generated = true;
}
- for (auto it = structs_.vec.begin();
- it != structs_.vec.end(); ++it) {
- if (!(*it)->predecl) {
- (*it)->generated = true;
- }
+ for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) {
+ if (!(*it)->predecl) { (*it)->generated = true; }
}
- for (auto it = services_.vec.begin();
- it != services_.vec.end(); ++it) {
+ for (auto it = services_.vec.begin(); it != services_.vec.end(); ++it) {
(*it)->generated = true;
}
}
return NoError();
}
-static bool compareEnumVals(const EnumVal *a, const EnumVal* b) {
+static bool compareEnumVals(const EnumVal *a, const EnumVal *b) {
return a->value < b->value;
}
}
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:
std::sort(v.begin(), v.end(), compareEnumVals);
// Temp: remove any duplicates, as .fbs files can't handle them.
- for (auto it = v.begin(); it != v.end(); ) {
- if (it != v.begin() && it[0]->value == it[-1]->value) it = v.erase(it);
- else ++it;
+ for (auto it = v.begin(); it != v.end();) {
+ if (it != v.begin() && it[0]->value == it[-1]->value)
+ it = v.erase(it);
+ else
+ ++it;
}
} else if (IsIdent("syntax")) { // Skip these.
NEXT();
ECHECK(ParseProtoCurliesOrIdent());
} else {
return Error("don\'t know how to parse .proto declaration starting with " +
- TokenToStringId(token_));
+ TokenToStringId(token_));
}
return NoError();
}
// Skip "(a.b)" style custom attributes.
while (token_ == '.' || token_ == kTokenIdentifier) NEXT();
EXPECT(')');
- while (Is('.')) { NEXT(); EXPECT(kTokenIdentifier); }
+ while (Is('.')) {
+ NEXT();
+ EXPECT(kTokenIdentifier);
+ }
} else {
EXPECT(kTokenIdentifier);
}
CheckedError Parser::ParseProtoCurliesOrIdent() {
if (Is('{')) {
NEXT();
- for (int nesting = 1; nesting; ) {
- if (token_ == '{') nesting++;
- else if (token_ == '}') nesting--;
+ for (int nesting = 1; nesting;) {
+ if (token_ == '{')
+ nesting++;
+ else if (token_ == '}')
+ nesting--;
NEXT();
}
} else {
// Parse a protobuf type, and map it to the corresponding FlatBuffer one.
CheckedError Parser::ParseTypeFromProtoType(Type *type) {
- struct type_lookup { const char *proto_type; BaseType fb_type, element; };
+ struct type_lookup {
+ 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 },
switch (token_) {
case '{': {
size_t fieldn_outer = 0;
- return ParseTableDelimiters(fieldn_outer, nullptr,
- [](const std::string &,
- size_t &fieldn, const StructDef *,
- void *state) -> CheckedError {
+ return ParseTableDelimiters(
+ fieldn_outer, nullptr,
+ [](const std::string &, size_t &fieldn, const StructDef *,
+ void *state) -> CheckedError {
auto *parser = static_cast<Parser *>(state);
ECHECK(parser->SkipAnyJsonValue());
fieldn++;
}
case '[': {
size_t count = 0;
- return ParseVectorDelimiters(count, [](size_t &,
- void *state) -> CheckedError {
- return static_cast<Parser *>(state)->SkipAnyJsonValue();
- },
- this);
+ return ParseVectorDelimiters(
+ count,
+ [](size_t &, void *state) -> CheckedError {
+ return static_cast<Parser *>(state)->SkipAnyJsonValue();
+ },
+ this);
}
case kTokenStringConstant:
case kTokenIntegerConstant:
- case kTokenFloatConstant:
- NEXT();
- break;
+ case kTokenFloatConstant: NEXT(); break;
default:
- if (IsIdent("true") || IsIdent("false") || IsIdent("null")) { NEXT(); }
- else return TokenError();
+ if (IsIdent("true") || IsIdent("false") || IsIdent("null")) {
+ NEXT();
+ } else
+ return TokenError();
}
return NoError();
}
this, builder);
auto start = builder->StartMap();
size_t fieldn_outer = 0;
- auto err = ParseTableDelimiters(fieldn_outer, nullptr,
- [](const std::string &name,
- size_t &fieldn, const StructDef *,
- void *state) -> CheckedError {
+ auto err = ParseTableDelimiters(
+ fieldn_outer, nullptr,
+ [](const std::string &name, size_t &fieldn, const StructDef *,
+ void *state) -> CheckedError {
auto *parser_and_builder =
static_cast<std::pair<Parser *, flexbuffers::Builder *> *>(
state);
builder->EndMap(start);
break;
}
- case '[':{
+ case '[': {
auto start = builder->StartVector();
size_t count = 0;
std::pair<Parser *, flexbuffers::Builder *> parser_and_builder_state(
this, builder);
- ECHECK(ParseVectorDelimiters(count, [](size_t &,
- void *state) -> CheckedError {
+ ECHECK(ParseVectorDelimiters(
+ count,
+ [](size_t &, void *state) -> CheckedError {
auto *parser_and_builder =
static_cast<std::pair<Parser *, flexbuffers::Builder *> *>(
state);
EXPECT(kTokenFloatConstant);
break;
default:
- if (IsIdent("true")) { builder->Bool(true); NEXT(); }
- else if (IsIdent("false")) { builder->Bool(false); NEXT(); }
- else if (IsIdent("null")) { builder->Null(); NEXT(); }
- else return TokenError();
+ if (IsIdent("true")) {
+ builder->Bool(true);
+ NEXT();
+ } else if (IsIdent("false")) {
+ builder->Bool(false);
+ NEXT();
+ } else if (IsIdent("null")) {
+ builder->Null();
+ NEXT();
+ } else
+ return TokenError();
}
return NoError();
}
return !ParseRoot(source, include_paths, source_filename).Check();
}
-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_ = cursor_ = source;
line_ = 1;
error_.clear();
ECHECK(SkipByteOrderMark());
NEXT();
- if (Is(kTokenEof))
- return Error("input file is empty");
+ if (Is(kTokenEof)) return Error("input file is empty");
return NoError();
}
CheckedError Parser::ParseRoot(const char *source, const char **include_paths,
- const char *source_filename) {
+ 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(); ) {
+ for (auto it = structs_.vec.begin(); it != structs_.vec.end();) {
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;
- for (size_t components = struct_def.defined_namespace->
- components.size() + 1;
+ for (size_t components =
+ struct_def.defined_namespace->components.size() + 1;
components && !enum_def; components--) {
- auto qualified_name = struct_def.defined_namespace->
- GetFullyQualifiedName(struct_def.name,
- components - 1);
+ auto qualified_name =
+ struct_def.defined_namespace->GetFullyQualifiedName(
+ struct_def.name, components - 1);
enum_def = LookupEnum(qualified_name);
}
if (enum_def) {
// This is pretty slow, but a simple solution for now.
auto initial_count = struct_def.refcount;
for (auto struct_it = structs_.vec.begin();
- struct_it != structs_.vec.end();
- ++struct_it) {
+ struct_it != structs_.vec.end(); ++struct_it) {
auto &sd = **struct_it;
for (auto field_it = sd.fields.vec.begin();
- field_it != sd.fields.vec.end();
- ++field_it) {
+ field_it != sd.fields.vec.end(); ++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 = field.value.type.base_type == BASE_TYPE_VECTOR
- ? field.value.type.element
- : field.value.type.base_type;
+ ? field.value.type.element
+ : field.value.type.base_type;
assert(bt == BASE_TYPE_STRUCT);
bt = enum_def->underlying_type.base_type;
struct_def.refcount--;
if (struct_def.refcount)
return Error("internal: " + NumToString(struct_def.refcount) + "/" +
NumToString(initial_count) +
- " use(s) of pre-declaration enum not accounted for: "
- + enum_def->name);
+ " use(s) of pre-declaration enum not accounted for: " +
+ enum_def->name);
structs_.dict.erase(structs_.dict.find(struct_def.name));
it = structs_.vec.erase(it);
delete &struct_def;
auto &enum_def = **it;
if (enum_def.is_union) {
for (auto val_it = enum_def.vals.vec.begin();
- val_it != enum_def.vals.vec.end();
- ++val_it) {
+ val_it != enum_def.vals.vec.end(); ++val_it) {
auto &val = **val_it;
- if (!SupportsVectorOfUnions() &&
- val.union_type.struct_def && val.union_type.struct_def->fixed)
+ if (!SupportsVectorOfUnions() && val.union_type.struct_def &&
+ val.union_type.struct_def->fixed)
return Error(
- "only tables can be union elements in the generated language: "
- + val.name);
+ "only tables can be union elements in the generated language: " +
+ val.name);
}
}
}
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) {
if (source_filename &&
included_files_.find(source_filename) == included_files_.end()) {
included_files_[source_filename] = include_filename ? include_filename : "";
// Includes must come before type declarations:
for (;;) {
// Parse pre-include proto statements if any:
- if (opts.proto_mode &&
- (attribute_ == "option" || attribute_ == "syntax" ||
- attribute_ == "package")) {
- ECHECK(ParseProtoDecl());
+ if (opts.proto_mode && (attribute_ == "option" || attribute_ == "syntax" ||
+ attribute_ == "package")) {
+ ECHECK(ParseProtoDecl());
} else if (IsIdent("native_include")) {
NEXT();
vector_emplace_back(&native_included_files_, attribute_);
std::string filepath;
for (auto paths = include_paths; paths && *paths; paths++) {
filepath = flatbuffers::ConCatPathFileName(*paths, name);
- if(FileExists(filepath.c_str())) break;
+ if (FileExists(filepath.c_str())) break;
}
if (filepath.empty())
return Error("unable to locate include file: " + name);
// entered into included_files_.
// This is recursive, but only go as deep as the number of include
// statements.
- return DoParse(source, include_paths, source_filename, include_filename);
+ return DoParse(source, include_paths, source_filename,
+ include_filename);
}
EXPECT(';');
} else {
}
uoffset_t toff;
ECHECK(ParseTable(*root_struct_def_, nullptr, &toff));
- builder_.Finish(Offset<Table>(toff),
- file_identifier_.length() ? file_identifier_.c_str() : nullptr);
+ builder_.Finish(Offset<Table>(toff), file_identifier_.length()
+ ? file_identifier_.c_str()
+ : nullptr);
} else if (IsIdent("enum")) {
ECHECK(ParseEnum(false, nullptr));
} else if (IsIdent("union")) {
ECHECK(ParseNamespacing(&root_type, nullptr));
if (!SetRootType(root_type.c_str()))
return Error("unknown root type: " + root_type);
- if (root_struct_def_->fixed)
- return Error("root type must be a table");
+ if (root_struct_def_->fixed) return Error("root type must be a table");
EXPECT(';');
} else if (IsIdent("file_identifier")) {
NEXT();
file_identifier_ = attribute_;
EXPECT(kTokenStringConstant);
- if (file_identifier_.length() !=
- FlatBufferBuilder::kFileIdentifierLength)
+ if (file_identifier_.length() != FlatBufferBuilder::kFileIdentifierLength)
return Error("file_identifier must be exactly " +
- NumToString(FlatBufferBuilder::kFileIdentifierLength) +
- " characters");
+ NumToString(FlatBufferBuilder::kFileIdentifierLength) +
+ " characters");
EXPECT(';');
} else if (IsIdent("file_extension")) {
NEXT();
file_extension_ = attribute_;
EXPECT(kTokenStringConstant);
EXPECT(';');
- } else if(IsIdent("include")) {
+ } else if (IsIdent("include")) {
return Error("includes must come before declarations");
- } else if(IsIdent("attribute")) {
+ } else if (IsIdent("attribute")) {
NEXT();
auto name = attribute_;
EXPECT(kTokenStringConstant);
// Schema serialization functionality:
-template<typename T> bool compareName(const T* a, const T* b) {
- return a->defined_namespace->GetFullyQualifiedName(a->name)
- < b->defined_namespace->GetFullyQualifiedName(b->name);
+template<typename T> bool compareName(const T *a, const T *b) {
+ return a->defined_namespace->GetFullyQualifiedName(a->name) <
+ b->defined_namespace->GetFullyQualifiedName(b->name);
}
template<typename T> void AssignIndices(const std::vector<T *> &defvec) {
(*it)->serialized_location = offset.o;
}
auto schema_offset = reflection::CreateSchema(
- builder_,
- builder_.CreateVectorOfSortedTables(&object_offsets),
- builder_.CreateVectorOfSortedTables(&enum_offsets),
- builder_.CreateString(file_identifier_),
- builder_.CreateString(file_extension_),
- root_struct_def_
- ? root_struct_def_->serialized_location
- : 0);
+ builder_, builder_.CreateVectorOfSortedTables(&object_offsets),
+ builder_.CreateVectorOfSortedTables(&enum_offsets),
+ builder_.CreateString(file_identifier_),
+ builder_.CreateString(file_extension_),
+ root_struct_def_ ? root_struct_def_->serialized_location : 0);
builder_.Finish(schema_offset, reflection::SchemaIdentifier());
}
const Parser &parser) const {
std::vector<Offset<reflection::Field>> field_offsets;
for (auto it = fields.vec.begin(); it != fields.vec.end(); ++it) {
- field_offsets.push_back(
- (*it)->Serialize(builder,
- static_cast<uint16_t>(it - fields.vec.begin()), parser));
+ field_offsets.push_back((*it)->Serialize(
+ builder, static_cast<uint16_t>(it - fields.vec.begin()), parser));
}
auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
- return reflection::CreateObject(*builder,
- builder->CreateString(qualified_name),
- builder->CreateVectorOfSortedTables(
- &field_offsets),
- fixed,
- static_cast<int>(minalign),
- static_cast<int>(bytesize),
- SerializeAttributes(builder, parser),
- parser.opts.binary_schema_comments
- ? builder->CreateVectorOfStrings(
- doc_comment)
- : 0);
+ return reflection::CreateObject(
+ *builder, builder->CreateString(qualified_name),
+ builder->CreateVectorOfSortedTables(&field_offsets), fixed,
+ static_cast<int>(minalign), static_cast<int>(bytesize),
+ SerializeAttributes(builder, parser),
+ parser.opts.binary_schema_comments
+ ? builder->CreateVectorOfStrings(doc_comment)
+ : 0);
}
Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder,
uint16_t id,
const Parser &parser) const {
- return reflection::CreateField(*builder,
- builder->CreateString(name),
- value.type.Serialize(builder),
- id,
- value.offset,
- IsInteger(value.type.base_type)
- ? StringToInt(value.constant.c_str())
- : 0,
- IsFloat(value.type.base_type)
- ? strtod(value.constant.c_str(), nullptr)
- : 0.0,
- deprecated,
- required,
- key,
- SerializeAttributes(builder, parser),
- parser.opts.binary_schema_comments
- ? builder->CreateVectorOfStrings(doc_comment)
- : 0);
+ return reflection::CreateField(
+ *builder, builder->CreateString(name), value.type.Serialize(builder), id,
+ value.offset,
+ IsInteger(value.type.base_type) ? StringToInt(value.constant.c_str()) : 0,
+ IsFloat(value.type.base_type) ? strtod(value.constant.c_str(), nullptr)
+ : 0.0,
+ deprecated, required, key, SerializeAttributes(builder, parser),
+ parser.opts.binary_schema_comments
+ ? builder->CreateVectorOfStrings(doc_comment)
+ : 0);
// TODO: value.constant is almost always "0", we could save quite a bit of
// space by sharing it. Same for common values of value.type.
}
enumval_offsets.push_back((*it)->Serialize(builder));
}
auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
- return reflection::CreateEnum(*builder,
- builder->CreateString(qualified_name),
- builder->CreateVector(enumval_offsets),
- is_union,
- underlying_type.Serialize(builder),
- SerializeAttributes(builder, parser),
- parser.opts.binary_schema_comments
- ? builder->CreateVectorOfStrings(doc_comment)
- : 0);
-}
-
-Offset<reflection::EnumVal> EnumVal::Serialize(FlatBufferBuilder *builder) const
- {
- return reflection::CreateEnumVal(*builder,
- builder->CreateString(name),
- value,
- union_type.struct_def
- ? union_type.struct_def->
- serialized_location
- : 0,
- union_type.Serialize(builder));
+ return reflection::CreateEnum(
+ *builder, builder->CreateString(qualified_name),
+ builder->CreateVector(enumval_offsets), is_union,
+ underlying_type.Serialize(builder), SerializeAttributes(builder, parser),
+ parser.opts.binary_schema_comments
+ ? builder->CreateVectorOfStrings(doc_comment)
+ : 0);
+}
+
+Offset<reflection::EnumVal> EnumVal::Serialize(
+ FlatBufferBuilder *builder) const {
+ return reflection::CreateEnumVal(
+ *builder, builder->CreateString(name), value,
+ union_type.struct_def ? union_type.struct_def->serialized_location : 0,
+ union_type.Serialize(builder));
}
Offset<reflection::Type> Type::Serialize(FlatBufferBuilder *builder) const {
- return reflection::CreateType(*builder,
- static_cast<reflection::BaseType>(base_type),
- static_cast<reflection::BaseType>(element),
- struct_def ? struct_def->index :
- (enum_def ? enum_def->index : -1));
+ return reflection::CreateType(
+ *builder, static_cast<reflection::BaseType>(base_type),
+ static_cast<reflection::BaseType>(element),
+ struct_def ? struct_def->index : (enum_def ? enum_def->index : -1));
}
-flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<
- reflection::KeyValue>>>
- Definition::SerializeAttributes(FlatBufferBuilder *builder,
- const Parser &parser) const {
+flatbuffers::Offset<
+ flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
+Definition::SerializeAttributes(FlatBufferBuilder *builder,
+ const Parser &parser) const {
std::vector<flatbuffers::Offset<reflection::KeyValue>> attrs;
for (auto kv = attributes.dict.begin(); kv != attributes.dict.end(); ++kv) {
auto it = parser.known_attributes_.find(kv->first);
assert(it != parser.known_attributes_.end());
if (!it->second) { // Custom attribute.
- attrs.push_back(
- reflection::CreateKeyValue(*builder, builder->CreateString(kv->first),
- builder->CreateString(
- kv->second->constant)));
+ attrs.push_back(reflection::CreateKeyValue(
+ *builder, builder->CreateString(kv->first),
+ builder->CreateString(kv->second->constant)));
}
}
if (attrs.size()) {
auto struct_def_base = base.LookupStruct(qualified_name);
if (!struct_def_base) continue;
for (auto fit = struct_def.fields.vec.begin();
- fit != struct_def.fields.vec.end(); ++fit) {
+ fit != struct_def.fields.vec.end(); ++fit) {
auto &field = **fit;
auto field_base = struct_def_base->fields.Lookup(field.name);
if (field_base) {
// But we should check if there is a field that has the same offset
// but is incompatible (in the case of field renaming).
for (auto fbit = struct_def_base->fields.vec.begin();
- fbit != struct_def_base->fields.vec.end(); ++fbit) {
+ fbit != struct_def_base->fields.vec.end(); ++fbit) {
field_base = *fbit;
if (field.value.offset == field_base->value.offset) {
if (!EqualByName(field.value.type, field_base->value.type))
enum_def.defined_namespace->GetFullyQualifiedName(enum_def.name);
auto enum_def_base = base.enums_.Lookup(qualified_name);
if (!enum_def_base) continue;
- for (auto evit = enum_def.vals.vec.begin();
- evit != enum_def.vals.vec.end(); ++evit) {
+ for (auto evit = enum_def.vals.vec.begin(); evit != enum_def.vals.vec.end();
+ ++evit) {
auto &enum_val = **evit;
auto enum_val_base = enum_def_base->vals.Lookup(enum_val.name);
if (enum_val_base) {
namespace flatbuffers {
int64_t GetAnyValueI(reflection::BaseType type, const uint8_t *data) {
-# define FLATBUFFERS_GET(T) static_cast<int64_t>(ReadScalar<T>(data))
+ // clang-format off
+ #define FLATBUFFERS_GET(T) static_cast<int64_t>(ReadScalar<T>(data))
switch (type) {
case reflection::UType:
case reflection::Bool:
}
default: return 0; // Tables & vectors do not make sense.
}
-# undef FLATBUFFERS_GET
+ #undef FLATBUFFERS_GET
+ // clang-format on
}
double GetAnyValueF(reflection::BaseType type, const uint8_t *data) {
switch (type) {
- case reflection::Float: return static_cast<double>(ReadScalar<float>(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);
+ auto s =
+ reinterpret_cast<const String *>(ReadScalar<uoffset_t>(data) + data);
return s ? strtod(s->c_str(), nullptr) : 0.0;
}
default: return static_cast<double>(GetAnyValueI(type, data));
case reflection::Float:
case reflection::Double: return NumToString(GetAnyValueF(type, data));
case reflection::String: {
- auto s = reinterpret_cast<const String *>(ReadScalar<uoffset_t>(data) +
- data);
+ auto s =
+ reinterpret_cast<const String *>(ReadScalar<uoffset_t>(data) + data);
return s ? s->c_str() : "";
}
case reflection::Obj:
s += "(struct)"; // TODO: implement this as well.
} else {
auto table_field = reinterpret_cast<const Table *>(
- ReadScalar<uoffset_t>(data) + data);
+ ReadScalar<uoffset_t>(data) + data);
s += " { ";
auto fielddefs = objectdef.fields();
for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
return "(table)";
}
case reflection::Vector:
- return "[(elements)]"; // TODO: implement this as well.
- case reflection::Union:
- return "(union)"; // TODO: implement this as well.
+ return "[(elements)]"; // TODO: implement this as well.
+ case reflection::Union: return "(union)"; // TODO: implement this as well.
default: return NumToString(GetAnyValueI(type, data));
}
}
void SetAnyValueI(reflection::BaseType type, uint8_t *data, int64_t val) {
-# define FLATBUFFERS_SET(T) WriteScalar(data, static_cast<T>(val))
+ // clang-format off
+ #define FLATBUFFERS_SET(T) WriteScalar(data, static_cast<T>(val))
switch (type) {
case reflection::UType:
case reflection::Bool:
// TODO: support strings
default: break;
}
-# undef FLATBUFFERS_SET
+ #undef FLATBUFFERS_SET
+ // clang-format on
}
void SetAnyValueF(reflection::BaseType type, uint8_t *data, double val) {
switch (type) {
- case reflection::Float: WriteScalar(data, static_cast<float>(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;
ResizeContext(const reflection::Schema &schema, uoffset_t start, int delta,
std::vector<uint8_t> *flatbuf,
const reflection::Object *root_table = nullptr)
- : schema_(schema), startptr_(vector_data(*flatbuf) + start),
- delta_(delta), buf_(*flatbuf),
- dag_check_(flatbuf->size() / sizeof(uoffset_t), false) {
+ : schema_(schema),
+ startptr_(vector_data(*flatbuf) + start),
+ delta_(delta),
+ buf_(*flatbuf),
+ dag_check_(flatbuf->size() / sizeof(uoffset_t), false) {
auto mask = static_cast<int>(sizeof(largest_scalar_t) - 1);
delta_ = (delta_ + mask) & ~mask;
if (!delta_) return; // We can't shrink by less than largest_scalar_t.
Straddle<uoffset_t, 1>(vector_data(buf_), root, vector_data(buf_));
ResizeTable(root_table ? *root_table : *schema.root_table(), root);
// We can now add or remove bytes at start.
- if (delta_ > 0) buf_.insert(buf_.begin() + start, delta_, 0);
- else buf_.erase(buf_.begin() + start, buf_.begin() + start - delta_);
+ if (delta_ > 0)
+ buf_.insert(buf_.begin() + start, delta_, 0);
+ else
+ buf_.erase(buf_.begin() + start, buf_.begin() + start - delta_);
}
// 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;
}
void ResizeTable(const reflection::Object &objectdef, Table *table) {
- if (DagCheck(table))
- return; // Table already visited.
+ 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 offset = table->GetOptionalFieldOffset(fielddef.offset());
if (!offset) continue;
// Ignore structs.
- auto subobjectdef = base_type == reflection::Obj ?
- schema_.objects()->Get(fielddef.type()->index()) : nullptr;
+ auto subobjectdef =
+ base_type == reflection::Obj
+ ? schema_.objects()->Get(fielddef.type()->index())
+ : nullptr;
if (subobjectdef && subobjectdef->is_struct()) continue;
// Get this fields' offset, and read it if safe.
auto offsetloc = tableloc + offset;
- if (DagCheck(offsetloc))
- continue; // This offset already visited.
+ if (DagCheck(offsetloc)) continue; // This offset already visited.
auto ref = offsetloc + ReadScalar<uoffset_t>(offsetloc);
Straddle<uoffset_t, 1>(offsetloc, ref, offsetloc);
// Recurse.
if (elem_type != reflection::Obj && elem_type != reflection::String)
break;
auto vec = reinterpret_cast<Vector<uoffset_t> *>(ref);
- auto elemobjectdef = elem_type == reflection::Obj
- ? schema_.objects()->Get(fielddef.type()->index())
- : nullptr;
+ auto elemobjectdef =
+ elem_type == reflection::Obj
+ ? schema_.objects()->Get(fielddef.type()->index())
+ : nullptr;
if (elemobjectdef && elemobjectdef->is_struct()) break;
for (uoffset_t i = 0; i < vec->size(); i++) {
auto loc = vec->Data() + i * sizeof(uoffset_t);
- if (DagCheck(loc))
- continue; // This offset already visited.
+ if (DagCheck(loc)) continue; // This offset already visited.
auto dest = loc + vec->Get(i);
- Straddle<uoffset_t, 1>(loc, dest ,loc);
+ Straddle<uoffset_t, 1>(loc, dest, loc);
if (elemobjectdef)
ResizeTable(*elemobjectdef, reinterpret_cast<Table *>(dest));
}
reinterpret_cast<Table *>(ref));
break;
}
- case reflection::String:
- break;
- default:
- assert(false);
+ case reflection::String: break;
+ default: assert(false);
}
}
// Check if the vtable offset points beyond the insertion point.
};
void SetString(const reflection::Schema &schema, const std::string &val,
- const String *str, std::vector<uint8_t> *flatbuf,
- const reflection::Object *root_table) {
+ const String *str, std::vector<uint8_t> *flatbuf,
+ const reflection::Object *root_table) {
auto delta = static_cast<int>(val.size()) - static_cast<int>(str->Length());
auto str_start = static_cast<uoffset_t>(
reinterpret_cast<const uint8_t *>(str) - vector_data(*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) -
- vector_data(*flatbuf);
+ auto vec_start =
+ reinterpret_cast<const uint8_t *>(vec) - vector_data(*flatbuf);
auto start = static_cast<uoffset_t>(vec_start + sizeof(uoffset_t) +
elem_size * num_elems);
if (delta_bytes) {
Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
const reflection::Schema &schema,
const reflection::Object &objectdef,
- const Table &table,
- bool use_string_pooling) {
+ 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;
switch (fielddef.type()->base_type()) {
case reflection::String: {
offset = use_string_pooling
- ? fbb.CreateSharedString(GetFieldS(table, fielddef)).o
- : fbb.CreateString(GetFieldS(table, fielddef)).o;
+ ? fbb.CreateSharedString(GetFieldS(table, fielddef)).o
+ : fbb.CreateString(GetFieldS(table, fielddef)).o;
break;
}
case reflection::Obj: {
auto &subobjectdef = *schema.objects()->Get(fielddef.type()->index());
if (!subobjectdef.is_struct()) {
- offset = CopyTable(fbb, schema, subobjectdef,
- *GetFieldT(table, fielddef)).o;
+ offset =
+ CopyTable(fbb, schema, subobjectdef, *GetFieldT(table, fielddef))
+ .o;
}
break;
}
case reflection::Union: {
auto &subobjectdef = GetUnionType(schema, objectdef, fielddef, table);
- offset = CopyTable(fbb, schema, subobjectdef,
- *GetFieldT(table, fielddef)).o;
+ offset =
+ CopyTable(fbb, schema, subobjectdef, *GetFieldT(table, fielddef)).o;
break;
}
case reflection::Vector: {
- auto vec = table.GetPointer<const Vector<Offset<Table>> *>(
- fielddef.offset());
+ auto vec =
+ table.GetPointer<const Vector<Offset<Table>> *>(fielddef.offset());
auto element_base_type = fielddef.type()->element();
- auto elemobjectdef = element_base_type == reflection::Obj
- ? schema.objects()->Get(fielddef.type()->index())
- : nullptr;
+ auto elemobjectdef =
+ element_base_type == reflection::Obj
+ ? schema.objects()->Get(fielddef.type()->index())
+ : 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);
for (uoffset_t i = 0; i < vec_s->size(); i++) {
elements[i] = use_string_pooling
- ? fbb.CreateSharedString(vec_s->Get(i)).o
- : fbb.CreateString(vec_s->Get(i)).o;
+ ? fbb.CreateSharedString(vec_s->Get(i)).o
+ : fbb.CreateString(vec_s->Get(i)).o;
}
offset = fbb.CreateVector(elements).o;
break;
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));
+ CopyTable(fbb, schema, *elemobjectdef, *vec->Get(i));
}
offset = fbb.CreateVector(elements).o;
break;
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();
+ 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;
case reflection::Vector:
fbb.AddOffset(fielddef.offset(), Offset<void>(offsets[offset_idx++]));
break;
- default: { // Scalars.
+ default: { // Scalars.
auto size = GetTypeSize(base_type);
CopyInline(fbb, fielddef, table, size, size);
break;
bool VerifyStruct(flatbuffers::Verifier &v,
const flatbuffers::Table &parent_table,
- voffset_t field_offset,
- const reflection::Object &obj,
+ 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.Verify(reinterpret_cast<const uint8_t*>(&parent_table)
- + offset, obj.bytesize());
+ return !offset ||
+ v.Verify(reinterpret_cast<const uint8_t *>(&parent_table) + offset,
+ obj.bytesize());
}
bool VerifyVectorOfStructs(flatbuffers::Verifier &v,
const flatbuffers::Table &parent_table,
voffset_t field_offset,
- const reflection::Object &obj,
- bool required) {
- auto p = parent_table.GetPointer<const uint8_t*>(field_offset);
- const uint8_t* end;
- if (required && !p) {
- return false;
- }
+ const reflection::Object &obj, bool required) {
+ auto p = parent_table.GetPointer<const uint8_t *>(field_offset);
+ const uint8_t *end;
+ if (required && !p) { return false; }
return !p || v.VerifyVector(p, obj.bytesize(), &end);
}
// forward declare to resolve cyclic deps between VerifyObject and VerifyVector
-bool VerifyObject(flatbuffers::Verifier &v,
- const reflection::Schema &schema,
+bool VerifyObject(flatbuffers::Verifier &v, const reflection::Schema &schema,
const reflection::Object &obj,
- const flatbuffers::Table *table,
- bool isRequired);
+ const flatbuffers::Table *table, bool isRequired);
-bool VerifyVector(flatbuffers::Verifier &v,
- const reflection::Schema &schema,
+bool VerifyVector(flatbuffers::Verifier &v, const reflection::Schema &schema,
const flatbuffers::Table &table,
const reflection::Field &vec_field) {
assert(vec_field.type()->base_type() == reflection::Vector);
- if (!table.VerifyField<uoffset_t>(v, vec_field.offset()))
- return false;
+ if (!table.VerifyField<uoffset_t>(v, vec_field.offset())) return false;
switch (vec_field.type()->element()) {
- case reflection::None:
- assert(false);
- break;
+ case reflection::None: assert(false); break;
case reflection::UType:
return v.Verify(flatbuffers::GetFieldV<uint8_t>(table, vec_field));
case reflection::Bool:
return v.Verify(flatbuffers::GetFieldV<double>(table, vec_field));
case reflection::String: {
auto vecString =
- flatbuffers::GetFieldV<flatbuffers::
- Offset<flatbuffers::String>>(table, vec_field);
+ flatbuffers::GetFieldV<flatbuffers::Offset<flatbuffers::String>>(
+ table, vec_field);
if (v.Verify(vecString) && v.VerifyVectorOfStrings(vecString)) {
return true;
} else {
return false;
}
}
- case reflection::Vector:
- assert(false);
- break;
+ case reflection::Vector: assert(false); break;
case reflection::Obj: {
auto obj = schema.objects()->Get(vec_field.type()->index());
if (obj->is_struct()) {
}
} else {
auto vec =
- flatbuffers::GetFieldV<flatbuffers::
- Offset<flatbuffers::Table>>(table, vec_field);
- if (!v.Verify(vec))
- return false;
+ flatbuffers::GetFieldV<flatbuffers::Offset<flatbuffers::Table>>(
+ table, vec_field);
+ if (!v.Verify(vec)) return false;
if (vec) {
for (uoffset_t j = 0; j < vec->size(); j++) {
if (!VerifyObject(v, schema, *obj, vec->Get(j), true)) {
}
return true;
}
- case reflection::Union:
- assert(false);
- break;
- default:
- assert(false);
- break;
+ case reflection::Union: assert(false); break;
+ default: assert(false); break;
}
return false;
}
-bool VerifyObject(flatbuffers::Verifier &v,
- const reflection::Schema &schema,
+bool VerifyObject(flatbuffers::Verifier &v, const reflection::Schema &schema,
const reflection::Object &obj,
- const flatbuffers::Table *table,
- bool required) {
+ const flatbuffers::Table *table, bool required) {
if (!table) {
if (!required)
return true;
return false;
}
- if (!table->VerifyTableStart(v))
- return false;
+ 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:
- assert(false);
- break;
+ case reflection::None: assert(false); break;
case reflection::UType:
- if (!table->VerifyField<uint8_t>(v, field_def->offset()))
- return false;
+ if (!table->VerifyField<uint8_t>(v, field_def->offset())) return false;
break;
case reflection::Bool:
case reflection::Byte:
case reflection::UByte:
- if (!table->VerifyField<int8_t>(v, field_def->offset()))
- return false;
+ if (!table->VerifyField<int8_t>(v, field_def->offset())) return false;
break;
case reflection::Short:
case reflection::UShort:
- if (!table->VerifyField<int16_t>(v, field_def->offset()))
- return false;
+ if (!table->VerifyField<int16_t>(v, field_def->offset())) return false;
break;
case reflection::Int:
case reflection::UInt:
- if (!table->VerifyField<int32_t>(v, field_def->offset()))
- return false;
+ if (!table->VerifyField<int32_t>(v, field_def->offset())) return false;
break;
case reflection::Long:
case reflection::ULong:
- if (!table->VerifyField<int64_t>(v, field_def->offset()))
- return false;
+ if (!table->VerifyField<int64_t>(v, field_def->offset())) return false;
break;
case reflection::Float:
- if (!table->VerifyField<float>(v, field_def->offset()))
- return false;
+ if (!table->VerifyField<float>(v, field_def->offset())) return false;
break;
case reflection::Double:
- if (!table->VerifyField<double>(v, field_def->offset()))
- return false;
+ if (!table->VerifyField<double>(v, field_def->offset())) return false;
break;
case reflection::String:
if (!table->VerifyField<uoffset_t>(v, field_def->offset()) ||
}
break;
case reflection::Vector:
- if (!VerifyVector(v, schema, *table, *field_def))
- return false;
+ if (!VerifyVector(v, schema, *table, *field_def)) return false;
break;
case reflection::Obj: {
auto child_obj = schema.objects()->Get(field_def->type()->index());
}
break;
}
- default:
- assert(false);
- break;
+ default: assert(false); break;
}
}
- if (!v.EndTable())
- return false;
-
+ if (!v.EndTable()) return false;
+
return true;
}
-bool Verify(const reflection::Schema &schema,
- const reflection::Object &root,
- const uint8_t *buf,
- size_t length) {
+bool Verify(const reflection::Schema &schema, const reflection::Object &root,
+ const uint8_t *buf, size_t length) {
Verifier v(buf, length);
return VerifyObject(v, schema, root, flatbuffers::GetAnyRoot(buf), true);
}
}
bool DirExists(const char *name) {
+ // clang-format off
#ifdef _WIN32
#define flatbuffers_stat _stat
#define FLATBUFFERS_S_IFDIR _S_IFDIR
#define flatbuffers_stat stat
#define FLATBUFFERS_S_IFDIR S_IFDIR
#endif
+ // clang-format on
struct flatbuffers_stat file_info;
if (flatbuffers_stat(name, &file_info) != 0) return false;
return (file_info.st_mode & FLATBUFFERS_S_IFDIR) != 0;
FileExistsFunction SetFileExistsFunction(
FileExistsFunction file_exists_function) {
FileExistsFunction previous_function = g_file_exists_function;
- g_file_exists_function = file_exists_function ?
- file_exists_function : FileExistsRaw;
+ g_file_exists_function =
+ file_exists_function ? file_exists_function : FileExistsRaw;
return previous_function;
}
}
MonsterStorage::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel)
- : channel_(channel) , rpcmethod_Store_(MonsterStorage_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel)
- , rpcmethod_Retrieve_(MonsterStorage_method_names[1], ::grpc::internal::RpcMethod::SERVER_STREAMING, channel)
+ : channel_(channel) , rpcmethod_Store_(MonsterStorage_method_names[0], ::grpc::RpcMethod::NORMAL_RPC, channel)
+ , rpcmethod_Retrieve_(MonsterStorage_method_names[1], ::grpc::RpcMethod::SERVER_STREAMING, channel)
{}
::grpc::Status MonsterStorage::Stub::Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, flatbuffers::grpc::Message<Stat>* response) {
- return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Store_, context, request, response);
+ return ::grpc::BlockingUnaryCall(channel_.get(), rpcmethod_Store_, context, request, response);
}
::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>* MonsterStorage::Stub::AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
- return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message<Stat>>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, true);
-}
-
-::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>* MonsterStorage::Stub::PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
- return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message<Stat>>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, false);
+ return ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>::Create(channel_.get(), cq, rpcmethod_Store_, context, request);
}
::grpc::ClientReader< flatbuffers::grpc::Message<Monster>>* MonsterStorage::Stub::RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request) {
- return ::grpc::internal::ClientReaderFactory< flatbuffers::grpc::Message<Monster>>::Create(channel_.get(), rpcmethod_Retrieve_, context, request);
+ return new ::grpc::ClientReader< flatbuffers::grpc::Message<Monster>>(channel_.get(), rpcmethod_Retrieve_, context, request);
}
::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>* MonsterStorage::Stub::AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq, void* tag) {
- return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message<Monster>>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, true, tag);
-}
-
-::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>* MonsterStorage::Stub::PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq) {
- return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message<Monster>>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, false, nullptr);
+ return ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, tag);
}
MonsterStorage::Service::Service() {
- AddMethod(new ::grpc::internal::RpcServiceMethod(
+ AddMethod(new ::grpc::RpcServiceMethod(
MonsterStorage_method_names[0],
- ::grpc::internal::RpcMethod::NORMAL_RPC,
- new ::grpc::internal::RpcMethodHandler< MonsterStorage::Service, flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>(
+ ::grpc::RpcMethod::NORMAL_RPC,
+ new ::grpc::RpcMethodHandler< MonsterStorage::Service, flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>(
std::mem_fn(&MonsterStorage::Service::Store), this)));
- AddMethod(new ::grpc::internal::RpcServiceMethod(
+ AddMethod(new ::grpc::RpcServiceMethod(
MonsterStorage_method_names[1],
- ::grpc::internal::RpcMethod::SERVER_STREAMING,
- new ::grpc::internal::ServerStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>(
+ ::grpc::RpcMethod::SERVER_STREAMING,
+ new ::grpc::ServerStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>(
std::mem_fn(&MonsterStorage::Service::Retrieve), this)));
}
#ifndef GRPC_monster_5ftest__INCLUDED
#define GRPC_monster_5ftest__INCLUDED
-#include "monster_test_generated.h"
#include "flatbuffers/grpc.h"
+#include "monster_test_generated.h"
#include <grpc++/impl/codegen/async_stream.h>
#include <grpc++/impl/codegen/async_unary_call.h>
namespace grpc {
class CompletionQueue;
class Channel;
+class RpcService;
class ServerCompletionQueue;
class ServerContext;
} // namespace grpc
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>>(AsyncStoreRaw(context, request, cq));
}
- std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
- return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>>(PrepareAsyncStoreRaw(context, request, cq));
- }
std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message<Monster>>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request) {
return std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message<Monster>>>(RetrieveRaw(context, request));
}
std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq, void* tag) {
return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>>(AsyncRetrieveRaw(context, request, cq, tag));
}
- std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq) {
- return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>>(PrepareAsyncRetrieveRaw(context, request, cq));
- }
private:
virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) = 0;
- virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientReaderInterface< flatbuffers::grpc::Message<Monster>>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request) = 0;
virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq, void* tag) = 0;
- virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq) = 0;
};
class Stub final : public StubInterface {
public:
std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>>(AsyncStoreRaw(context, request, cq));
}
- std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
- return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>>(PrepareAsyncStoreRaw(context, request, cq));
- }
std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message<Monster>>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request) {
return std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message<Monster>>>(RetrieveRaw(context, request));
}
std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq, void* tag) {
return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>>(AsyncRetrieveRaw(context, request, cq, tag));
}
- std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq) {
- return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>>(PrepareAsyncRetrieveRaw(context, request, cq));
- }
private:
std::shared_ptr< ::grpc::ChannelInterface> channel_;
::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) override;
- ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientReader< flatbuffers::grpc::Message<Monster>>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request) override;
::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq, void* tag) override;
- ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq) override;
- const ::grpc::internal::RpcMethod rpcmethod_Store_;
- const ::grpc::internal::RpcMethod rpcmethod_Retrieve_;
+ const ::grpc::RpcMethod rpcmethod_Store_;
+ const ::grpc::RpcMethod rpcmethod_Retrieve_;
};
static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions());
public:
WithStreamedUnaryMethod_Store() {
::grpc::Service::MarkMethodStreamed(0,
- new ::grpc::internal::StreamedUnaryHandler< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>(std::bind(&WithStreamedUnaryMethod_Store<BaseClass>::StreamedStore, this, std::placeholders::_1, std::placeholders::_2)));
+ new ::grpc::StreamedUnaryHandler< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>(std::bind(&WithStreamedUnaryMethod_Store<BaseClass>::StreamedStore, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_Store() override {
BaseClassMustBeDerivedFromService(this);
public:
WithSplitStreamingMethod_Retrieve() {
::grpc::Service::MarkMethodStreamed(1,
- new ::grpc::internal::SplitServerStreamingHandler< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>(std::bind(&WithSplitStreamingMethod_Retrieve<BaseClass>::StreamedRetrieve, this, std::placeholders::_1, std::placeholders::_2)));
+ new ::grpc::SplitServerStreamingHandler< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>(std::bind(&WithSplitStreamingMethod_Retrieve<BaseClass>::StreamedRetrieve, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithSplitStreamingMethod_Retrieve() override {
BaseClassMustBeDerivedFromService(this);
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {number}
*/
a():number {
- return this.bb!.readInt16(this.bb_pos);
+ return this.bb.readInt16(this.bb_pos);
};
/**
* @returns {boolean}
*/
mutate_a(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 0);
+ var offset = this.bb.__offset(this.bb_pos, 0);
if (offset === 0) {
return false;
}
- this.bb!.writeInt16(this.bb_pos + offset, value);
+ this.bb.writeInt16(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
b():number {
- return this.bb!.readInt8(this.bb_pos + 2);
+ return this.bb.readInt8(this.bb_pos + 2);
};
/**
* @returns {boolean}
*/
mutate_b(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 2);
+ var offset = this.bb.__offset(this.bb_pos, 2);
if (offset === 0) {
return false;
}
- this.bb!.writeInt8(this.bb_pos + offset, value);
+ this.bb.writeInt8(this.bb_pos + offset, value);
return true;
};
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {MyGame.Example.Color}
*/
color():MyGame.Example.Color {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? /** @type {MyGame.Example.Color} */ (this.bb!.readInt8(this.bb_pos + offset)) : MyGame.Example.Color.Green;
+ var offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? /** @type {MyGame.Example.Color} */ (this.bb.readInt8(this.bb_pos + offset)) : MyGame.Example.Color.Green;
};
/**
* @returns {boolean}
*/
mutate_color(value:MyGame.Example.Color):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
+ var offset = this.bb.__offset(this.bb_pos, 4);
if (offset === 0) {
return false;
}
- this.bb!.writeInt8(this.bb_pos + offset, value);
+ this.bb.writeInt8(this.bb_pos + offset, value);
return true;
};
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {number}
*/
x():number {
- return this.bb!.readFloat32(this.bb_pos);
+ return this.bb.readFloat32(this.bb_pos);
};
/**
* @returns {boolean}
*/
mutate_x(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 0);
+ var offset = this.bb.__offset(this.bb_pos, 0);
if (offset === 0) {
return false;
}
- this.bb!.writeFloat32(this.bb_pos + offset, value);
+ this.bb.writeFloat32(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
y():number {
- return this.bb!.readFloat32(this.bb_pos + 4);
+ return this.bb.readFloat32(this.bb_pos + 4);
};
/**
* @returns {boolean}
*/
mutate_y(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
+ var offset = this.bb.__offset(this.bb_pos, 4);
if (offset === 0) {
return false;
}
- this.bb!.writeFloat32(this.bb_pos + offset, value);
+ this.bb.writeFloat32(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
z():number {
- return this.bb!.readFloat32(this.bb_pos + 8);
+ return this.bb.readFloat32(this.bb_pos + 8);
};
/**
* @returns {boolean}
*/
mutate_z(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 8);
+ var offset = this.bb.__offset(this.bb_pos, 8);
if (offset === 0) {
return false;
}
- this.bb!.writeFloat32(this.bb_pos + offset, value);
+ this.bb.writeFloat32(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
test1():number {
- return this.bb!.readFloat64(this.bb_pos + 16);
+ return this.bb.readFloat64(this.bb_pos + 16);
};
/**
* @returns {boolean}
*/
mutate_test1(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 16);
+ var offset = this.bb.__offset(this.bb_pos, 16);
if (offset === 0) {
return false;
}
- this.bb!.writeFloat64(this.bb_pos + offset, value);
+ this.bb.writeFloat64(this.bb_pos + offset, value);
return true;
};
* @returns {MyGame.Example.Color}
*/
test2():MyGame.Example.Color {
- return /** @type {MyGame.Example.Color} */ (this.bb!.readInt8(this.bb_pos + 24));
+ return /** @type {MyGame.Example.Color} */ (this.bb.readInt8(this.bb_pos + 24));
};
/**
* @returns {boolean}
*/
mutate_test2(value:MyGame.Example.Color):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 24);
+ var offset = this.bb.__offset(this.bb_pos, 24);
if (offset === 0) {
return false;
}
- this.bb!.writeInt8(this.bb_pos + offset, value);
+ this.bb.writeInt8(this.bb_pos + offset, value);
return true;
};
* @returns {MyGame.Example.Test|null}
*/
test3(obj?:MyGame.Example.Test):MyGame.Example.Test|null {
- return (obj || new MyGame.Example.Test).__init(this.bb_pos + 26, this.bb!);
+ return (obj || new MyGame.Example.Test).__init(this.bb_pos + 26, this.bb);
};
/**
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {number}
*/
id():number {
- return this.bb!.readUint32(this.bb_pos);
+ return this.bb.readUint32(this.bb_pos);
};
/**
* @returns {boolean}
*/
mutate_id(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 0);
+ var offset = this.bb.__offset(this.bb_pos, 0);
if (offset === 0) {
return false;
}
- this.bb!.writeUint32(this.bb_pos + offset, value);
+ this.bb.writeUint32(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
distance():number {
- return this.bb!.readUint32(this.bb_pos + 4);
+ return this.bb.readUint32(this.bb_pos + 4);
};
/**
* @returns {boolean}
*/
mutate_distance(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
+ var offset = this.bb.__offset(this.bb_pos, 4);
if (offset === 0) {
return false;
}
- this.bb!.writeUint32(this.bb_pos + offset, value);
+ this.bb.writeUint32(this.bb_pos + offset, value);
return true;
};
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
id():string|null
id(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
id(optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
+ var offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
};
/**
* @returns {flatbuffers.Long}
*/
val():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
+ var offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
};
/**
* @returns {boolean}
*/
mutate_val(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 6);
+ var offset = this.bb.__offset(this.bb_pos, 6);
if (offset === 0) {
return false;
}
- this.bb!.writeInt64(this.bb_pos + offset, value);
+ this.bb.writeInt64(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
count():number {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_count(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 8);
+ var offset = this.bb.__offset(this.bb_pos, 8);
if (offset === 0) {
return false;
}
- this.bb!.writeUint16(this.bb_pos + offset, value);
+ this.bb.writeUint16(this.bb_pos + offset, value);
return true;
};
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {MyGame.Example.Vec3|null}
*/
pos(obj?:MyGame.Example.Vec3):MyGame.Example.Vec3|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? (obj || new MyGame.Example.Vec3).__init(this.bb_pos + offset, this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new MyGame.Example.Vec3).__init(this.bb_pos + offset, this.bb) : null;
};
/**
* @returns {number}
*/
mana():number {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? this.bb!.readInt16(this.bb_pos + offset) : 150;
+ var offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.readInt16(this.bb_pos + offset) : 150;
};
/**
* @returns {boolean}
*/
mutate_mana(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 6);
+ var offset = this.bb.__offset(this.bb_pos, 6);
if (offset === 0) {
return false;
}
- this.bb!.writeInt16(this.bb_pos + offset, value);
+ this.bb.writeInt16(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
hp():number {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? this.bb!.readInt16(this.bb_pos + offset) : 100;
+ var offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.readInt16(this.bb_pos + offset) : 100;
};
/**
* @returns {boolean}
*/
mutate_hp(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 8);
+ var offset = this.bb.__offset(this.bb_pos, 8);
if (offset === 0) {
return false;
}
- this.bb!.writeInt16(this.bb_pos + offset, value);
+ this.bb.writeInt16(this.bb_pos + offset, value);
return true;
};
name():string|null
name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
name(optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 10);
- return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
+ var offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
};
/**
* @returns {number}
*/
inventory(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 14);
- return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
};
/**
* @returns {number}
*/
inventoryLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 14);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {Uint8Array}
*/
inventoryArray():Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 14);
- return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+ var offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
};
/**
* @returns {MyGame.Example.Color}
*/
color():MyGame.Example.Color {
- var offset = this.bb!.__offset(this.bb_pos, 16);
- return offset ? /** @type {MyGame.Example.Color} */ (this.bb!.readInt8(this.bb_pos + offset)) : MyGame.Example.Color.Blue;
+ var offset = this.bb.__offset(this.bb_pos, 16);
+ return offset ? /** @type {MyGame.Example.Color} */ (this.bb.readInt8(this.bb_pos + offset)) : MyGame.Example.Color.Blue;
};
/**
* @returns {boolean}
*/
mutate_color(value:MyGame.Example.Color):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 16);
+ var offset = this.bb.__offset(this.bb_pos, 16);
if (offset === 0) {
return false;
}
- this.bb!.writeInt8(this.bb_pos + offset, value);
+ this.bb.writeInt8(this.bb_pos + offset, value);
return true;
};
* @returns {MyGame.Example.Any}
*/
testType():MyGame.Example.Any {
- var offset = this.bb!.__offset(this.bb_pos, 18);
- return offset ? /** @type {MyGame.Example.Any} */ (this.bb!.readUint8(this.bb_pos + offset)) : MyGame.Example.Any.NONE;
+ var offset = this.bb.__offset(this.bb_pos, 18);
+ return offset ? /** @type {MyGame.Example.Any} */ (this.bb.readUint8(this.bb_pos + offset)) : MyGame.Example.Any.NONE;
};
/**
* @returns {boolean}
*/
mutate_test_type(value:MyGame.Example.Any):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 18);
+ var offset = this.bb.__offset(this.bb_pos, 18);
if (offset === 0) {
return false;
}
- this.bb!.writeUint8(this.bb_pos + offset, value);
+ this.bb.writeUint8(this.bb_pos + offset, value);
return true;
};
* @returns {?flatbuffers.Table}
*/
test<T extends flatbuffers.Table>(obj:T):T|null {
- var offset = this.bb!.__offset(this.bb_pos, 20);
- return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null;
+ var offset = this.bb.__offset(this.bb_pos, 20);
+ return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
};
/**
* @returns {MyGame.Example.Test}
*/
test4(index: number, obj?:MyGame.Example.Test):MyGame.Example.Test|null {
- var offset = this.bb!.__offset(this.bb_pos, 22);
- return offset ? (obj || new MyGame.Example.Test).__init(this.bb!.__vector(this.bb_pos + offset) + index * 4, this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 22);
+ return offset ? (obj || new MyGame.Example.Test).__init(this.bb.__vector(this.bb_pos + offset) + index * 4, this.bb) : null;
};
/**
* @returns {number}
*/
test4Length():number {
- var offset = this.bb!.__offset(this.bb_pos, 22);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 22);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
testarrayofstring(index: number):string
testarrayofstring(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array
testarrayofstring(index: number,optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 24);
- return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+ var offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
};
/**
* @returns {number}
*/
testarrayofstringLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 24);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {MyGame.Example.Monster}
*/
testarrayoftables(index: number, obj?:MyGame.Example.Monster):MyGame.Example.Monster|null {
- var offset = this.bb!.__offset(this.bb_pos, 26);
- return offset ? (obj || new MyGame.Example.Monster).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? (obj || new MyGame.Example.Monster).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
};
/**
* @returns {number}
*/
testarrayoftablesLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 26);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {MyGame.Example.Monster|null}
*/
enemy(obj?:MyGame.Example.Monster):MyGame.Example.Monster|null {
- var offset = this.bb!.__offset(this.bb_pos, 28);
- return offset ? (obj || new MyGame.Example.Monster).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 28);
+ return offset ? (obj || new MyGame.Example.Monster).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
};
/**
* @returns {number}
*/
testnestedflatbuffer(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 30);
- return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 30);
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
};
/**
* @returns {number}
*/
testnestedflatbufferLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 30);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 30);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {Uint8Array}
*/
testnestedflatbufferArray():Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 30);
- return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+ var offset = this.bb.__offset(this.bb_pos, 30);
+ return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
};
/**
* @returns {MyGame.Example.Stat|null}
*/
testempty(obj?:MyGame.Example.Stat):MyGame.Example.Stat|null {
- var offset = this.bb!.__offset(this.bb_pos, 32);
- return offset ? (obj || new MyGame.Example.Stat).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 32);
+ return offset ? (obj || new MyGame.Example.Stat).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
};
/**
* @returns {boolean}
*/
testbool():boolean {
- var offset = this.bb!.__offset(this.bb_pos, 34);
- return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
+ var offset = this.bb.__offset(this.bb_pos, 34);
+ return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
};
/**
* @returns {boolean}
*/
mutate_testbool(value:boolean):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 34);
+ var offset = this.bb.__offset(this.bb_pos, 34);
if (offset === 0) {
return false;
}
- this.bb!.writeInt8(this.bb_pos + offset, +value);
+ this.bb.writeInt8(this.bb_pos + offset, +value);
return true;
};
* @returns {number}
*/
testhashs32Fnv1():number {
- var offset = this.bb!.__offset(this.bb_pos, 36);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 36);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_testhashs32_fnv1(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 36);
+ var offset = this.bb.__offset(this.bb_pos, 36);
if (offset === 0) {
return false;
}
- this.bb!.writeInt32(this.bb_pos + offset, value);
+ this.bb.writeInt32(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
testhashu32Fnv1():number {
- var offset = this.bb!.__offset(this.bb_pos, 38);
- return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 38);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_testhashu32_fnv1(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 38);
+ var offset = this.bb.__offset(this.bb_pos, 38);
if (offset === 0) {
return false;
}
- this.bb!.writeUint32(this.bb_pos + offset, value);
+ this.bb.writeUint32(this.bb_pos + offset, value);
return true;
};
* @returns {flatbuffers.Long}
*/
testhashs64Fnv1():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 40);
- return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
+ var offset = this.bb.__offset(this.bb_pos, 40);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
};
/**
* @returns {boolean}
*/
mutate_testhashs64_fnv1(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 40);
+ var offset = this.bb.__offset(this.bb_pos, 40);
if (offset === 0) {
return false;
}
- this.bb!.writeInt64(this.bb_pos + offset, value);
+ this.bb.writeInt64(this.bb_pos + offset, value);
return true;
};
* @returns {flatbuffers.Long}
*/
testhashu64Fnv1():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 42);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
+ var offset = this.bb.__offset(this.bb_pos, 42);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(0, 0);
};
/**
* @returns {boolean}
*/
mutate_testhashu64_fnv1(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 42);
+ var offset = this.bb.__offset(this.bb_pos, 42);
if (offset === 0) {
return false;
}
- this.bb!.writeUint64(this.bb_pos + offset, value);
+ this.bb.writeUint64(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
testhashs32Fnv1a():number {
- var offset = this.bb!.__offset(this.bb_pos, 44);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 44);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_testhashs32_fnv1a(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 44);
+ var offset = this.bb.__offset(this.bb_pos, 44);
if (offset === 0) {
return false;
}
- this.bb!.writeInt32(this.bb_pos + offset, value);
+ this.bb.writeInt32(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
testhashu32Fnv1a():number {
- var offset = this.bb!.__offset(this.bb_pos, 46);
- return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 46);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_testhashu32_fnv1a(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 46);
+ var offset = this.bb.__offset(this.bb_pos, 46);
if (offset === 0) {
return false;
}
- this.bb!.writeUint32(this.bb_pos + offset, value);
+ this.bb.writeUint32(this.bb_pos + offset, value);
return true;
};
* @returns {flatbuffers.Long}
*/
testhashs64Fnv1a():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 48);
- return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
+ var offset = this.bb.__offset(this.bb_pos, 48);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
};
/**
* @returns {boolean}
*/
mutate_testhashs64_fnv1a(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 48);
+ var offset = this.bb.__offset(this.bb_pos, 48);
if (offset === 0) {
return false;
}
- this.bb!.writeInt64(this.bb_pos + offset, value);
+ this.bb.writeInt64(this.bb_pos + offset, value);
return true;
};
* @returns {flatbuffers.Long}
*/
testhashu64Fnv1a():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 50);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
+ var offset = this.bb.__offset(this.bb_pos, 50);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(0, 0);
};
/**
* @returns {boolean}
*/
mutate_testhashu64_fnv1a(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 50);
+ var offset = this.bb.__offset(this.bb_pos, 50);
if (offset === 0) {
return false;
}
- this.bb!.writeUint64(this.bb_pos + offset, value);
+ this.bb.writeUint64(this.bb_pos + offset, value);
return true;
};
* @returns {boolean}
*/
testarrayofbools(index: number):boolean|null {
- var offset = this.bb!.__offset(this.bb_pos, 52);
- return offset ? !!this.bb!.readInt8(this.bb!.__vector(this.bb_pos + offset) + index) : false;
+ var offset = this.bb.__offset(this.bb_pos, 52);
+ return offset ? !!this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) : false;
};
/**
* @returns {number}
*/
testarrayofboolsLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 52);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 52);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {Int8Array}
*/
testarrayofboolsArray():Int8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 52);
- return offset ? new Int8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+ var offset = this.bb.__offset(this.bb_pos, 52);
+ return offset ? new Int8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
};
/**
* @returns {number}
*/
testf():number {
- var offset = this.bb!.__offset(this.bb_pos, 54);
- return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 3.14159;
+ var offset = this.bb.__offset(this.bb_pos, 54);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3.14159;
};
/**
* @returns {boolean}
*/
mutate_testf(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 54);
+ var offset = this.bb.__offset(this.bb_pos, 54);
if (offset === 0) {
return false;
}
- this.bb!.writeFloat32(this.bb_pos + offset, value);
+ this.bb.writeFloat32(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
testf2():number {
- var offset = this.bb!.__offset(this.bb_pos, 56);
- return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 3.0;
+ var offset = this.bb.__offset(this.bb_pos, 56);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3.0;
};
/**
* @returns {boolean}
*/
mutate_testf2(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 56);
+ var offset = this.bb.__offset(this.bb_pos, 56);
if (offset === 0) {
return false;
}
- this.bb!.writeFloat32(this.bb_pos + offset, value);
+ this.bb.writeFloat32(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
testf3():number {
- var offset = this.bb!.__offset(this.bb_pos, 58);
- return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0;
+ var offset = this.bb.__offset(this.bb_pos, 58);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0;
};
/**
* @returns {boolean}
*/
mutate_testf3(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 58);
+ var offset = this.bb.__offset(this.bb_pos, 58);
if (offset === 0) {
return false;
}
- this.bb!.writeFloat32(this.bb_pos + offset, value);
+ this.bb.writeFloat32(this.bb_pos + offset, value);
return true;
};
testarrayofstring2(index: number):string
testarrayofstring2(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array
testarrayofstring2(index: number,optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 60);
- return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+ var offset = this.bb.__offset(this.bb_pos, 60);
+ return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
};
/**
* @returns {number}
*/
testarrayofstring2Length():number {
- var offset = this.bb!.__offset(this.bb_pos, 60);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 60);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {MyGame.Example.Ability}
*/
testarrayofsortedstruct(index: number, obj?:MyGame.Example.Ability):MyGame.Example.Ability|null {
- var offset = this.bb!.__offset(this.bb_pos, 62);
- return offset ? (obj || new MyGame.Example.Ability).__init(this.bb!.__vector(this.bb_pos + offset) + index * 8, this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 62);
+ return offset ? (obj || new MyGame.Example.Ability).__init(this.bb.__vector(this.bb_pos + offset) + index * 8, this.bb) : null;
};
/**
* @returns {number}
*/
testarrayofsortedstructLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 62);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 62);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {number}
*/
flex(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 64);
- return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 64);
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
};
/**
* @returns {number}
*/
flexLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 64);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 64);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {Uint8Array}
*/
flexArray():Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 64);
- return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+ var offset = this.bb.__offset(this.bb_pos, 64);
+ return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
};
/**
* @returns {MyGame.Example.Test}
*/
test5(index: number, obj?:MyGame.Example.Test):MyGame.Example.Test|null {
- var offset = this.bb!.__offset(this.bb_pos, 66);
- return offset ? (obj || new MyGame.Example.Test).__init(this.bb!.__vector(this.bb_pos + offset) + index * 4, this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 66);
+ return offset ? (obj || new MyGame.Example.Test).__init(this.bb.__vector(this.bb_pos + offset) + index * 4, this.bb) : null;
};
/**
* @returns {number}
*/
test5Length():number {
- var offset = this.bb!.__offset(this.bb_pos, 66);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 66);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {flatbuffers.Long}
*/
vectorOfLongs(index: number):flatbuffers.Long|null {
- var offset = this.bb!.__offset(this.bb_pos, 68);
- return offset ? this.bb!.readInt64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : this.bb!.createLong(0, 0);
+ var offset = this.bb.__offset(this.bb_pos, 68);
+ return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) : this.bb.createLong(0, 0);
};
/**
* @returns {number}
*/
vectorOfLongsLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 68);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 68);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {number}
*/
vectorOfDoubles(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 70);
- return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 70);
+ return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0;
};
/**
* @returns {number}
*/
vectorOfDoublesLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 70);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 70);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {Float64Array}
*/
vectorOfDoublesArray():Float64Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 70);
- return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+ var offset = this.bb.__offset(this.bb_pos, 70);
+ return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
};
/**
* @returns {MyGame.InParentNamespace|null}
*/
parentNamespaceTest(obj?:MyGame.InParentNamespace):MyGame.InParentNamespace|null {
- var offset = this.bb!.__offset(this.bb_pos, 72);
- return offset ? (obj || new MyGame.InParentNamespace).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 72);
+ return offset ? (obj || new MyGame.InParentNamespace).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
};
/**
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {number}
*/
i8():number {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.readInt8(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readInt8(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_i8(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
+ var offset = this.bb.__offset(this.bb_pos, 4);
if (offset === 0) {
return false;
}
- this.bb!.writeInt8(this.bb_pos + offset, value);
+ this.bb.writeInt8(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
u8():number {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? this.bb!.readUint8(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_u8(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 6);
+ var offset = this.bb.__offset(this.bb_pos, 6);
if (offset === 0) {
return false;
}
- this.bb!.writeUint8(this.bb_pos + offset, value);
+ this.bb.writeUint8(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
i16():number {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? this.bb!.readInt16(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.readInt16(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_i16(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 8);
+ var offset = this.bb.__offset(this.bb_pos, 8);
if (offset === 0) {
return false;
}
- this.bb!.writeInt16(this.bb_pos + offset, value);
+ this.bb.writeInt16(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
u16():number {
- var offset = this.bb!.__offset(this.bb_pos, 10);
- return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_u16(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 10);
+ var offset = this.bb.__offset(this.bb_pos, 10);
if (offset === 0) {
return false;
}
- this.bb!.writeUint16(this.bb_pos + offset, value);
+ this.bb.writeUint16(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
i32():number {
- var offset = this.bb!.__offset(this.bb_pos, 12);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_i32(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 12);
+ var offset = this.bb.__offset(this.bb_pos, 12);
if (offset === 0) {
return false;
}
- this.bb!.writeInt32(this.bb_pos + offset, value);
+ this.bb.writeInt32(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
u32():number {
- var offset = this.bb!.__offset(this.bb_pos, 14);
- return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_u32(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 14);
+ var offset = this.bb.__offset(this.bb_pos, 14);
if (offset === 0) {
return false;
}
- this.bb!.writeUint32(this.bb_pos + offset, value);
+ this.bb.writeUint32(this.bb_pos + offset, value);
return true;
};
* @returns {flatbuffers.Long}
*/
i64():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 16);
- return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
+ var offset = this.bb.__offset(this.bb_pos, 16);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
};
/**
* @returns {boolean}
*/
mutate_i64(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 16);
+ var offset = this.bb.__offset(this.bb_pos, 16);
if (offset === 0) {
return false;
}
- this.bb!.writeInt64(this.bb_pos + offset, value);
+ this.bb.writeInt64(this.bb_pos + offset, value);
return true;
};
* @returns {flatbuffers.Long}
*/
u64():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 18);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
+ var offset = this.bb.__offset(this.bb_pos, 18);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(0, 0);
};
/**
* @returns {boolean}
*/
mutate_u64(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 18);
+ var offset = this.bb.__offset(this.bb_pos, 18);
if (offset === 0) {
return false;
}
- this.bb!.writeUint64(this.bb_pos + offset, value);
+ this.bb.writeUint64(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
f32():number {
- var offset = this.bb!.__offset(this.bb_pos, 20);
- return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0;
+ var offset = this.bb.__offset(this.bb_pos, 20);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0;
};
/**
* @returns {boolean}
*/
mutate_f32(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 20);
+ var offset = this.bb.__offset(this.bb_pos, 20);
if (offset === 0) {
return false;
}
- this.bb!.writeFloat32(this.bb_pos + offset, value);
+ this.bb.writeFloat32(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
f64():number {
- var offset = this.bb!.__offset(this.bb_pos, 22);
- return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0;
+ var offset = this.bb.__offset(this.bb_pos, 22);
+ return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0.0;
};
/**
* @returns {boolean}
*/
mutate_f64(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 22);
+ var offset = this.bb.__offset(this.bb_pos, 22);
if (offset === 0) {
return false;
}
- this.bb!.writeFloat64(this.bb_pos + offset, value);
+ this.bb.writeFloat64(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
v8(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 24);
- return offset ? this.bb!.readInt8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
};
/**
* @returns {number}
*/
v8Length():number {
- var offset = this.bb!.__offset(this.bb_pos, 24);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {Int8Array}
*/
v8Array():Int8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 24);
- return offset ? new Int8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+ var offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? new Int8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
};
/**
* @returns {number}
*/
vf64(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 26);
- return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0;
};
/**
* @returns {number}
*/
vf64Length():number {
- var offset = this.bb!.__offset(this.bb_pos, 26);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {Float64Array}
*/
vf64Array():Float64Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 26);
- return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+ var offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
};
/**
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {number}
*/
foo():number {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_foo(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
+ var offset = this.bb.__offset(this.bb_pos, 4);
if (offset === 0) {
return false;
}
- this.bb!.writeInt32(this.bb_pos + offset, value);
+ this.bb.writeInt32(this.bb_pos + offset, value);
return true;
};
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {number}
*/
a():number {
- return this.bb!.readInt32(this.bb_pos);
+ return this.bb.readInt32(this.bb_pos);
};
/**
* @returns {boolean}
*/
mutate_a(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 0);
+ var offset = this.bb.__offset(this.bb_pos, 0);
if (offset === 0) {
return false;
}
- this.bb!.writeInt32(this.bb_pos + offset, value);
+ this.bb.writeInt32(this.bb_pos + offset, value);
return true;
};
* @returns {number}
*/
b():number {
- return this.bb!.readInt32(this.bb_pos + 4);
+ return this.bb.readInt32(this.bb_pos + 4);
};
/**
* @returns {boolean}
*/
mutate_b(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
+ var offset = this.bb.__offset(this.bb_pos, 4);
if (offset === 0) {
return false;
}
- this.bb!.writeInt32(this.bb_pos + offset, value);
+ this.bb.writeInt32(this.bb_pos + offset, value);
return true;
};
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {NamespaceA.NamespaceB.TableInNestedNS|null}
*/
fooTable(obj?:NS9459827973991502386.NamespaceA.NamespaceB.TableInNestedNS):NS9459827973991502386.NamespaceA.NamespaceB.TableInNestedNS|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? (obj || new NS9459827973991502386.NamespaceA.NamespaceB.TableInNestedNS).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new NS9459827973991502386.NamespaceA.NamespaceB.TableInNestedNS).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
};
/**
* @returns {NamespaceA.NamespaceB.EnumInNestedNS}
*/
fooEnum():NS9459827973991502386.NamespaceA.NamespaceB.EnumInNestedNS {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? /** @type {NamespaceA.NamespaceB.EnumInNestedNS} */ (this.bb!.readInt8(this.bb_pos + offset)) : NS9459827973991502386.NamespaceA.NamespaceB.EnumInNestedNS.A;
+ var offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? /** @type {NamespaceA.NamespaceB.EnumInNestedNS} */ (this.bb.readInt8(this.bb_pos + offset)) : NS9459827973991502386.NamespaceA.NamespaceB.EnumInNestedNS.A;
};
/**
* @returns {boolean}
*/
mutate_foo_enum(value:NS9459827973991502386.NamespaceA.NamespaceB.EnumInNestedNS):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 6);
+ var offset = this.bb.__offset(this.bb_pos, 6);
if (offset === 0) {
return false;
}
- this.bb!.writeInt8(this.bb_pos + offset, value);
+ this.bb.writeInt8(this.bb_pos + offset, value);
return true;
};
* @returns {NamespaceA.NamespaceB.StructInNestedNS|null}
*/
fooStruct(obj?:NS9459827973991502386.NamespaceA.NamespaceB.StructInNestedNS):NS9459827973991502386.NamespaceA.NamespaceB.StructInNestedNS|null {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? (obj || new NS9459827973991502386.NamespaceA.NamespaceB.StructInNestedNS).__init(this.bb_pos + offset, this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? (obj || new NS9459827973991502386.NamespaceA.NamespaceB.StructInNestedNS).__init(this.bb_pos + offset, this.bb) : null;
};
/**
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {NamespaceA.TableInFirstNS|null}
*/
referToA1(obj?:NamespaceA.TableInFirstNS):NamespaceA.TableInFirstNS|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? (obj || new NamespaceA.TableInFirstNS).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new NamespaceA.TableInFirstNS).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
};
/**
* @returns {NamespaceA.SecondTableInA|null}
*/
referToA2(obj?:NamespaceA.SecondTableInA):NamespaceA.SecondTableInA|null {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? (obj || new NamespaceA.SecondTableInA).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? (obj || new NamespaceA.SecondTableInA).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
};
/**
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {NamespaceC.TableInC|null}
*/
referToC(obj?:NamespaceC.TableInC):NamespaceC.TableInC|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? (obj || new NamespaceC.TableInC).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+ var offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new NamespaceC.TableInC).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
};
/**
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
-#include "flatbuffers/util.h"
-#include "flatbuffers/registry.h"
#include "flatbuffers/minireflect.h"
+#include "flatbuffers/registry.h"
+#include "flatbuffers/util.h"
#include "monster_test_generated.h"
#include "namespace_test/namespace_test1_generated.h"
#include "namespace_test/namespace_test2_generated.h"
#include "union_vector/union_vector_generated.h"
+// clang-format off
#ifndef FLATBUFFERS_CPP98_STL
#include <random>
#endif
#define TEST_OUTPUT_LINE(...) \
{ printf(__VA_ARGS__); printf("\n"); }
#endif
+// clang-format on
int testing_fails = 0;
void TestEqStr(const char *expval, const char *val, const char *exp,
const char *file, int line) {
- if (strcmp(expval, val) != 0) {
- TestFail(expval, val, exp, file, line);
- }
+ if (strcmp(expval, val) != 0) { TestFail(expval, val, exp, file, line); }
}
template<typename T, typename U>
void TestEq(T expval, U val, const char *exp, const char *file, int line) {
if (U(expval) != val) {
TestFail(flatbuffers::NumToString(expval).c_str(),
- flatbuffers::NumToString(val).c_str(),
- exp, file, line);
+ flatbuffers::NumToString(val).c_str(), exp, file, line);
}
}
-#define TEST_EQ(exp, val) TestEq(exp, val, #exp, __FILE__, __LINE__)
+#define TEST_EQ(exp, val) TestEq(exp, val, #exp, __FILE__, __LINE__)
#define TEST_NOTNULL(exp) TestEq(exp == NULL, false, #exp, __FILE__, __LINE__)
-#define TEST_EQ_STR(exp, val) TestEqStr(exp, val, #exp, __FILE__, __LINE__)
+#define TEST_EQ_STR(exp, val) TestEqStr(exp, val, #exp, __FILE__, __LINE__)
// Include simple random number generator to ensure results will be the
// same cross platform.
// http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator
uint32_t lcg_seed = 48271;
uint32_t lcg_rand() {
- return lcg_seed = ((uint64_t)lcg_seed * 279470273UL) % 4294967291UL;
+ return lcg_seed = ((uint64_t)lcg_seed * 279470273UL) % 4294967291UL;
}
void lcg_reset() { lcg_seed = 48271; }
Test tests[] = { Test(10, 20), Test(30, 40) };
auto testv = builder.CreateVectorOfStructs(tests, 2);
-
+ // clang-format off
#ifndef FLATBUFFERS_CPP98_STL
// Create a vector of structures from a lambda.
auto testv2 = builder.CreateVectorOfStructs<Test>(
*s = (reinterpret_cast<Test*>(state))[i];
}, tests);
#endif // FLATBUFFERS_CPP98_STL
+ // clang-format on
// create monster with very few fields set:
// (same functionality as CreateMonster below, but sets fields manually)
// Create an array of strings. Also test string pooling, and lambdas.
auto vecofstrings =
- builder.CreateVector<flatbuffers::Offset<flatbuffers::String>>(4,
- [](size_t i, flatbuffers::FlatBufferBuilder *b)
- -> flatbuffers::Offset<flatbuffers::String> {
- static const char *names[] = { "bob", "fred", "bob", "fred" };
- return b->CreateSharedString(names[i]);
- }, &builder);
+ builder.CreateVector<flatbuffers::Offset<flatbuffers::String>>(
+ 4,
+ [](size_t i, flatbuffers::FlatBufferBuilder *b)
+ -> flatbuffers::Offset<flatbuffers::String> {
+ static const char *names[] = { "bob", "fred", "bob", "fred" };
+ return b->CreateSharedString(names[i]);
+ },
+ &builder);
// Creating vectors of strings in one convenient call.
std::vector<std::string> names2;
// If for whatever reason you don't have the nested_builder available, you
// can substitute flatbuffers::largest_scalar_t (64-bit) for the alignment, or
// the largest force_align value in your schema if you're using it.
- auto nested_flatbuffer_vector =
- builder.CreateVector(nested_builder.GetBufferPointer(),
- nested_builder.GetSize());
+ auto nested_flatbuffer_vector = builder.CreateVector(
+ nested_builder.GetBufferPointer(), nested_builder.GetSize());
// Test a nested FlexBuffer:
flexbuffers::Builder flexbuild;
// shortcut for creating monster with all fields set:
auto mloc = CreateMonster(builder, &vec, 150, 80, name, inventory, Color_Blue,
- Any_Monster, mlocs[1].Union(), // Store a union.
+ Any_Monster, mlocs[1].Union(), // Store a union.
testv, vecofstrings, vecoftables, 0,
- nested_flatbuffer_vector, 0, false,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.14159f, 3.0f, 0.0f,
- vecofstrings2, vecofstructs, flex, testv2);
+ nested_flatbuffer_vector, 0, false, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 3.14159f, 3.0f, 0.0f, vecofstrings2,
+ vecofstructs, flex, testv2);
FinishMonsterBuffer(builder, mloc);
+ // clang-format off
#ifdef FLATBUFFERS_TEST_VERBOSE
// print byte data for debugging:
auto p = builder.GetBufferPointer();
for (flatbuffers::uoffset_t i = 0; i < builder.GetSize(); i++)
printf("%d ", p[i]);
#endif
+ // clang-format on
// 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.ReleaseBufferPointer();
// example of accessing a buffer loaded in memory:
void AccessFlatBufferTest(const uint8_t *flatbuf, size_t length,
bool pooled = true) {
-
// First, verify the buffers integrity (optional)
flatbuffers::Verifier verifier(flatbuf, length);
TEST_EQ(VerifyMonsterBuffer(verifier), true);
std::vector<uint8_t> test_buff;
test_buff.resize(length * 2);
- std::memcpy(&test_buff[0], flatbuf , length);
- std::memcpy(&test_buff[length], flatbuf , length);
+ std::memcpy(&test_buff[0], flatbuf, length);
+ std::memcpy(&test_buff[length], flatbuf, length);
flatbuffers::Verifier verifier1(&test_buff[0], length);
TEST_EQ(VerifyMonsterBuffer(verifier1), true);
// Test accessing a vector of sorted structs
auto vecofstructs = monster->testarrayofsortedstruct();
if (vecofstructs) { // not filled in monster_test.bfbs
- for (flatbuffers::uoffset_t i = 0; i < vecofstructs->size()-1; i++) {
+ for (flatbuffers::uoffset_t i = 0; i < vecofstructs->size() - 1; i++) {
auto left = vecofstructs->Get(i);
- auto right = vecofstructs->Get(i+1);
+ auto right = vecofstructs->Get(i + 1);
TEST_EQ(true, (left->KeyCompareLessThan(right)));
}
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));
}
// Test nested FlatBuffers if available:
TEST_EQ(flatbuffers::AlignOf<Test>(), 2UL);
TEST_EQ(sizeof(Test), 4UL);
- const flatbuffers::Vector<const Test *>* tests_array[] = {
+ const flatbuffers::Vector<const Test *> *tests_array[] = {
monster->test4(),
monster->test5(),
};
// Monster originally at 150 mana (default value)
auto mana_default_ok = monster->mutate_mana(150); // Mutate to default value.
- TEST_EQ(mana_default_ok, true); // Mutation should succeed, because default value.
+ TEST_EQ(mana_default_ok,
+ true); // Mutation should succeed, because default value.
TEST_EQ(monster->mana(), 150);
auto mana_ok = monster->mutate_mana(10);
TEST_EQ(mana_ok, false); // Field was NOT present, because default value.
// 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;
- (void)hash;
- // Don't actually do anything, leave variable null.
- });
+ [](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;
- return 0;
- });
+ [](void *pointer) -> flatbuffers::hash_value_t {
+ (void)pointer;
+ return 0;
+ });
// Turn a buffer into C++ objects.
auto monster1 = UnPackMonster(flatbuf, &resolver);
auto len1 = fbb1.GetSize();
auto len2 = fbb2.GetSize();
TEST_EQ(len1, len2);
- TEST_EQ(memcmp(fbb1.GetBufferPointer(), fbb2.GetBufferPointer(),
- len1), 0);
+ TEST_EQ(memcmp(fbb1.GetBufferPointer(), fbb2.GetBufferPointer(), len1), 0);
// Test it with the original buffer test to make sure all data survived.
AccessFlatBufferTest(fbb2.GetBufferPointer(), len2, false);
void SizePrefixedTest() {
// Create size prefixed buffer.
flatbuffers::FlatBufferBuilder fbb;
- fbb.FinishSizePrefixed(CreateMonster(fbb, 0, 200, 300,
- fbb.CreateString("bob")));
+ fbb.FinishSizePrefixed(
+ CreateMonster(fbb, 0, 200, 300, fbb.CreateString("bob")));
// Verify it.
flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize());
// Access it.
auto m = flatbuffers::GetSizePrefixedRoot<MyGame::Example::Monster>(
- fbb.GetBufferPointer());
+ fbb.GetBufferPointer());
TEST_EQ(m->mana(), 200);
TEST_EQ(m->hp(), 300);
TEST_EQ_STR(m->name()->c_str(), "bob");
}
-
void TriviallyCopyableTest() {
+ // clang-format off
#if __GNUG__ && __GNUC__ < 5
TEST_EQ(__has_trivial_copy(Vec3), true);
#else
TEST_EQ(std::is_trivially_copyable<Vec3>::value, true);
#endif
#endif
+ // clang-format on
}
-
// example of parsing text straight into a buffer, and generating
// text back from it:
void ParseAndGenerateTextTest() {
// load FlatBuffer schema (.fbs) and JSON from disk
std::string schemafile;
std::string jsonfile;
+ TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
+ false, &schemafile),
+ true);
TEST_EQ(flatbuffers::LoadFile(
- (test_data_path + "monster_test.fbs").c_str(), false, &schemafile), true);
- TEST_EQ(flatbuffers::LoadFile(
- (test_data_path + "monsterdata_test.golden").c_str(), false, &jsonfile),
- true);
+ (test_data_path + "monsterdata_test.golden").c_str(), false,
+ &jsonfile),
+ true);
// parse schema first, so we can use it to parse the data after
flatbuffers::Parser parser;
auto include_test_path =
flatbuffers::ConCatPathFileName(test_data_path, "include_test");
- const char *include_directories[] = {
- test_data_path.c_str(), include_test_path.c_str(), nullptr
- };
+ const char *include_directories[] = { test_data_path.c_str(),
+ include_test_path.c_str(), nullptr };
TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
TEST_EQ(parser.Parse(jsonfile.c_str(), include_directories), true);
// to ensure it is correct, we now generate text back from the binary,
// and compare the two:
std::string jsongen;
- auto result = GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
+ auto result =
+ GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
TEST_EQ(result, true);
TEST_EQ_STR(jsongen.c_str(), jsonfile.c_str());
(test_data_path + "monster_test.fbs").c_str());
// Now we got this set up, we can parse by just specifying the identifier,
// the correct schema will be loaded on the fly:
- auto buf = registry.TextToFlatBuffer(jsonfile.c_str(),
- MonsterIdentifier());
+ auto buf = registry.TextToFlatBuffer(jsonfile.c_str(), MonsterIdentifier());
// If this fails, check registry.lasterror_.
TEST_NOTNULL(buf.data());
// Test the buffer, to be sure:
void ReflectionTest(uint8_t *flatbuf, size_t length) {
// Load a binary schema.
std::string bfbsfile;
- TEST_EQ(flatbuffers::LoadFile(
- (test_data_path + "monster_test.bfbs").c_str(), true, &bfbsfile),
- true);
+ TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.bfbs").c_str(),
+ true, &bfbsfile),
+ true);
// 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.
// Get struct field through reflection
auto pos_struct = flatbuffers::GetFieldStruct(root, *pos_field_ptr);
TEST_NOTNULL(pos_struct);
- TEST_EQ(flatbuffers::GetAnyFieldF(
- *pos_struct, *pos_table_ptr->fields()->LookupByKey("z")), 3.0f);
+ TEST_EQ(flatbuffers::GetAnyFieldF(*pos_struct,
+ *pos_table_ptr->fields()->LookupByKey("z")),
+ 3.0f);
auto test3_field = pos_table_ptr->fields()->LookupByKey("test3");
auto test3_struct = flatbuffers::GetFieldStruct(*pos_struct, *test3_field);
TEST_NOTNULL(test3_struct);
auto test3_object = schema.objects()->Get(test3_field->type()->index());
- TEST_EQ(flatbuffers::GetAnyFieldF(
- *test3_struct, *test3_object->fields()->LookupByKey("a")), 10);
+ TEST_EQ(flatbuffers::GetAnyFieldF(*test3_struct,
+ *test3_object->fields()->LookupByKey("a")),
+ 10);
// We can also modify it.
flatbuffers::SetField<uint16_t>(&root, hp_field, 200);
// Get the root.
// This time we wrap the result from GetAnyRoot in a smartpointer that
// will keep rroot valid as resizingbuf resizes.
- auto rroot = flatbuffers::piv(flatbuffers::GetAnyRoot(
- flatbuffers::vector_data(resizingbuf)), resizingbuf);
+ auto rroot = flatbuffers::piv(
+ flatbuffers::GetAnyRoot(flatbuffers::vector_data(resizingbuf)),
+ resizingbuf);
SetString(schema, "totally new string", GetFieldS(**rroot, name_field),
&resizingbuf);
// Here resizingbuf has changed, but rroot is still valid.
// Now lets extend a vector by 100 elements (10 -> 110).
auto &inventory_field = *fields->LookupByKey("inventory");
auto rinventory = flatbuffers::piv(
- flatbuffers::GetFieldV<uint8_t>(**rroot, inventory_field),
- resizingbuf);
+ flatbuffers::GetFieldV<uint8_t>(**rroot, inventory_field), resizingbuf);
flatbuffers::ResizeVector<uint8_t>(schema, 110, 50, *rinventory,
&resizingbuf);
// rinventory still valid, so lets read from it.
auto &testarrayofstring_field = *fields->LookupByKey("testarrayofstring");
// Find the vector value:
auto rtestarrayofstring = flatbuffers::piv(
- flatbuffers::GetFieldV<flatbuffers::Offset<flatbuffers::String>>(
- **rroot, testarrayofstring_field),
- resizingbuf);
+ flatbuffers::GetFieldV<flatbuffers::Offset<flatbuffers::String>>(
+ **rroot, testarrayofstring_field),
+ resizingbuf);
// It's a vector of 2 strings, to which we add one more, initialized to
// offset 0.
flatbuffers::ResizeVector<flatbuffers::Offset<flatbuffers::String>>(
- schema, 3, 0, *rtestarrayofstring, &resizingbuf);
+ schema, 3, 0, *rtestarrayofstring, &resizingbuf);
// Here we just create a buffer that contans a single string, but this
// could also be any complex set of tables and other values.
flatbuffers::FlatBufferBuilder stringfbb;
// Add the contents of it to our existing FlatBuffer.
// We do this last, so the pointer doesn't get invalidated (since it is
// at the end of the buffer):
- auto string_ptr = flatbuffers::AddFlatBuffer(resizingbuf,
- stringfbb.GetBufferPointer(),
- stringfbb.GetSize());
+ auto string_ptr = flatbuffers::AddFlatBuffer(
+ resizingbuf, stringfbb.GetBufferPointer(), stringfbb.GetSize());
// Finally, set the new value in the vector.
rtestarrayofstring->MutateOffset(2, string_ptr);
TEST_EQ_STR(rtestarrayofstring->Get(0)->c_str(), "bob");
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 *>(
- flatbuffers::vector_data(resizingbuf)),
- resizingbuf.size());
+ reinterpret_cast<const uint8_t *>(flatbuffers::vector_data(resizingbuf)),
+ resizingbuf.size());
TEST_EQ(VerifyMonsterBuffer(resize_verifier), true);
// Test buffer is valid using reflection as well
TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(),
flatbuffers::vector_data(resizingbuf),
- resizingbuf.size()), true);
+ resizingbuf.size()),
+ true);
// As an additional test, also set it on the name field.
// Note: unlike the name change above, this just overwrites the offset,
// tables and other things out of other FlatBuffers into a FlatBufferBuilder,
// either part or whole.
flatbuffers::FlatBufferBuilder fbb;
- auto root_offset = flatbuffers::CopyTable(fbb, schema, *root_table,
- *flatbuffers::GetAnyRoot(flatbuf),
- true);
+ auto root_offset = flatbuffers::CopyTable(
+ fbb, schema, *root_table, *flatbuffers::GetAnyRoot(flatbuf), true);
fbb.Finish(root_offset, MonsterIdentifier());
// Test that it was copied correctly:
AccessFlatBufferTest(fbb.GetBufferPointer(), fbb.GetSize());
// Test buffer is valid using reflection as well
TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(),
- fbb.GetBufferPointer(), fbb.GetSize()), true);
+ fbb.GetBufferPointer(), fbb.GetSize()),
+ true);
}
void MiniReflectFlatBuffersTest(uint8_t *flatbuf) {
auto s = flatbuffers::FlatBufferToString(flatbuf, MonsterTypeTable());
- TEST_EQ_STR(s.c_str(),
- "{ "
- "pos: { x: 1.0, y: 2.0, z: 3.0, test1: 0.0, test2: Red, test3: "
+ TEST_EQ_STR(
+ s.c_str(),
+ "{ "
+ "pos: { x: 1.0, y: 2.0, z: 3.0, test1: 0.0, test2: Red, test3: "
"{ a: 10, b: 20 } }, "
- "hp: 80, "
- "name: \"MyMonster\", "
- "inventory: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], "
- "test_type: Monster, "
- "test: { name: \"Fred\" }, "
- "test4: [ { a: 10, b: 20 }, { a: 30, b: 40 } ], "
- "testarrayofstring: [ \"bob\", \"fred\", \"bob\", \"fred\" ], "
- "testarrayoftables: [ { hp: 1000, name: \"Barney\" }, { name: \"Fred\" }, "
+ "hp: 80, "
+ "name: \"MyMonster\", "
+ "inventory: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], "
+ "test_type: Monster, "
+ "test: { name: \"Fred\" }, "
+ "test4: [ { a: 10, b: 20 }, { a: 30, b: 40 } ], "
+ "testarrayofstring: [ \"bob\", \"fred\", \"bob\", \"fred\" ], "
+ "testarrayoftables: [ { hp: 1000, name: \"Barney\" }, { name: \"Fred\" "
+ "}, "
"{ name: \"Wilma\" } ], "
- // TODO(wvo): should really print this nested buffer correctly.
- "testnestedflatbuffer: [ 20, 0, 0, 0, 77, 79, 78, 83, 12, 0, 12, 0, 0, 0, "
+ // TODO(wvo): should really print this nested buffer correctly.
+ "testnestedflatbuffer: [ 20, 0, 0, 0, 77, 79, 78, 83, 12, 0, 12, 0, 0, "
+ "0, "
"4, 0, 6, 0, 8, 0, 12, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 13, 0, 0, 0, 78, "
"101, 115, 116, 101, 100, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0 ], "
- "testarrayofstring2: [ \"jane\", \"mary\" ], "
- "testarrayofsortedstruct: [ { id: 1, distance: 10 }, "
+ "testarrayofstring2: [ \"jane\", \"mary\" ], "
+ "testarrayofsortedstruct: [ { id: 1, distance: 10 }, "
"{ id: 2, distance: 20 }, { id: 3, distance: 30 }, "
"{ id: 4, distance: 40 } ], "
- "flex: [ 210, 4, 5, 2 ], "
- "test5: [ { a: 10, b: 20 }, { a: 30, b: 40 } ] "
- "}");
+ "flex: [ 210, 4, 5, 2 ], "
+ "test5: [ { a: 10, b: 20 }, { a: 30, b: 40 } ] "
+ "}");
}
// Parse a .proto schema, output as .fbs
// load the .proto and the golden file from disk
std::string protofile;
std::string goldenfile;
- TEST_EQ(flatbuffers::LoadFile(
- (test_data_path + "prototest/test.proto").c_str(), false, &protofile),
- true);
- TEST_EQ(flatbuffers::LoadFile(
- (test_data_path + "prototest/test.golden").c_str(), false, &goldenfile),
- true);
+ TEST_EQ(
+ flatbuffers::LoadFile((test_data_path + "prototest/test.proto").c_str(),
+ false, &protofile),
+ true);
+ TEST_EQ(
+ flatbuffers::LoadFile((test_data_path + "prototest/test.golden").c_str(),
+ false, &goldenfile),
+ true);
flatbuffers::IDLOptions opts;
opts.include_dependence_headers = false;
TEST_EQ_STR(fbs.c_str(), goldenfile.c_str());
}
-template<typename T> void CompareTableFieldValue(flatbuffers::Table *table,
- flatbuffers::voffset_t voffset,
- T val) {
+template<typename T>
+void CompareTableFieldValue(flatbuffers::Table *table,
+ flatbuffers::voffset_t voffset, T val) {
T read = table->GetField(voffset, static_cast<T>(0));
TEST_EQ(read, val);
}
// Low level stress/fuzz test: serialize/deserialize a variety of
// different kinds of data in different combinations
void FuzzTest1() {
-
// Values we're testing against: chosen to ensure no bits get chopped
// off anywhere, and also be different from eachother.
- const uint8_t bool_val = true;
- const int8_t char_val = -127; // 0x81
- const uint8_t uchar_val = 0xFF;
- const int16_t short_val = -32222; // 0x8222;
+ const uint8_t bool_val = true;
+ const int8_t char_val = -127; // 0x81
+ const uint8_t uchar_val = 0xFF;
+ const int16_t short_val = -32222; // 0x8222;
const uint16_t ushort_val = 0xFEEE;
- const int32_t int_val = 0x83333333;
- const uint32_t uint_val = 0xFDDDDDDD;
- const int64_t long_val = 0x8444444444444444LL;
- const uint64_t ulong_val = 0xFCCCCCCCCCCCCCCCULL;
- const float float_val = 3.14159f;
- const double double_val = 3.14159265359;
+ const int32_t int_val = 0x83333333;
+ const uint32_t uint_val = 0xFDDDDDDD;
+ const int64_t long_val = 0x8444444444444444LL;
+ const uint64_t ulong_val = 0xFCCCCCCCCCCCCCCCULL;
+ const float float_val = 3.14159f;
+ const double double_val = 3.14159265359;
const int test_values_max = 11;
const flatbuffers::voffset_t fields_per_object = 4;
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);
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 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;
}
}
const int num_struct_definitions = 5; // Subset of num_definitions.
const int fields_per_definition = 15;
const int instances_per_definition = 5;
- const int deprecation_rate = 10; // 1 in deprecation_rate fields will
- // be deprecated.
+ const int deprecation_rate = 10; // 1 in deprecation_rate fields will
+ // be deprecated.
std::string schema = "namespace test;\n\n";
// 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,
+ std::string &schema_l, const int instances_per_definition_l,
const char *schema_add, const char *instance_add,
int definition) {
schema_l += schema_add;
}
};
+ // clang-format off
#define AddToSchemaAndInstances(schema_add, instance_add) \
RndDef::Add(definitions, schema, instances_per_definition, \
schema_add, instance_add, definition)
#define Dummy() \
RndDef::Add(definitions, schema, instances_per_definition, \
"byte", "1", definition)
+ // clang-format on
RndDef definitions[num_definitions];
bool is_struct = definition < num_struct_definitions;
AddToSchemaAndInstances(
- ((is_struct ? "struct " : "table ") + definition_name + " {\n").c_str(),
- "{\n");
+ ((is_struct ? "struct " : "table ") + definition_name + " {\n").c_str(),
+ "{\n");
for (int field = 0; field < fields_per_definition; field++) {
const bool is_last_field = field == fields_per_definition - 1;
// Deprecate 1 in deprecation_rate fields. Only table fields can be
// deprecated.
// Don't deprecate the last field to avoid dangling commas in JSON.
- const bool deprecated = !is_struct &&
- !is_last_field &&
- (lcg_rand() % deprecation_rate == 0);
+ const bool deprecated =
+ !is_struct && !is_last_field && (lcg_rand() % deprecation_rate == 0);
std::string field_name = "f" + flatbuffers::NumToString(field);
AddToSchemaAndInstances((" " + field_name + ":").c_str(),
deprecated ? "" : (field_name + ": ").c_str());
// Pick random type:
auto base_type = static_cast<flatbuffers::BaseType>(
- lcg_rand() % (flatbuffers::BASE_TYPE_UNION + 1));
+ lcg_rand() % (flatbuffers::BASE_TYPE_UNION + 1));
switch (base_type) {
case flatbuffers::BASE_TYPE_STRING:
if (is_struct) {
case flatbuffers::BASE_TYPE_VECTOR:
if (is_struct) {
Dummy(); // No vectors in structs.
- }
- else {
+ } else {
AddToSchemaAndInstances("[ubyte]",
deprecated ? "" : "[\n0,\n1,\n255\n]");
}
int defref = lcg_rand() % definition;
int instance = lcg_rand() % instances_per_definition;
AddToSchemaAndInstances(
- ("D" + flatbuffers::NumToString(defref)).c_str(),
- deprecated
- ? ""
- : definitions[defref].instances[instance].c_str());
+ ("D" + flatbuffers::NumToString(defref)).c_str(),
+ deprecated ? ""
+ : definitions[defref].instances[instance].c_str());
} else {
// If this is the first definition, we have no definition we can
// refer to.
}
break;
case flatbuffers::BASE_TYPE_BOOL:
- AddToSchemaAndInstances("bool", deprecated
- ? ""
- : (lcg_rand() % 2 ? "true" : "false"));
+ AddToSchemaAndInstances(
+ "bool", deprecated ? "" : (lcg_rand() % 2 ? "true" : "false"));
break;
default:
// All the scalar types.
// We want each instance to use its own random value.
for (int inst = 0; inst < instances_per_definition; inst++)
definitions[definition].instances[inst] +=
- flatbuffers::IsFloat(base_type)
- ? flatbuffers::NumToString<double>(lcg_rand() % 128).c_str()
- : flatbuffers::NumToString<int>(lcg_rand() % 128).c_str();
+ flatbuffers::IsFloat(base_type)
+ ? flatbuffers::NumToString<double>(lcg_rand() % 128)
+ .c_str()
+ : flatbuffers::NumToString<int>(lcg_rand() % 128).c_str();
}
}
- AddToSchemaAndInstances(
- deprecated ? "(deprecated);\n" : ";\n",
- deprecated ? "" : is_last_field ? "\n" : ",\n");
+ AddToSchemaAndInstances(deprecated ? "(deprecated);\n" : ";\n",
+ deprecated ? "" : is_last_field ? "\n" : ",\n");
}
AddToSchemaAndInstances("}\n\n", "}");
}
TEST_EQ(parser.Parse(schema.c_str()), true);
const std::string &json =
- definitions[num_definitions - 1].instances[0] + "\n";
+ definitions[num_definitions - 1].instances[0] + "\n";
TEST_EQ(parser.Parse(json.c_str()), true);
std::string jsongen;
parser.opts.indent_step = 0;
- auto result = GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
+ auto result =
+ GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
TEST_EQ(result, true);
if (jsongen != json) {
size_t len = std::min(json.length(), jsongen.length());
for (size_t i = 0; i < len; i++) {
if (json[i] != jsongen[i]) {
- i -= std::min(static_cast<size_t>(10), i); // show some context;
+ i -= std::min(static_cast<size_t>(10), i); // show some context;
size_t end = std::min(len, i + 20);
for (; i < end; i++)
TEST_OUTPUT_LINE("at %d: found \"%c\", expected \"%c\"\n",
TEST_NOTNULL(NULL);
}
+ // clang-format off
#ifdef FLATBUFFERS_TEST_VERBOSE
TEST_OUTPUT_LINE("%dk schema tested with %dk of json\n",
static_cast<int>(schema.length() / 1024),
static_cast<int>(json.length() / 1024));
#endif
+ // clang-format on
}
// Test that parser errors are actually generated.
TestError("table X { Y:int; } root_type X; { Y:", "string constant", true);
TestError("table X { Y:int; } root_type X; { \"Y\":1, }", "string constant",
true);
- TestError("struct X { Y:int; Z:int; } table W { V:X; } root_type W; "
- "{ V:{ Y:1 } }", "wrong number");
+ TestError(
+ "struct X { Y:int; Z:int; } table W { V:X; } root_type W; "
+ "{ V:{ Y:1 } }",
+ "wrong number");
TestError("enum E:byte { A } table X { Y:E; } root_type X; { Y:U }",
"unknown enum value");
TestError("table X { Y:byte; } root_type X; { Y:; }", "starting");
// Simple schema.
TEST_EQ(parser.Parse(std::string("table X { Y:" + std::string(type_name) +
- "; } root_type X;").c_str()), true);
+ "; } root_type X;")
+ .c_str()),
+ true);
TEST_EQ(parser.Parse(json), true);
auto root = flatbuffers::GetRoot<flatbuffers::Table>(
- parser.builder_.GetBufferPointer());
+ parser.builder_.GetBufferPointer());
return root->GetField<T>(flatbuffers::FieldIndexToOffset(0), 0);
}
// Additional parser testing not covered elsewhere.
void ValueTest() {
// Test scientific notation numbers.
- TEST_EQ(FloatCompare(TestValue<float>("{ Y:0.0314159e+2 }","float"),
- (float)3.14159), true);
+ TEST_EQ(FloatCompare(TestValue<float>("{ Y:0.0314159e+2 }", "float"),
+ (float)3.14159),
+ true);
// Test conversion functions.
- TEST_EQ(FloatCompare(TestValue<float>("{ Y:cos(rad(180)) }","float"), -1),
+ TEST_EQ(FloatCompare(TestValue<float>("{ Y:cos(rad(180)) }", "float"), -1),
true);
// Test negative hex constant.
- TEST_EQ(TestValue<int>("{ Y:-0x80 }","int"), -128);
+ TEST_EQ(TestValue<int>("{ Y:-0x80 }", "int"), -128);
// Make sure we do unsigned 64bit correctly.
- TEST_EQ(TestValue<uint64_t>("{ Y:12335089644688340133 }","ulong"),
- 12335089644688340133ULL);
+ TEST_EQ(TestValue<uint64_t>("{ Y:12335089644688340133 }", "ulong"),
+ 12335089644688340133ULL);
}
void NestedListTest() {
flatbuffers::Parser parser1;
TEST_EQ(parser1.Parse("struct Test { a:short; b:byte; } table T { F:[Test]; }"
"root_type T;"
- "{ F:[ [10,20], [30,40]] }"), true);
+ "{ F:[ [10,20], [30,40]] }"),
+ true);
}
void EnumStringsTest() {
flatbuffers::Parser parser1;
TEST_EQ(parser1.Parse("enum E:byte { A, B, C } table T { F:[E]; }"
"root_type T;"
- "{ F:[ A, B, \"C\", \"A B C\" ] }"), true);
+ "{ F:[ A, B, \"C\", \"A B C\" ] }"),
+ true);
flatbuffers::Parser parser2;
TEST_EQ(parser2.Parse("enum E:byte { A, B, C } table T { F:[int]; }"
"root_type T;"
- "{ F:[ \"E.C\", \"E.A E.B E.C\" ] }"), true);
+ "{ F:[ \"E.C\", \"E.A E.B E.C\" ] }"),
+ true);
}
void IntegerOutOfRangeTest() {
}
void IntegerBoundaryTest() {
- TEST_EQ(TestValue<int8_t>("{ Y:127 }","byte"), 127);
- TEST_EQ(TestValue<int8_t>("{ Y:-128 }","byte"), -128);
- TEST_EQ(TestValue<uint8_t>("{ Y:255 }","ubyte"), 255);
- TEST_EQ(TestValue<uint8_t>("{ Y:0 }","ubyte"), 0);
- TEST_EQ(TestValue<int16_t>("{ Y:32767 }","short"), 32767);
- TEST_EQ(TestValue<int16_t>("{ Y:-32768 }","short"), -32768);
- TEST_EQ(TestValue<uint16_t>("{ Y:65535 }","ushort"), 65535);
- TEST_EQ(TestValue<uint16_t>("{ Y:0 }","ushort"), 0);
- TEST_EQ(TestValue<int32_t>("{ Y:2147483647 }","int"), 2147483647);
- TEST_EQ(TestValue<int32_t>("{ Y:-2147483648 }","int"), (-2147483647 - 1));
- TEST_EQ(TestValue<uint32_t>("{ Y:4294967295 }","uint"), 4294967295);
- TEST_EQ(TestValue<uint32_t>("{ Y:0 }","uint"), 0);
- TEST_EQ(TestValue<int64_t>("{ Y:9223372036854775807 }","long"), 9223372036854775807);
- TEST_EQ(TestValue<int64_t>("{ Y:-9223372036854775808 }","long"), (-9223372036854775807 - 1));
- TEST_EQ(TestValue<uint64_t>("{ Y:18446744073709551615 }","ulong"), 18446744073709551615U);
- TEST_EQ(TestValue<uint64_t>("{ Y:0 }","ulong"), 0);
+ TEST_EQ(TestValue<int8_t>("{ Y:127 }", "byte"), 127);
+ TEST_EQ(TestValue<int8_t>("{ Y:-128 }", "byte"), -128);
+ TEST_EQ(TestValue<uint8_t>("{ Y:255 }", "ubyte"), 255);
+ TEST_EQ(TestValue<uint8_t>("{ Y:0 }", "ubyte"), 0);
+ TEST_EQ(TestValue<int16_t>("{ Y:32767 }", "short"), 32767);
+ TEST_EQ(TestValue<int16_t>("{ Y:-32768 }", "short"), -32768);
+ TEST_EQ(TestValue<uint16_t>("{ Y:65535 }", "ushort"), 65535);
+ TEST_EQ(TestValue<uint16_t>("{ Y:0 }", "ushort"), 0);
+ TEST_EQ(TestValue<int32_t>("{ Y:2147483647 }", "int"), 2147483647);
+ TEST_EQ(TestValue<int32_t>("{ Y:-2147483648 }", "int"), (-2147483647 - 1));
+ TEST_EQ(TestValue<uint32_t>("{ Y:4294967295 }", "uint"), 4294967295);
+ TEST_EQ(TestValue<uint32_t>("{ Y:0 }", "uint"), 0);
+ TEST_EQ(TestValue<int64_t>("{ Y:9223372036854775807 }", "long"),
+ 9223372036854775807);
+ TEST_EQ(TestValue<int64_t>("{ Y:-9223372036854775808 }", "long"),
+ (-9223372036854775807 - 1));
+ TEST_EQ(TestValue<uint64_t>("{ Y:18446744073709551615 }", "ulong"),
+ 18446744073709551615U);
+ TEST_EQ(TestValue<uint64_t>("{ Y:0 }", "ulong"), 0);
}
void UnicodeTest() {
flatbuffers::Parser parser;
- // Without setting allow_non_utf8 = true, we treat \x sequences as byte sequences
- // which are then validated as UTF-8.
+ // Without setting allow_non_utf8 = true, we treat \x sequences as byte
+ // sequences which are then validated as UTF-8.
TEST_EQ(parser.Parse("table T { F:string; }"
"root_type T;"
"{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
- "\\u5225\\u30B5\\u30A4\\u30C8\\xE2\\x82\\xAC\\u0080\\uD83D\\uDE0E\" }"),
+ "\\u5225\\u30B5\\u30A4\\u30C8\\xE2\\x82\\xAC\\u0080\\uD8"
+ "3D\\uDE0E\" }"),
true);
std::string jsongen;
parser.opts.indent_step = -1;
- auto result = GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
+ auto result =
+ GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
TEST_EQ(result, true);
TEST_EQ_STR(jsongen.c_str(),
- "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
- "\\u5225\\u30B5\\u30A4\\u30C8\\u20AC\\u0080\\uD83D\\uDE0E\"}");
+ "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
+ "\\u5225\\u30B5\\u30A4\\u30C8\\u20AC\\u0080\\uD83D\\uDE0E\"}");
}
void UnicodeTestAllowNonUTF8() {
flatbuffers::Parser parser;
parser.opts.allow_non_utf8 = true;
- TEST_EQ(parser.Parse("table T { F:string; }"
- "root_type T;"
- "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
- "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"), true);
+ TEST_EQ(
+ parser.Parse(
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
+ "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"),
+ true);
std::string jsongen;
parser.opts.indent_step = -1;
- auto result = GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
+ auto result =
+ GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
TEST_EQ(result, true);
- TEST_EQ_STR(jsongen.c_str(),
- "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
- "\\u5225\\u30B5\\u30A4\\u30C8\\u0001\\x80\\u0080\\uD83D\\uDE0E\"}");
+ TEST_EQ_STR(
+ jsongen.c_str(),
+ "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
+ "\\u5225\\u30B5\\u30A4\\u30C8\\u0001\\x80\\u0080\\uD83D\\uDE0E\"}");
}
void UnicodeTestGenerateTextFailsOnNonUTF8() {
flatbuffers::Parser parser;
- // Allow non-UTF-8 initially to model what happens when we load a binary flatbuffer from disk
- // which contains non-UTF-8 strings.
+ // Allow non-UTF-8 initially to model what happens when we load a binary
+ // flatbuffer from disk which contains non-UTF-8 strings.
parser.opts.allow_non_utf8 = true;
- TEST_EQ(parser.Parse("table T { F:string; }"
- "root_type T;"
- "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
- "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"), true);
+ TEST_EQ(
+ parser.Parse(
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
+ "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"),
+ true);
std::string jsongen;
parser.opts.indent_step = -1;
- // Now, disallow non-UTF-8 (the default behavior) so GenerateText indicates failure.
+ // Now, disallow non-UTF-8 (the default behavior) so GenerateText indicates
+ // failure.
parser.opts.allow_non_utf8 = false;
- auto result = GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
+ auto result =
+ GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
TEST_EQ(result, false);
}
void UnicodeSurrogatesTest() {
flatbuffers::Parser parser;
- TEST_EQ(
- parser.Parse(
- "table T { F:string (id: 0); }"
- "root_type T;"
- "{ F:\"\\uD83D\\uDCA9\"}"), true);
+ TEST_EQ(parser.Parse("table T { F:string (id: 0); }"
+ "root_type T;"
+ "{ F:\"\\uD83D\\uDCA9\"}"),
+ true);
auto root = flatbuffers::GetRoot<flatbuffers::Table>(
- parser.builder_.GetBufferPointer());
+ parser.builder_.GetBufferPointer());
auto string = root->GetPointer<flatbuffers::String *>(
- flatbuffers::FieldIndexToOffset(0));
+ flatbuffers::FieldIndexToOffset(0));
TEST_EQ_STR(string->c_str(), "\xF0\x9F\x92\xA9");
}
void UnicodeInvalidSurrogatesTest() {
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\\uD800\"}", "unpaired high surrogate");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\\uD800\"}",
+ "unpaired high surrogate");
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\\uD800abcd\"}", "unpaired high surrogate");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\\uD800abcd\"}",
+ "unpaired high surrogate");
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\\uD800\\n\"}", "unpaired high surrogate");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\\uD800\\n\"}",
+ "unpaired high surrogate");
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\\uD800\\uD800\"}", "multiple high surrogates");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\\uD800\\uD800\"}",
+ "multiple high surrogates");
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\\uDC00\"}", "unpaired low surrogate");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\\uDC00\"}",
+ "unpaired low surrogate");
}
void InvalidUTF8Test() {
// "1 byte" pattern, under min length of 2 bytes
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\x80\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\x80\"}",
+ "illegal UTF-8 sequence");
// 2 byte pattern, string too short
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xDF\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xDF\"}",
+ "illegal UTF-8 sequence");
// 3 byte pattern, string too short
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xEF\xBF\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xEF\xBF\"}",
+ "illegal UTF-8 sequence");
// 4 byte pattern, string too short
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xF7\xBF\xBF\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xF7\xBF\xBF\"}",
+ "illegal UTF-8 sequence");
// "5 byte" pattern, string too short
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xFB\xBF\xBF\xBF\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xFB\xBF\xBF\xBF\"}",
+ "illegal UTF-8 sequence");
// "6 byte" pattern, string too short
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xFD\xBF\xBF\xBF\xBF\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xFD\xBF\xBF\xBF\xBF\"}",
+ "illegal UTF-8 sequence");
// "7 byte" pattern, string too short
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\"}",
+ "illegal UTF-8 sequence");
// "5 byte" pattern, over max length of 4 bytes
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xFB\xBF\xBF\xBF\xBF\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xFB\xBF\xBF\xBF\xBF\"}",
+ "illegal UTF-8 sequence");
// "6 byte" pattern, over max length of 4 bytes
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xFD\xBF\xBF\xBF\xBF\xBF\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xFD\xBF\xBF\xBF\xBF\xBF\"}",
+ "illegal UTF-8 sequence");
// "7 byte" pattern, over max length of 4 bytes
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\xBF\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\xBF\"}",
+ "illegal UTF-8 sequence");
// Three invalid encodings for U+000A (\n, aka NEWLINE)
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xC0\x8A\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xC0\x8A\"}",
+ "illegal UTF-8 sequence");
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xE0\x80\x8A\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xE0\x80\x8A\"}",
+ "illegal UTF-8 sequence");
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xF0\x80\x80\x8A\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xF0\x80\x80\x8A\"}",
+ "illegal UTF-8 sequence");
// Two invalid encodings for U+00A9 (COPYRIGHT SYMBOL)
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xE0\x81\xA9\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xE0\x81\xA9\"}",
+ "illegal UTF-8 sequence");
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xF0\x80\x81\xA9\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xF0\x80\x81\xA9\"}",
+ "illegal UTF-8 sequence");
// Invalid encoding for U+20AC (EURO SYMBOL)
TestError(
- "table T { F:string; }"
- "root_type T;"
- "{ F:\"\xF0\x82\x82\xAC\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ "{ F:\"\xF0\x82\x82\xAC\"}",
+ "illegal UTF-8 sequence");
- // UTF-16 surrogate values between U+D800 and U+DFFF cannot be encoded in UTF-8
+ // UTF-16 surrogate values between U+D800 and U+DFFF cannot be encoded in
+ // UTF-8
TestError(
- "table T { F:string; }"
- "root_type T;"
- // U+10400 "encoded" as U+D801 U+DC00
- "{ F:\"\xED\xA0\x81\xED\xB0\x80\"}", "illegal UTF-8 sequence");
+ "table T { F:string; }"
+ "root_type T;"
+ // U+10400 "encoded" as U+D801 U+DC00
+ "{ F:\"\xED\xA0\x81\xED\xB0\x80\"}",
+ "illegal UTF-8 sequence");
}
void UnknownFieldsTest() {
"unknown_array: [ 1, 2, 3, 4],"
"unknown_object: { i: 10 },"
"\"unknown_object\": { \"i\": 10 },"
- "i:10}"), true);
+ "i:10}"),
+ true);
std::string jsongen;
parser.opts.indent_step = -1;
- auto result = GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
+ auto result =
+ GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
TEST_EQ(result, true);
TEST_EQ_STR(jsongen.c_str(), "{str: \"test\",i: 10}");
}
"union U { T }"
"table V { X:U; }"
"root_type V;"
- "{ X:{ A:1 }, X_type: T }"), true);
+ "{ X:{ A:1 }, X_type: T }"),
+ true);
// Unions must be parsable with prefixed namespace.
flatbuffers::Parser parser2;
TEST_EQ(parser2.Parse("namespace N; table A {} namespace; union U { N.A }"
"table B { e:U; } root_type B;"
- "{ e_type: N_A, e: {} }"), true);
+ "{ e_type: N_A, e: {} }"),
+ true);
}
void UnionVectorTest() {
// TODO: load a JSON file with such a vector when JSON support is ready.
std::string schemafile;
TEST_EQ(flatbuffers::LoadFile(
- (test_data_path + "union_vector/union_vector.fbs").c_str(), false,
- &schemafile), true);
+ (test_data_path + "union_vector/union_vector.fbs").c_str(), false,
+ &schemafile),
+ true);
// parse schema.
flatbuffers::IDLOptions idl_opts;
// create Movie.
const auto movie_offset =
- CreateMovie(fbb,
- Character_Rapunzel,
+ CreateMovie(fbb, Character_Rapunzel,
fbb.CreateStruct(Rapunzel(/*hair_length=*/6)).Union(),
- fbb.CreateVector(types),
- fbb.CreateVector(characters));
+ fbb.CreateVector(types), fbb.CreateVector(characters));
FinishMovieBuffer(fbb, movie_offset);
auto buf = fbb.GetBufferPointer();
TestMovie(repacked_movie);
- auto s = flatbuffers::FlatBufferToString(fbb.GetBufferPointer(),
- MovieTypeTable());
- TEST_EQ_STR(s.c_str(),
- "{ main_character_type: Rapunzel, main_character: { hair_length: 6 }, "
- "characters_type: [ Belle, MuLan, BookFan, Other, Unused ], "
- "characters: [ { books_read: 7 }, { sword_attack_damage: 5 }, "
- "{ books_read: 2 }, \"Other\", \"Unused\" ] }");
+ auto s =
+ flatbuffers::FlatBufferToString(fbb.GetBufferPointer(), MovieTypeTable());
+ TEST_EQ_STR(
+ s.c_str(),
+ "{ main_character_type: Rapunzel, main_character: { hair_length: 6 }, "
+ "characters_type: [ Belle, MuLan, BookFan, Other, Unused ], "
+ "characters: [ { books_read: 7 }, { sword_attack_damage: 5 }, "
+ "{ books_read: 2 }, \"Other\", \"Unused\" ] }");
}
void ConformTest() {
flatbuffers::Parser parser;
TEST_EQ(parser.Parse("table T { A:int; } enum E:byte { A }"), true);
- auto test_conform = [](flatbuffers::Parser &parser1,
- const char *test, const char *expected_err) {
+ auto test_conform = [](flatbuffers::Parser &parser1, const char *test,
+ const char *expected_err) {
flatbuffers::Parser parser2;
TEST_EQ(parser2.Parse(test), true);
auto err = parser2.ConformTo(parser1);
// omits `,`, `:` before `{` and a couple of other features.
flatbuffers::Parser parser;
parser.opts.protobuf_ascii_alike = true;
- TEST_EQ(parser.Parse(
- "table S { B:int; } table T { A:[int]; C:S; } root_type T;"), true);
+ TEST_EQ(
+ parser.Parse("table S { B:int; } table T { A:[int]; C:S; } root_type T;"),
+ true);
TEST_EQ(parser.Parse("{ A [1 2] C { B:2 }}"), true);
// Similarly, in text output, it should omit these.
std::string text;
- auto ok = flatbuffers::GenerateText(parser,
- parser.builder_.GetBufferPointer(),
- &text);
+ auto ok = flatbuffers::GenerateText(
+ parser, parser.builder_.GetBufferPointer(), &text);
TEST_EQ(ok, true);
TEST_EQ_STR(text.c_str(),
"{\n A [\n 1\n 2\n ]\n C {\n B: 2\n }\n}\n");
flexbuffers::BUILDER_FLAG_SHARE_KEYS_AND_STRINGS);
// Write the equivalent of:
- // { vec: [ -100, "Fred", 4.0, false ], bar: [ 1, 2, 3 ], bar3: [ 1, 2, 3 ], foo: 100, bool: true, mymap: { foo: "Fred" } }
+ // { vec: [ -100, "Fred", 4.0, false ], bar: [ 1, 2, 3 ], bar3: [ 1, 2, 3 ],
+ // foo: 100, bool: true, mymap: { foo: "Fred" } }
+ // clang-format off
#ifndef FLATBUFFERS_CPP98_STL
// It's possible to do this without std::function support as well.
slb.Map([&]() {
printf("%d ", flatbuffers::vector_data(slb.GetBuffer())[i]);
printf("\n");
#endif
+ // clang-format on
auto map = flexbuffers::GetRoot(slb.GetBuffer()).AsMap();
TEST_EQ(map.size(), 7);
TEST_EQ(vec[1].AsInt64(), 0); // Number parsing failed.
TEST_EQ(vec[2].AsDouble(), 4.0);
TEST_EQ(vec[2].AsString().IsTheEmptyString(), true); // Wrong Type.
- TEST_EQ_STR(vec[2].AsString().c_str(), ""); // This still works though.
+ TEST_EQ_STR(vec[2].AsString().c_str(), ""); // This still works though.
TEST_EQ_STR(vec[2].ToString().c_str(), "4.0"); // Or have it converted.
// Few tests for templated version of As.
auto blob = vec[3].AsBlob();
TEST_EQ(blob.size(), 1);
TEST_EQ(blob.data()[0], 77);
- TEST_EQ(vec[4].IsBool(), true); // Check if type is a bool
+ TEST_EQ(vec[4].IsBool(), true); // Check if type is a bool
TEST_EQ(vec[4].AsBool(), false); // Check if value is false
auto tvec = map["bar"].AsTypedVector();
TEST_EQ(tvec.size(), 3);
TEST_EQ(vec[2].MutateFloat(2.0f), true);
TEST_EQ(vec[2].AsFloat(), 2.0f);
TEST_EQ(vec[2].MutateFloat(3.14159), false); // Double does not fit in float.
- TEST_EQ(vec[4].AsBool(), false); // Is false before change
- TEST_EQ(vec[4].MutateBool(true), true); // Can change a bool
- TEST_EQ(vec[4].AsBool(), true); // Changed bool is now true
+ TEST_EQ(vec[4].AsBool(), false); // Is false before change
+ TEST_EQ(vec[4].MutateBool(true), true); // Can change a bool
+ TEST_EQ(vec[4].AsBool(), true); // Changed bool is now true
// Parse from JSON:
flatbuffers::Parser parser;
slb.Clear();
auto jsontest = "{ a: [ 123, 456.0 ], b: \"hello\", c: true, d: false }";
- TEST_EQ(parser.ParseFlexBuffer(jsontest, nullptr, &slb),
- true);
+ TEST_EQ(parser.ParseFlexBuffer(jsontest, nullptr, &slb), true);
auto jroot = flexbuffers::GetRoot(slb.GetBuffer());
auto jmap = jroot.AsMap();
auto jvec = jmap["a"].AsVector();
TEST_EQ(jvec[0].AsInt64(), 123);
TEST_EQ(jvec[1].AsDouble(), 456.0);
TEST_EQ_STR(jmap["b"].AsString().c_str(), "hello");
- TEST_EQ(jmap["c"].IsBool(), true); // Parsed correctly to a bool
- TEST_EQ(jmap["c"].AsBool(), true); // Parsed correctly to true
- TEST_EQ(jmap["d"].IsBool(), true); // Parsed correctly to a bool
- TEST_EQ(jmap["d"].AsBool(), false); // Parsed correctly to false
+ TEST_EQ(jmap["c"].IsBool(), true); // Parsed correctly to a bool
+ TEST_EQ(jmap["c"].AsBool(), true); // Parsed correctly to true
+ TEST_EQ(jmap["d"].IsBool(), true); // Parsed correctly to a bool
+ TEST_EQ(jmap["d"].AsBool(), false); // Parsed correctly to false
// And from FlexBuffer back to JSON:
auto jsonback = jroot.ToString();
TEST_EQ_STR(jsontest, jsonback.c_str());
}
-void TypeAliasesTest()
-{
+void TypeAliasesTest() {
flatbuffers::FlatBufferBuilder builder;
builder.Finish(CreateTypeAliases(
- builder,
- flatbuffers::numeric_limits<int8_t>::min(),
+ builder, flatbuffers::numeric_limits<int8_t>::min(),
flatbuffers::numeric_limits<uint8_t>::max(),
flatbuffers::numeric_limits<int16_t>::min(),
flatbuffers::numeric_limits<uint16_t>::max(),
flatbuffers::numeric_limits<int32_t>::min(),
flatbuffers::numeric_limits<uint32_t>::max(),
flatbuffers::numeric_limits<int64_t>::min(),
- flatbuffers::numeric_limits<uint64_t>::max(),
- 2.3f, 2.3));
+ flatbuffers::numeric_limits<uint64_t>::max(), 2.3f, 2.3));
auto p = builder.GetBufferPointer();
auto ta = flatbuffers::GetRoot<TypeAliases>(p);
}
void EndianSwapTest() {
- TEST_EQ(flatbuffers::EndianSwap(static_cast<int16_t>(0x1234)),
- 0x3412);
+ TEST_EQ(flatbuffers::EndianSwap(static_cast<int16_t>(0x1234)), 0x3412);
TEST_EQ(flatbuffers::EndianSwap(static_cast<int32_t>(0x12345678)),
0x78563412);
TEST_EQ(flatbuffers::EndianSwap(static_cast<int64_t>(0x1234567890ABCDEF)),
TEST_EQ(flatbuffers::EndianSwap(flatbuffers::EndianSwap(3.14f)), 3.14f);
}
-int main(int /*argc*/, const char * /*argv*/[]) {
+int main(int /*argc*/, const char * /*argv*/ []) {
+ // clang-format off
#if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && \
defined(_MSC_VER) && defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF
ParseProtoTest();
UnionVectorTest();
#endif
+ // clang-format on
FuzzTest1();
FuzzTest2();
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {number}
*/
swordAttackDamage():number {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
};
/**
* @returns {boolean}
*/
mutate_sword_attack_damage(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
+ var offset = this.bb.__offset(this.bb_pos, 4);
if (offset === 0) {
return false;
}
- this.bb!.writeInt32(this.bb_pos + offset, value);
+ this.bb.writeInt32(this.bb_pos + offset, value);
return true;
};
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {number}
*/
hairLength():number {
- return this.bb!.readInt32(this.bb_pos);
+ return this.bb.readInt32(this.bb_pos);
};
/**
* @returns {boolean}
*/
mutate_hair_length(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 0);
+ var offset = this.bb.__offset(this.bb_pos, 0);
if (offset === 0) {
return false;
}
- this.bb!.writeInt32(this.bb_pos + offset, value);
+ this.bb.writeInt32(this.bb_pos + offset, value);
return true;
};
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {number}
*/
booksRead():number {
- return this.bb!.readInt32(this.bb_pos);
+ return this.bb.readInt32(this.bb_pos);
};
/**
* @returns {boolean}
*/
mutate_books_read(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 0);
+ var offset = this.bb.__offset(this.bb_pos, 0);
if (offset === 0) {
return false;
}
- this.bb!.writeInt32(this.bb_pos + offset, value);
+ this.bb.writeInt32(this.bb_pos + offset, value);
return true;
};
/**
* @type {flatbuffers.ByteBuffer}
*/
- bb: flatbuffers.ByteBuffer|null = null;
+ bb: flatbuffers.ByteBuffer;
/**
* @type {number}
* @returns {Character}
*/
mainCharacterType():Character {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? /** @type {Character} */ (this.bb!.readUint8(this.bb_pos + offset)) : Character.NONE;
+ var offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? /** @type {Character} */ (this.bb.readUint8(this.bb_pos + offset)) : Character.NONE;
};
/**
* @returns {boolean}
*/
mutate_main_character_type(value:Character):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
+ var offset = this.bb.__offset(this.bb_pos, 4);
if (offset === 0) {
return false;
}
- this.bb!.writeUint8(this.bb_pos + offset, value);
+ this.bb.writeUint8(this.bb_pos + offset, value);
return true;
};
* @returns {?flatbuffers.Table}
*/
mainCharacter<T extends flatbuffers.Table>(obj:T):T|null {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null;
+ var offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
};
/**
* @returns {Character}
*/
charactersType(index: number):Character|null {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? /** @type {Character} */ (this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index)) : /** @type {Character} */ (0);
+ var offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? /** @type {Character} */ (this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index)) : /** @type {Character} */ (0);
};
/**
* @returns {number}
*/
charactersTypeLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**
* @returns {Uint8Array}
*/
charactersTypeArray():Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+ var offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
};
/**
* @returns {?flatbuffers.Table}
*/
characters<T extends flatbuffers.Table>(index: number, obj:T):T|null {
- var offset = this.bb!.__offset(this.bb_pos, 10);
- return offset ? this.bb!.__union(obj, this.bb!.__vector(this.bb_pos + offset) + index * 4) : null;
+ var offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.__union(obj, this.bb.__vector(this.bb_pos + offset) + index * 4) : null;
};
/**
* @returns {number}
*/
charactersLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 10);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+ var offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
};
/**