populated 0.0.6

Collection types that are guaranteed to be populated (i.e. non-empty). Based on std::collections types.
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
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
//! A library for working with non-empty collections i.e. populated collections.
//! Mirrors std collections in its populated versions that guarantee always containing at least one
//! element in the collection.
//!
//! These collections are useful when you want to ensure that a collection is never empty. Any attempt
//! to make it empty will result in a compile-time error. Also, these collections provide additional
//! guarantees about their length and capacity, which are always non-zero. This means that you do not
//! need to deal with `Option` in cases where you know that the collection will always have at least
//! one element. For example, you call `first()` on a `PopulatedVec` and you are guaranteed to get a
//! reference to the first element without having to deal with `Option`.
//!
//! # Safe transition to `std` collections when emptying a populated collection
//!
//! If you invoke an operation that empties a populated collection, the library provides a safe way to
//! transition to the corresponding `std` collection. For example, if you call `clear()` on a
//! `PopulatedVec`, it will return the underlying `Vec`. `clear()` on a `PopulatedVec` will take
//! ownership of the `PopulatedVec` and return the underlying `Vec`. This way any attempt to use
//! a cleared `PopulatedVec` will result in a compile-time error. At the same time, you can safely
//! and efficiently transition to the `Vec` when you need to.
//!
//! # Collections
//!
//! The following `std` collections have been mirrored in this library:
//!
//! - `Vec` → `PopulatedVec`
//! - `Slice` → `PopulatedSlice`
//! - `BinaryHeap` → `PopulatedBinaryHeap`
//! - `HashMap` → `PopulatedHashMap`
//! - `HashSet` → `PopulatedHashSet`
//! - `BTreeMap` → `PopulatedBTreeMap`
//! - `BTreeSet` → `PopulatedBTreeSet`
//! - `VecDeque` → `PopulatedVecDeque`
//!
//! # Examples
//!
//! `first()` on a `PopulatedVec` and `PopulatedSlice`:
//!
//! ```
//! use populated::{PopulatedVec, PopulatedSlice};
//!
//! let vec = PopulatedVec::new(1);
//! assert_eq!(vec.len().get(), 1);
//! assert_eq!(vec.first(), &1);
//!
//! let slice = vec.as_slice();
//! assert_eq!(slice.len().get(), 1);
//! assert_eq!(slice.first(), &1);
//! ```
//!
//! `clear()` on a `BTreeMap`:
//!
//! ```
//! use populated::PopulatedBTreeMap;
//!
//! let mut map = PopulatedBTreeMap::new("a", 1);
//! map.insert("b", 2);
//! assert_eq!(map.len().get(), 2);
//!
//! // Safe transition to std BTreeMap on clear
//! let map = map.clear();
//! assert_eq!(map.len(), 0);
//! ```

use std::{
    borrow::{Borrow, BorrowMut, Cow},
    cmp::Ordering,
    collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, TryReserveError, VecDeque},
    hash::{BuildHasher, Hash, RandomState},
    num::NonZeroUsize,
    ops::{
        Add, AddAssign, BitOr, Deref, DerefMut, Index, IndexMut, RangeBounds, RangeFull, RangeTo,
        RangeToInclusive,
    },
};

/// A non-empty `Vec` with at least one element.
#[derive(PartialEq, PartialOrd, Eq, Ord, Clone, Debug)]
pub struct PopulatedVec<T>(Vec<T>);

impl<T> From<PopulatedVec<T>> for Vec<T> {
    fn from(populated_vec: PopulatedVec<T>) -> Vec<T> {
        populated_vec.0
    }
}

impl<T> TryFrom<Vec<T>> for PopulatedVec<T> {
    type Error = Vec<T>;

    /// Attempts to create a `PopulatedVec` from a `Vec`. If the `Vec` is empty, it returns the original `Vec` as an error.
    /// Otherwise, it returns a `PopulatedVec` with `Ok`.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let vec = vec![1];
    /// let vec = PopulatedVec::try_from(vec).unwrap();
    /// assert_eq!(vec.len().get(), 1);
    /// assert_eq!(vec.first(), &1);
    /// ```
    ///
    /// If the `Vec` is empty, it returns the original `Vec` as an error.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let vec: Vec<u64> = vec![];
    /// let vec = PopulatedVec::try_from(vec);
    /// assert_eq!(vec, Err(vec![]));
    /// ```
    fn try_from(vec: Vec<T>) -> Result<PopulatedVec<T>, Self::Error> {
        if vec.is_empty() {
            Err(vec)
        } else {
            Ok(PopulatedVec(vec))
        }
    }
}

impl<T> PopulatedVec<T> {
    /// Constructs a `Vec<T>` populated with a single element.
    pub fn new(value: T) -> PopulatedVec<T> {
        PopulatedVec(vec![value])
    }

    /// Creates a new `PopulatedVec` with the specified capacity.
    /// The capacity must be non-zero. This creates a `PopulatedVec` with the specified capacity and the first element initialized
    /// with the provided value.
    pub fn with_capacity(capacity: NonZeroUsize, value: T) -> PopulatedVec<T> {
        let vec = Vec::with_capacity(capacity.get());
        PopulatedVec::pushed(vec, value)
    }

    /// Constructs a `PopulatedVec` from a `Vec<T>` by pushing a single element to it.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let vec = vec![1];
    /// let vec = PopulatedVec::pushed(vec, 2);
    /// assert_eq!(vec.len().get(), 2);
    /// assert_eq!(vec.first(), &1);
    /// assert_eq!(vec.last(), &2);
    /// ```
    pub fn pushed(mut vec: Vec<T>, value: T) -> PopulatedVec<T> {
        vec.push(value);
        PopulatedVec(vec)
    }

    /// Constructs a `PopulatedVec` from a `Vec<T>` by inserting a single element at the specified index.
    /// If the index is out of bounds, it will panic.
    /// If the index is within bounds, it will insert the element at the specified index.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let vec = vec![1, 3];
    /// let vec = PopulatedVec::inserted(vec, 1, 2);
    /// assert_eq!(vec.len().get(), 3);
    /// assert_eq!(vec.first(), &1);
    /// assert_eq!(vec.last(), &3);
    /// ```
    pub fn inserted(mut vec: Vec<T>, index: usize, value: T) -> PopulatedVec<T> {
        vec.insert(index, value);
        PopulatedVec(vec)
    }

    /// Constructs a `PopulatedVec` from a `Vec<T>` by providing the first element and the rest of the elements from an array.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let vec = PopulatedVec::from_first_and_rest_array(1, [2, 3]);
    /// assert_eq!(vec.len().get(), 3);
    /// assert_eq!(vec.first(), &1);
    /// assert_eq!(vec.last(), &3);
    /// ```
    pub fn from_first_and_rest_array<const N: usize>(first: T, rest: [T; N]) -> PopulatedVec<T> {
        let mut vec = PopulatedVec::with_capacity(NonZeroUsize::MIN.saturating_add(N), first);
        vec.extend_from_array(rest);
        vec
    }

    /// Returns the underlying `Vec<T>`.
    pub fn into_inner(self) -> Vec<T> {
        self.0
    }

    /// Appends an element to the back of a collection.
    pub fn push(&mut self, value: T) {
        self.0.push(value);
    }

    /// Appends elements from a slice to the back of a collection.
    /// This is a safe operation because this is a `PopulatedVec`.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let mut vec = PopulatedVec::new(1);
    /// vec.extend_from_slice(&[2, 3]);
    /// assert_eq!(vec.len().get(), 3);
    /// assert_eq!(vec.last(), &3);
    /// ```
    pub fn extend_from_array<const N: usize>(&mut self, array: [T; N]) {
        self.reserve(N);
        for value in array {
            self.push(value);
        }
    }

    /// Removes the last element from the vector and returns it, along with
    /// the remaining vector. Note that this is a safe operation because
    /// this is a `PopulatedVec`.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let vec = PopulatedVec::new(1);
    /// let (vec, last) = vec.pop();
    /// assert_eq!(last, 1);
    /// assert_eq!(vec.len(), 0);
    /// ```
    ///
    /// # Returns
    /// A tuple containing `Vec` (with the last element removed) and the last element of the vector
    /// The returned `Vec` has no additional guarantees about its length.
    pub fn pop(self) -> (Vec<T>, T) {
        let mut vec = self.0;
        let last = vec.pop().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedVec
        (vec, last)
    }

    /// Returns the first element of the slice. This is a safe operation
    /// because this is a `PopulatedVec`.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let vec = PopulatedVec::new(1);
    /// assert_eq!(vec.first(), &1);
    /// ```
    ///
    /// # Returns
    /// A reference to the first element of the vector.
    pub fn first(&self) -> &T {
        self.0.first().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedVec
    }

    /// Returns the last element of the slice. This is a safe operation
    /// because this is a `PopulatedVec`.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let vec = PopulatedVec::new(1);
    /// assert_eq!(vec.last(), &1);
    /// ```
    ///
    /// # Returns
    /// A reference to the last element of the vector.
    pub fn last(&self) -> &T {
        self.0.last().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedVec
    }

    /// Returns the number of elements in the vector, also referred to as its
    /// ‘length’. It is non-zero because this is a `PopulatedVec`.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let vec = PopulatedVec::new(1);
    /// assert_eq!(vec.len().get(), 1);
    /// ```
    ///
    /// # Returns
    /// The number of elements in the vector.
    pub fn len(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.len()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedVec
    }

    /// Returns the total number of elements the vector can hold without
    /// reallocating. Since this is a `PopulatedVec`, it is guaranteed to
    /// be non-zero.
    pub fn capacity(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.capacity()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedVec
    }

    /// Reserves capacity for at least `additional` more elements to be inserted.
    pub fn reserve(&mut self, additional: usize) {
        self.0.reserve(additional);
    }

    /// Reserves the minimum capacity for exactly `additional` more elements to be inserted.
    pub fn reserve_exact(&mut self, additional: usize) {
        self.0.reserve_exact(additional);
    }

    /// Tries to reserve capacity for at least `additional` more elements to be inserted.
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.0.try_reserve(additional)
    }

    /// Tries to reserve the minimum capacity for exactly `additional` more elements to be inserted.
    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.0.try_reserve_exact(additional)
    }

    /// Shrinks the capacity of the vector as much as possible.
    pub fn shrink_to_fit(&mut self) {
        self.0.shrink_to_fit();
    }

    /// Shrinks the capacity of the vector to the minimum allowed capacity.
    /// Note that this is a safe operation because capacity is guaranteed to be non-zero.
    pub fn shrink_to(&mut self, min_capacity: NonZeroUsize) {
        self.0.shrink_to(min_capacity.get());
    }

    /// Shortens the vector, keeping the first `len` elements and dropping the rest.
    /// Note that this is a safe operation because length is guaranteed to be non-zero.
    pub fn truncate(&mut self, len: NonZeroUsize) {
        self.0.truncate(len.get());
    }

    /// Shortens the vector, keeping the first `len` elements and dropping the rest.
    /// The truncated `Vec` is returned.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let vec = PopulatedVec::new(1);
    /// let vec = vec.truncate_into(0);
    /// assert_eq!(vec.len(), 0);
    /// ```
    ///
    /// # Returns
    /// A new `Vec` with the first `len` elements of the original vector.
    /// The returned `Vec` has no additional guarantees about its length.
    pub fn truncate_into(self, len: usize) -> Vec<T> {
        let mut vec = self.0;
        vec.truncate(len);
        vec
    }

    /// Extracts a slice containing the entire vector.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let vec = PopulatedVec::new(1);
    /// let slice = vec.as_slice();
    /// assert_eq!(slice.len().get(), 1);
    /// ```
    ///
    /// # Returns
    /// A `PopulatedSlice` containing the entire vector. The returned `PopulatedSlice` guarantees that it is non-empty.
    pub fn as_slice(&self) -> &PopulatedSlice<T> {
        self.0.deref().try_into().unwrap()
    }

    /// Extracts a mutable slice containing the entire vector.
    ///
    /// ```
    /// use populated::PopulatedVec;
    ///
    /// let mut vec = PopulatedVec::new(1);
    /// let slice = vec.as_mut_slice();
    /// assert_eq!(slice.len().get(), 1);
    /// ```
    ///
    /// # Returns
    /// A mutable `PopulatedSlice` containing the entire vector. The returned `PopulatedSlice` guarantees that it is non-empty.
    pub fn as_mut_slice(&mut self) -> &mut PopulatedSlice<T> {
        self.0.deref_mut().try_into().unwrap()
    }

    /// Removes an element from the vector and returns it along with the
    /// remaining `Vec`.
    ///
    /// The removed element is replaced by the last element of the vector.
    ///
    /// This does not preserve ordering, but is O(1). If you need to
    /// preserve the element order, use remove instead.
    ///
    /// # Panics
    ///
    /// Panics if the `index` is out of bounds.
    pub fn swap_remove(self, index: usize) -> (T, Vec<T>) {
        let mut vec = self.0;
        let removed = vec.swap_remove(index);
        (removed, vec)
    }

    /// Inserts an element at position index within the vector, shifting
    /// all elements after it to the right.
    pub fn insert(&mut self, index: usize, element: T) {
        self.0.insert(index, element);
    }

    /// Removes and returns the element at position index within the
    /// populated vector, shifting all elements after it to the left and
    /// returns the resulting `Vec`.
    ///
    /// Note: Because this shifts over the remaining elements, it has a
    /// worst-case performance of O(n). If you don’t need the order of
    /// elements to be preserved, use swap_remove instead. If you’d like
    /// to remove elements from the beginning of the Vec, consider using
    /// `VecDeque::pop_front` instead.
    pub fn remove(self, index: usize) -> (T, Vec<T>) {
        let mut vec = self.0;
        let removed = vec.remove(index);
        (removed, vec)
    }

    /// Retains only the elements specified by the predicate in the
    /// returned `Vec`.
    ///
    /// In other words, remove all elements `e` for which `f(&e)` returns
    /// false. This method operates in place, visiting each element
    /// exactly once in the original order, and preserves the order of
    /// the retained elements.
    pub fn retain(self, f: impl FnMut(&T) -> bool) -> Vec<T> {
        let mut vec = self.0;
        vec.retain(f);
        vec
    }

    /// Retains only the elements specified by the predicate in the returned
    /// `Vec`, passing a mutable reference to it.
    ///
    /// In other words, remove all elements `e` such that `f(&mut e)`
    /// returns false. This method operates in place, visiting each
    /// element exactly once in the original order, and preserves the
    /// order of the retained elements.
    pub fn retain_mut(self, f: impl FnMut(&mut T) -> bool) -> Vec<T> {
        let mut vec = self.0;
        vec.retain_mut(f);
        vec
    }

    /// Removes all but the first of consecutive elements in the vector that resolve to the same key.
    ///
    /// If the vector is sorted, this removes all duplicates.
    pub fn dedup_by_key<K: PartialEq>(&mut self, key: impl FnMut(&mut T) -> K) {
        self.0.dedup_by_key(key);
    }

    /// Removes all but the first of consecutive elements in the vector satisfying a given equality relation.
    ///
    /// The `same_bucket` function is passed references to two elements from the
    /// vector and must determine if the elements compare equal. The elements
    /// are passed in opposite order from their order in the slice, so if
    /// `same_bucket(a, b)` returns `true`, `a` is removed.
    ///
    /// If the vector is sorted, this removes all duplicates.
    pub fn dedup_by(&mut self, same_bucket: impl FnMut(&mut T, &mut T) -> bool) {
        self.0.dedup_by(same_bucket);
    }

    /// Moves all the elements of other into self, leaving other empty.
    pub fn append(&mut self, other: &mut Vec<T>) {
        self.0.append(other);
    }

    /// Unpopulates the vector, returning the underlying `Vec`.
    pub fn clear(self) -> Vec<T> {
        let mut vec = self.0;
        vec.clear();
        vec
    }

    pub fn split_off(&mut self, at: NonZeroUsize) -> Vec<T> {
        self.0.split_off(at.get())
    }

    pub fn split_into(self, at: usize) -> (Vec<T>, Vec<T>) {
        let mut vec = self.0;
        let other = vec.split_off(at);
        (vec, other)
    }

    // pub fn splice<I: IntoIterator<Item = T>>(
    //     &mut self,
    //     range: impl RangeBounds<usize>,
    //     replace_with: I,
    // ) -> Splice<'_, I::IntoIter> {
    //     self.0.splice(range, replace_with)
    // }
}
impl<T: Clone> PopulatedVec<T> {
    /// Resizes the vector in place so that `len` is equal to `new_len`.
    /// If `new_len` is greater than `len`, the vector is extended by the
    /// difference, with each additional slot filled with `value`. If `new_len`
    /// is less than `len`, the vector is simply truncated.
    pub fn resize(&mut self, new_len: NonZeroUsize, value: T) {
        self.0.resize(new_len.get(), value);
    }

    /// Resizes the vector in place so that `len` is equal to `new_len`.
    /// If `new_len` is greater than `len`, the vector is extended by the
    /// difference, with each additional slot filled with `value`. If `new_len`
    /// is less than `len`, the vector is simply truncated.
    ///
    /// This is a safe operation because this it returns the underlying `Vec` that can be empty.
    pub fn resize_into(self, new_len: usize, value: T) -> Vec<T> {
        let mut vec = self.0;
        vec.resize(new_len, value);
        vec
    }

    /// Clones and appends all elements in a slice to the Vec.
    ///
    /// Iterates over the slice other, clones each element, and then appends
    /// it to this Vec. The other slice is traversed in-order.
    ///
    /// Note that this function is same as extend except that it is
    /// specialized to work with slices instead. If and when Rust gets
    /// specialization this function will likely be deprecated (but still
    /// available).
    pub fn extend_from_slice(&mut self, other: &[T]) {
        self.0.extend_from_slice(other);
    }

    /// Copies elements from src range to the end of the vector.
    pub fn extend_from_within(&mut self, src: impl RangeBounds<usize>) {
        self.0.extend_from_within(src);
    }
}

impl<T: PartialEq> PopulatedVec<T> {
    /// Removes consecutive repeated elements in the vector according to the
    /// `PartialEq` trait implementation.
    ///
    /// If the vector is sorted, this removes all duplicates.
    pub fn dedup(&mut self) {
        self.0.dedup();
    }
}

impl<T> Index<usize> for PopulatedVec<T> {
    type Output = T;

    /// Performs the indexing (`container[index]`) operation.
    fn index(&self, index: usize) -> &Self::Output {
        &self.0[index]
    }
}

impl<T> Index<NonZeroUsize> for PopulatedVec<T> {
    type Output = T;

    /// Performs the indexing (`container[index]`) operation for a non-zero index.
    fn index(&self, index: NonZeroUsize) -> &Self::Output {
        &self.0[index.get() - 1]
    }
}

impl<T> IndexMut<usize> for PopulatedVec<T> {
    /// Performs the mutable indexing (`container[index]`) operation.
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.0[index]
    }
}

impl<T> Index<RangeFull> for PopulatedVec<T> {
    type Output = PopulatedSlice<T>;

    /// Performs the indexing (`container[..]`) operation to get a slice of the complete vector.
    fn index(&self, _: RangeFull) -> &Self::Output {
        self.deref()
    }
}

impl<T> IndexMut<RangeFull> for PopulatedVec<T> {
    /// Performs the mutable indexing (`container[..]`) operation to get a mutable reference to get a slice of the complete vector.
    fn index_mut(&mut self, _: RangeFull) -> &mut Self::Output {
        self.deref_mut()
    }
}

impl<T> PopulatedVec<T> {
    /// Returns a populated iterator over the elements of the vector.
    pub fn iter(&self) -> crate::slice::PopulatedIter<'_, T> {
        self.into_populated_iter()
    }

    /// Returns a mutable populated iterator over the elements of the vector.
    pub fn iter_mut(&mut self) -> slice::PopulatedIterMut<T> {
        self.into_populated_iter()
    }
}

impl<T> Extend<T> for PopulatedVec<T> {
    /// Extends the vector with the contents of an iterator.
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        self.0.extend(iter);
    }
}

impl<T, E> FromPopulatedIterator<Result<T, E>> for Result<PopulatedVec<T>, E> {
    fn from_populated_iter(iter: impl IntoPopulatedIterator<Item = Result<T, E>>) -> Self {
        let vec = Result::from_iter(iter.into_iter())?;
        Ok(PopulatedVec(vec))
    }
}

/// A macro pvec! to create a PopulatedVec with a list of elements.
///
/// # Examples
///
/// ```
/// use populated::pvec;
/// let vec = pvec![1, 2, 3];
/// assert_eq!(vec.len().get(), 3);
/// assert_eq!(vec.first(), &1);
/// assert_eq!(vec.last(), &3);
/// ```
///
/// Works with a single element
///
/// ```
/// use populated::pvec;
/// let vec = pvec![1];
/// assert_eq!(vec.len().get(), 1);
/// assert_eq!(vec.first(), &1);
/// assert_eq!(vec.last(), &1);
/// ```
///
/// Works with trailing comma
///
/// ```
/// use populated::pvec;
/// let vec = pvec![1, 2, 3,];
/// assert_eq!(vec.len().get(), 3);
/// assert_eq!(vec.first(), &1);
/// assert_eq!(vec.last(), &3);
/// ```
///
/// Fails to compile if no elements are provided
///
/// ```compile_fail
/// use populated::pvec;
/// // This will result in a compile-time error. Test should pass if the code fails to compile.
/// let vec = pvec![];
/// ```
#[macro_export]
macro_rules! pvec {
    () => {
        compile_error!("PopulatedVec requires at least one element");
    };
    ($first: expr $(,)?) => {
        $crate::PopulatedVec::new($first)
    };
    ($first:expr $(, $item:expr)+ $(,)? ) => ($crate::PopulatedVec::from_first_and_rest_array($first, [$($item),*]));
}

#[derive(PartialEq, PartialOrd, Eq, Ord, Debug)]
#[repr(transparent)]
pub struct PopulatedSlice<T>([T]);

impl<'a, T> From<&'a PopulatedSlice<T>> for &'a [T] {
    /// Convert a PopulatedSlice to a slice.
    fn from(populated_slice: &PopulatedSlice<T>) -> &[T] {
        &populated_slice.0
    }
}

impl<'a, T> From<&'a mut PopulatedSlice<T>> for &'a mut [T] {
    /// Convert a mutable PopulatedSlice to a mutable slice.
    fn from(populated_slice: &mut PopulatedSlice<T>) -> &mut [T] {
        &mut populated_slice.0
    }
}

#[derive(Debug)]
pub struct UnpopulatedError;

impl<'a, T> TryFrom<&'a [T]> for &'a PopulatedSlice<T> {
    type Error = UnpopulatedError;

    /// Convert a slice to a PopulatedSlice. If the slice is empty, an error is returned.
    /// If the slice is not empty, a reference to the PopulatedSlice is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use populated::PopulatedSlice;
    /// use std::convert::TryFrom;
    ///
    /// let slice: &[u64] = &[1, 2, 3];
    /// let populated_slice: &PopulatedSlice<u64> = TryFrom::try_from(slice).unwrap();
    /// assert_eq!(populated_slice.len().get(), 3);
    /// ```
    ///
    /// ```
    /// use populated::{PopulatedSlice, UnpopulatedError};
    /// use std::convert::TryFrom;
    ///
    /// let slice: &[u64] = &[];
    /// let populated_slice: Result<&PopulatedSlice<u64>, UnpopulatedError> = TryFrom::try_from(slice);
    /// assert!(populated_slice.is_err());
    /// ```
    fn try_from(slice: &'a [T]) -> Result<&'a PopulatedSlice<T>, Self::Error> {
        if slice.is_empty() {
            Err(UnpopulatedError)
        } else {
            Ok(unsafe { &*(slice as *const [T] as *const PopulatedSlice<T>) })
        }
    }
}

impl<'a, T> TryFrom<&'a mut [T]> for &'a mut PopulatedSlice<T> {
    type Error = UnpopulatedError;

    fn try_from(slice: &'a mut [T]) -> Result<&'a mut PopulatedSlice<T>, Self::Error> {
        if slice.is_empty() {
            Err(UnpopulatedError)
        } else {
            Ok(unsafe { &mut *(slice as *mut [T] as *mut PopulatedSlice<T>) })
        }
    }
}

impl<T> Index<usize> for PopulatedSlice<T> {
    type Output = T;

    /// Index into the populated slice.
    fn index(&self, index: usize) -> &Self::Output {
        &self.0[index]
    }
}

impl<T> IndexMut<usize> for PopulatedSlice<T> {
    /// Index into the populated slice mutably.
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.0[index]
    }
}

impl<T> Index<RangeFull> for PopulatedSlice<T> {
    type Output = PopulatedSlice<T>;
    fn index(&self, _index: RangeFull) -> &Self::Output {
        self
    }
}

impl<T> IndexMut<RangeFull> for PopulatedSlice<T> {
    fn index_mut(&mut self, _index: RangeFull) -> &mut Self::Output {
        self
    }
}

impl<T> Index<RangeToInclusive<usize>> for PopulatedSlice<T> {
    type Output = PopulatedSlice<T>;
    fn index(&self, index: RangeToInclusive<usize>) -> &Self::Output {
        TryFrom::try_from(&self.0[..=index.end]).unwrap() // unwrap is safe because the slice is populated
    }
}

impl<T> IndexMut<RangeToInclusive<usize>> for PopulatedSlice<T> {
    fn index_mut(&mut self, index: RangeToInclusive<usize>) -> &mut Self::Output {
        TryFrom::try_from(&mut self.0[..=index.end]).unwrap() // unwrap is safe because the slice is populated
    }
}

impl<T> Index<RangeTo<NonZeroUsize>> for PopulatedSlice<T> {
    type Output = PopulatedSlice<T>;
    fn index(&self, index: RangeTo<NonZeroUsize>) -> &Self::Output {
        TryFrom::try_from(&self.0[..index.end.get()]).unwrap() // unwrap is safe because the slice is populated
    }
}

impl<T> IndexMut<RangeTo<NonZeroUsize>> for PopulatedSlice<T> {
    fn index_mut(&mut self, index: RangeTo<NonZeroUsize>) -> &mut Self::Output {
        TryFrom::try_from(&mut self.0[..index.end.get()]).unwrap() // unwrap is safe because the slice is populated
    }
}

impl<T> PopulatedSlice<T> {
    /// Returns a populated iterator over the slice.
    pub fn iter(&self) -> slice::PopulatedIter<T> {
        self.into_populated_iter()
    }

    /// Returns a mutable populated iterator over the slice.
    pub fn iter_mut(&mut self) -> slice::PopulatedIterMut<T> {
        self.into_populated_iter()
    }

    /// Returns the length of the populated slice.
    ///
    /// ```
    /// use populated::PopulatedSlice;
    /// use std::num::NonZeroUsize;
    ///
    /// let slice: &[u64] = &[1, 2, 3];
    /// let slice: &PopulatedSlice<u64> = TryFrom::try_from(slice).unwrap();
    /// assert_eq!(slice.len(), NonZeroUsize::new(3).unwrap());
    /// ```
    pub fn len(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.len()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedSlice
    }

    /// Returns the first element of the populated slice.
    pub fn first(&self) -> &T {
        self.0.first().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedSlice
    }

    /// Returns a mutable pointer to the first element of the populated
    /// slice.
    pub fn first_mut(&mut self) -> &mut T {
        self.0.first_mut().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedSlice
    }

    /// Returns the first and all the rest of the elements of the populated slice.
    /// Note that the returned slice can be empty. It is not a PopulatedSlice.
    pub fn split_first(&self) -> (&T, &[T]) {
        self.0.split_first().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedSlice
    }

    /// Returns the first and all the rest of the elements of the populated slice. The returned
    /// first element and the rest of the elements are mutable.
    /// Note that the returned slice can be empty. It is not a PopulatedSlice.
    pub fn split_first_mut(&mut self) -> (&mut T, &mut [T]) {
        self.0.split_first_mut().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedSlice
    }

    /// Returns the last and all the rest of the elements of the populated slice.
    /// Note that the returned slice can be empty. It is not a PopulatedSlice.
    pub fn split_last(&self) -> (&T, &[T]) {
        self.0.split_last().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedSlice
    }

    /// Returns the mutable last and all the rest of the elements of the populated slice as a mutable slice.
    /// Note that the returned slice can be empty. It is not a PopulatedSlice.
    pub fn split_last_mut(&mut self) -> (&mut T, &mut [T]) {
        self.0.split_last_mut().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedSlice
    }

    /// Returns the last element of the populated slice.
    pub fn last(&self) -> &T {
        self.0.last().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedSlice
    }

    /// Returns a mutable reference to the last item in the populated slice.
    pub fn last_mut(&mut self) -> &mut T {
        self.0.last_mut().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedSlice
    }

    /// Swaps two elements in the slice.
    ///
    /// If a equals to b, it’s guaranteed that elements won’t change
    /// value.
    pub fn swap(&mut self, i: usize, j: usize) {
        self.0.swap(i, j);
    }

    /// Reverses the order of elements in the slice, in place.
    pub fn reverse(&mut self) {
        self.0.reverse();
    }

    /// Returns a reference to an element or subslice depending on the type of
    /// index. Since mid is a NonZeroUsize, it is guaranteed that the first slice is
    /// populated.
    pub fn split_at_populated(&self, mid: NonZeroUsize) -> (&PopulatedSlice<T>, &[T]) {
        let (left, right) = self.0.split_at(mid.get());
        (
            unsafe { &*(left as *const [T] as *const PopulatedSlice<T>) },
            right,
        )
    }

    /// Divides one slice into two at an index.
    ///
    /// The first will contain all indices from `[0, mid)` (excluding the
    /// index `mid` itself) and the second will contain all indices from
    /// `[mid, len)` (excluding the index `len` itself).
    pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
        self.0.split_at(mid)
    }

    /// Returns a mutable reference to an element or subslice depending on the
    /// type of index. Since mid is a NonZeroUsize, it is guaranteed that the first slice is
    /// populated.
    pub fn split_at_mut_populated(
        &mut self,
        mid: NonZeroUsize,
    ) -> (&mut PopulatedSlice<T>, &mut [T]) {
        let (left, right) = self.0.split_at_mut(mid.get());
        (
            unsafe { &mut *(left as *mut [T] as *mut PopulatedSlice<T>) },
            right,
        )
    }

    /// Divides one mutable slice into two at an index.
    ///
    /// The first will contain all indices from `[0, mid)` (excluding the
    /// index `mid` itself) and the second will contain all indices from
    /// `[mid, len)` (excluding the index `len` itself).
    pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
        self.0.split_at_mut(mid)
    }

    /// Binary searches this populated slice with a comparator function.
    ///
    /// The comparator function should return an order code that indicates
    /// whether its argument is `Less`, `Equal` or `Greater` the desired target. If
    /// the slice is not sorted or if the comparator function does not
    /// implement an order consistent with the sort order of the underlying
    /// slice, the returned result is unspecified and meaningless.
    ///
    /// If the value is found then Result::Ok is returned, containing the
    /// index of the matching element. If there are multiple matches, then any
    /// one of the matches could be returned. The index is chosen
    /// deterministically, but is subject to change in future versions of
    /// Rust. If the value is not found then Result::Err is returned,
    /// containing the index where a matching element could be inserted
    /// while maintaining sorted order.
    ///
    /// See also `binary_search`, `binary_search_by_key`, and `partition_point`.
    pub fn binary_search_by(&self, f: impl FnMut(&T) -> Ordering) -> Result<usize, usize> {
        self.0.binary_search_by(f)
    }

    /// Binary searches this populated slice with a key extraction function.
    ///
    /// Assumes that the slice is sorted by the key, for instance with sort_by_key using the same key extraction function. If the slice is
    /// not sorted by the key, the returned result is unspecified and meaningless.
    ///
    /// If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches, then
    /// any one of the matches could be returned. The index is chosen deterministically, but is subject to change in future versions of Rust.
    /// If the value is not found then Result::Err is returned, containing the index where a matching element could be inserted while
    /// maintaining sorted order.
    ///
    /// See also `binary_search`, `binary_search_by`, and `partition_point`.
    pub fn binary_search_by_key<K: Ord>(
        &self,
        key: &K,
        f: impl FnMut(&T) -> K,
    ) -> Result<usize, usize> {
        self.0.binary_search_by_key(key, f)
    }

    /// Sorts the populated slice with a comparator function, but might not preserve the order of equal elements.
    ///
    /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and O(n \* log(n)) worst-case.
    ///
    /// The comparator function must define a total ordering for the elements in the slice. If the ordering is not total, the order of the
    /// elements is unspecified. An order is a total order if it is (for all a, b and c):
    ///
    /// - total and antisymmetric: exactly one of a < b, a == b or a > b is true, and
    /// - transitive, a < b and b < c implies a < c. The same must hold for both == and >.
    ///
    /// For example, while f64 doesn’t implement Ord because NaN != NaN, we can use partial_cmp as our sort function when we know the slice
    /// doesn’t contain a NaN.
    pub fn sort_unstable_by(&mut self, f: impl FnMut(&T, &T) -> Ordering) {
        self.0.sort_unstable_by(f);
    }

    /// Sorts the populated slice with a key extraction function, but might not preserve the order of equal elements.
    ///
    /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and O(m \* n \* log(n)) worst-case,
    /// where the key function is O(m)
    pub fn sort_unstable_by_key<K: Ord>(&mut self, f: impl FnMut(&T) -> K) {
        self.0.sort_unstable_by_key(f);
    }

    pub fn select_nth_unstable_by(
        &mut self,
        index: usize,
        compare: impl FnMut(&T, &T) -> Ordering,
    ) -> (&mut [T], &mut T, &mut [T]) {
        self.0.select_nth_unstable_by(index, compare)
    }

    pub fn select_nth_unstable_by_key<K: Ord>(
        &mut self,
        index: usize,
        key: impl FnMut(&T) -> K,
    ) -> (&mut [T], &mut T, &mut [T]) {
        self.0.select_nth_unstable_by_key(index, key)
    }

    /// Rotates the slice in-place such that the first mid elements of
    /// the slice move to the end while the last `self.len() - mid`
    /// elements move to the front. After calling `rotate_left`, the
    /// element previously at index `mid` will become the first element in
    /// the slice.
    pub fn rotate_left(&mut self, mid: usize) {
        self.0.rotate_left(mid);
    }

    /// Rotates the slice in-place such that the first `self.len() - k`
    /// elements of the slice move to the end while the last `k` elements
    /// move to the front. After calling `rotate_right`, the element
    /// previously at index `self.len() - k` will become the first
    /// element in the slice.
    pub fn rotate_right(&mut self, mid: usize) {
        self.0.rotate_right(mid);
    }

    /// Fills self with elements returned by calling a closure repeatedly.
    ///
    /// This method uses a closure to create new values. If you’d rather
    /// `Clone` a given value, use `fill`. If you want to use the
    /// `Default` trait to generate values, you can pass
    /// `Default::default` as the argument.
    pub fn fill_with(&mut self, f: impl FnMut() -> T) {
        self.0.fill_with(f);
    }

    /// Swaps all elements in self with those in other.
    ///
    /// The length of other must be the same as self.
    pub fn swap_with_slice(&mut self, other: &mut PopulatedSlice<T>) {
        self.0.swap_with_slice(&mut other.0);
    }

    pub fn partition_point(&self, mut f: impl FnMut(&T) -> bool) -> usize {
        self.0.partition_point(|x| f(x))
    }

    /// Sorts the populated slice with a comparator function.
    ///
    /// This sort is stable (i.e., does not reorder equal elements) and
    /// O(n \* log(n)) worst-case.
    ///
    /// The comparator function must define a total ordering for the
    /// elements in the slice. If the ordering is not total, the order of
    /// the elements is unspecified. An order is a total order if it is
    /// (for all `a`, `b` and `c`):
    ///
    /// - total and antisymmetric: exactly one of `a < b`, `a == b` or
    ///   `a > b` is true, and
    /// - transitive, `a < b` and `b < c` implies `a < c`. The same must
    ///   hold for both `==` and `>`.
    ///
    /// For example, while `f64` doesn’t implement `Ord` because `NaN != NaN`,
    /// we can use `partial_cmp` as our sort function when we know the
    /// slice doesn’t contain a `NaN`.
    pub fn sort_by(&mut self, compare: impl FnMut(&T, &T) -> Ordering) {
        self.0.sort_by(compare);
    }

    /// Sorts the slice with a key extraction function.
    ///
    /// This sort is stable (i.e., does not reorder equal elements) and
    /// O(m \* n \* log(n)) worst-case, where the key function is O(m).
    ///
    /// For expensive key functions (e.g. functions that are not simple
    /// property accesses or basic operations), `sort_by_cached_key` is
    /// likely to be significantly faster, as it does not recompute
    /// element keys.
    ///
    /// When applicable, unstable sorting is preferred because it is
    /// generally faster than stable sorting and it doesn’t allocate
    /// auxiliary memory. See `sort_unstable_by_key`.
    pub fn sort_by_key<K: Ord>(&mut self, key: impl FnMut(&T) -> K) {
        self.0.sort_by_key(key);
    }

    /// Sorts the slice with a key extraction function.
    ///
    /// During sorting, the key function is called at most once per
    /// element, by using temporary storage to remember the results of
    /// key evaluation. The order of calls to the key function is
    /// unspecified and may change in future versions of the standard
    /// library.
    ///
    /// This sort is stable (i.e., does not reorder equal elements) and
    /// O(m \* n + n \* log(n)) worst-case, where the key function is
    /// O(m).
    ///
    /// For simple key functions (e.g., functions that are property accesses
    /// or basic operations), `sort_by_key` is likely to be faster.
    pub fn sort_by_cached_key<K: Ord>(&mut self, key: impl FnMut(&T) -> K) {
        self.0.sort_by_cached_key(key);
    }
}

impl<T: Clone> PopulatedSlice<T> {
    pub fn fill(&mut self, value: T) {
        self.0.fill(value);
    }

    /// Copies the elements from src into self.
    ///
    /// The length of src must be the same as self.
    pub fn clone_from_slice(&mut self, src: &PopulatedSlice<T>) {
        self.0.clone_from_slice(&src.0);
    }

    /// Copies `self` into a new `Vec`.
    pub fn to_vec(&self) -> PopulatedVec<T> {
        PopulatedVec(self.0.to_vec())
    }
}

impl<T: Copy> PopulatedSlice<T> {
    /// Copies all elements from src into self, using a memcpy.
    ///
    /// The length of src must be the same as self.
    ///
    /// If T does not implement Copy, use clone_from_slice.
    pub fn copy_from_slice(&mut self, src: &PopulatedSlice<T>) {
        self.0.copy_from_slice(&src.0);
    }

    /// Copies elements from one part of the slice to another part of itself, using a memmove.
    ///
    /// `src` is the range within `self` to copy from. `dest` is the starting
    /// index of the range within self to copy to, which will have the same
    /// length as src. The two ranges may overlap. The ends of the two ranges
    /// must be less than or equal to `self.len()`.
    pub fn copy_within(&mut self, src: impl RangeBounds<usize>, dest: usize) {
        self.0.copy_within(src, dest);
    }

    pub fn repeat(&self, n: NonZeroUsize) -> PopulatedVec<T> {
        PopulatedVec(self.0.repeat(n.get()))
    }
}

impl<T: PartialEq> PopulatedSlice<T> {
    /// Returns true if the slice contains an element with the given
    /// value.
    ///
    /// This operation is O(n).
    ///
    /// Note that if you have a sorted slice, `binary_search` may be
    /// faster.
    pub fn contains(&self, x: &T) -> bool {
        self.0.contains(x)
    }

    /// Returns true if needle is a prefix of the slice or equal to the
    /// slice.
    pub fn starts_with(&self, needle: &[T]) -> bool {
        self.0.starts_with(needle)
    }

    /// Returns true if needle is a suffix of the slice or equal to the
    /// slice.
    pub fn ends_with(&self, needle: &[T]) -> bool {
        self.0.ends_with(needle)
    }
}

impl<T: Ord> PopulatedSlice<T> {
    /// Binary searches this slice for a given element. If the slice is not
    /// sorted, the returned result is unspecified and meaningless.
    ///
    /// If the value is found then `Result::Ok` is returned, containing the
    /// index of the matching element. If there are multiple matches, then
    /// any one of the matches could be returned. The index is chosen
    /// deterministically, but is subject to change in future versions of
    /// Rust. If the value is not found then Result::Err is returned,
    /// containing the index where a matching element could be inserted while
    /// maintaining sorted order.
    ///
    /// See also `binary_search_by`, `binary_search_by_key`, and
    /// `partition_point`.
    pub fn binary_search(&self, x: &T) -> Result<usize, usize> {
        self.0.binary_search(x)
    }

    /// Sorts the slice, but might not preserve the order of equal elements.
    ///
    /// This sort is unstable (i.e., may reorder equal elements),
    /// in-place (i.e., does not allocate), and O(n * log(n)) worst-case.
    pub fn sort_unstable(&mut self) {
        self.0.sort_unstable();
    }

    pub fn select_nth_unstable(&mut self, index: usize) {
        self.0.select_nth_unstable(index);
    }

    /// Sorts the slice.
    ///
    /// This sort is stable (i.e., does not reorder equal elements) and
    /// $O(n * log(n))$ worst-case.
    ///
    /// When applicable, unstable sorting is preferred because it is
    /// generally faster than stable sorting and it doesn’t allocate
    /// auxiliary memory. See `sort_unstable`.
    pub fn sort(&mut self) {
        self.0.sort();
    }
}

impl PopulatedSlice<u8> {
    /// Checks if all bytes in this slice are within the ASCII range.
    pub const fn is_ascii(&self) -> bool {
        self.0.is_ascii()
    }
}

impl<T> Borrow<PopulatedSlice<T>> for PopulatedVec<T> {
    fn borrow(&self) -> &PopulatedSlice<T> {
        let slice: &[T] = self.0.deref();
        unsafe { &*(slice as *const [T] as *const PopulatedSlice<T>) }
    }
}

impl<T> BorrowMut<PopulatedSlice<T>> for PopulatedVec<T> {
    fn borrow_mut(&mut self) -> &mut PopulatedSlice<T> {
        let slice: &mut [T] = self.0.deref_mut();
        unsafe { &mut *(slice as *mut [T] as *mut PopulatedSlice<T>) }
    }
}

impl<T: Clone> From<&PopulatedSlice<T>> for PopulatedVec<T> {
    fn from(value: &PopulatedSlice<T>) -> Self {
        PopulatedVec(value.0.to_vec())
    }
}

impl<T: Clone> From<&mut PopulatedSlice<T>> for PopulatedVec<T> {
    fn from(value: &mut PopulatedSlice<T>) -> Self {
        PopulatedVec(value.0.to_vec())
    }
}

impl<T> Deref for PopulatedVec<T> {
    type Target = PopulatedSlice<T>;

    fn deref(&self) -> &Self::Target {
        let slice: &[T] = &self.0;
        unsafe { &*(slice as *const [T] as *const PopulatedSlice<T>) }
    }
}

impl<T> DerefMut for PopulatedVec<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        let slice: &mut [T] = &mut self.0;
        unsafe { &mut *(slice as *mut [T] as *mut PopulatedSlice<T>) }
    }
}

impl<T> AsRef<PopulatedSlice<T>> for PopulatedVec<T> {
    fn as_ref(&self) -> &PopulatedSlice<T> {
        self
    }
}

impl<T> AsMut<PopulatedSlice<T>> for PopulatedVec<T> {
    fn as_mut(&mut self) -> &mut PopulatedSlice<T> {
        self
    }
}

impl<T: Clone> ToOwned for PopulatedSlice<T> {
    type Owned = PopulatedVec<T>;

    fn to_owned(&self) -> Self::Owned {
        self.to_vec()
    }
}

impl<'a, T: Clone> From<&'a PopulatedSlice<T>> for Cow<'a, PopulatedSlice<T>> {
    fn from(slice: &'a PopulatedSlice<T>) -> Self {
        Cow::Borrowed(slice)
    }
}

/// A populated double-ended queue implemented with a growable ring
/// buffer. This type is guaranteed to contain at least one element, so
/// the underlying `VecDeque` is guaranteed to be non-empty.
#[derive(PartialEq, PartialOrd, Eq, Ord, Clone, Debug)]
pub struct PopulatedVecDeque<T>(VecDeque<T>);

impl<T> Extend<T> for PopulatedVecDeque<T> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        self.0.extend(iter);
    }
}

impl<T> From<PopulatedVecDeque<T>> for VecDeque<T> {
    fn from(populated_vec_deque: PopulatedVecDeque<T>) -> VecDeque<T> {
        populated_vec_deque.0
    }
}

impl<T> From<PopulatedVec<T>> for PopulatedVecDeque<T> {
    fn from(populated_vec: PopulatedVec<T>) -> PopulatedVecDeque<T> {
        PopulatedVecDeque(populated_vec.0.into())
    }
}

impl<T> TryFrom<VecDeque<T>> for PopulatedVecDeque<T> {
    type Error = VecDeque<T>;

    fn try_from(vec_deque: VecDeque<T>) -> Result<PopulatedVecDeque<T>, Self::Error> {
        if vec_deque.is_empty() {
            Err(vec_deque)
        } else {
            Ok(PopulatedVecDeque(vec_deque))
        }
    }
}

impl<T> PopulatedVecDeque<T> {
    /// Creates a singleton populated deque i.e. a deque with a single element.
    pub fn new(value: T) -> PopulatedVecDeque<T> {
        PopulatedVecDeque(VecDeque::from(vec![value]))
    }

    /// Creates a populated deque with a single element and space for at
    /// least `capacity` elements.
    pub fn with_capacity(capacity: NonZeroUsize, value: T) -> PopulatedVecDeque<T> {
        let mut vec_deque = VecDeque::with_capacity(capacity.get());
        vec_deque.push_back(value);
        PopulatedVecDeque(vec_deque)
    }

    /// Creates a populated deque with the given element inserted at the specified index.
    ///
    /// ```
    /// use std::collections::VecDeque;
    /// use std::num::NonZeroUsize;
    /// use populated::PopulatedVecDeque;
    ///
    /// let vec_deque = vec![1].into();
    /// let vec_deque = PopulatedVecDeque::inserted(vec_deque, 0, 2);
    /// assert_eq!(vec_deque.get(0), Some(&2));
    /// assert_eq!(vec_deque.get(1), Some(&1));
    /// ```
    pub fn inserted(mut vec_deque: VecDeque<T>, index: usize, value: T) -> PopulatedVecDeque<T> {
        vec_deque.insert(index, value);
        PopulatedVecDeque(vec_deque)
    }

    /// Provides a reference to the element at the given index.
    ///
    /// Element at index 0 is the front of the queue.
    pub fn get(&self, index: usize) -> Option<&T> {
        self.0.get(index)
    }

    /// Provides a mutable reference to the element at the given index.
    ///
    /// Element at index 0 is the front of the queue.
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        self.0.get_mut(index)
    }

    /// Swaps elements at indices i and j.
    ///
    /// `i` and `j` may be equal.
    ///
    /// Element at index 0 is the front of the queue.
    pub fn swap(&mut self, i: usize, j: usize) {
        self.0.swap(i, j);
    }

    pub fn into_inner(self) -> VecDeque<T> {
        self.0
    }

    /// Constructs a `PopulatedVecDeque` from a `VecDeque` by pushing back a
    /// single element.
    ///
    /// ```
    /// use std::collections::VecDeque;
    /// use std::num::NonZeroUsize;
    /// use populated::PopulatedVecDeque;
    ///
    /// let vec_deque = VecDeque::from([1, 2, 3]);
    /// let populated_vec_deque = PopulatedVecDeque::pushed_back(vec_deque, 42);
    /// assert_eq!(populated_vec_deque.len(), NonZeroUsize::new(4).unwrap());
    /// assert_eq!(populated_vec_deque.back(), &42);
    /// ```
    pub fn pushed_back(mut vec_deque: VecDeque<T>, value: T) -> PopulatedVecDeque<T> {
        vec_deque.push_back(value);
        PopulatedVecDeque(vec_deque)
    }

    /// Appends an element to the back of the deque.
    pub fn push_back(&mut self, value: T) {
        self.0.push_back(value);
    }

    /// Constructs a `PopulatedVecDeque` from a `VecDeque` by pushing front a
    /// single element.
    ///
    /// ```
    /// use std::collections::VecDeque;
    /// use std::num::NonZeroUsize;
    /// use populated::PopulatedVecDeque;
    ///
    /// let vec_deque = VecDeque::from([1, 2, 3]);
    /// let populated_vec_deque = PopulatedVecDeque::pushed_front(42, vec_deque);
    /// assert_eq!(populated_vec_deque.len(), NonZeroUsize::new(4).unwrap());
    /// assert_eq!(populated_vec_deque.front(), &42);
    /// ```
    pub fn pushed_front(value: T, mut vec_deque: VecDeque<T>) -> PopulatedVecDeque<T> {
        vec_deque.push_front(value);
        PopulatedVecDeque(vec_deque)
    }

    /// Prepends an element to the deque.
    pub fn push_front(&mut self, value: T) {
        self.0.push_front(value);
    }

    /// Removes the last element from the deque and returns it, along
    /// with the remaining deque.
    pub fn pop_back(self) -> (VecDeque<T>, T) {
        let mut vec_deque = self.0;
        let last = vec_deque.pop_back().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedVecDeque
        (vec_deque, last)
    }

    /// Removes the first element and returns it, along with the remaining deque.
    pub fn pop_front(self) -> (T, VecDeque<T>) {
        let mut vec_deque = self.0;
        let first = vec_deque.pop_front().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedVecDeque
        (first, vec_deque)
    }

    /// Provides a reference to the front element.
    pub fn front(&self) -> &T {
        self.0.front().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedVecDeque
    }

    /// Provides a mutable reference to the front element.
    pub fn front_mut(&mut self) -> &mut T {
        self.0.front_mut().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedVecDeque
    }

    /// Provides a reference to the back element.
    pub fn back(&self) -> &T {
        self.0.back().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedVecDeque
    }

    /// Provides a mutable reference to the back element.
    pub fn back_mut(&mut self) -> &mut T {
        self.0.back_mut().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedVecDeque
    }

    /// Returns number of elements in the populated deque.
    pub fn len(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.len()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedVecDeque
    }

    /// Returns the number of elements the deque can hold without
    /// reallocating.
    pub fn capacity(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.capacity()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedVecDeque
    }

    pub fn reserve(&mut self, additional: usize) {
        self.0.reserve(additional);
    }

    pub fn reserve_exact(&mut self, additional: usize) {
        self.0.reserve_exact(additional);
    }

    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.0.try_reserve(additional)
    }

    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.0.try_reserve_exact(additional)
    }

    pub fn shrink_to_fit(&mut self) {
        self.0.shrink_to_fit();
    }

    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.0.shrink_to(min_capacity);
    }

    pub fn truncate(&mut self, len: NonZeroUsize) {
        self.0.truncate(len.get());
    }

    /// Truncates the deque to the given length.
    pub fn truncate_into(self, len: usize) -> VecDeque<T> {
        let mut vec = self.0;
        vec.truncate(len);
        vec
    }

    /// Returns an iterator that yields references to the values.
    pub fn range(&self, range: impl RangeBounds<usize>) -> std::collections::vec_deque::Iter<T> {
        self.0.range(range)
    }

    /// Returns an iterator that allows modifying each value.
    /// The iterator yields mutable references to the values.
    pub fn range_mut(
        &mut self,
        range: impl RangeBounds<usize>,
    ) -> std::collections::vec_deque::IterMut<T> {
        self.0.range_mut(range)
    }

    /// Clears the deque, removing all values.
    /// Returns the cleared deque that is not populated.
    pub fn clear(self) -> VecDeque<T> {
        let mut vec_deque = self.0;
        vec_deque.clear();
        vec_deque
    }

    // pub fn swap_remove_front(self, index: usize) -> (Option<T>, VecDeque<T>) {
    //     let mut vec_deque = self.0;
    //     let removed = vec_deque.swap_remove_front(index);
    //     (removed, vec_deque)
    // }

    // pub fn swap_remove_back(self, index: usize) -> (Option<T>, VecDeque<T>) {
    //     let mut vec_deque = self.0;
    //     let removed = vec_deque.swap_remove_back(index);
    //     (removed, vec_deque)
    // }

    /// Inserts an element at `index` within the deque, shifting all elements
    /// with indices greater than or equal to `index` towards the back.
    ///
    /// Element at index 0 is the front of the queue.
    pub fn insert(&mut self, index: usize, element: T) {
        self.0.insert(index, element);
    }

    /// Removes and returns the element at `index` from the deque. Whichever
    /// end is closer to the removal point will be moved to make room, and
    /// all the affected elements will be moved to new positions. Returns
    /// `None` if `index` is out of bounds.
    ///
    /// Element at index 0 is the front of the queue.
    pub fn remove(self, index: usize) -> (Option<T>, VecDeque<T>) {
        let mut vec_deque = self.0;
        let removed = vec_deque.remove(index);
        (removed, vec_deque)
    }

    /// Splits the deque into two at the given index.
    ///
    /// Returns a newly allocated VecDeque. self contains elements
    /// `[0, at)`, and the returned deque contains elements `[at, len)`.
    ///
    /// `at` must be non-zero to ensure that the deque being mutated stays populated.
    ///
    /// Note that the capacity of self does not change.
    ///
    /// Element at index 0 is the front of the queue.
    pub fn split_off(&mut self, at: NonZeroUsize) -> VecDeque<T> {
        self.0.split_off(at.get())
    }

    pub fn split_into(self, at: usize) -> (VecDeque<T>, VecDeque<T>) {
        let mut vec_deque = self.0;
        let other = vec_deque.split_off(at);
        (vec_deque, other)
    }

    /// Moves all the elements of other into self, leaving other empty.
    pub fn append(&mut self, other: &mut VecDeque<T>) {
        self.0.append(other);
    }

    /// Retains only the elements specified by the predicate.
    ///
    /// In other words, remove all elements e for which `f(&e)` returns
    /// false. This method operates in place on the underlying `VecDeque`, visiting each element
    /// exactly once in the original order, and preserves the order of
    /// the retained elements.
    ///
    /// Since there is no guarantee that all elements will not be removed,
    /// the method returns the underlying VecDeque.
    pub fn retain(self, f: impl FnMut(&T) -> bool) -> VecDeque<T> {
        let mut vec_deque = self.0;
        vec_deque.retain(f);
        vec_deque
    }

    /// Retains only the elements specified by the predicate.
    ///
    /// In other words, remove all elements e for which `f(&e)` returns
    /// false. This method operates in place on the underlying `VecDeque`, visiting each element
    /// exactly once in the original order, and preserves the order of
    /// the retained elements.
    ///
    /// Since there is no guarantee that all elements will not be removed,
    /// the method returns the underlying VecDeque.
    pub fn retain_mut(self, f: impl FnMut(&mut T) -> bool) -> VecDeque<T> {
        let mut vec_deque = self.0;
        vec_deque.retain_mut(f);
        vec_deque
    }

    pub fn resize_with(&mut self, new_len: NonZeroUsize, f: impl FnMut() -> T) {
        self.0.resize_with(new_len.get(), f);
    }

    pub fn resize_with_into(self, new_len: usize, f: impl FnMut() -> T) -> VecDeque<T> {
        let mut vec_deque = self.0;
        vec_deque.resize_with(new_len, f);
        vec_deque
    }

    /// Rotates the double-ended queue `n` places to the left.
    ///
    /// Equivalently,
    ///
    /// - Rotates item `n` into the first position.
    /// - Pops the first `n` items and pushes them to the end.
    /// - Rotates `len() - n` places to the right.
    pub fn rotate_left(&mut self, n: usize) {
        self.0.rotate_left(n);
    }

    /// Rotates the double-ended queue `n` places to the right.
    ///
    /// Equivalently,
    ///
    /// - Rotates the first item into position `n`.
    /// - Pops the last `n` items and pushes them to the front.
    /// - Rotates `len() - n` places to the left.
    pub fn rotate_right(&mut self, n: usize) {
        self.0.rotate_right(n);
    }

    /// Binary searches this `PopulatedVecDeque` with a comparator
    /// function.
    ///
    /// The comparator function should return an order code that
    /// indicates whether its argument is `Less`, `Equal` or `Greater` the
    /// desired target. If the `PopulatedVecDeque` is not sorted or if
    /// the comparator function does not implement an order consistent
    /// with the sort order of the underlying `VecDeque`, the returned
    /// result is unspecified and meaningless.
    ///
    /// If the value is found then `Result::Ok` is returned, containing
    /// the index of the matching element. If there are multiple matches,
    /// then any one of the matches could be returned. If the value is
    /// not found then `Result::Err` is returned, containing the index
    /// where a matching element could be inserted while maintaining
    /// sorted order.
    ///
    /// See also `binary_search`, `binary_search_by_key`, and
    /// `partition_point`.
    pub fn binary_search_by(&self, f: impl FnMut(&T) -> Ordering) -> Result<usize, usize> {
        self.0.binary_search_by(f)
    }

    /// Binary searches this `PopulatedVecDeque` with a key extraction
    /// function.
    ///
    /// Assumes that the deque is sorted by the key, for instance with
    /// `make_contiguous().sort_by_key()` using the same key extraction
    /// function. If the deque is not sorted by the key, the returned result
    /// is unspecified and meaningless.
    ///
    /// If the value is found then `Result::Ok` is returned, containing the
    /// index of the matching element. If there are multiple matches, then
    /// any one of the matches could be returned. If the value is not found
    /// then `Result::Err` is returned, containing the index where a matching
    /// element could be inserted while maintaining sorted order.
    ///
    /// See also `binary_search`, `binary_search_by`, and `partition_point`.
    pub fn binary_search_by_key<K: Ord>(
        &self,
        key: &K,
        f: impl FnMut(&T) -> K,
    ) -> Result<usize, usize> {
        self.0.binary_search_by_key(key, f)
    }

    pub fn partition_point(&self, predicate: impl FnMut(&T) -> bool) -> usize {
        self.0.partition_point(predicate)
    }
}

impl<T: PartialEq> PopulatedVecDeque<T> {
    /// Returns true if the deque contains an element equal to the given
    /// value.
    ///
    /// This operation is O(n).
    ///
    /// Note that if you have a sorted `PopulatedVecDeque`, `binary_search` may be
    /// faster.
    pub fn contains(&self, x: &T) -> bool {
        self.0.contains(x)
    }
}

impl<T: Ord> PopulatedVecDeque<T> {
    /// Binary searches this `PopulatedVecDeque` for a given element. If the `PopulatedVecDeque`
    /// is not sorted, the returned result is unspecified and meaningless.
    ///
    /// If the value is found then `Result::Ok` is returned, containing the
    /// index of the matching element. If there are multiple matches, then
    /// any one of the matches could be returned. If the value is not found
    /// then `Result::Err` is returned, containing the index where a matching
    /// element could be inserted while maintaining sorted order.
    ///
    /// See also `binary_search_by`, `binary_search_by_key`, and
    /// `partition_point`.
    pub fn binary_search(&self, x: &T) -> Result<usize, usize> {
        self.0.binary_search(x)
    }
}

impl<T: Clone> PopulatedVecDeque<T> {
    pub fn resize(&mut self, new_len: NonZeroUsize, value: T) {
        self.0.resize(new_len.get(), value);
    }

    pub fn resize_into(self, new_len: usize, value: T) -> VecDeque<T> {
        let mut vec_deque = self.0;
        vec_deque.resize(new_len, value);
        vec_deque
    }
}

impl<T: PartialEq> PartialEq<VecDeque<T>> for PopulatedVecDeque<T> {
    fn eq(&self, other: &VecDeque<T>) -> bool {
        self.0.eq(other)
    }
}

impl<T: PartialEq> PartialEq<PopulatedVecDeque<T>> for VecDeque<T> {
    fn eq(&self, other: &PopulatedVecDeque<T>) -> bool {
        self.eq(&other.0)
    }
}

impl<T> Index<usize> for PopulatedVecDeque<T> {
    type Output = T;

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

impl<T> IndexMut<usize> for PopulatedVecDeque<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.0[index]
    }
}

impl<T> Index<NonZeroUsize> for PopulatedVecDeque<T> {
    type Output = T;

    fn index(&self, index: NonZeroUsize) -> &Self::Output {
        &self.0[index.get() - 1]
    }
}

impl<T> IndexMut<NonZeroUsize> for PopulatedVecDeque<T> {
    fn index_mut(&mut self, index: NonZeroUsize) -> &mut Self::Output {
        &mut self.0[index.get() - 1]
    }
}

impl<T> PopulatedVecDeque<T> {
    pub fn iter(&self) -> vec_deque::PopulatedIter<T> {
        self.into_populated_iter()
    }

    pub fn iter_mut(&mut self) -> vec_deque::PopulatedIterMut<T> {
        self.into_populated_iter()
    }
}

/// An iterator that guaratees that there is at least one element.
pub trait PopulatedIterator: IntoIterator // to enable using in for loops
{
    /// Advances the iterator and returns the first value and a new iterator
    /// to the remaining values.
    fn next(self) -> (Self::Item, Self::IntoIter);

    /// Collects the iterator into a collection. Supports constructing
    /// collections that require a populated iterator.
    fn collect<C: FromPopulatedIterator<Self::Item>>(self) -> C
    where
        Self: Sized,
    {
        C::from_populated_iter(self)
    }

    /// Takes a closure and creates an iterator which calls that closure on
    /// each element. Preserves the populated property.
    fn map<B, F: FnMut(Self::Item) -> B>(self, f: F) -> iter::Map<Self, F>
    where
        Self: Sized,
    {
        iter::Map { iter: self, f }
    }

    /// Creates an iterator giving the current element count along with the
    /// element. Preserves the populated property.
    fn enumerate(self) -> iter::Enumerate<Self>
    where
        Self: Sized,
    {
        iter::Enumerate { iter: self }
    }

    /// Zips this iterator with another iterator to yield a new iterator of
    /// pairs. Preserves the populated property.
    fn zip<J>(self, other: J) -> iter::Zip<Self, J>
    where
        Self: Sized,
    {
        iter::Zip { iter: self, other }
    }

    /// Flattens a populated iterator of populated iteratorables into a single iterator. Preserves
    /// the populated property.
    fn flatten(self) -> iter::Flatten<Self>
    where
        Self: Sized,
        Self::Item: IntoPopulatedIterator,
    {
        iter::Flatten { iter: self }
    }

    /// Creates an iterator taking at most `n` elements from this iterator, where `n` is non-zero.
    /// Preserves the populated property.
    fn take(self, n: NonZeroUsize) -> iter::Take<Self>
    where
        Self: Sized,
    {
        iter::Take::new(self, n)
    }

    /// Creates an iterator that works like `map`, but flattens nested populated structure. Preserves the
    /// populated property.
    fn flat_map<B: IntoPopulatedIterator, F: FnMut(Self::Item) -> B>(
        self,
        f: F,
    ) -> iter::Flatten<iter::Map<Self, F>>
    where
        Self: Sized,
    {
        self.map(f).flatten()
    }

    /// Returns the maximum element of the iterator. Note that unlike the standard library, this
    /// method directly returns the maximum element instead of an `Option`. This is because this
    /// method is only available on populated iterators.
    fn max(self) -> Self::Item
    where
        Self::Item: Ord,
        Self: Sized,
    {
        self.into_iter().max().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedIterator
    }

    /// Returns the minimum element of the iterator.
    fn min(self) -> Self::Item
    where
        Self::Item: Ord,
        Self: Sized,
    {
        self.into_iter().min().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedIterator
    }

    /// Takes self populator and another iteratorable and creates a new iterator over both in sequence. Preserves the populated property.
    fn chain<I: IntoIterator<Item = Self::Item>>(self, other: I) -> iter::Chain<Self, I::IntoIter>
    where
        Self: Sized,
    {
        iter::Chain {
            prefix: self,
            iter: other.into_iter(),
        }
    }

    /// Reduces the iterator to a single value using a closure. Note that unlike the standard library,
    /// this method directly returns the reduced value instead of an `Option`. This is because this
    /// method is only available on populated iterators.
    fn reduce(self, f: impl FnMut(Self::Item, Self::Item) -> Self::Item) -> Self::Item
    where
        Self: Sized,
    {
        let (first, iter) = self.next();
        iter.fold(first, f)
    }

    /// Returns the element that gives the maximum value from the specified function. Note that unlike the standard library,
    /// this method directly returns the maximum element instead of an `Option`. This is because this
    /// method is only available on populated iterators.
    fn max_by_key<K: Ord>(self, f: impl FnMut(&Self::Item) -> K) -> Self::Item
    where
        Self: Sized,
    {
        self.into_iter().max_by_key(f).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedIterator
    }

    /// Returns the element that gives the maximum value with respect to the specified comparison function. Note that unlike the standard library,
    /// this method directly returns the maximum element instead of an `Option`. This is because this
    /// method is only available on populated iterators.
    fn max_by(self, compare: impl FnMut(&Self::Item, &Self::Item) -> Ordering) -> Self::Item
    where
        Self: Sized,
    {
        self.into_iter().max_by(compare).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedIterator
    }

    /// Returns the element that gives the minimum value from the specified function. Note that unlike the standard library,
    /// this method directly returns the minimum element instead of an `Option`. This is because this
    /// method is only available on populated iterators.
    fn min_by_key<K: Ord>(self, f: impl FnMut(&Self::Item) -> K) -> Self::Item
    where
        Self: Sized,
    {
        self.into_iter().min_by_key(f).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedIterator
    }

    /// Returns the element that gives the minimum value with respect to the specified comparison function. Note that unlike the standard library,
    /// this method directly returns the minimum element instead of an `Option`. This is because this
    /// method is only available on populated iterators.
    fn min_by(self, compare: impl FnMut(&Self::Item, &Self::Item) -> Ordering) -> Self::Item
    where
        Self: Sized,
    {
        self.into_iter().min_by(compare).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedIterator
    }

    fn eq<I: IntoIterator>(self, other: I) -> bool
    where
        Self::Item: PartialEq<I::Item>,
        Self: Sized,
    {
        self.into_iter().eq(other)
    }

    fn last(self) -> Self::Item
    where
        Self: Sized,
    {
        self.into_iter().last().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedIterator
    }

    fn rev(self) -> iter::Rev<Self>
    where
        Self: Sized,
    {
        iter::Rev { iter: self }
    }

    fn nth(self, n: usize) -> (Option<Self::Item>, Self::IntoIter)
    where
        Self: Sized,
    {
        let mut iter = self.into_iter();
        let item = iter.nth(n);
        (item, iter)
    }

    fn count(self) -> NonZeroUsize
    where
        Self: Sized,
    {
        NonZeroUsize::new(self.into_iter().count()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedIterator
    }
}

pub trait PopulatedDoubleEndedIterator: PopulatedIterator
where
    Self::IntoIter: DoubleEndedIterator,
{
    fn next_back(self) -> (Self::IntoIter, Self::Item);
}

pub mod iter {

    use std::num::NonZeroUsize;

    use crate::{IntoPopulatedIterator, PopulatedDoubleEndedIterator, PopulatedIterator};

    pub struct Map<I, F> {
        pub(crate) iter: I,
        pub(crate) f: F,
    }

    impl<I: PopulatedIterator, B, F: FnMut(I::Item) -> B> IntoIterator for Map<I, F> {
        type Item = B;
        type IntoIter = std::iter::Map<I::IntoIter, F>;

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

    impl<I: PopulatedIterator, F: FnMut(I::Item) -> O, O> PopulatedIterator for Map<I, F> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let (item, iter) = self.iter.next();
            ((self.f)(item), iter.map(self.f))
        }
    }

    impl<I: PopulatedDoubleEndedIterator, B, F: FnMut(I::Item) -> B> PopulatedDoubleEndedIterator
        for Map<I, F>
    where
        I::IntoIter: DoubleEndedIterator,
    {
        fn next_back(
            mut self,
        ) -> (
            <Self as IntoIterator>::IntoIter,
            <Self as IntoIterator>::Item,
        ) {
            let (iter, item) = self.iter.next_back();
            let item = (self.f)(item);
            let iter = iter.map(self.f);
            (iter, item)
        }
    }

    pub struct Enumerate<I> {
        pub(crate) iter: I,
    }

    impl<I: PopulatedIterator> IntoIterator for Enumerate<I> {
        type Item = (usize, I::Item);
        type IntoIter = std::iter::Enumerate<I::IntoIter>;

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

    impl<I: PopulatedIterator> PopulatedIterator for Enumerate<I> {
        fn next(self) -> ((usize, I::Item), Self::IntoIter) {
            let mut iter = self.into_iter();
            let (index, item) = iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedVec

            ((index, item), iter)
        }
    }

    pub struct Zip<I, J> {
        pub(crate) iter: I,
        pub(crate) other: J,
    }

    impl<I: PopulatedIterator, J: PopulatedIterator> IntoIterator for Zip<I, J> {
        type Item = (I::Item, J::Item);
        type IntoIter = std::iter::Zip<I::IntoIter, J::IntoIter>;

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

    impl<I: PopulatedIterator, J: PopulatedIterator> PopulatedIterator for Zip<I, J> {
        fn next(self) -> (Self::Item, Self::IntoIter) {
            let (x, iter) = self.iter.next();
            let (y, other) = self.other.next();
            ((x, y), iter.zip(other))
        }
    }

    pub struct Flatten<I> {
        pub(crate) iter: I,
    }

    impl<I: PopulatedIterator> IntoIterator for Flatten<I>
    where
        I::Item: IntoPopulatedIterator,
    {
        type Item = <I::Item as IntoIterator>::Item;
        type IntoIter = std::iter::Flatten<I::IntoIter>;

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

    impl<I: PopulatedIterator> PopulatedIterator for Flatten<I>
    where
        I::Item: IntoPopulatedIterator,
    {
        fn next(self) -> (Self::Item, Self::IntoIter) {
            let mut iter = self.into_iter();
            let item = iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedIterator contain impl IntoPopulatedIterator
            (item, iter)
        }
    }

    pub struct Take<I: PopulatedIterator> {
        iter: std::iter::Take<I::IntoIter>,
    }
    impl<I: PopulatedIterator> Take<I> {
        pub(crate) fn new(iter: I, n: NonZeroUsize) -> Self {
            Take {
                iter: iter.into_iter().take(n.get()),
            }
        }
    }

    impl<I: PopulatedIterator> IntoIterator for Take<I> {
        type Item = I::Item;
        type IntoIter = std::iter::Take<I::IntoIter>;

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

    impl<I: PopulatedIterator> PopulatedIterator for Take<I> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let item = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedIterator
            (item, self.iter)
        }
    }

    // TODO: Cycle

    pub struct Chain<P, I> {
        pub(crate) prefix: P,
        pub(crate) iter: I,
    }

    impl<P: PopulatedIterator, I: Iterator<Item = P::Item>> IntoIterator for Chain<P, I> {
        type Item = P::Item;
        type IntoIter = std::iter::Chain<P::IntoIter, I>;

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

    impl<P: PopulatedIterator, I: Iterator<Item = P::Item>> PopulatedIterator for Chain<P, I> {
        fn next(self) -> (Self::Item, Self::IntoIter) {
            let (item, prefix) = self.prefix.next();
            let iter = self.iter;
            (item, prefix.chain(iter))
        }
    }

    pub struct Rev<I> {
        pub(crate) iter: I,
    }

    fn switch<A, B>((a, b): (A, B)) -> (B, A) {
        (b, a)
    }

    impl<I: PopulatedIterator> IntoIterator for Rev<I>
    where
        I::IntoIter: DoubleEndedIterator,
    {
        type Item = I::Item;
        type IntoIter = std::iter::Rev<I::IntoIter>;

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

    impl<I: PopulatedDoubleEndedIterator> PopulatedIterator for Rev<I>
    where
        I::IntoIter: DoubleEndedIterator,
    {
        fn next(self) -> (Self::Item, Self::IntoIter) {
            switch(self.next_back())
        }
    }

    impl<I: PopulatedDoubleEndedIterator> PopulatedDoubleEndedIterator for Rev<I>
    where
        I::IntoIter: DoubleEndedIterator,
    {
        fn next_back(self) -> (Self::IntoIter, Self::Item) {
            switch(self.next())
        }
    }
}

/// Conversion into a `PopulatedIterator`.
///
/// This trait is used to convert a type into a `PopulatedIterator`.
///
/// # Examples
///
/// ```
/// use populated::{PopulatedVecDeque, IntoPopulatedIterator, PopulatedIterator};
///
/// let mut vec_deque = PopulatedVecDeque::new(1);
/// vec_deque.push_back(2);
/// vec_deque.push_back(3);
/// let populated_iter = vec_deque.into_populated_iter();
///
/// let (first, iter) = populated_iter.next();
/// assert_eq!(first, 1);
/// assert_eq!(iter.collect::<Vec<_>>(), [2, 3]);
/// ```
pub trait IntoPopulatedIterator: IntoIterator {
    type PopulatedIntoIter: PopulatedIterator<
        Item = <Self as IntoIterator>::Item,
        IntoIter = <Self as IntoIterator>::IntoIter,
    >;

    /// Converts the type into a `PopulatedIterator`.
    fn into_populated_iter(self) -> Self::PopulatedIntoIter;
}

impl<I: PopulatedIterator> IntoPopulatedIterator for I {
    type PopulatedIntoIter = Self;

    fn into_populated_iter(self) -> Self::PopulatedIntoIter {
        self
    }
}

/// A trait for types that may be unpopulated.
/// This trait is used to mark types that may be unpopulated.
/// This is used to allow for the conversion of a `PopulatedIterator` into a type that may be unpopulated.
pub trait PotentiallyUnpopulated {}

impl<T> PotentiallyUnpopulated for std::collections::VecDeque<T> {}
impl<T> PotentiallyUnpopulated for Vec<T> {}
impl<T> PotentiallyUnpopulated for std::collections::LinkedList<T> {}
impl<T> PotentiallyUnpopulated for std::collections::BinaryHeap<T> {}
impl<T> PotentiallyUnpopulated for std::collections::HashSet<T> {}
impl<T> PotentiallyUnpopulated for std::collections::BTreeSet<T> {}
impl<K, V> PotentiallyUnpopulated for std::collections::HashMap<K, V> {}
impl<K, V> PotentiallyUnpopulated for std::collections::BTreeMap<K, V> {}
impl PotentiallyUnpopulated for String {}

/// Conversion from a `PopulatedIterator`.
///
/// This trait is used to convert a `PopulatedIterator` into `Self`.
pub trait FromPopulatedIterator<T>: Sized {
    /// Converts a `PopulatedIterator` into `Self`.
    fn from_populated_iter(iter: impl IntoPopulatedIterator<Item = T>) -> Self;
}

impl<T> FromPopulatedIterator<T> for PopulatedVec<T> {
    fn from_populated_iter(iter: impl IntoPopulatedIterator<Item = T>) -> Self {
        PopulatedVec(Vec::from_populated_iter(iter))
    }
}

impl<T> FromPopulatedIterator<T> for PopulatedVecDeque<T> {
    fn from_populated_iter(iter: impl IntoPopulatedIterator<Item = T>) -> Self {
        PopulatedVecDeque(VecDeque::from_populated_iter(iter))
    }
}

impl<T: Eq + Hash> FromPopulatedIterator<T> for PopulatedHashSet<T> {
    fn from_populated_iter(iter: impl IntoPopulatedIterator<Item = T>) -> Self {
        PopulatedHashSet(HashSet::from_populated_iter(iter))
    }
}

impl<T: Ord> FromPopulatedIterator<T> for PopulatedBTreeSet<T> {
    fn from_populated_iter(iter: impl IntoPopulatedIterator<Item = T>) -> Self {
        PopulatedBTreeSet(BTreeSet::from_populated_iter(iter))
    }
}

impl<K: Eq + Hash, V> FromPopulatedIterator<(K, V)> for PopulatedHashMap<K, V> {
    fn from_populated_iter(iter: impl IntoPopulatedIterator<Item = (K, V)>) -> Self {
        PopulatedHashMap(HashMap::from_populated_iter(iter))
    }
}

impl<K: Ord, V> FromPopulatedIterator<(K, V)> for PopulatedBTreeMap<K, V> {
    fn from_populated_iter(iter: impl IntoPopulatedIterator<Item = (K, V)>) -> Self {
        PopulatedBTreeMap(BTreeMap::from_populated_iter(iter))
    }
}

impl<T: Ord> FromPopulatedIterator<T> for PopulatedBinaryHeap<T> {
    fn from_populated_iter(iter: impl IntoPopulatedIterator<Item = T>) -> Self {
        PopulatedBinaryHeap(BinaryHeap::from_populated_iter(iter))
    }
}

impl<E, C: FromIterator<E> + PotentiallyUnpopulated> FromPopulatedIterator<E> for C {
    fn from_populated_iter(iter: impl IntoPopulatedIterator<Item = E>) -> C {
        iter.into_iter().collect()
    }
}

pub mod vec {
    use super::*;
    pub struct PopulatedIntoIter<T> {
        iter: std::vec::IntoIter<T>,
    }
    impl<T> IntoIterator for PopulatedIntoIter<T> {
        type Item = T;
        type IntoIter = std::vec::IntoIter<T>;

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

    impl<T> PopulatedIterator for PopulatedIntoIter<T> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedVec
            (first, self.iter)
        }
    }

    impl<T> IntoIterator for PopulatedVec<T> {
        type Item = T;
        type IntoIter = std::vec::IntoIter<T>;

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

    impl<T> IntoPopulatedIterator for PopulatedVec<T> {
        type PopulatedIntoIter = vec::PopulatedIntoIter<T>;

        fn into_populated_iter(self) -> vec::PopulatedIntoIter<T> {
            vec::PopulatedIntoIter {
                iter: self.into_iter(),
            }
        }
    }
}
pub mod slice {
    use crate::{IntoPopulatedIterator, PopulatedIterator, PopulatedSlice, PopulatedVec};

    pub struct PopulatedIter<'a, T> {
        iter: std::slice::Iter<'a, T>,
    }

    impl<'a, T> IntoIterator for PopulatedIter<'a, T> {
        type Item = &'a T;
        type IntoIter = std::slice::Iter<'a, T>;

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

    impl<'a, T> PopulatedIterator for PopulatedIter<'a, T> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedSlice
            (first, self.iter)
        }
    }

    impl<'a, T> IntoIterator for &'a PopulatedSlice<T> {
        type Item = &'a T;
        type IntoIter = std::slice::Iter<'a, T>;

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

    impl<'a, T> IntoPopulatedIterator for &'a PopulatedSlice<T> {
        type PopulatedIntoIter = PopulatedIter<'a, T>;

        fn into_populated_iter(self) -> PopulatedIter<'a, T> {
            PopulatedIter {
                iter: self.into_iter(),
            }
        }
    }

    impl<'a, T> IntoIterator for &'a PopulatedVec<T> {
        type Item = &'a T;
        type IntoIter = std::slice::Iter<'a, T>;

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

    impl<'a, T> IntoPopulatedIterator for &'a PopulatedVec<T> {
        type PopulatedIntoIter = PopulatedIter<'a, T>;

        fn into_populated_iter(self) -> PopulatedIter<'a, T> {
            PopulatedIter {
                iter: self.into_iter(),
            }
        }
    }

    pub struct PopulatedIterMut<'a, T> {
        iter: std::slice::IterMut<'a, T>,
    }

    impl<'a, T> IntoIterator for PopulatedIterMut<'a, T> {
        type Item = &'a mut T;
        type IntoIter = std::slice::IterMut<'a, T>;

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

    impl<'a, T> PopulatedIterator for PopulatedIterMut<'a, T> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedSlice
            (first, self.iter)
        }
    }

    impl<'a, T> IntoIterator for &'a mut PopulatedSlice<T> {
        type Item = &'a mut T;
        type IntoIter = std::slice::IterMut<'a, T>;

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

    impl<'a, T> IntoPopulatedIterator for &'a mut PopulatedSlice<T> {
        type PopulatedIntoIter = PopulatedIterMut<'a, T>;

        fn into_populated_iter(self) -> PopulatedIterMut<'a, T> {
            PopulatedIterMut {
                iter: self.into_iter(),
            }
        }
    }

    impl<'a, T> IntoIterator for &'a mut PopulatedVec<T> {
        type Item = &'a mut T;
        type IntoIter = std::slice::IterMut<'a, T>;

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

    impl<'a, T> IntoPopulatedIterator for &'a mut PopulatedVec<T> {
        type PopulatedIntoIter = PopulatedIterMut<'a, T>;

        fn into_populated_iter(self) -> PopulatedIterMut<'a, T> {
            PopulatedIterMut {
                iter: self.into_iter(),
            }
        }
    }
}

pub mod vec_deque {
    use super::*;
    pub struct PopulatedIntoIter<T> {
        iter: std::collections::vec_deque::IntoIter<T>,
    }

    impl<Y> IntoIterator for PopulatedIntoIter<Y> {
        type Item = Y;
        type IntoIter = std::collections::vec_deque::IntoIter<Y>;

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

    impl<T> PopulatedIterator for PopulatedIntoIter<T> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedVecDeque
            (first, self.iter)
        }
    }

    impl<T> IntoIterator for PopulatedVecDeque<T> {
        type Item = T;
        type IntoIter = std::collections::vec_deque::IntoIter<T>;

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

    impl<T> IntoPopulatedIterator for PopulatedVecDeque<T> {
        type PopulatedIntoIter = vec_deque::PopulatedIntoIter<T>;

        fn into_populated_iter(self) -> vec_deque::PopulatedIntoIter<T> {
            vec_deque::PopulatedIntoIter {
                iter: self.into_iter(),
            }
        }
    }

    pub struct PopulatedIter<'a, T> {
        iter: std::collections::vec_deque::Iter<'a, T>,
    }

    impl<'a, T> IntoIterator for PopulatedIter<'a, T> {
        type Item = &'a T;
        type IntoIter = std::collections::vec_deque::Iter<'a, T>;

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

    impl<'a, T> PopulatedIterator for PopulatedIter<'a, T> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedVecDeque
            (first, self.iter)
        }
    }

    impl<'a, T> IntoIterator for &'a PopulatedVecDeque<T> {
        type Item = &'a T;
        type IntoIter = std::collections::vec_deque::Iter<'a, T>;

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

    impl<'a, T> IntoPopulatedIterator for &'a PopulatedVecDeque<T> {
        type PopulatedIntoIter = vec_deque::PopulatedIter<'a, T>;

        fn into_populated_iter(self) -> vec_deque::PopulatedIter<'a, T> {
            vec_deque::PopulatedIter {
                iter: self.into_iter(),
            }
        }
    }

    pub struct PopulatedIterMut<'a, T> {
        iter: std::collections::vec_deque::IterMut<'a, T>,
    }

    impl<'a, T> IntoIterator for PopulatedIterMut<'a, T> {
        type Item = &'a mut T;
        type IntoIter = std::collections::vec_deque::IterMut<'a, T>;

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

    impl<'a, T> PopulatedIterator for PopulatedIterMut<'a, T> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedVecDeque
            (first, self.iter)
        }
    }

    impl<'a, T> IntoIterator for &'a mut PopulatedVecDeque<T> {
        type Item = &'a mut T;
        type IntoIter = std::collections::vec_deque::IterMut<'a, T>;

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

    impl<'a, T> IntoPopulatedIterator for &'a mut PopulatedVecDeque<T> {
        type PopulatedIntoIter = vec_deque::PopulatedIterMut<'a, T>;

        fn into_populated_iter(self) -> vec_deque::PopulatedIterMut<'a, T> {
            vec_deque::PopulatedIterMut {
                iter: self.into_iter(),
            }
        }
    }
}

/// PopulatedHashMap is a wrapper around `HashMap` that guarantees that the
/// map is non-empty. This is useful when you want to ensure that a map is
/// populated before using it.
#[derive(Clone, Debug)]
pub struct PopulatedHashMap<K, V, S = RandomState>(HashMap<K, V, S>);

impl<K, V, S> From<PopulatedHashMap<K, V, S>> for HashMap<K, V, S> {
    fn from(populated_hash_map: PopulatedHashMap<K, V, S>) -> HashMap<K, V, S> {
        populated_hash_map.0
    }
}

impl<K, V, S> TryFrom<HashMap<K, V, S>> for PopulatedHashMap<K, V, S> {
    type Error = HashMap<K, V, S>;

    fn try_from(hash_map: HashMap<K, V, S>) -> Result<PopulatedHashMap<K, V, S>, Self::Error> {
        if hash_map.is_empty() {
            Err(hash_map)
        } else {
            Ok(PopulatedHashMap(hash_map))
        }
    }
}

impl<K: Eq + Hash, V> PopulatedHashMap<K, V, RandomState> {
    /// Creates a singleton populated hash map i.e. a hash map with a single key-value pair.
    pub fn new(key: K, value: V) -> PopulatedHashMap<K, V, RandomState> {
        PopulatedHashMap(HashMap::from([(key, value)]))
    }

    /// Creates an empty `PopulatedHashMap` with the specified capacity
    /// and containing the given key-value-pair.
    ///
    /// Note the capacity must be non-zero and a key value pair must be
    /// supplied because this is a populated hash map i.e. non-empty
    /// hash map.
    pub fn with_capacity(
        capacity: NonZeroUsize,
        key: K,
        value: V,
    ) -> PopulatedHashMap<K, V, RandomState> {
        let mut hash_map = HashMap::with_capacity_and_hasher(capacity.get(), RandomState::new());
        hash_map.insert(key, value);
        PopulatedHashMap(hash_map)
    }
}

impl<K: Eq + Hash, V, S: BuildHasher> PopulatedHashMap<K, V, S> {
    pub fn with_hasher(hash_builder: S, key: K, value: V) -> PopulatedHashMap<K, V, S> {
        let mut hash_map = HashMap::with_hasher(hash_builder);
        hash_map.insert(key, value);
        PopulatedHashMap(hash_map)
    }

    pub fn with_capacity_and_hasher(
        capacity: NonZeroUsize,
        hash_builder: S,
        key: K,
        value: V,
    ) -> PopulatedHashMap<K, V, S> {
        let mut hash_map = HashMap::with_capacity_and_hasher(capacity.get(), hash_builder);
        hash_map.insert(key, value);
        PopulatedHashMap(hash_map)
    }

    /// Returns a reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of the map’s key type, but `Hash`
    /// and `Eq` on the borrowed form must match those for the key type.
    pub fn get<Q: Hash + Eq + ?Sized>(&self, k: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
    {
        self.0.get(k)
    }

    /// Returns the key-value pair corresponding to the supplied key.
    ///
    /// The supplied key may be any borrowed form of the map’s key type,
    /// but `Hash` and `Eq` on the borrowed form must match those for the key
    /// type.
    pub fn get_key_value<Q: Hash + Eq + ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
    where
        K: Borrow<Q>,
    {
        self.0.get_key_value(k)
    }

    /// Returns true if the map contains a value for the specified key.
    ///
    /// The key may be any borrowed form of the map’s key type, but `Hash`
    /// and `Eq` on the borrowed form must match those for the key type.
    pub fn contains_key<Q: Hash + Eq + ?Sized>(&self, k: &Q) -> bool
    where
        K: Borrow<Q>,
    {
        self.0.contains_key(k)
    }

    /// Returns a mutable reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of the map’s key type, but `Hash`
    /// and `Eq` on the borrowed form must match those for the key type.
    pub fn get_mut<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<&mut V>
    where
        K: Borrow<Q>,
    {
        self.0.get_mut(k)
    }

    /// Inserts a key-value pair into the map.
    ///
    /// If the map did not have this key present, None is returned.
    ///
    /// If the map did have this key present, the value is updated, and
    /// the old value is returned. The key is not updated, though; this
    /// matters for types that can be == without being identical. See the
    /// module-level documentation for more.
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        self.0.insert(key, value)
    }

    /// Inserts a key-value pair into the map return the map as a `PopulatedHashMap` since inserting guarantees a `len()` > 0.
    ///
    /// If the map did not have this key present, None is returned.
    ///
    /// If the map did have this key present, the value is updated, and
    /// the old value is returned. The key is not updated, though; this
    /// matters for types that can be == without being identical. See the
    /// module-level documentation for more.
    ///
    /// This method is useful when you want to ensure that the map is populated after inserting a key-value pair.
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use populated::PopulatedHashMap;
    /// use std::num::NonZeroUsize;
    ///
    /// let mut hash_map = HashMap::from([(42, "the answer")]);
    /// let (old, populated_hash_map) = PopulatedHashMap::inserted(hash_map, 42, "the updated answer");
    /// assert_eq!(populated_hash_map.len(), NonZeroUsize::new(1).unwrap());
    /// assert_eq!(old, Some("the answer"));
    /// ```
    pub fn inserted(
        hash_map: HashMap<K, V, S>,
        key: K,
        value: V,
    ) -> (Option<V>, PopulatedHashMap<K, V, S>) {
        let mut hash_map = hash_map;
        let old = hash_map.insert(key, value);
        (old, PopulatedHashMap(hash_map))
    }

    /// Removes a key from the map, returning the value at the key if the key was previously in the map.
    ///
    /// The key may be any borrowed form of the map’s key type, but `Hash` and
    /// `Eq` on the borrowed form must match those for the key type.
    pub fn remove<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<V>
    where
        K: Borrow<Q>,
    {
        self.0.remove(k)
    }

    /// Removes a key from the map, returning the stored key and value if
    /// the key was previously in the map.
    ///
    /// The key may be any borrowed form of the map’s key type, but `Hash`
    /// and Eq on the borrowed form must match those for the key type.
    pub fn remove_entry<Q: Hash + Eq + ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
    where
        K: Borrow<Q>,
    {
        self.0.remove_entry(k)
    }
}

impl<K, V, S> PopulatedHashMap<K, V, S> {
    /// Returns the number of elements the map can hold without reallocating.
    ///
    /// This number is a lower bound; the `PopulatedHashMap<K, V>` might
    /// be able to hold more, but is guaranteed to be able to hold at
    /// least this many.
    pub fn capacity(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.capacity()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedHashMap
    }

    /// Returns the number of elements in the map.
    pub fn len(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.len()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedHashMap
    }

    pub fn retain(self, predicate: impl FnMut(&K, &mut V) -> bool) -> HashMap<K, V, S> {
        let mut hash_map = self.0;
        hash_map.retain(predicate);
        hash_map
    }

    pub fn clear(self) -> HashMap<K, V, S> {
        let mut hash_map = self.0;
        hash_map.clear();
        hash_map
    }

    pub fn hasher(&self) -> &S {
        self.0.hasher()
    }
}

impl<Q: Eq + Hash + ?Sized, K: Eq + Hash + Borrow<Q>, V, S: BuildHasher> Index<&Q>
    for PopulatedHashMap<K, V, S>
{
    type Output = V;

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

impl<K, V, S> PopulatedHashMap<K, V, S> {
    pub fn iter(&self) -> hash_map::PopulatedIter<K, V> {
        self.into_populated_iter()
    }

    pub fn iter_mut(&mut self) -> hash_map::PopulatedIterMut<K, V> {
        self.into_populated_iter()
    }

    pub fn keys(&self) -> hash_map::PopulatedKeys<K, V> {
        hash_map::PopulatedKeys {
            keys: self.0.keys(),
        }
    }

    pub fn values(&self) -> hash_map::PopulatedValues<K, V> {
        hash_map::PopulatedValues {
            values: self.0.values(),
        }
    }

    pub fn values_mut(&mut self) -> hash_map::PopulatedValuesMut<K, V> {
        hash_map::PopulatedValuesMut {
            values: self.0.values_mut(),
        }
    }
}
impl<K, V, S> IntoIterator for PopulatedHashMap<K, V, S> {
    type Item = (K, V);
    type IntoIter = std::collections::hash_map::IntoIter<K, V>;

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

impl<'a, K, V, S> IntoIterator for &'a PopulatedHashMap<K, V, S> {
    type Item = (&'a K, &'a V);
    type IntoIter = std::collections::hash_map::Iter<'a, K, V>;

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

impl<'a, K, V, S> IntoIterator for &'a mut PopulatedHashMap<K, V, S> {
    type Item = (&'a K, &'a mut V);
    type IntoIter = std::collections::hash_map::IterMut<'a, K, V>;

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

pub mod hash_map {
    use super::*;
    pub struct PopulatedIntoIter<K, V> {
        iter: std::collections::hash_map::IntoIter<K, V>,
    }

    impl<K, V> IntoIterator for PopulatedIntoIter<K, V> {
        type Item = (K, V);
        type IntoIter = std::collections::hash_map::IntoIter<K, V>;

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

    impl<K, V> PopulatedIterator for PopulatedIntoIter<K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedHashMap
            (first, self.iter)
        }
    }

    impl<K, V, S> IntoPopulatedIterator for PopulatedHashMap<K, V, S> {
        type PopulatedIntoIter = hash_map::PopulatedIntoIter<K, V>;

        fn into_populated_iter(self) -> hash_map::PopulatedIntoIter<K, V> {
            hash_map::PopulatedIntoIter {
                iter: self.into_iter(),
            }
        }
    }

    pub struct PopulatedIter<'a, K, V> {
        iter: std::collections::hash_map::Iter<'a, K, V>,
    }

    impl<'a, K, V> IntoIterator for PopulatedIter<'a, K, V> {
        type Item = (&'a K, &'a V);
        type IntoIter = std::collections::hash_map::Iter<'a, K, V>;

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

    impl<'a, K, V> PopulatedIterator for PopulatedIter<'a, K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedHashMap
            (first, self.iter)
        }
    }

    impl<'a, K, V, S> IntoPopulatedIterator for &'a PopulatedHashMap<K, V, S> {
        type PopulatedIntoIter = PopulatedIter<'a, K, V>;

        fn into_populated_iter(self) -> PopulatedIter<'a, K, V> {
            PopulatedIter {
                iter: self.into_iter(),
            }
        }
    }

    pub struct PopulatedIterMut<'a, K, V> {
        iter: std::collections::hash_map::IterMut<'a, K, V>,
    }

    impl<'a, K, V> IntoIterator for PopulatedIterMut<'a, K, V> {
        type Item = (&'a K, &'a mut V);
        type IntoIter = std::collections::hash_map::IterMut<'a, K, V>;

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

    impl<'a, K, V> PopulatedIterator for PopulatedIterMut<'a, K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedHashMap
            (first, self.iter)
        }
    }

    impl<'a, K, V, S> IntoPopulatedIterator for &'a mut PopulatedHashMap<K, V, S> {
        type PopulatedIntoIter = PopulatedIterMut<'a, K, V>;

        fn into_populated_iter(self) -> PopulatedIterMut<'a, K, V> {
            PopulatedIterMut {
                iter: self.0.iter_mut(),
            }
        }
    }

    pub struct PopulatedKeys<'a, K, V> {
        pub(crate) keys: std::collections::hash_map::Keys<'a, K, V>,
    }

    impl<'a, K, V> IntoIterator for PopulatedKeys<'a, K, V> {
        type Item = &'a K;
        type IntoIter = std::collections::hash_map::Keys<'a, K, V>;

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

    impl<'a, K, V> PopulatedIterator for PopulatedKeys<'a, K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.keys.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedHashMap
            (first, self.keys)
        }
    }

    pub struct PopulatedValues<'a, K, V> {
        pub(crate) values: std::collections::hash_map::Values<'a, K, V>,
    }

    impl<'a, K, V> IntoIterator for PopulatedValues<'a, K, V> {
        type Item = &'a V;
        type IntoIter = std::collections::hash_map::Values<'a, K, V>;

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

    impl<'a, K, V> PopulatedIterator for PopulatedValues<'a, K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.values.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedHashMap
            (first, self.values)
        }
    }

    pub struct PopulatedValuesMut<'a, K, V> {
        pub(crate) values: std::collections::hash_map::ValuesMut<'a, K, V>,
    }

    impl<'a, K, V> IntoIterator for PopulatedValuesMut<'a, K, V> {
        type Item = &'a mut V;
        type IntoIter = std::collections::hash_map::ValuesMut<'a, K, V>;

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

    impl<'a, K, V> PopulatedIterator for PopulatedValuesMut<'a, K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.values.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedHashMap
            (first, self.values)
        }
    }

    pub struct PopulatedIntoKeys<K, V> {
        pub(crate) keys: std::collections::hash_map::IntoKeys<K, V>,
    }

    impl<K, V> IntoIterator for PopulatedIntoKeys<K, V> {
        type Item = K;
        type IntoIter = std::collections::hash_map::IntoKeys<K, V>;

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

    impl<K, V> PopulatedIterator for PopulatedIntoKeys<K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.keys.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedHashMap
            (first, self.keys)
        }
    }

    pub struct PopulatedIntoValues<K, V> {
        pub(crate) values: std::collections::hash_map::IntoValues<K, V>,
    }

    impl<K, V> IntoIterator for PopulatedIntoValues<K, V> {
        type Item = V;
        type IntoIter = std::collections::hash_map::IntoValues<K, V>;

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

    impl<K, V> PopulatedIterator for PopulatedIntoValues<K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.values.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedHashMap
            (first, self.values)
        }
    }
}
/// A hash set that is populated i.e. guaranteed to have at least one element.
#[derive(Clone, Debug)]
pub struct PopulatedHashSet<T, S = RandomState>(HashSet<T, S>);

impl<T: Eq + Hash, S: BuildHasher> PartialEq for PopulatedHashSet<T, S> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T: Eq + Hash, S: BuildHasher> PartialEq<HashSet<T, S>> for PopulatedHashSet<T, S> {
    fn eq(&self, other: &HashSet<T, S>) -> bool {
        &self.0 == other
    }
}

impl<T: Eq + Hash, S: BuildHasher> PartialEq<PopulatedHashSet<T, S>> for HashSet<T, S> {
    fn eq(&self, other: &PopulatedHashSet<T, S>) -> bool {
        self == &other.0
    }
}

impl<T: Eq + Hash, S: BuildHasher> Eq for PopulatedHashSet<T, S> {}

impl<T, S> From<PopulatedHashSet<T, S>> for HashSet<T, S> {
    fn from(populated_hash_set: PopulatedHashSet<T, S>) -> HashSet<T, S> {
        populated_hash_set.0
    }
}

impl<T, S> TryFrom<HashSet<T, S>> for PopulatedHashSet<T, S> {
    type Error = HashSet<T, S>;

    fn try_from(hash_set: HashSet<T, S>) -> Result<PopulatedHashSet<T, S>, Self::Error> {
        if hash_set.is_empty() {
            Err(hash_set)
        } else {
            Ok(PopulatedHashSet(hash_set))
        }
    }
}

impl<T: Eq + Hash> PopulatedHashSet<T> {
    /// Creates a singleton populated hash set i.e. a hash set with a single value.
    ///
    /// # Example
    ///
    /// ```
    /// use populated::PopulatedHashSet;
    /// use std::num::NonZeroUsize;
    ///
    /// let hash_set = PopulatedHashSet::new(42);
    /// assert_eq!(hash_set.len(), NonZeroUsize::new(1).unwrap());
    /// ```
    pub fn new(value: T) -> PopulatedHashSet<T> {
        PopulatedHashSet(HashSet::from([value]))
    }

    /// Creates an empty `PopulatedHashSet` with the specified capacity
    /// and containing the given value.
    ///
    /// Note the capacity must be non-zero and a value must be
    /// supplied because this is a populated hash set i.e. non-empty
    /// hash set.
    ///
    /// # Example
    ///
    /// ```
    /// use populated::PopulatedHashSet;
    /// use std::num::NonZeroUsize;
    ///
    /// let hash_set = PopulatedHashSet::with_capacity(NonZeroUsize::new(1).unwrap(), 42);
    /// assert_eq!(hash_set.len(), NonZeroUsize::new(1).unwrap());
    /// ```
    pub fn with_capacity(capacity: NonZeroUsize, value: T) -> PopulatedHashSet<T> {
        let mut hash_set = HashSet::with_capacity(capacity.get());
        hash_set.insert(value);
        PopulatedHashSet(hash_set)
    }
}

impl<T, S> PopulatedHashSet<T, S> {
    /// Returns the number of elements the set can hold without reallocating.
    /// The capacity is returned as a `NonZeroUsize` because this is a populated hash set.
    ///
    /// # Example
    ///
    /// ```
    /// use populated::PopulatedHashSet;
    ///
    /// let mut hash_set = PopulatedHashSet::new(42);
    /// hash_set.insert(43);
    /// assert!(hash_set.capacity().get() >= 2);
    /// ```
    pub fn capacity(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.capacity()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedHashSet
    }

    /// Returns an iterator over the set.
    pub fn iter(&self) -> std::collections::hash_set::Iter<T> {
        self.0.iter()
    }

    /// Returns the number of elements in the set.
    ///
    /// The length is returned as a `NonZeroUsize` because this is a populated hash set.
    ///
    /// # Example
    ///
    /// ```
    /// use populated::PopulatedHashSet;
    ///
    /// let mut hash_set = PopulatedHashSet::new(42);
    /// hash_set.insert(43);
    /// assert_eq!(hash_set.len().get(), 2);
    /// ```
    pub fn len(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.len()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedHashSet
    }

    /// Retains only the elements specified by the predicate.
    ///
    /// In other words, remove all elements e such that `predicate(&e)`
    /// returns `false`.
    ///
    /// # Example
    ///
    /// ```
    /// use populated::PopulatedHashSet;
    ///
    /// let mut hash_set = PopulatedHashSet::new(42);
    /// hash_set.insert(43);
    /// let hash_set = hash_set.retain(|&e| e == 42);
    /// assert_eq!(hash_set.len(), 1);
    /// ```
    pub fn retain(self, predicate: impl FnMut(&T) -> bool) -> HashSet<T, S> {
        let mut hash_set = self.0;
        hash_set.retain(predicate);
        hash_set
    }

    /// Clears the set, removing all values.
    ///
    /// This method returns the set as a `HashSet` because after clearing
    /// the set is no longer guaranteed to be populated.
    ///
    /// # Example
    ///
    /// ```
    /// use populated::PopulatedHashSet;
    ///
    /// let mut hash_set = PopulatedHashSet::new(42);
    /// hash_set.insert(43);
    ///
    /// let hash_set = hash_set.clear();
    /// assert_eq!(hash_set.len(), 0);
    /// ```
    pub fn clear(self) -> HashSet<T, S> {
        let mut hash_set = self.0;
        hash_set.clear();
        hash_set
    }

    pub fn hasher(&self) -> &S {
        self.0.hasher()
    }
}

impl<T: Eq + Hash, S: BuildHasher> PopulatedHashSet<T, S> {
    /// Creates a new `PopulatedHashSet` with the given hasher and value.
    ///
    /// # Example
    ///
    /// ```
    /// use populated::PopulatedHashSet;
    /// use std::collections::hash_map::RandomState;
    ///
    /// let hash_set = PopulatedHashSet::with_hasher(RandomState::new(), 42);
    /// assert_eq!(hash_set.len().get(), 1);
    /// ```
    pub fn with_hasher(hash_builder: S, value: T) -> PopulatedHashSet<T, S> {
        let mut hash_set = HashSet::with_hasher(hash_builder);
        hash_set.insert(value);
        PopulatedHashSet(hash_set)
    }

    /// Creates an empty `PopulatedHashSet` with the specified capacity
    /// and containing the given value.
    ///
    /// Note the capacity must be non-zero and a value must be
    /// supplied because this is a populated hash set i.e. non-empty
    /// hash set.
    ///
    /// # Example
    ///
    /// ```
    /// use populated::PopulatedHashSet;
    /// use std::collections::hash_map::RandomState;
    /// use std::num::NonZeroUsize;
    ///
    /// let hash_set = PopulatedHashSet::with_capacity_and_hasher(NonZeroUsize::new(1).unwrap(), RandomState::new(), 42);
    /// assert_eq!(hash_set.len().get(), 1);
    /// ```
    pub fn with_capacity_and_hasher(
        capacity: NonZeroUsize,
        hasher: S,
        value: T,
    ) -> PopulatedHashSet<T, S> {
        let mut hash_set = HashSet::with_capacity_and_hasher(capacity.get(), hasher);
        hash_set.insert(value);
        PopulatedHashSet(hash_set)
    }

    /// Reserves capacity for at least additional more elements to be inserted in the set.
    pub fn reserve(&mut self, additional: usize) {
        self.0.reserve(additional);
    }

    /// Tries to reserve capacity for at least additional more elements to be inserted in the set.
    /// If the capacity is already sufficient, nothing happens. If allocation is needed and fails,
    /// an error is returned.
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.0.try_reserve(additional)
    }

    /// Shrinks the capacity of the set as much as possible.
    pub fn shrink_to_fit(&mut self) {
        self.0.shrink_to_fit();
    }

    /// Shrinks the capacity of the set to the minimum needed to hold the elements.
    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.0.shrink_to(min_capacity);
    }

    /// Visits the values representing the difference, i.e., the values
    /// that are in self but not in other.
    pub fn difference<'a>(
        &'a self,
        other: &'a HashSet<T, S>,
    ) -> std::collections::hash_set::Difference<'a, T, S> {
        self.0.difference(other)
    }

    /// Visits the values representing the symmetric difference, i.e., the
    /// values that are in self or in other but not in both.
    pub fn symmetric_difference<'a>(
        &'a self,
        other: &'a HashSet<T, S>,
    ) -> std::collections::hash_set::SymmetricDifference<'a, T, S> {
        self.0.symmetric_difference(other)
    }

    /// Visits the values representing the intersection, i.e., the values
    /// that are both in `self` and `other`.
    ///
    /// When an equal element is present in `self` and `other` then the resulting
    /// `Intersection` may yield references to one or the other. This can be
    /// relevant if `T` contains fields which are not compared by its `Eq`
    /// implementation, and may hold different value between the two equal
    /// copies of `T` in the two sets.
    pub fn intersection<'a>(
        &'a self,
        other: &'a HashSet<T, S>,
    ) -> std::collections::hash_set::Intersection<'a, T, S> {
        self.0.intersection(other)
    }

    // TODO: union with populated iterator

    /// Returns true if the populated set contains a value.
    ///
    /// The value may be any borrowed form of the set’s value type, but
    /// `Hash` and `Eq` on the borrowed form must match those for the
    /// value type.
    pub fn contains<Q: Hash + Eq + ?Sized>(&self, value: &Q) -> bool
    where
        T: Borrow<Q>,
    {
        self.0.contains(value)
    }

    /// Returns a reference to the value in the populated set, if any,
    /// that is equal to the given value.
    ///
    /// The value may be any borrowed form of the set’s value type, but
    /// `Hash` and `Eq` on the borrowed form must match those for the
    /// value type.
    pub fn get<Q: Hash + Eq + ?Sized>(&self, value: &Q) -> Option<&T>
    where
        T: Borrow<Q>,
    {
        self.0.get(value)
    }

    /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to checking for an empty intersection.
    pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
        self.0.is_disjoint(other)
    }

    /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all the values in `self`.
    pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
        self.0.is_subset(other)
    }

    /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the values in `other`.
    pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
        self.0.is_superset(other)
    }

    /// Adds a value to the set.
    ///
    /// Returns whether the value was newly inserted. That is:
    ///
    /// - If the set did not previously contain this value, true is returned.
    /// - If the set already contained this value, false is returned, and the set is not modified: original value is not replaced, and the
    ///   value passed as argument is dropped.
    pub fn insert(&mut self, value: T) -> bool {
        self.0.insert(value)
    }

    /// Add a value to the hash set, returning the set as a `PopulatedHashSet` since inserting guarantees a `len()` > 0.
    ///
    /// Returns whether the value was newly inserted. That is:
    ///
    /// - If the set did not previously contain this value, true is returned.
    /// - If the set already contained this value, false is returned, and the set is not modified: original value is not replaced, and the
    ///  value passed as argument is dropped.
    ///
    /// This method is useful when you want to ensure that the set is populated after inserting a value.
    ///
    /// ```
    /// use std::collections::HashSet;
    /// use populated::PopulatedHashSet;
    /// use std::num::NonZeroUsize;
    ///
    /// let mut hash_set = HashSet::from([42]);
    /// let (inserted, populated_hash_set) = PopulatedHashSet::inserted(hash_set, 43);
    /// assert_eq!(populated_hash_set.len(), NonZeroUsize::new(2).unwrap());
    /// assert!(inserted);
    /// ```
    pub fn inserted(mut hash_set: HashSet<T, S>, value: T) -> (bool, PopulatedHashSet<T, S>) {
        let inserted = hash_set.insert(value);
        (inserted, PopulatedHashSet(hash_set))
    }

    /// Adds a value to the set, replacing the existing value, if any, that is equal to the given one. Returns the replaced value.
    pub fn replace(&mut self, value: T) -> Option<T> {
        self.0.replace(value)
    }

    /// Removes a value from the set. Returns whether the value was present in the set.
    ///
    /// The value may be any borrowed form of the set’s value type, but `Hash` and `Eq` on the borrowed form *must* match those for the value
    /// type.
    pub fn remove<Q: Hash + Eq + ?Sized>(
        self,
        value: &Q,
    ) -> Result<HashSet<T, S>, PopulatedHashSet<T, S>>
    where
        T: Borrow<Q>,
    {
        let mut set = self.0;
        if set.remove(value) {
            Ok(set)
        } else {
            Err(PopulatedHashSet(set))
        }
    }

    /// Removes and returns the value in the set, if any, that is equal to the given one.
    ///
    /// The value may be any borrowed form of the set’s value type, but Hash and Eq on the borrowed form must match those for the value type.
    pub fn take<Q: Hash + Eq + ?Sized>(
        self,
        value: &Q,
    ) -> Result<(T, HashSet<T, S>), PopulatedHashSet<T, S>>
    where
        T: Borrow<Q>,
    {
        let mut set = self.0;
        if let Some(value) = set.take(value) {
            Ok((value, set))
        } else {
            Err(PopulatedHashSet(set))
        }
    }
}

impl<'a, T, S> IntoIterator for &'a PopulatedHashSet<T, S> {
    type Item = &'a T;
    type IntoIter = std::collections::hash_set::Iter<'a, T>;

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

impl<T, S> IntoIterator for PopulatedHashSet<T, S> {
    type Item = T;
    type IntoIter = std::collections::hash_set::IntoIter<T>;

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

impl<T: Eq + Hash + Clone, S: BuildHasher + Default> BitOr for &PopulatedHashSet<T, S> {
    type Output = PopulatedHashSet<T, S>;

    fn bitor(self, other: &PopulatedHashSet<T, S>) -> Self::Output {
        let hash_set = &self.0 | &other.0;
        PopulatedHashSet(hash_set)
    }
}

impl<T: Eq + Hash + Clone, S: BuildHasher + Default> BitOr<&HashSet<T, S>>
    for &PopulatedHashSet<T, S>
{
    type Output = PopulatedHashSet<T, S>;

    fn bitor(self, other: &HashSet<T, S>) -> Self::Output {
        let hash_set = &self.0 | other;
        PopulatedHashSet(hash_set)
    }
}

impl<T: Eq + Hash + Clone, S: BuildHasher + Default> BitOr<&PopulatedHashSet<T, S>>
    for &HashSet<T, S>
{
    type Output = PopulatedHashSet<T, S>;

    fn bitor(self, other: &PopulatedHashSet<T, S>) -> Self::Output {
        let hash_set = self | &other.0;
        PopulatedHashSet(hash_set)
    }
}
pub mod hash_set {

    use crate::{IntoPopulatedIterator, PopulatedHashSet, PopulatedIterator};

    pub struct IntoPopulatedIter<T> {
        iter: std::collections::hash_set::IntoIter<T>,
    }

    impl<T> IntoIterator for IntoPopulatedIter<T> {
        type Item = T;
        type IntoIter = std::collections::hash_set::IntoIter<T>;

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

    impl<T> PopulatedIterator for IntoPopulatedIter<T> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedHashSet
            (first, self.iter)
        }
    }

    impl<T, S> IntoPopulatedIterator for PopulatedHashSet<T, S> {
        type PopulatedIntoIter = IntoPopulatedIter<T>;

        fn into_populated_iter(self) -> IntoPopulatedIter<T> {
            IntoPopulatedIter {
                iter: self.into_iter(),
            }
        }
    }

    pub struct PopulatedIter<'a, T> {
        iter: std::collections::hash_set::Iter<'a, T>,
        first: &'a T,
    }

    impl<'a, T> IntoIterator for PopulatedIter<'a, T> {
        type Item = &'a T;
        type IntoIter = std::collections::hash_set::Iter<'a, T>;

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

    impl<'a, T> PopulatedIterator for PopulatedIter<'a, T> {
        fn next(self) -> (Self::Item, Self::IntoIter) {
            (self.first, self.iter)
        }
    }

    impl<'a, T, S> IntoPopulatedIterator for &'a PopulatedHashSet<T, S> {
        type PopulatedIntoIter = PopulatedIter<'a, T>;

        fn into_populated_iter(self) -> PopulatedIter<'a, T> {
            let mut iter = self.iter();
            let first = iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedHashSet
            PopulatedIter { iter, first }
        }
    }
}

/// The result of removing an entry from a `PopulatedBTreeMap`.
pub type EntryRemovalResult<K, V> = Result<((K, V), BTreeMap<K, V>), PopulatedBTreeMap<K, V>>;

/// An ordered map based on a B-Tree that is guaranteed to have at least one key-value pair.
#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord)]
pub struct PopulatedBTreeMap<K, V>(BTreeMap<K, V>);

impl<K, V> From<PopulatedBTreeMap<K, V>> for BTreeMap<K, V> {
    fn from(populated_btree_map: PopulatedBTreeMap<K, V>) -> BTreeMap<K, V> {
        populated_btree_map.0
    }
}

impl<K, V> TryFrom<BTreeMap<K, V>> for PopulatedBTreeMap<K, V> {
    type Error = BTreeMap<K, V>;

    fn try_from(btree_map: BTreeMap<K, V>) -> Result<PopulatedBTreeMap<K, V>, Self::Error> {
        if btree_map.is_empty() {
            Err(btree_map)
        } else {
            Ok(PopulatedBTreeMap(btree_map))
        }
    }
}

impl<K: Ord, V> PopulatedBTreeMap<K, V> {
    /// Makes a new `PopulatedBTreeMap` with a single key-value pair.
    pub fn new(key: K, value: V) -> PopulatedBTreeMap<K, V> {
        PopulatedBTreeMap(BTreeMap::from([(key, value)]))
    }

    /// Returns a reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    pub fn get<Q: Ord + ?Sized>(&self, k: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
    {
        self.0.get(k)
    }

    /// Returns the key-value pair corresponding to the supplied key.
    ///
    /// The supplied key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on
    /// the key type.
    pub fn get_key_value<Q: Ord + ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
    where
        K: Borrow<Q>,
    {
        self.0.get_key_value(k)
    }

    /// Returns the first key-value pair in the map. The key in this pair is the minimum key in the map.
    pub fn first_key_value(&self) -> (&K, &V) {
        self.0.first_key_value().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
    }

    /// Removes and returns the first element in the map. The key of this element is the minimum key that was in the map.
    pub fn pop_first(self) -> ((K, V), BTreeMap<K, V>) {
        let mut btree_map = self.0;
        let first = btree_map.pop_first().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
        (first, btree_map)
    }

    /// Returns the last key-value pair in the map. The key in this pair is the maximum key in the map.
    pub fn last_key_value(&self) -> (&K, &V) {
        self.0.last_key_value().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
    }

    /// Removes and returns the last element in the map. The key of this element is the maximum key that was in the map.
    pub fn pop_last(self) -> (BTreeMap<K, V>, (K, V)) {
        let mut btree_map = self.0;
        let last = btree_map.pop_last().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
        (btree_map, last)
    }

    /// Returns true if the map contains a value for the specified key.
    ///
    /// The key may be any borrowed form of the map’s key type, but the
    /// ordering on the borrowed form must match the ordering on the key
    /// type.
    pub fn contains_key<Q: Ord + ?Sized>(&self, k: &Q) -> bool
    where
        K: Borrow<Q>,
    {
        self.0.contains_key(k)
    }

    /// Returns a mutable reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of the map’s key type, but the
    /// ordering on the borrowed form must match the ordering on the key
    /// type.
    pub fn get_mut<Q: Ord + ?Sized>(&mut self, k: &Q) -> Option<&mut V>
    where
        K: Borrow<Q>,
    {
        self.0.get_mut(k)
    }

    /// Inserts a key-value pair into the map.
    ///
    /// If the map did not have this key present, None is returned.
    ///
    /// If the map did have this key present, the value is updated, and
    /// the old value is returned. The key is not updated, though; this
    /// matters for types that can be == without being identical. See the
    /// module-level documentation for more.
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        self.0.insert(key, value)
    }

    /// Removes a key from the map, returning the value at the key if the key was previously in the map.
    ///
    /// The key may be any borrowed form of the map’s key type, but the
    /// ordering on the borrowed form must match the ordering on the key
    /// type.
    pub fn remove<Q: Ord + ?Sized>(
        self,
        k: &Q,
    ) -> Result<(V, BTreeMap<K, V>), PopulatedBTreeMap<K, V>>
    where
        K: Borrow<Q>,
    {
        let mut btree_map = self.0;
        if let Some(value) = btree_map.remove(k) {
            Ok((value, btree_map))
        } else {
            Err(PopulatedBTreeMap(btree_map))
        }
    }

    /// Removes a key from the map, returning the stored key and value if the key was previously in the map.
    ///
    /// The key may be any borrowed form of the map’s key type, but the
    /// ordering on the borrowed form must match the ordering on the key
    /// type.
    pub fn remove_entry<Q: Ord + ?Sized>(self, k: &Q) -> EntryRemovalResult<K, V>
    where
        K: Borrow<Q>,
    {
        let mut btree_map = self.0;
        if let Some(tuple) = btree_map.remove_entry(k) {
            Ok((tuple, btree_map))
        } else {
            Err(PopulatedBTreeMap(btree_map))
        }
    }

    /// Retains only the elements specified by the predicate.
    ///
    /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)`
    /// returns `false`. The elements are visited in ascending key order.
    pub fn retain(self, predicate: impl FnMut(&K, &mut V) -> bool) -> BTreeMap<K, V> {
        let mut btree_map = self.0;
        btree_map.retain(predicate);
        btree_map
    }

    /// Moves all elements from other into self, leaving other empty.
    ///
    /// If a key from other is already present in self, the respective
    /// value from self will be overwritten with the respective value
    /// from other.
    pub fn append(&mut self, other: &mut BTreeMap<K, V>) {
        self.0.append(other);
    }

    /// Constructs a double-ended iterator over a sub-range of elements in
    /// the map. The simplest way is to use the range syntax `min..max`,
    /// thus `range(min..max)` will yield elements from min (inclusive) to
    /// max (exclusive). The range may also be entered as
    /// `(Bound<T>, Bound<T>)`, so for example
    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive,
    /// right-inclusive range from 4 to 10.
    pub fn range<T: Ord + ?Sized>(
        &self,
        range: impl RangeBounds<T>,
    ) -> std::collections::btree_map::Range<'_, K, V>
    where
        K: Borrow<T>,
    {
        self.0.range(range)
    }

    pub fn split_at<Q: Ord + ?Sized>(self, key: &Q) -> (BTreeMap<K, V>, BTreeMap<K, V>)
    where
        K: Borrow<Q>,
    {
        let mut whole_btree_map = self.0;
        let other_half = whole_btree_map.split_off(key);
        (whole_btree_map, other_half)
    }
}

impl<K, V> PopulatedBTreeMap<K, V> {
    pub fn clear(self) -> BTreeMap<K, V> {
        let mut btree_map = self.0;
        btree_map.clear();
        btree_map
    }

    /// Returns the number of elements in the map.
    pub fn len(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.len()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
    }
}

impl<K, V> IntoIterator for PopulatedBTreeMap<K, V> {
    type Item = (K, V);
    type IntoIter = std::collections::btree_map::IntoIter<K, V>;

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

impl<'a, K, V> IntoIterator for &'a PopulatedBTreeMap<K, V> {
    type Item = (&'a K, &'a V);
    type IntoIter = std::collections::btree_map::Iter<'a, K, V>;

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

impl<'a, K, V> IntoIterator for &'a mut PopulatedBTreeMap<K, V> {
    type Item = (&'a K, &'a mut V);
    type IntoIter = std::collections::btree_map::IterMut<'a, K, V>;

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

pub mod btree_map {
    use crate::{IntoPopulatedIterator, PopulatedBTreeMap, PopulatedIterator};

    pub struct IntoPopulatedIter<K, V> {
        iter: std::collections::btree_map::IntoIter<K, V>,
    }

    impl<K, V> IntoIterator for IntoPopulatedIter<K, V> {
        type Item = (K, V);
        type IntoIter = std::collections::btree_map::IntoIter<K, V>;

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

    impl<K, V> PopulatedIterator for IntoPopulatedIter<K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
            (first, self.iter)
        }
    }

    impl<K, V> IntoPopulatedIterator for PopulatedBTreeMap<K, V> {
        type PopulatedIntoIter = IntoPopulatedIter<K, V>;

        fn into_populated_iter(self) -> IntoPopulatedIter<K, V> {
            IntoPopulatedIter {
                iter: self.into_iter(),
            }
        }
    }

    pub struct PopulatedIter<'a, K, V> {
        iter: std::collections::btree_map::Iter<'a, K, V>,
    }

    impl<'a, K, V> IntoIterator for PopulatedIter<'a, K, V> {
        type Item = (&'a K, &'a V);
        type IntoIter = std::collections::btree_map::Iter<'a, K, V>;

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

    impl<'a, K, V> PopulatedIterator for PopulatedIter<'a, K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
            (first, self.iter)
        }
    }

    impl<'a, K, V> IntoPopulatedIterator for &'a PopulatedBTreeMap<K, V> {
        type PopulatedIntoIter = PopulatedIter<'a, K, V>;

        fn into_populated_iter(self) -> PopulatedIter<'a, K, V> {
            PopulatedIter {
                iter: self.into_iter(),
            }
        }
    }

    pub struct PopulatedIterMut<'a, K, V> {
        iter: std::collections::btree_map::IterMut<'a, K, V>,
    }

    impl<'a, K, V> IntoIterator for PopulatedIterMut<'a, K, V> {
        type Item = (&'a K, &'a mut V);
        type IntoIter = std::collections::btree_map::IterMut<'a, K, V>;

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

    impl<'a, K, V> PopulatedIterator for PopulatedIterMut<'a, K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
            (first, self.iter)
        }
    }

    impl<'a, K, V> IntoPopulatedIterator for &'a mut PopulatedBTreeMap<K, V> {
        type PopulatedIntoIter = PopulatedIterMut<'a, K, V>;

        fn into_populated_iter(self) -> PopulatedIterMut<'a, K, V> {
            PopulatedIterMut {
                iter: self.into_iter(),
            }
        }
    }

    pub struct PopulatedKeys<'a, K, V> {
        pub(crate) iter: std::collections::btree_map::Keys<'a, K, V>,
    }

    impl<'a, K, V> IntoIterator for PopulatedKeys<'a, K, V> {
        type Item = &'a K;
        type IntoIter = std::collections::btree_map::Keys<'a, K, V>;

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

    impl<'a, K, V> PopulatedIterator for PopulatedKeys<'a, K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
            (first, self.iter)
        }
    }

    pub struct PopulatedValues<'a, K, V> {
        pub(crate) iter: std::collections::btree_map::Values<'a, K, V>,
    }

    impl<'a, K, V> IntoIterator for PopulatedValues<'a, K, V> {
        type Item = &'a V;
        type IntoIter = std::collections::btree_map::Values<'a, K, V>;

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

    impl<'a, K, V> PopulatedIterator for PopulatedValues<'a, K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
            (first, self.iter)
        }
    }

    pub struct PopulatedValuesMut<'a, K, V> {
        pub(crate) iter: std::collections::btree_map::ValuesMut<'a, K, V>,
    }

    impl<'a, K, V> IntoIterator for PopulatedValuesMut<'a, K, V> {
        type Item = &'a mut V;
        type IntoIter = std::collections::btree_map::ValuesMut<'a, K, V>;

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

    impl<'a, K, V> PopulatedIterator for PopulatedValuesMut<'a, K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
            (first, self.iter)
        }
    }

    pub struct PopulatedIntoKeys<K, V> {
        pub(crate) iter: std::collections::btree_map::IntoKeys<K, V>,
    }

    impl<K, V> IntoIterator for PopulatedIntoKeys<K, V> {
        type Item = K;
        type IntoIter = std::collections::btree_map::IntoKeys<K, V>;

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

    impl<K, V> PopulatedIterator for PopulatedIntoKeys<K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
            (first, self.iter)
        }
    }

    pub struct PopulatedIntoValues<K, V> {
        pub(crate) iter: std::collections::btree_map::IntoValues<K, V>,
    }

    impl<K, V> IntoIterator for PopulatedIntoValues<K, V> {
        type Item = V;
        type IntoIter = std::collections::btree_map::IntoValues<K, V>;

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

    impl<K, V> PopulatedIterator for PopulatedIntoValues<K, V> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeMap
            (first, self.iter)
        }
    }
}

impl<K, V> PopulatedBTreeMap<K, V> {
    pub fn iter(&self) -> btree_map::PopulatedIter<K, V> {
        self.into_populated_iter()
    }

    pub fn iter_mut(&mut self) -> btree_map::PopulatedIterMut<K, V> {
        self.into_populated_iter()
    }

    pub fn keys(&self) -> btree_map::PopulatedKeys<K, V> {
        btree_map::PopulatedKeys {
            iter: self.0.keys(),
        }
    }

    pub fn values(&self) -> btree_map::PopulatedValues<K, V> {
        btree_map::PopulatedValues {
            iter: self.0.values(),
        }
    }

    pub fn values_mut(&mut self) -> btree_map::PopulatedValuesMut<K, V> {
        btree_map::PopulatedValuesMut {
            iter: self.0.values_mut(),
        }
    }

    pub fn into_keys(self) -> btree_map::PopulatedIntoKeys<K, V> {
        btree_map::PopulatedIntoKeys {
            iter: self.0.into_keys(),
        }
    }

    pub fn into_values(self) -> btree_map::PopulatedIntoValues<K, V> {
        btree_map::PopulatedIntoValues {
            iter: self.0.into_values(),
        }
    }
}

// Indexing BTreeMap
impl<K, V> std::ops::Index<&K> for PopulatedBTreeMap<K, V>
where
    K: Ord,
{
    type Output = V;

    fn index(&self, key: &K) -> &V {
        &self.0[key]
    }
}

/// A populated (i.e. guaranteed to be non-empty) ordered set based on a B-Tree.
#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct PopulatedBTreeSet<T>(BTreeSet<T>);

impl<T> From<PopulatedBTreeSet<T>> for BTreeSet<T> {
    fn from(populated_btree_set: PopulatedBTreeSet<T>) -> BTreeSet<T> {
        populated_btree_set.0
    }
}

impl<T> TryFrom<BTreeSet<T>> for PopulatedBTreeSet<T> {
    type Error = BTreeSet<T>;

    fn try_from(btree_set: BTreeSet<T>) -> Result<PopulatedBTreeSet<T>, Self::Error> {
        if btree_set.is_empty() {
            Err(btree_set)
        } else {
            Ok(PopulatedBTreeSet(btree_set))
        }
    }
}

impl<T> PopulatedBTreeSet<T> {
    pub fn iter(&self) -> btree_set::PopulatedIter<T> {
        self.into_populated_iter()
    }
}

impl<T: Ord> PopulatedBTreeSet<T> {
    /// Creates a singleton set with the given value.
    pub fn new(value: T) -> PopulatedBTreeSet<T> {
        PopulatedBTreeSet(BTreeSet::from([value]))
    }

    /// Visits the elements representing the difference, i.e., the
    /// elements that are in self but not in other, in ascending order.
    pub fn difference<'a>(
        &'a self,
        other: &'a BTreeSet<T>,
    ) -> std::collections::btree_set::Difference<'a, T> {
        self.0.difference(other)
    }

    /// Visits the elements representing the symmetric difference, i.e.,
    /// the elements that are in self or in other but not in both, in
    /// ascending order.
    pub fn symmetric_difference<'a>(
        &'a self,
        other: &'a BTreeSet<T>,
    ) -> std::collections::btree_set::SymmetricDifference<'a, T> {
        self.0.symmetric_difference(other)
    }

    /// Visits the elements representing the intersection, i.e., the
    /// elements that are both in self and other, in ascending order.
    pub fn intersection<'a>(
        &'a self,
        other: &'a BTreeSet<T>,
    ) -> std::collections::btree_set::Intersection<'a, T> {
        self.0.intersection(other)
    }

    // TODO: union should return a populated iterator

    /// Returns true if the populated set contains an element equal to the
    /// value.
    ///
    /// The value may be any borrowed form of the set’s element type, but
    /// the ordering on the borrowed form must match the ordering on the
    /// element type.
    pub fn contains<Q: Ord + ?Sized>(&self, value: &Q) -> bool
    where
        T: Borrow<Q>,
    {
        self.0.contains(value)
    }

    /// Returns a reference to the element in the populated set, if any,
    /// that is equal to the value.
    ///
    /// The value may be any borrowed form of the set’s element type, but
    /// the ordering on the borrowed form must match the ordering on the
    /// element type.
    pub fn get<Q: Ord + ?Sized>(&self, value: &Q) -> Option<&T>
    where
        T: Borrow<Q>,
    {
        self.0.get(value)
    }

    /// Returns true if self has no elements in common with other. This
    /// is equivalent to checking for an empty intersection.
    pub fn is_disjoint(&self, other: &BTreeSet<T>) -> bool {
        self.0.is_disjoint(other)
    }

    /// Returns true if the set is a subset of another, i.e., other
    /// contains at least all the elements in self.
    pub fn is_subset(&self, other: &BTreeSet<T>) -> bool {
        self.0.is_subset(other)
    }

    /// Returns true if the set is a superset of another, i.e., self
    /// contains at least all the elements in other.
    pub fn is_superset(&self, other: &BTreeSet<T>) -> bool {
        self.0.is_superset(other)
    }

    /// Returns a reference to the first element in the populated set.
    /// This element is always the minimum of all elements in the set.
    pub fn first(&self) -> &T {
        self.0.first().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedBTreeSet
    }

    /// Returns a reference to the last element in the populated set. This
    /// element is always the maximum of all elements in the set.
    pub fn last(&self) -> &T {
        self.0.last().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedBTreeSet
    }

    /// Removes the first element from the populated set and returns it
    /// along with the remaining set. The first element is always the
    /// minimum element in the set.
    pub fn pop_first(self) -> (T, BTreeSet<T>) {
        let mut btree_set = self.0;
        let first = btree_set.pop_first().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeSet
        (first, btree_set)
    }

    /// Removes the last element from the set and returns it, if any. The
    /// last element is always the maximum element in the set.
    pub fn pop_last(self) -> (BTreeSet<T>, T) {
        let mut btree_set = self.0;
        let last = btree_set.pop_last().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeSet
        (btree_set, last)
    }

    /// Adds a value to the populated set.
    ///
    /// Returns whether the value was newly inserted. That is:
    ///
    /// - If the set did not previously contain an equal value, true is
    ///   returned.
    /// - If the set already contained an equal value, false is returned, and
    ///   the entry is not updated.
    pub fn insert(&mut self, value: T) -> bool {
        self.0.insert(value)
    }

    /// Adds a value to the set, replacing the existing element, if any,
    /// that is equal to the value. Returns the replaced element.
    pub fn replace(&mut self, value: T) -> Option<T> {
        self.0.replace(value)
    }

    /// Removes and returns the element in the set, if any, that is equal
    /// to the value.
    ///
    /// The value may be any borrowed form of the set’s element type, but
    /// the ordering on the borrowed form must match the ordering on the
    /// element type.
    pub fn take<Q: Ord + ?Sized>(self, value: &Q) -> Result<(T, BTreeSet<T>), PopulatedBTreeSet<T>>
    where
        T: Borrow<Q>,
    {
        let mut set = self.0;
        if let Some(value) = set.take(value) {
            Ok((value, set))
        } else {
            Err(PopulatedBTreeSet(set))
        }
    }

    /// Retains only the elements specified by the predicate.
    ///
    /// In other words, remove all elements `e` for which `f(&e)` returns
    /// `false`. The elements are visited in ascending order.
    pub fn retain(self, predicate: impl FnMut(&T) -> bool) -> BTreeSet<T> {
        let mut btree_set = self.0;
        btree_set.retain(predicate);
        btree_set
    }

    /// Moves all elements from other into self, leaving other empty.
    pub fn append(&mut self, other: &mut BTreeSet<T>) {
        self.0.append(other);
    }
}

impl<T> PopulatedBTreeSet<T> {
    /// Unpopulates the underlying set and returns it.
    pub fn clear(self) -> BTreeSet<T> {
        let mut btree_set = self.0;
        btree_set.clear();
        btree_set
    }

    /// Returns the number of elements in the set.
    pub fn len(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.len()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedBTreeSet
    }
}

impl<T> IntoIterator for PopulatedBTreeSet<T> {
    type Item = T;
    type IntoIter = std::collections::btree_set::IntoIter<T>;

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

impl<'a, T> IntoIterator for &'a PopulatedBTreeSet<T> {
    type Item = &'a T;
    type IntoIter = std::collections::btree_set::Iter<'a, T>;

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

pub mod btree_set {

    use crate::{IntoPopulatedIterator, PopulatedBTreeSet, PopulatedIterator};

    pub struct IntoPopulatedIter<T> {
        iter: std::collections::btree_set::IntoIter<T>,
    }

    impl<T> IntoIterator for IntoPopulatedIter<T> {
        type Item = T;
        type IntoIter = std::collections::btree_set::IntoIter<T>;

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

    impl<T> PopulatedIterator for IntoPopulatedIter<T> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeSet
            (first, self.iter)
        }
    }

    impl<T> IntoPopulatedIterator for std::collections::BTreeSet<T> {
        type PopulatedIntoIter = IntoPopulatedIter<T>;

        fn into_populated_iter(self) -> IntoPopulatedIter<T> {
            IntoPopulatedIter {
                iter: self.into_iter(),
            }
        }
    }

    pub struct PopulatedIter<'a, T> {
        iter: std::collections::btree_set::Iter<'a, T>,
    }

    impl<'a, T> IntoIterator for PopulatedIter<'a, T> {
        type Item = &'a T;
        type IntoIter = std::collections::btree_set::Iter<'a, T>;

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

    impl<'a, T> PopulatedIterator for PopulatedIter<'a, T> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBTreeSet
            (first, self.iter)
        }
    }

    impl<'a, T> IntoPopulatedIterator for &'a PopulatedBTreeSet<T> {
        type PopulatedIntoIter = PopulatedIter<'a, T>;

        fn into_populated_iter(self) -> PopulatedIter<'a, T> {
            PopulatedIter {
                iter: self.into_iter(),
            }
        }
    }
}

impl<T: Ord + Clone> BitOr<&PopulatedBTreeSet<T>> for &PopulatedBTreeSet<T> {
    type Output = PopulatedBTreeSet<T>;

    fn bitor(self, other: &PopulatedBTreeSet<T>) -> Self::Output {
        let btree_set = &self.0 | &other.0;
        PopulatedBTreeSet(btree_set)
    }
}

impl<T: Ord + Clone> BitOr<&BTreeSet<T>> for &PopulatedBTreeSet<T> {
    type Output = PopulatedBTreeSet<T>;

    fn bitor(self, other: &BTreeSet<T>) -> Self::Output {
        let btree_set = &self.0 | other;
        PopulatedBTreeSet(btree_set)
    }
}

impl<T: Ord + Clone> BitOr<&PopulatedBTreeSet<T>> for &BTreeSet<T> {
    type Output = PopulatedBTreeSet<T>;

    fn bitor(self, other: &PopulatedBTreeSet<T>) -> Self::Output {
        let btree_set = self | &other.0;
        PopulatedBTreeSet(btree_set)
    }
}

#[derive(Clone, Debug)]
pub struct PopulatedBinaryHeap<T>(BinaryHeap<T>);

impl<T: Ord> PopulatedBinaryHeap<T> {
    /// Creates a binary heap populated with a single value.
    pub fn new(value: T) -> PopulatedBinaryHeap<T> {
        PopulatedBinaryHeap(BinaryHeap::from([value]))
    }

    /// Creates a binary populated with a single value and the given
    /// capacity.
    pub fn with_capacity(capacity: NonZeroUsize, value: T) -> PopulatedBinaryHeap<T> {
        let mut binary_heap = BinaryHeap::with_capacity(capacity.get());
        binary_heap.push(value);
        PopulatedBinaryHeap(binary_heap)
    }

    /// Pushes an item onto the binary heap.
    pub fn push(&mut self, item: T) {
        self.0.push(item);
    }

    /// Consumes the `PopulatedBinaryHeap` and returns a populated vector
    /// in sorted (ascending) order.
    pub fn into_sorted_vec(self) -> PopulatedVec<T> {
        let vec = self.0.into_sorted_vec();
        PopulatedVec(vec)
    }

    /// Moves all the elements of other into self, leaving other empty.
    pub fn append(&mut self, other: &mut BinaryHeap<T>) {
        self.0.append(other);
    }

    /// Retains only the elements specified by the predicate.
    ///
    /// In other words, remove all elements e for which f(&e) returns
    /// false. The elements are visited in unsorted (and unspecified) order.
    ///
    /// Note that the binary heap is not guaranteed to be populated after
    /// calling this method.
    ///
    /// ```
    /// use populated::PopulatedBinaryHeap;
    /// use std::num::NonZeroUsize;
    ///
    /// let mut binary_heap = PopulatedBinaryHeap::with_capacity(NonZeroUsize::new(5).unwrap(), 1);
    /// binary_heap.push(2);
    /// binary_heap.push(3);
    /// let binary_heap = binary_heap.retain(|&x| x > 2);
    /// assert_eq!(binary_heap.len(), 1);
    /// ```
    pub fn retain(self, predicate: impl FnMut(&T) -> bool) -> BinaryHeap<T> {
        let mut binary_heap = self.0;
        binary_heap.retain(predicate);
        binary_heap
    }

    /// Removes the greatest item from the binary heap and returns it along
    /// with the remaining binary heap. Note that the returned binary heap
    /// is not guaranteed to be populated.
    ///
    /// ```
    /// use populated::PopulatedBinaryHeap;
    /// use std::num::NonZeroUsize;
    ///
    /// let mut binary_heap = PopulatedBinaryHeap::with_capacity(NonZeroUsize::new(5).unwrap(), 1);
    /// binary_heap.push(2);
    /// binary_heap.push(3);
    /// let (item, binary_heap) = binary_heap.pop();
    /// assert_eq!(item, 3);
    /// assert_eq!(binary_heap.len(), 2);
    /// ```
    pub fn pop(self) -> (T, BinaryHeap<T>) {
        let mut binary_heap = self.0;
        let item = binary_heap.pop().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBinaryHeap
        (item, binary_heap)
    }
}

impl<T> PopulatedBinaryHeap<T> {
    /// Returns the greatest item in the populated binary heap.
    ///
    /// ```
    /// use populated::PopulatedBinaryHeap;
    ///
    /// let mut binary_heap = PopulatedBinaryHeap::new(1);
    /// binary_heap.push(2);
    /// binary_heap.push(3);
    /// assert_eq!(binary_heap.peek(), &3);
    /// ```
    pub fn peek(&self) -> &T {
        self.0.peek().unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedBinaryHeap
    }

    /// Returns the number of elements the binary heap can hold without reallocating.
    ///
    /// ```
    /// use populated::PopulatedBinaryHeap;
    /// use std::num::NonZeroUsize;
    ///
    /// let binary_heap = PopulatedBinaryHeap::with_capacity(NonZeroUsize::new(10).unwrap(), 1);
    /// assert_eq!(binary_heap.capacity(), NonZeroUsize::new(10).unwrap());
    /// ```
    pub fn capacity(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.capacity()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedBinaryHeap
    }

    /// Discards as much additional capacity as possible.
    /// The capacity will never be less than the length.
    pub fn shrink_to_fit(&mut self) {
        self.0.shrink_to_fit();
    }

    /// Consumes the `PopulatedBinaryHeap` and returns a populated vector with elements in arbitrary order.
    ///
    /// ```
    /// use populated::PopulatedBinaryHeap;
    ///
    /// let mut binary_heap = PopulatedBinaryHeap::new(1);
    /// binary_heap.push(2);
    /// binary_heap.push(3);
    /// let vec = binary_heap.into_vec();
    /// assert_eq!(vec.len().get(), 3);
    /// ```
    pub fn into_vec(self) -> PopulatedVec<T> {
        let vec = self.0.into_vec();
        PopulatedVec(vec)
    }

    /// Returns the number of elements in the binary heap. Guaranteed to be non-zero.
    ///
    /// ```
    /// use populated::PopulatedBinaryHeap;
    ///
    /// let mut binary_heap = PopulatedBinaryHeap::new(1);
    /// binary_heap.push(2);
    /// binary_heap.push(3);
    /// assert_eq!(binary_heap.len().get(), 3);
    /// ```
    pub fn len(&self) -> NonZeroUsize {
        NonZeroUsize::new(self.0.len()).unwrap() // TODO: this can be done without unwrap safely because this is a PopulatedBinaryHeap
    }

    /// Drops all items from the binary heap. Since the underlying binary heap is now empty, the return value is the underlying binary heap that
    /// that is empty but still allocated.
    ///
    /// ```
    /// use populated::PopulatedBinaryHeap;
    /// use std::num::NonZeroUsize;
    ///
    /// let mut binary_heap = PopulatedBinaryHeap::with_capacity(NonZeroUsize::new(5).unwrap(), 1);
    /// binary_heap.push(2);
    /// binary_heap.push(3);
    /// let binary_heap = binary_heap.clear();
    /// assert_eq!(binary_heap.len(), 0);
    /// assert_eq!(binary_heap.capacity(), 5);
    /// ```
    pub fn clear(self) -> BinaryHeap<T> {
        let mut binary_heap = self.0;
        binary_heap.clear();
        binary_heap
    }
}

impl<T> IntoIterator for PopulatedBinaryHeap<T> {
    type Item = T;
    type IntoIter = std::collections::binary_heap::IntoIter<T>;

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

impl<'a, T> IntoIterator for &'a PopulatedBinaryHeap<T> {
    type Item = &'a T;
    type IntoIter = std::collections::binary_heap::Iter<'a, T>;

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

impl<T> From<PopulatedBinaryHeap<T>> for PopulatedVec<T> {
    fn from(populated_binary_heap: PopulatedBinaryHeap<T>) -> PopulatedVec<T> {
        PopulatedVec(Vec::from(populated_binary_heap.0))
    }
}

impl<T: Ord> From<PopulatedVec<T>> for PopulatedBinaryHeap<T> {
    fn from(populated_vec: PopulatedVec<T>) -> PopulatedBinaryHeap<T> {
        PopulatedBinaryHeap(BinaryHeap::from(populated_vec.0))
    }
}

pub mod binary_heap {
    use crate::{IntoPopulatedIterator, PopulatedBinaryHeap, PopulatedIterator};

    pub struct IntoPopulatedIter<T> {
        iter: std::collections::binary_heap::IntoIter<T>,
    }

    impl<T> IntoIterator for IntoPopulatedIter<T> {
        type Item = T;
        type IntoIter = std::collections::binary_heap::IntoIter<T>;

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

    impl<T> PopulatedIterator for IntoPopulatedIter<T> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBinaryHeap
            (first, self.iter)
        }
    }

    impl<T> IntoPopulatedIterator for PopulatedBinaryHeap<T> {
        type PopulatedIntoIter = IntoPopulatedIter<T>;

        fn into_populated_iter(self) -> IntoPopulatedIter<T> {
            IntoPopulatedIter {
                iter: self.0.into_iter(),
            }
        }
    }

    pub struct PopulatedIter<'a, T> {
        iter: std::collections::binary_heap::Iter<'a, T>,
    }

    impl<'a, T> IntoIterator for PopulatedIter<'a, T> {
        type Item = &'a T;
        type IntoIter = std::collections::binary_heap::Iter<'a, T>;

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

    impl<'a, T> PopulatedIterator for PopulatedIter<'a, T> {
        fn next(mut self) -> (Self::Item, Self::IntoIter) {
            let first = self.iter.next().unwrap(); // TODO: this can be done without unwrap safely because this is a PopulatedBinaryHeap
            (first, self.iter)
        }
    }

    impl<'a, T> IntoPopulatedIterator for &'a PopulatedBinaryHeap<T> {
        type PopulatedIntoIter = PopulatedIter<'a, T>;

        fn into_populated_iter(self) -> PopulatedIter<'a, T> {
            PopulatedIter {
                iter: self.into_iter(),
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PopulatedString(String);

#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(transparent)]
pub struct PopulatedStr(str);

// Write a macro for constructing a PopulatedStr from a string literal safely

/// Constructs a `PopulatedStr` from a string literal safely.
///
/// # Example
///
/// ```
/// use populated::pstr;
/// use populated::PopulatedStr;
/// use std::convert::TryFrom;
///
/// assert_eq!("Hello, world!", pstr!("Hello, world!").as_str());
/// ```
///
/// ```compile_fail
/// use populated::pstr;
/// use populated::PopulatedStr;
/// use std::convert::TryFrom;
///
/// assert_eq!("", pstr!("").as_str());
/// ```
///
/// # Safety
///
/// This macro is safe to use because it constructs a `PopulatedStr`
/// from a string literal in a way that is guaranteed to be safe.
#[macro_export]
macro_rules! pstr {
    ($string:literal) => {{
        const TEXT: &'static PopulatedStr = PopulatedStr::from_str_panic_if_empty($string);

        TEXT
    }};
}

impl From<PopulatedString> for String {
    fn from(populated_string: PopulatedString) -> String {
        populated_string.0
    }
}

impl<'a> From<&'a PopulatedStr> for &'a str {
    fn from(populated_str: &'a PopulatedStr) -> &'a str {
        &populated_str.0
    }
}

impl<'a> From<&'a mut PopulatedStr> for &'a mut str {
    fn from(populated_str: &'a mut PopulatedStr) -> &'a mut str {
        &mut populated_str.0
    }
}

impl TryFrom<String> for PopulatedString {
    type Error = String;

    fn try_from(string: String) -> Result<PopulatedString, String> {
        if string.is_empty() {
            Err(string)
        } else {
            Ok(PopulatedString(string))
        }
    }
}

impl TryFrom<&str> for PopulatedString {
    type Error = UnpopulatedError;

    fn try_from(string: &str) -> Result<PopulatedString, UnpopulatedError> {
        if string.is_empty() {
            Err(UnpopulatedError)
        } else {
            Ok(PopulatedString(string.to_string()))
        }
    }
}

impl From<&PopulatedStr> for PopulatedString {
    fn from(populated_str: &PopulatedStr) -> PopulatedString {
        PopulatedString(populated_str.0.to_string())
    }
}

impl<'a> TryFrom<&'a str> for &'a PopulatedStr {
    type Error = UnpopulatedError;

    fn try_from(string: &'a str) -> Result<&'a PopulatedStr, UnpopulatedError> {
        if string.is_empty() {
            Err(UnpopulatedError)
        } else {
            Ok(unsafe { &*(string as *const str as *const PopulatedStr) })
        }
    }
}

impl<'a> TryFrom<&'a mut str> for &'a mut PopulatedStr {
    type Error = UnpopulatedError;

    fn try_from(string: &'a mut str) -> Result<&'a mut PopulatedStr, UnpopulatedError> {
        if string.is_empty() {
            Err(UnpopulatedError)
        } else {
            Ok(unsafe { &mut *(string as *mut str as *mut PopulatedStr) })
        }
    }
}

impl Deref for PopulatedString {
    type Target = PopulatedStr;
    fn deref(&self) -> &Self::Target {
        unsafe { &*(self.0.as_str() as *const str as *const PopulatedStr) }
    }
}

impl DerefMut for PopulatedString {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *(self.0.as_mut_str() as *mut str as *mut PopulatedStr) }
    }
}

impl<'a> Extend<&'a str> for PopulatedString {
    fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) {
        self.0.extend(iter)
    }
}

impl<'a> Extend<&'a PopulatedStr> for PopulatedString {
    fn extend<T: IntoIterator<Item = &'a PopulatedStr>>(&mut self, iter: T) {
        self.0
            .extend(iter.into_iter().map(|populated_str| &populated_str.0))
    }
}

impl<'a> Extend<&'a PopulatedStr> for String {
    fn extend<T: IntoIterator<Item = &'a PopulatedStr>>(&mut self, iter: T) {
        self.extend(iter.into_iter().map(|populated_str| &populated_str.0))
    }
}

impl PopulatedString {
    pub fn as_str(&self) -> &PopulatedStr {
        self.deref()
    }

    pub fn as_mut_str(&mut self) -> &mut PopulatedStr {
        &mut *self
    }
    pub fn push_str(&mut self, string: &str) {
        self.0.push_str(string);
    }

    pub fn pushed_str(mut string: String, other: &PopulatedStr) -> PopulatedString {
        string.push_str(&other.0);
        PopulatedString(string)
    }

    pub fn capacity(&self) -> NonZeroUsize {
        unsafe { NonZeroUsize::new_unchecked(self.0.capacity()) }
    }

    pub fn push(&mut self, ch: char) {
        self.0.push(ch);
    }

    pub fn pushed(mut string: String, ch: char) -> PopulatedString {
        string.push(ch);
        PopulatedString(string)
    }

    pub fn pop(self) -> (String, char) {
        let mut string = self.0;
        let ch = string.pop().unwrap();
        (string, ch)
    }

    pub fn insert(&mut self, index: usize, ch: char) {
        self.0.insert(index, ch);
    }

    pub fn inserted(mut string: String, index: usize, ch: char) -> PopulatedString {
        string.insert(index, ch);
        PopulatedString(string)
    }

    pub fn insert_str(&mut self, index: usize, string: &str) {
        self.0.insert_str(index, string);
    }

    pub fn inserted_str(mut string: String, index: usize, other: &PopulatedStr) -> PopulatedString {
        string.insert_str(index, &other.0);
        PopulatedString(string)
    }

    pub fn len(&self) -> NonZeroUsize {
        unsafe { NonZeroUsize::new_unchecked(self.0.len()) }
    }

    pub fn split_off(&mut self, at: NonZeroUsize) -> String {
        self.0.split_off(at.get())
    }

    pub fn split_at_into(self, at: usize) -> (String, String) {
        let mut text = self.0;
        let other = text.split_off(at);
        (text, other)
    }

    pub fn clear(self) -> String {
        let mut text = self.0;
        text.clear();
        text
    }

    pub fn replace_range(&mut self, range: impl RangeBounds<usize>, replace_with: &PopulatedStr) {
        self.0.replace_range(range, &replace_with.0);
    }
}

impl PopulatedStr {
    pub const fn from_str_panic_if_empty(str: &str) -> &PopulatedStr {
        if str.is_empty() {
            panic!("Attempted to create a PopulatedStr from an empty string");
        }
        unsafe { &*(str as *const str as *const PopulatedStr) }
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns the length of `self`.
    ///
    /// This length is in bytes, not chars or graphemes. In other words, it might not be what a
    /// human considers the length of the string.
    pub fn len(&self) -> NonZeroUsize {
        unsafe { NonZeroUsize::new_unchecked(self.0.len()) }
    }

    pub fn is_char_boundary(&self, index: usize) -> bool {
        self.0.is_char_boundary(index)
    }

    pub fn split_at_populated(&self, mid: NonZeroUsize) -> (&PopulatedStr, &str) {
        let (left, right) = self.0.split_at(mid.get());
        (
            unsafe { &*(left as *const str as *const PopulatedStr) },
            right,
        )
    }

    pub fn split_at(&self, mid: usize) -> (&str, &str) {
        self.0.split_at(mid)
    }

    /// Returns a populated iterator over the chars of a string slice.
    pub fn chars(&self) -> str::Chars {
        str::Chars {
            inner: self.0.chars(),
        }
    }

    /// Returns the lowercase equivalent of this `PopulatedStr` slice, as a new `PopulatedString`.
    ///
    /// ‘Lowercase’ is defined according to the terms of the Unicode Derived Core Property
    /// `Lowercase`.
    ///
    /// Since some characters can expand into multiple characters when changing the case, this
    /// function returns a `PopulatedString` instead of modifying the parameter in-place.
    pub fn to_lowercase(&self) -> PopulatedString {
        PopulatedString(self.0.to_lowercase())
    }

    /// Returns the uppercase equivalent of this `PopulatedStr` slice, as a new `PopulatedString`.
    ///
    /// ‘Uppercase’ is defined according to the terms of the Unicode Derived Core Property
    /// `Uppercase`.
    ///
    /// Since some characters can expand into multiple characters when changing the case, this
    /// function returns a `PopulatedString` instead of modifying the parameter in-place.
    pub fn to_uppercase(&self) -> PopulatedString {
        PopulatedString(self.0.to_uppercase())
    }

    /// Creates a new `PopulatedString` by repeating a string n times. `n` must be greater than
    /// 0 to preserve populatedness.
    pub fn repeat(&self, n: NonZeroUsize) -> PopulatedString {
        PopulatedString(self.0.repeat(n.get()))
    }

    /// Returns a string slice with leading and trailing whitespace removed.
    ///
    /// ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property
    /// White_Space, which includes newlines.
    pub fn trim(&self) -> &str {
        self.0.trim()
    }

    /// Returns a string slice with leading whitespace removed.
    ///
    /// ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property
    /// White_Space, which includes newlines.
    pub fn trim_start(&self) -> &str {
        self.0.trim_start()
    }

    /// Returns a string slice with trailing whitespace removed.
    ///
    /// ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property
    /// White_Space, which includes newlines.
    pub fn trim_end(&self) -> &str {
        self.0.trim_end()
    }
}

pub mod str {
    use crate::{PopulatedDoubleEndedIterator, PopulatedIterator};

    pub struct Chars<'a> {
        pub(crate) inner: std::str::Chars<'a>,
    }

    impl<'a> IntoIterator for Chars<'a> {
        type Item = char;
        type IntoIter = std::str::Chars<'a>;

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

    impl<'a> PopulatedIterator for Chars<'a> {
        fn next(self) -> (Self::Item, Self::IntoIter) {
            let mut iter = self.inner;
            let first = iter.next().unwrap();
            (first, iter)
        }
    }

    impl<'a> PopulatedDoubleEndedIterator for Chars<'a> {
        fn next_back(self) -> (Self::IntoIter, Self::Item) {
            let mut iter = self.inner;
            let last = iter.next_back().unwrap();
            (iter, last)
        }
    }
}

impl PartialEq<str> for PopulatedStr {
    fn eq(&self, other: &str) -> bool {
        self.0 == *other
    }
}

impl PartialEq<PopulatedStr> for str {
    fn eq(&self, other: &PopulatedStr) -> bool {
        *self == other.0
    }
}

impl AsRef<PopulatedStr> for PopulatedString {
    fn as_ref(&self) -> &PopulatedStr {
        self.as_str()
    }
}

impl AsMut<PopulatedStr> for PopulatedString {
    fn as_mut(&mut self) -> &mut PopulatedStr {
        self.as_mut_str()
    }
}

impl Borrow<PopulatedStr> for PopulatedString {
    fn borrow(&self) -> &PopulatedStr {
        self.as_str()
    }
}

impl BorrowMut<PopulatedStr> for PopulatedString {
    fn borrow_mut(&mut self) -> &mut PopulatedStr {
        self.as_mut_str()
    }
}

impl ToOwned for PopulatedStr {
    type Owned = PopulatedString;

    fn to_owned(&self) -> Self::Owned {
        PopulatedString(self.0.to_owned())
    }
}

impl AsRef<str> for PopulatedStr {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Borrow<str> for PopulatedStr {
    fn borrow(&self) -> &str {
        &self.0
    }
}

// methods are likely to collide with the target type, so probably not a good idea
// to implement Deref for PopulatedStr
// impl Deref for PopulatedStr {
//     type Target = str;

//     fn deref(&self) -> &Self::Target {
//         &self.0
//     }
// }

impl Add<&str> for PopulatedString {
    type Output = PopulatedString;

    fn add(self, other: &str) -> Self::Output {
        PopulatedString(self.0 + other)
    }
}

impl Add<&PopulatedStr> for String {
    type Output = PopulatedString;

    fn add(self, other: &PopulatedStr) -> Self::Output {
        PopulatedString(self + &other.0)
    }
}

impl AddAssign<&str> for PopulatedString {
    fn add_assign(&mut self, other: &str) {
        self.0 += other;
    }
}

impl AddAssign<&PopulatedStr> for PopulatedString {
    fn add_assign(&mut self, other: &PopulatedStr) {
        self.0 += &other.0;
    }
}

impl<'a> FromPopulatedIterator<&'a PopulatedStr> for PopulatedString {
    fn from_populated_iter(iter: impl IntoPopulatedIterator<Item = &'a PopulatedStr>) -> Self {
        PopulatedString(iter.into_iter().map(|ps| &ps.0).collect())
    }
}

// Add tests for unsafe coercions involving PopulatedSlice

#[cfg(test)]
mod tests {
    use super::*;
    use std::num::NonZeroUsize;

    #[test]
    fn test_populated_vec() {
        let mut vec = pvec![1, 2, 3];
        assert_eq!(vec.len().get(), 3);
        assert_eq!(vec[0], 1);
        assert_eq!(vec[1], 2);
        assert_eq!(vec[2], 3);
        assert_eq!(vec.first(), &1);
        assert_eq!(vec.last(), &3);
        assert_eq!(vec.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
        assert_eq!(
            vec.iter_mut().collect::<Vec<_>>(),
            vec![&mut 1, &mut 2, &mut 3]
        );
        assert_eq!(vec.clone().into_iter().collect::<Vec<_>>(), vec![1, 2, 3]);
        assert_eq!(
            vec.clone().into_populated_iter().collect::<Vec<_>>(),
            vec![1, 2, 3]
        );
        assert_eq!(vec.capacity(), NonZeroUsize::new(3).unwrap());
        assert_eq!(vec.clone().clear().len(), 0);
        assert_eq!(vec.into_inner(), vec![1, 2, 3]);

        let mut vec = PopulatedVec::with_capacity(NonZeroUsize::new(5).unwrap(), 1);
        vec.push(2);
        vec.push(3);
        assert_eq!(vec.len().get(), 3);
        assert_eq!(vec.capacity(), NonZeroUsize::new(5).unwrap());

        let mut other = vec![4, 5, 6];
        vec.append(&mut other);
        assert_eq!(vec.len().get(), 6);
    }

    #[test]
    fn test_populated_btree_map() {
        let mut btree_map = PopulatedBTreeMap::new(0, 0);
        btree_map.insert(1, 2);
        btree_map.insert(3, 4);
        assert_eq!(btree_map.len().get(), 3);
        assert_eq!(btree_map[&1], (2));
        assert_eq!(btree_map.get_mut(&1), Some(&mut 2));
        assert_eq!(btree_map.contains_key(&1), true);
        assert_eq!(btree_map.contains_key(&2), false);
        assert_eq!(
            btree_map.iter().collect::<Vec<_>>(),
            vec![(&0, &0), (&1, &2), (&3, &4)]
        );
        assert_eq!(
            btree_map.iter_mut().collect::<Vec<_>>(),
            vec![(&0, &mut 0), (&1, &mut 2), (&3, &mut 4)]
        );
        assert_eq!(
            btree_map.clone().into_iter().collect::<Vec<_>>(),
            vec![(0, 0), (1, 2), (3, 4)]
        );
        assert_eq!(
            btree_map.clone().into_populated_iter().collect::<Vec<_>>(),
            vec![(0, 0), (1, 2), (3, 4)]
        );

        let (value, regular_btree_map) = btree_map.clone().remove(&0).unwrap();
        assert_eq!(value, 0);
        assert_eq!(regular_btree_map.len(), 2);

        let mut other = BTreeMap::from([(4, 5), (6, 7)]);
        btree_map.append(&mut other);
        assert_eq!(btree_map.len().get(), 5);
    }

    #[test]
    fn test_populated_btree_set() {
        let mut btree_set = PopulatedBTreeSet::new(1);
        btree_set.insert(2);
        btree_set.insert(3);
        assert_eq!(btree_set.len().get(), 3);
        assert_eq!(btree_set.contains(&1), true);
        assert_eq!(btree_set.contains(&4), false);
        assert_eq!(btree_set.is_disjoint(&BTreeSet::from([4, 5, 6])), true);
        assert_eq!(btree_set.is_subset(&BTreeSet::from([1, 2, 3, 4])), true);
        assert_eq!(btree_set.is_superset(&BTreeSet::from([1, 2, 3])), true);
        assert_eq!(btree_set.first(), &1);
        assert_eq!(btree_set.last(), &3);
        assert_eq!(btree_set.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);

        assert_eq!(
            btree_set.clone().into_iter().collect::<Vec<_>>(),
            vec![1, 2, 3]
        );
        assert_eq!(
            btree_set.clone().into_populated_iter().collect::<Vec<_>>(),
            vec![&1, &2, &3]
        );

        assert_eq!(
            btree_set
                .clone()
                .difference(&BTreeSet::from([1, 2, 3]))
                .count(),
            0
        );
        assert_eq!(
            btree_set
                .clone()
                .symmetric_difference(&BTreeSet::from([1, 2, 3]))
                .count(),
            0
        );
        assert_eq!(
            btree_set
                .clone()
                .intersection(&BTreeSet::from([1, 2, 3]))
                .count(),
            3
        );

        assert_eq!(btree_set.clone().retain(|&x| x > 2).len(), 1);
        assert_eq!(btree_set.clone().pop_first().0, 1);
        assert_eq!(btree_set.clone().pop_last().1, 3);

        let mut other = BTreeSet::from([4, 5, 6]);
        btree_set.append(&mut other);
        assert_eq!(btree_set.len().get(), 6);
        assert_eq!(other.len(), 0);

        let btree_set = &btree_set | &BTreeSet::from([7, 8, 9]);
        assert_eq!(btree_set.len().get(), 9);

        // Check for equality
        let mut btree_set = PopulatedBTreeSet::new(1);
        btree_set.insert(2);
        btree_set.insert(3);
        let mut other = PopulatedBTreeSet::new(3);
        other.insert(2);
        other.insert(1);
        assert_eq!(btree_set, other);
    }

    #[test]
    fn test_populated_binary_heap() {
        let mut binary_heap = PopulatedBinaryHeap::new(1);
        binary_heap.push(2);
        binary_heap.push(3);
        assert_eq!(binary_heap.len().get(), 3);
        assert_eq!(binary_heap.peek(), &3);
        assert_eq!(binary_heap.clone().into_vec().len().get(), 3);
        assert_eq!(binary_heap.clone().into_sorted_vec().len().get(), 3);
        assert_eq!(binary_heap.clone().clear().len(), 0);
        assert_eq!(binary_heap.clone().pop().0, 3);
        assert_eq!(binary_heap.clone().pop().1.len(), 2);
        assert_eq!(binary_heap.clone().retain(|&x| x > 2).len(), 1);

        let mut other = BinaryHeap::from([4, 5, 6]);
        binary_heap.append(&mut other);
        assert_eq!(binary_heap.len().get(), 6);
    }

    #[test]
    fn test_populated_slice() {
        let test = [1, 2, 3];
        let slice: &PopulatedSlice<_> = TryFrom::try_from(&test[..]).unwrap();
        assert_eq!(slice.len().get(), 3);
        assert_eq!(slice[0], 1);
        assert_eq!(slice[1], 2);
        assert_eq!(slice[2], 3);
        assert_eq!(slice.first(), &1);
        assert_eq!(slice.last(), &3);
        assert_eq!(slice.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
    }

    #[test]
    fn test_populated_slice_mut() {
        let mut test = [1, 2, 3];
        let slice: &mut PopulatedSlice<_> = TryFrom::try_from(&mut test[..]).unwrap();
        assert_eq!(slice.len().get(), 3);
        assert_eq!(slice[0], 1);
        assert_eq!(slice[1], 2);
        assert_eq!(slice[2], 3);
        assert_eq!(slice.first(), &1);
        assert_eq!(slice.last(), &3);
        assert_eq!(slice.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
    }

    #[test]
    fn test_populated_slice_from_vec() {
        let vec = vec![1, 2, 3];
        let slice: &PopulatedSlice<_> = TryFrom::try_from(&vec[..]).unwrap();
        assert_eq!(slice.len().get(), 3);
        assert_eq!(slice[0], 1);
        assert_eq!(slice[1], 2);
        assert_eq!(slice[2], 3);
        assert_eq!(slice.first(), &1);
        assert_eq!(slice.last(), &3);
        assert_eq!(slice.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
    }

    #[test]
    fn test_populated_slice_mut_from_vec() {
        let mut vec = vec![1, 2, 3];
        let slice: &mut PopulatedSlice<_> = TryFrom::try_from(&mut vec[..]).unwrap();
        assert_eq!(slice.len().get(), 3);
        assert_eq!(slice[0], 1);
        assert_eq!(slice[1], 2);
        assert_eq!(slice[2], 3);
        assert_eq!(slice.first(), &1);
        assert_eq!(slice.last(), &3);
        assert_eq!(slice.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
    }

    #[test]
    fn test_populated_slice_from_slice() {
        let slice = &[1, 2, 3][..];
        let slice: &PopulatedSlice<_> = TryFrom::try_from(slice).unwrap();
        assert_eq!(slice.len().get(), 3);
        assert_eq!(slice[0], 1);
        assert_eq!(slice[1], 2);
        assert_eq!(slice[2], 3);
        assert_eq!(slice.first(), &1);
        assert_eq!(slice.last(), &3);
        assert_eq!(slice.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
    }

    #[test]
    fn test_populated_slice_mut_from_slice() {
        let slice = &mut [1, 2, 3][..];
        let slice: &mut PopulatedSlice<_> = TryFrom::try_from(slice).unwrap();
        assert_eq!(slice.len().get(), 3);
        assert_eq!(slice[0], 1);
        assert_eq!(slice[1], 2);
        assert_eq!(slice[2], 3);
        assert_eq!(slice.first(), &1);
        assert_eq!(slice.last(), &3);
        assert_eq!(slice.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
    }

    #[test]
    fn test_populated_slice_from_populated_vec() {
        let vec = PopulatedVec(vec![1, 2, 3]);
        let slice: &PopulatedSlice<_> = TryFrom::try_from(&vec[..]).unwrap();
        assert_eq!(slice.len().get(), 3);
        assert_eq!(slice[0], 1);
        assert_eq!(slice[1], 2);
        assert_eq!(slice[2], 3);
        assert_eq!(slice.first(), &1);
        assert_eq!(slice.last(), &3);
        assert_eq!(slice.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
    }

    #[test]
    fn test_populated_slice_mut_from_populated_vec() {
        let mut vec = PopulatedVec(vec![1, 2, 3]);
        let slice: &mut PopulatedSlice<_> = TryFrom::try_from(&mut vec[..]).unwrap();
        assert_eq!(slice.len().get(), 3);
        assert_eq!(slice[0], 1);
        assert_eq!(slice[1], 2);
        assert_eq!(slice[2], 3);
        assert_eq!(slice.first(), &1);
        assert_eq!(slice.last(), &3);
        assert_eq!(slice.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
    }

    #[test]
    fn test_populated_slice_from_populated_slice() {
        let slice: &PopulatedSlice<_> = TryFrom::try_from(&[1, 2, 3][..]).unwrap();
        assert_eq!(slice.len().get(), 3);
        assert_eq!(slice[0], 1);
        assert_eq!(slice[1], 2);
        assert_eq!(slice[2], 3);
        assert_eq!(slice.first(), &1);
        assert_eq!(slice.last(), &3);
        assert_eq!(slice.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
    }

    #[test]
    fn test_populated_slice_mut_from_populated_slice() {
        let mut array = [1, 2, 3];
        let slice: &mut PopulatedSlice<_> = TryFrom::try_from(&mut array[..]).unwrap();
        assert_eq!(slice.len().get(), 3);
        assert_eq!(slice[0], 1);
        assert_eq!(slice[1], 2);
        assert_eq!(slice[2], 3);
        assert_eq!(slice.first(), &1);
        assert_eq!(slice.last(), &3);
        assert_eq!(slice.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
    }

    #[test]
    fn test_populated_vec_deque() {
        let mut vec_deque = PopulatedVecDeque::new(1);
        vec_deque.push_back(2);
        vec_deque.push_back(3);
        assert_eq!(vec_deque.len().get(), 3);
        assert_eq!(vec_deque[0], 1);
        assert_eq!(vec_deque[1], 2);
        assert_eq!(vec_deque[2], 3);
        assert_eq!(vec_deque.front(), &1);
        assert_eq!(vec_deque.back(), &3);
        assert_eq!(vec_deque.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
        assert_eq!(
            vec_deque.iter_mut().collect::<Vec<_>>(),
            vec![&mut 1, &mut 2, &mut 3]
        );
        assert_eq!(
            vec_deque.clone().into_iter().collect::<Vec<_>>(),
            vec![1, 2, 3]
        );
        assert_eq!(
            vec_deque.clone().into_populated_iter().collect::<Vec<_>>(),
            vec![1, 2, 3]
        );
        assert_eq!(vec_deque.clone().clear().len(), 0);
        assert_eq!(vec_deque.clone().pop_front(), (1, VecDeque::from([2, 3])));
        assert_eq!(vec_deque.clone().pop_back(), (VecDeque::from([1, 2]), 3));
    }

    #[test]
    fn test_populated_hash_map() {
        use std::collections::HashSet;

        let mut hash_map = PopulatedHashMap::new(1, 2);
        hash_map.insert(3, 4);

        assert_eq!(hash_map.len().get(), 2);
        assert_eq!(hash_map[&1], 2);
        assert_eq!(hash_map.get_mut(&1), Some(&mut 2));
        assert_eq!(hash_map.contains_key(&1), true);
        assert_eq!(hash_map.contains_key(&2), false);

        let clone_iter_set: HashSet<_> = hash_map.clone().into_iter().collect();
        let expected_clone_set: HashSet<_> = vec![(1, 2), (3, 4)].into_iter().collect();
        assert_eq!(clone_iter_set, expected_clone_set);

        let clone_populated_iter_set: HashSet<_> = hash_map.clone().into_populated_iter().collect();
        let expected_populated_set: HashSet<_> = vec![(1, 2), (3, 4)].into_iter().collect();
        assert_eq!(clone_populated_iter_set, expected_populated_set);
    }

    #[test]
    fn test_populated_hash_set() {
        let mut hash_set = PopulatedHashSet::new(1);
        hash_set.insert(2);
        hash_set.insert(3);
        assert_eq!(hash_set.len().get(), 3);
        assert_eq!(hash_set.contains(&1), true);
        assert_eq!(hash_set.contains(&4), false);
        assert_eq!(hash_set.is_disjoint(&HashSet::from([4, 5, 6])), true);
        assert_eq!(hash_set.is_subset(&HashSet::from([1, 2, 3, 4])), true);
        assert_eq!(hash_set.is_superset(&HashSet::from([1, 2, 3])), true);

        assert_eq!(hash_set, HashSet::from([1, 2, 3]));
    }

    #[test]
    fn test_populated_string() {
        let string = pstr!("hello");
        assert_eq!(string.len().get(), 5);
        assert_eq!(string.chars().collect::<String>(), "hello");
        assert_eq!(string.chars().rev().collect::<String>(), "olleh");
        assert_eq!(string.chars().nth(0).0, Some('h'));
        assert_eq!(string.chars().last(), 'o');
        assert_eq!(string.chars().count().get(), 5);
        assert_eq!(
            string.chars().collect::<Vec<_>>(),
            vec!['h', 'e', 'l', 'l', 'o']
        );
    }
}