2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/MapUtil.h>
21 #include <folly/portability/GTest.h>
23 using namespace folly;
25 TEST(MapUtil, get_default) {
28 EXPECT_EQ(2, get_default(m, 1, 42));
29 EXPECT_EQ(42, get_default(m, 2, 42));
30 EXPECT_EQ(0, get_default(m, 3));
33 TEST(MapUtil, get_default_function) {
36 EXPECT_EQ(2, get_default(m, 1, [] { return 42; }));
37 EXPECT_EQ(42, get_default(m, 2, [] { return 42; }));
38 EXPECT_EQ(0, get_default(m, 3));
41 TEST(MapUtil, get_or_throw) {
44 EXPECT_EQ(2, get_or_throw(m, 1));
45 EXPECT_THROW(get_or_throw(m, 2), std::out_of_range);
46 EXPECT_EQ(&m[1], &get_or_throw(m, 1));
47 get_or_throw(m, 1) = 3;
48 EXPECT_EQ(3, get_or_throw(m, 1));
50 EXPECT_EQ(&m[1], &get_or_throw(cm, 1));
51 EXPECT_EQ(3, get_or_throw(cm, 1));
52 EXPECT_THROW(get_or_throw(cm, 2), std::out_of_range);
55 TEST(MapUtil, get_or_throw_specified) {
58 EXPECT_EQ(2, get_or_throw<std::runtime_error>(m, 1));
59 EXPECT_THROW(get_or_throw<std::runtime_error>(m, 2), std::runtime_error);
62 TEST(MapUtil, get_optional) {
65 EXPECT_TRUE(get_optional(m, 1).hasValue());
66 EXPECT_EQ(2, get_optional(m, 1).value());
67 EXPECT_FALSE(get_optional(m, 2).hasValue());
70 TEST(MapUtil, get_ref_default) {
74 EXPECT_EQ(2, get_ref_default(m, 1, i));
75 EXPECT_EQ(42, get_ref_default(m, 2, i));
76 EXPECT_EQ(std::addressof(i), std::addressof(get_ref_default(m, 2, i)));
79 TEST(MapUtil, get_ref_default_function) {
83 EXPECT_EQ(2, get_ref_default(m, 1, [&i]() -> const int& { return i; }));
84 EXPECT_EQ(42, get_ref_default(m, 2, [&i]() -> const int& { return i; }));
88 get_ref_default(m, 2, [&i]() -> const int& { return i; })));
89 // statically disallowed:
90 // get_ref_default(m, 2, [] { return 7; });
93 TEST(MapUtil, get_ptr) {
96 EXPECT_EQ(2, *get_ptr(m, 1));
97 EXPECT_TRUE(get_ptr(m, 2) == nullptr);
99 EXPECT_EQ(4, m.at(1));