get_default and get_ref_default variants taking functions
[folly.git] / folly / test / MapUtilTest.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
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 #include <folly/MapUtil.h>
18
19 #include <map>
20 #include <gtest/gtest.h>
21
22 using namespace folly;
23
24 TEST(MapUtil, get_default) {
25   std::map<int, int> m;
26   m[1] = 2;
27   EXPECT_EQ(2, get_default(m, 1, 42));
28   EXPECT_EQ(42, get_default(m, 2, 42));
29   EXPECT_EQ(0, get_default(m, 3));
30 }
31
32 TEST(MapUtil, get_default_function) {
33   std::map<int, int> m;
34   m[1] = 2;
35   EXPECT_EQ(2, get_default(m, 1, [] { return 42; }));
36   EXPECT_EQ(42, get_default(m, 2, [] { return 42; }));
37   EXPECT_EQ(0, get_default(m, 3));
38 }
39
40 TEST(MapUtil, get_or_throw) {
41   std::map<int, int> m;
42   m[1] = 2;
43   EXPECT_EQ(2, get_or_throw(m, 1));
44   EXPECT_THROW(get_or_throw(m, 2), std::out_of_range);
45 }
46
47 TEST(MapUtil, get_or_throw_specified) {
48   std::map<int, int> m;
49   m[1] = 2;
50   EXPECT_EQ(2, get_or_throw<std::runtime_error>(m, 1));
51   EXPECT_THROW(get_or_throw<std::runtime_error>(m, 2), std::runtime_error);
52 }
53
54 TEST(MapUtil, get_optional) {
55   std::map<int, int> m;
56   m[1] = 2;
57   EXPECT_TRUE(get_optional(m, 1).hasValue());
58   EXPECT_EQ(2, get_optional(m, 1).value());
59   EXPECT_FALSE(get_optional(m, 2).hasValue());
60 }
61
62 TEST(MapUtil, get_ref_default) {
63   std::map<int, int> m;
64   m[1] = 2;
65   const int i = 42;
66   EXPECT_EQ(2, get_ref_default(m, 1, i));
67   EXPECT_EQ(42, get_ref_default(m, 2, i));
68   EXPECT_EQ(std::addressof(i), std::addressof(get_ref_default(m, 2, i)));
69 }
70
71 TEST(MapUtil, get_ref_default_function) {
72   std::map<int, int> m;
73   m[1] = 2;
74   const int i = 42;
75   EXPECT_EQ(2, get_ref_default(m, 1, [&i]() -> const int& { return i; }));
76   EXPECT_EQ(42, get_ref_default(m, 2, [&i]() -> const int& { return i; }));
77   EXPECT_EQ(
78       std::addressof(i),
79       std::addressof(
80           get_ref_default(m, 2, [&i]() -> const int& { return i; })));
81 }
82
83 TEST(MapUtil, get_ptr) {
84   std::map<int, int> m;
85   m[1] = 2;
86   EXPECT_EQ(2, *get_ptr(m, 1));
87   EXPECT_TRUE(get_ptr(m, 2) == nullptr);
88   *get_ptr(m, 1) = 4;
89   EXPECT_EQ(4, m.at(1));
90 }