stringtape 2.2.3

A tape class for strings arrays compatible with Apache Arrow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
#![cfg_attr(not(feature = "std"), no_std)]

//! # StringTape
//!
//! Memory-efficient string and bytes storage compatible with Apache Arrow.
//!
//! ## CharsTape - Sequential String Storage
//!
//! ```rust
//! use stringtape::{CharsTapeI32, StringTapeError};
//!
//! let mut tape = CharsTapeI32::new();
//! tape.push("hello")?;
//! tape.push("world")?;
//!
//! assert_eq!(tape.len(), 2);
//! assert_eq!(&tape[0], "hello");
//!
//! // Iterate over strings
//! for s in &tape {
//!     println!("{}", s);
//! }
//! # Ok::<(), StringTapeError>(())
//! ```
//!
//! ## CharsCows - Compressed Arbitrary-Order Slices
//!
//! For extremely large datasets, use `CharsCows` with configurable offset/length types:
//!
//! ```rust
//! use stringtape::{CharsCowsU32U16, StringTapeError};
//! use std::borrow::Cow;
//!
//! let data = "hello world foo bar";
//! // 6 bytes per entry (u32 offset + u16 length) vs 24+ bytes for Vec<String>
//! let cows = CharsCowsU32U16::from_iter_and_data(
//!     data.split_whitespace(),
//!     Cow::Borrowed(data.as_bytes())
//! )?;
//!
//! assert_eq!(&cows[0], "hello");
//! assert_eq!(&cows[3], "bar");
//! # Ok::<(), StringTapeError>(())
//! ```
//!
//! ## BytesTape - Binary Data
//!
//! ```rust
//! use stringtape::{BytesTapeI32, StringTapeError};
//!
//! let mut tape = BytesTapeI32::new();
//! tape.push(&[0xde, 0xad, 0xbe, 0xef])?;
//! tape.push(b"bytes")?;
//!
//! assert_eq!(&tape[1], b"bytes" as &[u8]);
//! # Ok::<(), StringTapeError>(())
//! ```

#[cfg(feature = "std")]
extern crate std;

#[cfg(not(feature = "std"))]
extern crate alloc;

use core::fmt;
use core::marker::PhantomData;
use core::ops::{
    Index, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, Sub,
};
use core::ptr::{self, NonNull};
use core::slice;

#[cfg(not(feature = "std"))]
use alloc::borrow::Cow;
#[cfg(not(feature = "std"))]
use alloc::string::String;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

#[cfg(feature = "std")]
use std::borrow::Cow;

use allocator_api2::alloc::{Allocator, Global, Layout};

/// Errors that can occur when working with tape classes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StringTapeError {
    /// Data size exceeds offset type maximum (e.g., >2GB for 32-bit offsets).
    OffsetOverflow,
    /// Memory allocation failed.
    AllocationError,
    /// Index out of bounds.
    IndexOutOfBounds,
    /// Invalid UTF-8 sequence.
    Utf8Error(core::str::Utf8Error),
}

impl fmt::Display for StringTapeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StringTapeError::OffsetOverflow => write!(f, "offset value too large for offset type"),
            StringTapeError::AllocationError => write!(f, "memory allocation failed"),
            StringTapeError::IndexOutOfBounds => write!(f, "index out of bounds"),
            StringTapeError::Utf8Error(e) => write!(f, "invalid UTF-8: {}", e),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for StringTapeError {}

/// A memory-efficient string storage structure compatible with Apache Arrow.
///
/// `CharsTape` stores multiple strings in a contiguous memory layout using offset-based
/// indexing, similar to Apache Arrow's String and LargeString arrays. All string data
/// is stored in a single buffer, with a separate offset array tracking string boundaries.
///
/// # Type Parameters
///
/// * `Offset` - Offset type (`i32`, `i64`, `u32`, `u64`)
/// * `A` - Allocator type (defaults to `Global`)
///
/// # Example
///
/// ```rust
/// use stringtape::{CharsTapeI32, StringTapeError};
///
/// let mut tape = CharsTapeI32::new();
/// tape.push("hello")?;
/// assert_eq!(&tape[0], "hello");
/// # Ok::<(), StringTapeError>(())
/// ```
///
/// Memory layout compatible with Apache Arrow:
/// ```text
/// Data:    [h,e,l,l,o,w,o,r,l,d]
/// Offsets: [0, 5, 10]
/// ```
struct RawTape<Offset: OffsetType, A: Allocator> {
    data: Option<NonNull<[u8]>>,
    offsets: Option<NonNull<[Offset]>>,
    len_bytes: usize,
    len_items: usize,
    allocator: A,
    _phantom: PhantomData<Offset>,
}

/// Named raw parts returned by `as_raw_parts` methods.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RawParts<Offset: OffsetType> {
    /// Pointer to the start of the contiguous data buffer.
    pub data_ptr: *const u8,
    /// Pointer to the start of the offsets buffer.
    pub offsets_ptr: *const Offset,
    /// Number of bytes of valid data in `data_ptr`.
    pub data_len: usize,
    /// Number of items stored (strings/bytes entries).
    pub items_count: usize,
}

/// UTF-8 string view over `RawTape`.
pub struct CharsTape<Offset: OffsetType = i32, A: Allocator = Global> {
    inner: RawTape<Offset, A>,
}

/// Binary bytes view over `RawTape`.
pub struct BytesTape<Offset: OffsetType = i32, A: Allocator = Global> {
    inner: RawTape<Offset, A>,
}

/// Zero-copy read-only view into a RawTape slice.
pub struct RawTapeView<'a, Offset: OffsetType> {
    data: &'a [u8],
    offsets: &'a [Offset],
}

/// UTF-8 string view over `RawTapeView`.
pub struct CharsTapeView<'a, Offset: OffsetType = i32> {
    inner: RawTapeView<'a, Offset>,
}

/// Binary bytes view over `RawTapeView`.
pub struct BytesTapeView<'a, Offset: OffsetType = i32> {
    inner: RawTapeView<'a, Offset>,
}

/// Trait for offset types used in CharsTape.
///
/// Implementations: `i32`/`i64` (Arrow-compatible), `u32`/`u64` (unsigned, no Arrow interop).
pub trait OffsetType: Copy + Default + PartialOrd + Sub<Output = Self> {
    /// Size of the offset type in bytes.
    const SIZE: usize;

    /// Convert a usize value to this offset type.
    ///
    /// Returns `None` if the value is too large to be represented by this offset type.
    fn from_usize(value: usize) -> Option<Self>;

    /// Convert this offset value to usize.
    fn to_usize(self) -> usize;
}

impl OffsetType for i32 {
    const SIZE: usize = 4;

    fn from_usize(value: usize) -> Option<Self> {
        if value <= i32::MAX as usize {
            Some(value as i32)
        } else {
            None
        }
    }

    fn to_usize(self) -> usize {
        self as usize
    }
}

impl OffsetType for i64 {
    const SIZE: usize = 8;

    fn from_usize(value: usize) -> Option<Self> {
        Some(value as i64)
    }

    fn to_usize(self) -> usize {
        self as usize
    }
}

impl OffsetType for u16 {
    const SIZE: usize = 2;

    fn from_usize(value: usize) -> Option<Self> {
        if value <= u16::MAX as usize {
            Some(value as u16)
        } else {
            None
        }
    }

    fn to_usize(self) -> usize {
        self as usize
    }
}

impl OffsetType for u32 {
    const SIZE: usize = 4;

    fn from_usize(value: usize) -> Option<Self> {
        if value <= u32::MAX as usize {
            Some(value as u32)
        } else {
            None
        }
    }

    fn to_usize(self) -> usize {
        self as usize
    }
}

impl OffsetType for u64 {
    const SIZE: usize = 8;

    fn from_usize(value: usize) -> Option<Self> {
        Some(value as u64)
    }

    fn to_usize(self) -> usize {
        self as usize
    }
}

/// Trait for length types used in slice collections.
///
/// This trait defines the interface for length types that can be used to represent
/// the length of string cows. Implementations are provided for `u8`, `u16`, `u32`, and `u64`.
pub trait LengthType: Copy + Default + PartialOrd {
    /// Size of the length type in bytes.
    const SIZE: usize;

    /// Convert a usize value to this length type.
    ///
    /// Returns `None` if the value is too large to be represented by this length type.
    fn from_usize(value: usize) -> Option<Self>;

    /// Convert this length value to usize.
    fn to_usize(self) -> usize;
}

impl LengthType for u8 {
    const SIZE: usize = 1;

    fn from_usize(value: usize) -> Option<Self> {
        if value <= u8::MAX as usize {
            Some(value as u8)
        } else {
            None
        }
    }

    fn to_usize(self) -> usize {
        self as usize
    }
}

impl LengthType for u16 {
    const SIZE: usize = 2;

    fn from_usize(value: usize) -> Option<Self> {
        if value <= u16::MAX as usize {
            Some(value as u16)
        } else {
            None
        }
    }

    fn to_usize(self) -> usize {
        self as usize
    }
}

impl LengthType for u32 {
    const SIZE: usize = 4;

    fn from_usize(value: usize) -> Option<Self> {
        if value <= u32::MAX as usize {
            Some(value as u32)
        } else {
            None
        }
    }

    fn to_usize(self) -> usize {
        self as usize
    }
}

impl LengthType for u64 {
    const SIZE: usize = 8;

    fn from_usize(value: usize) -> Option<Self> {
        Some(value as u64)
    }

    fn to_usize(self) -> usize {
        self as usize
    }
}

impl<Offset: OffsetType, A: Allocator> RawTape<Offset, A> {
    /// Creates a new, empty CharsTape with the global allocator.
    ///
    /// This operation is O(1) and does not allocate memory until the first string is pushed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsTapeI32;
    ///
    /// let tape = CharsTapeI32::new();
    /// assert!(tape.is_empty());
    /// assert_eq!(tape.len(), 0);
    /// ```
    pub fn new() -> RawTape<Offset, Global> {
        RawTape::new_in(Global)
    }

    /// Creates a new, empty CharsTape with a custom allocator.
    ///
    /// This operation is O(1) and does not allocate memory until the first string is pushed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsTape;
    /// use allocator_api2::alloc::Global;
    ///
    /// let tape: CharsTape<i32, Global> = CharsTape::new_in(Global);
    /// assert!(tape.is_empty());
    /// assert_eq!(tape.len(), 0);
    /// ```
    pub fn new_in(allocator: A) -> Self {
        Self {
            data: None,
            offsets: None,
            len_bytes: 0,
            len_items: 0,
            allocator,
            _phantom: PhantomData,
        }
    }

    /// Creates a tape with pre-allocated capacity.
    ///
    /// # Arguments
    ///
    /// * `data_capacity` - Bytes for string data
    /// * `strings_capacity` - Number of string slots
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::{CharsTapeI32, StringTapeError};
    ///
    /// // Pre-allocate space for ~1KB of string data and 100 strings
    /// let tape = CharsTapeI32::with_capacity(1024, 100)?;
    /// assert_eq!(tape.data_capacity(), 1024);
    /// # Ok::<(), StringTapeError>(())
    /// ```
    pub fn with_capacity(
        data_capacity: usize,
        strings_capacity: usize,
    ) -> Result<RawTape<Offset, Global>, StringTapeError> {
        RawTape::with_capacity_in(data_capacity, strings_capacity, Global)
    }

    /// Creates a new CharsTape with pre-allocated capacity and a custom allocator.
    ///
    /// Pre-allocating capacity can improve performance when you know approximately
    /// how much data you'll be storing.
    ///
    /// # Arguments
    ///
    /// * `data_capacity` - Number of bytes to pre-allocate for string data
    /// * `strings_capacity` - Number of string slots to pre-allocate
    /// * `allocator` - The allocator to use for memory management
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::{CharsTape, StringTapeError};
    /// use allocator_api2::alloc::Global;
    ///
    /// let tape: CharsTape<i32, Global> = CharsTape::with_capacity_in(1024, 100, Global)?;
    /// assert_eq!(tape.data_capacity(), 1024);
    /// # Ok::<(), StringTapeError>(())
    /// ```
    pub fn with_capacity_in(
        data_capacity: usize,
        strings_capacity: usize,
        allocator: A,
    ) -> Result<Self, StringTapeError> {
        let mut tape = Self::new_in(allocator);
        tape.reserve(data_capacity, strings_capacity)?;
        Ok(tape)
    }

    pub fn reserve(
        &mut self,
        additional_bytes: usize,
        additional_strings: usize,
    ) -> Result<(), StringTapeError> {
        if additional_bytes > 0 {
            let current_capacity = self.data_capacity();
            let new_capacity = current_capacity
                .checked_add(additional_bytes)
                .ok_or(StringTapeError::AllocationError)?;
            self.grow_data(new_capacity)?;
        }

        if additional_strings > 0 {
            let current_capacity = self.offsets_capacity();
            let new_capacity = current_capacity
                .checked_add(additional_strings + 1)
                .ok_or(StringTapeError::AllocationError)?;
            self.grow_offsets(new_capacity)?;
        }
        Ok(())
    }

    fn grow_data(&mut self, new_capacity: usize) -> Result<(), StringTapeError> {
        let current_capacity = self.data_capacity();
        if new_capacity <= current_capacity {
            return Ok(());
        }

        let new_layout =
            Layout::array::<u8>(new_capacity).map_err(|_| StringTapeError::AllocationError)?;

        let new_ptr = if let Some(old_ptr) = self.data {
            // Grow existing allocation
            let old_layout = Layout::array::<u8>(current_capacity).unwrap();
            unsafe {
                self.allocator
                    .grow(old_ptr.cast(), old_layout, new_layout)
                    .map_err(|_| StringTapeError::AllocationError)?
            }
        } else {
            // Initial allocation
            self.allocator
                .allocate(new_layout)
                .map_err(|_| StringTapeError::AllocationError)?
        };

        self.data = Some(NonNull::slice_from_raw_parts(new_ptr.cast(), new_capacity));
        Ok(())
    }

    fn grow_offsets(&mut self, new_capacity: usize) -> Result<(), StringTapeError> {
        let current_capacity = self.offsets_capacity();
        if new_capacity <= current_capacity {
            return Ok(());
        }

        let new_layout =
            Layout::array::<Offset>(new_capacity).map_err(|_| StringTapeError::AllocationError)?;

        let new_ptr = if let Some(old_ptr) = self.offsets {
            // Grow existing allocation
            let old_layout = Layout::array::<Offset>(current_capacity).unwrap();
            unsafe {
                self.allocator
                    .grow(old_ptr.cast(), old_layout, new_layout)
                    .map_err(|_| StringTapeError::AllocationError)?
            }
        } else {
            // Initial allocation with first offset = 0
            self.allocator
                .allocate_zeroed(new_layout)
                .map_err(|_| StringTapeError::AllocationError)?
        };

        self.offsets = Some(NonNull::slice_from_raw_parts(new_ptr.cast(), new_capacity));
        Ok(())
    }

    /// Appends bytes to the tape.
    ///
    /// # Errors
    ///
    /// - `OffsetOverflow` if data size exceeds offset type maximum
    /// - `AllocationError` if memory allocation fails
    ///
    /// # Example
    ///
    /// ```rust
    /// # use stringtape::{BytesTapeI32, StringTapeError};
    /// let mut tape = BytesTapeI32::new();
    /// tape.push(b"hello")?;
    /// assert_eq!(tape.len(), 1);
    /// # Ok::<(), StringTapeError>(())
    /// ```
    pub fn push(&mut self, bytes: &[u8]) -> Result<(), StringTapeError> {
        let required_capacity = self
            .len_bytes
            .checked_add(bytes.len())
            .ok_or(StringTapeError::AllocationError)?;

        let current_data_capacity = self.data_capacity();
        if required_capacity > current_data_capacity {
            let new_capacity = (current_data_capacity * 2).max(required_capacity).max(64);
            self.grow_data(new_capacity)?;
        }

        let current_offsets_capacity = self.offsets_capacity();
        if self.len_items + 1 >= current_offsets_capacity {
            let new_capacity = (current_offsets_capacity * 2)
                .max(self.len_items + 2)
                .max(8);
            self.grow_offsets(new_capacity)?;
        }

        // Copy string data
        if let Some(data_ptr) = self.data {
            unsafe {
                ptr::copy_nonoverlapping(
                    bytes.as_ptr(),
                    data_ptr.as_ptr().cast::<u8>().add(self.len_bytes),
                    bytes.len(),
                );
            }
        }

        self.len_bytes += bytes.len();
        self.len_items += 1;

        // Write new offset
        let offset = Offset::from_usize(self.len_bytes).ok_or(StringTapeError::OffsetOverflow)?;
        if let Some(offsets_ptr) = self.offsets {
            unsafe {
                ptr::write(
                    offsets_ptr.as_ptr().cast::<Offset>().add(self.len_items),
                    offset,
                );
            }
        }

        Ok(())
    }

    /// Returns a reference to the bytes at the given index, or `None` if out of bounds.
    ///
    /// This operation is O(1).
    pub fn get(&self, index: usize) -> Option<&[u8]> {
        if index >= self.len_items {
            return None;
        }

        let (data_ptr, offsets_ptr) = match (self.data, self.offsets) {
            (Some(data), Some(offsets)) => (data, offsets),
            _ => return None,
        };

        unsafe {
            let offsets_ptr = offsets_ptr.as_ptr().cast::<Offset>();
            let start_offset = if index == 0 {
                0
            } else {
                ptr::read(offsets_ptr.add(index)).to_usize()
            };
            let end_offset = ptr::read(offsets_ptr.add(index + 1)).to_usize();

            Some(slice::from_raw_parts(
                data_ptr.as_ptr().cast::<u8>().add(start_offset),
                end_offset - start_offset,
            ))
        }
    }

    /// Returns the number of items in the tape.
    pub fn len(&self) -> usize {
        self.len_items
    }

    /// Returns `true` if the CharsTape contains no strings.
    pub fn is_empty(&self) -> bool {
        self.len_items == 0
    }

    /// Returns the total number of bytes used by string data.
    pub fn data_len(&self) -> usize {
        self.len_bytes
    }

    /// Returns the number of items currently stored (same as `len()`).
    #[allow(dead_code)]
    pub fn capacity(&self) -> usize {
        self.len_items
    }

    /// Returns the number of bytes allocated for string data.
    pub fn data_capacity(&self) -> usize {
        self.data.map(|ptr| ptr.len()).unwrap_or(0)
    }

    /// Returns the number of offset slots allocated.
    pub fn offsets_capacity(&self) -> usize {
        self.offsets.map(|ptr| ptr.len()).unwrap_or(0)
    }

    /// Removes all items from the tape, keeping allocated capacity.
    pub fn clear(&mut self) {
        self.len_bytes = 0;
        self.len_items = 0;
        if let Some(offsets_ptr) = self.offsets {
            unsafe {
                ptr::write(offsets_ptr.as_ptr().cast::<Offset>(), Offset::default());
            }
        }
    }

    /// Keeps the first `len` items, drops the rest.
    pub fn truncate(&mut self, len: usize) {
        if len >= self.len_items {
            return;
        }

        self.len_items = len;
        self.len_bytes = if len == 0 {
            0
        } else if let Some(offsets_ptr) = self.offsets {
            unsafe { ptr::read(offsets_ptr.as_ptr().cast::<Offset>().add(len)).to_usize() }
        } else {
            0
        };
    }

    /// Appends all items from an iterator.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use stringtape::{BytesTapeI32, StringTapeError};
    /// let mut tape = BytesTapeI32::new();
    /// tape.extend([b"hello".as_slice(), b"world".as_slice()])?;
    /// # Ok::<(), StringTapeError>(())
    /// ```
    pub fn extend<I>(&mut self, iter: I) -> Result<(), StringTapeError>
    where
        I: IntoIterator,
        I::Item: AsRef<[u8]>,
    {
        for s in iter {
            self.push(s.as_ref())?;
        }
        Ok(())
    }

    /// Returns raw pointers for Apache Arrow compatibility.
    ///
    /// Returns `data_ptr`, `offsets_ptr`, `data_len`, `items_count`.
    ///
    /// # Safety
    ///
    /// Pointers valid only while tape is unmodified.
    pub fn as_raw_parts(&self) -> RawParts<Offset> {
        let data_ptr = self
            .data
            .map(|ptr| ptr.as_ptr().cast::<u8>() as *const u8)
            .unwrap_or(ptr::null());
        let offsets_ptr = self
            .offsets
            .map(|ptr| ptr.as_ptr().cast::<Offset>() as *const Offset)
            .unwrap_or(ptr::null());
        RawParts {
            data_ptr,
            offsets_ptr,
            data_len: self.len_bytes,
            items_count: self.len_items,
        }
    }

    /// Returns a slice view of the data buffer.
    ///
    /// This provides a cleaner interface for accessing the underlying data
    /// without dealing with raw pointers.
    pub fn data_slice(&self) -> &[u8] {
        if let Some(data_ptr) = self.data {
            unsafe { core::slice::from_raw_parts(data_ptr.as_ptr().cast::<u8>(), self.len_bytes) }
        } else {
            &[]
        }
    }

    /// Returns a slice view of the offsets buffer.
    ///
    /// This provides a cleaner interface for accessing the underlying offsets
    /// without dealing with raw pointers. The slice contains `len() + 1` elements.
    pub fn offsets_slice(&self) -> &[Offset] {
        if let Some(offsets_ptr) = self.offsets {
            unsafe {
                core::slice::from_raw_parts(
                    offsets_ptr.as_ptr().cast::<Offset>(),
                    self.len_items + 1,
                )
            }
        } else {
            &[]
        }
    }

    /// Returns a reference to the allocator used by this tape.
    pub fn allocator(&self) -> &A {
        &self.allocator
    }

    /// Creates a view of the entire tape.
    pub fn view(&self) -> RawTapeView<'_, Offset> {
        RawTapeView::new(self, 0, self.len_items).unwrap_or(RawTapeView {
            data: &[],
            offsets: &[],
        })
    }

    /// Creates a subview of a continuous slice of this tape.
    pub fn subview(
        &self,
        start: usize,
        end: usize,
    ) -> Result<RawTapeView<'_, Offset>, StringTapeError> {
        RawTapeView::new(self, start, end)
    }
}

impl<Offset: OffsetType, A: Allocator> Drop for RawTape<Offset, A> {
    fn drop(&mut self) {
        if let Some(data_ptr) = self.data {
            let layout = Layout::array::<u8>(data_ptr.len()).unwrap();
            unsafe {
                self.allocator.deallocate(data_ptr.cast(), layout);
            }
        }
        if let Some(offsets_ptr) = self.offsets {
            let layout = Layout::array::<Offset>(offsets_ptr.len()).unwrap();
            unsafe {
                self.allocator.deallocate(offsets_ptr.cast(), layout);
            }
        }
    }
}

unsafe impl<Offset: OffsetType + Send, A: Allocator + Send> Send for RawTape<Offset, A> {}
unsafe impl<Offset: OffsetType + Sync, A: Allocator + Sync> Sync for RawTape<Offset, A> {}

// Index trait implementations for RawTape to support [i..n] syntax
impl<Offset: OffsetType, A: Allocator> Index<Range<usize>> for RawTape<Offset, A> {
    type Output = [u8];

    fn index(&self, range: Range<usize>) -> &Self::Output {
        let view = self
            .subview(range.start, range.end)
            .expect("range out of bounds");
        // Return the underlying data slice
        view.data
    }
}

impl<Offset: OffsetType, A: Allocator> Index<RangeFrom<usize>> for RawTape<Offset, A> {
    type Output = [u8];

    fn index(&self, range: RangeFrom<usize>) -> &Self::Output {
        let view = self
            .subview(range.start, self.len_items)
            .expect("range out of bounds");
        view.data
    }
}

impl<Offset: OffsetType, A: Allocator> Index<RangeTo<usize>> for RawTape<Offset, A> {
    type Output = [u8];

    fn index(&self, range: RangeTo<usize>) -> &Self::Output {
        let view = self.subview(0, range.end).expect("range out of bounds");
        view.data
    }
}

impl<Offset: OffsetType, A: Allocator> Index<RangeFull> for RawTape<Offset, A> {
    type Output = [u8];

    fn index(&self, _range: RangeFull) -> &Self::Output {
        let view = self.view();
        view.data
    }
}

impl<Offset: OffsetType, A: Allocator> Index<RangeInclusive<usize>> for RawTape<Offset, A> {
    type Output = [u8];

    fn index(&self, range: RangeInclusive<usize>) -> &Self::Output {
        let view = self
            .subview(*range.start(), range.end() + 1)
            .expect("range out of bounds");
        view.data
    }
}

impl<Offset: OffsetType, A: Allocator> Index<RangeToInclusive<usize>> for RawTape<Offset, A> {
    type Output = [u8];

    fn index(&self, range: RangeToInclusive<usize>) -> &Self::Output {
        let view = self.subview(0, range.end + 1).expect("range out of bounds");
        view.data
    }
}

// ========================
// RawTapeView implementation
// ========================

impl<'a, Offset: OffsetType> RawTapeView<'a, Offset> {
    /// Creates a view into a slice of the RawTape from start to end (exclusive).
    pub(crate) fn new<A: Allocator>(
        tape: &'a RawTape<Offset, A>,
        start: usize,
        end: usize,
    ) -> Result<Self, StringTapeError> {
        if start > end || end > tape.len() {
            return Err(StringTapeError::IndexOutOfBounds);
        }

        let (data_ptr, offsets_ptr) = match (tape.data, tape.offsets) {
            (Some(data), Some(offsets)) => (data, offsets),
            _ => return Err(StringTapeError::IndexOutOfBounds),
        };

        // Keep the data pointer at the beginning of the parent tape to remain Arrow-compatible.
        // Offsets remain absolute (not normalized) and are sliced to the requested range.
        let data = unsafe { slice::from_raw_parts(data_ptr.as_ptr().cast::<u8>(), tape.len_bytes) };

        let offsets = unsafe {
            slice::from_raw_parts(
                offsets_ptr.as_ptr().cast::<Offset>().add(start),
                (end - start) + 1,
            )
        };

        Ok(Self { data, offsets })
    }

    /// Creates a zero-copy view from raw Arrow-compatible parts.
    ///
    /// # Safety
    ///
    /// The caller must ensure that:
    /// - `data` contains valid bytes for the lifetime `'a`
    /// - `offsets` contains valid offsets with length `items_count + 1`
    /// - All offsets are within bounds of the data slice
    /// - For CharsTapeView, data must be valid UTF-8
    pub unsafe fn from_raw_parts(data: &'a [u8], offsets: &'a [Offset]) -> Self {
        Self { data, offsets }
    }

    /// Returns a reference to the bytes at the given index within this view.
    pub fn get(&self, index: usize) -> Option<&[u8]> {
        if index >= self.len() {
            return None;
        }

        let start_offset = self.offsets[index].to_usize();
        let end_offset = self.offsets[index + 1].to_usize();

        Some(&self.data[start_offset..end_offset])
    }

    /// Returns the number of items in this view.
    pub fn len(&self) -> usize {
        self.offsets.len().saturating_sub(1)
    }

    /// Returns `true` if the view contains no items.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the total number of bytes in this view.
    pub fn data_len(&self) -> usize {
        // Span covered by this view
        self.offsets[self.offsets.len() - 1].to_usize() - self.offsets[0].to_usize()
    }

    /// Creates a sub-view of this view
    pub fn subview(
        &self,
        start: usize,
        end: usize,
    ) -> Result<RawTapeView<'a, Offset>, StringTapeError> {
        if start > end || end > self.len() {
            return Err(StringTapeError::IndexOutOfBounds);
        }

        Ok(RawTapeView {
            // Keep same data pointer, only narrow the offsets slice
            data: self.data,
            offsets: &self.offsets[start..=end],
        })
    }

    /// Returns the raw parts of the view for Apache Arrow compatibility.
    pub fn as_raw_parts(&self) -> RawParts<Offset> {
        // Expose an Arrow-compatible view: data_ptr remains at the tape base,
        // offsets are absolute into that buffer, and data_len reaches the last used byte.
        RawParts {
            data_ptr: self.data.as_ptr(),
            offsets_ptr: self.offsets.as_ptr(),
            data_len: self.offsets[self.offsets.len() - 1].to_usize(),
            items_count: self.len(),
        }
    }
}

impl<'a, Offset: OffsetType> Index<usize> for RawTapeView<'a, Offset> {
    type Output = [u8];

    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of bounds")
    }
}

// Index trait implementations for RawTapeView to support [i..n] syntax
impl<'a, Offset: OffsetType> Index<Range<usize>> for RawTapeView<'a, Offset> {
    type Output = [u8];

    fn index(&self, range: Range<usize>) -> &Self::Output {
        let view = self
            .subview(range.start, range.end)
            .expect("range out of bounds");
        let start = view.offsets[0].to_usize();
        let end = view.offsets[view.offsets.len() - 1].to_usize();
        &view.data[start..end]
    }
}

impl<'a, Offset: OffsetType> Index<RangeFrom<usize>> for RawTapeView<'a, Offset> {
    type Output = [u8];

    fn index(&self, range: RangeFrom<usize>) -> &Self::Output {
        let view = self
            .subview(range.start, self.len())
            .expect("range out of bounds");
        let start = view.offsets[0].to_usize();
        let end = view.offsets[view.offsets.len() - 1].to_usize();
        &view.data[start..end]
    }
}

impl<'a, Offset: OffsetType> Index<RangeTo<usize>> for RawTapeView<'a, Offset> {
    type Output = [u8];

    fn index(&self, range: RangeTo<usize>) -> &Self::Output {
        let view = self.subview(0, range.end).expect("range out of bounds");
        let start = view.offsets[0].to_usize();
        let end = view.offsets[view.offsets.len() - 1].to_usize();
        &view.data[start..end]
    }
}

impl<'a, Offset: OffsetType> Index<RangeFull> for RawTapeView<'a, Offset> {
    type Output = [u8];

    fn index(&self, _range: RangeFull) -> &Self::Output {
        let start = self.offsets[0].to_usize();
        let end = self.offsets[self.offsets.len() - 1].to_usize();
        &self.data[start..end]
    }
}

impl<'a, Offset: OffsetType> Index<RangeInclusive<usize>> for RawTapeView<'a, Offset> {
    type Output = [u8];

    fn index(&self, range: RangeInclusive<usize>) -> &Self::Output {
        let view = self
            .subview(*range.start(), range.end() + 1)
            .expect("range out of bounds");
        let start = view.offsets[0].to_usize();
        let end = view.offsets[view.offsets.len() - 1].to_usize();
        &view.data[start..end]
    }
}

impl<'a, Offset: OffsetType> Index<RangeToInclusive<usize>> for RawTapeView<'a, Offset> {
    type Output = [u8];

    fn index(&self, range: RangeToInclusive<usize>) -> &Self::Output {
        let view = self.subview(0, range.end + 1).expect("range out of bounds");
        let start = view.offsets[0].to_usize();
        let end = view.offsets[view.offsets.len() - 1].to_usize();
        &view.data[start..end]
    }
}

// ========================
// CharsTapeView implementation
// ========================

impl<'a, Offset: OffsetType> CharsTapeView<'a, Offset> {
    /// Creates a zero-copy CharsTapeView from raw Arrow StringArray parts.
    ///
    /// # Safety
    ///
    /// The caller must ensure that:
    /// - `data` contains valid UTF-8 bytes for the lifetime `'a`
    /// - `offsets` contains valid offsets with appropriate length
    /// - All offsets are within bounds of the data slice
    pub unsafe fn from_raw_parts(data: &'a [u8], offsets: &'a [Offset]) -> Self {
        Self {
            inner: RawTapeView::from_raw_parts(data, offsets),
        }
    }

    /// Returns a reference to the string at the given index, or `None` if out of bounds.
    pub fn get(&self, index: usize) -> Option<&str> {
        // Safe because CharsTapeView only comes from CharsTape which validates UTF-8
        self.inner
            .get(index)
            .map(|b| unsafe { core::str::from_utf8_unchecked(b) })
    }

    /// Returns the number of strings in this view.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns `true` if the view contains no strings.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Returns the total number of bytes in this view.
    pub fn data_len(&self) -> usize {
        self.inner.data_len()
    }

    /// Creates a sub-view of this view
    pub fn subview(
        &self,
        start: usize,
        end: usize,
    ) -> Result<CharsTapeView<'a, Offset>, StringTapeError> {
        Ok(CharsTapeView {
            inner: self.inner.subview(start, end)?,
        })
    }

    /// Returns the raw parts of the view for Apache Arrow compatibility.
    pub fn as_raw_parts(&self) -> RawParts<Offset> {
        self.inner.as_raw_parts()
    }

    /// Returns an iterator over the strings in this view.
    pub fn iter(&'a self) -> CharsTapeViewIter<'a, Offset> {
        CharsTapeViewIter {
            view: self,
            index: 0,
        }
    }
}

/// Iterator over CharsTapeView strings.
pub struct CharsTapeViewIter<'a, Offset: OffsetType> {
    view: &'a CharsTapeView<'a, Offset>,
    index: usize,
}

impl<'a, Offset: OffsetType> Iterator for CharsTapeViewIter<'a, Offset> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        let result = self.view.get(self.index);
        if result.is_some() {
            self.index += 1;
        }
        result
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.view.len() - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a, Offset: OffsetType> ExactSizeIterator for CharsTapeViewIter<'a, Offset> {}

impl<'a, Offset: OffsetType> Index<usize> for CharsTapeView<'a, Offset> {
    type Output = str;

    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of bounds")
    }
}

impl<'a, Offset: OffsetType> IntoIterator for &'a CharsTapeView<'a, Offset> {
    type Item = &'a str;
    type IntoIter = CharsTapeViewIter<'a, Offset>;

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

// ========================
// BytesTapeView implementation
// ========================

impl<'a, Offset: OffsetType> BytesTapeView<'a, Offset> {
    /// Creates a zero-copy BytesTapeView from raw Arrow BinaryArray parts.
    ///
    /// # Safety
    ///
    /// The caller must ensure that:
    /// - `data` contains valid bytes for the lifetime `'a`
    /// - `offsets` contains valid offsets with appropriate length
    /// - All offsets are within bounds of the data slice
    pub unsafe fn from_raw_parts(data: &'a [u8], offsets: &'a [Offset]) -> Self {
        Self {
            inner: RawTapeView::from_raw_parts(data, offsets),
        }
    }

    /// Returns a reference to the bytes at the given index, or `None` if out of bounds.
    pub fn get(&self, index: usize) -> Option<&[u8]> {
        self.inner.get(index)
    }

    /// Returns the number of items in this view.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns `true` if the view contains no items.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Returns the total number of bytes in this view.
    pub fn data_len(&self) -> usize {
        self.inner.data_len()
    }

    /// Creates a sub-view of this view
    pub fn subview(
        &self,
        start: usize,
        end: usize,
    ) -> Result<BytesTapeView<'a, Offset>, StringTapeError> {
        Ok(BytesTapeView {
            inner: self.inner.subview(start, end)?,
        })
    }

    /// Returns the raw parts of the view for Apache Arrow compatibility.
    pub fn as_raw_parts(&self) -> RawParts<Offset> {
        self.inner.as_raw_parts()
    }

    /// Returns an iterator over the byte slices in this view.
    pub fn iter(&'a self) -> BytesTapeViewIter<'a, Offset> {
        BytesTapeViewIter {
            view: self,
            index: 0,
        }
    }
}

/// Iterator over BytesTapeView byte slices.
pub struct BytesTapeViewIter<'a, Offset: OffsetType> {
    view: &'a BytesTapeView<'a, Offset>,
    index: usize,
}

impl<'a, Offset: OffsetType> Iterator for BytesTapeViewIter<'a, Offset> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        let result = self.view.get(self.index);
        if result.is_some() {
            self.index += 1;
        }
        result
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.view.len() - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a, Offset: OffsetType> ExactSizeIterator for BytesTapeViewIter<'a, Offset> {}

impl<'a, Offset: OffsetType> Index<usize> for BytesTapeView<'a, Offset> {
    type Output = [u8];

    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of bounds")
    }
}

impl<'a, Offset: OffsetType> IntoIterator for &'a BytesTapeView<'a, Offset> {
    type Item = &'a [u8];
    type IntoIter = BytesTapeViewIter<'a, Offset>;

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

// ========================
// CharsTape (UTF-8 view)
// ========================

impl<Offset: OffsetType, A: Allocator> CharsTape<Offset, A> {
    /// Creates a new, empty CharsTape with the global allocator.
    pub fn new() -> CharsTape<Offset, Global> {
        CharsTape {
            inner: RawTape::<Offset, Global>::new(),
        }
    }

    /// Creates a new, empty CharsTape with a custom allocator.
    pub fn new_in(allocator: A) -> Self {
        Self {
            inner: RawTape::<Offset, A>::new_in(allocator),
        }
    }

    /// Creates a new CharsTape with pre-allocated capacity using the global allocator.
    pub fn with_capacity(
        data_capacity: usize,
        strings_capacity: usize,
    ) -> Result<CharsTape<Offset, Global>, StringTapeError> {
        Ok(CharsTape {
            inner: RawTape::<Offset, Global>::with_capacity(data_capacity, strings_capacity)?,
        })
    }

    /// Creates a new CharsTape with pre-allocated capacity and a custom allocator.
    pub fn with_capacity_in(
        data_capacity: usize,
        strings_capacity: usize,
        allocator: A,
    ) -> Result<Self, StringTapeError> {
        Ok(Self {
            inner: RawTape::<Offset, A>::with_capacity_in(
                data_capacity,
                strings_capacity,
                allocator,
            )?,
        })
    }

    /// Adds a string to the end of the CharsTape.
    pub fn push(&mut self, s: &str) -> Result<(), StringTapeError> {
        self.inner.push(s.as_bytes())
    }

    /// Returns a reference to the string at the given index, or `None` if out of bounds.
    pub fn get(&self, index: usize) -> Option<&str> {
        // Safe because CharsTape only accepts &str pushes.
        self.inner
            .get(index)
            .map(|b| unsafe { core::str::from_utf8_unchecked(b) })
    }

    /// Returns the number of strings in the CharsTape.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns `true` if the CharsTape contains no strings.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Returns the total number of bytes used by string data.
    pub fn data_len(&self) -> usize {
        self.inner.data_len()
    }

    /// Returns the number of strings currently stored (same as `len()`).
    pub fn capacity(&self) -> usize {
        self.inner.len()
    }

    /// Returns the number of bytes allocated for string data.
    pub fn data_capacity(&self) -> usize {
        self.inner.data_capacity()
    }

    /// Returns the number of offset slots allocated.
    pub fn offsets_capacity(&self) -> usize {
        self.inner.offsets_capacity()
    }

    /// Removes all strings from the CharsTape, keeping allocated capacity.
    pub fn clear(&mut self) {
        self.inner.clear()
    }

    /// Shortens the CharsTape, keeping the first `len` strings and dropping the rest.
    pub fn truncate(&mut self, len: usize) {
        self.inner.truncate(len)
    }

    /// Extends the CharsTape with the contents of an iterator.
    pub fn extend<I>(&mut self, iter: I) -> Result<(), StringTapeError>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        for s in iter {
            self.push(s.as_ref())?;
        }
        Ok(())
    }

    /// Returns the raw parts of the CharsTape for Apache Arrow compatibility.
    pub fn as_raw_parts(&self) -> RawParts<Offset> {
        self.inner.as_raw_parts()
    }

    /// Returns a slice view of the data buffer.
    pub fn data_slice(&self) -> &[u8] {
        self.inner.data_slice()
    }

    /// Returns a slice view of the offsets buffer.
    pub fn offsets_slice(&self) -> &[Offset] {
        self.inner.offsets_slice()
    }

    pub fn iter(&self) -> CharsTapeIter<'_, Offset, A> {
        CharsTapeIter {
            tape: self,
            index: 0,
        }
    }

    /// Returns a reference to the allocator used by this CharsTape.
    pub fn allocator(&self) -> &A {
        self.inner.allocator()
    }

    /// Creates a view of the entire CharsTape.
    pub fn view(&self) -> CharsTapeView<'_, Offset> {
        CharsTapeView {
            inner: self.inner.view(),
        }
    }

    /// Creates a subview of a continuous slice of this CharsTape.
    pub fn subview(
        &self,
        start: usize,
        end: usize,
    ) -> Result<CharsTapeView<'_, Offset>, StringTapeError> {
        Ok(CharsTapeView {
            inner: self.inner.subview(start, end)?,
        })
    }

    /// Creates a CharsCows view of the tape.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use stringtape::{CharsTapeI32, CharsCows, StringTapeError};
    /// # use std::borrow::Cow;
    /// let mut tape = CharsTapeI32::new();
    /// tape.extend(["apple", "banana", "cherry"])?;
    ///
    /// let cows: CharsCows<i32, u16> = tape.as_reorderable()?;
    /// assert_eq!(cows.get(0), Some("apple"));
    /// # Ok::<(), StringTapeError>(())
    /// ```
    pub fn as_reorderable<Length: LengthType>(
        &self,
    ) -> Result<CharsCows<'_, Offset, Length>, StringTapeError> {
        CharsCows::from_iter_and_data(self, Cow::Borrowed(self.data_slice()))
    }

    /// Returns data and offsets slices for zero-copy Arrow conversion.
    pub fn arrow_slices(&self) -> (&[u8], &[Offset]) {
        (self.data_slice(), self.offsets_slice())
    }
}

impl<Offset: OffsetType, A: Allocator> Drop for CharsTape<Offset, A> {
    fn drop(&mut self) {
        // Explicit drop of inner to run RawTape's Drop
        // (redundant but keeps intent clear)
    }
}

unsafe impl<Offset: OffsetType + Send, A: Allocator + Send> Send for CharsTape<Offset, A> {}
unsafe impl<Offset: OffsetType + Sync, A: Allocator + Sync> Sync for CharsTape<Offset, A> {}

pub struct CharsTapeIter<'a, Offset: OffsetType, A: Allocator> {
    tape: &'a CharsTape<Offset, A>,
    index: usize,
}

impl<'a, Offset: OffsetType, A: Allocator> Iterator for CharsTapeIter<'a, Offset, A> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        let result = self.tape.get(self.index);
        if result.is_some() {
            self.index += 1;
        }
        result
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.tape.len() - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a, Offset: OffsetType, A: Allocator> ExactSizeIterator for CharsTapeIter<'a, Offset, A> {}

impl<Offset: OffsetType> FromIterator<String> for CharsTape<Offset, Global> {
    fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self {
        let mut tape = CharsTape::<Offset, Global>::new();
        for s in iter {
            tape.push(&s)
                .expect("Failed to build CharsTape from iterator");
        }
        tape
    }
}

impl<'a, Offset: OffsetType> FromIterator<&'a str> for CharsTape<Offset, Global> {
    fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> Self {
        let mut tape = CharsTape::<Offset, Global>::new();
        for s in iter {
            tape.push(s)
                .expect("Failed to build CharsTape from iterator");
        }
        tape
    }
}

impl<Offset: OffsetType, A: Allocator> Index<usize> for CharsTape<Offset, A> {
    type Output = str;

    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of bounds")
    }
}

impl<'a, Offset: OffsetType, A: Allocator> IntoIterator for &'a CharsTape<Offset, A> {
    type Item = &'a str;
    type IntoIter = CharsTapeIter<'a, Offset, A>;

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

// ======================
// BytesTape (bytes view)
// ======================

impl<Offset: OffsetType, A: Allocator> BytesTape<Offset, A> {
    /// Creates a new, empty BytesTape with the global allocator.
    pub fn new() -> BytesTape<Offset, Global> {
        BytesTape {
            inner: RawTape::<Offset, Global>::new(),
        }
    }

    /// Creates a new, empty BytesTape with a custom allocator.
    pub fn new_in(allocator: A) -> Self {
        Self {
            inner: RawTape::<Offset, A>::new_in(allocator),
        }
    }

    /// Creates a new BytesTape with pre-allocated capacity using the global allocator.
    pub fn with_capacity(
        data_capacity: usize,
        items_capacity: usize,
    ) -> Result<BytesTape<Offset, Global>, StringTapeError> {
        Ok(BytesTape {
            inner: RawTape::<Offset, Global>::with_capacity(data_capacity, items_capacity)?,
        })
    }

    /// Creates a new BytesTape with pre-allocated capacity and a custom allocator.
    pub fn with_capacity_in(
        data_capacity: usize,
        items_capacity: usize,
        allocator: A,
    ) -> Result<Self, StringTapeError> {
        Ok(Self {
            inner: RawTape::<Offset, A>::with_capacity_in(
                data_capacity,
                items_capacity,
                allocator,
            )?,
        })
    }

    /// Adds bytes to the end of the tape.
    pub fn push(&mut self, bytes: &[u8]) -> Result<(), StringTapeError> {
        self.inner.push(bytes)
    }

    /// Returns a reference to the bytes at the given index, or `None` if out of bounds.
    pub fn get(&self, index: usize) -> Option<&[u8]> {
        self.inner.get(index)
    }

    /// Returns the number of items in the tape.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns `true` if the tape contains no items.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Returns the total number of bytes used by data.
    pub fn data_len(&self) -> usize {
        self.inner.data_len()
    }

    /// Returns the number of bytes allocated for data.
    pub fn data_capacity(&self) -> usize {
        self.inner.data_capacity()
    }

    /// Returns the number of offset slots allocated.
    pub fn offsets_capacity(&self) -> usize {
        self.inner.offsets_capacity()
    }

    /// Removes all items from the tape, keeping allocated capacity.
    pub fn clear(&mut self) {
        self.inner.clear()
    }

    /// Shortens the tape, keeping the first `len` items and dropping the rest.
    pub fn truncate(&mut self, len: usize) {
        self.inner.truncate(len)
    }

    /// Extends the tape with the contents of an iterator of bytes.
    pub fn extend<I>(&mut self, iter: I) -> Result<(), StringTapeError>
    where
        I: IntoIterator,
        I::Item: AsRef<[u8]>,
    {
        self.inner.extend(iter)
    }

    /// Returns the raw parts of the tape for Apache Arrow compatibility.
    pub fn as_raw_parts(&self) -> RawParts<Offset> {
        self.inner.as_raw_parts()
    }

    /// Returns a slice view of the data buffer.
    pub fn data_slice(&self) -> &[u8] {
        self.inner.data_slice()
    }

    /// Returns a slice view of the offsets buffer.
    pub fn offsets_slice(&self) -> &[Offset] {
        self.inner.offsets_slice()
    }

    /// Returns a reference to the allocator used by this BytesTape.
    pub fn allocator(&self) -> &A {
        self.inner.allocator()
    }

    /// Creates a view of the entire BytesTape.
    pub fn view(&self) -> BytesTapeView<'_, Offset> {
        BytesTapeView {
            inner: self.inner.view(),
        }
    }

    /// Returns an iterator over the byte cows.
    pub fn iter(&self) -> BytesTapeIter<'_, Offset, A> {
        BytesTapeIter {
            tape: self,
            index: 0,
        }
    }

    /// Creates a subview of a continuous slice of this BytesTape.
    pub fn subview(
        &self,
        start: usize,
        end: usize,
    ) -> Result<BytesTapeView<'_, Offset>, StringTapeError> {
        Ok(BytesTapeView {
            inner: self.inner.subview(start, end)?,
        })
    }

    /// Creates a BytesCows view of the tape.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use stringtape::{BytesTapeI32, BytesCows, StringTapeError};
    /// # use std::borrow::Cow;
    /// let mut tape = BytesTapeI32::new();
    /// tape.push(&[1, 2, 3])?;
    /// tape.push(&[4, 5, 6])?;
    /// tape.push(&[7, 8, 9])?;
    ///
    /// let cows: BytesCows<i32, u16> = tape.as_reorderable()?;
    /// assert_eq!(cows.get(0), Some(&[1, 2, 3][..]));
    /// # Ok::<(), StringTapeError>(())
    /// ```
    pub fn as_reorderable<Length: LengthType>(
        &self,
    ) -> Result<BytesCows<'_, Offset, Length>, StringTapeError> {
        BytesCows::from_iter_and_data(self, Cow::Borrowed(self.data_slice()))
    }

    /// Returns data and offsets slices for zero-copy Arrow conversion.
    pub fn arrow_slices(&self) -> (&[u8], &[Offset]) {
        (self.data_slice(), self.offsets_slice())
    }
}

impl<Offset: OffsetType, A: Allocator> Index<usize> for BytesTape<Offset, A> {
    type Output = [u8];

    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of bounds")
    }
}

pub struct BytesTapeIter<'a, Offset: OffsetType, A: Allocator> {
    tape: &'a BytesTape<Offset, A>,
    index: usize,
}

impl<'a, Offset: OffsetType, A: Allocator> Iterator for BytesTapeIter<'a, Offset, A> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        let result = self.tape.get(self.index);
        if result.is_some() {
            self.index += 1;
        }
        result
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.tape.len() - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a, Offset: OffsetType, A: Allocator> ExactSizeIterator for BytesTapeIter<'a, Offset, A> {}

impl<'a, Offset: OffsetType, A: Allocator> IntoIterator for &'a BytesTape<Offset, A> {
    type Item = &'a [u8];
    type IntoIter = BytesTapeIter<'a, Offset, A>;

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

// Signed (Arrow-compatible) aliases
pub type CharsTapeI32 = CharsTape<i32, Global>;
pub type CharsTapeI64 = CharsTape<i64, Global>;
pub type BytesTapeI32 = BytesTape<i32, Global>;
pub type BytesTapeI64 = BytesTape<i64, Global>;

pub type CharsTapeViewI32<'a> = CharsTapeView<'a, i32>;
pub type CharsTapeViewI64<'a> = CharsTapeView<'a, i64>;
pub type BytesTapeViewI32<'a> = BytesTapeView<'a, i32>;
pub type BytesTapeViewI64<'a> = BytesTapeView<'a, i64>;

// Unsigned aliases (not zero-copy with Arrow)
pub type CharsTapeU32 = CharsTape<u32, Global>;
pub type CharsTapeU64 = CharsTape<u64, Global>;
pub type BytesTapeU16 = BytesTape<u16, Global>;
pub type BytesTapeU32 = BytesTape<u32, Global>;
pub type BytesTapeU64 = BytesTape<u64, Global>;

pub type CharsTapeViewU32<'a> = CharsTapeView<'a, u32>;
pub type CharsTapeViewU64<'a> = CharsTapeView<'a, u64>;
pub type BytesTapeViewU16<'a> = BytesTapeView<'a, u16>;
pub type BytesTapeViewU32<'a> = BytesTapeView<'a, u32>;
pub type BytesTapeViewU64<'a> = BytesTapeView<'a, u64>;

// Conversion implementations between BytesTape and CharsTape
impl<Offset: OffsetType, A: Allocator> TryFrom<BytesTape<Offset, A>> for CharsTape<Offset, A> {
    type Error = StringTapeError;

    fn try_from(bytes_tape: BytesTape<Offset, A>) -> Result<Self, Self::Error> {
        // Validate that all byte sequences are valid UTF-8
        for i in 0..bytes_tape.len() {
            if let Err(e) = core::str::from_utf8(&bytes_tape[i]) {
                return Err(StringTapeError::Utf8Error(e));
            }
        }

        // Since validation passed, we can safely convert
        // We need to take ownership of the inner RawTape without dropping BytesTape
        let inner = unsafe {
            // Take ownership of the inner RawTape
            let inner = core::ptr::read(&bytes_tape.inner);
            // Prevent BytesTape's destructor from running
            core::mem::forget(bytes_tape);
            inner
        };
        Ok(CharsTape { inner })
    }
}

impl<Offset: OffsetType, A: Allocator> From<CharsTape<Offset, A>> for BytesTape<Offset, A> {
    fn from(chars_tape: CharsTape<Offset, A>) -> Self {
        // CharsTape already contains valid UTF-8, so conversion to BytesTape is infallible
        // We need to take ownership of the inner RawTape without dropping CharsTape
        let inner = unsafe {
            // Take ownership of the inner RawTape
            let inner = core::ptr::read(&chars_tape.inner);
            // Prevent CharsTape's destructor from running
            core::mem::forget(chars_tape);
            inner
        };
        BytesTape { inner }
    }
}

impl<Offset: OffsetType, A: Allocator> BytesTape<Offset, A> {
    pub fn try_into_chars_tape(self) -> Result<CharsTape<Offset, A>, StringTapeError> {
        self.try_into()
    }
}

impl<Offset: OffsetType, A: Allocator> CharsTape<Offset, A> {
    pub fn into_bytes_tape(self) -> BytesTape<Offset, A> {
        self.into()
    }
}

// Conversion implementations between BytesTapeView and CharsTapeView
impl<'a, Offset: OffsetType> TryFrom<BytesTapeView<'a, Offset>> for CharsTapeView<'a, Offset> {
    type Error = StringTapeError;

    fn try_from(bytes_view: BytesTapeView<'a, Offset>) -> Result<Self, Self::Error> {
        // Validate that all byte sequences are valid UTF-8
        for i in 0..bytes_view.len() {
            let bytes = bytes_view.get(i).ok_or(StringTapeError::IndexOutOfBounds)?;
            if core::str::from_utf8(bytes).is_err() {
                return Err(StringTapeError::Utf8Error(
                    core::str::from_utf8(bytes).unwrap_err(),
                ));
            }
        }

        // Since validation passed, construct a CharsTapeView over the same inner view
        Ok(CharsTapeView {
            inner: bytes_view.inner,
        })
    }
}

impl<'a, Offset: OffsetType> From<CharsTapeView<'a, Offset>> for BytesTapeView<'a, Offset> {
    fn from(chars_view: CharsTapeView<'a, Offset>) -> Self {
        // UTF-8 bytes can always be viewed as bytes
        BytesTapeView {
            inner: chars_view.inner,
        }
    }
}

impl<'a, Offset: OffsetType> BytesTapeView<'a, Offset> {
    pub fn try_into_chars_view(self) -> Result<CharsTapeView<'a, Offset>, StringTapeError> {
        self.try_into()
    }
}

impl<'a, Offset: OffsetType> CharsTapeView<'a, Offset> {
    pub fn into_bytes_view(self) -> BytesTapeView<'a, Offset> {
        self.into()
    }
}

impl<Offset: OffsetType> Default for CharsTape<Offset, Global> {
    fn default() -> Self {
        Self::new()
    }
}

// ========================
// CharsCows - Compact slice collection with configurable offset/length types
// ========================

/// Packed entry struct to eliminate padding overhead between offset and length.
///
/// For example, `(u64, u8)` tuple uses 16 bytes (8 + 8 padding), but
/// `PackedEntry<u64, u8>` uses only 9 bytes (8 + 1).
#[repr(C, packed(1))]
#[derive(Copy, Clone, Debug)]
struct PackedEntry<Offset, Length> {
    offset: Offset,
    length: Length,
}

/// A memory-efficient collection of string slices with configurable offset and length types.
///
/// `CharsCows` stores references to string slices in a shared data buffer using compact
/// (offset, length) pairs. This is ideal for large datasets where you want to reference
/// substrings without duplicating the underlying data.
///
/// # Type Parameters
///
/// * `Offset` - The offset type (u8, u16, u32, u64) determining maximum data size
/// * `Length` - The length type (u8, u16, u32, u64) determining maximum slice size
///
/// # Memory Efficiency
///
/// For 500M words (8 bytes avg) from a 4GB file:
/// - `Vec<String>`: ~66 GB (24 bytes per String + heap overhead)
/// - `CharsCows<u32, u16>`: ~7 GB (4+2 bytes per entry + shared 4GB data)
///
/// # Examples
///
/// ```rust
/// use stringtape::{CharsCows, StringTapeError};
/// use std::borrow::Cow;
///
/// let data = "hello world foo bar";
/// let cows = CharsCows::<u32, u16>::from_iter_and_data(
///     data.split_whitespace(),
///     Cow::Borrowed(data.as_bytes())
/// )?;
///
/// assert_eq!(cows.len(), 4);
/// assert_eq!(cows.get(0), Some("hello"));
/// assert_eq!(cows.get(3), Some("bar"));
/// # Ok::<(), StringTapeError>(())
/// ```
#[derive(Debug, Clone)]
pub struct CharsCows<'a, Offset: OffsetType = u32, Length: LengthType = u16> {
    data: Cow<'a, [u8]>,
    entries: Vec<PackedEntry<Offset, Length>>,
}

/// A memory-efficient collection of byte slices with configurable offset and length types.
///
/// Similar to `CharsCows` but for arbitrary binary data without UTF-8 validation.
#[derive(Debug, Clone)]
pub struct BytesCows<'a, Offset: OffsetType = u32, Length: LengthType = u16> {
    data: Cow<'a, [u8]>,
    entries: Vec<PackedEntry<Offset, Length>>,
}

impl<'a, Offset: OffsetType, Length: LengthType> CharsCows<'a, Offset, Length> {
    /// Creates a CharsCows from an iterator of string slices and shared data buffer.
    ///
    /// The slices must be subslices of the data buffer. Offsets and lengths are inferred
    /// from the slice pointers.
    ///
    /// # Arguments
    ///
    /// * `iter` - Iterator yielding string slices that are subslices of `data`
    /// * `data` - Cow-wrapped data buffer (borrowed or owned)
    ///
    /// # Errors
    ///
    /// - `OffsetOverflow` if offset/length exceeds type maximum
    /// - `IndexOutOfBounds` if slice not within data buffer
    ///
    /// # Example
    ///
    /// ```rust
    /// # use stringtape::{CharsCowsU32U8, StringTapeError};
    /// # use std::borrow::Cow;
    /// let data = "hello world";
    /// let cows = CharsCowsU32U8::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// )?;
    /// # Ok::<(), StringTapeError>(())
    /// ```
    pub fn from_iter_and_data<I>(iter: I, data: Cow<'a, [u8]>) -> Result<Self, StringTapeError>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        let data_ptr = data.as_ptr() as usize;
        let data_end = data_ptr + data.len();
        let mut entries = Vec::new();

        for s in iter {
            let s_ref = s.as_ref();
            let s_bytes = s_ref.as_bytes();
            let s_ptr = s_bytes.as_ptr() as usize;

            // Calculate offset from base pointer
            if s_ptr < data_ptr || s_ptr > data_end {
                return Err(StringTapeError::IndexOutOfBounds);
            }

            let offset = s_ptr - data_ptr;
            let length = s_bytes.len();

            if offset + length > data.len() {
                return Err(StringTapeError::IndexOutOfBounds);
            }

            let offset_typed = Offset::from_usize(offset).ok_or(StringTapeError::OffsetOverflow)?;
            let length_typed = Length::from_usize(length).ok_or(StringTapeError::OffsetOverflow)?;

            entries.push(PackedEntry {
                offset: offset_typed,
                length: length_typed,
            });
        }

        Ok(Self { data, entries })
    }

    /// Returns a reference to the string at the given index, or `None` if out of bounds.
    pub fn get(&self, index: usize) -> Option<&'_ str> {
        self.entries.get(index).map(|entry| {
            // Must copy fields from packed struct (can't take references)
            let start = entry.offset.to_usize();
            let len = entry.length.to_usize();
            // Safety: UTF-8 validated during construction
            // The lifetime of the returned &str is tied to self.data, not self
            unsafe { core::str::from_utf8_unchecked(&self.data[start..start + len]) }
        })
    }

    /// Returns the number of slices in the collection.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` if the collection contains no cows.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Returns an iterator over the string cows.
    pub fn iter(&self) -> CharsCowsIter<'_, Offset, Length> {
        CharsCowsIter {
            slices: self,
            index: 0,
        }
    }

    /// Returns a reference to the underlying data buffer.
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Returns a reference to the parent string that all slices reference.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsU32U8;
    /// use std::borrow::Cow;
    ///
    /// let data = "hello world";
    /// let cows = CharsCowsU32U8::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// assert_eq!(cows.parent(), "hello world");
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn parent(&self) -> &str {
        // Safety: CharsCows is constructed with valid UTF-8 data
        unsafe { core::str::from_utf8_unchecked(&self.data) }
    }

    /// Sorts the slices in-place using the default string comparison.
    ///
    /// This is a stable sort that preserves the order of equal elements.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsU32U8;
    /// use std::borrow::Cow;
    ///
    /// let data = "zebra apple banana";
    /// let mut cows = CharsCowsU32U8::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// cows.sort();
    /// let sorted: Vec<&str> = cows.iter().collect();
    /// assert_eq!(sorted, vec!["apple", "banana", "zebra"]);
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn sort(&mut self)
    where
        Offset: OffsetType,
        Length: LengthType,
    {
        self.entries.sort_by(|a, b| {
            let str_a = {
                let start = a.offset.to_usize();
                let len = a.length.to_usize();
                unsafe { core::str::from_utf8_unchecked(&self.data[start..start + len]) }
            };
            let str_b = {
                let start = b.offset.to_usize();
                let len = b.length.to_usize();
                unsafe { core::str::from_utf8_unchecked(&self.data[start..start + len]) }
            };
            str_a.cmp(str_b)
        });
    }

    /// Sorts the slices in-place using an unstable sorting algorithm.
    ///
    /// This is faster than stable sort but may not preserve the order of equal elements.
    pub fn sort_unstable(&mut self)
    where
        Offset: OffsetType,
        Length: LengthType,
    {
        self.entries.sort_unstable_by(|a, b| {
            let str_a = {
                let start = a.offset.to_usize();
                let len = a.length.to_usize();
                unsafe { core::str::from_utf8_unchecked(&self.data[start..start + len]) }
            };
            let str_b = {
                let start = b.offset.to_usize();
                let len = b.length.to_usize();
                unsafe { core::str::from_utf8_unchecked(&self.data[start..start + len]) }
            };
            str_a.cmp(str_b)
        });
    }

    /// Sorts the slices in-place using a custom comparison function.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsU32U8;
    /// use std::borrow::Cow;
    ///
    /// let data = "aaa bb c";
    /// let mut cows = CharsCowsU32U8::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// // Sort by length, then alphabetically
    /// cows.sort_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(b)));
    /// let sorted: Vec<&str> = cows.iter().collect();
    /// assert_eq!(sorted, vec!["c", "bb", "aaa"]);
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn sort_by<F>(&mut self, mut compare: F)
    where
        F: FnMut(&str, &str) -> core::cmp::Ordering,
        Offset: OffsetType,
        Length: LengthType,
    {
        self.entries.sort_by(|a, b| {
            let str_a = {
                let start = a.offset.to_usize();
                let len = a.length.to_usize();
                unsafe { core::str::from_utf8_unchecked(&self.data[start..start + len]) }
            };
            let str_b = {
                let start = b.offset.to_usize();
                let len = b.length.to_usize();
                unsafe { core::str::from_utf8_unchecked(&self.data[start..start + len]) }
            };
            compare(str_a, str_b)
        });
    }

    /// Sorts the slices in-place using a key extraction function.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsU32U8;
    /// use std::borrow::Cow;
    ///
    /// let data = "aaa bb c";
    /// let mut cows = CharsCowsU32U8::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// // Sort by string length
    /// cows.sort_by_key(|s| s.len());
    /// let sorted: Vec<&str> = cows.iter().collect();
    /// assert_eq!(sorted, vec!["c", "bb", "aaa"]);
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn sort_by_key<K, F>(&mut self, mut f: F)
    where
        F: FnMut(&str) -> K,
        K: Ord,
        Offset: OffsetType,
        Length: LengthType,
    {
        self.entries.sort_by_key(|entry| {
            let start = entry.offset.to_usize();
            let len = entry.length.to_usize();
            let s = unsafe { core::str::from_utf8_unchecked(&self.data[start..start + len]) };
            f(s)
        });
    }
}

impl<'a, Offset: OffsetType, Length: LengthType> BytesCows<'a, Offset, Length> {
    /// Creates BytesCows from iterator of byte slices and shared data buffer.
    ///
    /// Slices must be subslices of the data buffer. Offsets and lengths are inferred
    /// from slice pointers.
    pub fn from_iter_and_data<I>(iter: I, data: Cow<'a, [u8]>) -> Result<Self, StringTapeError>
    where
        I: IntoIterator,
        I::Item: AsRef<[u8]>,
    {
        let data_ptr = data.as_ptr() as usize;
        let data_end = data_ptr + data.len();
        let mut entries = Vec::new();

        for b in iter {
            let b_ref = b.as_ref();
            let b_ptr = b_ref.as_ptr() as usize;

            if b_ptr < data_ptr || b_ptr > data_end {
                return Err(StringTapeError::IndexOutOfBounds);
            }

            let offset = b_ptr - data_ptr;
            let length = b_ref.len();

            if offset + length > data.len() {
                return Err(StringTapeError::IndexOutOfBounds);
            }

            let offset_typed = Offset::from_usize(offset).ok_or(StringTapeError::OffsetOverflow)?;
            let length_typed = Length::from_usize(length).ok_or(StringTapeError::OffsetOverflow)?;

            entries.push(PackedEntry {
                offset: offset_typed,
                length: length_typed,
            });
        }

        Ok(Self { data, entries })
    }

    /// Creates BytesCows from iterator of (offset, length) pairs and data buffer.
    pub fn from_offsets_and_data<I>(iter: I, data: Cow<'a, [u8]>) -> Result<Self, StringTapeError>
    where
        I: IntoIterator<Item = (usize, usize)>,
    {
        let mut entries = Vec::new();

        for (offset, length) in iter {
            let offset_typed = Offset::from_usize(offset).ok_or(StringTapeError::OffsetOverflow)?;
            let length_typed = Length::from_usize(length).ok_or(StringTapeError::OffsetOverflow)?;

            let end = offset
                .checked_add(length)
                .ok_or(StringTapeError::OffsetOverflow)?;
            if end > data.len() {
                return Err(StringTapeError::IndexOutOfBounds);
            }

            entries.push(PackedEntry {
                offset: offset_typed,
                length: length_typed,
            });
        }

        Ok(Self { data, entries })
    }

    /// Returns a reference to the bytes at the given index, or `None` if out of bounds.
    pub fn get(&self, index: usize) -> Option<&[u8]> {
        self.entries.get(index).map(|entry| {
            let start = entry.offset.to_usize();
            let len = entry.length.to_usize();
            &self.data[start..start + len]
        })
    }

    /// Returns the number of slices in the collection.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` if the collection contains no cows.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Returns an iterator over the byte cows.
    pub fn iter(&self) -> BytesCowsIter<'_, Offset, Length> {
        BytesCowsIter {
            slices: self,
            index: 0,
        }
    }

    /// Returns a reference to the underlying data buffer.
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Returns a reference to the parent byte buffer that all slices reference.
    ///
    /// This is an alias for `data()` that provides a consistent API across all Cows types.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::BytesCowsU32U8;
    /// use std::borrow::Cow;
    ///
    /// let data = b"hello world";
    /// let bytes = BytesCowsU32U8::from_iter_and_data(
    ///     data.split(|&b| b == b' '),
    ///     Cow::Borrowed(&data[..])
    /// ).unwrap();
    ///
    /// assert_eq!(bytes.parent(), b"hello world");
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn parent(&self) -> &[u8] {
        &self.data
    }

    /// Returns a zero-copy view of this `BytesCows` as a `CharsCows` if all slices are valid UTF-8.
    ///
    /// This validates that all byte slices contain valid UTF-8, then reinterprets the collection
    /// as strings without copying or moving any data.
    ///
    /// # Errors
    ///
    /// Returns `StringTapeError::Utf8Error` if any slice contains invalid UTF-8.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::BytesCowsU32U8;
    /// use std::borrow::Cow;
    ///
    /// let data = b"hello world";
    /// let bytes = BytesCowsU32U8::from_iter_and_data(
    ///     data.split(|&b| b == b' '),
    ///     Cow::Borrowed(&data[..])
    /// ).unwrap();
    ///
    /// let chars = bytes.as_chars().unwrap();
    /// assert_eq!(chars.get(0), Some("hello"));
    /// assert_eq!(chars.get(1), Some("world"));
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn as_chars(&self) -> Result<CharsCows<'_, Offset, Length>, StringTapeError> {
        // Validate that all slices contain valid UTF-8
        for i in 0..self.len() {
            let slice = self.get(i).ok_or(StringTapeError::IndexOutOfBounds)?;
            core::str::from_utf8(slice).map_err(StringTapeError::Utf8Error)?;
        }

        // Safety: All slices validated as UTF-8
        Ok(CharsCows {
            data: Cow::Borrowed(self.data.as_ref()),
            entries: self.entries.clone(),
        })
    }
}

pub struct CharsCowsIter<'a, Offset: OffsetType, Length: LengthType> {
    slices: &'a CharsCows<'a, Offset, Length>,
    index: usize,
}

impl<'a, Offset: OffsetType, Length: LengthType> Iterator for CharsCowsIter<'a, Offset, Length> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        let result = self.slices.get(self.index);
        if result.is_some() {
            self.index += 1;
        }
        result
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.slices.len() - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a, Offset: OffsetType, Length: LengthType> ExactSizeIterator
    for CharsCowsIter<'a, Offset, Length>
{
}

pub struct BytesCowsIter<'a, Offset: OffsetType, Length: LengthType> {
    slices: &'a BytesCows<'a, Offset, Length>,
    index: usize,
}

impl<'a, Offset: OffsetType, Length: LengthType> Iterator for BytesCowsIter<'a, Offset, Length> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        let result = self.slices.get(self.index);
        if result.is_some() {
            self.index += 1;
        }
        result
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.slices.len() - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a, Offset: OffsetType, Length: LengthType> ExactSizeIterator
    for BytesCowsIter<'a, Offset, Length>
{
}

impl<'a, Offset: OffsetType, Length: LengthType> Index<usize> for CharsCows<'a, Offset, Length> {
    type Output = str;

    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of bounds")
    }
}

impl<'a, Offset: OffsetType, Length: LengthType> Index<usize> for BytesCows<'a, Offset, Length> {
    type Output = [u8];

    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of bounds")
    }
}

impl<'a, Offset: OffsetType, Length: LengthType> IntoIterator
    for &'a CharsCows<'a, Offset, Length>
{
    type Item = &'a str;
    type IntoIter = CharsCowsIter<'a, Offset, Length>;

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

impl<'a, Offset: OffsetType, Length: LengthType> IntoIterator
    for &'a BytesCows<'a, Offset, Length>
{
    type Item = &'a [u8];
    type IntoIter = BytesCowsIter<'a, Offset, Length>;

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

// Conversion implementations between BytesCows and CharsCows
impl<'a, Offset: OffsetType, Length: LengthType> TryFrom<BytesCows<'a, Offset, Length>>
    for CharsCows<'a, Offset, Length>
{
    type Error = StringTapeError;

    fn try_from(bytes_slices: BytesCows<'a, Offset, Length>) -> Result<Self, Self::Error> {
        // Validate that all slices contain valid UTF-8
        for i in 0..bytes_slices.len() {
            let slice = bytes_slices
                .get(i)
                .ok_or(StringTapeError::IndexOutOfBounds)?;
            core::str::from_utf8(slice).map_err(StringTapeError::Utf8Error)?;
        }

        // Safety: All slices validated as UTF-8
        Ok(CharsCows {
            data: bytes_slices.data,
            entries: bytes_slices.entries,
        })
    }
}

impl<'a, Offset: OffsetType, Length: LengthType> From<CharsCows<'a, Offset, Length>>
    for BytesCows<'a, Offset, Length>
{
    fn from(chars_slices: CharsCows<'a, Offset, Length>) -> Self {
        // CharsCows contains valid UTF-8, so conversion to BytesCows is infallible
        BytesCows {
            data: chars_slices.data,
            entries: chars_slices.entries,
        }
    }
}

impl<'a, Offset: OffsetType, Length: LengthType> BytesCows<'a, Offset, Length> {
    pub fn try_into_chars_slices(self) -> Result<CharsCows<'a, Offset, Length>, StringTapeError> {
        self.try_into()
    }
}

impl<'a, Offset: OffsetType, Length: LengthType> CharsCows<'a, Offset, Length> {
    pub fn into_bytes_slices(self) -> BytesCows<'a, Offset, Length> {
        self.into()
    }

    /// Returns a zero-copy view of this `CharsCows` as a `BytesCows`.
    ///
    /// This is a no-cost operation that reinterprets the string collection as bytes
    /// without copying or moving any data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsU32U8;
    /// use std::borrow::Cow;
    ///
    /// let data = "hello world";
    /// let cows = CharsCowsU32U8::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// let bytes = cows.as_bytes();
    /// assert_eq!(bytes.get(0), Some(&b"hello"[..]));
    /// assert_eq!(bytes.get(1), Some(&b"world"[..]));
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn as_bytes(&self) -> BytesCows<'_, Offset, Length> {
        BytesCows {
            data: Cow::Borrowed(self.data.as_ref()),
            entries: self.entries.clone(),
        }
    }
}

// Type aliases for common configurations
pub type CharsCowsU32U16<'a> = CharsCows<'a, u32, u16>;
pub type CharsCowsU32U8<'a> = CharsCows<'a, u32, u8>;
pub type CharsCowsU16U8<'a> = CharsCows<'a, u16, u8>;
pub type CharsCowsU64U32<'a> = CharsCows<'a, u64, u32>;

pub type BytesCowsU32U16<'a> = BytesCows<'a, u32, u16>;
pub type BytesCowsU32U8<'a> = BytesCows<'a, u32, u8>;
pub type BytesCowsU16U8<'a> = BytesCows<'a, u16, u8>;
pub type BytesCowsU64U32<'a> = BytesCows<'a, u64, u32>;

// ========================
// Auto-selecting CharsCows
// ========================

/// Automatically selects the most memory-efficient CharsCows type based on data size.
///
/// Returns an enum that can hold any combination of offset/length types.
pub enum CharsCowsAuto<'a> {
    U32U8(CharsCows<'a, u32, u8>),
    U32U16(CharsCows<'a, u32, u16>),
    U32U32(CharsCows<'a, u32, u32>),
    U64U8(CharsCows<'a, u64, u8>),
    U64U16(CharsCows<'a, u64, u16>),
    U64U32(CharsCows<'a, u64, u32>),
}

impl<'a> CharsCowsAuto<'a> {
    /// Creates the most memory-efficient CharsCows based on data size and max word length.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = "hello world";
    /// let cows = CharsCowsAuto::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// // Automatically picks CharsCows<u32, u8> for small data
    /// assert_eq!(cows.len(), 2);
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    /// Creates the most memory-efficient CharsCows using a two-pass strategy.
    ///
    /// First pass scans to find the maximum word length, then second pass builds
    /// with optimal types. Requires `Clone` iterator for memory efficiency.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = "hello world";
    /// let cows = CharsCowsAuto::from_iter_and_data(
    ///     data.split_whitespace(),  // Clone iterator
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// assert_eq!(cows.len(), 2);
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn from_iter_and_data<I>(iter: I, data: Cow<'a, [u8]>) -> Result<Self, StringTapeError>
    where
        I: IntoIterator + Clone,
        I::Item: AsRef<str>,
    {
        let data_len = data.len();

        // First pass: find max word length without materializing
        let max_word_len = iter
            .clone()
            .into_iter()
            .map(|s| s.as_ref().len())
            .max()
            .unwrap_or(0);

        // Pick smallest offset type
        let needs_u64_offset = data_len > u32::MAX as usize;

        // Second pass: build with optimal types
        if max_word_len <= u8::MAX as usize {
            if needs_u64_offset {
                Ok(Self::U64U8(CharsCows::from_iter_and_data(iter, data)?))
            } else {
                Ok(Self::U32U8(CharsCows::from_iter_and_data(iter, data)?))
            }
        } else if max_word_len <= u16::MAX as usize {
            if needs_u64_offset {
                Ok(Self::U64U16(CharsCows::from_iter_and_data(iter, data)?))
            } else {
                Ok(Self::U32U16(CharsCows::from_iter_and_data(iter, data)?))
            }
        } else if needs_u64_offset {
            Ok(Self::U64U32(CharsCows::from_iter_and_data(iter, data)?))
        } else {
            Ok(Self::U32U32(CharsCows::from_iter_and_data(iter, data)?))
        }
    }

    /// Returns the number of cows.
    pub fn len(&self) -> usize {
        match self {
            Self::U32U8(s) => s.len(),
            Self::U32U16(s) => s.len(),
            Self::U32U32(s) => s.len(),
            Self::U64U8(s) => s.len(),
            Self::U64U16(s) => s.len(),
            Self::U64U32(s) => s.len(),
        }
    }

    /// Returns `true` if the collection contains no cows.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a reference to the string at the given index.
    pub fn get(&self, index: usize) -> Option<&str> {
        match self {
            Self::U32U8(s) => s.get(index),
            Self::U32U16(s) => s.get(index),
            Self::U32U32(s) => s.get(index),
            Self::U64U8(s) => s.get(index),
            Self::U64U16(s) => s.get(index),
            Self::U64U32(s) => s.get(index),
        }
    }

    /// Returns the byte size per entry for the selected type combination.
    pub fn bytes_per_entry(&self) -> usize {
        match self {
            Self::U32U8(_) => 5,   // u32(4) + u8(1)
            Self::U32U16(_) => 6,  // u32(4) + u16(2)
            Self::U32U32(_) => 8,  // u32(4) + u32(4)
            Self::U64U8(_) => 9,   // u64(8) + u8(1)
            Self::U64U16(_) => 10, // u64(8) + u16(2)
            Self::U64U32(_) => 12, // u64(8) + u32(4)
        }
    }

    /// Returns a string describing the selected type combination.
    pub fn type_name(&self) -> &'static str {
        match self {
            Self::U32U8(_) => "CharsCows<u32, u8>",
            Self::U32U16(_) => "CharsCows<u32, u16>",
            Self::U32U32(_) => "CharsCows<u32, u32>",
            Self::U64U8(_) => "CharsCows<u64, u8>",
            Self::U64U16(_) => "CharsCows<u64, u16>",
            Self::U64U32(_) => "CharsCows<u64, u32>",
        }
    }

    /// Returns an iterator over the string cows.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = "hello world foo";
    /// let cows = CharsCowsAuto::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// let words: Vec<&str> = cows.iter().collect();
    /// assert_eq!(words, vec!["hello", "world", "foo"]);
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn iter(&self) -> CharsCowsAutoIter<'_> {
        CharsCowsAutoIter {
            inner: self,
            index: 0,
        }
    }

    /// Sorts the slices in-place using the default string comparison.
    ///
    /// This is a stable sort that preserves the order of equal elements.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = "zebra apple banana";
    /// let mut cows = CharsCowsAuto::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// cows.sort();
    /// let sorted: Vec<&str> = cows.iter().collect();
    /// assert_eq!(sorted, vec!["apple", "banana", "zebra"]);
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn sort(&mut self) {
        match self {
            Self::U32U8(s) => s.sort(),
            Self::U32U16(s) => s.sort(),
            Self::U32U32(s) => s.sort(),
            Self::U64U8(s) => s.sort(),
            Self::U64U16(s) => s.sort(),
            Self::U64U32(s) => s.sort(),
        }
    }

    /// Sorts the slices in-place using an unstable sorting algorithm.
    ///
    /// This is faster than stable sort but may not preserve the order of equal elements.
    pub fn sort_unstable(&mut self) {
        match self {
            Self::U32U8(s) => s.sort_unstable(),
            Self::U32U16(s) => s.sort_unstable(),
            Self::U32U32(s) => s.sort_unstable(),
            Self::U64U8(s) => s.sort_unstable(),
            Self::U64U16(s) => s.sort_unstable(),
            Self::U64U32(s) => s.sort_unstable(),
        }
    }

    /// Sorts the slices in-place using a custom comparison function.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = "aaa bb c";
    /// let mut cows = CharsCowsAuto::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// // Sort by length, then alphabetically
    /// cows.sort_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(b)));
    /// let sorted: Vec<&str> = cows.iter().collect();
    /// assert_eq!(sorted, vec!["c", "bb", "aaa"]);
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn sort_by<F>(&mut self, compare: F)
    where
        F: FnMut(&str, &str) -> core::cmp::Ordering,
    {
        match self {
            Self::U32U8(s) => s.sort_by(compare),
            Self::U32U16(s) => s.sort_by(compare),
            Self::U32U32(s) => s.sort_by(compare),
            Self::U64U8(s) => s.sort_by(compare),
            Self::U64U16(s) => s.sort_by(compare),
            Self::U64U32(s) => s.sort_by(compare),
        }
    }

    /// Sorts the slices in-place using a key extraction function.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = "aaa bb c";
    /// let mut cows = CharsCowsAuto::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// // Sort by string length
    /// cows.sort_by_key(|s| s.len());
    /// let sorted: Vec<&str> = cows.iter().collect();
    /// assert_eq!(sorted, vec!["c", "bb", "aaa"]);
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn sort_by_key<K, F>(&mut self, f: F)
    where
        F: FnMut(&str) -> K,
        K: Ord,
    {
        match self {
            Self::U32U8(s) => s.sort_by_key(f),
            Self::U32U16(s) => s.sort_by_key(f),
            Self::U32U32(s) => s.sort_by_key(f),
            Self::U64U8(s) => s.sort_by_key(f),
            Self::U64U16(s) => s.sort_by_key(f),
            Self::U64U32(s) => s.sort_by_key(f),
        }
    }

    /// Returns a reference to the underlying data buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = "hello world";
    /// let cows = CharsCowsAuto::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// assert_eq!(cows.data(), b"hello world");
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn data(&self) -> &[u8] {
        match self {
            Self::U32U8(s) => s.data(),
            Self::U32U16(s) => s.data(),
            Self::U32U32(s) => s.data(),
            Self::U64U8(s) => s.data(),
            Self::U64U16(s) => s.data(),
            Self::U64U32(s) => s.data(),
        }
    }

    /// Returns a reference to the parent string that all slices reference.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = "hello world";
    /// let cows = CharsCowsAuto::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// assert_eq!(cows.parent(), "hello world");
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn parent(&self) -> &str {
        match self {
            Self::U32U8(s) => s.parent(),
            Self::U32U16(s) => s.parent(),
            Self::U32U32(s) => s.parent(),
            Self::U64U8(s) => s.parent(),
            Self::U64U16(s) => s.parent(),
            Self::U64U32(s) => s.parent(),
        }
    }

    /// Returns a zero-copy view of this `CharsCowsAuto` as a `BytesCowsAuto`.
    ///
    /// This is a no-cost operation that reinterprets the string collection as bytes
    /// without copying or moving any data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::CharsCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = "hello world";
    /// let cows = CharsCowsAuto::from_iter_and_data(
    ///     data.split_whitespace(),
    ///     Cow::Borrowed(data.as_bytes())
    /// ).unwrap();
    ///
    /// let bytes = cows.as_bytes();
    /// assert_eq!(bytes.get(0), Some(&b"hello"[..]));
    /// assert_eq!(bytes.get(1), Some(&b"world"[..]));
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn as_bytes(&self) -> BytesCowsAuto<'_> {
        match self {
            Self::U32U8(s) => BytesCowsAuto::U32U8(s.as_bytes()),
            Self::U32U16(s) => BytesCowsAuto::U32U16(s.as_bytes()),
            Self::U32U32(s) => BytesCowsAuto::U32U32(s.as_bytes()),
            Self::U64U8(s) => BytesCowsAuto::U64U8(s.as_bytes()),
            Self::U64U16(s) => BytesCowsAuto::U64U16(s.as_bytes()),
            Self::U64U32(s) => BytesCowsAuto::U64U32(s.as_bytes()),
        }
    }
}

/// Iterator over CharsCowsAuto string cows.
pub struct CharsCowsAutoIter<'a> {
    inner: &'a CharsCowsAuto<'a>,
    index: usize,
}

impl<'a> Iterator for CharsCowsAutoIter<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        let result = self.inner.get(self.index);
        if result.is_some() {
            self.index += 1;
        }
        result
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.inner.len() - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a> ExactSizeIterator for CharsCowsAutoIter<'a> {}

impl<'a> IntoIterator for &'a CharsCowsAuto<'a> {
    type Item = &'a str;
    type IntoIter = CharsCowsAutoIter<'a>;

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

// ========================
// Auto-selecting BytesCows
// ========================

/// Automatically selects the most memory-efficient BytesCows type based on data size.
pub enum BytesCowsAuto<'a> {
    U32U8(BytesCows<'a, u32, u8>),
    U32U16(BytesCows<'a, u32, u16>),
    U32U32(BytesCows<'a, u32, u32>),
    U64U8(BytesCows<'a, u64, u8>),
    U64U16(BytesCows<'a, u64, u16>),
    U64U32(BytesCows<'a, u64, u32>),
}

impl<'a> BytesCowsAuto<'a> {
    /// Creates BytesCowsAuto from iterator of byte cows.
    /// Auto-selects offset and length types based on data size and max slice length.
    pub fn from_iter_and_data<I>(iter: I, data: Cow<'a, [u8]>) -> Result<Self, StringTapeError>
    where
        I: IntoIterator + Clone,
        I::Item: AsRef<[u8]>,
    {
        let data_len = data.len();

        // First pass: find max slice length
        let max_len = iter
            .clone()
            .into_iter()
            .map(|b| b.as_ref().len())
            .max()
            .unwrap_or(0);

        let needs_u64_offset = data_len > u32::MAX as usize;

        // Second pass: build with optimal types
        if max_len <= u8::MAX as usize {
            if needs_u64_offset {
                Ok(Self::U64U8(BytesCows::from_iter_and_data(iter, data)?))
            } else {
                Ok(Self::U32U8(BytesCows::from_iter_and_data(iter, data)?))
            }
        } else if max_len <= u16::MAX as usize {
            if needs_u64_offset {
                Ok(Self::U64U16(BytesCows::from_iter_and_data(iter, data)?))
            } else {
                Ok(Self::U32U16(BytesCows::from_iter_and_data(iter, data)?))
            }
        } else if needs_u64_offset {
            Ok(Self::U64U32(BytesCows::from_iter_and_data(iter, data)?))
        } else {
            Ok(Self::U32U32(BytesCows::from_iter_and_data(iter, data)?))
        }
    }

    pub fn len(&self) -> usize {
        match self {
            Self::U32U8(s) => s.len(),
            Self::U32U16(s) => s.len(),
            Self::U32U32(s) => s.len(),
            Self::U64U8(s) => s.len(),
            Self::U64U16(s) => s.len(),
            Self::U64U32(s) => s.len(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn get(&self, index: usize) -> Option<&[u8]> {
        match self {
            Self::U32U8(s) => s.get(index),
            Self::U32U16(s) => s.get(index),
            Self::U32U32(s) => s.get(index),
            Self::U64U8(s) => s.get(index),
            Self::U64U16(s) => s.get(index),
            Self::U64U32(s) => s.get(index),
        }
    }

    /// Returns a zero-copy view of this `BytesCowsAuto` as a `CharsCowsAuto` if all slices are valid UTF-8.
    ///
    /// This validates that all byte slices contain valid UTF-8, then reinterprets the collection
    /// as strings without copying or moving any data.
    ///
    /// # Errors
    ///
    /// Returns `StringTapeError::Utf8Error` if any slice contains invalid UTF-8.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::BytesCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = b"hello world";
    /// let bytes = BytesCowsAuto::from_iter_and_data(
    ///     data.split(|&b| b == b' '),
    ///     Cow::Borrowed(&data[..])
    /// ).unwrap();
    ///
    /// let chars = bytes.as_chars().unwrap();
    /// assert_eq!(chars.get(0), Some("hello"));
    /// assert_eq!(chars.get(1), Some("world"));
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn as_chars(&self) -> Result<CharsCowsAuto<'_>, StringTapeError> {
        match self {
            Self::U32U8(s) => Ok(CharsCowsAuto::U32U8(s.as_chars()?)),
            Self::U32U16(s) => Ok(CharsCowsAuto::U32U16(s.as_chars()?)),
            Self::U32U32(s) => Ok(CharsCowsAuto::U32U32(s.as_chars()?)),
            Self::U64U8(s) => Ok(CharsCowsAuto::U64U8(s.as_chars()?)),
            Self::U64U16(s) => Ok(CharsCowsAuto::U64U16(s.as_chars()?)),
            Self::U64U32(s) => Ok(CharsCowsAuto::U64U32(s.as_chars()?)),
        }
    }

    /// Returns a reference to the underlying data buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::BytesCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = b"hello world";
    /// let bytes = BytesCowsAuto::from_iter_and_data(
    ///     data.split(|&b| b == b' '),
    ///     Cow::Borrowed(&data[..])
    /// ).unwrap();
    ///
    /// assert_eq!(bytes.data(), b"hello world");
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn data(&self) -> &[u8] {
        match self {
            Self::U32U8(s) => s.data(),
            Self::U32U16(s) => s.data(),
            Self::U32U32(s) => s.data(),
            Self::U64U8(s) => s.data(),
            Self::U64U16(s) => s.data(),
            Self::U64U32(s) => s.data(),
        }
    }

    /// Returns a reference to the parent byte buffer that all slices reference.
    ///
    /// This is an alias for `data()` that provides a consistent API across all Cows types.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::BytesCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = b"hello world";
    /// let bytes = BytesCowsAuto::from_iter_and_data(
    ///     data.split(|&b| b == b' '),
    ///     Cow::Borrowed(&data[..])
    /// ).unwrap();
    ///
    /// assert_eq!(bytes.parent(), b"hello world");
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn parent(&self) -> &[u8] {
        match self {
            Self::U32U8(s) => s.parent(),
            Self::U32U16(s) => s.parent(),
            Self::U32U32(s) => s.parent(),
            Self::U64U8(s) => s.parent(),
            Self::U64U16(s) => s.parent(),
            Self::U64U32(s) => s.parent(),
        }
    }

    /// Returns an iterator over the byte cows.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stringtape::BytesCowsAuto;
    /// use std::borrow::Cow;
    ///
    /// let data = b"hello world foo";
    /// let bytes = BytesCowsAuto::from_iter_and_data(
    ///     data.split(|&b| b == b' '),
    ///     Cow::Borrowed(&data[..])
    /// ).unwrap();
    ///
    /// let slices: Vec<&[u8]> = bytes.iter().collect();
    /// assert_eq!(slices, vec![&b"hello"[..], &b"world"[..], &b"foo"[..]]);
    /// # Ok::<(), stringtape::StringTapeError>(())
    /// ```
    pub fn iter(&self) -> BytesCowsAutoIter<'_> {
        BytesCowsAutoIter {
            inner: self,
            index: 0,
        }
    }
}

/// Iterator over BytesCowsAuto byte cows.
pub struct BytesCowsAutoIter<'a> {
    inner: &'a BytesCowsAuto<'a>,
    index: usize,
}

impl<'a> Iterator for BytesCowsAutoIter<'a> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        let result = self.inner.get(self.index);
        if result.is_some() {
            self.index += 1;
        }
        result
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.inner.len() - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a> ExactSizeIterator for BytesCowsAutoIter<'a> {}

impl<'a> IntoIterator for &'a BytesCowsAuto<'a> {
    type Item = &'a [u8];
    type IntoIter = BytesCowsAutoIter<'a>;

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

// ========================
// Auto-selecting CharsTape
// ========================

/// Automatically selects the most memory-efficient CharsTape offset type.
pub enum CharsTapeAuto<A: Allocator = Global> {
    I32(CharsTape<i32, A>),
    U32(CharsTape<u32, A>),
    U64(CharsTape<u64, A>),
}

impl<A: Allocator> CharsTapeAuto<A> {
    /// Creates CharsTapeAuto with custom allocator.
    pub fn new_in(allocator: A) -> Self {
        Self::I32(CharsTape::new_in(allocator))
    }

    pub fn push(&mut self, s: &str) -> Result<(), StringTapeError> {
        match self {
            Self::I32(t) => t.push(s),
            Self::U32(t) => t.push(s),
            Self::U64(t) => t.push(s),
        }
    }

    pub fn len(&self) -> usize {
        match self {
            Self::I32(t) => t.len(),
            Self::U32(t) => t.len(),
            Self::U64(t) => t.len(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn get(&self, index: usize) -> Option<&str> {
        match self {
            Self::I32(t) => t.get(index),
            Self::U32(t) => t.get(index),
            Self::U64(t) => t.get(index),
        }
    }
}

impl Default for CharsTapeAuto<Global> {
    fn default() -> Self {
        Self::new_in(Global)
    }
}

impl<A: Allocator + Clone> CharsTapeAuto<A> {
    /// Creates tape from clonable iterator, auto-selecting offset type (I32/U32/U64) based on total data size.
    /// Two-pass: first calculates size, second builds tape.
    pub fn from_iter_in<'a, I>(iter: I, allocator: A) -> Self
    where
        I: IntoIterator<Item = &'a str> + Clone,
    {
        // First pass: calculate total data size to determine offset type
        let total_size: usize = iter.clone().into_iter().map(|s| s.len()).sum();

        // Choose optimal type based on data size
        if total_size <= i32::MAX as usize {
            let mut tape = CharsTape::new_in(allocator);
            for s in iter {
                tape.push(s).ok();
            }
            Self::I32(tape)
        } else if total_size <= u32::MAX as usize {
            let mut tape = CharsTape::new_in(allocator);
            for s in iter {
                tape.push(s).ok();
            }
            Self::U32(tape)
        } else {
            let mut tape = CharsTape::new_in(allocator);
            for s in iter {
                tape.push(s).ok();
            }
            Self::U64(tape)
        }
    }
}

impl CharsTapeAuto<Global> {
    /// Creates tape from clonable iterator with global allocator.
    #[allow(clippy::should_implement_trait)]
    pub fn from_iter<'a, I>(iter: I) -> Self
    where
        I: IntoIterator<Item = &'a str> + Clone,
    {
        Self::from_iter_in(iter, Global)
    }
}

// ========================
// Auto-selecting BytesTape
// ========================

/// Automatically selects the most memory-efficient BytesTape offset type.
pub enum BytesTapeAuto<A: Allocator = Global> {
    U16(BytesTape<u16, A>),
    U32(BytesTape<u32, A>),
    U64(BytesTape<u64, A>),
}

impl<A: Allocator> BytesTapeAuto<A> {
    /// Creates BytesTapeAuto with custom allocator.
    pub fn new_in(allocator: A) -> Self {
        Self::U16(BytesTape::new_in(allocator))
    }

    pub fn push(&mut self, bytes: &[u8]) -> Result<(), StringTapeError> {
        match self {
            Self::U16(t) => t.push(bytes),
            Self::U32(t) => t.push(bytes),
            Self::U64(t) => t.push(bytes),
        }
    }

    pub fn len(&self) -> usize {
        match self {
            Self::U16(t) => t.len(),
            Self::U32(t) => t.len(),
            Self::U64(t) => t.len(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn get(&self, index: usize) -> Option<&[u8]> {
        match self {
            Self::U16(t) => t.get(index),
            Self::U32(t) => t.get(index),
            Self::U64(t) => t.get(index),
        }
    }
}

impl Default for BytesTapeAuto<Global> {
    fn default() -> Self {
        Self::new_in(Global)
    }
}

impl<A: Allocator + Clone> BytesTapeAuto<A> {
    /// Creates tape from clonable iterator, auto-selecting offset type (U16/U32/U64) based on total data size.
    /// Two-pass: first calculates size, second builds tape.
    pub fn from_iter_in<'a, I>(iter: I, allocator: A) -> Self
    where
        I: IntoIterator<Item = &'a [u8]> + Clone,
    {
        // First pass: calculate total data size to determine offset type
        let total_size: usize = iter.clone().into_iter().map(|b| b.len()).sum();

        // Choose optimal type based on data size
        if total_size <= u16::MAX as usize {
            let mut tape = BytesTape::new_in(allocator);
            for bytes in iter {
                tape.push(bytes).ok();
            }
            Self::U16(tape)
        } else if total_size <= u32::MAX as usize {
            let mut tape = BytesTape::new_in(allocator);
            for bytes in iter {
                tape.push(bytes).ok();
            }
            Self::U32(tape)
        } else {
            let mut tape = BytesTape::new_in(allocator);
            for bytes in iter {
                tape.push(bytes).ok();
            }
            Self::U64(tape)
        }
    }
}

impl BytesTapeAuto<Global> {
    /// Creates tape from clonable iterator with global allocator.
    #[allow(clippy::should_implement_trait)]
    pub fn from_iter<'a, I>(iter: I) -> Self
    where
        I: IntoIterator<Item = &'a [u8]> + Clone,
    {
        Self::from_iter_in(iter, Global)
    }
}

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

    #[cfg(not(feature = "std"))]
    use alloc::string::ToString;
    #[cfg(not(feature = "std"))]
    use alloc::vec;
    #[cfg(not(feature = "std"))]
    use alloc::vec::Vec;

    #[test]
    fn basic_operations() {
        let mut tape = CharsTapeI32::new();
        assert!(tape.is_empty());

        tape.push("hello").unwrap();
        tape.push("world").unwrap();
        tape.push("foo").unwrap();

        assert_eq!(tape.len(), 3);
        assert_eq!(tape.get(0), Some("hello"));
        assert_eq!(tape.get(1), Some("world"));
        assert_eq!(tape.get(2), Some("foo"));
        assert_eq!(tape.get(3), None);
    }

    #[test]
    fn unsigned_basic_operations() {
        // u32
        let mut t32 = CharsTapeU32::new();
        t32.push("hello").unwrap();
        t32.push("world").unwrap();
        assert_eq!(t32.len(), 2);
        assert_eq!(t32.get(0), Some("hello"));
        assert_eq!(t32.get(1), Some("world"));

        // u64
        let mut t64 = CharsTapeU64::new();
        t64.extend(["a", "", "bbb"]).unwrap();
        assert_eq!(t64.len(), 3);
        assert_eq!(t64.get(0), Some("a"));
        assert_eq!(t64.get(1), Some(""));
        assert_eq!(t64.get(2), Some("bbb"));
    }

    #[test]
    fn offsets_64bit() {
        let mut tape = CharsTapeI64::new();
        tape.push("test").unwrap();
        assert_eq!(tape.get(0), Some("test"));
    }

    #[test]
    fn iterator_basics() {
        let mut tape = CharsTapeI32::new();
        tape.push("a").unwrap();
        tape.push("b").unwrap();
        tape.push("c").unwrap();

        let strings: Vec<&str> = tape.iter().collect();
        assert_eq!(strings, vec!["a", "b", "c"]);
    }

    #[test]
    fn empty_strings() {
        let mut tape = CharsTapeI32::new();
        tape.push("").unwrap();
        tape.push("non-empty").unwrap();
        tape.push("").unwrap();

        assert_eq!(tape.len(), 3);
        assert_eq!(tape.get(0), Some(""));
        assert_eq!(tape.get(1), Some("non-empty"));
        assert_eq!(tape.get(2), Some(""));
    }

    #[test]
    fn index_trait() {
        let mut tape = CharsTapeI32::new();
        tape.push("hello").unwrap();
        tape.push("world").unwrap();

        assert_eq!(&tape[0], "hello");
        assert_eq!(&tape[1], "world");
    }

    #[test]
    fn into_iterator() {
        let mut tape = CharsTapeI32::new();
        tape.push("a").unwrap();
        tape.push("b").unwrap();
        tape.push("c").unwrap();

        let strings: Vec<&str> = (&tape).into_iter().collect();
        assert_eq!(strings, vec!["a", "b", "c"]);

        // Test for-loop syntax
        let mut result = Vec::new();
        for s in &tape {
            result.push(s);
        }
        assert_eq!(result, vec!["a", "b", "c"]);
    }

    #[test]
    fn from_iterator() {
        let strings = vec!["hello", "world", "test"];
        let tape: CharsTapeI32 = strings.into_iter().collect();

        assert_eq!(tape.len(), 3);
        assert_eq!(tape.get(0), Some("hello"));
        assert_eq!(tape.get(1), Some("world"));
        assert_eq!(tape.get(2), Some("test"));
    }

    #[test]
    fn from_iterator_unsigned() {
        let strings = vec!["hello", "world", "test"];
        let tape_u32: CharsTapeU32 = strings.clone().into_iter().collect();
        let tape_u64: CharsTapeU64 = strings.clone().into_iter().collect();
        assert_eq!(tape_u32.len(), 3);
        assert_eq!(tape_u64.len(), 3);
        assert_eq!(tape_u32.get(1), Some("world"));
        assert_eq!(tape_u64.get(2), Some("test"));
    }

    #[test]
    fn extend() {
        let mut tape = CharsTapeI32::new();
        tape.push("initial").unwrap();

        let additional = vec!["hello", "world"];
        tape.extend(additional).unwrap();

        assert_eq!(tape.len(), 3);
        assert_eq!(tape.get(0), Some("initial"));
        assert_eq!(tape.get(1), Some("hello"));
        assert_eq!(tape.get(2), Some("world"));
    }

    #[test]
    fn clear_and_truncate() {
        let mut tape = CharsTapeI32::new();
        tape.push("a").unwrap();
        tape.push("b").unwrap();
        tape.push("c").unwrap();

        assert_eq!(tape.len(), 3);

        tape.truncate(2);
        assert_eq!(tape.len(), 2);
        assert_eq!(tape.get(0), Some("a"));
        assert_eq!(tape.get(1), Some("b"));
        assert_eq!(tape.get(2), None);

        tape.clear();
        assert_eq!(tape.len(), 0);
        assert!(tape.is_empty());
    }

    #[test]
    fn unsigned_views_and_subviews() {
        let mut tape = CharsTapeU32::new();
        tape.extend(["0", "1", "22", "333"]).unwrap();
        let view = tape.subview(1, 4).unwrap();
        assert_eq!(view.len(), 3);
        assert_eq!(view.get(0), Some("1"));
        assert_eq!(view.get(2), Some("333"));
        let sub = view.subview(1, 2).unwrap();
        assert_eq!(sub.len(), 1);
        assert_eq!(sub.get(0), Some("22"));
    }

    #[test]
    fn capacity() {
        let tape = CharsTapeI32::with_capacity(100, 10).unwrap();
        assert_eq!(tape.data_capacity(), 100);
        assert_eq!(tape.capacity(), 0); // No strings added yet
    }

    #[test]
    fn custom_allocator() {
        // Using the Global allocator explicitly
        let mut tape: CharsTape<i32, Global> = CharsTape::new_in(Global);

        tape.push("hello").unwrap();
        tape.push("world").unwrap();

        assert_eq!(tape.len(), 2);
        assert_eq!(tape.get(0), Some("hello"));
        assert_eq!(tape.get(1), Some("world"));

        // Verify we can access the allocator
        let _allocator_ref = tape.allocator();
    }

    #[test]
    fn custom_allocator_with_capacity() {
        let tape: CharsTape<i64, Global> = CharsTape::with_capacity_in(256, 50, Global).unwrap();

        assert_eq!(tape.data_capacity(), 256);
        assert!(tape.is_empty());
    }

    #[test]
    fn bytes_tape_basic() {
        let mut tape = BytesTapeI32::new();
        tape.push(&[1, 2, 3]).unwrap();
        tape.push(b"abc").unwrap();

        assert_eq!(tape.len(), 2);
        assert_eq!(&tape[0], &[1u8, 2, 3] as &[u8]);
        assert_eq!(&tape[1], b"abc" as &[u8]);
    }

    #[test]
    fn unsigned_bytes_tape_basic() {
        let mut tape = BytesTapeU64::new();
        tape.push(&[1u8, 2]).unwrap();
        tape.push(&[3u8, 4, 5]).unwrap();
        assert_eq!(tape.len(), 2);
        assert_eq!(&tape[0], &[1u8, 2] as &[u8]);
        assert_eq!(&tape[1], &[3u8, 4, 5] as &[u8]);
    }

    #[test]
    fn chars_tape_view_basic() {
        let mut tape = CharsTapeI32::new();
        tape.push("hello").unwrap();
        tape.push("world").unwrap();
        tape.push("foo").unwrap();
        tape.push("bar").unwrap();

        // Test basic subview creation
        let view = tape.subview(1, 3).unwrap();
        assert_eq!(view.len(), 2);
        assert_eq!(view.get(0), Some("world"));
        assert_eq!(view.get(1), Some("foo"));
        assert_eq!(view.get(2), None);

        // Test indexing
        assert_eq!(&view[0], "world");
        assert_eq!(&view[1], "foo");
    }

    #[test]
    fn chars_tape_range_syntax() {
        let mut tape = CharsTapeI32::new();
        tape.push("a").unwrap();
        tape.push("b").unwrap();
        tape.push("c").unwrap();
        tape.push("d").unwrap();

        // Test view() method
        let full_view = tape.view();
        assert_eq!(full_view.len(), 4);
        assert_eq!(full_view.get(0), Some("a"));
        assert_eq!(full_view.get(3), Some("d"));

        // Test subview
        let sub = tape.subview(1, 3).unwrap();
        assert_eq!(sub.len(), 2);
        assert_eq!(sub.get(0), Some("b"));
        assert_eq!(sub.get(1), Some("c"));
    }

    #[test]
    fn chars_tape_view_subslicing() {
        let mut tape = CharsTapeI32::new();
        tape.push("0").unwrap();
        tape.push("1").unwrap();
        tape.push("2").unwrap();
        tape.push("3").unwrap();
        tape.push("4").unwrap();

        // Create initial subview
        let view = tape.subview(1, 4).unwrap(); // ["1", "2", "3"]
        assert_eq!(view.len(), 3);

        // Create sub-view of a view
        let subview = view.subview(1, 2).unwrap(); // ["2"]
        assert_eq!(subview.len(), 1);
        assert_eq!(subview.get(0), Some("2"));

        // Test subviews with different ranges
        let subview_from = view.subview(1, view.len()).unwrap(); // ["2", "3"]
        assert_eq!(subview_from.len(), 2);
        assert_eq!(subview_from.get(0), Some("2"));
        assert_eq!(subview_from.get(1), Some("3"));

        let subview_to = view.subview(0, 2).unwrap(); // ["1", "2"]
        assert_eq!(subview_to.len(), 2);
        assert_eq!(subview_to.get(0), Some("1"));
        assert_eq!(subview_to.get(1), Some("2"));
    }

    #[test]
    fn bytes_tape_view_basic() {
        let mut tape = BytesTapeI32::new();
        tape.push(&[1u8, 2]).unwrap();
        tape.push(&[3u8, 4]).unwrap();
        tape.push(&[5u8, 6]).unwrap();
        tape.push(&[7u8, 8]).unwrap();

        // Test basic subview creation
        let view = tape.subview(1, 3).unwrap();
        assert_eq!(view.len(), 2);
        assert_eq!(view.get(0), Some(&[3u8, 4] as &[u8]));
        assert_eq!(view.get(1), Some(&[5u8, 6] as &[u8]));
        assert_eq!(view.get(2), None);

        // Test indexing
        assert_eq!(&view[0], &[3u8, 4] as &[u8]);
        assert_eq!(&view[1], &[5u8, 6] as &[u8]);
    }

    #[test]
    fn view_empty_strings() {
        let mut tape = CharsTapeI32::new();
        tape.push("").unwrap();
        tape.push("non-empty").unwrap();
        tape.push("").unwrap();
        tape.push("another").unwrap();

        let view = tape.subview(0, 3).unwrap();
        assert_eq!(view.len(), 3);
        assert_eq!(view.get(0), Some(""));
        assert_eq!(view.get(1), Some("non-empty"));
        assert_eq!(view.get(2), Some(""));
    }

    #[test]
    fn view_single_item() {
        let mut tape = CharsTapeI32::new();
        tape.push("only").unwrap();

        let view = tape.subview(0, 1).unwrap();
        assert_eq!(view.len(), 1);
        assert_eq!(view.get(0), Some("only"));
    }

    #[test]
    fn view_bounds_checking() {
        let mut tape = CharsTapeI32::new();
        tape.push("a").unwrap();
        tape.push("b").unwrap();

        // Out of bounds subview creation
        assert!(tape.subview(0, 3).is_err());
        assert!(tape.subview(2, 1).is_err());
        assert!(tape.subview(3, 4).is_err());

        // Valid empty subview
        let empty_view = tape.subview(1, 1).unwrap();
        assert_eq!(empty_view.len(), 0);
        assert!(empty_view.is_empty());
    }

    #[test]
    fn view_data_properties() {
        let mut tape = CharsTapeI32::new();
        tape.push("hello").unwrap(); // 5 bytes
        tape.push("world").unwrap(); // 5 bytes
        tape.push("!").unwrap(); // 1 byte

        let view = tape.subview(0, 2).unwrap(); // "hello", "world" = 10 bytes
        assert_eq!(view.data_len(), 10);
        assert!(!view.is_empty());

        let full_view = tape.subview(0, 3).unwrap(); // all = 11 bytes
        assert_eq!(full_view.data_len(), 11);
    }

    #[test]
    fn view_raw_parts() {
        let mut tape = CharsTapeI32::new();
        tape.push("test").unwrap();
        tape.push("data").unwrap();

        let view = tape.subview(0, 2).unwrap();
        let parts = view.as_raw_parts();

        assert!(!parts.data_ptr.is_null());
        assert!(!parts.offsets_ptr.is_null());
        assert_eq!(parts.data_len, 8); // "test" + "data"
        assert_eq!(parts.items_count, 2);
    }

    #[test]
    fn subview_raw_parts_consistency_chars() {
        let mut tape = CharsTapeI32::new();
        tape.extend(["abc", "", "xyz", "pq"]).unwrap();

        // Subview over middle two items: ["", "xyz"]
        let view = tape.subview(1, 3).unwrap();
        let parts = view.as_raw_parts();

        // Offsets len must be items_count + 1 and data_len equals absolute last offset
        unsafe {
            let offsets: &[i32] =
                core::slice::from_raw_parts(parts.offsets_ptr, parts.items_count + 1);
            assert_eq!(offsets.len(), parts.items_count + 1);
            assert!(offsets.windows(2).all(|w| w[0] <= w[1]));
            let last_abs = offsets[offsets.len() - 1] as usize;
            assert_eq!(last_abs, parts.data_len);
        }

        // Also check that element boundaries are respected
        assert_eq!(view.len(), 2);
        assert_eq!(view.get(0), Some(""));
        assert_eq!(view.get(1), Some("xyz"));
    }

    #[test]
    fn subview_raw_parts_consistency_bytes() {
        let mut tape = BytesTapeI32::new();
        tape.extend([
            b"a".as_slice(),
            b"".as_slice(),
            b"bc".as_slice(),
            b"def".as_slice(),
        ])
        .unwrap();

        // Subview over last two items: ["bc", "def"]
        let view = tape.subview(2, 4).unwrap();
        let parts = view.as_raw_parts();

        unsafe {
            let offsets: &[i32] =
                core::slice::from_raw_parts(parts.offsets_ptr, parts.items_count + 1);
            assert_eq!(offsets.len(), parts.items_count + 1);
            assert!(offsets.windows(2).all(|w| w[0] <= w[1]));
            let last_abs = offsets[offsets.len() - 1] as usize;
            assert_eq!(last_abs, parts.data_len);
        }

        assert_eq!(view.len(), 2);
        assert_eq!(view.get(0), Some(b"bc" as &[u8]));
        assert_eq!(view.get(1), Some(b"def" as &[u8]));
    }

    #[test]
    fn view_type_aliases() {
        let mut tape = CharsTapeI32::new();
        tape.push("test").unwrap();

        let _view: CharsTapeViewI32 = tape.subview(0, 1).unwrap();

        let mut bytes_tape = BytesTapeI64::new();
        bytes_tape.push(b"test").unwrap();

        let _bytes_view: BytesTapeViewI64 = bytes_tape.subview(0, 1).unwrap();
    }

    #[test]
    fn build_i32_from_other_offset_iterators() {
        let items = ["x", "yy", "", "zzz"];

        // From u32 iterator
        let mut u32t = CharsTapeU32::new();
        u32t.extend(items).unwrap();
        let t_from_u32: CharsTapeI32 = u32t.iter().collect();
        assert_eq!(t_from_u32.len(), items.len());
        assert_eq!(t_from_u32.get(1), Some("yy"));

        // From u64 iterator
        let mut u64t = CharsTapeU64::new();
        u64t.extend(items).unwrap();
        let t_from_u64: CharsTapeI32 = u64t.iter().collect();
        assert_eq!(t_from_u64.len(), items.len());
        assert_eq!(t_from_u64.get(3), Some("zzz"));

        // From i64 iterator
        let mut i64t = CharsTapeI64::new();
        i64t.extend(items).unwrap();
        let t_from_i64: CharsTapeI32 = i64t.iter().collect();
        assert_eq!(t_from_i64.len(), items.len());
        assert_eq!(t_from_i64.get(2), Some(""));
    }

    #[test]
    fn range_indexing_syntax() {
        let mut tape = CharsTapeI32::new();
        tape.push("a").unwrap();
        tape.push("b").unwrap();
        tape.push("c").unwrap();
        tape.push("d").unwrap();

        // While we can't return views with [..] syntax due to lifetime constraints,
        // we can test that the view() and subview() API works correctly

        // Get full view
        let full_view = tape.view();
        assert_eq!(full_view.len(), 4);

        // Get subviews
        let sub = tape.subview(1, 3).unwrap();
        assert_eq!(sub.len(), 2);
        assert_eq!(sub.get(0), Some("b"));
        assert_eq!(sub.get(1), Some("c"));

        // Test subview of subview
        let sub_sub = sub.subview(0, 1).unwrap();
        assert_eq!(sub_sub.len(), 1);
        assert_eq!(sub_sub.get(0), Some("b"));
    }

    #[cfg(test)]
    use arrow::array::{Array, BinaryArray, StringArray};
    #[cfg(test)]
    use arrow::buffer::{Buffer, OffsetBuffer, ScalarBuffer};

    #[test]
    fn charstape_to_arrow_string_array() {
        let mut tape = CharsTapeI32::new();
        tape.extend(["hello", "world", "", "arrow"]).unwrap();

        let (data_slice, offsets_slice) = tape.arrow_slices();
        let data_buffer = Buffer::from_slice_ref(data_slice);
        let offsets_buffer = OffsetBuffer::new(ScalarBuffer::new(
            Buffer::from_slice_ref(offsets_slice),
            0,
            offsets_slice.len(),
        ));
        let arrow_array = StringArray::new(offsets_buffer, data_buffer, None);

        assert_eq!(arrow_array.len(), 4);
        assert_eq!(arrow_array.value(0), "hello");
        assert_eq!(arrow_array.value(2), "");
    }

    #[test]
    fn arrow_string_array_to_charstape_view() {
        let arrow_array = StringArray::from(vec!["foo", "bar", ""]);

        // Zero-copy conversion to CharsTapeView
        let view = unsafe {
            CharsTapeViewI32::from_raw_parts(arrow_array.values(), arrow_array.offsets().as_ref())
        };

        assert_eq!(view.len(), 3);
        assert_eq!(view.get(0), Some("foo"));
        assert_eq!(view.get(1), Some("bar"));
        assert_eq!(view.get(2), Some(""));
    }

    #[test]
    fn arrow_binary_array_to_bytestape_view() {
        let values: Vec<Option<&[u8]>> = vec![
            Some(&[1u8, 2, 3] as &[u8]),
            Some(&[] as &[u8]),
            Some(&[4u8, 5] as &[u8]),
        ];
        let arrow_array = BinaryArray::from(values);

        // Zero-copy conversion to BytesTapeView
        let view = unsafe {
            BytesTapeViewI32::from_raw_parts(arrow_array.values(), arrow_array.offsets().as_ref())
        };

        assert_eq!(view.len(), 3);
        assert_eq!(view.get(0), Some(&[1u8, 2, 3] as &[u8]));
        assert_eq!(view.get(1), Some(&[] as &[u8]));
        assert_eq!(view.get(2), Some(&[4u8, 5] as &[u8]));
    }

    #[test]
    fn zero_copy_roundtrip() {
        // Original data
        let mut tape = CharsTapeI32::new();
        tape.extend(["hello", "", "world"]).unwrap();

        // Convert to Arrow (zero-copy)
        let (data_slice, offsets_slice) = tape.arrow_slices();
        let data_buffer = Buffer::from_slice_ref(data_slice);
        let offsets_buffer = OffsetBuffer::new(ScalarBuffer::new(
            Buffer::from_slice_ref(offsets_slice),
            0,
            offsets_slice.len(),
        ));
        let arrow_array = StringArray::new(offsets_buffer, data_buffer, None);

        // Convert back to CharsTapeView (zero-copy)
        let view = unsafe {
            CharsTapeViewI32::from_raw_parts(arrow_array.values(), arrow_array.offsets().as_ref())
        };

        // Verify data integrity without any copying
        assert_eq!(view.len(), 3);
        assert_eq!(view.get(0), Some("hello"));
        assert_eq!(view.get(1), Some(""));
        assert_eq!(view.get(2), Some("world"));
    }

    #[test]
    fn bytes_to_string_conversion() {
        // Test successful conversion with valid UTF-8
        let mut bytes_tape = BytesTapeI32::new();
        bytes_tape.push(b"hello").unwrap();
        bytes_tape.push(b"world").unwrap();
        bytes_tape.push(b"").unwrap();
        bytes_tape.push(b"rust").unwrap();

        let chars_tape: Result<CharsTapeI32, _> = bytes_tape.try_into();
        assert!(chars_tape.is_ok());

        let chars_tape = chars_tape.unwrap();
        assert_eq!(chars_tape.len(), 4);
        assert_eq!(chars_tape.get(0), Some("hello"));
        assert_eq!(chars_tape.get(1), Some("world"));
        assert_eq!(chars_tape.get(2), Some(""));
        assert_eq!(chars_tape.get(3), Some("rust"));
    }

    #[test]
    fn bytes_to_string_invalid_utf8() {
        // Test conversion failure with invalid UTF-8
        let mut bytes_tape = BytesTapeI32::new();
        bytes_tape.push(b"valid").unwrap();
        bytes_tape.push(&[0xFF, 0xFE]).unwrap(); // Invalid UTF-8 sequence
        bytes_tape.push(b"also valid").unwrap();

        let chars_tape: Result<CharsTapeI32, _> = bytes_tape.try_into();
        assert!(chars_tape.is_err());

        match chars_tape {
            Err(StringTapeError::Utf8Error(_)) => {}
            _ => panic!("Expected Utf8Error"),
        }
    }

    #[test]
    fn string_to_bytes_conversion() {
        // Test infallible conversion from CharsTape to BytesTape
        let mut chars_tape = CharsTapeI32::new();
        chars_tape.push("hello").unwrap();
        chars_tape.push("世界").unwrap(); // Unicode characters
        chars_tape.push("").unwrap();
        chars_tape.push("🦀").unwrap(); // Emoji

        let bytes_tape: BytesTapeI32 = chars_tape.into();
        assert_eq!(bytes_tape.len(), 4);
        assert_eq!(&bytes_tape[0], b"hello");
        assert_eq!(&bytes_tape[1], "世界".as_bytes());
        assert_eq!(&bytes_tape[2], b"");
        assert_eq!(&bytes_tape[3], "🦀".as_bytes());
    }

    #[test]
    fn conversion_convenience_methods() {
        // Test try_into_chars_tape method
        let mut bytes_tape = BytesTapeI32::new();
        bytes_tape.push(b"test").unwrap();
        let string_result = bytes_tape.try_into_chars_tape();
        assert!(string_result.is_ok());
        assert_eq!(string_result.unwrap().get(0), Some("test"));

        // Test into_bytes_tape method
        let mut chars_tape = CharsTapeI32::new();
        chars_tape.push("test").unwrap();
        let bytes_back = chars_tape.into_bytes_tape();
        assert_eq!(&bytes_back[0], b"test");
    }

    #[test]
    fn conversion_round_trip() {
        // Test round-trip conversion preserves data
        let mut original = CharsTapeI32::new();
        original.push("first").unwrap();
        original.push("second").unwrap();
        original.push("third").unwrap();

        // Store expected values before conversion
        let expected = vec!["first", "second", "third"];

        // Convert to BytesTape and back
        let bytes: BytesTapeI32 = original.into();
        let recovered: CharsTapeI32 = bytes.try_into().unwrap();

        assert_eq!(expected.len(), recovered.len());
        for (i, expected_str) in expected.iter().enumerate() {
            assert_eq!(recovered.get(i), Some(*expected_str));
        }
    }

    #[test]
    fn view_to_view_conversions_valid_utf8() {
        // Prepare a CharsTape and obtain its view
        let mut ct = CharsTapeI32::new();
        ct.extend(["abc", "", "世界"]).unwrap();
        let chars_view = ct.view();

        // Chars -> Bytes view conversion is infallible
        let bytes_view: BytesTapeViewI32 = chars_view.into_bytes_view();
        assert_eq!(bytes_view.len(), 3);
        assert_eq!(bytes_view.get(0), Some("abc".as_bytes()));
        assert_eq!(bytes_view.get(1), Some(b"" as &[u8]));
        assert_eq!(bytes_view.get(2), Some("世界".as_bytes()));

        // Bytes -> Chars view conversion is fallible, but should succeed for valid UTF-8
        let chars_back: Result<CharsTapeViewI32, _> = bytes_view.try_into_chars_view();
        assert!(chars_back.is_ok());
        let chars_back = chars_back.unwrap();
        assert_eq!(chars_back.len(), 3);
        assert_eq!(chars_back.get(0), Some("abc"));
        assert_eq!(chars_back.get(1), Some(""));
        assert_eq!(chars_back.get(2), Some("世界"));
    }

    #[test]
    fn view_to_view_bytes_to_chars_invalid_utf8() {
        // Prepare a BytesTape with invalid UTF-8 payload
        let mut bt = BytesTapeI32::new();
        bt.push(b"ok").unwrap();
        bt.push(&[0xFF, 0xFE]).unwrap(); // invalid UTF-8
        let bview = bt.view();

        // Converting to CharsTapeView should fail
        let res: Result<CharsTapeViewI32, _> = bview.try_into_chars_view();
        assert!(res.is_err());
        match res {
            Err(StringTapeError::Utf8Error(_)) => {}
            _ => panic!("Expected Utf8Error"),
        }
    }

    #[test]
    fn chars_slices_basic() {
        let data = "hello world foo bar";
        let cows = CharsCowsU32U16::from_iter_and_data(
            data.split_whitespace(),
            Cow::Borrowed(data.as_bytes()),
        )
        .unwrap();

        assert_eq!(cows.len(), 4);
        assert_eq!(cows.get(0), Some("hello"));
        assert_eq!(cows.get(1), Some("world"));
        assert_eq!(cows.get(2), Some("foo"));
        assert_eq!(cows.get(3), Some("bar"));
        assert_eq!(cows.get(4), None);
    }

    #[test]
    fn chars_slices_index() {
        let data = "abc def";

        let cows = CharsCowsU64U32::from_iter_and_data(
            data.split_whitespace(),
            Cow::Borrowed(data.as_bytes()),
        )
        .unwrap();

        assert_eq!(&cows[0], "abc");
        assert_eq!(&cows[1], "def");
    }

    #[test]
    fn chars_slices_iterator() {
        let data = "a b c";

        let cows = CharsCowsU64U32::from_iter_and_data(
            data.split_whitespace(),
            Cow::Borrowed(data.as_bytes()),
        )
        .unwrap();

        let result: Vec<&str> = cows.iter().collect();
        assert_eq!(result, vec!["a", "b", "c"]);

        // Test for-loop
        let mut count = 0;
        for s in &cows {
            assert_eq!(s.len(), 1);
            count += 1;
        }
        assert_eq!(count, 3);
    }

    #[test]
    fn chars_slices_arbitrary_order() {
        let data = "0123456789";
        // Create slices in non-sequential order manually
        let s1 = &data[5..7]; // "56"
        let s2 = &data[0..1]; // "0"
        let s3 = &data[9..10]; // "9"
        let s4 = &data[2..5]; // "234"

        let cows =
            CharsCowsU64U32::from_iter_and_data([s1, s2, s3, s4], Cow::Borrowed(data.as_bytes()))
                .unwrap();

        assert_eq!(cows.get(0), Some("56"));
        assert_eq!(cows.get(1), Some("0"));
        assert_eq!(cows.get(2), Some("9"));
        assert_eq!(cows.get(3), Some("234"));
    }

    #[test]
    fn chars_slices_empty_strings() {
        let data = "ab";
        let s1 = &data[0..0]; // empty
        let s2 = &data[1..2]; // "b"
        let s3 = &data[2..2]; // empty

        let cows =
            CharsCowsU64U32::from_iter_and_data([s1, s2, s3], Cow::Borrowed(data.as_bytes()))
                .unwrap();

        assert_eq!(cows.len(), 3);
        assert_eq!(cows.get(0), Some(""));
        assert_eq!(cows.get(1), Some("b"));
        assert_eq!(cows.get(2), Some(""));
    }

    #[test]
    fn chars_slices_overflow_checks() {
        let data_vec = vec![b'x'; 300];
        let data = core::str::from_utf8(&data_vec).unwrap();

        // u8 length overflow - 256 bytes exceeds u8::MAX
        let long_slice = &data[0..256];
        let result = CharsCowsU32U8::from_iter_and_data(
            core::iter::once(long_slice),
            Cow::Borrowed(data.as_bytes()),
        );
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), StringTapeError::OffsetOverflow);

        // Valid with u16 length
        let result = CharsCowsU32U16::from_iter_and_data(
            core::iter::once(long_slice),
            Cow::Borrowed(data.as_bytes()),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn chars_slices_bounds_check() {
        let data = String::from("hello");
        let other_data = String::from("world");

        // Slice from different string - should fail
        let result = CharsCowsU64U32::from_iter_and_data(
            core::iter::once(other_data.as_str()),
            Cow::Borrowed(data.as_bytes()),
        );
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), StringTapeError::IndexOutOfBounds);

        // Valid slice from same string
        let result = CharsCowsU64U32::from_iter_and_data(
            core::iter::once(data.as_str()),
            Cow::Borrowed(data.as_bytes()),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn slices_conversions() {
        let data = "hello world";
        let chars = CharsCowsU32U8::from_iter_and_data(
            data.split_whitespace(),
            Cow::Borrowed(data.as_bytes()),
        )
        .unwrap();

        // CharsCows -> BytesCows
        let bytes: BytesCowsU32U8 = chars.into();
        assert_eq!(bytes.get(0), Some(b"hello" as &[u8]));
        assert_eq!(bytes.get(1), Some(b"world" as &[u8]));

        // N -> CharsCows
        let chars_back: CharsCowsU32U8 = bytes.try_into().unwrap();
        assert_eq!(chars_back.get(0), Some("hello"));
        assert_eq!(chars_back.get(1), Some("world"));
    }

    #[test]
    fn slices_type_aliases() {
        let data = "test";

        let _s1: CharsCowsU32U16 =
            CharsCows::from_iter_and_data(core::iter::once(data), Cow::Borrowed(data.as_bytes()))
                .unwrap();
        let _s2: CharsCowsU32U8 =
            CharsCows::from_iter_and_data(core::iter::once(data), Cow::Borrowed(data.as_bytes()))
                .unwrap();
        let _s3: CharsCowsU16U8 =
            CharsCows::from_iter_and_data(core::iter::once(data), Cow::Borrowed(data.as_bytes()))
                .unwrap();
        let _s4: CharsCowsU64U32 =
            CharsCows::from_iter_and_data(core::iter::once(data), Cow::Borrowed(data.as_bytes()))
                .unwrap();
    }

    #[test]
    fn chars_slices_auto_sorted() {
        let data = "zebra apple banana cherry";
        let mut cows = CharsCowsAuto::from_iter_and_data(
            data.split_whitespace(),
            Cow::Borrowed(data.as_bytes()),
        )
        .unwrap();

        // Sort in-place using standard Rust patterns
        cows.sort();

        let sorted: Vec<&str> = cows.iter().collect();
        assert_eq!(sorted, vec!["apple", "banana", "cherry", "zebra"]);
    }

    #[test]
    fn chars_slices_auto_to_vec_string() {
        let data = "hello world foo";
        let cows = CharsCowsAuto::from_iter_and_data(
            data.split_whitespace(),
            Cow::Borrowed(data.as_bytes()),
        )
        .unwrap();

        // Convert to Vec<String> using iterator
        let vec_string: Vec<String> = cows.iter().map(|s| s.to_string()).collect();

        assert_eq!(vec_string, vec!["hello", "world", "foo"]);
    }

    #[test]
    fn chars_slices_auto_filter_map() {
        let data = "hello world foo bar";
        let cows = CharsCowsAuto::from_iter_and_data(
            data.split_whitespace(),
            Cow::Borrowed(data.as_bytes()),
        )
        .unwrap();

        // Filter and uppercase using iterator - common Vec<String> pattern
        let result: Vec<String> = cows
            .iter()
            .filter_map(|word| {
                if word.len() > 3 {
                    Some(word.to_uppercase())
                } else {
                    None
                }
            })
            .collect();

        assert_eq!(result, vec!["HELLO", "WORLD"]);
    }

    #[test]
    fn chars_slices_auto_type_selection() {
        // Small data -> u32 offset, u8 length
        let small = "hi";
        let s1 = CharsCowsAuto::from_iter_and_data(
            core::iter::once(small),
            Cow::Borrowed(small.as_bytes()),
        )
        .unwrap();
        assert!(matches!(s1, CharsCowsAuto::U32U8(_)));
        assert_eq!(s1.bytes_per_entry(), 5);

        // Long word -> u32 offset, u16 length
        let long_word = "a".repeat(300);
        let s2 = CharsCowsAuto::from_iter_and_data(
            core::iter::once(long_word.as_str()),
            Cow::Borrowed(long_word.as_bytes()),
        )
        .unwrap();
        assert!(matches!(s2, CharsCowsAuto::U32U16(_)));
        assert_eq!(s2.bytes_per_entry(), 6);
    }
}

// ========================
// Examples
// ========================

#[cfg(all(feature = "std", not(test)))]
pub mod examples {
    use super::*;
    use std::env;
    use std::fs;

    pub fn bench_vec_string() -> std::io::Result<()> {
        let path = env::args().nth(1).expect("Usage: bench_vec_string <file>");

        eprintln!("[Vec<String>] Loading file: {}", path);
        let content = fs::read_to_string(&path)?;
        eprintln!("[Vec<String>] File size: {} bytes", content.len());

        eprintln!("[Vec<String>] Collecting words...");
        let words: Vec<String> = content.split_whitespace().map(|s| s.to_string()).collect();

        eprintln!("[Vec<String>] Collected {} words", words.len());

        // Keep alive to measure peak
        std::thread::sleep(std::time::Duration::from_millis(1000));
        Ok(())
    }

    pub fn bench_vec_slice() -> std::io::Result<()> {
        let path = env::args().nth(1).expect("Usage: bench_vec_slice <file>");

        eprintln!("[Vec<&[u8]>] Loading file: {}", path);
        let content = fs::read_to_string(&path)?;
        eprintln!("[Vec<&[u8]>] File size: {} bytes", content.len());

        eprintln!("[Vec<&[u8]>] Collecting words...");
        let words: Vec<&[u8]> = content.split_whitespace().map(|s| s.as_bytes()).collect();

        eprintln!("[Vec<&[u8]>] Collected {} words", words.len());

        // Keep alive to measure peak
        std::thread::sleep(std::time::Duration::from_millis(1000));
        Ok(())
    }

    pub fn bench_chars_slices() -> Result<(), Box<dyn std::error::Error>> {
        let path = env::args()
            .nth(1)
            .expect("Usage: bench_chars_slices <file>");

        eprintln!("[CharsCows] Loading file: {}", path);
        let content = fs::read_to_string(&path)?;
        eprintln!("[CharsCows] File size: {} bytes", content.len());

        eprintln!("[CharsCows] Building CharsCows from words...");
        // Use u64 offset for files >4GB, u32 length for words up to 4GB
        let cows = CharsCowsAuto::from_iter_and_data(
            content.split_whitespace(),
            Cow::Borrowed(content.as_bytes()),
        )?;

        eprintln!("[CharsCows] Collected {} words", cows.len());

        // Keep alive to measure peak
        std::thread::sleep(std::time::Duration::from_millis(1000));
        Ok(())
    }

    pub fn bench_chars_tape() -> Result<(), Box<dyn std::error::Error>> {
        let path = env::args().nth(1).expect("Usage: bench_chars_tape <file>");

        eprintln!("[CharsTape] Loading file: {}", path);
        let content = fs::read_to_string(&path)?;
        eprintln!("[CharsTape] File size: {} bytes", content.len());

        eprintln!("[CharsTape] Building CharsTape from words...");
        // Use from_iter for automatic type selection based on total data size
        let tape = CharsTapeAuto::from_iter(content.split_whitespace());

        eprintln!("[CharsTape] Collected {} words", tape.len());

        // Keep alive to measure peak
        std::thread::sleep(std::time::Duration::from_millis(1000));
        Ok(())
    }
}

// ========================
// Binary entry points
// ========================

#[cfg(all(feature = "std", not(test)))]
#[allow(dead_code)] // Only used when building binaries, not when checking lib
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let exe_path = std::env::current_exe()?;
    let exe_name = exe_path.file_name().and_then(|n| n.to_str()).unwrap_or("");

    match exe_name {
        "bench_vec_string" => examples::bench_vec_string()?,
        "bench_vec_slice" => examples::bench_vec_slice()?,
        "bench_chars_slices" => examples::bench_chars_slices()?,
        "bench_chars_tape" => examples::bench_chars_tape()?,
        _ => {
            eprintln!("Unknown binary: {}", exe_name);
            eprintln!("Available: bench_vec_string, bench_vec_slice, bench_chars_slices, bench_chars_tape");
            std::process::exit(1);
        }
    }

    Ok(())
}