nb-tree 0.2.0-alpha01

Very simple tree structure with generic node and branch data.
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! `Path<B>`s are arrays of branches of type `B`.
//! They are used to designate a position in a [`Tree<N, B>`].
//!
//!
//!
//!
//!
//! [`Tree`]: crate::tree::Tree
//! [`Tree<N, B>`]: crate::tree::Tree
//! [`TreeNode`]: crate::tree::node::TreeNode

use std::collections::vec_deque::{Iter, IterMut};
use std::collections::{vec_deque::IntoIter, VecDeque};
use std::fmt::{Debug as Dbg, Display};
use std::hash::Hash;
use std::ops::{Deref, Index, IndexMut};
use std::str::FromStr;

use crate::prelude::iter::depth::Traversal;

/// Path branch index
pub type PathIDX = usize;

/// A path to a [`Tree`] node.
///
/// A `Path` is a collection of branches to follow to get to the desired node.
/// An empty `Path` represents the root of the [`Tree`].
///
/// # Examples
/// ```rust
/// use nb_tree::{path, prelude::{Tree, Path}};
/// let mut tree = Tree::new();
/// // Paths from string litterals, vectors, or manually built
/// let path_d: Path<String> = "/b/d".into();
/// let path_e: Path<String> = vec!["a", "c", "e"].into();
/// let path_g: Path<String> = path!["a", "g"];
/// let mut path_f = Path::new();
/// path_f.l("b").l("f");
/// // Use paths to insert data
/// tree.i("/", 0)
///     .i("/a", 1)
///     .i("/b", 2)
///     .i("/a/c", 3)
///     .i(path_d, 4)
///     .i(path_e, 5)
///     .i(path_f, 6)
///     .i(path_g, 7);
///
/// // Use paths to retrieve data
/// assert_eq!(tree.get(&"/a/c".into()), Ok(&3));
///
/// // Use paths to remove data
/// assert_eq!(tree.len(), 8);
/// assert_eq!(tree.remove_subtree(&"/a".into()), Ok(()));
/// // The whole "/a/[c/e, g]" subtree is removed, removing all nodes below it too
/// assert_eq!(tree.len(), 4);
/// ```
///
/// [`Tree`]: crate::tree::Tree
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Path<B> {
    /// Array of branches.
    path: VecDeque<B>,
}

impl<B> Default for Path<B> {
    fn default() -> Self {
        Self {
            path: VecDeque::default(),
        }
    }
}

impl<B: Clone> Clone for Path<B> {
    fn clone(&self) -> Self {
        Self {
            path: self.path.clone(),
        }
    }
}

impl<B> Path<B> {
    /// Creates a new empty `Path`.
    pub fn new() -> Self {
        Self {
            path: VecDeque::new(),
        }
    }

    /// Creates a new empty `Path`.
    pub fn with(root: B) -> Self {
        let mut path = VecDeque::new();
        path.push_back(root);
        Self { path }
    }

    /// Removes the first branch of the `Path`.
    pub fn pop_first(&mut self) -> Option<B> {
        self.path.pop_front()
    }

    /// Removes the last branch of the `Path`.
    pub fn pop_last(&mut self) -> Option<B> {
        self.path.pop_back()
    }

    /// Adds `branch` at the end of the `Path`.
    pub fn push_last(&mut self, branch: B) {
        self.path.push_back(branch);
    }

    /// Appends all `branches` at the end of the `Path`.
    pub fn append(&mut self, mut branches: Path<B>) {
        self.path.append(&mut branches.path);
    }

    /// Adds `branch` at the end of the `Path`.
    ///
    /// Calls can be chained.
    pub fn l(&mut self, branch: impl Into<B>) -> &mut Self {
        self.path.push_back(branch.into());
        self
    }

    /// Adds `branch` at the start of the `Path`.
    pub fn push_first(&mut self, branch: B) {
        self.path.push_front(branch);
    }

    /// Returns the last branch of the `Path`.
    ///
    /// If the `Path` is empty, None is returned.
    pub fn last(&self) -> Option<&B> {
        self.path.back()
    }

    /// Returns the first branch of the `Path`.
    ///
    /// If the `Path` is empty, None is returned.
    pub fn first(&self) -> Option<&B> {
        self.path.front()
    }

    /// Returns true if the `Path` is empty, false otherwise.
    pub fn is_empty(&self) -> bool {
        self.path.is_empty()
    }

    /// Returns the length of the `Path`.
    pub fn len(&self) -> usize {
        self.path.len()
    }

    /// Removes `n` branches from the end of the Path.
    pub fn truncate_end(&mut self, n: usize) {
        if self.path.len() <= n {
            self.path.clear();
        } else {
            self.path.truncate(self.path.len() - n);
        }
    }

    /// Removes `n` branches from the start of the Path.
    pub fn truncate_start(&mut self, n: usize) {
        if self.path.len() <= n {
            self.path.clear();
        } else {
            self.path.rotate_left(n);
            self.path.truncate(self.path.len() - n);
        }
    }

    /// Clears the Path.
    pub fn clear(&mut self) {
        self.path.clear()
    }

    /// Traverses the Tree nodes depth first.
    ///
    /// The children are visited in arbitrary order.
    pub fn iter(&self) -> std::collections::vec_deque::Iter<'_, B> {
        self.path.iter()
    }

    pub fn range<R>(&self, range: R) -> std::collections::vec_deque::Iter<'_, B>
    where
        R: std::ops::RangeBounds<usize>,
    {
        self.path.range(range)
    }
}

impl<B> Index<PathIDX> for Path<B> {
    type Output = B;

    fn index(&self, index: PathIDX) -> &Self::Output {
        &self.path[index]
    }
}

impl<B> IndexMut<PathIDX> for Path<B> {
    fn index_mut(&mut self, index: PathIDX) -> &mut Self::Output {
        &mut self.path[index]
    }
}

impl<B> Path<B>
where
    B: Clone,
{
    /// Creates a copy stopping at the given index (excluded).
    pub fn path_to(&self, path_idx: PathIDX) -> Path<B> {
        Self {
            path: self.path.range(..path_idx).cloned().collect(),
        }
    }

    /// Creates a copy starting at the given index (included).
    pub fn path_from(&self, path_idx: PathIDX) -> Path<B> {
        Self {
            path: self.path.range(path_idx..).cloned().collect(),
        }
    }

    /// Follows the given [`DepthFirstTraversalNode`], moving up the `Path` and going down a branch.
    ///
    /// The branch type can be something else than B, as long as it can be converted to it.
    /// # Examples
    /// ```rust
    /// use nb_tree::prelude::{Tree, Path};
    /// let mut tree: Tree<usize, String> = Tree::new();
    /// tree.i("/", 0).i("/a", 1).i("/a/b", 2);
    /// let mut iter = tree.into_iter();
    /// let mut path: Path<String> = Path::new();
    /// path.apply(&iter.next().unwrap());
    /// assert_eq!(path, "/".into());
    /// path.apply(&iter.next().unwrap());
    /// assert_eq!(path, "/a".into());
    /// path.apply(&iter.next().unwrap());
    /// assert_eq!(path, "/a/b".into());
    /// ```
    pub fn apply<N>(&mut self, node: &Traversal<N, B>) -> bool {
        if let Traversal::Step {
            up,
            branch,
            data: _,
        } = node
        {
            assert!(self.len() >= *up, "Moving up out of the tree");
            // Move up
            self.truncate_end(*up);
            // Move down
            self.push_last(branch.clone());
            true
        } else {
            false
        }
    }

    /// Dereferences the branch in `node` and applies it like [`apply()`].
    ///
    /// [`apply()`]: Self::apply()
    pub fn apply_deref<N, C>(&mut self, node: &Traversal<N, C>) -> bool
    where
        C: Deref<Target = B>,
    {
        if let Traversal::Step {
            up,
            branch,
            data: _,
        } = node
        {
            assert!(self.len() >= *up, "Moving up out of the tree");
            // Move up
            self.truncate_end(*up);
            // Move down
            self.push_last(branch.deref().clone());
            true
        } else {
            false
        }
    }

    /// Follows the given [`DepthFirstTraversalNode`] like [`apply()`] transformed by the given `op`.
    ///
    /// # Examples
    /// ```rust
    /// use nb_tree::{path, prelude::{Tree, Path}};
    /// let mut tree: Tree<usize, String> = Tree::new();
    /// tree.i("/", 0).i("/a", 1).i("/a/b", 2);
    /// let mut iter = tree.iter();
    /// let mut path = Path::new();
    /// let mut e = 0;
    /// path.apply_with(&iter.next().unwrap(), |&c: &&String| (c.clone(), e.clone()));
    /// e += 1;
    /// path.apply_with(&iter.next().unwrap(), |&c: &&String| (c.clone(), e.clone()));
    /// assert_eq!(path, path![("a".into(), 1)]);
    /// e += 1;
    /// path.apply_with(&iter.next().unwrap(), |&c: &&String| (c.clone(), e.clone()));
    /// assert_eq!(path, path![("a".into(), 1), ("b".into(), 2)]);
    /// ```
    ///
    /// [`apply()`]: Self::apply()
    pub fn apply_with<N, C>(&mut self, node: &Traversal<N, C>, op: impl Fn(&C) -> B) -> bool {
        if let Traversal::Step {
            up,
            branch,
            data: _,
        } = node
        {
            assert!(self.len() >= *up, "Moving up out of the tree");
            // Move up
            self.truncate_end(*up);
            // Move down
            self.push_last(op(branch));
            true
        } else {
            false
        }
    }
}

impl<B> Path<B>
where
    B: Clone + Eq,
{
    pub fn offshoot_from(&self, branch: Self) -> Path<B> {
        let mut iter = self.iter().zip(branch.iter());
        let mut next = iter.next();
        while next.and_then(|(sb, ob)| (sb == ob).then_some(())).is_some() {
            next = iter.next();
        }

        if let Some((root, _)) = next {
            iter.fold(Path::with(root.clone()), |mut ph, (b, _)| {
                ph.push_last(b.clone());
                ph
            })
        } else {
            Path::new()
        }
    }
}

impl<B> Path<&B>
where
    B: Clone,
{
    pub fn branches_to_owned(&self) -> Path<B> {
        Path {
            path: self.path.iter().map(|&i| i.clone()).collect(),
        }
    }
}

/// Error describing a failed attempt at parsing a `Path`.
#[derive(Debug)]
pub enum ParsePathError<P> {
    /// The given value to parse does not contain any root.
    NoRoot,
    /// The parsing failed.
    ParseError(P),
}

impl<P> From<P> for ParsePathError<P> {
    fn from(value: P) -> Self {
        ParsePathError::ParseError(value)
    }
}

impl<B: FromStr> FromStr for Path<B> {
    type Err = ParsePathError<B::Err>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if !s.contains('/') {
            return Err(ParsePathError::NoRoot);
        }
        // Skip everything preceeding the root slash
        Ok(Self {
            path: s
                .split('/')
                .skip(1)
                .filter(|s| !s.is_empty())
                .map(|s| s.parse::<B>())
                .collect::<Result<VecDeque<B>, _>>()
                .map_err(ParsePathError::ParseError)?,
        })
    }
}

impl<B> From<&str> for Path<B>
where
    B: FromStr,
    <B as FromStr>::Err: Dbg,
{
    fn from(value: &str) -> Self {
        value.parse().unwrap()
    }
}

impl<A: Into<B>, B> From<Vec<A>> for Path<B> {
    fn from(value: Vec<A>) -> Self {
        Self {
            path: value.into_iter().map(|v| v.into()).collect(),
        }
    }
}

impl<'a, B> IntoIterator for &'a Path<B> {
    type Item = &'a B;

    type IntoIter = Iter<'a, B>;

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

impl<'a, B> IntoIterator for &'a mut Path<B> {
    type Item = &'a mut B;

    type IntoIter = IterMut<'a, B>;

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

impl<B> IntoIterator for Path<B> {
    type Item = B;

    type IntoIter = IntoIter<B>;

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

impl<B> FromIterator<B> for Path<B> {
    fn from_iter<T: IntoIterator<Item = B>>(iter: T) -> Self {
        Self {
            path: iter.into_iter().collect(),
        }
    }
}

impl<B: Display> Display for Path<B> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.is_empty() {
            write!(f, "/")?;
        } else {
            //NOTE: multi line B display management?
            for b in self.path.iter() {
                write!(f, "/{}", b)?;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::prelude::Tree;

    use super::*;

    fn path() -> Path<i32> {
        let mut path: Path<i32> = Path::new();
        path.l(0).l(1).l(2).l(3).l(4).l(5).l(6).l(7).l(8).l(9);
        path
    }

    fn tree() -> Tree<i32, i32> {
        let mut tree = Tree::new();
        tree.insert(&"/".into(), 75).unwrap();
        tree.insert(&"/0".into(), 0).unwrap();
        tree.insert(&"/0/1".into(), 1).unwrap();
        tree.insert(&"/0/1/2".into(), 2).unwrap();
        tree.insert(&"/0/1/2/3".into(), 3).unwrap();
        tree.insert(&"/0/1/2/3/4".into(), 4).unwrap();
        tree
    }

    #[test]
    fn push_pop_get() {
        let mut path = Path::new();
        path.push_last(0);
        path.push_last(1);
        path.push_last(2);
        path.l(6).l(7);
        assert_eq!(path, vec![0, 1, 2, 6, 7].into());
        path.pop_last();
        path.pop_last();
        path.push_last(3);
        assert_eq!(path, vec![0, 1, 2, 3].into());
        path.pop_first();
        assert_eq!(path, vec![1, 2, 3].into());
        assert_eq!(path.last(), Some(&3));
        path.push_first(10);
        assert_eq!(path, vec![10, 1, 2, 3].into());
        assert_eq!(path.first(), Some(&10));
    }

    #[test]
    fn from_to() {
        let mut path = path();
        assert_eq!(path, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9].into());
        path = path.path_to(5);
        assert_eq!(path, vec![0, 1, 2, 3, 4].into());
        path = path.path_from(2);
        assert_eq!(path, vec![2, 3, 4].into());
    }

    #[test]
    fn apply() {
        let mut path: Path<i32> = Path::new();
        let mut tree = tree();
        tree.insert(&"/0/1/5".into(), 5).unwrap();
        let mut iter = tree.into_iter();
        path.apply(&iter.next().unwrap());
        assert_eq!(path, "/".into());
        path.apply(&iter.next().unwrap());
        assert_eq!(path, "/0".into());
        path.apply(&iter.next().unwrap());
        assert_eq!(path, "/0/1".into());
        let node = iter.next().unwrap();
        if *node.branch().unwrap() == 2 {
            path.apply(&node);
            assert_eq!(path, "/0/1/2".into());
            path.apply(&iter.next().unwrap());
            assert_eq!(path, "/0/1/2/3".into());
            path.apply(&iter.next().unwrap());
            assert_eq!(path, "/0/1/2/3/4".into());
            path.apply(&iter.next().unwrap());
            assert_eq!(path, "/0/1/5".into());
        } else {
            path.apply(&node);
            assert_eq!(path, "/0/1/5".into());
            path.apply(&iter.next().unwrap());
            assert_eq!(path, "/0/1/2".into());
            path.apply(&iter.next().unwrap());
            assert_eq!(path, "/0/1/2/3".into());
            path.apply(&iter.next().unwrap());
            assert_eq!(path, "/0/1/2/3/4".into());
        }
    }

    #[test]
    fn apply_deref() {
        let mut path: Path<i32> = Path::new();
        let mut tree = tree();
        tree.insert(&"/0/1/5".into(), 5).unwrap();
        let mut iter = tree.iter();
        path.apply_deref(&iter.next().unwrap());
        assert_eq!(path, "/".into());
        path.apply_deref(&iter.next().unwrap());
        assert_eq!(path, "/0".into());
        path.apply_deref(&iter.next().unwrap());
        assert_eq!(path, "/0/1".into());
        let node = iter.next().unwrap();
        if **node.branch().unwrap() == 2 {
            path.apply_deref(&node);
            assert_eq!(path, "/0/1/2".into());
            path.apply_deref(&iter.next().unwrap());
            assert_eq!(path, "/0/1/2/3".into());
            path.apply_deref(&iter.next().unwrap());
            assert_eq!(path, "/0/1/2/3/4".into());
            path.apply_deref(&iter.next().unwrap());
            assert_eq!(path, "/0/1/5".into());
        } else {
            path.apply_deref(&node);
            assert_eq!(path, "/0/1/5".into());
            path.apply_deref(&iter.next().unwrap());
            assert_eq!(path, "/0/1/2".into());
            path.apply_deref(&iter.next().unwrap());
            assert_eq!(path, "/0/1/2/3".into());
            path.apply_deref(&iter.next().unwrap());
            assert_eq!(path, "/0/1/2/3/4".into());
        }
    }

    #[test]
    fn apply_with() {
        let mut path = Path::new();
        let mut tree = tree();
        let c = |&&c: &&i32| 10 - c;
        tree.insert(&"/0/1/5".into(), 5).unwrap();
        let mut iter = tree.iter();
        path.apply_with(&iter.next().unwrap(), c);
        assert_eq!(path, "/".into());
        path.apply_with(&iter.next().unwrap(), c);
        assert_eq!(path, "/10".into());
        path.apply_with(&iter.next().unwrap(), c);
        assert_eq!(path, "/10/9".into());
        let node = iter.next().unwrap();
        if node.branch().unwrap() == &&2 {
            path.apply_with(&node, c);
            assert_eq!(path, "/10/9/8".into());
            path.apply_with(&iter.next().unwrap(), c);
            assert_eq!(path, "/10/9/8/7".into());
            path.apply_with(&iter.next().unwrap(), c);
            assert_eq!(path, "/10/9/8/7/6".into());
            path.apply_with(&iter.next().unwrap(), c);
            assert_eq!(path, "/10/9/5".into());
        } else {
            path.apply_with(&node, c);
            assert_eq!(path, "/10/9/5".into());
            path.apply_with(&iter.next().unwrap(), c);
            assert_eq!(path, "/10/9/8".into());
            path.apply_with(&iter.next().unwrap(), c);
            assert_eq!(path, "/10/9/8/7".into());
            path.apply_with(&iter.next().unwrap(), c);
            assert_eq!(path, "/10/9/8/7/6".into());
        }
    }

    #[test]
    fn iter() {
        for (v, &b) in path().iter().enumerate() {
            assert_eq!(v as i32, b);
        }
    }
}