• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "alignment_test.h"
2 
3 #include "tests/alignment_test_generated.h"
4 #include "flatbuffers/flatbuffer_builder.h"
5 #include "flatbuffers/util.h"
6 #include "test_assert.h"
7 
8 namespace flatbuffers {
9 namespace tests {
10 
AlignmentTest()11 void AlignmentTest() {
12   FlatBufferBuilder builder;
13 
14   BadAlignmentLarge large;
15   Offset<OuterLarge> outer_large = CreateOuterLarge(builder, &large);
16 
17   BadAlignmentSmall *small;
18   Offset<Vector<const BadAlignmentSmall *>> small_offset =
19       builder.CreateUninitializedVectorOfStructs(9, &small);
20   (void)small;  // We do not have to write data to trigger the test failure
21 
22   Offset<BadAlignmentRoot> root =
23       CreateBadAlignmentRoot(builder, outer_large, small_offset);
24 
25   builder.Finish(root);
26 
27   Verifier verifier(builder.GetBufferPointer(), builder.GetSize());
28   TEST_ASSERT(verifier.VerifyBuffer<BadAlignmentRoot>(nullptr));
29 
30 
31   // ============= Test Small Structs Vector misalignment ========
32 
33   builder.Clear();
34 
35   // creating 5 structs with 2 bytes each
36   // 10 bytes in total for Vector data is needed
37   std::vector<JustSmallStruct> small_vector = {
38     { 2, 1 }, { 3, 1 }, { 4, 1 }
39   };
40   // CreateVectorOfStructs is used in the generated CreateSmallStructsDirect()
41   // method, but we test it directly
42   Offset<Vector<const JustSmallStruct *>> small_structs_offset =
43       builder.CreateVectorOfStructs<JustSmallStruct>(small_vector);
44   Offset<SmallStructs> small_structs_root =
45       CreateSmallStructs(builder, small_structs_offset);
46 
47   builder.Finish(small_structs_root);
48 
49   // Save the binary that we later can annotate with `flatc --annotate` command
50   // NOTE: the conversion of the JSON data to --binary via `flatc --binary`
51   //       command is not changed with that fix and was always producing the
52   //       correct binary data.
53   // SaveFile("alignment_test_{before,after}_fix.bin",
54   //          reinterpret_cast<char *>(builder.GetBufferPointer()),
55   //          builder.GetSize(), true);
56 
57   Verifier verifier_small_structs(builder.GetBufferPointer(),
58                                   builder.GetSize());
59   TEST_ASSERT(verifier_small_structs.VerifyBuffer<SmallStructs>(nullptr));
60 
61   // Reading SmallStructs vector values back and compare with original
62   auto root_msg =
63       flatbuffers::GetRoot<SmallStructs>(builder.GetBufferPointer());
64 
65   TEST_EQ(root_msg->small_structs()->size(), small_vector.size());
66   for (flatbuffers::uoffset_t i = 0; i < root_msg->small_structs()->size();
67        ++i) {
68     TEST_EQ(small_vector[i].var_0(),
69             root_msg->small_structs()->Get(i)->var_0());
70     TEST_EQ(small_vector[i].var_1(),
71             root_msg->small_structs()->Get(i)->var_1());
72   }
73 }
74 
75 }  // namespace tests
76 }  // namespace flatbuffers
77