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