ic_storage/adapter/
iteration.rs1use super::{Memory, Storable, bridge::TreeMemory};
3use crate::{DefaultMemoryImpl, ordered_map};
4use std::{borrow::Cow, marker::PhantomData};
5
6pub 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 pub const fn key(&self) -> &K {
19 &self.key
20 }
21 pub fn value(&self) -> V {
23 ordered_map::decode(Cow::Borrowed(self.bytes.as_slice()))
24 }
25 pub fn into_pair(self) -> (K, V) {
27 (self.key, self.bytes.decode())
28 }
29 pub fn into_key(self) -> K {
31 self.key
32 }
33 pub fn into_value(self) -> V {
35 self.bytes.decode()
36 }
37}
38pub 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 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}