Made all C++ files clang-formatted.

Also added missing generated files.

Change-Id: Ifd22a643a08e3f2edfce92812ed57b87fc0e1875
parent 5d9930aa
---
Language: Cpp
BasedOnStyle: Google
Language: Cpp
BasedOnStyle: Google
DerivePointerAlignment: false
PointerAlignment: Right
IndentPPDirectives: AfterHash
Cpp11BracedListStyle: false
AlwaysBreakTemplateDeclarations: false
AllowShortCaseLabelsOnASingleLine: true
SpaceAfterTemplateKeyword: false
AllowShortBlocksOnASingleLine: true
...
......@@ -40,8 +40,8 @@
#include <vector>
#ifndef GRPC_CUSTOM_STRING
#include <string>
#define GRPC_CUSTOM_STRING std::string
# include <string>
# define GRPC_CUSTOM_STRING std::string
#endif
namespace grpc {
......
......@@ -18,46 +18,48 @@
#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:
......@@ -90,7 +92,7 @@ void RunServer() {
server_instance->Wait();
}
int main(int /*argc*/, const char * /*argv*/[]) {
int main(int /*argc*/, const char * /*argv*/ []) {
// Launch server.
std::thread server_thread(RunServer);
......@@ -103,7 +105,6 @@ int main(int /*argc*/, const char * /*argv*/[]) {
grpc::InsecureChannelCredentials());
auto stub = MyGame::Example::MonsterStorage::NewStub(channel);
flatbuffers::grpc::MessageBuilder fbb;
{
grpc::ClientContext context;
......@@ -138,7 +139,7 @@ int main(int /*argc*/, const char * /*argv*/[]) {
}
}
#if !FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION
#if !FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION
{
// Test that an invalid request errors out correctly
grpc::ClientContext context;
......@@ -149,9 +150,10 @@ int main(int /*argc*/, const char * /*argv*/[]) {
// 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
......
......@@ -49,7 +49,7 @@ class CodeWriter {
// 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;
}
......@@ -71,8 +71,7 @@ class BaseGenerator {
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:
......@@ -128,8 +127,7 @@ struct CommentConfig {
};
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
......
This diff is collapsed.
......@@ -14,15 +14,15 @@
* 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 {
......@@ -49,12 +49,10 @@ class FlatCompiler {
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.
......@@ -65,21 +63,20 @@ class 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 &params) : 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;
......@@ -91,7 +88,6 @@ class FlatCompiler {
InitParams params_;
};
} // namespace flatbuffers
#endif // FLATC_H_
This diff is collapsed.
......@@ -30,13 +30,12 @@ namespace grpc {
// `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;
......@@ -137,7 +136,7 @@ namespace detail {
struct SliceAllocatorMember {
SliceAllocator slice_allocator_;
};
}
} // namespace detail
// MessageBuilder is a gRPC-specific FlatBufferBuilder that uses SliceAllocator
// to allocate gRPC buffers.
......@@ -145,7 +144,7 @@ class MessageBuilder : private detail::SliceAllocatorMember,
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;
......@@ -155,8 +154,7 @@ class MessageBuilder : private detail::SliceAllocatorMember,
// 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
......@@ -178,8 +176,7 @@ class MessageBuilder : private detail::SliceAllocatorMember,
return msg;
}
template <class T>
Message<T> ReleaseMessage() {
template<class T> Message<T> ReleaseMessage() {
Message<T> msg = GetMessage<T>();
Reset();
return msg;
......@@ -194,8 +191,7 @@ class MessageBuilder : private detail::SliceAllocatorMember,
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) {
......@@ -237,19 +233,19 @@ class SerializationTraits<flatbuffers::grpc::Message<T>> {
*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_
......@@ -24,26 +24,22 @@
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;
......@@ -52,8 +48,7 @@ T HashFnv1(const char *input) {
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);
......@@ -62,21 +57,20 @@ T HashFnv1a(const char *input) {
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> },
};
......
This diff is collapsed.
......@@ -65,8 +65,7 @@ struct IterationVisitor {
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() {}
};
......@@ -75,34 +74,24 @@ inline size_t InlineSize(ElementaryType type, const TypeTable *type_table) {
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;
}
}
......@@ -118,7 +107,7 @@ inline int32_t LookupEnum(int32_t enum_val, const int32_t *values,
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];
}
......@@ -126,13 +115,11 @@ template<typename T> const char *EnumName(T tval, const TypeTable *type_table) {
}
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);
......@@ -200,9 +187,7 @@ inline void IterateValue(ElementaryType type, 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);
......@@ -211,10 +196,10 @@ inline void IterateValue(ElementaryType type, const uint8_t *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: {
......@@ -225,17 +210,14 @@ inline void IterateValue(ElementaryType type, const uint8_t *val,
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;
}
......@@ -257,14 +239,12 @@ inline void IterateObject(const uint8_t *obj, const TypeTable *type_table,
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];
}
......@@ -310,24 +290,29 @@ struct ToStringVisitor : public IterationVisitor {
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);
}
......
This diff is collapsed.
......@@ -37,18 +37,16 @@ class Registry {
// 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;
......@@ -82,38 +80,36 @@ class Registry {
// 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_;
......
......@@ -17,6 +17,8 @@
#ifndef FLATBUFFERS_STL_EMULATION_H_
#define FLATBUFFERS_STL_EMULATION_H_
// clang-format off
#include <string>
#include <type_traits>
#include <vector>
......
......@@ -17,32 +17,31 @@
#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.
......@@ -61,18 +60,18 @@ template<> inline std::string NumToString<unsigned char>(unsigned char t) {
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.
......@@ -100,10 +99,7 @@ template<> inline std::string NumToString<float>(float t) {
// 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();
}
......@@ -111,21 +107,25 @@ inline std::string IntToStringHex(int i, int xdigits) {
// 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,
......@@ -134,9 +134,8 @@ typedef bool (*FileExistsFunction)(const char *filename);
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);
......@@ -239,16 +238,19 @@ inline std::string PosixPath(const char *path) {
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
......@@ -262,6 +264,7 @@ inline std::string AbsolutePath(const std::string &filepath) {
? abs_path
: filepath;
#endif // FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
// clang-format on
}
// To and from UTF-8 unicode conversion functions
......@@ -279,7 +282,7 @@ inline int ToUTF8(uint32_t ucc, std::string *out) {
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);
......@@ -309,9 +312,7 @@ inline int FromUTF8(const char **in) {
if ((**in << len) & 0x80) return -1; // Bit after leading 1's must be 0.
if (!len) return *(*in)++;
// UTF-8 encoded values with a length are between 2 and 4 bytes.
if (len < 2 || len > 4) {
return -1;
}
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++) {
......@@ -321,28 +322,20 @@ inline int FromUTF8(const char **in) {
}
// 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;
......@@ -421,7 +414,8 @@ inline bool EscapeString(const char *s, size_t length, std::string *_text,
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;
......
......@@ -14,13 +14,13 @@
* 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;
......@@ -53,7 +53,7 @@ int main(int /*argc*/, const char * /*argv*/[]) {
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.
......@@ -83,8 +83,8 @@ int main(int /*argc*/, const char * /*argv*/[]) {
(void)inv;
// Get and test the `weapons` FlatBuffers's `vector`.
std::string expected_weapon_names[] = {"Sword", "Axe"};
short expected_weapon_damages[] = {3, 5};
std::string expected_weapon_names[] = { "Sword", "Axe" };
short expected_weapon_damages[] = { 3, 5 };
auto weps = monster->weapons();
for (unsigned int i = 0; i < weps->size(); i++) {
assert(weps->Get(i)->name()->str() == expected_weapon_names[i]);
......@@ -95,11 +95,10 @@ int main(int /*argc*/, const char * /*argv*/[]) {
// 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");
}
......@@ -17,13 +17,13 @@
#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;
......
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
......@@ -20,24 +20,19 @@
#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);
......@@ -119,7 +114,6 @@ std::string BaseGenerator::WrapInNameSpace(const Namespace *ns,
return qualified_name + name;
}
std::string BaseGenerator::WrapInNameSpace(const Definition &def) const {
return WrapInNameSpace(def.defined_namespace, def.name);
}
......@@ -150,12 +144,12 @@ void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
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) {
......@@ -166,5 +160,5 @@ void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
} // namespace flatbuffers
#if defined(_MSC_VER)
#pragma warning(pop)
# pragma warning(pop)
#endif
This diff is collapsed.
......@@ -19,26 +19,17 @@
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);
}
......@@ -46,61 +37,43 @@ int main(int argc, const char *argv[]) {
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;
......
......@@ -14,20 +14,16 @@
* 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");
......@@ -50,7 +46,7 @@ int main(int argc, char* argv[]) {
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);
......@@ -66,15 +62,21 @@ int main(int argc, char* argv[]) {
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) {
......@@ -90,8 +92,7 @@ int main(int argc, char* argv[]) {
else if (hash_function64)
ss << hash_function64(arg);
if (annotate)
ss << " /* \"" << arg << "\" */";
if (annotate) ss << " /* \"" << arg << "\" */";
ss << "\n";
......@@ -100,4 +101,3 @@ int main(int argc, char* argv[]) {
}
return 0;
}
This diff is collapsed.
......@@ -16,10 +16,10 @@
// 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 {
......@@ -27,16 +27,15 @@ static std::string GenType(const Type &type, bool underlying = false) {
switch (type.base_type) {
case BASE_TYPE_STRUCT:
return type.struct_def->defined_namespace->GetFullyQualifiedName(
type.struct_def->name);
case BASE_TYPE_VECTOR:
return "[" + GenType(type.VectorType()) + "]";
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];
}
}
}
......@@ -47,7 +46,7 @@ static void GenNameSpace(const Namespace &name_space, std::string *_schema,
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;
}
......@@ -69,6 +68,7 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
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();
......@@ -82,18 +82,19 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
}
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";
......@@ -101,14 +102,14 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
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, " ");
......@@ -123,12 +124,10 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
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
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/*
* 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 {
......@@ -30,8 +30,7 @@ namespace jsons {
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:
......@@ -41,16 +40,13 @@ std::string GenNativeType(BaseType type) {
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) {
......@@ -60,7 +56,7 @@ template <class T> std::string GenFullName(const T *enum_def) {
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) + "\"";
}
......@@ -93,11 +89,10 @@ std::string GenType(const Type &type) {
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(",");
......@@ -106,10 +101,8 @@ std::string GenType(const Type &type) {
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));
}
}
......@@ -130,35 +123,29 @@ class JsonSchemaGenerator : public BaseGenerator {
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) {
......@@ -169,10 +156,9 @@ class JsonSchemaGenerator : public BaseGenerator {
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
......@@ -184,8 +170,7 @@ class JsonSchemaGenerator : public BaseGenerator {
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(", ");
......@@ -196,9 +181,7 @@ class JsonSchemaGenerator : public BaseGenerator {
}
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
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -57,6 +57,7 @@ bool FileExists(const char *name) {
}
bool DirExists(const char *name) {
// clang-format off
#ifdef _WIN32
#define flatbuffers_stat _stat
#define FLATBUFFERS_S_IFDIR _S_IFDIR
......@@ -64,6 +65,7 @@ bool DirExists(const char *name) {
#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;
......@@ -78,8 +80,8 @@ LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function) {
FileExistsFunction SetFileExistsFunction(
FileExistsFunction file_exists_function) {
FileExistsFunction previous_function = g_file_exists_function;
g_file_exists_function = file_exists_function ?
file_exists_function : FileExistsRaw;
g_file_exists_function =
file_exists_function ? file_exists_function : FileExistsRaw;
return previous_function;
}
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment