Skip to main content

ic_storage/adapter/
iteration.rs

1//! Owned entries and iterator views over the independent ordered engine.
2use super::{Memory, Storable, bridge::TreeMemory};
3use crate::{DefaultMemoryImpl, ordered_map};
4use std::{borrow::Cow, marker::PhantomData};
5
6///
7/// `MapEntry`
8///
9/// An owned key and encoded value from an ordered scan. Decoding failures trap.
10///
11pub struct MapEntry<K, V> {
12    key: K,
13    bytes: ordered_map::EncodedValue,
14    value: PhantomData<V>,
15}
16impl<K, V: Storable> MapEntry<K, V> {
17    /// Borrow the decoded key.
18    pub const fn key(&self) -> &K {
19        &self.key
20    }
21    /// Decode the value. Malformed stored bytes trap.
22    pub fn value(&self) -> V {
23        ordered_map::decode(Cow::Borrowed(self.bytes.as_slice()))
24    }
25    /// Consume the entry and decode its value.
26    pub fn into_pair(self) -> (K, V) {
27        (self.key, self.bytes.decode())
28    }
29    /// Consume only the key without decoding its value.
30    pub fn into_key(self) -> K {
31        self.key
32    }
33    /// Consume and decode only the value.
34    pub fn into_value(self) -> V {
35        self.bytes.decode()
36    }
37}
38///
39/// `MapIter`
40///
41/// Bidirectional ordered traversal retaining its governed map borrow.
42///
43pub struct MapIter<'a, K: Storable + Ord + Clone, V: Storable, M: Memory = DefaultMemoryImpl>(
44    pub(super) ordered_map::Entries<'a, K, V, TreeMemory<M>>,
45);
46fn entry<K, V>((key, bytes): (K, ordered_map::EncodedValue)) -> MapEntry<K, V> {
47    MapEntry {
48        key,
49        bytes,
50        value: PhantomData,
51    }
52}
53impl<K: Storable + Ord + Clone, V: Storable, M: Memory> Iterator for MapIter<'_, K, V, M> {
54    type Item = MapEntry<K, V>;
55    fn next(&mut self) -> Option<Self::Item> {
56        self.0.next().map(entry)
57    }
58    fn nth(&mut self, n: usize) -> Option<Self::Item> {
59        self.0.nth(n).map(entry)
60    }
61    fn last(mut self) -> Option<Self::Item> {
62        // The reverse cursor already respects bounds and consumption from either end.
63        self.next_back()
64    }
65    fn count(self) -> usize {
66        self.0.count()
67    }
68    fn size_hint(&self) -> (usize, Option<usize>) {
69        self.0.size_hint()
70    }
71}
72impl<K: Storable + Ord + Clone, V: Storable, M: Memory> DoubleEndedIterator
73    for MapIter<'_, K, V, M>
74{
75    fn next_back(&mut self) -> Option<Self::Item> {
76        self.0.next_back().map(entry)
77    }
78    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
79        self.0.nth_back(n).map(entry)
80    }
81}