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