1 // Copyright 2023 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef BASE_CONTAINERS_MAP_UTIL_H_
6 #define BASE_CONTAINERS_MAP_UTIL_H_
7
8 #include <memory>
9
10 namespace base {
11
12 namespace internal {
13
14 template <typename Map>
15 using MappedType = typename Map::mapped_type;
16
17 } // namespace internal
18
19 // Returns a pointer to the const value associated with the given key if it
20 // exists, or null otherwise.
21 template <typename Map, typename Key>
FindOrNull(const Map & map,const Key & key)22 constexpr const internal::MappedType<Map>* FindOrNull(const Map& map,
23 const Key& key) {
24 auto it = map.find(key);
25 return it != map.end() ? &it->second : nullptr;
26 }
27
28 // Returns a pointer to the value associated with the given key if it exists, or
29 // null otherwise.
30 template <typename Map, typename Key>
FindOrNull(Map & map,const Key & key)31 constexpr internal::MappedType<Map>* FindOrNull(Map& map, const Key& key) {
32 auto it = map.find(key);
33 return it != map.end() ? &it->second : nullptr;
34 }
35
36 // Returns the const pointer value associated with the given key. If none is
37 // found, null is returned. The function is designed to be used with a map of
38 // keys to pointers or smart pointers.
39 //
40 // This function does not distinguish between a missing key and a key mapped
41 // to a null value.
42 template <typename Map,
43 typename Key,
44 typename MappedElementType =
45 std::pointer_traits<internal::MappedType<Map>>::element_type>
FindPtrOrNull(const Map & map,const Key & key)46 constexpr const MappedElementType* FindPtrOrNull(const Map& map,
47 const Key& key) {
48 auto it = map.find(key);
49 return it != map.end() ? std::to_address(it->second) : nullptr;
50 }
51
52 // Returns the pointer value associated with the given key. If none is found,
53 // null is returned. The function is designed to be used with a map of keys to
54 // pointers or smart pointers.
55 //
56 // This function does not distinguish between a missing key and a key mapped
57 // to a null value.
58 template <typename Map,
59 typename Key,
60 typename MappedElementType =
61 std::pointer_traits<internal::MappedType<Map>>::element_type>
FindPtrOrNull(Map & map,const Key & key)62 constexpr MappedElementType* FindPtrOrNull(Map& map, const Key& key) {
63 auto it = map.find(key);
64 return it != map.end() ? std::to_address(it->second) : nullptr;
65 }
66
67 } // namespace base
68
69 #endif // BASE_CONTAINERS_MAP_UTIL_H_
70