pfds 0.6.0

Purely Functional 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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
use crate::{HashSet, Hashable};
use std::{ops::Deref, sync::Arc};

/// A trait for accumulating data while traversing a tree.
/// 
/// This trait is used with recursive tree operations to maintain
/// state during traversal, such as collecting a path from root to current node.
pub trait TreeAcc<D: Clone> {
    /// Push data onto the accumulator.
    fn push(&mut self, data: &D);
    
    /// Pop data from the accumulator.
    fn pop(&mut self);
}

#[derive(Clone)]
struct Node<D: Clone>(Arc<NodePriv<D>>);

#[derive(Clone)]
struct NodePriv<D: Clone> {
    data: D,
    children: HashSet<Node<D>>,
}

impl<D: Clone> Hashable for Node<D> {
    fn hash(&self) -> u64 {
        Arc::as_ptr(&self.0) as usize as u64
    }
}

impl<D: Clone> PartialEq for Node<D> {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl<D: Clone> Eq for Node<D> {}

impl<D: Clone> Node<D> {
    pub fn data(&self) -> &D {
        &self.0.data
    }

    pub fn iter_children<'a>(&self) -> crate::hashset::HSIter<'a, Self> {
        self.0.children.iter()
    }

    fn new(data: D, children: HashSet<Node<D>>) -> Self {
        Self(Arc::new(NodePriv { data, children }))
    }

    fn apply<F: FnOnce(&D) -> Option<D>>(&self, f: F) -> Option<Self> {
        let new_data = f(self.data());
        new_data.map(|data| {
            Self(Arc::new(NodePriv {
                data,
                children: self.0.children.clone(),
            }))
        })
    }

    fn apply_recursive<F: FnMut(&D) -> Option<D>>(&self, f: &mut F) -> Option<Self> {
        let mut changed = false;
        let mut children = HashSet::empty();

        // TODO: using while let Some(c) = self.0.children.iter() seems to make this hangs: Investigate!!!!
        for c in self.0.children.iter() {
            let child = match c.apply_recursive(f) {
                Some(c) => {
                    changed |= true;
                    c
                }
                None => c,
            };
            children = children.insert(child);
        }

        let children = if changed {
            children
        } else {
            self.0.children.clone()
        };

        let new_data = f(self.data());
        changed |= new_data.is_some();
        let data = match new_data {
            Some(data) => data,
            None => self.0.data.clone(),
        };

        if changed {
            Some(Self(Arc::new(NodePriv { data, children })))
        } else {
            None
        }
    }

    fn apply_acc_recursive<Acc: TreeAcc<D>, F: FnMut(&mut Acc, &D) -> Option<D>>(
        &self,
        acc: &mut Acc,
        f: &mut F,
    ) -> Option<Self> {
        let mut changed = false;
        let mut children = HashSet::empty();

        acc.push(self.data());
        let new_data = f(acc, self.data());

        // TODO: using while let Some(c) = self.0.children.iter() seems to make this hangs: Investigate!!!!
        for c in self.0.children.iter() {
            let child = match c.apply_acc_recursive(acc, f) {
                Some(c) => {
                    changed |= true;
                    c
                }
                None => c,
            };
            children = children.insert(child);
        }

        let children = if changed {
            children
        } else {
            self.0.children.clone()
        };
        acc.pop();

        changed |= new_data.is_some();
        let data = match new_data {
            Some(data) => data,
            None => self.0.data.clone(),
        };

        if changed {
            Some(Self(Arc::new(NodePriv { data, children })))
        } else {
            None
        }
    }
    ///
    /// Returns a new tree containing only the nodes for which the given predicate "f" returns "true"
    ///
    fn filter_recursive<F: Fn(&D) -> bool>(&self, f: Arc<F>) -> Option<Self> {
        match f(self.data()) {
            true => {
                let mut children = HashSet::empty();
                for c in self.iter_children() {
                    match c.filter_recursive(f.clone()) {
                        Some(cc) => children = children.insert(cc),
                        None => (),
                    }
                }
                Some(Self(Arc::new(NodePriv {
                    data: self.data().clone(),
                    children,
                })))
            }
            false => None,
        }
    }

    pub fn map_data<F: FnMut(&D) -> Option<D>>(&self, f: &mut F) -> Option<Self> {
        let mut children: HashSet<Node<D>> = HashSet::empty();
        let mut children_changed = false;
        for c in self.0.children.iter() {
            children = match c.map_data(f) {
                Some(d) => {
                    children_changed = true;
                    children.insert(d)
                }
                None => children.insert(c.clone()),
            };
        }

        match f(self.data()) {
            Some(d) => Some(if children_changed {
                Node::new(d, children)
            } else {
                Node::new(d, self.0.children.clone())
            }),
            None => {
                if children_changed {
                    Some(Node::new(self.data().clone(), children))
                } else {
                    None
                }
            }
        }
    }
}

#[derive(Clone)]
struct PathPriv<D: Clone> {
    node_vec: Vec<Node<D>>,
}

impl<D: Clone> PathPriv<D> {
    pub fn new(data: D) -> Arc<Self> {
        Arc::new(Self {
            node_vec: vec![Node(Arc::new(NodePriv {
                data,
                children: HashSet::empty(),
            }))],
        })
    }

    pub fn add_node(&self, data: D) -> Arc<Self> {
        assert!(self.node_vec.len() >= 1);
        for i in 1..self.node_vec.len() {
            assert!(self.node_vec[i - 1]
                .0
                .children
                .exist(self.node_vec[i].clone()));
        }

        let new_child = Node::new(data, HashSet::empty());
        let mut new_path = vec![new_child.clone()];
        let len = self.node_vec.len();
        for i in 0..len {
            let parent = &self.node_vec[len - i - 1];
            let mut children = parent.0.children.insert(new_path[i].clone());
            children = if i != 0 {
                children.remove(self.node_vec[len - i].clone()) // remove the old node (old parent) after inserting the new modified one
            } else {
                children
            };

            let new_parent = Node(Arc::new(NodePriv {
                data: parent.0.data.clone(),
                children,
            }));
            new_path.push(new_parent.clone());
        }

        new_path.reverse();

        Arc::new(Self { node_vec: new_path })
    }

    pub fn remove_node(&self) -> Arc<Self> {
        assert!(self.node_vec.len() > 1);

        let mut new_path: Vec<Node<D>> = Vec::new();
        let len = self.node_vec.len();
        for i in 0..len - 1 {
            let parent = &self.node_vec[len - i - 2];
            let mut children = parent.0.children.remove(self.node_vec[len - i - 1].clone());
            children = if i != 0 {
                children.insert(new_path[i - 1].clone()) // insert the modified node (old parent rebuilt) after removing the old one
            } else {
                children
            };

            let new_parent = Node(Arc::new(NodePriv {
                data: parent.0.data.clone(),
                children,
            }));
            new_path.push(new_parent.clone());
        }

        new_path.reverse();
        Arc::new(Self { node_vec: new_path })
    }

    pub fn set_data(&self, data: D) -> Arc<Self> {
        let rm = self.remove_node();
        rm.add_node(data)
    }

    fn node(&self) -> Node<D> {
        self.node_vec.last().unwrap().clone()
    }

    fn propagate_last_node_change(&self, node: Node<D>) -> Arc<Self> {
        let new_child = node;
        let mut new_path = vec![new_child.clone()];
        let len = self.node_vec.len();
        for i in 0..len - 1 {
            let parent = &self.node_vec[len - i - 2];

            let children = parent
                .0
                .children
                // remove the old child node;
                .remove(self.node_vec[len - i - 1].clone())
                // insert the new child node
                .insert(new_path[i].clone());

            assert!(parent.0.children.len() == children.len());

            let new_parent = Node(Arc::new(NodePriv {
                data: parent.0.data.clone(),
                children,
            }));
            new_path.push(new_parent.clone());
        }
        new_path.reverse();
        Arc::new(Self { node_vec: new_path })
    }

    fn apply<F: FnOnce(&D) -> Option<D>>(&self, f: F) -> Option<Arc<Self>> {
        self.node()
            .apply(f)
            .map(|n| self.propagate_last_node_change(n))
    }

    fn apply_recursive<F: FnMut(&D) -> Option<D>>(&self, f: &mut F) -> Option<Arc<Self>> {
        self.node()
            .apply_recursive(f)
            .map(|n| self.propagate_last_node_change(n))
    }

    fn apply_acc_recursive<Acc: TreeAcc<D>, F: FnMut(&mut Acc, &D) -> Option<D>>(
        &self,
        init: &mut Acc,
        f: &mut F,
    ) -> Option<Arc<Self>> {
        self.node()
            .apply_acc_recursive(init, f)
            .map(|n| self.propagate_last_node_change(n))
    }

    fn filter_recursive<F: Fn(&D) -> bool>(&self, f: F) -> Option<Arc<Self>> {
        self.node()
            .filter_recursive(Arc::new(f))
            .map(|n| self.propagate_last_node_change(n))
    }
}

/// A persistent (immutable) multi-way tree with path-based navigation.
/// 
/// `Path` represents a position in a tree, maintaining the path from root
/// to the current node. All operations return new paths, leaving the original
/// tree structure unchanged through structural sharing.
/// 
/// # Performance
/// 
/// - Navigation (parent/children): O(1) to O(c) where c is number of children
/// - Add/remove node: O(h) where h is height of tree
/// - Apply operations: O(n) for recursive, O(1) for single node
/// - Flatten: O(n) where n is total nodes in subtree
#[derive(Clone)]
pub struct Path<D: Clone> {
    path: Arc<PathPriv<D>>,
}

impl<D: Clone> Path<D> {
    /// Creates a new tree with a single root node containing the given data.
    /// 
    /// # Arguments
    /// 
    /// * `root_data` - The data for the root node
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new("root");
    /// assert_eq!(tree.len(), 1);
    /// assert_eq!(*tree.data(), "root");
    /// ```
    pub fn new(root_data: D) -> Self {
        Self {
            path: PathPriv::new(root_data),
        }
    }

    /// Adds a new child node to the current node.
    /// 
    /// Returns a new path pointing to the newly added child.
    /// This operation is O(h) where h is the height of the tree.
    /// 
    /// # Arguments
    /// 
    /// * `data` - The data for the new child node
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new("root");
    /// let child = tree.add_node("child1");
    /// assert_eq!(*child.data(), "child1");
    /// assert_eq!(child.len(), 2); // Path length is 2 (root -> child)
    /// ```
    pub fn add_node(&self, data: D) -> Self {
        Self {
            path: self.path.add_node(data),
        }
    }

    /// Removes the current node from the tree.
    /// 
    /// Returns a path pointing to the parent of the removed node.
    /// This operation is O(h) where h is the height of the tree.
    /// 
    /// # Panics
    /// 
    /// Panics if called on the root node (path length = 1).
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new("root");
    /// let child = tree.add_node("child");
    /// let back_to_root = child.remove_node();
    /// assert_eq!(back_to_root.len(), 1);
    /// ```
    pub fn remove_node(&self) -> Self {
        Self {
            path: self.path.remove_node(),
        }
    }

    /// Returns a path pointing to the root of the tree.
    /// 
    /// This operation is O(1).
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new("root");
    /// let deep = tree.add_node("a").add_node("b").add_node("c");
    /// let root = deep.root();
    /// assert_eq!(root.len(), 1);
    /// assert_eq!(*root.data(), "root");
    /// ```
    pub fn root(&self) -> Self {
        Self {
            path: Arc::new(PathPriv {
                node_vec: vec![self.path.node_vec[0].clone()],
            }),
        }
    }

    /// Returns a reference to the data of the current node.
    /// 
    /// This operation is O(1).
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new(42);
    /// assert_eq!(*tree.data(), 42);
    /// ```
    pub fn data(&self) -> &D {
        self.path.node_vec.last().unwrap().data()
    }

    /// Returns a vector of paths to all children of the current node.
    /// 
    /// Each returned path points to a child node and includes
    /// the full path from root to that child.
    /// This operation is O(c) where c is the number of children.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new("root");
    /// let with_children = tree.add_node("a").parent().add_node("b");
    /// let root = with_children.root();
    /// assert_eq!(root.children().len(), 2);
    /// ```
    pub fn children(&self) -> Vec<Self> {
        let mut res = Vec::new();
        let iter = self.path.node_vec.last().unwrap().iter_children();
        for c in iter {
            let mut new_path = self.path.node_vec.clone();
            new_path.push(c);

            res.push(Self {
                path: Arc::new(PathPriv { node_vec: new_path }),
            });
        }
        res
    }

    /// Returns a path pointing to the parent of the current node.
    /// 
    /// This operation is O(1).
    /// 
    /// # Panics
    /// 
    /// Panics if called on the root node.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new("root");
    /// let child = tree.add_node("child");
    /// let parent = child.parent();
    /// assert_eq!(*parent.data(), "root");
    /// ```
    pub fn parent(&self) -> Self {
        let len = self.path.node_vec.len();
        let parent_path = Vec::from(&self.path.node_vec[0..len - 1]);
        Self {
            path: Arc::new(PathPriv {
                node_vec: parent_path,
            }),
        }
    }

    /// Creates a new tree with the current node's data replaced.
    /// 
    /// This operation is O(h) where h is the height of the tree.
    /// 
    /// # Arguments
    /// 
    /// * `data` - The new data for the current node
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new("root").add_node("old");
    /// let updated = tree.set_data("new");
    /// assert_eq!(*tree.data(), "old");    // Original unchanged
    /// assert_eq!(*updated.data(), "new");
    /// ```
    pub fn set_data(&self, data: D) -> Self {
        Self {
            path: self.path.set_data(data),
        }
    }

    /// Applies a function to the current node's data.
    /// 
    /// If the function returns `Some(new_data)`, creates a new tree with
    /// the updated data. If it returns `None`, returns the original tree.
    /// 
    /// # Arguments
    /// 
    /// * `f` - Function that transforms the node data
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new(5);
    /// let doubled = tree.apply(|x| Some(x * 2));
    /// assert_eq!(*doubled.data(), 10);
    /// ```
    pub fn apply<F: FnOnce(&D) -> Option<D>>(&self, f: F) -> Self {
        match self.path.apply(f) {
            Some(path) => Self { path },
            None => self.clone(),
        }
    }

    /// Recursively applies a function to all nodes in the subtree.
    /// 
    /// Traverses the entire subtree rooted at the current node,
    /// applying the function to each node's data.
    /// 
    /// # Arguments
    /// 
    /// * `f` - Function that transforms node data
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new(1)
    ///     .add_node(2).parent()
    ///     .add_node(3);
    /// let doubled = tree.root().apply_recursive(|x| Some(x * 2));
    /// // All nodes in tree are doubled
    /// ```
    pub fn apply_recursive<F: FnMut(&D) -> Option<D>>(&self, mut f: F) -> Self {
        match self.path.apply_recursive(&mut f) {
            Some(path) => Self { path },
            None => self.clone(),
        }
    }

    pub fn apply_acc_recursive<Acc: TreeAcc<D>, F: FnMut(&mut Acc, &D) -> Option<D>>(
        &self,
        init: &mut Acc,
        mut f: F,
    ) -> Self {
        match self.path.apply_acc_recursive(init, &mut f) {
            Some(path) => Self { path },
            None => self.clone(),
        }
    }

    fn flatten_recursive(node: &Self, res: &mut Vec<Self>) {
        res.push(node.clone());

        for c in node.children() {
            Self::flatten_recursive(&c, res);
        }
    }

    /// Returns a vector of paths to all nodes in the subtree.
    /// 
    /// Performs a depth-first traversal of the subtree rooted at
    /// the current node, returning paths to all nodes including
    /// the current node itself.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new("root")
    ///     .add_node("a").parent()
    ///     .add_node("b");
    /// let all_nodes = tree.root().flatten();
    /// assert_eq!(all_nodes.len(), 3); // root, a, b
    /// ```
    pub fn flatten(&self) -> Vec<Self> {
        let mut res = Vec::new();
        Self::flatten_recursive(&self, &mut res);
        res
    }

    /// Returns the length of the path from root to current node.
    /// 
    /// This is the depth of the current node plus one.
    /// The root has length 1.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new("root");
    /// assert_eq!(tree.len(), 1);
    /// let child = tree.add_node("child");
    /// assert_eq!(child.len(), 2);
    /// ```
    pub fn len(&self) -> usize {
        self.path.node_vec.len()
    }

    /// Recursively filters the tree, keeping only nodes that satisfy the predicate.
    /// 
    /// Returns `Some(tree)` with only matching nodes and their ancestors,
    /// or `None` if no nodes match.
    /// 
    /// # Arguments
    /// 
    /// * `f` - Predicate function to test each node
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new(5)
    ///     .add_node(3).parent()
    ///     .add_node(7);
    /// let filtered = tree.root().filter_recursive(|x| *x > 4);
    /// // Only nodes with values > 4 are kept
    /// ```
    pub fn filter_recursive<F: Fn(&D) -> bool>(&self, f: F) -> Option<Self> {
        match self.path.filter_recursive(f) {
            Some(path) => Some(Self { path }),
            None => None,
        }
    }

    // breath first
    pub fn iter_acc_recursive<Acc: TreeAcc<D>, F: FnMut(&mut Acc, &Path<D>)>(
        &self,
        init: &mut Acc,
        f: &mut F,
    ) {
        init.push(self.data());

        f(init, &self);
        for c in self.children().iter() {
            c.iter_acc_recursive(init, f);
        }

        init.pop();
    }

    // breath first
    #[inline(never)]
    /// Recursively iterates over all nodes in the subtree.
    /// 
    /// Performs a breadth-first traversal, calling the function
    /// on each node in the subtree.
    /// 
    /// # Arguments
    /// 
    /// * `f` - Function to call on each node
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new("root")
    ///     .add_node("child1").parent()
    ///     .add_node("child2");
    /// let mut count = 0;
    /// tree.root().iter_recursive(&mut |_node| count += 1);
    /// assert_eq!(count, 3);
    /// ```
    pub fn iter_recursive<F: FnMut(&Path<D>)>(&self, f: &mut F) {
        f(self);
        for c in self.children().iter() {
            c.iter_recursive(f);
        }
    }

    /// Removes all children from the current node.
    /// 
    /// Returns a new tree where the current node has no children.
    /// If the node already has no children, returns the original tree.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new("root")
    ///     .add_node("a").parent()
    ///     .add_node("b").parent();
    /// let no_children = tree.remove_all_children();
    /// assert_eq!(no_children.children().len(), 0);
    /// ```
    pub fn remove_all_children(&self) -> Self {
        match self.path.node().0.children.len() {
            x if x > 0 => {
                let mut n = (*self.path.node().0).clone();
                n.children = HashSet::empty();
                let p = self.path.propagate_last_node_change(Node(Arc::new(n)));
                Self { path: p }
            }
            _ => self.clone(),
        }
    }

    /// Maps a function over the data of the current node and all its descendants.
    /// 
    /// Recursively applies the function to transform data in the entire subtree.
    /// 
    /// # Arguments
    /// 
    /// * `f` - Function to transform each node's data
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pfds::Path;
    /// 
    /// let tree = Path::new(1)
    ///     .add_node(2).parent()
    ///     .add_node(3);
    /// let incremented = tree.root().map_data(|x| Some(x + 1));
    /// // All values in tree are incremented by 1
    /// ```
    pub fn map_data<F: FnMut(&D) -> Option<D>>(&self, mut f: F) -> Self {
        match self.path.node_vec[self.path.node_vec.len() - 1].map_data(&mut f) {
            Some(n) => Path {
                path: self.path.propagate_last_node_change(n),
            },
            None => self.clone(),
        }
    }
}

impl<D: Clone> PartialEq for Path<D> {
    fn eq(&self, other: &Self) -> bool {
        if !Arc::ptr_eq(&self.path, &other.path) {
            // check if the path length are different
            if self.path.node_vec.len() != other.path.node_vec.len() {
                return false;
            }
            // path is equal: check if node to node are equal
            for i in 0..self.path.node_vec.len() {
                if !Arc::ptr_eq(&self.path.node_vec[i].0, &other.path.node_vec[i].0) {
                    return false;
                }
            }

            println!("warning! slow path equality check");
            // they are equal
            true
        } else {
            true
        }
    }
}

impl<D: Clone> Eq for Path<D> {}

impl<D: Clone> Deref for Path<D> {
    type Target = D;
    fn deref(&self) -> &Self::Target {
        self.data()
    }
}

impl<T: Clone> TreeAcc<T> for Vec<T> {
    fn push(&mut self, data: &T) {
        self.push(data.clone());
    }

    fn pop(&mut self) {
        self.pop();
    }
}

#[cfg(test)]
mod tests {
    use crate::tree::*;
    use std::ops::Sub;

    static mut SEED: i64 = 777;

    fn rand() -> i32 {
        unsafe {
            SEED = SEED.wrapping_mul(1664525).wrapping_add(1013904223);
            (SEED >> 24) as i32
        }
    }

    #[test]
    fn add_roots() {
        let mut tree = Path::new(0);
        for i in 0..128 {
            let t = tree.add_node(i);
            tree = t.parent();
        }

        let mut s = std::collections::HashSet::new();
        for r in tree.children() {
            s.insert(*r.data());
        }

        for i in 0..128 {
            assert!(s.contains(&i));
        }
    }

    #[test]
    fn add_children() {
        let mut tree = Path::new(0);
        let mut cs = std::collections::HashSet::new();
        for i in 0..128 {
            let node = tree.add_node(i);
            let ch1 = rand();
            let ch2 = rand();
            cs.insert((i, ch1));
            cs.insert((i, ch2));
            let node1 = node.add_node(ch1);
            let node2 = node1.parent().add_node(ch2);
            tree = node2.root();
        }

        let mut s = std::collections::HashSet::new();
        for r in tree.children() {
            let d = *r.data();
            s.insert(d);
            assert_eq!(r.children().len(), 2);
        }

        for i in 0..128 {
            assert!(s.contains(&i));
        }

        for r in tree.children() {
            for ch in r.children() {
                assert!(cs.contains(&(*r.data(), *ch.data())));
            }
        }
    }

    #[test]
    fn remove_roots() {
        let mut tree = Path::new(0);
        for i in 0..128 {
            let t = tree.add_node(i);
            tree = t.root();
        }

        let mut s = std::collections::HashSet::new();
        for r in tree.root().children() {
            s.insert(*r.data());
        }

        for i in 0..128 {
            assert!(s.contains(&i));
        }

        let mut r = std::collections::HashSet::new();

        while let Some(n) = tree.root().children().iter().next() {
            r.insert(*n.data());
            let t = n.remove_node();
            tree = t;
            for c in tree.root().children() {
                assert!(!r.contains(c.data()))
            }

            let isub = s.sub(&r);
            for c in tree.root().children() {
                assert!(isub.contains(c.data()))
            }
        }
    }

    #[test]
    fn remove_roots_and_nodes() {
        let mut tree = Path::new(0);
        let mut cs = std::collections::HashSet::new();
        for i in 0..128 {
            let node = tree.add_node(i);
            let ch1 = rand();
            let ch2 = rand();
            cs.insert((i, ch1));
            cs.insert((i, ch2));
            let node1 = node.add_node(ch1);
            let node2 = node1.parent().add_node(ch2);
            tree = node2.root();
        }

        let mut s = std::collections::HashSet::new();
        for r in tree.root().children() {
            assert_eq!(r.children().len(), 2);
            let d = *r.data();
            s.insert(d);
            for cc in r.children() {
                s.insert(*cc.data());
            }
        }

        for i in 0..128 {
            assert!(s.contains(&i));
        }

        let mut r = std::collections::HashSet::new();

        //
        // highly unadvisable ("reassign tree") inside the loop, since tree and children order will change
        //
        let mut checked_root: std::collections::HashSet<i32> = std::collections::HashSet::new();
        let mut i = 0;
        let mut children = tree.root().children();
        let mut iter = children.iter();
        while let Some(n) = iter.next() {
            if i >= 128 {
                break;
            }

            let d = *n.data();
            if checked_root.contains(&d) {
                continue;
            }

            i += 1;
            checked_root.insert(*n.data());
            assert_eq!(n.children().len(), 2);
            let children1 = n.children();
            let child = children1.last().unwrap();
            r.insert(*child.data());
            let t = child.remove_node();
            tree = t.root();
            for c in tree.root().children() {
                assert!(!r.contains(c.data()));
                for cc in c.children() {
                    assert!(!r.contains(cc.data()));
                }
            }

            let isub = s.sub(&r);
            for c in tree.root().children() {
                assert!(isub.contains(c.data()));
                for cc in c.children() {
                    assert!(isub.contains(cc.data()))
                }
            }
            children = tree.root().children();
            iter = children.iter();
        }
    }

    #[test]
    fn apply_roots() {
        let mut tree = Path::new(0);
        for i in 0..128 {
            let t = tree.add_node(i);
            tree = t.parent();
        }

        let mut s = std::collections::HashSet::new();
        for r in tree.children() {
            s.insert(*r.data());
        }

        for i in 0..128 {
            assert!(s.contains(&i));
        }

        for c in tree.children() {
            let new_c = c.apply(|x| Some(*x * 2));
            assert_eq!(*c.data() * 2, *new_c.data());
        }
    }

    #[test]
    fn apply_recursive_on_roots() {
        let mut tree = Path::new(0);
        for i in 0..128 {
            let t = tree.add_node(i);
            tree = t.parent();
        }

        let mut s = std::collections::HashSet::new();
        for r in tree.children() {
            s.insert(*r.data());
        }

        for i in 0..128 {
            assert!(s.contains(&i));
        }

        for c in tree.children() {
            let new_c = c.apply_recursive(&mut |x: &i32| Some(*x * 2));
            assert_eq!(*c.data() * 2, *new_c.data());
        }
    }

    #[test]
    fn apply_recursive_children() {
        let mut tree = Path::new(0);
        let mut cs = std::collections::HashSet::new();
        for i in 0..128 {
            let node = tree.add_node(i);
            let ch1 = rand() & 0xFFFF;
            let ch2 = rand() & 0xFFFF;
            cs.insert((i, ch1));
            cs.insert((i, ch2));
            let node1 = node.add_node(ch1);
            let node2 = node1.parent().add_node(ch2);
            tree = node2.root();
        }

        let mut s = std::collections::HashSet::new();
        for r in tree.children() {
            let d = *r.data();
            s.insert(d);
            assert_eq!(r.children().len(), 2);
        }

        for i in 0..128 {
            assert!(s.contains(&i));
        }

        for r in tree.children() {
            for ch in r.children() {
                assert!(cs.contains(&(*r.data(), *ch.data())));
            }
        }

        let mut n = 0;
        let tree_double = tree.apply_recursive(|x| {
            n = 3;
            Some(*x * 2)
        });
        assert_eq!(n, 3);

        for r in tree_double.children() {
            for ch in r.children() {
                assert!(cs.contains(&(*r.data() / 2, *ch.data() / 2)));
            }
        }
    }

    #[test]
    fn test_remove_all_children() {
        let mut tree = Path::new(0);
        for i in 1..10 {
            tree = tree.add_node(i)
        }

        let n9 = tree.parent();
        assert_eq!(*n9.data(), 8);

        let n8 = n9.parent();
        assert_eq!(*n8.data(), 7);

        assert_eq!(n8.children().len(), 1);
        assert_eq!(n8.remove_all_children().children().len(), 0);
    }

    #[test]
    fn test_map_data() {
        let mut tree = Path::new(0);
        for i in 1..10 {
            tree = tree.add_node(i)
        }

        let n9 = tree.parent();
        assert_eq!(*n9.data(), 8);

        let n8 = n9.parent();
        assert_eq!(*n8.data(), 7);

        assert_eq!(n8.children().len(), 1);

        let nn8 = n8.map_data(|_| None);
        assert!(nn8 == n8);
    }
}