willow-data-model 0.7.0

The core datatypes of Willow, an eventually consistent data store with improved distributed deletion.
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
//! Functionality around Willow [Paths](https://willowprotocol.org/specs/data-model/index.html#Path).
//!
//! The central type of this module is the [`Path`] struct, which represents a single willow Path. [`Paths`](Path) are *immutable*, which means any operation that would traditionally mutate paths (for example, appending a new component) returns a new, independent value instead.
//!
//! The [`Path`] struct is generic over three const generic parameters, corresponding to the Willow parameters which limit the size of paths:
//!
//! - the `MCL` parameter gives the ([max\_component\_length](https://willowprotocol.org/specs/data-model/index.html#max_component_length)),
//! - the `MCC` parameter gives the ([max\_component\_count](https://willowprotocol.org/specs/data-model/index.html#max_component_count)), and
//! - the `MPL` parameter gives the ([max\_path\_length](https://willowprotocol.org/specs/data-model/index.html#max_path_length)).
//!
//! All (safely created) [`Paths`](Path)respect those parameters. The functions in this module return [`PathErrors`](PathError) or [`PathFromComponentsErrors`](PathFromComponentsError) when those invariants would be violated.
//!
//! The type-level docs of [`Path`] list all the ways in which you can build up paths dynamically.
//!
//! The [`Path`] struct provides methods for checking various properties of paths: from simple properties ("[how many components does this have](Path::component_count)") to various comparisons ("[is this path a prefix of some other](Path::is_prefix_of)"), the methods should have you covered.
//!
//! Because [path prefixes](https://willowprotocol.org/specs/data-model/index.html#path_prefix) play such a [central role for deletion](https://willowprotocol.org/specs/data-model/index.html#prefix_pruning) in Willow, the functionality around prefixes is optimised. [Creating a prefix](Path::create_prefix) or even iterating over [all prefixes](Path::all_prefixes) performs no memory allocations.
//!
//! The [`Component`] type represents individual path [Components](https://willowprotocol.org/specs/data-model/index.html#Component). This type is a thin wrapper around `[u8]` (enforcing a maximal length of `MCL` bytes); like `[u8]` it must always be used as part of a pointer type — for example, `&Component<MCL>`. Alternatively, the [`OwnedComponent`] type can be used by itself — keeping an [`OwnedComponent`] alive will also keep around the heap allocation for the full [`Path`] from which it was constructed, though. Generally speaking, the more lightweight [`Component`] should be preferred over [`OwnedComponent`] where possible.

#[cfg(feature = "dev")]
use arbitrary::{Arbitrary, Error as ArbitraryError, Unstructured, size_hint::and_all};
use derive_more::{Display, Error};
use order_theory::{
    GreatestElement, LeastElement, LowerSemilattice, PredecessorExceptForLeast,
    SuccessorExceptForGreatest, TryPredecessor, TrySuccessor, UpperSemilattice,
};

// The `Path` struct is tested in `fuzz/path.rs`, `fuzz/path2.rs`, `fuzz/path3.rs`, `fuzz/path3.rs` by comparing against a non-optimised reference implementation.
// Further, the `successor` and `greater_but_not_prefixed` methods of that reference implementation are tested in `fuzz/path_successor.rs` and friends, and `fuzz/path_successor_of_prefix.rs` and friends.

use core::cmp::Ordering;
use core::fmt::Debug;
use core::hash::Hash;
use core::mem::size_of;
use core::ops::RangeBounds;
use core::{convert::AsRef, fmt};

use bytes::{BufMut, Bytes, BytesMut};

mod builder;
pub use builder::PathBuilder;

mod representation;
use representation::Representation;

mod component;
pub use component::*;

mod codec;
pub use codec::*;

pub mod private;

/// An error arising from trying to construct an invalid [`Path`] from valid [`Component`]s.
///
/// #### Examples
///
/// ```
/// use willow_data_model::prelude::*;
/// assert_eq!(
///     Path::<4, 4, 2>::from_component(Component::new(b"oops").unwrap()),
///     Err(PathFromComponentsError::PathTooLong),
/// );
/// assert_eq!(
///     Path::<4, 1, 9>::from_components(&[
///         Component::new(b"").unwrap(),
///         Component::new(b"").unwrap()
///     ]),
///     Err(PathFromComponentsError::TooManyComponents),
/// );
/// ```
#[derive(Debug, Display, Error, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PathFromComponentsError {
    /// The [`Path`]'s total length in bytes would have been greater than the [max\_path\_length](https://willowprotocol.org/specs/data-model/index.html#max_path_length).
    #[display("total path length exceeded maximum")]
    PathTooLong,
    /// The [`Path`] would have had more [`Component`] than the [max\_component\_count](https://willowprotocol.org/specs/data-model/index.html#max_component_count).
    #[display("number of components exceeded maximum")]
    TooManyComponents,
}

/// An error arising from trying to construct an invalid [`Path`].
///
/// #### Examples
///
/// ```
/// use willow_data_model::prelude::*;
/// assert_eq!(Path::<4, 4, 2>::from_slice(b"oops"), Err(PathError::PathTooLong));
/// assert_eq!(Path::<2, 2, 9>::from_slices(&[b"", b"", b""]), Err(PathError::TooManyComponents));
/// assert_eq!(Path::<4, 4, 9>::from_slice(b"oopsie"), Err(PathError::ComponentTooLong));
/// ```
#[derive(Debug, Display, Error, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PathError {
    /// The [`Path`]'s total length in bytes would have been greater than the [max\_path\_length](https://willowprotocol.org/specs/data-model/index.html#max_path_length).
    #[display("total path length exceeded maximum")]
    PathTooLong,
    /// The [`Path`] would have had more [`Component`] than the [max\_component\_count](https://willowprotocol.org/specs/data-model/index.html#max_component_count).
    #[display("number of components exceeded maximum")]
    TooManyComponents,
    /// The [`Path`] would have contained a [`Component`] of length greater than the [max\_component\_length](https://willowprotocol.org/specs/data-model/index.html#max_component_length)
    #[display("length of a component exceeded maximum")]
    ComponentTooLong,
}

impl From<PathFromComponentsError> for PathError {
    fn from(value: PathFromComponentsError) -> Self {
        match value {
            PathFromComponentsError::PathTooLong => Self::PathTooLong,
            PathFromComponentsError::TooManyComponents => Self::TooManyComponents,
        }
    }
}

impl From<InvalidComponentError> for PathError {
    fn from(_value: InvalidComponentError) -> Self {
        Self::ComponentTooLong
    }
}

/// An immutable Willow [Path](https://willowprotocol.org/specs/data-model/index.html#Path). Thread-safe, cheap to clone, cheap to take prefixes of, expensive to append to (linear time complexity).
///
/// A Willow Path is any sequence of bytestrings — called [Components](https://willowprotocol.org/specs/data-model/index.html#Component) — fulfilling certain constraints:
///
/// - each [`Component`] has a length of at most `MCL` ([max\_component\_length](https://willowprotocol.org/specs/data-model/index.html#max_component_length)),
/// - each [`Path`] has at most `MCC` ([max\_component\_count](https://willowprotocol.org/specs/data-model/index.html#max_component_count)) components, and
/// - the total size in bytes of all [`Component`]s is at most `MPL` ([max\_path\_length](https://willowprotocol.org/specs/data-model/index.html#max_path_length)).
///
/// This type statically enforces these invariants for all (safely) created instances.
///
/// Because appending [`Component`]s takes time linear in the length of the full [`Path`], you should not build up [`Path`]s this way. Instead, use [`Path::from_components`], [`Path::from_slices`], [`Path::from_components_iter`], [`Path::from_slices_iter`], or a [`PathBuilder`].
///
/// ```
/// use willow_data_model::prelude::*;
/// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
///
/// assert_eq!(p.component_count(), 2);
/// assert_eq!(p.component(1), Some(Component::new(b"ho")?));
/// assert_eq!(p.total_length(), 4);
/// assert!(p.is_prefixed_by(&Path::from_slice(b"hi")?));
/// assert_eq!(
///     p.longest_common_prefix(&Path::from_slices(&[b"hi", b"he"])?),
///     Path::from_slice(b"hi")?
/// );
/// # Ok::<(), PathError>(())
/// ```
#[derive(Clone)]
pub struct Path<const MCL: usize, const MCC: usize, const MPL: usize> {
    /// The data of the underlying path.
    data: Bytes,
    /// The first component of the `data` to consider for this particular path. Must be less than or equal to the total number of components in `data`.
    /// This field, with `component_count`, enables cheap slicing and suffix creation by cloning the heap data.
    first_component: usize,
    /// Number of components of the `data` to consider for this particular path (starting from the `first_component`). Must be less than or equal to the total number of components minus the `first_component` offset.
    /// This field enables cheap prefix creation by cloning the heap data (which is reference counted) and adjusting the `component_count`.
    component_count: usize,
}

/// The default [`Path`] is the empty [`Path`].
impl<const MCL: usize, const MCC: usize, const MPL: usize> Default for Path<MCL, MCC, MPL> {
    /// Returns an empty [`Path`].
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// assert_eq!(Path::<4, 4, 4>::default().component_count(), 0);
    /// assert_eq!(Path::<4, 4, 4>::default(), Path::<4, 4, 4>::new());
    /// ```
    fn default() -> Self {
        Self::new()
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> Path<MCL, MCC, MPL> {
    /// Returns an empty [`Path`], i.e., a [`Path`] of zero [`Component`]s.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// assert_eq!(Path::<4, 4, 4>::new().component_count(), 0);
    /// assert_eq!(Path::<4, 4, 4>::new(), Path::<4, 4, 4>::default());
    /// ```
    pub fn new() -> Self {
        PathBuilder::new(0, 0)
            .expect("empty path is legal for every choice of of MCL, MCC, and MPL")
            .build()
    }

    /// Creates a singleton [`Path`], consisting of exactly one [`Component`].
    ///
    /// Copies the bytes of the [`Component`] into an owned allocation on the heap.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n)`, where `n` is the length of the [`Component`]. Performs a single allocation of `O(n)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p = Path::<4, 4, 4>::from_component(Component::new(b"hi!")?)?;
    /// assert_eq!(p.component_count(), 1);
    ///
    /// assert_eq!(
    ///     Path::<4, 4, 2>::from_component(Component::new(b"hi!")?),
    ///     Err(PathFromComponentsError::PathTooLong),
    /// );
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn from_component(comp: &Component<MCL>) -> Result<Self, PathFromComponentsError> {
        let mut builder = PathBuilder::new(comp.as_ref().len(), 1)?;
        builder.append_component(comp);
        Ok(builder.build())
    }

    /// Creates a singleton [`Path`], consisting of exactly one [`Component`], from a raw slice of bytes.
    ///
    /// Copies the bytes into an owned allocation on the heap.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n)`, where `n` is the length of the [`Component`]. Performs a single allocation of `O(n)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p = Path::<4, 4, 4>::from_slice(b"hi!")?;
    /// assert_eq!(p.component_count(), 1);
    ///
    /// assert_eq!(
    ///     Path::<4, 4, 4>::from_slice(b"too_long_for_single_component"),
    ///     Err(PathError::ComponentTooLong),
    /// );
    /// assert_eq!(
    ///     Path::<4, 3, 1>::from_slice(b"nope"),
    ///     Err(PathError::PathTooLong),
    /// );
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn from_slice(comp: &[u8]) -> Result<Self, PathError> {
        Ok(Self::from_component(Component::new(comp)?)?)
    }

    /// Creates a [`Path`] from a slice of [`Component`]s.
    ///
    /// Copies the bytes of the [`Component`]s into an owned allocation on the heap.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the created [`Path`] in bytes, and `m` is the number of its [`Component`]s. Performs a single allocation of `O(n + m)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let components: Vec<&Component<4>> = vec![
    ///     &Component::new(b"hi")?,
    ///     &Component::new(b"!")?,
    /// ];
    ///
    /// assert!(Path::<4, 4, 4>::from_components(&components[..]).is_ok());
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn from_components(
        components: &[&Component<MCL>],
    ) -> Result<Self, PathFromComponentsError> {
        let mut total_length = 0;
        for comp in components {
            total_length += comp.as_ref().len();
        }

        Self::from_components_iter(total_length, &mut components.iter().cloned())
    }

    /// Create a new [`Path`] from a slice of byte slices.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the created [`Path`] in bytes, and `m` is the number of its [`Component`]s. Performs a single allocation of `O(n + m)` bytes.
    ///
    /// # Example
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// // Ok
    /// let path = Path::<12, 3, 30>::from_slices(&[b"alfie", b"notes"]).unwrap();
    ///
    /// // Err
    /// let result1 = Path::<12, 3, 30>::from_slices(&[b"themaxpath", b"lengthis30", b"thisislonger"]);
    /// assert_eq!(result1, Err(PathError::PathTooLong));
    ///
    /// // Err
    /// let result2 = Path::<12, 3, 30>::from_slices(&[b"too", b"many", b"components", b"error"]);
    /// assert_eq!(result2, Err(PathError::TooManyComponents));
    ///
    /// // Err
    /// let result3 = Path::<12, 3, 30>::from_slices(&[b"overencumbered"]);
    /// assert_eq!(result3, Err(PathError::ComponentTooLong));
    /// ```
    pub fn from_slices(slices: &[&[u8]]) -> Result<Self, PathError> {
        let total_length = slices.iter().map(|it| it.as_ref().len()).sum();
        let mut builder = PathBuilder::new(total_length, slices.len())?;

        for component_slice in slices {
            builder.append_slice(component_slice.as_ref())?;
        }

        Ok(builder.build())
    }

    /// Creates a [`Path`] of known total length from an [`ExactSizeIterator`] of [`Component`]s.
    ///
    /// Copies the bytes of the [`Component`]s into an owned allocation on the heap.
    ///
    /// Panics if the claimed `total_length` does not match the sum of the lengths of all the [`Component`]s.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the created [`Path`] in bytes, and `m` is the number of its [`Component`]s. Performs a single allocation of `O(n + m)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let components: Vec<&Component<4>> = vec![
    ///     &Component::new(b"hi")?,
    ///     &Component::new(b"!")?,
    /// ];
    ///
    /// assert!(Path::<4, 4, 4>::from_components_iter(3, &mut components.into_iter()).is_ok());
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn from_components_iter<'c, I>(
        total_length: usize,
        iter: &mut I,
    ) -> Result<Self, PathFromComponentsError>
    where
        I: ExactSizeIterator<Item = &'c Component<MCL>>,
    {
        let mut builder = PathBuilder::new(total_length, iter.len())?;

        for component in iter {
            builder.append_component(component);
        }

        Ok(builder.build())
    }

    /// Creates a [`Path`] of known total length from an [`ExactSizeIterator`] of byte slices.
    ///
    /// Copies the bytes of the [`Component`]s into an owned allocation on the heap.
    ///
    /// Panics if the claimed `total_length` does not match the sum of the lengths of all the [`Component`]s.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the created [`Path`] in bytes, and `m` is the number of its [`Component`]s. Performs a single allocation of `O(n + m)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let components: Vec<&[u8]> = vec![b"hi", b"!"];
    /// assert!(Path::<4, 4, 4>::from_slices_iter(3, &mut components.into_iter()).is_ok());
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn from_slices_iter<'a, I>(total_length: usize, iter: &mut I) -> Result<Self, PathError>
    where
        I: ExactSizeIterator<Item = &'a [u8]>,
    {
        let mut builder = PathBuilder::new(total_length, iter.len())?;

        for slice in iter {
            builder.append_slice(slice.as_ref())?;
        }

        Ok(builder.build())
    }

    /// Creates a new [`Path`] by appending a [`Component`] to `&self`.
    ///
    /// Creates a fully separate copy of the new data on the heap; which includes cloning all data in `&self`. To efficiently construct [`Path`]s, use [`Path::from_components`], [`Path::from_slices`], [`Path::from_components_iter`], [`Path::from_slices_iter`], or a [`PathBuilder`].
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the resulting [`Path`] in bytes, and `m` is the number of its [`Component`]s. Performs a single allocation of `O(n + m)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p0: Path<4, 4, 4> = Path::new();
    /// let p1 = p0.append_component(Component::new(b"hi")?)?;
    /// let p2 = p1.append_component(Component::new(b"!")?)?;
    /// assert_eq!(
    ///     p2.append_component(Component::new(b"no!")?),
    ///     Err(PathFromComponentsError::PathTooLong),
    /// );
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn append_component(&self, comp: &Component<MCL>) -> Result<Self, PathFromComponentsError> {
        let mut builder = PathBuilder::new(
            self.total_length() + comp.as_ref().len(),
            self.component_count() + 1,
        )?;

        for component in self.components() {
            builder.append_component(component);
        }
        builder.append_component(comp);

        Ok(builder.build())
    }

    /// Creates a new [`Path`] by appending a [`Component`] to `&self`.
    ///
    /// Creates a fully separate copy of the new data on the heap; which includes cloning all data in `&self`. To efficiently construct [`Path`]s, use [`Path::from_components`], [`Path::from_slices`], [`Path::from_components_iter`], [`Path::from_slices_iter`], or a [`PathBuilder`].
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the resulting [`Path`] in bytes, and `m` is the number of its [`Component`]s. Performs a single allocation of `O(n + m)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p0: Path<4, 4, 4> = Path::new();
    /// let p1 = p0.append_slice(b"hi")?;
    /// let p2 = p1.append_slice(b"!")?;
    /// assert_eq!(
    ///     p2.append_slice(b"no!"),
    ///     Err(PathError::PathTooLong),
    /// );
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn append_slice(&self, comp: &[u8]) -> Result<Self, PathError> {
        Ok(self.append_component(Component::new(comp)?)?)
    }

    /// Creates a new [`Path`] by appending a slice of [`Component`]s to `&self`.
    ///
    /// Creates a fully separate copy of the new data on the heap; which includes cloning all data in `&self`. To efficiently construct [`Path`]s, use [`Path::from_components`], [`Path::from_slices`], [`Path::from_components_iter`], [`Path::from_slices_iter`], or a [`PathBuilder`].
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the resulting [`Path`] in bytes, and `m` is the number of its [`Component`]s. Performs a single allocation of `O(n + m)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p0: Path<4, 4, 4> = Path::new();
    /// let p1 = p0.append_components(&[Component::new(b"hi")?, Component::new(b"!")?])?;
    /// assert_eq!(
    ///     p1.append_components(&[Component::new(b"no!")?]),
    ///     Err(PathFromComponentsError::PathTooLong),
    /// );
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn append_components(
        &self,
        components: &[&Component<MCL>],
    ) -> Result<Self, PathFromComponentsError> {
        let mut total_length = self.total_length();
        for comp in components {
            total_length += comp.as_ref().len();
        }

        let mut builder = PathBuilder::new_from_prefix(
            total_length,
            self.component_count() + components.len(),
            self,
            self.component_count(),
        )?;

        for additional_component in components {
            builder.append_component(*additional_component);
        }

        Ok(builder.build())
    }

    /// Creates a new [`Path`] by appending a slice of [`Component`]s to `&self`.
    ///
    /// Creates a fully separate copy of the new data on the heap; which includes cloning all data in `&self`. To efficiently construct [`Path`]s, use [`Path::from_components`], [`Path::from_slices`], [`Path::from_components_iter`], [`Path::from_slices_iter`], or a [`PathBuilder`].
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the resulting [`Path`] in bytes, and `m` is the number of its [`Component`]s. Performs a single allocation of `O(n + m)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p0: Path<4, 4, 4> = Path::new();
    /// let p1 = p0.append_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(
    ///     p1.append_slices(&[b"no!"]),
    ///     Err(PathError::PathTooLong),
    /// );
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn append_slices(&self, components: &[&[u8]]) -> Result<Self, PathError> {
        let mut total_length = self.total_length();
        for comp in components {
            total_length += comp.as_ref().len();
        }

        let mut builder = PathBuilder::new_from_prefix(
            total_length,
            self.component_count() + components.len(),
            self,
            self.component_count(),
        )?;

        for additional_component in components {
            builder.append_slice(additional_component.as_ref())?;
        }

        Ok(builder.build())
    }

    /// Creates a new [`Path`] by appending another [`Path`] to `&self`.
    ///
    /// Creates a fully separate copy of the new data on the heap; which includes cloning all data in `&self` and in `&other`.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the resulting [`Path`] in bytes, and `m` is the number of its [`Component`]s. Performs a single allocation of `O(n + m)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p0: Path<4, 4, 4> = Path::new();
    /// let p1 = p0.append_path(&Path::from_slices(&[b"hi", b"ho"])?)?;
    /// assert_eq!(
    ///     p1.append_path(&Path::from_slice(b"no!")?),
    ///     Err(PathFromComponentsError::PathTooLong),
    /// );
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn append_path(
        &self,
        other: &Path<MCL, MCC, MPL>,
    ) -> Result<Self, PathFromComponentsError> {
        let total_length = self.total_length() + other.total_length();

        let mut builder = PathBuilder::new_from_prefix(
            total_length,
            self.component_count() + other.component_count(),
            self,
            self.component_count(),
        )?;

        for additional_component in other.components() {
            builder.append_component(additional_component);
        }

        Ok(builder.build())
    }

    /// Returns the least [`Path`] which is strictly greater (lexicographically) than `self` and which is not [prefixed by](https://willowprotocol.org/specs/data-model/index.html#path_prefix) `self`; or [`None`] if no such [`Path`] exists.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the [`Path`] in bytes, and `m` is the number of [`Component`]s. Performs a single allocation of `O(n + m)` bytes.
    pub fn greater_but_not_prefixed(&self) -> Option<Self> {
        // We iterate through all components in reverse order. For each component, we check whether we can replace it by another cmponent that is strictly greater but not prefixed by the original component. If that is possible, we do replace it with the least such component and drop all later components. If that is impossible, we try again with the previous component. If this impossible for all components, then this function returns `None`.

        for (i, component) in self.components().enumerate().rev() {
            // If it is possible to append a zero byte to a component, then doing so yields its successor.

            let prefix_length = Representation::sum_of_lengths_for_component(
                self.data.as_ref(),
                i + self.first_component,
            ) - match self.first_component {
                0 => 0,
                offset => {
                    Representation::sum_of_lengths_for_component(self.data.as_ref(), offset - 1)
                }
            };

            if component.len() < MCL && prefix_length < MPL {
                let mut buf = clone_prefix_and_lengthen_final_component(
                    &self.data,
                    i,
                    1,
                    self.first_component,
                );
                buf.put_u8(0);

                return Some(Path {
                    data: buf.freeze(),
                    component_count: i + 1,
                    first_component: 0,
                });
            }

            // Next, we check whether the i-th component can be changed into the least component that is greater but not prefixed by the original. If so, do that and cut off all later components.
            let mut next_component_length = None;
            for (j, comp_byte) in component.iter().enumerate().rev() {
                if *comp_byte < 255 {
                    next_component_length = Some(j + 1);
                    break;
                }
            }

            if let Some(next_component_length) = next_component_length {
                // Yay, we can replace the i-th comopnent and then we are done.

                let mut buf = clone_prefix_and_lengthen_final_component(
                    &self.data,
                    i,
                    0,
                    self.first_component,
                );
                let length_of_prefix = Representation::sum_of_lengths_for_component(&buf, i);

                // Update the length of the final component.
                buf_set_final_component_length(
                    buf.as_mut(),
                    i,
                    length_of_prefix - (component.len() - next_component_length),
                );

                // Increment the byte at position `next_component_length` of the final component.
                let offset = Representation::start_offset_of_component(buf.as_ref(), i)
                    + next_component_length
                    - 1;
                let byte = buf.as_ref()[offset]; // guaranteed < 255...
                buf.as_mut()[offset] = byte + 1; // ... hence no overflow here.

                return Some(Path {
                    data: buf.freeze(),
                    component_count: i + 1,
                    first_component: 0,
                });
            }
        }

        None
    }

    /// Returns the number of [`Component`]s in `&self`.
    ///
    /// Guaranteed to be at most `MCC`.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(p.component_count(), 2);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn component_count(&self) -> usize {
        self.component_count
    }

    /// Returns whether `&self` has zero [`Component`]s.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// assert_eq!(Path::<4, 4, 4>::new().is_empty(), true);
    ///
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(p.is_empty(), false);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn is_empty(&self) -> bool {
        self.component_count() == 0
    }

    /// Returns the sum of the lengths of all [`Component`]s in `&self`.
    ///
    /// Guaranteed to be at most `MCC`.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(p.total_length(), 4);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn total_length(&self) -> usize {
        self.total_length_of_prefix(self.component_count())
    }

    /// Returns the sum of the lengths of the first `i` [`Component`]s in `&self`; panics if `i >= self.component_count()`. More efficient than `path.create_prefix(i).path_length()`.
    ///
    /// Guaranteed to be at most `MCC`.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(p.total_length_of_prefix(0), 0);
    /// assert_eq!(p.total_length_of_prefix(1), 2);
    /// assert_eq!(p.total_length_of_prefix(2), 4);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn total_length_of_prefix(&self, i: usize) -> usize {
        let size_offset = Representation::total_length(&self.data, self.first_component);

        Representation::total_length(&self.data, i + self.first_component) - size_offset
    }

    /// Tests whether `&self` is a [prefix](https://willowprotocol.org/specs/data-model/index.html#path_prefix) of the given [`Path`].
    /// [`Path`]s are always a prefix of themselves, and the empty [`Path`] is a prefix of every [`Path`].
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the longer [`Path`] in bytes, and `m` is the greatest number of [`Component`]s.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert!(Path::new().is_prefix_of(&p));
    /// assert!(Path::from_slice(b"hi")?.is_prefix_of(&p));
    /// assert!(Path::from_slices(&[b"hi", b"ho"])?.is_prefix_of(&p));
    /// assert!(!Path::from_slices(&[b"hi", b"gh"])?.is_prefix_of(&p));
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn is_prefix_of(&self, other: &Self) -> bool {
        self.prefix_cmp(other)
            .map(|ord| ord.is_le())
            .unwrap_or(false)
    }

    /// Tests whether `&self` is [prefixed by](https://willowprotocol.org/specs/data-model/index.html#path_prefix) the given [`Path`].
    /// [`Path`]s are always prefixed by themselves, and by the empty [`Path`].
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the longer [`Path`] in bytes, and `m` is the greatest number of [`Component`]s.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert!(p.is_prefixed_by(&Path::new()));
    /// assert!(p.is_prefixed_by(&Path::from_slice(b"hi")?));
    /// assert!(p.is_prefixed_by(&Path::from_slices(&[b"hi", b"ho"])?));
    /// assert!(!p.is_prefixed_by(&Path::from_slices(&[b"hi", b"gh"])?));
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn is_prefixed_by(&self, other: &Self) -> bool {
        other.is_prefix_of(self)
    }

    /// Tests whether `&self` is [related](https://willowprotocol.org/specs/data-model/index.html#path_related) to the given [`Path`], that is, whether either one is a [prefix](https://willowprotocol.org/specs/data-model/index.html#path_prefix) of the other.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the longer [`Path`] in bytes, and `m` is the greatest number of [`Component`]s.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slice(b"hi")?;
    /// assert!(p.is_related_to(&Path::new()));
    /// assert!(p.is_related_to(&Path::from_slice(b"hi")?));
    /// assert!(p.is_related_to(&Path::from_slices(&[b"hi", b"ho"])?));
    /// assert!(!p.is_related_to(&Path::from_slices(&[b"no"])?));
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn is_related_to(&self, other: &Self) -> bool {
        self.prefix_cmp(other).is_some()
    }

    /// Returns the [`Ordering`] describing the prefix relation between `self` and `other`.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the longer [`Path`] in bytes, and `m` is the greatest number of [`Component`]s.
    ///
    /// #### Examples
    ///
    /// ```
    /// use core::cmp::Ordering;
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slice(b"hi")?;
    /// assert_eq!(p.prefix_cmp(&Path::new()), Some(Ordering::Greater));
    /// assert_eq!(p.prefix_cmp(&Path::from_slice(b"hi")?), Some(Ordering::Equal));
    /// assert_eq!(p.prefix_cmp(&Path::from_slices(&[b"hi", b"ho"])?), Some(Ordering::Less));
    /// assert_eq!(p.prefix_cmp(&Path::from_slice(b"no")?), None);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn prefix_cmp(&self, other: &Self) -> Option<Ordering> {
        for (comp_a, comp_b) in self.components().zip(other.components()) {
            if comp_a != comp_b {
                return None;
            }
        }

        self.component_count().partial_cmp(&other.component_count())
    }

    /// Returns the `i`-th [`Component`] of `&self`.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(p.component(0), Some(Component::new(b"hi")?));
    /// assert_eq!(p.component(1), Some(Component::new(b"ho")?));
    /// assert_eq!(p.component(2), None);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn component(&self, i: usize) -> Option<&Component<MCL>> {
        if i < self.component_count {
            Some(Representation::component(
                &self.data,
                i + self.first_component,
            ))
        } else {
            None
        }
    }

    /// Returns the `i`-th [`Component`] of `&self`, without checking whether `i < self.component_count()`.
    ///
    /// #### Safety
    ///
    /// Undefined behaviour if `i >= self.component_count()`.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(unsafe { p.component_unchecked(0) }, Component::new(b"hi")?);
    /// assert_eq!(unsafe { p.component_unchecked(1) }, Component::new(b"ho")?);
    /// # Ok::<(), PathError>(())
    /// ```
    pub unsafe fn component_unchecked(&self, i: usize) -> &Component<MCL> {
        Representation::component(&self.data, i + self.first_component)
    }

    /// Returns an [owned handle](OwnedComponent) to the `i`-th component of `&self`.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(p.owned_component(0), Some(OwnedComponent::new(b"hi")?));
    /// assert_eq!(p.owned_component(1), Some(OwnedComponent::new(b"ho")?));
    /// assert_eq!(p.owned_component(2), None);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn owned_component(&self, i: usize) -> Option<OwnedComponent<MCL>> {
        if i < self.component_count {
            let start =
                Representation::start_offset_of_component(&self.data, i + self.first_component);
            let end = Representation::end_offset_of_component(&self.data, i + self.first_component);
            Some(OwnedComponent(self.data.slice(start..end)))
        } else {
            None
        }
    }

    /// Returns an [owned handle](OwnedComponent) to the `i`-th component of `&self`, without checking whether `i < self.component_count()`.
    ///
    /// #### Safety
    ///
    /// Undefined behaviour if `i >= self.component_count()`.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(p.owned_component(0), Some(OwnedComponent::new(b"hi")?));
    /// assert_eq!(p.owned_component(1), Some(OwnedComponent::new(b"ho")?));
    /// assert_eq!(p.owned_component(2), None);
    /// # Ok::<(), PathError>(())
    /// ```
    pub unsafe fn owned_component_unchecked(&self, i: usize) -> OwnedComponent<MCL> {
        debug_assert!(
            i < self.component_count(),
            "Component index {} is out of range for path {} with {} components",
            i,
            self,
            self.component_count()
        );
        let start = Representation::start_offset_of_component(&self.data, i + self.first_component);
        let end = Representation::end_offset_of_component(&self.data, i + self.first_component);
        OwnedComponent(self.data.slice(start..end))
    }

    /// Creates an iterator over the [`Component`]s of `&self`.
    ///
    /// Stepping the iterator takes `O(1)` time and performs no memory allocations.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// let mut comps = p.components();
    /// assert_eq!(comps.next(), Some(Component::new(b"hi")?));
    /// assert_eq!(comps.next(), Some(Component::new(b"ho")?));
    /// assert_eq!(comps.next(), None);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn components(
        &self,
    ) -> impl DoubleEndedIterator<Item = &Component<MCL>> + ExactSizeIterator<Item = &Component<MCL>>
    {
        self.suffix_components(0)
    }

    /// Creates an iterator over the [`Component`]s of `&self`, starting at the `i`-th [`Component`]. If `i` is greater than or equal to the number of [`Component`]s, the iterator yields zero items.
    ///
    /// Stepping the iterator takes `O(1)` time and performs no memory allocations.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// let mut comps = p.suffix_components(1);
    /// assert_eq!(comps.next(), Some(Component::new(b"ho")?));
    /// assert_eq!(comps.next(), None);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn suffix_components(
        &'_ self,
        i: usize,
    ) -> impl DoubleEndedIterator<Item = &Component<MCL>> + ExactSizeIterator<Item = &Component<MCL>>
    {
        (i..self.component_count()).map(|i| {
            self.component(i).unwrap() // Only `None` if `i >= self.component_count()`
        })
    }

    /// Creates an iterator over [owned handles](OwnedComponent) to the components of `&self`.
    ///
    /// Stepping the iterator takes `O(1)` time and performs no memory allocations.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// let mut comps = p.owned_components();
    /// assert_eq!(comps.next(), Some(OwnedComponent::new(b"hi")?));
    /// assert_eq!(comps.next(), Some(OwnedComponent::new(b"ho")?));
    /// assert_eq!(comps.next(), None);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn owned_components(
        &self,
    ) -> impl DoubleEndedIterator<Item = OwnedComponent<MCL>>
    + ExactSizeIterator<Item = OwnedComponent<MCL>>
    + '_ {
        self.suffix_owned_components(0)
    }

    /// Creates an iterator over [owned handles](OwnedComponent) to the components of `&self`, starting at the `i`-th [`OwnedComponent`]. If `i` is greater than or equal to the number of [`OwnedComponent`], the iterator yields zero items.
    ///
    /// Stepping the iterator takes `O(1)` time and performs no memory allocations.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// let mut comps = p.suffix_owned_components(1);
    /// assert_eq!(comps.next(), Some(OwnedComponent::new(b"ho")?));
    /// assert_eq!(comps.next(), None);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn suffix_owned_components(
        &self,
        i: usize,
    ) -> impl DoubleEndedIterator<Item = OwnedComponent<MCL>>
    + ExactSizeIterator<Item = OwnedComponent<MCL>>
    + '_ {
        (i..self.component_count()).map(|i| {
            self.owned_component(i).unwrap() // Only `None` if `i >= self.component_count()`
        })
    }

    /// Creates a new [`Path`] that consists of the first `component_count` [`Component`]s of `&self`. More efficient than creating a new [`Path`] from scratch.
    ///
    /// Returns [`None`] if `component_count` is greater than `self.get_component_count()`.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(p.create_prefix(0), Some(Path::new()));
    /// assert_eq!(p.create_prefix(1), Some(Path::from_slice(b"hi")?));
    /// assert_eq!(p.create_prefix(2), Some(Path::from_slices(&[b"hi", b"ho"])?));
    /// assert_eq!(p.create_prefix(3), None);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn create_prefix(&self, component_count: usize) -> Option<Self> {
        if component_count > self.component_count() {
            None
        } else {
            Some(unsafe { self.create_prefix_unchecked(component_count) })
        }
    }

    /// Creates a new [`Path`] that consists of the first `component_count` [`Component`]s of `&self`. More efficient than creating a new [`Path`] from scratch.
    ///
    /// #### Safety
    ///
    /// Undefined behaviour if `component_count` is greater than `self.component_count()`. May manifest directly, or at any later
    /// function invocation that operates on the resulting [`Path`].
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(unsafe { p.create_prefix_unchecked(0) }, Path::new());
    /// assert_eq!(unsafe { p.create_prefix_unchecked(1) }, Path::from_slice(b"hi")?);
    /// assert_eq!(unsafe { p.create_prefix_unchecked(2) }, Path::from_slices(&[b"hi", b"ho"])?);
    /// # Ok::<(), PathError>(())
    /// ```
    pub unsafe fn create_prefix_unchecked(&self, component_count: usize) -> Self {
        // #### Safety
        //
        // Safety guarantees for RangeTo for create_slice_unchecked are the same as those for component_count to create_prefix_unchecked
        unsafe { self.create_slice_unchecked(..component_count) }
    }

    /// Creates an iterator over all [prefixes](https://willowprotocol.org/specs/data-model/index.html#path_prefix) of `&self` (including the empty [`Path`] and `&self` itself).
    ///
    /// Stepping the iterator takes `O(1)` time and performs no memory allocations.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)`, performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// let mut prefixes = p.all_prefixes();
    /// assert_eq!(prefixes.next(), Some(Path::new()));
    /// assert_eq!(prefixes.next(), Some(Path::from_slice(b"hi")?));
    /// assert_eq!(prefixes.next(), Some(Path::from_slices(&[b"hi", b"ho"])?));
    /// assert_eq!(prefixes.next(), None);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn all_prefixes(&self) -> impl DoubleEndedIterator<Item = Self> + '_ {
        (0..=self.component_count()).map(|i| {
            unsafe {
                self.create_prefix_unchecked(i) // safe to call for i <= self.component_count()
            }
        })
    }

    /// Returns the longest common [prefix](https://willowprotocol.org/specs/data-model/index.html#path_prefix) of `&self` and the given [`Path`].
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the shorter of the two [`Path`]s, and `m` is the lesser number of [`Component`]s. Performs a single allocation of `O(n + m)` bytes to create the return value.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p1: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// let p2: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"he"])?;
    /// assert_eq!(p1.longest_common_prefix(&p2), Path::from_slice(b"hi")?);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn longest_common_prefix(&self, other: &Self) -> Self {
        let mut lcp_len = 0;

        for (comp_a, comp_b) in self.components().zip(other.components()) {
            if comp_a != comp_b {
                break;
            }

            lcp_len += 1
        }

        self.create_prefix(lcp_len).unwrap() // zip ensures that lcp_len <= self.component_count()
    }

    /// Creates a [`Path`] whose [`Component`]s are those of `&self` indexed by the given `range`, without checking that those components exist.
    ///
    /// #### Safety
    ///
    /// Undefined behaviour if either the start or the end of `range` are explicitly greater than `self.component_count()`, or if `range` is decreasing.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)` and performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(unsafe{p.create_slice_unchecked(..)}, p);
    /// assert_eq!(unsafe{p.create_slice_unchecked(..1)}, Path::from_slices(&[b"hi"])?);
    /// assert_eq!(unsafe{p.create_slice_unchecked(1..)}, Path::from_slices(&[b"ho"])?);
    /// assert_eq!(unsafe{p.create_slice_unchecked(1..1)}, Path::new());
    /// # Ok::<(), PathError>(())
    /// ```
    pub unsafe fn create_slice_unchecked<R>(&self, range: R) -> Self
    where
        R: RangeBounds<usize>,
    {
        let n = match range.start_bound() {
            core::ops::Bound::Included(&n) => n,
            core::ops::Bound::Excluded(&n) => n + 1,
            core::ops::Bound::Unbounded => 0,
        };

        let m = match range.end_bound() {
            core::ops::Bound::Included(&m) => m + 1,
            core::ops::Bound::Excluded(&m) => m,
            core::ops::Bound::Unbounded => self.component_count(),
        };

        debug_assert!(
            m.max(n) <= self.component_count,
            "Path slice indexes component {}, which is out of range for path {} with {} components",
            m.max(n),
            self,
            self.component_count()
        );
        debug_assert!(
            m >= n,
            "Path slice end index {m} is before path slice start index {n}"
        );
        Path {
            data: self.data.clone(),
            first_component: n + self.first_component,
            component_count: m - n,
        }
    }

    /// Creates a [`Path`] whose [`Component`]s are those of `&self` indexed by the given `range`.
    /// Returns [`None`] if either the start or end of `range` are explicitly greater than `&self.component_count()` or if `range` is decreasing.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)` and performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(p.create_slice(..), Some(p.clone()));
    /// assert_eq!(p.create_slice(1..2), Some(Path::from_slices(&[b"ho"])?));
    /// assert_eq!(p.create_slice(1..3), None);
    /// assert_eq!(p.create_slice(2..1), None);
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn create_slice<R>(&self, range: R) -> Option<Self>
    where
        R: RangeBounds<usize>,
    {
        let n = match range.start_bound() {
            core::ops::Bound::Included(&n) => Some(n),
            core::ops::Bound::Excluded(&n) => n.checked_add(1),
            core::ops::Bound::Unbounded => Some(0),
        };

        let m = match range.end_bound() {
            core::ops::Bound::Included(&m) => m.checked_add(1),
            core::ops::Bound::Excluded(&m) => Some(m),
            core::ops::Bound::Unbounded => Some(self.component_count),
        };

        let (n, m) = match (n, m) {
            (Some(n), Some(m)) if n > m || m > self.component_count || n > self.component_count => {
                return None;
            }
            (Some(n), Some(m)) => (n, m),
            _ => return None,
        };

        Some(Path {
            data: self.data.clone(),
            first_component: n + self.first_component,
            component_count: m - n,
        })
    }

    /// Creates a [`Path`] whose [`Component`]s are the last `component_count` components of `&self`, without checking that `&self` has at least `component_count` components.
    ///
    /// #### Safety
    ///
    /// Undefined behaviour if `component_count > self.component_count()`.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)` and performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// let p: Path<4, 4, 4> = Path::from_slices(&[b"a", b"b", b"c", b"d"])?;
    /// assert_eq!(unsafe{p.create_suffix_unchecked(2)}, Path::from_slices(&[b"c", b"d"])?);
    /// assert_eq!(unsafe{p.create_suffix_unchecked(0)}, Path::new());
    /// # Ok::<(), PathError>(())
    /// ```
    pub unsafe fn create_suffix_unchecked(&self, component_count: usize) -> Self {
        debug_assert!(
            component_count <= self.component_count(),
            "Tried to create a suffix from {} components of path {} which has only {} components",
            component_count,
            self,
            self.component_count()
        );

        // #### Safety
        //
        // Safety guarantees for RangeFrom argument to create_slice_unchecked are the same as those for component_count in create_suffix_unchecked
        unsafe { self.create_slice_unchecked(self.component_count() - component_count..) }
    }

    /// Creates a [`Path`] whose [`Component`]s are the last `component_count` components of `&self`.
    /// Returns [`None`] if `&self` does not have at least `component_count` components.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(1)` and performs no allocations.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    ///
    /// let p: Path<4,4,4> = Path::from_slices(&[b"hi", b"ho"])?;
    /// assert_eq!(p.create_suffix(0), Some(Path::new()));
    /// assert_eq!(p.create_suffix(1), Some(Path::from_slices(&[b"ho"])?));
    /// assert_eq!(p.create_suffix(2), Some(Path::from_slices(&[b"hi", b"ho"])?));
    /// assert_eq!(p.create_suffix(3), None);
    ///
    /// # Ok::<(), PathError>(())
    /// ```
    pub fn create_suffix(&self, component_count: usize) -> Option<Self> {
        if component_count > self.component_count() {
            None
        } else {
            unsafe { Some(self.create_suffix_unchecked(component_count)) }
        }
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> PartialEq for Path<MCL, MCC, MPL> {
    fn eq(&self, other: &Self) -> bool {
        if self.component_count != other.component_count {
            false
        } else {
            self.components().eq(other.components())
        }
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> Eq for Path<MCL, MCC, MPL> {}

impl<const MCL: usize, const MCC: usize, const MPL: usize> Hash for Path<MCL, MCC, MPL> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.component_count.hash(state);

        for comp in self.components() {
            comp.hash(state);
        }
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> PartialOrd for Path<MCL, MCC, MPL> {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Compares paths lexicographically, since that is the path ordering that the Willow spec always uses.
impl<const MCL: usize, const MCC: usize, const MPL: usize> Ord for Path<MCL, MCC, MPL> {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.components().cmp(other.components())
    }
}

/// The least path is the empty path.
impl<const MCL: usize, const MCC: usize, const MPL: usize> LeastElement for Path<MCL, MCC, MPL> {
    /// Returns the least path.
    fn least() -> Self {
        Self::new()
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> GreatestElement for Path<MCL, MCC, MPL> {
    /// Creates the greatest possible [`Path`] (with respect to lexicographical ordering, which is also the [`Ord`] implementation of [`Path`]).
    ///
    /// #### Complexity
    ///
    /// Runs in `O(MCC + MPL)`. Performs a single allocation of `O(MPL)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// use order_theory::GreatestElement;
    ///
    /// let p = Path::<4, 4, 4>::greatest();
    /// assert_eq!(p.component_count(), 4);
    /// assert_eq!(p.component(0).unwrap().as_ref(), &[255, 255, 255, 255]);
    /// assert!(p.component(1).unwrap().is_empty());
    /// assert!(p.component(2).unwrap().is_empty());
    /// assert!(p.component(3).unwrap().is_empty());
    /// ```
    fn greatest() -> Self {
        let max_comp_bytes = [255; MCL];

        let mut num_comps = if MCL == 0 {
            MCC
        } else {
            core::cmp::min(MCC, MPL.div_ceil(MCL))
        };
        let mut path_builder = PathBuilder::new(MPL, MCC).unwrap();

        let mut len_so_far = 0;

        for _ in 0..num_comps {
            let comp_len = core::cmp::min(MCL, MPL - len_so_far);
            let component = unsafe { Component::new_unchecked(&max_comp_bytes[..comp_len]) };
            path_builder.append_component(component);

            len_so_far += comp_len;
        }

        while num_comps < MCC {
            path_builder.append_component(Component::new_empty());
            num_comps += 1;
        }

        path_builder.build()
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> LowerSemilattice
    for Path<MCL, MCC, MPL>
{
    fn greatest_lower_bound(&self, other: &Self) -> Self {
        if self <= other {
            self.clone()
        } else {
            other.clone()
        }
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> UpperSemilattice
    for Path<MCL, MCC, MPL>
{
    fn least_upper_bound(&self, other: &Self) -> Self {
        if self >= other {
            self.clone()
        } else {
            other.clone()
        }
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> TryPredecessor for Path<MCL, MCC, MPL> {
    fn try_predecessor(&self) -> Option<Self> {
        if self.component_count() == 0 {
            // We are the empty path, so we do not have a predecessor.
            None
        } else {
            let final_component = self.component(self.component_count() - 1).unwrap();

            // We have a component. Our predecessor depends only on the final component, with several options depending on the final byte:
            if final_component.as_bytes().is_empty() {
                // If the final component is empty, we simply remove it to obtain the predecessor.
                Some(unsafe { self.create_prefix_unchecked(self.component_count() - 1) })
            } else {
                let final_byte = final_component.as_bytes()[final_component.len() - 1];

                // The final component was non-empty. We now decrement the final component, and then fill up the path with maximally many maximal components.

                // Create a builder for the new component, which will be of maximal length, maximal component count, and starting with `self` sans the final_component.
                let predecessor_total_len = core::cmp::min(
                    MPL,
                    self.total_length_of_prefix(self.component_count() - 1) // unchanged components
                        + if final_byte == 0 { final_component.len() - 1 } else { MCL } // replacement of self.final_comp
                        + ((MCC - self.component_count()) * MCL), // padding 255 bytes
                );
                let mut builder = PathBuilder::new_from_prefix(
                    predecessor_total_len,
                    MCC,
                    self,
                    self.component_count() - 1,
                )
                .unwrap();

                // The meaning of "decrement the final component" depends on the final byte.
                // In either case we do not actually construct a coponent, but merely apend the decremented component to the builder.
                if final_byte == 0 {
                    // If the final byte is zero, we simply remove it from the component.
                    builder.append_component(unsafe {
                        Component::<MCL>::new_unchecked(
                            &final_component[..final_component.len() - 1],
                        )
                    });
                } else {
                    // If the final byte is not zero, we decrement the final byte by one and then append 255 bytes until hitting the MCL or the MPL, whichever happens first..

                    // The way we actually implement this is by creating a mutable array of MCL many 255 bytes, overwriting the start of it, and then feeding the correct prefix into the builder.
                    let mut arr = [255; MCL];

                    arr[0..final_component.len()].copy_from_slice(final_component);
                    arr[final_component.len() - 1] = final_byte - 1;

                    builder.append_component(unsafe {
                        Component::<MCL>::new_unchecked(
                            &arr[..core::cmp::min(
                                MCL,
                                MPL - self.total_length_of_prefix(self.component_count() - 1),
                            )],
                        )
                    });
                }

                while builder.component_count() < MCC {
                    // We have decremented the final component. Now we append maximal components while we can.
                    let comp_len = core::cmp::min(MCL, MPL - builder.total_length());

                    let arr = [255; MCL];
                    builder.append_component(unsafe {
                        Component::<MCL>::new_unchecked(&arr[..comp_len])
                    });
                }

                Some(builder.build())
            }
        }
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> PredecessorExceptForLeast
    for Path<MCL, MCC, MPL>
{
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> TrySuccessor for Path<MCL, MCC, MPL> {
    /// Returns the least path which is strictly greater than `self`, or return `None` if `self` is the greatest possible path.
    ///
    /// #### Complexity
    ///
    /// Runs in `O(n + m)`, where `n` is the total length of the [`Path`] in bytes, and `m` is the number of [`Component`]s. Performs a single allocation of `O(n + m)` bytes.
    ///
    /// #### Examples
    ///
    /// ```
    /// use willow_data_model::prelude::*;
    /// use order_theory::TrySuccessor;
    ///
    /// let p: Path<3, 3, 3> = Path::from_slices(&[
    ///     [255].as_slice(),
    ///     [9, 255].as_slice(),
    ///     [].as_slice(),
    /// ])?;
    /// assert_eq!(p.try_successor(), Some(Path::from_slices(&[
    ///     [255].as_slice(),
    ///     [10].as_slice(),
    /// ])?));
    /// # Ok::<(), PathError>(())
    /// ```
    fn try_successor(&self) -> Option<Self> {
        // If it is possible to append an empty component, then doing so yields the successor.
        if let Ok(path) = self.append_component(Component::new_empty()) {
            return Some(path);
        }

        // Otherwise, we try incrementing the final component. If that fails,
        // we try to increment the second-to-final component, and so on.
        // All components that come after the incremented component are discarded.
        // If *no* component can be incremented, `self` is the maximal path and we return `None`.

        for (i, component) in self.components().enumerate().rev() {
            // It would be nice to call a `try_increment_component` function, but in order to avoid
            // memory allocations, we write some lower-level but more efficient code.

            // If it is possible to append a zero byte to a component, then doing so yields its successor.
            let mut length_offset = 0;
            if self.first_component > 0 {
                length_offset = Representation::sum_of_lengths_for_component(
                    self.data.as_ref(),
                    self.first_component - 1,
                );
            }
            let length_offset = length_offset;
            if component.len() < MCL
                && Representation::sum_of_lengths_for_component(
                    self.data.as_ref(),
                    i + self.first_component,
                ) - length_offset
                    < MPL
            {
                // We now know how to construct the path successor of `self`:
                // Take the first `i` components (this *excludes* the current `component`),
                // then append `component` with an additional zero byte at the end.
                let mut buf = clone_prefix_and_lengthen_final_component(
                    &self.data,
                    i,
                    1,
                    self.first_component,
                );
                buf.put_u8(0);

                return Some(Path {
                    data: buf.freeze(),
                    component_count: i + 1,
                    first_component: 0,
                });
            }

            // We **cannot** append a zero byte, so instead we check whether we can treat the component as a fixed-width integer and increment it. The only failure case is if that component consists of 255-bytes only.
            let can_increment = !component.iter().all(|byte| *byte == 255);

            // If we cannot increment, we go to the next iteration of the loop. But if we can, we can create a copy of the
            // prefix on the first `i + 1` components, and mutate its backing memory in-place.
            if can_increment {
                let mut buf = clone_prefix_and_lengthen_final_component(
                    &self.data,
                    i,
                    0,
                    self.first_component,
                );

                let start_component_offset =
                    Representation::start_offset_of_component(buf.as_ref(), i);
                let end_component_offset = Representation::end_offset_of_component(buf.as_ref(), i);

                let overflows = fixed_width_increment_reporting_overflows(
                    &mut buf.as_mut()[start_component_offset..end_component_offset],
                );
                let new_sum_of_lengths =
                    Representation::sum_of_lengths_for_component(buf.as_ref(), i) - overflows;
                buf_set_final_component_length(buf.as_mut(), i, new_sum_of_lengths);

                return Some(Path {
                    data: buf.freeze(),
                    component_count: i + 1,
                    first_component: 0,
                });
            }
        }

        // Failed to increment any component, so `self` is the maximal path.
        None
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> SuccessorExceptForGreatest
    for Path<MCL, MCC, MPL>
{
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> Debug for Path<MCL, MCC, MPL> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Path").field(&FmtHelper(self)).finish()
    }
}

struct FmtHelper<'a, const MCL: usize, const MCC: usize, const MPL: usize>(&'a Path<MCL, MCC, MPL>);

impl<'a, const MCL: usize, const MCC: usize, const MPL: usize> fmt::Debug
    for FmtHelper<'a, MCL, MCC, MPL>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.0.is_empty() {
            write!(f, "<empty>")
        } else {
            for comp in self.0.components() {
                write!(f, "/")?;
                write!(f, "{:?}", ComponentFmtHelper::new(&comp, false))?;
            }

            Ok(())
        }
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize> fmt::Display for Path<MCL, MCC, MPL> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:?}", FmtHelper(self))
    }
}

#[cfg(feature = "dev")]
impl<'a, const MCL: usize, const MCC: usize, const MPL: usize> Arbitrary<'a>
    for Path<MCL, MCC, MPL>
{
    fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self, ArbitraryError> {
        let mut total_length_in_bytes: usize = Arbitrary::arbitrary(u)?;
        total_length_in_bytes %= MPL + 1;

        let data: Box<[u8]> = Arbitrary::arbitrary(u)?;
        total_length_in_bytes = core::cmp::min(total_length_in_bytes, data.len());

        let mut num_components: usize = Arbitrary::arbitrary(u)?;
        num_components %= MCC + 1;

        if num_components == 0 {
            total_length_in_bytes = 0;
        }

        let mut builder = PathBuilder::new(total_length_in_bytes, num_components).unwrap();

        let mut length_total_so_far = 0;
        for i in 0..num_components {
            // Determine the length of the i-th component: randomly within some constraints for all but the final one. The final length is chosen to match the total_length_in_bytes.
            let length_of_ith_component = if i + 1 == num_components {
                if total_length_in_bytes - length_total_so_far > MCL {
                    return Err(ArbitraryError::IncorrectFormat);
                } else {
                    total_length_in_bytes - length_total_so_far
                }
            } else {
                // Any non-final component can take on a random length, ...
                let mut component_length: usize = Arbitrary::arbitrary(u)?;
                // ... except it must be at most the MCL, and...
                component_length %= MCL + 1;
                // ... the total length of all components must not exceed the total path length.
                component_length = core::cmp::min(
                    component_length,
                    total_length_in_bytes - length_total_so_far,
                );
                component_length
            };

            builder.append_component(
                Component::new(
                    &data[length_total_so_far..length_total_so_far + length_of_ith_component],
                )
                .unwrap(),
            );
            length_total_so_far += length_of_ith_component;
        }

        Ok(builder.build())
    }

    #[inline]
    fn size_hint(depth: usize) -> (usize, Option<usize>) {
        (
            and_all(&[
                usize::size_hint(depth),
                usize::size_hint(depth),
                Box::<[u8]>::size_hint(depth),
            ])
            .0,
            None,
        )
    }
}

/////////////////////////////////////////////////////////////////////
// Helpers for efficiently creating successors.                    //
// Efficiency warrants some low-level fiddling around here, sorry. //
/////////////////////////////////////////////////////////////////////

/// Creates a new BufMut that stores the heap encoding of the first i components of `original`, but increasing the length of the final component by `extra_capacity`. No data to fill that extra capacity is written into the buffer.
fn clone_prefix_and_lengthen_final_component(
    representation: &[u8],
    i: usize,
    extra_capacity: usize,
    first_component_offset: usize,
) -> BytesMut {
    let mut successor_path_length =
        Representation::sum_of_lengths_for_component(representation, i + first_component_offset)
            + extra_capacity;

    let mut size_offset = 0;

    if first_component_offset > 0 {
        size_offset = Representation::sum_of_lengths_for_component(
            representation,
            first_component_offset - 1,
        );
        successor_path_length -= size_offset;
    }

    let size_offset = size_offset;
    let successor_path_length = successor_path_length;

    let buf_capacity = size_of::<usize>() * (i + 2) + successor_path_length;
    let mut buf = BytesMut::with_capacity(buf_capacity);

    // Write the length of the successor path as the first usize.
    buf.extend_from_slice(&(i + 1).to_ne_bytes());

    // Next, copy the total path lengths for the first i prefixes.
    if first_component_offset > 0 {
        // We have to adjust each path length if we are working with an offset first component
        for component_offset in first_component_offset..first_component_offset + i + 1 {
            buf.extend_from_slice(
                &(Representation::sum_of_lengths_for_component(representation, component_offset)
                    - size_offset)
                    .to_ne_bytes(),
            );
        }
    } else {
        // Otherwise we can copy all the path length bytes more cheaply
        buf.extend_from_slice(
            &representation[Representation::start_offset_of_sum_of_lengths_for_component(0)
                ..Representation::start_offset_of_sum_of_lengths_for_component(i + 1)],
        );
    }

    // Now, write the length of the final component, which is one greater than before.
    buf_set_final_component_length(buf.as_mut(), i, successor_path_length);

    // Finally, copy the raw bytes of the first i+1 components.
    buf.extend_from_slice(
        &representation[Representation::start_offset_of_component(
            representation,
            first_component_offset,
        )
            ..Representation::start_offset_of_component(
                representation,
                first_component_offset + i + 1,
            )],
    );

    buf
}

// In a buffer that stores a path on the heap, set the sum of all component lengths for the i-th component, which must be the final component.
fn buf_set_final_component_length(buf: &mut [u8], i: usize, new_sum_of_lengths: usize) {
    let comp_len_start = Representation::start_offset_of_sum_of_lengths_for_component(i);
    let comp_len_end = comp_len_start + size_of::<usize>();
    buf[comp_len_start..comp_len_end].copy_from_slice(&new_sum_of_lengths.to_ne_bytes()[..]);
}

// Overflows to all zeroes if all bytes are 255. Returns the number of overflowing bytes.
fn fixed_width_increment_reporting_overflows(buf: &mut [u8]) -> usize {
    let mut overflows = 0;
    for byte_ref in buf.iter_mut().rev() {
        if *byte_ref == 255 {
            *byte_ref = 0;
            overflows += 1;
        } else {
            *byte_ref += 1;
            return overflows;
        }
    }

    overflows
}

#[test]
fn greatest() {
    let path1 = Path::<3, 3, 6>::greatest();

    assert!(path1.try_successor().is_none());

    let path2 = Path::<4, 4, 16>::greatest();
    assert!(path2.try_successor().is_none());

    let path3 = Path::<0, 4, 0>::greatest();
    assert!(path3.try_successor().is_none());

    let path4 = Path::<4, 2, 6>::greatest();
    assert!(path4.try_successor().is_none())
}