remove eof whitespace lines
[folly.git] / folly / MapUtil.h
1 /*
2  * Copyright 2014 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 #ifndef FOLLY_MAPUTIL_H_
18 #define FOLLY_MAPUTIL_H_
19
20 namespace folly {
21
22 /**
23  * Given a map and a key, return the value corresponding to the key in the map,
24  * or a given default value if the key doesn't exist in the map.
25  */
26 template <class Map>
27 typename Map::mapped_type get_default(
28     const Map& map, const typename Map::key_type& key,
29     const typename Map::mapped_type& dflt =
30     typename Map::mapped_type()) {
31   auto pos = map.find(key);
32   return (pos != map.end() ? pos->second : dflt);
33 }
34
35 /**
36  * Given a map and a key, return a reference to the value corresponding to the
37  * key in the map, or the given default reference if the key doesn't exist in
38  * the map.
39  */
40 template <class Map>
41 const typename Map::mapped_type& get_ref_default(
42     const Map& map, const typename Map::key_type& key,
43     const typename Map::mapped_type& dflt) {
44   auto pos = map.find(key);
45   return (pos != map.end() ? pos->second : dflt);
46 }
47
48 /**
49  * Given a map and a key, return a pointer to the value corresponding to the
50  * key in the map, or nullptr if the key doesn't exist in the map.
51  */
52 template <class Map>
53 const typename Map::mapped_type* get_ptr(
54     const Map& map, const typename Map::key_type& key) {
55   auto pos = map.find(key);
56   return (pos != map.end() ? &pos->second : nullptr);
57 }
58
59 /**
60  * Non-const overload of the above.
61  */
62 template <class Map>
63 typename Map::mapped_type* get_ptr(
64     Map& map, const typename Map::key_type& key) {
65   auto pos = map.find(key);
66   return (pos != map.end() ? &pos->second : nullptr);
67 }
68
69 }  // namespace folly
70
71 #endif /* FOLLY_MAPUTIL_H_ */