OLD | NEW |
| (Empty) |
1 // Copyright (c) 2012 The Chromium 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 CHROME_TEST_CHROMEDRIVER_SYNCHRONIZED_MAP_H_ | |
6 #define CHROME_TEST_CHROMEDRIVER_SYNCHRONIZED_MAP_H_ | |
7 | |
8 #include <map> | |
9 #include <utility> | |
10 #include <vector> | |
11 | |
12 #include "base/basictypes.h" | |
13 #include "base/synchronization/lock.h" | |
14 | |
15 template <typename K, typename V> | |
16 class SynchronizedMap { | |
17 public: | |
18 SynchronizedMap(); | |
19 ~SynchronizedMap(); | |
20 | |
21 void Set(const K& key, const V& value); | |
22 bool Get(const K& key, V* value) const; | |
23 bool Has(const K& key) const; | |
24 bool Remove(const K& key); | |
25 | |
26 void GetKeys(std::vector<K>* keys) const; | |
27 | |
28 private: | |
29 typedef std::map<K, V> Map; | |
30 Map map_; | |
31 mutable base::Lock map_lock_; | |
32 | |
33 DISALLOW_COPY_AND_ASSIGN(SynchronizedMap); | |
34 }; | |
35 | |
36 template <typename K, typename V> | |
37 SynchronizedMap<K, V>::SynchronizedMap() {} | |
38 | |
39 template <typename K, typename V> | |
40 SynchronizedMap<K, V>::~SynchronizedMap() {} | |
41 | |
42 template <typename K, typename V> | |
43 void SynchronizedMap<K, V>::Set(const K& key, const V& value) { | |
44 base::AutoLock lock(map_lock_); | |
45 typename Map::iterator iter = map_.find(key); | |
46 if (iter != map_.end()) | |
47 map_.erase(iter); | |
48 map_.insert(std::make_pair(key, value)); | |
49 } | |
50 | |
51 template <typename K, typename V> | |
52 bool SynchronizedMap<K, V>::Get(const K& key, V* value) const { | |
53 base::AutoLock lock(map_lock_); | |
54 typename Map::const_iterator iter = map_.find(key); | |
55 if (iter == map_.end()) | |
56 return false; | |
57 *value = iter->second; | |
58 return true; | |
59 } | |
60 | |
61 template <typename K, typename V> | |
62 bool SynchronizedMap<K, V>::Has(const K& key) const { | |
63 base::AutoLock lock(map_lock_); | |
64 return map_.find(key) != map_.end(); | |
65 } | |
66 | |
67 template <typename K, typename V> | |
68 bool SynchronizedMap<K, V>::Remove(const K& key) { | |
69 base::AutoLock lock(map_lock_); | |
70 typename Map::iterator iter = map_.find(key); | |
71 if (iter == map_.end()) | |
72 return false; | |
73 map_.erase(iter); | |
74 return true; | |
75 } | |
76 | |
77 template <typename K, typename V> | |
78 void SynchronizedMap<K, V>::GetKeys(std::vector<K>* keys) const { | |
79 keys->clear(); | |
80 base::AutoLock lock(map_lock_); | |
81 typename Map::const_iterator iter; | |
82 for (iter = map_.begin(); iter != map_.end(); iter++) | |
83 keys->push_back(iter->first); | |
84 } | |
85 | |
86 #endif // CHROME_TEST_CHROMEDRIVER_SYNCHRONIZED_MAP_H_ | |
OLD | NEW |