Commit 01189d7e authored by Vladimir Glavnyy's avatar Vladimir Glavnyy Committed by Wouter van Oortmerssen

[C++] Fix for printing of enum in case output_enum_identifiers=1. (#5706)

* Add test-case for testing of the future Color in json (output_enum_identifiers = true)

* Refactoring of idl_gen_text.cpp. Fix for printing of bit-enum with active output_enum_identifiers=1.

* Move  GenerateText implementation into class

* Remove unnecessary code from flatbuffers.h
parent c4b2b0a2
...@@ -443,6 +443,13 @@ template<typename T, uint16_t length> class Array { ...@@ -443,6 +443,13 @@ template<typename T, uint16_t length> class Array {
return_type operator[](uoffset_t i) const { return Get(i); } return_type operator[](uoffset_t i) const { return Get(i); }
// If this is a Vector of enums, T will be its storage type, not the enum
// type. This function makes it convenient to retrieve value with enum
// type E.
template<typename E> E GetEnum(uoffset_t i) const {
return static_cast<E>(Get(i));
}
const_iterator begin() const { return const_iterator(Data(), 0); } const_iterator begin() const { return const_iterator(Data(), 0); }
const_iterator end() const { return const_iterator(Data(), size()); } const_iterator end() const { return const_iterator(Data(), size()); }
...@@ -518,10 +525,12 @@ template<typename T, uint16_t length> class Array<Offset<T>, length> { ...@@ -518,10 +525,12 @@ template<typename T, uint16_t length> class Array<Offset<T>, length> {
static_assert(flatbuffers::is_same<T, void>::value, "unexpected type T"); static_assert(flatbuffers::is_same<T, void>::value, "unexpected type T");
public: public:
typedef const void* return_type;
const uint8_t *Data() const { return data_; } const uint8_t *Data() const { return data_; }
// Make idl_gen_text.cpp::PrintContainer happy. // Make idl_gen_text.cpp::PrintContainer happy.
const void *operator[](uoffset_t) const { return_type operator[](uoffset_t) const {
FLATBUFFERS_ASSERT(false); FLATBUFFERS_ASSERT(false);
return nullptr; return nullptr;
} }
......
...@@ -23,301 +23,337 @@ ...@@ -23,301 +23,337 @@
namespace flatbuffers { namespace flatbuffers {
static bool GenStruct(const StructDef &struct_def, const Table *table, struct PrintScalarTag {};
int indent, const IDLOptions &opts, std::string *_text); struct PrintPointerTag {};
template<typename T> struct PrintTag { typedef PrintScalarTag type; };
template<> struct PrintTag<const void *> { typedef PrintPointerTag type; };
// If indentation is less than 0, that indicates we don't want any newlines struct JsonPrinter {
// either. // If indentation is less than 0, that indicates we don't want any newlines
const char *NewLine(const IDLOptions &opts) { // either.
return opts.indent_step >= 0 ? "\n" : ""; void AddNewLine() {
} if (opts.indent_step >= 0) text += '\n';
}
int Indent(const IDLOptions &opts) { return std::max(opts.indent_step, 0); } void AddIndent(int ident) { text.append(ident, ' '); }
// Output an identifier with or without quotes depending on strictness. int Indent() const { return std::max(opts.indent_step, 0); }
void OutputIdentifier(const std::string &name, const IDLOptions &opts,
std::string *_text) {
std::string &text = *_text;
if (opts.strict_json) text += "\"";
text += name;
if (opts.strict_json) text += "\"";
}
// Print (and its template specialization below for pointers) generate text // Output an identifier with or without quotes depending on strictness.
// for a single FlatBuffer value into JSON format. void OutputIdentifier(const std::string &name) {
// The general case for scalars: if (opts.strict_json) text += '\"';
template<typename T> text += name;
bool Print(T val, Type type, int /*indent*/, const uint8_t * /*prev_val*/, if (opts.strict_json) text += '\"';
soffset_t /*vector_index*/, const IDLOptions &opts, }
std::string *_text) {
std::string &text = *_text; // Print (and its template specialization below for pointers) generate text
if (type.enum_def && opts.output_enum_identifiers) { // for a single FlatBuffer value into JSON format.
std::vector<EnumVal const *> enum_values; // The general case for scalars:
if (auto ev = type.enum_def->ReverseLookup(static_cast<int64_t>(val))) { template<typename T>
enum_values.push_back(ev); bool PrintScalar(T val, const Type &type, int /*indent*/) {
} else if (val && type.enum_def->attributes.Lookup("bit_flags")) { if (IsBool(type.base_type)) {
for (auto it = type.enum_def->Vals().begin(), text += val != 0 ? "true" : "false";
e = type.enum_def->Vals().end(); return true; // done
it != e; ++it) {
if ((*it)->GetAsUInt64() & static_cast<uint64_t>(val))
enum_values.push_back(*it);
}
} }
if (!enum_values.empty()) {
text += '\"'; if (opts.output_enum_identifiers && type.enum_def) {
for (auto it = enum_values.begin(), e = enum_values.end(); it != e; ++it) const auto &enum_def = *type.enum_def;
text += (*it)->name + ' '; if (auto ev = enum_def.ReverseLookup(static_cast<int64_t>(val))) {
text[text.length() - 1] = '\"'; text += '\"';
return true; text += ev->name;
text += '\"';
return true; // done
} else if (val && enum_def.attributes.Lookup("bit_flags")) {
const auto entry_len = text.length();
const auto u64 = static_cast<uint64_t>(val);
uint64_t mask = 0;
text += '\"';
for (auto it = enum_def.Vals().begin(), e = enum_def.Vals().end();
it != e; ++it) {
auto f = (*it)->GetAsUInt64();
if (f & u64) {
mask |= f;
text += (*it)->name;
text += ' ';
}
}
// Don't slice if (u64 != mask)
if (mask && (u64 == mask)) {
text[text.length() - 1] = '\"';
return true; // done
}
text.resize(entry_len); // restore
}
// print as numeric value
} }
}
if (type.base_type == BASE_TYPE_BOOL) {
text += val != 0 ? "true" : "false";
} else {
text += NumToString(val); text += NumToString(val);
return true;
} }
return true; void AddComma() {
} if (!opts.protobuf_ascii_alike) text += ',';
}
// Print a vector or an array of JSON values, comma seperated, wrapped in "[]". // Print a vector or an array of JSON values, comma seperated, wrapped in
template<typename T, typename Container> // "[]".
bool PrintContainer(const Container &c, size_t size, Type type, int indent, template<typename Container>
const uint8_t *prev_val, const IDLOptions &opts, bool PrintContainer(PrintScalarTag, const Container &c, size_t size,
std::string *_text) { const Type &type, int indent, const uint8_t *) {
std::string &text = *_text; const auto elem_indent = indent + Indent();
text += "["; text += '[';
text += NewLine(opts); AddNewLine();
for (uoffset_t i = 0; i < size; i++) { for (uoffset_t i = 0; i < size; i++) {
if (i) { if (i) {
if (!opts.protobuf_ascii_alike) text += ","; AddComma();
text += NewLine(opts); AddNewLine();
}
AddIndent(elem_indent);
if (!PrintScalar(c[i], type, elem_indent)) { return false; }
} }
text.append(indent + Indent(opts), ' '); AddNewLine();
if (IsStruct(type)) { AddIndent(indent);
if (!Print(reinterpret_cast<const void *>(c.Data() + text += ']';
i * type.struct_def->bytesize), return true;
type, indent + Indent(opts), nullptr, -1, opts, _text)) { }
return false;
// Print a vector or an array of JSON values, comma seperated, wrapped in
// "[]".
template<typename Container>
bool PrintContainer(PrintPointerTag, const Container &c, size_t size,
const Type &type, int indent, const uint8_t *prev_val) {
const auto is_struct = IsStruct(type);
const auto elem_indent = indent + Indent();
text += '[';
AddNewLine();
for (uoffset_t i = 0; i < size; i++) {
if (i) {
AddComma();
AddNewLine();
} }
} else { AddIndent(elem_indent);
if (!Print(c[i], type, indent + Indent(opts), prev_val, auto ptr = is_struct ? reinterpret_cast<const void *>(
static_cast<soffset_t>(i), opts, _text)) { c.Data() + type.struct_def->bytesize * i)
: c[i];
if (!PrintOffset(ptr, type, elem_indent, prev_val,
static_cast<soffset_t>(i))) {
return false; return false;
} }
} }
AddNewLine();
AddIndent(indent);
text += ']';
return true;
} }
text += NewLine(opts);
text.append(indent, ' ');
text += "]";
return true;
}
template<typename T> template<typename T>
bool PrintVector(const Vector<T> &v, Type type, int indent, bool PrintVector(const void *val, const Type &type, int indent,
const uint8_t *prev_val, const IDLOptions &opts, const uint8_t *prev_val) {
std::string *_text) { typedef Vector<T> Container;
return PrintContainer<T, Vector<T>>(v, v.size(), type, indent, prev_val, opts, typedef typename PrintTag<typename Container::return_type>::type tag;
_text); auto &vec = *reinterpret_cast<const Container *>(val);
} return PrintContainer<Container>(tag(), vec, vec.size(), type, indent,
prev_val);
}
// Print an array a sequence of JSON values, comma separated, wrapped in "[]". // Print an array a sequence of JSON values, comma separated, wrapped in "[]".
template<typename T> template<typename T>
bool PrintArray(const Array<T, 0xFFFF> &a, size_t size, Type type, int indent, bool PrintArray(const void *val, size_t size, const Type &type, int indent) {
const IDLOptions &opts, std::string *_text) { typedef Array<T, 0xFFFF> Container;
return PrintContainer<T, Array<T, 0xFFFF>>(a, size, type, indent, nullptr, typedef typename PrintTag<typename Container::return_type>::type tag;
opts, _text); auto &arr = *reinterpret_cast<const Container *>(val);
} return PrintContainer<Container>(tag(), arr, size, type, indent, nullptr);
}
// Specialization of Print above for pointer types. bool PrintOffset(const void *val, const Type &type, int indent,
template<> const uint8_t *prev_val, soffset_t vector_index) {
bool Print<const void *>(const void *val, Type type, int indent, switch (type.base_type) {
const uint8_t *prev_val, soffset_t vector_index, case BASE_TYPE_UNION: {
const IDLOptions &opts, std::string *_text) { // If this assert hits, you have an corrupt buffer, a union type field
switch (type.base_type) { // was not present or was out of range.
case BASE_TYPE_UNION: { FLATBUFFERS_ASSERT(prev_val);
// If this assert hits, you have an corrupt buffer, a union type field auto union_type_byte = *prev_val; // Always a uint8_t.
// was not present or was out of range. if (vector_index >= 0) {
FLATBUFFERS_ASSERT(prev_val); auto type_vec = reinterpret_cast<const Vector<uint8_t> *>(
auto union_type_byte = *prev_val; // Always a uint8_t. prev_val + ReadScalar<uoffset_t>(prev_val));
if (vector_index >= 0) { union_type_byte = type_vec->Get(static_cast<uoffset_t>(vector_index));
auto type_vec = reinterpret_cast<const Vector<uint8_t> *>( }
prev_val + ReadScalar<uoffset_t>(prev_val)); auto enum_val = type.enum_def->ReverseLookup(union_type_byte, true);
union_type_byte = type_vec->Get(static_cast<uoffset_t>(vector_index)); if (enum_val) {
return PrintOffset(val, enum_val->union_type, indent, nullptr, -1);
} else {
return false;
}
} }
auto enum_val = type.enum_def->ReverseLookup(union_type_byte, true); case BASE_TYPE_STRUCT:
if (enum_val) { return GenStruct(*type.struct_def, reinterpret_cast<const Table *>(val),
return Print<const void *>(val, enum_val->union_type, indent, nullptr, indent);
-1, opts, _text); case BASE_TYPE_STRING: {
} else { auto s = reinterpret_cast<const String *>(val);
return false; return EscapeString(s->c_str(), s->size(), &text, opts.allow_non_utf8,
opts.natural_utf8);
} }
} case BASE_TYPE_VECTOR: {
case BASE_TYPE_STRUCT: const auto vec_type = type.VectorType();
return GenStruct(*type.struct_def, reinterpret_cast<const Table *>(val), // Call PrintVector above specifically for each element type:
indent, opts, _text); // clang-format off
case BASE_TYPE_STRING: { switch (vec_type.base_type) {
auto s = reinterpret_cast<const String *>(val);
return EscapeString(s->c_str(), s->size(), _text, opts.allow_non_utf8,
opts.natural_utf8);
}
case BASE_TYPE_VECTOR: {
const auto vec_type = type.VectorType();
// Call PrintVector above specifically for each element type:
// clang-format off
switch (vec_type.base_type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \ #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
case BASE_TYPE_ ## ENUM: \ case BASE_TYPE_ ## ENUM: \
if (!PrintVector<CTYPE>( \ if (!PrintVector<CTYPE>( \
*reinterpret_cast<const Vector<CTYPE> *>(val), \ val, vec_type, indent, prev_val)) { \
vec_type, indent, prev_val, opts, _text)) { \
return false; \ return false; \
} \ } \
break; break;
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
}
// clang-format on
return true;
} }
// clang-format on case BASE_TYPE_ARRAY: {
return true; const auto vec_type = type.VectorType();
} // Call PrintArray above specifically for each element type:
case BASE_TYPE_ARRAY: { // clang-format off
const auto vec_type = type.VectorType(); switch (vec_type.base_type) {
// Call PrintArray above specifically for each element type:
// clang-format off
switch (vec_type.base_type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \ #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
case BASE_TYPE_ ## ENUM: \ case BASE_TYPE_ ## ENUM: \
if (!PrintArray<CTYPE>( \ if (!PrintArray<CTYPE>( \
*reinterpret_cast<const Array<CTYPE, 0xFFFF> *>(val), \ val, type.fixed_length, vec_type, indent)) { \
type.fixed_length, \ return false; \
vec_type, indent, opts, _text)) { \ } \
return false; \ break;
} \ FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
break; // Arrays of scalars or structs are only possible.
FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD) FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
// Arrays of scalars or structs are only possible.
FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
case BASE_TYPE_ARRAY: FLATBUFFERS_ASSERT(0); case BASE_TYPE_ARRAY: FLATBUFFERS_ASSERT(0);
}
// clang-format on
return true;
} }
// clang-format on default: FLATBUFFERS_ASSERT(0); return false;
return true;
} }
default: FLATBUFFERS_ASSERT(0); return false;
} }
}
template<typename T> static T GetFieldDefault(const FieldDef &fd) {
T val;
auto check = StringToNumber(fd.value.constant.c_str(), &val);
(void)check;
FLATBUFFERS_ASSERT(check);
return val;
}
// Generate text for a scalar field. template<typename T> static T GetFieldDefault(const FieldDef &fd) {
template<typename T> T val;
static bool GenField(const FieldDef &fd, const Table *table, bool fixed, auto check = StringToNumber(fd.value.constant.c_str(), &val);
const IDLOptions &opts, int indent, std::string *_text) { (void)check;
return Print( FLATBUFFERS_ASSERT(check);
fixed ? reinterpret_cast<const Struct *>(table)->GetField<T>( return val;
fd.value.offset) }
: table->GetField<T>(fd.value.offset, GetFieldDefault<T>(fd)),
fd.value.type, indent, nullptr, -1, opts, _text);
}
static bool GenStruct(const StructDef &struct_def, const Table *table, // Generate text for a scalar field.
int indent, const IDLOptions &opts, std::string *_text); template<typename T>
bool GenField(const FieldDef &fd, const Table *table, bool fixed,
int indent) {
return PrintScalar(
fixed ? reinterpret_cast<const Struct *>(table)->GetField<T>(
fd.value.offset)
: table->GetField<T>(fd.value.offset, GetFieldDefault<T>(fd)),
fd.value.type, indent);
}
// Generate text for non-scalar field. // Generate text for non-scalar field.
static bool GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed, bool GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
int indent, const uint8_t *prev_val, int indent, const uint8_t *prev_val) {
const IDLOptions &opts, std::string *_text) { const void *val = nullptr;
const void *val = nullptr; if (fixed) {
if (fixed) { // The only non-scalar fields in structs are structs or arrays.
// The only non-scalar fields in structs are structs or arrays. FLATBUFFERS_ASSERT(IsStruct(fd.value.type) || IsArray(fd.value.type));
FLATBUFFERS_ASSERT(IsStruct(fd.value.type) || IsArray(fd.value.type)); val = reinterpret_cast<const Struct *>(table)->GetStruct<const void *>(
val = reinterpret_cast<const Struct *>(table)->GetStruct<const void *>( fd.value.offset);
fd.value.offset); } else if (fd.flexbuffer) {
} else if (fd.flexbuffer) { auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset); auto root = flexbuffers::GetRoot(vec->data(), vec->size());
auto root = flexbuffers::GetRoot(vec->data(), vec->size()); root.ToString(true, opts.strict_json, text);
root.ToString(true, opts.strict_json, *_text); return true;
return true; } else if (fd.nested_flatbuffer) {
} else if (fd.nested_flatbuffer) { auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset); auto root = GetRoot<Table>(vec->data());
auto root = GetRoot<Table>(vec->data()); return GenStruct(*fd.nested_flatbuffer, root, indent);
return GenStruct(*fd.nested_flatbuffer, root, indent, opts, _text); } else {
} else { val = IsStruct(fd.value.type)
val = IsStruct(fd.value.type) ? table->GetStruct<const void *>(fd.value.offset)
? table->GetStruct<const void *>(fd.value.offset) : table->GetPointer<const void *>(fd.value.offset);
: table->GetPointer<const void *>(fd.value.offset); }
return PrintOffset(val, fd.value.type, indent, prev_val, -1);
} }
return Print(val, fd.value.type, indent, prev_val, -1, opts, _text);
}
// Generate text for a struct or table, values separated by commas, indented, // Generate text for a struct or table, values separated by commas, indented,
// and bracketed by "{}" // and bracketed by "{}"
static bool GenStruct(const StructDef &struct_def, const Table *table, bool GenStruct(const StructDef &struct_def, const Table *table, int indent) {
int indent, const IDLOptions &opts, std::string *_text) { text += '{';
std::string &text = *_text; int fieldout = 0;
text += "{"; const uint8_t *prev_val = nullptr;
int fieldout = 0; const auto elem_indent = indent + Indent();
const uint8_t *prev_val = nullptr; for (auto it = struct_def.fields.vec.begin();
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;
FieldDef &fd = **it; auto is_present = struct_def.fixed || table->CheckField(fd.value.offset);
auto is_present = struct_def.fixed || table->CheckField(fd.value.offset); auto output_anyway = opts.output_default_scalars_in_json &&
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 (is_present || output_anyway) { if (fieldout++) { AddComma(); }
if (fieldout++) { AddNewLine();
if (!opts.protobuf_ascii_alike) text += ","; AddIndent(elem_indent);
} OutputIdentifier(fd.name);
text += NewLine(opts); if (!opts.protobuf_ascii_alike ||
text.append(indent + Indent(opts), ' '); (fd.value.type.base_type != BASE_TYPE_STRUCT &&
OutputIdentifier(fd.name, opts, _text); fd.value.type.base_type != BASE_TYPE_VECTOR))
if (!opts.protobuf_ascii_alike || text += ':';
(fd.value.type.base_type != BASE_TYPE_STRUCT && text += ' ';
fd.value.type.base_type != BASE_TYPE_VECTOR))
text += ":";
text += " ";
switch (fd.value.type.base_type) {
// clang-format off // clang-format off
switch (fd.value.type.base_type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \ #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
case BASE_TYPE_ ## ENUM: \ case BASE_TYPE_ ## ENUM: \
if (!GenField<CTYPE>(fd, table, struct_def.fixed, \ if (!GenField<CTYPE>(fd, table, struct_def.fixed, elem_indent)) { \
opts, indent + Indent(opts), _text)) { \
return false; \ return false; \
} \ } \
break; break;
FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD) FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
// Generate drop-thru case statements for all pointer types: // Generate drop-thru case statements for all pointer types:
#define FLATBUFFERS_TD(ENUM, ...) \ #define FLATBUFFERS_TD(ENUM, ...) \
case BASE_TYPE_ ## ENUM: case BASE_TYPE_ ## ENUM:
FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD) FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
FLATBUFFERS_GEN_TYPE_ARRAY(FLATBUFFERS_TD) FLATBUFFERS_GEN_TYPE_ARRAY(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
if (!GenFieldOffset(fd, table, struct_def.fixed, indent + Indent(opts), if (!GenFieldOffset(fd, table, struct_def.fixed, elem_indent, prev_val)) {
prev_val, opts, _text)) { return false;
return false; }
}
break; break;
}
// clang-format on // clang-format on
} // Track prev val for use with union types.
// Track prev val for use with union types. if (struct_def.fixed) {
if (struct_def.fixed) { prev_val = reinterpret_cast<const uint8_t *>(table) + fd.value.offset;
prev_val = reinterpret_cast<const uint8_t *>(table) + fd.value.offset; } else {
} else { prev_val = table->GetAddressOf(fd.value.offset);
prev_val = table->GetAddressOf(fd.value.offset); }
} }
} }
AddNewLine();
AddIndent(indent);
text += '}';
return true;
}
JsonPrinter(const Parser &parser, std::string &dest)
: opts(parser.opts), text(dest) {
text.reserve(1024); // Reduce amount of inevitable reallocs.
} }
text += NewLine(opts);
text.append(indent, ' '); const IDLOptions &opts;
text += "}"; std::string &text;
};
static bool GenerateTextImpl(const Parser &parser, const Table *table,
const StructDef &struct_def, std::string *_text) {
JsonPrinter printer(parser, *_text);
if (!printer.GenStruct(struct_def, table, 0)) { return false; }
printer.AddNewLine();
return true; return true;
} }
...@@ -326,31 +362,21 @@ bool GenerateTextFromTable(const Parser &parser, const void *table, ...@@ -326,31 +362,21 @@ bool GenerateTextFromTable(const Parser &parser, const void *table,
const std::string &table_name, std::string *_text) { const std::string &table_name, std::string *_text) {
auto struct_def = parser.LookupStruct(table_name); auto struct_def = parser.LookupStruct(table_name);
if (struct_def == nullptr) { return false; } if (struct_def == nullptr) { return false; }
auto &text = *_text;
text.reserve(1024); // Reduce amount of inevitable reallocs.
auto root = static_cast<const Table *>(table); auto root = static_cast<const Table *>(table);
if (!GenStruct(*struct_def, root, 0, parser.opts, &text)) { return false; } return GenerateTextImpl(parser, root, *struct_def, _text);
text += NewLine(parser.opts);
return true;
} }
// Generate a text representation of a flatbuffer in JSON format. // Generate a text representation of a flatbuffer in JSON format.
bool GenerateText(const Parser &parser, const void *flatbuffer, bool GenerateText(const Parser &parser, const void *flatbuffer,
std::string *_text) { std::string *_text) {
std::string &text = *_text;
FLATBUFFERS_ASSERT(parser.root_struct_def_); // call SetRootType() FLATBUFFERS_ASSERT(parser.root_struct_def_); // call SetRootType()
text.reserve(1024); // Reduce amount of inevitable reallocs.
auto root = parser.opts.size_prefixed ? GetSizePrefixedRoot<Table>(flatbuffer) auto root = parser.opts.size_prefixed ? GetSizePrefixedRoot<Table>(flatbuffer)
: GetRoot<Table>(flatbuffer); : GetRoot<Table>(flatbuffer);
if (!GenStruct(*parser.root_struct_def_, root, 0, parser.opts, _text)) { return GenerateTextImpl(parser, root, *parser.root_struct_def_, _text);
return false;
}
text += NewLine(parser.opts);
return true;
} }
std::string TextFileName(const std::string &path, static std::string TextFileName(const std::string &path,
const std::string &file_name) { const std::string &file_name) {
return path + file_name + ".json"; return path + file_name + ".json";
} }
......
...@@ -650,6 +650,19 @@ void JsonEnumsTest() { ...@@ -650,6 +650,19 @@ void JsonEnumsTest() {
auto result = GenerateText(parser, builder.GetBufferPointer(), &jsongen); auto result = GenerateText(parser, builder.GetBufferPointer(), &jsongen);
TEST_EQ(result, true); TEST_EQ(result, true);
TEST_EQ(std::string::npos != jsongen.find("color: \"Red Blue\""), true); TEST_EQ(std::string::npos != jsongen.find("color: \"Red Blue\""), true);
// Test forward compatibility with 'output_enum_identifiers = true'.
// Current Color doesn't have '(1u << 2)' field, let's add it.
builder.Clear();
std::string future_json;
auto future_name = builder.CreateString("future bitflag_enum");
MonsterBuilder future_color(builder);
future_color.add_name(future_name);
future_color.add_color(
static_cast<Color>((1u << 2) | Color_Blue | Color_Red));
FinishMonsterBuffer(builder, future_color.Finish());
result = GenerateText(parser, builder.GetBufferPointer(), &future_json);
TEST_EQ(result, true);
TEST_EQ(std::string::npos != future_json.find("color: 13"), true);
} }
#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) #if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
......
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