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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use std::ops::Index;
use std::collections::{HashMap, hash_map};
use crate::SplitAddr::{self,Prefix,Term};


/// Hierarchical prefix tree
#[derive(Debug,Clone,PartialEq)]
pub struct Trie<V> {
    leaf_nodes: HashMap<String,V>,
    internal_nodes: HashMap<String,Trie<V>>
}

impl<V> Trie<V> {
    /// Construct an empty Trie.
    pub fn new() -> Self {
        Trie {
            leaf_nodes: HashMap::new(),
            internal_nodes: HashMap::new()
        }
    }

    /// Return `true` if a Trie is empty (has no leaf or internal nodes), otherwise `false`.
    pub fn is_empty(&self) -> bool {
        self.leaf_nodes.is_empty() && self.internal_nodes.is_empty()
    }

    /// Return `true` if a Trie has a leaf node at `addr`, otherwise `false`.
    pub fn has_leaf_node(&self, addr: &str) -> bool {
        match SplitAddr::from_addr(addr) {
            Term(addr) => {
                self.leaf_nodes.contains_key(addr)
            }
            Prefix(first, rest) => {
                if self.internal_nodes.contains_key(first) {
                    self.internal_nodes[first].has_leaf_node(rest)
                } else {
                    false
                }
            }
        }
    }

    /// Return `Some(&value)` if `self` contains a `value` located at `addr`, otherwise `None`.
    pub fn get_leaf_node(&self, addr: &str) -> Option<&V> {
        match SplitAddr::from_addr(addr) {
            Term(addr) => {
                self.leaf_nodes.get(addr)
            }
            Prefix(first, rest) => {
                self.internal_nodes[first].get_leaf_node(rest)
            }
        }
    }

    /// Insert `value` as a leaf node located at `addr`.
    /// 
    /// If there was a value `prev` located at `addr`, return `Some(prev)`, otherwise `None`.
    pub fn insert_leaf_node(&mut self, addr: &str, value: V) -> Option<V> {
        match SplitAddr::from_addr(addr) {
            Term(addr) => {
                self.leaf_nodes.insert(addr.to_string(), value)
            }
            Prefix(first, rest) => {
                let node = self.internal_nodes
                    .entry(first.to_string())
                    .or_insert(Trie::new());
                node.insert_leaf_node(rest, value)
            }
        }
    }

    /// Return `Some(value)` if `self` contains a `value` located at `addr` and remove `value` from the leaf nodes, otherwise return `None`.
    pub fn remove_leaf_node(&mut self, addr: &str) -> Option<V> {
        match SplitAddr::from_addr(addr) {
            Term(addr) => {
                self.leaf_nodes.remove(addr)
            }
            Prefix(first, rest) => {
                let node = self.internal_nodes.get_mut(first).unwrap();
                let leaf = node.remove_leaf_node(rest);
                if node.is_empty() {
                    self.remove_internal_node(first);
                }
                leaf
            }
        }
    }

    /// Return an iterator over a Trie's leaf nodes.
    pub fn leaf_iter(&self) -> hash_map::Iter<'_, String, V> {
        self.leaf_nodes.iter()
    }

    /// Return `true` if a Trie has an internal node at `addr`, otherwise `false`.
    pub fn has_internal_node(&self, addr: &str) -> bool {
        match SplitAddr::from_addr(addr) {
            Term(addr) => {
                self.internal_nodes.contains_key(addr)
            }
            Prefix(first, rest) => {
                if self.internal_nodes.contains_key(first) {
                    self.internal_nodes[first].has_internal_node(rest)
                } else {
                    false
                }
            }
        }
    }

    /// Return `Some(&subtrie)` if `self` contains a `subtrie` located at `addr`, otherwise `None`.
    pub fn get_internal_node(&self, addr: &str) -> Option<&Self> {
        match SplitAddr::from_addr(addr) {
            Term(addr) => {
                self.internal_nodes.get(addr)
            }
            Prefix(first, rest) => {
                self.internal_nodes[first].get_internal_node(rest)
            }
        }
    }

    /// Insert `subtrie` as an internal node located at `addr`.
    /// 
    /// If there was a value `prev_subtrie` located at `addr`, return `Some(prev_subtrie)`, otherwise `None`.
    /// Panics if `subtrie.is_empty()`.
    pub fn insert_internal_node(&mut self, addr: &str, new_node: Self) -> Option<Trie<V>> {
        match SplitAddr::from_addr(addr) {
            Term(addr) => {
                if !new_node.is_empty() {
                    self.internal_nodes.insert(addr.to_string(), new_node)
                } else {
                    panic!("attempted to insert empty inode")
                }
            }
            Prefix(first, rest) => {
                let node = self.internal_nodes
                    .entry(first.to_string())
                    .or_insert(Trie::new());
                node.insert_internal_node(rest, new_node)
            }
        }
    }

    /// Return `Some(subtrie)` if `self` contains a `subtrie` located at `addr` and remove `subtrie` from the internal nodes, otherwise return `None`.
    pub fn remove_internal_node(&mut self, addr: &str) -> Option<Trie<V>> {
        match SplitAddr::from_addr(addr) {
            Term(addr) => {
                self.internal_nodes.remove(addr)
            }
            Prefix(first, _) => {
                self.internal_nodes.remove(first)
            }
        }
    }

    /// Return an iterator over a Trie's internal nodes.
    pub fn internal_iter(&self) -> hash_map::Iter<'_, String, Trie<V>> {
        self.internal_nodes.iter()
    }

    /// Merge `other` into `self`, freeing previous values and subtries at each `addr` in `self` if `other` also has an entry at `addr`.
    /// 
    /// Returns the mutated `self`.
    pub fn merge(mut self, other: Self) -> Self {
        for (addr, value) in other.leaf_nodes.into_iter() {
            self.insert_leaf_node(&addr, value);
        }
        for (addr, subtrie) in other.internal_nodes.into_iter() {
            self.insert_internal_node(&addr, subtrie);
        }
        self
    }
}


// specializations

impl<V> Trie<(V,f64)> {
    /// Return the sum of all the weights of the leaf nodes and the recursive sum of all internal nodes.
    pub fn sum(&self) -> f64 {
        self.internal_nodes.values().fold(0., |acc, t| acc + t.sum()) +
        self.leaf_nodes.values().fold(0., |acc, v| acc + v.1)
    }

    /// Convert a weighted `Trie` into the equivalent unweighted version by discarding all the weights.
    pub fn into_unweighted(self) -> Trie<V> {
        Trie {
            internal_nodes: self.internal_nodes.into_iter().map(|(addr, t)| (addr, t.into_unweighted())).collect::<_>(),
            leaf_nodes: self.leaf_nodes.into_iter().map(|(addr, v)| (addr, v.0)).collect::<_>()
        }
    }

    /// Convert an unweighted `Trie` into the equivalent weighted version by adding a weight of `0.` to all leaf nodes.
    pub fn from_unweighted(trie: Trie<V>) -> Self {
        Trie {
            internal_nodes: trie.internal_nodes.into_iter().map(|(addr, t)| (addr, Self::from_unweighted(t))).collect::<_>(),
            leaf_nodes: trie.leaf_nodes.into_iter().map(|(addr, v)| (addr, (v, 0.))).collect::<_>()
        }
    }
}

use std::{rc::Rc,any::Any};

impl Trie<Rc<dyn Any>> {
    /// Optimistically casts the reference-counted `dyn Any` at `addr` into type `V`, and returns a cloned value.
    pub fn read<V: 'static + Clone>(&self, addr: &str) -> V {
        self.get_leaf_node(addr)
            .unwrap()
            .clone()
            .downcast::<V>()
            .ok()
            .unwrap()
            .as_ref()
            .clone()
    }
}

impl Trie<(Rc<dyn Any>,f64)> {
    /// Optimistically casts the reference-counted `dyn Any` at `addr` into type `V`, and returns a cloned value.
    pub fn read<V: 'static + Clone>(&self, addr: &str) -> V {
        self.get_leaf_node(addr)
            .unwrap().0
            .clone()
            .downcast::<V>()
            .ok()
            .unwrap()
            .as_ref()
            .clone()
    }
}

impl<V> Index<&str> for Trie<V> {
    type Output = V;

    fn index(&self, index: &str) -> &Self::Output {
        self.get_leaf_node(index).unwrap()
    }
}