1 // Copyright 2021 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/utils/map.h"
16
17 #include <unordered_map>
18
19 #include "gtest/gtest.h"
20
21 namespace tint {
22 namespace utils {
23 namespace {
24
TEST(Lookup,Test)25 TEST(Lookup, Test) {
26 std::unordered_map<int, int> map;
27 map.emplace(10, 1);
28 EXPECT_EQ(Lookup(map, 10, 0), 1); // exists, with if_missing
29 EXPECT_EQ(Lookup(map, 10), 1); // exists, without if_missing
30 EXPECT_EQ(Lookup(map, 20, 50), 50); // missing, with if_missing
31 EXPECT_EQ(Lookup(map, 20), 0); // missing, without if_missing
32 }
33
TEST(GetOrCreateTest,NewKey)34 TEST(GetOrCreateTest, NewKey) {
35 std::unordered_map<int, int> map;
36 EXPECT_EQ(GetOrCreate(map, 1, [&] { return 2; }), 2);
37 EXPECT_EQ(map.size(), 1u);
38 EXPECT_EQ(map[1], 2);
39 }
40
TEST(GetOrCreateTest,ExistingKey)41 TEST(GetOrCreateTest, ExistingKey) {
42 std::unordered_map<int, int> map;
43 map[1] = 2;
44 bool called = false;
45 EXPECT_EQ(GetOrCreate(map, 1,
46 [&] {
47 called = true;
48 return -2;
49 }),
50 2);
51 EXPECT_EQ(called, false);
52 EXPECT_EQ(map.size(), 1u);
53 EXPECT_EQ(map[1], 2);
54 }
55
56 } // namespace
57 } // namespace utils
58 } // namespace tint
59