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