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 CHROME_BROWSER_ANDROID_THUMBNAIL_SCOPED_PTR_EXPIRING_CACHE_H_ 6 #define CHROME_BROWSER_ANDROID_THUMBNAIL_SCOPED_PTR_EXPIRING_CACHE_H_ 7 8 #include "base/memory/scoped_ptr.h" 9 #include "net/base/linked_hash_map.h" 10 11 template <class Key, class Value> 12 class ScopedPtrExpiringCache { 13 private: 14 typedef linked_hash_map<Key, Value*> LinkedHashMap; 15 16 public: 17 typedef typename LinkedHashMap::iterator iterator; 18 ScopedPtrExpiringCache(size_t max_cache_size)19 explicit ScopedPtrExpiringCache(size_t max_cache_size) 20 : max_cache_size_(max_cache_size) {} 21 ~ScopedPtrExpiringCache()22 ~ScopedPtrExpiringCache() {} 23 Put(const Key & key,scoped_ptr<Value> value)24 void Put(const Key& key, scoped_ptr<Value> value) { 25 Remove(key); 26 map_[key] = value.release(); 27 EvictIfFull(); 28 } 29 Get(const Key & key)30 Value* Get(const Key& key) { 31 iterator iter = map_.find(key); 32 if (iter != map_.end()) 33 return iter->second; 34 return NULL; 35 } 36 Remove(const Key & key)37 void Remove(const Key& key) { 38 iterator iter = map_.find(key); 39 if (iter != map_.end()) { 40 delete iter->second; 41 map_.erase(key); 42 } 43 } 44 Clear()45 void Clear() { 46 for (iterator iter = map_.begin(); iter != map_.end(); iter++) { 47 delete iter->second; 48 } 49 map_.clear(); 50 } 51 begin()52 iterator begin() { return map_.begin(); } end()53 iterator end() { return map_.end(); } MaximumCacheSize()54 size_t MaximumCacheSize() const { return max_cache_size_; } size()55 size_t size() const { return map_.size(); } 56 57 private: EvictIfFull()58 void EvictIfFull() { 59 while (map_.size() > max_cache_size_) { 60 iterator it = map_.begin(); 61 delete it->second; 62 map_.erase(it); 63 } 64 } 65 66 size_t max_cache_size_; 67 LinkedHashMap map_; 68 69 DISALLOW_COPY_AND_ASSIGN(ScopedPtrExpiringCache); 70 }; 71 72 #endif // CHROME_BROWSER_ANDROID_THUMBNAIL_SCOPED_PTR_EXPIRING_CACHE_H_ 73