xref: /aosp_15_r20/external/flatbuffers/tests/cpp17/test_cpp17.cpp (revision 890232f25432b36107d06881e0a25aaa6b473652)
1 /*
2  * Copyright 2014 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // This is a sandbox for modeling C++17 code generator.
18 // C++17 code generator: "flatc --cpp-std c++17".
19 // Warning:
20 // This is an experimental feature and could change at any time.
21 
22 #include "flatbuffers/flatbuffers.h"
23 #include "flatbuffers/flex_flat_util.h"
24 #include "flatbuffers/flexbuffers.h"
25 #include "flatbuffers/idl.h"
26 #include "flatbuffers/minireflect.h"
27 #include "flatbuffers/registry.h"
28 #include "flatbuffers/util.h"
29 #include "stringify_util.h"
30 #include "test_assert.h"
31 
32 // Embed generated code into an isolated namespace.
33 namespace cpp17 {
34 #include "generated_cpp17/monster_test_generated.h"
35 #include "generated_cpp17/optional_scalars_generated.h"
36 #include "generated_cpp17/union_vector_generated.h"
37 }  // namespace cpp17
38 
39 namespace cpp11 {
40 #include "../monster_test_generated.h"
41 #include "../optional_scalars_generated.h"
42 }  // namespace cpp11
43 
44 using ::cpp17::MyGame::Example::Monster;
45 using ::cpp17::MyGame::Example::Vec3;
46 
47 /*******************************************************************************
48 ** Build some FB objects.
49 *******************************************************************************/
50 namespace {
BuildMonster(flatbuffers::FlatBufferBuilder & fbb)51 const Monster *BuildMonster(flatbuffers::FlatBufferBuilder &fbb) {
52   using ::cpp17::MyGame::Example::Color;
53   using ::cpp17::MyGame::Example::MonsterBuilder;
54   using ::cpp17::MyGame::Example::Test;
55   auto name = fbb.CreateString("my_monster");
56   auto inventory = fbb.CreateVector(std::vector<uint8_t>{ 4, 5, 6, 7 });
57   MonsterBuilder builder(fbb);
58   auto vec3 = Vec3{ /*x=*/1.1f,
59                     /*y=*/2.2f,
60                     /*z=*/3.3f,
61                     /*test1=*/6.6,
62                     /*test2=*/Color::Green,
63                     /*test3=*/
64                     Test(
65                         /*a=*/11,
66                         /*b=*/90) };
67   builder.add_pos(&vec3);
68   builder.add_name(name);
69   builder.add_mana(1);
70   builder.add_hp(2);
71   builder.add_testbool(true);
72   builder.add_testhashs32_fnv1(4);
73   builder.add_testhashu32_fnv1(5);
74   builder.add_testhashs64_fnv1(6);
75   builder.add_testhashu64_fnv1(7);
76   builder.add_testhashs32_fnv1a(8);
77   builder.add_testhashu32_fnv1a(9);
78   builder.add_testhashs64_fnv1a(10);
79   builder.add_testhashu64_fnv1a(11);
80   builder.add_testf(12.1f);
81   builder.add_testf2(13.1f);
82   builder.add_testf3(14.1f);
83   builder.add_single_weak_reference(15);
84   builder.add_co_owning_reference(16);
85   builder.add_non_owning_reference(17);
86   builder.add_inventory(inventory);
87   fbb.Finish(builder.Finish());
88   const Monster *monster =
89       flatbuffers::GetRoot<Monster>(fbb.GetBufferPointer());
90   return monster;
91 }
92 
93 /*******************************************************************************
94 ** Test Case: Static Field Reflection Traits for Table & Structs.
95 *******************************************************************************/
96 // This test tests & demonstrates the power of the static reflection. Using it,
97 // we can given any Flatbuffer type to a generic function and it will be able to
98 // produce is full recursive string representation of it.
99 //
100 // This test covers all types: primitive types, structs, tables, Vectors, etc.
101 //
StringifyAnyFlatbuffersTypeTest()102 void StringifyAnyFlatbuffersTypeTest() {
103   flatbuffers::FlatBufferBuilder fbb;
104   // We are using a Monster here, but we could have used any type, because the
105   // code that follows is totally generic!
106   const auto *monster = BuildMonster(fbb);
107 
108   std::string expected = R"(MyGame.Example.Monster{
109         pos = MyGame.Example.Vec3{
110           x = 1.1
111           y = 2.2
112           z = 3.3
113           test1 = 6.6
114           test2 = 2
115           test3 = MyGame.Example.Test{
116             a = 11
117             b = 90
118           }
119         }
120         mana = 1
121         hp = 2
122         name = "my_monster"
123         inventory = [
124           4,
125           5,
126           6,
127           7
128         ]
129         color = 8
130         test_type = 0
131         testbool = 1
132         testhashs32_fnv1 = 4
133         testhashu32_fnv1 = 5
134         testhashs64_fnv1 = 6
135         testhashu64_fnv1 = 7
136         testhashs32_fnv1a = 8
137         testhashu32_fnv1a = 9
138         testhashs64_fnv1a = 10
139         testhashu64_fnv1a = 11
140         testf = 12.1
141         testf2 = 13.1
142         testf3 = 14.1
143         single_weak_reference = 15
144         co_owning_reference = 16
145         non_owning_reference = 17
146         any_unique_type = 0
147         any_ambiguous_type = 0
148         signed_enum = -1
149       })";
150 
151   // Call a generic function that has no specific knowledge of the flatbuffer we
152   // are passing in; it should use only static reflection to produce a string
153   // representations of the field names and values recursively. We give it an
154   // initial indentation so that the result can be compared with our raw string
155   // above, which we wanted to indent so that it will look nicer in this code.
156   //
157   // A note about JSON: as can be seen from the string above, this produces a
158   // JSON-like notation, but we are not using any of Flatbuffers' JSON infra to
159   // produce this! It is produced entirely using compile-time reflection, and
160   // thus does not require any runtime access to the *.fbs definition files!
161   std::optional<std::string> result =
162       cpp17::StringifyFlatbufferValue(*monster, /*indent=*/"      ");
163 
164   TEST_ASSERT(result.has_value());
165   TEST_EQ_STR(expected.c_str(), result->c_str());
166 }
167 
168 /*******************************************************************************
169 ** Test Traits::FieldType
170 *******************************************************************************/
171 using pos_type = Monster::Traits::FieldType<0>;
172 static_assert(std::is_same_v<pos_type, const Vec3 *>);
173 
174 using mana_type = Monster::Traits::FieldType<1>;
175 static_assert(std::is_same_v<mana_type, int16_t>);
176 
177 using name_type = Monster::Traits::FieldType<3>;
178 static_assert(std::is_same_v<name_type, const flatbuffers::String *>);
179 
180 /*******************************************************************************
181 ** Generic Create Function Test.
182 *******************************************************************************/
CreateTableByTypeTest()183 void CreateTableByTypeTest() {
184   flatbuffers::FlatBufferBuilder builder;
185 
186   // We will create an object of this type using only the type.
187   using type_to_create_t = cpp17::MyGame::Example::Stat;
188 
189   [&builder] {
190     auto id_str = builder.CreateString("my_id");
191     auto table = type_to_create_t::Traits::Create(builder, id_str, 42, 7);
192     // Be sure that the correct return type was inferred.
193     static_assert(
194         std::is_same_v<decltype(table), flatbuffers::Offset<type_to_create_t>>);
195     builder.Finish(table);
196   }();
197 
198   // Access it.
199   auto stat =
200       flatbuffers::GetRoot<type_to_create_t>(builder.GetBufferPointer());
201   TEST_EQ_STR(stat->id()->c_str(), "my_id");
202   TEST_EQ(stat->val(), 42);
203   TEST_EQ(stat->count(), 7);
204 }
205 
OptionalScalarsTest()206 void OptionalScalarsTest() {
207   static_assert(
208       std::is_same<flatbuffers::Optional<float>, std::optional<float>>::value);
209   static_assert(std::is_same<flatbuffers::nullopt_t, std::nullopt_t>::value);
210 
211   // test C++ nullable
212   flatbuffers::FlatBufferBuilder fbb;
213   FinishScalarStuffBuffer(fbb, cpp17::optional_scalars::CreateScalarStuff(
214                                    fbb, 1, static_cast<int8_t>(2)));
215   auto opts =
216       cpp17::optional_scalars::GetMutableScalarStuff(fbb.GetBufferPointer());
217   TEST_ASSERT(!opts->maybe_bool());
218   TEST_ASSERT(!opts->maybe_f32().has_value());
219   TEST_ASSERT(opts->maybe_i8().has_value());
220   TEST_EQ(opts->maybe_i8().value(), 2);
221   TEST_ASSERT(opts->mutate_maybe_i8(3));
222   TEST_ASSERT(opts->maybe_i8().has_value());
223   TEST_EQ(opts->maybe_i8().value(), 3);
224   TEST_ASSERT(!opts->mutate_maybe_i16(-10));
225 
226   cpp17::optional_scalars::ScalarStuffT obj;
227   opts->UnPackTo(&obj);
228   TEST_ASSERT(!obj.maybe_bool);
229   TEST_ASSERT(!obj.maybe_f32.has_value());
230   TEST_ASSERT(obj.maybe_i8.has_value() && obj.maybe_i8.value() == 3);
231   TEST_ASSERT(obj.maybe_i8 && *obj.maybe_i8 == 3);
232   obj.maybe_i32 = -1;
233 
234   fbb.Clear();
235   FinishScalarStuffBuffer(
236       fbb, cpp17::optional_scalars::ScalarStuff::Pack(fbb, &obj));
237   opts = cpp17::optional_scalars::GetMutableScalarStuff(fbb.GetBufferPointer());
238   TEST_ASSERT(opts->maybe_i8().has_value());
239   TEST_EQ(opts->maybe_i8().value(), 3);
240   TEST_ASSERT(opts->maybe_i32().has_value());
241   TEST_EQ(opts->maybe_i32().value(), -1);
242 
243   TEST_EQ(std::optional<int32_t>(opts->maybe_i32()).value(), -1);
244   TEST_EQ(std::optional<int64_t>(opts->maybe_i32()).value(), -1);
245   TEST_ASSERT(opts->maybe_i32() == std::optional<int64_t>(-1));
246 }
247 
FlatBufferCpp17Tests()248 int FlatBufferCpp17Tests() {
249   CreateTableByTypeTest();
250   OptionalScalarsTest();
251   StringifyAnyFlatbuffersTypeTest();
252   return 0;
253 }
254 } // namespace
255 
main(int,const char * [])256 int main(int /*argc*/, const char * /*argv*/[]) {
257   InitTestEngine();
258 
259   FlatBufferCpp17Tests();
260 
261   if (!testing_fails) {
262     TEST_OUTPUT_LINE("C++17: ALL TESTS PASSED");
263   } else {
264     TEST_OUTPUT_LINE("C++17: %d FAILED TESTS", testing_fails);
265   }
266   return CloseTestEngine();
267 }
268