2 * Copyright 2014 Google Inc. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "flatbuffers/flatbuffers.h"
18 #include "flatbuffers/idl.h"
19 #include "flatbuffers/minireflect.h"
20 #include "flatbuffers/registry.h"
21 #include "flatbuffers/util.h"
24 #ifdef FLATBUFFERS_CPP98_STL
25 #include "flatbuffers/stl_emulation.h"
27 using flatbuffers::unique_ptr;
32 #include "monster_test_generated.h"
33 #include "namespace_test/namespace_test1_generated.h"
34 #include "namespace_test/namespace_test2_generated.h"
35 #include "union_vector/union_vector_generated.h"
36 #include "monster_extra_generated.h"
37 #if !defined(_MSC_VER) || _MSC_VER >= 1700
38 # include "arrays_test_generated.h"
40 #include "test_assert.h"
42 #include "flatbuffers/flexbuffers.h"
45 // Check that char* and uint8_t* are interoperable types.
46 // The reinterpret_cast<> between the pointers are used to simplify data loading.
47 static_assert(flatbuffers::is_same<uint8_t, char>::value ||
48 flatbuffers::is_same<uint8_t, unsigned char>::value,
49 "unexpected uint8_t type");
51 #if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
52 // Ensure IEEE-754 support if tests of floats with NaN/Inf will run.
53 static_assert(std::numeric_limits<float>::is_iec559 &&
54 std::numeric_limits<double>::is_iec559,
55 "IEC-559 (IEEE-754) standard required");
59 // Shortcuts for the infinity.
60 static const auto infinityf = std::numeric_limits<float>::infinity();
61 static const auto infinityd = std::numeric_limits<double>::infinity();
63 using namespace MyGame::Example;
65 void FlatBufferBuilderTest();
67 // Include simple random number generator to ensure results will be the
68 // same cross platform.
69 // http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator
70 uint32_t lcg_seed = 48271;
72 return lcg_seed = (static_cast<uint64_t>(lcg_seed) * 279470273UL) % 4294967291UL;
74 void lcg_reset() { lcg_seed = 48271; }
76 std::string test_data_path =
77 #ifdef BAZEL_TEST_DATA_PATH
78 "../com_github_google_flatbuffers/tests/";
83 // example of how to build up a serialized buffer algorithmically:
84 flatbuffers::DetachedBuffer CreateFlatBufferTest(std::string &buffer) {
85 flatbuffers::FlatBufferBuilder builder;
87 auto vec = Vec3(1, 2, 3, 0, Color_Red, Test(10, 20));
89 auto name = builder.CreateString("MyMonster");
91 unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
92 auto inventory = builder.CreateVector(inv_data, 10);
94 // Alternatively, create the vector first, and fill in data later:
95 // unsigned char *inv_buf = nullptr;
96 // auto inventory = builder.CreateUninitializedVector<unsigned char>(
98 // memcpy(inv_buf, inv_data, 10);
100 Test tests[] = { Test(10, 20), Test(30, 40) };
101 auto testv = builder.CreateVectorOfStructs(tests, 2);
104 #ifndef FLATBUFFERS_CPP98_STL
105 // Create a vector of structures from a lambda.
106 auto testv2 = builder.CreateVectorOfStructs<Test>(
107 2, [&](size_t i, Test* s) -> void {
111 // Create a vector of structures using a plain old C++ function.
112 auto testv2 = builder.CreateVectorOfStructs<Test>(
113 2, [](size_t i, Test* s, void *state) -> void {
114 *s = (reinterpret_cast<Test*>(state))[i];
116 #endif // FLATBUFFERS_CPP98_STL
119 // create monster with very few fields set:
120 // (same functionality as CreateMonster below, but sets fields manually)
121 flatbuffers::Offset<Monster> mlocs[3];
122 auto fred = builder.CreateString("Fred");
123 auto barney = builder.CreateString("Barney");
124 auto wilma = builder.CreateString("Wilma");
125 MonsterBuilder mb1(builder);
127 mlocs[0] = mb1.Finish();
128 MonsterBuilder mb2(builder);
129 mb2.add_name(barney);
131 mlocs[1] = mb2.Finish();
132 MonsterBuilder mb3(builder);
134 mlocs[2] = mb3.Finish();
136 // Create an array of strings. Also test string pooling, and lambdas.
138 builder.CreateVector<flatbuffers::Offset<flatbuffers::String>>(
140 [](size_t i, flatbuffers::FlatBufferBuilder *b)
141 -> flatbuffers::Offset<flatbuffers::String> {
142 static const char *names[] = { "bob", "fred", "bob", "fred" };
143 return b->CreateSharedString(names[i]);
147 // Creating vectors of strings in one convenient call.
148 std::vector<std::string> names2;
149 names2.push_back("jane");
150 names2.push_back("mary");
151 auto vecofstrings2 = builder.CreateVectorOfStrings(names2);
153 // Create an array of sorted tables, can be used with binary search when read:
154 auto vecoftables = builder.CreateVectorOfSortedTables(mlocs, 3);
156 // Create an array of sorted structs,
157 // can be used with binary search when read:
158 std::vector<Ability> abilities;
159 abilities.push_back(Ability(4, 40));
160 abilities.push_back(Ability(3, 30));
161 abilities.push_back(Ability(2, 20));
162 abilities.push_back(Ability(1, 10));
163 auto vecofstructs = builder.CreateVectorOfSortedStructs(&abilities);
165 // Create a nested FlatBuffer.
166 // Nested FlatBuffers are stored in a ubyte vector, which can be convenient
167 // since they can be memcpy'd around much easier than other FlatBuffer
168 // values. They have little overhead compared to storing the table directly.
169 // As a test, create a mostly empty Monster buffer:
170 flatbuffers::FlatBufferBuilder nested_builder;
171 auto nmloc = CreateMonster(nested_builder, nullptr, 0, 0,
172 nested_builder.CreateString("NestedMonster"));
173 FinishMonsterBuffer(nested_builder, nmloc);
174 // Now we can store the buffer in the parent. Note that by default, vectors
175 // are only aligned to their elements or size field, so in this case if the
176 // buffer contains 64-bit elements, they may not be correctly aligned. We fix
178 builder.ForceVectorAlignment(nested_builder.GetSize(), sizeof(uint8_t),
179 nested_builder.GetBufferMinAlignment());
180 // If for whatever reason you don't have the nested_builder available, you
181 // can substitute flatbuffers::largest_scalar_t (64-bit) for the alignment, or
182 // the largest force_align value in your schema if you're using it.
183 auto nested_flatbuffer_vector = builder.CreateVector(
184 nested_builder.GetBufferPointer(), nested_builder.GetSize());
186 // Test a nested FlexBuffer:
187 flexbuffers::Builder flexbuild;
190 auto flex = builder.CreateVector(flexbuild.GetBuffer());
192 // Test vector of enums.
193 Color colors[] = { Color_Blue, Color_Green };
194 // We use this special creation function because we have an array of
195 // pre-C++11 (enum class) enums whose size likely is int, yet its declared
196 // type in the schema is byte.
197 auto vecofcolors = builder.CreateVectorScalarCast<uint8_t, Color>(colors, 2);
199 // shortcut for creating monster with all fields set:
200 auto mloc = CreateMonster(builder, &vec, 150, 80, name, inventory, Color_Blue,
201 Any_Monster, mlocs[1].Union(), // Store a union.
202 testv, vecofstrings, vecoftables, 0,
203 nested_flatbuffer_vector, 0, false, 0, 0, 0, 0, 0,
204 0, 0, 0, 0, 3.14159f, 3.0f, 0.0f, vecofstrings2,
205 vecofstructs, flex, testv2, 0, 0, 0, 0, 0, 0, 0, 0,
206 0, 0, 0, AnyUniqueAliases_NONE, 0,
207 AnyAmbiguousAliases_NONE, 0, vecofcolors);
209 FinishMonsterBuffer(builder, mloc);
212 #ifdef FLATBUFFERS_TEST_VERBOSE
213 // print byte data for debugging:
214 auto p = builder.GetBufferPointer();
215 for (flatbuffers::uoffset_t i = 0; i < builder.GetSize(); i++)
220 // return the buffer for the caller to use.
222 reinterpret_cast<const char *>(builder.GetBufferPointer());
223 buffer.assign(bufferpointer, bufferpointer + builder.GetSize());
225 return builder.Release();
228 // example of accessing a buffer loaded in memory:
229 void AccessFlatBufferTest(const uint8_t *flatbuf, size_t length,
230 bool pooled = true) {
231 // First, verify the buffers integrity (optional)
232 flatbuffers::Verifier verifier(flatbuf, length);
233 TEST_EQ(VerifyMonsterBuffer(verifier), true);
236 #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
237 std::vector<uint8_t> test_buff;
238 test_buff.resize(length * 2);
239 std::memcpy(&test_buff[0], flatbuf, length);
240 std::memcpy(&test_buff[length], flatbuf, length);
242 flatbuffers::Verifier verifier1(&test_buff[0], length);
243 TEST_EQ(VerifyMonsterBuffer(verifier1), true);
244 TEST_EQ(verifier1.GetComputedSize(), length);
246 flatbuffers::Verifier verifier2(&test_buff[length], length);
247 TEST_EQ(VerifyMonsterBuffer(verifier2), true);
248 TEST_EQ(verifier2.GetComputedSize(), length);
252 TEST_EQ(strcmp(MonsterIdentifier(), "MONS"), 0);
253 TEST_EQ(MonsterBufferHasIdentifier(flatbuf), true);
254 TEST_EQ(strcmp(MonsterExtension(), "mon"), 0);
256 // Access the buffer from the root.
257 auto monster = GetMonster(flatbuf);
259 TEST_EQ(monster->hp(), 80);
260 TEST_EQ(monster->mana(), 150); // default
261 TEST_EQ_STR(monster->name()->c_str(), "MyMonster");
262 // Can't access the following field, it is deprecated in the schema,
263 // which means accessors are not generated:
264 // monster.friendly()
266 auto pos = monster->pos();
268 TEST_EQ(pos->z(), 3);
269 TEST_EQ(pos->test3().a(), 10);
270 TEST_EQ(pos->test3().b(), 20);
272 auto inventory = monster->inventory();
273 TEST_EQ(VectorLength(inventory), 10UL); // Works even if inventory is null.
274 TEST_NOTNULL(inventory);
275 unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
276 // Check compatibilty of iterators with STL.
277 std::vector<unsigned char> inv_vec(inventory->begin(), inventory->end());
279 for (auto it = inventory->begin(); it != inventory->end(); ++it, ++n) {
280 auto indx = it - inventory->begin();
281 TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check.
282 TEST_EQ(*it, inv_data[indx]);
284 TEST_EQ(n, inv_vec.size());
287 for (auto it = inventory->cbegin(); it != inventory->cend(); ++it, ++n) {
288 auto indx = it - inventory->cbegin();
289 TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check.
290 TEST_EQ(*it, inv_data[indx]);
292 TEST_EQ(n, inv_vec.size());
295 for (auto it = inventory->rbegin(); it != inventory->rend(); ++it, ++n) {
296 auto indx = inventory->rend() - it - 1;
297 TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check.
298 TEST_EQ(*it, inv_data[indx]);
300 TEST_EQ(n, inv_vec.size());
303 for (auto it = inventory->crbegin(); it != inventory->crend(); ++it, ++n) {
304 auto indx = inventory->crend() - it - 1;
305 TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check.
306 TEST_EQ(*it, inv_data[indx]);
308 TEST_EQ(n, inv_vec.size());
310 TEST_EQ(monster->color(), Color_Blue);
312 // Example of accessing a union:
313 TEST_EQ(monster->test_type(), Any_Monster); // First make sure which it is.
314 auto monster2 = reinterpret_cast<const Monster *>(monster->test());
315 TEST_NOTNULL(monster2);
316 TEST_EQ_STR(monster2->name()->c_str(), "Fred");
318 // Example of accessing a vector of strings:
319 auto vecofstrings = monster->testarrayofstring();
320 TEST_EQ(vecofstrings->size(), 4U);
321 TEST_EQ_STR(vecofstrings->Get(0)->c_str(), "bob");
322 TEST_EQ_STR(vecofstrings->Get(1)->c_str(), "fred");
324 // These should have pointer equality because of string pooling.
325 TEST_EQ(vecofstrings->Get(0)->c_str(), vecofstrings->Get(2)->c_str());
326 TEST_EQ(vecofstrings->Get(1)->c_str(), vecofstrings->Get(3)->c_str());
329 auto vecofstrings2 = monster->testarrayofstring2();
331 TEST_EQ(vecofstrings2->size(), 2U);
332 TEST_EQ_STR(vecofstrings2->Get(0)->c_str(), "jane");
333 TEST_EQ_STR(vecofstrings2->Get(1)->c_str(), "mary");
336 // Example of accessing a vector of tables:
337 auto vecoftables = monster->testarrayoftables();
338 TEST_EQ(vecoftables->size(), 3U);
339 for (auto it = vecoftables->begin(); it != vecoftables->end(); ++it)
340 TEST_EQ(strlen(it->name()->c_str()) >= 4, true);
341 TEST_EQ_STR(vecoftables->Get(0)->name()->c_str(), "Barney");
342 TEST_EQ(vecoftables->Get(0)->hp(), 1000);
343 TEST_EQ_STR(vecoftables->Get(1)->name()->c_str(), "Fred");
344 TEST_EQ_STR(vecoftables->Get(2)->name()->c_str(), "Wilma");
345 TEST_NOTNULL(vecoftables->LookupByKey("Barney"));
346 TEST_NOTNULL(vecoftables->LookupByKey("Fred"));
347 TEST_NOTNULL(vecoftables->LookupByKey("Wilma"));
349 // Test accessing a vector of sorted structs
350 auto vecofstructs = monster->testarrayofsortedstruct();
351 if (vecofstructs) { // not filled in monster_test.bfbs
352 for (flatbuffers::uoffset_t i = 0; i < vecofstructs->size() - 1; i++) {
353 auto left = vecofstructs->Get(i);
354 auto right = vecofstructs->Get(i + 1);
355 TEST_EQ(true, (left->KeyCompareLessThan(right)));
357 TEST_NOTNULL(vecofstructs->LookupByKey(3));
358 TEST_EQ(static_cast<const Ability *>(nullptr),
359 vecofstructs->LookupByKey(5));
362 // Test nested FlatBuffers if available:
363 auto nested_buffer = monster->testnestedflatbuffer();
365 // nested_buffer is a vector of bytes you can memcpy. However, if you
366 // actually want to access the nested data, this is a convenient
367 // accessor that directly gives you the root table:
368 auto nested_monster = monster->testnestedflatbuffer_nested_root();
369 TEST_EQ_STR(nested_monster->name()->c_str(), "NestedMonster");
372 // Test flexbuffer if available:
373 auto flex = monster->flex();
374 // flex is a vector of bytes you can memcpy etc.
375 TEST_EQ(flex->size(), 4); // Encoded FlexBuffer bytes.
376 // However, if you actually want to access the nested data, this is a
377 // convenient accessor that directly gives you the root value:
378 TEST_EQ(monster->flex_flexbuffer_root().AsInt16(), 1234);
380 // Test vector of enums:
381 auto colors = monster->vector_of_enums();
383 TEST_EQ(colors->size(), 2);
384 TEST_EQ(colors->Get(0), Color_Blue);
385 TEST_EQ(colors->Get(1), Color_Green);
388 // Since Flatbuffers uses explicit mechanisms to override the default
389 // compiler alignment, double check that the compiler indeed obeys them:
390 // (Test consists of a short and byte):
391 TEST_EQ(flatbuffers::AlignOf<Test>(), 2UL);
392 TEST_EQ(sizeof(Test), 4UL);
394 const flatbuffers::Vector<const Test *> *tests_array[] = {
398 for (size_t i = 0; i < sizeof(tests_array) / sizeof(tests_array[0]); ++i) {
399 auto tests = tests_array[i];
401 auto test_0 = tests->Get(0);
402 auto test_1 = tests->Get(1);
403 TEST_EQ(test_0->a(), 10);
404 TEST_EQ(test_0->b(), 20);
405 TEST_EQ(test_1->a(), 30);
406 TEST_EQ(test_1->b(), 40);
407 for (auto it = tests->begin(); it != tests->end(); ++it) {
408 TEST_EQ(it->a() == 10 || it->a() == 30, true); // Just testing iterators.
412 // Checking for presence of fields:
413 TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_HP), true);
414 TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_MANA), false);
416 // Obtaining a buffer from a root:
417 TEST_EQ(GetBufferStartFromRootPointer(monster), flatbuf);
420 // Change a FlatBuffer in-place, after it has been constructed.
421 void MutateFlatBuffersTest(uint8_t *flatbuf, std::size_t length) {
422 // Get non-const pointer to root.
423 auto monster = GetMutableMonster(flatbuf);
425 // Each of these tests mutates, then tests, then set back to the original,
426 // so we can test that the buffer in the end still passes our original test.
427 auto hp_ok = monster->mutate_hp(10);
428 TEST_EQ(hp_ok, true); // Field was present.
429 TEST_EQ(monster->hp(), 10);
430 // Mutate to default value
431 auto hp_ok_default = monster->mutate_hp(100);
432 TEST_EQ(hp_ok_default, true); // Field was present.
433 TEST_EQ(monster->hp(), 100);
434 // Test that mutate to default above keeps field valid for further mutations
435 auto hp_ok_2 = monster->mutate_hp(20);
436 TEST_EQ(hp_ok_2, true);
437 TEST_EQ(monster->hp(), 20);
438 monster->mutate_hp(80);
440 // Monster originally at 150 mana (default value)
441 auto mana_default_ok = monster->mutate_mana(150); // Mutate to default value.
442 TEST_EQ(mana_default_ok,
443 true); // Mutation should succeed, because default value.
444 TEST_EQ(monster->mana(), 150);
445 auto mana_ok = monster->mutate_mana(10);
446 TEST_EQ(mana_ok, false); // Field was NOT present, because default value.
447 TEST_EQ(monster->mana(), 150);
450 auto pos = monster->mutable_pos();
451 auto test3 = pos->mutable_test3(); // Struct inside a struct.
452 test3.mutate_a(50); // Struct fields never fail.
453 TEST_EQ(test3.a(), 50);
457 auto inventory = monster->mutable_inventory();
458 inventory->Mutate(9, 100);
459 TEST_EQ(inventory->Get(9), 100);
460 inventory->Mutate(9, 9);
462 auto tables = monster->mutable_testarrayoftables();
463 auto first = tables->GetMutableObject(0);
464 TEST_EQ(first->hp(), 1000);
466 TEST_EQ(first->hp(), 0);
467 first->mutate_hp(1000);
469 // Run the verifier and the regular test to make sure we didn't trample on
471 AccessFlatBufferTest(flatbuf, length);
474 // Unpack a FlatBuffer into objects.
475 void ObjectFlatBuffersTest(uint8_t *flatbuf) {
476 // Optional: we can specify resolver and rehasher functions to turn hashed
477 // strings into object pointers and back, to implement remote references
479 auto resolver = flatbuffers::resolver_function_t(
480 [](void **pointer_adr, flatbuffers::hash_value_t hash) {
483 // Don't actually do anything, leave variable null.
485 auto rehasher = flatbuffers::rehasher_function_t(
486 [](void *pointer) -> flatbuffers::hash_value_t {
491 // Turn a buffer into C++ objects.
492 auto monster1 = UnPackMonster(flatbuf, &resolver);
494 // Re-serialize the data.
495 flatbuffers::FlatBufferBuilder fbb1;
496 fbb1.Finish(CreateMonster(fbb1, monster1.get(), &rehasher),
497 MonsterIdentifier());
499 // Unpack again, and re-serialize again.
500 auto monster2 = UnPackMonster(fbb1.GetBufferPointer(), &resolver);
501 flatbuffers::FlatBufferBuilder fbb2;
502 fbb2.Finish(CreateMonster(fbb2, monster2.get(), &rehasher),
503 MonsterIdentifier());
505 // Now we've gone full round-trip, the two buffers should match.
506 auto len1 = fbb1.GetSize();
507 auto len2 = fbb2.GetSize();
509 TEST_EQ(memcmp(fbb1.GetBufferPointer(), fbb2.GetBufferPointer(), len1), 0);
511 // Test it with the original buffer test to make sure all data survived.
512 AccessFlatBufferTest(fbb2.GetBufferPointer(), len2, false);
514 // Test accessing fields, similar to AccessFlatBufferTest above.
515 TEST_EQ(monster2->hp, 80);
516 TEST_EQ(monster2->mana, 150); // default
517 TEST_EQ_STR(monster2->name.c_str(), "MyMonster");
519 auto &pos = monster2->pos;
521 TEST_EQ(pos->z(), 3);
522 TEST_EQ(pos->test3().a(), 10);
523 TEST_EQ(pos->test3().b(), 20);
525 auto &inventory = monster2->inventory;
526 TEST_EQ(inventory.size(), 10UL);
527 unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
528 for (auto it = inventory.begin(); it != inventory.end(); ++it)
529 TEST_EQ(*it, inv_data[it - inventory.begin()]);
531 TEST_EQ(monster2->color, Color_Blue);
533 auto monster3 = monster2->test.AsMonster();
534 TEST_NOTNULL(monster3);
535 TEST_EQ_STR(monster3->name.c_str(), "Fred");
537 auto &vecofstrings = monster2->testarrayofstring;
538 TEST_EQ(vecofstrings.size(), 4U);
539 TEST_EQ_STR(vecofstrings[0].c_str(), "bob");
540 TEST_EQ_STR(vecofstrings[1].c_str(), "fred");
542 auto &vecofstrings2 = monster2->testarrayofstring2;
543 TEST_EQ(vecofstrings2.size(), 2U);
544 TEST_EQ_STR(vecofstrings2[0].c_str(), "jane");
545 TEST_EQ_STR(vecofstrings2[1].c_str(), "mary");
547 auto &vecoftables = monster2->testarrayoftables;
548 TEST_EQ(vecoftables.size(), 3U);
549 TEST_EQ_STR(vecoftables[0]->name.c_str(), "Barney");
550 TEST_EQ(vecoftables[0]->hp, 1000);
551 TEST_EQ_STR(vecoftables[1]->name.c_str(), "Fred");
552 TEST_EQ_STR(vecoftables[2]->name.c_str(), "Wilma");
554 auto &tests = monster2->test4;
555 TEST_EQ(tests[0].a(), 10);
556 TEST_EQ(tests[0].b(), 20);
557 TEST_EQ(tests[1].a(), 30);
558 TEST_EQ(tests[1].b(), 40);
561 // Prefix a FlatBuffer with a size field.
562 void SizePrefixedTest() {
563 // Create size prefixed buffer.
564 flatbuffers::FlatBufferBuilder fbb;
565 FinishSizePrefixedMonsterBuffer(
567 CreateMonster(fbb, 0, 200, 300, fbb.CreateString("bob")));
570 flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize());
571 TEST_EQ(VerifySizePrefixedMonsterBuffer(verifier), true);
574 auto m = GetSizePrefixedMonster(fbb.GetBufferPointer());
575 TEST_EQ(m->mana(), 200);
576 TEST_EQ(m->hp(), 300);
577 TEST_EQ_STR(m->name()->c_str(), "bob");
580 void TriviallyCopyableTest() {
582 #if __GNUG__ && __GNUC__ < 5
583 TEST_EQ(__has_trivial_copy(Vec3), true);
585 #if __cplusplus >= 201103L
586 TEST_EQ(std::is_trivially_copyable<Vec3>::value, true);
592 // Check stringify of an default enum value to json
593 void JsonDefaultTest() {
594 // load FlatBuffer schema (.fbs) from disk
595 std::string schemafile;
596 TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
597 false, &schemafile), true);
598 // parse schema first, so we can use it to parse the data after
599 flatbuffers::Parser parser;
600 auto include_test_path =
601 flatbuffers::ConCatPathFileName(test_data_path, "include_test");
602 const char *include_directories[] = { test_data_path.c_str(),
603 include_test_path.c_str(), nullptr };
605 TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
606 // create incomplete monster and store to json
607 parser.opts.output_default_scalars_in_json = true;
608 parser.opts.output_enum_identifiers = true;
609 flatbuffers::FlatBufferBuilder builder;
610 auto name = builder.CreateString("default_enum");
611 MonsterBuilder color_monster(builder);
612 color_monster.add_name(name);
613 FinishMonsterBuffer(builder, color_monster.Finish());
615 auto result = GenerateText(parser, builder.GetBufferPointer(), &jsongen);
616 TEST_EQ(result, true);
617 // default value of the "color" field is Blue
618 TEST_EQ(std::string::npos != jsongen.find("color: \"Blue\""), true);
619 // default value of the "testf" field is 3.14159
620 TEST_EQ(std::string::npos != jsongen.find("testf: 3.14159"), true);
623 void JsonEnumsTest() {
624 // load FlatBuffer schema (.fbs) from disk
625 std::string schemafile;
626 TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
629 // parse schema first, so we can use it to parse the data after
630 flatbuffers::Parser parser;
631 auto include_test_path =
632 flatbuffers::ConCatPathFileName(test_data_path, "include_test");
633 const char *include_directories[] = { test_data_path.c_str(),
634 include_test_path.c_str(), nullptr };
635 parser.opts.output_enum_identifiers = true;
636 TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
637 flatbuffers::FlatBufferBuilder builder;
638 auto name = builder.CreateString("bitflag_enum");
639 MonsterBuilder color_monster(builder);
640 color_monster.add_name(name);
641 color_monster.add_color(Color(Color_Blue | Color_Red));
642 FinishMonsterBuffer(builder, color_monster.Finish());
644 auto result = GenerateText(parser, builder.GetBufferPointer(), &jsongen);
645 TEST_EQ(result, true);
646 TEST_EQ(std::string::npos != jsongen.find("color: \"Red Blue\""), true);
649 #if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
650 // The IEEE-754 quiet_NaN is not simple binary constant.
651 // All binary NaN bit strings have all the bits of the biased exponent field E
652 // set to 1. A quiet NaN bit string should be encoded with the first bit d[1]
653 // of the trailing significand field T being 1 (d[0] is implicit bit).
654 // It is assumed that endianness of floating-point is same as integer.
655 template<typename T, typename U, U qnan_base> bool is_quiet_nan_impl(T v) {
656 static_assert(sizeof(T) == sizeof(U), "unexpected");
658 std::memcpy(&b, &v, sizeof(T));
659 return ((b & qnan_base) == qnan_base);
661 static bool is_quiet_nan(float v) {
662 return is_quiet_nan_impl<float, uint32_t, 0x7FC00000u>(v);
664 static bool is_quiet_nan(double v) {
665 return is_quiet_nan_impl<double, uint64_t, 0x7FF8000000000000ul>(v);
668 void TestMonsterExtraFloats() {
669 TEST_EQ(is_quiet_nan(1.0), false);
670 TEST_EQ(is_quiet_nan(infinityd), false);
671 TEST_EQ(is_quiet_nan(-infinityf), false);
672 TEST_EQ(is_quiet_nan(std::numeric_limits<float>::quiet_NaN()), true);
673 TEST_EQ(is_quiet_nan(std::numeric_limits<double>::quiet_NaN()), true);
675 using namespace flatbuffers;
676 using namespace MyGame;
677 // Load FlatBuffer schema (.fbs) from disk.
678 std::string schemafile;
679 TEST_EQ(LoadFile((test_data_path + "monster_extra.fbs").c_str(), false,
682 // Parse schema first, so we can use it to parse the data after.
684 auto include_test_path = ConCatPathFileName(test_data_path, "include_test");
685 const char *include_directories[] = { test_data_path.c_str(),
686 include_test_path.c_str(), nullptr };
687 TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
688 // Create empty extra and store to json.
689 parser.opts.output_default_scalars_in_json = true;
690 parser.opts.output_enum_identifiers = true;
691 FlatBufferBuilder builder;
692 const auto def_root = MonsterExtraBuilder(builder).Finish();
693 FinishMonsterExtraBuffer(builder, def_root);
694 const auto def_obj = builder.GetBufferPointer();
695 const auto def_extra = GetMonsterExtra(def_obj);
696 TEST_NOTNULL(def_extra);
697 TEST_EQ(is_quiet_nan(def_extra->f0()), true);
698 TEST_EQ(is_quiet_nan(def_extra->f1()), true);
699 TEST_EQ(def_extra->f2(), +infinityf);
700 TEST_EQ(def_extra->f3(), -infinityf);
701 TEST_EQ(is_quiet_nan(def_extra->d0()), true);
702 TEST_EQ(is_quiet_nan(def_extra->d1()), true);
703 TEST_EQ(def_extra->d2(), +infinityd);
704 TEST_EQ(def_extra->d3(), -infinityd);
706 auto result = GenerateText(parser, def_obj, &jsongen);
707 TEST_EQ(result, true);
708 // Check expected default values.
709 TEST_EQ(std::string::npos != jsongen.find("f0: nan"), true);
710 TEST_EQ(std::string::npos != jsongen.find("f1: nan"), true);
711 TEST_EQ(std::string::npos != jsongen.find("f2: inf"), true);
712 TEST_EQ(std::string::npos != jsongen.find("f3: -inf"), true);
713 TEST_EQ(std::string::npos != jsongen.find("d0: nan"), true);
714 TEST_EQ(std::string::npos != jsongen.find("d1: nan"), true);
715 TEST_EQ(std::string::npos != jsongen.find("d2: inf"), true);
716 TEST_EQ(std::string::npos != jsongen.find("d3: -inf"), true);
717 // Parse 'mosterdata_extra.json'.
718 const auto extra_base = test_data_path + "monsterdata_extra";
720 TEST_EQ(LoadFile((extra_base + ".json").c_str(), false, &jsongen), true);
721 TEST_EQ(parser.Parse(jsongen.c_str()), true);
722 const auto test_file = parser.builder_.GetBufferPointer();
723 const auto test_size = parser.builder_.GetSize();
724 Verifier verifier(test_file, test_size);
725 TEST_ASSERT(VerifyMonsterExtraBuffer(verifier));
726 const auto extra = GetMonsterExtra(test_file);
728 TEST_EQ(is_quiet_nan(extra->f0()), true);
729 TEST_EQ(is_quiet_nan(extra->f1()), true);
730 TEST_EQ(extra->f2(), +infinityf);
731 TEST_EQ(extra->f3(), -infinityf);
732 TEST_EQ(is_quiet_nan(extra->d0()), true);
733 TEST_EQ(extra->d1(), +infinityd);
734 TEST_EQ(extra->d2(), -infinityd);
735 TEST_EQ(is_quiet_nan(extra->d3()), true);
736 TEST_NOTNULL(extra->fvec());
737 TEST_EQ(extra->fvec()->size(), 4);
738 TEST_EQ(extra->fvec()->Get(0), 1.0f);
739 TEST_EQ(extra->fvec()->Get(1), -infinityf);
740 TEST_EQ(extra->fvec()->Get(2), +infinityf);
741 TEST_EQ(is_quiet_nan(extra->fvec()->Get(3)), true);
742 TEST_NOTNULL(extra->dvec());
743 TEST_EQ(extra->dvec()->size(), 4);
744 TEST_EQ(extra->dvec()->Get(0), 2.0);
745 TEST_EQ(extra->dvec()->Get(1), +infinityd);
746 TEST_EQ(extra->dvec()->Get(2), -infinityd);
747 TEST_EQ(is_quiet_nan(extra->dvec()->Get(3)), true);
750 void TestMonsterExtraFloats() {}
753 // example of parsing text straight into a buffer, and generating
754 // text back from it:
755 void ParseAndGenerateTextTest(bool binary) {
756 // load FlatBuffer schema (.fbs) and JSON from disk
757 std::string schemafile;
758 std::string jsonfile;
759 TEST_EQ(flatbuffers::LoadFile(
760 (test_data_path + "monster_test." + (binary ? "bfbs" : "fbs"))
762 binary, &schemafile),
764 TEST_EQ(flatbuffers::LoadFile(
765 (test_data_path + "monsterdata_test.golden").c_str(), false,
769 auto include_test_path =
770 flatbuffers::ConCatPathFileName(test_data_path, "include_test");
771 const char *include_directories[] = { test_data_path.c_str(),
772 include_test_path.c_str(), nullptr };
774 // parse schema first, so we can use it to parse the data after
775 flatbuffers::Parser parser;
777 flatbuffers::Verifier verifier(
778 reinterpret_cast<const uint8_t *>(schemafile.c_str()),
780 TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
781 //auto schema = reflection::GetSchema(schemafile.c_str());
782 TEST_EQ(parser.Deserialize((const uint8_t *)schemafile.c_str(), schemafile.size()), true);
784 TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
786 TEST_EQ(parser.Parse(jsonfile.c_str(), include_directories), true);
788 // here, parser.builder_ contains a binary buffer that is the parsed data.
790 // First, verify it, just in case:
791 flatbuffers::Verifier verifier(parser.builder_.GetBufferPointer(),
792 parser.builder_.GetSize());
793 TEST_EQ(VerifyMonsterBuffer(verifier), true);
795 AccessFlatBufferTest(parser.builder_.GetBufferPointer(),
796 parser.builder_.GetSize(), false);
798 // to ensure it is correct, we now generate text back from the binary,
799 // and compare the two:
802 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
803 TEST_EQ(result, true);
804 TEST_EQ_STR(jsongen.c_str(), jsonfile.c_str());
806 // We can also do the above using the convenient Registry that knows about
807 // a set of file_identifiers mapped to schemas.
808 flatbuffers::Registry registry;
809 // Make sure schemas can find their includes.
810 registry.AddIncludeDirectory(test_data_path.c_str());
811 registry.AddIncludeDirectory(include_test_path.c_str());
812 // Call this with many schemas if possible.
813 registry.Register(MonsterIdentifier(),
814 (test_data_path + "monster_test.fbs").c_str());
815 // Now we got this set up, we can parse by just specifying the identifier,
816 // the correct schema will be loaded on the fly:
817 auto buf = registry.TextToFlatBuffer(jsonfile.c_str(), MonsterIdentifier());
818 // If this fails, check registry.lasterror_.
819 TEST_NOTNULL(buf.data());
820 // Test the buffer, to be sure:
821 AccessFlatBufferTest(buf.data(), buf.size(), false);
822 // We can use the registry to turn this back into text, in this case it
823 // will get the file_identifier from the binary:
825 auto ok = registry.FlatBufferToText(buf.data(), buf.size(), &text);
826 // If this fails, check registry.lasterror_.
828 TEST_EQ_STR(text.c_str(), jsonfile.c_str());
830 // Generate text for UTF-8 strings without escapes.
831 std::string jsonfile_utf8;
832 TEST_EQ(flatbuffers::LoadFile((test_data_path + "unicode_test.json").c_str(),
833 false, &jsonfile_utf8),
835 TEST_EQ(parser.Parse(jsonfile_utf8.c_str(), include_directories), true);
836 // To ensure it is correct, generate utf-8 text back from the binary.
837 std::string jsongen_utf8;
838 // request natural printing for utf-8 strings
839 parser.opts.natural_utf8 = true;
840 parser.opts.strict_json = true;
842 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen_utf8),
844 TEST_EQ_STR(jsongen_utf8.c_str(), jsonfile_utf8.c_str());
847 void ReflectionTest(uint8_t *flatbuf, size_t length) {
848 // Load a binary schema.
849 std::string bfbsfile;
850 TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.bfbs").c_str(),
854 // Verify it, just in case:
855 flatbuffers::Verifier verifier(
856 reinterpret_cast<const uint8_t *>(bfbsfile.c_str()), bfbsfile.length());
857 TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
859 // Make sure the schema is what we expect it to be.
860 auto &schema = *reflection::GetSchema(bfbsfile.c_str());
861 auto root_table = schema.root_table();
862 TEST_EQ_STR(root_table->name()->c_str(), "MyGame.Example.Monster");
863 auto fields = root_table->fields();
864 auto hp_field_ptr = fields->LookupByKey("hp");
865 TEST_NOTNULL(hp_field_ptr);
866 auto &hp_field = *hp_field_ptr;
867 TEST_EQ_STR(hp_field.name()->c_str(), "hp");
868 TEST_EQ(hp_field.id(), 2);
869 TEST_EQ(hp_field.type()->base_type(), reflection::Short);
870 auto friendly_field_ptr = fields->LookupByKey("friendly");
871 TEST_NOTNULL(friendly_field_ptr);
872 TEST_NOTNULL(friendly_field_ptr->attributes());
873 TEST_NOTNULL(friendly_field_ptr->attributes()->LookupByKey("priority"));
875 // Make sure the table index is what we expect it to be.
876 auto pos_field_ptr = fields->LookupByKey("pos");
877 TEST_NOTNULL(pos_field_ptr);
878 TEST_EQ(pos_field_ptr->type()->base_type(), reflection::Obj);
879 auto pos_table_ptr = schema.objects()->Get(pos_field_ptr->type()->index());
880 TEST_NOTNULL(pos_table_ptr);
881 TEST_EQ_STR(pos_table_ptr->name()->c_str(), "MyGame.Example.Vec3");
883 // Now use it to dynamically access a buffer.
884 auto &root = *flatbuffers::GetAnyRoot(flatbuf);
886 // Verify the buffer first using reflection based verification
887 TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), flatbuf, length),
890 auto hp = flatbuffers::GetFieldI<uint16_t>(root, hp_field);
893 // Rather than needing to know the type, we can also get the value of
894 // any field as an int64_t/double/string, regardless of what it actually is.
895 auto hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
896 TEST_EQ(hp_int64, 80);
897 auto hp_double = flatbuffers::GetAnyFieldF(root, hp_field);
898 TEST_EQ(hp_double, 80.0);
899 auto hp_string = flatbuffers::GetAnyFieldS(root, hp_field, &schema);
900 TEST_EQ_STR(hp_string.c_str(), "80");
902 // Get struct field through reflection
903 auto pos_struct = flatbuffers::GetFieldStruct(root, *pos_field_ptr);
904 TEST_NOTNULL(pos_struct);
905 TEST_EQ(flatbuffers::GetAnyFieldF(*pos_struct,
906 *pos_table_ptr->fields()->LookupByKey("z")),
909 auto test3_field = pos_table_ptr->fields()->LookupByKey("test3");
910 auto test3_struct = flatbuffers::GetFieldStruct(*pos_struct, *test3_field);
911 TEST_NOTNULL(test3_struct);
912 auto test3_object = schema.objects()->Get(test3_field->type()->index());
914 TEST_EQ(flatbuffers::GetAnyFieldF(*test3_struct,
915 *test3_object->fields()->LookupByKey("a")),
918 // We can also modify it.
919 flatbuffers::SetField<uint16_t>(&root, hp_field, 200);
920 hp = flatbuffers::GetFieldI<uint16_t>(root, hp_field);
923 // We can also set fields generically:
924 flatbuffers::SetAnyFieldI(&root, hp_field, 300);
925 hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
926 TEST_EQ(hp_int64, 300);
927 flatbuffers::SetAnyFieldF(&root, hp_field, 300.5);
928 hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
929 TEST_EQ(hp_int64, 300);
930 flatbuffers::SetAnyFieldS(&root, hp_field, "300");
931 hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
932 TEST_EQ(hp_int64, 300);
934 // Test buffer is valid after the modifications
935 TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), flatbuf, length),
938 // Reset it, for further tests.
939 flatbuffers::SetField<uint16_t>(&root, hp_field, 80);
941 // More advanced functionality: changing the size of items in-line!
942 // First we put the FlatBuffer inside an std::vector.
943 std::vector<uint8_t> resizingbuf(flatbuf, flatbuf + length);
944 // Find the field we want to modify.
945 auto &name_field = *fields->LookupByKey("name");
947 // This time we wrap the result from GetAnyRoot in a smartpointer that
948 // will keep rroot valid as resizingbuf resizes.
949 auto rroot = flatbuffers::piv(
950 flatbuffers::GetAnyRoot(flatbuffers::vector_data(resizingbuf)),
952 SetString(schema, "totally new string", GetFieldS(**rroot, name_field),
954 // Here resizingbuf has changed, but rroot is still valid.
955 TEST_EQ_STR(GetFieldS(**rroot, name_field)->c_str(), "totally new string");
956 // Now lets extend a vector by 100 elements (10 -> 110).
957 auto &inventory_field = *fields->LookupByKey("inventory");
958 auto rinventory = flatbuffers::piv(
959 flatbuffers::GetFieldV<uint8_t>(**rroot, inventory_field), resizingbuf);
960 flatbuffers::ResizeVector<uint8_t>(schema, 110, 50, *rinventory,
962 // rinventory still valid, so lets read from it.
963 TEST_EQ(rinventory->Get(10), 50);
965 // For reflection uses not covered already, there is a more powerful way:
966 // we can simply generate whatever object we want to add/modify in a
967 // FlatBuffer of its own, then add that to an existing FlatBuffer:
968 // As an example, let's add a string to an array of strings.
969 // First, find our field:
970 auto &testarrayofstring_field = *fields->LookupByKey("testarrayofstring");
971 // Find the vector value:
972 auto rtestarrayofstring = flatbuffers::piv(
973 flatbuffers::GetFieldV<flatbuffers::Offset<flatbuffers::String>>(
974 **rroot, testarrayofstring_field),
976 // It's a vector of 2 strings, to which we add one more, initialized to
978 flatbuffers::ResizeVector<flatbuffers::Offset<flatbuffers::String>>(
979 schema, 3, 0, *rtestarrayofstring, &resizingbuf);
980 // Here we just create a buffer that contans a single string, but this
981 // could also be any complex set of tables and other values.
982 flatbuffers::FlatBufferBuilder stringfbb;
983 stringfbb.Finish(stringfbb.CreateString("hank"));
984 // Add the contents of it to our existing FlatBuffer.
985 // We do this last, so the pointer doesn't get invalidated (since it is
986 // at the end of the buffer):
987 auto string_ptr = flatbuffers::AddFlatBuffer(
988 resizingbuf, stringfbb.GetBufferPointer(), stringfbb.GetSize());
989 // Finally, set the new value in the vector.
990 rtestarrayofstring->MutateOffset(2, string_ptr);
991 TEST_EQ_STR(rtestarrayofstring->Get(0)->c_str(), "bob");
992 TEST_EQ_STR(rtestarrayofstring->Get(2)->c_str(), "hank");
993 // Test integrity of all resize operations above.
994 flatbuffers::Verifier resize_verifier(
995 reinterpret_cast<const uint8_t *>(flatbuffers::vector_data(resizingbuf)),
997 TEST_EQ(VerifyMonsterBuffer(resize_verifier), true);
999 // Test buffer is valid using reflection as well
1000 TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(),
1001 flatbuffers::vector_data(resizingbuf),
1002 resizingbuf.size()),
1005 // As an additional test, also set it on the name field.
1006 // Note: unlike the name change above, this just overwrites the offset,
1007 // rather than changing the string in-place.
1008 SetFieldT(*rroot, name_field, string_ptr);
1009 TEST_EQ_STR(GetFieldS(**rroot, name_field)->c_str(), "hank");
1011 // Using reflection, rather than mutating binary FlatBuffers, we can also copy
1012 // tables and other things out of other FlatBuffers into a FlatBufferBuilder,
1013 // either part or whole.
1014 flatbuffers::FlatBufferBuilder fbb;
1015 auto root_offset = flatbuffers::CopyTable(
1016 fbb, schema, *root_table, *flatbuffers::GetAnyRoot(flatbuf), true);
1017 fbb.Finish(root_offset, MonsterIdentifier());
1018 // Test that it was copied correctly:
1019 AccessFlatBufferTest(fbb.GetBufferPointer(), fbb.GetSize());
1021 // Test buffer is valid using reflection as well
1022 TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(),
1023 fbb.GetBufferPointer(), fbb.GetSize()),
1027 void MiniReflectFlatBuffersTest(uint8_t *flatbuf) {
1028 auto s = flatbuffers::FlatBufferToString(flatbuf, Monster::MiniReflectTypeTable());
1032 "pos: { x: 1.0, y: 2.0, z: 3.0, test1: 0.0, test2: Red, test3: "
1033 "{ a: 10, b: 20 } }, "
1035 "name: \"MyMonster\", "
1036 "inventory: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], "
1037 "test_type: Monster, "
1038 "test: { name: \"Fred\" }, "
1039 "test4: [ { a: 10, b: 20 }, { a: 30, b: 40 } ], "
1040 "testarrayofstring: [ \"bob\", \"fred\", \"bob\", \"fred\" ], "
1041 "testarrayoftables: [ { hp: 1000, name: \"Barney\" }, { name: \"Fred\" "
1043 "{ name: \"Wilma\" } ], "
1044 // TODO(wvo): should really print this nested buffer correctly.
1045 "testnestedflatbuffer: [ 20, 0, 0, 0, 77, 79, 78, 83, 12, 0, 12, 0, 0, "
1047 "4, 0, 6, 0, 8, 0, 12, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 13, 0, 0, 0, 78, "
1048 "101, 115, 116, 101, 100, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0 ], "
1049 "testarrayofstring2: [ \"jane\", \"mary\" ], "
1050 "testarrayofsortedstruct: [ { id: 1, distance: 10 }, "
1051 "{ id: 2, distance: 20 }, { id: 3, distance: 30 }, "
1052 "{ id: 4, distance: 40 } ], "
1053 "flex: [ 210, 4, 5, 2 ], "
1054 "test5: [ { a: 10, b: 20 }, { a: 30, b: 40 } ], "
1055 "vector_of_enums: [ Blue, Green ] "
1059 Vec3 vec(1,2,3, 1.5, Color_Red, test);
1060 flatbuffers::FlatBufferBuilder vec_builder;
1061 vec_builder.Finish(vec_builder.CreateStruct(vec));
1062 auto vec_buffer = vec_builder.Release();
1063 auto vec_str = flatbuffers::FlatBufferToString(vec_buffer.data(),
1064 Vec3::MiniReflectTypeTable());
1067 "{ x: 1.0, y: 2.0, z: 3.0, test1: 1.5, test2: Red, test3: { a: 16, b: 32 } }");
1070 // Parse a .proto schema, output as .fbs
1071 void ParseProtoTest() {
1072 // load the .proto and the golden file from disk
1073 std::string protofile;
1074 std::string goldenfile;
1075 std::string goldenunionfile;
1077 flatbuffers::LoadFile((test_data_path + "prototest/test.proto").c_str(),
1081 flatbuffers::LoadFile((test_data_path + "prototest/test.golden").c_str(),
1082 false, &goldenfile),
1085 flatbuffers::LoadFile((test_data_path +
1086 "prototest/test_union.golden").c_str(),
1087 false, &goldenunionfile),
1090 flatbuffers::IDLOptions opts;
1091 opts.include_dependence_headers = false;
1092 opts.proto_mode = true;
1095 flatbuffers::Parser parser(opts);
1096 auto protopath = test_data_path + "prototest/";
1097 const char *include_directories[] = { protopath.c_str(), nullptr };
1098 TEST_EQ(parser.Parse(protofile.c_str(), include_directories), true);
1101 auto fbs = flatbuffers::GenerateFBS(parser, "test");
1103 // Ensure generated file is parsable.
1104 flatbuffers::Parser parser2;
1105 TEST_EQ(parser2.Parse(fbs.c_str(), nullptr), true);
1106 TEST_EQ_STR(fbs.c_str(), goldenfile.c_str());
1108 // Parse proto with --oneof-union option.
1109 opts.proto_oneof_union = true;
1110 flatbuffers::Parser parser3(opts);
1111 TEST_EQ(parser3.Parse(protofile.c_str(), include_directories), true);
1114 auto fbs_union = flatbuffers::GenerateFBS(parser3, "test");
1116 // Ensure generated file is parsable.
1117 flatbuffers::Parser parser4;
1118 TEST_EQ(parser4.Parse(fbs_union.c_str(), nullptr), true);
1119 TEST_EQ_STR(fbs_union.c_str(), goldenunionfile.c_str());
1122 template<typename T>
1123 void CompareTableFieldValue(flatbuffers::Table *table,
1124 flatbuffers::voffset_t voffset, T val) {
1125 T read = table->GetField(voffset, static_cast<T>(0));
1129 // Low level stress/fuzz test: serialize/deserialize a variety of
1130 // different kinds of data in different combinations
1132 // Values we're testing against: chosen to ensure no bits get chopped
1133 // off anywhere, and also be different from eachother.
1134 const uint8_t bool_val = true;
1135 const int8_t char_val = -127; // 0x81
1136 const uint8_t uchar_val = 0xFF;
1137 const int16_t short_val = -32222; // 0x8222;
1138 const uint16_t ushort_val = 0xFEEE;
1139 const int32_t int_val = 0x83333333;
1140 const uint32_t uint_val = 0xFDDDDDDD;
1141 const int64_t long_val = 0x8444444444444444LL;
1142 const uint64_t ulong_val = 0xFCCCCCCCCCCCCCCCULL;
1143 const float float_val = 3.14159f;
1144 const double double_val = 3.14159265359;
1146 const int test_values_max = 11;
1147 const flatbuffers::voffset_t fields_per_object = 4;
1148 const int num_fuzz_objects = 10000; // The higher, the more thorough :)
1150 flatbuffers::FlatBufferBuilder builder;
1152 lcg_reset(); // Keep it deterministic.
1154 flatbuffers::uoffset_t objects[num_fuzz_objects];
1156 // Generate num_fuzz_objects random objects each consisting of
1157 // fields_per_object fields, each of a random type.
1158 for (int i = 0; i < num_fuzz_objects; i++) {
1159 auto start = builder.StartTable();
1160 for (flatbuffers::voffset_t f = 0; f < fields_per_object; f++) {
1161 int choice = lcg_rand() % test_values_max;
1162 auto off = flatbuffers::FieldIndexToOffset(f);
1164 case 0: builder.AddElement<uint8_t>(off, bool_val, 0); break;
1165 case 1: builder.AddElement<int8_t>(off, char_val, 0); break;
1166 case 2: builder.AddElement<uint8_t>(off, uchar_val, 0); break;
1167 case 3: builder.AddElement<int16_t>(off, short_val, 0); break;
1168 case 4: builder.AddElement<uint16_t>(off, ushort_val, 0); break;
1169 case 5: builder.AddElement<int32_t>(off, int_val, 0); break;
1170 case 6: builder.AddElement<uint32_t>(off, uint_val, 0); break;
1171 case 7: builder.AddElement<int64_t>(off, long_val, 0); break;
1172 case 8: builder.AddElement<uint64_t>(off, ulong_val, 0); break;
1173 case 9: builder.AddElement<float>(off, float_val, 0); break;
1174 case 10: builder.AddElement<double>(off, double_val, 0); break;
1177 objects[i] = builder.EndTable(start);
1179 builder.PreAlign<flatbuffers::largest_scalar_t>(0); // Align whole buffer.
1181 lcg_reset(); // Reset.
1183 uint8_t *eob = builder.GetCurrentBufferPointer() + builder.GetSize();
1185 // Test that all objects we generated are readable and return the
1186 // expected values. We generate random objects in the same order
1187 // so this is deterministic.
1188 for (int i = 0; i < num_fuzz_objects; i++) {
1189 auto table = reinterpret_cast<flatbuffers::Table *>(eob - objects[i]);
1190 for (flatbuffers::voffset_t f = 0; f < fields_per_object; f++) {
1191 int choice = lcg_rand() % test_values_max;
1192 flatbuffers::voffset_t off = flatbuffers::FieldIndexToOffset(f);
1194 case 0: CompareTableFieldValue(table, off, bool_val); break;
1195 case 1: CompareTableFieldValue(table, off, char_val); break;
1196 case 2: CompareTableFieldValue(table, off, uchar_val); break;
1197 case 3: CompareTableFieldValue(table, off, short_val); break;
1198 case 4: CompareTableFieldValue(table, off, ushort_val); break;
1199 case 5: CompareTableFieldValue(table, off, int_val); break;
1200 case 6: CompareTableFieldValue(table, off, uint_val); break;
1201 case 7: CompareTableFieldValue(table, off, long_val); break;
1202 case 8: CompareTableFieldValue(table, off, ulong_val); break;
1203 case 9: CompareTableFieldValue(table, off, float_val); break;
1204 case 10: CompareTableFieldValue(table, off, double_val); break;
1210 // High level stress/fuzz test: generate a big schema and
1211 // matching json data in random combinations, then parse both,
1212 // generate json back from the binary, and compare with the original.
1214 lcg_reset(); // Keep it deterministic.
1216 const int num_definitions = 30;
1217 const int num_struct_definitions = 5; // Subset of num_definitions.
1218 const int fields_per_definition = 15;
1219 const int instances_per_definition = 5;
1220 const int deprecation_rate = 10; // 1 in deprecation_rate fields will
1223 std::string schema = "namespace test;\n\n";
1226 std::string instances[instances_per_definition];
1228 // Since we're generating schema and corresponding data in tandem,
1229 // this convenience function adds strings to both at once.
1230 static void Add(RndDef (&definitions_l)[num_definitions],
1231 std::string &schema_l, const int instances_per_definition_l,
1232 const char *schema_add, const char *instance_add,
1234 schema_l += schema_add;
1235 for (int i = 0; i < instances_per_definition_l; i++)
1236 definitions_l[definition].instances[i] += instance_add;
1241 #define AddToSchemaAndInstances(schema_add, instance_add) \
1242 RndDef::Add(definitions, schema, instances_per_definition, \
1243 schema_add, instance_add, definition)
1246 RndDef::Add(definitions, schema, instances_per_definition, \
1247 "byte", "1", definition)
1250 RndDef definitions[num_definitions];
1252 // We are going to generate num_definitions, the first
1253 // num_struct_definitions will be structs, the rest tables. For each
1254 // generate random fields, some of which may be struct/table types
1255 // referring to previously generated structs/tables.
1256 // Simultanenously, we generate instances_per_definition JSON data
1257 // definitions, which will have identical structure to the schema
1258 // being generated. We generate multiple instances such that when creating
1259 // hierarchy, we get some variety by picking one randomly.
1260 for (int definition = 0; definition < num_definitions; definition++) {
1261 std::string definition_name = "D" + flatbuffers::NumToString(definition);
1263 bool is_struct = definition < num_struct_definitions;
1265 AddToSchemaAndInstances(
1266 ((is_struct ? "struct " : "table ") + definition_name + " {\n").c_str(),
1269 for (int field = 0; field < fields_per_definition; field++) {
1270 const bool is_last_field = field == fields_per_definition - 1;
1272 // Deprecate 1 in deprecation_rate fields. Only table fields can be
1274 // Don't deprecate the last field to avoid dangling commas in JSON.
1275 const bool deprecated =
1276 !is_struct && !is_last_field && (lcg_rand() % deprecation_rate == 0);
1278 std::string field_name = "f" + flatbuffers::NumToString(field);
1279 AddToSchemaAndInstances((" " + field_name + ":").c_str(),
1280 deprecated ? "" : (field_name + ": ").c_str());
1281 // Pick random type:
1282 auto base_type = static_cast<flatbuffers::BaseType>(
1283 lcg_rand() % (flatbuffers::BASE_TYPE_UNION + 1));
1284 switch (base_type) {
1285 case flatbuffers::BASE_TYPE_STRING:
1287 Dummy(); // No strings in structs.
1289 AddToSchemaAndInstances("string", deprecated ? "" : "\"hi\"");
1292 case flatbuffers::BASE_TYPE_VECTOR:
1294 Dummy(); // No vectors in structs.
1296 AddToSchemaAndInstances("[ubyte]",
1297 deprecated ? "" : "[\n0,\n1,\n255\n]");
1300 case flatbuffers::BASE_TYPE_NONE:
1301 case flatbuffers::BASE_TYPE_UTYPE:
1302 case flatbuffers::BASE_TYPE_STRUCT:
1303 case flatbuffers::BASE_TYPE_UNION:
1305 // Pick a random previous definition and random data instance of
1307 int defref = lcg_rand() % definition;
1308 int instance = lcg_rand() % instances_per_definition;
1309 AddToSchemaAndInstances(
1310 ("D" + flatbuffers::NumToString(defref)).c_str(),
1312 : definitions[defref].instances[instance].c_str());
1314 // If this is the first definition, we have no definition we can
1319 case flatbuffers::BASE_TYPE_BOOL:
1320 AddToSchemaAndInstances(
1321 "bool", deprecated ? "" : (lcg_rand() % 2 ? "true" : "false"));
1323 case flatbuffers::BASE_TYPE_ARRAY:
1325 AddToSchemaAndInstances(
1327 deprecated ? "" : "255"); // No fixed-length arrays in tables.
1329 AddToSchemaAndInstances("[int:3]", deprecated ? "" : "[\n,\n,\n]");
1333 // All the scalar types.
1334 schema += flatbuffers::kTypeNames[base_type];
1337 // We want each instance to use its own random value.
1338 for (int inst = 0; inst < instances_per_definition; inst++)
1339 definitions[definition].instances[inst] +=
1340 flatbuffers::IsFloat(base_type)
1341 ? flatbuffers::NumToString<double>(lcg_rand() % 128)
1343 : flatbuffers::NumToString<int>(lcg_rand() % 128).c_str();
1346 AddToSchemaAndInstances(deprecated ? "(deprecated);\n" : ";\n",
1347 deprecated ? "" : is_last_field ? "\n" : ",\n");
1349 AddToSchemaAndInstances("}\n\n", "}");
1352 schema += "root_type D" + flatbuffers::NumToString(num_definitions - 1);
1355 flatbuffers::Parser parser;
1357 // Will not compare against the original if we don't write defaults
1358 parser.builder_.ForceDefaults(true);
1360 // Parse the schema, parse the generated data, then generate text back
1361 // from the binary and compare against the original.
1362 TEST_EQ(parser.Parse(schema.c_str()), true);
1364 const std::string &json =
1365 definitions[num_definitions - 1].instances[0] + "\n";
1367 TEST_EQ(parser.Parse(json.c_str()), true);
1369 std::string jsongen;
1370 parser.opts.indent_step = 0;
1372 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1373 TEST_EQ(result, true);
1375 if (jsongen != json) {
1376 // These strings are larger than a megabyte, so we show the bytes around
1377 // the first bytes that are different rather than the whole string.
1378 size_t len = std::min(json.length(), jsongen.length());
1379 for (size_t i = 0; i < len; i++) {
1380 if (json[i] != jsongen[i]) {
1381 i -= std::min(static_cast<size_t>(10), i); // show some context;
1382 size_t end = std::min(len, i + 20);
1383 for (; i < end; i++)
1384 TEST_OUTPUT_LINE("at %d: found \"%c\", expected \"%c\"\n",
1385 static_cast<int>(i), jsongen[i], json[i]);
1393 #ifdef FLATBUFFERS_TEST_VERBOSE
1394 TEST_OUTPUT_LINE("%dk schema tested with %dk of json\n",
1395 static_cast<int>(schema.length() / 1024),
1396 static_cast<int>(json.length() / 1024));
1401 // Test that parser errors are actually generated.
1402 void TestError_(const char *src, const char *error_substr, bool strict_json,
1403 const char *file, int line, const char *func) {
1404 flatbuffers::IDLOptions opts;
1405 opts.strict_json = strict_json;
1406 flatbuffers::Parser parser(opts);
1407 if (parser.Parse(src)) {
1408 TestFail("true", "false",
1409 ("parser.Parse(\"" + std::string(src) + "\")").c_str(), file, line,
1411 } else if (!strstr(parser.error_.c_str(), error_substr)) {
1412 TestFail(parser.error_.c_str(), error_substr,
1413 ("parser.Parse(\"" + std::string(src) + "\")").c_str(), file, line,
1418 void TestError_(const char *src, const char *error_substr, const char *file,
1419 int line, const char *func) {
1420 TestError_(src, error_substr, false, file, line, func);
1424 # define TestError(src, ...) \
1425 TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
1427 # define TestError(src, ...) \
1428 TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1431 // Test that parsing errors occur as we'd expect.
1432 // Also useful for coverage, making sure these paths are run.
1434 // In order they appear in idl_parser.cpp
1435 TestError("table X { Y:byte; } root_type X; { Y: 999 }", "does not fit");
1436 TestError("\"\0", "illegal");
1437 TestError("\"\\q", "escape code");
1438 TestError("table ///", "documentation");
1439 TestError("@", "illegal");
1440 TestError("table 1", "expecting");
1441 TestError("table X { Y:[[int]]; }", "nested vector");
1442 TestError("table X { Y:1; }", "illegal type");
1443 TestError("table X { Y:int; Y:int; }", "field already");
1444 TestError("table Y {} table X { Y:int; }", "same as table");
1445 TestError("struct X { Y:string; }", "only scalar");
1446 TestError("table X { Y:string = \"\"; }", "default values");
1447 TestError("struct X { a:uint = 42; }", "default values");
1448 TestError("enum Y:byte { Z = 1 } table X { y:Y; }", "not part of enum");
1449 TestError("struct X { Y:int (deprecated); }", "deprecate");
1450 TestError("union Z { X } table X { Y:Z; } root_type X; { Y: {}, A:1 }",
1451 "missing type field");
1452 TestError("union Z { X } table X { Y:Z; } root_type X; { Y_type: 99, Y: {",
1454 TestError("table X { Y:int; } root_type X; { Z:", "unknown field");
1455 TestError("table X { Y:int; } root_type X; { Y:", "string constant", true);
1456 TestError("table X { Y:int; } root_type X; { \"Y\":1, }", "string constant",
1459 "struct X { Y:int; Z:int; } table W { V:X; } root_type W; "
1462 TestError("enum E:byte { A } table X { Y:E; } root_type X; { Y:U }",
1463 "unknown enum value");
1464 TestError("table X { Y:byte; } root_type X; { Y:; }", "starting");
1465 TestError("enum X:byte { Y } enum X {", "enum already");
1466 TestError("enum X:float {}", "underlying");
1467 TestError("enum X:byte { Y, Y }", "value already");
1468 TestError("enum X:byte { Y=2, Z=1 }", "ascending");
1469 TestError("table X { Y:int; } table X {", "datatype already");
1470 TestError("struct X (force_align: 7) { Y:int; }", "force_align");
1471 TestError("struct X {}", "size 0");
1472 TestError("{}", "no root");
1473 TestError("table X { Y:byte; } root_type X; { Y:1 } { Y:1 }", "end of file");
1474 TestError("table X { Y:byte; } root_type X; { Y:1 } table Y{ Z:int }",
1476 TestError("root_type X;", "unknown root");
1477 TestError("struct X { Y:int; } root_type X;", "a table");
1478 TestError("union X { Y }", "referenced");
1479 TestError("union Z { X } struct X { Y:int; }", "only tables");
1480 TestError("table X { Y:[int]; YLength:int; }", "clash");
1481 TestError("table X { Y:byte; } root_type X; { Y:1, Y:2 }", "more than once");
1482 // float to integer conversion is forbidden
1483 TestError("table X { Y:int; } root_type X; { Y:1.0 }", "float");
1484 TestError("table X { Y:bool; } root_type X; { Y:1.0 }", "float");
1485 TestError("enum X:bool { Y = true }", "must be integral");
1488 template<typename T>
1489 T TestValue(const char *json, const char *type_name,
1490 const char *decls = nullptr) {
1491 flatbuffers::Parser parser;
1492 parser.builder_.ForceDefaults(true); // return defaults
1493 auto check_default = json ? false : true;
1494 if (check_default) { parser.opts.output_default_scalars_in_json = true; }
1496 std::string schema = std::string(decls ? decls : "") + "\n" +
1497 "table X { Y:" + std::string(type_name) +
1499 auto schema_done = parser.Parse(schema.c_str());
1500 TEST_EQ_STR(parser.error_.c_str(), "");
1501 TEST_EQ(schema_done, true);
1503 auto done = parser.Parse(check_default ? "{}" : json);
1504 TEST_EQ_STR(parser.error_.c_str(), "");
1505 TEST_EQ(done, true);
1507 // Check with print.
1508 std::string print_back;
1509 parser.opts.indent_step = -1;
1510 TEST_EQ(GenerateText(parser, parser.builder_.GetBufferPointer(), &print_back),
1512 // restore value from its default
1513 if (check_default) { TEST_EQ(parser.Parse(print_back.c_str()), true); }
1515 auto root = flatbuffers::GetRoot<flatbuffers::Table>(
1516 parser.builder_.GetBufferPointer());
1517 return root->GetField<T>(flatbuffers::FieldIndexToOffset(0), 0);
1520 bool FloatCompare(float a, float b) { return fabs(a - b) < 0.001; }
1522 // Additional parser testing not covered elsewhere.
1524 // Test scientific notation numbers.
1525 TEST_EQ(FloatCompare(TestValue<float>("{ Y:0.0314159e+2 }", "float"),
1529 TEST_EQ(FloatCompare(TestValue<float>("{ Y:\"0.0314159e+2\" }", "float"),
1533 // Test conversion functions.
1534 TEST_EQ(FloatCompare(TestValue<float>("{ Y:cos(rad(180)) }", "float"), -1),
1537 // int embedded to string
1538 TEST_EQ(TestValue<int>("{ Y:\"-876\" }", "int=-123"), -876);
1539 TEST_EQ(TestValue<int>("{ Y:\"876\" }", "int=-123"), 876);
1541 // Test negative hex constant.
1542 TEST_EQ(TestValue<int>("{ Y:-0x8ea0 }", "int=-0x8ea0"), -36512);
1543 TEST_EQ(TestValue<int>(nullptr, "int=-0x8ea0"), -36512);
1545 // positive hex constant
1546 TEST_EQ(TestValue<int>("{ Y:0x1abcdef }", "int=0x1"), 0x1abcdef);
1547 // with optional '+' sign
1548 TEST_EQ(TestValue<int>("{ Y:+0x1abcdef }", "int=+0x1"), 0x1abcdef);
1550 TEST_EQ(TestValue<int>("{ Y:\"0x1abcdef\" }", "int=+0x1"), 0x1abcdef);
1552 // Make sure we do unsigned 64bit correctly.
1553 TEST_EQ(TestValue<uint64_t>("{ Y:12335089644688340133 }", "ulong"),
1554 12335089644688340133ULL);
1557 TEST_EQ(TestValue<bool>("{ Y:\"false\" }", "bool=true"), false);
1558 TEST_EQ(TestValue<bool>("{ Y:\"true\" }", "bool=\"true\""), true);
1559 TEST_EQ(TestValue<bool>("{ Y:'false' }", "bool=true"), false);
1560 TEST_EQ(TestValue<bool>("{ Y:'true' }", "bool=\"true\""), true);
1562 // check comments before and after json object
1563 TEST_EQ(TestValue<int>("/*before*/ { Y:1 } /*after*/", "int"), 1);
1564 TEST_EQ(TestValue<int>("//before \n { Y:1 } //after", "int"), 1);
1568 void NestedListTest() {
1569 flatbuffers::Parser parser1;
1570 TEST_EQ(parser1.Parse("struct Test { a:short; b:byte; } table T { F:[Test]; }"
1572 "{ F:[ [10,20], [30,40]] }"),
1576 void EnumStringsTest() {
1577 flatbuffers::Parser parser1;
1578 TEST_EQ(parser1.Parse("enum E:byte { A, B, C } table T { F:[E]; }"
1580 "{ F:[ A, B, \"C\", \"A B C\" ] }"),
1582 flatbuffers::Parser parser2;
1583 TEST_EQ(parser2.Parse("enum E:byte { A, B, C } table T { F:[int]; }"
1585 "{ F:[ \"E.C\", \"E.A E.B E.C\" ] }"),
1587 // unsigned bit_flags
1588 flatbuffers::Parser parser3;
1590 parser3.Parse("enum E:uint16 (bit_flags) { F0, F07=7, F08, F14=14, F15 }"
1591 " table T { F: E = \"F15 F08\"; }"
1596 void EnumNamesTest() {
1597 TEST_EQ_STR("Red", EnumNameColor(Color_Red));
1598 TEST_EQ_STR("Green", EnumNameColor(Color_Green));
1599 TEST_EQ_STR("Blue", EnumNameColor(Color_Blue));
1600 // Check that Color to string don't crash while decode a mixture of Colors.
1601 // 1) Example::Color enum is enum with unfixed underlying type.
1602 // 2) Valid enum range: [0; 2^(ceil(log2(Color_ANY))) - 1].
1603 // Consequence: A value is out of this range will lead to UB (since C++17).
1604 // For details see C++17 standard or explanation on the SO:
1605 // stackoverflow.com/questions/18195312/what-happens-if-you-static-cast-invalid-value-to-enum-class
1606 TEST_EQ_STR("", EnumNameColor(static_cast<Color>(0)));
1607 TEST_EQ_STR("", EnumNameColor(static_cast<Color>(Color_ANY-1)));
1608 TEST_EQ_STR("", EnumNameColor(static_cast<Color>(Color_ANY+1)));
1611 void EnumOutOfRangeTest() {
1612 TestError("enum X:byte { Y = 128 }", "enum value does not fit");
1613 TestError("enum X:byte { Y = -129 }", "enum value does not fit");
1614 TestError("enum X:byte { Y = 126, Z0, Z1 }", "enum value does not fit");
1615 TestError("enum X:ubyte { Y = -1 }", "enum value does not fit");
1616 TestError("enum X:ubyte { Y = 256 }", "enum value does not fit");
1617 TestError("enum X:ubyte { Y = 255, Z }", "enum value does not fit");
1618 // Unions begin with an implicit "NONE = 0".
1619 TestError("table Y{} union X { Y = -1 }",
1620 "enum values must be specified in ascending order");
1621 TestError("table Y{} union X { Y = 256 }", "enum value does not fit");
1622 TestError("table Y{} union X { Y = 255, Z:Y }", "enum value does not fit");
1623 TestError("enum X:int { Y = -2147483649 }", "enum value does not fit");
1624 TestError("enum X:int { Y = 2147483648 }", "enum value does not fit");
1625 TestError("enum X:uint { Y = -1 }", "enum value does not fit");
1626 TestError("enum X:uint { Y = 4294967297 }", "enum value does not fit");
1627 TestError("enum X:long { Y = 9223372036854775808 }", "does not fit");
1628 TestError("enum X:long { Y = 9223372036854775807, Z }", "enum value does not fit");
1629 TestError("enum X:ulong { Y = -1 }", "does not fit");
1630 TestError("enum X:ubyte (bit_flags) { Y=8 }", "bit flag out");
1631 TestError("enum X:byte (bit_flags) { Y=7 }", "must be unsigned"); // -128
1632 // bit_flgs out of range
1633 TestError("enum X:ubyte (bit_flags) { Y0,Y1,Y2,Y3,Y4,Y5,Y6,Y7,Y8 }", "out of range");
1636 void EnumValueTest() {
1637 // json: "{ Y:0 }", schema: table X { Y : "E"}
1638 // 0 in enum (V=0) E then Y=0 is valid.
1639 TEST_EQ(TestValue<int>("{ Y:0 }", "E", "enum E:int { V }"), 0);
1640 TEST_EQ(TestValue<int>("{ Y:V }", "E", "enum E:int { V }"), 0);
1641 // A default value of Y is 0.
1642 TEST_EQ(TestValue<int>("{ }", "E", "enum E:int { V }"), 0);
1643 TEST_EQ(TestValue<int>("{ Y:5 }", "E=V", "enum E:int { V=5 }"), 5);
1644 // Generate json with defaults and check.
1645 TEST_EQ(TestValue<int>(nullptr, "E=V", "enum E:int { V=5 }"), 5);
1647 TEST_EQ(TestValue<int>("{ Y:5 }", "E", "enum E:int { Z, V=5 }"), 5);
1648 TEST_EQ(TestValue<int>("{ Y:5 }", "E=V", "enum E:int { Z, V=5 }"), 5);
1649 // Generate json with defaults and check.
1650 TEST_EQ(TestValue<int>(nullptr, "E", "enum E:int { Z, V=5 }"), 0);
1651 TEST_EQ(TestValue<int>(nullptr, "E=V", "enum E:int { Z, V=5 }"), 5);
1653 TEST_EQ(TestValue<uint64_t>(nullptr, "E=V",
1654 "enum E:ulong { V = 13835058055282163712 }"),
1655 13835058055282163712ULL);
1656 TEST_EQ(TestValue<uint64_t>(nullptr, "E=V",
1657 "enum E:ulong { V = 18446744073709551615 }"),
1658 18446744073709551615ULL);
1659 // Assign non-enum value to enum field. Is it right?
1660 TEST_EQ(TestValue<int>("{ Y:7 }", "E", "enum E:int { V = 0 }"), 7);
1663 void IntegerOutOfRangeTest() {
1664 TestError("table T { F:byte; } root_type T; { F:128 }",
1665 "constant does not fit");
1666 TestError("table T { F:byte; } root_type T; { F:-129 }",
1667 "constant does not fit");
1668 TestError("table T { F:ubyte; } root_type T; { F:256 }",
1669 "constant does not fit");
1670 TestError("table T { F:ubyte; } root_type T; { F:-1 }",
1671 "constant does not fit");
1672 TestError("table T { F:short; } root_type T; { F:32768 }",
1673 "constant does not fit");
1674 TestError("table T { F:short; } root_type T; { F:-32769 }",
1675 "constant does not fit");
1676 TestError("table T { F:ushort; } root_type T; { F:65536 }",
1677 "constant does not fit");
1678 TestError("table T { F:ushort; } root_type T; { F:-1 }",
1679 "constant does not fit");
1680 TestError("table T { F:int; } root_type T; { F:2147483648 }",
1681 "constant does not fit");
1682 TestError("table T { F:int; } root_type T; { F:-2147483649 }",
1683 "constant does not fit");
1684 TestError("table T { F:uint; } root_type T; { F:4294967296 }",
1685 "constant does not fit");
1686 TestError("table T { F:uint; } root_type T; { F:-1 }",
1687 "constant does not fit");
1688 // Check fixed width aliases
1689 TestError("table X { Y:uint8; } root_type X; { Y: -1 }", "does not fit");
1690 TestError("table X { Y:uint8; } root_type X; { Y: 256 }", "does not fit");
1691 TestError("table X { Y:uint16; } root_type X; { Y: -1 }", "does not fit");
1692 TestError("table X { Y:uint16; } root_type X; { Y: 65536 }", "does not fit");
1693 TestError("table X { Y:uint32; } root_type X; { Y: -1 }", "");
1694 TestError("table X { Y:uint32; } root_type X; { Y: 4294967296 }",
1696 TestError("table X { Y:uint64; } root_type X; { Y: -1 }", "");
1697 TestError("table X { Y:uint64; } root_type X; { Y: -9223372036854775809 }",
1699 TestError("table X { Y:uint64; } root_type X; { Y: 18446744073709551616 }",
1702 TestError("table X { Y:int8; } root_type X; { Y: -129 }", "does not fit");
1703 TestError("table X { Y:int8; } root_type X; { Y: 128 }", "does not fit");
1704 TestError("table X { Y:int16; } root_type X; { Y: -32769 }", "does not fit");
1705 TestError("table X { Y:int16; } root_type X; { Y: 32768 }", "does not fit");
1706 TestError("table X { Y:int32; } root_type X; { Y: -2147483649 }", "");
1707 TestError("table X { Y:int32; } root_type X; { Y: 2147483648 }",
1709 TestError("table X { Y:int64; } root_type X; { Y: -9223372036854775809 }",
1711 TestError("table X { Y:int64; } root_type X; { Y: 9223372036854775808 }",
1713 // check out-of-int64 as int8
1714 TestError("table X { Y:int8; } root_type X; { Y: -9223372036854775809 }",
1716 TestError("table X { Y:int8; } root_type X; { Y: 9223372036854775808 }",
1719 // Check default values
1720 TestError("table X { Y:int64=-9223372036854775809; } root_type X; {}",
1722 TestError("table X { Y:int64= 9223372036854775808; } root_type X; {}",
1724 TestError("table X { Y:uint64; } root_type X; { Y: -1 }", "");
1725 TestError("table X { Y:uint64=-9223372036854775809; } root_type X; {}",
1727 TestError("table X { Y:uint64= 18446744073709551616; } root_type X; {}",
1731 void IntegerBoundaryTest() {
1732 // Check numerical compatibility with non-C++ languages.
1733 // By the C++ standard, std::numerical_limits<int64_t>::min() == -9223372036854775807 (-2^63+1) or less*
1734 // The Flatbuffers grammar and most of the languages (C#, Java, Rust) expect
1735 // that minimum values are: -128, -32768,.., -9223372036854775808.
1736 // Since C++20, static_cast<int64>(0x8000000000000000ULL) is well-defined two's complement cast.
1737 // Therefore -9223372036854775808 should be valid negative value.
1738 TEST_EQ(flatbuffers::numeric_limits<int8_t>::min(), -128);
1739 TEST_EQ(flatbuffers::numeric_limits<int8_t>::max(), 127);
1740 TEST_EQ(flatbuffers::numeric_limits<int16_t>::min(), -32768);
1741 TEST_EQ(flatbuffers::numeric_limits<int16_t>::max(), 32767);
1742 TEST_EQ(flatbuffers::numeric_limits<int32_t>::min() + 1, -2147483647);
1743 TEST_EQ(flatbuffers::numeric_limits<int32_t>::max(), 2147483647ULL);
1744 TEST_EQ(flatbuffers::numeric_limits<int64_t>::min() + 1LL,
1745 -9223372036854775807LL);
1746 TEST_EQ(flatbuffers::numeric_limits<int64_t>::max(), 9223372036854775807ULL);
1747 TEST_EQ(flatbuffers::numeric_limits<uint8_t>::max(), 255);
1748 TEST_EQ(flatbuffers::numeric_limits<uint16_t>::max(), 65535);
1749 TEST_EQ(flatbuffers::numeric_limits<uint32_t>::max(), 4294967295ULL);
1750 TEST_EQ(flatbuffers::numeric_limits<uint64_t>::max(),
1751 18446744073709551615ULL);
1753 TEST_EQ(TestValue<int8_t>("{ Y:127 }", "byte"), 127);
1754 TEST_EQ(TestValue<int8_t>("{ Y:-128 }", "byte"), -128);
1755 TEST_EQ(TestValue<uint8_t>("{ Y:255 }", "ubyte"), 255);
1756 TEST_EQ(TestValue<uint8_t>("{ Y:0 }", "ubyte"), 0);
1757 TEST_EQ(TestValue<int16_t>("{ Y:32767 }", "short"), 32767);
1758 TEST_EQ(TestValue<int16_t>("{ Y:-32768 }", "short"), -32768);
1759 TEST_EQ(TestValue<uint16_t>("{ Y:65535 }", "ushort"), 65535);
1760 TEST_EQ(TestValue<uint16_t>("{ Y:0 }", "ushort"), 0);
1761 TEST_EQ(TestValue<int32_t>("{ Y:2147483647 }", "int"), 2147483647);
1762 TEST_EQ(TestValue<int32_t>("{ Y:-2147483648 }", "int") + 1, -2147483647);
1763 TEST_EQ(TestValue<uint32_t>("{ Y:4294967295 }", "uint"), 4294967295);
1764 TEST_EQ(TestValue<uint32_t>("{ Y:0 }", "uint"), 0);
1765 TEST_EQ(TestValue<int64_t>("{ Y:9223372036854775807 }", "long"),
1766 9223372036854775807LL);
1767 TEST_EQ(TestValue<int64_t>("{ Y:-9223372036854775808 }", "long") + 1LL,
1768 -9223372036854775807LL);
1769 TEST_EQ(TestValue<uint64_t>("{ Y:18446744073709551615 }", "ulong"),
1770 18446744073709551615ULL);
1771 TEST_EQ(TestValue<uint64_t>("{ Y:0 }", "ulong"), 0);
1772 TEST_EQ(TestValue<uint64_t>("{ Y: 18446744073709551615 }", "uint64"),
1773 18446744073709551615ULL);
1774 // check that the default works
1775 TEST_EQ(TestValue<uint64_t>(nullptr, "uint64 = 18446744073709551615"),
1776 18446744073709551615ULL);
1779 void ValidFloatTest() {
1780 // check rounding to infinity
1781 TEST_EQ(TestValue<float>("{ Y:+3.4029e+38 }", "float"), +infinityf);
1782 TEST_EQ(TestValue<float>("{ Y:-3.4029e+38 }", "float"), -infinityf);
1783 TEST_EQ(TestValue<double>("{ Y:+1.7977e+308 }", "double"), +infinityd);
1784 TEST_EQ(TestValue<double>("{ Y:-1.7977e+308 }", "double"), -infinityd);
1787 FloatCompare(TestValue<float>("{ Y:0.0314159e+2 }", "float"), 3.14159f),
1790 TEST_EQ(FloatCompare(TestValue<float>("{ Y:\" 0.0314159e+2 \" }", "float"),
1794 TEST_EQ(TestValue<float>("{ Y:1 }", "float"), 1.0f);
1795 TEST_EQ(TestValue<float>("{ Y:1.0 }", "float"), 1.0f);
1796 TEST_EQ(TestValue<float>("{ Y:1. }", "float"), 1.0f);
1797 TEST_EQ(TestValue<float>("{ Y:+1. }", "float"), 1.0f);
1798 TEST_EQ(TestValue<float>("{ Y:-1. }", "float"), -1.0f);
1799 TEST_EQ(TestValue<float>("{ Y:1.e0 }", "float"), 1.0f);
1800 TEST_EQ(TestValue<float>("{ Y:1.e+0 }", "float"), 1.0f);
1801 TEST_EQ(TestValue<float>("{ Y:1.e-0 }", "float"), 1.0f);
1802 TEST_EQ(TestValue<float>("{ Y:0.125 }", "float"), 0.125f);
1803 TEST_EQ(TestValue<float>("{ Y:.125 }", "float"), 0.125f);
1804 TEST_EQ(TestValue<float>("{ Y:-.125 }", "float"), -0.125f);
1805 TEST_EQ(TestValue<float>("{ Y:+.125 }", "float"), +0.125f);
1806 TEST_EQ(TestValue<float>("{ Y:5 }", "float"), 5.0f);
1807 TEST_EQ(TestValue<float>("{ Y:\"5\" }", "float"), 5.0f);
1809 #if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
1810 // Old MSVC versions may have problem with this check.
1811 // https://www.exploringbinary.com/visual-c-plus-plus-strtod-still-broken/
1812 TEST_EQ(TestValue<double>("{ Y:6.9294956446009195e15 }", "double"),
1813 6929495644600920.0);
1815 TEST_EQ(std::isnan(TestValue<double>("{ Y:nan }", "double")), true);
1816 TEST_EQ(std::isnan(TestValue<float>("{ Y:nan }", "float")), true);
1817 TEST_EQ(std::isnan(TestValue<float>("{ Y:\"nan\" }", "float")), true);
1818 TEST_EQ(std::isnan(TestValue<float>("{ Y:+nan }", "float")), true);
1819 TEST_EQ(std::isnan(TestValue<float>("{ Y:-nan }", "float")), true);
1820 TEST_EQ(std::isnan(TestValue<float>(nullptr, "float=nan")), true);
1821 TEST_EQ(std::isnan(TestValue<float>(nullptr, "float=-nan")), true);
1823 TEST_EQ(TestValue<float>("{ Y:inf }", "float"), infinityf);
1824 TEST_EQ(TestValue<float>("{ Y:\"inf\" }", "float"), infinityf);
1825 TEST_EQ(TestValue<float>("{ Y:+inf }", "float"), infinityf);
1826 TEST_EQ(TestValue<float>("{ Y:-inf }", "float"), -infinityf);
1827 TEST_EQ(TestValue<float>(nullptr, "float=inf"), infinityf);
1828 TEST_EQ(TestValue<float>(nullptr, "float=-inf"), -infinityf);
1830 "{ Y : [0.2, .2, 1.0, -1.0, -2., 2., 1e0, -1e0, 1.0e0, -1.0e0, -3.e2, "
1834 "{ Y : [0.2, .2, 1.0, -1.0, -2., 2., 1e0, -1e0, 1.0e0, -1.0e0, -3.e2, "
1838 // Test binary format of float point.
1839 // https://en.cppreference.com/w/cpp/language/floating_literal
1840 // 0x11.12p-1 = (1*16^1 + 2*16^0 + 3*16^-1 + 4*16^-2) * 2^-1 =
1841 TEST_EQ(TestValue<double>("{ Y:0x12.34p-1 }", "double"), 9.1015625);
1842 // hex fraction 1.2 (decimal 1.125) scaled by 2^3, that is 9.0
1843 TEST_EQ(TestValue<float>("{ Y:-0x0.2p0 }", "float"), -0.125f);
1844 TEST_EQ(TestValue<float>("{ Y:-0x.2p1 }", "float"), -0.25f);
1845 TEST_EQ(TestValue<float>("{ Y:0x1.2p3 }", "float"), 9.0f);
1846 TEST_EQ(TestValue<float>("{ Y:0x10.1p0 }", "float"), 16.0625f);
1847 TEST_EQ(TestValue<double>("{ Y:0x1.2p3 }", "double"), 9.0);
1848 TEST_EQ(TestValue<double>("{ Y:0x10.1p0 }", "double"), 16.0625);
1849 TEST_EQ(TestValue<double>("{ Y:0xC.68p+2 }", "double"), 49.625);
1850 TestValue<double>("{ Y : [0x20.4ep1, +0x20.4ep1, -0x20.4ep1] }", "[double]");
1851 TestValue<float>("{ Y : [0x20.4ep1, +0x20.4ep1, -0x20.4ep1] }", "[float]");
1853 #else // FLATBUFFERS_HAS_NEW_STRTOD
1854 TEST_OUTPUT_LINE("FLATBUFFERS_HAS_NEW_STRTOD tests skipped");
1855 #endif // !FLATBUFFERS_HAS_NEW_STRTOD
1858 void InvalidFloatTest() {
1859 auto invalid_msg = "invalid number";
1860 auto comma_msg = "expecting: ,";
1861 TestError("table T { F:float; } root_type T; { F:1,0 }", "");
1862 TestError("table T { F:float; } root_type T; { F:. }", "");
1863 TestError("table T { F:float; } root_type T; { F:- }", invalid_msg);
1864 TestError("table T { F:float; } root_type T; { F:+ }", invalid_msg);
1865 TestError("table T { F:float; } root_type T; { F:-. }", invalid_msg);
1866 TestError("table T { F:float; } root_type T; { F:+. }", invalid_msg);
1867 TestError("table T { F:float; } root_type T; { F:.e }", "");
1868 TestError("table T { F:float; } root_type T; { F:-e }", invalid_msg);
1869 TestError("table T { F:float; } root_type T; { F:+e }", invalid_msg);
1870 TestError("table T { F:float; } root_type T; { F:-.e }", invalid_msg);
1871 TestError("table T { F:float; } root_type T; { F:+.e }", invalid_msg);
1872 TestError("table T { F:float; } root_type T; { F:-e1 }", invalid_msg);
1873 TestError("table T { F:float; } root_type T; { F:+e1 }", invalid_msg);
1874 TestError("table T { F:float; } root_type T; { F:1.0e+ }", invalid_msg);
1875 TestError("table T { F:float; } root_type T; { F:1.0e- }", invalid_msg);
1876 // exponent pP is mandatory for hex-float
1877 TestError("table T { F:float; } root_type T; { F:0x0 }", invalid_msg);
1878 TestError("table T { F:float; } root_type T; { F:-0x. }", invalid_msg);
1879 TestError("table T { F:float; } root_type T; { F:0x. }", invalid_msg);
1880 // eE not exponent in hex-float!
1881 TestError("table T { F:float; } root_type T; { F:0x0.0e+ }", invalid_msg);
1882 TestError("table T { F:float; } root_type T; { F:0x0.0e- }", invalid_msg);
1883 TestError("table T { F:float; } root_type T; { F:0x0.0p }", invalid_msg);
1884 TestError("table T { F:float; } root_type T; { F:0x0.0p+ }", invalid_msg);
1885 TestError("table T { F:float; } root_type T; { F:0x0.0p- }", invalid_msg);
1886 TestError("table T { F:float; } root_type T; { F:0x0.0pa1 }", invalid_msg);
1887 TestError("table T { F:float; } root_type T; { F:0x0.0e+ }", invalid_msg);
1888 TestError("table T { F:float; } root_type T; { F:0x0.0e- }", invalid_msg);
1889 TestError("table T { F:float; } root_type T; { F:0x0.0e+0 }", invalid_msg);
1890 TestError("table T { F:float; } root_type T; { F:0x0.0e-0 }", invalid_msg);
1891 TestError("table T { F:float; } root_type T; { F:0x0.0ep+ }", invalid_msg);
1892 TestError("table T { F:float; } root_type T; { F:0x0.0ep- }", invalid_msg);
1893 TestError("table T { F:float; } root_type T; { F:1.2.3 }", invalid_msg);
1894 TestError("table T { F:float; } root_type T; { F:1.2.e3 }", invalid_msg);
1895 TestError("table T { F:float; } root_type T; { F:1.2e.3 }", invalid_msg);
1896 TestError("table T { F:float; } root_type T; { F:1.2e0.3 }", invalid_msg);
1897 TestError("table T { F:float; } root_type T; { F:1.2e3. }", invalid_msg);
1898 TestError("table T { F:float; } root_type T; { F:1.2e3.0 }", invalid_msg);
1899 TestError("table T { F:float; } root_type T; { F:+-1.0 }", invalid_msg);
1900 TestError("table T { F:float; } root_type T; { F:1.0e+-1 }", invalid_msg);
1901 TestError("table T { F:float; } root_type T; { F:\"1.0e+-1\" }", invalid_msg);
1902 TestError("table T { F:float; } root_type T; { F:1.e0e }", comma_msg);
1903 TestError("table T { F:float; } root_type T; { F:0x1.p0e }", comma_msg);
1904 TestError("table T { F:float; } root_type T; { F:\" 0x10 \" }", invalid_msg);
1906 TestError("table T { F:float; } root_type T; { F:\"1,2.\" }", invalid_msg);
1907 TestError("table T { F:float; } root_type T; { F:\"1.2e3.\" }", invalid_msg);
1908 TestError("table T { F:float; } root_type T; { F:\"0x1.p0e\" }", invalid_msg);
1909 TestError("table T { F:float; } root_type T; { F:\"0x1.0\" }", invalid_msg);
1910 TestError("table T { F:float; } root_type T; { F:\" 0x1.0\" }", invalid_msg);
1911 TestError("table T { F:float; } root_type T; { F:\"+ 0\" }", invalid_msg);
1912 // disable escapes for "number-in-string"
1913 TestError("table T { F:float; } root_type T; { F:\"\\f1.2e3.\" }", "invalid");
1914 TestError("table T { F:float; } root_type T; { F:\"\\t1.2e3.\" }", "invalid");
1915 TestError("table T { F:float; } root_type T; { F:\"\\n1.2e3.\" }", "invalid");
1916 TestError("table T { F:float; } root_type T; { F:\"\\r1.2e3.\" }", "invalid");
1917 TestError("table T { F:float; } root_type T; { F:\"4\\x005\" }", "invalid");
1918 TestError("table T { F:float; } root_type T; { F:\"\'12\'\" }", invalid_msg);
1919 // null is not a number constant!
1920 TestError("table T { F:float; } root_type T; { F:\"null\" }", invalid_msg);
1921 TestError("table T { F:float; } root_type T; { F:null }", invalid_msg);
1924 void GenerateTableTextTest() {
1925 std::string schemafile;
1926 std::string jsonfile;
1928 flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
1929 false, &schemafile) &&
1930 flatbuffers::LoadFile((test_data_path + "monsterdata_test.json").c_str(),
1933 auto include_test_path =
1934 flatbuffers::ConCatPathFileName(test_data_path, "include_test");
1935 const char *include_directories[] = {test_data_path.c_str(),
1936 include_test_path.c_str(), nullptr};
1937 flatbuffers::IDLOptions opt;
1938 opt.indent_step = -1;
1939 flatbuffers::Parser parser(opt);
1940 ok = parser.Parse(schemafile.c_str(), include_directories) &&
1941 parser.Parse(jsonfile.c_str(), include_directories);
1944 const Monster *monster = GetMonster(parser.builder_.GetBufferPointer());
1945 std::string jsongen;
1946 auto result = GenerateTextFromTable(parser, monster, "MyGame.Example.Monster",
1948 TEST_EQ(result, true);
1950 const Vec3 *pos = monster->pos();
1952 result = GenerateTextFromTable(parser, pos, "MyGame.Example.Vec3", &jsongen);
1953 TEST_EQ(result, true);
1956 "{x: 1.0,y: 2.0,z: 3.0,test1: 3.0,test2: \"Green\",test3: {a: 5,b: 6}}");
1957 const Test &test3 = pos->test3();
1960 GenerateTextFromTable(parser, &test3, "MyGame.Example.Test", &jsongen);
1961 TEST_EQ(result, true);
1962 TEST_EQ_STR(jsongen.c_str(), "{a: 5,b: 6}");
1963 const Test *test4 = monster->test4()->Get(0);
1966 GenerateTextFromTable(parser, test4, "MyGame.Example.Test", &jsongen);
1967 TEST_EQ(result, true);
1968 TEST_EQ_STR(jsongen.c_str(), "{a: 10,b: 20}");
1971 template<typename T>
1972 void NumericUtilsTestInteger(const char *lower, const char *upper) {
1974 TEST_EQ(flatbuffers::StringToNumber("1q", &x), false);
1976 TEST_EQ(flatbuffers::StringToNumber(upper, &x), false);
1977 TEST_EQ(x, flatbuffers::numeric_limits<T>::max());
1978 TEST_EQ(flatbuffers::StringToNumber(lower, &x), false);
1979 auto expval = flatbuffers::is_unsigned<T>::value
1980 ? flatbuffers::numeric_limits<T>::max()
1981 : flatbuffers::numeric_limits<T>::lowest();
1985 template<typename T>
1986 void NumericUtilsTestFloat(const char *lower, const char *upper) {
1988 TEST_EQ(flatbuffers::StringToNumber("", &f), false);
1989 TEST_EQ(flatbuffers::StringToNumber("1q", &f), false);
1991 TEST_EQ(flatbuffers::StringToNumber(upper, &f), true);
1992 TEST_EQ(f, +flatbuffers::numeric_limits<T>::infinity());
1993 TEST_EQ(flatbuffers::StringToNumber(lower, &f), true);
1994 TEST_EQ(f, -flatbuffers::numeric_limits<T>::infinity());
1997 void NumericUtilsTest() {
1998 NumericUtilsTestInteger<uint64_t>("-1", "18446744073709551616");
1999 NumericUtilsTestInteger<uint8_t>("-1", "256");
2000 NumericUtilsTestInteger<int64_t>("-9223372036854775809",
2001 "9223372036854775808");
2002 NumericUtilsTestInteger<int8_t>("-129", "128");
2003 NumericUtilsTestFloat<float>("-3.4029e+38", "+3.4029e+38");
2004 NumericUtilsTestFloat<float>("-1.7977e+308", "+1.7977e+308");
2007 void IsAsciiUtilsTest() {
2009 for (int cnt = 0; cnt < 256; cnt++) {
2010 auto alpha = (('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z'));
2011 auto dec = (('0' <= c) && (c <= '9'));
2012 auto hex = (('a' <= c) && (c <= 'f')) || (('A' <= c) && (c <= 'F'));
2013 TEST_EQ(flatbuffers::is_alpha(c), alpha);
2014 TEST_EQ(flatbuffers::is_alnum(c), alpha || dec);
2015 TEST_EQ(flatbuffers::is_digit(c), dec);
2016 TEST_EQ(flatbuffers::is_xdigit(c), dec || hex);
2021 void UnicodeTest() {
2022 flatbuffers::Parser parser;
2023 // Without setting allow_non_utf8 = true, we treat \x sequences as byte
2024 // sequences which are then validated as UTF-8.
2025 TEST_EQ(parser.Parse("table T { F:string; }"
2027 "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
2028 "\\u5225\\u30B5\\u30A4\\u30C8\\xE2\\x82\\xAC\\u0080\\uD8"
2031 std::string jsongen;
2032 parser.opts.indent_step = -1;
2034 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
2035 TEST_EQ(result, true);
2036 TEST_EQ_STR(jsongen.c_str(),
2037 "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
2038 "\\u5225\\u30B5\\u30A4\\u30C8\\u20AC\\u0080\\uD83D\\uDE0E\"}");
2041 void UnicodeTestAllowNonUTF8() {
2042 flatbuffers::Parser parser;
2043 parser.opts.allow_non_utf8 = true;
2046 "table T { F:string; }"
2048 "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
2049 "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"),
2051 std::string jsongen;
2052 parser.opts.indent_step = -1;
2054 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
2055 TEST_EQ(result, true);
2058 "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
2059 "\\u5225\\u30B5\\u30A4\\u30C8\\u0001\\x80\\u0080\\uD83D\\uDE0E\"}");
2062 void UnicodeTestGenerateTextFailsOnNonUTF8() {
2063 flatbuffers::Parser parser;
2064 // Allow non-UTF-8 initially to model what happens when we load a binary
2065 // flatbuffer from disk which contains non-UTF-8 strings.
2066 parser.opts.allow_non_utf8 = true;
2069 "table T { F:string; }"
2071 "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
2072 "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"),
2074 std::string jsongen;
2075 parser.opts.indent_step = -1;
2076 // Now, disallow non-UTF-8 (the default behavior) so GenerateText indicates
2078 parser.opts.allow_non_utf8 = false;
2080 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
2081 TEST_EQ(result, false);
2084 void UnicodeSurrogatesTest() {
2085 flatbuffers::Parser parser;
2087 TEST_EQ(parser.Parse("table T { F:string (id: 0); }"
2089 "{ F:\"\\uD83D\\uDCA9\"}"),
2091 auto root = flatbuffers::GetRoot<flatbuffers::Table>(
2092 parser.builder_.GetBufferPointer());
2093 auto string = root->GetPointer<flatbuffers::String *>(
2094 flatbuffers::FieldIndexToOffset(0));
2095 TEST_EQ_STR(string->c_str(), "\xF0\x9F\x92\xA9");
2098 void UnicodeInvalidSurrogatesTest() {
2100 "table T { F:string; }"
2103 "unpaired high surrogate");
2105 "table T { F:string; }"
2107 "{ F:\"\\uD800abcd\"}",
2108 "unpaired high surrogate");
2110 "table T { F:string; }"
2112 "{ F:\"\\uD800\\n\"}",
2113 "unpaired high surrogate");
2115 "table T { F:string; }"
2117 "{ F:\"\\uD800\\uD800\"}",
2118 "multiple high surrogates");
2120 "table T { F:string; }"
2123 "unpaired low surrogate");
2126 void InvalidUTF8Test() {
2127 // "1 byte" pattern, under min length of 2 bytes
2129 "table T { F:string; }"
2132 "illegal UTF-8 sequence");
2133 // 2 byte pattern, string too short
2135 "table T { F:string; }"
2138 "illegal UTF-8 sequence");
2139 // 3 byte pattern, string too short
2141 "table T { F:string; }"
2143 "{ F:\"\xEF\xBF\"}",
2144 "illegal UTF-8 sequence");
2145 // 4 byte pattern, string too short
2147 "table T { F:string; }"
2149 "{ F:\"\xF7\xBF\xBF\"}",
2150 "illegal UTF-8 sequence");
2151 // "5 byte" pattern, string too short
2153 "table T { F:string; }"
2155 "{ F:\"\xFB\xBF\xBF\xBF\"}",
2156 "illegal UTF-8 sequence");
2157 // "6 byte" pattern, string too short
2159 "table T { F:string; }"
2161 "{ F:\"\xFD\xBF\xBF\xBF\xBF\"}",
2162 "illegal UTF-8 sequence");
2163 // "7 byte" pattern, string too short
2165 "table T { F:string; }"
2167 "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\"}",
2168 "illegal UTF-8 sequence");
2169 // "5 byte" pattern, over max length of 4 bytes
2171 "table T { F:string; }"
2173 "{ F:\"\xFB\xBF\xBF\xBF\xBF\"}",
2174 "illegal UTF-8 sequence");
2175 // "6 byte" pattern, over max length of 4 bytes
2177 "table T { F:string; }"
2179 "{ F:\"\xFD\xBF\xBF\xBF\xBF\xBF\"}",
2180 "illegal UTF-8 sequence");
2181 // "7 byte" pattern, over max length of 4 bytes
2183 "table T { F:string; }"
2185 "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\xBF\"}",
2186 "illegal UTF-8 sequence");
2188 // Three invalid encodings for U+000A (\n, aka NEWLINE)
2190 "table T { F:string; }"
2192 "{ F:\"\xC0\x8A\"}",
2193 "illegal UTF-8 sequence");
2195 "table T { F:string; }"
2197 "{ F:\"\xE0\x80\x8A\"}",
2198 "illegal UTF-8 sequence");
2200 "table T { F:string; }"
2202 "{ F:\"\xF0\x80\x80\x8A\"}",
2203 "illegal UTF-8 sequence");
2205 // Two invalid encodings for U+00A9 (COPYRIGHT SYMBOL)
2207 "table T { F:string; }"
2209 "{ F:\"\xE0\x81\xA9\"}",
2210 "illegal UTF-8 sequence");
2212 "table T { F:string; }"
2214 "{ F:\"\xF0\x80\x81\xA9\"}",
2215 "illegal UTF-8 sequence");
2217 // Invalid encoding for U+20AC (EURO SYMBOL)
2219 "table T { F:string; }"
2221 "{ F:\"\xF0\x82\x82\xAC\"}",
2222 "illegal UTF-8 sequence");
2224 // UTF-16 surrogate values between U+D800 and U+DFFF cannot be encoded in
2227 "table T { F:string; }"
2229 // U+10400 "encoded" as U+D801 U+DC00
2230 "{ F:\"\xED\xA0\x81\xED\xB0\x80\"}",
2231 "illegal UTF-8 sequence");
2233 // Check independence of identifier from locale.
2234 std::string locale_ident;
2235 locale_ident += "table T { F";
2236 locale_ident += static_cast<char>(-32); // unsigned 0xE0
2237 locale_ident += " :string; }";
2238 locale_ident += "root_type T;";
2239 locale_ident += "{}";
2240 TestError(locale_ident.c_str(), "");
2243 void UnknownFieldsTest() {
2244 flatbuffers::IDLOptions opts;
2245 opts.skip_unexpected_fields_in_json = true;
2246 flatbuffers::Parser parser(opts);
2248 TEST_EQ(parser.Parse("table T { str:string; i:int;}"
2251 "unknown_string:\"test\","
2252 "\"unknown_string\":\"test\","
2254 "unknown_float:1.0,"
2255 "unknown_array: [ 1, 2, 3, 4],"
2256 "unknown_object: { i: 10 },"
2257 "\"unknown_object\": { \"i\": 10 },"
2261 std::string jsongen;
2262 parser.opts.indent_step = -1;
2264 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
2265 TEST_EQ(result, true);
2266 TEST_EQ_STR(jsongen.c_str(), "{str: \"test\",i: 10}");
2269 void ParseUnionTest() {
2270 // Unions must be parseable with the type field following the object.
2271 flatbuffers::Parser parser;
2272 TEST_EQ(parser.Parse("table T { A:int; }"
2276 "{ X:{ A:1 }, X_type: T }"),
2278 // Unions must be parsable with prefixed namespace.
2279 flatbuffers::Parser parser2;
2280 TEST_EQ(parser2.Parse("namespace N; table A {} namespace; union U { N.A }"
2281 "table B { e:U; } root_type B;"
2282 "{ e_type: N_A, e: {} }"),
2286 void InvalidNestedFlatbufferTest() {
2287 // First, load and parse FlatBuffer schema (.fbs)
2288 std::string schemafile;
2289 TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
2290 false, &schemafile),
2292 auto include_test_path =
2293 flatbuffers::ConCatPathFileName(test_data_path, "include_test");
2294 const char *include_directories[] = { test_data_path.c_str(),
2295 include_test_path.c_str(), nullptr };
2296 flatbuffers::Parser parser1;
2297 TEST_EQ(parser1.Parse(schemafile.c_str(), include_directories), true);
2299 // "color" inside nested flatbuffer contains invalid enum value
2300 TEST_EQ(parser1.Parse("{ name: \"Bender\", testnestedflatbuffer: { name: "
2301 "\"Leela\", color: \"nonexistent\"}}"),
2303 // Check that Parser is destroyed correctly after parsing invalid json
2306 void UnionVectorTest() {
2307 // load FlatBuffer fbs schema and json.
2308 std::string schemafile, jsonfile;
2309 TEST_EQ(flatbuffers::LoadFile(
2310 (test_data_path + "union_vector/union_vector.fbs").c_str(),
2311 false, &schemafile),
2313 TEST_EQ(flatbuffers::LoadFile(
2314 (test_data_path + "union_vector/union_vector.json").c_str(),
2319 flatbuffers::IDLOptions idl_opts;
2320 idl_opts.lang_to_generate |= flatbuffers::IDLOptions::kBinary;
2321 flatbuffers::Parser parser(idl_opts);
2322 TEST_EQ(parser.Parse(schemafile.c_str()), true);
2324 flatbuffers::FlatBufferBuilder fbb;
2327 std::vector<uint8_t> types;
2328 types.push_back(static_cast<uint8_t>(Character_Belle));
2329 types.push_back(static_cast<uint8_t>(Character_MuLan));
2330 types.push_back(static_cast<uint8_t>(Character_BookFan));
2331 types.push_back(static_cast<uint8_t>(Character_Other));
2332 types.push_back(static_cast<uint8_t>(Character_Unused));
2335 std::vector<flatbuffers::Offset<void>> characters;
2336 characters.push_back(fbb.CreateStruct(BookReader(/*books_read=*/7)).Union());
2337 characters.push_back(CreateAttacker(fbb, /*sword_attack_damage=*/5).Union());
2338 characters.push_back(fbb.CreateStruct(BookReader(/*books_read=*/2)).Union());
2339 characters.push_back(fbb.CreateString("Other").Union());
2340 characters.push_back(fbb.CreateString("Unused").Union());
2343 const auto movie_offset =
2344 CreateMovie(fbb, Character_Rapunzel,
2345 fbb.CreateStruct(Rapunzel(/*hair_length=*/6)).Union(),
2346 fbb.CreateVector(types), fbb.CreateVector(characters));
2347 FinishMovieBuffer(fbb, movie_offset);
2348 auto buf = fbb.GetBufferPointer();
2350 flatbuffers::Verifier verifier(buf, fbb.GetSize());
2351 TEST_EQ(VerifyMovieBuffer(verifier), true);
2353 auto flat_movie = GetMovie(buf);
2355 auto TestMovie = [](const Movie *movie) {
2356 TEST_EQ(movie->main_character_type() == Character_Rapunzel, true);
2358 auto cts = movie->characters_type();
2359 TEST_EQ(movie->characters_type()->size(), 5);
2360 TEST_EQ(cts->GetEnum<Character>(0) == Character_Belle, true);
2361 TEST_EQ(cts->GetEnum<Character>(1) == Character_MuLan, true);
2362 TEST_EQ(cts->GetEnum<Character>(2) == Character_BookFan, true);
2363 TEST_EQ(cts->GetEnum<Character>(3) == Character_Other, true);
2364 TEST_EQ(cts->GetEnum<Character>(4) == Character_Unused, true);
2366 auto rapunzel = movie->main_character_as_Rapunzel();
2367 TEST_NOTNULL(rapunzel);
2368 TEST_EQ(rapunzel->hair_length(), 6);
2370 auto cs = movie->characters();
2371 TEST_EQ(cs->size(), 5);
2372 auto belle = cs->GetAs<BookReader>(0);
2373 TEST_EQ(belle->books_read(), 7);
2374 auto mu_lan = cs->GetAs<Attacker>(1);
2375 TEST_EQ(mu_lan->sword_attack_damage(), 5);
2376 auto book_fan = cs->GetAs<BookReader>(2);
2377 TEST_EQ(book_fan->books_read(), 2);
2378 auto other = cs->GetAsString(3);
2379 TEST_EQ_STR(other->c_str(), "Other");
2380 auto unused = cs->GetAsString(4);
2381 TEST_EQ_STR(unused->c_str(), "Unused");
2384 TestMovie(flat_movie);
2386 // Also test the JSON we loaded above.
2387 TEST_EQ(parser.Parse(jsonfile.c_str()), true);
2388 auto jbuf = parser.builder_.GetBufferPointer();
2389 flatbuffers::Verifier jverifier(jbuf, parser.builder_.GetSize());
2390 TEST_EQ(VerifyMovieBuffer(jverifier), true);
2391 TestMovie(GetMovie(jbuf));
2393 auto movie_object = flat_movie->UnPack();
2394 TEST_EQ(movie_object->main_character.AsRapunzel()->hair_length(), 6);
2395 TEST_EQ(movie_object->characters[0].AsBelle()->books_read(), 7);
2396 TEST_EQ(movie_object->characters[1].AsMuLan()->sword_attack_damage, 5);
2397 TEST_EQ(movie_object->characters[2].AsBookFan()->books_read(), 2);
2398 TEST_EQ_STR(movie_object->characters[3].AsOther()->c_str(), "Other");
2399 TEST_EQ_STR(movie_object->characters[4].AsUnused()->c_str(), "Unused");
2402 fbb.Finish(Movie::Pack(fbb, movie_object));
2404 delete movie_object;
2406 auto repacked_movie = GetMovie(fbb.GetBufferPointer());
2408 TestMovie(repacked_movie);
2411 flatbuffers::FlatBufferToString(fbb.GetBufferPointer(), MovieTypeTable());
2414 "{ main_character_type: Rapunzel, main_character: { hair_length: 6 }, "
2415 "characters_type: [ Belle, MuLan, BookFan, Other, Unused ], "
2416 "characters: [ { books_read: 7 }, { sword_attack_damage: 5 }, "
2417 "{ books_read: 2 }, \"Other\", \"Unused\" ] }");
2420 flatbuffers::ToStringVisitor visitor("\n", true, " ");
2421 IterateFlatBuffer(fbb.GetBufferPointer(), MovieTypeTable(), &visitor);
2425 " \"main_character_type\": \"Rapunzel\",\n"
2426 " \"main_character\": {\n"
2427 " \"hair_length\": 6\n"
2429 " \"characters_type\": [\n"
2436 " \"characters\": [\n"
2438 " \"books_read\": 7\n"
2441 " \"sword_attack_damage\": 5\n"
2444 " \"books_read\": 2\n"
2451 flatbuffers::Parser parser2(idl_opts);
2452 TEST_EQ(parser2.Parse("struct Bool { b:bool; }"
2453 "union Any { Bool }"
2454 "table Root { a:Any; }"
2455 "root_type Root;"), true);
2456 TEST_EQ(parser2.Parse("{a_type:Bool,a:{b:true}}"), true);
2459 void ConformTest() {
2460 flatbuffers::Parser parser;
2461 TEST_EQ(parser.Parse("table T { A:int; } enum E:byte { A }"), true);
2463 auto test_conform = [](flatbuffers::Parser &parser1, const char *test,
2464 const char *expected_err) {
2465 flatbuffers::Parser parser2;
2466 TEST_EQ(parser2.Parse(test), true);
2467 auto err = parser2.ConformTo(parser1);
2468 TEST_NOTNULL(strstr(err.c_str(), expected_err));
2471 test_conform(parser, "table T { A:byte; }", "types differ for field");
2472 test_conform(parser, "table T { B:int; A:int; }", "offsets differ for field");
2473 test_conform(parser, "table T { A:int = 1; }", "defaults differ for field");
2474 test_conform(parser, "table T { B:float; }",
2475 "field renamed to different type");
2476 test_conform(parser, "enum E:byte { B, A }", "values differ for enum");
2479 void ParseProtoBufAsciiTest() {
2480 // We can put the parser in a mode where it will accept JSON that looks more
2481 // like Protobuf ASCII, for users that have data in that format.
2482 // This uses no "" for field names (which we already support by default,
2483 // omits `,`, `:` before `{` and a couple of other features.
2484 flatbuffers::Parser parser;
2485 parser.opts.protobuf_ascii_alike = true;
2487 parser.Parse("table S { B:int; } table T { A:[int]; C:S; } root_type T;"),
2489 TEST_EQ(parser.Parse("{ A [1 2] C { B:2 }}"), true);
2490 // Similarly, in text output, it should omit these.
2492 auto ok = flatbuffers::GenerateText(
2493 parser, parser.builder_.GetBufferPointer(), &text);
2495 TEST_EQ_STR(text.c_str(),
2496 "{\n A [\n 1\n 2\n ]\n C {\n B: 2\n }\n}\n");
2499 void FlexBuffersTest() {
2500 flexbuffers::Builder slb(512,
2501 flexbuffers::BUILDER_FLAG_SHARE_KEYS_AND_STRINGS);
2503 // Write the equivalent of:
2504 // { vec: [ -100, "Fred", 4.0, false ], bar: [ 1, 2, 3 ], bar3: [ 1, 2, 3 ],
2505 // foo: 100, bool: true, mymap: { foo: "Fred" } }
2507 #ifndef FLATBUFFERS_CPP98_STL
2508 // It's possible to do this without std::function support as well.
2510 slb.Vector("vec", [&]() {
2511 slb += -100; // Equivalent to slb.Add(-100) or slb.Int(-100);
2513 slb.IndirectFloat(4.0f);
2514 uint8_t blob[] = { 77 };
2518 int ints[] = { 1, 2, 3 };
2519 slb.Vector("bar", ints, 3);
2520 slb.FixedTypedVector("bar3", ints, 3);
2521 bool bools[] = {true, false, true, false};
2522 slb.Vector("bools", bools, 4);
2523 slb.Bool("bool", true);
2524 slb.Double("foo", 100);
2525 slb.Map("mymap", [&]() {
2526 slb.String("foo", "Fred"); // Testing key and string reuse.
2531 // It's possible to do this without std::function support as well.
2532 slb.Map([](flexbuffers::Builder& slb2) {
2533 slb2.Vector("vec", [](flexbuffers::Builder& slb3) {
2534 slb3 += -100; // Equivalent to slb.Add(-100) or slb.Int(-100);
2536 slb3.IndirectFloat(4.0f);
2537 uint8_t blob[] = { 77 };
2541 int ints[] = { 1, 2, 3 };
2542 slb2.Vector("bar", ints, 3);
2543 slb2.FixedTypedVector("bar3", ints, 3);
2544 slb2.Bool("bool", true);
2545 slb2.Double("foo", 100);
2546 slb2.Map("mymap", [](flexbuffers::Builder& slb3) {
2547 slb3.String("foo", "Fred"); // Testing key and string reuse.
2551 #endif // FLATBUFFERS_CPP98_STL
2553 #ifdef FLATBUFFERS_TEST_VERBOSE
2554 for (size_t i = 0; i < slb.GetBuffer().size(); i++)
2555 printf("%d ", flatbuffers::vector_data(slb.GetBuffer())[i]);
2560 auto map = flexbuffers::GetRoot(slb.GetBuffer()).AsMap();
2561 TEST_EQ(map.size(), 7);
2562 auto vec = map["vec"].AsVector();
2563 TEST_EQ(vec.size(), 5);
2564 TEST_EQ(vec[0].AsInt64(), -100);
2565 TEST_EQ_STR(vec[1].AsString().c_str(), "Fred");
2566 TEST_EQ(vec[1].AsInt64(), 0); // Number parsing failed.
2567 TEST_EQ(vec[2].AsDouble(), 4.0);
2568 TEST_EQ(vec[2].AsString().IsTheEmptyString(), true); // Wrong Type.
2569 TEST_EQ_STR(vec[2].AsString().c_str(), ""); // This still works though.
2570 TEST_EQ_STR(vec[2].ToString().c_str(), "4.0"); // Or have it converted.
2572 // Few tests for templated version of As.
2573 TEST_EQ(vec[0].As<int64_t>(), -100);
2574 TEST_EQ_STR(vec[1].As<std::string>().c_str(), "Fred");
2575 TEST_EQ(vec[1].As<int64_t>(), 0); // Number parsing failed.
2576 TEST_EQ(vec[2].As<double>(), 4.0);
2578 // Test that the blob can be accessed.
2579 TEST_EQ(vec[3].IsBlob(), true);
2580 auto blob = vec[3].AsBlob();
2581 TEST_EQ(blob.size(), 1);
2582 TEST_EQ(blob.data()[0], 77);
2583 TEST_EQ(vec[4].IsBool(), true); // Check if type is a bool
2584 TEST_EQ(vec[4].AsBool(), false); // Check if value is false
2585 auto tvec = map["bar"].AsTypedVector();
2586 TEST_EQ(tvec.size(), 3);
2587 TEST_EQ(tvec[2].AsInt8(), 3);
2588 auto tvec3 = map["bar3"].AsFixedTypedVector();
2589 TEST_EQ(tvec3.size(), 3);
2590 TEST_EQ(tvec3[2].AsInt8(), 3);
2591 TEST_EQ(map["bool"].AsBool(), true);
2592 auto tvecb = map["bools"].AsTypedVector();
2593 TEST_EQ(tvecb.ElementType(), flexbuffers::FBT_BOOL);
2594 TEST_EQ(map["foo"].AsUInt8(), 100);
2595 TEST_EQ(map["unknown"].IsNull(), true);
2596 auto mymap = map["mymap"].AsMap();
2597 // These should be equal by pointer equality, since key and value are shared.
2598 TEST_EQ(mymap.Keys()[0].AsKey(), map.Keys()[4].AsKey());
2599 TEST_EQ(mymap.Values()[0].AsString().c_str(), vec[1].AsString().c_str());
2600 // We can mutate values in the buffer.
2601 TEST_EQ(vec[0].MutateInt(-99), true);
2602 TEST_EQ(vec[0].AsInt64(), -99);
2603 TEST_EQ(vec[1].MutateString("John"), true); // Size must match.
2604 TEST_EQ_STR(vec[1].AsString().c_str(), "John");
2605 TEST_EQ(vec[1].MutateString("Alfred"), false); // Too long.
2606 TEST_EQ(vec[2].MutateFloat(2.0f), true);
2607 TEST_EQ(vec[2].AsFloat(), 2.0f);
2608 TEST_EQ(vec[2].MutateFloat(3.14159), false); // Double does not fit in float.
2609 TEST_EQ(vec[4].AsBool(), false); // Is false before change
2610 TEST_EQ(vec[4].MutateBool(true), true); // Can change a bool
2611 TEST_EQ(vec[4].AsBool(), true); // Changed bool is now true
2614 flatbuffers::Parser parser;
2616 auto jsontest = "{ a: [ 123, 456.0 ], b: \"hello\", c: true, d: false }";
2617 TEST_EQ(parser.ParseFlexBuffer(jsontest, nullptr, &slb), true);
2618 auto jroot = flexbuffers::GetRoot(slb.GetBuffer());
2619 auto jmap = jroot.AsMap();
2620 auto jvec = jmap["a"].AsVector();
2621 TEST_EQ(jvec[0].AsInt64(), 123);
2622 TEST_EQ(jvec[1].AsDouble(), 456.0);
2623 TEST_EQ_STR(jmap["b"].AsString().c_str(), "hello");
2624 TEST_EQ(jmap["c"].IsBool(), true); // Parsed correctly to a bool
2625 TEST_EQ(jmap["c"].AsBool(), true); // Parsed correctly to true
2626 TEST_EQ(jmap["d"].IsBool(), true); // Parsed correctly to a bool
2627 TEST_EQ(jmap["d"].AsBool(), false); // Parsed correctly to false
2628 // And from FlexBuffer back to JSON:
2629 auto jsonback = jroot.ToString();
2630 TEST_EQ_STR(jsontest, jsonback.c_str());
2633 void TypeAliasesTest() {
2634 flatbuffers::FlatBufferBuilder builder;
2636 builder.Finish(CreateTypeAliases(
2637 builder, flatbuffers::numeric_limits<int8_t>::min(),
2638 flatbuffers::numeric_limits<uint8_t>::max(),
2639 flatbuffers::numeric_limits<int16_t>::min(),
2640 flatbuffers::numeric_limits<uint16_t>::max(),
2641 flatbuffers::numeric_limits<int32_t>::min(),
2642 flatbuffers::numeric_limits<uint32_t>::max(),
2643 flatbuffers::numeric_limits<int64_t>::min(),
2644 flatbuffers::numeric_limits<uint64_t>::max(), 2.3f, 2.3));
2646 auto p = builder.GetBufferPointer();
2647 auto ta = flatbuffers::GetRoot<TypeAliases>(p);
2649 TEST_EQ(ta->i8(), flatbuffers::numeric_limits<int8_t>::min());
2650 TEST_EQ(ta->u8(), flatbuffers::numeric_limits<uint8_t>::max());
2651 TEST_EQ(ta->i16(), flatbuffers::numeric_limits<int16_t>::min());
2652 TEST_EQ(ta->u16(), flatbuffers::numeric_limits<uint16_t>::max());
2653 TEST_EQ(ta->i32(), flatbuffers::numeric_limits<int32_t>::min());
2654 TEST_EQ(ta->u32(), flatbuffers::numeric_limits<uint32_t>::max());
2655 TEST_EQ(ta->i64(), flatbuffers::numeric_limits<int64_t>::min());
2656 TEST_EQ(ta->u64(), flatbuffers::numeric_limits<uint64_t>::max());
2657 TEST_EQ(ta->f32(), 2.3f);
2658 TEST_EQ(ta->f64(), 2.3);
2659 using namespace flatbuffers; // is_same
2660 static_assert(is_same<decltype(ta->i8()), int8_t>::value, "invalid type");
2661 static_assert(is_same<decltype(ta->i16()), int16_t>::value, "invalid type");
2662 static_assert(is_same<decltype(ta->i32()), int32_t>::value, "invalid type");
2663 static_assert(is_same<decltype(ta->i64()), int64_t>::value, "invalid type");
2664 static_assert(is_same<decltype(ta->u8()), uint8_t>::value, "invalid type");
2665 static_assert(is_same<decltype(ta->u16()), uint16_t>::value, "invalid type");
2666 static_assert(is_same<decltype(ta->u32()), uint32_t>::value, "invalid type");
2667 static_assert(is_same<decltype(ta->u64()), uint64_t>::value, "invalid type");
2668 static_assert(is_same<decltype(ta->f32()), float>::value, "invalid type");
2669 static_assert(is_same<decltype(ta->f64()), double>::value, "invalid type");
2672 void EndianSwapTest() {
2673 TEST_EQ(flatbuffers::EndianSwap(static_cast<int16_t>(0x1234)), 0x3412);
2674 TEST_EQ(flatbuffers::EndianSwap(static_cast<int32_t>(0x12345678)),
2676 TEST_EQ(flatbuffers::EndianSwap(static_cast<int64_t>(0x1234567890ABCDEF)),
2677 0xEFCDAB9078563412);
2678 TEST_EQ(flatbuffers::EndianSwap(flatbuffers::EndianSwap(3.14f)), 3.14f);
2681 void UninitializedVectorTest() {
2682 flatbuffers::FlatBufferBuilder builder;
2684 Test *buf = nullptr;
2685 auto vector_offset = builder.CreateUninitializedVectorOfStructs<Test>(2, &buf);
2687 buf[0] = Test(10, 20);
2688 buf[1] = Test(30, 40);
2690 auto required_name = builder.CreateString("myMonster");
2691 auto monster_builder = MonsterBuilder(builder);
2692 monster_builder.add_name(required_name); // required field mandated for monster.
2693 monster_builder.add_test4(vector_offset);
2694 builder.Finish(monster_builder.Finish());
2696 auto p = builder.GetBufferPointer();
2697 auto uvt = flatbuffers::GetRoot<Monster>(p);
2699 auto vec = uvt->test4();
2701 auto test_0 = vec->Get(0);
2702 auto test_1 = vec->Get(1);
2703 TEST_EQ(test_0->a(), 10);
2704 TEST_EQ(test_0->b(), 20);
2705 TEST_EQ(test_1->a(), 30);
2706 TEST_EQ(test_1->b(), 40);
2709 void EqualOperatorTest() {
2712 TEST_EQ(b == a, true);
2713 TEST_EQ(b != a, false);
2716 TEST_EQ(b == a, false);
2717 TEST_EQ(b != a, true);
2719 TEST_EQ(b == a, true);
2720 TEST_EQ(b != a, false);
2722 b.inventory.push_back(3);
2723 TEST_EQ(b == a, false);
2724 TEST_EQ(b != a, true);
2725 b.inventory.clear();
2726 TEST_EQ(b == a, true);
2727 TEST_EQ(b != a, false);
2729 b.test.type = Any_Monster;
2730 TEST_EQ(b == a, false);
2731 TEST_EQ(b != a, true);
2734 // For testing any binaries, e.g. from fuzzing.
2735 void LoadVerifyBinaryTest() {
2737 if (flatbuffers::LoadFile((test_data_path +
2738 "fuzzer/your-filename-here").c_str(),
2740 flatbuffers::Verifier verifier(
2741 reinterpret_cast<const uint8_t *>(binary.data()), binary.size());
2742 TEST_EQ(VerifyMonsterBuffer(verifier), true);
2746 void CreateSharedStringTest() {
2747 flatbuffers::FlatBufferBuilder builder;
2748 const auto one1 = builder.CreateSharedString("one");
2749 const auto two = builder.CreateSharedString("two");
2750 const auto one2 = builder.CreateSharedString("one");
2751 TEST_EQ(one1.o, one2.o);
2752 const auto onetwo = builder.CreateSharedString("onetwo");
2753 TEST_EQ(onetwo.o != one1.o, true);
2754 TEST_EQ(onetwo.o != two.o, true);
2756 // Support for embedded nulls
2757 const char chars_b[] = {'a', '\0', 'b'};
2758 const char chars_c[] = {'a', '\0', 'c'};
2759 const auto null_b1 = builder.CreateSharedString(chars_b, sizeof(chars_b));
2760 const auto null_c = builder.CreateSharedString(chars_c, sizeof(chars_c));
2761 const auto null_b2 = builder.CreateSharedString(chars_b, sizeof(chars_b));
2762 TEST_EQ(null_b1.o != null_c.o, true); // Issue#5058 repro
2763 TEST_EQ(null_b1.o, null_b2.o);
2765 // Put the strings into an array for round trip verification.
2766 const flatbuffers::Offset<flatbuffers::String> array[7] = { one1, two, one2, onetwo, null_b1, null_c, null_b2 };
2767 const auto vector_offset = builder.CreateVector(array, flatbuffers::uoffset_t(7));
2768 MonsterBuilder monster_builder(builder);
2769 monster_builder.add_name(two);
2770 monster_builder.add_testarrayofstring(vector_offset);
2771 builder.Finish(monster_builder.Finish());
2773 // Read the Monster back.
2774 const auto *monster = flatbuffers::GetRoot<Monster>(builder.GetBufferPointer());
2775 TEST_EQ_STR(monster->name()->c_str(), "two");
2776 const auto *testarrayofstring = monster->testarrayofstring();
2777 TEST_EQ(testarrayofstring->size(), flatbuffers::uoffset_t(7));
2778 const auto &a = *testarrayofstring;
2779 TEST_EQ_STR(a[0]->c_str(), "one");
2780 TEST_EQ_STR(a[1]->c_str(), "two");
2781 TEST_EQ_STR(a[2]->c_str(), "one");
2782 TEST_EQ_STR(a[3]->c_str(), "onetwo");
2783 TEST_EQ(a[4]->str(), (std::string(chars_b, sizeof(chars_b))));
2784 TEST_EQ(a[5]->str(), (std::string(chars_c, sizeof(chars_c))));
2785 TEST_EQ(a[6]->str(), (std::string(chars_b, sizeof(chars_b))));
2787 // Make sure String::operator< works, too, since it is related to StringOffsetCompare.
2788 TEST_EQ((*a[0]) < (*a[1]), true);
2789 TEST_EQ((*a[1]) < (*a[0]), false);
2790 TEST_EQ((*a[1]) < (*a[2]), false);
2791 TEST_EQ((*a[2]) < (*a[1]), true);
2792 TEST_EQ((*a[4]) < (*a[3]), true);
2793 TEST_EQ((*a[5]) < (*a[4]), false);
2794 TEST_EQ((*a[5]) < (*a[4]), false);
2795 TEST_EQ((*a[6]) < (*a[5]), true);
2798 void FixedLengthArrayTest() {
2799 // VS10 does not support typed enums, exclude from tests
2800 #if !defined(_MSC_VER) || _MSC_VER >= 1700
2801 // Generate an ArrayTable containing one ArrayStruct.
2802 flatbuffers::FlatBufferBuilder fbb;
2803 MyGame::Example::NestedStruct nStruct0(MyGame::Example::TestEnum::B);
2804 TEST_NOTNULL(nStruct0.mutable_a());
2805 nStruct0.mutable_a()->Mutate(0, 1);
2806 nStruct0.mutable_a()->Mutate(1, 2);
2807 TEST_NOTNULL(nStruct0.mutable_c());
2808 nStruct0.mutable_c()->Mutate(0, MyGame::Example::TestEnum::C);
2809 nStruct0.mutable_c()->Mutate(1, MyGame::Example::TestEnum::A);
2810 MyGame::Example::NestedStruct nStruct1(MyGame::Example::TestEnum::C);
2811 TEST_NOTNULL(nStruct1.mutable_a());
2812 nStruct1.mutable_a()->Mutate(0, 3);
2813 nStruct1.mutable_a()->Mutate(1, 4);
2814 TEST_NOTNULL(nStruct1.mutable_c());
2815 nStruct1.mutable_c()->Mutate(0, MyGame::Example::TestEnum::C);
2816 nStruct1.mutable_c()->Mutate(1, MyGame::Example::TestEnum::A);
2817 MyGame::Example::ArrayStruct aStruct(2, 12);
2818 TEST_NOTNULL(aStruct.b());
2819 TEST_NOTNULL(aStruct.mutable_b());
2820 TEST_NOTNULL(aStruct.mutable_d());
2821 for (int i = 0; i < aStruct.b()->size(); i++)
2822 aStruct.mutable_b()->Mutate(i, i + 1);
2823 aStruct.mutable_d()->Mutate(0, nStruct0);
2824 aStruct.mutable_d()->Mutate(1, nStruct1);
2825 auto aTable = MyGame::Example::CreateArrayTable(fbb, &aStruct);
2828 // Verify correctness of the ArrayTable.
2829 flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize());
2830 MyGame::Example::VerifyArrayTableBuffer(verifier);
2831 auto p = MyGame::Example::GetMutableArrayTable(fbb.GetBufferPointer());
2832 auto mArStruct = p->mutable_a();
2833 TEST_NOTNULL(mArStruct);
2834 TEST_NOTNULL(mArStruct->b());
2835 TEST_NOTNULL(mArStruct->d());
2836 TEST_NOTNULL(mArStruct->mutable_b());
2837 TEST_NOTNULL(mArStruct->mutable_d());
2838 mArStruct->mutable_b()->Mutate(14, -14);
2839 TEST_EQ(mArStruct->a(), 2);
2840 TEST_EQ(mArStruct->b()->size(), 15);
2841 TEST_EQ(mArStruct->b()->Get(aStruct.b()->size() - 1), -14);
2842 TEST_EQ(mArStruct->c(), 12);
2843 TEST_NOTNULL(mArStruct->d()->Get(0).a());
2844 TEST_EQ(mArStruct->d()->Get(0).a()->Get(0), 1);
2845 TEST_EQ(mArStruct->d()->Get(0).a()->Get(1), 2);
2846 TEST_NOTNULL(mArStruct->d()->Get(1).a());
2847 TEST_EQ(mArStruct->d()->Get(1).a()->Get(0), 3);
2848 TEST_EQ(mArStruct->d()->Get(1).a()->Get(1), 4);
2849 TEST_NOTNULL(mArStruct->mutable_d()->GetMutablePointer(1));
2850 TEST_NOTNULL(mArStruct->mutable_d()->GetMutablePointer(1)->mutable_a());
2851 mArStruct->mutable_d()->GetMutablePointer(1)->mutable_a()->Mutate(1, 5);
2852 TEST_EQ(mArStruct->d()->Get(1).a()->Get(1), 5);
2853 TEST_EQ(mArStruct->d()->Get(0).b() == MyGame::Example::TestEnum::B, true);
2854 TEST_NOTNULL(mArStruct->d()->Get(0).c());
2855 TEST_EQ(mArStruct->d()->Get(0).c()->Get(0) == MyGame::Example::TestEnum::C,
2857 TEST_EQ(mArStruct->d()->Get(0).c()->Get(1) == MyGame::Example::TestEnum::A,
2859 TEST_EQ(mArStruct->d()->Get(1).b() == MyGame::Example::TestEnum::C, true);
2860 TEST_NOTNULL(mArStruct->d()->Get(1).c());
2861 TEST_EQ(mArStruct->d()->Get(1).c()->Get(0) == MyGame::Example::TestEnum::C,
2863 TEST_EQ(mArStruct->d()->Get(1).c()->Get(1) == MyGame::Example::TestEnum::A,
2865 for (int i = 0; i < mArStruct->b()->size() - 1; i++)
2866 TEST_EQ(mArStruct->b()->Get(i), i + 1);
2870 void FixedLengthArrayJsonTest(bool binary) {
2871 // VS10 does not support typed enums, exclude from tests
2872 #if !defined(_MSC_VER) || _MSC_VER >= 1700
2873 // load FlatBuffer schema (.fbs) and JSON from disk
2874 std::string schemafile;
2875 std::string jsonfile;
2877 flatbuffers::LoadFile(
2878 (test_data_path + "arrays_test." + (binary ? "bfbs" : "fbs")).c_str(),
2879 binary, &schemafile),
2881 TEST_EQ(flatbuffers::LoadFile((test_data_path + "arrays_test.golden").c_str(),
2885 // parse schema first, so we can use it to parse the data after
2886 flatbuffers::Parser parserOrg, parserGen;
2888 flatbuffers::Verifier verifier(
2889 reinterpret_cast<const uint8_t *>(schemafile.c_str()),
2891 TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
2892 TEST_EQ(parserOrg.Deserialize((const uint8_t *)schemafile.c_str(),
2895 TEST_EQ(parserGen.Deserialize((const uint8_t *)schemafile.c_str(),
2899 TEST_EQ(parserOrg.Parse(schemafile.c_str()), true);
2900 TEST_EQ(parserGen.Parse(schemafile.c_str()), true);
2902 TEST_EQ(parserOrg.Parse(jsonfile.c_str()), true);
2904 // First, verify it, just in case:
2905 flatbuffers::Verifier verifierOrg(parserOrg.builder_.GetBufferPointer(),
2906 parserOrg.builder_.GetSize());
2907 TEST_EQ(VerifyArrayTableBuffer(verifierOrg), true);
2910 std::string jsonGen;
2912 GenerateText(parserOrg, parserOrg.builder_.GetBufferPointer(), &jsonGen),
2916 TEST_EQ(parserGen.Parse(jsonGen.c_str()), true);
2918 // Verify buffer from generated JSON
2919 flatbuffers::Verifier verifierGen(parserGen.builder_.GetBufferPointer(),
2920 parserGen.builder_.GetSize());
2921 TEST_EQ(VerifyArrayTableBuffer(verifierGen), true);
2923 // Compare generated buffer to original
2924 TEST_EQ(parserOrg.builder_.GetSize(), parserGen.builder_.GetSize());
2925 TEST_EQ(std::memcmp(parserOrg.builder_.GetBufferPointer(),
2926 parserGen.builder_.GetBufferPointer(),
2927 parserOrg.builder_.GetSize()),
2934 int FlatBufferTests() {
2937 // Run our various test suites:
2940 auto flatbuf1 = CreateFlatBufferTest(rawbuf);
2941 #if !defined(FLATBUFFERS_CPP98_STL)
2942 auto flatbuf = std::move(flatbuf1); // Test move assignment.
2944 auto &flatbuf = flatbuf1;
2945 #endif // !defined(FLATBUFFERS_CPP98_STL)
2947 TriviallyCopyableTest();
2949 AccessFlatBufferTest(reinterpret_cast<const uint8_t *>(rawbuf.c_str()),
2951 AccessFlatBufferTest(flatbuf.data(), flatbuf.size());
2953 MutateFlatBuffersTest(flatbuf.data(), flatbuf.size());
2955 ObjectFlatBuffersTest(flatbuf.data());
2957 MiniReflectFlatBuffersTest(flatbuf.data());
2961 #ifndef FLATBUFFERS_NO_FILE_TESTS
2962 #ifdef FLATBUFFERS_TEST_PATH_PREFIX
2963 test_data_path = FLATBUFFERS_STRING(FLATBUFFERS_TEST_PATH_PREFIX) +
2966 ParseAndGenerateTextTest(false);
2967 ParseAndGenerateTextTest(true);
2968 FixedLengthArrayJsonTest(false);
2969 FixedLengthArrayJsonTest(true);
2970 ReflectionTest(flatbuf.data(), flatbuf.size());
2973 LoadVerifyBinaryTest();
2974 GenerateTableTextTest();
2986 EnumOutOfRangeTest();
2987 IntegerOutOfRangeTest();
2988 IntegerBoundaryTest();
2990 UnicodeTestAllowNonUTF8();
2991 UnicodeTestGenerateTextFailsOnNonUTF8();
2992 UnicodeSurrogatesTest();
2993 UnicodeInvalidSurrogatesTest();
2995 UnknownFieldsTest();
2997 InvalidNestedFlatbufferTest();
2999 ParseProtoBufAsciiTest();
3002 CreateSharedStringTest();
3006 UninitializedVectorTest();
3007 EqualOperatorTest();
3012 TestMonsterExtraFloats();
3013 FixedLengthArrayTest();
3017 int main(int /*argc*/, const char * /*argv*/ []) {
3020 std::string req_locale;
3021 if (flatbuffers::ReadEnvironmentVariable("FLATBUFFERS_TEST_LOCALE",
3023 TEST_OUTPUT_LINE("The environment variable FLATBUFFERS_TEST_LOCALE=%s",
3024 req_locale.c_str());
3025 req_locale = flatbuffers::RemoveStringQuotes(req_locale);
3026 std::string the_locale;
3028 flatbuffers::SetGlobalTestLocale(req_locale.c_str(), &the_locale));
3029 TEST_OUTPUT_LINE("The global C-locale changed: %s", the_locale.c_str());
3033 FlatBufferBuilderTest();
3035 if (!testing_fails) {
3036 TEST_OUTPUT_LINE("ALL TESTS PASSED");
3038 TEST_OUTPUT_LINE("%d FAILED TESTS", testing_fails);
3040 return CloseTestEngine();