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
use eav::{eavi::EntityAttributeValueIndex, query::EaviQuery};
use error::{HcResult, HolochainError};
use objekt;
use std::{
collections::BTreeSet,
fmt::Debug,
sync::{Arc, RwLock},
};
pub trait EntityAttributeValueStorage: objekt::Clone + Send + Sync + Debug {
fn add_eavi(
&mut self,
eav: &EntityAttributeValueIndex,
) -> Result<Option<EntityAttributeValueIndex>, HolochainError>;
fn fetch_eavi(
&self,
query: &EaviQuery,
) -> Result<BTreeSet<EntityAttributeValueIndex>, HolochainError>;
}
clone_trait_object!(EntityAttributeValueStorage);
#[derive(Clone, Debug, Default)]
pub struct ExampleEntityAttributeValueStorage {
storage: Arc<RwLock<BTreeSet<EntityAttributeValueIndex>>>,
}
impl ExampleEntityAttributeValueStorage {
pub fn new() -> ExampleEntityAttributeValueStorage {
Default::default()
}
}
impl EntityAttributeValueStorage for ExampleEntityAttributeValueStorage {
fn add_eavi(
&mut self,
eav: &EntityAttributeValueIndex,
) -> Result<Option<EntityAttributeValueIndex>, HolochainError> {
let mut map = self.storage.write()?;
let new_eav = increment_key_till_no_collision(eav.clone(), map.clone())?;
map.insert(new_eav.clone());
Ok(Some(new_eav.clone()))
}
fn fetch_eavi(
&self,
query: &EaviQuery,
) -> Result<BTreeSet<EntityAttributeValueIndex>, HolochainError> {
let lock = self.storage.read()?;
let set = (*lock).clone();
let iter = set.iter().cloned();
Ok(query.run(iter))
}
}
impl PartialEq for dyn EntityAttributeValueStorage {
fn eq(&self, other: &dyn EntityAttributeValueStorage) -> bool {
let query = EaviQuery::default();
self.fetch_eavi(&query) == other.fetch_eavi(&query)
}
}
pub fn increment_key_till_no_collision(
mut eav: EntityAttributeValueIndex,
map: BTreeSet<EntityAttributeValueIndex>,
) -> HcResult<EntityAttributeValueIndex> {
if map.iter().any(|e| e.index() == eav.index()) {
let timestamp = eav.clone().index() + 1;
eav.set_index(timestamp);
increment_key_till_no_collision(eav, map)
} else {
Ok(eav)
}
}