blob: 0a137305d417738a8886270bba0464ef8d55a1e9 [file] [log] [blame]
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001// 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_TINT_UTILS_MAP_H_
16#define SRC_TINT_UTILS_MAP_H_
17
18#include <unordered_map>
19
dan sinclairfe4bfd42022-04-07 16:55:55 +000020namespace tint::utils {
Ryan Harrisondbc13af2022-02-21 15:19:07 +000021
22/// Lookup is a utility function for fetching a value from an unordered map if
23/// it exists, otherwise returning the `if_missing` argument.
24/// @param map the unordered_map
25/// @param key the map key of the item to query
26/// @param if_missing the value to return if the map does not contain the given
27/// key. Defaults to the zero-initializer for the value type.
28/// @return the map item value, or `if_missing` if the map does not contain the
29/// given key
30template <typename K, typename V, typename H, typename C, typename KV = K>
dan sinclair41e4d9a2022-05-01 14:40:55 +000031V Lookup(const std::unordered_map<K, V, H, C>& map, const KV& key, const V& if_missing = {}) {
32 auto it = map.find(key);
33 return it != map.end() ? it->second : if_missing;
Ryan Harrisondbc13af2022-02-21 15:19:07 +000034}
35
36/// GetOrCreate is a utility function for lazily adding to an unordered map.
37/// If the map already contains the key `key` then this is returned, otherwise
38/// `create()` is called and the result is added to the map and is returned.
39/// @param map the unordered_map
40/// @param key the map key of the item to query or add
41/// @param create a callable function-like object with the signature `V()`
42/// @return the value of the item with the given key, or the newly created item
43template <typename K, typename V, typename H, typename C, typename CREATE>
dan sinclair41e4d9a2022-05-01 14:40:55 +000044V GetOrCreate(std::unordered_map<K, V, H, C>& map, const K& key, CREATE&& create) {
45 auto it = map.find(key);
46 if (it != map.end()) {
47 return it->second;
48 }
49 V value = create();
50 map.emplace(key, value);
51 return value;
Ryan Harrisondbc13af2022-02-21 15:19:07 +000052}
53
dan sinclairfe4bfd42022-04-07 16:55:55 +000054} // namespace tint::utils
Ryan Harrisondbc13af2022-02-21 15:19:07 +000055
56#endif // SRC_TINT_UTILS_MAP_H_