epoch_db/db/
iter.rs

1//! The `iter` module contains the core logic and struct for the database
2//! iteration method.
3
4use std::error::Error;
5use std::str::from_utf8;
6use std::sync::Arc;
7
8use crate::{
9    DB,
10    Metadata
11};
12
13/// This is an iterator struct that represents the Database main iterator
14/// struct.
15pub struct DataIter {
16    pub data: (sled::Iter, Arc<sled::Tree>)
17}
18
19impl Iterator for DataIter {
20    type Item = Result<(String, String, Metadata), Box<dyn Error>>;
21
22    fn next(&mut self) -> Option<Self::Item> {
23        let data_iter = &mut self.data.0;
24
25        let data = match data_iter.next()? {
26            Ok(a) => a,
27            Err(e) => {
28                return Some(Err(Box::new(e)));
29            }
30        };
31
32        let (kb, vb) = data;
33
34        let meta_tree = &mut self.data.1;
35
36        let mb = match meta_tree.get(&kb) {
37            Ok(a) => a,
38            Err(e) => {
39                return Some(Err(Box::new(e)));
40            }
41        }?;
42
43        let key = match from_utf8(&kb) {
44            Ok(a) => a,
45            Err(e) => {
46                return Some(Err(Box::new(e)));
47            }
48        }
49        .to_string();
50
51        let value = match from_utf8(&vb) {
52            Ok(a) => a,
53            Err(e) => {
54                return Some(Err(Box::new(e)));
55            }
56        }
57        .to_string();
58
59        let meta = match Metadata::from_u8(&mb) {
60            Ok(a) => a,
61            Err(e) => {
62                return Some(Err(Box::new(e)));
63            }
64        };
65
66        Some(Ok((key, value, meta)))
67    }
68}
69
70impl DB {
71    /// This function returns the iterator of the database, which will contain a
72    /// key and its corresponding value in each iteration, (key, value).
73    pub fn iter(&mut self) -> DataIter {
74        DataIter {
75            data: (self.data_tree.iter(), self.meta_tree.clone())
76        }
77    }
78}