Add 'fsanitize=address,undefined' to tests and flatc targets (#5009)
[platform/upstream/flatbuffers.git] / tests / test.cpp
1 /*
2  * Copyright 2014 Google Inc. All rights reserved.
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 #include <cmath>
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"
22
23 // clang-format off
24 #ifdef FLATBUFFERS_CPP98_STL
25   #include "flatbuffers/stl_emulation.h"
26   namespace std {
27     using flatbuffers::unique_ptr;
28   }
29 #endif
30 // clang-format on
31
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 "test_assert.h"
37
38 #include "flatbuffers/flexbuffers.h"
39
40 using namespace MyGame::Example;
41
42 void FlatBufferBuilderTest();
43
44 // Include simple random number generator to ensure results will be the
45 // same cross platform.
46 // http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator
47 uint32_t lcg_seed = 48271;
48 uint32_t lcg_rand() {
49   return lcg_seed = (static_cast<uint64_t>(lcg_seed) * 279470273UL) % 4294967291UL;
50 }
51 void lcg_reset() { lcg_seed = 48271; }
52
53 std::string test_data_path = "tests/";
54
55 // example of how to build up a serialized buffer algorithmically:
56 flatbuffers::DetachedBuffer CreateFlatBufferTest(std::string &buffer) {
57   flatbuffers::FlatBufferBuilder builder;
58
59   auto vec = Vec3(1, 2, 3, 0, Color_Red, Test(10, 20));
60
61   auto name = builder.CreateString("MyMonster");
62
63   unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
64   auto inventory = builder.CreateVector(inv_data, 10);
65
66   // Alternatively, create the vector first, and fill in data later:
67   // unsigned char *inv_buf = nullptr;
68   // auto inventory = builder.CreateUninitializedVector<unsigned char>(
69   //                                                              10, &inv_buf);
70   // memcpy(inv_buf, inv_data, 10);
71
72   Test tests[] = { Test(10, 20), Test(30, 40) };
73   auto testv = builder.CreateVectorOfStructs(tests, 2);
74
75   // clang-format off
76   #ifndef FLATBUFFERS_CPP98_STL
77     // Create a vector of structures from a lambda.
78     auto testv2 = builder.CreateVectorOfStructs<Test>(
79           2, [&](size_t i, Test* s) -> void {
80             *s = tests[i];
81           });
82   #else
83     // Create a vector of structures using a plain old C++ function.
84     auto testv2 = builder.CreateVectorOfStructs<Test>(
85           2, [](size_t i, Test* s, void *state) -> void {
86             *s = (reinterpret_cast<Test*>(state))[i];
87           }, tests);
88   #endif  // FLATBUFFERS_CPP98_STL
89   // clang-format on
90
91   // create monster with very few fields set:
92   // (same functionality as CreateMonster below, but sets fields manually)
93   flatbuffers::Offset<Monster> mlocs[3];
94   auto fred = builder.CreateString("Fred");
95   auto barney = builder.CreateString("Barney");
96   auto wilma = builder.CreateString("Wilma");
97   MonsterBuilder mb1(builder);
98   mb1.add_name(fred);
99   mlocs[0] = mb1.Finish();
100   MonsterBuilder mb2(builder);
101   mb2.add_name(barney);
102   mb2.add_hp(1000);
103   mlocs[1] = mb2.Finish();
104   MonsterBuilder mb3(builder);
105   mb3.add_name(wilma);
106   mlocs[2] = mb3.Finish();
107
108   // Create an array of strings. Also test string pooling, and lambdas.
109   auto vecofstrings =
110       builder.CreateVector<flatbuffers::Offset<flatbuffers::String>>(
111           4,
112           [](size_t i, flatbuffers::FlatBufferBuilder *b)
113               -> flatbuffers::Offset<flatbuffers::String> {
114             static const char *names[] = { "bob", "fred", "bob", "fred" };
115             return b->CreateSharedString(names[i]);
116           },
117           &builder);
118
119   // Creating vectors of strings in one convenient call.
120   std::vector<std::string> names2;
121   names2.push_back("jane");
122   names2.push_back("mary");
123   auto vecofstrings2 = builder.CreateVectorOfStrings(names2);
124
125   // Create an array of sorted tables, can be used with binary search when read:
126   auto vecoftables = builder.CreateVectorOfSortedTables(mlocs, 3);
127
128   // Create an array of sorted structs,
129   // can be used with binary search when read:
130   std::vector<Ability> abilities;
131   abilities.push_back(Ability(4, 40));
132   abilities.push_back(Ability(3, 30));
133   abilities.push_back(Ability(2, 20));
134   abilities.push_back(Ability(1, 10));
135   auto vecofstructs = builder.CreateVectorOfSortedStructs(&abilities);
136
137   // Create a nested FlatBuffer.
138   // Nested FlatBuffers are stored in a ubyte vector, which can be convenient
139   // since they can be memcpy'd around much easier than other FlatBuffer
140   // values. They have little overhead compared to storing the table directly.
141   // As a test, create a mostly empty Monster buffer:
142   flatbuffers::FlatBufferBuilder nested_builder;
143   auto nmloc = CreateMonster(nested_builder, nullptr, 0, 0,
144                              nested_builder.CreateString("NestedMonster"));
145   FinishMonsterBuffer(nested_builder, nmloc);
146   // Now we can store the buffer in the parent. Note that by default, vectors
147   // are only aligned to their elements or size field, so in this case if the
148   // buffer contains 64-bit elements, they may not be correctly aligned. We fix
149   // that with:
150   builder.ForceVectorAlignment(nested_builder.GetSize(), sizeof(uint8_t),
151                                nested_builder.GetBufferMinAlignment());
152   // If for whatever reason you don't have the nested_builder available, you
153   // can substitute flatbuffers::largest_scalar_t (64-bit) for the alignment, or
154   // the largest force_align value in your schema if you're using it.
155   auto nested_flatbuffer_vector = builder.CreateVector(
156       nested_builder.GetBufferPointer(), nested_builder.GetSize());
157
158   // Test a nested FlexBuffer:
159   flexbuffers::Builder flexbuild;
160   flexbuild.Int(1234);
161   flexbuild.Finish();
162   auto flex = builder.CreateVector(flexbuild.GetBuffer());
163
164   // shortcut for creating monster with all fields set:
165   auto mloc = CreateMonster(builder, &vec, 150, 80, name, inventory, Color_Blue,
166                             Any_Monster, mlocs[1].Union(),  // Store a union.
167                             testv, vecofstrings, vecoftables, 0,
168                             nested_flatbuffer_vector, 0, false, 0, 0, 0, 0, 0,
169                             0, 0, 0, 0, 3.14159f, 3.0f, 0.0f, vecofstrings2,
170                             vecofstructs, flex, testv2);
171
172   FinishMonsterBuffer(builder, mloc);
173
174   // clang-format off
175   #ifdef FLATBUFFERS_TEST_VERBOSE
176   // print byte data for debugging:
177   auto p = builder.GetBufferPointer();
178   for (flatbuffers::uoffset_t i = 0; i < builder.GetSize(); i++)
179     printf("%d ", p[i]);
180   #endif
181   // clang-format on
182
183   // return the buffer for the caller to use.
184   auto bufferpointer =
185       reinterpret_cast<const char *>(builder.GetBufferPointer());
186   buffer.assign(bufferpointer, bufferpointer + builder.GetSize());
187
188   return builder.ReleaseBufferPointer();
189 }
190
191 //  example of accessing a buffer loaded in memory:
192 void AccessFlatBufferTest(const uint8_t *flatbuf, size_t length,
193                           bool pooled = true) {
194   // First, verify the buffers integrity (optional)
195   flatbuffers::Verifier verifier(flatbuf, length);
196   TEST_EQ(VerifyMonsterBuffer(verifier), true);
197
198   std::vector<uint8_t> test_buff;
199   test_buff.resize(length * 2);
200   std::memcpy(&test_buff[0], flatbuf, length);
201   std::memcpy(&test_buff[length], flatbuf, length);
202
203   flatbuffers::Verifier verifier1(&test_buff[0], length);
204   TEST_EQ(VerifyMonsterBuffer(verifier1), true);
205   TEST_EQ(verifier1.GetComputedSize(), length);
206
207   flatbuffers::Verifier verifier2(&test_buff[length], length);
208   TEST_EQ(VerifyMonsterBuffer(verifier2), true);
209   TEST_EQ(verifier2.GetComputedSize(), length);
210
211   TEST_EQ(strcmp(MonsterIdentifier(), "MONS"), 0);
212   TEST_EQ(MonsterBufferHasIdentifier(flatbuf), true);
213   TEST_EQ(strcmp(MonsterExtension(), "mon"), 0);
214
215   // Access the buffer from the root.
216   auto monster = GetMonster(flatbuf);
217
218   TEST_EQ(monster->hp(), 80);
219   TEST_EQ(monster->mana(), 150);  // default
220   TEST_EQ_STR(monster->name()->c_str(), "MyMonster");
221   // Can't access the following field, it is deprecated in the schema,
222   // which means accessors are not generated:
223   // monster.friendly()
224
225   auto pos = monster->pos();
226   TEST_NOTNULL(pos);
227   TEST_EQ(pos->z(), 3);
228   TEST_EQ(pos->test3().a(), 10);
229   TEST_EQ(pos->test3().b(), 20);
230
231   auto inventory = monster->inventory();
232   TEST_EQ(VectorLength(inventory), 10UL);  // Works even if inventory is null.
233   TEST_NOTNULL(inventory);
234   unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
235   // Check compatibilty of iterators with STL.
236   std::vector<unsigned char> inv_vec(inventory->begin(), inventory->end());
237   for (auto it = inventory->begin(); it != inventory->end(); ++it) {
238     auto indx = it - inventory->begin();
239     TEST_EQ(*it, inv_vec.at(indx));  // Use bounds-check.
240     TEST_EQ(*it, inv_data[indx]);
241   }
242
243   TEST_EQ(monster->color(), Color_Blue);
244
245   // Example of accessing a union:
246   TEST_EQ(monster->test_type(), Any_Monster);  // First make sure which it is.
247   auto monster2 = reinterpret_cast<const Monster *>(monster->test());
248   TEST_NOTNULL(monster2);
249   TEST_EQ_STR(monster2->name()->c_str(), "Fred");
250
251   // Example of accessing a vector of strings:
252   auto vecofstrings = monster->testarrayofstring();
253   TEST_EQ(vecofstrings->Length(), 4U);
254   TEST_EQ_STR(vecofstrings->Get(0)->c_str(), "bob");
255   TEST_EQ_STR(vecofstrings->Get(1)->c_str(), "fred");
256   if (pooled) {
257     // These should have pointer equality because of string pooling.
258     TEST_EQ(vecofstrings->Get(0)->c_str(), vecofstrings->Get(2)->c_str());
259     TEST_EQ(vecofstrings->Get(1)->c_str(), vecofstrings->Get(3)->c_str());
260   }
261
262   auto vecofstrings2 = monster->testarrayofstring2();
263   if (vecofstrings2) {
264     TEST_EQ(vecofstrings2->Length(), 2U);
265     TEST_EQ_STR(vecofstrings2->Get(0)->c_str(), "jane");
266     TEST_EQ_STR(vecofstrings2->Get(1)->c_str(), "mary");
267   }
268
269   // Example of accessing a vector of tables:
270   auto vecoftables = monster->testarrayoftables();
271   TEST_EQ(vecoftables->Length(), 3U);
272   for (auto it = vecoftables->begin(); it != vecoftables->end(); ++it)
273     TEST_EQ(strlen(it->name()->c_str()) >= 4, true);
274   TEST_EQ_STR(vecoftables->Get(0)->name()->c_str(), "Barney");
275   TEST_EQ(vecoftables->Get(0)->hp(), 1000);
276   TEST_EQ_STR(vecoftables->Get(1)->name()->c_str(), "Fred");
277   TEST_EQ_STR(vecoftables->Get(2)->name()->c_str(), "Wilma");
278   TEST_NOTNULL(vecoftables->LookupByKey("Barney"));
279   TEST_NOTNULL(vecoftables->LookupByKey("Fred"));
280   TEST_NOTNULL(vecoftables->LookupByKey("Wilma"));
281
282   // Test accessing a vector of sorted structs
283   auto vecofstructs = monster->testarrayofsortedstruct();
284   if (vecofstructs) {  // not filled in monster_test.bfbs
285     for (flatbuffers::uoffset_t i = 0; i < vecofstructs->size() - 1; i++) {
286       auto left = vecofstructs->Get(i);
287       auto right = vecofstructs->Get(i + 1);
288       TEST_EQ(true, (left->KeyCompareLessThan(right)));
289     }
290     TEST_NOTNULL(vecofstructs->LookupByKey(3));
291     TEST_EQ(static_cast<const Ability *>(nullptr),
292             vecofstructs->LookupByKey(5));
293   }
294
295   // Test nested FlatBuffers if available:
296   auto nested_buffer = monster->testnestedflatbuffer();
297   if (nested_buffer) {
298     // nested_buffer is a vector of bytes you can memcpy. However, if you
299     // actually want to access the nested data, this is a convenient
300     // accessor that directly gives you the root table:
301     auto nested_monster = monster->testnestedflatbuffer_nested_root();
302     TEST_EQ_STR(nested_monster->name()->c_str(), "NestedMonster");
303   }
304
305   // Test flexbuffer if available:
306   auto flex = monster->flex();
307   // flex is a vector of bytes you can memcpy etc.
308   TEST_EQ(flex->size(), 4);  // Encoded FlexBuffer bytes.
309   // However, if you actually want to access the nested data, this is a
310   // convenient accessor that directly gives you the root value:
311   TEST_EQ(monster->flex_flexbuffer_root().AsInt16(), 1234);
312
313   // Since Flatbuffers uses explicit mechanisms to override the default
314   // compiler alignment, double check that the compiler indeed obeys them:
315   // (Test consists of a short and byte):
316   TEST_EQ(flatbuffers::AlignOf<Test>(), 2UL);
317   TEST_EQ(sizeof(Test), 4UL);
318
319   const flatbuffers::Vector<const Test *> *tests_array[] = {
320     monster->test4(),
321     monster->test5(),
322   };
323   for (size_t i = 0; i < sizeof(tests_array) / sizeof(tests_array[0]); ++i) {
324     auto tests = tests_array[i];
325     TEST_NOTNULL(tests);
326     auto test_0 = tests->Get(0);
327     auto test_1 = tests->Get(1);
328     TEST_EQ(test_0->a(), 10);
329     TEST_EQ(test_0->b(), 20);
330     TEST_EQ(test_1->a(), 30);
331     TEST_EQ(test_1->b(), 40);
332     for (auto it = tests->begin(); it != tests->end(); ++it) {
333       TEST_EQ(it->a() == 10 || it->a() == 30, true);  // Just testing iterators.
334     }
335   }
336
337   // Checking for presence of fields:
338   TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_HP), true);
339   TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_MANA), false);
340
341   // Obtaining a buffer from a root:
342   TEST_EQ(GetBufferStartFromRootPointer(monster), flatbuf);
343 }
344
345 // Change a FlatBuffer in-place, after it has been constructed.
346 void MutateFlatBuffersTest(uint8_t *flatbuf, std::size_t length) {
347   // Get non-const pointer to root.
348   auto monster = GetMutableMonster(flatbuf);
349
350   // Each of these tests mutates, then tests, then set back to the original,
351   // so we can test that the buffer in the end still passes our original test.
352   auto hp_ok = monster->mutate_hp(10);
353   TEST_EQ(hp_ok, true);  // Field was present.
354   TEST_EQ(monster->hp(), 10);
355   // Mutate to default value
356   auto hp_ok_default = monster->mutate_hp(100);
357   TEST_EQ(hp_ok_default, true);  // Field was present.
358   TEST_EQ(monster->hp(), 100);
359   // Test that mutate to default above keeps field valid for further mutations
360   auto hp_ok_2 = monster->mutate_hp(20);
361   TEST_EQ(hp_ok_2, true);
362   TEST_EQ(monster->hp(), 20);
363   monster->mutate_hp(80);
364
365   // Monster originally at 150 mana (default value)
366   auto mana_default_ok = monster->mutate_mana(150);  // Mutate to default value.
367   TEST_EQ(mana_default_ok,
368           true);  // Mutation should succeed, because default value.
369   TEST_EQ(monster->mana(), 150);
370   auto mana_ok = monster->mutate_mana(10);
371   TEST_EQ(mana_ok, false);  // Field was NOT present, because default value.
372   TEST_EQ(monster->mana(), 150);
373
374   // Mutate structs.
375   auto pos = monster->mutable_pos();
376   auto test3 = pos->mutable_test3();  // Struct inside a struct.
377   test3.mutate_a(50);                 // Struct fields never fail.
378   TEST_EQ(test3.a(), 50);
379   test3.mutate_a(10);
380
381   // Mutate vectors.
382   auto inventory = monster->mutable_inventory();
383   inventory->Mutate(9, 100);
384   TEST_EQ(inventory->Get(9), 100);
385   inventory->Mutate(9, 9);
386
387   auto tables = monster->mutable_testarrayoftables();
388   auto first = tables->GetMutableObject(0);
389   TEST_EQ(first->hp(), 1000);
390   first->mutate_hp(0);
391   TEST_EQ(first->hp(), 0);
392   first->mutate_hp(1000);
393
394   // Run the verifier and the regular test to make sure we didn't trample on
395   // anything.
396   AccessFlatBufferTest(flatbuf, length);
397 }
398
399 // Unpack a FlatBuffer into objects.
400 void ObjectFlatBuffersTest(uint8_t *flatbuf) {
401   // Optional: we can specify resolver and rehasher functions to turn hashed
402   // strings into object pointers and back, to implement remote references
403   // and such.
404   auto resolver = flatbuffers::resolver_function_t(
405       [](void **pointer_adr, flatbuffers::hash_value_t hash) {
406         (void)pointer_adr;
407         (void)hash;
408         // Don't actually do anything, leave variable null.
409       });
410   auto rehasher = flatbuffers::rehasher_function_t(
411       [](void *pointer) -> flatbuffers::hash_value_t {
412         (void)pointer;
413         return 0;
414       });
415
416   // Turn a buffer into C++ objects.
417   auto monster1 = UnPackMonster(flatbuf, &resolver);
418
419   // Re-serialize the data.
420   flatbuffers::FlatBufferBuilder fbb1;
421   fbb1.Finish(CreateMonster(fbb1, monster1.get(), &rehasher),
422               MonsterIdentifier());
423
424   // Unpack again, and re-serialize again.
425   auto monster2 = UnPackMonster(fbb1.GetBufferPointer(), &resolver);
426   flatbuffers::FlatBufferBuilder fbb2;
427   fbb2.Finish(CreateMonster(fbb2, monster2.get(), &rehasher),
428               MonsterIdentifier());
429
430   // Now we've gone full round-trip, the two buffers should match.
431   auto len1 = fbb1.GetSize();
432   auto len2 = fbb2.GetSize();
433   TEST_EQ(len1, len2);
434   TEST_EQ(memcmp(fbb1.GetBufferPointer(), fbb2.GetBufferPointer(), len1), 0);
435
436   // Test it with the original buffer test to make sure all data survived.
437   AccessFlatBufferTest(fbb2.GetBufferPointer(), len2, false);
438
439   // Test accessing fields, similar to AccessFlatBufferTest above.
440   TEST_EQ(monster2->hp, 80);
441   TEST_EQ(monster2->mana, 150);  // default
442   TEST_EQ_STR(monster2->name.c_str(), "MyMonster");
443
444   auto &pos = monster2->pos;
445   TEST_NOTNULL(pos);
446   TEST_EQ(pos->z(), 3);
447   TEST_EQ(pos->test3().a(), 10);
448   TEST_EQ(pos->test3().b(), 20);
449
450   auto &inventory = monster2->inventory;
451   TEST_EQ(inventory.size(), 10UL);
452   unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
453   for (auto it = inventory.begin(); it != inventory.end(); ++it)
454     TEST_EQ(*it, inv_data[it - inventory.begin()]);
455
456   TEST_EQ(monster2->color, Color_Blue);
457
458   auto monster3 = monster2->test.AsMonster();
459   TEST_NOTNULL(monster3);
460   TEST_EQ_STR(monster3->name.c_str(), "Fred");
461
462   auto &vecofstrings = monster2->testarrayofstring;
463   TEST_EQ(vecofstrings.size(), 4U);
464   TEST_EQ_STR(vecofstrings[0].c_str(), "bob");
465   TEST_EQ_STR(vecofstrings[1].c_str(), "fred");
466
467   auto &vecofstrings2 = monster2->testarrayofstring2;
468   TEST_EQ(vecofstrings2.size(), 2U);
469   TEST_EQ_STR(vecofstrings2[0].c_str(), "jane");
470   TEST_EQ_STR(vecofstrings2[1].c_str(), "mary");
471
472   auto &vecoftables = monster2->testarrayoftables;
473   TEST_EQ(vecoftables.size(), 3U);
474   TEST_EQ_STR(vecoftables[0]->name.c_str(), "Barney");
475   TEST_EQ(vecoftables[0]->hp, 1000);
476   TEST_EQ_STR(vecoftables[1]->name.c_str(), "Fred");
477   TEST_EQ_STR(vecoftables[2]->name.c_str(), "Wilma");
478
479   auto &tests = monster2->test4;
480   TEST_EQ(tests[0].a(), 10);
481   TEST_EQ(tests[0].b(), 20);
482   TEST_EQ(tests[1].a(), 30);
483   TEST_EQ(tests[1].b(), 40);
484 }
485
486 // Prefix a FlatBuffer with a size field.
487 void SizePrefixedTest() {
488   // Create size prefixed buffer.
489   flatbuffers::FlatBufferBuilder fbb;
490   FinishSizePrefixedMonsterBuffer(
491       fbb,
492       CreateMonster(fbb, 0, 200, 300, fbb.CreateString("bob")));
493
494   // Verify it.
495   flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize());
496   TEST_EQ(VerifySizePrefixedMonsterBuffer(verifier), true);
497
498   // Access it.
499   auto m = GetSizePrefixedMonster(fbb.GetBufferPointer());
500   TEST_EQ(m->mana(), 200);
501   TEST_EQ(m->hp(), 300);
502   TEST_EQ_STR(m->name()->c_str(), "bob");
503 }
504
505 void TriviallyCopyableTest() {
506   // clang-format off
507   #if __GNUG__ && __GNUC__ < 5
508     TEST_EQ(__has_trivial_copy(Vec3), true);
509   #else
510     #if __cplusplus >= 201103L
511       TEST_EQ(std::is_trivially_copyable<Vec3>::value, true);
512     #endif
513   #endif
514   // clang-format on
515 }
516
517 // Check stringify of an default enum value to json
518 void JsonDefaultTest() {
519   // load FlatBuffer schema (.fbs) from disk
520   std::string schemafile;
521   TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
522                                 false, &schemafile), true);
523   // parse schema first, so we can use it to parse the data after
524   flatbuffers::Parser parser;
525   auto include_test_path =
526       flatbuffers::ConCatPathFileName(test_data_path, "include_test");
527   const char *include_directories[] = { test_data_path.c_str(),
528                                         include_test_path.c_str(), nullptr };
529
530   TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
531   // create incomplete monster and store to json
532   parser.opts.output_default_scalars_in_json = true;
533   parser.opts.output_enum_identifiers = true;
534   flatbuffers::FlatBufferBuilder builder;
535   auto name = builder.CreateString("default_enum");
536   MonsterBuilder color_monster(builder);
537   color_monster.add_name(name);
538   FinishMonsterBuffer(builder, color_monster.Finish());
539   std::string jsongen;
540   auto result = GenerateText(parser, builder.GetBufferPointer(), &jsongen);
541   TEST_EQ(result, true);
542   // default value of the "color" field is Blue
543   TEST_EQ(std::string::npos != jsongen.find("color: \"Blue\""), true);
544   // default value of the "testf" field is 3.14159
545   TEST_EQ(std::string::npos != jsongen.find("testf: 3.14159"), true);
546 }
547
548 // example of parsing text straight into a buffer, and generating
549 // text back from it:
550 void ParseAndGenerateTextTest() {
551   // load FlatBuffer schema (.fbs) and JSON from disk
552   std::string schemafile;
553   std::string jsonfile;
554   TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.fbs").c_str(),
555                                 false, &schemafile),
556           true);
557   TEST_EQ(flatbuffers::LoadFile(
558               (test_data_path + "monsterdata_test.golden").c_str(), false,
559               &jsonfile),
560           true);
561
562   // parse schema first, so we can use it to parse the data after
563   flatbuffers::Parser parser;
564   auto include_test_path =
565       flatbuffers::ConCatPathFileName(test_data_path, "include_test");
566   const char *include_directories[] = { test_data_path.c_str(),
567                                         include_test_path.c_str(), nullptr };
568   TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
569   TEST_EQ(parser.Parse(jsonfile.c_str(), include_directories), true);
570
571   // here, parser.builder_ contains a binary buffer that is the parsed data.
572
573   // First, verify it, just in case:
574   flatbuffers::Verifier verifier(parser.builder_.GetBufferPointer(),
575                                  parser.builder_.GetSize());
576   TEST_EQ(VerifyMonsterBuffer(verifier), true);
577
578   AccessFlatBufferTest(parser.builder_.GetBufferPointer(),
579                        parser.builder_.GetSize(), false);
580
581   // to ensure it is correct, we now generate text back from the binary,
582   // and compare the two:
583   std::string jsongen;
584   auto result =
585       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
586   TEST_EQ(result, true);
587   TEST_EQ_STR(jsongen.c_str(), jsonfile.c_str());
588
589   // We can also do the above using the convenient Registry that knows about
590   // a set of file_identifiers mapped to schemas.
591   flatbuffers::Registry registry;
592   // Make sure schemas can find their includes.
593   registry.AddIncludeDirectory(test_data_path.c_str());
594   registry.AddIncludeDirectory(include_test_path.c_str());
595   // Call this with many schemas if possible.
596   registry.Register(MonsterIdentifier(),
597                     (test_data_path + "monster_test.fbs").c_str());
598   // Now we got this set up, we can parse by just specifying the identifier,
599   // the correct schema will be loaded on the fly:
600   auto buf = registry.TextToFlatBuffer(jsonfile.c_str(), MonsterIdentifier());
601   // If this fails, check registry.lasterror_.
602   TEST_NOTNULL(buf.data());
603   // Test the buffer, to be sure:
604   AccessFlatBufferTest(buf.data(), buf.size(), false);
605   // We can use the registry to turn this back into text, in this case it
606   // will get the file_identifier from the binary:
607   std::string text;
608   auto ok = registry.FlatBufferToText(buf.data(), buf.size(), &text);
609   // If this fails, check registry.lasterror_.
610   TEST_EQ(ok, true);
611   TEST_EQ_STR(text.c_str(), jsonfile.c_str());
612
613   // Generate text for UTF-8 strings without escapes.
614   std::string jsonfile_utf8;
615   TEST_EQ(flatbuffers::LoadFile((test_data_path + "unicode_test.json").c_str(),
616                                 false, &jsonfile_utf8),
617           true);
618   TEST_EQ(parser.Parse(jsonfile_utf8.c_str(), include_directories), true);
619   // To ensure it is correct, generate utf-8 text back from the binary.
620   std::string jsongen_utf8;
621   // request natural printing for utf-8 strings
622   parser.opts.natural_utf8 = true;
623   parser.opts.strict_json = true;
624   TEST_EQ(
625       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen_utf8),
626       true);
627   TEST_EQ_STR(jsongen_utf8.c_str(), jsonfile_utf8.c_str());
628 }
629
630 void ReflectionTest(uint8_t *flatbuf, size_t length) {
631   // Load a binary schema.
632   std::string bfbsfile;
633   TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.bfbs").c_str(),
634                                 true, &bfbsfile),
635           true);
636
637   // Verify it, just in case:
638   flatbuffers::Verifier verifier(
639       reinterpret_cast<const uint8_t *>(bfbsfile.c_str()), bfbsfile.length());
640   TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
641
642   // Make sure the schema is what we expect it to be.
643   auto &schema = *reflection::GetSchema(bfbsfile.c_str());
644   auto root_table = schema.root_table();
645   TEST_EQ_STR(root_table->name()->c_str(), "MyGame.Example.Monster");
646   auto fields = root_table->fields();
647   auto hp_field_ptr = fields->LookupByKey("hp");
648   TEST_NOTNULL(hp_field_ptr);
649   auto &hp_field = *hp_field_ptr;
650   TEST_EQ_STR(hp_field.name()->c_str(), "hp");
651   TEST_EQ(hp_field.id(), 2);
652   TEST_EQ(hp_field.type()->base_type(), reflection::Short);
653   auto friendly_field_ptr = fields->LookupByKey("friendly");
654   TEST_NOTNULL(friendly_field_ptr);
655   TEST_NOTNULL(friendly_field_ptr->attributes());
656   TEST_NOTNULL(friendly_field_ptr->attributes()->LookupByKey("priority"));
657
658   // Make sure the table index is what we expect it to be.
659   auto pos_field_ptr = fields->LookupByKey("pos");
660   TEST_NOTNULL(pos_field_ptr);
661   TEST_EQ(pos_field_ptr->type()->base_type(), reflection::Obj);
662   auto pos_table_ptr = schema.objects()->Get(pos_field_ptr->type()->index());
663   TEST_NOTNULL(pos_table_ptr);
664   TEST_EQ_STR(pos_table_ptr->name()->c_str(), "MyGame.Example.Vec3");
665
666   // Now use it to dynamically access a buffer.
667   auto &root = *flatbuffers::GetAnyRoot(flatbuf);
668
669   // Verify the buffer first using reflection based verification
670   TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), flatbuf, length),
671           true);
672
673   auto hp = flatbuffers::GetFieldI<uint16_t>(root, hp_field);
674   TEST_EQ(hp, 80);
675
676   // Rather than needing to know the type, we can also get the value of
677   // any field as an int64_t/double/string, regardless of what it actually is.
678   auto hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
679   TEST_EQ(hp_int64, 80);
680   auto hp_double = flatbuffers::GetAnyFieldF(root, hp_field);
681   TEST_EQ(hp_double, 80.0);
682   auto hp_string = flatbuffers::GetAnyFieldS(root, hp_field, &schema);
683   TEST_EQ_STR(hp_string.c_str(), "80");
684
685   // Get struct field through reflection
686   auto pos_struct = flatbuffers::GetFieldStruct(root, *pos_field_ptr);
687   TEST_NOTNULL(pos_struct);
688   TEST_EQ(flatbuffers::GetAnyFieldF(*pos_struct,
689                                     *pos_table_ptr->fields()->LookupByKey("z")),
690           3.0f);
691
692   auto test3_field = pos_table_ptr->fields()->LookupByKey("test3");
693   auto test3_struct = flatbuffers::GetFieldStruct(*pos_struct, *test3_field);
694   TEST_NOTNULL(test3_struct);
695   auto test3_object = schema.objects()->Get(test3_field->type()->index());
696
697   TEST_EQ(flatbuffers::GetAnyFieldF(*test3_struct,
698                                     *test3_object->fields()->LookupByKey("a")),
699           10);
700
701   // We can also modify it.
702   flatbuffers::SetField<uint16_t>(&root, hp_field, 200);
703   hp = flatbuffers::GetFieldI<uint16_t>(root, hp_field);
704   TEST_EQ(hp, 200);
705
706   // We can also set fields generically:
707   flatbuffers::SetAnyFieldI(&root, hp_field, 300);
708   hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
709   TEST_EQ(hp_int64, 300);
710   flatbuffers::SetAnyFieldF(&root, hp_field, 300.5);
711   hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
712   TEST_EQ(hp_int64, 300);
713   flatbuffers::SetAnyFieldS(&root, hp_field, "300");
714   hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field);
715   TEST_EQ(hp_int64, 300);
716
717   // Test buffer is valid after the modifications
718   TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), flatbuf, length),
719           true);
720
721   // Reset it, for further tests.
722   flatbuffers::SetField<uint16_t>(&root, hp_field, 80);
723
724   // More advanced functionality: changing the size of items in-line!
725   // First we put the FlatBuffer inside an std::vector.
726   std::vector<uint8_t> resizingbuf(flatbuf, flatbuf + length);
727   // Find the field we want to modify.
728   auto &name_field = *fields->LookupByKey("name");
729   // Get the root.
730   // This time we wrap the result from GetAnyRoot in a smartpointer that
731   // will keep rroot valid as resizingbuf resizes.
732   auto rroot = flatbuffers::piv(
733       flatbuffers::GetAnyRoot(flatbuffers::vector_data(resizingbuf)),
734       resizingbuf);
735   SetString(schema, "totally new string", GetFieldS(**rroot, name_field),
736             &resizingbuf);
737   // Here resizingbuf has changed, but rroot is still valid.
738   TEST_EQ_STR(GetFieldS(**rroot, name_field)->c_str(), "totally new string");
739   // Now lets extend a vector by 100 elements (10 -> 110).
740   auto &inventory_field = *fields->LookupByKey("inventory");
741   auto rinventory = flatbuffers::piv(
742       flatbuffers::GetFieldV<uint8_t>(**rroot, inventory_field), resizingbuf);
743   flatbuffers::ResizeVector<uint8_t>(schema, 110, 50, *rinventory,
744                                      &resizingbuf);
745   // rinventory still valid, so lets read from it.
746   TEST_EQ(rinventory->Get(10), 50);
747
748   // For reflection uses not covered already, there is a more powerful way:
749   // we can simply generate whatever object we want to add/modify in a
750   // FlatBuffer of its own, then add that to an existing FlatBuffer:
751   // As an example, let's add a string to an array of strings.
752   // First, find our field:
753   auto &testarrayofstring_field = *fields->LookupByKey("testarrayofstring");
754   // Find the vector value:
755   auto rtestarrayofstring = flatbuffers::piv(
756       flatbuffers::GetFieldV<flatbuffers::Offset<flatbuffers::String>>(
757           **rroot, testarrayofstring_field),
758       resizingbuf);
759   // It's a vector of 2 strings, to which we add one more, initialized to
760   // offset 0.
761   flatbuffers::ResizeVector<flatbuffers::Offset<flatbuffers::String>>(
762       schema, 3, 0, *rtestarrayofstring, &resizingbuf);
763   // Here we just create a buffer that contans a single string, but this
764   // could also be any complex set of tables and other values.
765   flatbuffers::FlatBufferBuilder stringfbb;
766   stringfbb.Finish(stringfbb.CreateString("hank"));
767   // Add the contents of it to our existing FlatBuffer.
768   // We do this last, so the pointer doesn't get invalidated (since it is
769   // at the end of the buffer):
770   auto string_ptr = flatbuffers::AddFlatBuffer(
771       resizingbuf, stringfbb.GetBufferPointer(), stringfbb.GetSize());
772   // Finally, set the new value in the vector.
773   rtestarrayofstring->MutateOffset(2, string_ptr);
774   TEST_EQ_STR(rtestarrayofstring->Get(0)->c_str(), "bob");
775   TEST_EQ_STR(rtestarrayofstring->Get(2)->c_str(), "hank");
776   // Test integrity of all resize operations above.
777   flatbuffers::Verifier resize_verifier(
778       reinterpret_cast<const uint8_t *>(flatbuffers::vector_data(resizingbuf)),
779       resizingbuf.size());
780   TEST_EQ(VerifyMonsterBuffer(resize_verifier), true);
781
782   // Test buffer is valid using reflection as well
783   TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(),
784                               flatbuffers::vector_data(resizingbuf),
785                               resizingbuf.size()),
786           true);
787
788   // As an additional test, also set it on the name field.
789   // Note: unlike the name change above, this just overwrites the offset,
790   // rather than changing the string in-place.
791   SetFieldT(*rroot, name_field, string_ptr);
792   TEST_EQ_STR(GetFieldS(**rroot, name_field)->c_str(), "hank");
793
794   // Using reflection, rather than mutating binary FlatBuffers, we can also copy
795   // tables and other things out of other FlatBuffers into a FlatBufferBuilder,
796   // either part or whole.
797   flatbuffers::FlatBufferBuilder fbb;
798   auto root_offset = flatbuffers::CopyTable(
799       fbb, schema, *root_table, *flatbuffers::GetAnyRoot(flatbuf), true);
800   fbb.Finish(root_offset, MonsterIdentifier());
801   // Test that it was copied correctly:
802   AccessFlatBufferTest(fbb.GetBufferPointer(), fbb.GetSize());
803
804   // Test buffer is valid using reflection as well
805   TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(),
806                               fbb.GetBufferPointer(), fbb.GetSize()),
807           true);
808 }
809
810 void MiniReflectFlatBuffersTest(uint8_t *flatbuf) {
811   auto s = flatbuffers::FlatBufferToString(flatbuf, Monster::MiniReflectTypeTable());
812   TEST_EQ_STR(
813       s.c_str(),
814       "{ "
815       "pos: { x: 1.0, y: 2.0, z: 3.0, test1: 0.0, test2: Red, test3: "
816       "{ a: 10, b: 20 } }, "
817       "hp: 80, "
818       "name: \"MyMonster\", "
819       "inventory: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], "
820       "test_type: Monster, "
821       "test: { name: \"Fred\" }, "
822       "test4: [ { a: 10, b: 20 }, { a: 30, b: 40 } ], "
823       "testarrayofstring: [ \"bob\", \"fred\", \"bob\", \"fred\" ], "
824       "testarrayoftables: [ { hp: 1000, name: \"Barney\" }, { name: \"Fred\" "
825       "}, "
826       "{ name: \"Wilma\" } ], "
827       // TODO(wvo): should really print this nested buffer correctly.
828       "testnestedflatbuffer: [ 20, 0, 0, 0, 77, 79, 78, 83, 12, 0, 12, 0, 0, "
829       "0, "
830       "4, 0, 6, 0, 8, 0, 12, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 13, 0, 0, 0, 78, "
831       "101, 115, 116, 101, 100, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0 ], "
832       "testarrayofstring2: [ \"jane\", \"mary\" ], "
833       "testarrayofsortedstruct: [ { id: 1, distance: 10 }, "
834       "{ id: 2, distance: 20 }, { id: 3, distance: 30 }, "
835       "{ id: 4, distance: 40 } ], "
836       "flex: [ 210, 4, 5, 2 ], "
837       "test5: [ { a: 10, b: 20 }, { a: 30, b: 40 } ] "
838       "}");
839 }
840
841 // Parse a .proto schema, output as .fbs
842 void ParseProtoTest() {
843   // load the .proto and the golden file from disk
844   std::string protofile;
845   std::string goldenfile;
846   std::string goldenunionfile;
847   TEST_EQ(
848       flatbuffers::LoadFile((test_data_path + "prototest/test.proto").c_str(),
849                             false, &protofile),
850       true);
851   TEST_EQ(
852       flatbuffers::LoadFile((test_data_path + "prototest/test.golden").c_str(),
853                             false, &goldenfile),
854       true);
855   TEST_EQ(
856       flatbuffers::LoadFile((test_data_path +
857                             "prototest/test_union.golden").c_str(),
858                             false, &goldenunionfile),
859       true);
860
861   flatbuffers::IDLOptions opts;
862   opts.include_dependence_headers = false;
863   opts.proto_mode = true;
864
865   // Parse proto.
866   flatbuffers::Parser parser(opts);
867   auto protopath = test_data_path + "prototest/";
868   const char *include_directories[] = { protopath.c_str(), nullptr };
869   TEST_EQ(parser.Parse(protofile.c_str(), include_directories), true);
870
871   // Generate fbs.
872   auto fbs = flatbuffers::GenerateFBS(parser, "test");
873
874   // Ensure generated file is parsable.
875   flatbuffers::Parser parser2;
876   TEST_EQ(parser2.Parse(fbs.c_str(), nullptr), true);
877   TEST_EQ_STR(fbs.c_str(), goldenfile.c_str());
878
879   // Parse proto with --oneof-union option.
880   opts.proto_oneof_union = true;
881   flatbuffers::Parser parser3(opts);
882   TEST_EQ(parser3.Parse(protofile.c_str(), include_directories), true);
883
884   // Generate fbs.
885   auto fbs_union = flatbuffers::GenerateFBS(parser3, "test");
886
887   // Ensure generated file is parsable.
888   flatbuffers::Parser parser4;
889   TEST_EQ(parser4.Parse(fbs_union.c_str(), nullptr), true);
890   TEST_EQ_STR(fbs_union.c_str(), goldenunionfile.c_str());
891 }
892
893 template<typename T>
894 void CompareTableFieldValue(flatbuffers::Table *table,
895                             flatbuffers::voffset_t voffset, T val) {
896   T read = table->GetField(voffset, static_cast<T>(0));
897   TEST_EQ(read, val);
898 }
899
900 // Low level stress/fuzz test: serialize/deserialize a variety of
901 // different kinds of data in different combinations
902 void FuzzTest1() {
903   // Values we're testing against: chosen to ensure no bits get chopped
904   // off anywhere, and also be different from eachother.
905   const uint8_t bool_val = true;
906   const int8_t char_val = -127;  // 0x81
907   const uint8_t uchar_val = 0xFF;
908   const int16_t short_val = -32222;  // 0x8222;
909   const uint16_t ushort_val = 0xFEEE;
910   const int32_t int_val = 0x83333333;
911   const uint32_t uint_val = 0xFDDDDDDD;
912   const int64_t long_val = 0x8444444444444444LL;
913   const uint64_t ulong_val = 0xFCCCCCCCCCCCCCCCULL;
914   const float float_val = 3.14159f;
915   const double double_val = 3.14159265359;
916
917   const int test_values_max = 11;
918   const flatbuffers::voffset_t fields_per_object = 4;
919   const int num_fuzz_objects = 10000;  // The higher, the more thorough :)
920
921   flatbuffers::FlatBufferBuilder builder;
922
923   lcg_reset();  // Keep it deterministic.
924
925   flatbuffers::uoffset_t objects[num_fuzz_objects];
926
927   // Generate num_fuzz_objects random objects each consisting of
928   // fields_per_object fields, each of a random type.
929   for (int i = 0; i < num_fuzz_objects; i++) {
930     auto start = builder.StartTable();
931     for (flatbuffers::voffset_t f = 0; f < fields_per_object; f++) {
932       int choice = lcg_rand() % test_values_max;
933       auto off = flatbuffers::FieldIndexToOffset(f);
934       switch (choice) {
935         case 0: builder.AddElement<uint8_t>(off, bool_val, 0); break;
936         case 1: builder.AddElement<int8_t>(off, char_val, 0); break;
937         case 2: builder.AddElement<uint8_t>(off, uchar_val, 0); break;
938         case 3: builder.AddElement<int16_t>(off, short_val, 0); break;
939         case 4: builder.AddElement<uint16_t>(off, ushort_val, 0); break;
940         case 5: builder.AddElement<int32_t>(off, int_val, 0); break;
941         case 6: builder.AddElement<uint32_t>(off, uint_val, 0); break;
942         case 7: builder.AddElement<int64_t>(off, long_val, 0); break;
943         case 8: builder.AddElement<uint64_t>(off, ulong_val, 0); break;
944         case 9: builder.AddElement<float>(off, float_val, 0); break;
945         case 10: builder.AddElement<double>(off, double_val, 0); break;
946       }
947     }
948     objects[i] = builder.EndTable(start);
949   }
950   builder.PreAlign<flatbuffers::largest_scalar_t>(0);  // Align whole buffer.
951
952   lcg_reset();  // Reset.
953
954   uint8_t *eob = builder.GetCurrentBufferPointer() + builder.GetSize();
955
956   // Test that all objects we generated are readable and return the
957   // expected values. We generate random objects in the same order
958   // so this is deterministic.
959   for (int i = 0; i < num_fuzz_objects; i++) {
960     auto table = reinterpret_cast<flatbuffers::Table *>(eob - objects[i]);
961     for (flatbuffers::voffset_t f = 0; f < fields_per_object; f++) {
962       int choice = lcg_rand() % test_values_max;
963       flatbuffers::voffset_t off = flatbuffers::FieldIndexToOffset(f);
964       switch (choice) {
965         case 0: CompareTableFieldValue(table, off, bool_val); break;
966         case 1: CompareTableFieldValue(table, off, char_val); break;
967         case 2: CompareTableFieldValue(table, off, uchar_val); break;
968         case 3: CompareTableFieldValue(table, off, short_val); break;
969         case 4: CompareTableFieldValue(table, off, ushort_val); break;
970         case 5: CompareTableFieldValue(table, off, int_val); break;
971         case 6: CompareTableFieldValue(table, off, uint_val); break;
972         case 7: CompareTableFieldValue(table, off, long_val); break;
973         case 8: CompareTableFieldValue(table, off, ulong_val); break;
974         case 9: CompareTableFieldValue(table, off, float_val); break;
975         case 10: CompareTableFieldValue(table, off, double_val); break;
976       }
977     }
978   }
979 }
980
981 // High level stress/fuzz test: generate a big schema and
982 // matching json data in random combinations, then parse both,
983 // generate json back from the binary, and compare with the original.
984 void FuzzTest2() {
985   lcg_reset();  // Keep it deterministic.
986
987   const int num_definitions = 30;
988   const int num_struct_definitions = 5;  // Subset of num_definitions.
989   const int fields_per_definition = 15;
990   const int instances_per_definition = 5;
991   const int deprecation_rate = 10;  // 1 in deprecation_rate fields will
992                                     // be deprecated.
993
994   std::string schema = "namespace test;\n\n";
995
996   struct RndDef {
997     std::string instances[instances_per_definition];
998
999     // Since we're generating schema and corresponding data in tandem,
1000     // this convenience function adds strings to both at once.
1001     static void Add(RndDef (&definitions_l)[num_definitions],
1002                     std::string &schema_l, const int instances_per_definition_l,
1003                     const char *schema_add, const char *instance_add,
1004                     int definition) {
1005       schema_l += schema_add;
1006       for (int i = 0; i < instances_per_definition_l; i++)
1007         definitions_l[definition].instances[i] += instance_add;
1008     }
1009   };
1010
1011   // clang-format off
1012   #define AddToSchemaAndInstances(schema_add, instance_add) \
1013     RndDef::Add(definitions, schema, instances_per_definition, \
1014                 schema_add, instance_add, definition)
1015
1016   #define Dummy() \
1017     RndDef::Add(definitions, schema, instances_per_definition, \
1018                 "byte", "1", definition)
1019   // clang-format on
1020
1021   RndDef definitions[num_definitions];
1022
1023   // We are going to generate num_definitions, the first
1024   // num_struct_definitions will be structs, the rest tables. For each
1025   // generate random fields, some of which may be struct/table types
1026   // referring to previously generated structs/tables.
1027   // Simultanenously, we generate instances_per_definition JSON data
1028   // definitions, which will have identical structure to the schema
1029   // being generated. We generate multiple instances such that when creating
1030   // hierarchy, we get some variety by picking one randomly.
1031   for (int definition = 0; definition < num_definitions; definition++) {
1032     std::string definition_name = "D" + flatbuffers::NumToString(definition);
1033
1034     bool is_struct = definition < num_struct_definitions;
1035
1036     AddToSchemaAndInstances(
1037         ((is_struct ? "struct " : "table ") + definition_name + " {\n").c_str(),
1038         "{\n");
1039
1040     for (int field = 0; field < fields_per_definition; field++) {
1041       const bool is_last_field = field == fields_per_definition - 1;
1042
1043       // Deprecate 1 in deprecation_rate fields. Only table fields can be
1044       // deprecated.
1045       // Don't deprecate the last field to avoid dangling commas in JSON.
1046       const bool deprecated =
1047           !is_struct && !is_last_field && (lcg_rand() % deprecation_rate == 0);
1048
1049       std::string field_name = "f" + flatbuffers::NumToString(field);
1050       AddToSchemaAndInstances(("  " + field_name + ":").c_str(),
1051                               deprecated ? "" : (field_name + ": ").c_str());
1052       // Pick random type:
1053       auto base_type = static_cast<flatbuffers::BaseType>(
1054           lcg_rand() % (flatbuffers::BASE_TYPE_UNION + 1));
1055       switch (base_type) {
1056         case flatbuffers::BASE_TYPE_STRING:
1057           if (is_struct) {
1058             Dummy();  // No strings in structs.
1059           } else {
1060             AddToSchemaAndInstances("string", deprecated ? "" : "\"hi\"");
1061           }
1062           break;
1063         case flatbuffers::BASE_TYPE_VECTOR:
1064           if (is_struct) {
1065             Dummy();  // No vectors in structs.
1066           } else {
1067             AddToSchemaAndInstances("[ubyte]",
1068                                     deprecated ? "" : "[\n0,\n1,\n255\n]");
1069           }
1070           break;
1071         case flatbuffers::BASE_TYPE_NONE:
1072         case flatbuffers::BASE_TYPE_UTYPE:
1073         case flatbuffers::BASE_TYPE_STRUCT:
1074         case flatbuffers::BASE_TYPE_UNION:
1075           if (definition) {
1076             // Pick a random previous definition and random data instance of
1077             // that definition.
1078             int defref = lcg_rand() % definition;
1079             int instance = lcg_rand() % instances_per_definition;
1080             AddToSchemaAndInstances(
1081                 ("D" + flatbuffers::NumToString(defref)).c_str(),
1082                 deprecated ? ""
1083                            : definitions[defref].instances[instance].c_str());
1084           } else {
1085             // If this is the first definition, we have no definition we can
1086             // refer to.
1087             Dummy();
1088           }
1089           break;
1090         case flatbuffers::BASE_TYPE_BOOL:
1091           AddToSchemaAndInstances(
1092               "bool", deprecated ? "" : (lcg_rand() % 2 ? "true" : "false"));
1093           break;
1094         default:
1095           // All the scalar types.
1096           schema += flatbuffers::kTypeNames[base_type];
1097
1098           if (!deprecated) {
1099             // We want each instance to use its own random value.
1100             for (int inst = 0; inst < instances_per_definition; inst++)
1101               definitions[definition].instances[inst] +=
1102                   flatbuffers::IsFloat(base_type)
1103                       ? flatbuffers::NumToString<double>(lcg_rand() % 128)
1104                             .c_str()
1105                       : flatbuffers::NumToString<int>(lcg_rand() % 128).c_str();
1106           }
1107       }
1108       AddToSchemaAndInstances(deprecated ? "(deprecated);\n" : ";\n",
1109                               deprecated ? "" : is_last_field ? "\n" : ",\n");
1110     }
1111     AddToSchemaAndInstances("}\n\n", "}");
1112   }
1113
1114   schema += "root_type D" + flatbuffers::NumToString(num_definitions - 1);
1115   schema += ";\n";
1116
1117   flatbuffers::Parser parser;
1118
1119   // Will not compare against the original if we don't write defaults
1120   parser.builder_.ForceDefaults(true);
1121
1122   // Parse the schema, parse the generated data, then generate text back
1123   // from the binary and compare against the original.
1124   TEST_EQ(parser.Parse(schema.c_str()), true);
1125
1126   const std::string &json =
1127       definitions[num_definitions - 1].instances[0] + "\n";
1128
1129   TEST_EQ(parser.Parse(json.c_str()), true);
1130
1131   std::string jsongen;
1132   parser.opts.indent_step = 0;
1133   auto result =
1134       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1135   TEST_EQ(result, true);
1136
1137   if (jsongen != json) {
1138     // These strings are larger than a megabyte, so we show the bytes around
1139     // the first bytes that are different rather than the whole string.
1140     size_t len = std::min(json.length(), jsongen.length());
1141     for (size_t i = 0; i < len; i++) {
1142       if (json[i] != jsongen[i]) {
1143         i -= std::min(static_cast<size_t>(10), i);  // show some context;
1144         size_t end = std::min(len, i + 20);
1145         for (; i < end; i++)
1146           TEST_OUTPUT_LINE("at %d: found \"%c\", expected \"%c\"\n",
1147                            static_cast<int>(i), jsongen[i], json[i]);
1148         break;
1149       }
1150     }
1151     TEST_NOTNULL(NULL);
1152   }
1153
1154   // clang-format off
1155   #ifdef FLATBUFFERS_TEST_VERBOSE
1156     TEST_OUTPUT_LINE("%dk schema tested with %dk of json\n",
1157                      static_cast<int>(schema.length() / 1024),
1158                      static_cast<int>(json.length() / 1024));
1159   #endif
1160   // clang-format on
1161 }
1162
1163 // Test that parser errors are actually generated.
1164 void TestError_(const char *src, const char *error_substr, bool strict_json,
1165                 const char *file, int line, const char *func) {
1166   flatbuffers::IDLOptions opts;
1167   opts.strict_json = strict_json;
1168   flatbuffers::Parser parser(opts);
1169   if (parser.Parse(src)) {
1170     TestFail("true", "false",
1171              ("parser.Parse(\"" + std::string(src) + "\")").c_str(), file, line,
1172              func);
1173   } else if (!strstr(parser.error_.c_str(), error_substr)) {
1174     TestFail(parser.error_.c_str(), error_substr,
1175              ("parser.Parse(\"" + std::string(src) + "\")").c_str(), file, line,
1176              func);
1177   }
1178 }
1179
1180 void TestError_(const char *src, const char *error_substr, const char *file,
1181                 int line, const char *func) {
1182   TestError_(src, error_substr, false, file, line, func);
1183 }
1184
1185 #ifdef WIN32
1186 #  define TestError(src, ...) \
1187     TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
1188 #else
1189 #  define TestError(src, ...) \
1190     TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1191 #endif
1192
1193 // Test that parsing errors occur as we'd expect.
1194 // Also useful for coverage, making sure these paths are run.
1195 void ErrorTest() {
1196   // In order they appear in idl_parser.cpp
1197   TestError("table X { Y:byte; } root_type X; { Y: 999 }", "does not fit");
1198   TestError("\"\0", "illegal");
1199   TestError("\"\\q", "escape code");
1200   TestError("table ///", "documentation");
1201   TestError("@", "illegal");
1202   TestError("table 1", "expecting");
1203   TestError("table X { Y:[[int]]; }", "nested vector");
1204   TestError("table X { Y:1; }", "illegal type");
1205   TestError("table X { Y:int; Y:int; }", "field already");
1206   TestError("table Y {} table X { Y:int; }", "same as table");
1207   TestError("struct X { Y:string; }", "only scalar");
1208   TestError("table X { Y:string = \"\"; }", "default values");
1209   TestError("enum Y:byte { Z = 1 } table X { y:Y; }", "not part of enum");
1210   TestError("struct X { Y:int (deprecated); }", "deprecate");
1211   TestError("union Z { X } table X { Y:Z; } root_type X; { Y: {}, A:1 }",
1212             "missing type field");
1213   TestError("union Z { X } table X { Y:Z; } root_type X; { Y_type: 99, Y: {",
1214             "type id");
1215   TestError("table X { Y:int; } root_type X; { Z:", "unknown field");
1216   TestError("table X { Y:int; } root_type X; { Y:", "string constant", true);
1217   TestError("table X { Y:int; } root_type X; { \"Y\":1, }", "string constant",
1218             true);
1219   TestError(
1220       "struct X { Y:int; Z:int; } table W { V:X; } root_type W; "
1221       "{ V:{ Y:1 } }",
1222       "wrong number");
1223   TestError("enum E:byte { A } table X { Y:E; } root_type X; { Y:U }",
1224             "unknown enum value");
1225   TestError("table X { Y:byte; } root_type X; { Y:; }", "starting");
1226   TestError("enum X:byte { Y } enum X {", "enum already");
1227   TestError("enum X:float {}", "underlying");
1228   TestError("enum X:byte { Y, Y }", "value already");
1229   TestError("enum X:byte { Y=2, Z=1 }", "ascending");
1230   TestError("enum X:byte (bit_flags) { Y=8 }", "bit flag out");
1231   TestError("table X { Y:int; } table X {", "datatype already");
1232   TestError("struct X (force_align: 7) { Y:int; }", "force_align");
1233   TestError("{}", "no root");
1234   TestError("table X { Y:byte; } root_type X; { Y:1 } { Y:1 }", "end of file");
1235   TestError("table X { Y:byte; } root_type X; { Y:1 } table Y{ Z:int }",
1236             "end of file");
1237   TestError("root_type X;", "unknown root");
1238   TestError("struct X { Y:int; } root_type X;", "a table");
1239   TestError("union X { Y }", "referenced");
1240   TestError("union Z { X } struct X { Y:int; }", "only tables");
1241   TestError("table X { Y:[int]; YLength:int; }", "clash");
1242   TestError("table X { Y:byte; } root_type X; { Y:1, Y:2 }", "more than once");
1243   // float to integer conversion is forbidden
1244   TestError("table X { Y:int; } root_type X; { Y:1.0 }", "float");
1245   TestError("table X { Y:bool; } root_type X; { Y:1.0 }", "float");
1246   TestError("enum X:bool { Y = true }", "must be integral");
1247 }
1248
1249 template<typename T> T TestValue(const char *json, const char *type_name) {
1250   flatbuffers::Parser parser;
1251   parser.builder_.ForceDefaults(true);  // return defaults
1252   auto check_default = json ? false : true;
1253   if (check_default) { parser.opts.output_default_scalars_in_json = true; }
1254   // Simple schema.
1255   std::string schema =
1256       "table X { Y:" + std::string(type_name) + "; } root_type X;";
1257   TEST_EQ(parser.Parse(schema.c_str()), true);
1258
1259   auto done = parser.Parse(check_default ? "{}" : json);
1260   TEST_EQ_STR(parser.error_.c_str(), "");
1261   TEST_EQ(done, true);
1262
1263   // Check with print.
1264   std::string print_back;
1265   parser.opts.indent_step = -1;
1266   TEST_EQ(GenerateText(parser, parser.builder_.GetBufferPointer(), &print_back),
1267           true);
1268   // restore value from its default
1269   if (check_default) { TEST_EQ(parser.Parse(print_back.c_str()), true); }
1270
1271   auto root = flatbuffers::GetRoot<flatbuffers::Table>(
1272       parser.builder_.GetBufferPointer());
1273   return root->GetField<T>(flatbuffers::FieldIndexToOffset(0), 0);
1274 }
1275
1276 bool FloatCompare(float a, float b) { return fabs(a - b) < 0.001; }
1277
1278 // Additional parser testing not covered elsewhere.
1279 void ValueTest() {
1280   // Test scientific notation numbers.
1281   TEST_EQ(FloatCompare(TestValue<float>("{ Y:0.0314159e+2 }", "float"),
1282                        3.14159f),
1283           true);
1284   // number in string
1285   TEST_EQ(FloatCompare(TestValue<float>("{ Y:\"0.0314159e+2\" }", "float"),
1286                        3.14159f),
1287           true);
1288
1289   // Test conversion functions.
1290   TEST_EQ(FloatCompare(TestValue<float>("{ Y:cos(rad(180)) }", "float"), -1),
1291           true);
1292
1293   // int embedded to string
1294   TEST_EQ(TestValue<int>("{ Y:\"-876\" }", "int=-123"), -876);
1295   TEST_EQ(TestValue<int>("{ Y:\"876\" }", "int=-123"), 876);
1296
1297   // Test negative hex constant.
1298   TEST_EQ(TestValue<int>("{ Y:-0x8ea0 }", "int=-0x8ea0"), -36512);
1299   TEST_EQ(TestValue<int>(nullptr, "int=-0x8ea0"), -36512);
1300
1301   // positive hex constant
1302   TEST_EQ(TestValue<int>("{ Y:0x1abcdef }", "int=0x1"), 0x1abcdef);
1303   // with optional '+' sign
1304   TEST_EQ(TestValue<int>("{ Y:+0x1abcdef }", "int=+0x1"), 0x1abcdef);
1305   // hex in string
1306   TEST_EQ(TestValue<int>("{ Y:\"0x1abcdef\" }", "int=+0x1"), 0x1abcdef);
1307
1308   // Make sure we do unsigned 64bit correctly.
1309   TEST_EQ(TestValue<uint64_t>("{ Y:12335089644688340133 }", "ulong"),
1310           12335089644688340133ULL);
1311
1312   // bool in string
1313   TEST_EQ(TestValue<bool>("{ Y:\"false\" }", "bool=true"), false);
1314   TEST_EQ(TestValue<bool>("{ Y:\"true\" }", "bool=\"true\""), true);
1315   TEST_EQ(TestValue<bool>("{ Y:'false' }", "bool=true"), false);
1316   TEST_EQ(TestValue<bool>("{ Y:'true' }", "bool=\"true\""), true);
1317
1318   // check comments before and after json object
1319   TEST_EQ(TestValue<int>("/*before*/ { Y:1 } /*after*/", "int"), 1);
1320   TEST_EQ(TestValue<int>("//before \n { Y:1 } //after", "int"), 1);
1321
1322 }
1323
1324 void NestedListTest() {
1325   flatbuffers::Parser parser1;
1326   TEST_EQ(parser1.Parse("struct Test { a:short; b:byte; } table T { F:[Test]; }"
1327                         "root_type T;"
1328                         "{ F:[ [10,20], [30,40]] }"),
1329           true);
1330 }
1331
1332 void EnumStringsTest() {
1333   flatbuffers::Parser parser1;
1334   TEST_EQ(parser1.Parse("enum E:byte { A, B, C } table T { F:[E]; }"
1335                         "root_type T;"
1336                         "{ F:[ A, B, \"C\", \"A B C\" ] }"),
1337           true);
1338   flatbuffers::Parser parser2;
1339   TEST_EQ(parser2.Parse("enum E:byte { A, B, C } table T { F:[int]; }"
1340                         "root_type T;"
1341                         "{ F:[ \"E.C\", \"E.A E.B E.C\" ] }"),
1342           true);
1343 }
1344
1345 void EnumNamesTest() {
1346   TEST_EQ_STR("Red", EnumNameColor(Color_Red));
1347   TEST_EQ_STR("Green", EnumNameColor(Color_Green));
1348   TEST_EQ_STR("Blue", EnumNameColor(Color_Blue));
1349   // Check that Color to string don't crash while decode a mixture of Colors.
1350   // 1) Example::Color enum is enum with unfixed underlying type.
1351   // 2) Valid enum range: [0; 2^(ceil(log2(Color_ANY))) - 1].
1352   // Consequence: A value is out of this range will lead to UB (since C++17).
1353   // For details see C++17 standard or explanation on the SO:
1354   // stackoverflow.com/questions/18195312/what-happens-if-you-static-cast-invalid-value-to-enum-class
1355   TEST_EQ_STR("", EnumNameColor(static_cast<Color>(0)));
1356   TEST_EQ_STR("", EnumNameColor(static_cast<Color>(Color_ANY-1)));
1357   TEST_EQ_STR("", EnumNameColor(static_cast<Color>(Color_ANY+1)));
1358 }
1359
1360 void EnumOutOfRangeTest() {
1361   TestError("enum X:byte { Y = 128 }", "enum value does not fit");
1362   TestError("enum X:byte { Y = -129 }", "enum value does not fit");
1363   TestError("enum X:byte { Y = 127, Z }", "enum value does not fit");
1364   TestError("enum X:ubyte { Y = -1 }", "enum value does not fit");
1365   TestError("enum X:ubyte { Y = 256 }", "enum value does not fit");
1366   // Unions begin with an implicit "NONE = 0".
1367   TestError("table Y{} union X { Y = -1 }",
1368             "enum values must be specified in ascending order");
1369   TestError("table Y{} union X { Y = 256 }", "enum value does not fit");
1370   TestError("table Y{} union X { Y = 255, Z:Y }", "enum value does not fit");
1371   TestError("enum X:int { Y = -2147483649 }", "enum value does not fit");
1372   TestError("enum X:int { Y = 2147483648 }", "enum value does not fit");
1373   TestError("enum X:uint { Y = -1 }", "enum value does not fit");
1374   TestError("enum X:uint { Y = 4294967297 }", "enum value does not fit");
1375   TestError("enum X:long { Y = 9223372036854775808 }", "constant does not fit");
1376   TestError("enum X:long { Y = 9223372036854775807, Z }", "enum value overflows");
1377   TestError("enum X:ulong { Y = -1 }", "enum value does not fit");
1378   // TODO: these are perfectly valid constants that shouldn't fail
1379   TestError("enum X:ulong { Y = 13835058055282163712 }", "constant does not fit");
1380   TestError("enum X:ulong { Y = 18446744073709551615 }", "constant does not fit");
1381 }
1382
1383 void IntegerOutOfRangeTest() {
1384   TestError("table T { F:byte; } root_type T; { F:128 }",
1385             "constant does not fit");
1386   TestError("table T { F:byte; } root_type T; { F:-129 }",
1387             "constant does not fit");
1388   TestError("table T { F:ubyte; } root_type T; { F:256 }",
1389             "constant does not fit");
1390   TestError("table T { F:ubyte; } root_type T; { F:-1 }",
1391             "constant does not fit");
1392   TestError("table T { F:short; } root_type T; { F:32768 }",
1393             "constant does not fit");
1394   TestError("table T { F:short; } root_type T; { F:-32769 }",
1395             "constant does not fit");
1396   TestError("table T { F:ushort; } root_type T; { F:65536 }",
1397             "constant does not fit");
1398   TestError("table T { F:ushort; } root_type T; { F:-1 }",
1399             "constant does not fit");
1400   TestError("table T { F:int; } root_type T; { F:2147483648 }",
1401             "constant does not fit");
1402   TestError("table T { F:int; } root_type T; { F:-2147483649 }",
1403             "constant does not fit");
1404   TestError("table T { F:uint; } root_type T; { F:4294967296 }",
1405             "constant does not fit");
1406   TestError("table T { F:uint; } root_type T; { F:-1 }",
1407             "constant does not fit");
1408   // Check fixed width aliases
1409   TestError("table X { Y:uint8; } root_type X; { Y: -1 }", "does not fit");
1410   TestError("table X { Y:uint8; } root_type X; { Y: 256 }", "does not fit");
1411   TestError("table X { Y:uint16; } root_type X; { Y: -1 }", "does not fit");
1412   TestError("table X { Y:uint16; } root_type X; { Y: 65536 }", "does not fit");
1413   TestError("table X { Y:uint32; } root_type X; { Y: -1 }", "");
1414   TestError("table X { Y:uint32; } root_type X; { Y: 4294967296 }",
1415             "does not fit");
1416   TestError("table X { Y:uint64; } root_type X; { Y: -1 }", "");
1417   TestError("table X { Y:uint64; } root_type X; { Y: -9223372036854775809 }",
1418             "does not fit");
1419   TestError("table X { Y:uint64; } root_type X; { Y: 18446744073709551616 }",
1420             "does not fit");
1421
1422   TestError("table X { Y:int8; } root_type X; { Y: -129 }", "does not fit");
1423   TestError("table X { Y:int8; } root_type X; { Y: 128 }", "does not fit");
1424   TestError("table X { Y:int16; } root_type X; { Y: -32769 }", "does not fit");
1425   TestError("table X { Y:int16; } root_type X; { Y: 32768 }", "does not fit");
1426   TestError("table X { Y:int32; } root_type X; { Y: -2147483649 }", "");
1427   TestError("table X { Y:int32; } root_type X; { Y: 2147483648 }",
1428             "does not fit");
1429   TestError("table X { Y:int64; } root_type X; { Y: -9223372036854775809 }",
1430             "does not fit");
1431   TestError("table X { Y:int64; } root_type X; { Y: 9223372036854775808 }",
1432             "does not fit");
1433   // check out-of-int64 as int8
1434   TestError("table X { Y:int8; } root_type X; { Y: -9223372036854775809 }",
1435             "does not fit");
1436   TestError("table X { Y:int8; } root_type X; { Y: 9223372036854775808 }",
1437             "does not fit");
1438
1439   // Check default values
1440   TestError("table X { Y:int64=-9223372036854775809; } root_type X; {}",
1441             "does not fit");
1442   TestError("table X { Y:int64= 9223372036854775808; } root_type X; {}",
1443             "does not fit");
1444   TestError("table X { Y:uint64; } root_type X; { Y: -1 }", "");
1445   TestError("table X { Y:uint64=-9223372036854775809; } root_type X; {}",
1446             "does not fit");
1447   TestError("table X { Y:uint64= 18446744073709551616; } root_type X; {}",
1448             "does not fit");
1449 }
1450
1451 void IntegerBoundaryTest() {
1452   TEST_EQ(TestValue<int8_t>("{ Y:127 }", "byte"), 127);
1453   TEST_EQ(TestValue<int8_t>("{ Y:-128 }", "byte"), -128);
1454   TEST_EQ(TestValue<uint8_t>("{ Y:255 }", "ubyte"), 255);
1455   TEST_EQ(TestValue<uint8_t>("{ Y:0 }", "ubyte"), 0);
1456   TEST_EQ(TestValue<int16_t>("{ Y:32767 }", "short"), 32767);
1457   TEST_EQ(TestValue<int16_t>("{ Y:-32768 }", "short"), -32768);
1458   TEST_EQ(TestValue<uint16_t>("{ Y:65535 }", "ushort"), 65535);
1459   TEST_EQ(TestValue<uint16_t>("{ Y:0 }", "ushort"), 0);
1460   TEST_EQ(TestValue<int32_t>("{ Y:2147483647 }", "int"), 2147483647);
1461   TEST_EQ(TestValue<int32_t>("{ Y:-2147483648 }", "int"), (-2147483647 - 1));
1462   TEST_EQ(TestValue<uint32_t>("{ Y:4294967295 }", "uint"), 4294967295);
1463   TEST_EQ(TestValue<uint32_t>("{ Y:0 }", "uint"), 0);
1464   TEST_EQ(TestValue<int64_t>("{ Y:9223372036854775807 }", "long"),
1465           9223372036854775807);
1466   TEST_EQ(TestValue<int64_t>("{ Y:-9223372036854775808 }", "long"),
1467           (-9223372036854775807 - 1));
1468   TEST_EQ(TestValue<uint64_t>("{ Y:18446744073709551615 }", "ulong"),
1469           18446744073709551615U);
1470   TEST_EQ(TestValue<uint64_t>("{ Y:0 }", "ulong"), 0);
1471   TEST_EQ(TestValue<uint64_t>("{ Y: 18446744073709551615 }", "uint64"),
1472           18446744073709551615ULL);
1473   // check that the default works
1474   TEST_EQ(TestValue<uint64_t>(nullptr, "uint64 = 18446744073709551615"),
1475           18446744073709551615ULL);
1476 }
1477
1478 void ValidFloatTest() {
1479   const auto infinityf = flatbuffers::numeric_limits<float>::infinity();
1480   const auto infinityd = flatbuffers::numeric_limits<double>::infinity();
1481   // check rounding to infinity
1482   TEST_EQ(TestValue<float>("{ Y:+3.4029e+38 }", "float"), +infinityf);
1483   TEST_EQ(TestValue<float>("{ Y:-3.4029e+38 }", "float"), -infinityf);
1484   TEST_EQ(TestValue<double>("{ Y:+1.7977e+308 }", "double"), +infinityd);
1485   TEST_EQ(TestValue<double>("{ Y:-1.7977e+308 }", "double"), -infinityd);
1486
1487   TEST_EQ(
1488       FloatCompare(TestValue<float>("{ Y:0.0314159e+2 }", "float"), 3.14159f),
1489       true);
1490   // float in string
1491   TEST_EQ(FloatCompare(TestValue<float>("{ Y:\" 0.0314159e+2  \" }", "float"),
1492                        3.14159f),
1493           true);
1494
1495   TEST_EQ(TestValue<float>("{ Y:1 }", "float"), 1.0f);
1496   TEST_EQ(TestValue<float>("{ Y:1.0 }", "float"), 1.0f);
1497   TEST_EQ(TestValue<float>("{ Y:1. }", "float"), 1.0f);
1498   TEST_EQ(TestValue<float>("{ Y:+1. }", "float"), 1.0f);
1499   TEST_EQ(TestValue<float>("{ Y:-1. }", "float"), -1.0f);
1500   TEST_EQ(TestValue<float>("{ Y:1.e0 }", "float"), 1.0f);
1501   TEST_EQ(TestValue<float>("{ Y:1.e+0 }", "float"), 1.0f);
1502   TEST_EQ(TestValue<float>("{ Y:1.e-0 }", "float"), 1.0f);
1503   TEST_EQ(TestValue<float>("{ Y:0.125 }", "float"), 0.125f);
1504   TEST_EQ(TestValue<float>("{ Y:.125 }", "float"), 0.125f);
1505   TEST_EQ(TestValue<float>("{ Y:-.125 }", "float"), -0.125f);
1506   TEST_EQ(TestValue<float>("{ Y:+.125 }", "float"), +0.125f);
1507   TEST_EQ(TestValue<float>("{ Y:5 }", "float"), 5.0f);
1508   TEST_EQ(TestValue<float>("{ Y:\"5\" }", "float"), 5.0f);
1509
1510   #if defined(FLATBUFFERS_HAS_NEW_STRTOD)
1511   // Old MSVC versions may have problem with this check.
1512   // https://www.exploringbinary.com/visual-c-plus-plus-strtod-still-broken/
1513   TEST_EQ(TestValue<double>("{ Y:6.9294956446009195e15 }", "double"),
1514     6929495644600920);
1515   // check nan's
1516   TEST_EQ(std::isnan(TestValue<double>("{ Y:nan }", "double")), true);
1517   TEST_EQ(std::isnan(TestValue<float>("{ Y:nan }", "float")), true);
1518   TEST_EQ(std::isnan(TestValue<float>("{ Y:\"nan\" }", "float")), true);
1519   TEST_EQ(std::isnan(TestValue<float>("{ Y:+nan }", "float")), true);
1520   TEST_EQ(std::isnan(TestValue<float>("{ Y:-nan }", "float")), true);
1521   TEST_EQ(std::isnan(TestValue<float>(nullptr, "float=nan")), true);
1522   TEST_EQ(std::isnan(TestValue<float>(nullptr, "float=-nan")), true);
1523   // check inf
1524   TEST_EQ(TestValue<float>("{ Y:inf }", "float"), infinityf);
1525   TEST_EQ(TestValue<float>("{ Y:\"inf\" }", "float"), infinityf);
1526   TEST_EQ(TestValue<float>("{ Y:+inf }", "float"), infinityf);
1527   TEST_EQ(TestValue<float>("{ Y:-inf }", "float"), -infinityf);
1528   TEST_EQ(TestValue<float>(nullptr, "float=inf"), infinityf);
1529   TEST_EQ(TestValue<float>(nullptr, "float=-inf"), -infinityf);
1530   TestValue<double>(
1531       "{ Y : [0.2, .2, 1.0, -1.0, -2., 2., 1e0, -1e0, 1.0e0, -1.0e0, -3.e2, "
1532       "3.0e2] }",
1533       "[double]");
1534   TestValue<float>(
1535       "{ Y : [0.2, .2, 1.0, -1.0, -2., 2., 1e0, -1e0, 1.0e0, -1.0e0, -3.e2, "
1536       "3.0e2] }",
1537       "[float]");
1538
1539   // Test binary format of float point.
1540   // https://en.cppreference.com/w/cpp/language/floating_literal
1541   // 0x11.12p-1 = (1*16^1 + 2*16^0 + 3*16^-1 + 4*16^-2) * 2^-1 =
1542   TEST_EQ(TestValue<double>("{ Y:0x12.34p-1 }", "double"), 9.1015625);
1543   // hex fraction 1.2 (decimal 1.125) scaled by 2^3, that is 9.0
1544   TEST_EQ(TestValue<float>("{ Y:-0x0.2p0 }", "float"), -0.125f);
1545   TEST_EQ(TestValue<float>("{ Y:-0x.2p1 }", "float"), -0.25f);
1546   TEST_EQ(TestValue<float>("{ Y:0x1.2p3 }", "float"), 9.0f);
1547   TEST_EQ(TestValue<float>("{ Y:0x10.1p0 }", "float"), 16.0625f);
1548   TEST_EQ(TestValue<double>("{ Y:0x1.2p3 }", "double"), 9.0);
1549   TEST_EQ(TestValue<double>("{ Y:0x10.1p0 }", "double"), 16.0625);
1550   TEST_EQ(TestValue<double>("{ Y:0xC.68p+2 }", "double"), 49.625);
1551   TestValue<double>("{ Y : [0x20.4ep1, +0x20.4ep1, -0x20.4ep1] }", "[double]");
1552   TestValue<float>("{ Y : [0x20.4ep1, +0x20.4ep1, -0x20.4ep1] }", "[float]");
1553
1554 #else   // FLATBUFFERS_HAS_NEW_STRTOD
1555   TEST_OUTPUT_LINE("FLATBUFFERS_HAS_NEW_STRTOD tests skipped");
1556 #endif  // FLATBUFFERS_HAS_NEW_STRTOD
1557 }
1558
1559 void InvalidFloatTest() {
1560   auto invalid_msg = "invalid number";
1561   auto comma_msg = "expecting: ,";
1562   TestError("table T { F:float; } root_type T; { F:1,0 }", "");
1563   TestError("table T { F:float; } root_type T; { F:. }", "");
1564   TestError("table T { F:float; } root_type T; { F:- }", invalid_msg);
1565   TestError("table T { F:float; } root_type T; { F:+ }", invalid_msg);
1566   TestError("table T { F:float; } root_type T; { F:-. }", invalid_msg);
1567   TestError("table T { F:float; } root_type T; { F:+. }", invalid_msg);
1568   TestError("table T { F:float; } root_type T; { F:.e }", "");
1569   TestError("table T { F:float; } root_type T; { F:-e }", invalid_msg);
1570   TestError("table T { F:float; } root_type T; { F:+e }", invalid_msg);
1571   TestError("table T { F:float; } root_type T; { F:-.e }", invalid_msg);
1572   TestError("table T { F:float; } root_type T; { F:+.e }", invalid_msg);
1573   TestError("table T { F:float; } root_type T; { F:-e1 }", invalid_msg);
1574   TestError("table T { F:float; } root_type T; { F:+e1 }", invalid_msg);
1575   TestError("table T { F:float; } root_type T; { F:1.0e+ }", invalid_msg);
1576   TestError("table T { F:float; } root_type T; { F:1.0e- }", invalid_msg);
1577   // exponent pP is mandatory for hex-float
1578   TestError("table T { F:float; } root_type T; { F:0x0 }", invalid_msg);
1579   TestError("table T { F:float; } root_type T; { F:-0x. }", invalid_msg);
1580   TestError("table T { F:float; } root_type T; { F:0x. }", invalid_msg);
1581   // eE not exponent in hex-float!
1582   TestError("table T { F:float; } root_type T; { F:0x0.0e+ }", invalid_msg);
1583   TestError("table T { F:float; } root_type T; { F:0x0.0e- }", invalid_msg);
1584   TestError("table T { F:float; } root_type T; { F:0x0.0p }", invalid_msg);
1585   TestError("table T { F:float; } root_type T; { F:0x0.0p+ }", invalid_msg);
1586   TestError("table T { F:float; } root_type T; { F:0x0.0p- }", invalid_msg);
1587   TestError("table T { F:float; } root_type T; { F:0x0.0pa1 }", invalid_msg);
1588   TestError("table T { F:float; } root_type T; { F:0x0.0e+ }", invalid_msg);
1589   TestError("table T { F:float; } root_type T; { F:0x0.0e- }", invalid_msg);
1590   TestError("table T { F:float; } root_type T; { F:0x0.0e+0 }", invalid_msg);
1591   TestError("table T { F:float; } root_type T; { F:0x0.0e-0 }", invalid_msg);
1592   TestError("table T { F:float; } root_type T; { F:0x0.0ep+ }", invalid_msg);
1593   TestError("table T { F:float; } root_type T; { F:0x0.0ep- }", invalid_msg);
1594   TestError("table T { F:float; } root_type T; { F:1.2.3 }", invalid_msg);
1595   TestError("table T { F:float; } root_type T; { F:1.2.e3 }", invalid_msg);
1596   TestError("table T { F:float; } root_type T; { F:1.2e.3 }", invalid_msg);
1597   TestError("table T { F:float; } root_type T; { F:1.2e0.3 }", invalid_msg);
1598   TestError("table T { F:float; } root_type T; { F:1.2e3. }", invalid_msg);
1599   TestError("table T { F:float; } root_type T; { F:1.2e3.0 }", invalid_msg);
1600   TestError("table T { F:float; } root_type T; { F:+-1.0 }", invalid_msg);
1601   TestError("table T { F:float; } root_type T; { F:1.0e+-1 }", invalid_msg);
1602   TestError("table T { F:float; } root_type T; { F:\"1.0e+-1\" }", invalid_msg);
1603   TestError("table T { F:float; } root_type T; { F:1.e0e }", comma_msg);
1604   TestError("table T { F:float; } root_type T; { F:0x1.p0e }", comma_msg);
1605   TestError("table T { F:float; } root_type T; { F:\" 0x10 \" }", invalid_msg);
1606   // floats in string
1607   TestError("table T { F:float; } root_type T; { F:\"1,2.\" }", invalid_msg);
1608   TestError("table T { F:float; } root_type T; { F:\"1.2e3.\" }", invalid_msg);
1609   TestError("table T { F:float; } root_type T; { F:\"0x1.p0e\" }", invalid_msg);
1610   TestError("table T { F:float; } root_type T; { F:\"0x1.0\" }", invalid_msg);
1611   TestError("table T { F:float; } root_type T; { F:\" 0x1.0\" }", invalid_msg);
1612   TestError("table T { F:float; } root_type T; { F:\"+ 0\" }", invalid_msg);
1613   // disable escapes for "number-in-string"
1614   TestError("table T { F:float; } root_type T; { F:\"\\f1.2e3.\" }", "invalid");
1615   TestError("table T { F:float; } root_type T; { F:\"\\t1.2e3.\" }", "invalid");
1616   TestError("table T { F:float; } root_type T; { F:\"\\n1.2e3.\" }", "invalid");
1617   TestError("table T { F:float; } root_type T; { F:\"\\r1.2e3.\" }", "invalid");
1618   TestError("table T { F:float; } root_type T; { F:\"4\\x005\" }", "invalid");
1619   TestError("table T { F:float; } root_type T; { F:\"\'12\'\" }", invalid_msg);
1620   // null is not a number constant!
1621   TestError("table T { F:float; } root_type T; { F:\"null\" }", invalid_msg);
1622   TestError("table T { F:float; } root_type T; { F:null }", invalid_msg);
1623 }
1624
1625 template<typename T>
1626 void NumericUtilsTestInteger(const char *lower, const char *upper) {
1627   T x;
1628   TEST_EQ(flatbuffers::StringToNumber("1q", &x), false);
1629   TEST_EQ(x, 0);
1630   TEST_EQ(flatbuffers::StringToNumber(upper, &x), false);
1631   TEST_EQ(x, flatbuffers::numeric_limits<T>::max());
1632   TEST_EQ(flatbuffers::StringToNumber(lower, &x), false);
1633   auto expval = flatbuffers::is_unsigned<T>::value
1634                     ? flatbuffers::numeric_limits<T>::max()
1635                     : flatbuffers::numeric_limits<T>::lowest();
1636   TEST_EQ(x, expval);
1637 }
1638
1639 template<typename T>
1640 void NumericUtilsTestFloat(const char *lower, const char *upper) {
1641   T f;
1642   TEST_EQ(flatbuffers::StringToNumber("1q", &f), false);
1643   TEST_EQ(f, 0);
1644   TEST_EQ(flatbuffers::StringToNumber(upper, &f), true);
1645   TEST_EQ(f, +flatbuffers::numeric_limits<T>::infinity());
1646   TEST_EQ(flatbuffers::StringToNumber(lower, &f), true);
1647   TEST_EQ(f, -flatbuffers::numeric_limits<T>::infinity());
1648 }
1649
1650 void NumericUtilsTest() {
1651   NumericUtilsTestInteger<uint64_t>("-1", "18446744073709551616");
1652   NumericUtilsTestInteger<uint8_t>("-1", "256");
1653   NumericUtilsTestInteger<int64_t>("-9223372036854775809",
1654                                    "9223372036854775808");
1655   NumericUtilsTestInteger<int8_t>("-129", "128");
1656   NumericUtilsTestFloat<float>("-3.4029e+38", "+3.4029e+38");
1657   NumericUtilsTestFloat<float>("-1.7977e+308", "+1.7977e+308");
1658 }
1659
1660 void IsAsciiUtilsTest() {
1661   char c = -128;
1662   for (int cnt = 0; cnt < 256; cnt++) {
1663     auto alpha = (('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z'));
1664     auto dec = (('0' <= c) && (c <= '9'));
1665     auto hex = (('a' <= c) && (c <= 'f')) || (('A' <= c) && (c <= 'F'));
1666     TEST_EQ(flatbuffers::is_alpha(c), alpha);
1667     TEST_EQ(flatbuffers::is_alnum(c), alpha || dec);
1668     TEST_EQ(flatbuffers::is_digit(c), dec);
1669     TEST_EQ(flatbuffers::is_xdigit(c), dec || hex);
1670     c += 1;
1671   }
1672 }
1673
1674 void UnicodeTest() {
1675   flatbuffers::Parser parser;
1676   // Without setting allow_non_utf8 = true, we treat \x sequences as byte
1677   // sequences which are then validated as UTF-8.
1678   TEST_EQ(parser.Parse("table T { F:string; }"
1679                        "root_type T;"
1680                        "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1681                        "\\u5225\\u30B5\\u30A4\\u30C8\\xE2\\x82\\xAC\\u0080\\uD8"
1682                        "3D\\uDE0E\" }"),
1683           true);
1684   std::string jsongen;
1685   parser.opts.indent_step = -1;
1686   auto result =
1687       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1688   TEST_EQ(result, true);
1689   TEST_EQ_STR(jsongen.c_str(),
1690               "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1691               "\\u5225\\u30B5\\u30A4\\u30C8\\u20AC\\u0080\\uD83D\\uDE0E\"}");
1692 }
1693
1694 void UnicodeTestAllowNonUTF8() {
1695   flatbuffers::Parser parser;
1696   parser.opts.allow_non_utf8 = true;
1697   TEST_EQ(
1698       parser.Parse(
1699           "table T { F:string; }"
1700           "root_type T;"
1701           "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1702           "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"),
1703       true);
1704   std::string jsongen;
1705   parser.opts.indent_step = -1;
1706   auto result =
1707       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1708   TEST_EQ(result, true);
1709   TEST_EQ_STR(
1710       jsongen.c_str(),
1711       "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1712       "\\u5225\\u30B5\\u30A4\\u30C8\\u0001\\x80\\u0080\\uD83D\\uDE0E\"}");
1713 }
1714
1715 void UnicodeTestGenerateTextFailsOnNonUTF8() {
1716   flatbuffers::Parser parser;
1717   // Allow non-UTF-8 initially to model what happens when we load a binary
1718   // flatbuffer from disk which contains non-UTF-8 strings.
1719   parser.opts.allow_non_utf8 = true;
1720   TEST_EQ(
1721       parser.Parse(
1722           "table T { F:string; }"
1723           "root_type T;"
1724           "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC"
1725           "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"),
1726       true);
1727   std::string jsongen;
1728   parser.opts.indent_step = -1;
1729   // Now, disallow non-UTF-8 (the default behavior) so GenerateText indicates
1730   // failure.
1731   parser.opts.allow_non_utf8 = false;
1732   auto result =
1733       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1734   TEST_EQ(result, false);
1735 }
1736
1737 void UnicodeSurrogatesTest() {
1738   flatbuffers::Parser parser;
1739
1740   TEST_EQ(parser.Parse("table T { F:string (id: 0); }"
1741                        "root_type T;"
1742                        "{ F:\"\\uD83D\\uDCA9\"}"),
1743           true);
1744   auto root = flatbuffers::GetRoot<flatbuffers::Table>(
1745       parser.builder_.GetBufferPointer());
1746   auto string = root->GetPointer<flatbuffers::String *>(
1747       flatbuffers::FieldIndexToOffset(0));
1748   TEST_EQ_STR(string->c_str(), "\xF0\x9F\x92\xA9");
1749 }
1750
1751 void UnicodeInvalidSurrogatesTest() {
1752   TestError(
1753       "table T { F:string; }"
1754       "root_type T;"
1755       "{ F:\"\\uD800\"}",
1756       "unpaired high surrogate");
1757   TestError(
1758       "table T { F:string; }"
1759       "root_type T;"
1760       "{ F:\"\\uD800abcd\"}",
1761       "unpaired high surrogate");
1762   TestError(
1763       "table T { F:string; }"
1764       "root_type T;"
1765       "{ F:\"\\uD800\\n\"}",
1766       "unpaired high surrogate");
1767   TestError(
1768       "table T { F:string; }"
1769       "root_type T;"
1770       "{ F:\"\\uD800\\uD800\"}",
1771       "multiple high surrogates");
1772   TestError(
1773       "table T { F:string; }"
1774       "root_type T;"
1775       "{ F:\"\\uDC00\"}",
1776       "unpaired low surrogate");
1777 }
1778
1779 void InvalidUTF8Test() {
1780   // "1 byte" pattern, under min length of 2 bytes
1781   TestError(
1782       "table T { F:string; }"
1783       "root_type T;"
1784       "{ F:\"\x80\"}",
1785       "illegal UTF-8 sequence");
1786   // 2 byte pattern, string too short
1787   TestError(
1788       "table T { F:string; }"
1789       "root_type T;"
1790       "{ F:\"\xDF\"}",
1791       "illegal UTF-8 sequence");
1792   // 3 byte pattern, string too short
1793   TestError(
1794       "table T { F:string; }"
1795       "root_type T;"
1796       "{ F:\"\xEF\xBF\"}",
1797       "illegal UTF-8 sequence");
1798   // 4 byte pattern, string too short
1799   TestError(
1800       "table T { F:string; }"
1801       "root_type T;"
1802       "{ F:\"\xF7\xBF\xBF\"}",
1803       "illegal UTF-8 sequence");
1804   // "5 byte" pattern, string too short
1805   TestError(
1806       "table T { F:string; }"
1807       "root_type T;"
1808       "{ F:\"\xFB\xBF\xBF\xBF\"}",
1809       "illegal UTF-8 sequence");
1810   // "6 byte" pattern, string too short
1811   TestError(
1812       "table T { F:string; }"
1813       "root_type T;"
1814       "{ F:\"\xFD\xBF\xBF\xBF\xBF\"}",
1815       "illegal UTF-8 sequence");
1816   // "7 byte" pattern, string too short
1817   TestError(
1818       "table T { F:string; }"
1819       "root_type T;"
1820       "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\"}",
1821       "illegal UTF-8 sequence");
1822   // "5 byte" pattern, over max length of 4 bytes
1823   TestError(
1824       "table T { F:string; }"
1825       "root_type T;"
1826       "{ F:\"\xFB\xBF\xBF\xBF\xBF\"}",
1827       "illegal UTF-8 sequence");
1828   // "6 byte" pattern, over max length of 4 bytes
1829   TestError(
1830       "table T { F:string; }"
1831       "root_type T;"
1832       "{ F:\"\xFD\xBF\xBF\xBF\xBF\xBF\"}",
1833       "illegal UTF-8 sequence");
1834   // "7 byte" pattern, over max length of 4 bytes
1835   TestError(
1836       "table T { F:string; }"
1837       "root_type T;"
1838       "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\xBF\"}",
1839       "illegal UTF-8 sequence");
1840
1841   // Three invalid encodings for U+000A (\n, aka NEWLINE)
1842   TestError(
1843       "table T { F:string; }"
1844       "root_type T;"
1845       "{ F:\"\xC0\x8A\"}",
1846       "illegal UTF-8 sequence");
1847   TestError(
1848       "table T { F:string; }"
1849       "root_type T;"
1850       "{ F:\"\xE0\x80\x8A\"}",
1851       "illegal UTF-8 sequence");
1852   TestError(
1853       "table T { F:string; }"
1854       "root_type T;"
1855       "{ F:\"\xF0\x80\x80\x8A\"}",
1856       "illegal UTF-8 sequence");
1857
1858   // Two invalid encodings for U+00A9 (COPYRIGHT SYMBOL)
1859   TestError(
1860       "table T { F:string; }"
1861       "root_type T;"
1862       "{ F:\"\xE0\x81\xA9\"}",
1863       "illegal UTF-8 sequence");
1864   TestError(
1865       "table T { F:string; }"
1866       "root_type T;"
1867       "{ F:\"\xF0\x80\x81\xA9\"}",
1868       "illegal UTF-8 sequence");
1869
1870   // Invalid encoding for U+20AC (EURO SYMBOL)
1871   TestError(
1872       "table T { F:string; }"
1873       "root_type T;"
1874       "{ F:\"\xF0\x82\x82\xAC\"}",
1875       "illegal UTF-8 sequence");
1876
1877   // UTF-16 surrogate values between U+D800 and U+DFFF cannot be encoded in
1878   // UTF-8
1879   TestError(
1880       "table T { F:string; }"
1881       "root_type T;"
1882       // U+10400 "encoded" as U+D801 U+DC00
1883       "{ F:\"\xED\xA0\x81\xED\xB0\x80\"}",
1884       "illegal UTF-8 sequence");
1885
1886   // Check independence of identifier from locale.
1887   std::string locale_ident;
1888   locale_ident += "table T { F";
1889   locale_ident += static_cast<char>(-32); // unsigned 0xE0
1890   locale_ident += " :string; }";
1891   locale_ident += "root_type T;";
1892   locale_ident += "{}";
1893   TestError(locale_ident.c_str(), "");
1894 }
1895
1896 void UnknownFieldsTest() {
1897   flatbuffers::IDLOptions opts;
1898   opts.skip_unexpected_fields_in_json = true;
1899   flatbuffers::Parser parser(opts);
1900
1901   TEST_EQ(parser.Parse("table T { str:string; i:int;}"
1902                        "root_type T;"
1903                        "{ str:\"test\","
1904                        "unknown_string:\"test\","
1905                        "\"unknown_string\":\"test\","
1906                        "unknown_int:10,"
1907                        "unknown_float:1.0,"
1908                        "unknown_array: [ 1, 2, 3, 4],"
1909                        "unknown_object: { i: 10 },"
1910                        "\"unknown_object\": { \"i\": 10 },"
1911                        "i:10}"),
1912           true);
1913
1914   std::string jsongen;
1915   parser.opts.indent_step = -1;
1916   auto result =
1917       GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen);
1918   TEST_EQ(result, true);
1919   TEST_EQ_STR(jsongen.c_str(), "{str: \"test\",i: 10}");
1920 }
1921
1922 void ParseUnionTest() {
1923   // Unions must be parseable with the type field following the object.
1924   flatbuffers::Parser parser;
1925   TEST_EQ(parser.Parse("table T { A:int; }"
1926                        "union U { T }"
1927                        "table V { X:U; }"
1928                        "root_type V;"
1929                        "{ X:{ A:1 }, X_type: T }"),
1930           true);
1931   // Unions must be parsable with prefixed namespace.
1932   flatbuffers::Parser parser2;
1933   TEST_EQ(parser2.Parse("namespace N; table A {} namespace; union U { N.A }"
1934                         "table B { e:U; } root_type B;"
1935                         "{ e_type: N_A, e: {} }"),
1936           true);
1937 }
1938
1939 void UnionVectorTest() {
1940   // load FlatBuffer fbs schema.
1941   // TODO: load a JSON file with such a vector when JSON support is ready.
1942   std::string schemafile;
1943   TEST_EQ(flatbuffers::LoadFile(
1944               (test_data_path + "union_vector/union_vector.fbs").c_str(), false,
1945               &schemafile),
1946           true);
1947
1948   // parse schema.
1949   flatbuffers::IDLOptions idl_opts;
1950   idl_opts.lang_to_generate |= flatbuffers::IDLOptions::kCpp;
1951   flatbuffers::Parser parser(idl_opts);
1952   TEST_EQ(parser.Parse(schemafile.c_str()), true);
1953
1954   flatbuffers::FlatBufferBuilder fbb;
1955
1956   // union types.
1957   std::vector<uint8_t> types;
1958   types.push_back(static_cast<uint8_t>(Character_Belle));
1959   types.push_back(static_cast<uint8_t>(Character_MuLan));
1960   types.push_back(static_cast<uint8_t>(Character_BookFan));
1961   types.push_back(static_cast<uint8_t>(Character_Other));
1962   types.push_back(static_cast<uint8_t>(Character_Unused));
1963
1964   // union values.
1965   std::vector<flatbuffers::Offset<void>> characters;
1966   characters.push_back(fbb.CreateStruct(BookReader(/*books_read=*/7)).Union());
1967   characters.push_back(CreateAttacker(fbb, /*sword_attack_damage=*/5).Union());
1968   characters.push_back(fbb.CreateStruct(BookReader(/*books_read=*/2)).Union());
1969   characters.push_back(fbb.CreateString("Other").Union());
1970   characters.push_back(fbb.CreateString("Unused").Union());
1971
1972   // create Movie.
1973   const auto movie_offset =
1974       CreateMovie(fbb, Character_Rapunzel,
1975                   fbb.CreateStruct(Rapunzel(/*hair_length=*/6)).Union(),
1976                   fbb.CreateVector(types), fbb.CreateVector(characters));
1977   FinishMovieBuffer(fbb, movie_offset);
1978   auto buf = fbb.GetBufferPointer();
1979
1980   flatbuffers::Verifier verifier(buf, fbb.GetSize());
1981   TEST_EQ(VerifyMovieBuffer(verifier), true);
1982
1983   auto flat_movie = GetMovie(buf);
1984
1985   auto TestMovie = [](const Movie *movie) {
1986     TEST_EQ(movie->main_character_type() == Character_Rapunzel, true);
1987
1988     auto cts = movie->characters_type();
1989     TEST_EQ(movie->characters_type()->size(), 5);
1990     TEST_EQ(cts->GetEnum<Character>(0) == Character_Belle, true);
1991     TEST_EQ(cts->GetEnum<Character>(1) == Character_MuLan, true);
1992     TEST_EQ(cts->GetEnum<Character>(2) == Character_BookFan, true);
1993     TEST_EQ(cts->GetEnum<Character>(3) == Character_Other, true);
1994     TEST_EQ(cts->GetEnum<Character>(4) == Character_Unused, true);
1995
1996     auto rapunzel = movie->main_character_as_Rapunzel();
1997     TEST_EQ(rapunzel->hair_length(), 6);
1998
1999     auto cs = movie->characters();
2000     TEST_EQ(cs->size(), 5);
2001     auto belle = cs->GetAs<BookReader>(0);
2002     TEST_EQ(belle->books_read(), 7);
2003     auto mu_lan = cs->GetAs<Attacker>(1);
2004     TEST_EQ(mu_lan->sword_attack_damage(), 5);
2005     auto book_fan = cs->GetAs<BookReader>(2);
2006     TEST_EQ(book_fan->books_read(), 2);
2007     auto other = cs->GetAsString(3);
2008     TEST_EQ_STR(other->c_str(), "Other");
2009     auto unused = cs->GetAsString(4);
2010     TEST_EQ_STR(unused->c_str(), "Unused");
2011   };
2012
2013   TestMovie(flat_movie);
2014
2015   auto movie_object = flat_movie->UnPack();
2016   TEST_EQ(movie_object->main_character.AsRapunzel()->hair_length(), 6);
2017   TEST_EQ(movie_object->characters[0].AsBelle()->books_read(), 7);
2018   TEST_EQ(movie_object->characters[1].AsMuLan()->sword_attack_damage, 5);
2019   TEST_EQ(movie_object->characters[2].AsBookFan()->books_read(), 2);
2020   TEST_EQ_STR(movie_object->characters[3].AsOther()->c_str(), "Other");
2021   TEST_EQ_STR(movie_object->characters[4].AsUnused()->c_str(), "Unused");
2022
2023   fbb.Clear();
2024   fbb.Finish(Movie::Pack(fbb, movie_object));
2025
2026   delete movie_object;
2027
2028   auto repacked_movie = GetMovie(fbb.GetBufferPointer());
2029
2030   TestMovie(repacked_movie);
2031
2032   auto s =
2033       flatbuffers::FlatBufferToString(fbb.GetBufferPointer(), MovieTypeTable());
2034   TEST_EQ_STR(
2035       s.c_str(),
2036       "{ main_character_type: Rapunzel, main_character: { hair_length: 6 }, "
2037       "characters_type: [ Belle, MuLan, BookFan, Other, Unused ], "
2038       "characters: [ { books_read: 7 }, { sword_attack_damage: 5 }, "
2039       "{ books_read: 2 }, \"Other\", \"Unused\" ] }");
2040
2041
2042   flatbuffers::ToStringVisitor visitor("\n", true, "  ");
2043   IterateFlatBuffer(fbb.GetBufferPointer(), MovieTypeTable(), &visitor);
2044   TEST_EQ_STR(
2045       visitor.s.c_str(),
2046       "{\n"
2047       "  \"main_character_type\": \"Rapunzel\",\n"
2048       "  \"main_character\": {\n"
2049       "    \"hair_length\": 6\n"
2050       "  },\n"
2051       "  \"characters_type\": [\n"
2052       "    \"Belle\",\n"
2053       "    \"MuLan\",\n"
2054       "    \"BookFan\",\n"
2055       "    \"Other\",\n"
2056       "    \"Unused\"\n"
2057       "  ],\n"
2058       "  \"characters\": [\n"
2059       "    {\n"
2060       "      \"books_read\": 7\n"
2061       "    },\n"
2062       "    {\n"
2063       "      \"sword_attack_damage\": 5\n"
2064       "    },\n"
2065       "    {\n"
2066       "      \"books_read\": 2\n"
2067       "    },\n"
2068       "    \"Other\",\n"
2069       "    \"Unused\"\n"
2070       "  ]\n"
2071       "}");
2072 }
2073
2074 void ConformTest() {
2075   flatbuffers::Parser parser;
2076   TEST_EQ(parser.Parse("table T { A:int; } enum E:byte { A }"), true);
2077
2078   auto test_conform = [](flatbuffers::Parser &parser1, const char *test,
2079                          const char *expected_err) {
2080     flatbuffers::Parser parser2;
2081     TEST_EQ(parser2.Parse(test), true);
2082     auto err = parser2.ConformTo(parser1);
2083     TEST_NOTNULL(strstr(err.c_str(), expected_err));
2084   };
2085
2086   test_conform(parser, "table T { A:byte; }", "types differ for field");
2087   test_conform(parser, "table T { B:int; A:int; }", "offsets differ for field");
2088   test_conform(parser, "table T { A:int = 1; }", "defaults differ for field");
2089   test_conform(parser, "table T { B:float; }",
2090                "field renamed to different type");
2091   test_conform(parser, "enum E:byte { B, A }", "values differ for enum");
2092 }
2093
2094 void ParseProtoBufAsciiTest() {
2095   // We can put the parser in a mode where it will accept JSON that looks more
2096   // like Protobuf ASCII, for users that have data in that format.
2097   // This uses no "" for field names (which we already support by default,
2098   // omits `,`, `:` before `{` and a couple of other features.
2099   flatbuffers::Parser parser;
2100   parser.opts.protobuf_ascii_alike = true;
2101   TEST_EQ(
2102       parser.Parse("table S { B:int; } table T { A:[int]; C:S; } root_type T;"),
2103       true);
2104   TEST_EQ(parser.Parse("{ A [1 2] C { B:2 }}"), true);
2105   // Similarly, in text output, it should omit these.
2106   std::string text;
2107   auto ok = flatbuffers::GenerateText(
2108       parser, parser.builder_.GetBufferPointer(), &text);
2109   TEST_EQ(ok, true);
2110   TEST_EQ_STR(text.c_str(),
2111               "{\n  A [\n    1\n    2\n  ]\n  C {\n    B: 2\n  }\n}\n");
2112 }
2113
2114 void FlexBuffersTest() {
2115   flexbuffers::Builder slb(512,
2116                            flexbuffers::BUILDER_FLAG_SHARE_KEYS_AND_STRINGS);
2117
2118   // Write the equivalent of:
2119   // { vec: [ -100, "Fred", 4.0, false ], bar: [ 1, 2, 3 ], bar3: [ 1, 2, 3 ],
2120   // foo: 100, bool: true, mymap: { foo: "Fred" } }
2121   // clang-format off
2122   #ifndef FLATBUFFERS_CPP98_STL
2123     // It's possible to do this without std::function support as well.
2124     slb.Map([&]() {
2125        slb.Vector("vec", [&]() {
2126         slb += -100;  // Equivalent to slb.Add(-100) or slb.Int(-100);
2127         slb += "Fred";
2128         slb.IndirectFloat(4.0f);
2129         uint8_t blob[] = { 77 };
2130         slb.Blob(blob, 1);
2131         slb += false;
2132       });
2133       int ints[] = { 1, 2, 3 };
2134       slb.Vector("bar", ints, 3);
2135       slb.FixedTypedVector("bar3", ints, 3);
2136       bool bools[] = {true, false, true, false};
2137       slb.Vector("bools", bools, 4);
2138       slb.Bool("bool", true);
2139       slb.Double("foo", 100);
2140       slb.Map("mymap", [&]() {
2141         slb.String("foo", "Fred");  // Testing key and string reuse.
2142       });
2143     });
2144     slb.Finish();
2145   #else
2146     // It's possible to do this without std::function support as well.
2147     slb.Map([](flexbuffers::Builder& slb2) {
2148        slb2.Vector("vec", [](flexbuffers::Builder& slb3) {
2149         slb3 += -100;  // Equivalent to slb.Add(-100) or slb.Int(-100);
2150         slb3 += "Fred";
2151         slb3.IndirectFloat(4.0f);
2152         uint8_t blob[] = { 77 };
2153         slb3.Blob(blob, 1);
2154         slb3 += false;
2155       }, slb2);
2156       int ints[] = { 1, 2, 3 };
2157       slb2.Vector("bar", ints, 3);
2158       slb2.FixedTypedVector("bar3", ints, 3);
2159       slb2.Bool("bool", true);
2160       slb2.Double("foo", 100);
2161       slb2.Map("mymap", [](flexbuffers::Builder& slb3) {
2162         slb3.String("foo", "Fred");  // Testing key and string reuse.
2163       }, slb2);
2164     }, slb);
2165     slb.Finish();
2166   #endif  // FLATBUFFERS_CPP98_STL
2167
2168   #ifdef FLATBUFFERS_TEST_VERBOSE
2169     for (size_t i = 0; i < slb.GetBuffer().size(); i++)
2170       printf("%d ", flatbuffers::vector_data(slb.GetBuffer())[i]);
2171     printf("\n");
2172   #endif
2173   // clang-format on
2174
2175   auto map = flexbuffers::GetRoot(slb.GetBuffer()).AsMap();
2176   TEST_EQ(map.size(), 7);
2177   auto vec = map["vec"].AsVector();
2178   TEST_EQ(vec.size(), 5);
2179   TEST_EQ(vec[0].AsInt64(), -100);
2180   TEST_EQ_STR(vec[1].AsString().c_str(), "Fred");
2181   TEST_EQ(vec[1].AsInt64(), 0);  // Number parsing failed.
2182   TEST_EQ(vec[2].AsDouble(), 4.0);
2183   TEST_EQ(vec[2].AsString().IsTheEmptyString(), true);  // Wrong Type.
2184   TEST_EQ_STR(vec[2].AsString().c_str(), "");     // This still works though.
2185   TEST_EQ_STR(vec[2].ToString().c_str(), "4.0");  // Or have it converted.
2186
2187   // Few tests for templated version of As.
2188   TEST_EQ(vec[0].As<int64_t>(), -100);
2189   TEST_EQ_STR(vec[1].As<std::string>().c_str(), "Fred");
2190   TEST_EQ(vec[1].As<int64_t>(), 0);  // Number parsing failed.
2191   TEST_EQ(vec[2].As<double>(), 4.0);
2192
2193   // Test that the blob can be accessed.
2194   TEST_EQ(vec[3].IsBlob(), true);
2195   auto blob = vec[3].AsBlob();
2196   TEST_EQ(blob.size(), 1);
2197   TEST_EQ(blob.data()[0], 77);
2198   TEST_EQ(vec[4].IsBool(), true);   // Check if type is a bool
2199   TEST_EQ(vec[4].AsBool(), false);  // Check if value is false
2200   auto tvec = map["bar"].AsTypedVector();
2201   TEST_EQ(tvec.size(), 3);
2202   TEST_EQ(tvec[2].AsInt8(), 3);
2203   auto tvec3 = map["bar3"].AsFixedTypedVector();
2204   TEST_EQ(tvec3.size(), 3);
2205   TEST_EQ(tvec3[2].AsInt8(), 3);
2206   TEST_EQ(map["bool"].AsBool(), true);
2207   auto tvecb = map["bools"].AsTypedVector();
2208   TEST_EQ(tvecb.ElementType(), flexbuffers::FBT_BOOL);
2209   TEST_EQ(map["foo"].AsUInt8(), 100);
2210   TEST_EQ(map["unknown"].IsNull(), true);
2211   auto mymap = map["mymap"].AsMap();
2212   // These should be equal by pointer equality, since key and value are shared.
2213   TEST_EQ(mymap.Keys()[0].AsKey(), map.Keys()[4].AsKey());
2214   TEST_EQ(mymap.Values()[0].AsString().c_str(), vec[1].AsString().c_str());
2215   // We can mutate values in the buffer.
2216   TEST_EQ(vec[0].MutateInt(-99), true);
2217   TEST_EQ(vec[0].AsInt64(), -99);
2218   TEST_EQ(vec[1].MutateString("John"), true);  // Size must match.
2219   TEST_EQ_STR(vec[1].AsString().c_str(), "John");
2220   TEST_EQ(vec[1].MutateString("Alfred"), false);  // Too long.
2221   TEST_EQ(vec[2].MutateFloat(2.0f), true);
2222   TEST_EQ(vec[2].AsFloat(), 2.0f);
2223   TEST_EQ(vec[2].MutateFloat(3.14159), false);  // Double does not fit in float.
2224   TEST_EQ(vec[4].AsBool(), false);              // Is false before change
2225   TEST_EQ(vec[4].MutateBool(true), true);       // Can change a bool
2226   TEST_EQ(vec[4].AsBool(), true);               // Changed bool is now true
2227
2228   // Parse from JSON:
2229   flatbuffers::Parser parser;
2230   slb.Clear();
2231   auto jsontest = "{ a: [ 123, 456.0 ], b: \"hello\", c: true, d: false }";
2232   TEST_EQ(parser.ParseFlexBuffer(jsontest, nullptr, &slb), true);
2233   auto jroot = flexbuffers::GetRoot(slb.GetBuffer());
2234   auto jmap = jroot.AsMap();
2235   auto jvec = jmap["a"].AsVector();
2236   TEST_EQ(jvec[0].AsInt64(), 123);
2237   TEST_EQ(jvec[1].AsDouble(), 456.0);
2238   TEST_EQ_STR(jmap["b"].AsString().c_str(), "hello");
2239   TEST_EQ(jmap["c"].IsBool(), true);   // Parsed correctly to a bool
2240   TEST_EQ(jmap["c"].AsBool(), true);   // Parsed correctly to true
2241   TEST_EQ(jmap["d"].IsBool(), true);   // Parsed correctly to a bool
2242   TEST_EQ(jmap["d"].AsBool(), false);  // Parsed correctly to false
2243   // And from FlexBuffer back to JSON:
2244   auto jsonback = jroot.ToString();
2245   TEST_EQ_STR(jsontest, jsonback.c_str());
2246 }
2247
2248 void TypeAliasesTest() {
2249   flatbuffers::FlatBufferBuilder builder;
2250
2251   builder.Finish(CreateTypeAliases(
2252       builder, flatbuffers::numeric_limits<int8_t>::min(),
2253       flatbuffers::numeric_limits<uint8_t>::max(),
2254       flatbuffers::numeric_limits<int16_t>::min(),
2255       flatbuffers::numeric_limits<uint16_t>::max(),
2256       flatbuffers::numeric_limits<int32_t>::min(),
2257       flatbuffers::numeric_limits<uint32_t>::max(),
2258       flatbuffers::numeric_limits<int64_t>::min(),
2259       flatbuffers::numeric_limits<uint64_t>::max(), 2.3f, 2.3));
2260
2261   auto p = builder.GetBufferPointer();
2262   auto ta = flatbuffers::GetRoot<TypeAliases>(p);
2263
2264   TEST_EQ(ta->i8(), flatbuffers::numeric_limits<int8_t>::min());
2265   TEST_EQ(ta->u8(), flatbuffers::numeric_limits<uint8_t>::max());
2266   TEST_EQ(ta->i16(), flatbuffers::numeric_limits<int16_t>::min());
2267   TEST_EQ(ta->u16(), flatbuffers::numeric_limits<uint16_t>::max());
2268   TEST_EQ(ta->i32(), flatbuffers::numeric_limits<int32_t>::min());
2269   TEST_EQ(ta->u32(), flatbuffers::numeric_limits<uint32_t>::max());
2270   TEST_EQ(ta->i64(), flatbuffers::numeric_limits<int64_t>::min());
2271   TEST_EQ(ta->u64(), flatbuffers::numeric_limits<uint64_t>::max());
2272   TEST_EQ(ta->f32(), 2.3f);
2273   TEST_EQ(ta->f64(), 2.3);
2274   TEST_EQ(sizeof(ta->i8()), 1);
2275   TEST_EQ(sizeof(ta->i16()), 2);
2276   TEST_EQ(sizeof(ta->i32()), 4);
2277   TEST_EQ(sizeof(ta->i64()), 8);
2278   TEST_EQ(sizeof(ta->u8()), 1);
2279   TEST_EQ(sizeof(ta->u16()), 2);
2280   TEST_EQ(sizeof(ta->u32()), 4);
2281   TEST_EQ(sizeof(ta->u64()), 8);
2282   TEST_EQ(sizeof(ta->f32()), 4);
2283   TEST_EQ(sizeof(ta->f64()), 8);
2284 }
2285
2286 void EndianSwapTest() {
2287   TEST_EQ(flatbuffers::EndianSwap(static_cast<int16_t>(0x1234)), 0x3412);
2288   TEST_EQ(flatbuffers::EndianSwap(static_cast<int32_t>(0x12345678)),
2289           0x78563412);
2290   TEST_EQ(flatbuffers::EndianSwap(static_cast<int64_t>(0x1234567890ABCDEF)),
2291           0xEFCDAB9078563412);
2292   TEST_EQ(flatbuffers::EndianSwap(flatbuffers::EndianSwap(3.14f)), 3.14f);
2293 }
2294
2295 void UninitializedVectorTest() {
2296   flatbuffers::FlatBufferBuilder builder;
2297
2298   Test *buf = nullptr;
2299   auto vector_offset = builder.CreateUninitializedVectorOfStructs<Test>(2, &buf);
2300   TEST_NOTNULL(buf);
2301   buf[0] = Test(10, 20);
2302   buf[1] = Test(30, 40);
2303
2304   auto required_name = builder.CreateString("myMonster");
2305   auto monster_builder = MonsterBuilder(builder);
2306   monster_builder.add_name(required_name); // required field mandated for monster.
2307   monster_builder.add_test4(vector_offset);
2308   builder.Finish(monster_builder.Finish());
2309
2310   auto p = builder.GetBufferPointer();
2311   auto uvt = flatbuffers::GetRoot<Monster>(p);
2312   TEST_NOTNULL(uvt);
2313   auto vec = uvt->test4();
2314   TEST_NOTNULL(vec);
2315   auto test_0 = vec->Get(0);
2316   auto test_1 = vec->Get(1);
2317   TEST_EQ(test_0->a(), 10);
2318   TEST_EQ(test_0->b(), 20);
2319   TEST_EQ(test_1->a(), 30);
2320   TEST_EQ(test_1->b(), 40);
2321 }
2322
2323 void EqualOperatorTest() {
2324   MonsterT a;
2325   MonsterT b;
2326   TEST_EQ(b == a, true);
2327
2328   b.mana = 33;
2329   TEST_EQ(b == a, false);
2330   b.mana = 150;
2331   TEST_EQ(b == a, true);
2332
2333   b.inventory.push_back(3);
2334   TEST_EQ(b == a, false);
2335   b.inventory.clear();
2336   TEST_EQ(b == a, true);
2337
2338   b.test.type = Any_Monster;
2339   TEST_EQ(b == a, false);
2340 }
2341
2342 // For testing any binaries, e.g. from fuzzing.
2343 void LoadVerifyBinaryTest() {
2344   std::string binary;
2345   if (flatbuffers::LoadFile((test_data_path +
2346                              "fuzzer/your-filename-here").c_str(),
2347                             true, &binary)) {
2348     flatbuffers::Verifier verifier(
2349           reinterpret_cast<const uint8_t *>(binary.data()), binary.size());
2350     TEST_EQ(VerifyMonsterBuffer(verifier), true);
2351   }
2352 }
2353
2354 int FlatBufferTests() {
2355   // clang-format off
2356   #if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && \
2357       defined(_MSC_VER) && defined(_DEBUG)
2358     _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF
2359       // For more thorough checking:
2360       //| _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_DELAY_FREE_MEM_DF
2361     );
2362   #endif
2363
2364   // Run our various test suites:
2365
2366   std::string rawbuf;
2367   auto flatbuf1 = CreateFlatBufferTest(rawbuf);
2368   #if !defined(FLATBUFFERS_CPP98_STL)
2369     auto flatbuf = std::move(flatbuf1);  // Test move assignment.
2370   #else
2371     auto &flatbuf = flatbuf1;
2372   #endif // !defined(FLATBUFFERS_CPP98_STL)
2373
2374   TriviallyCopyableTest();
2375
2376   AccessFlatBufferTest(reinterpret_cast<const uint8_t *>(rawbuf.c_str()),
2377                        rawbuf.length());
2378   AccessFlatBufferTest(flatbuf.data(), flatbuf.size());
2379
2380   MutateFlatBuffersTest(flatbuf.data(), flatbuf.size());
2381
2382   ObjectFlatBuffersTest(flatbuf.data());
2383
2384   MiniReflectFlatBuffersTest(flatbuf.data());
2385
2386   SizePrefixedTest();
2387
2388   #ifndef FLATBUFFERS_NO_FILE_TESTS
2389     #ifdef FLATBUFFERS_TEST_PATH_PREFIX
2390       test_data_path = FLATBUFFERS_STRING(FLATBUFFERS_TEST_PATH_PREFIX) +
2391                        test_data_path;
2392     #endif
2393     ParseAndGenerateTextTest();
2394     ReflectionTest(flatbuf.data(), flatbuf.size());
2395     ParseProtoTest();
2396     UnionVectorTest();
2397     LoadVerifyBinaryTest();
2398   #endif
2399   // clang-format on
2400
2401   FuzzTest1();
2402   FuzzTest2();
2403
2404   ErrorTest();
2405   ValueTest();
2406   EnumStringsTest();
2407   EnumNamesTest();
2408   EnumOutOfRangeTest();
2409   IntegerOutOfRangeTest();
2410   IntegerBoundaryTest();
2411   UnicodeTest();
2412   UnicodeTestAllowNonUTF8();
2413   UnicodeTestGenerateTextFailsOnNonUTF8();
2414   UnicodeSurrogatesTest();
2415   UnicodeInvalidSurrogatesTest();
2416   InvalidUTF8Test();
2417   UnknownFieldsTest();
2418   ParseUnionTest();
2419   ConformTest();
2420   ParseProtoBufAsciiTest();
2421   TypeAliasesTest();
2422   EndianSwapTest();
2423   JsonDefaultTest();
2424   FlexBuffersTest();
2425   UninitializedVectorTest();
2426   EqualOperatorTest();
2427   NumericUtilsTest();
2428   IsAsciiUtilsTest();
2429   ValidFloatTest();
2430   InvalidFloatTest();
2431   return 0;
2432 }
2433
2434 int main(int /*argc*/, const char * /*argv*/ []) {
2435   InitTestEngine();
2436
2437   FlatBufferTests();
2438   FlatBufferBuilderTest();
2439
2440   if (!testing_fails) {
2441     TEST_OUTPUT_LINE("ALL TESTS PASSED");
2442     return 0;
2443   } else {
2444     TEST_OUTPUT_LINE("%d FAILED TESTS", testing_fails);
2445     return 1;
2446   }
2447 }