blob: 3c88b8dbd76ba5afe033776e7ece7306b4b7e960 [file] [log] [blame]
Ben Clayton648bd7b2022-09-02 11:40:19 +00001// Copyright 2022 The Tint Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "src/tint/reflection.h"
16#include "gtest/gtest.h"
17
18namespace tint {
19namespace {
20
21struct S {
22 int i;
23 unsigned u;
24 bool b;
25 TINT_REFLECT(i, u, b);
26};
27
28static_assert(!HasReflection<int>);
29static_assert(HasReflection<S>);
30
31TEST(ReflectionTest, ForeachFieldConst) {
32 const S s{1, 2, true};
33 size_t field_idx = 0;
34 ForeachField(s, [&](auto& field) {
35 using T = std::decay_t<decltype(field)>;
36 switch (field_idx) {
37 case 0:
38 EXPECT_TRUE((std::is_same_v<T, int>));
39 EXPECT_EQ(field, static_cast<T>(1));
40 break;
41 case 1:
42 EXPECT_TRUE((std::is_same_v<T, unsigned>));
43 EXPECT_EQ(field, static_cast<T>(2));
44 break;
45 case 2:
46 EXPECT_TRUE((std::is_same_v<T, bool>));
47 EXPECT_EQ(field, static_cast<T>(true));
48 break;
49 default:
50 FAIL() << "unexpected field";
51 break;
52 }
53 field_idx++;
54 });
55}
56
57TEST(ReflectionTest, ForeachFieldNonConst) {
58 S s{1, 2, true};
59 size_t field_idx = 0;
60 ForeachField(s, [&](auto& field) {
61 using T = std::decay_t<decltype(field)>;
62 switch (field_idx) {
63 case 0:
64 EXPECT_TRUE((std::is_same_v<T, int>));
65 EXPECT_EQ(field, static_cast<T>(1));
66 field = static_cast<T>(10);
67 break;
68 case 1:
69 EXPECT_TRUE((std::is_same_v<T, unsigned>));
70 EXPECT_EQ(field, static_cast<T>(2));
71 field = static_cast<T>(20);
72 break;
73 case 2:
74 EXPECT_TRUE((std::is_same_v<T, bool>));
75 EXPECT_EQ(field, static_cast<T>(true));
76 field = static_cast<T>(false);
77 break;
78 default:
79 FAIL() << "unexpected field";
80 break;
81 }
82 field_idx++;
83 });
84
85 EXPECT_EQ(s.i, 10);
86 EXPECT_EQ(s.u, 20u);
87 EXPECT_EQ(s.b, false);
88}
89
90} // namespace
91} // namespace tint