any-rope 1.2.5

A fast and robust arbitrary rope for Rust. Based on Ropey.
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
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
use std::{cmp::Ordering, iter::FromIterator, ops::RangeBounds, sync::Arc};

use crate::{
    end_bound_to_num,
    iter::{Chunks, Iter},
    measures_from_range,
    rope_builder::RopeBuilder,
    slice::RopeSlice,
    slice_utils::{end_measure_to_index, index_to_measure, start_measure_to_index},
    start_bound_to_num,
    tree::{max_children, max_len, min_len, BranchChildren, Node, SliceInfo},
    Error, FallibleOrd, Measurable, MeasureRange, Result,
};

/// A rope of elements that are [`Measurable`].
///
/// The time complexity of nearly all edit and query operations on [`Rope<M>`]
/// are worst-case `O(log N)` in the length of the rope. [`Rope<M>`] is designed
/// to work efficiently even for huge (in the gigabytes) arrays of
/// [`M`][Measurable].
///
/// In the examples below, a struct called [`Width`][crate::Width] will be used
/// in order to demonstrate AnyRope's features.
///
/// # Editing Operations
///
/// The primary editing operations on [`Rope<M>`] are insertion and removal of
/// slices or individual elements.
/// For example:
///
/// ```
/// # use any_rope::{Rope, Width};
/// let mut rope = Rope::from_slice(&[
///     Width(1),
///     Width(2),
///     Width(3),
///     Width(0),
///     Width(0),
///     Width(2),
///     Width(1),
/// ]);
/// rope.remove_inclusive(6..8, usize::cmp);
/// rope.insert(6, Width(5), usize::cmp);
///
/// assert_eq!(
///     rope,
///     [Width(1), Width(2), Width(3), Width(5), Width(1)].as_slice()
/// );
/// ```
///
/// # Query Operations
///
/// [`Rope<M>`] gives you the ability to query an element at any given index or
/// measure, and the convertion between the two. You can either convert an index
/// to a measure, or convert the measure at the start or end of an element to an
/// index. For example:
///
/// ```rust
/// # use any_rope::{Rope, Width};
/// let rope = Rope::from_slice(&[
///     Width(0),
///     Width(0),
///     Width(1),
///     Width(1),
///     Width(2),
///     Width(25),
///     Width(0),
///     Width(0),
///     Width(1),
/// ]);
///
/// // `start_measure_to_index()` will pick the first element that starts at the given index.
/// assert_eq!(rope.start_measure_to_index(0, usize::cmp), 0);
/// // `end_measure_to_index()` will pick the last element that still starts at the given index.
/// assert_eq!(rope.end_measure_to_index(0, usize::cmp), 2);
/// assert_eq!(rope.start_measure_to_index(2, usize::cmp), 4);
/// assert_eq!(rope.start_measure_to_index(3, usize::cmp), 4);
/// assert_eq!(rope.start_measure_to_index(16, usize::cmp), 5);
/// assert_eq!(rope.start_measure_to_index(29, usize::cmp), 6);
/// ```
///
/// # Slicing
///
/// You can take immutable slices of a [`Rope<M>`] using
/// [`measure_slice()`][Rope::measure_slice]
/// or [`index_slice()`][Rope::index_slice]:
///
/// ```rust
/// # use any_rope::{Rope, Width};
/// let mut rope = Rope::from_slice(&[
///     Width(1),
///     Width(2),
///     Width(3),
///     Width(0),
///     Width(0),
///     Width(2),
///     Width(1),
/// ]);
/// let measure_slice = rope.measure_slice(3..6, usize::cmp);
/// let index_slice = rope.index_slice(2..5);
///
/// assert_eq!(measure_slice, index_slice);
/// ```
///
/// # Cloning
///
/// Cloning [`Rope<M>`]s is extremely cheap, running in `O(1)` time and taking a
/// small constant amount of memory for the new clone, regardless of slice size.
/// This is accomplished by data sharing between [`Rope<M>`] clones. The memory
/// used by clones only grows incrementally as the their contents diverge due
/// to edits. All of this is thread safe, so clones can be sent freely
/// between threads.
///
/// The primary intended use-case for this feature is to allow asynchronous
/// processing of [`Rope<M>`]s.
#[derive(Clone)]
pub struct Rope<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    pub(crate) root: Arc<Node<M>>,
}

impl<M> Rope<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    //-----------------------------------------------------------------------
    // Constructors

    /// Creates an empty [`Rope<M>`].
    #[inline]
    pub fn new() -> Self {
        Rope {
            root: Arc::new(Node::new()),
        }
    }

    /// Creates a [`Rope<M>`] from an [`M`][Measurable] slice.
    ///
    /// Runs in O(N) time.
    #[inline]
    #[allow(clippy::should_implement_trait)]
    pub fn from_slice(slice: &[M]) -> Self {
        RopeBuilder::new().build_at_once(slice)
    }

    //-----------------------------------------------------------------------
    // Informational methods

    /// Total number of elements in [`Rope<M>`].
    ///
    /// Runs in O(N) time.
    #[inline]
    pub fn len(&self) -> usize {
        self.root.len()
    }

    /// Returns `true` if the [`Rope<M>`] is empty.
    ///
    /// Runs in O(N) time.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.root.len() == 0
    }

    /// Sum of all measures of in [`Rope<M>`].
    ///
    /// Runs in O(N) time.
    #[inline]
    pub fn measure(&self) -> M::Measure {
        self.root.measure()
    }

    //-----------------------------------------------------------------------
    // Memory management methods

    /// Total size of the [`Rope<M>`]'s buffer space.
    ///
    /// This includes unoccupied buffer space. You can calculate
    /// the unoccupied space with `Rope::capacity() - Rope::len()`. In general,
    /// there will always be some unoccupied buffer space.
    ///
    /// Runs in O(N) time.
    #[inline]
    pub fn capacity(&self) -> usize {
        let mut count = 0;
        for chunk in self.chunks() {
            count += chunk.len().max(max_len::<M, M::Measure>());
        }
        count
    }

    /// Shrinks the [`Rope<M>`]'s capacity to the minimum possible.
    ///
    /// This will rarely result in `Rope::capacity() == Rope::len()`.
    /// [`Rope<M>`] stores [`M`][Measurable]s in a sequence of
    /// fixed-capacity chunks, so an exact fit only happens for lists of a
    /// lenght that is a multiple of that capacity.
    ///
    /// After calling this, the difference between `capacity()` and
    /// `len()` is typically under 1000 for each 1000000 [`M`][Measurable] in
    /// the [`Rope<M>`].
    ///
    /// **NOTE:** calling this on a [`Rope<M>`] clone causes it to stop sharing
    /// all data with its other clones. In such cases you will very likely
    /// be _increasing_ total memory usage despite shrinking the [`Rope<M>`]'s
    /// capacity.
    ///
    /// Runs in O(N) time, and uses O(log N) additional space during
    /// shrinking.
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        let mut node_stack = Vec::new();
        let mut builder = RopeBuilder::new();

        node_stack.push(self.root.clone());
        *self = Rope::new();

        loop {
            if node_stack.is_empty() {
                break;
            }

            if node_stack.last().unwrap().is_leaf() {
                builder.append_slice(node_stack.pop().unwrap().leaf_slice());
            } else if node_stack.last().unwrap().child_count() == 0 {
                node_stack.pop();
            } else {
                let (_, next_node) = Arc::make_mut(node_stack.last_mut().unwrap())
                    .children_mut()
                    .remove(0);
                node_stack.push(next_node);
            }
        }

        *self = builder.finish();
    }

    //-----------------------------------------------------------------------
    // Edit methods

    /// Inserts [`slice`][Measurable] at `measure`.
    ///
    /// Runs in O(L + log N) time, where N is the length of the [`Rope<M>`] and
    /// L is the length of [`slice`][Measurable].
    ///
    /// # Panics
    ///
    /// Panics if the `measure` is out of bounds (i.e. `measure >
    /// Rope::measure()`).
    #[inline]
    pub fn insert_slice(
        &mut self,
        measure: M::Measure,
        slice: &[M],
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) {
        // Bounds check
        self.try_insert_slice(measure, slice, cmp).unwrap()
    }

    /// Inserts a single [`M`][Measurable] at `measure`.
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `measure` is out of bounds (i.e. `measure >
    /// Rope::measure()`).
    #[inline]
    pub fn insert(
        &mut self,
        measure: M::Measure,
        measurable: M,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) {
        self.try_insert(measure, measurable, &cmp).unwrap()
    }

    /// Private internal-only method that does a single insertion of
    /// a sufficiently small slice.
    ///
    /// This only works correctly for insertion slices smaller than or equal to
    /// `MAX_BYTES - 4`.
    #[inline]
    fn insert_internal(
        &mut self,
        measure: M::Measure,
        slice: &[M],
        cmp: &impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) {
        let root_info = self.root.info();

        let (l_info, residual) = Arc::make_mut(&mut self.root).edit_chunk_at_measure(
            measure,
            cmp,
            root_info,
            |index, cur_info, leaf_slice| {
                // Find our index
                let index = end_measure_to_index(leaf_slice, index, cmp);

                // No node splitting
                if (leaf_slice.len() + slice.len()) <= max_len::<M, M::Measure>() {
                    // Calculate new info without doing a full re-scan of cur_slice.
                    let new_info = cur_info + SliceInfo::<M::Measure>::from_slice(slice);
                    leaf_slice.insert_slice(index, slice);
                    (new_info, None)
                }
                // We're splitting the node
                else {
                    let r_slice = leaf_slice.insert_slice_split(index, slice);
                    let l_slice_info = SliceInfo::<M::Measure>::from_slice(leaf_slice);
                    if r_slice.len() > 0 {
                        let r_slice_info = SliceInfo::<M::Measure>::from_slice(&r_slice);
                        (
                            l_slice_info,
                            Some((r_slice_info, Arc::new(Node::Leaf(r_slice)))),
                        )
                    } else {
                        // Leaf couldn't be validly split, so leave it oversized
                        (l_slice_info, None)
                    }
                }
            },
        );

        // Handle root splitting, if any.
        if let Some((r_info, r_node)) = residual {
            let mut l_node = Arc::new(Node::new());
            std::mem::swap(&mut l_node, &mut self.root);

            let mut children = BranchChildren::new();
            children.push((l_info, l_node));
            children.push((r_info, r_node));

            *Arc::make_mut(&mut self.root) = Node::Branch(children);
        }
    }

    /// Removes the slice in the given measure range.
    ///
    /// Uses range syntax, e.g. `2..7`, `2..`, etc.
    ///
    /// Runs in O(M + log N) time, where N is the length of the [`Rope<M>`] and
    /// M is the length of the range being removed.
    ///
    /// The first removed [`M`][Measurable] will be the first with a end measure
    /// sum greater than the starting bound if its
    /// [`measure()`][Measurable::measure] is greater than 0, or equal to the
    /// starting bound if its [`measure()`][Measurable::measure] is equal to 0.
    ///
    /// The last removed [`M`][Measurable] will be the first with a start
    /// measure sum greater than the ending bound if its
    /// [`measure()`][Measurable::measure] is greater than 0, or the last one
    /// with a start measure sum equal to the ending bound if its
    /// [`measure()`][Measurable::measure] is equal to 0.
    ///
    /// In essence, this means the following:
    /// - A range starting between a [`M`][Measurable]'s start and end measure
    ///   sums will remove
    /// said [`M`][Measurable].
    /// - A range ending in the start of a list of 0 measure [`M`][Measurable]s
    ///   will remove
    /// all of them.
    /// - An empty range that starts and ends in a list of 0 measure
    ///   [`M`][Measurable]s will
    /// remove all of them, and nothing else. This contrasts with Rust's usual
    /// definition of an empty range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use any_rope::{Rope, Width};
    /// let array = [
    ///     Width(1),
    ///     Width(2),
    ///     Width(3),
    ///     Width(0),
    ///     Width(0),
    ///     Width(2),
    ///     Width(1),
    /// ];
    /// let mut rope = Rope::from_slice(&array);
    ///
    /// // Removing in the middle of `Width(3)`.
    /// rope.remove_inclusive(5.., usize::cmp);
    ///
    /// assert_eq!(rope, [Width(1), Width(2)].as_slice());
    /// ```
    /// ```rust
    /// # use any_rope::{Rope, Width};
    /// let array = [
    ///     Width(1),
    ///     Width(2),
    ///     Width(3),
    ///     Width(0),
    ///     Width(0),
    ///     Width(2),
    ///     Width(1),
    /// ];
    /// let mut rope = Rope::from_slice(&array);
    ///
    /// // End bound coincides with a 0 measure list.
    /// rope.remove_inclusive(1..6, usize::cmp);
    ///
    /// assert_eq!(rope, [Width(1), Width(2), Width(1)].as_slice());
    /// ```
    /// ```rust
    /// # use any_rope::{Rope, Width};
    /// let array = [
    ///     Width(1),
    ///     Width(2),
    ///     Width(3),
    ///     Width(0),
    ///     Width(0),
    ///     Width(2),
    ///     Width(1),
    /// ];
    /// let mut rope = Rope::from_slice(&array);
    ///
    /// // Empty range at the start of a 0 measure list.
    /// rope.remove_inclusive(6..6, usize::cmp);
    ///
    /// // Inclusively removing an empty range does nothing.
    /// assert_eq!(
    ///     rope,
    ///     [Width(1), Width(2), Width(3), Width(2), Width(1)].as_slice()
    /// );
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the start of the range is greater than the end, or if the
    /// end is out of bounds (i.e. `end > self.measure()`).
    #[inline]
    pub fn remove_inclusive(
        &mut self,
        range: impl MeasureRange<M>,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) {
        self.try_remove_inclusive(range, cmp).unwrap()
    }

    /// Same as [`remove_inclusive()`][Rope::remove_inclusive], but keeps
    /// elements measure measure equal to 0 at the edges.
    ///
    /// If the `measure_range` doesn't cover the entire measure of a single
    /// [`M`][Measurable], then the removal does nothing.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use any_rope::{Rope, Width};
    /// let array = [
    ///     Width(1),
    ///     Width(2),
    ///     Width(3),
    ///     Width(0),
    ///     Width(0),
    ///     Width(2),
    ///     Width(1),
    /// ];
    /// let mut rope = Rope::from_slice(&array);
    ///
    /// // End bound coincides with a 0 measure list, which does not get removed.
    /// rope.remove_exclusive(1..6, usize::cmp);
    ///
    /// assert_eq!(
    ///     rope,
    ///     [Width(1), Width(0), Width(0), Width(2), Width(1)].as_slice()
    /// );
    /// ```
    /// ```rust
    /// # use any_rope::{Rope, Width};
    /// let array = [
    ///     Width(1),
    ///     Width(2),
    ///     Width(3),
    ///     Width(0),
    ///     Width(0),
    ///     Width(2),
    ///     Width(1),
    /// ];
    /// let mut rope = Rope::from_slice(&array);
    ///
    /// // Empty range at the start of a 0 measure list.
    /// rope.remove_exclusive(6..6, usize::cmp);
    ///
    /// // Exclusively removing an empty range does nothing.
    /// assert_eq!(rope, array.as_slice());
    /// ```
    /// ```rust
    /// # use any_rope::{Rope, Width};
    /// let array = [
    ///     Width(1),
    ///     Width(2),
    ///     Width(3),
    ///     Width(0),
    ///     Width(0),
    ///     Width(2),
    ///     Width(1),
    /// ];
    /// let mut rope = Rope::from_slice(&array);
    ///
    /// // Removing in the middle of `Width(3)`.
    /// rope.remove_exclusive(5..6, usize::cmp);
    ///
    /// // Exclusively removing in the middle of an element does nothing.
    /// assert_eq!(rope, array.as_slice());
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the start of the range is greater than the end, or if the
    /// end is out of bounds (i.e. `end > self.measure()`).
    #[inline]
    pub fn remove_exclusive(
        &mut self,
        range: impl MeasureRange<M>,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) {
        self.try_remove_exclusive(range, cmp).unwrap()
    }

    /// Splits the [`Rope<M>`] at `measure`, returning the right part of the
    /// split.
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `measure` is out of bounds (i.e. `measure >
    /// self.measure()`).
    #[inline]
    pub fn split_off(
        &mut self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Self {
        self.try_split_off(measure, cmp).unwrap()
    }

    /// Appends a [`Rope<M>`] to the end of this one, consuming the other
    /// [`Rope<M>`].
    ///
    /// Runs in O(log N) time.
    #[inline]
    pub fn append(&mut self, other: Self) {
        if other.measure().fallible_cmp(&M::Measure::default()).is_gt() {
            let left_info = self.root.info();
            let right_info = other.root.info();

            let l_depth = self.root.depth();
            let r_depth = other.root.depth();

            if l_depth > r_depth {
                let extra =
                    Arc::make_mut(&mut self.root).append_at_depth(other.root, l_depth - r_depth);
                if let Some(node) = extra {
                    let mut children = BranchChildren::new();
                    children.push((self.root.info(), Arc::clone(&self.root)));
                    children.push((node.info(), node));
                    self.root = Arc::new(Node::Branch(children));
                }
            } else {
                let mut other = other;
                let extra = Arc::make_mut(&mut other.root)
                    .prepend_at_depth(Arc::clone(&self.root), r_depth - l_depth);
                if let Some(node) = extra {
                    let mut children = BranchChildren::new();
                    children.push((node.info(), node));
                    children.push((other.root.info(), Arc::clone(&other.root)));
                    other.root = Arc::new(Node::Branch(children));
                }
                *self = other;
            };

            // Fix up any mess left behind.
            let root = Arc::make_mut(&mut self.root);
            if (left_info.len as usize) < min_len::<M, M::Measure>()
                || (right_info.len as usize) < min_len::<M, M::Measure>()
            {
                root.fix_tree_seam(left_info.measure, &M::Measure::fallible_cmp);
            }
            self.pull_up_singular_nodes();
        }
    }

    //-----------------------------------------------------------------------
    // Index conversion methods

    /// Returns the measure sum at the start of the given index.
    ///
    /// Notes:
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `index` is out of bounds (i.e. `index > Rope::len()`).
    #[inline]
    pub fn index_to_measure(&self, index: usize) -> M::Measure {
        self.try_index_to_measure(index).unwrap()
    }

    /// Returns an index, given a starting measure sum.
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `measure` is out of bounds (i.e. `measure >
    /// Rope::measure()`).
    #[inline]
    pub fn start_measure_to_index(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> usize {
        self.try_start_measure_to_index(measure, cmp).unwrap()
    }

    /// Returns an index, given an ending measure sum.
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `measure` is out of bounds (i.e. `measure >
    /// Rope::measure()`).
    #[inline]
    pub fn end_measure_to_index(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> usize {
        self.try_end_measure_to_index(measure, cmp).unwrap()
    }

    //-----------------------------------------------------------------------
    // Fetch methods

    /// Returns the [`M`][Measurable] at `index` and the starting measure sum of
    /// that element.
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `index` is out of bounds (i.e. `index > Rope::len()`).
    #[inline]
    pub fn from_index(&self, index: usize) -> (M::Measure, M) {
        // Bounds check
        if let Some(out) = self.get_from_index(index) {
            out
        } else {
            panic!(
                "Attempt to index past end of Rope: index {}, Rope length {}",
                index,
                self.len()
            );
        }
    }

    /// Returns the [`M`][Measurable] at `measure` and the starting measure sum
    /// of that element.
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `measure` is out of bounds (i.e. `measure >
    /// Rope::measure()`).
    #[inline]
    pub fn from_measure(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> (M::Measure, M) {
        if let Some(out) = self.get_from_measure(measure, cmp) {
            out
        } else {
            panic!(
                "Attempt to index past end of Rope: measure {:?}, Total rope measure is {:?}",
                measure,
                self.measure()
            );
        }
    }

    /// Returns the chunk containing the given index.
    ///
    /// Also returns the index and widht of the beginning of the chunk.
    ///
    /// Note: for convenience, a one-past-the-end `index` returns the last
    /// chunk of the `RopeSlice`.
    ///
    /// The return value is organized as
    /// `(chunk, chunk_index, chunk_measure)`.
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `index` is out of bounds (i.e. `index > Rope::len()`).
    #[inline]
    pub fn chunk_at_index(&self, index: usize) -> (&[M], usize, M::Measure) {
        // Bounds check
        if let Some(out) = self.get_chunk_at_index(index) {
            out
        } else {
            panic!(
                "Attempt to index past end of Rope: index {}, Rope length {}",
                index,
                self.len()
            );
        }
    }

    /// Returns the chunk containing the given measure.
    ///
    /// Also returns the index and measure of the beginning of the chunk.
    ///
    /// Note: for convenience, a one-past-the-end `measure` returns the last
    /// chunk of the `RopeSlice`.
    ///
    /// The return value is organized as
    /// `(chunk, chunk_index, chunk_measure)`.
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `measure` is out of bounds (i.e. `measure >
    /// Rope::measure()`).
    #[inline]
    pub fn chunk_at_measure(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> (&[M], usize, M::Measure) {
        if let Some(out) = self.get_chunk_at_measure(measure, &cmp) {
            out
        } else {
            panic!(
                "Attempt to index past end of Rope: measure {:?}, Rope measure {:?}",
                measure,
                self.measure()
            );
        }
    }

    //-----------------------------------------------------------------------
    // Slicing

    /// Gets an immutable slice of the [`Rope<M>`], using a measure range.
    ///
    /// Uses range syntax, e.g. `2..7`, `2..`, etc.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use any_rope::{Rope, Width};
    /// let mut rope = Rope::from_slice(&[
    ///     Width(1),
    ///     Width(2),
    ///     Width(3),
    ///     Width(0),
    ///     Width(0),
    ///     Width(2),
    ///     Width(1),
    /// ]);
    /// let slice = rope.measure_slice(..5, usize::cmp);
    ///
    /// assert_eq!(slice, [Width(1), Width(2), Width(3)].as_slice());
    /// ```
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the start of the range is greater than the end, or if the
    /// end is out of bounds (i.e. `end > Rope::measure()`).
    #[inline]
    pub fn measure_slice(
        &self,
        measure_range: impl MeasureRange<M>,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> RopeSlice<M> {
        self.get_measure_slice(measure_range, cmp).unwrap()
    }

    /// Gets and immutable slice of the [`Rope<M>`], using an index range.
    ///
    /// Uses range syntax, e.g. `2..7`, `2..`, etc.
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if:
    /// - The start of the range is greater than the end.
    /// - The end is out of bounds (i.e. `end > Rope::len()`).
    #[inline]
    pub fn index_slice(&self, index_range: impl RangeBounds<usize>) -> RopeSlice<M> {
        match self.get_index_slice_impl(index_range) {
            Ok(s) => return s,
            Err(e) => panic!("index_slice(): {}", e),
        }
    }

    //-----------------------------------------------------------------------
    // Iterator methods

    /// Creates an iterator over the [`Rope<M>`].
    ///
    /// This iterator will return values of type [Option<(usize, M)>], where the
    /// `usize` is the measure sum where the given [`M`][Measurable] starts.
    ///
    /// Runs in O(log N) time.
    #[inline]
    pub fn iter(&self) -> Iter<M> {
        Iter::new(&self.root)
    }

    /// Creates an iterator over the  [`Rope<M>`], starting at `measure`.
    ///
    /// This iterator will return values of type [`Option<(usize, M)>`], where
    /// the `usize` is the measure where the given [`M`][Measurable] starts.
    /// Since one can iterate in between an [`M`][Measurable]s start and end
    /// measure sums. the first `usize` may not actually corelate to the
    /// `measure` given to the function.
    ///
    /// If `measure == Rope::measure()` then an iterator at the end of the
    /// [`Rope<M>`] is created (i.e. [`next()`][crate::iter::Iter::next] will
    /// return [`None`]).
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `measure` is out of bounds (i.e. `measure >
    /// Rope::measure()`).
    #[inline]
    pub fn iter_at_measure(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Iter<M> {
        if let Some(out) = self.get_iter_at_measure(measure, cmp) {
            out
        } else {
            panic!(
                "Attempt to index past end of Rope: measure {:?}, Rope measure {:?}",
                measure,
                self.measure()
            );
        }
    }

    /// Creates an iterator over the chunks of the [`Rope<M>`].
    ///
    /// Runs in O(log N) time.
    #[inline]
    pub fn chunks(&self) -> Chunks<M> {
        Chunks::new(&self.root)
    }

    /// Creates an iterator over the chunks of the [`Rope<M>`], with the
    /// iterator starting at the chunk containing the `index`.
    ///
    /// Also returns the index and measure of the beginning of the first
    /// chunk to be yielded.
    ///
    /// If `index == Rope::len()` an iterator at the end of the [`Rope<M>`]
    /// (yielding [`None`] on a call to [`next()`][crate::iter::Iter::next]) is
    /// created.
    ///
    /// The return value is organized as `(iterator, chunk_index,
    /// chunk_measure)`.
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `index` is out of bounds (i.e. `index > Rope::len()`).
    #[inline]
    pub fn chunks_at_index(&self, index: usize) -> (Chunks<M>, usize, M::Measure) {
        if let Some(out) = self.get_chunks_at_index(index) {
            out
        } else {
            panic!(
                "Attempt to index past end of Rope: index {}, Rope length {}",
                index,
                self.len()
            );
        }
    }

    /// Creates an iterator over the chunks of the [`Rope<M>`], with the
    /// iterator starting at the chunk containing the `measure`.
    ///
    /// Also returns the index and measure of the beginning of the first
    /// chunk to be yielded.
    ///
    /// If `measure == Rope::measure()` an iterator at the end of the
    /// [`Rope<M>`] (yielding [`None`] on a call to
    /// [`next()`][crate::iter::Iter::next]) is created.
    ///
    /// The return value is organized as `(iterator, chunk_index,
    /// chunk_measure)`.
    ///
    /// Runs in O(log N) time.
    ///
    /// # Panics
    ///
    /// Panics if the `measure` is out of bounds (i.e. `measure >
    /// Rope::measure()`).
    #[inline]
    pub fn chunks_at_measure(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> (Chunks<M>, usize, M::Measure) {
        if let Some(out) = self.get_chunks_at_measure(measure, &cmp) {
            out
        } else {
            panic!(
                "Attempt to index past end of Rope: measure {:?}, Rope measure {:?}",
                measure,
                self.measure()
            );
        }
    }

    /// Returns true if this rope and `other` point to precisely the same
    /// in-memory data.
    ///
    /// This happens when one of the ropes is a clone of the other and
    /// neither have been modified since then. Because clones initially
    /// share all the same data, it can be useful to check if they still
    /// point to precisely the same memory as a way of determining
    /// whether they are both still unmodified.
    ///
    /// Note: this is distinct from checking for equality: two ropes can
    /// have the same *contents* (equal) but be stored in different
    /// memory locations (not instances). Importantly, two clones that
    /// post-cloning are modified identically will *not* be instances
    /// anymore, even though they will have equal contents.
    ///
    /// Runs in O(1) time.
    #[inline]
    pub fn is_instance(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.root, &other.root)
    }

    //-----------------------------------------------------------------------
    // Debugging

    /// NOT PART OF THE PUBLIC API (hidden from docs for a reason!)
    ///
    /// Debugging tool to make sure that all of the meta-data of the
    /// tree is consistent with the actual data.
    #[doc(hidden)]
    pub fn assert_integrity(&self) {
        self.root.assert_integrity();
    }

    /// NOT PART OF THE PUBLIC API (hidden from docs for a reason!)
    ///
    /// Debugging tool to make sure that all of the following invariants
    /// hold true throughout the tree:
    ///
    /// - The tree is the same height everywhere.
    /// - All internal nodes have the minimum number of children.
    /// - All leaf nodes are non-empty.
    #[doc(hidden)]
    pub fn assert_invariants(&self) {
        self.root.assert_balance();
        self.root.assert_node_size(true);
    }

    //-----------------------------------------------------------------------
    // Internal utilities

    /// Iteratively replaces the root node with its child if it only has
    /// one child.
    #[inline]
    pub(crate) fn pull_up_singular_nodes(&mut self) {
        while (!self.root.is_leaf()) && self.root.child_count() == 1 {
            let child = if let Node::Branch(ref children) = *self.root {
                Arc::clone(&children.nodes()[0])
            } else {
                unreachable!()
            };

            self.root = child;
        }
    }
}

/// # Non-Panicking
///
/// The methods in this impl block provide non-panicking versions of
/// [`Rope<M>`]'s panicking methods. They return either `Option::None` or
/// `Result::Err()` when their panicking counterparts would have panicked.
impl<M> Rope<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    /// Non-panicking version of [`insert()`][Rope::insert].
    #[inline]
    pub fn try_insert_slice(
        &mut self,
        measure: M::Measure,
        mut slice: &[M],
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Result<(), M> {
        // Bounds check
        if cmp(&measure, &self.measure()).is_le() {
            // We have three cases here:
            // 1. The insertion slice is very large, in which case building a new Rope out
            //    of it and splicing it into the existing Rope is most efficient.
            // 2. The insertion slice is somewhat large, in which case splitting it up into
            //    chunks and repeatedly inserting them is the most efficient. The splitting
            //    is necessary because the insertion code only works correctly below a
            //    certain insertion size.
            // 3. The insertion slice is small, in which case we can simply insert it.
            //
            // Cases #2 and #3 are rolled into one case here, where case #3 just
            // results in the slice being "split" into only one chunk.
            //
            // The boundary for what constitutes "very large" slice was arrived at
            // experimentally, by testing at what point Rope build + splice becomes
            // faster than split + repeated insert.
            if slice.len() > max_len::<M, M::Measure>() * 6 {
                // Case #1: very large slice, build rope and splice it in.
                let rope = Rope::from_slice(slice);
                let right = self.split_off(measure, &cmp);
                self.append(rope);
                self.append(right);
            } else {
                // Cases #2 and #3: split into chunks and repeatedly insert.
                while !slice.is_empty() {
                    // Split a chunk off from the end of the slice.
                    // We do this from the end instead of the front so that
                    // the repeated insertions can keep re-using the same
                    // insertion point.
                    let split_index = slice.len().saturating_sub(max_len::<M, M::Measure>() - 4);
                    let ins_slice = &slice[split_index..];
                    slice = &slice[..split_index];

                    // Do the insertion.
                    self.insert_internal(measure, ins_slice, &cmp);
                }
            }
            Ok(())
        } else {
            Err(Error::MeasureOutOfBounds(measure, self.measure()))
        }
    }

    /// Non-panicking version of [`insert()`][Rope::insert].
    #[inline]
    pub fn try_insert(
        &mut self,
        measure: M::Measure,
        measurable: M,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Result<(), M> {
        // Bounds check
        if cmp(&measure, &self.measure()).is_le() {
            self.insert_internal(measure, &[measurable], &cmp);
            Ok(())
        } else {
            Err(Error::MeasureOutOfBounds(measure, self.measure()))
        }
    }

    /// Non-panicking version of [`remove_inclusive()`][Rope::remove_inclusive].
    #[inline]
    pub fn try_remove_inclusive(
        &mut self,
        range: impl MeasureRange<M>,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Result<(), M> {
        self.try_remove_internal(range, &cmp, true)
    }

    /// Non-panicking version of [`remove_exclusive()`][Rope::remove_exclusive].
    #[inline]
    pub fn try_remove_exclusive(
        &mut self,
        range: impl MeasureRange<M>,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Result<(), M> {
        self.try_remove_internal(range, &cmp, false)
    }

    fn try_remove_internal(
        &mut self,
        range: impl MeasureRange<M>,
        cmp: &impl Fn(&M::Measure, &M::Measure) -> Ordering,
        inclusive: bool,
    ) -> Result<(), M> {
        let (start, end) = measures_from_range(&range, self.measure())?;

        if cmp(&start, &M::Measure::default()).is_eq()
            && cmp(&end, &self.measure()).is_eq()
            && inclusive
        {
            self.root = Arc::new(Node::new());
            Ok(())
        } else {
            let root = Arc::make_mut(&mut self.root);

            let (_, needs_fix) = root.remove_range(start, end, &cmp, inclusive, inclusive);

            if needs_fix {
                root.fix_tree_seam(start, &cmp);
            }

            self.pull_up_singular_nodes();
            Ok(())
        }
    }

    /// Non-panicking version of [`split_off()`][Rope::split_off].
    #[inline]
    pub fn try_split_off(
        &mut self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Result<Self, M> {
        // Bounds check
        if cmp(&measure, &self.measure()).is_le() {
            if measure == M::Measure::default() {
                // Special case 1
                let mut new_rope = Rope::new();
                std::mem::swap(self, &mut new_rope);
                Ok(new_rope)
            } else if measure == self.measure() {
                // Special case 2
                Ok(Rope::new())
            } else {
                // Do the split
                let mut new_rope = Rope {
                    root: Arc::new(Arc::make_mut(&mut self.root).end_split(measure, &cmp)),
                };

                // Fix up the edges
                Arc::make_mut(&mut self.root).zip_fix_right();
                Arc::make_mut(&mut new_rope.root).zip_fix_left();
                self.pull_up_singular_nodes();
                new_rope.pull_up_singular_nodes();

                Ok(new_rope)
            }
        } else {
            Err(Error::MeasureOutOfBounds(measure, self.measure()))
        }
    }

    /// Non-panicking version of [`index_to_measure()`][Rope::index_to_measure].
    #[inline]
    pub fn try_index_to_measure(&self, index: usize) -> Result<M::Measure, M> {
        // Bounds check
        if index <= self.len() {
            let (chunk, b, c) = self.chunk_at_index(index);
            Ok(c + index_to_measure(chunk, index - b))
        } else {
            Err(Error::IndexOutOfBounds(index, self.len()))
        }
    }

    /// Non-panicking version of
    /// [`start_measure_to_index()`][Rope::start_measure_to_index].
    #[inline]
    pub fn try_start_measure_to_index(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Result<usize, M> {
        // Bounds check
        if cmp(&measure, &self.measure()).is_le() {
            let (chunk, b, c) = self.chunk_at_measure(measure, &cmp);
            Ok(b + start_measure_to_index(chunk, measure - c, cmp))
        } else {
            Err(Error::MeasureOutOfBounds(measure, self.measure()))
        }
    }

    /// Non-panicking version of
    /// [`end_measure_to_index()`][Rope::end_measure_to_index].
    #[inline]
    pub fn try_end_measure_to_index(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Result<usize, M> {
        // Bounds check
        if cmp(&measure, &self.measure()).is_le() {
            let (chunk, b, c) = self.chunk_at_measure(measure, &cmp);
            Ok(b + end_measure_to_index(chunk, measure - c, cmp))
        } else {
            Err(Error::MeasureOutOfBounds(measure, self.measure()))
        }
    }

    /// Non-panicking version of [`from_index()`][Rope::from_index].
    #[inline]
    pub fn get_from_index(&self, index: usize) -> Option<(M::Measure, M)> {
        // Bounds check
        if index < self.len() {
            let (chunk, chunk_index, chunk_measure) = self.chunk_at_index(index);
            let index = index - chunk_index;
            let measure = index_to_measure(chunk, index);
            Some((measure + chunk_measure, chunk[index].clone()))
        } else {
            None
        }
    }

    /// Non-panicking version of [`from_measure()`][Rope::from_measure].
    #[inline]
    pub fn get_from_measure(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Option<(M::Measure, M)> {
        // Bounds check
        if cmp(&measure, &self.measure()).is_lt() && !self.is_empty() {
            let (chunk, _, chunk_measure) = self.chunk_at_measure(measure, &cmp);
            let index = start_measure_to_index(chunk, measure - chunk_measure, cmp);
            let measure = index_to_measure(chunk, index);
            Some((measure + chunk_measure, chunk[index.min(chunk.len() - 1)].clone()))
        } else {
            None
        }
    }

    /// Non-panicking version of [`chunk_at_index()`][Rope::chunk_at_index].
    #[inline]
    pub fn get_chunk_at_index(&self, index: usize) -> Option<(&[M], usize, M::Measure)> {
        // Bounds check
        if index <= self.len() {
            let (chunk, info) = self.root.get_chunk_at_index(index);
            Some((chunk, info.len as usize, info.measure))
        } else {
            None
        }
    }

    /// Non-panicking version of [`chunk_at_measure()`][Rope::chunk_at_measure].
    #[inline]
    pub fn get_chunk_at_measure(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Option<(&[M], usize, M::Measure)> {
        // Bounds check
        if cmp(&measure, &self.measure()).is_lt() && !self.is_empty() {
            let (chunk, info) = self.root.get_first_chunk_at_measure(measure, &cmp);
            Some((chunk, info.len as usize, info.measure))
        } else {
            None
        }
    }

    /// Non-panicking version of [`measure_slice()`][Rope::measure_slice].
    #[inline]
    pub fn get_measure_slice(
        &self,
        range: impl MeasureRange<M>,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Result<RopeSlice<M>, M> {
        let (start, end) = measures_from_range(&range, self.measure())?;

        // Bounds check
        Ok(RopeSlice::new_with_range(&self.root, start, end, &cmp))
    }

    /// Non-panicking version of [`index_slice()`][Rope::index_slice].
    #[inline]
    pub fn get_index_slice(&self, index_range: impl RangeBounds<usize>) -> Option<RopeSlice<M>> {
        self.get_index_slice_impl(index_range).ok()
    }

    pub(crate) fn get_index_slice_impl(
        &self,
        index_range: impl RangeBounds<usize>,
    ) -> Result<RopeSlice<M>, M> {
        let start_range = start_bound_to_num(index_range.start_bound());
        let end_range = end_bound_to_num(index_range.end_bound());

        // Bounds checks.
        match (start_range, end_range) {
            (Some(start), Some(end)) => {
                if start > end {
                    return Err(Error::IndexRangeInvalid(start, end));
                } else if end > self.len() {
                    return Err(Error::IndexRangeOutOfBounds(
                        start_range,
                        end_range,
                        self.len(),
                    ));
                }
            }
            (Some(s), None) => {
                if s > self.len() {
                    return Err(Error::IndexRangeOutOfBounds(
                        start_range,
                        end_range,
                        self.len(),
                    ));
                }
            }
            (None, Some(e)) => {
                if e > self.len() {
                    return Err(Error::IndexRangeOutOfBounds(None, end_range, self.len()));
                }
            }
            _ => {}
        }

        let (start, end) = (
            start_range.unwrap_or(0),
            end_range.unwrap_or_else(|| self.len()),
        );

        RopeSlice::new_with_index_range(&self.root, start, end)
    }

    /// Non-panicking version of [`iter_at_measure()`][Rope::iter_at_measure].
    #[inline]
    pub fn get_iter_at_measure(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Option<Iter<M>> {
        // Bounds check
        if cmp(&measure, &self.measure()).is_le() {
            Some(Iter::new_with_range_at_measure(
                &self.root,
                measure,
                (0, self.len()),
                (M::Measure::default(), self.measure()),
                cmp,
            ))
        } else {
            None
        }
    }

    /// Non-panicking version of [`chunks_at_index()`][Rope::chunks_at_index].
    #[inline]
    pub fn get_chunks_at_index(&self, index: usize) -> Option<(Chunks<M>, usize, M::Measure)> {
        // Bounds check
        if index <= self.len() {
            Some(Chunks::new_with_range_at_index(
                &self.root,
                index,
                (0, self.len()),
                (M::Measure::default(), self.measure()),
            ))
        } else {
            None
        }
    }

    /// Non-panicking version of
    /// [`chunks_at_measure()`][Rope::chunks_at_measure].
    #[inline]
    pub fn get_chunks_at_measure(
        &self,
        measure: M::Measure,
        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
    ) -> Option<(Chunks<M>, usize, M::Measure)> {
        // Bounds check
        if cmp(&measure, &self.measure()).is_le() {
            Some(Chunks::new_with_range_at_measure(
                &self.root,
                measure,
                (0, self.len()),
                (M::Measure::default(), self.measure()),
                cmp,
            ))
        } else {
            None
        }
    }
}

//==============================================================
// Conversion impls

impl<'a, M> From<&'a [M]> for Rope<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn from(slice: &'a [M]) -> Self {
        Rope::from_slice(slice)
    }
}

impl<'a, M> From<std::borrow::Cow<'a, [M]>> for Rope<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn from(slice: std::borrow::Cow<'a, [M]>) -> Self {
        Rope::from_slice(&slice)
    }
}

impl<M> From<Vec<M>> for Rope<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn from(slice: Vec<M>) -> Self {
        Rope::from_slice(&slice)
    }
}

/// Will share data where possible.
///
/// Runs in O(log N) time.
impl<'a, M> From<RopeSlice<'a, M>> for Rope<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    fn from(s: RopeSlice<'a, M>) -> Self {
        use crate::slice::RSEnum;
        match s {
            RopeSlice(RSEnum::Full {
                node,
                start_info,
                end_info,
            }) => {
                let mut rope = Rope {
                    root: Arc::clone(node),
                };

                // Chop off right end if needed
                if end_info.measure.fallible_cmp(&node.info().measure).is_lt() {
                    {
                        let root = Arc::make_mut(&mut rope.root);
                        root.end_split(end_info.measure, &M::Measure::fallible_cmp);
                        root.zip_fix_right();
                    }
                    rope.pull_up_singular_nodes();
                }

                // Chop off left end if needed
                if start_info
                    .measure
                    .fallible_cmp(&M::Measure::default())
                    .is_gt()
                {
                    {
                        let root = Arc::make_mut(&mut rope.root);
                        *root = root.start_split(start_info.measure, &M::Measure::fallible_cmp);
                        root.zip_fix_left();
                    }
                    rope.pull_up_singular_nodes();
                }

                // Return the rope
                rope
            }
            RopeSlice(RSEnum::Light { slice, .. }) => Rope::from_slice(slice),
        }
    }
}

impl<M> From<Rope<M>> for Vec<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn from(r: Rope<M>) -> Self {
        Vec::from(&r)
    }
}

impl<'a, M> From<&'a Rope<M>> for Vec<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn from(r: &'a Rope<M>) -> Self {
        let mut vec = Vec::with_capacity(r.len());
        vec.extend(r.chunks().flat_map(|chunk| chunk.iter()).cloned());
        vec
    }
}

impl<'a, M> From<Rope<M>> for std::borrow::Cow<'a, [M]>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn from(r: Rope<M>) -> Self {
        std::borrow::Cow::Owned(Vec::from(r))
    }
}

/// Attempts to borrow the contents of the [`Rope<M>`], but will convert to an
/// owned [`[M]`][Measurable] if the contents is not contiguous in memory.
///
/// Runs in best case O(1), worst case O(N).
impl<'a, M> From<&'a Rope<M>> for std::borrow::Cow<'a, [M]>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn from(r: &'a Rope<M>) -> Self {
        if let Node::Leaf(ref slice) = *r.root {
            std::borrow::Cow::Borrowed(slice)
        } else {
            std::borrow::Cow::Owned(Vec::from(r))
        }
    }
}

impl<'a, M> FromIterator<&'a [M]> for Rope<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = &'a [M]>,
    {
        let mut builder = RopeBuilder::new();
        for chunk in iter {
            builder.append_slice(chunk);
        }
        builder.finish()
    }
}

impl<'a, M> FromIterator<std::borrow::Cow<'a, [M]>> for Rope<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = std::borrow::Cow<'a, [M]>>,
    {
        let mut builder = RopeBuilder::new();
        for chunk in iter {
            builder.append_slice(&chunk);
        }
        builder.finish()
    }
}

impl<M> FromIterator<Vec<M>> for Rope<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = Vec<M>>,
    {
        let mut builder = RopeBuilder::new();
        for chunk in iter {
            builder.append_slice(&chunk);
        }
        builder.finish()
    }
}

//==============================================================
// Other impls

impl<M> std::fmt::Debug for Rope<M>
where
    M: Measurable + std::fmt::Debug,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_list().entries(self.chunks()).finish()
    }
}

impl<M> std::fmt::Display for Rope<M>
where
    M: Measurable + std::fmt::Display,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str("[")?;

        let mut iter = self.iter();
        iter.next()
            .map(|(_, measurable)| f.write_fmt(format_args!("{}", measurable)))
            .transpose()?;

        for (_, measurable) in iter {
            f.write_fmt(format_args!(", {}", measurable))?;
        }
        f.write_str("]")
    }
}

impl<M> std::default::Default for Rope<M>
where
    M: Measurable,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<M> std::cmp::Eq for Rope<M>
where
    M: Measurable + Eq,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
}

impl<M> std::cmp::PartialEq<Rope<M>> for Rope<M>
where
    M: Measurable + PartialEq,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn eq(&self, other: &Rope<M>) -> bool {
        self.measure_slice(.., M::Measure::fallible_cmp)
            == other.measure_slice(.., M::Measure::fallible_cmp)
    }
}

impl<'a, M> std::cmp::PartialEq<&'a [M]> for Rope<M>
where
    M: Measurable + PartialEq,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn eq(&self, other: &&'a [M]) -> bool {
        self.measure_slice(.., M::Measure::fallible_cmp) == *other
    }
}

impl<'a, M> std::cmp::PartialEq<Rope<M>> for &'a [M]
where
    M: Measurable + PartialEq,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn eq(&self, other: &Rope<M>) -> bool {
        *self == other.measure_slice(.., M::Measure::fallible_cmp)
    }
}

impl<M> std::cmp::PartialEq<[M]> for Rope<M>
where
    M: Measurable + PartialEq,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn eq(&self, other: &[M]) -> bool {
        self.measure_slice(.., M::Measure::fallible_cmp) == other
    }
}

impl<M> std::cmp::PartialEq<Rope<M>> for [M]
where
    M: Measurable + PartialEq,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn eq(&self, other: &Rope<M>) -> bool {
        self == other.measure_slice(.., M::Measure::fallible_cmp)
    }
}

impl<M> std::cmp::PartialEq<Vec<M>> for Rope<M>
where
    M: Measurable + PartialEq,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn eq(&self, other: &Vec<M>) -> bool {
        self.measure_slice(.., M::Measure::fallible_cmp) == other.as_slice()
    }
}

impl<M> std::cmp::PartialEq<Rope<M>> for Vec<M>
where
    M: Measurable + PartialEq,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn eq(&self, other: &Rope<M>) -> bool {
        self.as_slice() == other.measure_slice(.., M::Measure::fallible_cmp)
    }
}

impl<'a, M> std::cmp::PartialEq<std::borrow::Cow<'a, [M]>> for Rope<M>
where
    M: Measurable + PartialEq,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn eq(&self, other: &std::borrow::Cow<'a, [M]>) -> bool {
        self.measure_slice(.., M::Measure::fallible_cmp) == **other
    }
}

impl<'a, M> std::cmp::PartialEq<Rope<M>> for std::borrow::Cow<'a, [M]>
where
    M: Measurable + PartialEq,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn eq(&self, other: &Rope<M>) -> bool {
        **self == other.measure_slice(.., M::Measure::fallible_cmp)
    }
}

impl<M> std::cmp::Ord for Rope<M>
where
    M: Measurable + Ord,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn cmp(&self, other: &Rope<M>) -> std::cmp::Ordering {
        self.measure_slice(.., M::Measure::fallible_cmp)
            .cmp(&other.measure_slice(.., M::Measure::fallible_cmp))
    }
}

impl<M> std::cmp::PartialOrd<Rope<M>> for Rope<M>
where
    M: Measurable + PartialOrd + Ord,
    [(); max_len::<M, M::Measure>()]: Sized,
    [(); max_children::<M, M::Measure>()]: Sized,
{
    #[inline]
    fn partial_cmp(&self, other: &Rope<M>) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

//==============================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Width;

    /// 70 elements, total measure of 135.
    fn pseudo_random() -> Vec<Width> {
        (0..70)
            .map(|num| match num % 14 {
                0 | 7 => Width(1),
                1 | 8 => Width(2),
                2 => Width(4),
                3 | 10 => Width(0),
                4 | 11 => Width(0),
                5 => Width(5),
                6 => Width(1),
                9 => Width(8),
                12 => Width(3),
                13 => Width(0),
                _ => unreachable!(),
            })
            .collect()
    }

    /// 5 elements, total measure of 6.
    const SHORT_LOREM: &[Width] = &[Width(1), Width(2), Width(3), Width(0), Width(0)];

    #[test]
    fn new_01() {
        let rope: Rope<Width> = Rope::new();
        assert_eq!(rope, [].as_slice());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn from_slice() {
        let rope = Rope::from(pseudo_random());
        assert_eq!(rope, pseudo_random());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn len_01() {
        let rope = Rope::from(pseudo_random());
        assert_eq!(rope.len(), 70);
    }

    #[test]
    fn measure_02() {
        let rope: Rope<Width> = Rope::from_slice(&[]);
        assert_eq!(rope.len(), 0);
    }

    #[test]
    fn len_from_measures_01() {
        let rope = Rope::from(pseudo_random());
        assert_eq!(rope.measure(), 135);
    }

    #[test]
    fn len_from_measures_02() {
        let rope: Rope<Width> = Rope::from_slice(&[]);
        assert_eq!(rope.measure(), 0);
    }

    #[test]
    fn insert_01() {
        let mut rope = Rope::from_slice(SHORT_LOREM);
        rope.insert_slice(3, &[Width(1), Width(2), Width(3)], usize::cmp);

        assert_eq!(
            rope,
            [
                Width(1),
                Width(2),
                Width(1),
                Width(2),
                Width(3),
                Width(3),
                Width(0),
                Width(0)
            ]
            .as_slice()
        );

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn insert_02() {
        let mut rope = Rope::from_slice(SHORT_LOREM);
        rope.insert_slice(0, &[Width(1), Width(2), Width(3)], usize::cmp);

        assert_eq!(
            rope,
            [
                Width(1),
                Width(2),
                Width(3),
                Width(1),
                Width(2),
                Width(3),
                Width(0),
                Width(0)
            ]
            .as_slice()
        );

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn insert_03() {
        let mut rope = Rope::from_slice(SHORT_LOREM);
        rope.insert_slice(6, &[Width(1), Width(2), Width(3)], usize::cmp);

        assert_eq!(
            rope,
            [
                Width(1),
                Width(2),
                Width(3),
                Width(0),
                Width(0),
                Width(1),
                Width(2),
                Width(3)
            ]
            .as_slice()
        );

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn insert_04() {
        let mut rope = Rope::new();
        rope.insert_slice(0, &[Width(1), Width(2)], usize::cmp);
        rope.insert_slice(2, &[Width(5)], usize::cmp);
        rope.insert_slice(3, &[Width(0)], usize::cmp);
        rope.insert_slice(4, &[Width(4)], usize::cmp);
        rope.insert_slice(11, &[Width(3)], usize::cmp);

        // NOTE: Inserting in the middle of an item'slice measure range, makes it so
        // you actually place it at the end of said item.
        assert_eq!(
            rope,
            [Width(1), Width(2), Width(0), Width(5), Width(4), Width(3)].as_slice()
        );

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn insert_05() {
        let mut rope = Rope::new();
        rope.insert_slice(0, &[Width(15), Width(20)], usize::cmp);
        rope.insert_slice(7, &[Width(0), Width(0)], usize::cmp);
        assert_eq!(rope, [Width(15), Width(0), Width(0), Width(20)].as_slice());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn insert_06() {
        let mut rope = Rope::new();
        rope.insert(0, Width(15), usize::cmp);
        rope.insert(1, Width(20), usize::cmp);
        rope.insert(2, Width(10), usize::cmp);
        rope.insert(3, Width(4), usize::cmp);
        rope.insert_slice(20, &[Width(0), Width(0)], usize::cmp);
        assert_eq!(
            rope,
            [
                Width(15),
                Width(4),
                Width(10),
                Width(0),
                Width(0),
                Width(20)
            ]
            .as_slice()
        );

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn remove_01() {
        let slice = &[
            Width(15),
            Width(0),
            Width(0),
            Width(24),
            Width(1),
            Width(2),
            Width(7),
        ];
        let mut rope = Rope::from_slice(slice);

        rope.remove_inclusive(0..11, usize::cmp);
        rope.remove_inclusive(24..31, usize::cmp);
        rope.remove_inclusive(0..0, usize::cmp);
        assert_eq!(rope, [Width(24)].as_slice());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn remove_02() {
        let slice = &[Width(1); 15];
        let mut rope = Rope::from_slice(slice);

        // assert_invariants() below.
        rope.remove_inclusive(3..6, usize::cmp);
        assert_eq!(rope, [Width(1); 12].as_slice());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn remove_03() {
        let mut rope = Rope::from(pseudo_random());

        // Make sure removing an empty range, on a non 0 measure element, does nothing.
        rope.remove_inclusive(45..45, usize::cmp);
        assert_eq!(rope, pseudo_random());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn remove_04() {
        let mut rope = Rope::from(pseudo_random());

        // Make sure removing everything works.
        rope.remove_inclusive(0..135, usize::cmp);
        assert_eq!(rope, [].as_slice());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn remove_05() {
        let mut rope = Rope::from(pseudo_random());

        // Make sure removing a large range works.
        rope.remove_inclusive(3..135, usize::cmp);
        assert_eq!(rope, &pseudo_random()[..2]);

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn remove_06() {
        let mut vec = Vec::from([Width(1); 2]);
        vec.extend_from_slice(&[Width(0); 300]);
        vec.extend_from_slice(&[Width(2); 3]);

        let mut rope = Rope::from(vec);
        rope.remove_inclusive(2..2, usize::cmp);

        assert_eq!(
            rope,
            [Width(1), Width(1), Width(2), Width(2), Width(2)].as_slice()
        );
    }

    #[test]
    #[should_panic]
    fn remove_07() {
        let mut rope = Rope::from(pseudo_random());
        #[allow(clippy::reversed_empty_ranges)]
        rope.remove_inclusive(56..55, usize::cmp); // Wrong ordering of start/end on purpose.
    }

    #[test]
    #[should_panic]
    fn remove_08() {
        let mut rope = Rope::from(pseudo_random());
        rope.remove_inclusive(134..136, usize::cmp); // Removing past the end
    }

    #[test]
    fn split_off_01() {
        let mut rope = Rope::from(pseudo_random());

        let split = rope.split_off(50, usize::cmp);
        assert_eq!(rope, &pseudo_random()[..24]);
        assert_eq!(split, &pseudo_random()[24..]);

        rope.assert_integrity();
        split.assert_integrity();
        rope.assert_invariants();
        split.assert_invariants();
    }

    #[test]
    fn split_off_02() {
        let mut rope = Rope::from(pseudo_random());

        let split = rope.split_off(1, usize::cmp);
        assert_eq!(rope, [Width(1)].as_slice());
        assert_eq!(split, &pseudo_random()[1..]);

        rope.assert_integrity();
        split.assert_integrity();
        rope.assert_invariants();
        split.assert_invariants();
    }

    #[test]
    fn split_off_03() {
        let mut rope = Rope::from(pseudo_random());

        let split = rope.split_off(134, usize::cmp);
        assert_eq!(rope, &pseudo_random()[..69]);
        assert_eq!(split, [Width(0)].as_slice());

        rope.assert_integrity();
        split.assert_integrity();
        rope.assert_invariants();
        split.assert_invariants();
    }

    #[test]
    fn split_off_04() {
        let mut rope = Rope::from(pseudo_random());

        let split = rope.split_off(0, usize::cmp);
        assert_eq!(rope, [].as_slice());
        assert_eq!(split, pseudo_random().as_slice());

        rope.assert_integrity();
        split.assert_integrity();
        rope.assert_invariants();
        split.assert_invariants();
    }

    #[test]
    fn split_off_05() {
        let mut rope = Rope::from(pseudo_random());

        let split = rope.split_off(135, usize::cmp);
        assert_eq!(rope, pseudo_random().as_slice());
        assert_eq!(split, [].as_slice());

        rope.assert_integrity();
        split.assert_integrity();
        rope.assert_invariants();
        split.assert_invariants();
    }

    #[test]
    #[should_panic]
    fn split_off_06() {
        let mut rope = Rope::from(pseudo_random());
        rope.split_off(136, usize::cmp); // One past the end of the rope
    }

    #[test]
    fn append_01() {
        let mut rope = Rope::from_slice(&pseudo_random()[..35]);
        let append = Rope::from_slice(&pseudo_random()[35..]);

        rope.append(append);
        assert_eq!(rope, pseudo_random().as_slice());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn append_02() {
        let mut rope = Rope::from_slice(&pseudo_random()[..68]);
        let append = Rope::from_slice(&[Width(3), Width(0)]);

        rope.append(append);
        assert_eq!(rope, pseudo_random());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn append_03() {
        let mut rope = Rope::from_slice(&[Width(1), Width(2)]);
        let append = Rope::from_slice(&pseudo_random()[2..]);

        rope.append(append);
        assert_eq!(rope, pseudo_random());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn append_04() {
        let mut rope = Rope::from(pseudo_random());
        let append = Rope::from_slice([].as_slice());

        rope.append(append);
        assert_eq!(rope, pseudo_random());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn append_05() {
        let mut rope = Rope::from_slice([].as_slice());
        let append = Rope::from(pseudo_random());

        rope.append(append);
        assert_eq!(rope, pseudo_random());

        rope.assert_integrity();
        rope.assert_invariants();
    }

    #[test]
    fn measure_to_index_01() {
        let rope = Rope::from(pseudo_random());

        assert_eq!(rope.start_measure_to_index(0, usize::cmp), 0);
        assert_eq!(rope.start_measure_to_index(1, usize::cmp), 1);
        assert_eq!(rope.start_measure_to_index(2, usize::cmp), 1);

        assert_eq!(rope.start_measure_to_index(91, usize::cmp), 47);
        assert_eq!(rope.start_measure_to_index(92, usize::cmp), 47);
        assert_eq!(rope.start_measure_to_index(93, usize::cmp), 48);
        assert_eq!(rope.start_measure_to_index(94, usize::cmp), 49);

        assert_eq!(rope.start_measure_to_index(102, usize::cmp), 51);
        assert_eq!(rope.start_measure_to_index(103, usize::cmp), 51);
    }

    #[test]
    fn from_index_01() {
        let rope = Rope::from(pseudo_random());

        assert_eq!(rope.from_index(0), (0, Width(1)));

        assert_eq!(rope.from_index(67), (132, Width(0)));
        assert_eq!(rope.from_index(68), (132, Width(3)));
        assert_eq!(rope.from_index(69), (135, Width(0)));
    }

    #[test]
    #[should_panic]
    fn from_index_02() {
        let rope = Rope::from(pseudo_random());
        rope.from_index(70);
    }

    #[test]
    #[should_panic]
    fn from_index_03() {
        let rope: Rope<Width> = Rope::from_slice(&[]);
        rope.from_index(0);
    }

    #[test]
    fn from_measure_01() {
        let rope = Rope::from(pseudo_random());

        assert_eq!(rope.from_measure(0, usize::cmp), (0, Width(1)));
        assert_eq!(rope.from_measure(10, usize::cmp), (7, Width(5)));
        assert_eq!(rope.from_measure(18, usize::cmp), (16, Width(8)));
        assert_eq!(rope.from_measure(108, usize::cmp), (108, Width(0)));
    }

    #[test]
    #[should_panic]
    fn from_measure_02() {
        let rope = Rope::from(pseudo_random());
        rope.from_measure(136, usize::cmp);
    }

    #[test]
    #[should_panic]
    fn from_measure_03() {
        let rope: Rope<Width> = Rope::from_slice(&[]);
        rope.from_measure(0, usize::cmp);
    }

    #[test]
    fn chunk_at_index() {
        let rope = Rope::from(pseudo_random());
        let lorem_ipsum = pseudo_random();
        let mut total = lorem_ipsum.as_slice();

        let mut last_chunk = [].as_slice();
        for i in 0..rope.len() {
            let (chunk, index, measure) = rope.chunk_at_index(i);
            assert_eq!(measure, index_to_measure(&lorem_ipsum, index));
            if chunk != last_chunk {
                assert_eq!(chunk, &total[..chunk.len()]);
                total = &total[chunk.len()..];
                last_chunk = chunk;
            }

            let measure_1 = lorem_ipsum.get(i).unwrap();
            let measure_2 = {
                let i2 = i - index;
                chunk.get(i2).unwrap()
            };
            assert_eq!(measure_1, measure_2);
        }
        assert_eq!(total.len(), 0);
    }

    #[test]
    fn chunk_at_measure() {
        let rope = Rope::from(pseudo_random());
        let lorem_ipsum = pseudo_random();
        let mut total = lorem_ipsum.as_slice();

        let mut last_chunk = [].as_slice();
        for i in 0..rope.measure() {
            let (chunk, _, measure) = rope.chunk_at_measure(i, usize::cmp);
            if chunk != last_chunk {
                assert_eq!(chunk, &total[..chunk.len()]);
                total = &total[chunk.len()..];
                last_chunk = chunk;
            }

            let measure_1 = {
                let index_1 = start_measure_to_index(&lorem_ipsum, i, usize::cmp);
                lorem_ipsum.get(index_1).unwrap()
            };
            let measure_2 = {
                let index_2 = start_measure_to_index(chunk, i - measure, usize::cmp);
                chunk.get(index_2)
            };
            if let Some(measure_2) = measure_2 {
                assert_eq!(measure_1, measure_2);
            }
        }
        assert_eq!(total.len(), 0);
    }

    #[test]
    fn measure_slice_01() {
        let rope = Rope::from(pseudo_random());

        let slice = rope.measure_slice(0..rope.measure(), usize::cmp);

        assert_eq!(slice, pseudo_random());
    }

    #[test]
    fn measure_slice_02() {
        let rope = Rope::from(pseudo_random());

        let slice = rope.measure_slice(5..21, usize::cmp);

        assert_eq!(slice, &pseudo_random()[2..10]);
    }

    #[test]
    fn measure_slice_03() {
        let rope = Rope::from(pseudo_random());

        let slice = rope.measure_slice(31..135, usize::cmp);

        assert_eq!(slice, &pseudo_random()[16..70]);
    }

    #[test]
    fn measure_slice_04() {
        let rope = Rope::from(pseudo_random());

        let slice = rope.measure_slice(53..53, usize::cmp);

        assert_eq!([].as_slice(), slice);
    }

    #[test]
    #[should_panic]
    fn measure_slice_05() {
        let rope = Rope::from(pseudo_random());
        #[allow(clippy::reversed_empty_ranges)]
        rope.measure_slice(53..52, usize::cmp); // Wrong ordering on purpose.
    }

    #[test]
    #[should_panic]
    fn measure_slice_06() {
        let rope = Rope::from(pseudo_random());
        rope.measure_slice(134..136, usize::cmp);
    }

    #[test]
    fn index_slice_01() {
        let rope = Rope::from(pseudo_random());

        let slice = rope.index_slice(0..rope.len());

        assert_eq!(pseudo_random(), slice);
    }

    #[test]
    fn index_slice_02() {
        let rope = Rope::from(pseudo_random());

        let slice = rope.index_slice(5..21);

        assert_eq!(&pseudo_random()[5..21], slice);
    }

    #[test]
    fn index_slice_03() {
        let rope = Rope::from(pseudo_random());

        let slice = rope.index_slice(31..55);

        assert_eq!(&pseudo_random()[31..55], slice);
    }

    #[test]
    fn index_slice_04() {
        let rope = Rope::from(pseudo_random());

        let slice = rope.index_slice(53..53);

        assert_eq!([].as_slice(), slice);
    }

    #[test]
    #[should_panic]
    fn index_slice_05() {
        let rope = Rope::from(pseudo_random());
        #[allow(clippy::reversed_empty_ranges)]
        rope.index_slice(53..52); // Wrong ordering on purpose.
    }

    #[test]
    #[should_panic]
    fn index_slice_06() {
        let rope = Rope::from(pseudo_random());
        rope.index_slice(20..72);
    }

    #[test]
    fn eq_rope_01() {
        let rope: Rope<Width> = Rope::from_slice([].as_slice());

        assert_eq!(rope, rope);
    }

    #[test]
    fn eq_rope_02() {
        let rope = Rope::from(pseudo_random());

        assert_eq!(rope, rope);
    }

    #[test]
    fn eq_rope_03() {
        let rope_1 = Rope::from(pseudo_random());
        let mut rope_2 = rope_1.clone();
        rope_2.remove_inclusive(26..27, usize::cmp);
        rope_2.insert(26, Width(1000), usize::cmp);

        assert_ne!(rope_1, rope_2);
    }

    #[test]
    fn eq_rope_04() {
        let rope: Rope<Width> = Rope::from_slice([].as_slice());

        assert_eq!(rope, [].as_slice());
        assert_eq!([].as_slice(), rope);
    }

    #[test]
    fn eq_rope_05() {
        let rope = Rope::from(pseudo_random());

        assert_eq!(rope, pseudo_random());
        assert_eq!(pseudo_random(), rope);
    }

    #[test]
    fn eq_rope_06() {
        let mut rope = Rope::from(pseudo_random());
        rope.remove_inclusive(26..27, usize::cmp);
        rope.insert(26, Width(5000), usize::cmp);

        assert_ne!(rope, pseudo_random());
        assert_ne!(pseudo_random(), rope);
    }

    #[test]
    fn eq_rope_07() {
        let rope = Rope::from(pseudo_random());
        let slice: Vec<Width> = pseudo_random();

        assert_eq!(rope, slice);
        assert_eq!(slice, rope);
    }

    #[test]
    fn to_vec_01() {
        let rope = Rope::from(pseudo_random());
        let slice: Vec<Width> = (&rope).into();

        assert_eq!(rope, slice);
    }

    #[test]
    fn to_cow_01() {
        use std::borrow::Cow;
        let rope = Rope::from(pseudo_random());
        let cow: Cow<[Width]> = (&rope).into();

        assert_eq!(rope, cow);
    }

    #[test]
    fn to_cow_02() {
        use std::borrow::Cow;
        let rope = Rope::from(pseudo_random());
        let cow: Cow<[Width]> = (rope.clone()).into();

        assert_eq!(rope, cow);
    }

    #[test]
    fn to_cow_03() {
        use std::borrow::Cow;
        let rope = Rope::from_slice(&[Width(1)]);
        let cow: Cow<[Width]> = (&rope).into();

        // Make sure it'slice borrowed.
        if let Cow::Owned(_) = cow {
            panic!("Small Cow conversions should result in a borrow.");
        }

        assert_eq!(rope, cow);
    }

    #[test]
    fn from_rope_slice_01() {
        let rope_1 = Rope::from(pseudo_random());
        let slice = rope_1.measure_slice(.., usize::cmp);
        let rope_2: Rope<Width> = slice.into();

        assert_eq!(rope_1, rope_2);
        assert_eq!(slice, rope_2);
    }

    #[test]
    fn from_rope_slice_02() {
        let rope_1 = Rope::from(pseudo_random());
        let slice = rope_1.measure_slice(0..24, usize::cmp);
        let rope_2: Rope<Width> = slice.into();

        assert_eq!(slice, rope_2);
    }

    #[test]
    fn from_rope_slice_03() {
        let rope_1 = Rope::from(pseudo_random());
        let slice = rope_1.measure_slice(13..89, usize::cmp);
        let rope_2: Rope<Width> = slice.into();

        assert_eq!(slice, rope_2);
    }

    #[test]
    fn from_rope_slice_04() {
        let rope_1 = Rope::from(pseudo_random());
        let slice = rope_1.measure_slice(13..41, usize::cmp);
        let rope_2: Rope<Width> = slice.into();

        assert_eq!(slice, rope_2);
    }

    #[test]
    fn from_iter_01() {
        let rope_1 = Rope::from(pseudo_random());
        let rope_2 = Rope::from_iter(rope_1.chunks());

        assert_eq!(rope_1, rope_2);
    }

    #[test]
    fn is_instance_01() {
        let rope = Rope::from_slice(&[Width(1), Width(2), Width(10), Width(0), Width(0)]);
        let mut c1 = rope.clone();
        let c2 = c1.clone();

        assert!(rope.is_instance(&c1));
        assert!(rope.is_instance(&c2));
        assert!(c1.is_instance(&c2));

        c1.insert_slice(0, &[Width(8)], usize::cmp);

        assert!(!rope.is_instance(&c1));
        assert!(rope.is_instance(&c2));
        assert!(!c1.is_instance(&c2));
    }
}