1 // Copyright 2021 The Tint Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef SRC_UTILS_MAP_H_
16 #define SRC_UTILS_MAP_H_
17
18 #include <unordered_map>
19
20 namespace tint {
21 namespace utils {
22
23 /// Lookup is a utility function for fetching a value from an unordered map if
24 /// it exists, otherwise returning the `if_missing` argument.
25 /// @param map the unordered_map
26 /// @param key the map key of the item to query
27 /// @param if_missing the value to return if the map does not contain the given
28 /// key. Defaults to the zero-initializer for the value type.
29 /// @return the map item value, or `if_missing` if the map does not contain the
30 /// given key
31 template <typename K, typename V, typename H, typename C, typename KV = K>
32 V Lookup(std::unordered_map<K, V, H, C>& map,
33 const KV& key,
34 const KV& if_missing = {}) {
35 auto it = map.find(key);
36 return it != map.end() ? it->second : if_missing;
37 }
38
39 /// GetOrCreate is a utility function for lazily adding to an unordered map.
40 /// If the map already contains the key `key` then this is returned, otherwise
41 /// `create()` is called and the result is added to the map and is returned.
42 /// @param map the unordered_map
43 /// @param key the map key of the item to query or add
44 /// @param create a callable function-like object with the signature `V()`
45 /// @return the value of the item with the given key, or the newly created item
46 template <typename K, typename V, typename H, typename C, typename CREATE>
GetOrCreate(std::unordered_map<K,V,H,C> & map,const K & key,CREATE && create)47 V GetOrCreate(std::unordered_map<K, V, H, C>& map,
48 const K& key,
49 CREATE&& create) {
50 auto it = map.find(key);
51 if (it != map.end()) {
52 return it->second;
53 }
54 V value = create();
55 map.emplace(key, value);
56 return value;
57 }
58
59 } // namespace utils
60 } // namespace tint
61
62 #endif // SRC_UTILS_MAP_H_
63