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 #include "base/types/to_address.h"
11
12 namespace base {
13
14 namespace internal {
15
16 template <typename Map>
17 using MappedType = typename Map::mapped_type;
18
19 } // namespace internal
20
21 // Returns a pointer to the const value associated with the given key if it
22 // exists, or null otherwise.
23 template <typename Map, typename Key>
FindOrNull(const Map & map,const Key & key)24 constexpr const internal::MappedType<Map>* FindOrNull(const Map& map,
25 const Key& key) {
26 auto it = map.find(key);
27 return it != map.end() ? &it->second : nullptr;
28 }
29
30 // Returns a pointer to the value associated with the given key if it exists, or
31 // null otherwise.
32 template <typename Map, typename Key>
FindOrNull(Map & map,const Key & key)33 constexpr internal::MappedType<Map>* FindOrNull(Map& map, const Key& key) {
34 auto it = map.find(key);
35 return it != map.end() ? &it->second : nullptr;
36 }
37
38 // Returns the const pointer value associated with the given key. If none is
39 // found, null is returned. The function is designed to be used with a map of
40 // keys to pointers or smart pointers.
41 //
42 // This function does not distinguish between a missing key and a key mapped
43 // to a null value.
44 template <typename Map,
45 typename Key,
46 typename MappedElementType =
47 std::pointer_traits<internal::MappedType<Map>>::element_type>
FindPtrOrNull(const Map & map,const Key & key)48 constexpr const MappedElementType* FindPtrOrNull(const Map& map,
49 const Key& key) {
50 auto it = map.find(key);
51 return it != map.end() ? base::to_address(it->second) : nullptr;
52 }
53
54 // Returns the pointer value associated with the given key. If none is found,
55 // null is returned. The function is designed to be used with a map of keys to
56 // pointers or smart pointers.
57 //
58 // This function does not distinguish between a missing key and a key mapped
59 // to a null value.
60 template <typename Map,
61 typename Key,
62 typename MappedElementType =
63 std::pointer_traits<internal::MappedType<Map>>::element_type>
FindPtrOrNull(Map & map,const Key & key)64 constexpr MappedElementType* FindPtrOrNull(Map& map, const Key& key) {
65 auto it = map.find(key);
66 return it != map.end() ? base::to_address(it->second) : nullptr;
67 }
68
69 } // namespace base
70
71 #endif // BASE_CONTAINERS_MAP_UTIL_H_
72