const_lru/iters/
iter_key_order_mut.rs

1use num_traits::{PrimInt, Unsigned};
2
3use crate::ConstLru;
4
5/// Iterates through the keys and mutable values of the `ConstLru` in the keys' sorted order
6///
7/// Does not change the LRU order of the elements.
8pub struct IterKeyOrderMut<'a, K, V, const CAP: usize, I: PrimInt + Unsigned> {
9    /// from_smallest_bsi == from_largest_bsi means ended
10    from_smallest_bsi: I,
11    from_largest_bsi: I,
12    const_lru: &'a mut ConstLru<K, V, CAP, I>,
13}
14
15impl<'a, K, V, const CAP: usize, I: PrimInt + Unsigned> IterKeyOrderMut<'a, K, V, CAP, I> {
16    pub fn new(const_lru: &'a mut ConstLru<K, V, CAP, I>) -> Self {
17        Self {
18            from_smallest_bsi: I::zero(),
19            from_largest_bsi: const_lru.len(),
20            const_lru,
21        }
22    }
23
24    fn get_entry_mut(&mut self, bs_i: I) -> (&'a K, &'a mut V) {
25        let i = self.const_lru.bs_index[bs_i.to_usize().unwrap()]
26            .to_usize()
27            .unwrap();
28        // TODO: double check unsafes
29        let key_ptr = unsafe { self.const_lru.keys[i].assume_init_ref() } as *const _;
30        let key: &'a K = unsafe { &*key_ptr };
31        let val_ptr = unsafe { self.const_lru.values[i].assume_init_mut() } as *mut _;
32        let val: &'a mut V = unsafe { &mut *val_ptr };
33        (key, val)
34    }
35
36    fn has_ended(&self) -> bool {
37        self.from_smallest_bsi == self.from_largest_bsi
38    }
39}
40
41impl<'a, K, V, const CAP: usize, I: PrimInt + Unsigned> Iterator
42    for IterKeyOrderMut<'a, K, V, CAP, I>
43{
44    type Item = (&'a K, &'a mut V);
45
46    fn next(&mut self) -> Option<Self::Item> {
47        if self.has_ended() {
48            return None;
49        }
50        // consume then increment
51        let res = self.get_entry_mut(self.from_smallest_bsi);
52        self.from_smallest_bsi = self.from_smallest_bsi + I::one();
53        Some(res)
54    }
55
56    fn size_hint(&self) -> (usize, Option<usize>) {
57        let l = (self.from_largest_bsi - self.from_smallest_bsi)
58            .to_usize()
59            .unwrap();
60        (l, Some(l))
61    }
62}
63
64// TODO: look into https://doc.rust-lang.org/std/iter/trait.TrustedLen.html when it lands in stable
65impl<'a, K, V, const CAP: usize, I: PrimInt + Unsigned> ExactSizeIterator
66    for IterKeyOrderMut<'a, K, V, CAP, I>
67{
68}
69
70impl<'a, K, V, const CAP: usize, I: PrimInt + Unsigned> DoubleEndedIterator
71    for IterKeyOrderMut<'a, K, V, CAP, I>
72{
73    fn next_back(&mut self) -> Option<Self::Item> {
74        if self.has_ended() {
75            return None;
76        }
77        // decrement then consume
78        self.from_largest_bsi = self.from_largest_bsi - I::one();
79        let res = self.get_entry_mut(self.from_largest_bsi);
80        Some(res)
81    }
82}