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