forked from facebook/watchman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MapUtil.h
55 lines (48 loc) · 1.82 KB
/
MapUtil.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* Copyright 2016-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#pragma once
#include <utility>
namespace watchman {
// Remove key from the map. Returns true if any keys were removed.
template <typename Map, typename Key>
bool mapRemove(Map& map, Key& key) {
return map.erase(key) > 0;
}
// Inserts Key->Value mapping if Key is not already present.
// Returns a boolean indicating whether insertion happened.
template <typename Map, typename Key, typename Value>
bool mapInsert(Map& map, const Key& key, const Value& value) {
auto pair = map.insert(std::make_pair(key, value));
return pair.second;
}
// Returns true if the map contains any of the passed keys
template <typename Map, typename Key>
bool mapContainsAny(const Map& map, const Key& key) {
return map.find(key) != map.end();
}
// Returns true if the map contains any of the passed keys
template <typename Map, typename Key, typename... Args>
bool mapContainsAny(const Map& map, const Key& firstKey, Args... args) {
return mapContainsAny(map, firstKey) || mapContainsAny(map, args...);
}
// Returns true if the map contains any of a list of passed keys
template <typename Map, typename Iterator>
bool mapContainsAnyOf(const Map& map, Iterator first, Iterator last) {
for (auto it = first; it != last; ++it) {
if (map.find(*it) != map.end()) {
return true;
}
}
return false;
}
// Returns Map[Key] or if it isn't present, returns a default value.
// if the default isn't specified, returns a default-constructed value.
template <class Map, typename Key = typename Map::key_type>
typename Map::mapped_type mapGetDefault(
const Map& map,
const Key& key,
const typename Map::mapped_type& dflt = typename Map::mapped_type()) {
auto pos = map.find(key);
return (pos != map.end() ? pos->second : dflt);
}
} // namespace watchman