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"
44 using namespace MyGame::Example;
46 void FlatBufferBuilderTest();
48 // Include simple random number generator to ensure results will be the
49 // same cross platform.
50 // http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator
51 uint32_t lcg_seed = 48271;
53 return lcg_seed = (static_cast<uint64_t>(lcg_seed) * 279470273UL) % 4294967291UL;
55 void lcg_reset() { lcg_seed = 48271; }
57 std::string test_data_path =
58 #ifdef BAZEL_TEST_DATA_PATH
59 "../com_github_google_flatbuffers/tests/";
64 // example of how to build up a serialized buffer algorithmically:
65 flatbuffers::DetachedBuffer CreateFlatBufferTest(std::string &buffer) {
66 flatbuffers::FlatBufferBuilder builder;
68 auto vec = Vec3(1, 2, 3, 0, Color_Red, Test(10, 20));
70 auto name = builder.CreateString("MyMonster");
72 unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
73 auto inventory = builder.CreateVector(inv_data, 10);
75 // Alternatively, create the vector first, and fill in data later:
76 // unsigned char *inv_buf = nullptr;
77 // auto inventory = builder.CreateUninitializedVector<unsigned char>(
79 // memcpy(inv_buf, inv_data, 10);
81 Test tests[] = { Test(10, 20), Test(30, 40) };
82 auto testv = builder.CreateVectorOfStructs(tests, 2);
85 #ifndef FLATBUFFERS_CPP98_STL
86 // Create a vector of structures from a lambda.
87 auto testv2 = builder.CreateVectorOfStructs<Test>(
88 2, [&](size_t i, Test* s) -> void {
92 // Create a vector of structures using a plain old C++ function.
93 auto testv2 = builder.CreateVectorOfStructs<Test>(
94 2, [](size_t i, Test* s, void *state) -> void {
95 *s = (reinterpret_cast<Test*>(state))[i];
97 #endif // FLATBUFFERS_CPP98_STL
100 // create monster with very few fields set:
101 // (same functionality as CreateMonster below, but sets fields manually)
102 flatbuffers::Offset<Monster> mlocs[3];
103 auto fred = builder.CreateString("Fred");
104 auto barney = builder.CreateString("Barney");
105 auto wilma = builder.CreateString("Wilma");
106 MonsterBuilder mb1(builder);
108 mlocs[0] = mb1.Finish();
109 MonsterBuilder mb2(builder);
110 mb2.add_name(barney);
112 mlocs[1] = mb2.Finish();
113 MonsterBuilder mb3(builder);
115 mlocs[2] = mb3.Finish();
117 // Create an array of strings. Also test string pooling, and lambdas.
119 builder.CreateVector<flatbuffers::Offset<flatbuffers::String>>(
121 [](size_t i, flatbuffers::FlatBufferBuilder *b)
122 -> flatbuffers::Offset<flatbuffers::String> {
123 static const char *names[] = { "bob", "fred", "bob", "fred" };
124 return b->CreateSharedString(names[i]);
128 // Creating vectors of strings in one convenient call.
129 std::vector<std::string> names2;
130 names2.push_back("jane");
131 names2.push_back("mary");
132 auto vecofstrings2 = builder.CreateVectorOfStrings(names2);
134 // Create an array of sorted tables, can be used with binary search when read:
135 auto vecoftables = builder.CreateVectorOfSortedTables(mlocs, 3);
137 // Create an array of sorted structs,
138 // can be used with binary search when read:
139 std::vector<Ability> abilities;
140 abilities.push_back(Ability(4, 40));
141 abilities.push_back(Ability(3, 30));
142 abilities.push_back(Ability(2, 20));
143 abilities.push_back(Ability(1, 10));
144 auto vecofstructs = builder.CreateVectorOfSortedStructs(&abilities);
146 // Create a nested FlatBuffer.
147 // Nested FlatBuffers are stored in a ubyte vector, which can be convenient
148 // since they can be memcpy'd around much easier than other FlatBuffer
149 // values. They have little overhead compared to storing the table directly.
150 // As a test, create a mostly empty Monster buffer:
151 flatbuffers::FlatBufferBuilder nested_builder;
152 auto nmloc = CreateMonster(nested_builder, nullptr, 0, 0,
153 nested_builder.CreateString("NestedMonster"));
154 FinishMonsterBuffer(nested_builder, nmloc);
155 // Now we can store the buffer in the parent. Note that by default, vectors
156 // are only aligned to their elements or size field, so in this case if the
157 // buffer contains 64-bit elements, they may not be correctly aligned. We fix
159 builder.ForceVectorAlignment(nested_builder.GetSize(), sizeof(uint8_t),
160 nested_builder.GetBufferMinAlignment());
161 // If for whatever reason you don't have the nested_builder available, you
162 // can substitute flatbuffers::largest_scalar_t (64-bit) for the alignment, or
163 // the largest force_align value in your schema if you're using it.
164 auto nested_flatbuffer_vector = builder.CreateVector(
165 nested_builder.GetBufferPointer(), nested_builder.GetSize());
167 // Test a nested FlexBuffer:
168 flexbuffers::Builder flexbuild;
171 auto flex = builder.CreateVector(flexbuild.GetBuffer());
173 // Test vector of enums.
174 Color colors[] = { Color_Blue, Color_Green };
175 // We use this special creation function because we have an array of
176 // pre-C++11 (enum class) enums whose size likely is int, yet its declared
177 // type in the schema is byte.
178 auto vecofcolors = builder.CreateVectorScalarCast<uint8_t, Color>(colors, 2);
180 // shortcut for creating monster with all fields set:
181 auto mloc = CreateMonster(builder, &vec, 150, 80, name, inventory, Color_Blue,
182 Any_Monster, mlocs[1].Union(), // Store a union.
183 testv, vecofstrings, vecoftables, 0,
184 nested_flatbuffer_vector, 0, false, 0, 0, 0, 0, 0,
185 0, 0, 0, 0, 3.14159f, 3.0f, 0.0f, vecofstrings2,
186 vecofstructs, flex, testv2, 0, 0, 0, 0, 0, 0, 0, 0,
187 0, 0, 0, AnyUniqueAliases_NONE, 0,
188 AnyAmbiguousAliases_NONE, 0, vecofcolors);
190 FinishMonsterBuffer(builder, mloc);
193 #ifdef FLATBUFFERS_TEST_VERBOSE
194 // print byte data for debugging:
195 auto p = builder.GetBufferPointer();
196 for (flatbuffers::uoffset_t i = 0; i < builder.GetSize(); i++)
201 // return the buffer for the caller to use.
203 reinterpret_cast<const char *>(builder.GetBufferPointer());
204 buffer.assign(bufferpointer, bufferpointer + builder.GetSize());
206 return builder.Release();
209 // example of accessing a buffer loaded in memory:
210 void AccessFlatBufferTest(const uint8_t *flatbuf, size_t length,
211 bool pooled = true) {
212 // First, verify the buffers integrity (optional)
213 flatbuffers::Verifier verifier(flatbuf, length);
214 TEST_EQ(VerifyMonsterBuffer(verifier), true);
217 #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
218 std::vector<uint8_t> test_buff;
219 test_buff.resize(length * 2);
220 std::memcpy(&test_buff[0], flatbuf, length);
221 std::memcpy(&test_buff[length], flatbuf, length);
223 flatbuffers::Verifier verifier1(&test_buff[0], length);
224 TEST_EQ(VerifyMonsterBuffer(verifier1), true);
225 TEST_EQ(verifier1.GetComputedSize(), length);
227 flatbuffers::Verifier verifier2(&test_buff[length], length);
228 TEST_EQ(VerifyMonsterBuffer(verifier2), true);
229 TEST_EQ(verifier2.GetComputedSize(), length);
233 TEST_EQ(strcmp(MonsterIdentifier(), "MONS"), 0);
234 TEST_EQ(MonsterBufferHasIdentifier(flatbuf), true);
235 TEST_EQ(strcmp(MonsterExtension(), "mon"), 0);
237 // Access the buffer from the root.
238 auto monster = GetMonster(flatbuf);
240 TEST_EQ(monster->hp(), 80);
241 TEST_EQ(monster->mana(), 150); // default
242 TEST_EQ_STR(monster->name()->c_str(), "MyMonster");
243 // Can't access the following field, it is deprecated in the schema,
244 // which means accessors are not generated:
245 // monster.friendly()
247 auto pos = monster->pos();
249 TEST_EQ(pos->z(), 3);
250 TEST_EQ(pos->test3().a(), 10);
251 TEST_EQ(pos->test3().b(), 20);
253 auto inventory = monster->inventory();
254 TEST_EQ(VectorLength(inventory), 10UL); // Works even if inventory is null.
255 TEST_NOTNULL(inventory);
256 unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
257 // Check compatibilty of iterators with STL.
258 std::vector<unsigned char> inv_vec(inventory->begin(), inventory->end());
260 for (auto it = inventory->begin(); it != inventory->end(); ++it, ++n) {
261 auto indx = it - inventory->begin();
262 TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check.
263 TEST_EQ(*it, inv_data[indx]);
265 TEST_EQ(n, inv_vec.size());
268 for (auto it = inventory->cbegin(); it != inventory->cend(); ++it, ++n) {
269 auto indx = it - inventory->cbegin();
270 TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check.
271 TEST_EQ(*it, inv_data[indx]);
273 TEST_EQ(n, inv_vec.size());
276 for (auto it = inventory->rbegin(); it != inventory->rend(); ++it, ++n) {
277 auto indx = inventory->rend() - it - 1;
278 TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check.
279 TEST_EQ(*it, inv_data[indx]);
281 TEST_EQ(n, inv_vec.size());
284 for (auto it = inventory->crbegin(); it != inventory->crend(); ++it, ++n) {
285 auto indx = inventory->crend() - it - 1;
286 TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check.
287 TEST_EQ(*it, inv_data[indx]);
289 TEST_EQ(n, inv_vec.size());
291 TEST_EQ(monster->color(), Color_Blue);
293 // Example of accessing a union:
294 TEST_EQ(monster->test_type(), Any_Monster); // First make sure which it is.
295 auto monster2 = reinterpret_cast<const Monster *>(monster->test());
296 TEST_NOTNULL(monster2);
297 TEST_EQ_STR(monster2->name()->c_str(), "Fred");
299 // Example of accessing a vector of strings:
300 auto vecofstrings = monster->testarrayofstring();
301 TEST_EQ(vecofstrings->size(), 4U);
302 TEST_EQ_STR(vecofstrings->Get(0)->c_str(), "bob");
303 TEST_EQ_STR(vecofstrings->Get(1)->c_str(), "fred");
305 // These should have pointer equality because of string pooling.
306 TEST_EQ(vecofstrings->Get(0)->c_str(), vecofstrings->Get(2)->c_str());
307 TEST_EQ(vecofstrings->Get(1)->c_str(), vecofstrings->Get(3)->c_str());
310 auto vecofstrings2 = monster->testarrayofstring2();
312 TEST_EQ(vecofstrings2->size(), 2U);
313 TEST_EQ_STR(vecofstrings2->Get(0)->c_str(), "jane");
314 TEST_EQ_STR(vecofstrings2->Get(1)->c_str(), "mary");
317 // Example of accessing a vector of tables:
318 auto vecoftables = monster->testarrayoftables();
319 TEST_EQ(vecoftables->size(), 3U);
320 for (auto it = vecoftables->begin(); it != vecoftables->end(); ++it)
321 TEST_EQ(strlen(it->name()->c_str()) >= 4, true);
322 TEST_EQ_STR(vecoftables->Get(0)->name()->c_str(), "Barney");
323 TEST_EQ(vecoftables->Get(0)->hp(), 1000);
324 TEST_EQ_STR(vecoftables->Get(1)->name()->c_str(), "Fred");
325 TEST_EQ_STR(vecoftables->Get(2)->name()->c_str(), "Wilma");
326 TEST_NOTNULL(vecoftables->LookupByKey("Barney"));
327 TEST_NOTNULL(vecoftables->LookupByKey("Fred"));
328 TEST_NOTNULL(vecoftables->LookupByKey("Wilma"));
330 // Test accessing a vector of sorted structs
331 auto vecofstructs = monster->testarrayofsortedstruct();
332 if (vecofstructs) { // not filled in monster_test.bfbs
333 for (flatbuffers::uoffset_t i = 0; i < vecofstructs->size() - 1; i++) {
334 auto left = vecofstructs->Get(i);
335 auto right = vecofstructs->Get(i + 1);
336 TEST_EQ(true, (left->KeyCompareLessThan(right)));
338 TEST_NOTNULL(vecofstructs->LookupByKey(3));
339 TEST_EQ(static_cast<const Ability *>(nullptr),
340 vecofstructs->LookupByKey(5));
343 // Test nested FlatBuffers if available:
344 auto nested_buffer = monster->testnestedflatbuffer();
346 // nested_buffer is a vector of bytes you can memcpy. However, if you
347 // actually want to access the nested data, this is a convenient
348 // accessor that directly gives you the root table:
349 auto nested_monster = monster->testnestedflatbuffer_nested_root();
350 TEST_EQ_STR(nested_monster->name()->c_str(), "NestedMonster");
353 // Test flexbuffer if available:
354 auto flex = monster->flex();
355 // flex is a vector of bytes you can memcpy etc.
356 TEST_EQ(flex->size(), 4); // Encoded FlexBuffer bytes.
357 // However, if you actually want to access the nested data, this is a
358 // convenient accessor that directly gives you the root value:
359 TEST_EQ(monster->flex_flexbuffer_root().AsInt16(), 1234);
361 // Test vector of enums:
362 auto colors = monster->vector_of_enums();
364 TEST_EQ(colors->size(), 2);
365 TEST_EQ(colors->Get(0), Color_Blue);
366 TEST_EQ(colors->Get(1), Color_Green);
369 // Since Flatbuffers uses explicit mechanisms to override the default
370 // compiler alignment, double check that the compiler indeed obeys them:
371 // (Test consists of a short and byte):
372 TEST_EQ(flatbuffers::AlignOf<Test>(), 2UL);
373 TEST_EQ(sizeof(Test), 4UL);
375 const flatbuffers::Vector<const Test *> *tests_array[] = {
379 for (size_t i = 0; i < sizeof(tests_array) / sizeof(tests_array[0]); ++i) {
380 auto tests = tests_array[i];
382 auto test_0 = tests->Get(0);
383 auto test_1 = tests->Get(1);
384 TEST_EQ(test_0->a(), 10);
385 TEST_EQ(test_0->b(), 20);
386 TEST_EQ(test_1->a(), 30);
387 TEST_EQ(test_1->b(), 40);
388 for (auto it = tests->begin(); it != tests->end(); ++it) {
389 TEST_EQ(it->a() == 10 || it->a() == 30, true); // Just testing iterators.
393 // Checking for presence of fields:
394 TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_HP), true);
395 TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_MANA), false);
397 // Obtaining a buffer from a root:
398 TEST_EQ(GetBufferStartFromRootPointer(monster), flatbuf);
401 // Change a FlatBuffer in-place, after it has been constructed.
402 void MutateFlatBuffersTest(uint8_t *flatbuf, std::size_t length) {
403 // Get non-const pointer to root.
404 auto monster = GetMutableMonster(flatbuf);
406 // Each of these tests mutates, then tests, then set back to the original,
407 // so we can test that the buffer in the end still passes our original test.
408 auto hp_ok = monster->mutate_hp(10);
409 TEST_EQ(hp_ok, true); // Field was present.
410 TEST_EQ(monster->hp(), 10);
411 // Mutate to default value
412 auto hp_ok_default = monster->mutate_hp(100);
413 TEST_EQ(hp_ok_default, true); // Field was present.
414 TEST_EQ(monster->hp(), 100);
415 // Test that mutate to default above keeps field valid for further mutations
416 auto hp_ok_2 = monster->mutate_hp(20);
417 TEST_EQ(hp_ok_2, true);
418 TEST_EQ(monster->hp(), 20);
419 monster->mutate_hp(80);
421 // Monster originally at 150 mana (default value)
422 auto mana_default_ok = monster->mutate_mana(150); // Mutate to default value.
423 TEST_EQ(mana_default_ok,
424 true); // Mutation should succeed, because default value.
425 TEST_EQ(monster->mana(), 150);
426 auto mana_ok = monster->mutate_mana(10);
427 TEST_EQ(mana_ok, false); // Field was NOT present, because default value.
428 TEST_EQ(monster->mana(), 150);
431 auto pos = monster->mutable_pos();
432 auto test3 = pos->mutable_test3(); // Struct inside a struct.
433 test3.mutate_a(50); // Struct fields never fail.
434 TEST_EQ(test3.a(), 50);
438 auto inventory = monster->mutable_inventory();
439 inventory->Mutate(9, 100);
440 TEST_EQ(inventory->Get(9), 100);
441 inventory->Mutate(9, 9);
443 auto tables = monster->mutable_testarrayoftables();
444 auto first = tables->GetMutableObject(0);
445 TEST_EQ(first->hp(), 1000);
447 TEST_EQ(first->hp(), 0);
448 first->mutate_hp(1000);
450 // Run the verifier and the regular test to make sure we didn't trample on
452 AccessFlatBufferTest(flatbuf, length);
455 // Unpack a FlatBuffer into objects.
456 void ObjectFlatBuffersTest(uint8_t *flatbuf) {
457 // Optional: we can specify resolver and rehasher functions to turn hashed
458 // strings into object pointers and back, to implement remote references
460 auto resolver = flatbuffers::resolver_function_t(
461 [](void **pointer_adr, flatbuffers::hash_value_t hash) {
464 // Don't actually do anything, leave variable null.
466 auto rehasher = flatbuffers::rehasher_function_t(
467 [](void *pointer) -> flatbuffers::hash_value_t {
472 // Turn a buffer into C++ objects.
473 auto monster1 = UnPackMonster(flatbuf, &resolver);
475 // Re-serialize the data.
476 flatbuffers::FlatBufferBuilder fbb1;
477 fbb1.Finish(CreateMonster(fbb1, monster1.get(), &rehasher),
478 MonsterIdentifier());
480 // Unpack again, and re-serialize again.
481 auto monster2 = UnPackMonster(fbb1.GetBufferPointer(), &resolver);
482 flatbuffers::FlatBufferBuilder fbb2;
483 fbb2.Finish(CreateMonster(fbb2, monster2.get(), &rehasher),
484 MonsterIdentifier());
486 // Now we've gone full round-trip, the two buffers should match.
487 auto len1 = fbb1.GetSize();
488 auto len2 = fbb2.GetSize();
490 TEST_EQ(memcmp(fbb1.GetBufferPointer(), fbb2.GetBufferPointer(), len1), 0);
492 // Test it with the original buffer test to make sure all data survived.
493 AccessFlatBufferTest(fbb2.GetBufferPointer(), len2, false);
495 // Test accessing fields, similar to AccessFlatBufferTest above.
496 TEST_EQ(monster2->hp, 80);
497 TEST_EQ(monster2->mana, 150); // default
498 TEST_EQ_STR(monster2->name.c_str(), "MyMonster");
500 auto &pos = monster2->pos;
502 TEST_EQ(pos->z(), 3);
503 TEST_EQ(pos->test3().a(), 10);
504 TEST_EQ(pos->test3().b(), 20);
506 auto &inventory = monster2->inventory;
507 TEST_EQ(inventory.size(), 10UL);
508 unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
509 for (auto it = inventory.begin(); it != inventory.end(); ++it)
510 TEST_EQ(*it, inv_data[it - inventory.begin()]);
512 TEST_EQ(monster2->color, Color_Blue);
514 auto monster3 = monster2->test.AsMonster();
515 TEST_NOTNULL(monster3);
516 TEST_EQ_STR(monster3->name.c_str(), "Fred");
518 auto &vecofstrings = monster2->testarrayofstring;
519 TEST_EQ(vecofstrings.size(), 4U);
520 TEST_EQ_STR(vecofstrings[0].c_str(), "bob");
521 TEST_EQ_STR(vecofstrings[1].c_str(), "fred");
523 auto &vecofstrings2 = monster2->testarrayofstring2;
524 TEST_EQ(vecofstrings2.size(), 2U);
525 TEST_EQ_STR(vecofstrings2[0].c_str(), "jane");
526 TEST_EQ_STR(vecofstrings2[1].c_str(), "mary");
528 auto &vecoftables = monster2->testarrayoftables;
529 TEST_EQ(vecoftables.size(), 3U);
530 TEST_EQ_STR(vecoftables[0]->name.c_str(), "Barney");
531 TEST_EQ(vecoftables[0]->hp, 1000);
532 TEST_EQ_STR(vecoftables[1]->name.c_str(), "Fred");
533 TEST_EQ_STR(vecoftables[2]->name.c_str(), "Wilma");
535 auto &tests = monster2->test4;
536 TEST_EQ(tests[0].a(), 10);
537 TEST_EQ(tests[0].b(), 20);
538 TEST_EQ(tests[1].a(), 30);
539 TEST_EQ(tests[1].b(), 40);
542 // Prefix a FlatBuffer with a size field.
543 void SizePrefixedTest() {
544 // Create size prefixed buffer.
545 flatbuffers::FlatBufferBuilder fbb;
546 FinishSizePrefixedMonsterBuffer(
548 CreateMonster(fbb, 0, 200, 300, fbb.CreateString("bob")));
551 flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize());
552 TEST_EQ(VerifySizePrefixedMonsterBuffer(verifier), true);
555 auto m = GetSizePrefixedMonster(fbb.GetBufferPointer());
556 TEST_EQ(m->mana(), 200);
557 TEST_EQ(m->hp(), 300);
558 TEST_EQ_STR(m->name()->c_str(), "bob");
561 void TriviallyCopyableTest() {
563 #if __GNUG__ && __GNUC__ < 5
564 TEST_EQ(__has_trivial_copy(Vec3), true);
566 #if __cplusplus >= 201103L
567 TEST_EQ(std::is_trivially_copyable<Vec3>::value, true);
573 // Check stringify of an default enum value to json
574 void JsonDefaultTest() {
575 // load FlatBuffer schema (.fbs) from disk
576 std::string schemafile;
577 TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
578 false, &schemafile), true);
579 // parse schema first, so we can use it to parse the data after
580 flatbuffers::Parser parser;
581 auto include_test_path =
582 flatbuffers::ConCatPathFileName(test_data_path, "include_test");
583 const char *include_directories[] = { test_data_path.c_str(),
584 include_test_path.c_str(), nullptr };
586 TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
587 // create incomplete monster and store to json
588 parser.opts.output_default_scalars_in_json = true;
589 parser.opts.output_enum_identifiers = true;
590 flatbuffers::FlatBufferBuilder builder;
591 auto name = builder.CreateString("default_enum");
592 MonsterBuilder color_monster(builder);
593 color_monster.add_name(name);
594 FinishMonsterBuffer(builder, color_monster.Finish());
596 auto result = GenerateText(parser, builder.GetBufferPointer(), &jsongen);
597 TEST_EQ(result, true);
598 // default value of the "color" field is Blue
599 TEST_EQ(std::string::npos != jsongen.find("color: \"Blue\""), true);
600 // default value of the "testf" field is 3.14159
601 TEST_EQ(std::string::npos != jsongen.find("testf: 3.14159"), true);
604 #if defined(FLATBUFFERS_HAS_NEW_STRTOD)
605 void TestMonsterExtraFloats() {
606 using namespace MyGame;
607 // Load FlatBuffer schema (.fbs) from disk.
608 std::string schemafile;
609 TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_extra.fbs").c_str(),
612 // Parse schema first, so we can use it to parse the data after.
613 flatbuffers::Parser parser;
614 auto include_test_path =
615 flatbuffers::ConCatPathFileName(test_data_path, "include_test");
616 const char *include_directories[] = { test_data_path.c_str(),
617 include_test_path.c_str(), nullptr };
618 TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
619 // Create empty extra and store to json.
620 parser.opts.output_default_scalars_in_json = true;
621 parser.opts.output_enum_identifiers = true;
622 flatbuffers::FlatBufferBuilder builder;
623 MonsterExtraBuilder extra(builder);
624 FinishMonsterExtraBuffer(builder, extra.Finish());
626 auto result = GenerateText(parser, builder.GetBufferPointer(), &jsongen);
627 TEST_EQ(result, true);
628 TEST_EQ(std::string::npos != jsongen.find("testf_nan: nan"), true);
629 TEST_EQ(std::string::npos != jsongen.find("testf_pinf: inf"), true);
630 TEST_EQ(std::string::npos != jsongen.find("testf_ninf: -inf"), true);
631 TEST_EQ(std::string::npos != jsongen.find("testd_nan: nan"), true);
632 TEST_EQ(std::string::npos != jsongen.find("testd_pinf: inf"), true);
633 TEST_EQ(std::string::npos != jsongen.find("testd_ninf: -inf"), true);
636 void TestMonsterExtraFloats() {}
639 // example of parsing text straight into a buffer, and generating
640 // text back from it:
641 void ParseAndGenerateTextTest(bool binary) {
642 // load FlatBuffer schema (.fbs) and JSON from disk
643 std::string schemafile;
644 std::string jsonfile;
645 TEST_EQ(flatbuffers::LoadFile(
646 (test_data_path + "monster_test." + (binary ? "bfbs" : "fbs"))
648 binary, &schemafile),
650 TEST_EQ(flatbuffers::LoadFile(
651 (test_data_path + "monsterdata_test.golden").c_str(), false,
655 auto include_test_path =
656 flatbuffers::ConCatPathFileName(test_data_path, "include_test");
657 const char *include_directories[] = { test_data_path.c_str(),
658 include_test_path.c_str(), nullptr };
660 // parse schema first, so we can use it to parse the data after
661 flatbuffers::Parser parser;
663 flatbuffers::Verifier verifier(
664 reinterpret_cast<const uint8_t *>(schemafile.c_str()),
666 TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
667 //auto schema = reflection::GetSchema(schemafile.c_str());
668 TEST_EQ(parser.Deserialize((const uint8_t *)schemafile.c_str(), schemafile.size()), true);
670 TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
672 TEST_EQ(parser.Parse(jsonfile.c_str(), include_directories), true);
674 // here, parser.builder_ contains a binary buffer that is the parsed data.
676 // First, verify it, just in case:
677 flatbuffers::Verifier verifier(parser.builder_.GetBufferPointer(),
678 parser.builder_.GetSize());
679 TEST_EQ(VerifyMonsterBuffer(verifier), true);
681 AccessFlatBufferTest(parser.builder_.GetBufferPointer(),
682 parser.builder_.GetSize(), false);
684 // to ensure it is correct, we now generate text back from the binary,
685 // and compare the two:
688 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
689 TEST_EQ(result, true);
690 TEST_EQ_STR(jsongen.c_str(), jsonfile.c_str());
692 // We can also do the above using the convenient Registry that knows about
693 // a set of file_identifiers mapped to schemas.
694 flatbuffers::Registry registry;
695 // Make sure schemas can find their includes.
696 registry.AddIncludeDirectory(test_data_path.c_str());
697 registry.AddIncludeDirectory(include_test_path.c_str());
698 // Call this with many schemas if possible.
699 registry.Register(MonsterIdentifier(),
700 (test_data_path + "monster_test.fbs").c_str());
701 // Now we got this set up, we can parse by just specifying the identifier,
702 // the correct schema will be loaded on the fly:
703 auto buf = registry.TextToFlatBuffer(jsonfile.c_str(), MonsterIdentifier());
704 // If this fails, check registry.lasterror_.
705 TEST_NOTNULL(buf.data());
706 // Test the buffer, to be sure:
707 AccessFlatBufferTest(buf.data(), buf.size(), false);
708 // We can use the registry to turn this back into text, in this case it
709 // will get the file_identifier from the binary:
711 auto ok = registry.FlatBufferToText(buf.data(), buf.size(), &text);
712 // If this fails, check registry.lasterror_.
714 TEST_EQ_STR(text.c_str(), jsonfile.c_str());
716 // Generate text for UTF-8 strings without escapes.
717 std::string jsonfile_utf8;
718 TEST_EQ(flatbuffers::LoadFile((test_data_path + "unicode_test.json").c_str(),
719 false, &jsonfile_utf8),
721 TEST_EQ(parser.Parse(jsonfile_utf8.c_str(), include_directories), true);
722 // To ensure it is correct, generate utf-8 text back from the binary.
723 std::string jsongen_utf8;
724 // request natural printing for utf-8 strings
725 parser.opts.natural_utf8 = true;
726 parser.opts.strict_json = true;
728 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen_utf8),
730 TEST_EQ_STR(jsongen_utf8.c_str(), jsonfile_utf8.c_str());
733 void ReflectionTest(uint8_t *flatbuf, size_t length) {
734 // Load a binary schema.
735 std::string bfbsfile;
736 TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.bfbs").c_str(),
740 // Verify it, just in case:
741 flatbuffers::Verifier verifier(
742 reinterpret_cast<const uint8_t *>(bfbsfile.c_str()), bfbsfile.length());
743 TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
745 // Make sure the schema is what we expect it to be.
746 auto &schema = *reflection::GetSchema(bfbsfile.c_str());
747 auto root_table = schema.root_table();
748 TEST_EQ_STR(root_table->name()->c_str(), "MyGame.Example.Monster");
749 auto fields = root_table->fields();
750 auto hp_field_ptr = fields->LookupByKey("hp");
751 TEST_NOTNULL(hp_field_ptr);
752 auto &hp_field = *hp_field_ptr;
753 TEST_EQ_STR(hp_field.name()->c_str(), "hp");
754 TEST_EQ(hp_field.id(), 2);
755 TEST_EQ(hp_field.type()->base_type(), reflection::Short);
756 auto friendly_field_ptr = fields->LookupByKey("friendly");
757 TEST_NOTNULL(friendly_field_ptr);
758 TEST_NOTNULL(friendly_field_ptr->attributes());
759 TEST_NOTNULL(friendly_field_ptr->attributes()->LookupByKey("priority"));
761 // Make sure the table index is what we expect it to be.
762 auto pos_field_ptr = fields->LookupByKey("pos");
763 TEST_NOTNULL(pos_field_ptr);
764 TEST_EQ(pos_field_ptr->type()->base_type(), reflection::Obj);
765 auto pos_table_ptr = schema.objects()->Get(pos_field_ptr->type()->index());
766 TEST_NOTNULL(pos_table_ptr);
767 TEST_EQ_STR(pos_table_ptr->name()->c_str(), "MyGame.Example.Vec3");
769 // Now use it to dynamically access a buffer.
770 auto &root = *flatbuffers::GetAnyRoot(flatbuf);
772 // Verify the buffer first using reflection based verification
773 TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), flatbuf, length),
776 auto hp = flatbuffers::GetFieldI<uint16_t>(root, hp_field);
779 // Rather than needing to know the type, we can also get the value of
780 // any field as an int64_t/double/string, regardless of what it actually is.
781 auto hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
782 TEST_EQ(hp_int64, 80);
783 auto hp_double = flatbuffers::GetAnyFieldF(root, hp_field);
784 TEST_EQ(hp_double, 80.0);
785 auto hp_string = flatbuffers::GetAnyFieldS(root, hp_field, &schema);
786 TEST_EQ_STR(hp_string.c_str(), "80");
788 // Get struct field through reflection
789 auto pos_struct = flatbuffers::GetFieldStruct(root, *pos_field_ptr);
790 TEST_NOTNULL(pos_struct);
791 TEST_EQ(flatbuffers::GetAnyFieldF(*pos_struct,
792 *pos_table_ptr->fields()->LookupByKey("z")),
795 auto test3_field = pos_table_ptr->fields()->LookupByKey("test3");
796 auto test3_struct = flatbuffers::GetFieldStruct(*pos_struct, *test3_field);
797 TEST_NOTNULL(test3_struct);
798 auto test3_object = schema.objects()->Get(test3_field->type()->index());
800 TEST_EQ(flatbuffers::GetAnyFieldF(*test3_struct,
801 *test3_object->fields()->LookupByKey("a")),
804 // We can also modify it.
805 flatbuffers::SetField<uint16_t>(&root, hp_field, 200);
806 hp = flatbuffers::GetFieldI<uint16_t>(root, hp_field);
809 // We can also set fields generically:
810 flatbuffers::SetAnyFieldI(&root, hp_field, 300);
811 hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
812 TEST_EQ(hp_int64, 300);
813 flatbuffers::SetAnyFieldF(&root, hp_field, 300.5);
814 hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
815 TEST_EQ(hp_int64, 300);
816 flatbuffers::SetAnyFieldS(&root, hp_field, "300");
817 hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
818 TEST_EQ(hp_int64, 300);
820 // Test buffer is valid after the modifications
821 TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), flatbuf, length),
824 // Reset it, for further tests.
825 flatbuffers::SetField<uint16_t>(&root, hp_field, 80);
827 // More advanced functionality: changing the size of items in-line!
828 // First we put the FlatBuffer inside an std::vector.
829 std::vector<uint8_t> resizingbuf(flatbuf, flatbuf + length);
830 // Find the field we want to modify.
831 auto &name_field = *fields->LookupByKey("name");
833 // This time we wrap the result from GetAnyRoot in a smartpointer that
834 // will keep rroot valid as resizingbuf resizes.
835 auto rroot = flatbuffers::piv(
836 flatbuffers::GetAnyRoot(flatbuffers::vector_data(resizingbuf)),
838 SetString(schema, "totally new string", GetFieldS(**rroot, name_field),
840 // Here resizingbuf has changed, but rroot is still valid.
841 TEST_EQ_STR(GetFieldS(**rroot, name_field)->c_str(), "totally new string");
842 // Now lets extend a vector by 100 elements (10 -> 110).
843 auto &inventory_field = *fields->LookupByKey("inventory");
844 auto rinventory = flatbuffers::piv(
845 flatbuffers::GetFieldV<uint8_t>(**rroot, inventory_field), resizingbuf);
846 flatbuffers::ResizeVector<uint8_t>(schema, 110, 50, *rinventory,
848 // rinventory still valid, so lets read from it.
849 TEST_EQ(rinventory->Get(10), 50);
851 // For reflection uses not covered already, there is a more powerful way:
852 // we can simply generate whatever object we want to add/modify in a
853 // FlatBuffer of its own, then add that to an existing FlatBuffer:
854 // As an example, let's add a string to an array of strings.
855 // First, find our field:
856 auto &testarrayofstring_field = *fields->LookupByKey("testarrayofstring");
857 // Find the vector value:
858 auto rtestarrayofstring = flatbuffers::piv(
859 flatbuffers::GetFieldV<flatbuffers::Offset<flatbuffers::String>>(
860 **rroot, testarrayofstring_field),
862 // It's a vector of 2 strings, to which we add one more, initialized to
864 flatbuffers::ResizeVector<flatbuffers::Offset<flatbuffers::String>>(
865 schema, 3, 0, *rtestarrayofstring, &resizingbuf);
866 // Here we just create a buffer that contans a single string, but this
867 // could also be any complex set of tables and other values.
868 flatbuffers::FlatBufferBuilder stringfbb;
869 stringfbb.Finish(stringfbb.CreateString("hank"));
870 // Add the contents of it to our existing FlatBuffer.
871 // We do this last, so the pointer doesn't get invalidated (since it is
872 // at the end of the buffer):
873 auto string_ptr = flatbuffers::AddFlatBuffer(
874 resizingbuf, stringfbb.GetBufferPointer(), stringfbb.GetSize());
875 // Finally, set the new value in the vector.
876 rtestarrayofstring->MutateOffset(2, string_ptr);
877 TEST_EQ_STR(rtestarrayofstring->Get(0)->c_str(), "bob");
878 TEST_EQ_STR(rtestarrayofstring->Get(2)->c_str(), "hank");
879 // Test integrity of all resize operations above.
880 flatbuffers::Verifier resize_verifier(
881 reinterpret_cast<const uint8_t *>(flatbuffers::vector_data(resizingbuf)),
883 TEST_EQ(VerifyMonsterBuffer(resize_verifier), true);
885 // Test buffer is valid using reflection as well
886 TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(),
887 flatbuffers::vector_data(resizingbuf),
891 // As an additional test, also set it on the name field.
892 // Note: unlike the name change above, this just overwrites the offset,
893 // rather than changing the string in-place.
894 SetFieldT(*rroot, name_field, string_ptr);
895 TEST_EQ_STR(GetFieldS(**rroot, name_field)->c_str(), "hank");
897 // Using reflection, rather than mutating binary FlatBuffers, we can also copy
898 // tables and other things out of other FlatBuffers into a FlatBufferBuilder,
899 // either part or whole.
900 flatbuffers::FlatBufferBuilder fbb;
901 auto root_offset = flatbuffers::CopyTable(
902 fbb, schema, *root_table, *flatbuffers::GetAnyRoot(flatbuf), true);
903 fbb.Finish(root_offset, MonsterIdentifier());
904 // Test that it was copied correctly:
905 AccessFlatBufferTest(fbb.GetBufferPointer(), fbb.GetSize());
907 // Test buffer is valid using reflection as well
908 TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(),
909 fbb.GetBufferPointer(), fbb.GetSize()),
913 void MiniReflectFlatBuffersTest(uint8_t *flatbuf) {
914 auto s = flatbuffers::FlatBufferToString(flatbuf, Monster::MiniReflectTypeTable());
918 "pos: { x: 1.0, y: 2.0, z: 3.0, test1: 0.0, test2: Red, test3: "
919 "{ a: 10, b: 20 } }, "
921 "name: \"MyMonster\", "
922 "inventory: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], "
923 "test_type: Monster, "
924 "test: { name: \"Fred\" }, "
925 "test4: [ { a: 10, b: 20 }, { a: 30, b: 40 } ], "
926 "testarrayofstring: [ \"bob\", \"fred\", \"bob\", \"fred\" ], "
927 "testarrayoftables: [ { hp: 1000, name: \"Barney\" }, { name: \"Fred\" "
929 "{ name: \"Wilma\" } ], "
930 // TODO(wvo): should really print this nested buffer correctly.
931 "testnestedflatbuffer: [ 20, 0, 0, 0, 77, 79, 78, 83, 12, 0, 12, 0, 0, "
933 "4, 0, 6, 0, 8, 0, 12, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 13, 0, 0, 0, 78, "
934 "101, 115, 116, 101, 100, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0 ], "
935 "testarrayofstring2: [ \"jane\", \"mary\" ], "
936 "testarrayofsortedstruct: [ { id: 1, distance: 10 }, "
937 "{ id: 2, distance: 20 }, { id: 3, distance: 30 }, "
938 "{ id: 4, distance: 40 } ], "
939 "flex: [ 210, 4, 5, 2 ], "
940 "test5: [ { a: 10, b: 20 }, { a: 30, b: 40 } ], "
941 "vector_of_enums: [ Blue, Green ] "
945 Vec3 vec(1,2,3, 1.5, Color_Red, test);
946 flatbuffers::FlatBufferBuilder vec_builder;
947 vec_builder.Finish(vec_builder.CreateStruct(vec));
948 auto vec_buffer = vec_builder.Release();
949 auto vec_str = flatbuffers::FlatBufferToString(vec_buffer.data(),
950 Vec3::MiniReflectTypeTable());
953 "{ x: 1.0, y: 2.0, z: 3.0, test1: 1.5, test2: Red, test3: { a: 16, b: 32 } }");
956 // Parse a .proto schema, output as .fbs
957 void ParseProtoTest() {
958 // load the .proto and the golden file from disk
959 std::string protofile;
960 std::string goldenfile;
961 std::string goldenunionfile;
963 flatbuffers::LoadFile((test_data_path + "prototest/test.proto").c_str(),
967 flatbuffers::LoadFile((test_data_path + "prototest/test.golden").c_str(),
971 flatbuffers::LoadFile((test_data_path +
972 "prototest/test_union.golden").c_str(),
973 false, &goldenunionfile),
976 flatbuffers::IDLOptions opts;
977 opts.include_dependence_headers = false;
978 opts.proto_mode = true;
981 flatbuffers::Parser parser(opts);
982 auto protopath = test_data_path + "prototest/";
983 const char *include_directories[] = { protopath.c_str(), nullptr };
984 TEST_EQ(parser.Parse(protofile.c_str(), include_directories), true);
987 auto fbs = flatbuffers::GenerateFBS(parser, "test");
989 // Ensure generated file is parsable.
990 flatbuffers::Parser parser2;
991 TEST_EQ(parser2.Parse(fbs.c_str(), nullptr), true);
992 TEST_EQ_STR(fbs.c_str(), goldenfile.c_str());
994 // Parse proto with --oneof-union option.
995 opts.proto_oneof_union = true;
996 flatbuffers::Parser parser3(opts);
997 TEST_EQ(parser3.Parse(protofile.c_str(), include_directories), true);
1000 auto fbs_union = flatbuffers::GenerateFBS(parser3, "test");
1002 // Ensure generated file is parsable.
1003 flatbuffers::Parser parser4;
1004 TEST_EQ(parser4.Parse(fbs_union.c_str(), nullptr), true);
1005 TEST_EQ_STR(fbs_union.c_str(), goldenunionfile.c_str());
1008 template<typename T>
1009 void CompareTableFieldValue(flatbuffers::Table *table,
1010 flatbuffers::voffset_t voffset, T val) {
1011 T read = table->GetField(voffset, static_cast<T>(0));
1015 // Low level stress/fuzz test: serialize/deserialize a variety of
1016 // different kinds of data in different combinations
1018 // Values we're testing against: chosen to ensure no bits get chopped
1019 // off anywhere, and also be different from eachother.
1020 const uint8_t bool_val = true;
1021 const int8_t char_val = -127; // 0x81
1022 const uint8_t uchar_val = 0xFF;
1023 const int16_t short_val = -32222; // 0x8222;
1024 const uint16_t ushort_val = 0xFEEE;
1025 const int32_t int_val = 0x83333333;
1026 const uint32_t uint_val = 0xFDDDDDDD;
1027 const int64_t long_val = 0x8444444444444444LL;
1028 const uint64_t ulong_val = 0xFCCCCCCCCCCCCCCCULL;
1029 const float float_val = 3.14159f;
1030 const double double_val = 3.14159265359;
1032 const int test_values_max = 11;
1033 const flatbuffers::voffset_t fields_per_object = 4;
1034 const int num_fuzz_objects = 10000; // The higher, the more thorough :)
1036 flatbuffers::FlatBufferBuilder builder;
1038 lcg_reset(); // Keep it deterministic.
1040 flatbuffers::uoffset_t objects[num_fuzz_objects];
1042 // Generate num_fuzz_objects random objects each consisting of
1043 // fields_per_object fields, each of a random type.
1044 for (int i = 0; i < num_fuzz_objects; i++) {
1045 auto start = builder.StartTable();
1046 for (flatbuffers::voffset_t f = 0; f < fields_per_object; f++) {
1047 int choice = lcg_rand() % test_values_max;
1048 auto off = flatbuffers::FieldIndexToOffset(f);
1050 case 0: builder.AddElement<uint8_t>(off, bool_val, 0); break;
1051 case 1: builder.AddElement<int8_t>(off, char_val, 0); break;
1052 case 2: builder.AddElement<uint8_t>(off, uchar_val, 0); break;
1053 case 3: builder.AddElement<int16_t>(off, short_val, 0); break;
1054 case 4: builder.AddElement<uint16_t>(off, ushort_val, 0); break;
1055 case 5: builder.AddElement<int32_t>(off, int_val, 0); break;
1056 case 6: builder.AddElement<uint32_t>(off, uint_val, 0); break;
1057 case 7: builder.AddElement<int64_t>(off, long_val, 0); break;
1058 case 8: builder.AddElement<uint64_t>(off, ulong_val, 0); break;
1059 case 9: builder.AddElement<float>(off, float_val, 0); break;
1060 case 10: builder.AddElement<double>(off, double_val, 0); break;
1063 objects[i] = builder.EndTable(start);
1065 builder.PreAlign<flatbuffers::largest_scalar_t>(0); // Align whole buffer.
1067 lcg_reset(); // Reset.
1069 uint8_t *eob = builder.GetCurrentBufferPointer() + builder.GetSize();
1071 // Test that all objects we generated are readable and return the
1072 // expected values. We generate random objects in the same order
1073 // so this is deterministic.
1074 for (int i = 0; i < num_fuzz_objects; i++) {
1075 auto table = reinterpret_cast<flatbuffers::Table *>(eob - objects[i]);
1076 for (flatbuffers::voffset_t f = 0; f < fields_per_object; f++) {
1077 int choice = lcg_rand() % test_values_max;
1078 flatbuffers::voffset_t off = flatbuffers::FieldIndexToOffset(f);
1080 case 0: CompareTableFieldValue(table, off, bool_val); break;
1081 case 1: CompareTableFieldValue(table, off, char_val); break;
1082 case 2: CompareTableFieldValue(table, off, uchar_val); break;
1083 case 3: CompareTableFieldValue(table, off, short_val); break;
1084 case 4: CompareTableFieldValue(table, off, ushort_val); break;
1085 case 5: CompareTableFieldValue(table, off, int_val); break;
1086 case 6: CompareTableFieldValue(table, off, uint_val); break;
1087 case 7: CompareTableFieldValue(table, off, long_val); break;
1088 case 8: CompareTableFieldValue(table, off, ulong_val); break;
1089 case 9: CompareTableFieldValue(table, off, float_val); break;
1090 case 10: CompareTableFieldValue(table, off, double_val); break;
1096 // High level stress/fuzz test: generate a big schema and
1097 // matching json data in random combinations, then parse both,
1098 // generate json back from the binary, and compare with the original.
1100 lcg_reset(); // Keep it deterministic.
1102 const int num_definitions = 30;
1103 const int num_struct_definitions = 5; // Subset of num_definitions.
1104 const int fields_per_definition = 15;
1105 const int instances_per_definition = 5;
1106 const int deprecation_rate = 10; // 1 in deprecation_rate fields will
1109 std::string schema = "namespace test;\n\n";
1112 std::string instances[instances_per_definition];
1114 // Since we're generating schema and corresponding data in tandem,
1115 // this convenience function adds strings to both at once.
1116 static void Add(RndDef (&definitions_l)[num_definitions],
1117 std::string &schema_l, const int instances_per_definition_l,
1118 const char *schema_add, const char *instance_add,
1120 schema_l += schema_add;
1121 for (int i = 0; i < instances_per_definition_l; i++)
1122 definitions_l[definition].instances[i] += instance_add;
1127 #define AddToSchemaAndInstances(schema_add, instance_add) \
1128 RndDef::Add(definitions, schema, instances_per_definition, \
1129 schema_add, instance_add, definition)
1132 RndDef::Add(definitions, schema, instances_per_definition, \
1133 "byte", "1", definition)
1136 RndDef definitions[num_definitions];
1138 // We are going to generate num_definitions, the first
1139 // num_struct_definitions will be structs, the rest tables. For each
1140 // generate random fields, some of which may be struct/table types
1141 // referring to previously generated structs/tables.
1142 // Simultanenously, we generate instances_per_definition JSON data
1143 // definitions, which will have identical structure to the schema
1144 // being generated. We generate multiple instances such that when creating
1145 // hierarchy, we get some variety by picking one randomly.
1146 for (int definition = 0; definition < num_definitions; definition++) {
1147 std::string definition_name = "D" + flatbuffers::NumToString(definition);
1149 bool is_struct = definition < num_struct_definitions;
1151 AddToSchemaAndInstances(
1152 ((is_struct ? "struct " : "table ") + definition_name + " {\n").c_str(),
1155 for (int field = 0; field < fields_per_definition; field++) {
1156 const bool is_last_field = field == fields_per_definition - 1;
1158 // Deprecate 1 in deprecation_rate fields. Only table fields can be
1160 // Don't deprecate the last field to avoid dangling commas in JSON.
1161 const bool deprecated =
1162 !is_struct && !is_last_field && (lcg_rand() % deprecation_rate == 0);
1164 std::string field_name = "f" + flatbuffers::NumToString(field);
1165 AddToSchemaAndInstances((" " + field_name + ":").c_str(),
1166 deprecated ? "" : (field_name + ": ").c_str());
1167 // Pick random type:
1168 auto base_type = static_cast<flatbuffers::BaseType>(
1169 lcg_rand() % (flatbuffers::BASE_TYPE_UNION + 1));
1170 switch (base_type) {
1171 case flatbuffers::BASE_TYPE_STRING:
1173 Dummy(); // No strings in structs.
1175 AddToSchemaAndInstances("string", deprecated ? "" : "\"hi\"");
1178 case flatbuffers::BASE_TYPE_VECTOR:
1180 Dummy(); // No vectors in structs.
1182 AddToSchemaAndInstances("[ubyte]",
1183 deprecated ? "" : "[\n0,\n1,\n255\n]");
1186 case flatbuffers::BASE_TYPE_NONE:
1187 case flatbuffers::BASE_TYPE_UTYPE:
1188 case flatbuffers::BASE_TYPE_STRUCT:
1189 case flatbuffers::BASE_TYPE_UNION:
1191 // Pick a random previous definition and random data instance of
1193 int defref = lcg_rand() % definition;
1194 int instance = lcg_rand() % instances_per_definition;
1195 AddToSchemaAndInstances(
1196 ("D" + flatbuffers::NumToString(defref)).c_str(),
1198 : definitions[defref].instances[instance].c_str());
1200 // If this is the first definition, we have no definition we can
1205 case flatbuffers::BASE_TYPE_BOOL:
1206 AddToSchemaAndInstances(
1207 "bool", deprecated ? "" : (lcg_rand() % 2 ? "true" : "false"));
1209 case flatbuffers::BASE_TYPE_ARRAY:
1211 AddToSchemaAndInstances(
1213 deprecated ? "" : "255"); // No fixed-length arrays in tables.
1215 AddToSchemaAndInstances("[int:3]", deprecated ? "" : "[\n,\n,\n]");
1219 // All the scalar types.
1220 schema += flatbuffers::kTypeNames[base_type];
1223 // We want each instance to use its own random value.
1224 for (int inst = 0; inst < instances_per_definition; inst++)
1225 definitions[definition].instances[inst] +=
1226 flatbuffers::IsFloat(base_type)
1227 ? flatbuffers::NumToString<double>(lcg_rand() % 128)
1229 : flatbuffers::NumToString<int>(lcg_rand() % 128).c_str();
1232 AddToSchemaAndInstances(deprecated ? "(deprecated);\n" : ";\n",
1233 deprecated ? "" : is_last_field ? "\n" : ",\n");
1235 AddToSchemaAndInstances("}\n\n", "}");
1238 schema += "root_type D" + flatbuffers::NumToString(num_definitions - 1);
1241 flatbuffers::Parser parser;
1243 // Will not compare against the original if we don't write defaults
1244 parser.builder_.ForceDefaults(true);
1246 // Parse the schema, parse the generated data, then generate text back
1247 // from the binary and compare against the original.
1248 TEST_EQ(parser.Parse(schema.c_str()), true);
1250 const std::string &json =
1251 definitions[num_definitions - 1].instances[0] + "\n";
1253 TEST_EQ(parser.Parse(json.c_str()), true);
1255 std::string jsongen;
1256 parser.opts.indent_step = 0;
1258 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1259 TEST_EQ(result, true);
1261 if (jsongen != json) {
1262 // These strings are larger than a megabyte, so we show the bytes around
1263 // the first bytes that are different rather than the whole string.
1264 size_t len = std::min(json.length(), jsongen.length());
1265 for (size_t i = 0; i < len; i++) {
1266 if (json[i] != jsongen[i]) {
1267 i -= std::min(static_cast<size_t>(10), i); // show some context;
1268 size_t end = std::min(len, i + 20);
1269 for (; i < end; i++)
1270 TEST_OUTPUT_LINE("at %d: found \"%c\", expected \"%c\"\n",
1271 static_cast<int>(i), jsongen[i], json[i]);
1279 #ifdef FLATBUFFERS_TEST_VERBOSE
1280 TEST_OUTPUT_LINE("%dk schema tested with %dk of json\n",
1281 static_cast<int>(schema.length() / 1024),
1282 static_cast<int>(json.length() / 1024));
1287 // Test that parser errors are actually generated.
1288 void TestError_(const char *src, const char *error_substr, bool strict_json,
1289 const char *file, int line, const char *func) {
1290 flatbuffers::IDLOptions opts;
1291 opts.strict_json = strict_json;
1292 flatbuffers::Parser parser(opts);
1293 if (parser.Parse(src)) {
1294 TestFail("true", "false",
1295 ("parser.Parse(\"" + std::string(src) + "\")").c_str(), file, line,
1297 } else if (!strstr(parser.error_.c_str(), error_substr)) {
1298 TestFail(parser.error_.c_str(), error_substr,
1299 ("parser.Parse(\"" + std::string(src) + "\")").c_str(), file, line,
1304 void TestError_(const char *src, const char *error_substr, const char *file,
1305 int line, const char *func) {
1306 TestError_(src, error_substr, false, file, line, func);
1310 # define TestError(src, ...) \
1311 TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
1313 # define TestError(src, ...) \
1314 TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1317 // Test that parsing errors occur as we'd expect.
1318 // Also useful for coverage, making sure these paths are run.
1320 // In order they appear in idl_parser.cpp
1321 TestError("table X { Y:byte; } root_type X; { Y: 999 }", "does not fit");
1322 TestError("\"\0", "illegal");
1323 TestError("\"\\q", "escape code");
1324 TestError("table ///", "documentation");
1325 TestError("@", "illegal");
1326 TestError("table 1", "expecting");
1327 TestError("table X { Y:[[int]]; }", "nested vector");
1328 TestError("table X { Y:1; }", "illegal type");
1329 TestError("table X { Y:int; Y:int; }", "field already");
1330 TestError("table Y {} table X { Y:int; }", "same as table");
1331 TestError("struct X { Y:string; }", "only scalar");
1332 TestError("table X { Y:string = \"\"; }", "default values");
1333 TestError("struct X { a:uint = 42; }", "default values");
1334 TestError("enum Y:byte { Z = 1 } table X { y:Y; }", "not part of enum");
1335 TestError("struct X { Y:int (deprecated); }", "deprecate");
1336 TestError("union Z { X } table X { Y:Z; } root_type X; { Y: {}, A:1 }",
1337 "missing type field");
1338 TestError("union Z { X } table X { Y:Z; } root_type X; { Y_type: 99, Y: {",
1340 TestError("table X { Y:int; } root_type X; { Z:", "unknown field");
1341 TestError("table X { Y:int; } root_type X; { Y:", "string constant", true);
1342 TestError("table X { Y:int; } root_type X; { \"Y\":1, }", "string constant",
1345 "struct X { Y:int; Z:int; } table W { V:X; } root_type W; "
1348 TestError("enum E:byte { A } table X { Y:E; } root_type X; { Y:U }",
1349 "unknown enum value");
1350 TestError("table X { Y:byte; } root_type X; { Y:; }", "starting");
1351 TestError("enum X:byte { Y } enum X {", "enum already");
1352 TestError("enum X:float {}", "underlying");
1353 TestError("enum X:byte { Y, Y }", "value already");
1354 TestError("enum X:byte { Y=2, Z=1 }", "ascending");
1355 TestError("table X { Y:int; } table X {", "datatype already");
1356 TestError("struct X (force_align: 7) { Y:int; }", "force_align");
1357 TestError("struct X {}", "size 0");
1358 TestError("{}", "no root");
1359 TestError("table X { Y:byte; } root_type X; { Y:1 } { Y:1 }", "end of file");
1360 TestError("table X { Y:byte; } root_type X; { Y:1 } table Y{ Z:int }",
1362 TestError("root_type X;", "unknown root");
1363 TestError("struct X { Y:int; } root_type X;", "a table");
1364 TestError("union X { Y }", "referenced");
1365 TestError("union Z { X } struct X { Y:int; }", "only tables");
1366 TestError("table X { Y:[int]; YLength:int; }", "clash");
1367 TestError("table X { Y:byte; } root_type X; { Y:1, Y:2 }", "more than once");
1368 // float to integer conversion is forbidden
1369 TestError("table X { Y:int; } root_type X; { Y:1.0 }", "float");
1370 TestError("table X { Y:bool; } root_type X; { Y:1.0 }", "float");
1371 TestError("enum X:bool { Y = true }", "must be integral");
1374 template<typename T>
1375 T TestValue(const char *json, const char *type_name,
1376 const char *decls = nullptr) {
1377 flatbuffers::Parser parser;
1378 parser.builder_.ForceDefaults(true); // return defaults
1379 auto check_default = json ? false : true;
1380 if (check_default) { parser.opts.output_default_scalars_in_json = true; }
1382 std::string schema = std::string(decls ? decls : "") + "\n" +
1383 "table X { Y:" + std::string(type_name) +
1385 auto schema_done = parser.Parse(schema.c_str());
1386 TEST_EQ_STR(parser.error_.c_str(), "");
1387 TEST_EQ(schema_done, true);
1389 auto done = parser.Parse(check_default ? "{}" : json);
1390 TEST_EQ_STR(parser.error_.c_str(), "");
1391 TEST_EQ(done, true);
1393 // Check with print.
1394 std::string print_back;
1395 parser.opts.indent_step = -1;
1396 TEST_EQ(GenerateText(parser, parser.builder_.GetBufferPointer(), &print_back),
1398 // restore value from its default
1399 if (check_default) { TEST_EQ(parser.Parse(print_back.c_str()), true); }
1401 auto root = flatbuffers::GetRoot<flatbuffers::Table>(
1402 parser.builder_.GetBufferPointer());
1403 return root->GetField<T>(flatbuffers::FieldIndexToOffset(0), 0);
1406 bool FloatCompare(float a, float b) { return fabs(a - b) < 0.001; }
1408 // Additional parser testing not covered elsewhere.
1410 // Test scientific notation numbers.
1411 TEST_EQ(FloatCompare(TestValue<float>("{ Y:0.0314159e+2 }", "float"),
1415 TEST_EQ(FloatCompare(TestValue<float>("{ Y:\"0.0314159e+2\" }", "float"),
1419 // Test conversion functions.
1420 TEST_EQ(FloatCompare(TestValue<float>("{ Y:cos(rad(180)) }", "float"), -1),
1423 // int embedded to string
1424 TEST_EQ(TestValue<int>("{ Y:\"-876\" }", "int=-123"), -876);
1425 TEST_EQ(TestValue<int>("{ Y:\"876\" }", "int=-123"), 876);
1427 // Test negative hex constant.
1428 TEST_EQ(TestValue<int>("{ Y:-0x8ea0 }", "int=-0x8ea0"), -36512);
1429 TEST_EQ(TestValue<int>(nullptr, "int=-0x8ea0"), -36512);
1431 // positive hex constant
1432 TEST_EQ(TestValue<int>("{ Y:0x1abcdef }", "int=0x1"), 0x1abcdef);
1433 // with optional '+' sign
1434 TEST_EQ(TestValue<int>("{ Y:+0x1abcdef }", "int=+0x1"), 0x1abcdef);
1436 TEST_EQ(TestValue<int>("{ Y:\"0x1abcdef\" }", "int=+0x1"), 0x1abcdef);
1438 // Make sure we do unsigned 64bit correctly.
1439 TEST_EQ(TestValue<uint64_t>("{ Y:12335089644688340133 }", "ulong"),
1440 12335089644688340133ULL);
1443 TEST_EQ(TestValue<bool>("{ Y:\"false\" }", "bool=true"), false);
1444 TEST_EQ(TestValue<bool>("{ Y:\"true\" }", "bool=\"true\""), true);
1445 TEST_EQ(TestValue<bool>("{ Y:'false' }", "bool=true"), false);
1446 TEST_EQ(TestValue<bool>("{ Y:'true' }", "bool=\"true\""), true);
1448 // check comments before and after json object
1449 TEST_EQ(TestValue<int>("/*before*/ { Y:1 } /*after*/", "int"), 1);
1450 TEST_EQ(TestValue<int>("//before \n { Y:1 } //after", "int"), 1);
1454 void NestedListTest() {
1455 flatbuffers::Parser parser1;
1456 TEST_EQ(parser1.Parse("struct Test { a:short; b:byte; } table T { F:[Test]; }"
1458 "{ F:[ [10,20], [30,40]] }"),
1462 void EnumStringsTest() {
1463 flatbuffers::Parser parser1;
1464 TEST_EQ(parser1.Parse("enum E:byte { A, B, C } table T { F:[E]; }"
1466 "{ F:[ A, B, \"C\", \"A B C\" ] }"),
1468 flatbuffers::Parser parser2;
1469 TEST_EQ(parser2.Parse("enum E:byte { A, B, C } table T { F:[int]; }"
1471 "{ F:[ \"E.C\", \"E.A E.B E.C\" ] }"),
1473 // unsigned bit_flags
1474 flatbuffers::Parser parser3;
1476 parser3.Parse("enum E:uint16 (bit_flags) { F0, F07=7, F08, F14=14, F15 }"
1477 " table T { F: E = \"F15 F08\"; }"
1482 void EnumNamesTest() {
1483 TEST_EQ_STR("Red", EnumNameColor(Color_Red));
1484 TEST_EQ_STR("Green", EnumNameColor(Color_Green));
1485 TEST_EQ_STR("Blue", EnumNameColor(Color_Blue));
1486 // Check that Color to string don't crash while decode a mixture of Colors.
1487 // 1) Example::Color enum is enum with unfixed underlying type.
1488 // 2) Valid enum range: [0; 2^(ceil(log2(Color_ANY))) - 1].
1489 // Consequence: A value is out of this range will lead to UB (since C++17).
1490 // For details see C++17 standard or explanation on the SO:
1491 // stackoverflow.com/questions/18195312/what-happens-if-you-static-cast-invalid-value-to-enum-class
1492 TEST_EQ_STR("", EnumNameColor(static_cast<Color>(0)));
1493 TEST_EQ_STR("", EnumNameColor(static_cast<Color>(Color_ANY-1)));
1494 TEST_EQ_STR("", EnumNameColor(static_cast<Color>(Color_ANY+1)));
1497 void EnumOutOfRangeTest() {
1498 TestError("enum X:byte { Y = 128 }", "enum value does not fit");
1499 TestError("enum X:byte { Y = -129 }", "enum value does not fit");
1500 TestError("enum X:byte { Y = 126, Z0, Z1 }", "enum value does not fit");
1501 TestError("enum X:ubyte { Y = -1 }", "enum value does not fit");
1502 TestError("enum X:ubyte { Y = 256 }", "enum value does not fit");
1503 TestError("enum X:ubyte { Y = 255, Z }", "enum value does not fit");
1504 // Unions begin with an implicit "NONE = 0".
1505 TestError("table Y{} union X { Y = -1 }",
1506 "enum values must be specified in ascending order");
1507 TestError("table Y{} union X { Y = 256 }", "enum value does not fit");
1508 TestError("table Y{} union X { Y = 255, Z:Y }", "enum value does not fit");
1509 TestError("enum X:int { Y = -2147483649 }", "enum value does not fit");
1510 TestError("enum X:int { Y = 2147483648 }", "enum value does not fit");
1511 TestError("enum X:uint { Y = -1 }", "enum value does not fit");
1512 TestError("enum X:uint { Y = 4294967297 }", "enum value does not fit");
1513 TestError("enum X:long { Y = 9223372036854775808 }", "does not fit");
1514 TestError("enum X:long { Y = 9223372036854775807, Z }", "enum value does not fit");
1515 TestError("enum X:ulong { Y = -1 }", "does not fit");
1516 TestError("enum X:ubyte (bit_flags) { Y=8 }", "bit flag out");
1517 TestError("enum X:byte (bit_flags) { Y=7 }", "must be unsigned"); // -128
1518 // bit_flgs out of range
1519 TestError("enum X:ubyte (bit_flags) { Y0,Y1,Y2,Y3,Y4,Y5,Y6,Y7,Y8 }", "out of range");
1522 void EnumValueTest() {
1523 // json: "{ Y:0 }", schema: table X { Y : "E"}
1524 // 0 in enum (V=0) E then Y=0 is valid.
1525 TEST_EQ(TestValue<int>("{ Y:0 }", "E", "enum E:int { V }"), 0);
1526 TEST_EQ(TestValue<int>("{ Y:V }", "E", "enum E:int { V }"), 0);
1527 // A default value of Y is 0.
1528 TEST_EQ(TestValue<int>("{ }", "E", "enum E:int { V }"), 0);
1529 TEST_EQ(TestValue<int>("{ Y:5 }", "E=V", "enum E:int { V=5 }"), 5);
1530 // Generate json with defaults and check.
1531 TEST_EQ(TestValue<int>(nullptr, "E=V", "enum E:int { V=5 }"), 5);
1533 TEST_EQ(TestValue<int>("{ Y:5 }", "E", "enum E:int { Z, V=5 }"), 5);
1534 TEST_EQ(TestValue<int>("{ Y:5 }", "E=V", "enum E:int { Z, V=5 }"), 5);
1535 // Generate json with defaults and check.
1536 TEST_EQ(TestValue<int>(nullptr, "E", "enum E:int { Z, V=5 }"), 0);
1537 TEST_EQ(TestValue<int>(nullptr, "E=V", "enum E:int { Z, V=5 }"), 5);
1539 TEST_EQ(TestValue<uint64_t>(nullptr, "E=V",
1540 "enum E:ulong { V = 13835058055282163712 }"),
1541 13835058055282163712ULL);
1542 TEST_EQ(TestValue<uint64_t>(nullptr, "E=V",
1543 "enum E:ulong { V = 18446744073709551615 }"),
1544 18446744073709551615ULL);
1545 // Assign non-enum value to enum field. Is it right?
1546 TEST_EQ(TestValue<int>("{ Y:7 }", "E", "enum E:int { V = 0 }"), 7);
1549 void IntegerOutOfRangeTest() {
1550 TestError("table T { F:byte; } root_type T; { F:128 }",
1551 "constant does not fit");
1552 TestError("table T { F:byte; } root_type T; { F:-129 }",
1553 "constant does not fit");
1554 TestError("table T { F:ubyte; } root_type T; { F:256 }",
1555 "constant does not fit");
1556 TestError("table T { F:ubyte; } root_type T; { F:-1 }",
1557 "constant does not fit");
1558 TestError("table T { F:short; } root_type T; { F:32768 }",
1559 "constant does not fit");
1560 TestError("table T { F:short; } root_type T; { F:-32769 }",
1561 "constant does not fit");
1562 TestError("table T { F:ushort; } root_type T; { F:65536 }",
1563 "constant does not fit");
1564 TestError("table T { F:ushort; } root_type T; { F:-1 }",
1565 "constant does not fit");
1566 TestError("table T { F:int; } root_type T; { F:2147483648 }",
1567 "constant does not fit");
1568 TestError("table T { F:int; } root_type T; { F:-2147483649 }",
1569 "constant does not fit");
1570 TestError("table T { F:uint; } root_type T; { F:4294967296 }",
1571 "constant does not fit");
1572 TestError("table T { F:uint; } root_type T; { F:-1 }",
1573 "constant does not fit");
1574 // Check fixed width aliases
1575 TestError("table X { Y:uint8; } root_type X; { Y: -1 }", "does not fit");
1576 TestError("table X { Y:uint8; } root_type X; { Y: 256 }", "does not fit");
1577 TestError("table X { Y:uint16; } root_type X; { Y: -1 }", "does not fit");
1578 TestError("table X { Y:uint16; } root_type X; { Y: 65536 }", "does not fit");
1579 TestError("table X { Y:uint32; } root_type X; { Y: -1 }", "");
1580 TestError("table X { Y:uint32; } root_type X; { Y: 4294967296 }",
1582 TestError("table X { Y:uint64; } root_type X; { Y: -1 }", "");
1583 TestError("table X { Y:uint64; } root_type X; { Y: -9223372036854775809 }",
1585 TestError("table X { Y:uint64; } root_type X; { Y: 18446744073709551616 }",
1588 TestError("table X { Y:int8; } root_type X; { Y: -129 }", "does not fit");
1589 TestError("table X { Y:int8; } root_type X; { Y: 128 }", "does not fit");
1590 TestError("table X { Y:int16; } root_type X; { Y: -32769 }", "does not fit");
1591 TestError("table X { Y:int16; } root_type X; { Y: 32768 }", "does not fit");
1592 TestError("table X { Y:int32; } root_type X; { Y: -2147483649 }", "");
1593 TestError("table X { Y:int32; } root_type X; { Y: 2147483648 }",
1595 TestError("table X { Y:int64; } root_type X; { Y: -9223372036854775809 }",
1597 TestError("table X { Y:int64; } root_type X; { Y: 9223372036854775808 }",
1599 // check out-of-int64 as int8
1600 TestError("table X { Y:int8; } root_type X; { Y: -9223372036854775809 }",
1602 TestError("table X { Y:int8; } root_type X; { Y: 9223372036854775808 }",
1605 // Check default values
1606 TestError("table X { Y:int64=-9223372036854775809; } root_type X; {}",
1608 TestError("table X { Y:int64= 9223372036854775808; } root_type X; {}",
1610 TestError("table X { Y:uint64; } root_type X; { Y: -1 }", "");
1611 TestError("table X { Y:uint64=-9223372036854775809; } root_type X; {}",
1613 TestError("table X { Y:uint64= 18446744073709551616; } root_type X; {}",
1617 void IntegerBoundaryTest() {
1618 // Check numerical compatibility with non-C++ languages.
1619 // By the C++ standard, std::numerical_limits<int64_t>::min() == -9223372036854775807 (-2^63+1) or less*
1620 // The Flatbuffers grammar and most of the languages (C#, Java, Rust) expect
1621 // that minimum values are: -128, -32768,.., -9223372036854775808.
1622 // Since C++20, static_cast<int64>(0x8000000000000000ULL) is well-defined two's complement cast.
1623 // Therefore -9223372036854775808 should be valid negative value.
1624 TEST_EQ(flatbuffers::numeric_limits<int8_t>::min(), -128);
1625 TEST_EQ(flatbuffers::numeric_limits<int8_t>::max(), 127);
1626 TEST_EQ(flatbuffers::numeric_limits<int16_t>::min(), -32768);
1627 TEST_EQ(flatbuffers::numeric_limits<int16_t>::max(), 32767);
1628 TEST_EQ(flatbuffers::numeric_limits<int32_t>::min() + 1, -2147483647);
1629 TEST_EQ(flatbuffers::numeric_limits<int32_t>::max(), 2147483647ULL);
1630 TEST_EQ(flatbuffers::numeric_limits<int64_t>::min() + 1LL,
1631 -9223372036854775807LL);
1632 TEST_EQ(flatbuffers::numeric_limits<int64_t>::max(), 9223372036854775807ULL);
1633 TEST_EQ(flatbuffers::numeric_limits<uint8_t>::max(), 255);
1634 TEST_EQ(flatbuffers::numeric_limits<uint16_t>::max(), 65535);
1635 TEST_EQ(flatbuffers::numeric_limits<uint32_t>::max(), 4294967295ULL);
1636 TEST_EQ(flatbuffers::numeric_limits<uint64_t>::max(),
1637 18446744073709551615ULL);
1639 TEST_EQ(TestValue<int8_t>("{ Y:127 }", "byte"), 127);
1640 TEST_EQ(TestValue<int8_t>("{ Y:-128 }", "byte"), -128);
1641 TEST_EQ(TestValue<uint8_t>("{ Y:255 }", "ubyte"), 255);
1642 TEST_EQ(TestValue<uint8_t>("{ Y:0 }", "ubyte"), 0);
1643 TEST_EQ(TestValue<int16_t>("{ Y:32767 }", "short"), 32767);
1644 TEST_EQ(TestValue<int16_t>("{ Y:-32768 }", "short"), -32768);
1645 TEST_EQ(TestValue<uint16_t>("{ Y:65535 }", "ushort"), 65535);
1646 TEST_EQ(TestValue<uint16_t>("{ Y:0 }", "ushort"), 0);
1647 TEST_EQ(TestValue<int32_t>("{ Y:2147483647 }", "int"), 2147483647);
1648 TEST_EQ(TestValue<int32_t>("{ Y:-2147483648 }", "int") + 1, -2147483647);
1649 TEST_EQ(TestValue<uint32_t>("{ Y:4294967295 }", "uint"), 4294967295);
1650 TEST_EQ(TestValue<uint32_t>("{ Y:0 }", "uint"), 0);
1651 TEST_EQ(TestValue<int64_t>("{ Y:9223372036854775807 }", "long"),
1652 9223372036854775807LL);
1653 TEST_EQ(TestValue<int64_t>("{ Y:-9223372036854775808 }", "long") + 1LL,
1654 -9223372036854775807LL);
1655 TEST_EQ(TestValue<uint64_t>("{ Y:18446744073709551615 }", "ulong"),
1656 18446744073709551615ULL);
1657 TEST_EQ(TestValue<uint64_t>("{ Y:0 }", "ulong"), 0);
1658 TEST_EQ(TestValue<uint64_t>("{ Y: 18446744073709551615 }", "uint64"),
1659 18446744073709551615ULL);
1660 // check that the default works
1661 TEST_EQ(TestValue<uint64_t>(nullptr, "uint64 = 18446744073709551615"),
1662 18446744073709551615ULL);
1665 void ValidFloatTest() {
1666 const auto infinityf = flatbuffers::numeric_limits<float>::infinity();
1667 const auto infinityd = flatbuffers::numeric_limits<double>::infinity();
1668 // check rounding to infinity
1669 TEST_EQ(TestValue<float>("{ Y:+3.4029e+38 }", "float"), +infinityf);
1670 TEST_EQ(TestValue<float>("{ Y:-3.4029e+38 }", "float"), -infinityf);
1671 TEST_EQ(TestValue<double>("{ Y:+1.7977e+308 }", "double"), +infinityd);
1672 TEST_EQ(TestValue<double>("{ Y:-1.7977e+308 }", "double"), -infinityd);
1675 FloatCompare(TestValue<float>("{ Y:0.0314159e+2 }", "float"), 3.14159f),
1678 TEST_EQ(FloatCompare(TestValue<float>("{ Y:\" 0.0314159e+2 \" }", "float"),
1682 TEST_EQ(TestValue<float>("{ Y:1 }", "float"), 1.0f);
1683 TEST_EQ(TestValue<float>("{ Y:1.0 }", "float"), 1.0f);
1684 TEST_EQ(TestValue<float>("{ Y:1. }", "float"), 1.0f);
1685 TEST_EQ(TestValue<float>("{ Y:+1. }", "float"), 1.0f);
1686 TEST_EQ(TestValue<float>("{ Y:-1. }", "float"), -1.0f);
1687 TEST_EQ(TestValue<float>("{ Y:1.e0 }", "float"), 1.0f);
1688 TEST_EQ(TestValue<float>("{ Y:1.e+0 }", "float"), 1.0f);
1689 TEST_EQ(TestValue<float>("{ Y:1.e-0 }", "float"), 1.0f);
1690 TEST_EQ(TestValue<float>("{ Y:0.125 }", "float"), 0.125f);
1691 TEST_EQ(TestValue<float>("{ Y:.125 }", "float"), 0.125f);
1692 TEST_EQ(TestValue<float>("{ Y:-.125 }", "float"), -0.125f);
1693 TEST_EQ(TestValue<float>("{ Y:+.125 }", "float"), +0.125f);
1694 TEST_EQ(TestValue<float>("{ Y:5 }", "float"), 5.0f);
1695 TEST_EQ(TestValue<float>("{ Y:\"5\" }", "float"), 5.0f);
1697 #if defined(FLATBUFFERS_HAS_NEW_STRTOD)
1698 // Old MSVC versions may have problem with this check.
1699 // https://www.exploringbinary.com/visual-c-plus-plus-strtod-still-broken/
1700 TEST_EQ(TestValue<double>("{ Y:6.9294956446009195e15 }", "double"),
1701 6929495644600920.0);
1703 TEST_EQ(std::isnan(TestValue<double>("{ Y:nan }", "double")), true);
1704 TEST_EQ(std::isnan(TestValue<float>("{ Y:nan }", "float")), true);
1705 TEST_EQ(std::isnan(TestValue<float>("{ Y:\"nan\" }", "float")), true);
1706 TEST_EQ(std::isnan(TestValue<float>("{ Y:+nan }", "float")), true);
1707 TEST_EQ(std::isnan(TestValue<float>("{ Y:-nan }", "float")), true);
1708 TEST_EQ(std::isnan(TestValue<float>(nullptr, "float=nan")), true);
1709 TEST_EQ(std::isnan(TestValue<float>(nullptr, "float=-nan")), true);
1711 TEST_EQ(TestValue<float>("{ Y:inf }", "float"), infinityf);
1712 TEST_EQ(TestValue<float>("{ Y:\"inf\" }", "float"), infinityf);
1713 TEST_EQ(TestValue<float>("{ Y:+inf }", "float"), infinityf);
1714 TEST_EQ(TestValue<float>("{ Y:-inf }", "float"), -infinityf);
1715 TEST_EQ(TestValue<float>(nullptr, "float=inf"), infinityf);
1716 TEST_EQ(TestValue<float>(nullptr, "float=-inf"), -infinityf);
1718 "{ Y : [0.2, .2, 1.0, -1.0, -2., 2., 1e0, -1e0, 1.0e0, -1.0e0, -3.e2, "
1722 "{ Y : [0.2, .2, 1.0, -1.0, -2., 2., 1e0, -1e0, 1.0e0, -1.0e0, -3.e2, "
1726 // Test binary format of float point.
1727 // https://en.cppreference.com/w/cpp/language/floating_literal
1728 // 0x11.12p-1 = (1*16^1 + 2*16^0 + 3*16^-1 + 4*16^-2) * 2^-1 =
1729 TEST_EQ(TestValue<double>("{ Y:0x12.34p-1 }", "double"), 9.1015625);
1730 // hex fraction 1.2 (decimal 1.125) scaled by 2^3, that is 9.0
1731 TEST_EQ(TestValue<float>("{ Y:-0x0.2p0 }", "float"), -0.125f);
1732 TEST_EQ(TestValue<float>("{ Y:-0x.2p1 }", "float"), -0.25f);
1733 TEST_EQ(TestValue<float>("{ Y:0x1.2p3 }", "float"), 9.0f);
1734 TEST_EQ(TestValue<float>("{ Y:0x10.1p0 }", "float"), 16.0625f);
1735 TEST_EQ(TestValue<double>("{ Y:0x1.2p3 }", "double"), 9.0);
1736 TEST_EQ(TestValue<double>("{ Y:0x10.1p0 }", "double"), 16.0625);
1737 TEST_EQ(TestValue<double>("{ Y:0xC.68p+2 }", "double"), 49.625);
1738 TestValue<double>("{ Y : [0x20.4ep1, +0x20.4ep1, -0x20.4ep1] }", "[double]");
1739 TestValue<float>("{ Y : [0x20.4ep1, +0x20.4ep1, -0x20.4ep1] }", "[float]");
1741 #else // FLATBUFFERS_HAS_NEW_STRTOD
1742 TEST_OUTPUT_LINE("FLATBUFFERS_HAS_NEW_STRTOD tests skipped");
1743 #endif // FLATBUFFERS_HAS_NEW_STRTOD
1746 void InvalidFloatTest() {
1747 auto invalid_msg = "invalid number";
1748 auto comma_msg = "expecting: ,";
1749 TestError("table T { F:float; } root_type T; { F:1,0 }", "");
1750 TestError("table T { F:float; } root_type T; { F:. }", "");
1751 TestError("table T { F:float; } root_type T; { F:- }", invalid_msg);
1752 TestError("table T { F:float; } root_type T; { F:+ }", invalid_msg);
1753 TestError("table T { F:float; } root_type T; { F:-. }", invalid_msg);
1754 TestError("table T { F:float; } root_type T; { F:+. }", invalid_msg);
1755 TestError("table T { F:float; } root_type T; { F:.e }", "");
1756 TestError("table T { F:float; } root_type T; { F:-e }", invalid_msg);
1757 TestError("table T { F:float; } root_type T; { F:+e }", invalid_msg);
1758 TestError("table T { F:float; } root_type T; { F:-.e }", invalid_msg);
1759 TestError("table T { F:float; } root_type T; { F:+.e }", invalid_msg);
1760 TestError("table T { F:float; } root_type T; { F:-e1 }", invalid_msg);
1761 TestError("table T { F:float; } root_type T; { F:+e1 }", invalid_msg);
1762 TestError("table T { F:float; } root_type T; { F:1.0e+ }", invalid_msg);
1763 TestError("table T { F:float; } root_type T; { F:1.0e- }", invalid_msg);
1764 // exponent pP is mandatory for hex-float
1765 TestError("table T { F:float; } root_type T; { F:0x0 }", invalid_msg);
1766 TestError("table T { F:float; } root_type T; { F:-0x. }", invalid_msg);
1767 TestError("table T { F:float; } root_type T; { F:0x. }", invalid_msg);
1768 // eE not exponent in hex-float!
1769 TestError("table T { F:float; } root_type T; { F:0x0.0e+ }", invalid_msg);
1770 TestError("table T { F:float; } root_type T; { F:0x0.0e- }", invalid_msg);
1771 TestError("table T { F:float; } root_type T; { F:0x0.0p }", invalid_msg);
1772 TestError("table T { F:float; } root_type T; { F:0x0.0p+ }", invalid_msg);
1773 TestError("table T { F:float; } root_type T; { F:0x0.0p- }", invalid_msg);
1774 TestError("table T { F:float; } root_type T; { F:0x0.0pa1 }", invalid_msg);
1775 TestError("table T { F:float; } root_type T; { F:0x0.0e+ }", invalid_msg);
1776 TestError("table T { F:float; } root_type T; { F:0x0.0e- }", invalid_msg);
1777 TestError("table T { F:float; } root_type T; { F:0x0.0e+0 }", invalid_msg);
1778 TestError("table T { F:float; } root_type T; { F:0x0.0e-0 }", invalid_msg);
1779 TestError("table T { F:float; } root_type T; { F:0x0.0ep+ }", invalid_msg);
1780 TestError("table T { F:float; } root_type T; { F:0x0.0ep- }", invalid_msg);
1781 TestError("table T { F:float; } root_type T; { F:1.2.3 }", invalid_msg);
1782 TestError("table T { F:float; } root_type T; { F:1.2.e3 }", invalid_msg);
1783 TestError("table T { F:float; } root_type T; { F:1.2e.3 }", invalid_msg);
1784 TestError("table T { F:float; } root_type T; { F:1.2e0.3 }", invalid_msg);
1785 TestError("table T { F:float; } root_type T; { F:1.2e3. }", invalid_msg);
1786 TestError("table T { F:float; } root_type T; { F:1.2e3.0 }", invalid_msg);
1787 TestError("table T { F:float; } root_type T; { F:+-1.0 }", invalid_msg);
1788 TestError("table T { F:float; } root_type T; { F:1.0e+-1 }", invalid_msg);
1789 TestError("table T { F:float; } root_type T; { F:\"1.0e+-1\" }", invalid_msg);
1790 TestError("table T { F:float; } root_type T; { F:1.e0e }", comma_msg);
1791 TestError("table T { F:float; } root_type T; { F:0x1.p0e }", comma_msg);
1792 TestError("table T { F:float; } root_type T; { F:\" 0x10 \" }", invalid_msg);
1794 TestError("table T { F:float; } root_type T; { F:\"1,2.\" }", invalid_msg);
1795 TestError("table T { F:float; } root_type T; { F:\"1.2e3.\" }", invalid_msg);
1796 TestError("table T { F:float; } root_type T; { F:\"0x1.p0e\" }", invalid_msg);
1797 TestError("table T { F:float; } root_type T; { F:\"0x1.0\" }", invalid_msg);
1798 TestError("table T { F:float; } root_type T; { F:\" 0x1.0\" }", invalid_msg);
1799 TestError("table T { F:float; } root_type T; { F:\"+ 0\" }", invalid_msg);
1800 // disable escapes for "number-in-string"
1801 TestError("table T { F:float; } root_type T; { F:\"\\f1.2e3.\" }", "invalid");
1802 TestError("table T { F:float; } root_type T; { F:\"\\t1.2e3.\" }", "invalid");
1803 TestError("table T { F:float; } root_type T; { F:\"\\n1.2e3.\" }", "invalid");
1804 TestError("table T { F:float; } root_type T; { F:\"\\r1.2e3.\" }", "invalid");
1805 TestError("table T { F:float; } root_type T; { F:\"4\\x005\" }", "invalid");
1806 TestError("table T { F:float; } root_type T; { F:\"\'12\'\" }", invalid_msg);
1807 // null is not a number constant!
1808 TestError("table T { F:float; } root_type T; { F:\"null\" }", invalid_msg);
1809 TestError("table T { F:float; } root_type T; { F:null }", invalid_msg);
1812 void GenerateTableTextTest() {
1813 std::string schemafile;
1814 std::string jsonfile;
1816 flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
1817 false, &schemafile) &&
1818 flatbuffers::LoadFile((test_data_path + "monsterdata_test.json").c_str(),
1821 auto include_test_path =
1822 flatbuffers::ConCatPathFileName(test_data_path, "include_test");
1823 const char *include_directories[] = {test_data_path.c_str(),
1824 include_test_path.c_str(), nullptr};
1825 flatbuffers::IDLOptions opt;
1826 opt.indent_step = -1;
1827 flatbuffers::Parser parser(opt);
1828 ok = parser.Parse(schemafile.c_str(), include_directories) &&
1829 parser.Parse(jsonfile.c_str(), include_directories);
1832 const Monster *monster = GetMonster(parser.builder_.GetBufferPointer());
1833 std::string jsongen;
1834 auto result = GenerateTextFromTable(parser, monster, "MyGame.Example.Monster",
1836 TEST_EQ(result, true);
1838 const Vec3 *pos = monster->pos();
1840 result = GenerateTextFromTable(parser, pos, "MyGame.Example.Vec3", &jsongen);
1841 TEST_EQ(result, true);
1844 "{x: 1.0,y: 2.0,z: 3.0,test1: 3.0,test2: \"Green\",test3: {a: 5,b: 6}}");
1845 const Test &test3 = pos->test3();
1848 GenerateTextFromTable(parser, &test3, "MyGame.Example.Test", &jsongen);
1849 TEST_EQ(result, true);
1850 TEST_EQ_STR(jsongen.c_str(), "{a: 5,b: 6}");
1851 const Test *test4 = monster->test4()->Get(0);
1854 GenerateTextFromTable(parser, test4, "MyGame.Example.Test", &jsongen);
1855 TEST_EQ(result, true);
1856 TEST_EQ_STR(jsongen.c_str(), "{a: 10,b: 20}");
1859 template<typename T>
1860 void NumericUtilsTestInteger(const char *lower, const char *upper) {
1862 TEST_EQ(flatbuffers::StringToNumber("1q", &x), false);
1864 TEST_EQ(flatbuffers::StringToNumber(upper, &x), false);
1865 TEST_EQ(x, flatbuffers::numeric_limits<T>::max());
1866 TEST_EQ(flatbuffers::StringToNumber(lower, &x), false);
1867 auto expval = flatbuffers::is_unsigned<T>::value
1868 ? flatbuffers::numeric_limits<T>::max()
1869 : flatbuffers::numeric_limits<T>::lowest();
1873 template<typename T>
1874 void NumericUtilsTestFloat(const char *lower, const char *upper) {
1876 TEST_EQ(flatbuffers::StringToNumber("", &f), false);
1877 TEST_EQ(flatbuffers::StringToNumber("1q", &f), false);
1879 TEST_EQ(flatbuffers::StringToNumber(upper, &f), true);
1880 TEST_EQ(f, +flatbuffers::numeric_limits<T>::infinity());
1881 TEST_EQ(flatbuffers::StringToNumber(lower, &f), true);
1882 TEST_EQ(f, -flatbuffers::numeric_limits<T>::infinity());
1885 void NumericUtilsTest() {
1886 NumericUtilsTestInteger<uint64_t>("-1", "18446744073709551616");
1887 NumericUtilsTestInteger<uint8_t>("-1", "256");
1888 NumericUtilsTestInteger<int64_t>("-9223372036854775809",
1889 "9223372036854775808");
1890 NumericUtilsTestInteger<int8_t>("-129", "128");
1891 NumericUtilsTestFloat<float>("-3.4029e+38", "+3.4029e+38");
1892 NumericUtilsTestFloat<float>("-1.7977e+308", "+1.7977e+308");
1895 void IsAsciiUtilsTest() {
1897 for (int cnt = 0; cnt < 256; cnt++) {
1898 auto alpha = (('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z'));
1899 auto dec = (('0' <= c) && (c <= '9'));
1900 auto hex = (('a' <= c) && (c <= 'f')) || (('A' <= c) && (c <= 'F'));
1901 TEST_EQ(flatbuffers::is_alpha(c), alpha);
1902 TEST_EQ(flatbuffers::is_alnum(c), alpha || dec);
1903 TEST_EQ(flatbuffers::is_digit(c), dec);
1904 TEST_EQ(flatbuffers::is_xdigit(c), dec || hex);
1909 void UnicodeTest() {
1910 flatbuffers::Parser parser;
1911 // Without setting allow_non_utf8 = true, we treat \x sequences as byte
1912 // sequences which are then validated as UTF-8.
1913 TEST_EQ(parser.Parse("table T { F:string; }"
1915 "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1916 "\\u5225\\u30B5\\u30A4\\u30C8\\xE2\\x82\\xAC\\u0080\\uD8"
1919 std::string jsongen;
1920 parser.opts.indent_step = -1;
1922 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1923 TEST_EQ(result, true);
1924 TEST_EQ_STR(jsongen.c_str(),
1925 "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1926 "\\u5225\\u30B5\\u30A4\\u30C8\\u20AC\\u0080\\uD83D\\uDE0E\"}");
1929 void UnicodeTestAllowNonUTF8() {
1930 flatbuffers::Parser parser;
1931 parser.opts.allow_non_utf8 = true;
1934 "table T { F:string; }"
1936 "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1937 "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"),
1939 std::string jsongen;
1940 parser.opts.indent_step = -1;
1942 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1943 TEST_EQ(result, true);
1946 "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1947 "\\u5225\\u30B5\\u30A4\\u30C8\\u0001\\x80\\u0080\\uD83D\\uDE0E\"}");
1950 void UnicodeTestGenerateTextFailsOnNonUTF8() {
1951 flatbuffers::Parser parser;
1952 // Allow non-UTF-8 initially to model what happens when we load a binary
1953 // flatbuffer from disk which contains non-UTF-8 strings.
1954 parser.opts.allow_non_utf8 = true;
1957 "table T { F:string; }"
1959 "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1960 "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"),
1962 std::string jsongen;
1963 parser.opts.indent_step = -1;
1964 // Now, disallow non-UTF-8 (the default behavior) so GenerateText indicates
1966 parser.opts.allow_non_utf8 = false;
1968 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1969 TEST_EQ(result, false);
1972 void UnicodeSurrogatesTest() {
1973 flatbuffers::Parser parser;
1975 TEST_EQ(parser.Parse("table T { F:string (id: 0); }"
1977 "{ F:\"\\uD83D\\uDCA9\"}"),
1979 auto root = flatbuffers::GetRoot<flatbuffers::Table>(
1980 parser.builder_.GetBufferPointer());
1981 auto string = root->GetPointer<flatbuffers::String *>(
1982 flatbuffers::FieldIndexToOffset(0));
1983 TEST_EQ_STR(string->c_str(), "\xF0\x9F\x92\xA9");
1986 void UnicodeInvalidSurrogatesTest() {
1988 "table T { F:string; }"
1991 "unpaired high surrogate");
1993 "table T { F:string; }"
1995 "{ F:\"\\uD800abcd\"}",
1996 "unpaired high surrogate");
1998 "table T { F:string; }"
2000 "{ F:\"\\uD800\\n\"}",
2001 "unpaired high surrogate");
2003 "table T { F:string; }"
2005 "{ F:\"\\uD800\\uD800\"}",
2006 "multiple high surrogates");
2008 "table T { F:string; }"
2011 "unpaired low surrogate");
2014 void InvalidUTF8Test() {
2015 // "1 byte" pattern, under min length of 2 bytes
2017 "table T { F:string; }"
2020 "illegal UTF-8 sequence");
2021 // 2 byte pattern, string too short
2023 "table T { F:string; }"
2026 "illegal UTF-8 sequence");
2027 // 3 byte pattern, string too short
2029 "table T { F:string; }"
2031 "{ F:\"\xEF\xBF\"}",
2032 "illegal UTF-8 sequence");
2033 // 4 byte pattern, string too short
2035 "table T { F:string; }"
2037 "{ F:\"\xF7\xBF\xBF\"}",
2038 "illegal UTF-8 sequence");
2039 // "5 byte" pattern, string too short
2041 "table T { F:string; }"
2043 "{ F:\"\xFB\xBF\xBF\xBF\"}",
2044 "illegal UTF-8 sequence");
2045 // "6 byte" pattern, string too short
2047 "table T { F:string; }"
2049 "{ F:\"\xFD\xBF\xBF\xBF\xBF\"}",
2050 "illegal UTF-8 sequence");
2051 // "7 byte" pattern, string too short
2053 "table T { F:string; }"
2055 "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\"}",
2056 "illegal UTF-8 sequence");
2057 // "5 byte" pattern, over max length of 4 bytes
2059 "table T { F:string; }"
2061 "{ F:\"\xFB\xBF\xBF\xBF\xBF\"}",
2062 "illegal UTF-8 sequence");
2063 // "6 byte" pattern, over max length of 4 bytes
2065 "table T { F:string; }"
2067 "{ F:\"\xFD\xBF\xBF\xBF\xBF\xBF\"}",
2068 "illegal UTF-8 sequence");
2069 // "7 byte" pattern, over max length of 4 bytes
2071 "table T { F:string; }"
2073 "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\xBF\"}",
2074 "illegal UTF-8 sequence");
2076 // Three invalid encodings for U+000A (\n, aka NEWLINE)
2078 "table T { F:string; }"
2080 "{ F:\"\xC0\x8A\"}",
2081 "illegal UTF-8 sequence");
2083 "table T { F:string; }"
2085 "{ F:\"\xE0\x80\x8A\"}",
2086 "illegal UTF-8 sequence");
2088 "table T { F:string; }"
2090 "{ F:\"\xF0\x80\x80\x8A\"}",
2091 "illegal UTF-8 sequence");
2093 // Two invalid encodings for U+00A9 (COPYRIGHT SYMBOL)
2095 "table T { F:string; }"
2097 "{ F:\"\xE0\x81\xA9\"}",
2098 "illegal UTF-8 sequence");
2100 "table T { F:string; }"
2102 "{ F:\"\xF0\x80\x81\xA9\"}",
2103 "illegal UTF-8 sequence");
2105 // Invalid encoding for U+20AC (EURO SYMBOL)
2107 "table T { F:string; }"
2109 "{ F:\"\xF0\x82\x82\xAC\"}",
2110 "illegal UTF-8 sequence");
2112 // UTF-16 surrogate values between U+D800 and U+DFFF cannot be encoded in
2115 "table T { F:string; }"
2117 // U+10400 "encoded" as U+D801 U+DC00
2118 "{ F:\"\xED\xA0\x81\xED\xB0\x80\"}",
2119 "illegal UTF-8 sequence");
2121 // Check independence of identifier from locale.
2122 std::string locale_ident;
2123 locale_ident += "table T { F";
2124 locale_ident += static_cast<char>(-32); // unsigned 0xE0
2125 locale_ident += " :string; }";
2126 locale_ident += "root_type T;";
2127 locale_ident += "{}";
2128 TestError(locale_ident.c_str(), "");
2131 void UnknownFieldsTest() {
2132 flatbuffers::IDLOptions opts;
2133 opts.skip_unexpected_fields_in_json = true;
2134 flatbuffers::Parser parser(opts);
2136 TEST_EQ(parser.Parse("table T { str:string; i:int;}"
2139 "unknown_string:\"test\","
2140 "\"unknown_string\":\"test\","
2142 "unknown_float:1.0,"
2143 "unknown_array: [ 1, 2, 3, 4],"
2144 "unknown_object: { i: 10 },"
2145 "\"unknown_object\": { \"i\": 10 },"
2149 std::string jsongen;
2150 parser.opts.indent_step = -1;
2152 GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
2153 TEST_EQ(result, true);
2154 TEST_EQ_STR(jsongen.c_str(), "{str: \"test\",i: 10}");
2157 void ParseUnionTest() {
2158 // Unions must be parseable with the type field following the object.
2159 flatbuffers::Parser parser;
2160 TEST_EQ(parser.Parse("table T { A:int; }"
2164 "{ X:{ A:1 }, X_type: T }"),
2166 // Unions must be parsable with prefixed namespace.
2167 flatbuffers::Parser parser2;
2168 TEST_EQ(parser2.Parse("namespace N; table A {} namespace; union U { N.A }"
2169 "table B { e:U; } root_type B;"
2170 "{ e_type: N_A, e: {} }"),
2174 void InvalidNestedFlatbufferTest() {
2175 // First, load and parse FlatBuffer schema (.fbs)
2176 std::string schemafile;
2177 TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
2178 false, &schemafile),
2180 auto include_test_path =
2181 flatbuffers::ConCatPathFileName(test_data_path, "include_test");
2182 const char *include_directories[] = { test_data_path.c_str(),
2183 include_test_path.c_str(), nullptr };
2184 flatbuffers::Parser parser1;
2185 TEST_EQ(parser1.Parse(schemafile.c_str(), include_directories), true);
2187 // "color" inside nested flatbuffer contains invalid enum value
2188 TEST_EQ(parser1.Parse("{ name: \"Bender\", testnestedflatbuffer: { name: "
2189 "\"Leela\", color: \"nonexistent\"}}"),
2191 // Check that Parser is destroyed correctly after parsing invalid json
2194 void UnionVectorTest() {
2195 // load FlatBuffer fbs schema and json.
2196 std::string schemafile, jsonfile;
2197 TEST_EQ(flatbuffers::LoadFile(
2198 (test_data_path + "union_vector/union_vector.fbs").c_str(),
2199 false, &schemafile),
2201 TEST_EQ(flatbuffers::LoadFile(
2202 (test_data_path + "union_vector/union_vector.json").c_str(),
2207 flatbuffers::IDLOptions idl_opts;
2208 idl_opts.lang_to_generate |= flatbuffers::IDLOptions::kBinary;
2209 flatbuffers::Parser parser(idl_opts);
2210 TEST_EQ(parser.Parse(schemafile.c_str()), true);
2212 flatbuffers::FlatBufferBuilder fbb;
2215 std::vector<uint8_t> types;
2216 types.push_back(static_cast<uint8_t>(Character_Belle));
2217 types.push_back(static_cast<uint8_t>(Character_MuLan));
2218 types.push_back(static_cast<uint8_t>(Character_BookFan));
2219 types.push_back(static_cast<uint8_t>(Character_Other));
2220 types.push_back(static_cast<uint8_t>(Character_Unused));
2223 std::vector<flatbuffers::Offset<void>> characters;
2224 characters.push_back(fbb.CreateStruct(BookReader(/*books_read=*/7)).Union());
2225 characters.push_back(CreateAttacker(fbb, /*sword_attack_damage=*/5).Union());
2226 characters.push_back(fbb.CreateStruct(BookReader(/*books_read=*/2)).Union());
2227 characters.push_back(fbb.CreateString("Other").Union());
2228 characters.push_back(fbb.CreateString("Unused").Union());
2231 const auto movie_offset =
2232 CreateMovie(fbb, Character_Rapunzel,
2233 fbb.CreateStruct(Rapunzel(/*hair_length=*/6)).Union(),
2234 fbb.CreateVector(types), fbb.CreateVector(characters));
2235 FinishMovieBuffer(fbb, movie_offset);
2236 auto buf = fbb.GetBufferPointer();
2238 flatbuffers::Verifier verifier(buf, fbb.GetSize());
2239 TEST_EQ(VerifyMovieBuffer(verifier), true);
2241 auto flat_movie = GetMovie(buf);
2243 auto TestMovie = [](const Movie *movie) {
2244 TEST_EQ(movie->main_character_type() == Character_Rapunzel, true);
2246 auto cts = movie->characters_type();
2247 TEST_EQ(movie->characters_type()->size(), 5);
2248 TEST_EQ(cts->GetEnum<Character>(0) == Character_Belle, true);
2249 TEST_EQ(cts->GetEnum<Character>(1) == Character_MuLan, true);
2250 TEST_EQ(cts->GetEnum<Character>(2) == Character_BookFan, true);
2251 TEST_EQ(cts->GetEnum<Character>(3) == Character_Other, true);
2252 TEST_EQ(cts->GetEnum<Character>(4) == Character_Unused, true);
2254 auto rapunzel = movie->main_character_as_Rapunzel();
2255 TEST_NOTNULL(rapunzel);
2256 TEST_EQ(rapunzel->hair_length(), 6);
2258 auto cs = movie->characters();
2259 TEST_EQ(cs->size(), 5);
2260 auto belle = cs->GetAs<BookReader>(0);
2261 TEST_EQ(belle->books_read(), 7);
2262 auto mu_lan = cs->GetAs<Attacker>(1);
2263 TEST_EQ(mu_lan->sword_attack_damage(), 5);
2264 auto book_fan = cs->GetAs<BookReader>(2);
2265 TEST_EQ(book_fan->books_read(), 2);
2266 auto other = cs->GetAsString(3);
2267 TEST_EQ_STR(other->c_str(), "Other");
2268 auto unused = cs->GetAsString(4);
2269 TEST_EQ_STR(unused->c_str(), "Unused");
2272 TestMovie(flat_movie);
2274 // Also test the JSON we loaded above.
2275 TEST_EQ(parser.Parse(jsonfile.c_str()), true);
2276 auto jbuf = parser.builder_.GetBufferPointer();
2277 flatbuffers::Verifier jverifier(jbuf, parser.builder_.GetSize());
2278 TEST_EQ(VerifyMovieBuffer(jverifier), true);
2279 TestMovie(GetMovie(jbuf));
2281 auto movie_object = flat_movie->UnPack();
2282 TEST_EQ(movie_object->main_character.AsRapunzel()->hair_length(), 6);
2283 TEST_EQ(movie_object->characters[0].AsBelle()->books_read(), 7);
2284 TEST_EQ(movie_object->characters[1].AsMuLan()->sword_attack_damage, 5);
2285 TEST_EQ(movie_object->characters[2].AsBookFan()->books_read(), 2);
2286 TEST_EQ_STR(movie_object->characters[3].AsOther()->c_str(), "Other");
2287 TEST_EQ_STR(movie_object->characters[4].AsUnused()->c_str(), "Unused");
2290 fbb.Finish(Movie::Pack(fbb, movie_object));
2292 delete movie_object;
2294 auto repacked_movie = GetMovie(fbb.GetBufferPointer());
2296 TestMovie(repacked_movie);
2299 flatbuffers::FlatBufferToString(fbb.GetBufferPointer(), MovieTypeTable());
2302 "{ main_character_type: Rapunzel, main_character: { hair_length: 6 }, "
2303 "characters_type: [ Belle, MuLan, BookFan, Other, Unused ], "
2304 "characters: [ { books_read: 7 }, { sword_attack_damage: 5 }, "
2305 "{ books_read: 2 }, \"Other\", \"Unused\" ] }");
2308 flatbuffers::ToStringVisitor visitor("\n", true, " ");
2309 IterateFlatBuffer(fbb.GetBufferPointer(), MovieTypeTable(), &visitor);
2313 " \"main_character_type\": \"Rapunzel\",\n"
2314 " \"main_character\": {\n"
2315 " \"hair_length\": 6\n"
2317 " \"characters_type\": [\n"
2324 " \"characters\": [\n"
2326 " \"books_read\": 7\n"
2329 " \"sword_attack_damage\": 5\n"
2332 " \"books_read\": 2\n"
2339 flatbuffers::Parser parser2(idl_opts);
2340 TEST_EQ(parser2.Parse("struct Bool { b:bool; }"
2341 "union Any { Bool }"
2342 "table Root { a:Any; }"
2343 "root_type Root;"), true);
2344 TEST_EQ(parser2.Parse("{a_type:Bool,a:{b:true}}"), true);
2347 void ConformTest() {
2348 flatbuffers::Parser parser;
2349 TEST_EQ(parser.Parse("table T { A:int; } enum E:byte { A }"), true);
2351 auto test_conform = [](flatbuffers::Parser &parser1, const char *test,
2352 const char *expected_err) {
2353 flatbuffers::Parser parser2;
2354 TEST_EQ(parser2.Parse(test), true);
2355 auto err = parser2.ConformTo(parser1);
2356 TEST_NOTNULL(strstr(err.c_str(), expected_err));
2359 test_conform(parser, "table T { A:byte; }", "types differ for field");
2360 test_conform(parser, "table T { B:int; A:int; }", "offsets differ for field");
2361 test_conform(parser, "table T { A:int = 1; }", "defaults differ for field");
2362 test_conform(parser, "table T { B:float; }",
2363 "field renamed to different type");
2364 test_conform(parser, "enum E:byte { B, A }", "values differ for enum");
2367 void ParseProtoBufAsciiTest() {
2368 // We can put the parser in a mode where it will accept JSON that looks more
2369 // like Protobuf ASCII, for users that have data in that format.
2370 // This uses no "" for field names (which we already support by default,
2371 // omits `,`, `:` before `{` and a couple of other features.
2372 flatbuffers::Parser parser;
2373 parser.opts.protobuf_ascii_alike = true;
2375 parser.Parse("table S { B:int; } table T { A:[int]; C:S; } root_type T;"),
2377 TEST_EQ(parser.Parse("{ A [1 2] C { B:2 }}"), true);
2378 // Similarly, in text output, it should omit these.
2380 auto ok = flatbuffers::GenerateText(
2381 parser, parser.builder_.GetBufferPointer(), &text);
2383 TEST_EQ_STR(text.c_str(),
2384 "{\n A [\n 1\n 2\n ]\n C {\n B: 2\n }\n}\n");
2387 void FlexBuffersTest() {
2388 flexbuffers::Builder slb(512,
2389 flexbuffers::BUILDER_FLAG_SHARE_KEYS_AND_STRINGS);
2391 // Write the equivalent of:
2392 // { vec: [ -100, "Fred", 4.0, false ], bar: [ 1, 2, 3 ], bar3: [ 1, 2, 3 ],
2393 // foo: 100, bool: true, mymap: { foo: "Fred" } }
2395 #ifndef FLATBUFFERS_CPP98_STL
2396 // It's possible to do this without std::function support as well.
2398 slb.Vector("vec", [&]() {
2399 slb += -100; // Equivalent to slb.Add(-100) or slb.Int(-100);
2401 slb.IndirectFloat(4.0f);
2402 uint8_t blob[] = { 77 };
2406 int ints[] = { 1, 2, 3 };
2407 slb.Vector("bar", ints, 3);
2408 slb.FixedTypedVector("bar3", ints, 3);
2409 bool bools[] = {true, false, true, false};
2410 slb.Vector("bools", bools, 4);
2411 slb.Bool("bool", true);
2412 slb.Double("foo", 100);
2413 slb.Map("mymap", [&]() {
2414 slb.String("foo", "Fred"); // Testing key and string reuse.
2419 // It's possible to do this without std::function support as well.
2420 slb.Map([](flexbuffers::Builder& slb2) {
2421 slb2.Vector("vec", [](flexbuffers::Builder& slb3) {
2422 slb3 += -100; // Equivalent to slb.Add(-100) or slb.Int(-100);
2424 slb3.IndirectFloat(4.0f);
2425 uint8_t blob[] = { 77 };
2429 int ints[] = { 1, 2, 3 };
2430 slb2.Vector("bar", ints, 3);
2431 slb2.FixedTypedVector("bar3", ints, 3);
2432 slb2.Bool("bool", true);
2433 slb2.Double("foo", 100);
2434 slb2.Map("mymap", [](flexbuffers::Builder& slb3) {
2435 slb3.String("foo", "Fred"); // Testing key and string reuse.
2439 #endif // FLATBUFFERS_CPP98_STL
2441 #ifdef FLATBUFFERS_TEST_VERBOSE
2442 for (size_t i = 0; i < slb.GetBuffer().size(); i++)
2443 printf("%d ", flatbuffers::vector_data(slb.GetBuffer())[i]);
2448 auto map = flexbuffers::GetRoot(slb.GetBuffer()).AsMap();
2449 TEST_EQ(map.size(), 7);
2450 auto vec = map["vec"].AsVector();
2451 TEST_EQ(vec.size(), 5);
2452 TEST_EQ(vec[0].AsInt64(), -100);
2453 TEST_EQ_STR(vec[1].AsString().c_str(), "Fred");
2454 TEST_EQ(vec[1].AsInt64(), 0); // Number parsing failed.
2455 TEST_EQ(vec[2].AsDouble(), 4.0);
2456 TEST_EQ(vec[2].AsString().IsTheEmptyString(), true); // Wrong Type.
2457 TEST_EQ_STR(vec[2].AsString().c_str(), ""); // This still works though.
2458 TEST_EQ_STR(vec[2].ToString().c_str(), "4.0"); // Or have it converted.
2460 // Few tests for templated version of As.
2461 TEST_EQ(vec[0].As<int64_t>(), -100);
2462 TEST_EQ_STR(vec[1].As<std::string>().c_str(), "Fred");
2463 TEST_EQ(vec[1].As<int64_t>(), 0); // Number parsing failed.
2464 TEST_EQ(vec[2].As<double>(), 4.0);
2466 // Test that the blob can be accessed.
2467 TEST_EQ(vec[3].IsBlob(), true);
2468 auto blob = vec[3].AsBlob();
2469 TEST_EQ(blob.size(), 1);
2470 TEST_EQ(blob.data()[0], 77);
2471 TEST_EQ(vec[4].IsBool(), true); // Check if type is a bool
2472 TEST_EQ(vec[4].AsBool(), false); // Check if value is false
2473 auto tvec = map["bar"].AsTypedVector();
2474 TEST_EQ(tvec.size(), 3);
2475 TEST_EQ(tvec[2].AsInt8(), 3);
2476 auto tvec3 = map["bar3"].AsFixedTypedVector();
2477 TEST_EQ(tvec3.size(), 3);
2478 TEST_EQ(tvec3[2].AsInt8(), 3);
2479 TEST_EQ(map["bool"].AsBool(), true);
2480 auto tvecb = map["bools"].AsTypedVector();
2481 TEST_EQ(tvecb.ElementType(), flexbuffers::FBT_BOOL);
2482 TEST_EQ(map["foo"].AsUInt8(), 100);
2483 TEST_EQ(map["unknown"].IsNull(), true);
2484 auto mymap = map["mymap"].AsMap();
2485 // These should be equal by pointer equality, since key and value are shared.
2486 TEST_EQ(mymap.Keys()[0].AsKey(), map.Keys()[4].AsKey());
2487 TEST_EQ(mymap.Values()[0].AsString().c_str(), vec[1].AsString().c_str());
2488 // We can mutate values in the buffer.
2489 TEST_EQ(vec[0].MutateInt(-99), true);
2490 TEST_EQ(vec[0].AsInt64(), -99);
2491 TEST_EQ(vec[1].MutateString("John"), true); // Size must match.
2492 TEST_EQ_STR(vec[1].AsString().c_str(), "John");
2493 TEST_EQ(vec[1].MutateString("Alfred"), false); // Too long.
2494 TEST_EQ(vec[2].MutateFloat(2.0f), true);
2495 TEST_EQ(vec[2].AsFloat(), 2.0f);
2496 TEST_EQ(vec[2].MutateFloat(3.14159), false); // Double does not fit in float.
2497 TEST_EQ(vec[4].AsBool(), false); // Is false before change
2498 TEST_EQ(vec[4].MutateBool(true), true); // Can change a bool
2499 TEST_EQ(vec[4].AsBool(), true); // Changed bool is now true
2502 flatbuffers::Parser parser;
2504 auto jsontest = "{ a: [ 123, 456.0 ], b: \"hello\", c: true, d: false }";
2505 TEST_EQ(parser.ParseFlexBuffer(jsontest, nullptr, &slb), true);
2506 auto jroot = flexbuffers::GetRoot(slb.GetBuffer());
2507 auto jmap = jroot.AsMap();
2508 auto jvec = jmap["a"].AsVector();
2509 TEST_EQ(jvec[0].AsInt64(), 123);
2510 TEST_EQ(jvec[1].AsDouble(), 456.0);
2511 TEST_EQ_STR(jmap["b"].AsString().c_str(), "hello");
2512 TEST_EQ(jmap["c"].IsBool(), true); // Parsed correctly to a bool
2513 TEST_EQ(jmap["c"].AsBool(), true); // Parsed correctly to true
2514 TEST_EQ(jmap["d"].IsBool(), true); // Parsed correctly to a bool
2515 TEST_EQ(jmap["d"].AsBool(), false); // Parsed correctly to false
2516 // And from FlexBuffer back to JSON:
2517 auto jsonback = jroot.ToString();
2518 TEST_EQ_STR(jsontest, jsonback.c_str());
2521 void TypeAliasesTest() {
2522 flatbuffers::FlatBufferBuilder builder;
2524 builder.Finish(CreateTypeAliases(
2525 builder, flatbuffers::numeric_limits<int8_t>::min(),
2526 flatbuffers::numeric_limits<uint8_t>::max(),
2527 flatbuffers::numeric_limits<int16_t>::min(),
2528 flatbuffers::numeric_limits<uint16_t>::max(),
2529 flatbuffers::numeric_limits<int32_t>::min(),
2530 flatbuffers::numeric_limits<uint32_t>::max(),
2531 flatbuffers::numeric_limits<int64_t>::min(),
2532 flatbuffers::numeric_limits<uint64_t>::max(), 2.3f, 2.3));
2534 auto p = builder.GetBufferPointer();
2535 auto ta = flatbuffers::GetRoot<TypeAliases>(p);
2537 TEST_EQ(ta->i8(), flatbuffers::numeric_limits<int8_t>::min());
2538 TEST_EQ(ta->u8(), flatbuffers::numeric_limits<uint8_t>::max());
2539 TEST_EQ(ta->i16(), flatbuffers::numeric_limits<int16_t>::min());
2540 TEST_EQ(ta->u16(), flatbuffers::numeric_limits<uint16_t>::max());
2541 TEST_EQ(ta->i32(), flatbuffers::numeric_limits<int32_t>::min());
2542 TEST_EQ(ta->u32(), flatbuffers::numeric_limits<uint32_t>::max());
2543 TEST_EQ(ta->i64(), flatbuffers::numeric_limits<int64_t>::min());
2544 TEST_EQ(ta->u64(), flatbuffers::numeric_limits<uint64_t>::max());
2545 TEST_EQ(ta->f32(), 2.3f);
2546 TEST_EQ(ta->f64(), 2.3);
2547 using namespace flatbuffers; // is_same
2548 static_assert(is_same<decltype(ta->i8()), int8_t>::value, "invalid type");
2549 static_assert(is_same<decltype(ta->i16()), int16_t>::value, "invalid type");
2550 static_assert(is_same<decltype(ta->i32()), int32_t>::value, "invalid type");
2551 static_assert(is_same<decltype(ta->i64()), int64_t>::value, "invalid type");
2552 static_assert(is_same<decltype(ta->u8()), uint8_t>::value, "invalid type");
2553 static_assert(is_same<decltype(ta->u16()), uint16_t>::value, "invalid type");
2554 static_assert(is_same<decltype(ta->u32()), uint32_t>::value, "invalid type");
2555 static_assert(is_same<decltype(ta->u64()), uint64_t>::value, "invalid type");
2556 static_assert(is_same<decltype(ta->f32()), float>::value, "invalid type");
2557 static_assert(is_same<decltype(ta->f64()), double>::value, "invalid type");
2560 void EndianSwapTest() {
2561 TEST_EQ(flatbuffers::EndianSwap(static_cast<int16_t>(0x1234)), 0x3412);
2562 TEST_EQ(flatbuffers::EndianSwap(static_cast<int32_t>(0x12345678)),
2564 TEST_EQ(flatbuffers::EndianSwap(static_cast<int64_t>(0x1234567890ABCDEF)),
2565 0xEFCDAB9078563412);
2566 TEST_EQ(flatbuffers::EndianSwap(flatbuffers::EndianSwap(3.14f)), 3.14f);
2569 void UninitializedVectorTest() {
2570 flatbuffers::FlatBufferBuilder builder;
2572 Test *buf = nullptr;
2573 auto vector_offset = builder.CreateUninitializedVectorOfStructs<Test>(2, &buf);
2575 buf[0] = Test(10, 20);
2576 buf[1] = Test(30, 40);
2578 auto required_name = builder.CreateString("myMonster");
2579 auto monster_builder = MonsterBuilder(builder);
2580 monster_builder.add_name(required_name); // required field mandated for monster.
2581 monster_builder.add_test4(vector_offset);
2582 builder.Finish(monster_builder.Finish());
2584 auto p = builder.GetBufferPointer();
2585 auto uvt = flatbuffers::GetRoot<Monster>(p);
2587 auto vec = uvt->test4();
2589 auto test_0 = vec->Get(0);
2590 auto test_1 = vec->Get(1);
2591 TEST_EQ(test_0->a(), 10);
2592 TEST_EQ(test_0->b(), 20);
2593 TEST_EQ(test_1->a(), 30);
2594 TEST_EQ(test_1->b(), 40);
2597 void EqualOperatorTest() {
2600 TEST_EQ(b == a, true);
2601 TEST_EQ(b != a, false);
2604 TEST_EQ(b == a, false);
2605 TEST_EQ(b != a, true);
2607 TEST_EQ(b == a, true);
2608 TEST_EQ(b != a, false);
2610 b.inventory.push_back(3);
2611 TEST_EQ(b == a, false);
2612 TEST_EQ(b != a, true);
2613 b.inventory.clear();
2614 TEST_EQ(b == a, true);
2615 TEST_EQ(b != a, false);
2617 b.test.type = Any_Monster;
2618 TEST_EQ(b == a, false);
2619 TEST_EQ(b != a, true);
2622 // For testing any binaries, e.g. from fuzzing.
2623 void LoadVerifyBinaryTest() {
2625 if (flatbuffers::LoadFile((test_data_path +
2626 "fuzzer/your-filename-here").c_str(),
2628 flatbuffers::Verifier verifier(
2629 reinterpret_cast<const uint8_t *>(binary.data()), binary.size());
2630 TEST_EQ(VerifyMonsterBuffer(verifier), true);
2634 void CreateSharedStringTest() {
2635 flatbuffers::FlatBufferBuilder builder;
2636 const auto one1 = builder.CreateSharedString("one");
2637 const auto two = builder.CreateSharedString("two");
2638 const auto one2 = builder.CreateSharedString("one");
2639 TEST_EQ(one1.o, one2.o);
2640 const auto onetwo = builder.CreateSharedString("onetwo");
2641 TEST_EQ(onetwo.o != one1.o, true);
2642 TEST_EQ(onetwo.o != two.o, true);
2644 // Support for embedded nulls
2645 const char chars_b[] = {'a', '\0', 'b'};
2646 const char chars_c[] = {'a', '\0', 'c'};
2647 const auto null_b1 = builder.CreateSharedString(chars_b, sizeof(chars_b));
2648 const auto null_c = builder.CreateSharedString(chars_c, sizeof(chars_c));
2649 const auto null_b2 = builder.CreateSharedString(chars_b, sizeof(chars_b));
2650 TEST_EQ(null_b1.o != null_c.o, true); // Issue#5058 repro
2651 TEST_EQ(null_b1.o, null_b2.o);
2653 // Put the strings into an array for round trip verification.
2654 const flatbuffers::Offset<flatbuffers::String> array[7] = { one1, two, one2, onetwo, null_b1, null_c, null_b2 };
2655 const auto vector_offset = builder.CreateVector(array, flatbuffers::uoffset_t(7));
2656 MonsterBuilder monster_builder(builder);
2657 monster_builder.add_name(two);
2658 monster_builder.add_testarrayofstring(vector_offset);
2659 builder.Finish(monster_builder.Finish());
2661 // Read the Monster back.
2662 const auto *monster = flatbuffers::GetRoot<Monster>(builder.GetBufferPointer());
2663 TEST_EQ_STR(monster->name()->c_str(), "two");
2664 const auto *testarrayofstring = monster->testarrayofstring();
2665 TEST_EQ(testarrayofstring->size(), flatbuffers::uoffset_t(7));
2666 const auto &a = *testarrayofstring;
2667 TEST_EQ_STR(a[0]->c_str(), "one");
2668 TEST_EQ_STR(a[1]->c_str(), "two");
2669 TEST_EQ_STR(a[2]->c_str(), "one");
2670 TEST_EQ_STR(a[3]->c_str(), "onetwo");
2671 TEST_EQ(a[4]->str(), (std::string(chars_b, sizeof(chars_b))));
2672 TEST_EQ(a[5]->str(), (std::string(chars_c, sizeof(chars_c))));
2673 TEST_EQ(a[6]->str(), (std::string(chars_b, sizeof(chars_b))));
2675 // Make sure String::operator< works, too, since it is related to StringOffsetCompare.
2676 TEST_EQ((*a[0]) < (*a[1]), true);
2677 TEST_EQ((*a[1]) < (*a[0]), false);
2678 TEST_EQ((*a[1]) < (*a[2]), false);
2679 TEST_EQ((*a[2]) < (*a[1]), true);
2680 TEST_EQ((*a[4]) < (*a[3]), true);
2681 TEST_EQ((*a[5]) < (*a[4]), false);
2682 TEST_EQ((*a[5]) < (*a[4]), false);
2683 TEST_EQ((*a[6]) < (*a[5]), true);
2686 void FixedLengthArrayTest() {
2687 // VS10 does not support typed enums, exclude from tests
2688 #if !defined(_MSC_VER) || _MSC_VER >= 1700
2689 // Generate an ArrayTable containing one ArrayStruct.
2690 flatbuffers::FlatBufferBuilder fbb;
2691 MyGame::Example::NestedStruct nStruct0(MyGame::Example::TestEnum::B);
2692 TEST_NOTNULL(nStruct0.mutable_a());
2693 nStruct0.mutable_a()->Mutate(0, 1);
2694 nStruct0.mutable_a()->Mutate(1, 2);
2695 TEST_NOTNULL(nStruct0.mutable_c());
2696 nStruct0.mutable_c()->Mutate(0, MyGame::Example::TestEnum::C);
2697 nStruct0.mutable_c()->Mutate(1, MyGame::Example::TestEnum::A);
2698 MyGame::Example::NestedStruct nStruct1(MyGame::Example::TestEnum::C);
2699 TEST_NOTNULL(nStruct1.mutable_a());
2700 nStruct1.mutable_a()->Mutate(0, 3);
2701 nStruct1.mutable_a()->Mutate(1, 4);
2702 TEST_NOTNULL(nStruct1.mutable_c());
2703 nStruct1.mutable_c()->Mutate(0, MyGame::Example::TestEnum::C);
2704 nStruct1.mutable_c()->Mutate(1, MyGame::Example::TestEnum::A);
2705 MyGame::Example::ArrayStruct aStruct(2, 12);
2706 TEST_NOTNULL(aStruct.b());
2707 TEST_NOTNULL(aStruct.mutable_b());
2708 TEST_NOTNULL(aStruct.mutable_d());
2709 for (int i = 0; i < aStruct.b()->size(); i++)
2710 aStruct.mutable_b()->Mutate(i, i + 1);
2711 aStruct.mutable_d()->Mutate(0, nStruct0);
2712 aStruct.mutable_d()->Mutate(1, nStruct1);
2713 auto aTable = MyGame::Example::CreateArrayTable(fbb, &aStruct);
2716 // Verify correctness of the ArrayTable.
2717 flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize());
2718 MyGame::Example::VerifyArrayTableBuffer(verifier);
2719 auto p = MyGame::Example::GetMutableArrayTable(fbb.GetBufferPointer());
2720 auto mArStruct = p->mutable_a();
2721 TEST_NOTNULL(mArStruct);
2722 TEST_NOTNULL(mArStruct->b());
2723 TEST_NOTNULL(mArStruct->d());
2724 TEST_NOTNULL(mArStruct->mutable_b());
2725 TEST_NOTNULL(mArStruct->mutable_d());
2726 mArStruct->mutable_b()->Mutate(14, -14);
2727 TEST_EQ(mArStruct->a(), 2);
2728 TEST_EQ(mArStruct->b()->size(), 15);
2729 TEST_EQ(mArStruct->b()->Get(aStruct.b()->size() - 1), -14);
2730 TEST_EQ(mArStruct->c(), 12);
2731 TEST_NOTNULL(mArStruct->d()->Get(0).a());
2732 TEST_EQ(mArStruct->d()->Get(0).a()->Get(0), 1);
2733 TEST_EQ(mArStruct->d()->Get(0).a()->Get(1), 2);
2734 TEST_NOTNULL(mArStruct->d()->Get(1).a());
2735 TEST_EQ(mArStruct->d()->Get(1).a()->Get(0), 3);
2736 TEST_EQ(mArStruct->d()->Get(1).a()->Get(1), 4);
2737 TEST_NOTNULL(mArStruct->mutable_d()->GetMutablePointer(1));
2738 TEST_NOTNULL(mArStruct->mutable_d()->GetMutablePointer(1)->mutable_a());
2739 mArStruct->mutable_d()->GetMutablePointer(1)->mutable_a()->Mutate(1, 5);
2740 TEST_EQ(mArStruct->d()->Get(1).a()->Get(1), 5);
2741 TEST_EQ(mArStruct->d()->Get(0).b() == MyGame::Example::TestEnum::B, true);
2742 TEST_NOTNULL(mArStruct->d()->Get(0).c());
2743 TEST_EQ(mArStruct->d()->Get(0).c()->Get(0) == MyGame::Example::TestEnum::C,
2745 TEST_EQ(mArStruct->d()->Get(0).c()->Get(1) == MyGame::Example::TestEnum::A,
2747 TEST_EQ(mArStruct->d()->Get(1).b() == MyGame::Example::TestEnum::C, true);
2748 TEST_NOTNULL(mArStruct->d()->Get(1).c());
2749 TEST_EQ(mArStruct->d()->Get(1).c()->Get(0) == MyGame::Example::TestEnum::C,
2751 TEST_EQ(mArStruct->d()->Get(1).c()->Get(1) == MyGame::Example::TestEnum::A,
2753 for (int i = 0; i < mArStruct->b()->size() - 1; i++)
2754 TEST_EQ(mArStruct->b()->Get(i), i + 1);
2758 void FixedLengthArrayJsonTest(bool binary) {
2759 // VS10 does not support typed enums, exclude from tests
2760 #if !defined(_MSC_VER) || _MSC_VER >= 1700
2761 // load FlatBuffer schema (.fbs) and JSON from disk
2762 std::string schemafile;
2763 std::string jsonfile;
2765 flatbuffers::LoadFile(
2766 (test_data_path + "arrays_test." + (binary ? "bfbs" : "fbs")).c_str(),
2767 binary, &schemafile),
2769 TEST_EQ(flatbuffers::LoadFile((test_data_path + "arrays_test.golden").c_str(),
2773 // parse schema first, so we can use it to parse the data after
2774 flatbuffers::Parser parserOrg, parserGen;
2776 flatbuffers::Verifier verifier(
2777 reinterpret_cast<const uint8_t *>(schemafile.c_str()),
2779 TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
2780 TEST_EQ(parserOrg.Deserialize((const uint8_t *)schemafile.c_str(),
2783 TEST_EQ(parserGen.Deserialize((const uint8_t *)schemafile.c_str(),
2787 TEST_EQ(parserOrg.Parse(schemafile.c_str()), true);
2788 TEST_EQ(parserGen.Parse(schemafile.c_str()), true);
2790 TEST_EQ(parserOrg.Parse(jsonfile.c_str()), true);
2792 // First, verify it, just in case:
2793 flatbuffers::Verifier verifierOrg(parserOrg.builder_.GetBufferPointer(),
2794 parserOrg.builder_.GetSize());
2795 TEST_EQ(VerifyArrayTableBuffer(verifierOrg), true);
2798 std::string jsonGen;
2800 GenerateText(parserOrg, parserOrg.builder_.GetBufferPointer(), &jsonGen),
2804 TEST_EQ(parserGen.Parse(jsonGen.c_str()), true);
2806 // Verify buffer from generated JSON
2807 flatbuffers::Verifier verifierGen(parserGen.builder_.GetBufferPointer(),
2808 parserGen.builder_.GetSize());
2809 TEST_EQ(VerifyArrayTableBuffer(verifierGen), true);
2811 // Compare generated buffer to original
2812 TEST_EQ(parserOrg.builder_.GetSize(), parserGen.builder_.GetSize());
2813 TEST_EQ(std::memcmp(parserOrg.builder_.GetBufferPointer(),
2814 parserGen.builder_.GetBufferPointer(),
2815 parserOrg.builder_.GetSize()),
2822 int FlatBufferTests() {
2825 // Run our various test suites:
2828 auto flatbuf1 = CreateFlatBufferTest(rawbuf);
2829 #if !defined(FLATBUFFERS_CPP98_STL)
2830 auto flatbuf = std::move(flatbuf1); // Test move assignment.
2832 auto &flatbuf = flatbuf1;
2833 #endif // !defined(FLATBUFFERS_CPP98_STL)
2835 TriviallyCopyableTest();
2837 AccessFlatBufferTest(reinterpret_cast<const uint8_t *>(rawbuf.c_str()),
2839 AccessFlatBufferTest(flatbuf.data(), flatbuf.size());
2841 MutateFlatBuffersTest(flatbuf.data(), flatbuf.size());
2843 ObjectFlatBuffersTest(flatbuf.data());
2845 MiniReflectFlatBuffersTest(flatbuf.data());
2849 #ifndef FLATBUFFERS_NO_FILE_TESTS
2850 #ifdef FLATBUFFERS_TEST_PATH_PREFIX
2851 test_data_path = FLATBUFFERS_STRING(FLATBUFFERS_TEST_PATH_PREFIX) +
2854 ParseAndGenerateTextTest(false);
2855 ParseAndGenerateTextTest(true);
2856 FixedLengthArrayJsonTest(false);
2857 FixedLengthArrayJsonTest(true);
2858 ReflectionTest(flatbuf.data(), flatbuf.size());
2861 LoadVerifyBinaryTest();
2862 GenerateTableTextTest();
2874 EnumOutOfRangeTest();
2875 IntegerOutOfRangeTest();
2876 IntegerBoundaryTest();
2878 UnicodeTestAllowNonUTF8();
2879 UnicodeTestGenerateTextFailsOnNonUTF8();
2880 UnicodeSurrogatesTest();
2881 UnicodeInvalidSurrogatesTest();
2883 UnknownFieldsTest();
2885 InvalidNestedFlatbufferTest();
2887 ParseProtoBufAsciiTest();
2890 CreateSharedStringTest();
2893 UninitializedVectorTest();
2894 EqualOperatorTest();
2899 TestMonsterExtraFloats();
2900 FixedLengthArrayTest();
2904 int main(int /*argc*/, const char * /*argv*/ []) {
2907 std::string req_locale;
2908 if (flatbuffers::ReadEnvironmentVariable("FLATBUFFERS_TEST_LOCALE",
2910 TEST_OUTPUT_LINE("The environment variable FLATBUFFERS_TEST_LOCALE=%s",
2911 req_locale.c_str());
2912 req_locale = flatbuffers::RemoveStringQuotes(req_locale);
2913 std::string the_locale;
2915 flatbuffers::SetGlobalTestLocale(req_locale.c_str(), &the_locale));
2916 TEST_OUTPUT_LINE("The global C-locale changed: %s", the_locale.c_str());
2920 FlatBufferBuilderTest();
2922 if (!testing_fails) {
2923 TEST_OUTPUT_LINE("ALL TESTS PASSED");
2925 TEST_OUTPUT_LINE("%d FAILED TESTS", testing_fails);
2927 return CloseTestEngine();