Inserts an entry in the queue, becoming the most recently used. If the entry already exists, returns the previous value.
(&mut self, key: K, value: V)
| 102 | /// Inserts an entry in the queue, becoming the most recently used. |
| 103 | /// If the entry already exists, returns the previous value. |
| 104 | pub fn put(&mut self, key: K, value: V) -> Option<V> { |
| 105 | let old_value = self.remove(&key); |
| 106 | |
| 107 | let node = Arc::new(Mutex::new(LruNode { |
| 108 | key: key.clone(), |
| 109 | prev: None, |
| 110 | next: None, |
| 111 | })); |
| 112 | |
| 113 | match self.queue.head { |
| 114 | // queue is not empty |
| 115 | Some(ref old_head) => { |
| 116 | old_head |
| 117 | .upgrade() |
| 118 | .expect("value has been unexpectedly dropped") |
| 119 | .lock() |
| 120 | .prev = Some(Arc::downgrade(&node)); |
| 121 | node.lock().next = Some(Weak::clone(old_head)); |
| 122 | self.queue.head = Some(Arc::downgrade(&node)); |
| 123 | } |
| 124 | // queue is empty |
| 125 | _ => { |
| 126 | self.queue.head = Some(Arc::downgrade(&node)); |
| 127 | self.queue.tail = Some(Arc::downgrade(&node)); |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | self.data.insert(key, (node, value)); |
| 132 | |
| 133 | old_value |
| 134 | } |
| 135 | |
| 136 | /// Removes and returns the least recently used value. |
| 137 | /// Returns `None` if the queue is empty. |