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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#[cfg(test)]
mod tests {
    use crate::TrieNode;

    #[test]
    fn general_tests() {
        let mut trie = TrieNode::new();
        trie.insert(&[0, 1, 2]);
        trie.insert(&[0, 1, 2, 3, 4]);
        trie.insert(&[0, 1, 3]);
        trie.insert(&[]);
        trie.insert(&[]);
        assert!(trie.exists(&[0, 1, 2]));
        assert!(trie.exists(&[0, 1, 2, 3, 4]));
        assert!(trie.exists(&[0, 1, 3]));
        assert!(trie.exists(&[]));
        assert!(!trie.exists(&[1, 2, 3]));
        assert_eq!(
            trie,
            TrieNode {
                prefix: vec![],
                branches: vec![TrieNode {
                    prefix: vec![0, 1],
                    branches: vec![
                        TrieNode {
                            prefix: vec![2],
                            branches: vec![TrieNode {
                                prefix: vec![3, 4],
                                branches: vec![]
                            },]
                        },
                        TrieNode {
                            prefix: vec![3],
                            branches: vec![]
                        }
                    ]
                },]
            }
        )
    }

    #[test]
    fn insert_empty() {
        let mut trie = TrieNode::new();
        trie.insert(&[0, 1, 2]);
        trie.insert(&[]);
        trie.insert(&[0, 1, 2, 3, 4]);
        trie.insert(&[0, 1, 2, 3, 4, 5, 6]);
        assert!(trie.exists(&[0, 1, 2]));
        assert!(trie.exists(&[]));
        assert!(!trie.exists(&[0, 1, 2, 3]));
        assert!(!trie.exists(&[0, 1]));
        assert_eq!(
            trie,
            TrieNode {
                prefix: vec![],
                branches: vec![TrieNode {
                    prefix: vec![0, 1, 2],
                    branches: vec![TrieNode {
                        prefix: vec![3, 4],
                        branches: vec![TrieNode {
                            prefix: vec![5, 6],
                            branches: vec![]
                        }]
                    }]
                },]
            }
        )
    }

    #[test]
    fn insert_very_different_strings() {
        let mut trie = TrieNode::new();
        trie.insert(&[0, 1, 2, 3]);
        trie.insert(&[4, 5, 6, 7]);
        assert_eq!(
            trie,
            TrieNode {
                prefix: vec![],
                branches: vec![
                    TrieNode {
                        prefix: vec![0, 1, 2, 3],
                        branches: vec![]
                    },
                    TrieNode {
                        prefix: vec![4, 5, 6, 7],
                        branches: vec![]
                    }
                ]
            }
        )
    }

    #[test]
    fn get_something_that_exist() {
        let mut trie = TrieNode::new();
        trie.insert(&[0, 1, 2, 3]);
        trie.insert(&[4, 5, 6, 7]);
        assert_eq!(
            trie,
            TrieNode {
                prefix: vec![],
                branches: vec![
                    TrieNode {
                        prefix: vec![0, 1, 2, 3],
                        branches: vec![]
                    },
                    TrieNode {
                        prefix: vec![4, 5, 6, 7],
                        branches: vec![]
                    }
                ]
            }
        );
        assert!(trie.exists(&[0, 1, 2, 3]));
    }

    #[test]
    fn initialize_with_something_big() {
        let mut trie = TrieNode::with_key(&[0, 1, 2, 3]);
        trie.insert(&[0, 1, 2, 3, 4]);
        assert_eq!(
            trie,
            TrieNode {
                prefix: vec![0, 1, 2, 3],
                branches: vec![TrieNode {
                    prefix: vec![4],
                    branches: vec![]
                },]
            }
        );
        assert!(trie.exists(&[0, 1, 2, 3]));
    }

    #[test]
    fn get_empty_exists() {
        let trie = TrieNode::new();
        assert!(trie.exists(&[]));
    }

    #[test]
    fn get_nested_exists() {
        let mut trie = TrieNode::new();
        trie.insert(&[0, 1, 2]);
        trie.insert(&[]);
        trie.insert(&[0, 1, 2, 3, 4]);
        trie.insert(&[0, 1, 2, 3, 4, 5, 6]);
        assert_eq!(
            trie,
            TrieNode {
                prefix: vec![],
                branches: vec![TrieNode {
                    prefix: vec![0, 1, 2],
                    branches: vec![TrieNode {
                        prefix: vec![3, 4],
                        branches: vec![TrieNode {
                            prefix: vec![5, 6],
                            branches: vec![]
                        }]
                    }]
                },]
            }
        );
        assert!(!trie.exists(&[0, 1, 2, 3]));
        assert!(trie.exists(&[0, 1, 2, 3, 4]));
        assert!(!trie.exists(&[0, 1, 2, 3, 4, 5]));
        assert!(trie.exists(&[0, 1, 2, 3, 4, 5, 6]));
    }
}

#[derive(PartialEq, Debug)]
enum Cut {
    Parent(usize),
    Child(usize),
    BothBegin,
    BothMiddle(usize),
    BothEnd,
}

#[derive(PartialEq, Debug)]
pub struct TrieNode {
    prefix: Vec<u8>,
    branches: Vec<TrieNode>,
}

impl TrieNode {
    pub fn new() -> TrieNode {
        TrieNode {
            prefix: vec![],
            branches: vec![],
        }
    }

    pub fn with_key(key: &[u8]) -> TrieNode {
        TrieNode {
            prefix: Vec::from(key),
            branches: vec![],
        }
    }

    pub fn with_branches(branches: Vec<TrieNode>) -> TrieNode {
        TrieNode {
            prefix: vec![],
            branches,
        }
    }

    pub fn with_key_and_branches(key: &[u8], branches: Vec<TrieNode>) -> TrieNode {
        TrieNode {
            prefix: Vec::from(key),
            branches,
        }
    }

    pub fn insert(&mut self, new_key: &[u8]) {
        self.insert_impl(new_key);
    }

    fn insert_impl(&mut self, new_key: &[u8]) -> bool {
        let cut = self.cut_key(new_key);
        match cut {
            Cut::Parent(p) => {
                let drained_key = self.prefix.drain(p..).collect::<Vec<_>>();
                let drained_branch = self.branches.drain(..).collect();
                self.branches.push(TrieNode {
                    prefix: drained_key,
                    branches: drained_branch,
                });
                true
            }
            Cut::Child(c) => {
                let cut_child = &new_key[c..];
                if !self.branches.iter_mut().any(|x| x.insert_impl(cut_child)) {
                    self.branches.push(TrieNode::with_key(cut_child));
                }
                true
            }
            Cut::BothBegin => return false,
            Cut::BothMiddle(p) => {
                let drained_key = self.prefix.drain(p..).collect::<Vec<_>>();
                let drained_children = self.branches.drain(..).collect();
                self.branches.push(TrieNode {
                    prefix: drained_key,
                    branches: drained_children,
                });
                self.branches.push(TrieNode {
                    prefix: Vec::from(&new_key[p..]),
                    branches: vec![],
                });
                true
            }
            Cut::BothEnd => true,
        }
    }

    pub fn exists(&self, key: &[u8]) -> bool {
        match self.cut_key(key) {
            Cut::Parent(_) => false,
            Cut::Child(idx) => self.branches.iter().any(|x| x.exists(&key[idx..])),
            Cut::BothBegin => false,
            Cut::BothMiddle(_) => false,
            Cut::BothEnd => true,
        }
    }

    fn cut_key<'b>(&self, child_key: &'b [u8]) -> Cut {
        let idx = self.prefix.iter().zip(child_key).position(|(l, r)| l != r);
        if let Some(idx) = idx {
            if idx == 0 {
                Cut::BothBegin
            } else {
                Cut::BothMiddle(idx)
            }
        } else {
            let (llen, clen) = (self.prefix.len(), child_key.len());
            match llen.cmp(&clen) {
                std::cmp::Ordering::Less => Cut::Child(llen),
                std::cmp::Ordering::Equal => Cut::BothEnd,
                std::cmp::Ordering::Greater => Cut::Parent(clen),
            }
        }
    }
}