OLD | NEW |
(Empty) | |
| 1 // Copyright 2014 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 COMPONENTS_COPRESENCE_COMMON_TIMED_MAP_ |
| 6 #define COMPONENTS_COPRESENCE_COMMON_TIMED_MAP_ |
| 7 |
| 8 #include <map> |
| 9 #include <queue> |
| 10 #include <vector> |
| 11 |
| 12 #include "base/macros.h" |
| 13 #include "base/time/time.h" |
| 14 #include "base/timer/timer.h" |
| 15 |
| 16 namespace copresence { |
| 17 |
| 18 // TimedMap is a map with the added functionality of clearing any |
| 19 // key/value pair after their specified lifetime is over. |
| 20 template <typename KeyType, typename ValueType> |
| 21 class TimedMap { |
| 22 public: |
| 23 TimedMap(const base::TimeDelta& lifetime, size_t max_elements) |
| 24 : kEmptyValue(ValueType()), |
| 25 lifetime_(lifetime), |
| 26 max_elements_(max_elements) { |
| 27 timer_.Start(FROM_HERE, lifetime_, this, &TimedMap::ClearExpiredTokens); |
| 28 } |
| 29 |
| 30 ~TimedMap() {} |
| 31 |
| 32 void Add(const KeyType& key, const ValueType& value) { |
| 33 map_[key] = value; |
| 34 expiry_queue_.push(KeyTimeTuple(key, base::Time::Now() + lifetime_)); |
| 35 while (map_.size() > max_elements_) |
| 36 ClearOldestToken(); |
| 37 } |
| 38 |
| 39 bool HasKey(const KeyType& key) { |
| 40 ClearExpiredTokens(); |
| 41 return map_.find(key) != map_.end(); |
| 42 } |
| 43 |
| 44 const ValueType& GetValue(const KeyType& key) { |
| 45 ClearExpiredTokens(); |
| 46 typename std::map<KeyType, ValueType>::const_iterator elt = map_.find(key); |
| 47 return elt == map_.end() ? kEmptyValue : elt->second; |
| 48 } |
| 49 |
| 50 private: |
| 51 void ClearExpiredTokens() { |
| 52 while (!expiry_queue_.empty() && |
| 53 expiry_queue_.top().second >= base::Time::Now()) |
| 54 ClearOldestToken(); |
| 55 } |
| 56 |
| 57 void ClearOldestToken() { |
| 58 map_.erase(expiry_queue_.top().first); |
| 59 expiry_queue_.pop(); |
| 60 } |
| 61 |
| 62 typedef std::pair<KeyType, base::Time> KeyTimeTuple; |
| 63 |
| 64 class EarliestFirstComparator { |
| 65 public: |
| 66 // The earlier end_time should be the 'higher' value. |
| 67 bool operator()(const KeyTimeTuple& left, const KeyTimeTuple& right) const { |
| 68 return left.second > right.second; |
| 69 } |
| 70 }; |
| 71 |
| 72 typedef std::priority_queue<KeyTimeTuple, |
| 73 std::vector<KeyTimeTuple>, |
| 74 EarliestFirstComparator> ExpiryQueue; |
| 75 |
| 76 const ValueType kEmptyValue; |
| 77 |
| 78 base::RepeatingTimer<TimedMap> timer_; |
| 79 const base::TimeDelta lifetime_; |
| 80 const size_t max_elements_; |
| 81 std::map<KeyType, ValueType> map_; |
| 82 ExpiryQueue expiry_queue_; |
| 83 |
| 84 DISALLOW_COPY_AND_ASSIGN(TimedMap); |
| 85 }; |
| 86 |
| 87 } // namespace copresence |
| 88 |
| 89 #endif // COMPONENTS_COPRESENCE_COMMON_TIMED_MAP_ |
OLD | NEW |