1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 //! A cache that holds a limited number of key-value pairs. When the
13 //! capacity of the cache is exceeded, the least-recently-used
14 //! (where "used" means a look-up or putting the pair into the cache)
15 //! pair is automatically removed.
20 //! use collections::LruCache;
22 //! let mut cache: LruCache<int, int> = LruCache::new(2);
26 //! assert!(cache.get(&1).is_none());
27 //! assert_eq!(*cache.get(&2).unwrap(), 20);
28 //! assert_eq!(*cache.get(&3).unwrap(), 30);
31 //! assert_eq!(*cache.get(&2).unwrap(), 22);
34 //! assert!(cache.get(&3).is_none());
36 //! cache.change_capacity(1);
37 //! assert!(cache.get(&2).is_none());
40 use std::container::Container;
41 use std::to_bytes::Cb;
47 struct KeyRef<K> { k: *K }
49 struct LruEntry<K, V> {
52 next: *mut LruEntry<K, V>,
53 prev: *mut LruEntry<K, V>,
57 pub struct LruCache<K, V> {
58 priv map: HashMap<KeyRef<K>, ~LruEntry<K, V>>,
60 priv head: *mut LruEntry<K, V>,
61 priv tail: *mut LruEntry<K, V>,
64 impl<K: IterBytes> IterBytes for KeyRef<K> {
65 fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool {
66 unsafe{ (*self.k).iter_bytes(lsb0, f) }
70 impl<K: Eq> Eq for KeyRef<K> {
71 fn eq(&self, other: &KeyRef<K>) -> bool {
72 unsafe{ (*self.k).eq(&*other.k) }
76 impl<K, V> LruEntry<K, V> {
77 fn new() -> LruEntry<K, V> {
81 next: ptr::mut_null(),
82 prev: ptr::mut_null(),
86 fn with_key_value(k: K, v: V) -> LruEntry<K, V> {
90 next: ptr::mut_null(),
91 prev: ptr::mut_null(),
96 impl<K: IterBytes + Eq, V> LruCache<K, V> {
97 /// Create an LRU Cache that holds at most `capacity` items.
98 pub fn new(capacity: uint) -> LruCache<K, V> {
99 let cache = LruCache {
102 head: unsafe{ cast::transmute(~LruEntry::<K, V>::new()) },
103 tail: unsafe{ cast::transmute(~LruEntry::<K, V>::new()) },
106 (*cache.head).next = cache.tail;
107 (*cache.tail).prev = cache.head;
112 /// Put a key-value pair into cache.
113 pub fn put(&mut self, k: K, v: V) {
114 let mut key_existed = false;
115 let (node_ptr, node_opt) = match self.map.find_mut(&KeyRef{k: &k}) {
118 node.value = Some(v);
119 let node_ptr: *mut LruEntry<K, V> = &mut **node;
123 let mut node = ~LruEntry::with_key_value(k, v);
124 let node_ptr: *mut LruEntry<K, V> = &mut *node;
125 (node_ptr, Some(node))
129 self.detach(node_ptr);
130 self.attach(node_ptr);
132 let keyref = unsafe { (*node_ptr).key.as_ref().unwrap() };
133 self.map.swap(KeyRef{k: keyref}, node_opt.unwrap());
134 self.attach(node_ptr);
135 if self.len() > self.capacity() {
141 /// Return a value corresponding to the key in the cache.
142 pub fn get<'a>(&'a mut self, k: &K) -> Option<&'a V> {
143 let (value, node_ptr_opt) = match self.map.find_mut(&KeyRef{k: k}) {
144 None => (None, None),
146 let node_ptr: *mut LruEntry<K, V> = &mut **node;
148 match (*node_ptr).value {
149 None => (None, None),
150 Some(ref value) => (Some(value), Some(node_ptr))
158 self.detach(node_ptr);
159 self.attach(node_ptr);
165 /// Remove and return a value corresponding to the key from the cache.
166 pub fn pop(&mut self, k: &K) -> Option<V> {
167 match self.map.pop(&KeyRef{k: k}) {
169 Some(lru_entry) => lru_entry.value
173 /// Return the maximum number of key-value pairs the cache can hold.
174 pub fn capacity(&self) -> uint {
178 /// Change the number of key-value pairs the cache can hold. Remove
179 /// least-recently-used key-value pairs if necessary.
180 pub fn change_capacity(&mut self, capacity: uint) {
181 for _ in range(capacity, self.len()) {
184 self.max_size = capacity;
188 fn remove_lru(&mut self) {
190 let lru = unsafe { (*self.tail).prev };
195 Some(ref k) => { self.map.pop(&KeyRef{k: k}); }
202 fn detach(&mut self, node: *mut LruEntry<K, V>) {
204 (*(*node).prev).next = (*node).next;
205 (*(*node).next).prev = (*node).prev;
210 fn attach(&mut self, node: *mut LruEntry<K, V>) {
212 (*node).next = (*self.head).next;
213 (*node).prev = self.head;
214 (*self.head).next = node;
215 (*(*node).next).prev = node;
220 impl<A: ToStr + IterBytes + Eq, B: ToStr> ToStr for LruCache<A, B> {
221 /// Return a string that lists the key-value pairs from most-recently
222 /// used to least-recently used.
224 fn to_str(&self) -> ~str {
226 let mut cur = self.head;
227 for i in range(0, self.len()) {
234 // should never print nil
235 None => acc.push_str("nil"),
236 Some(ref k) => acc.push_str(k.to_str())
242 // should never print nil
243 None => acc.push_str("nil"),
244 Some(ref value) => acc.push_str(value.to_str())
253 impl<K: IterBytes + Eq, V> Container for LruCache<K, V> {
254 /// Return the number of key-value pairs in the cache.
255 fn len(&self) -> uint {
260 impl<K: IterBytes + Eq, V> Mutable for LruCache<K, V> {
261 /// Clear the cache of all key-value pairs.
262 fn clear(&mut self) {
268 impl<K, V> Drop for LruCache<K, V> {
271 let _: ~LruEntry<K, V> = cast::transmute(self.head);
272 let _: ~LruEntry<K, V> = cast::transmute(self.tail);
281 fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) {
282 assert!(opt.is_some());
283 assert_eq!(opt.unwrap(), &v);
287 fn test_put_and_get() {
288 let mut cache: LruCache<int, int> = LruCache::new(2);
291 assert_opt_eq(cache.get(&1), 10);
292 assert_opt_eq(cache.get(&2), 20);
293 assert_eq!(cache.len(), 2);
297 fn test_put_update() {
298 let mut cache: LruCache<~str, ~[u8]> = LruCache::new(1);
299 cache.put(~"1", ~[10, 10]);
300 cache.put(~"1", ~[10, 19]);
301 assert_opt_eq(cache.get(&~"1"), ~[10, 19]);
302 assert_eq!(cache.len(), 1);
306 fn test_expire_lru() {
307 let mut cache: LruCache<~str, ~str> = LruCache::new(2);
308 cache.put(~"foo1", ~"bar1");
309 cache.put(~"foo2", ~"bar2");
310 cache.put(~"foo3", ~"bar3");
311 assert!(cache.get(&~"foo1").is_none());
312 cache.put(~"foo2", ~"bar2update");
313 cache.put(~"foo4", ~"bar4");
314 assert!(cache.get(&~"foo3").is_none());
319 let mut cache: LruCache<int, int> = LruCache::new(2);
322 assert_eq!(cache.len(), 2);
323 let opt1 = cache.pop(&1);
324 assert!(opt1.is_some());
325 assert_eq!(opt1.unwrap(), 10);
326 assert!(cache.get(&1).is_none());
327 assert_eq!(cache.len(), 1);
331 fn test_change_capacity() {
332 let mut cache: LruCache<int, int> = LruCache::new(2);
333 assert_eq!(cache.capacity(), 2);
336 cache.change_capacity(1);
337 assert!(cache.get(&1).is_none());
338 assert_eq!(cache.capacity(), 1);
343 let mut cache: LruCache<int, int> = LruCache::new(3);
347 assert_eq!(cache.to_str(), ~"{3: 30, 2: 20, 1: 10}");
349 assert_eq!(cache.to_str(), ~"{2: 22, 3: 30, 1: 10}");
351 assert_eq!(cache.to_str(), ~"{6: 60, 2: 22, 3: 30}");
353 assert_eq!(cache.to_str(), ~"{3: 30, 6: 60, 2: 22}");
354 cache.change_capacity(2);
355 assert_eq!(cache.to_str(), ~"{3: 30, 6: 60}");
360 let mut cache: LruCache<int, int> = LruCache::new(2);
364 assert!(cache.get(&1).is_none());
365 assert!(cache.get(&2).is_none());
366 assert_eq!(cache.to_str(), ~"{}");