ec915ed56ed3b8ec286607a502bf4173854cc9d5
[folly.git] / folly / test / MapUtilTest.cpp
1 /*
2  * Copyright 2015 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_or_throw) {
33   std::map<int, int> m;
34   m[1] = 2;
35   EXPECT_EQ(2, get_or_throw(m, 1));
36   EXPECT_THROW(get_or_throw(m, 2), std::out_of_range);
37 }
38
39 TEST(MapUtil, get_or_throw_specified) {
40   std::map<int, int> m;
41   m[1] = 2;
42   EXPECT_EQ(2, get_or_throw<std::runtime_error>(m, 1));
43   EXPECT_THROW(get_or_throw<std::runtime_error>(m, 2), std::runtime_error);
44 }
45
46 TEST(MapUtil, get_optional) {
47   std::map<int, int> m;
48   m[1] = 2;
49   EXPECT_TRUE(get_optional(m, 1).hasValue());
50   EXPECT_EQ(2, get_optional(m, 1).value());
51   EXPECT_FALSE(get_optional(m, 2).hasValue());
52 }
53
54 TEST(MapUtil, get_ref_default) {
55   std::map<int, int> m;
56   m[1] = 2;
57   const int i = 42;
58   EXPECT_EQ(2, get_ref_default(m, 1, i));
59   EXPECT_EQ(42, get_ref_default(m, 2, i));
60 }
61
62 TEST(MapUtil, get_ptr) {
63   std::map<int, int> m;
64   m[1] = 2;
65   EXPECT_EQ(2, *get_ptr(m, 1));
66   EXPECT_TRUE(get_ptr(m, 2) == nullptr);
67   *get_ptr(m, 1) = 4;
68   EXPECT_EQ(4, m.at(1));
69 }