OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 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 MEDIA_BLINK_RANGEMAP_H_ |
| 6 #define MEDIA_BLINK_RANGEMAP_H_ |
| 7 |
| 8 #include <map> |
| 9 |
| 10 #include "base/logging.h" |
| 11 |
| 12 namespace media { |
| 13 |
| 14 template<typename KeyType, typename ValueType> |
| 15 class RangeMap { |
| 16 public: |
| 17 typedef std::map<KeyType, ValueType> MapType; |
| 18 |
| 19 ValueType operator[](KeyType k) const { |
| 20 typename MapType::const_iterator i = map_.upper_bound(k); |
| 21 if (i == map_.begin()) { |
| 22 return 0; |
| 23 } else { |
| 24 --i; |
| 25 return i->second; |
| 26 } |
| 27 } |
| 28 |
| 29 // Increase [from..to) by howmuch. |
| 30 void IncrementRange(KeyType from, KeyType to, ValueType howmuch) { |
| 31 DCHECK_GE(to, from); |
| 32 if (from == to || howmuch == 0) return; |
| 33 typename MapType::iterator a = MakeEntry(from); |
| 34 typename MapType::iterator b = MakeEntry(to); |
| 35 for (typename MapType::iterator i = a; i != b; ++i) { |
| 36 i->second += howmuch; |
| 37 } |
| 38 RemoveDuplicates(a); |
| 39 // b may be invalid |
| 40 RemoveDuplicates(map_.lower_bound(to)); |
| 41 } |
| 42 |
| 43 const MapType& map() { return map_; } |
| 44 |
| 45 private: |
| 46 typename MapType::iterator MakeEntry(KeyType k) { |
| 47 typename MapType::value_type tmp(k, 0); |
| 48 std::pair<typename MapType::iterator, bool> insert_result; |
| 49 insert_result = map_.insert(tmp); |
| 50 if (insert_result.second) { |
| 51 if (insert_result.first != map_.begin()) { |
| 52 typename MapType::iterator i = insert_result.first; |
| 53 --i; |
| 54 insert_result.first->second = i->second; |
| 55 } |
| 56 } |
| 57 return insert_result.first; |
| 58 } |
| 59 |
| 60 void RemoveDuplicates(typename MapType::iterator i) { |
| 61 if (i == map_.end()) return; |
| 62 if (i == map_.begin() && i->second == 0) { |
| 63 typename MapType::iterator j = i; |
| 64 ++i; |
| 65 map_.erase(j); |
| 66 if (i == map_.end()) return; |
| 67 } |
| 68 if (i != map_.begin()) { |
| 69 typename MapType::iterator j = i; |
| 70 --i; |
| 71 if (i ->second == j->second) { |
| 72 map_.erase(j); |
| 73 } |
| 74 } |
| 75 typename MapType::iterator j = i; |
| 76 ++j; |
| 77 if (j != map_.end() && i ->second == j->second) { |
| 78 map_.erase(j); |
| 79 } |
| 80 } |
| 81 |
| 82 MapType map_; |
| 83 }; |
| 84 |
| 85 } // namespace media |
| 86 |
| 87 #endif // MEDIA_BLINK_RANGEMAP_H_ |
OLD | NEW |