Skip to main content

nimiq_database/mdbx/
iterators.rs

1use std::{borrow::Cow, marker::PhantomData};
2
3use libmdbx::{TransactionKind, RO, RW};
4use nimiq_database_value::FromDatabaseBytes;
5
6use crate::traits::{Row, Table};
7
8/// Iterates over database entries (key, value pairs).
9/// Can be instantiated for both read and write transactions.
10pub struct IntoIter<'txn, Kind: TransactionKind, T: Table> {
11    pub(super) iter:
12        <libmdbx::IterDup<'txn, 'txn, Kind, Cow<'txn, [u8]>, Cow<'txn, [u8]>> as Iterator>::Item,
13    pub(super) _t: PhantomData<T>,
14}
15
16impl<Kind: TransactionKind, T: Table> Iterator for IntoIter<'_, Kind, T> {
17    type Item = Row<T>;
18
19    fn next(&mut self) -> Option<Self::Item> {
20        self.iter.next().map(|item| {
21            let (key, value) = item.unwrap();
22            (
23                FromDatabaseBytes::from_key_bytes(&key),
24                FromDatabaseBytes::from_value_bytes(&value),
25            )
26        })
27    }
28}
29
30/// Proxy that abstracts away the transaction kind.
31pub enum IntoIterProxy<'txn, T: Table> {
32    Read(IntoIter<'txn, RO, T>),
33    Write(IntoIter<'txn, RW, T>),
34}
35
36impl<T: Table> Iterator for IntoIterProxy<'_, T> {
37    type Item = Row<T>;
38
39    fn next(&mut self) -> Option<Self::Item> {
40        match self {
41            IntoIterProxy::Read(iter) => iter.next(),
42            IntoIterProxy::Write(iter) => iter.next(),
43        }
44    }
45}