Skip to main content

luminos_contracts/support/interacts_with_data/
mod.rs

1mod contains;
2
3use std::collections::{BTreeMap, HashMap};
4
5pub trait InteractsWithData {
6    type Value;
7    type Item;
8
9    /// Get the data for the container.
10    fn data(&self) -> &Self::Value;
11
12    /// Get all of the data
13    fn all(&self) -> Self::Value where Self::Value: Clone {
14        self.data().clone()
15    }
16
17    /// Does the data container the key? 
18    fn exists(&self, key: &Self::Item) -> bool where Self::Value: Contains<Self::Item> {
19        self.data().contains_item(key)
20    }
21
22    /// Does the data contain the key?
23    fn has(&self, key: &Self::Item) -> bool where Self::Value: Contains<Self::Item> {
24        self.exists(key)
25    }
26
27    /// Execute the closure when the instnce contains the given key.
28    fn when_has<F>(&mut self, key: &Self::Item, mut closure: F ) 
29    where 
30        Self::Value: Contains<Self::Item>,
31        F: FnMut(&mut Self),
32    {
33        if self.has(key) {
34            closure(self);
35        }
36    }
37
38    /// Determine if the instance contains a non-empty value for the key.
39    fn filled(&self, key: &Self::Item) -> bool {
40        false
41    }
42
43    /// Determine if the instance contains an empty value for the key.
44    fn is_not_filled(&self, key: &Self::Item) -> bool {
45        true
46    }
47
48    /// Do any of the given keys contain a non-empty value?
49    fn any_filled(&self, keys: Vec<&Self::Item>) -> bool {
50        false
51    }
52
53}
54
55pub trait IntoData {
56    type Item;
57    type IntoIter: IntoIterator<Item = Self::Item>;
58
59    fn data(self) -> Self::IntoIter;
60}
61
62pub trait Contains<T> {
63    fn contains_item(&self, item: &T) -> bool;
64}
65
66
67// Test module
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[test]
73    fn test_vec_interacts_with_data() {
74        let vec = vec![1, 2, 3, 4];
75        
76        assert_eq!(vec.all(), vec![1, 2, 3, 4]);
77        
78        assert!(vec.exists(&3)); 
79        assert!(!vec.exists(&5)); 
80    }
81
82    #[test]
83    fn test_hashmap_interacts_with_data() {
84        let mut map = HashMap::new();
85        map.insert("a", 1);
86        map.insert("b", 2);
87
88        let expected_map = HashMap::from([("a", 1), ("b", 2)]);
89        assert_eq!(map.all(), expected_map);
90        
91        assert!(map.exists(&"b")); 
92        assert!(!map.exists(&"c")); 
93    }
94
95    #[test]
96    fn test_btreemap_interacts_with_data() {
97        let mut map = BTreeMap::new();
98        map.insert("a", 1);
99        map.insert("b", 2);
100
101        let expected_map = BTreeMap::from([("a", 1), ("b", 2)]);
102        assert_eq!(map.all(), expected_map);
103        
104        assert!(map.exists(&"b")); 
105        assert!(!map.exists(&"c")); 
106    }
107}