extended-collections 0.2.0

An extension to the collections in the standard library with various data structures.
Documentation
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use radix::map::{RadixMap, RadixMapIntoIter, RadixMapIter};

/// An ordered set implemented using a radix tree.
///
/// A radix tree is a space optimized trie where nodes are merged with its parent if it is the only
/// child or if it contains a value. This particular implementation of a radix tree accepts keys as
/// byte vectors for flexibility. Additionally, in order to conserve memory usage, the children of
/// a node are represented as a singly linked list rather than an array of pointers. The
/// performance of this radix tree is relatively fast given that the keys are fairly sparse. The
/// children should be represented as a fixed length array of size 256 if the tree is dense for
/// performance.
///
/// # Examples
/// ```
/// use extended_collections::radix::RadixSet;
///
/// let mut set = RadixSet::new();
/// set.insert("foo".as_bytes());
/// set.insert("foobar".as_bytes());
///
/// assert_eq!(set.len(), 2);
///
/// assert_eq!(set.min(), Some(String::from("foo").into_bytes()));
///
/// assert_eq!(
///     set.get_longest_prefix(&"foob".as_bytes()),
///     vec![String::from("foobar").into_bytes()],
/// );
///
/// assert_eq!(
///     set.remove("foo".as_bytes()),
///     Some(String::from("foo").into_bytes()),
/// );
/// ```
pub struct RadixSet {
    map: RadixMap<()>,
}

impl RadixSet {
    /// Constructs a new, empty `RadixSet`.
    ///
    /// # Examples
    /// ```
    /// use extended_collections::radix::RadixSet;
    ///
    /// let set = RadixSet::new();
    /// ```
    pub fn new() -> Self {
        RadixSet {
            map: RadixMap::new(),
        }
    }

    /// Inserts a key into the set. If the key already exists in the set, it will return and
    /// replace the old key.
    ///
    /// # Examples
    /// ```
    /// use extended_collections::radix::RadixSet;
    ///
    /// let mut set = RadixSet::new();
    /// assert_eq!(set.insert("foo".as_bytes()), None);
    /// assert!(set.contains("foo".as_bytes()));
    /// assert_eq!(
    ///     set.insert("foo".as_bytes()),
    ///     Some(String::from("foo").into_bytes()),
    /// );
    /// ```
    pub fn insert(&mut self, key: &[u8]) -> Option<Vec<u8>> {
        self.map.insert(key, ()).map(|pair| pair.0)
    }

    /// Removes a key from the set. If the key exists in the set, it will return the associated
    /// key. Otherwise it will return `None`.
    ///
    /// # Examples
    /// ```
    /// use extended_collections::radix::RadixSet;
    ///
    /// let mut set = RadixSet::new();
    /// set.insert("foo".as_bytes());
    /// assert_eq!(
    ///     set.remove("foo".as_bytes()),
    ///     Some(String::from("foo").into_bytes()),
    /// );
    /// assert_eq!(set.remove("foobar".as_bytes()), None);
    /// ```
    pub fn remove(&mut self, key: &[u8]) -> Option<Vec<u8>> {
        self.map.remove(key).map(|pair| pair.0)
    }

    /// Checks if a key exists in the set.
    ///
    /// # Examples
    /// ```
    /// use extended_collections::radix::RadixSet;
    ///
    /// let mut set = RadixSet::new();
    /// set.insert("foo".as_bytes());
    /// assert!(set.contains("foo".as_bytes()));
    /// assert!(!set.contains("foobar".as_bytes()));
    /// ```
    pub fn contains(&self, key: &[u8]) -> bool {
        self.map.contains_key(key)
    }

    /// Returns the number of elements in the set.
    ///
    /// # Examples
    /// ```
    /// use extended_collections::radix::RadixSet;
    ///
    /// let mut set = RadixSet::new();
    /// set.insert("foo".as_bytes());
    /// assert_eq!(set.len(), 1);
    /// ```
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Returns `true` if the set is empty.
    ///
    /// # Examples
    /// ```
    /// use extended_collections::radix::RadixSet;
    ///
    /// let set = RadixSet::new();
    /// assert!(set.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Clears the set, removing all values.
    ///
    /// # Examples
    /// ```
    /// use extended_collections::radix::RadixSet;
    ///
    /// let mut set = RadixSet::new();
    /// set.insert("foo".as_bytes());
    /// set.insert("foobar".as_bytes());
    /// set.clear();
    /// assert_eq!(set.is_empty(), true);
    /// ```
    pub fn clear(&mut self) {
        self.map.clear();
    }

    /// Returns all keys that share the longest common prefix with the specified key.
    ///
    /// # Examples
    /// ```
    /// use extended_collections::radix::RadixSet;
    ///
    /// let mut set = RadixSet::new();
    /// set.insert("foo".as_bytes());
    /// set.insert("foobar".as_bytes());
    ///
    /// assert_eq!(
    ///     set.get_longest_prefix(&"foob".as_bytes()),
    ///     vec![String::from("foobar").into_bytes()],
    /// );
    /// ```
    pub fn get_longest_prefix(&self, key: &[u8]) -> Vec<Vec<u8>> {
        self.map.get_longest_prefix(key)
    }

    /// Returns the minimum lexographic key of the set. Returns `None` if the set is empty.
    ///
    /// # Examples
    /// ```
    /// use extended_collections::radix::RadixSet;
    ///
    /// let mut set = RadixSet::new();
    /// set.insert("foo".as_bytes());
    /// set.insert("foobar".as_bytes());
    /// assert_eq!(set.min(), Some(String::from("foo").into_bytes()));
    /// ```
    pub fn min(&self) -> Option<Vec<u8>> {
        self.map.min()
    }

    /// Returns the maximum lexographic key of the set. Returns `None` if the set is empty.
    ///
    /// # Examples
    /// ```
    /// use extended_collections::radix::RadixSet;
    ///
    /// let mut set = RadixSet::new();
    /// set.insert("foo".as_bytes());
    /// set.insert("foobar".as_bytes());
    /// assert_eq!(set.max(), Some(String::from("foobar").into_bytes()));
    /// ```
    pub fn max(&self) -> Option<Vec<u8>> {
        self.map.max()
    }

    /// Returns an iterator over the set. The iterator will yield keys in lexographic order.
    ///
    /// # Examples
    /// ```
    /// use extended_collections::radix::RadixSet;
    ///
    /// let mut set = RadixSet::new();
    /// set.insert("foo".as_bytes());
    /// set.insert("foobar".as_bytes());
    ///
    /// let mut iterator = set.iter();
    /// assert_eq!(iterator.next(), Some(String::from("foo").into_bytes()));
    /// assert_eq!(iterator.next(), Some(String::from("foobar").into_bytes()));
    /// assert_eq!(iterator.next(), None);
    /// ```
    pub fn iter(&self) -> RadixSetIter {
        RadixSetIter {
            map_iter: self.map.iter(),
        }
    }
}

impl IntoIterator for RadixSet {
    type Item = Vec<u8>;
    type IntoIter = RadixSetIntoIter;

    fn into_iter(self) -> Self::IntoIter {
        Self::IntoIter {
            map_iter: self.map.into_iter(),
        }
    }
}

impl<'a> IntoIterator for &'a RadixSet {
    type Item = Vec<u8>;
    type IntoIter = RadixSetIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// An owning iterator for `RadixSet`.
///
/// This iterator traverse the elements of the set in lexographic order and yields owned keys.
pub struct RadixSetIntoIter {
    map_iter: RadixMapIntoIter<()>,
}

impl Iterator for RadixSetIntoIter {
    type Item = Vec<u8>;

    fn next(&mut self) -> Option<Self::Item> {
        self.map_iter.next().map(|pair| pair.0)
    }
}

/// An iterator for `RadixSet`.
///
/// This iterator traverse the elements of the set in lexographic order and yields owned keys.
pub struct RadixSetIter<'a> {
    map_iter: RadixMapIter<'a, ()>,
}

impl<'a> Iterator for RadixSetIter<'a> {
    type Item = Vec<u8>;

    fn next(&mut self) -> Option<Self::Item> {
        self.map_iter.next().map(|pair| pair.0)
    }
}

impl Default for RadixSet {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::RadixSet;

    fn get_bytes_slice(key: &str) -> &[u8] {
        key.as_bytes()
    }

    fn get_bytes_vec(key: &str) -> Vec<u8> {
        String::from(key).into_bytes()
    }

    #[test]
    fn test_len_empty() {
        let set = RadixSet::new();
        assert_eq!(set.len(), 0);
    }

    #[test]
    fn test_is_empty() {
        let set = RadixSet::new();
        assert!(set.is_empty());
    }

    #[test]
    fn test_min_max_empty() {
        let set = RadixSet::new();
        assert_eq!(set.min(), None);
        assert_eq!(set.max(), None);
    }

    #[test]
    fn test_insert() {
        let mut set = RadixSet::new();
        assert_eq!(set.insert(get_bytes_slice("aaaa")), None);
        assert_eq!(set.insert(get_bytes_slice("aabb")), None);

        assert_eq!(set.insert(get_bytes_slice("bb")), None);
        assert_eq!(set.insert(get_bytes_slice("bbbb")), None);

        assert_eq!(set.insert(get_bytes_slice("cccc")), None);
        assert_eq!(set.insert(get_bytes_slice("cc")), None);

        assert_eq!(
            set.iter().collect::<Vec<Vec<u8>>>(),
            [
                get_bytes_vec("aaaa"),
                get_bytes_vec("aabb"),
                get_bytes_vec("bb"),
                get_bytes_vec("bbbb"),
                get_bytes_vec("cc"),
                get_bytes_vec("cccc"),
            ]
        );
    }

    #[test]
    fn test_insert_replace() {
        let mut set = RadixSet::new();
        assert_eq!(set.insert(get_bytes_slice("a")), None);
        assert_eq!(
            set.insert(get_bytes_slice("a")),
            Some(get_bytes_vec("a")),
        );
    }

    #[test]
    fn test_remove() {
        let mut set = RadixSet::new();
        set.insert(get_bytes_slice("aaaa"));
        set.insert(get_bytes_slice("aabb"));

        set.insert(get_bytes_slice("bb"));
        set.insert(get_bytes_slice("bbbb"));
        set.insert(get_bytes_slice("bbaa"));

        set.insert(get_bytes_slice("cccc"));
        set.insert(get_bytes_slice("ccdd"));
        set.insert(get_bytes_slice("cc"));

        assert_eq!(set.remove(get_bytes_slice("a")), None);

        assert_eq!(set.remove(get_bytes_slice("aaaa")), Some(get_bytes_vec("aaaa")));
        assert_eq!(set.remove(get_bytes_slice("aabb")), Some(get_bytes_vec("aabb")));

        assert_eq!(set.remove(get_bytes_slice("bb")), Some(get_bytes_vec("bb")));
        assert_eq!(set.remove(get_bytes_slice("bbbb")), Some(get_bytes_vec("bbbb")));
        assert_eq!(set.remove(get_bytes_slice("bbaa")), Some(get_bytes_vec("bbaa")));

        assert_eq!(set.remove(get_bytes_slice("cccc")), Some(get_bytes_vec("cccc")));
        assert_eq!(set.remove(get_bytes_slice("ccdd")), Some(get_bytes_vec("ccdd")));
        assert_eq!(set.remove(get_bytes_slice("cc")), Some(get_bytes_vec("cc")));

        assert_eq!(set.remove(get_bytes_slice("a")), None);
    }

    #[test]
    fn test_contains_key() {
        let mut set = RadixSet::new();
        assert_eq!(set.insert(get_bytes_slice("a")), None);
        assert!(set.contains(get_bytes_slice("a")));
    }

    #[test]
    fn test_get_longest_prefix() {
        let mut set = RadixSet::new();
        set.insert(get_bytes_slice("aaaa"));
        assert_eq!(
            set.get_longest_prefix(&get_bytes_slice("aaa")),
            vec![get_bytes_vec("aaaa")],
        );

        let mut set = RadixSet::new();
        set.insert(get_bytes_slice("aaaa"));
        set.insert(get_bytes_slice("aaab"));
        assert_eq!(
            set.get_longest_prefix(&get_bytes_slice("aaa")),
            vec![get_bytes_vec("aaaa"), get_bytes_vec("aaab")],
        );

        let mut set = RadixSet::new();
        set.insert(get_bytes_slice("aaa"));
        set.insert(get_bytes_slice("aaaa"));
        set.insert(get_bytes_slice("aaab"));
        assert_eq!(
            set.get_longest_prefix(&get_bytes_slice("aaa")),
            vec![
                get_bytes_vec("aaa"),
                get_bytes_vec("aaaa"),
                get_bytes_vec("aaab"),
            ],
        );

        let mut set = RadixSet::new();
        set.insert(get_bytes_slice("aa"));
        assert_eq!(
            set.get_longest_prefix(&get_bytes_slice("aaa")),
            vec![get_bytes_vec("aa")],
        );

        let mut set = RadixSet::new();
        set.insert(get_bytes_slice("aaba"));
        set.insert(get_bytes_slice("aabb"));
        assert_eq!(
            set.get_longest_prefix(&get_bytes_slice("aaa")),
            vec![get_bytes_vec("aaba"), get_bytes_vec("aabb")],
        );

        let mut set = RadixSet::new();
        set.insert(get_bytes_slice("b"));
        assert_eq!(set.get_longest_prefix(&get_bytes_slice("aaa")).len(), 0);
    }

    #[test]
    fn test_min_max() {
        let mut set = RadixSet::new();

        set.insert(get_bytes_slice("a"));
        set.insert(get_bytes_slice("aa"));
        set.insert(get_bytes_slice("ba"));
        set.insert(get_bytes_slice("bb"));

        assert_eq!(set.min(), Some(get_bytes_vec("a")));
        assert_eq!(set.max(), Some(get_bytes_vec("bb")));
    }

    #[test]
    fn test_into_iter() {
        let mut set = RadixSet::new();
        set.insert(get_bytes_slice("a"));
        set.insert(get_bytes_slice("ab"));
        set.insert(get_bytes_slice("aa"));

        assert_eq!(
            set.into_iter().collect::<Vec<Vec<u8>>>(),
            vec![get_bytes_vec("a"), get_bytes_vec("aa"), get_bytes_vec("ab")],
        );
    }

    #[test]
    fn test_iter() {
        let mut set = RadixSet::new();
        set.insert(get_bytes_slice("a"));
        set.insert(get_bytes_slice("ab"));
        set.insert(get_bytes_slice("aa"));

        assert_eq!(
            (&set).into_iter().collect::<Vec<Vec<u8>>>(),
            vec![get_bytes_vec("a"), get_bytes_vec("aa"), get_bytes_vec("ab")],
        );
    }
}