2 * Copyright 2015 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 #ifndef FOLLY_MAPUTIL_H_
18 #define FOLLY_MAPUTIL_H_
20 #include <folly/Conv.h>
21 #include <folly/Optional.h>
26 * Given a map and a key, return the value corresponding to the key in the map,
27 * or a given default value if the key doesn't exist in the map.
30 typename Map::mapped_type get_default(
31 const Map& map, const typename Map::key_type& key,
32 const typename Map::mapped_type& dflt =
33 typename Map::mapped_type()) {
34 auto pos = map.find(key);
35 return (pos != map.end() ? pos->second : dflt);
39 * Given a map and a key, return the value corresponding to the key in the map,
40 * or throw an exception of the specified type.
42 template <class E = std::out_of_range, class Map>
43 typename Map::mapped_type get_or_throw(
44 const Map& map, const typename Map::key_type& key,
45 const std::string& exceptionStrPrefix = std::string()) {
46 auto pos = map.find(key);
47 if (pos != map.end()) {
50 throw E(folly::to<std::string>(exceptionStrPrefix, key));
54 * Given a map and a key, return a Optional<V> if the key exists and None if the
55 * key does not exist in the map.
58 folly::Optional<typename Map::mapped_type> get_optional(
59 const Map& map, const typename Map::key_type& key) {
60 auto pos = map.find(key);
61 if (pos != map.end()) {
62 return folly::Optional<typename Map::mapped_type>(pos->second);
69 * Given a map and a key, return a reference to the value corresponding to the
70 * key in the map, or the given default reference if the key doesn't exist in
74 const typename Map::mapped_type& get_ref_default(
75 const Map& map, const typename Map::key_type& key,
76 const typename Map::mapped_type& dflt) {
77 auto pos = map.find(key);
78 return (pos != map.end() ? pos->second : dflt);
82 * Given a map and a key, return a pointer to the value corresponding to the
83 * key in the map, or nullptr if the key doesn't exist in the map.
86 const typename Map::mapped_type* get_ptr(
87 const Map& map, const typename Map::key_type& key) {
88 auto pos = map.find(key);
89 return (pos != map.end() ? &pos->second : nullptr);
93 * Non-const overload of the above.
96 typename Map::mapped_type* get_ptr(
97 Map& map, const typename Map::key_type& key) {
98 auto pos = map.find(key);
99 return (pos != map.end() ? &pos->second : nullptr);
104 #endif /* FOLLY_MAPUTIL_H_ */