oca_dag/versioning/
mod.rs

1pub mod bundle;
2pub mod ocafile;
3use crate::data_storage::DataStorage;
4
5pub struct Graph {
6    pub db: Box<dyn DataStorage>,
7}
8
9#[allow(dead_code)]
10impl Graph {
11    fn new(db: Box<dyn DataStorage>) -> Self {
12        Self { db }
13    }
14
15    pub fn add(&self, new: &str, to: Option<&str>) -> Result<(), String> {
16        self.db.insert(
17            &format!("{}.upscending", new),
18            &self.generate_parents_digests(to),
19        )?;
20
21        if let Some(to) = to {
22            let k = &format!("{}.downscending", to);
23            let children_digests: Option<Vec<u8>> = self.db.get(k)?;
24            self.db.insert(
25                &format!("{}.downscending", to),
26                &self.update_children_digests(children_digests.as_deref(), new),
27            )?;
28        }
29
30        Ok(())
31    }
32
33    fn generate_parents_digests(&self, parent_said: Option<&str>) -> Vec<u8> {
34        let mut digests: Vec<u8> = Vec::new();
35        if let Some(to) = parent_said {
36            digests.push(to.len().try_into().unwrap());
37            digests.extend(to.as_bytes());
38        }
39        digests
40    }
41
42    fn update_children_digests(&self, children_digest: Option<&[u8]>, new: &str) -> Vec<u8> {
43        let mut digests: Vec<u8> = Vec::new();
44        if let Some(children_digest) = children_digest {
45            digests.extend(children_digest);
46        }
47        digests.push(new.len().try_into().unwrap());
48        digests.extend(new.as_bytes());
49        digests
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56    use crate::data_storage::{DataStorage, SledDataStorage};
57
58    #[test]
59    fn test_history() {
60        let db = SledDataStorage::open("db_test");
61        let graph = Graph::new(Box::new(db));
62        let _ = graph.add("dag1", None);
63        let _ = graph.add("dag2", Some("dag1"));
64        let _ = graph.add("dag3", Some("dag2"));
65        let _ = graph.add("dag4", Some("dag2"));
66        let _ = graph.add("dag5", Some("dag4"));
67
68        /* dbg!(graph.db.get("dag1.upscending"));
69        dbg!(graph.db.get("dag1.downscending"));
70        dbg!(graph.db.get("dag2.upscending"));
71        dbg!(graph.db.get("dag2.downscending"));
72        dbg!(graph.db.get("dag3.upscending"));
73        dbg!(graph.db.get("dag3.downscending"));
74        dbg!(graph.db.get("dag4.upscending"));
75        dbg!(graph.db.get("dag4.downscending"));
76        dbg!(graph.db.get("dag5.upscending"));
77        dbg!(graph.db.get("dag5.downscending")); */
78    }
79}