1use std::cmp::Ordering;
2
3mod avl;
4
5pub type ImmutableSet<T> = avl::ImmutAvlTree<T>;
6
7#[derive(Clone, Debug)]
8struct ImmutableMapContent<T: PartialOrd + Clone, V: Clone + Default> {
9 key: T,
10 val: V,
11}
12
13impl<T: PartialOrd + Clone, V: Clone + Default> PartialOrd for ImmutableMapContent<T, V> {
14 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
15 self.key.partial_cmp(&other.key)
16 }
17}
18
19impl<T: PartialOrd + Clone, V: Clone + Default> PartialEq for ImmutableMapContent<T, V> {
20 fn eq(&self, other: &Self) -> bool {
21 self.key == other.key
22 }
23}
24
25pub struct ImmutableMap<T: PartialOrd + Clone, V: Clone + Default> {
26 set: ImmutableSet<ImmutableMapContent<T, V>>,
27}
28
29impl<T: PartialOrd + Clone, V: Clone + Default> ImmutableMap<T, V> {
30 pub fn new() -> Self {
31 ImmutableMap {
32 set: ImmutableSet::new(),
33 }
34 }
35 pub fn insert(&self, key: T, val: V) -> Self {
36 ImmutableMap {
37 set: self.set.insert(ImmutableMapContent { key, val }),
38 }
39 }
40 pub fn delete(&self, key: T) -> Self {
41 ImmutableMap {
42 set: self.set.delete(ImmutableMapContent {
43 key,
44 val: V::default(),
45 }),
46 }
47 }
48 pub fn contains(&self, key: T, val: V) -> bool {
49 self.set.contains(ImmutableMapContent { key, val })
50 }
51 pub fn size(&self) -> usize {
52 self.set.size()
53 }
54 pub fn get_val_as_ref(&self, key: T) -> Option<&V> {
55 let content = self.set.get_as_ref(ImmutableMapContent {
56 key,
57 val: V::default(),
58 });
59 if let Some(content) = content {
60 Some(&content.val)
61 } else {
62 None
63 }
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70 #[test]
71 fn test() {
72 let set = ImmutableSet::new();
73 let new_set = set.insert(1);
74 assert_eq!(new_set.size(), 1);
75
76 let map = ImmutableMap::new();
77 let new_map = map.insert(1, "abc");
78 assert_eq!(new_map.size(), 1);
79 let new_map = new_map.insert(2, "def");
80 assert_eq!(new_map.get_val_as_ref(2), Some(&"def"));
81 let new_map = new_map.delete(1);
82 assert_eq!(new_map.size(), 1);
83 }
84}