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