summaryrefslogtreecommitdiffstats
path: root/src/dag_backend.rs
blob: a91a8ec842601fd1df7011f9ef3bd6132d0ea4b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

use anyhow::Result;
use async_trait::async_trait;

use crate::NodeId;
use crate::Node;

#[async_trait]
pub trait DagBackend<Id, N>
    where N: Node,
          Id: NodeId + Send
{
    async fn get(&self, id: Id) -> Result<Option<N>>;
    async fn put(&mut self, node: N) -> Result<Id>;
}

#[cfg(test)]
mod tests {
    use std::pin::Pin;

    use anyhow::Result;
    use anyhow::anyhow;
    use async_trait::async_trait;
    use tokio_test::block_on;

    use crate::test_impl as test;
    use crate::*;

    #[test]
    fn test_backend_get() {
        let b = test::Backend::new(vec![Some(test::Node {
            id: test::Id(0),
            parents: vec![],
            data: 42,
        })]);

        let node = tokio_test::block_on(b.get(test::Id(0)));
        assert!(node.is_ok());
        let node = node.unwrap();

        assert!(node.is_some());
        let node = node.unwrap();

        assert_eq!(node.data, 42);
        assert_eq!(node.id, test::Id(0));
        assert!(node.parents.is_empty());
    }

    #[test]
    fn test_backend_put() {
        let mut b = test::Backend::new(vec![Some(test::Node {
            id: test::Id(0),
            parents: vec![],
            data: 42,
        })]);

        let id = tokio_test::block_on(b.put({
            test::Node {
                id: test::Id(1),
                parents: vec![],
                data: 43,
            }
        }));

        {
            let node = tokio_test::block_on(b.get(test::Id(0)));
            assert!(node.is_ok());
            let node = node.unwrap();

            assert!(node.is_some());
            let node = node.unwrap();

            assert_eq!(node.data, 42);
            assert_eq!(node.id, test::Id(0));
            assert!(node.parents.is_empty());
        }
        {
            let node = tokio_test::block_on(b.get(test::Id(1)));
            assert!(node.is_ok());
            let node = node.unwrap();

            assert!(node.is_some());
            let node = node.unwrap();

            assert_eq!(node.data, 43);
            assert_eq!(node.id, test::Id(1));
            assert!(node.parents.is_empty());
        }
        {
            let node = tokio_test::block_on(b.get(test::Id(2)));
            assert!(node.is_ok());
            let node = node.unwrap();

            assert!(node.is_none());
        }
    }

}