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
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
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
//! # Tree
//! A tree structure.
//! ## Data Structure
//! The nb_tree crate provides a [`Tree<N, B>`](crate::tree::Tree) type
//! generic over node and branch data.
//!
//! Trees have an O(n) indexing. More precisely, it retrieves every node
//! on the path from the tree root to the targetted node.
//! Insertion and removal take a Path to target a node, binding their complexity
//! to the one of indexing, thus O(n).
//! Entries can be used to insert or remove at the [Entry](crate::tree::entry::Entry)'s
//! position in the tree, which only takes O(1).
//!
//! Trees can be [built](type@crate::tree::default::TreeBuilder),
//! [navigated and modified](type@crate::tree::entry::Entry),
//! [diffed](type@crate::tree::diff::DiffTree), [combined](type@crate::tree::combine) and [iterated](crate::tree::iter::Iter) on
//! amongst other operations.
//!
//! # Building trees
//! Trees can be built in several ways using (chainable) insertion methods.
//!
//! ## Inserting data
//! Data can be added or overwritten at a specified location via [insert].
//! ```
//! use nb_tree::prelude::Tree;
//! let mut tree: Tree<usize, String> = Tree::new();
//! // Insert at root
//! // (None reflects the creation of a new node
//! //  there is no previous value to return)
//! assert_eq!(tree.insert(&"/".into(), 0), Ok(None));
//! // Insert at various given Paths
//! assert_eq!(tree.insert(&"/a".into(), 1), Ok(None));
//! assert_eq!(tree.insert(&"/b".into(), 2), Ok(None));
//! assert_eq!(tree.insert(&"/b/c".into(), 3), Ok(None));
//! // One can't insert below an inexistent node with `insert`
//! // Use `insert_extend` for this
//! assert_eq!(tree.insert(&"/a/x/z".into(), 12), Err(Some("/a".into())));
//! ```
//! A shorthand exists for chaining insertions
//! ```
//! use nb_tree::prelude::Tree;
//! let mut tree: Tree<usize, String> = Tree::new();
//! tree.i("/", 0)
//!     .i("/a", 1)
//!     .i("/a/b", 2)
//!     .i("/a/c", 3)
//!     .i("/d", 4);
//! ```
//! Note that [i] panics if the insertion fails.
//!
//! For node data types that are [Default], [insert_extend] can be used to build
//! intermediary nodes with default data between the last existing node of the
//! given [Path] in the [Tree] and the one to insert
//! ```
//! use nb_tree::prelude::Tree;
//! let mut tree: Tree<usize, String> = Tree::new();
//! tree.insert_extend(&"/a/b/c/x/y/z".into(), 1000000);
//! assert_eq!(tree.values().len(), 7);
//! // A shorthand for `insert_extend` also exists and can be chained
//! tree.ix("/a/b/i/j/k", 101010)
//!     .ix("/a/u/v/w/i/j/k", 222);
//! assert_eq!(tree.values().len(), 16);
//! ```
//! [`insert_extend`] returns the old value if any.
//! If the node did not exist, it returns the default value of the node type.
//!
//! ### Builder
//! [`TreeBuilder`] is a [`Tree`] wrapping each node data in an `Option`.
//! [`Tree`]s with `Option<N>` node data have a [`try_build()`] method to build
//! a `Tree<N>` from it.
//!
//! ```
//! use nb_tree::prelude::{Tree, TreeBuilder};
//! let mut tree: TreeBuilder<usize, String> = TreeBuilder::new();
//! tree.ix("/a/b/c", Some(3))
//!     .ix("/a/b", Some(2));
//! // The tree can't be built because there are empty nodes ("/" and "/a") left
//! assert_eq!(tree.is_buildable(), false);
//!
//! tree.ix("/", Some(0))
//!     .ix("/a", Some(1));
//! // The tree is now buildable
//! assert_eq!(tree.is_buildable(), true);
//!
//! let mut tree_cmp: Tree<usize, String> = Tree::new();
//! tree_cmp.i("/", 0).i("/a", 1).i("/a/b", 2).i("/a/b/c", 3);
//! assert_eq!(tree.build(), tree_cmp);
//! ```
//!
//! ## Removing data
//! Subtrees can be removed from a tree:
//! [remove_subtree] removes the subtree starting at the given [Path].
//! ```
//! use nb_tree::prelude::Tree;
//! let mut tree: Tree<usize, String> = Tree::new();
//! tree.i("/", 0)
//!     .i("/a", 1)
//!     .i("/a/b", 2)
//!     .i("/a/c", 3);
//! // Removes the subtree at /a
//! tree.remove_subtree(&"/a".into());
//! // Only the root node (of value 0) now remains
//! assert_eq!(tree.values().len(), 1);
//! ```
//! [remove_subtree_trim] also trims out parent nodes containing the default value:
//! ```
//! use nb_tree::prelude::Tree;
//! let mut tree: Tree<Option<usize>, String> = Tree::new();
//! assert!(tree.insert(&"/".into(), Some(0)).is_ok());
//! assert!(tree.insert(&"/a".into(), Some(1)).is_ok());
//! tree.insert_extend(&"/a/b/c/i/j/k/x/y/z".into(), Some(1000000));
//! // `remove_subtree` only removes the subtree
//! tree.remove_subtree(&"/a/b/c/i/j/k".into());
//! assert_eq!(tree.len(), 6);
//! // `remove_subtree_trim` also removes the parent nodes containing `None`
//! tree.remove_subtree_trim(&"/a/b/c".into());
//! // Only the root node and the node at "/a" containing non default data remain
//! assert_eq!(tree.len(), 2);
//! ```
//!
//! ## Navigation and manipulation
//!
//! [Entries](type@crate::tree::entry::Entry) allow for tree navigation and mutation,
//! similarly to HashMaps' entry system.
//! It represents an entry at a given Path.
//! It may lead to a defined node or not.
//! ```
//! use nb_tree::prelude::Tree;
//! let mut tree: Tree<usize, String> = Tree::new();
//! tree.i("/", 0)
//!     .i("/a", 1)
//!     .i("/a/b", 2)
//!     .i("/c", 3)
//!     .i("/f", 4);
//! let mut entry = tree.entry_mut(&"/a".into());
//! // Insert only if there isn't a value already defined
//! // (won't do anything since /a is already set)
//! entry.or_insert(10);
//! // Move down to an other node
//! entry.move_down("/b/w".into());
//! // inserts 12 at /b/w
//! entry.or_insert(12);
//! // `or_insert_extend` is only available if N is Default
//! let mut tree2: Tree<Option<usize>, String> = Tree::new();
//! let mut entry2 = tree2.entry_mut(&"/i/j/k".into());
//! entry2.or_insert_extend(Some(12));
//! assert_eq!(tree2.len(), 4);
//! ```
//! `and_modify` only applies the given function to the node's value if it is defined.
//! ```
//! # use nb_tree::prelude::Tree;
//! # let mut tree: Tree<usize, String> = Tree::new();
//! # tree.i("/", 0)
//! #     .i("/a", 1)
//! #     .i("/a/b", 2)
//! #     .i("/c", 3)
//! #     .i("/f", 4);
//! let mut entry = tree.entry_mut(&"/a/b".into());
//! entry.and_modify(|mut n| *n += 1);
//! ```
//! The previous methods like `insert` and `remove_subtree` are also available
//! for inserting and removing data at entry position.
//!
//! # Differentials
//! ## Diffing
//! Trees can be compared via [`diff`], producing a [`DiffTree`] containing
//! all differing nodes between the compared trees.
//! [`DiffTree`]s are `Tree`s with `DiffNode`s which have the type `(Option(N), Option(N))`.
//! The `Option`s signal the presence (or absence thereof) of the node in the compared trees.
//! The `DiffTree` produced by `diff` only contains data for nodes differing,
//! so the diff tree will be extended with empty nodes (`(None, None)`) to build the tree.
//! ```
//! use nb_tree::prelude::{Tree, DiffTree};
//! let mut tree1: Tree<usize, String> = Tree::new();
//! tree1.i("/", 0)
//!     .i("/a", 1)
//!     .i("/a/b", 2)
//!     .i("/c", 3)
//!     .i("/f", 4);
//!
//! let mut tree2: Tree<usize, String> = Tree::new();
//! tree2.i("/", 9)
//!     .i("/a", 2)
//!     .i("/a/b", 1)
//!     .i("/c", 3)
//!     .i("/c/d", 4);
//!
//! // Create a DiffTree containing the differences between `tree1` and `tree2`
//! let diff = tree1.diff(&tree2);
//!
//! let mut diff_cmp: DiffTree<usize, String> = DiffTree::new();
//! diff_cmp.i("/", (Some(0), Some(9)))
//!     .i("/a", (Some(1), Some(2)))
//!     .i("/a/b", (Some(2), Some(1)))
//!     .i("/f", (Some(4), None))
//!     .ix("/c/d", (None, Some(4)));
//! // "/c/d" node insertion needs a node at "/c"
//! // `ix` will extend the tree with an empty node (`(None, None)`) to allow for that
//! assert_eq!(diff, diff_cmp);
//! ```
//! [`zip`] will combine both trees into a [DiffTree].
//!
//! ## Applying diffs
//!
//! [`DiffTree`]s can be applied to a tree via [`apply`] and [`apply_extend`].
//! ```
//! # use nb_tree::prelude::{Tree, DiffTree};
//! # let mut tree1: Tree<usize, String> = Tree::new();
//! # tree1.i("/", 0)
//! #     .i("/a", 1)
//! #     .i("/a/b", 2)
//! #     .i("/c", 3)
//! #     .i("/f", 4);
//! # let mut tree2: Tree<usize, String> = Tree::new();
//! # tree2.i("/", 9)
//! #     .i("/a", 2)
//! #     .i("/a/b", 1)
//! #     .i("/c", 3)
//! #     .i("/c/d", 4);
//! # let mut diff = tree1.diff(&tree2);
//! // … taking back `tree1`, `tree2` and `diff` from the previous example
//! let tree1_orig = tree1.clone();
//! // Apply the differential between `tree1` and `tree2`
//! tree1.apply(diff.clone());
//! // They are both equal now
//! assert_eq!(tree1, tree2);
//! // Applying the reversed diff will restore tree1
//! diff.rev();
//! tree1.apply(diff);
//! assert_eq!(tree1, tree1_orig);
//! ```
//!
//! Single diff data can be applied via the `apply_diff` method which takes a
//! Path and a `DiffNode` and applies it to the tree.
//! These diffs can be gathered into a `DiffMap` that too can be applied
//! via `apply_map`.
//! ```
//! use nb_tree::prelude::{Tree, DiffMap};
//! use std::collections::HashMap;
//! let mut tree: Tree<usize, String> = Tree::new();
//! tree.i("/", 0)
//!     .i("/a", 1)
//!     .i("/a/b", 2)
//!     .i("/c", 3)
//!     .i("/f", 4);
//! // Changes the value of the node at /c from 3 to 7
//! tree.apply_diff("/c".into(), (Some(3), Some(7)));
//! // Removes the node at /a that had the value 1 and the subtree below it
//! tree.apply_diff("/a".into(), (Some(1), None));
//! // Changes /f from 4 to 0, creates /f/z with value 5
//! let map = HashMap::from([
//!     ("/f".into(), (Some(4), Some(0))),
//!     ("/f/z".into(),
//!     (None, Some(5)))]).into();
//! let mut tree_cmp: Tree<usize, String> = Tree::new();
//! tree.apply_map(map);
//! tree_cmp.i("/", 0)
//!     .i("/c", 7)
//!     .i("/f", 0)
//!     .i("/f/z", 5);
//! assert_eq!(tree, tree_cmp);
//! ```
//! # Combining
//! Combining trees can be done through the `combine()` method.
//! Data present in both trees can be chosen from either tree,
//! data only present in one of them can be kept or discarded.
//! `CombinationMode::Union` and `CombinationMode::Intersection` are available,
//! as well as a `CombinationMode::Free` mode which lets freely select
//! the data to keep during the combination.
//! ```
//! use nb_tree::prelude::{Tree, CombinationMode};
//! let mut tree1: Tree<usize, String> = Tree::new();
//! tree1.i("/", 0)
//!      .i("/a", 1)
//!      .i("/a/b", 11)
//!      .i("/c", 2)
//!      .i("/f", 3);
//!
//! let mut tree2: Tree<usize, String> = Tree::new();
//! tree2.i("/", 500)   // |- overlaping data
//!      .i("/a", 900)  // |
//!      .i("/a/w", 910)// |- new data
//!      .i("/x", 100)  // |
//!      .i("/x/y", 110)// |
//!      .i("/z", 300); // |
//!
//! // tree1 is combined with tree2, keeping tree1's nodes absent from tree2,
//! // growing tree1 with tree2's nodes absent from tree1
//! // and overwriting tree1's data with tree2's for nodes common to both trees.
//! tree1.combine(tree2, CombinationMode::Free{keep: true, grow: true, overwrite: true});
//! // (this is the same as `CombinationMode::Union(true)`)
//!
//! let mut tree_comb: Tree<usize, String> = Tree::new();
//! tree_comb.i("/", 500)   // |- common nodes with tree2's data (overwrite)
//!          .i("/a", 900)  // |
//!          .i("/a/b", 11) // |- tree1's nodes (keep)
//!          .i("/c", 2)    // |
//!          .i("/f", 3)    // |
//!          .i("/a/w", 910)// |- tree2's nodes (grow)
//!          .i("/x", 100)  // |
//!          .i("/x/y", 110)// |
//!          .i("/z", 300); // |
//!
//! assert_eq!(tree1, tree_comb);
//! ```
//! # Iterating
//!
//! The default iteration method is depth first (width first is not yet available)
//! ```
//! use nb_tree::prelude::{Tree, DiffMap};
//! let mut tree1: Tree<usize, String> = Tree::new();
//! tree1.i("/", 0)
//!     .i("/a", 1)
//!     .i("/a/b", 12)
//!     .i("/c", 3)
//!     .i("/f", 4);
//! // Prints each node's branch and value
//! for iter_node in tree1 {
//!     println!("{} at {:?}", iter_node.data(), iter_node.branch());
//! }
//! ```
//! `iter` and `into_iter` are implemented (`iter_mut` is not yet available).
//! The iteration nodes contain information about the position in the tree
//! relative to the previous node.
//! The path to the current node can be built by applying these relative movements to it.
//! ```
//! # use nb_tree::prelude::{Tree, DiffMap};
//! # let mut tree1: Tree<usize, String> = Tree::new();
//! # tree1.i("/", 0)
//! #     .i("/a", 1)
//! #     .i("/a/b", 12)
//! #     .i("/c", 3)
//! #     .i("/f", 4);
//! # use nb_tree::prelude::Path;
//! let mut path = Path::new();
//! for iter_node in tree1 {
//!     path.apply(&iter_node);
//!     println!("{} at {}", iter_node.data(), path);
//! }
//! ```
//! The usual iterator operations are available as well as `absolute` and `skip_below`.
//!
//! `absolute` returns the next value with its Path.
//! ```
//! # use nb_tree::prelude::{Tree, DiffMap};
//! # let mut tree1: Tree<usize, String> = Tree::new();
//! # tree1.i("/", 0)
//! #     .i("/a", 1)
//! #     .i("/a/b", 12)
//! #     .i("/c", 3)
//! #     .i("/f", 4);
//! # use nb_tree::prelude::Path;
//! use itertools::Itertools;
//! use crate::nb_tree::tree::iter::{TreeIterTools, TraversalNode};
//! assert_eq!(
//!     tree1.into_iter().absolute().map(|n| n.path).sorted().collect::<Vec<Path<String>>>(),
//!     vec!["/".into(), "/a".into(), "/a/b".into(), "/c".into(), "/f".into()]
//!     );
//! ```
//!
//! `skip_below` takes a predicate and skips all nodes at and below the current path.
//! ```
//! use nb_tree::prelude::{Tree, DiffMap};
//! let mut tree1: Tree<usize, String> = Tree::new();
//! tree1.i("/", 0)
//!     .i("/a", 1)
//!     .i("/a/b", 12)
//!     .i("/a/b/z", 6)
//!     .i("/c", 3)
//!     .i("/c/d", 7)
//!     .i("/c/d/y", 5)
//!     .i("/f", 11)
//!     .i("/g", 10)
//!     .i("/h", 11)
//!     .i("/i", 19)
//!     .i("/i/w", 18)
//!     .i("/i/w/n", 8)
//!     .i("/k", 15);
//! use itertools::Itertools;
//! use nb_tree::prelude::Path;
//! use crate::nb_tree::tree::iter::TreeIterTools;
//! assert_eq!(
//!     tree1.into_iter().skip_below(|item| {
//!         *item.data() >= 10
//!     }).map(|n| n.data().clone()).sorted().collect::<Vec<usize>>(),
//!     vec![0, 1, 3, 5, 7]
//!     );
//! ```

pub(crate) mod clone;
pub(crate) mod default;
pub use default::TreeBuilder;
pub(crate) mod diff;
pub use diff::{DiffMap, DiffNode, DiffTree};
/// [`Tree`] iteration.
///
/// [`Tree`]: crate::tree::Tree
pub mod iter;
pub(crate) mod node;
use node::TreeNode;
/// [`Tree`] navigation.
///
/// [`Tree`]: crate::tree::Tree
pub mod entry;
pub(crate) mod position;
pub use position::Position;
use replace_with::replace_with_or_abort;

use self::diff::DiffApplyError;
use self::entry::{TreeMutEntry, TREEBOUND};
use self::iter::depth::IntoIter;
use self::{
    entry::{detached::DetachedEntry, node::Node, Entry},
    position::{AttachedPosition, DetachedPosition},
};
use super::path::Path;
use crate::path::PathIDX;

use iter::depth::{Iter, Traversal, TreeIterTarget};
use std::hash::Hash;
use std::mem;
use std::ops::Index;
use std::{fmt::Debug as Dbg, ops::Deref};
use tracing::{debug, error, trace, trace_span};

/// Takes a Result and returns the Some value or returns the given value.
macro_rules! or_return {
    ( $e:expr, $r:expr ) => {
        match $e {
            Some(x) => x,
            None => return $r,
        }
    };
}

/// The index of a node in the tree.
///
/// Since these can change, they cannot be used as node identifiers
/// and should not be exposed in the API.
pub(crate) type NodeIDX = usize;

/// Tree structure with generic node and branch data.
///
/// For more information about Trees and their usage,
/// see the [module level documentation](self).
///
/// Each node aside from the root node has a parent to which it is linked via a branch.
/// Nodes as well as branches have a value, which allows for giving names and wheights
/// to branches.
///
/// # Examples
/// A quick way to build a tree is by using the chainable version of `insert()` called `i()`
/// ```
/// use nb_tree::prelude::Tree;
/// let mut tree: Tree<usize, String> = Tree::new();
///
/// tree.i("/", 0)
///     .i("/a", 1)
///     .i("/a/b", 2)
///     .i("/a/b/z", 6)
///     .i("/c", 3)
///     .i("/c/d", 7);
/// ```
/// The resulting tree looks like this:
/// ```text
/// ╱┬→ 0
///  ├a┬→ 1
///  │ └b┬→ 2
///  │   └z─→ 6
///  └c┬→ 3
///    └d─→ 7
/// ```
/// # Data management
///
/// Removing a node from the tree also removes its children recursively.
/// Removal is done in constant time, since the nodes are only unlinked
/// from their parent and marked as removed.
/// Since the nodes are stored in a Vec, shifting the ones succeeding
/// the removed node would be costful and removing the whole subtree
/// would take O(n) given n the number of nodes in that subtree.
#[derive(Debug, Clone)]
pub struct Tree<N, B> {
    /// Nodes are added and removed through `insert()` and `remove()` only.
    nodes: Vec<TreeNode<N, B>>,
    /// Nodes removed from the tree.
    /// These indexes will be reused later upon inserting new nodes
    /// via `insert()`.
    /// `remove()` adds them to the vec.
    removed: Vec<NodeIDX>,
}

impl<N, B> Default for Tree<N, B> {
    fn default() -> Self {
        Self {
            nodes: Vec::default(),
            removed: Vec::default(),
        }
    }
}

impl<N, B> Index<&Path<B>> for Tree<N, B>
where
    B: Eq + Hash + Clone,
{
    type Output = N;
    fn index(&self, index: &Path<B>) -> &Self::Output {
        self.get(index)
            .unwrap_or_else(|_| panic!("Could not index into the tree with the given path"))
    }
}

impl<N, B> PartialEq for Tree<N, B>
where
    N: Eq,
    B: Eq + Hash,
{
    fn eq(&self, other: &Self) -> bool {
        (self.is_empty() && other.is_empty())
            || (!self.is_empty()
                && !other.is_empty()
                && self.is_subtree_eq(
                    self.get_root_idx().unwrap(),
                    other,
                    other.get_root_idx().unwrap(),
                ))
    }
}

impl<N, B> Eq for Tree<N, B>
where
    N: Eq,
    B: Eq + Hash,
{
}

impl<N, B> Tree<N, B> {
    /// Creates a new empty generic tree over node data (`N`)
    /// and branch data (`B`) types.
    ///
    /// # Examples
    /// ```
    /// use nb_tree::prelude::Tree;
    /// let tree: Tree<usize, String> = Tree::new();
    /// ```
    pub fn new() -> Self {
        Default::default()
    }

    /// Creates a new empty tree with at least the given capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            nodes: Vec::with_capacity(capacity),
            ..Default::default()
        }
    }

    /// Reserves space for at least the given additional amount of nodes in the tree.
    pub fn reserve(&mut self, additional: usize) {
        self.nodes.reserve(additional)
    }

    /// Returns the value of the root node if there is one, returns None otherwise.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nb_tree::prelude::Tree;
    /// let mut tree: Tree<String, String> = Tree::new();
    /// // The tree is empty
    /// assert_eq!(tree.get_root(), None);
    /// tree.i("/", "a".to_string());
    ///
    /// assert_eq!(tree.get_root(), Some(&"a".to_string()));
    /// ```
    pub fn get_root(&self) -> Option<&N> {
        if self.is_empty() {
            None
        } else {
            Some(&self.nodes[0].value)
        }
    }

    /// Returns the index of the root node if there is one, returns None otherwise.
    ///
    /// There is no guaranty that the root node will always be 0.
    fn get_root_idx(&self) -> Option<NodeIDX> {
        (!self.is_empty()).then_some(0)
    }

    /// Inserts a value at the root and returns the previous value if there is one.
    ///
    /// # Examples
    /// ```rust
    /// use nb_tree::prelude::Tree;
    /// let mut tree: Tree<String, String> = Tree::new();
    /// assert_eq!(tree.insert_root("a".to_string()), None);
    /// assert_eq!(tree.insert_root("b".to_string()), Some("a".to_string()));
    /// ```
    pub fn insert_root(&mut self, value: N) -> Option<N> {
        if self.nodes.is_empty() {
            // Initialize the tree with a root node
            self.nodes.push(value.into());
            None
        } else if self.removed.last() == Some(&0) {
            // Reinsert the removed node
            self.removed.pop();
            self.removed
                .append(&mut self.nodes[0].children.values().cloned().collect());
            self.nodes[0] = value.into();
            self.nodes[0].children = Default::default();
            None
        } else {
            // The root should not have been removed
            debug_assert!(
                !self.removed.contains(&0),
                "Root has been removed but is not the most recent deletion"
            );
            // Replace the current value
            Some(mem::replace(&mut self.nodes[0].value, value))
        }
    }

    /// Removes all nodes from the tree.
    fn clear(&mut self) {
        *self = Tree::default();
        /* Alternative not removing any node
        if self.removed.last().map_or(true, |l| *l != 0) {
            self.removed.push(0);
        }*/
    }

    /// Returns true is the tree has no nodes.
    ///
    /// # Examples
    /// ```rust
    /// use nb_tree::prelude::Tree;
    /// let mut tree: Tree<String, String> = Tree::new();
    /// assert!(tree.is_empty());
    /// tree.insert_root("a".to_string());
    /// assert!(!tree.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty() || self.removed.last() == Some(&0)
    }

    /// Return the number of nodes in the tree.
    ///
    /// # Examples
    /// ```rust
    /// use nb_tree::prelude::Tree;
    /// let mut tree: Tree<usize, String> = Tree::new();
    /// assert_eq!(tree.len(), 0);
    /// tree.i("/", 10);
    /// assert_eq!(tree.len(), 1);
    /// tree.i("/a", 20)
    ///     .i("/a/b", 30)
    ///     .i("/a/b/z", 40)
    ///     .i("/c", 50)
    ///     .i("/c/d", 60);
    /// assert_eq!(tree.len(), 6);
    /// ```
    pub fn len(&self) -> usize {
        self.iter_on::<()>().count()
    }

    /// Returns a vector of references to the tree's node values in arbitrary order.
    ///
    /// # Examples
    /// ```rust
    /// use std::collections::HashSet;
    /// use std::iter::FromIterator;
    /// use nb_tree::prelude::Tree;
    ///
    /// let mut tree: Tree<usize, String> = Tree::new();
    /// tree.i("/", 0)
    ///     .i("/a", 1)
    ///     .i("/a/b", 2);
    /// let values: HashSet<usize> = HashSet::from_iter(vec![0,1,2].into_iter());
    /// let tree_values: HashSet<usize> = HashSet::from_iter(tree.values().into_iter().cloned());
    /// assert_eq!(
    ///     tree_values,
    ///     values);
    /// ```
    pub fn values(&self) -> Vec<&N> {
        self.iter().map(|n| n.take()).collect()
    }

    /// Returns an iterator over [TreeIterTarget] data from each thee node
    /// relatively to one another.
    ///
    /// The iterator returns [`Traversal`]s containing
    /// the associated TreeIterTarget.
    fn iter_on<'a, T: TreeIterTarget<'a, N, B>>(&'a self) -> Iter<'a, N, B, T> {
        Iter::new(self)
    }

    /// Returns an depth first iterator over the tree's node data relatively to one another.
    ///
    /// The iterator returns [`Traversal`]s containing the associated node data.
    /// If the tree is not empty, the first item is a [`Root`] node
    /// containing a reference to the root node's data.
    /// All subsequent items are [`Node`]s containing their position
    /// relative to the previous item and a reference to the node's data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nb_tree::prelude::{iter::depth::Traversal, Path, Tree};
    /// let mut tree: Tree<usize, String> = Tree::new();
    /// tree.i("/", 0)
    ///     .i("/a", 1)
    ///     .i("/a/B", 10)
    ///     .i("/a/B/i", 100)
    ///     .i("/a/B/j", 200)
    ///     .i("/a/C", 11)
    ///     .i("/a/C/x", 111)
    ///     .i("/a/C/y", 222);
    /// let mut iter = tree.iter();
    /// if let Traversal::Start(data) = iter.next().expect("Root node expected") {
    ///     // The root node's data is 0
    ///     assert_eq!(*data, 0);
    /// } else {
    ///     panic!("Expected a Root node");
    /// }
    /// if let Traversal::Step { up, branch, data } =
    ///     iter.next().expect("Root child Node expected")
    /// {
    ///     // The node is below the root node
    ///     assert_eq!(up, 0);
    ///     // The node is at branch "a"
    ///     assert_eq!(*branch, "a");
    ///     // The node's data is 1
    ///     assert_eq!(*data, 1);
    /// } else {
    ///     panic!("Expected a non Root node");
    /// }
    /// let mut path = Path::new();
    /// for iter_node in tree {
    ///     // Move up the path
    ///     if iter_node.up() > 0 {
    ///         for _ in 0..iter_node.up() {
    ///             path.pop_last();
    ///         }
    ///         //
    ///         println!(
    ///             "{}╭{}┘ up",
    ///             " ".repeat(path.to_string().len()),
    ///             "──".repeat(iter_node.up()-1)
    ///         );
    ///     }
    ///     // Get the branch if any (there is none for the Root)
    ///     if let Some(branch) = iter_node.branch() {
    ///         path.push_last(branch.clone());
    ///     }
    ///     // Get the data
    ///     println!("{}: {}", path, iter_node.data());
    /// }
    /// ```
    /// One possible output would be:
    /// ```text
    ///     /: 0
    ///     /a: 1
    ///     /a/B: 10
    ///     /a/B/i: 100
    ///         ╭┘ up
    ///     /a/B/j: 200
    ///       ╭──┘ up
    ///     /a/C: 11
    ///     /a/C/x: 111
    ///         ╭┘ up
    ///     /a/C/y: 222
    /// ```
    /// As the iteration order of children of a node is unknown,
    /// "/a/C" can be visited before "/a/B", as can "/a/B/j" and "/a/B/i"
    /// as well as "/a/C/y" and "/a/C/x".
    pub fn iter(&self) -> Iter<N, B, &N> {
        self.iter_on()
    }
}

impl<N, B> Tree<N, B>
where
    B: Eq + Hash,
{
    /// Returns the index of the node pointed to by the given [path].
    ///
    /// If the node doesn't exist, it returns the index of the closest
    /// existing node in the tree and the index of the inexistent child in [path].
    /// If the tree is empty, None is returned.
    fn get_idx(
        &self,
        path: &Path<B>,
        from_idx: Option<NodeIDX>,
    ) -> Result<NodeIDX, Option<(NodeIDX, PathIDX)>> {
        let root_idx = if let Some(idx) = self.get_root_idx() {
            idx
        } else {
            return Err(None);
        };
        path.iter().enumerate().try_fold(
            from_idx.unwrap_or(root_idx),
            |node_idx, (path_idx, branch)| {
                self.nodes[node_idx]
                    .children
                    .get(branch)
                    .cloned()
                    .ok_or(Some((node_idx, path_idx)))
            },
        )
    }

    /// Returns a vector of the index of every node along the given [path].
    ///
    /// If a node doesn't exist, the index vector up until this node is returned
    /// as well as the index of the inexistent child in [path].
    /// If the tree is empty, None is returned.
    fn get_path_idxs(&self, path: &Path<B>) -> Result<Vec<NodeIDX>, Option<(Vec<NodeIDX>, usize)>> {
        let root_idx = if let Some(idx) = self.get_root_idx() {
            idx
        } else {
            return Err(None);
        };
        path.iter()
            .enumerate()
            .try_fold(vec![root_idx], |mut node_idx, (path_idx, branch)| {
                node_idx.push(
                    self.nodes[*node_idx.last().unwrap()]
                        .children
                        .get(branch)
                        .cloned()
                        //NOTE: No way to do without the cloning? (E0505)
                        .ok_or(Some((node_idx.clone(), path_idx)))?,
                );
                Ok(node_idx)
            })
    }

    /// Inserts a value as the [child] node of the given parent.
    ///
    /// # Warning
    /// Does not check the validity of [parent_idx].
    fn insert_at(&mut self, parent_idx: NodeIDX, child: B, value: N) -> (Option<N>, NodeIDX) {
        // Child exists?
        if let Some(child_idx) = self.nodes[parent_idx].children.get(&child).cloned() {
            (
                Some(mem::replace(&mut self.nodes[child_idx].value, value)),
                child_idx,
            )
        } else {
            // Get a node
            let idx = if let Some(idx) = self.removed.pop() {
                // Use a removed one
                self.removed
                    .append(&mut self.nodes[idx].children.values().cloned().collect());
                self.nodes[idx] = From::from(value);
                self.nodes[parent_idx].children.insert(child, idx);
                idx
            } else {
                let idx = self.nodes.len();
                // Extend the vec
                self.nodes.push(From::from(value));
                //NOTE: Any way to do without the variable? (E0502)
                self.nodes[parent_idx].children.insert(child, idx);
                idx
            };

            (None, idx)
        }
    }

    /// Removes the subtree at the [child] of the given parent node.
    ///
    /// # Warning
    /// Does not check [parent_idx]'s validity
    fn remove_subtree_at(&mut self, parent_idx: NodeIDX, child: B) -> Option<NodeIDX> {
        let idx = self.nodes[parent_idx].children.remove(&child)?;
        self.remove_subtree_idx(idx)
    }

    /// Adds the subtree at the given [idx] to the `removed` array.
    ///
    /// # Warning
    /// Does not check [idx]'s validity
    fn remove_subtree_idx(&mut self, idx: NodeIDX) -> Option<NodeIDX> {
        self.removed.push(idx);
        Some(idx)
    }
}

impl<N, B> Tree<N, B>
where
    B: Eq + Hash + Clone,
{
    /// Returns a reference to the value of the node at the given [path].
    /// If the path leaves the tree, the path to the last node in the tree on the given path is returned, or None if the tree is empty.
    /// # Examples
    /// ```
    /// use nb_tree::prelude::Tree;
    /// let mut tree: Tree<usize, String> = Tree::new();
    /// // Can't get any node from an empty node
    /// assert_eq!(tree.get(&"/a/b/w".into()), Err(None));
    /// tree.i("/", 0)
    ///     .i("/a", 1)
    ///     .i("/a/b", 2)
    ///     .i("/c", 3);
    /// // Get a reference to the node data at "/a"
    /// assert_eq!(tree.get(&"/a".into()), Ok(&1));
    /// // "/a/b/w" is out of the tree, "/a/b" being the last node in the tree of the path
    /// assert_eq!(tree.get(&"/a/b/w".into()), Err(Some("/a/b".into())));
    /// ```
    pub fn get(&self, path: &Path<B>) -> Result<&N, Option<Path<B>>> {
        Ok(&self.nodes[self
            .get_idx(path, None)
            .map_err(|r| r.map(|(_, i)| path.path_to(i)))?]
        .value)
    }

    /// Returns a mutable reference to the value of the node at the given [path].
    /// If the path leaves the tree, the path to the last node in the tree on the given path is returned, or None if the tree is empty.
    /// # Examples
    /// ```
    /// use nb_tree::prelude::Tree;
    /// let mut tree: Tree<usize, String> = Tree::new();
    /// // Can't get any node from an empty node
    /// assert_eq!(tree.get(&"/a/b/w".into()), Err(None));
    /// tree.i("/", 0)
    ///     .i("/a", 1)
    ///     .i("/a/b", 2)
    ///     .i("/c", 3);
    /// // Get a reference to the node data at "/a"
    /// assert_eq!(tree.get_mut(&"/a".into()), Ok(&mut 1));
    /// // "/a/b/w" is out of the tree, "/a/b" being the last node in the tree of the path
    /// assert_eq!(tree.get_mut(&"/a/b/w".into()), Err(Some("/a/b".into())));
    /// ```
    pub fn get_mut(&mut self, path: &Path<B>) -> Result<&mut N, Option<Path<B>>> {
        let idx = self
            .get_idx(path, None)
            .map_err(|r| r.map(|(_, i)| path.path_to(i)))?;
        Ok(&mut self.nodes[idx].value)
    }

    /// Returns an [Entry] with read only access to the root node's position.
    ///
    /// # Examples
    /// ```
    /// use nb_tree::prelude::Tree;
    /// let mut tree: Tree<usize, String> = Tree::new();
    /// let entry = tree.root_entry();
    /// assert!(!entry.is_node());
    /// tree.i("/", 7)
    ///     .i("/c1", 1);
    /// let mut entry = tree.root_entry();
    /// assert_eq!(entry.value(), Some(&7));
    /// entry.move_down_branch("c1".into());
    /// assert_eq!(entry.value(), Some(&1));
    /// ```
    pub fn root_entry(&self) -> Entry<&Self, N, B, TREEBOUND> {
        match self.get_root_idx() {
            Some(root) => {
                Node::from(self, AttachedPosition::from(Path::new(), Path::with(root))).into()
            }
            None => {
                DetachedEntry::from(self, DetachedPosition::from(Path::new(), Path::new())).into()
            }
        }
    }

    /// Returns an [Entry] with mutable access to the root node's position.
    ///
    /// # Examples
    /// ```
    /// use nb_tree::prelude::Tree;
    /// let mut tree: Tree<usize, String> = Tree::new();
    /// let mut entry = tree.root_entry_mut();
    /// assert!(!entry.is_node());
    /// assert_eq!(entry.or_insert(5), &mut 5);
    /// entry.move_down_branch("c1".into());
    /// assert_eq!(entry.or_insert(1), &mut 1);
    /// ```
    pub fn root_entry_mut(&mut self) -> Entry<&mut Self, N, B, TREEBOUND> {
        match self.get_root_idx() {
            Some(root) => {
                Node::from(self, AttachedPosition::from(Path::new(), Path::with(root))).into()
            }
            None => {
                DetachedEntry::from(self, DetachedPosition::from(Path::new(), Path::new())).into()
            }
        }
    }

    /// Returns an [Entry] with read only access to the given position in the tree.
    ///
    /// # Examples
    /// ```
    /// use nb_tree::prelude::Tree;
    /// let mut tree: Tree<usize, String> = Tree::new();
    /// tree.i("/", 0)
    ///     .i("/a", 1)
    ///     .i("/a/b", 2)
    ///     .i("/c", 3);
    /// let entry = tree.entry(&"/a/b".into());
    /// assert_eq!(entry.value(), Some(&2));
    /// ```
    pub fn entry(&self, path: &Path<B>) -> Entry<&Self, N, B, TREEBOUND> {
        Self::get_entry(self, path)
    }

    /// Returns an [Entry] with mutable access to the given position in the tree.
    ///
    /// # Examples
    /// ```
    /// use nb_tree::prelude::Tree;
    /// let mut tree: Tree<usize, String> = Tree::new();
    /// tree.i("/", 0)
    ///     .i("/a", 1)
    ///     .i("/a/b", 2)
    ///     .i("/c", 3);
    /// let mut entry = tree.entry_mut(&"/a/b/d".into());
    /// assert_eq!(entry.or_insert(4), &mut 4);
    /// ```
    pub fn entry_mut(&mut self, path: &Path<B>) -> Entry<&mut Self, N, B, TREEBOUND> {
        Self::get_entry(self, path)
    }

    /// Returns an Entry to the given position in the given tree.
    fn get_entry<R: Deref<Target = Tree<N, B>>>(s: R, path: &Path<B>) -> Entry<R, N, B, TREEBOUND> {
        match s.get_path_idxs(path) {
            Ok(idxs) => Node::from(s, AttachedPosition::from(path.clone(), idxs.into())).into(),
            Err(e) => DetachedEntry::from(
                s,
                DetachedPosition::from(
                    path.clone(),
                    e.map(|(idxs, _)| idxs.into()).unwrap_or_default(),
                ),
            )
            .into(),
        }
    }

    /// Inserts a value at the given [path].
    /// Returns the existing value if any.
    /// Insertions can be done on any existing node ([path] points to an existing node)
    /// or on children of existing nodes ([path] points to
    /// an inexistent immediate child of an existing node).
    /// Insertions cannot be done if [path] points to a node further away
    /// from the existing tree as it cannot close the gap between the last
    /// existing node and the new one to insert.
    /// In this case the operation will fail and the [Path] to the closest
    /// existing node will be returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use nb_tree::prelude::Tree;
    /// let mut tree: Tree<_, String> = Tree::new();
    /// // Set root
    /// assert_eq!(tree.insert(&"/".into(), 0), Ok(None));
    /// // Append node
    /// assert_eq!(tree.insert(&"/a".into(), 1), Ok(None));
    /// // Overwrite existing node
    /// assert_eq!(tree.insert(&"/a".into(), 2), Ok(Some(1)));
    /// // Leave tree
    /// assert_eq!(tree.insert(&"/a/b/c".into(), 2), Err(Some("/a".into())));
    /// ```
    pub fn insert(&mut self, path: &Path<B>, value: N) -> Result<Option<N>, Option<Path<B>>> {
        let mut path = path.clone();
        if let Some(child) = path.pop_last() {
            Ok(self
                .insert_at(
                    self.get_idx(&path, None)
                        .map_err(|r| r.map(|(_, i)| path.path_to(i)))?,
                    child,
                    value,
                )
                .0)
        } else {
            Ok(self.insert_root(value))
        }
    }

    //TODO: Remove the nodes immediately and return the nodes as a Tree
    /// Removes the subtree at the given [path] from the tree
    /// If the root node is not found, it returns the path to the closest
    /// existing node, or None if the tree is empty.
    /// # Examples
    /// ```
    /// use nb_tree::prelude::Tree;
    /// let mut tree1: Tree<usize, String> = Tree::new();
    /// tree1.insert(&"/".into(), 0);
    /// tree1.insert(&"/a".into(), 1);
    /// tree1.insert(&"/a".into(), 2);
    /// tree1.insert(&"/b".into(), 3);
    /// let mut tree2 = tree1.clone();
    ///
    /// // Add a branch to tree2
    /// tree2.insert(&"/c".into(), 4);
    /// tree2.insert(&"/c/d".into(), 5);
    ///
    /// // Remove the branch
    /// tree2.remove_subtree(&"/c".into());
    /// assert_eq!(tree1, tree2);
    /// ```
    pub fn remove_subtree(&mut self, path: &Path<B>) -> Result<(), Option<Path<B>>> {
        let mut path = path.clone();
        if self.is_empty() {
            Err(None)
        } else if let Some(child) = path.pop_last() {
            // Remove a node
            let parent_idx = self
                .get_idx(&path, None)
                .map_err(|r| r.map(|(_, i)| path.path_to(i)))?;
            self.remove_subtree_at(parent_idx, child)
                .map(|_| ())
                .ok_or(Some(path))
        } else {
            // Root is being removed
            self.nodes.clear();
            self.removed.clear();
            Ok(())
        }
    }

    /// Applies the differential to the tree without checking its validity beforehand
    ///
    /// Nodes that can't be added or removed are skipped.
    ///
    /// # Examples
    /// ```
    /// use nb_tree::prelude::{Tree, DiffTree};
    /// let mut tree1: Tree<usize, String> = Tree::new();
    /// tree1.i("/", 0)
    ///     .i("/a", 1)
    ///     .i("/a/b", 2)
    ///     .i("/c", 3);
    /// let mut diff: DiffTree<usize, String> = DiffTree::new();
    /// diff.i("/", (Some(0), Some(9)))
    ///     .i("/a", (Some(1), Some(2)))
    ///     .i("/a/w", (Some(2), Some(100)))
    ///     .i("/x", (Some(40), None))
    ///     .i("/z", (None, Some(200)))
    ///     .i("/c", (None, Some(4)));
    /// tree1.force_apply(diff);
    ///
    /// let mut tree_applied: Tree<usize, String> = Tree::new();
    /// tree_applied.i("/", 9)
    ///     .i("/a", 2)
    ///     .i("/a/b", 2)
    ///     .i("/a/w", 100)
    ///     .i("/z", 200)
    ///     .i("/c", 4);
    /// assert_eq!(tree1, tree_applied);
    /// ```
    pub fn force_apply(&mut self, diff: DiffTree<N, B>) -> bool {
        self.force_apply_with(
            diff,
            |entry, now| entry.insert(now).is_some(),
            |entry| {
                replace_with_or_abort(entry, |e| e.remove_subtree());
                true
            },
        )
    }
    pub fn force_apply_with<'a>(
        &'a mut self,
        diff: DiffTree<N, B>,
        insert: InsertWith<&'a mut Tree<N, B>, N, B, false>,
        delete: DeleteWith<&'a mut Tree<N, B>, N, B, false>,
    ) -> bool {
        let mut apply_success = true;
        let mut diff = diff.into_iter();
        // Manage the root
        let mut entry = self.entry_mut(&Path::new());
        let mut deleted = None;
        match diff.next() {
            Some(Traversal::Start((b, n))) => {
                if let Some(now) = n {
                    // New or change node
                    apply_success = insert(&mut entry, now);
                } else if b.is_some() {
                    // Remove node
                    // Deleted root prevents any further change
                    delete(&mut entry);
                    return diff.next().is_none();
                }
            }
            None => {
                // Empty diff
                return true;
            }
            Some(_) => {
                unreachable!("Tree iteration should always start with a Root node");
            }
        };

        for d in diff {
            entry.apply_move(&d);
            if let Some(d) = deleted {
                // Remove if at the same path level (the targetted node
                // will thus have changed)
                if d >= entry.path().len() {
                    deleted = None;
                }
            }
            let (b, n) = d.take();

            if let Some(now) = n {
                // New or change node
                if deleted.is_some() {
                    apply_success = false;
                } else if !insert(&mut entry, now) {
                    // Extend needed
                    apply_success = false;
                }
            } else if b.is_some() {
                // Remove node
                if deleted.is_none() {
                    deleted = Some(entry.path().len());
                    if entry.is_node() {
                        delete(&mut entry);
                    } else {
                        apply_success = false;
                    }
                } // else if a parent has been deleted, no further deleting is necessary
            }
        }
        apply_success
    }

    /// Combines two trees together following a given mode
    ///
    /// The mode specifies whether to :
    ///     - keep the nodes only present in the initial tree
    ///     - grow the tree with nodes only present in the other tree
    ///     - overwrite the nodes' data with the ones of the other tree
    ///
    /// # Examples
    /// ```
    /// use nb_tree::prelude::Tree;
    /// use nb_tree::tree::CombinationMode;
    /// let mut tree1: Tree<usize, String> = Tree::new();
    /// tree1.i("/", 0)
    ///     .i("/a", 1)
    ///     .i("/a/b", 2)
    ///     .i("/c", 3);
    ///
    /// let mut tree2: Tree<usize, String> = Tree::new();
    /// tree2.i("/", 10)
    ///      .i("/a", 11)
    ///      .i("/a/d", 7);
    ///
    /// tree1.combine(tree2, CombinationMode::Free{keep: true, grow: true, overwrite: true});
    /// let mut tree_res = Tree::new();
    /// tree_res.i("/", 10)
    ///         .i("/a", 11)
    ///         .i("/a/d", 7)
    ///         .i("/a/b", 2)
    ///         .i("/c", 3);
    ///
    /// assert_eq!(tree1, tree_res);
    /// ```
    pub fn combine(&mut self, tree: Tree<N, B>, mode: CombinationMode) -> bool {
        self.combine_with(tree, mode, |entry, now| entry.insert(now).is_some())
    }

    pub(crate) fn combine_with<'a>(
        &'a mut self,
        tree: Tree<N, B>,
        mode: CombinationMode,
        grow: InsertWith<&'a mut Tree<N, B>, N, B, false>,
    ) -> bool {
        let mut entry = self.root_entry_mut();
        let iter: IntoIter<N, B, TreeNode<N, B>> = IntoIter::new(tree);

        for step in iter {
            // check if above root node
            if entry.apply_move(&step).is_err() {
                // left the (sub)tree
                // return before iteration end
                return false;
            }
            if let Some(node) = entry.node_mut() {
                // remove ignored if not kept
                if !mode.keep() {
                    node.remove_child_subtrees(
                        node.children()
                            .into_iter()
                            .filter(|&c| step.data().children.contains_key(c))
                            .cloned()
                            .collect(),
                    );
                }
                if mode.overwrite() {
                    // overwrite
                    node.insert(step.take().value);
                }
            } else if mode.grow() {
                // grow
                grow(&mut entry, step.take().value);
            }
        }
        true
    }
}

type InsertWith<R, N, B, const BND: bool> = fn(&mut Entry<R, N, B, BND>, N) -> bool;
type DeleteWith<R, N, B, const BND: bool> = fn(&mut Entry<R, N, B, BND>) -> bool;

/// Description of how two trees will be combinedthe way the way
pub enum CombinationMode {
    /// Keeps and grows the tree, overwriting the data if the boolean is set to true
    Union(bool),
    /// Only keeps nodes common to both trees, overwriting the data if the boolean is set to true
    Intersection(bool),
    /// Specify manually the data to be kept and removed
    Free {
        /// Keep nodes only present in the first tree
        keep: bool,
        /// Keep nodes only present in the second tree
        grow: bool,
        /// Overwrites data in nodes common to both trees
        overwrite: bool,
    },
}

impl CombinationMode {
    pub fn keep(&self) -> bool {
        use CombinationMode::*;
        match self {
            Union(_) => true,
            Intersection(_) => false,
            Free { keep, .. } => *keep,
        }
    }
    pub fn grow(&self) -> bool {
        use CombinationMode::*;
        match self {
            Union(_) => true,
            Intersection(_) => false,
            Free { grow, .. } => *grow,
        }
    }
    pub fn overwrite(&self) -> bool {
        use CombinationMode::*;
        match self {
            Union(overwrite) => *overwrite,
            Intersection(overwrite) => *overwrite,
            Free { overwrite, .. } => *overwrite,
        }
    }
}

impl<N, B> Tree<N, B>
where
    B: Eq + Hash + Clone + Dbg,
{
    /// Chainable insertion
    /// Calls `insert` and returns a mutable reference to self
    /// # Panics
    /// Panics if the insertion fails
    pub fn i(&mut self, path: impl Into<Path<B>>, value: N) -> &mut Self {
        let ph: Path<B> = path.into();
        self.insert(&ph, value)
            .unwrap_or_else(|_| panic!("Could not insert into the tree at {:?}", &ph));
        self
    }
}

impl<N, B> Tree<N, B>
where
    N: Eq,
    B: Eq + Hash,
{
    /// # Warning
    /// It does not check for index validity.
    fn is_subtree_eq(&self, idx_s: usize, o: &Self, idx_o: usize) -> bool {
        let ns = &self.nodes[idx_s];
        let no = &o.nodes[idx_o];
        ns.value == no.value
            && ns.children.len() == no.children.len()
            && !ns.children.keys().any(|branch| {
                !self.is_subtree_eq(
                    *or_return!(ns.children.get(branch), false),
                    o,
                    *or_return!(no.children.get(branch), false),
                )
            })
    }
}
impl<N, B> Tree<N, B>
where
    N: Eq,
    B: Eq + Hash + Clone,
{
    /// Applies the differential to the tree if it is valid
    ///
    /// # Examples
    /// ```
    /// use nb_tree::prelude::Tree;
    /// let mut tree1: Tree<usize, String> = Tree::new();
    /// tree1.i("/", 0)
    ///     .i("/a", 1)
    ///     .i("/a/b", 2)
    ///     .i("/c", 3)
    ///     .i("/f", 4)
    ///     .i("/f/d", 5);
    /// let mut tree2: Tree<usize, String> = Tree::new();
    /// tree2
    ///     .i("/", 9)
    ///     .i("/a", 2)
    ///     .i("/a/b", 1)
    ///     .i("/c", 3)
    ///     .i("/c/d", 4)
    ///     .i("/c/d/e", 2);
    /// let mut diff = tree1.diff(&tree2);
    /// // taking back `tree1`, `tree2` and `diff` from the previous example
    /// let tree1_orig = tree1.clone();
    /// // Apply the differential between `tree1` and `tree2`
    /// tree1.apply(diff.clone()).unwrap();
    /// // They are both equal now
    /// assert_eq!(tree1, tree2, "Both trees are not equal");
    /// // Applying the reversed diff will restore tree1
    /// diff.rev();
    /// tree1.apply(diff).unwrap();
    /// assert_eq!(tree1, tree1_orig);
    /// ```
    pub fn apply(&mut self, diff: DiffTree<N, B>) -> Result<bool, DiffApplyError<B>> {
        // Check diff
        diff.is_applicable(self)?;

        // Apply diff
        Ok(self.force_apply(diff))
    }

    /// Applies a DiffNode at the given Path in the tree
    ///
    /// # Examples
    /// ```
    /// use nb_tree::prelude::Tree;
    /// let mut tree1: Tree<usize, String> = Tree::new();
    /// tree1.i("/", 0)
    ///     .i("/a", 1)
    ///     .i("/a/b", 2)
    ///     .i("/c", 3);
    /// let mut tree2 = tree1.clone();
    /// tree2.i("/a/b/d", 7);
    /// tree1.apply_diff("/a/b/d".into(), (None, Some(7)));
    /// assert_eq!(tree1, tree2);
    /// ```
    pub fn apply_diff(
        &mut self,
        path: Path<B>,
        diff: DiffNode<N>,
    ) -> Result<(), DiffApplyError<B>> {
        self.apply_diff_with(path, diff, |entry, v| {
            if entry.offshoot_len() <= 1 {
                entry.insert(v);
                Ok(())
            } else {
                Err(DiffApplyError::Other("Expected Parent".to_string()))
            }
        })
    }

    /// Applies the DiffNode at the given Path according to the given insertion function
    fn apply_diff_with(
        &mut self,
        path: Path<B>,
        diff: DiffNode<N>,
        insert: fn(&mut TreeMutEntry<N, B, TREEBOUND>, N) -> Result<(), DiffApplyError<B>>,
    ) -> Result<(), DiffApplyError<B>> {
        let mut entry = self.entry_mut(&path);
        if diff.0.is_some() {
            if entry.is_detached() {
                return Err(DiffApplyError::Expected(path));
            }
            if let Some(value) = diff.1 {
                // Change
                entry.insert(value);
                Ok(())
            } else {
                // Delete
                entry.remove_subtree();
                Ok(())
            }
        } else if let Some(value) = diff.1 {
            // New or change
            insert(&mut entry, value)
        } else {
            Ok(())
        }
    }

    /// Applies a DiffMap to the tree
    ///
    /// Returns true if all diffs have been applied, and false otherwise
    pub fn apply_map(&mut self, map: DiffMap<N, B>) -> bool {
        map.into_iter().fold(true, |mut res, (ph, diff)| {
            if self.apply_diff(ph, diff).is_err() {
                res = false;
            }
            res
        })
    }
}

#[cfg(test)]
mod tests {
    use std::collections::{HashMap, HashSet};

    use test_log::test;
    use tracing::{debug, trace};

    use crate::prelude::{iter::depth::Traversal, DiffTree, Tree};

    fn new_tree() -> Tree<usize, String> {
        let mut tree: Tree<usize, String> = Tree::new();
        tree.i("/", 0)
            .i("/a", 1)
            .i("/a/b", 2)
            .i("/c", 3)
            .i("/f", 4)
            .i("/f/d", 5);
        tree
    }

    #[test]
    fn index() {
        let mut tree1 = new_tree();
        assert_eq!(tree1[&"/".into()], 0);
        assert_eq!(tree1[&"/a".into()], 1);
        assert_eq!(tree1[&"/f/d".into()], 5);
        tree1.i("/z", 2);
        assert_eq!(tree1[&"/z".into()], 2);
    }

    #[test]
    #[should_panic]
    fn index_inexistent1() {
        let tree1 = new_tree();
        tree1[&"/w".into()];
    }

    #[test]
    #[should_panic]
    fn index_inexistent2() {
        let tree1 = new_tree();
        tree1[&"/f/d/z".into()];
    }

    #[test]
    #[should_panic]
    fn index_inexistent3() {
        let tree1 = new_tree();
        tree1[&"/f/a".into()];
    }

    #[test]
    fn eq_tree() {
        let tree1 = new_tree();
        // Same
        assert_eq!(tree1, new_tree());
        // Empty
        assert_eq!(Tree::<usize, usize>::new(), Tree::<usize, usize>::new());
        // Different branch
        let mut tree_branch = new_tree();
        tree_branch.i("/w", 7);
        assert_ne!(tree1, tree_branch);
        // Different value
        let mut tree_value = new_tree();
        tree_value.i("/a", 7);
        assert_ne!(tree1, tree_value);
        // One is empty
        assert_ne!(tree1, Tree::<usize, String>::new());
    }

    #[test]
    fn new() {
        let tree1: Tree<usize, String> = Tree::new();
        assert!(tree1.is_empty());
    }

    #[test]
    fn get_root() {
        let mut tree1: Tree<usize, String> = Tree::new();
        assert!(tree1.get_root().is_none());
        tree1.i("/", 5);
        assert_eq!(tree1.get_root(), Some(&5));
    }

    #[test]
    fn get_root_idx() {
        let mut tree1: Tree<usize, String> = Tree::new();
        assert!(tree1.get_root().is_none());
        tree1.i("/", 5);
        assert!(tree1.get_root().is_some());
    }

    #[test]
    fn insert_root() {
        let mut tree1: Tree<usize, String> = Tree::new();
        assert_eq!(tree1.insert_root(0), None);
        assert_eq!(tree1.len(), 1);
        assert_eq!(tree1.insert_root(1), Some(0));
        assert_eq!(tree1.insert_root(1), Some(1));
        assert_eq!(tree1.insert_root(2), Some(1));
        assert_eq!(tree1.insert_root(3), Some(2));
        tree1.clear();
        assert_eq!(tree1.insert_root(1), None);
        assert_eq!(tree1.insert_root(3), Some(1));
        tree1.i("/branch", 7);
        assert_eq!(tree1.len(), 2);
        assert_eq!(tree1.insert_root(5), Some(3));
        assert_eq!(tree1.len(), 2);
        assert_eq!(tree1.get_root(), Some(&5));
    }

    #[test]
    fn clear() {
        let mut tree1: Tree<usize, String> = new_tree();
        tree1.clear();
        assert_eq!(tree1, Tree::new());
        tree1.i("/", 1);
        let mut small_tree = Tree::new();
        small_tree.i("/", 1);
        assert_eq!(tree1, small_tree);
        tree1.clear();
        assert_eq!(tree1, Tree::new());
        tree1.i("/", 1);
        tree1.i("/i", 2);
        tree1.i("/v", 2);
        tree1.i("/c", 5);
        tree1.i("/c/d", 3);
        tree1.remove_subtree(&"/c".into()).unwrap();
        tree1.remove_subtree(&"/i".into()).unwrap();
        tree1.remove_subtree(&"/v".into()).unwrap();
        assert_eq!(tree1, small_tree);
        tree1.clear();
        assert_eq!(tree1, Tree::new());
    }

    #[test]
    fn is_empty() {
        let mut tree1: Tree<usize, String> = Tree::new();
        assert!(tree1.is_empty());
        tree1.i("/", 0);
        assert!(!tree1.is_empty());
        tree1.clear();
        assert!(tree1.is_empty());
        tree1.ix("/a", 1);
        assert!(!tree1.is_empty());
    }

    #[test]
    fn len() {
        let mut tree1: Tree<usize, String> = Tree::new();
        assert_eq!(tree1.len(), 0);
        tree1.i("/", 1);
        assert_eq!(tree1.len(), 1);
        tree1.i("/a", 5);
        assert_eq!(tree1.len(), 2);
        tree1.i("/", 3);
        assert_eq!(tree1.len(), 2);
        tree1.i("/a/c", 6);
        assert_eq!(tree1.len(), 3);
        tree1.i("/a/c/d", 4);
        assert_eq!(tree1.len(), 4);
        tree1.i("/b", 8);
        assert_eq!(tree1.len(), 5);
        tree1.i("/b/e", 9);
        assert_eq!(tree1.len(), 6);
        tree1.remove_subtree(&"/a".into()).unwrap();
        assert_eq!(tree1.len(), 3);
        tree1.ix("/a/c", 1);
        assert_eq!(tree1.len(), 5);
        tree1.insert_root(10);
        assert_eq!(tree1.len(), 5);
        tree1.clear();
        assert_eq!(tree1.len(), 0);
        tree1.insert_root(100);
        assert_eq!(tree1.len(), 1);
    }

    #[test]
    fn values() {
        let mut tree1 = new_tree();
        tree1.i("/z", 2);
        let values: HashSet<usize> = HashSet::from_iter([0, 1, 2, 3, 4, 5, 2].into_iter());
        let tree_values: HashSet<usize> = HashSet::from_iter(tree1.values().into_iter().cloned());
        assert_eq!(tree_values, values);
    }

    #[test]
    fn iter_iter_on() {
        let tree1 = new_tree();
        let mut iter = tree1.iter_on::<()>();

        match iter.next().expect("Root node expected") {
            Traversal::Start(()) => (),
            _ => panic!("Expected a Root node"),
        }
        match iter.next().expect("Root child Node expected") {
            Traversal::Step {
                up,
                branch,
                data: (),
            } => {
                assert_eq!(up, 0);
                // The node is at branch "a"
                assert!(["a", "c", "f"].contains(&branch.as_str()));
            }
            _ => panic!("Expected Root child node"),
        }

        let mut tree2: Tree<Option<usize>, String> = Tree::new();
        tree2
            .i("/", Some(0))
            .i("/a", Some(1))
            .i("/a/b", Some(2))
            .i("/c", Some(3))
            .i("/f", Some(4))
            .i("/f/d", Some(5));
        let mut entry = tree2.root_entry_mut();
        let mut iter = tree1.iter();
        if let Traversal::Start(root) = iter.next().unwrap() {
            assert_eq!(entry.value().unwrap(), &Some(*root));
            entry.insert(None);
        } else {
            panic!("Expected a Root node")
        }
        for item in iter {
            if let Traversal::Step { up, branch, data } = item {
                entry.move_up(up);
                entry.move_down_branch(branch.clone());
                assert_eq!(
                    entry
                        .value()
                        .expect("Node inexistent")
                        .expect("Node already visited"),
                    *data
                );
                entry.insert(None);
            } else {
                panic!("Expected a Node")
            }
        }
        assert!(!tree2.iter().any(|item| item.data().is_some()));
    }

    #[test]
    fn get_idx_path_idxs() {
        let mut tree1 = new_tree();
        let mut map = HashMap::new();
        map.insert("/", tree1.get_idx(&"/".into(), None).unwrap());
        map.insert("/a", tree1.get_idx(&"/a".into(), None).unwrap());
        map.insert("/a/b", tree1.get_idx(&"/a/b".into(), None).unwrap());
        map.insert("/c", tree1.get_idx(&"/c".into(), None).unwrap());
        map.insert("/f", tree1.get_idx(&"/f".into(), None).unwrap());
        map.insert("/f/d", tree1.get_idx(&"/f/d".into(), None).unwrap());
        let values: HashSet<usize> = HashSet::from_iter(map.values().copied());
        assert_eq!(values.len(), 6);
        assert_eq!(tree1.get_idx(&"/b".into(), None), Err(Some((map["/"], 0))));
        assert_eq!(tree1.get_idx(&"/w".into(), None), Err(Some((map["/"], 0))));
        assert_eq!(
            tree1.get_idx(&"/b/a".into(), None),
            Err(Some((map["/"], 0)))
        );
        assert_eq!(
            tree1.get_idx(&"/x/y/z".into(), None),
            Err(Some((map["/"], 0)))
        );
        assert_eq!(
            tree1.get_idx(&"/a/d".into(), None),
            Err(Some((map["/a"], 1)))
        );
        assert_eq!(
            tree1.get_idx(&"/a/b/x".into(), None),
            Err(Some((map["/a/b"], 2)))
        );

        assert_eq!(
            Tree::<usize, String>::new().get_idx(&"/a".into(), None),
            Err(None)
        );

        assert_eq!(
            tree1.get_path_idxs(&"/a/b".into()),
            Ok(vec![map["/"], map["/a"], map["/a/b"]])
        );
        assert_eq!(
            tree1.get_path_idxs(&"/f/d".into()),
            Ok(vec![map["/"], map["/f"], map["/f/d"]])
        );
        assert_eq!(
            tree1.get_path_idxs(&"/a/b/w".into()),
            Err(Some((vec![map["/"], map["/a"], map["/a/b"]], 2)))
        );
        assert_eq!(
            Tree::<usize, String>::new().get_path_idxs(&"/a/b/w".into()),
            Err(None)
        );
    }

    #[test]
    fn insert_at() {
        let mut tree1 = Tree::new();
        assert_eq!(tree1.len(), 0);
        tree1.insert_root(0);
        assert_eq!(tree1.len(), 1);
        let (_, a_idx) = tree1.insert_at(tree1.get_root_idx().unwrap(), "a".to_string(), 1);
        assert_eq!(tree1.len(), 2);
        tree1.insert_at(a_idx, "b".to_string(), 2);
        assert_eq!(tree1.len(), 3);
        tree1.insert_at(tree1.get_root_idx().unwrap(), "c".to_string(), 3);
        assert_eq!(tree1.len(), 4);
        let (_, f_idx) = tree1.insert_at(tree1.get_root_idx().unwrap(), "f".to_string(), 4);
        assert_eq!(tree1.len(), 5);
        tree1.insert_at(f_idx, "d".to_string(), 5);
        assert_eq!(tree1.len(), 6);
        assert_eq!(tree1, new_tree());
        tree1.insert_at(tree1.get_root_idx().unwrap(), "a".to_string(), 1);
        assert_eq!(tree1.len(), 6);
        assert_eq!(tree1, new_tree());
    }

    #[test]
    #[should_panic]
    fn insert_at_panic_parent() {
        new_tree().insert_at(7, "P".to_string(), 2);
    }

    #[test]
    fn remove_subtree_at() {
        let mut tree1 = new_tree();
        tree1.remove_subtree_at(tree1.get_root_idx().unwrap(), "a".to_string());
        assert_eq!(tree1.len(), 4);
        tree1.remove_subtree_at(tree1.get_root_idx().unwrap(), "c".to_string());
        assert_eq!(tree1.len(), 3);
        tree1.remove_subtree_at(tree1.get_idx(&"/f".into(), None).unwrap(), "d".to_string());
        assert_eq!(tree1.len(), 2);
        tree1.remove_subtree_at(tree1.get_root_idx().unwrap(), "f".to_string());
        assert_eq!(tree1.len(), 1);
    }

    #[test]
    fn get() {
        let mut tree1: Tree<usize, String> = Tree::new();
        // Can't get any node from an empty node
        assert_eq!(tree1.get(&"/a/b/w".into()), Err(None));
        tree1 = new_tree();
        // Get a reference to the node data at "/a"
        assert_eq!(tree1.get(&"/a".into()), Ok(&1));
        assert_eq!(tree1.get(&"/a/b".into()), Ok(&2));
        // "/a/b/w" is out of the tree, "/a/b" being the last node in the tree of the path
        assert_eq!(tree1.get(&"/a/b/w".into()), Err(Some("/a/b".into())));
        assert_eq!(tree1.get(&"/b/a".into()), Err(Some("/".into())));
    }

    #[test]
    fn get_mut() {
        let mut tree1: Tree<usize, String> = Tree::new();
        // Can't get any node from an empty node
        assert_eq!(tree1.get_mut(&"/a/b/w".into()), Err(None));
        tree1 = new_tree();
        // Get a reference to the node data at "/a"
        assert_eq!(tree1.get_mut(&"/a".into()), Ok(&mut 1));
        assert_eq!(tree1.get_mut(&"/a/b".into()), Ok(&mut 2));
        // "/a/b/w" is out of the tree, "/a/b" being the last node in the tree of the path
        assert_eq!(tree1.get_mut(&"/a/b/w".into()), Err(Some("/a/b".into())));
        assert_eq!(tree1.get_mut(&"/b/a".into()), Err(Some("/".into())));
    }

    #[test]
    fn root_entry() {
        let mut tree1: Tree<usize, String> = Tree::new();
        let entry = tree1.root_entry();
        assert!(!entry.is_node());
        tree1.i("/", 7).i("/c1", 1);
        let mut entry = tree1.root_entry();
        assert_eq!(entry.value(), Some(&7));
        entry.move_down_branch("c1".into());
        assert_eq!(entry.value(), Some(&1));
        tree1.clear();
        let entry = tree1.root_entry();
        assert!(!entry.is_node());
    }

    #[test]
    fn root_entry_mut() {
        let mut tree1: Tree<usize, String> = Tree::new();
        let mut entry = tree1.root_entry_mut();
        assert!(!entry.is_node());
        assert_eq!(entry.or_insert(5), &mut 5);
        entry.move_down_branch("c1".into());
        assert_eq!(entry.or_insert(1), &mut 1);
        entry.move_up(1);
        assert!(entry.is_node());
    }

    #[test]
    fn entry() {
        let mut tree1: Tree<usize, String> = Tree::new();
        tree1.i("/", 0).i("/a", 1).i("/a/b", 2).i("/c", 3);
        let mut entry = tree1.entry(&"/a/b".into());
        assert_eq!(entry.value(), Some(&2));
        entry.move_up(1);
        assert_eq!(entry.value(), Some(&1));
        entry.move_up(1);
        assert_eq!(entry.value(), Some(&0));
    }

    #[test]
    fn entry_mut() {
        let mut tree1: Tree<usize, String> = Tree::new();
        tree1.i("/", 0).i("/a", 1).i("/a/b", 2).i("/c", 3);
        let mut entry = tree1.entry_mut(&"/a/b".into());
        assert_eq!(entry.or_insert(4), &mut 2);
        entry.move_up(2);
        entry.move_down_branch("f".into());
        assert_eq!(entry.or_insert(4), &mut 4);
        entry.move_down_branch("e".into());
        assert_eq!(entry.or_insert(5), &mut 5);
        assert_eq!(tree1, new_tree());
    }

    /*
    #[test]
    fn get_entry() {
    }*/

    #[test]
    fn insert() {
        let mut tree1: Tree<_, String> = Tree::new();
        assert_eq!(tree1.insert(&"/".into(), 0), Ok(None));
        assert_eq!(tree1.insert(&"/a".into(), 2), Ok(None));
        assert_eq!(tree1.insert(&"/a".into(), 1), Ok(Some(2)));
        assert_eq!(tree1.insert(&"/a/b/c".into(), 2), Err(Some("/a".into())));
        assert_eq!(tree1.insert(&"/a/b".into(), 2), Ok(None));
        assert_eq!(tree1.insert(&"/c".into(), 3), Ok(None));
        assert_eq!(tree1.insert(&"/f".into(), 4), Ok(None));
        assert_eq!(tree1.insert(&"/f/e".into(), 5), Ok(None));
        assert_eq!(tree1, new_tree());
        tree1.clear();
        assert_eq!(tree1.len(), 0);
        assert_eq!(tree1.insert(&"/a/b/c".into(), 2), Err(None));
        assert_eq!(tree1.insert(&"/".into(), 7), Ok(None));
        assert_eq!(tree1.len(), 1);
        assert_eq!(tree1[&"/".into()], 7);
    }

    #[test]
    fn remove_subtree() {
        let mut tree1: Tree<usize, String> = Tree::new();
        tree1.insert(&"/".into(), 0).unwrap();
        tree1.insert(&"/a".into(), 1).unwrap();
        tree1.insert(&"/a".into(), 2).unwrap();
        tree1.insert(&"/b".into(), 3).unwrap();
        let mut tree2 = tree1.clone();

        // Add a branch to tree2
        tree2.insert(&"/c".into(), 4).unwrap();
        tree2.insert(&"/c/d".into(), 5).unwrap();

        // Remove the branch
        tree2.remove_subtree(&"/c".into()).unwrap();
        assert_eq!(tree1, tree2);
    }

    #[test]
    fn force_apply() {
        let mut tree1 = new_tree();
        let mut diff = Tree::new();
        let mut tree_res = Tree::new();

        diff.i("/", (Some(0), Some(9)))
            .i("/a", (None, None))
            .i("/a/b", (Some(2), Some(8)))
            .i("/f", (Some(4), None))
            .i("/f/g", (Some(1000), Some(14))) // wrong initial value and change below deletion
            .i("/c", (None, Some(12))) // wrong initial value
            .i("/c/e", (None, Some(11)));
        assert!(!tree1.force_apply(diff.clone()));

        tree_res
            .i("/", 9)
            .i("/a", 1)
            .i("/a/b", 8)
            .i("/c", 12)
            .i("/c/e", 11);

        assert_eq!(tree1, tree_res, "Both trees are not equal");
    }

    #[test]
    fn combine() {}

    #[test]
    fn i() {}

    #[test]
    fn is_subtree_eq() {}

    #[test]
    fn apply() {
        let mut tree1 = new_tree();
        let mut tree_diff = DiffTree::new();
        tree_diff
            .i("/", (None, None))
            .i("/a", (Some(1), None))
            .i("/c", (Some(3), Some(10)))
            .i("/c/f", (None, Some(11)))
            .i("/c/f/g", (None, Some(12)));

        let mut tree_res: Tree<usize, String> = Tree::new();
        tree_res
            .i("/", 0)
            .i("/c", 10)
            .i("/c/f", 11)
            .i("/c/f/g", 12)
            .i("/f", 4)
            .i("/f/d", 5);
        // Apply the differential between `tree1` and `tree2`
        tree1.apply(tree_diff).unwrap();
        // They are both equal now
        assert_eq!(tree1, tree_res, "Both trees are not equal");
    }

    #[test]
    fn apply_diff() {}

    #[test]
    fn apply_diff_with() {}

    #[test]
    fn apply_map() {}
}

/*
pub fn move_subtree(
    &mut self,
    from: Path<B>,
    to: Path<B>,
    destination: Option<&mut Tree<N, B>>,
) -> Result<(), Path<B>> {
    let path_idxs = self
        .get_path_idxs(path)
        .map_err(|(_, idx)| path.path_to(idx))?;

    //remove children
    self.move_subtree(path_idxs.pop().unwrap());
    let mut attr = path.pop_leaf();

    //remove empty parent nodes
    while !path_idxs.is_empty() && self.nodes[path_idxs.last()].children.len() == 1 {
        self.nodes.remove(path_idxs.pop().unwrap());
        attr = path.pop_leaf();
    }

    //remove child link of parent
    if !path_idxs.is_empty() {
        self.nodes[path_idxs].children.remove(attr);
    }
    Ok(())
}*/
//fn move_subtree(&mut self, from: NodeIDX, to: NodeIDX, tree: &mut Tree<N, B>) {
//      tree.nodes[to].children.insert(attr, tree.nodes.len());
//      tree.nodes.push(TreeNode {})
//      self.remove_subtree(idx, );