1 // Copyright 2014 The Chromium OS Authors. All rights reserved.
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 LIBBRILLO_BRILLO_MAP_UTILS_H_
6 #define LIBBRILLO_BRILLO_MAP_UTILS_H_
7
8 #include <map>
9 #include <set>
10 #include <utility>
11 #include <vector>
12
13 namespace brillo {
14
15 // Given an STL map, returns a set containing all keys from the map.
16 template<typename T>
GetMapKeys(const T & map)17 inline std::set<typename T::key_type> GetMapKeys(const T& map) {
18 std::set<typename T::key_type> keys;
19 for (const auto& pair : map)
20 keys.insert(keys.end(), pair.first); // Map keys are already sorted.
21 return keys;
22 }
23
24 // Given an STL map, returns a vector containing all keys from the map.
25 // The keys in the vector are sorted.
26 template<typename T>
GetMapKeysAsVector(const T & map)27 inline std::vector<typename T::key_type> GetMapKeysAsVector(const T& map) {
28 std::vector<typename T::key_type> keys;
29 keys.reserve(map.size());
30 for (const auto& pair : map)
31 keys.push_back(pair.first);
32 return keys;
33 }
34
35 // Given an STL map, returns a vector containing all values from the map.
36 template<typename T>
GetMapValues(const T & map)37 inline std::vector<typename T::mapped_type> GetMapValues(const T& map) {
38 std::vector<typename T::mapped_type> values;
39 values.reserve(map.size());
40 for (const auto& pair : map)
41 values.push_back(pair.second);
42 return values;
43 }
44
45 // Given an STL map, returns a vector of key-value pairs from the map.
46 template<typename T>
47 inline std::vector<std::pair<typename T::key_type, typename T::mapped_type>>
MapToVector(const T & map)48 MapToVector(const T& map) {
49 std::vector<std::pair<typename T::key_type, typename T::mapped_type>> vector;
50 vector.reserve(map.size());
51 for (const auto& pair : map)
52 vector.push_back(pair);
53 return vector;
54 }
55
56 // Given an STL map, returns the value associated with a given key or a default
57 // value if the key is not present in the map.
58 template<typename T>
GetOrDefault(const T & map,typename T::key_type key,const typename T::mapped_type & def)59 inline typename T::mapped_type GetOrDefault(
60 const T& map,
61 typename T::key_type key,
62 const typename T::mapped_type& def) {
63 typename T::const_iterator it = map.find(key);
64 if (it == map.end())
65 return def;
66 return it->second;
67 }
68
69 } // namespace brillo
70
71 #endif // LIBBRILLO_BRILLO_MAP_UTILS_H_
72