libnsave/tmohash/
iter.rs

1use super::tmo::*;
2use std::{fmt, hash::Hash, marker::PhantomData};
3
4pub struct Iter<'a, K, V>
5where
6    K: Eq + Hash,
7{
8    pub(crate) done: usize,
9    pub(crate) len: usize,
10    pub(crate) next: *const Node<K, V>,
11    pub(crate) phantom: PhantomData<&'a (K, V)>,
12}
13
14impl<'a, K, V> Iterator for Iter<'a, K, V>
15where
16    K: Eq + Hash,
17{
18    type Item = (&'a K, &'a V);
19
20    /// 仅从最老的一端开始
21    fn next(&mut self) -> Option<(&'a K, &'a V)> {
22        if self.done >= self.len {
23            return None;
24        }
25
26        unsafe {
27            let k = &(*(*self.next).key.as_ptr()) as &K;
28            let v = &(*(*self.next).value.as_ptr()) as &V;
29            self.next = (*self.next).next;
30            self.done += 1;
31            Some((k, v))
32        }
33    }
34
35    fn size_hint(&self) -> (usize, Option<usize>) {
36        (0, Some(self.len - self.done))
37    }
38}
39
40impl<K, V> fmt::Debug for Iter<'_, K, V>
41where
42    K: Eq + Hash + fmt::Debug,
43{
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        if self.done >= self.len {
46            write!(f, "Iter [{:?}/{:?}]", self.done, self.len)
47        } else {
48            let next = unsafe { &(*(*self.next).key.as_ptr()) };
49            write!(f, "Iter [{:?}/{:?} next: {:?}]", self.done, self.len, next)
50        }
51    }
52}
53
54impl<K, V> fmt::Display for Iter<'_, K, V>
55where
56    K: Eq + Hash + fmt::Debug + fmt::Display,
57    V: fmt::Display,
58{
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        if self.done >= self.len {
61            write!(f, "Iter [{}/{}]", self.done, self.len)
62        } else {
63            let next = unsafe { &(*(*self.next).key.as_ptr()) };
64            write!(f, "Iter [{}/{} next: {}]", self.done, self.len, next)
65        }
66    }
67}