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
//! Janet array (vector) type.
use core::{
    cmp::Ordering,
    fmt::{self, Debug, Write},
    iter::FusedIterator,
    marker::PhantomData,
    ops::{Bound, Index, IndexMut, Range, RangeBounds},
    ptr,
    slice::{
        Chunks, ChunksExact, ChunksExactMut, ChunksMut, RChunks, RChunksExact, RChunksExactMut,
        RChunksMut, Windows,
    },
};

use evil_janet::{Janet as CJanet, JanetArray as CJanetArray};

use crate::jpanic;

use super::{DeepEq, Janet, JanetExtend, JanetTuple};

pub type Split<'a, P> = core::slice::Split<'a, Janet, P>;
pub type SplitMut<'a, P> = core::slice::SplitMut<'a, Janet, P>;
pub type RSplit<'a, P> = core::slice::RSplit<'a, Janet, P>;
pub type RSplitMut<'a, P> = core::slice::RSplitMut<'a, Janet, P>;
pub type SplitN<'a, P> = core::slice::SplitN<'a, Janet, P>;
pub type SplitNMut<'a, P> = core::slice::SplitNMut<'a, Janet, P>;
pub type RSplitN<'a, P> = core::slice::RSplitN<'a, Janet, P>;
pub type RSplitNMut<'a, P> = core::slice::RSplitNMut<'a, Janet, P>;


/// Janet [arrays](https://janet-lang.org/docs/data_structures/arrays.html) are a fundamental
/// datatype in Janet. Janet Arrays are values that contain a sequence of other values.
///
/// Arrays are also mutable, meaning that values can be added or removed in place.
///
/// To facilitate the creation of this structure, you can use the macro
/// [`array`](crate::array!).
///
/// # Examples
/// ```
/// use janetrs::JanetArray;
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let mut arr = JanetArray::new();
/// arr.push(10.1);
/// arr.push(12);
///
/// assert_eq!(2, arr.len());
/// ```
#[repr(transparent)]
pub struct JanetArray<'data> {
    pub(crate) raw: *mut CJanetArray,
    phantom: PhantomData<&'data ()>,
}

impl<'data> JanetArray<'data> {
    /// Creates a empty [`JanetArray`].
    ///
    /// It is initially created with capacity 0, so it will not allocate data space until
    /// it is first pushed into. There is an allocation related to the space for be
    /// object in the GC memory.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetArray;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = JanetArray::new();
    /// ```
    #[inline]
    #[must_use = "function is a constructor associated function"]
    pub fn new() -> Self {
        Self {
            raw:     unsafe { evil_janet::janet_array(0) },
            phantom: PhantomData,
        }
    }

    /// Creates a empty [`JanetArray`] that uses weak references.
    ///
    /// It is initially created with capacity 0, so it will not allocate until it is
    /// first pushed into. There is an allocation related to the space for be object in
    /// the GC memory.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetArray;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = JanetArray::weak();
    /// ```
    #[inline]
    #[crate::cjvg("1.32.0")]
    #[must_use = "function is a constructor associated function"]
    pub fn weak() -> Self {
        Self {
            raw:     unsafe { evil_janet::janet_array_weak(0) },
            phantom: PhantomData,
        }
    }

    /// Create a empty [`JanetArray`] given to Janet the specified `capacity`.
    ///
    /// When `capacity` is lesser than zero, it's the same as calling with `capacity`
    /// equals to zero.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetArray;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = JanetArray::with_capacity(20);
    /// ```
    #[inline]
    #[must_use = "function is a constructor associated function"]
    pub fn with_capacity(capacity: i32) -> Self {
        Self {
            raw:     unsafe { evil_janet::janet_array(capacity) },
            phantom: PhantomData,
        }
    }

    /// Create a empty [`JanetArray`] with weak references given to Janet the specified
    /// `capacity`.
    ///
    /// When `capacity` is lesser than zero, it's the same as calling with `capacity`
    /// equals to zero.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetArray;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = JanetArray::weak_with_capacity(20);
    /// ```
    #[inline]
    #[crate::cjvg("1.32.0")]
    #[must_use = "function is a constructor associated function"]
    pub fn weak_with_capacity(capacity: i32) -> Self {
        Self {
            raw:     unsafe { evil_janet::janet_array(capacity) },
            phantom: PhantomData,
        }
    }

    /// Create a new [`JanetArray`] with a `raw` pointer.
    ///
    /// # Safety
    /// This function do not check if the given `raw` is `NULL` or not. Use at your
    /// own risk.
    #[inline]
    pub const unsafe fn from_raw(raw: *mut CJanetArray) -> Self {
        Self {
            raw,
            phantom: PhantomData,
        }
    }

    /// Returns the number of elements the array can hold without reallocating.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetArray;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = JanetArray::with_capacity(20);
    /// assert_eq!(arr.capacity(), 20);
    /// ```
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn capacity(&self) -> i32 {
        unsafe { (*self.raw).capacity }
    }

    /// Returns the number of elements in the array, also referred to as its 'length'.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetArray;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = JanetArray::new();
    /// assert_eq!(arr.len(), 0);
    ///
    /// arr.push(10);
    /// assert_eq!(arr.len(), 1);
    /// ```
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn len(&self) -> i32 {
        unsafe { (*self.raw).count }
    }

    /// Returns `true` if the array contains no elements.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetArray;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = JanetArray::new();
    /// assert!(arr.is_empty());
    ///
    /// arr.push(10);
    /// assert!(!arr.is_empty());
    /// ```
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Splits the collection into two at the given index.
    ///
    /// Returns a newly allocated vector containing the elements in the range
    /// `[at, len)`. After the call, the original vector will be left containing
    /// the elements `[0, at)` with its previous capacity unchanged.
    ///
    /// - If you want to take ownership of the entire contents and capacity of the vector,
    ///   see [`mem::take`] or [`mem::replace`].
    /// - If you don't need the returned vector at all, see [`Vec::truncate`].
    /// - If you want to take ownership of an arbitrary subslice, or you don't necessarily
    ///   want to store the removed items in a vector, see [`Vec::drain`].
    ///
    /// # Panics
    ///
    /// Panics if `at > len`.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, assert_deep_eq};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = array![1, 2, 3];
    /// let arr2 = arr.split_off(1);
    /// assert_deep_eq!(arr, array![1]);
    /// assert_deep_eq!(arr2, array![2, 3]);
    /// ```
    #[inline]
    #[must_use = "use `.truncate()` if you don't need the other half"]
    pub fn split_off(&mut self, at: i32) -> Self {
        #[cold]
        #[track_caller]
        fn assert_failed(at: i32, len: i32) -> ! {
            crate::jpanic!("`at` split index (is {at}) should be <= len (is {len})")
        }

        if at > self.len() {
            assert_failed(at, self.len());
        }

        let other_len = self.len() - at;
        let mut other = JanetArray::with_capacity(other_len);

        self.set_len(at);

        other.set_len(other_len);

        unsafe {
            ptr::copy_nonoverlapping(
                self.as_ptr().add(at as usize),
                other.as_mut_ptr(),
                other.len() as usize,
            );
        }

        other
    }

    /// Set the length of the array to `new_len`.
    ///
    /// If `new_len` is greater than the current
    /// array length, this append [`Janet`] `nil` values into the array, and if `new_len`
    /// is lesser than the current array length, the Janet garbage collector will handle
    /// the elements not used anymore, that's the reason this function is safe to call
    /// compared to the Rust [`Vec`](Vec) method with the same name.
    ///
    /// This functions does nothing if `new_len` is lesser than zero.
    #[inline]
    pub fn set_len(&mut self, new_len: i32) {
        unsafe { evil_janet::janet_array_setcount(self.raw, new_len) };
    }

    /// Ensure that an array has enough space for `check_capacity` elements. If not,
    /// resize the backing memory to `check_capacity` * `growth` slots. In most cases,
    /// `growth` should be `1` or `2`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::JanetArray;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = JanetArray::new();
    /// assert_eq!(arr.capacity(), 0);
    ///
    /// arr.ensure(2, 2);
    /// assert_eq!(arr.capacity(), 4);
    /// ```
    #[inline]
    pub fn ensure(&mut self, check_capacity: i32, growth: i32) {
        unsafe { evil_janet::janet_array_ensure(self.raw, check_capacity, growth) };
    }

    /// Reserves capacity for at least `additional` more elements to be inserted
    /// in the given `JanetArray`. The collection may reserve more space to avoid
    /// frequent reallocations. After calling `reserve`, capacity will be
    /// greater than or equal to `self.len() + additional`. Does nothing if
    /// capacity is already sufficient.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `i32::MAX` bytes.
    ///
    /// # Examples
    /// ```
    /// use janetrs::array;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = array![1];
    /// arr.reserve(10);
    /// assert!(arr.capacity() >= 11);
    /// ```
    #[inline]
    pub fn reserve(&mut self, additional: i32) {
        if self.len() + additional > self.capacity() {
            self.ensure(self.len() + additional, 2);
        }
    }

    /// Reserves the minimum capacity for exactly `additional` more elements to
    /// be inserted in the given `JanetArray`. After calling `reserve_exact`,
    /// capacity will be greater than or equal to `self.len() + additional`.
    /// Does nothing if the capacity is already sufficient.
    ///
    /// Note that the allocator may give the collection more space than it
    /// requests. Therefore, capacity can not be relied upon to be precisely
    /// minimal. Prefer `reserve` if future insertions are expected.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `i32`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::array;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = array![1];
    /// arr.reserve_exact(10);
    /// assert_eq!(arr.capacity(), 11);
    /// ```
    #[inline]
    pub fn reserve_exact(&mut self, additional: i32) {
        if self.len() + additional > self.capacity() {
            self.ensure(self.len() + additional, 1);
        }
    }

    /// Clears the array, removing all values.
    ///
    /// Note that this method has no effect on the allocated capacity of the array.
    #[inline]
    pub fn clear(&mut self) {
        self.set_len(0);
    }

    /// Appends an element to the back of the array.
    ///
    /// # Panics
    /// Panics if the number of elements overflow a `i32`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetArray};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = JanetArray::new();
    ///
    /// arr.push(10);
    /// assert_eq!(arr[0], &Janet::integer(10));
    /// ```
    #[inline]
    pub fn push(&mut self, value: impl Into<Janet>) {
        let value = value.into();
        unsafe { evil_janet::janet_array_push(self.raw, value.inner) };
    }

    /// Appends an element if there is sufficient spare capacity, otherwise an error is
    /// returned with the element.
    ///
    /// Unlike [`push`] this method will not reallocate when there's insufficient
    /// capacity. The caller should use [`reserve`] to ensure that
    /// there is enough capacity.
    ///
    /// [`push`]: Self::push
    /// [`reserve`]: Self::reserve
    ///
    ///
    /// # Time complexity
    ///
    /// Takes *O*(1) time.
    // TODO: Examples
    #[inline]
    pub fn push_within_capacity(&mut self, value: impl Into<Janet>) -> Result<(), Janet> {
        let value = value.into();

        if self.len() == self.capacity() {
            return Err(value);
        }
        self.push(value);
        Ok(())
    }

    /// Removes the last element from a array and returns it, or None if it is
    /// empty.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetArray};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = JanetArray::new();
    ///
    /// arr.push(10);
    /// assert_eq!(arr.len(), 1);
    /// assert_eq!(arr.pop(), Some(Janet::integer(10)));
    /// assert!(arr.is_empty())
    /// ```
    #[inline]
    pub fn pop(&mut self) -> Option<Janet> {
        if self.is_empty() {
            None
        } else {
            Some(unsafe { evil_janet::janet_array_pop(self.raw).into() })
        }
    }

    /// Removes and returns the last element in a vector if the predicate
    /// returns `true`, or [`None`] if the predicate returns false or the vector
    /// is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, DeepEq, Janet, JanetArray};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut array = array![1, 2, 3, 4];
    /// let pred = |x: &mut Janet| match x.try_unwrap::<i32>() {
    ///     Ok(x) => x % 2 == 0,
    ///     Err(_) => false,
    /// };
    ///
    /// assert_eq!(array.pop_if(pred), Some(Janet::from(4)));
    /// assert!(array.deep_eq(&array![1, 2, 3]));
    /// assert_eq!(array.pop_if(pred), None);
    /// ```
    pub fn pop_if<F>(&mut self, f: F) -> Option<Janet>
    where
        F: FnOnce(&mut Janet) -> bool,
    {
        let last = self.last_mut()?;
        if f(last) { self.pop() } else { None }
    }

    /// Returns a copy of the last element in the array without modifying it.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetArray};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = JanetArray::new();
    ///
    /// arr.push(10);
    /// assert_eq!(arr.len(), 1);
    /// assert_eq!(arr.peek(), Janet::integer(10));
    /// assert_eq!(arr.len(), 1);
    /// ```
    #[inline]
    pub fn peek(&mut self) -> Janet {
        unsafe { evil_janet::janet_array_peek(self.raw).into() }
    }

    /// Returns a reference to an element in the array at the`index`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetArray};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = JanetArray::new();
    ///
    /// arr.push(10);
    /// assert_eq!(arr.get(0), Some(&Janet::integer(10)));
    /// assert_eq!(arr.get(1), None);
    /// ```
    #[inline]
    #[must_use]
    pub fn get(&self, index: i32) -> Option<&Janet> {
        if index < 0 || index >= self.len() {
            None
        } else {
            // SAFETY: it's safe because we just checked that it is in bounds
            unsafe {
                let ptr = (*self.raw).data.offset(index as isize) as *mut Janet;
                Some(&(*ptr))
            }
        }
    }

    /// Returns a mutable reference to an element in the array at the`index`.
    /// Returns a reference to an element in the array at the`index`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{Janet, JanetArray};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = JanetArray::new();
    ///
    /// arr.push(10);
    /// assert_eq!(arr.get_mut(0), Some(&mut Janet::integer(10)));
    /// assert_eq!(arr.get(1), None);
    ///
    /// *arr.get_mut(0).unwrap() = Janet::boolean(true);
    /// assert_eq!(arr[0], &Janet::boolean(true));
    /// ```
    #[inline]
    pub fn get_mut(&mut self, index: i32) -> Option<&'data mut Janet> {
        if index < 0 || index >= self.len() {
            None
        } else {
            // SAFETY: it's safe because we just checked that it is in bounds
            unsafe {
                let ptr = (*self.raw).data.offset(index as isize) as *mut Janet;
                Some(&mut (*ptr))
            }
        }
    }

    /// Returns a reference to an element, without doing bounds checking.
    ///
    /// # Safety
    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
    /// even if the resulting reference is not used.
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub unsafe fn get_unchecked(&self, index: i32) -> &Janet {
        let item = (*self.raw).data.offset(index as isize) as *const Janet;
        &*item
    }

    /// Returns a exclusive reference to an element, without doing bounds checking.
    ///
    /// # Safety
    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
    /// even if the resulting reference is not used.
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub unsafe fn get_unchecked_mut(&mut self, index: i32) -> &Janet {
        let item = (*self.raw).data.offset(index as isize) as *mut Janet;
        &mut *item
    }

    #[inline]
    #[must_use]
    pub fn get_range<R>(&self, range: R) -> Option<&[Janet]>
    where
        R: RangeBounds<i32>,
    {
        into_range(self.len(), (range.start_bound(), range.end_bound()))
            .and_then(|range| self.get_r(range))
    }

    #[inline]
    #[must_use]
    pub fn get_range_mut<R>(&mut self, range: R) -> Option<&mut [Janet]>
    where
        R: RangeBounds<i32>,
    {
        into_range(self.len(), (range.start_bound(), range.end_bound()))
            .and_then(|range| self.get_r_mut(range))
    }

    /// # Safety
    #[inline]
    pub unsafe fn get_range_unchecked<R>(&self, range: R) -> &[Janet]
    where
        R: RangeBounds<i32>,
    {
        self.get_r_unchecked(into_range_unchecked(
            self.len(),
            (range.start_bound(), range.end_bound()),
        ))
    }

    /// # Safety
    #[inline]
    pub unsafe fn get_range_unchecked_mut<R>(&mut self, range: R) -> &mut [Janet]
    where
        R: RangeBounds<i32>,
    {
        self.get_r_unchecked_mut(into_range_unchecked(
            self.len(),
            (range.start_bound(), range.end_bound()),
        ))
    }

    /// Returns `true` if the array contains an element with the given `value`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::array;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array![1.0, "foo", 4.0];
    /// assert!(arr.contains("foo"));
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn contains(&self, value: impl Into<Janet>) -> bool {
        let value = value.into();
        self.iter().any(|&elem| elem == value)
    }

    /// Moves all the elements of `other` into the array, leaving `other` empty.
    ///
    /// # Panics
    /// Panics if the number of elements overflow a `i32`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::array;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr1 = array![1, 2, 3];
    /// let mut arr2 = array![4, 5, 6];
    ///
    /// assert_eq!(arr1.len(), 3);
    /// assert!(!arr2.is_empty());
    /// arr1.append(&mut arr2);
    /// assert_eq!(arr1.len(), 6);
    /// assert!(arr2.is_empty());
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn append(&mut self, other: &mut Self) {
        other.iter().for_each(|&j| self.push(j));
        other.clear();
    }

    /// Inserts an element at position `index` within the array, shifting all elements
    /// after it to the right.
    ///
    /// # Janet Panics
    /// Janet panics if `index < 0` or `index > len`.
    ///
    /// # Examples
    /// ```
    /// use janetrs::array;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut array = array![1, 2];
    /// array.insert(1, 3) // now it's `[1, 3, 2]`
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn insert(&mut self, index: i32, element: impl Into<Janet>) {
        if index < 0 || index > self.len() + 1 {
            crate::jpanic!(
                "insertion index (is {}) should be >= 0 and <= {})",
                index,
                self.len()
            );
        } else {
            self.set_len(self.len() + 1);

            // shift all elements from index to the last one
            for i in (index..self.len()).rev() {
                self[i] = self[i - 1];
            }
            self[index] = element.into();
        }
    }

    /// Removes and returns the element at position index within the vector, shifting all
    /// elements after it to the left.
    ///
    /// # Panics
    /// Panics if `index` is out of the bounds.
    ///
    /// # Examples
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = array![1, "2", 3.0];
    /// let rmed = arr.remove(1);
    /// assert_eq!(rmed, Janet::from("2"));
    /// assert_eq!(arr.len(), 2);
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn remove(&mut self, index: i32) -> Janet {
        let ret = self[index];

        // Shift all elements to the right
        for i in index..self.len() - 1 {
            self[i] = self[i + 1];
        }

        self.set_len(self.len() - 1);

        ret
    }

    /// 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, visiting each element exactly once in the
    /// original order, and preserves the order of the retained elements.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut vec = vec![1, 2, 3, 4];
    /// vec.retain(|&x| x % 2 == 0);
    /// assert_eq!(vec, [2, 4]);
    /// ```
    ///
    /// Because the elements are visited exactly once in the original order,
    /// external state may be used to decide which elements to keep.
    ///
    /// ```
    /// let mut vec = vec![1, 2, 3, 4, 5];
    /// let keep = [false, true, true, false, true];
    /// let mut iter = keep.iter();
    /// vec.retain(|_| *iter.next().unwrap());
    /// assert_eq!(vec, [2, 3, 5]);
    /// ```
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&Janet) -> bool,
    {
        self.retain_mut(|elem| f(elem));
    }

    /// Retains only the elements specified by the predicate, 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.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, assert_deep_eq, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut array = array![1, 2, 3, 4];
    /// array.retain_mut(|x| {
    ///     let val = match x.try_unwrap::<i32>() {
    ///         Ok(x) => x,
    ///         _ => return false,
    ///     };
    ///
    ///     if val <= 3 {
    ///         *x = Janet::integer(val + 1);
    ///         true
    ///     } else {
    ///         false
    ///     }
    /// });
    ///
    /// assert_deep_eq!(array, array![2, 3, 4]);
    /// ```
    pub fn retain_mut<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut Janet) -> bool,
    {
        // Array: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
        //        |<-              processed len   ->| ^- next to check
        //                    |<-  deleted cnt     ->|
        //        |<-              original_len                          ->|
        // Kept: Elements which predicate returns true on.
        // Hole: Moved or dropped element slot.
        // Unchecked: Unchecked valid elements.
        //
        // This drop guard will be invoked when predicate or `drop` of element panicked.
        // It shifts unchecked elements to cover holes and `set_len` to the correct length.
        // In cases when predicate and `drop` never panick, it will be optimized out.
        struct BackshiftOnDrop<'a, 'data> {
            v: &'a mut JanetArray<'data>,
            processed_len: usize,
            deleted_cnt: usize,
            original_len: usize,
        }

        impl<'a, 'data> Drop for BackshiftOnDrop<'a, 'data> {
            fn drop(&mut self) {
                if self.deleted_cnt > 0 {
                    // SAFETY: Trailing unchecked items must be valid since we never touch them.
                    unsafe {
                        ptr::copy(
                            self.v.as_ptr().add(self.processed_len),
                            self.v
                                .as_mut_ptr()
                                .add(self.processed_len - self.deleted_cnt),
                            self.original_len - self.processed_len,
                        );
                    }
                }
                self.v
                    .set_len((self.original_len - self.deleted_cnt) as i32);
            }
        }

        fn process_loop<F, const DELETED: bool>(
            original_len: usize, f: &mut F, g: &mut BackshiftOnDrop<'_, '_>,
        ) where
            F: FnMut(&mut Janet) -> bool,
        {
            while g.processed_len != original_len {
                // SAFETY: Unchecked element must be valid.
                let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };
                if !f(cur) {
                    // Advance early to avoid double drop if `drop_in_place` panicked.
                    g.processed_len += 1;
                    g.deleted_cnt += 1;
                    // SAFETY: We never touch this element again after dropped.
                    // unsafe { ptr::drop_in_place(cur) };
                    // We already advanced the counter.
                    if DELETED {
                        continue;
                    } else {
                        break;
                    }
                }
                if DELETED {
                    // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with
                    // current element. We use copy for move, and
                    // never touch this element again.
                    //
                    unsafe {
                        let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt);
                        ptr::copy_nonoverlapping(cur, hole_slot, 1);
                    }
                }
                g.processed_len += 1;
            }
        }

        let original_len = self.len() as usize;
        let mut g = BackshiftOnDrop {
            v: self,
            processed_len: 0,
            deleted_cnt: 0,
            original_len,
        };

        // Stage 1: Nothing was deleted.
        process_loop::<F, false>(original_len, &mut f, &mut g);

        // Stage 2: Some elements were deleted.
        process_loop::<F, true>(original_len, &mut f, &mut g);

        // All item are processed.
        drop(g);
    }

    /// Shortens the array, keeping the first `len` elements and dropping the rest.
    ///
    /// If `len` is greater than the array's current length or `len` is lesser than 0,
    /// this has no effect.
    ///
    /// # Examples
    ///
    /// Truncating a five element vector to two elements:
    ///
    /// ```
    /// use janetrs::array;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = array![1, 2, 3, 4, 5];
    /// arr.truncate(2);
    /// assert_eq!(arr.len(), 2);
    /// ```
    ///
    /// No truncation occurs when `len` is greater than the vector's current
    /// length:
    ///
    /// ```
    /// use janetrs::array;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = array![1, 2, 3];
    /// arr.truncate(8);
    /// assert_eq!(arr.len(), 3);
    /// ```
    ///
    /// Truncating when `len == 0` is equivalent to calling the [`clear`]
    /// method.
    ///
    /// ```
    /// use janetrs::array;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = array![1, 2, 3];
    /// arr.truncate(0);
    /// assert!(arr.is_empty());
    /// ```
    ///
    /// [`clear`]: #method.clear
    #[inline]
    pub fn truncate(&mut self, len: i32) {
        if len <= self.len() && len >= 0 {
            self.set_len(len);
        }
    }

    /// Returns a reference to the first element of the array, or `None` if it is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let v = array![10, 40, 30];
    /// assert_eq!(Some(&Janet::from(10)), v.first());
    ///
    /// let w = array![];
    /// assert_eq!(None, w.first());
    /// ```
    #[inline]
    #[must_use]
    pub fn first(&self) -> Option<&Janet> {
        if let [first, ..] = self.as_ref() {
            Some(first)
        } else {
            None
        }
    }

    /// Returns a mutable reference to the first element of the array, or `None` if it is
    /// empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut x = array![0, 1, 2];
    ///
    /// if let Some(first) = x.first_mut() {
    ///     *first = Janet::from(5);
    /// }
    /// assert_eq!(x.as_ref(), array![5, 1, 2].as_ref());
    /// ```
    #[inline]
    pub fn first_mut(&mut self) -> Option<&mut Janet> {
        if let [first, ..] = self.as_mut() {
            Some(first)
        } else {
            None
        }
    }

    /// Returns a reference of the first and a reference to all the rest of the elements
    /// of the array, or `None` if it is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let x = array![0, 1, 2];
    ///
    /// if let Some((first, elements)) = x.split_first() {
    ///     assert_eq!(first, &Janet::from(0));
    ///     assert_eq!(elements, &[Janet::from(1), Janet::from(2)]);
    /// }
    /// ```
    #[inline]
    #[must_use]
    pub fn split_first(&self) -> Option<(&Janet, &[Janet])> {
        if let [first, tail @ ..] = self.as_ref() {
            Some((first, tail))
        } else {
            None
        }
    }

    /// Returns a mutable reference of the first and a mutable reference to all the rest
    /// of the elements of the array, or `None` if it is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut x = array![0, 1, 2];
    ///
    /// if let Some((first, elements)) = x.split_first_mut() {
    ///     *first = Janet::from(3);
    ///     elements[0] = Janet::from(4);
    ///     elements[1] = Janet::from(5);
    /// }
    /// assert_eq!(x.as_ref(), array![3, 4, 5].as_ref());
    /// ```
    #[inline]
    pub fn split_first_mut(&mut self) -> Option<(&mut Janet, &mut [Janet])> {
        if let [first, tail @ ..] = self.as_mut() {
            Some((first, tail))
        } else {
            None
        }
    }

    /// Returns a reference to the last element of the array, or `None` if it is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let v = array![10, 40, 30];
    /// assert_eq!(Some(&Janet::from(30)), v.last());
    ///
    /// let w = array![];
    /// assert_eq!(None, w.last());
    /// ```
    #[inline]
    #[must_use]
    pub fn last(&self) -> Option<&Janet> {
        if let [.., last] = self.as_ref() {
            Some(last)
        } else {
            None
        }
    }

    /// Returns a mutable reference to the last element of the array, or `None` if it is
    /// empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut x = array![0, 1, 2];
    ///
    /// if let Some(last) = x.last_mut() {
    ///     *last = Janet::from(10);
    /// }
    /// assert_eq!(x.as_ref(), array![0, 1, 10].as_ref());
    /// ```
    #[inline]
    pub fn last_mut(&mut self) -> Option<&mut Janet> {
        if let [.., last] = self.as_mut() {
            Some(last)
        } else {
            None
        }
    }

    /// Returns a reference of the last and all the rest of the elements of the array, or
    /// `None` if it is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let x = array![0, 1, 2];
    ///
    /// if let Some((last, elements)) = x.split_last() {
    ///     assert_eq!(last, &Janet::from(2));
    ///     assert_eq!(elements, &[Janet::from(0), Janet::from(1)]);
    /// }
    /// ```
    #[inline]
    #[must_use]
    pub fn split_last(&self) -> Option<(&Janet, &[Janet])> {
        if let [init @ .., last] = self.as_ref() {
            Some((last, init))
        } else {
            None
        }
    }

    /// Returns a mutable to the last and all the rest of the elements of the slice, or
    /// `None` if it is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut x = array![0, 1, 2];
    ///
    /// if let Some((last, elements)) = x.split_last_mut() {
    ///     *last = Janet::from(3);
    ///     elements[0] = Janet::from(4);
    ///     elements[1] = Janet::from(5);
    /// }
    /// assert_eq!(x.as_ref(), array![4, 5, 3].as_ref());
    /// ```
    #[inline]
    pub fn split_last_mut(&mut self) -> Option<(&mut Janet, &mut [Janet])> {
        if let [init @ .., last] = self.as_mut() {
            Some((last, init))
        } else {
            None
        }
    }

    /// Divides one array 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).
    ///
    /// # Janet Panics
    ///
    /// Panics if `mid > len` or `mid < 0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let v = array![1, 2, 3, 4, 5, 6];
    ///
    /// {
    ///     let (left, right) = v.split_at(0);
    ///     assert!(left.is_empty());
    ///     assert_eq!(right, array![1, 2, 3, 4, 5, 6].as_ref());
    /// }
    ///
    /// {
    ///     let (left, right) = v.split_at(2);
    ///     assert_eq!(left, array![1, 2].as_ref());
    ///     assert_eq!(right, array![3, 4, 5, 6].as_ref());
    /// }
    ///
    /// {
    ///     let (left, right) = v.split_at(6);
    ///     assert_eq!(left, array![1, 2, 3, 4, 5, 6].as_ref());
    ///     assert!(right.is_empty());
    /// }
    /// ```
    #[inline]
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub fn split_at(&self, mid: i32) -> (&[Janet], &[Janet]) {
        if mid < 0 {
            crate::jpanic!(
                "index out of bounds: the index ({}) is negative and must be positive",
                mid
            )
        }
        self.as_ref().split_at(mid as usize)
    }

    /// 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).
    ///
    /// # Janet Panics
    ///
    /// Panics if `mid > len` or `mid < 0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![1, 0, 3, 0, 5, 6];
    /// // scoped to restrict the lifetime of the borrows
    /// {
    ///     let (left, right) = v.split_at_mut(2);
    ///     assert_eq!(left, array![1, 0].as_ref());
    ///     assert_eq!(right, array![3, 0, 5, 6].as_ref());
    ///     left[1] = Janet::from(2);
    ///     right[1] = Janet::from(4);
    /// }
    /// assert_eq!(v.as_ref(), array![1, 2, 3, 4, 5, 6].as_ref());
    /// ```
    #[inline]
    pub fn split_at_mut(&mut self, mid: i32) -> (&mut [Janet], &mut [Janet]) {
        if mid < 0 {
            crate::jpanic!(
                "index out of bounds: the index ({}) is negative and must be positive",
                mid
            )
        }
        self.as_mut().split_at_mut(mid as usize)
    }

    /// Swaps two elements in the array.
    ///
    /// # Arguments
    ///
    /// * a - The index of the first element
    /// * b - The index of the second element
    ///
    /// # Janet Panics
    ///
    /// Panics if `a` or `b` are out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, assert_deep_eq, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array!["a", "b", "c", "d"];
    /// v.swap(1, 3);
    /// assert_deep_eq!(v, array!["a", "d", "c", "b"]);
    /// ```
    #[inline]
    pub fn swap(&mut self, a: i32, b: i32) {
        // Can't take two mutable loans from one vector, so instead just cast
        // them to their raw pointers to do the swap.
        let pa: *mut Janet = &mut self[a];
        let pb: *mut Janet = &mut self[b];
        // SAFETY: `pa` and `pb` have been created from safe mutable references and refer
        // to elements in the slice and therefore are guaranteed to be valid and aligned.
        // Note that accessing the elements behind `a` and `b` is checked and will
        // panic when out of bounds.
        unsafe {
            ptr::swap(pa, pb);
        }
    }

    /// Swaps two elements in the array, without doing bounds checking.
    ///
    /// For a safe alternative see [`swap`].
    ///
    /// # Arguments
    ///
    /// * a - The index of the first element
    /// * b - The index of the second element
    ///
    /// # Safety
    ///
    /// Calling this method with an out-of-bounds index is *[undefined behavior]*.
    /// The caller has to ensure that `a < self.len()` and `b < self.len()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, assert_deep_eq, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = array!["a", "b", "c", "d"];
    /// // SAFETY: we know that 1 and 3 are both indices of the slice
    /// unsafe { arr.swap_unchecked(1, 3) };
    /// assert_deep_eq!(arr, array!["a", "d", "c", "b"]);
    /// ```
    ///
    /// [`swap`]: Self::swap
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    pub unsafe fn swap_unchecked(&mut self, a: i32, b: i32) {
        debug_assert!(
            a >= 0 && a < self.len() && b >= 0 && b < self.len(),
            "JanetArray::swap_unchecked requires that the indices are within the slice",
        );

        let ptr = self.as_mut_ptr();
        // SAFETY: caller has to guarantee that `a < self.len()` and `b < self.len()`
        unsafe {
            ptr::swap(ptr.add(a as usize), ptr.add(b as usize));
        }
    }

    /// Reverses the order of elements in the array, in place.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![1, 2, 3];
    /// v.reverse();
    /// assert_eq!(v.as_ref(), array![3, 2, 1].as_ref());
    /// ```
    #[inline]
    pub fn reverse(&mut self) {
        self.as_mut().reverse()
    }

    /// Creates a array by repeating a array `n` times.
    ///
    /// # Janet Panics
    ///
    /// This function will panic if the capacity would overflow.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// assert_eq!(
    ///     array![1, 2].repeat(3).as_ref(),
    ///     array![1, 2, 1, 2, 1, 2].as_ref()
    /// );
    /// ```
    ///
    /// A panic upon overflow:
    ///
    /// ```should_panic
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// // this will panic at runtime
    /// b"0123456789abcdef".repeat(usize::MAX);
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    #[must_use = "this returns a repeated array as a new JanetArray, without modifying the original"]
    pub fn repeat(&self, n: usize) -> Self {
        // self.as_ref().repeat(n).into_iter().collect()
        if n == 0 {
            return JanetArray::new();
        }

        // If `n` is larger than zero, it can be split as
        // `n = 2^expn + rem (2^expn > rem, expn >= 0, rem >= 0)`.
        // `2^expn` is the number represented by the leftmost '1' bit of `n`,
        // and `rem` is the remaining part of `n`.

        let capacity = match self.len().checked_mul(n as i32) {
            Some(cap) => cap,
            None => jpanic!("capacity overflow"),
        };
        let mut buf = JanetArray::with_capacity(capacity);

        for _ in 0..n {
            Extend::extend(&mut buf, self);
        }

        buf
    }

    /// Returns `true` if `needle` is a prefix of the array.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let v = array![10, 40, 30];
    /// assert!(v.starts_with(&[Janet::from(10)]));
    /// assert!(v.starts_with(&[Janet::from(10), Janet::from(40)]));
    /// assert!(!v.starts_with(&[Janet::from(50)]));
    /// assert!(!v.starts_with(&[Janet::from(10), Janet::from(50)]));
    /// ```
    ///
    /// Always returns `true` if `needle` is an empty slice:
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let v = array![10, 40, 30];
    /// assert!(v.starts_with(&[]));
    /// let v = array![];
    /// assert!(v.starts_with(&[]));
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    #[must_use]
    pub fn starts_with(&self, needle: &[Janet]) -> bool {
        self.as_ref().starts_with(needle)
    }

    /// Returns `true` if `needle` is a suffix of the array.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let v = array![10, 40, 30];
    /// assert!(v.ends_with(&[Janet::from(30)]));
    /// assert!(v.ends_with(&[Janet::from(40), Janet::from(30)]));
    /// assert!(!v.ends_with(&[Janet::from(50)]));
    /// assert!(!v.ends_with(&[Janet::from(50), Janet::from(30)]));
    /// ```
    ///
    /// Always returns `true` if `needle` is an empty slice:
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let v = array![10, 40, 30];
    /// assert!(v.ends_with(&[]));
    /// let v = array![];
    /// assert!(v.ends_with(&[]));
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    #[must_use]
    pub fn ends_with(&self, needle: &[Janet]) -> bool {
        self.as_ref().ends_with(needle)
    }

    /// Binary searches this array for a given element.
    ///
    /// 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.
    ///
    /// # Examples
    ///
    /// Looks up a series of four elements. The first is found, with a
    /// uniquely determined position; the second and third are not
    /// found; the fourth could match any position in `[1, 4]`.
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let s = array![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
    ///
    /// assert_eq!(s.binary_search(&Janet::from(13)), Ok(9));
    /// assert_eq!(s.binary_search(&Janet::from(4)), Err(7));
    /// assert_eq!(s.binary_search(&Janet::from(100)), Err(13));
    /// let r = s.binary_search(&Janet::from(1));
    /// assert!(match r {
    ///     Ok(1..=4) => true,
    ///     _ => false,
    /// });
    /// ```
    ///
    /// If you want to insert an item to a sorted vector, while maintaining
    /// sort order:
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut s = array![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
    /// let num = Janet::from(42);
    /// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
    /// s.insert(idx as i32, num);
    /// assert_eq!(
    ///     s.as_ref(),
    ///     array![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55].as_ref()
    /// );
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn binary_search(&self, x: &Janet) -> Result<usize, usize> {
        self.binary_search_by(|p| p.cmp(x))
    }

    /// Binary searches this sorted array with a comparator function.
    ///
    /// The comparator function should implement an order consistent
    /// with the sort order of the underlying slice, returning an
    /// order code that indicates whether its argument is `Less`,
    /// `Equal` or `Greater` the desired target.
    ///
    /// 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.
    ///
    /// # Examples
    ///
    /// Looks up a series of four elements. The first is found, with a
    /// uniquely determined position; the second and third are not
    /// found; the fourth could match any position in `[1, 4]`.
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let s = array![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
    ///
    /// let seek = Janet::from(13);
    /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
    /// let seek = Janet::from(4);
    /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
    /// let seek = Janet::from(100);
    /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
    /// let seek = Janet::from(1);
    /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
    /// assert!(match r {
    ///     Ok(1..=4) => true,
    ///     _ => false,
    /// });
    /// ```
    #[inline]
    pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
    where
        F: FnMut(&'a Janet) -> Ordering,
    {
        self.as_ref().binary_search_by(f)
    }

    /// Binary searches this array with a key extraction function.
    ///
    /// Assumes that the array is sorted by the key, for instance with
    /// [`sort_by_key`] using the same key extraction function.
    ///
    /// 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.
    ///
    /// [`sort_by_key`]: #method.sort_by_key
    ///
    /// # Examples
    /// TODO: Find a good example
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    /// ```
    #[inline]
    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
    where
        F: FnMut(&'a Janet) -> B,
        B: Ord,
    {
        self.binary_search_by(|k| f(k).cmp(b))
    }

    /// Removes consecutive repeated elements in the array according to the
    /// [`DeepEq`] trait implementation.
    ///
    /// If the array is sorted, this removes all duplicates.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, DeepEq, Janet, TaggedJanet::Number};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    /// let mut arr = array![1, 2, 2, 3, 2];
    ///
    /// arr.dedup();
    ///
    /// assert!(arr.deep_eq(&array![1, 2, 3, 2]));
    /// ```
    #[inline]
    pub fn dedup(&mut self) {
        self.dedup_by(|a, b| a.deep_eq(b))
    }

    /// Removes all but the first of consecutive elements in the array that resolve to the
    /// same key.
    ///
    /// If the array is sorted, this removes all duplicates.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, DeepEq, Janet, TaggedJanet::Number};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    /// let mut arr = array![10, 20, 21, 30, 20];
    ///
    /// arr.dedup_by_key(|i| {
    ///     if let Number(i) = i.unwrap() {
    ///         ((i / 10.0) as i32).into()
    ///     } else {
    ///         Janet::nil()
    ///     }
    /// });
    ///
    /// assert!(arr.deep_eq(&array![10, 20, 30, 20]));
    /// ```
    #[inline]
    pub fn dedup_by_key<F>(&mut self, mut key: F)
    where
        F: FnMut(&mut Janet) -> Janet,
    {
        self.dedup_by(|a, b| key(a) == key(b))
    }

    /// Removes all but the first of consecutive elements in the array 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.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, DeepEq, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    /// let mut arr = array!["foo", "bar", "bar", "baz", "bar"];
    ///
    /// arr.dedup_by(|&mut a, &mut b| a.eq(&b));
    /// assert!(arr.deep_eq(&array!["foo", "bar", "baz", "bar"]));
    /// ```
    #[cfg_attr(feature = "inline-more", inline)]
    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
    where
        F: FnMut(&mut Janet, &mut Janet) -> bool,
    {
        let len = self.len() as usize;
        if len <= 1 {
            return;
        }

        // read: Offset of the element we want to check if it is duplicate.
        // write: Offset of the place where we want to place the non-duplicate when we find it.
        let (mut read, mut write) = (1, 1usize);
        let ptr = self.as_mut_ptr();

        // SAFETY: INVARIANT: arr.len() > read >= write > write-1 >= 0
        unsafe {
            while read < len {
                let read_ptr = ptr.add(read);
                let prev_ptr = ptr.add(write.wrapping_sub(1));

                if !same_bucket(&mut *read_ptr, &mut *prev_ptr) {
                    let write_ptr = ptr.add(write);

                    ptr::copy(read_ptr, write_ptr, 1);

                    // We have filled that place, so go further
                    write += 1;
                }

                read += 1;
            }

            // How many items were left
            // Basically array[read..].len()
            let items_left = len.wrapping_sub(read);

            // Pointer to first item in array[write..write+items_left] slice
            let dropped_ptr = ptr.add(write);
            // Pointer to first item in array[read..] slice
            let valid_ptr = ptr.add(read);

            // Copy `array[read..]` to `array[write..write+items_left]`.
            // The slices can overlap, so `copy_nonoverlapping` cannot be used
            ptr::copy(valid_ptr, dropped_ptr, items_left);

            // How many items have been already dropped
            // Basically array[read..write].len()
            let dropped = read.wrapping_sub(write);

            self.set_len((len - dropped) as i32);
        }
    }

    /// Sorts the array.
    ///
    /// 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`](#method.sort_unstable).
    ///
    /// # Current implementation
    ///
    /// The current algorithm is an adaptive, iterative merge sort inspired by
    /// [timsort](https://en.wikipedia.org/wiki/Timsort).
    /// It is designed to be very fast in cases where the slice is nearly sorted, or
    /// consists of two or more sorted sequences concatenated one after another.
    ///
    /// Also, it allocates temporary storage half the size of `self`, but for short slices
    /// a non-allocating insertion sort is used instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![-5, 4, 1, -3, 2];
    ///
    /// v.sort();
    /// assert_eq!(v.as_ref(), array![-5, -3, 1, 2, 4].as_ref());
    /// ```
    #[inline]
    pub fn sort(&mut self) {
        self.as_mut().sort()
    }

    /// Sorts the array 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 `>`.
    ///
    /// 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`](#method.sort_unstable_by).
    ///
    /// # Current implementation
    ///
    /// The current algorithm is an adaptive, iterative merge sort inspired by
    /// [timsort](https://en.wikipedia.org/wiki/Timsort).
    /// It is designed to be very fast in cases where the slice is nearly sorted, or
    /// consists of two or more sorted sequences concatenated one after another.
    ///
    /// Also, it allocates temporary storage half the size of `self`, but for short slices
    /// a non-allocating insertion sort is used instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![5, 4, 1, 3, 2];
    /// v.sort_by(|a, b| a.cmp(b));
    /// assert_eq!(v.as_ref(), array![1, 2, 3, 4, 5].as_ref());
    ///
    /// // reverse sorting
    /// v.sort_by(|a, b| b.cmp(a));
    /// assert_eq!(v.as_ref(), array![5, 4, 3, 2, 1].as_ref());
    /// ```
    #[inline]
    pub fn sort_by<F>(&mut self, compare: F)
    where
        F: FnMut(&Janet, &Janet) -> Ordering,
    {
        self.as_mut().sort_by(compare)
    }

    /// Sorts the array 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`](#method.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`](#method.sort_unstable_by_key).
    ///
    /// # Current implementation
    ///
    /// The current algorithm is an adaptive, iterative merge sort inspired by
    /// [timsort](https://en.wikipedia.org/wiki/Timsort).
    /// It is designed to be very fast in cases where the slice is nearly sorted, or
    /// consists of two or more sorted sequences concatenated one after another.
    ///
    /// Also, it allocates temporary storage half the size of `self`, but for short slices
    /// a non-allocating insertion sort is used instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![-5i32, 4, 1, -3, 2];
    ///
    /// v.sort_by_key(|k| match k.unwrap() {
    ///     TaggedJanet::Number(n) => n.abs() as i128,
    ///     _ => 0,
    /// });
    /// assert_eq!(v.as_ref(), array![1, 2, -3, 4, -5].as_ref());
    /// ```
    #[inline]
    pub fn sort_by_key<K, F>(&mut self, f: F)
    where
        F: FnMut(&Janet) -> K,
        K: Ord,
    {
        self.as_mut().sort_by_key(f)
    }

    /// Sorts the array, but may 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.
    ///
    /// # Current implementation
    ///
    /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson
    /// Peters, which combines the fast average case of randomized quicksort with the
    /// fast worst case of heapsort, while achieving linear time on slices with
    /// certain patterns. It uses some randomization to avoid degenerate cases, but
    /// with a fixed seed to always provide deterministic behavior.
    ///
    /// It is typically faster than stable sorting, except in a few special cases, e.g.,
    /// when the slice consists of several concatenated sorted sequences.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![-5, 4, 1, -3, 2];
    ///
    /// v.sort_unstable();
    /// assert_eq!(v.as_ref(), array![-5, -3, 1, 2, 4].as_ref());
    /// ```
    ///
    /// [pdqsort]: https://github.com/orlp/pdqsort
    #[inline]
    pub fn sort_unstable(&mut self) {
        self.as_mut().sort_unstable()
    }

    /// Sorts the array with a comparator function, but may 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
    /// array. 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 >.
    ///
    /// # Current implementation
    ///
    /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson
    /// Peters, which combines the fast average case of randomized quicksort with the
    /// fast worst case of heapsort, while achieving linear time on slices with
    /// certain patterns. It uses some randomization to avoid degenerate cases, but
    /// with a fixed seed to always provide deterministic behavior.
    ///
    /// It is typically faster than stable sorting, except in a few special cases, e.g.,
    /// when the slice consists of several concatenated sorted sequences.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![5, 4, 1, 3, 2];
    /// v.sort_unstable_by(|a, b| a.cmp(b));
    /// assert_eq!(v.as_ref(), array![1, 2, 3, 4, 5].as_ref());
    ///
    /// // reverse sorting
    /// v.sort_unstable_by(|a, b| b.cmp(a));
    /// assert_eq!(v.as_ref(), array![5, 4, 3, 2, 1].as_ref());
    /// ```
    ///
    /// [pdqsort]: https://github.com/orlp/pdqsort
    #[inline]
    pub fn sort_unstable_by<F>(&mut self, compare: F)
    where
        F: FnMut(&Janet, &Janet) -> Ordering,
    {
        self.as_mut().sort_unstable_by(compare)
    }

    /// Sorts the array with a key extraction function, but may 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*).
    ///
    /// # Current implementation
    ///
    /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson
    /// Peters, which combines the fast average case of randomized quicksort with the
    /// fast worst case of heapsort, while achieving linear time on slices with
    /// certain patterns. It uses some randomization to avoid degenerate cases, but
    /// with a fixed seed to always provide deterministic behavior.
    ///
    /// Due to its key calling strategy,
    /// [`sort_unstable_by_key`](#method.sort_unstable_by_key) is likely to be slower
    /// than [`sort_by_cached_key`](#method.sort_by_cached_key) in cases where the key
    /// function is expensive.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![-5i32, 4, 1, -3, 2];
    ///
    /// v.sort_unstable_by_key(|k| match k.unwrap() {
    ///     TaggedJanet::Number(n) => n.abs() as i128,
    ///     _ => 0,
    /// });
    /// assert_eq!(v.as_ref(), array![1, 2, -3, 4, -5].as_ref());
    /// ```
    ///
    /// [pdqsort]: https://github.com/orlp/pdqsort
    #[inline]
    pub fn sort_unstable_by_key<K, F>(&mut self, f: F)
    where
        F: FnMut(&Janet) -> K,
        K: Ord,
    {
        self.as_mut().sort_unstable_by_key(f)
    }

    /// Creates a iterator over the reference of the array itens.
    ///
    /// # Examples
    /// ```
    /// use janetrs::array;
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array![1, 2, "janet"];
    ///
    /// for elem in arr.iter() {
    ///     println!("{}", elem);
    /// }
    /// ```
    #[inline]
    pub fn iter(&self) -> Iter<'_, '_> {
        Iter {
            arr: self,
            index_head: 0,
            index_tail: self.len(),
        }
    }

    /// Creates a iterator over the mutable reference of the array itens.
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut arr = array![1, 2, "janet"];
    ///
    /// for elem in arr.iter_mut() {
    ///     *elem = Janet::from("Janet");
    /// }
    ///
    /// assert!(arr.iter().all(|j| j == Janet::from("Janet")));
    /// ```
    #[inline]
    pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, 'data> {
        let len = self.len();
        IterMut {
            arr: self,
            index_head: 0,
            index_tail: len,
        }
    }

    /// Creates an iterator over all contiguous windows of length
    /// `size`. The windows overlap. If the array is shorter than
    /// `size`, the iterator returns no values.
    ///
    /// # Janet Panics
    ///
    /// Panics if `size` is 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array!['r', 'u', 's', 't'];
    /// let mut iter = arr.windows(2);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('r'), Janet::from('u')]);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('u'), Janet::from('s')]);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('s'), Janet::from('t')]);
    /// assert!(iter.next().is_none());
    /// ```
    ///
    /// If the array is shorter than `size`:
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array!['f', 'o', 'o'];
    /// let mut iter = arr.windows(4);
    /// assert!(iter.next().is_none());
    /// ```
    #[inline]
    pub fn windows(&self, size: usize) -> Windows<'_, Janet> {
        self.as_ref().windows(size)
    }

    /// Creates an iterator over `chunk_size` elements of the array at a time, starting at
    /// the beginning of the array.
    ///
    /// The chunks are slices and do not overlap. If `chunk_size` does not divide the
    /// length of the array, then the last chunk will not have length `chunk_size`.
    ///
    /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always
    /// exactly `chunk_size` elements, and [`rchunks`] for the same iterator but
    /// starting at the end of the array.
    ///
    /// # Janet Panics
    ///
    /// Panics if `chunk_size` is 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array!['l', 'o', 'r', 'e', 'm'];
    /// let mut iter = arr.chunks(2);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('l'), Janet::from('o')]);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('r'), Janet::from('e')]);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('m')]);
    /// assert!(iter.next().is_none());
    /// ```
    ///
    /// [`chunks_exact`]: #method.chunks_exact
    /// [`rchunks`]: #method.rchunks
    #[inline]
    pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, Janet> {
        self.as_ref().chunks(chunk_size)
    }

    /// Creates an iterator over `chunk_size` elements of the array at a time, starting at
    /// the beginning of the array.
    ///
    /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide
    /// the length of the array, then the last chunk will not have length
    /// `chunk_size`.
    ///
    /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of
    /// always exactly `chunk_size` elements, and [`rchunks_mut`] for the same
    /// iterator but starting at the end of the array.
    ///
    /// # Janet Panics
    ///
    /// Panics if `chunk_size` is 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![0, 0, 0, 0, 0];
    /// let mut count = 1;
    ///
    /// for chunk in v.chunks_mut(2) {
    ///     for elem in chunk.iter_mut() {
    ///         *elem = Janet::from(count);
    ///     }
    ///     count += 1;
    /// }
    /// assert_eq!(v.as_ref(), array![1, 1, 2, 2, 3].as_ref());
    /// ```
    ///
    /// [`chunks_exact_mut`]: #method.chunks_exact_mut
    /// [`rchunks_mut`]: #method.rchunks_mut
    #[inline]
    pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, Janet> {
        self.as_mut().chunks_mut(chunk_size)
    }

    /// Creates an iterator over `chunk_size` elements of the array at a time, starting at
    /// the beginning of the array.
    ///
    /// The chunks are slices and do not overlap. If `chunk_size` does not divide the
    /// length of the array, then the last up to `chunk_size-1` elements will be
    /// omitted and can be retrieved from the `remainder` function of the iterator.
    ///
    /// Due to each chunk having exactly `chunk_size` elements, the compiler can often
    /// optimize the resulting code better than in the case of [`chunks`].
    ///
    /// See [`chunks`] for a variant of this iterator that also returns the remainder as a
    /// smaller chunk, and [`rchunks_exact`] for the same iterator but starting at the
    /// end of the array.
    ///
    /// # Janet Panics
    ///
    /// Panics if `chunk_size` is 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array!['l', 'o', 'r', 'e', 'm'];
    /// let mut iter = arr.chunks_exact(2);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('l'), Janet::from('o')]);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('r'), Janet::from('e')]);
    /// assert!(iter.next().is_none());
    /// assert_eq!(iter.remainder(), &[Janet::from('m')]);
    /// ```
    ///
    /// [`chunks`]: #method.chunks
    /// [`rchunks_exact`]: #method.rchunks_exact
    #[inline]
    pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, Janet> {
        self.as_ref().chunks_exact(chunk_size)
    }

    /// Creates an iterator over `chunk_size` elements of the array at a time, starting at
    /// the beginning of the array.
    ///
    /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide
    /// the length of the array, then the last up to `chunk_size-1` elements will be
    /// omitted and can be retrieved from the `into_remainder` function of the
    /// iterator.
    ///
    /// Due to each chunk having exactly `chunk_size` elements, the compiler can often
    /// optimize the resulting code better than in the case of [`chunks_mut`].
    ///
    /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder
    /// as a smaller chunk, and [`rchunks_exact_mut`] for the same iterator but
    /// starting at the end of the array.
    ///
    /// # Janet Panics
    ///
    /// Panics if `chunk_size` is 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![0, 0, 0, 0, 0];
    /// let mut count = 1;
    ///
    /// for chunk in v.chunks_exact_mut(2) {
    ///     for elem in chunk.iter_mut() {
    ///         *elem = Janet::from(count);
    ///     }
    ///     count += 1;
    /// }
    /// assert_eq!(v.as_ref(), array![1, 1, 2, 2, 0].as_ref());
    /// ```
    ///
    /// [`chunks_mut`]: #method.chunks_mut
    /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
    #[inline]
    pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, Janet> {
        self.as_mut().chunks_exact_mut(chunk_size)
    }

    /// Create an iterator over `chunk_size` elements of the array at a time, starting at
    /// the end of the array.
    ///
    /// The chunks are slices and do not overlap. If `chunk_size` does not divide the
    /// length of the array, then the last chunk will not have length `chunk_size`.
    ///
    /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always
    /// exactly `chunk_size` elements, and [`chunks`] for the same iterator but
    /// starting at the beginning of the array.
    ///
    /// # Janet Panics
    ///
    /// Panics if `chunk_size` is 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array!['l', 'o', 'r', 'e', 'm'];
    /// let mut iter = arr.rchunks(2);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('e'), Janet::from('m')]);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('o'), Janet::from('r')]);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('l')]);
    /// assert!(iter.next().is_none());
    /// ```
    ///
    /// [`rchunks_exact`]: #method.rchunks_exact
    /// [`chunks`]: #method.chunks
    #[inline]
    pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, Janet> {
        self.as_ref().rchunks(chunk_size)
    }

    /// Create an iterator over `chunk_size` elements of the array at a time, starting at
    /// the end of the array.
    ///
    /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide
    /// the length of the array, then the last chunk will not have length
    /// `chunk_size`.
    ///
    /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of
    /// always exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator
    /// but starting at the beginning of the array.
    ///
    /// # Janet Panics
    ///
    /// Panics if `chunk_size` is 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![0, 0, 0, 0, 0];
    /// let mut count = 1;
    ///
    /// for chunk in v.rchunks_mut(2) {
    ///     for elem in chunk.iter_mut() {
    ///         *elem = Janet::from(count);
    ///     }
    ///     count += 1;
    /// }
    /// assert_eq!(v.as_ref(), array![3, 2, 2, 1, 1].as_ref());
    /// ```
    ///
    /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
    /// [`chunks_mut`]: #method.chunks_mut
    #[inline]
    pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, Janet> {
        self.as_mut().rchunks_mut(chunk_size)
    }

    /// Returns an iterator over `chunk_size` elements of the array at a time, starting at
    /// the end of the array.
    ///
    /// The chunks are slices and do not overlap. If `chunk_size` does not divide the
    /// length of the array, then the last up to `chunk_size-1` elements will be
    /// omitted and can be retrieved from the `remainder` function of the iterator.
    ///
    /// Due to each chunk having exactly `chunk_size` elements, the compiler can often
    /// optimize the resulting code better than in the case of [`chunks`].
    ///
    /// See [`rchunks`] for a variant of this iterator that also returns the remainder as
    /// a smaller chunk, and [`chunks_exact`] for the same iterator but starting at
    /// the beginning of the array.
    ///
    /// # Janet Panics
    ///
    /// Panics if `chunk_size` is 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array!['l', 'o', 'r', 'e', 'm'];
    /// let mut iter = arr.rchunks_exact(2);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('e'), Janet::from('m')]);
    /// assert_eq!(iter.next().unwrap(), &[Janet::from('o'), Janet::from('r')]);
    /// assert!(iter.next().is_none());
    /// assert_eq!(iter.remainder(), &[Janet::from('l')]);
    /// ```
    ///
    /// [`chunks`]: #method.chunks
    /// [`rchunks`]: #method.rchunks
    /// [`chunks_exact`]: #method.chunks_exact
    #[inline]
    pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, Janet> {
        self.as_ref().rchunks_exact(chunk_size)
    }

    /// Returns an iterator over `chunk_size` elements of the array at a time, starting at
    /// the end of the array.
    ///
    /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide
    /// the length of the array, then the last up to `chunk_size-1` elements will be
    /// omitted and can be retrieved from the `into_remainder` function of the
    /// iterator.
    ///
    /// Due to each chunk having exactly `chunk_size` elements, the compiler can often
    /// optimize the resulting code better than in the case of [`chunks_mut`].
    ///
    /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder
    /// as a smaller chunk, and [`chunks_exact_mut`] for the same iterator but
    /// starting at the beginning of the array.
    ///
    /// # Janet Panics
    ///
    /// Panics if `chunk_size` is 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![0, 0, 0, 0, 0];
    /// let mut count = 1;
    ///
    /// for chunk in v.rchunks_exact_mut(2) {
    ///     for elem in chunk.iter_mut() {
    ///         *elem = Janet::from(count);
    ///     }
    ///     count += 1;
    /// }
    /// assert_eq!(v.as_ref(), array![0, 2, 2, 1, 1].as_ref());
    /// ```
    ///
    /// [`chunks_mut`]: #method.chunks_mut
    /// [`rchunks_mut`]: #method.rchunks_mut
    /// [`chunks_exact_mut`]: #method.chunks_exact_mut
    #[inline]
    pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, Janet> {
        self.as_mut().rchunks_exact_mut(chunk_size)
    }

    /// Creates an iterator over subslices separated by elements that match
    /// `pred`. The matched element is not contained in the subslices.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array![10, 40, 33, 20];
    /// let mut iter = arr.split(|j| match j.unwrap() {
    ///     TaggedJanet::Number(num) => (num % 3.0) as u128 == 0,
    ///     _ => false,
    /// });
    ///
    /// assert_eq!(iter.next().unwrap(), array![10, 40].as_ref());
    /// assert_eq!(iter.next().unwrap(), array![20].as_ref());
    /// assert!(iter.next().is_none());
    /// ```
    ///
    /// If the first element is matched, an empty slice will be the first item
    /// returned by the iterator. Similarly, if the last element in the slice
    /// is matched, an empty slice will be the last item returned by the
    /// iterator:
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array![10, 40, 33];
    /// let mut iter = arr.split(|j| match j.unwrap() {
    ///     TaggedJanet::Number(num) => (num % 3.0) as u128 == 0,
    ///     _ => false,
    /// });
    ///
    /// assert_eq!(iter.next().unwrap(), array![10, 40].as_ref());
    /// assert_eq!(iter.next().unwrap(), array![].as_ref());
    /// assert!(iter.next().is_none());
    /// ```
    ///
    /// If two matched elements are directly adjacent, an empty slice will be
    /// present between them:
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array![10, 6, 33, 20];
    /// let mut iter = arr.split(|j| match j.unwrap() {
    ///     TaggedJanet::Number(num) => (num % 3.0) as u128 == 0,
    ///     _ => false,
    /// });
    ///
    /// assert_eq!(iter.next().unwrap(), array![10].as_ref());
    /// assert_eq!(iter.next().unwrap(), array![].as_ref());
    /// assert_eq!(iter.next().unwrap(), array![20].as_ref());
    /// assert!(iter.next().is_none());
    /// ```
    #[inline]
    pub fn split<F>(&self, pred: F) -> Split<'_, F>
    where
        F: FnMut(&Janet) -> bool,
    {
        self.as_ref().split(pred)
    }

    /// Creates an iterator over mutable subslices separated by elements that
    /// match `pred`. The matched element is not contained in the subslices.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![10, 40, 30, 20, 60, 50];
    ///
    /// for group in v.split_mut(|j| match j.unwrap() {
    ///     TaggedJanet::Number(num) => (num % 3.0) as i128 == 0,
    ///     _ => false,
    /// }) {
    ///     group[0] = Janet::from(1);
    /// }
    /// assert_eq!(v.as_ref(), array![1, 40, 30, 1, 60, 1].as_ref());
    /// ```
    #[inline]
    pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, F>
    where
        F: FnMut(&Janet) -> bool,
    {
        self.as_mut().split_mut(pred)
    }

    /// Creates an iterator over subslices separated by elements that match
    /// `pred`, starting at the end of the slice and working backwards.
    /// The matched element is not contained in the subslices.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let arr = array![11, 22, 33, 0, 44, 55];
    /// let mut iter = arr.rsplit(|j| match j.unwrap() {
    ///     TaggedJanet::Number(num) => num as i64 == 0,
    ///     _ => false,
    /// });
    ///
    /// assert_eq!(iter.next().unwrap(), array![44, 55].as_ref());
    /// assert_eq!(iter.next().unwrap(), array![11, 22, 33].as_ref());
    /// assert_eq!(iter.next(), None);
    /// ```
    ///
    /// As with `split()`, if the first or last element is matched, an empty
    /// slice will be the first (or last) item returned by the iterator.
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let v = array![0, 1, 1, 2, 3, 5, 8];
    /// let mut it = v.rsplit(|j| match j.unwrap() {
    ///     TaggedJanet::Number(n) => n as i64 % 2 == 0,
    ///     _ => false,
    /// });
    /// assert_eq!(it.next().unwrap(), array![].as_ref());
    /// assert_eq!(it.next().unwrap(), array![3, 5].as_ref());
    /// assert_eq!(it.next().unwrap(), array![1, 1].as_ref());
    /// assert_eq!(it.next().unwrap(), array![].as_ref());
    /// assert_eq!(it.next(), None);
    /// ```
    #[inline]
    pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, F>
    where
        F: FnMut(&Janet) -> bool,
    {
        self.as_ref().rsplit(pred)
    }

    /// Creates an iterator over mutable subslices separated by elements that
    /// match `pred`, starting at the end of the slice and working
    /// backwards. The matched element is not contained in the subslices.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![100, 400, 300, 200, 600, 500];
    ///
    /// let mut count = 0;
    /// for group in v.rsplit_mut(|j| match j.unwrap() {
    ///     TaggedJanet::Number(num) => (num % 3.0) as i128 == 0,
    ///     _ => false,
    /// }) {
    ///     count += 1;
    ///     group[0] = Janet::from(count);
    /// }
    /// assert_eq!(v.as_ref(), array![3, 400, 300, 2, 600, 1].as_ref());
    /// ```
    #[inline]
    pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, F>
    where
        F: FnMut(&Janet) -> bool,
    {
        self.as_mut().rsplit_mut(pred)
    }

    /// Creates an iterator over subslices separated by elements that match
    /// `pred`, limited to returning at most `n` items. The matched element is
    /// not contained in the subslices.
    ///
    /// The last element returned, if any, will contain the remainder of the
    /// array.
    ///
    /// # Examples
    ///
    /// Print the array split once by numbers divisible by 3 (i.e., `[10, 40]`,
    /// `[20, 60, 50]`):
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let v = array![10, 40, 30, 20, 60, 50];
    ///
    /// for group in v.splitn(2, |j| match j.unwrap() {
    ///     TaggedJanet::Number(num) => num as i64 % 3 == 0,
    ///     _ => false,
    /// }) {
    ///     println!("{:?}", group);
    /// }
    /// ```
    #[inline]
    pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, F>
    where
        F: FnMut(&Janet) -> bool,
    {
        self.as_ref().splitn(n, pred)
    }

    /// Creates an iterator over subslices separated by elements that match
    /// `pred`, limited to returning at most `n` items. The matched element is
    /// not contained in the subslices.
    ///
    /// The last element returned, if any, will contain the remainder of the
    /// array.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut v = array![10, 40, 30, 20, 60, 50];
    ///
    /// for group in v.splitn_mut(2, |j| match j.unwrap() {
    ///     TaggedJanet::Number(num) => num as i64 % 3 == 0,
    ///     _ => false,
    /// }) {
    ///     group[0] = Janet::from(1);
    /// }
    /// assert_eq!(v.as_ref(), array![1, 40, 30, 1, 60, 50].as_ref());
    /// ```
    #[inline]
    pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, F>
    where
        F: FnMut(&Janet) -> bool,
    {
        self.as_mut().splitn_mut(n, pred)
    }

    /// Returns an iterator over subslices separated by elements that match
    /// `pred` limited to returning at most `n` items. This starts at the end of
    /// the array and works backwards. The matched element is not contained in
    /// the subslices.
    ///
    /// The last element returned, if any, will contain the remainder of the
    /// array.
    ///
    /// # Examples
    ///
    /// Print the array split once, starting from the end, by numbers divisible
    /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let v = array![10, 40, 30, 20, 60, 50];
    ///
    /// for group in v.rsplitn(2, |j| match j.unwrap() {
    ///     TaggedJanet::Number(num) => num as i64 % 3 == 0,
    ///     _ => false,
    /// }) {
    ///     println!("{:?}", group);
    /// }
    /// ```
    #[inline]
    pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, F>
    where
        F: FnMut(&Janet) -> bool,
    {
        self.as_ref().rsplitn(n, pred)
    }

    /// Creates an iterator over subslices separated by elements that match
    /// `pred` limited to returning at most `n` items. This starts at the end of
    /// the array and works backwards. The matched element is not contained in
    /// the subslices.
    ///
    /// The last element returned, if any, will contain the remainder of the
    /// array.
    ///
    /// # Examples
    ///
    /// ```
    /// use janetrs::{array, Janet, TaggedJanet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut s = array![10, 40, 30, 20, 60, 50];
    ///
    /// for group in s.rsplitn_mut(2, |j| match j.unwrap() {
    ///     TaggedJanet::Number(num) => num as i64 % 3 == 0,
    ///     _ => false,
    /// }) {
    ///     group[0] = Janet::from(1);
    /// }
    /// assert_eq!(s.as_ref(), array![1, 40, 30, 20, 60, 1].as_ref());
    /// ```
    #[inline]
    pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, F>
    where
        F: FnMut(&Janet) -> bool,
    {
        self.as_mut().rsplitn_mut(n, pred)
    }

    // Creates an iterator which uses a closure to determine if an element should be removed.
    /// If the closure returns true, then the element is removed and yielded.
    /// If the closure returns false, the element will remain in the vector and will not
    /// be yielded by the iterator.
    ///
    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without
    /// iterating or the iteration short-circuits, then the remaining elements will be
    /// retained. Use [`retain`] with a negated predicate if you do not need the
    /// returned iterator.
    ///
    /// [`retain`]: Self::retain
    ///
    /// Using this method is equivalent to the following code:
    ///
    /// ```
    /// use janetrs::{array, assert_deep_eq, Janet};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    /// # let some_predicate = |x: &mut Janet| {
    /// #     x.try_unwrap::<i32>()
    /// #         .map(|x| x == 2 || x == 3 || x == 6)
    /// #         .unwrap_or(false)
    /// # };
    /// # let mut arr = array![1, 2, 3, 4, 5, 6];
    /// let mut i = 0;
    /// while i < arr.len() {
    ///     if some_predicate(&mut arr[i]) {
    ///         let _val = arr.remove(i);
    ///         // your code here
    ///     } else {
    ///         i += 1;
    ///     }
    /// }
    /// # assert_deep_eq!(arr, array![1, 4, 5]);
    /// ```
    ///
    /// But `extract_if` is easier to use. `extract_if` is also more efficient,
    /// because it can backshift the elements of the array in bulk.
    ///
    /// Note that `extract_if` also lets you mutate every element in the filter closure,
    /// regardless of whether you choose to keep or remove it.
    ///
    /// # Examples
    ///
    /// Splitting an array into evens and odds, reusing the original allocation:
    ///
    /// ```
    /// use janetrs::{array, assert_deep_eq, Janet, JanetArray};
    /// # let _client = janetrs::client::JanetClient::init().unwrap();
    ///
    /// let mut numbers = array![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
    ///
    /// let evens = numbers
    ///     .extract_if(|x| x.try_unwrap::<i32>().map(|x| x % 2 == 0).unwrap_or(false))
    ///     .collect::<JanetArray>();
    /// let odds = numbers;
    ///
    /// assert_deep_eq!(evens, array![2, 4, 6, 8, 14]);
    /// assert_deep_eq!(odds, array![1, 3, 5, 9, 11, 13, 15]);
    /// ```
    pub fn extract_if<F>(&mut self, filter: F) -> ExtractIf<'_, 'data, F>
    where
        F: FnMut(&mut Janet) -> bool,
    {
        let old_len = self.len() as usize;
        ExtractIf {
            arr: self,
            idx: 0,
            del: 0,
            old_len,
            pred: filter,
        }
    }

    /// Return a raw pointer to the array raw structure.
    ///
    /// The caller must ensure that the array outlives the pointer this function returns,
    /// or else it will end up pointing to garbage.
    ///
    /// If you need to mutate the contents of the slice, use [`as_mut_ptr`].
    ///
    /// [`as_mut_ptr`]: #method.as_mut_raw
    #[inline]
    #[must_use]
    pub const fn as_raw(&self) -> *const CJanetArray {
        self.raw
    }

    /// Return a raw mutable pointer to the array raw structure.
    ///
    /// The caller must ensure that the array outlives the pointer this function returns,
    /// or else it will end up pointing to garbage.
    #[inline]
    pub fn as_mut_raw(&mut self) -> *mut CJanetArray {
        self.raw
    }

    /// Return a raw pointer to the array first data.
    ///
    /// The caller must ensure that the array outlives the pointer this function returns,
    /// or else it will end up pointing to garbage.
    #[inline]
    #[must_use]
    pub fn as_ptr(&self) -> *const Janet {
        unsafe { (*self.raw).data as _ }
    }

    /// Return a raw mutable pointer to the array first data.
    ///
    /// The caller must ensure that the array outlives the pointer this function returns,
    /// or else it will end up pointing to garbage.
    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut Janet {
        unsafe { (*self.raw).data as _ }
    }
}

// Private methods
impl<'data> JanetArray<'data> {
    fn get_r(&self, range: Range<i32>) -> Option<&[Janet]> {
        if range.start < 0 || range.start > range.end || range.end > self.len() {
            None
        } else {
            // SAFETY: `self` is checked to be valid and in bounds above.
            unsafe { Some(self.get_r_unchecked(range)) }
        }
    }

    unsafe fn get_r_unchecked(&self, range: Range<i32>) -> &[Janet] {
        // SAFETY: the caller guarantees that `slice` is not dangling, so it
        // cannot be longer than `isize::MAX`. They also guarantee that
        // `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
        // so the call to `add` is safe and the length calculation cannot overflow.
        unsafe {
            // FIXME: use usize::unchecked_sub after 1.79.0 release
            let new_len =
                usize::checked_sub(range.end as usize, range.start as usize).unwrap_unchecked();
            &*ptr::slice_from_raw_parts(self.as_ptr().add(range.start as usize), new_len)
        }
    }

    fn get_r_mut(&mut self, range: Range<i32>) -> Option<&mut [Janet]> {
        if range.start < 0 || range.start > range.end || range.end > self.len() {
            None
        } else {
            // SAFETY: `self` is checked to be valid and in bounds above.
            unsafe { Some(self.get_r_unchecked_mut(range)) }
        }
    }

    unsafe fn get_r_unchecked_mut(&mut self, range: Range<i32>) -> &mut [Janet] {
        // SAFETY: the caller guarantees that `slice` is not dangling, so it
        // cannot be longer than `isize::MAX`. They also guarantee that
        // `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
        // so the call to `add` is safe and the length calculation cannot overflow.
        unsafe {
            // FIXME: use usize::unchecked_sub after 1.79.0 release
            let new_len =
                usize::checked_sub(range.end as usize, range.start as usize).unwrap_unchecked();
            &mut *ptr::slice_from_raw_parts_mut(
                self.as_mut_ptr().add(range.start as usize),
                new_len,
            )
        }
    }
}

impl Debug for JanetArray<'_> {
    #[cfg_attr(feature = "inline-more", inline)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_char('@')?;
        f.debug_list().entries(self.iter()).finish()
    }
}

impl Clone for JanetArray<'_> {
    #[cfg_attr(feature = "inline-more", inline)]
    fn clone(&self) -> Self {
        let mut clone = Self::with_capacity(self.len());

        self.into_iter().for_each(|&j| clone.push(j));

        clone
    }
}

impl PartialOrd for JanetArray<'_> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for JanetArray<'_> {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.raw.cmp(&other.raw)
    }
}

impl PartialEq for JanetArray<'_> {
    #[inline]
    #[allow(clippy::unconditional_recursion)] // false positive
    fn eq(&self, other: &Self) -> bool {
        self.raw.eq(&other.raw)
    }
}

impl Eq for JanetArray<'_> {}

impl DeepEq for JanetArray<'_> {
    #[inline]
    fn deep_eq(&self, other: &Self) -> bool {
        if self.len() == other.len() {
            return self.iter().zip(other.iter()).all(|(s, o)| s.deep_eq(o));
        }
        false
    }
}

impl DeepEq<JanetTuple<'_>> for JanetArray<'_> {
    #[inline]
    fn deep_eq(&self, other: &JanetTuple) -> bool {
        if self.len() == other.len() {
            return self.iter().zip(other.iter()).all(|(s, o)| s.deep_eq(o));
        }
        false
    }
}


impl AsRef<[Janet]> for JanetArray<'_> {
    #[inline]
    fn as_ref(&self) -> &[Janet] {
        // SAFETY: Janet uses i32 as max size for all collections and indexing, so it always has
        // len lesser than isize::MAX
        // SAFETY 2: Checks for empty array, if it is, returns an empty slice and avoid trying to
        // access null data
        if self.is_empty() {
            &[]
        } else {
            unsafe {
                core::slice::from_raw_parts((*self.raw).data as *const Janet, self.len() as usize)
            }
        }
    }
}

impl AsMut<[Janet]> for JanetArray<'_> {
    #[inline]
    fn as_mut(&mut self) -> &mut [Janet] {
        // SAFETY: Janet uses i32 as max size for all collections and indexing, so it always has
        // len lesser than isize::MAX and we have exclusive access to the data
        // SAFETY 2: Checks for empty array, if it is, returns an empty slice and avoid trying to
        // access null data
        if self.is_empty() {
            &mut []
        } else {
            unsafe {
                core::slice::from_raw_parts_mut((*self.raw).data as *mut Janet, self.len() as usize)
            }
        }
    }
}

impl<'data> IntoIterator for JanetArray<'data> {
    type IntoIter = IntoIter<'data>;
    type Item = Janet;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        let len = self.len();

        IntoIter {
            arr: self,
            index_head: 0,
            index_tail: len,
        }
    }
}

impl<'a, 'data> IntoIterator for &'a JanetArray<'data> {
    type IntoIter = Iter<'a, 'data>;
    type Item = &'a Janet;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        let len = self.len();

        Iter {
            arr: self,
            index_head: 0,
            index_tail: len,
        }
    }
}

impl<'a, 'data> IntoIterator for &'a mut JanetArray<'data> {
    type IntoIter = IterMut<'a, 'data>;
    type Item = &'a mut Janet;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        let len = self.len();

        IterMut {
            arr: self,
            index_head: 0,
            index_tail: len,
        }
    }
}

impl<U: Into<Janet>> FromIterator<U> for JanetArray<'_> {
    #[cfg_attr(feature = "inline-more", inline)]
    fn from_iter<T: IntoIterator<Item = U>>(iter: T) -> Self {
        let iter = iter.into_iter();
        let (lower, upper) = iter.size_hint();

        let mut new = if let Some(upper) = upper {
            Self::with_capacity(upper as i32)
        } else {
            Self::with_capacity(lower as i32)
        };

        for item in iter {
            new.push(item);
        }
        new
    }
}

impl From<JanetTuple<'_>> for JanetArray<'_> {
    #[cfg_attr(feature = "inline-more", inline)]
    fn from(tup: JanetTuple<'_>) -> Self {
        tup.into_iter().collect()
    }
}

impl TryFrom<&[Janet]> for JanetArray<'_> {
    type Error = core::num::TryFromIntError;

    #[cfg_attr(feature = "inline-more", inline)]
    fn try_from(slice: &[Janet]) -> Result<Self, Self::Error> {
        let len = slice.len().try_into()?;
        let mut j_array = Self::with_capacity(len);

        slice.iter().for_each(|&e| j_array.push(e));

        Ok(j_array)
    }
}

impl TryFrom<&[CJanet]> for JanetArray<'_> {
    type Error = core::num::TryFromIntError;

    #[inline]
    fn try_from(slice: &[CJanet]) -> Result<Self, Self::Error> {
        let len = slice.len().try_into()?;

        Ok(Self {
            raw:     unsafe { evil_janet::janet_array_n(slice.as_ptr(), len) },
            phantom: PhantomData,
        })
    }
}

impl Default for JanetArray<'_> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Extend<Janet> for JanetArray<'_> {
    #[cfg_attr(feature = "inline-more", inline)]
    fn extend<T: IntoIterator<Item = Janet>>(&mut self, iter: T) {
        let iter = iter.into_iter();
        self.reserve_exact(iter.size_hint().0 as i32);
        iter.for_each(|val| self.push(val));
    }
}

impl<'a> Extend<&'a Janet> for JanetArray<'_> {
    #[cfg_attr(feature = "inline-more", inline)]
    fn extend<T: IntoIterator<Item = &'a Janet>>(&mut self, iter: T) {
        let iter = iter.into_iter();
        self.reserve_exact(iter.size_hint().0 as i32);
        iter.for_each(|&val| self.push(val));
    }
}

impl<T: AsRef<[Janet]>> JanetExtend<T> for JanetArray<'_> {
    #[inline]
    fn extend(&mut self, collection: T) {
        collection.as_ref().iter().for_each(|&elem| self.push(elem))
    }
}

impl Index<i32> for JanetArray<'_> {
    type Output = Janet;

    /// Get a immutable reference of the [`Janet`] hold by [`JanetArray`] at `index`.
    ///
    /// # Janet Panics
    /// Janet panic if try to access `index` out of the bounds.
    #[inline]
    fn index(&self, index: i32) -> &Self::Output {
        if index < 0 {
            crate::jpanic!(
                "index out of bounds: the index ({}) is negative and must be positive",
                index
            )
        }

        self.get(index).unwrap_or_else(|| {
            crate::jpanic!(
                "index out of bounds: the len is {} but the index is {}",
                self.len(),
                index
            )
        })
    }
}

impl IndexMut<i32> for JanetArray<'_> {
    /// Get a exclusive reference of the [`Janet`] hold by [`JanetArray`] at `index`.
    ///
    /// # Janet Panics
    /// Janet panic if try to access `index` out of the bounds.
    #[inline]
    fn index_mut(&mut self, index: i32) -> &mut Self::Output {
        let len = self.len();

        if index < 0 {
            crate::jpanic!(
                "index out of bounds: the index ({}) is negative and must be positive",
                index
            )
        }

        self.get_mut(index).unwrap_or_else(|| {
            crate::jpanic!(
                "index out of bounds: the len is {} but the index is {}",
                len,
                index
            )
        })
    }
}

/// An iterator over a reference to the [`JanetArray`] elements.
#[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Iter<'a, 'data> {
    arr: &'a JanetArray<'data>,
    index_head: i32,
    index_tail: i32,
}

impl Debug for Iter<'_, '_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.arr.as_ref()).finish()
    }
}

impl<'a> Iterator for Iter<'a, '_> {
    type Item = &'a Janet;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.index_head >= self.index_tail {
            None
        } else {
            let ret = self.arr.get(self.index_head);
            self.index_head += 1;
            ret
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let exact = (self.index_tail - self.index_head) as usize;
        (exact, Some(exact))
    }
}

impl DoubleEndedIterator for Iter<'_, '_> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.index_head == self.index_tail {
            None
        } else {
            self.index_tail -= 1;
            self.arr.get(self.index_tail)
        }
    }
}

impl ExactSizeIterator for Iter<'_, '_> {}

impl FusedIterator for Iter<'_, '_> {}

/// An iterator over a mutable reference to the [`JanetArray`] elements.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct IterMut<'a, 'data> {
    arr: &'a mut JanetArray<'data>,
    index_head: i32,
    index_tail: i32,
}

impl<'a, 'data> Iterator for IterMut<'a, 'data> {
    type Item = &'a mut Janet;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.index_head >= self.index_tail {
            None
        } else {
            let ret = self.arr.get_mut(self.index_head);
            self.index_head += 1;
            ret
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let exact = (self.index_tail - self.index_head) as usize;
        (exact, Some(exact))
    }
}

impl Debug for IterMut<'_, '_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.arr.as_ref()).finish()
    }
}

impl<'a, 'data> DoubleEndedIterator for IterMut<'a, 'data> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.index_head == self.index_tail {
            None
        } else {
            self.index_tail -= 1;
            self.arr.get_mut(self.index_tail)
        }
    }
}

impl ExactSizeIterator for IterMut<'_, '_> {}

impl FusedIterator for IterMut<'_, '_> {}

/// An iterator that moves out of a [`JanetArray`].
#[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct IntoIter<'data> {
    arr: JanetArray<'data>,
    index_head: i32,
    index_tail: i32,
}

impl Debug for IntoIter<'_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.arr.as_ref()).finish()
    }
}

impl Iterator for IntoIter<'_> {
    type Item = Janet;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.index_head >= self.index_tail {
            None
        } else {
            let ret = self.arr.get(self.index_head).cloned();
            self.index_head += 1;
            ret
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let exact = (self.index_tail - self.index_head) as usize;
        (exact, Some(exact))
    }
}

impl DoubleEndedIterator for IntoIter<'_> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.index_head == self.index_tail {
            None
        } else {
            self.index_tail -= 1;
            self.arr.get(self.index_tail).cloned()
        }
    }
}

impl ExactSizeIterator for IntoIter<'_> {}

impl FusedIterator for IntoIter<'_> {}

/// An iterator which uses a closure to determine if an element should be removed.
///
/// This struct is created by [`Vec::extract_if`].
/// See its documentation for more.
///
/// # Example
///
/// ```
/// use janetrs::{array, array::ExtractIf, Janet};
/// # let _client = janetrs::client::JanetClient::init().unwrap();
///
/// let mut array = array![0, 1, 2];
/// let iter: ExtractIf<'_, '_, _> =
///     array.extract_if(|x| x.try_unwrap::<i32>().map(|x| x % 2 == 0).unwrap_or(false));
/// ```
#[derive(Debug)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct ExtractIf<'a, 'data, F>
where
    F: FnMut(&mut Janet) -> bool,
{
    arr:     &'a mut JanetArray<'data>,
    idx:     usize,
    del:     usize,
    old_len: usize,
    pred:    F,
}

impl<F> Iterator for ExtractIf<'_, '_, F>
where
    F: FnMut(&mut Janet) -> bool,
{
    type Item = Janet;

    fn next(&mut self) -> Option<Self::Item> {
        use core::slice;
        unsafe {
            while self.idx < self.old_len {
                let i = self.idx;
                let v = slice::from_raw_parts_mut(self.arr.as_mut_ptr(), self.old_len);
                let drained = (self.pred)(&mut v[i]);

                // Update the index *after* the predicate is called. If the index
                // is updated prior and the predicate panics, the element at this
                // index would be leaked.
                self.idx += 1;
                if drained {
                    self.del += 1;
                    return Some(ptr::read(&v[i]));
                } else if self.del > 0 {
                    let del = self.del;
                    let src: *const Janet = &v[i];
                    let dst: *mut Janet = &mut v[i - del];
                    ptr::copy_nonoverlapping(src, dst, 1);
                }
            }
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.old_len - self.idx))
    }
}

impl<F> Drop for ExtractIf<'_, '_, F>
where
    F: FnMut(&mut Janet) -> bool,
{
    fn drop(&mut self) {
        unsafe {
            if self.idx < self.old_len && self.del > 0 {
                // This is a pretty messed up state, and there isn't really an
                // obviously right thing to do. We don't want to keep trying
                // to execute `pred`, so we just backshift all the unprocessed
                // elements and tell the vec that they still exist. The backshift
                // is required to prevent a double-drop of the last successfully
                // drained item prior to a panic in the predicate.
                let ptr = self.arr.as_mut_ptr();
                let src = ptr.add(self.idx);
                let dst = src.sub(self.del);
                let tail_len = self.old_len - self.idx;
                src.copy_to(dst, tail_len);
            }
            self.arr.set_len((self.old_len - self.del) as i32);
        }
    }
}

/// Convert pair of `ops::Bound`s into `ops::Range`.
/// Returns `None` on overflowing indices.
pub(crate) fn into_range(len: i32, (start, end): (Bound<&i32>, Bound<&i32>)) -> Option<Range<i32>> {
    let start = match start {
        Bound::Included(&start) => start,
        Bound::Excluded(&start) => start.checked_add(1)?,
        Bound::Unbounded => 0,
    };

    let end = match end {
        Bound::Included(&end) => end.checked_add(1)?,
        Bound::Excluded(&end) => end,
        Bound::Unbounded => len,
    };

    // Don't bother with checking `start < end` and `end <= len`
    // since these checks are handled by `Range` impls

    Some(start..end)
}

/// Convert pair of `ops::Bound`s into `ops::Range` without performing any bounds checking
/// and (in debug) overflow checking
pub(crate) fn into_range_unchecked(
    len: i32, (start, end): (Bound<&i32>, Bound<&i32>),
) -> Range<i32> {
    let start = match start {
        Bound::Included(&i) => i,
        Bound::Excluded(&i) => i + 1,
        Bound::Unbounded => 0,
    };
    let end = match end {
        Bound::Included(&i) => i + 1,
        Bound::Excluded(&i) => i,
        Bound::Unbounded => len,
    };
    start..end
}

#[cfg(all(test, any(feature = "amalgation", feature = "link-system")))]
mod tests {
    use super::*;
    use crate::{array, assert_deep_eq, client::JanetClient};
    use alloc::vec;

    #[test]
    fn empty_as_ref_as_mut() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;

        let mut v = array![];
        assert!(v.as_ref().is_empty());
        assert!(v.as_mut().is_empty());
        Ok(())
    }

    #[test]
    fn creation() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let array = JanetArray::new();

        assert_eq!(0, array.capacity());

        let array = JanetArray::with_capacity(10);
        assert_eq!(10, array.capacity());
        Ok(())
    }

    #[test]
    fn insert_and_length() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut array = JanetArray::new();

        assert!(array.is_empty());

        for i in 0..10 {
            array.push(i);
        }

        assert_eq!(10, array.len());
        Ok(())
    }

    #[test]
    fn push_within_capacity() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut array = JanetArray::with_capacity(3);

        assert!(array.push_within_capacity(10).is_ok());
        assert!(array.push_within_capacity(11).is_ok());
        assert!(array.push_within_capacity(12).is_ok());
        assert!(array.push_within_capacity(13).is_err());

        Ok(())
    }

    #[test]
    fn pop_and_peek() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut array = JanetArray::new();

        for i in 0..10 {
            array.push(i);
        }

        for _ in 0..10 {
            let last_peek = array.peek();
            let poped_last = array.pop().unwrap();

            assert_eq!(last_peek, poped_last);
        }
        Ok(())
    }

    #[test]
    fn pop_if() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;


        let mut array = array![1, 2, 3, 4];
        let pred = |x: &mut Janet| match x.try_unwrap::<i32>() {
            Ok(x) => x % 2 == 0,
            Err(_) => false,
        };

        assert_eq!(array.pop_if(pred), Some(Janet::from(4)));
        assert_deep_eq!(array, array![1, 2, 3]);
        assert_eq!(array.pop_if(pred), None);

        Ok(())
    }

    #[test]
    fn set_length() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut array = JanetArray::new();

        for i in 0..10 {
            array.push(i);
        }

        assert_eq!(10, array.len());
        array.set_len(0);
        assert_eq!(0, array.len());
        array.set_len(19);
        assert_eq!(19, array.len());
        assert_eq!(Janet::nil(), array.peek());
        array.set_len(-10);
        assert_eq!(19, array.len());
        Ok(())
    }

    #[test]
    fn get() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut array = JanetArray::new();
        array.push(10);

        assert_eq!(None, array.get(-1));
        assert_eq!(Some(&Janet::integer(10)), array.get(0));
        assert_eq!(None, array.get(1));
        Ok(())
    }

    #[test]
    fn get_mut() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut array = JanetArray::new();
        array.push(10);

        assert_eq!(None, array.get_mut(-1));
        assert_eq!(Some(&mut Janet::integer(10)), array.get_mut(0));
        assert_eq!(None, array.get_mut(1));

        *array.get_mut(0).unwrap() = Janet::boolean(true);
        assert_eq!(Some(&Janet::boolean(true)), array.get(0));
        Ok(())
    }

    #[test]
    #[allow(clippy::reversed_empty_ranges)]
    fn get_range() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let array = array![1, 2, 3, 4, 5];

        assert_eq!(array.len(), 5);

        assert_eq!(None, array.get_range(-1..));
        assert_eq!(None, array.get_range(-1..3));
        assert_eq!(None, array.get_range(-1..-2));
        assert_eq!(None, array.get_range(-2..-1));
        assert_eq!(None, array.get_range(..=5));

        assert_eq!(Some(array![1, 2].as_ref()), array.get_range(0..2));
        assert_eq!(Some(array![1, 2, 3].as_ref()), array.get_range(0..=2));
        assert_eq!(Some(array![1, 2, 3, 4].as_ref()), array.get_range(..=3));
        assert_eq!(Some(array![2, 3, 4, 5].as_ref()), array.get_range(1..));
        assert_eq!(Some(array![1, 2, 3, 4, 5].as_ref()), array.get_range(..));

        Ok(())
    }

    #[test]
    #[allow(clippy::reversed_empty_ranges)]
    fn get_range_mut() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut array = array![1, 2, 3, 4, 5];

        assert_eq!(array.len(), 5);

        assert_eq!(None, array.get_range_mut(-1..));
        assert_eq!(None, array.get_range_mut(-1..3));
        assert_eq!(None, array.get_range_mut(-2..-1));
        assert_eq!(None, array.get_range_mut(-2..-1));
        assert_eq!(None, array.get_range_mut(..=5));

        assert_eq!(Some(array![1, 2].as_mut()), array.get_range_mut(0..2));
        assert_eq!(Some(array![1, 2, 3].as_mut()), array.get_range_mut(0..=2));
        assert_eq!(Some(array![1, 2, 3, 4].as_mut()), array.get_range_mut(..=3));
        assert_eq!(Some(array![2, 3, 4, 5].as_mut()), array.get_range_mut(1..));
        assert_eq!(
            Some(array![1, 2, 3, 4, 5].as_mut()),
            array.get_range_mut(..)
        );

        Ok(())
    }

    #[test]
    fn iter_iterator() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let array = array![1, "hey", true];

        let mut iter = array.iter();

        assert_eq!(Some(&Janet::integer(1)), iter.next());
        assert_eq!(Some(&Janet::from("hey")), iter.next());
        assert_eq!(Some(&Janet::boolean(true)), iter.next());
        assert_eq!(None, iter.next());
        Ok(())
    }

    #[test]
    fn iter_double_ended_iterator() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let numbers = array![1, 2, 3, 4, 5, 6];

        let mut iter = numbers.iter();

        assert_eq!(Some(&Janet::integer(1)), iter.next());
        assert_eq!(Some(&Janet::integer(6)), iter.next_back());
        assert_eq!(Some(&Janet::integer(5)), iter.next_back());
        assert_eq!(Some(&Janet::integer(2)), iter.next());
        assert_eq!(Some(&Janet::integer(3)), iter.next());
        assert_eq!(Some(&Janet::integer(4)), iter.next());
        assert_eq!(None, iter.next());
        assert_eq!(None, iter.next_back());
        Ok(())
    }

    #[test]
    fn itermut_iterator() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut array = array![1, "hey", true];

        let mut iter = array.iter_mut();

        assert_eq!(Some(&mut Janet::integer(1)), iter.next());
        assert_eq!(Some(&mut Janet::from("hey")), iter.next());
        assert_eq!(Some(&mut Janet::boolean(true)), iter.next());
        assert_eq!(None, iter.next());
        Ok(())
    }

    #[test]
    fn itermut_double_ended_iterator() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut numbers = array![1, 2, 3, 4, 5, 6];

        let mut iter = numbers.iter_mut();

        assert_eq!(Some(&mut Janet::integer(1)), iter.next());
        assert_eq!(Some(&mut Janet::integer(6)), iter.next_back());
        assert_eq!(Some(&mut Janet::integer(5)), iter.next_back());
        assert_eq!(Some(&mut Janet::integer(2)), iter.next());
        assert_eq!(Some(&mut Janet::integer(3)), iter.next());
        assert_eq!(Some(&mut Janet::integer(4)), iter.next());
        assert_eq!(None, iter.next());
        assert_eq!(None, iter.next_back());
        Ok(())
    }

    #[test]
    fn intoiter_iterator() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let array = array![1, "hey", true];

        let mut iter = array.into_iter();

        assert_eq!(Some(Janet::integer(1)), iter.next());
        assert_eq!(Some(Janet::from("hey")), iter.next());
        assert_eq!(Some(Janet::boolean(true)), iter.next());
        assert_eq!(None, iter.next());
        Ok(())
    }

    #[test]
    fn intoiter_double_ended_iterator() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let numbers = array![1, 2, 3, 4, 5, 6];

        let mut iter = numbers.into_iter();

        assert_eq!(Some(Janet::integer(1)), iter.next());
        assert_eq!(Some(Janet::integer(6)), iter.next_back());
        assert_eq!(Some(Janet::integer(5)), iter.next_back());
        assert_eq!(Some(Janet::integer(2)), iter.next());
        assert_eq!(Some(Janet::integer(3)), iter.next());
        assert_eq!(Some(Janet::integer(4)), iter.next());
        assert_eq!(None, iter.next());
        assert_eq!(None, iter.next_back());
        Ok(())
    }

    #[test]
    fn collect() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let vec = vec![Janet::nil(); 100];

        let jarr: JanetArray<'_> = vec.into_iter().collect();
        assert_eq!(jarr.len(), 100);
        assert!(jarr.iter().all(|j| j == Janet::nil()));

        let vec = vec![101.0; 100];

        let jarr: JanetArray<'_> = vec.into_iter().collect();
        assert_eq!(jarr.len(), 100);
        assert!(jarr.iter().all(|j| j == Janet::number(101.0)));
        Ok(())
    }

    #[test]
    fn split_off() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;

        let mut arr = array![1, 2, 3];
        let arr2 = arr.split_off(1);
        assert_deep_eq!(arr, array![1]);
        assert_deep_eq!(arr2, array![2, 3]);

        Ok(())
    }

    #[test]
    fn size_hint() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut iter = array![Janet::nil(); 100].into_iter();

        // The code for all the iterators of the array are the same
        assert_eq!(iter.len(), 100);
        let _ = iter.next();
        assert_eq!(iter.len(), 99);
        let _ = iter.next_back();
        assert_eq!(iter.len(), 98);
        Ok(())
    }

    #[test]
    fn insert() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut array = array![1, 2, 3, 4];

        assert_eq!(array.len(), 4);
        assert_eq!(array[1], &Janet::integer(2));
        assert_eq!(array[2], &Janet::integer(3));

        array.insert(1, 10);

        assert_eq!(array.len(), 5);
        assert_eq!(array[1], &Janet::integer(10));
        assert_eq!(array[2], &Janet::integer(2));
        assert_eq!(array[3], &Janet::integer(3));
        Ok(())
    }

    #[test]
    fn remove() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut array = array![1, 2, 3, 4];

        assert_eq!(array.len(), 4);
        let rm = array.remove(1);
        assert_eq!(array.len(), 3);
        assert_eq!(rm, Janet::integer(2));
        Ok(())
    }

    #[test]
    fn retain() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;

        let mut array = array![1, 2, 3, 4];
        array.retain(|&x| x.try_unwrap::<i32>().map(|x| x % 2 == 0).unwrap_or(false));
        assert_deep_eq!(array, array![2, 4]);

        Ok(())
    }

    #[test]
    fn retain_mut() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;

        let mut array = array![1, 2, 3, 4];
        array.retain_mut(|x| {
            let val = match x.try_unwrap::<i32>() {
                Ok(x) => x,
                _ => return false,
            };

            if val <= 3 {
                *x = Janet::integer(val + 1);
                true
            } else {
                false
            }
        });

        assert_deep_eq!(array, array![2, 3, 4]);

        Ok(())
    }

    #[test]
    fn dedup_by() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init().unwrap();
        let mut arr = array!["foo", "bar", "bar", "baz", "bar"];

        arr.dedup_by(|&mut a, &mut b| a.eq(&b));
        assert!(arr.deep_eq(&array!["foo", "bar", "baz", "bar"]));

        Ok(())
    }

    #[test]
    fn clear() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;
        let mut array = array![1, 2, 3, 4, "5", 6.0];

        assert_eq!(array.len(), 6);
        assert_eq!(array.capacity(), 6);

        array.clear();

        assert!(array.is_empty());
        assert_eq!(array.capacity(), 6);
        Ok(())
    }

    #[test]
    fn repeat() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;

        let array = array![1, 2];
        let repeated = array.repeat(6);

        assert_eq!(repeated.len(), 12);
        assert_deep_eq!(repeated, array![1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]);

        Ok(())
    }

    #[test]
    fn extract_if() -> Result<(), crate::client::Error> {
        let _client = JanetClient::init()?;

        let mut array = array![0, 1, 2];
        let _iter: ExtractIf<'_, '_, _> =
            array.extract_if(|x| x.try_unwrap::<i32>().map(|x| x % 2 == 0).unwrap_or(false));


        // Splitting an array into evens and odds, reusing the original allocation:

        let mut numbers = array![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];

        let evens = numbers
            .extract_if(|x| x.try_unwrap::<i32>().map(|x| x % 2 == 0).unwrap_or(false))
            .collect::<JanetArray>();
        let odds = numbers;

        assert_deep_eq!(evens, array![2, 4, 6, 8, 14]);
        assert_deep_eq!(odds, array![1, 3, 5, 9, 11, 13, 15]);
        Ok(())
    }
}