blob: 4066869ca60ffe6166c20ed4ecd60da799d4c8d6 [file] [log] [blame]
Yifan Hong84888d32017-02-06 15:32:41 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef ANDROID_HIDL_CONCURRENT_MAP_H
17#define ANDROID_HIDL_CONCURRENT_MAP_H
18
19#include <mutex>
20#include <map>
21
22namespace android {
23namespace hardware {
24
25template<typename K, typename V>
26class ConcurrentMap {
27private:
28 using size_type = typename std::map<K, V>::size_type;
29 using iterator = typename std::map<K, V>::iterator;
30 using const_iterator = typename std::map<K, V>::const_iterator;
31
32public:
33 void set(K &&k, V &&v) {
34 std::unique_lock<std::mutex> _lock(mMutex);
35 mMap[std::forward<K>(k)] = std::forward<V>(v);
36 }
37
38 // get with the given default value.
39 const V &get(const K &k, const V &def) const {
40 std::unique_lock<std::mutex> _lock(mMutex);
41 const_iterator iter = mMap.find(k);
42 if (iter == mMap.end()) {
43 return def;
44 }
45 return iter->second;
46 }
47
48 size_type erase(const K &k) {
49 std::unique_lock<std::mutex> _lock(mMutex);
50 return mMap.erase(k);
51 }
52
Martijn Coenen62950272017-07-27 13:26:54 +020053 size_type eraseIfEqual(const K& k, const V& v) {
54 std::unique_lock<std::mutex> _lock(mMutex);
55 const_iterator iter = mMap.find(k);
56 if (iter == mMap.end()) {
57 return 0;
58 }
59 if (iter->second == v) {
60 mMap.erase(iter);
61 return 1;
62 } else {
63 return 0;
64 }
65 }
66
Steven Morelande67a6762017-05-16 14:53:28 -070067 std::unique_lock<std::mutex> lock() { return std::unique_lock<std::mutex>(mMutex); }
68
69 void setLocked(K&& k, V&& v) { mMap[std::forward<K>(k)] = std::forward<V>(v); }
70
71 const V& getLocked(const K& k, const V& def) const {
72 const_iterator iter = mMap.find(k);
73 if (iter == mMap.end()) {
74 return def;
75 }
76 return iter->second;
77 }
78
79 private:
Yifan Hong84888d32017-02-06 15:32:41 -080080 mutable std::mutex mMutex;
81 std::map<K, V> mMap;
82};
83
84} // namespace hardware
85} // namespace android
86
87
88#endif // ANDROID_HIDL_CONCURRENT_MAP_H