1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
use std::borrow::Borrow;
use std::collections::{btree_map, BTreeMap};
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::RangeBounds;

use crate::lru::{EntryCache, EntryRef, IntoIter, LruCache, NodeId, Removed};
use crate::LruMap;

/// A Least Recently Used map with fixed capacity that stores keys using a
/// [`BTreeMap`] internally. Inserting and querying has similar performance to
/// using a [`BTreeMap`], but internally this data structure keeps track of the
/// order in which the keys were last touched.
///
/// When inserting a new key and the map is at-capacity, the least recently used
/// key will be evicted to make room for the new key.
///
/// To avoid `unsafe`, this crate must store each entry's key twice. This means
/// that `Key` must implement `Clone`. If you're using expensive-to-clone keys,
/// consider wrapping the key in an `Rc`/`Arc` or using an alternate LRU crate.
#[derive(Debug)]
#[must_use]
pub struct LruBTreeMap<Key, Value> {
    map: BTreeMap<Key, NodeId>,
    cache: LruCache<Key, Value>,
}

impl<Key, Value> LruBTreeMap<Key, Value>
where
    Key: Ord + Clone,
{
    /// Creates a new map with the maximum `capacity`.
    ///
    /// # Panics
    ///
    /// Panics if `capacity` is <= 1 or > `u32::MAX`.
    pub fn new(capacity: usize) -> Self {
        assert!(capacity > 1);
        assert!(capacity <= usize::try_from(u32::MAX).unwrap());
        Self {
            map: BTreeMap::new(),
            cache: LruCache::new(capacity),
        }
    }

    /// Returns the stored value for `key`, if present.
    ///
    /// This function touches the key, making it the most recently used key.
    pub fn get<QueryKey>(&mut self, key: &QueryKey) -> Option<&Value>
    where
        QueryKey: Ord + ?Sized,
        Key: Borrow<QueryKey>,
    {
        let node = self.map.get(key).copied();
        node.map(|node| self.cache.get(node).value())
    }

    /// Returns the stored value for `key`, if present.
    ///
    /// This function does not touch the key, preserving its current position in
    /// the lru cache.
    pub fn get_without_update<QueryKey>(&self, key: &QueryKey) -> Option<&Value>
    where
        QueryKey: Ord + ?Sized,
        Key: Borrow<QueryKey>,
    {
        self.map
            .get(key)
            .map(|node| self.cache.get_without_touch(*node).value())
    }

    /// Returns an [`EntryRef`] for `key`, if present.
    ///
    /// This function does not touch the key, preserving its current position in
    /// the lru cache. The [`EntryRef`] can touch the key, depending on which
    /// functions are used.
    ///
    /// ```rust
    /// use lrumap::{LruBTreeMap, LruMap, Removed};
    ///
    /// let mut lru = LruBTreeMap::new(3);
    /// lru.push(1, 1);
    /// lru.push(2, 2);
    /// lru.push(3, 3);
    ///
    /// // The cache has been updated once since entry 2 was touched.
    /// let mut entry = lru.entry(&2).unwrap();
    /// assert_eq!(entry.staleness(), 1);
    /// // Peeking the value will not update the entry's position.
    /// assert_eq!(entry.peek_value(), &2);
    /// assert_eq!(entry.staleness(), 1);
    /// // Querying the value or touching the entry will move it to the
    /// // front of the cache.
    /// assert_eq!(entry.value(), &2);
    /// assert_eq!(entry.staleness(), 0);
    ///
    /// assert_eq!(lru.head().unwrap().key(), &2);
    /// ```
    pub fn entry<QueryKey>(&mut self, key: &QueryKey) -> Option<EntryRef<'_, Self, Key, Value>>
    where
        QueryKey: Ord + ?Sized,
        Key: Borrow<QueryKey>,
    {
        self.map
            .get(key)
            .copied()
            .map(|node| EntryRef::new(self, node))
    }

    /// Inserts `value` for `key` into this map. If a value is already stored
    /// for this key, [`Removed::PreviousValue`] is returned with the previously
    /// stored value. If no value is currently stored and the map is full, the
    /// least recently used entry will be returned in [`Removed::Evicted`].
    /// Otherwise, `None` will be returned.
    ///
    /// This function touches the key, making it the most recently used key.
    ///
    /// ```rust
    /// use lrumap::{LruBTreeMap, LruMap, Removed};
    ///
    /// let mut lru = LruBTreeMap::new(3);
    /// lru.push(1, 1);
    /// lru.push(2, 2);
    /// lru.push(3, 3);
    ///
    /// // The cache is now full. The next push will evict an entry.
    /// let removed = lru.push(4, 4);
    /// assert_eq!(removed, Some(Removed::Evicted(1, 1)));
    ///
    /// // This leaves the cache with 4 as the most recent key, and 2 as the
    /// // least recent key.
    /// assert_eq!(lru.head().unwrap().key(), &4);
    /// assert_eq!(lru.tail().unwrap().key(), &2);
    /// ```
    pub fn push(&mut self, key: Key, value: Value) -> Option<Removed<Key, Value>> {
        // Create the new entry for this key/value pair, which also puts it at
        // the front of the LRU
        // let existing_entry = self.map.entry(key.clone());
        let entry = self.map.entry(key.clone());

        if let btree_map::Entry::Occupied(entry) = &entry {
            let node_ref = *entry.get();
            // Swap the value out.
            let value = self.cache.get_mut(node_ref).replace_value(value);

            return Some(Removed::PreviousValue(value));
        }

        // Key is not currently contained. Create a new node.
        let (node, result) = self.cache.push(key, value);

        // Insert the node into the BTreeMap
        entry.or_insert(node);

        if let Some(Removed::Evicted(key, _)) = &result {
            self.map.remove(key);
        }

        result
    }

    /// Pushes all items from `iterator` into this map. If there are more
    /// entries in the iterator than capacity remaining, keys will be evicted as
    /// needed.
    ///
    /// This function is equivalent to a for loop calling [`Self::push()`].
    ///
    /// ```rust
    /// use lrumap::{LruBTreeMap, LruMap};
    ///
    /// let mut lru = LruBTreeMap::new(3);
    /// lru.extend([(1, 1), (2, 2), (3, 3), (4, 4)]);
    ///
    /// assert_eq!(lru.head().unwrap().key(), &4);
    /// assert_eq!(lru.tail().unwrap().key(), &2);
    /// ```
    pub fn extend<IntoIter: IntoIterator<Item = (Key, Value)>>(&mut self, iterator: IntoIter) {
        for (key, value) in iterator {
            let (node_id, removed) = self.cache.push(key.clone(), value);
            if let Some(Removed::Evicted(evicted_key, _)) = removed {
                self.map.remove(&evicted_key);
            }
            self.map.insert(key, node_id);
        }
    }

    /// Returns the most recently touched entry with a key within `range`.
    ///
    /// This function uses [`BTreeMap::range`] to identify all entries that
    /// match the given range. For each returned entry, the entry's
    /// [staleness](EntryRef::staleness) is compared, and the least stale entry
    /// is returned. If no keys match the range, `None` is returned.
    ///
    /// This function does not touch any keys, preserving the current order of
    /// the lru cache. The [`EntryRef`] returned can be used to peek, touch, or
    /// remove the entry.
    ///
    /// ```rust
    /// use lrumap::LruBTreeMap;
    ///
    /// let mut lru = LruBTreeMap::new(5);
    /// lru.extend([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]);
    ///
    /// assert_eq!(lru.most_recent_in_range(2..=4).unwrap().key(), &4);
    /// // Change the order by retrieving key 2.
    /// lru.get(&2);
    /// assert_eq!(lru.most_recent_in_range(2..=4).unwrap().key(), &2);
    /// ```
    pub fn most_recent_in_range<QueryKey, Range>(
        &mut self,
        range: Range,
    ) -> Option<EntryRef<'_, Self, Key, Value>>
    where
        QueryKey: Ord + ?Sized,
        Key: Borrow<QueryKey>,
        Range: RangeBounds<QueryKey>,
    {
        self.most_recent_in_range_where(range, |_, _| true)
    }

    /// Returns the most recently touched entry with a key within `range` that
    /// passes the `condition` check.
    ///
    /// This function uses [`BTreeMap::range`] to identify all entries that
    /// match the given range. Each key and value that matches is passed to
    /// `condition`. For each entry where `condition` returns true, the
    /// [staleness](EntryRef::staleness) is compared, and the least stale entry
    /// is returned. If no keys match the range, `None` is returned.
    ///
    /// This function does not touch any keys, preserving the current order of
    /// the lru cache. The [`EntryRef`] returned can be used to peek, touch, or
    /// remove the entry.
    ///
    /// ```rust
    /// use lrumap::LruBTreeMap;
    ///
    /// let mut lru = LruBTreeMap::<u32, u16>::new(5);
    /// lru.extend([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]);
    ///
    /// let condition = |key: &u32, value: &u16| key == &3 || value == &4;
    /// assert_eq!(
    ///     lru.most_recent_in_range_where(2..=4, condition)
    ///         .unwrap()
    ///         .key(),
    ///     &4
    /// );
    ///
    /// // Change the order by retrieving key 2. However, 2 doesn't meet the
    /// // condition, so the result is unchanged.
    /// lru.get(&2);
    /// assert_eq!(
    ///     lru.most_recent_in_range_where(2..=4, condition)
    ///         .unwrap()
    ///         .key(),
    ///     &4
    /// );
    ///
    /// // Request 3, moving it to the front. Since 3 matches the condition, the
    /// // result is now 3.
    /// lru.get(&3);
    /// assert_eq!(
    ///     lru.most_recent_in_range_where(2..=4, condition)
    ///         .unwrap()
    ///         .key(),
    ///     &3
    /// );
    /// ```
    pub fn most_recent_in_range_where<QueryKey, Range, Condition>(
        &mut self,
        range: Range,
        mut condition: Condition,
    ) -> Option<EntryRef<'_, Self, Key, Value>>
    where
        QueryKey: Ord + ?Sized,
        Key: Borrow<QueryKey>,
        Range: RangeBounds<QueryKey>,
        Condition: for<'key, 'value> FnMut(&'key Key, &'value Value) -> bool,
    {
        let mut closest_node = None;
        let mut closest_staleness = usize::MAX;
        for (_, &node_id) in self.map.range(range) {
            let node = self.cache.get_without_touch(node_id);
            if condition(node.key(), node.value()) {
                let staleness = self.cache.sequence().wrapping_sub(node.last_accessed());
                if staleness < closest_staleness {
                    closest_staleness = staleness;
                    closest_node = Some(node_id);
                }
            }
        }
        closest_node.map(|node| EntryRef::new(self, node))
    }
}

impl<Key, Value> LruMap<Key, Value> for LruBTreeMap<Key, Value>
where
    Key: Ord + Clone,
{
    fn new(capacity: usize) -> Self {
        Self::new(capacity)
    }

    fn len(&self) -> usize {
        self.cache.len()
    }

    fn head(&mut self) -> Option<EntryRef<'_, Self, Key, Value>> {
        self.cache.head().map(|node| EntryRef::new(self, node))
    }

    fn tail(&mut self) -> Option<EntryRef<'_, Self, Key, Value>> {
        self.cache.tail().map(|node| EntryRef::new(self, node))
    }

    fn iter(&self) -> crate::lru::Iter<'_, Key, Value> {
        self.cache.iter()
    }

    fn get<QueryKey>(&mut self, key: &QueryKey) -> Option<&Value>
    where
        QueryKey: Ord + Hash + Eq + ?Sized,
        Key: Borrow<QueryKey> + Ord + Eq + Hash,
    {
        self.get(key)
    }

    fn get_without_update<QueryKey>(&self, key: &QueryKey) -> Option<&Value>
    where
        QueryKey: Ord + Hash + Eq + ?Sized,
        Key: Borrow<QueryKey> + Ord + Eq + Hash,
    {
        self.get_without_update(key)
    }

    fn entry<QueryKey>(&mut self, key: &QueryKey) -> Option<EntryRef<'_, Self, Key, Value>>
    where
        QueryKey: Ord + Hash + Eq + ?Sized,
        Key: Borrow<QueryKey> + Ord + Eq + Hash,
    {
        self.entry(key)
    }

    fn push(&mut self, key: Key, value: Value) -> Option<Removed<Key, Value>> {
        self.push(key, value)
    }

    fn extend<IntoIter: IntoIterator<Item = (Key, Value)>>(&mut self, iterator: IntoIter) {
        self.extend(iterator);
    }
}

impl<Key, Value> EntryCache<Key, Value> for LruBTreeMap<Key, Value>
where
    Key: Ord + Clone,
{
    fn cache(&self) -> &LruCache<Key, Value> {
        &self.cache
    }

    fn cache_mut(&mut self) -> &mut LruCache<Key, Value> {
        &mut self.cache
    }

    fn remove(&mut self, node: NodeId) -> ((Key, Value), Option<NodeId>, Option<NodeId>) {
        let ((key, value), next, previous) = self.cache.remove(node);
        self.map.remove(&key);
        ((key, value), next, previous)
    }
}

impl<Key, Value> IntoIterator for LruBTreeMap<Key, Value>
where
    Key: Ord + Clone,
{
    type IntoIter = IntoIter<Key, Value>;
    type Item = (Key, Value);

    fn into_iter(self) -> Self::IntoIter {
        IntoIter::from(self.cache)
    }
}

#[test]
fn most_recent_in_range_test() {
    let mut lru = LruBTreeMap::new(5);
    lru.extend([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]);

    assert_eq!(lru.most_recent_in_range(2..=4).unwrap().key(), &4);
    lru.get(&2);
    assert_eq!(lru.most_recent_in_range(2..=4).unwrap().key(), &2);
    assert_eq!(
        lru.most_recent_in_range_where(2..=4, |key: &u32, _value: &u16| key != &2)
            .unwrap()
            .key(),
        &4
    );
}