const_lru/entry/
vacant.rs

1use num_traits::{PrimInt, Unsigned};
2
3use crate::ConstLru;
4
5/// A view into an vacant entry in a ConstLru. It is part of the Entry enum.
6#[derive(Debug)]
7pub struct VacantEntry<'a, K, V, const CAP: usize, I: PrimInt + Unsigned> {
8    const_lru: &'a mut ConstLru<K, V, CAP, I>,
9    key: K,
10    insert_bs_i: I,
11}
12
13impl<'a, K, V, const CAP: usize, I: PrimInt + Unsigned> VacantEntry<'a, K, V, CAP, I> {
14    pub(crate) fn new(const_lru: &'a mut ConstLru<K, V, CAP, I>, key: K, insert_bs_i: I) -> Self {
15        Self {
16            const_lru,
17            key,
18            insert_bs_i,
19        }
20    }
21
22    /// Take ownership of the key.
23    pub fn into_key(self) -> K {
24        self.key
25    }
26
27    /// Gets a reference to the key that would be used when inserting a value through the `VacantEntry`.
28    pub fn key(&self) -> &K {
29        &self.key
30    }
31}
32
33impl<'a, K: Ord, V, const CAP: usize, I: PrimInt + Unsigned> VacantEntry<'a, K, V, CAP, I> {
34    /// Sets the value of the entry with the `VacantEntry`’s key, and returns:
35    /// - a mutable reference to the new value
36    /// - LRU evicted entry, if ConstLru is full
37    pub fn insert(self, v: V) -> (&'a mut V, Option<(K, V)>) {
38        let (i, opt) = if self.const_lru.is_full() {
39            let (i, (old_k, old_v)) =
40                self.const_lru
41                    .insert_evict_lru(self.insert_bs_i, self.key, v);
42            (i, Some((old_k, old_v)))
43        } else {
44            let i = self
45                .const_lru
46                .insert_alloc_new(self.insert_bs_i, self.key, v);
47            (i, None)
48        };
49        (self.const_lru.get_mut_by_index(i), opt)
50    }
51}