1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
/// Text buffer that uses PieceTree with integrated line tracking
/// Architecture where the tree is the single source of truth for text and line information
use crate::model::encoding;
use crate::model::filesystem::{
FileMetadata, FileSearchCursor, FileSearchOptions, FileSystem, WriteOp,
};
use crate::model::piece_tree::{
BufferData, BufferLocation, Cursor, PieceInfo, PieceRangeIter, PieceTree, PieceView, Position,
StringBuffer, TreeStats,
};
use crate::model::piece_tree_diff::PieceTreeDiff;
use crate::primitives::grapheme;
use anyhow::{Context, Result};
use regex::bytes::Regex;
use std::io::{self, Write};
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::sync::Arc;
// Re-export Encoding for backward compatibility
pub use encoding::Encoding;
/// Error returned when a file save operation requires elevated privileges.
///
/// This error contains all the information needed to perform the save via sudo
/// in a single operation, preserving original file ownership and permissions.
#[derive(Debug, Clone, PartialEq)]
pub struct SudoSaveRequired {
/// Path to the temporary file containing the new content
pub temp_path: PathBuf,
/// Destination path where the file should be saved
pub dest_path: PathBuf,
/// Original file owner (UID)
pub uid: u32,
/// Original file group (GID)
pub gid: u32,
/// Original file permissions (mode)
pub mode: u32,
}
impl std::fmt::Display for SudoSaveRequired {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Permission denied saving to {}. Use sudo to complete the operation.",
self.dest_path.display()
)
}
}
impl std::error::Error for SudoSaveRequired {}
/// Error returned when a large file has a non-resynchronizable encoding
/// and requires user confirmation before loading the entire file into memory.
///
/// Non-resynchronizable encodings (like Shift-JIS, GB18030, GBK, EUC-KR) cannot
/// determine character boundaries when jumping into the middle of a file.
/// This means the entire file must be loaded and decoded sequentially.
#[derive(Debug, Clone, PartialEq)]
pub struct LargeFileEncodingConfirmation {
/// Path to the file
pub path: PathBuf,
/// Size of the file in bytes
pub file_size: usize,
/// The detected encoding that requires full loading
pub encoding: Encoding,
}
impl std::fmt::Display for LargeFileEncodingConfirmation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let size_mb = self.file_size as f64 / (1024.0 * 1024.0);
write!(
f,
"{} ({:.0} MB) requires full load. (l)oad, (e)ncoding, (C)ancel? ",
self.encoding.display_name(),
size_mb
)
}
}
impl std::error::Error for LargeFileEncodingConfirmation {}
/// A work item for incremental line-feed scanning (one per leaf).
#[derive(Debug, Clone)]
pub struct LineScanChunk {
/// Index of the leaf in the piece tree's leaf array.
pub leaf_index: usize,
/// Number of bytes in this leaf.
pub byte_len: usize,
/// True if the leaf already had a known line_feed_cnt (no I/O needed).
pub already_known: bool,
}
// Re-export SearchMatch from filesystem — same type is used by both
// FileSystem::search_file (project grep on disk) and the piece-tree
// search below (in-editor Ctrl+F and dirty buffers).
pub use crate::model::filesystem::SearchMatch;
/// Mutable state for an incremental chunked search over a TextBuffer's
/// piece tree. This is the in-editor search path — it reads chunks via
/// `get_text_range_mut` which loads lazily from disk and works with the
/// piece tree's edit history.
///
/// For searching files on disk (project-wide grep), see
/// `FileSystem::search_file` which uses `read_range` and doesn't need
/// a TextBuffer at all.
///
/// Created by `TextBuffer::search_scan_init`, advanced by
/// `TextBuffer::search_scan_next_chunk`. The same struct is used by
/// both the Editor's incremental (non-blocking) search and the project-
/// wide search running inside `spawn_blocking`.
#[derive(Debug)]
pub struct ChunkedSearchState {
/// One work item per piece-tree leaf (after `prepare_line_scan` splits).
pub chunks: Vec<LineScanChunk>,
/// Index of the next chunk to process.
pub next_chunk: usize,
/// Running document byte offset for the next chunk.
pub next_doc_offset: usize,
/// Total bytes in the buffer.
pub total_bytes: usize,
/// Bytes scanned so far (for progress reporting).
pub scanned_bytes: usize,
/// Compiled regex for searching.
pub regex: regex::bytes::Regex,
/// Accumulated match results with line/column/context.
pub matches: Vec<SearchMatch>,
/// Tail bytes from the previous chunk for cross-boundary matching.
pub overlap_tail: Vec<u8>,
/// Byte offset of the overlap_tail's first byte in the document.
pub overlap_doc_offset: usize,
/// Maximum number of matches before capping.
pub max_matches: usize,
/// Whether the match count was capped.
pub capped: bool,
/// Length of the original query string (for overlap sizing).
pub query_len: usize,
/// 1-based line number at the start of the next non-overlap data.
/// Advanced incrementally as chunks are processed.
pub(crate) running_line: usize,
}
impl ChunkedSearchState {
/// Returns true if the scan is complete (all chunks processed or capped).
pub fn is_done(&self) -> bool {
self.next_chunk >= self.chunks.len() || self.capped
}
/// Progress as a percentage (0–100).
pub fn progress_percent(&self) -> usize {
if self.total_bytes > 0 {
(self.scanned_bytes * 100) / self.total_bytes
} else {
100
}
}
}
// Large file support configuration
/// Default threshold for considering a file "large" (100 MB)
pub const DEFAULT_LARGE_FILE_THRESHOLD: usize = 100 * 1024 * 1024;
/// Chunk size to load when lazy loading (1 MB)
pub const LOAD_CHUNK_SIZE: usize = 1024 * 1024;
/// Chunk alignment for lazy loading (64 KB)
pub const CHUNK_ALIGNMENT: usize = 64 * 1024;
/// Configuration passed to TextBuffer constructors.
#[derive(Debug, Clone)]
pub struct BufferConfig {
/// Estimated average line length in bytes. Used for approximate line number
/// display in large files and for goto-line byte offset estimation.
pub estimated_line_length: usize,
}
impl Default for BufferConfig {
fn default() -> Self {
Self {
estimated_line_length: 80,
}
}
}
/// Line ending format used in the file
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineEnding {
/// Unix/Linux/Mac format (\n)
#[default]
LF,
/// Windows format (\r\n)
CRLF,
/// Old Mac format (\r) - rare but supported
CR,
}
impl LineEnding {
/// Get the string representation of this line ending
pub fn as_str(&self) -> &'static str {
match self {
Self::LF => "\n",
Self::CRLF => "\r\n",
Self::CR => "\r",
}
}
/// Get the display name for status bar
pub fn display_name(&self) -> &'static str {
match self {
Self::LF => "LF",
Self::CRLF => "CRLF",
Self::CR => "CR",
}
}
}
/// A write recipe built from the piece tree for saving
struct WriteRecipe {
/// The source file path for Copy operations (if any)
src_path: Option<PathBuf>,
/// Data chunks for Insert operations (owned to avoid lifetime issues)
insert_data: Vec<Vec<u8>>,
/// Sequence of actions to build the output file
actions: Vec<RecipeAction>,
}
/// An action in a write recipe
#[derive(Debug, Clone, Copy)]
enum RecipeAction {
/// Copy bytes from source file at offset
Copy { offset: u64, len: u64 },
/// Insert data from insert_data[index]
Insert { index: usize },
}
impl WriteRecipe {
/// Convert the recipe to WriteOp slice for use with filesystem write_patched
fn to_write_ops(&self) -> Vec<WriteOp<'_>> {
self.actions
.iter()
.map(|action| match action {
RecipeAction::Copy { offset, len } => WriteOp::Copy {
offset: *offset,
len: *len,
},
RecipeAction::Insert { index } => WriteOp::Insert {
data: &self.insert_data[*index],
},
})
.collect()
}
/// Check if this recipe has any Copy operations
fn has_copy_ops(&self) -> bool {
self.actions
.iter()
.any(|a| matches!(a, RecipeAction::Copy { .. }))
}
/// Flatten all Insert operations into a single buffer.
/// Only valid when has_copy_ops() returns false.
fn flatten_inserts(&self) -> Vec<u8> {
let mut result = Vec::new();
for action in &self.actions {
if let RecipeAction::Insert { index } = action {
result.extend_from_slice(&self.insert_data[*index]);
}
}
result
}
}
/// Represents a line number (simplified for new implementation)
/// Legacy enum kept for backwards compatibility - always Absolute now
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineNumber {
/// Absolute line number - this is the actual line number in the file
Absolute(usize),
/// Relative line number (deprecated - now same as Absolute)
Relative {
line: usize,
from_cached_line: usize,
},
}
impl LineNumber {
/// Get the line number value
pub fn value(&self) -> usize {
match self {
Self::Absolute(line) | Self::Relative { line, .. } => *line,
}
}
/// Check if this is an absolute line number
pub fn is_absolute(&self) -> bool {
matches!(self, LineNumber::Absolute(_))
}
/// Check if this is a relative line number
pub fn is_relative(&self) -> bool {
matches!(self, LineNumber::Relative { .. })
}
/// Format the line number for display
pub fn format(&self) -> String {
match self {
Self::Absolute(line) => format!("{}", line + 1),
Self::Relative { line, .. } => format!("~{}", line + 1),
}
}
}
/// A text buffer that manages document content using a piece table
/// with integrated line tracking
pub struct TextBuffer {
/// Filesystem abstraction for file I/O operations.
/// Stored internally so methods can access it without threading through call chains.
fs: Arc<dyn FileSystem + Send + Sync>,
/// The piece tree for efficient text manipulation with integrated line tracking
piece_tree: PieceTree,
/// Snapshot of the piece tree root at last save (shared via Arc)
saved_root: Arc<crate::model::piece_tree::PieceTreeNode>,
/// List of string buffers containing chunks of text data
/// Index 0 is typically the original/stored buffer
/// Additional buffers are added for modifications
buffers: Vec<StringBuffer>,
/// Next buffer ID to assign
next_buffer_id: usize,
/// Optional file path for persistence
file_path: Option<PathBuf>,
/// Has the buffer been modified since last save?
modified: bool,
/// Does the buffer have unsaved changes for recovery auto-save?
/// This is separate from `modified` because recovery auto-save doesn't
/// clear `modified` (buffer still differs from on-disk file).
recovery_pending: bool,
/// Is this a large file (no line indexing, lazy loading enabled)?
large_file: bool,
/// Has a line feed scan been performed on this large file?
/// When true, piece tree leaves have accurate `line_feed_cnt` values,
/// and edits will ensure the relevant chunk is loaded before splitting
/// so that `compute_line_feeds_static` can recount accurately.
line_feeds_scanned: bool,
/// Is this a binary file? Binary files are opened read-only and render
/// unprintable characters as code points.
is_binary: bool,
/// Line ending format detected from the file (or default for new files)
line_ending: LineEnding,
/// Original line ending format when file was loaded (used for conversion on save)
/// This tracks what the file had when loaded, so we can detect if the user
/// changed the line ending format and needs conversion on save.
original_line_ending: LineEnding,
/// Text encoding format detected from the file (or default for new files)
encoding: Encoding,
/// Original encoding when file was loaded (used for conversion on save)
/// Similar to original_line_ending, tracks what the file had when loaded.
original_encoding: Encoding,
/// The file size on disk after the last save.
/// Used for chunked recovery to know the original file size for reconstruction.
/// Updated when loading from file or after saving.
saved_file_size: Option<usize>,
/// Monotonic version counter for change tracking.
version: u64,
/// Buffer configuration (estimated line length, etc.)
config: BufferConfig,
}
/// Snapshot of a TextBuffer's piece tree and associated string buffers.
///
/// Used by BulkEdit undo/redo to capture the complete buffer state.
/// Without this, consolidate_after_save() would destroy the string buffers
/// that a BulkEdit's piece tree snapshot references, causing corruption on undo.
#[derive(Debug, Clone)]
pub struct BufferSnapshot {
pub piece_tree: PieceTree,
pub buffers: Vec<StringBuffer>,
pub next_buffer_id: usize,
}
impl TextBuffer {
/// Create a new text buffer with the given filesystem implementation.
/// Note: large_file_threshold is ignored in the new implementation
pub fn new(_large_file_threshold: usize, fs: Arc<dyn FileSystem + Send + Sync>) -> Self {
let piece_tree = PieceTree::empty();
let line_ending = LineEnding::default();
let encoding = Encoding::default();
TextBuffer {
fs,
saved_root: piece_tree.root(),
piece_tree,
buffers: vec![StringBuffer::new(0, Vec::new())],
next_buffer_id: 1,
file_path: None,
modified: false,
recovery_pending: false,
large_file: false,
line_feeds_scanned: false,
is_binary: false,
line_ending,
original_line_ending: line_ending,
encoding,
original_encoding: encoding,
saved_file_size: None,
version: 0,
config: BufferConfig::default(),
}
}
/// Create an empty buffer associated with a file path.
/// Used for files that don't exist yet — the path is set so saving will create the file.
pub fn new_with_path(
large_file_threshold: usize,
fs: Arc<dyn FileSystem + Send + Sync>,
path: PathBuf,
) -> Self {
let mut buffer = Self::new(large_file_threshold, fs);
buffer.file_path = Some(path);
buffer
}
/// Current buffer version (monotonic, wraps on overflow)
pub fn version(&self) -> u64 {
self.version
}
/// Get a reference to the filesystem implementation used by this buffer.
pub fn filesystem(&self) -> &Arc<dyn FileSystem + Send + Sync> {
&self.fs
}
/// Set the filesystem implementation for this buffer.
pub fn set_filesystem(&mut self, fs: Arc<dyn FileSystem + Send + Sync>) {
self.fs = fs;
}
#[inline]
fn bump_version(&mut self) {
self.version = self.version.wrapping_add(1);
}
#[inline]
fn mark_content_modified(&mut self) {
self.modified = true;
self.recovery_pending = true;
self.bump_version();
}
/// Create a text buffer from raw bytes WITHOUT encoding conversion.
/// Used for binary files where we want to preserve the exact bytes.
fn from_bytes_raw(content: Vec<u8>, fs: Arc<dyn FileSystem + Send + Sync>) -> Self {
let bytes = content.len();
// For binary files, detect line ending but don't convert encoding
let line_ending = Self::detect_line_ending(&content);
// Create initial StringBuffer with ID 0
let buffer = StringBuffer::new(0, content);
let line_feed_cnt = buffer.line_feed_count();
let piece_tree = if bytes > 0 {
PieceTree::new(BufferLocation::Stored(0), 0, bytes, line_feed_cnt)
} else {
PieceTree::empty()
};
let saved_root = piece_tree.root();
TextBuffer {
fs,
line_ending,
original_line_ending: line_ending,
encoding: Encoding::Utf8, // Binary files treated as raw bytes (no conversion)
original_encoding: Encoding::Utf8,
piece_tree,
saved_root,
buffers: vec![buffer],
next_buffer_id: 1,
file_path: None,
modified: false,
recovery_pending: false,
large_file: false,
line_feeds_scanned: false,
is_binary: true,
saved_file_size: Some(bytes),
version: 0,
config: BufferConfig::default(),
}
}
/// Create a text buffer from initial content with the given filesystem.
pub fn from_bytes(content: Vec<u8>, fs: Arc<dyn FileSystem + Send + Sync>) -> Self {
// Auto-detect encoding and convert to UTF-8 if needed
let (encoding, utf8_content) = Self::detect_and_convert_encoding(&content);
let bytes = utf8_content.len();
// Auto-detect line ending format from content
let line_ending = Self::detect_line_ending(&utf8_content);
// Create initial StringBuffer with ID 0
let buffer = StringBuffer::new(0, utf8_content);
let line_feed_cnt = buffer.line_feed_count();
let piece_tree = if bytes > 0 {
PieceTree::new(BufferLocation::Stored(0), 0, bytes, line_feed_cnt)
} else {
PieceTree::empty()
};
let saved_root = piece_tree.root();
TextBuffer {
fs,
line_ending,
original_line_ending: line_ending,
encoding,
original_encoding: encoding,
piece_tree,
saved_root,
buffers: vec![buffer],
next_buffer_id: 1,
file_path: None,
modified: false,
recovery_pending: false,
large_file: false,
line_feeds_scanned: false,
is_binary: false,
saved_file_size: Some(bytes), // Treat initial content as "saved" state
version: 0,
config: BufferConfig::default(),
}
}
/// Create a text buffer from bytes with a specific encoding (no auto-detection).
pub fn from_bytes_with_encoding(
content: Vec<u8>,
encoding: Encoding,
fs: Arc<dyn FileSystem + Send + Sync>,
) -> Self {
// Convert from specified encoding to UTF-8
let utf8_content = encoding::convert_to_utf8(&content, encoding);
let bytes = utf8_content.len();
// Auto-detect line ending format from content
let line_ending = Self::detect_line_ending(&utf8_content);
// Create initial StringBuffer with ID 0
let buffer = StringBuffer::new(0, utf8_content);
let line_feed_cnt = buffer.line_feed_count();
let piece_tree = if bytes > 0 {
PieceTree::new(BufferLocation::Stored(0), 0, bytes, line_feed_cnt)
} else {
PieceTree::empty()
};
let saved_root = piece_tree.root();
TextBuffer {
fs,
line_ending,
original_line_ending: line_ending,
encoding,
original_encoding: encoding,
piece_tree,
saved_root,
buffers: vec![buffer],
next_buffer_id: 1,
file_path: None,
modified: false,
recovery_pending: false,
large_file: false,
line_feeds_scanned: false,
is_binary: false,
saved_file_size: Some(bytes),
version: 0,
config: BufferConfig::default(),
}
}
/// Create a text buffer from a string with the given filesystem.
pub fn from_str(
s: &str,
_large_file_threshold: usize,
fs: Arc<dyn FileSystem + Send + Sync>,
) -> Self {
Self::from_bytes(s.as_bytes().to_vec(), fs)
}
/// Create an empty text buffer with the given filesystem.
pub fn empty(fs: Arc<dyn FileSystem + Send + Sync>) -> Self {
let piece_tree = PieceTree::empty();
let saved_root = piece_tree.root();
let line_ending = LineEnding::default();
let encoding = Encoding::default();
TextBuffer {
fs,
piece_tree,
saved_root,
buffers: vec![StringBuffer::new(0, Vec::new())],
next_buffer_id: 1,
file_path: None,
modified: false,
recovery_pending: false,
large_file: false,
line_feeds_scanned: false,
is_binary: false,
line_ending,
original_line_ending: line_ending,
encoding,
original_encoding: encoding,
saved_file_size: None,
version: 0,
config: BufferConfig::default(),
}
}
/// Load a text buffer from a file using the given filesystem.
pub fn load_from_file<P: AsRef<Path>>(
path: P,
large_file_threshold: usize,
fs: Arc<dyn FileSystem + Send + Sync>,
) -> anyhow::Result<Self> {
let path = path.as_ref();
// Get file size to determine loading strategy
let metadata = fs.metadata(path)?;
let file_size = metadata.size as usize;
// Use threshold parameter or default
let threshold = if large_file_threshold > 0 {
large_file_threshold
} else {
DEFAULT_LARGE_FILE_THRESHOLD
};
// Choose loading strategy based on file size
if file_size >= threshold {
Self::load_large_file(path, file_size, fs)
} else {
Self::load_small_file(path, fs)
}
}
/// Load a text buffer from a file with a specific encoding (no auto-detection).
pub fn load_from_file_with_encoding<P: AsRef<Path>>(
path: P,
encoding: Encoding,
fs: Arc<dyn FileSystem + Send + Sync>,
config: BufferConfig,
) -> anyhow::Result<Self> {
let path = path.as_ref();
let contents = fs.read_file(path)?;
let mut buffer = Self::from_bytes_with_encoding(contents, encoding, fs);
buffer.file_path = Some(path.to_path_buf());
buffer.modified = false;
buffer.config = config;
Ok(buffer)
}
/// Load a small file with full eager loading and line indexing
fn load_small_file(path: &Path, fs: Arc<dyn FileSystem + Send + Sync>) -> anyhow::Result<Self> {
let contents = fs.read_file(path)?;
// Use unified encoding/binary detection
let (encoding, is_binary) = Self::detect_encoding_or_binary(&contents, false);
// For binary files, skip encoding conversion to preserve raw bytes
let mut buffer = if is_binary {
Self::from_bytes_raw(contents, fs)
} else {
// from_bytes handles encoding detection/conversion and line ending detection
Self::from_bytes(contents, fs)
};
buffer.file_path = Some(path.to_path_buf());
buffer.modified = false;
buffer.large_file = false;
buffer.is_binary = is_binary;
// For binary files, ensure encoding matches detection
if is_binary {
buffer.encoding = encoding;
buffer.original_encoding = encoding;
}
// Note: line_ending and encoding are already set by from_bytes/from_bytes_raw
Ok(buffer)
}
/// Check if loading a large file requires user confirmation due to encoding.
///
/// Some encodings (like Shift-JIS, GB18030, GBK, EUC-KR) cannot be "resynchronized" -
/// meaning you cannot determine character boundaries when jumping into the middle
/// of a file. These encodings require loading the entire file into memory.
///
/// Returns `Some(confirmation)` if user confirmation is needed, `None` if the file
/// can be loaded with lazy/streaming loading.
pub fn check_large_file_encoding(
path: impl AsRef<Path>,
fs: Arc<dyn FileSystem + Send + Sync>,
) -> anyhow::Result<Option<LargeFileEncodingConfirmation>> {
let path = path.as_ref();
let metadata = fs.metadata(path)?;
let file_size = metadata.size as usize;
// Only check for large files
if file_size < DEFAULT_LARGE_FILE_THRESHOLD {
return Ok(None);
}
// Read a sample to detect encoding
let sample_size = file_size.min(8 * 1024);
let sample = fs.read_range(path, 0, sample_size)?;
let (encoding, is_binary) =
Self::detect_encoding_or_binary(&sample, file_size > sample_size);
// Binary files don't need confirmation (loaded as-is)
if is_binary {
return Ok(None);
}
// Check if the encoding requires full file loading
if encoding.requires_full_file_load() {
return Ok(Some(LargeFileEncodingConfirmation {
path: path.to_path_buf(),
file_size,
encoding,
}));
}
Ok(None)
}
/// Load a large file with unloaded buffer (no line indexing, lazy loading)
///
/// If `force_full_load` is true, loads the entire file regardless of encoding.
/// This should be set to true after user confirms loading a non-resynchronizable encoding.
fn load_large_file(
path: &Path,
file_size: usize,
fs: Arc<dyn FileSystem + Send + Sync>,
) -> anyhow::Result<Self> {
Self::load_large_file_internal(path, file_size, fs, false)
}
/// Load a large file, optionally forcing full load for non-resynchronizable encodings.
///
/// Called with `force_full_load=true` after user confirms the warning about
/// non-resynchronizable encodings requiring full file loading.
pub fn load_large_file_confirmed(
path: impl AsRef<Path>,
fs: Arc<dyn FileSystem + Send + Sync>,
) -> anyhow::Result<Self> {
let path = path.as_ref();
let metadata = fs.metadata(path)?;
let file_size = metadata.size as usize;
Self::load_large_file_internal(path, file_size, fs, true)
}
/// Internal implementation for loading large files.
fn load_large_file_internal(
path: &Path,
file_size: usize,
fs: Arc<dyn FileSystem + Send + Sync>,
force_full_load: bool,
) -> anyhow::Result<Self> {
use crate::model::piece_tree::{BufferData, BufferLocation};
// Read a sample of the file to detect encoding and whether it's binary
// We read the first 8KB for detection
let sample_size = file_size.min(8 * 1024);
let sample = fs.read_range(path, 0, sample_size)?;
// Use unified encoding/binary detection
let (encoding, is_binary) =
Self::detect_encoding_or_binary(&sample, file_size > sample_size);
// Binary files skip encoding conversion to preserve raw bytes
if is_binary {
tracing::info!("Large binary file detected, loading without encoding conversion");
let contents = fs.read_file(path)?;
let mut buffer = Self::from_bytes_raw(contents, fs);
buffer.file_path = Some(path.to_path_buf());
buffer.modified = false;
buffer.large_file = true;
buffer.encoding = encoding;
buffer.original_encoding = encoding;
return Ok(buffer);
}
// Check if encoding requires full file loading
let requires_full_load = encoding.requires_full_file_load();
// For non-resynchronizable encodings, require confirmation unless forced
if requires_full_load && !force_full_load {
anyhow::bail!(LargeFileEncodingConfirmation {
path: path.to_path_buf(),
file_size,
encoding,
});
}
// For encodings that require full load (non-resynchronizable or non-UTF-8),
// load the entire file and convert
if !matches!(encoding, Encoding::Utf8 | Encoding::Ascii) {
tracing::info!(
"Large file with non-UTF-8 encoding ({:?}), loading fully for conversion",
encoding
);
let contents = fs.read_file(path)?;
let mut buffer = Self::from_bytes(contents, fs);
buffer.file_path = Some(path.to_path_buf());
buffer.modified = false;
buffer.large_file = true; // Still mark as large file for UI purposes
buffer.is_binary = is_binary;
return Ok(buffer);
}
// UTF-8/ASCII files can use lazy loading
let line_ending = Self::detect_line_ending(&sample);
// Create an unloaded buffer that references the entire file
let buffer = StringBuffer {
id: 0,
data: BufferData::Unloaded {
file_path: path.to_path_buf(),
file_offset: 0,
bytes: file_size,
},
stored_file_offset: None,
};
// Create piece tree with a single piece covering the whole file
// No line feed count (None) since we're not computing line indexing
let piece_tree = if file_size > 0 {
PieceTree::new(BufferLocation::Stored(0), 0, file_size, None)
} else {
PieceTree::empty()
};
let saved_root = piece_tree.root();
tracing::debug!(
"Buffer::load_from_file: loaded {} bytes, saved_file_size={}",
file_size,
file_size
);
Ok(TextBuffer {
fs,
piece_tree,
saved_root,
buffers: vec![buffer],
next_buffer_id: 1,
file_path: Some(path.to_path_buf()),
modified: false,
recovery_pending: false,
large_file: true,
line_feeds_scanned: false,
is_binary,
line_ending,
original_line_ending: line_ending,
encoding,
original_encoding: encoding,
saved_file_size: Some(file_size),
version: 0,
config: BufferConfig::default(),
})
}
/// Save the buffer to its associated file
pub fn save(&mut self) -> anyhow::Result<()> {
if let Some(path) = &self.file_path {
self.save_to_file(path.clone())
} else {
anyhow::bail!(io::Error::new(
io::ErrorKind::NotFound,
"No file path associated with buffer",
))
}
}
/// Check if we should use in-place writing to preserve file ownership.
/// Returns true if the file exists and is owned by a different user.
/// On Unix, only root or the file owner can change file ownership with chown.
/// When the current user is not the file owner, using atomic write (temp file + rename)
/// would change the file's ownership to the current user. To preserve ownership,
/// we must write directly to the existing file instead.
fn should_use_inplace_write(&self, dest_path: &Path) -> bool {
!self.fs.is_owner(dest_path)
}
/// Build a write recipe from the piece tree for saving.
///
/// This creates a recipe of Copy and Insert operations that can reconstruct
/// the buffer content. Copy operations reference unchanged regions in the
/// source file, while Insert operations contain new/modified data.
///
/// # Returns
/// A WriteRecipe with the source path, insert data, and sequence of actions.
fn build_write_recipe(&self) -> io::Result<WriteRecipe> {
let total = self.total_bytes();
// Determine the source file for Copy operations (if any)
// We can only use Copy if:
// 1. We have a source file path
// 2. The source file exists
// 3. No line ending conversion is needed
// 4. No encoding conversion is needed
let needs_line_ending_conversion = self.line_ending != self.original_line_ending;
// We need encoding conversion if:
// - NOT a binary file (binary files preserve raw bytes), AND
// - Either the encoding changed from the original, OR
// - The target encoding isn't plain UTF-8/ASCII (since internal storage is UTF-8)
// For example: UTF-8 BOM files are stored as UTF-8, so we need to add BOM on save
let needs_encoding_conversion = !self.is_binary
&& (self.encoding != self.original_encoding
|| !matches!(self.encoding, Encoding::Utf8 | Encoding::Ascii));
let needs_conversion = needs_line_ending_conversion || needs_encoding_conversion;
let src_path_for_copy: Option<&Path> = if needs_conversion {
None
} else {
self.file_path.as_deref().filter(|p| self.fs.exists(p))
};
let target_ending = self.line_ending;
let target_encoding = self.encoding;
let mut insert_data: Vec<Vec<u8>> = Vec::new();
let mut actions: Vec<RecipeAction> = Vec::new();
// Add BOM as the first piece if the target encoding has one
if let Some(bom) = target_encoding.bom_bytes() {
insert_data.push(bom.to_vec());
actions.push(RecipeAction::Insert { index: 0 });
}
for piece_view in self.piece_tree.iter_pieces_in_range(0, total) {
let buffer_id = piece_view.location.buffer_id();
let buffer = self.buffers.get(buffer_id).ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Buffer {} not found", buffer_id),
)
})?;
match &buffer.data {
// Unloaded buffer: can use Copy if same source file, else load and send
BufferData::Unloaded {
file_path,
file_offset,
..
} => {
// Can only use Copy if:
// - This is a Stored piece (original file content)
// - We have a valid source for copying
// - This buffer is from that source
// - No line ending or encoding conversion needed
let can_copy = matches!(piece_view.location, BufferLocation::Stored(_))
&& src_path_for_copy.is_some_and(|src| file_path == src);
if can_copy {
let src_offset = (*file_offset + piece_view.buffer_offset) as u64;
actions.push(RecipeAction::Copy {
offset: src_offset,
len: piece_view.bytes as u64,
});
continue;
}
// Need to load and send this unloaded region
// This happens when: different source file, or conversion needed
let data = self.fs.read_range(
file_path,
(*file_offset + piece_view.buffer_offset) as u64,
piece_view.bytes,
)?;
let data = if needs_line_ending_conversion {
Self::convert_line_endings_to(&data, target_ending)
} else {
data
};
// Convert encoding if needed
let data = if needs_encoding_conversion {
Self::convert_to_encoding(&data, target_encoding)
} else {
data
};
let index = insert_data.len();
insert_data.push(data);
actions.push(RecipeAction::Insert { index });
}
// Loaded data: send as Insert
BufferData::Loaded { data, .. } => {
let start = piece_view.buffer_offset;
let end = start + piece_view.bytes;
let chunk = &data[start..end];
let chunk = if needs_line_ending_conversion {
Self::convert_line_endings_to(chunk, target_ending)
} else {
chunk.to_vec()
};
// Convert encoding if needed
let chunk = if needs_encoding_conversion {
Self::convert_to_encoding(&chunk, target_encoding)
} else {
chunk
};
let index = insert_data.len();
insert_data.push(chunk);
actions.push(RecipeAction::Insert { index });
}
}
}
Ok(WriteRecipe {
src_path: src_path_for_copy.map(|p| p.to_path_buf()),
insert_data,
actions,
})
}
/// Create a temporary file for saving.
///
/// Tries to create the file in the same directory as the destination file first
/// to allow for an atomic rename. If that fails (e.g., due to directory permissions),
/// falls back to the system temporary directory.
fn create_temp_file(
&self,
dest_path: &Path,
) -> io::Result<(PathBuf, Box<dyn crate::model::filesystem::FileWriter>)> {
// Try creating in same directory first
let same_dir_temp = self.fs.temp_path_for(dest_path);
match self.fs.create_file(&same_dir_temp) {
Ok(file) => Ok((same_dir_temp, file)),
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
// Fallback to system temp directory
let temp_path = self.fs.unique_temp_path(dest_path);
let file = self.fs.create_file(&temp_path)?;
Ok((temp_path, file))
}
Err(e) => Err(e),
}
}
/// Create a temporary file in the recovery directory for in-place writes.
/// This allows recovery if a crash occurs during the in-place write operation.
fn create_recovery_temp_file(
&self,
dest_path: &Path,
) -> io::Result<(PathBuf, Box<dyn crate::model::filesystem::FileWriter>)> {
// Get recovery directory: $XDG_DATA_HOME/fresh/recovery or ~/.local/share/fresh/recovery
let recovery_dir = crate::input::input_history::get_data_dir()
.map(|d| d.join("recovery"))
.unwrap_or_else(|_| std::env::temp_dir());
// Ensure directory exists
self.fs.create_dir_all(&recovery_dir)?;
// Create unique filename based on destination file and timestamp
let file_name = dest_path
.file_name()
.unwrap_or_else(|| std::ffi::OsStr::new("fresh-save"));
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let pid = std::process::id();
let temp_name = format!(
".inplace-{}-{}-{}.tmp",
file_name.to_string_lossy(),
pid,
timestamp
);
let temp_path = recovery_dir.join(temp_name);
let file = self.fs.create_file(&temp_path)?;
Ok((temp_path, file))
}
/// Get the path for in-place write recovery metadata.
/// Uses the same recovery directory as temp files.
fn inplace_recovery_meta_path(&self, dest_path: &Path) -> PathBuf {
let recovery_dir = crate::input::input_history::get_data_dir()
.map(|d| d.join("recovery"))
.unwrap_or_else(|_| std::env::temp_dir());
let hash = crate::services::recovery::path_hash(dest_path);
recovery_dir.join(format!("{}.inplace.json", hash))
}
/// Write in-place recovery metadata using self.fs.
/// This is called before the dangerous streaming step so we can recover on crash.
fn write_inplace_recovery_meta(
&self,
meta_path: &Path,
dest_path: &Path,
temp_path: &Path,
original_metadata: &Option<FileMetadata>,
) -> io::Result<()> {
#[cfg(unix)]
let (uid, gid, mode) = original_metadata
.as_ref()
.map(|m| {
(
m.uid.unwrap_or(0),
m.gid.unwrap_or(0),
m.permissions.as_ref().map(|p| p.mode()).unwrap_or(0o644),
)
})
.unwrap_or((0, 0, 0o644));
#[cfg(not(unix))]
let (uid, gid, mode) = (0u32, 0u32, 0o644u32);
let recovery = crate::services::recovery::InplaceWriteRecovery::new(
dest_path.to_path_buf(),
temp_path.to_path_buf(),
uid,
gid,
mode,
);
let json = serde_json::to_string_pretty(&recovery)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
self.fs.write_file(meta_path, json.as_bytes())
}
/// Save the buffer to a specific file
///
/// Uses the write recipe approach for both local and remote filesystems:
/// - Copy ops reference unchanged regions in the source file
/// - Insert ops contain new/modified data
///
/// For remote filesystems, the recipe is sent to the agent which reconstructs
/// the file server-side, avoiding transfer of unchanged content.
///
/// For local filesystems with ownership concerns (file owned by another user),
/// uses in-place writing to preserve ownership. Otherwise uses atomic writes.
///
/// If the line ending format has been changed (via set_line_ending), all content
/// will be converted to the new format during save.
pub fn save_to_file<P: AsRef<Path>>(&mut self, path: P) -> anyhow::Result<()> {
let dest_path = path.as_ref();
let total = self.total_bytes();
// Handle empty files
if total == 0 {
self.fs.write_file(dest_path, &[])?;
self.finalize_save(dest_path)?;
return Ok(());
}
// Build the write recipe (unified for all filesystem types)
let recipe = self.build_write_recipe()?;
let ops = recipe.to_write_ops();
// Check if we need in-place writing to preserve file ownership (local only)
// Remote filesystems handle this differently
let is_local = self.fs.remote_connection_info().is_none();
let use_inplace = is_local && self.should_use_inplace_write(dest_path);
if use_inplace {
// In-place write: write directly to preserve ownership
self.save_with_inplace_write(dest_path, &recipe)?;
} else if !recipe.has_copy_ops() && !is_local {
// Remote with no Copy ops: use write_file directly (more efficient)
let data = recipe.flatten_inserts();
self.fs.write_file(dest_path, &data)?;
} else if is_local {
// Local: use write_file or write_patched with sudo fallback
let write_result = if !recipe.has_copy_ops() {
let data = recipe.flatten_inserts();
self.fs.write_file(dest_path, &data)
} else {
let src_for_patch = recipe.src_path.as_deref().unwrap_or(dest_path);
self.fs.write_patched(src_for_patch, dest_path, &ops)
};
if let Err(e) = write_result {
if e.kind() == io::ErrorKind::PermissionDenied {
// Create temp file and return sudo error
let original_metadata = self.fs.metadata_if_exists(dest_path);
let (temp_path, mut temp_file) = self.create_temp_file(dest_path)?;
self.write_recipe_to_file(&mut temp_file, &recipe)?;
temp_file.sync_all()?;
drop(temp_file);
return Err(self.make_sudo_error(temp_path, dest_path, original_metadata));
}
return Err(e.into());
}
} else {
// Remote with Copy ops: use write_patched
let src_for_patch = recipe.src_path.as_deref().unwrap_or(dest_path);
self.fs.write_patched(src_for_patch, dest_path, &ops)?;
}
self.finalize_save(dest_path)?;
Ok(())
}
/// Write using in-place mode to preserve file ownership.
///
/// This is used when the file is owned by a different user and we need
/// to write directly to the existing file to preserve its ownership.
///
/// The approach:
/// 1. Write the recipe to a temp file first (reads from original, writes to temp)
/// 2. Stream the temp file content to the destination file (truncates and writes)
/// 3. Delete the temp file
///
/// This avoids the bug where truncating the destination before reading Copy chunks
/// would corrupt the file. It also works for huge files since we stream in chunks.
fn save_with_inplace_write(
&self,
dest_path: &Path,
recipe: &WriteRecipe,
) -> anyhow::Result<()> {
let original_metadata = self.fs.metadata_if_exists(dest_path);
// Optimization: if no Copy ops, we can write directly without a temp file
// (same as the non-inplace path for small files)
if !recipe.has_copy_ops() {
let data = recipe.flatten_inserts();
return self.write_data_inplace(dest_path, &data, original_metadata);
}
// Step 1: Write recipe to a temp file in the recovery directory
// This reads Copy chunks from the original file (still intact) and writes to temp.
// Using the recovery directory allows crash recovery if the operation fails.
let (temp_path, mut temp_file) = self.create_recovery_temp_file(dest_path)?;
if let Err(e) = self.write_recipe_to_file(&mut temp_file, recipe) {
// Best-effort cleanup of temp file on write failure
#[allow(clippy::let_underscore_must_use)]
let _ = self.fs.remove_file(&temp_path);
return Err(e.into());
}
temp_file.sync_all()?;
drop(temp_file);
// Step 1.5: Save recovery metadata before the dangerous step
// If we crash during step 2, this metadata + temp file allows recovery
let recovery_meta_path = self.inplace_recovery_meta_path(dest_path);
// Best effort - don't fail the save if we can't write recovery metadata
#[allow(clippy::let_underscore_must_use)]
let _ = self.write_inplace_recovery_meta(
&recovery_meta_path,
dest_path,
&temp_path,
&original_metadata,
);
// Step 2: Stream temp file content to destination
// Now it's safe to truncate the destination since all data is in temp
match self.fs.open_file_for_write(dest_path) {
Ok(mut out_file) => {
if let Err(e) = self.stream_file_to_writer(&temp_path, &mut out_file) {
// Don't delete temp file or recovery metadata - allow recovery
return Err(e.into());
}
out_file.sync_all()?;
// Success! Clean up temp file and recovery metadata (best-effort)
#[allow(clippy::let_underscore_must_use)]
let _ = self.fs.remove_file(&temp_path);
#[allow(clippy::let_underscore_must_use)]
let _ = self.fs.remove_file(&recovery_meta_path);
Ok(())
}
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
// Can't write to destination - trigger sudo fallback
// Keep temp file for sudo to use, clean up recovery metadata (best-effort)
#[allow(clippy::let_underscore_must_use)]
let _ = self.fs.remove_file(&recovery_meta_path);
Err(self.make_sudo_error(temp_path, dest_path, original_metadata))
}
Err(e) => {
// Don't delete temp file or recovery metadata - allow recovery
Err(e.into())
}
}
}
/// Write data directly to a file in-place, with sudo fallback on permission denied.
fn write_data_inplace(
&self,
dest_path: &Path,
data: &[u8],
original_metadata: Option<FileMetadata>,
) -> anyhow::Result<()> {
match self.fs.open_file_for_write(dest_path) {
Ok(mut out_file) => {
out_file.write_all(data)?;
out_file.sync_all()?;
Ok(())
}
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
// Create temp file for sudo fallback
let (temp_path, mut temp_file) = self.create_temp_file(dest_path)?;
temp_file.write_all(data)?;
temp_file.sync_all()?;
drop(temp_file);
Err(self.make_sudo_error(temp_path, dest_path, original_metadata))
}
Err(e) => Err(e.into()),
}
}
/// Stream a file's content to a writer in chunks to avoid memory issues with large files.
fn stream_file_to_writer(
&self,
src_path: &Path,
out_file: &mut Box<dyn crate::model::filesystem::FileWriter>,
) -> io::Result<()> {
const CHUNK_SIZE: usize = 1024 * 1024; // 1MB chunks
let file_size = self.fs.metadata(src_path)?.size;
let mut offset = 0u64;
while offset < file_size {
let remaining = file_size - offset;
let chunk_len = std::cmp::min(remaining, CHUNK_SIZE as u64) as usize;
let chunk = self.fs.read_range(src_path, offset, chunk_len)?;
out_file.write_all(&chunk)?;
offset += chunk_len as u64;
}
Ok(())
}
/// Write the recipe content to a file writer.
fn write_recipe_to_file(
&self,
out_file: &mut Box<dyn crate::model::filesystem::FileWriter>,
recipe: &WriteRecipe,
) -> io::Result<()> {
for action in &recipe.actions {
match action {
RecipeAction::Copy { offset, len } => {
// Read from source and write to output
let src_path = recipe.src_path.as_ref().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "Copy action without source")
})?;
let data = self.fs.read_range(src_path, *offset, *len as usize)?;
out_file.write_all(&data)?;
}
RecipeAction::Insert { index } => {
out_file.write_all(&recipe.insert_data[*index])?;
}
}
}
Ok(())
}
/// Finalize save state after successful write.
fn finalize_save(&mut self, dest_path: &Path) -> anyhow::Result<()> {
let new_size = self.fs.metadata(dest_path)?.size as usize;
tracing::debug!(
"Buffer::save: updating saved_file_size from {:?} to {}",
self.saved_file_size,
new_size
);
self.saved_file_size = Some(new_size);
self.file_path = Some(dest_path.to_path_buf());
// Consolidate the piece tree to synchronize with disk (for large files)
// or to simplify structure (for small files).
self.consolidate_after_save(dest_path, new_size);
self.mark_saved_snapshot();
self.original_line_ending = self.line_ending;
self.original_encoding = self.encoding;
Ok(())
}
/// Finalize buffer state after an external save operation (e.g., via sudo).
///
/// This updates the saved snapshot and file size to match the new state on disk.
pub fn finalize_external_save(&mut self, dest_path: PathBuf) -> anyhow::Result<()> {
let new_size = self.fs.metadata(&dest_path)?.size as usize;
self.saved_file_size = Some(new_size);
self.file_path = Some(dest_path.clone());
// Consolidate the piece tree to synchronize with disk or simplify structure.
self.consolidate_after_save(&dest_path, new_size);
self.mark_saved_snapshot();
self.original_line_ending = self.line_ending;
self.original_encoding = self.encoding;
Ok(())
}
/// Consolidate the piece tree into a single piece.
/// For large files, this creates a reference to the disk file to save memory and sync offsets.
/// For small files, this flattens all edits into a single in-memory buffer.
fn consolidate_after_save(&mut self, path: &Path, file_size: usize) {
if self.large_file {
self.consolidate_large_file(path, file_size);
} else {
self.consolidate_small_file();
}
}
/// Consolidate large file piece tree into a single piece pointing to the new file.
/// This ensures that subsequent operations correctly reference the new content and offsets.
/// Preserves total line feed count from the old tree if a scan was previously done.
fn consolidate_large_file(&mut self, path: &Path, file_size: usize) {
// Preserve line feed count from the old tree if we had scanned it
let preserved_lf = if self.line_feeds_scanned {
self.piece_tree.line_count().map(|c| c.saturating_sub(1))
} else {
None
};
let buffer = StringBuffer {
id: 0,
data: BufferData::Unloaded {
file_path: path.to_path_buf(),
file_offset: 0,
bytes: file_size,
},
stored_file_offset: None,
};
self.piece_tree = if file_size > 0 {
PieceTree::new(BufferLocation::Stored(0), 0, file_size, preserved_lf)
} else {
PieceTree::empty()
};
self.buffers = vec![buffer];
self.next_buffer_id = 1;
tracing::debug!(
"Buffer::consolidate_large_file: consolidated into single piece of {} bytes",
file_size
);
}
/// Consolidate small file edits into a single in-memory buffer and re-index lines.
fn consolidate_small_file(&mut self) {
if let Some(bytes) = self.get_all_text() {
let line_feed_cnt = bytes.iter().filter(|&&b| b == b'\n').count();
let len = bytes.len();
// Create a single loaded buffer with line indexing
let buffer = StringBuffer::new_loaded(0, bytes, true);
self.piece_tree = if len > 0 {
PieceTree::new(BufferLocation::Stored(0), 0, len, Some(line_feed_cnt))
} else {
PieceTree::empty()
};
self.buffers = vec![buffer];
self.next_buffer_id = 1;
tracing::debug!(
"Buffer::consolidate_small_file: consolidated into single loaded buffer of {} bytes",
len
);
}
}
/// Internal helper to create a SudoSaveRequired error.
fn make_sudo_error(
&self,
temp_path: PathBuf,
dest_path: &Path,
original_metadata: Option<FileMetadata>,
) -> anyhow::Error {
#[cfg(unix)]
let (uid, gid, mode) = if let Some(ref meta) = original_metadata {
(
meta.uid.unwrap_or(0),
meta.gid.unwrap_or(0),
meta.permissions
.as_ref()
.map(|p| p.mode() & 0o7777)
.unwrap_or(0),
)
} else {
(0, 0, 0)
};
#[cfg(not(unix))]
let (uid, gid, mode) = (0u32, 0u32, 0u32);
let _ = original_metadata; // suppress unused warning on non-Unix
anyhow::anyhow!(SudoSaveRequired {
temp_path,
dest_path: dest_path.to_path_buf(),
uid,
gid,
mode,
})
}
/// Get the total number of bytes in the document
pub fn total_bytes(&self) -> usize {
self.piece_tree.total_bytes()
}
/// Get the total number of lines in the document
/// Uses the piece tree's integrated line tracking
/// Returns None if line count is unknown (e.g., for large files without line indexing)
pub fn line_count(&self) -> Option<usize> {
self.piece_tree.line_count()
}
/// Snapshot the current tree as the saved baseline
pub fn mark_saved_snapshot(&mut self) {
self.saved_root = self.piece_tree.root();
self.modified = false;
}
/// Refresh the saved root to match the current tree structure without
/// clearing the modified flag. Call this after structural-only changes
/// (e.g. chunk_split_and_load during search scan) so that
/// `diff_since_saved()` can take the fast `Arc::ptr_eq` path.
pub fn refresh_saved_root_if_unmodified(&mut self) {
if !self.modified {
self.saved_root = self.piece_tree.root();
}
}
/// Apply a chunk-load buffer replacement to `saved_root`.
///
/// When viewport loading converts a `Stored(buffer_id)` piece to
/// `Added(new_buffer_id)` in the current tree and the buffer is already
/// modified, we must apply the same transformation to `saved_root` so
/// that `diff_since_saved()` can match loaded-but-unedited regions by
/// `(location, offset)` identity.
fn apply_chunk_load_to_saved_root(
&mut self,
old_buffer_id: usize,
chunk_offset_in_buffer: usize,
chunk_bytes: usize,
new_buffer_id: usize,
) {
use crate::model::piece_tree::{LeafData, PieceTree};
let mut leaves = Vec::new();
self.saved_root.collect_leaves(&mut leaves);
let mut modified = false;
let mut new_leaves: Vec<LeafData> = Vec::with_capacity(leaves.len() + 2);
for leaf in &leaves {
if leaf.location.buffer_id() != old_buffer_id {
new_leaves.push(*leaf);
continue;
}
let leaf_start = leaf.offset;
let leaf_end = leaf.offset + leaf.bytes;
let chunk_start = chunk_offset_in_buffer;
let chunk_end = chunk_offset_in_buffer + chunk_bytes;
// Check if this leaf overlaps the chunk range
if chunk_start >= leaf_end || chunk_end <= leaf_start {
// No overlap — keep as-is
new_leaves.push(*leaf);
continue;
}
modified = true;
// Prefix: portion of this leaf before the chunk
if chunk_start > leaf_start {
new_leaves.push(LeafData::new(
leaf.location,
leaf.offset,
chunk_start - leaf_start,
None, // line feed count unknown after split
));
}
// The chunk itself — replaced with Added(new_buffer_id)
let actual_start = chunk_start.max(leaf_start);
let actual_end = chunk_end.min(leaf_end);
let offset_in_chunk = actual_start - chunk_start;
new_leaves.push(LeafData::new(
BufferLocation::Added(new_buffer_id),
offset_in_chunk,
actual_end - actual_start,
None,
));
// Suffix: portion of this leaf after the chunk
if chunk_end < leaf_end {
new_leaves.push(LeafData::new(
leaf.location,
chunk_end,
leaf_end - chunk_end,
None,
));
}
}
if modified {
self.saved_root = PieceTree::from_leaves(&new_leaves).root();
}
}
/// Diff the current piece tree against the last saved snapshot.
///
/// This compares actual byte content, not just tree structure. This means
/// that if you delete text and then paste it back, the diff will correctly
/// show no changes (even though the tree structure differs).
///
/// Uses a two-phase algorithm for efficiency:
/// - Phase 1: Fast structure-based diff to find changed byte ranges (O(num_leaves))
/// - Phase 2: Only compare actual content within changed ranges (O(edit_size))
///
/// This is O(edit_size) instead of O(file_size) for small edits in large files.
pub fn diff_since_saved(&self) -> PieceTreeDiff {
let _span = tracing::info_span!(
"diff_since_saved",
large_file = self.large_file,
modified = self.modified,
lf_scanned = self.line_feeds_scanned
)
.entered();
// Fast path: if the buffer hasn't been modified since loading/saving,
// the content is identical to the saved version by definition.
// This avoids an expensive O(num_leaves) structure walk when the tree
// has been restructured for non-edit reasons (viewport chunk loading,
// line-scan preparation, search-scan splits).
if !self.modified {
tracing::trace!("diff_since_saved: not modified → equal");
return PieceTreeDiff {
equal: true,
byte_ranges: Vec::new(),
nodes_visited: 0,
};
}
// Quick check: if tree roots are identical (Arc pointer equality),
// the content is definitely the same.
if Arc::ptr_eq(&self.saved_root, &self.piece_tree.root()) {
tracing::trace!("diff_since_saved: Arc::ptr_eq fast path → equal");
return PieceTreeDiff {
equal: true,
byte_ranges: Vec::new(),
nodes_visited: 0,
};
}
// Phase 1: Fast structure-based diff to find which byte ranges differ
// This is O(number of leaves) - very fast even for large files
let structure_diff = self.diff_trees_by_structure();
// If structure says trees are equal (same pieces in same order), we're done
if structure_diff.equal {
tracing::trace!("diff_since_saved: structure equal");
return structure_diff;
}
// Phase 2: For small changed regions, verify with actual content comparison
// This handles the case where different pieces contain identical content
// (e.g., delete text then paste it back)
let total_changed_bytes: usize = structure_diff
.byte_ranges
.iter()
.map(|r| r.end.saturating_sub(r.start))
.sum();
// Only do content verification if the changed region is reasonably small
// For large changes, trust the structure-based diff
const MAX_VERIFY_BYTES: usize = 64 * 1024; // 64KB threshold for verification
if total_changed_bytes <= MAX_VERIFY_BYTES && !structure_diff.byte_ranges.is_empty() {
// Check if content in the changed ranges is actually different
if self.verify_content_differs_in_ranges(&structure_diff.byte_ranges) {
tracing::trace!(
"diff_since_saved: content differs, byte_ranges={}",
structure_diff.byte_ranges.len(),
);
// Content actually differs - return the structure diff result
return structure_diff;
} else {
// Content is the same despite structure differences (rare case: undo/redo)
return PieceTreeDiff {
equal: true,
byte_ranges: Vec::new(),
nodes_visited: structure_diff.nodes_visited,
};
}
}
tracing::info!(
"diff_since_saved: large change, byte_ranges={}, nodes_visited={}",
structure_diff.byte_ranges.len(),
structure_diff.nodes_visited
);
// For large changes or when we can't verify, trust the structure diff
structure_diff
}
/// Check if the actual byte content differs in the given ranges.
/// Returns true if content differs, false if content is identical.
fn verify_content_differs_in_ranges(&self, byte_ranges: &[std::ops::Range<usize>]) -> bool {
let saved_bytes = self.tree_total_bytes(&self.saved_root);
let current_bytes = self.piece_tree.total_bytes();
// Different total sizes means content definitely differs
if saved_bytes != current_bytes {
return true;
}
// For each changed range, compare the actual bytes
for range in byte_ranges {
if range.start >= range.end {
continue;
}
// Extract bytes from saved tree for this range
let saved_slice =
self.extract_range_from_tree(&self.saved_root, range.start, range.end);
// Extract bytes from current tree for this range
let current_slice = self.get_text_range(range.start, range.end);
match (saved_slice, current_slice) {
(Some(saved), Some(current)) => {
if saved != current {
return true; // Content differs
}
}
_ => {
// Couldn't read content, assume it differs to be safe
return true;
}
}
}
// All ranges have identical content
false
}
/// Extract a byte range from a saved tree root
fn extract_range_from_tree(
&self,
root: &Arc<crate::model::piece_tree::PieceTreeNode>,
start: usize,
end: usize,
) -> Option<Vec<u8>> {
let mut result = Vec::with_capacity(end.saturating_sub(start));
self.collect_range_from_node(root, start, end, 0, &mut result)?;
Some(result)
}
/// Recursively collect bytes from a range within a tree node
fn collect_range_from_node(
&self,
node: &Arc<crate::model::piece_tree::PieceTreeNode>,
range_start: usize,
range_end: usize,
node_offset: usize,
result: &mut Vec<u8>,
) -> Option<()> {
use crate::model::piece_tree::PieceTreeNode;
match node.as_ref() {
PieceTreeNode::Internal {
left_bytes,
left,
right,
..
} => {
let left_end = node_offset + left_bytes;
// Check if range overlaps with left subtree
if range_start < left_end {
self.collect_range_from_node(
left,
range_start,
range_end,
node_offset,
result,
)?;
}
// Check if range overlaps with right subtree
if range_end > left_end {
self.collect_range_from_node(right, range_start, range_end, left_end, result)?;
}
}
PieceTreeNode::Leaf {
location,
offset,
bytes,
..
} => {
let node_end = node_offset + bytes;
// Check if this leaf overlaps with our range
if range_start < node_end && range_end > node_offset {
let buf = self.buffers.get(location.buffer_id())?;
let data = buf.get_data()?;
// Calculate the slice within this leaf
let leaf_start = range_start.saturating_sub(node_offset);
let leaf_end = (range_end - node_offset).min(*bytes);
if leaf_start < leaf_end {
let slice = data.get(*offset + leaf_start..*offset + leaf_end)?;
result.extend_from_slice(slice);
}
}
}
}
Some(())
}
/// Helper to get total bytes from a tree root
fn tree_total_bytes(&self, root: &Arc<crate::model::piece_tree::PieceTreeNode>) -> usize {
use crate::model::piece_tree::PieceTreeNode;
match root.as_ref() {
PieceTreeNode::Internal {
left_bytes, right, ..
} => left_bytes + self.tree_total_bytes(right),
PieceTreeNode::Leaf { bytes, .. } => *bytes,
}
}
/// Structure-based diff comparing piece tree leaves
fn diff_trees_by_structure(&self) -> PieceTreeDiff {
crate::model::piece_tree_diff::diff_piece_trees(&self.saved_root, &self.piece_tree.root())
}
/// Convert a byte offset to a line/column position
pub fn offset_to_position(&self, offset: usize) -> Option<Position> {
self.piece_tree
.offset_to_position(offset, &self.buffers)
.map(|(line, column)| Position { line, column })
}
/// Convert a line/column position to a byte offset
pub fn position_to_offset(&self, position: Position) -> usize {
self.piece_tree
.position_to_offset(position.line, position.column, &self.buffers)
}
/// Insert text at the given byte offset
pub fn insert_bytes(&mut self, offset: usize, text: Vec<u8>) -> Cursor {
if text.is_empty() {
return self.piece_tree.cursor_at_offset(offset);
}
// Mark as modified (updates version)
self.mark_content_modified();
// Count line feeds in the text to insert
let line_feed_cnt = Some(text.iter().filter(|&&b| b == b'\n').count());
// Optimization: try to append to existing buffer if insertion is at piece boundary
let (buffer_location, buffer_offset, text_len) =
if let Some(append_info) = self.try_append_to_existing_buffer(offset, &text) {
append_info
} else {
// Create a new StringBuffer for this insertion
let buffer_id = self.next_buffer_id;
self.next_buffer_id += 1;
let buffer = StringBuffer::new(buffer_id, text.clone());
self.buffers.push(buffer);
(BufferLocation::Added(buffer_id), 0, text.len())
};
// When line feeds have been scanned, ensure the chunk at the insertion
// point is loaded so compute_line_feeds_static can recount during splits.
if self.line_feeds_scanned {
self.ensure_chunk_loaded_at(offset);
}
// Update piece tree (need to pass buffers reference)
self.piece_tree.insert(
offset,
buffer_location,
buffer_offset,
text_len,
line_feed_cnt,
&self.buffers,
)
}
/// Try to append to an existing buffer if insertion point aligns with buffer end
/// Returns (BufferLocation, buffer_offset, text_len) if append succeeds, None otherwise
fn try_append_to_existing_buffer(
&mut self,
offset: usize,
text: &[u8],
) -> Option<(BufferLocation, usize, usize)> {
// Only optimize for non-empty insertions after existing content
if text.is_empty() || offset == 0 {
return None;
}
// Find the piece containing the byte just before the insertion point
// This avoids the saturating_sub issue
let piece_info = self.piece_tree.find_by_offset(offset - 1)?;
// Check if insertion is exactly at the end of this piece
// offset_in_piece tells us where (offset-1) is within the piece
// For insertion to be at piece end, (offset-1) must be the last byte
let offset_in_piece = piece_info.offset_in_piece?;
if offset_in_piece + 1 != piece_info.bytes {
return None; // Not at the end of the piece
}
// Only append to "Added" buffers (not original Stored buffers)
if !matches!(piece_info.location, BufferLocation::Added(_)) {
return None;
}
let buffer_id = piece_info.location.buffer_id();
let buffer = self.buffers.get_mut(buffer_id)?;
// Check if buffer is loaded
let buffer_len = buffer.get_data()?.len();
// Check if this piece ends exactly at the end of its buffer
if piece_info.offset + piece_info.bytes != buffer_len {
return None;
}
// Perfect! Append to this buffer
let append_offset = buffer.append(text);
Some((piece_info.location, append_offset, text.len()))
}
/// Insert text (from &str) at the given byte offset
pub fn insert(&mut self, offset: usize, text: &str) {
self.insert_bytes(offset, text.as_bytes().to_vec());
}
/// Insert text at a line/column position
/// This now uses the optimized piece_tree.insert_at_position() for a single traversal
pub fn insert_at_position(&mut self, position: Position, text: Vec<u8>) -> Cursor {
if text.is_empty() {
let offset = self.position_to_offset(position);
return self.piece_tree.cursor_at_offset(offset);
}
self.mark_content_modified();
// Count line feeds in the text to insert
let line_feed_cnt = text.iter().filter(|&&b| b == b'\n').count();
// Create a new StringBuffer for this insertion
let buffer_id = self.next_buffer_id;
self.next_buffer_id += 1;
let buffer = StringBuffer::new(buffer_id, text.clone());
self.buffers.push(buffer);
// Use the optimized position-based insertion (single traversal)
self.piece_tree.insert_at_position(
position.line,
position.column,
BufferLocation::Added(buffer_id),
0,
text.len(),
line_feed_cnt,
&self.buffers,
)
}
/// Delete text starting at the given byte offset
pub fn delete_bytes(&mut self, offset: usize, bytes: usize) {
if bytes == 0 || offset >= self.total_bytes() {
return;
}
// When line feeds have been scanned, ensure chunks at delete boundaries
// are loaded so compute_line_feeds_static can recount during splits.
if self.line_feeds_scanned {
self.ensure_chunk_loaded_at(offset);
let end = (offset + bytes).min(self.total_bytes());
if end > offset {
self.ensure_chunk_loaded_at(end.saturating_sub(1));
}
}
// Update piece tree
self.piece_tree.delete(offset, bytes, &self.buffers);
self.mark_content_modified();
}
/// Delete text in a range
pub fn delete(&mut self, range: Range<usize>) {
if range.end > range.start {
self.delete_bytes(range.start, range.end - range.start);
}
}
/// Delete text in a line/column range
/// This now uses the optimized piece_tree.delete_position_range() for a single traversal
pub fn delete_range(&mut self, start: Position, end: Position) {
// Use the optimized position-based deletion
self.piece_tree.delete_position_range(
start.line,
start.column,
end.line,
end.column,
&self.buffers,
);
self.mark_content_modified();
}
/// Replace the entire buffer content with new content
/// This is an O(n) operation that rebuilds the piece tree in a single pass,
/// avoiding the O(n²) complexity of applying individual edits.
///
/// This is used for bulk operations like "replace all" where applying
/// individual edits would be prohibitively slow.
pub fn replace_content(&mut self, new_content: &str) {
let bytes = new_content.len();
let content_bytes = new_content.as_bytes().to_vec();
// Count line feeds in the new content
let line_feed_cnt = content_bytes.iter().filter(|&&b| b == b'\n').count();
// Create a new StringBuffer for the new content
let buffer_id = self.next_buffer_id;
self.next_buffer_id += 1;
let buffer = StringBuffer::new(buffer_id, content_bytes);
self.buffers.push(buffer);
// Rebuild the piece tree with a single piece containing all the new content
if bytes > 0 {
self.piece_tree = PieceTree::new(
BufferLocation::Added(buffer_id),
0,
bytes,
Some(line_feed_cnt),
);
} else {
self.piece_tree = PieceTree::empty();
}
self.mark_content_modified();
}
/// Restore a previously saved buffer state (for undo/redo of BulkEdit).
///
/// This restores the piece tree AND the buffers list, which is critical
/// because consolidate_after_save() replaces self.buffers. Without restoring
/// buffers, the piece tree would reference buffer IDs that no longer exist.
pub fn restore_buffer_state(&mut self, snapshot: &BufferSnapshot) {
self.piece_tree = snapshot.piece_tree.clone();
self.buffers = snapshot.buffers.clone();
self.next_buffer_id = snapshot.next_buffer_id;
self.mark_content_modified();
}
/// Snapshot the current buffer state (piece tree + buffers) for BulkEdit undo/redo.
///
/// The snapshot includes buffers because consolidate_after_save() can replace
/// self.buffers between the snapshot and restore, which would otherwise cause
/// the restored piece tree to reference nonexistent buffer IDs.
pub fn snapshot_buffer_state(&self) -> Arc<BufferSnapshot> {
Arc::new(BufferSnapshot {
piece_tree: self.piece_tree.clone(),
buffers: self.buffers.clone(),
next_buffer_id: self.next_buffer_id,
})
}
/// Apply bulk edits efficiently in a single pass
/// Returns the net change in bytes
pub fn apply_bulk_edits(&mut self, edits: &[(usize, usize, &str)]) -> isize {
// Pre-allocate buffers for all insert texts (only non-empty texts)
// This avoids the borrow conflict in the closure
// IMPORTANT: Only add entries for non-empty texts because the closure
// is only called for edits with non-empty insert text
let mut buffer_info: Vec<(BufferLocation, usize, usize, Option<usize>)> = Vec::new();
for (_, _, text) in edits {
if !text.is_empty() {
let buffer_id = self.next_buffer_id;
self.next_buffer_id += 1;
let content = text.as_bytes().to_vec();
let lf_cnt = content.iter().filter(|&&b| b == b'\n').count();
let bytes = content.len();
let buffer = StringBuffer::new(buffer_id, content);
self.buffers.push(buffer);
buffer_info.push((BufferLocation::Added(buffer_id), 0, bytes, Some(lf_cnt)));
}
// No placeholder for empty texts - the closure is only called for non-empty texts
}
// Now call apply_bulk_edits with a simple index-based closure
let mut idx = 0;
let delta = self
.piece_tree
.apply_bulk_edits(edits, &self.buffers, |_text| {
let info = buffer_info[idx];
idx += 1;
info
});
self.mark_content_modified();
delta
}
/// Get text from a byte offset range
/// This now uses the optimized piece_tree.iter_pieces_in_range() for a single traversal
/// Get text from a byte offset range (read-only)
/// Returns None if any buffer in the range is unloaded
/// PRIVATE: External code should use get_text_range_mut() which handles lazy loading
fn get_text_range(&self, offset: usize, bytes: usize) -> Option<Vec<u8>> {
if bytes == 0 {
return Some(Vec::new());
}
let mut result = Vec::with_capacity(bytes);
let end_offset = offset + bytes;
let mut collected = 0;
// Use the efficient piece iterator (single O(log n) traversal + O(N) iteration)
for piece_view in self.piece_tree.iter_pieces_in_range(offset, end_offset) {
let buffer_id = piece_view.location.buffer_id();
if let Some(buffer) = self.buffers.get(buffer_id) {
// Calculate the range to read from this piece
let piece_start_in_doc = piece_view.doc_offset;
let piece_end_in_doc = piece_view.doc_offset + piece_view.bytes;
// Clip to the requested range
let read_start = offset.max(piece_start_in_doc);
let read_end = end_offset.min(piece_end_in_doc);
if read_end > read_start {
let offset_in_piece = read_start - piece_start_in_doc;
let bytes_to_read = read_end - read_start;
let buffer_start = piece_view.buffer_offset + offset_in_piece;
let buffer_end = buffer_start + bytes_to_read;
// Return None if buffer is unloaded (type-safe)
let data = buffer.get_data()?;
if buffer_end <= data.len() {
result.extend_from_slice(&data[buffer_start..buffer_end]);
collected += bytes_to_read;
if collected >= bytes {
break;
}
}
}
}
}
Some(result)
}
/// Get text from a byte offset range with lazy loading
/// This will load unloaded chunks on-demand and always returns complete data
///
/// Returns an error if loading fails or if data cannot be read for any reason.
///
/// NOTE: Currently loads entire buffers on-demand. Future optimization would split
/// large pieces and load only LOAD_CHUNK_SIZE chunks at a time.
pub fn get_text_range_mut(&mut self, offset: usize, bytes: usize) -> Result<Vec<u8>> {
let _span = tracing::info_span!("get_text_range_mut", offset, bytes).entered();
if bytes == 0 {
return Ok(Vec::new());
}
let mut result = Vec::with_capacity(bytes);
// Clamp end_offset to buffer length to handle reads beyond EOF
let end_offset = (offset + bytes).min(self.len());
let mut current_offset = offset;
let mut iteration_count = 0u32;
// Keep iterating until we've collected all requested bytes
while current_offset < end_offset {
iteration_count += 1;
let mut made_progress = false;
let mut restarted_iteration = false;
// Use the efficient piece iterator (single O(log n) traversal + O(N) iteration)
for piece_view in self
.piece_tree
.iter_pieces_in_range(current_offset, end_offset)
{
let buffer_id = piece_view.location.buffer_id();
// Check if buffer needs loading
let needs_loading = self
.buffers
.get(buffer_id)
.map(|b| !b.is_loaded())
.unwrap_or(false);
if needs_loading && self.chunk_split_and_load(&piece_view, current_offset)? {
restarted_iteration = true;
break;
}
// Calculate the range to read from this piece
let piece_start_in_doc = piece_view.doc_offset;
let piece_end_in_doc = piece_view.doc_offset + piece_view.bytes;
// Clip to the requested range
let read_start = current_offset.max(piece_start_in_doc);
let read_end = end_offset.min(piece_end_in_doc);
if read_end > read_start {
let offset_in_piece = read_start - piece_start_in_doc;
let bytes_to_read = read_end - read_start;
let buffer_start = piece_view.buffer_offset + offset_in_piece;
let buffer_end = buffer_start + bytes_to_read;
// Buffer should be loaded now
let buffer = self.buffers.get(buffer_id).context("Buffer not found")?;
let data = buffer
.get_data()
.context("Buffer data unavailable after load")?;
anyhow::ensure!(
buffer_end <= data.len(),
"Buffer range out of bounds: requested {}..{}, buffer size {}",
buffer_start,
buffer_end,
data.len()
);
result.extend_from_slice(&data[buffer_start..buffer_end]);
current_offset = read_end;
made_progress = true;
}
}
// If we didn't make progress and didn't restart iteration, this is an error
if !made_progress && !restarted_iteration {
tracing::error!(
"get_text_range_mut: No progress at offset {} (requested range: {}..{}, buffer len: {})",
current_offset,
offset,
end_offset,
self.len()
);
tracing::error!(
"Piece tree stats: {} total bytes",
self.piece_tree.stats().total_bytes
);
anyhow::bail!(
"Failed to read data at offset {}: no progress made (requested {}..{}, buffer len: {})",
current_offset,
offset,
end_offset,
self.len()
);
}
}
if iteration_count > 1 {
tracing::info!(
iteration_count,
result_len = result.len(),
"get_text_range_mut: completed with multiple iterations"
);
}
Ok(result)
}
/// Prepare a viewport for rendering
///
/// This is called before rendering with &mut access to pre-load all data
/// that will be needed for the viewport. It estimates the number of bytes
/// needed based on the line count and pre-loads them.
///
/// # Arguments
/// * `start_offset` - The byte offset where the viewport starts
/// * `line_count` - The number of lines to prepare (estimate)
///
/// # Returns
/// Ok(()) if preparation succeeded, Err if loading failed
pub fn prepare_viewport(&mut self, start_offset: usize, line_count: usize) -> Result<()> {
let _span = tracing::info_span!("prepare_viewport", start_offset, line_count).entered();
// Estimate how many bytes we need (pessimistic assumption)
// Average line length is typically 80-100 bytes, but we use 200 to be safe
let estimated_bytes = line_count.saturating_mul(200);
// Cap the estimate at the remaining bytes in the document
let remaining_bytes = self.total_bytes().saturating_sub(start_offset);
let bytes_to_load = estimated_bytes.min(remaining_bytes);
tracing::trace!(
bytes_to_load,
total_bytes = self.total_bytes(),
"prepare_viewport loading"
);
// Pre-load with full chunk-splitting support
// This may load more than we need, but ensures all data is available
self.get_text_range_mut(start_offset, bytes_to_load)?;
Ok(())
}
/// Split a piece that references a large unloaded buffer, create a chunk
/// buffer for the region around `current_offset`, and load it.
///
/// Returns `true` if the piece tree was modified (caller must restart its
/// iteration), `false` if the piece was small enough to load in-place.
fn chunk_split_and_load(
&mut self,
piece_view: &PieceView,
current_offset: usize,
) -> Result<bool> {
let buffer_id = piece_view.location.buffer_id();
// The underlying buffer may be much larger than this piece (e.g. the
// whole-file Stored buffer after rebuild_with_pristine_saved_root).
// We must chunk-split if either the piece or its buffer exceeds
// LOAD_CHUNK_SIZE, because `load()` loads the entire buffer.
let buffer_bytes = self
.buffers
.get(buffer_id)
.and_then(|b| b.unloaded_bytes())
.unwrap_or(0);
let needs_chunk_split =
piece_view.bytes > LOAD_CHUNK_SIZE || buffer_bytes > piece_view.bytes;
tracing::info!(
buffer_id,
piece_bytes = piece_view.bytes,
buffer_bytes,
needs_chunk_split,
piece_doc_offset = piece_view.doc_offset,
current_offset,
"chunk_split_and_load: loading unloaded piece"
);
if !needs_chunk_split {
// Piece is small enough and its buffer matches — load in-place.
let _span = tracing::info_span!(
"load_small_buffer",
piece_bytes = piece_view.bytes,
buffer_id,
)
.entered();
self.buffers
.get_mut(buffer_id)
.context("Buffer not found")?
.load(&*self.fs)
.context("Failed to load buffer")?;
return Ok(false);
}
let _span = tracing::info_span!(
"chunk_split_and_load",
piece_bytes = piece_view.bytes,
buffer_id,
)
.entered();
let piece_start_in_doc = piece_view.doc_offset;
let offset_in_piece = current_offset.saturating_sub(piece_start_in_doc);
// When the piece already fits within LOAD_CHUNK_SIZE, create a chunk
// buffer for the exact piece range (no alignment/splitting needed).
// Alignment rounding is only useful when carving a sub-range out of a
// piece larger than LOAD_CHUNK_SIZE.
let (chunk_start_in_buffer, chunk_bytes) = if piece_view.bytes <= LOAD_CHUNK_SIZE {
(piece_view.buffer_offset, piece_view.bytes)
} else {
let start =
(piece_view.buffer_offset + offset_in_piece) / CHUNK_ALIGNMENT * CHUNK_ALIGNMENT;
let bytes = LOAD_CHUNK_SIZE
.min((piece_view.buffer_offset + piece_view.bytes).saturating_sub(start));
(start, bytes)
};
// Calculate document offsets for splitting
let chunk_start_offset_in_piece =
chunk_start_in_buffer.saturating_sub(piece_view.buffer_offset);
let split_start_in_doc = piece_start_in_doc + chunk_start_offset_in_piece;
let split_end_in_doc = split_start_in_doc + chunk_bytes;
// Split the piece to isolate the chunk
if chunk_start_offset_in_piece > 0 {
self.piece_tree
.split_at_offset(split_start_in_doc, &self.buffers);
}
if split_end_in_doc < piece_start_in_doc + piece_view.bytes {
self.piece_tree
.split_at_offset(split_end_in_doc, &self.buffers);
}
// Create a new buffer for this chunk
let chunk_buffer = self
.buffers
.get(buffer_id)
.context("Buffer not found")?
.create_chunk_buffer(self.next_buffer_id, chunk_start_in_buffer, chunk_bytes)
.context("Failed to create chunk buffer")?;
self.next_buffer_id += 1;
let new_buffer_id = chunk_buffer.id;
self.buffers.push(chunk_buffer);
// Update the piece to reference the new chunk buffer
self.piece_tree.replace_buffer_reference(
buffer_id,
piece_view.buffer_offset + chunk_start_offset_in_piece,
chunk_bytes,
BufferLocation::Added(new_buffer_id),
);
// Load the chunk buffer
self.buffers
.get_mut(new_buffer_id)
.context("Chunk buffer not found")?
.load(&*self.fs)
.context("Failed to load chunk")?;
// split_at_offset uses compute_line_feeds_static which returns None
// for unloaded buffers, destroying the scanned line feed counts.
// Fix up: the loaded chunk is counted from memory, remaining unloaded
// pieces use the filesystem's count_line_feeds_in_range.
if self.line_feeds_scanned {
let leaves = self.piece_tree.get_leaves();
let mut fixups: Vec<(usize, usize)> = Vec::new();
for (idx, leaf) in leaves.iter().enumerate() {
if leaf.line_feed_cnt.is_none() {
if let Ok(count) = self.scan_leaf(leaf) {
fixups.push((idx, count));
}
}
}
if !fixups.is_empty() {
self.piece_tree.update_leaf_line_feeds_path_copy(&fixups);
}
}
// Keep saved_root in sync with viewport-loading tree restructures so
// that diff_since_saved() can match by (location, offset) identity.
//
// When !modified the current tree IS the saved state, so just snapshot.
// When modified, we must apply the same Stored→Added leaf replacement
// to saved_root so the diff doesn't see loaded-but-unedited regions as
// changed.
if !self.modified {
self.saved_root = self.piece_tree.root();
} else {
self.apply_chunk_load_to_saved_root(
buffer_id,
chunk_start_in_buffer,
chunk_bytes,
new_buffer_id,
);
}
Ok(true)
}
/// Get all text as a single Vec<u8>
/// Returns None if any buffers are unloaded (lazy loading)
/// CRATE-PRIVATE: External code should use get_text_range_mut() or DocumentModel methods
pub(crate) fn get_all_text(&self) -> Option<Vec<u8>> {
self.get_text_range(0, self.total_bytes())
}
/// Get all text as a String
/// Returns None if any buffers are unloaded (lazy loading)
/// CRATE-PRIVATE: External code should use get_text_range_mut() or DocumentModel methods
pub(crate) fn get_all_text_string(&self) -> Option<String> {
self.get_all_text()
.map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
}
/// Get text from a byte range as bytes
/// CRATE-PRIVATE: Returns empty vector if any buffers are unloaded (silently fails!)
/// Only use this when you KNOW the data is loaded (e.g., for syntax highlighting small regions)
/// External code should use get_text_range_mut() or DocumentModel methods
pub(crate) fn slice_bytes(&self, range: Range<usize>) -> Vec<u8> {
self.get_text_range(range.start, range.end.saturating_sub(range.start))
.unwrap_or_default()
}
/// Get all text as a String
/// Returns None if any buffers are unloaded (lazy loading)
pub fn to_string(&self) -> Option<String> {
self.get_all_text_string()
}
/// Get the total number of bytes
pub fn len(&self) -> usize {
self.total_bytes()
}
/// Check if the buffer is empty
pub fn is_empty(&self) -> bool {
self.total_bytes() == 0
}
/// Get the file path associated with this buffer
pub fn file_path(&self) -> Option<&Path> {
self.file_path.as_deref()
}
/// Update the file path after a rename operation on disk.
pub fn rename_file_path(&mut self, path: PathBuf) {
self.file_path = Some(path);
}
/// Clear the file path (make buffer unnamed)
/// Note: This does NOT affect Unloaded chunk file_paths used for lazy loading.
/// Those still point to the original source file for chunk loading.
pub fn clear_file_path(&mut self) {
self.file_path = None;
}
/// Extend buffer to include more bytes from a streaming source file.
/// Used for stdin streaming where the temp file grows over time.
/// Appends a new Unloaded chunk for the new bytes.
pub fn extend_streaming(&mut self, source_path: &Path, new_size: usize) {
let old_size = self.total_bytes();
if new_size <= old_size {
return;
}
let additional_bytes = new_size - old_size;
// Create new Unloaded buffer for the appended region
let buffer_id = self.next_buffer_id;
self.next_buffer_id += 1;
let new_buffer = StringBuffer::new_unloaded(
buffer_id,
source_path.to_path_buf(),
old_size, // file_offset - where this chunk starts in the file
additional_bytes, // bytes - size of this chunk
);
self.buffers.push(new_buffer);
// Append piece at end of document (insert at offset == total_bytes)
self.piece_tree.insert(
old_size,
BufferLocation::Stored(buffer_id),
0,
additional_bytes,
None, // line_feed_cnt unknown for unloaded chunk
&self.buffers,
);
}
/// Check if the buffer has been modified since last save
pub fn is_modified(&self) -> bool {
self.modified
}
/// Clear the modified flag (after save)
pub fn clear_modified(&mut self) {
self.modified = false;
}
/// Set the modified flag explicitly
/// Used by undo/redo to restore the correct modified state
pub fn set_modified(&mut self, modified: bool) {
self.modified = modified;
}
/// Check if buffer has pending changes for recovery auto-save
pub fn is_recovery_pending(&self) -> bool {
self.recovery_pending
}
/// Mark buffer as needing recovery auto-save (call after edits)
pub fn set_recovery_pending(&mut self, pending: bool) {
self.recovery_pending = pending;
}
/// Ensure the buffer chunk at the given byte offset is loaded.
///
/// When `line_feeds_scanned` is true, piece splits during insert/delete need
/// the buffer data to be loaded so `compute_line_feeds_static` can accurately
/// recount line feeds for each half. This method loads the chunk if needed.
fn ensure_chunk_loaded_at(&mut self, offset: usize) {
if let Some(piece_info) = self.piece_tree.find_by_offset(offset) {
let buffer_id = piece_info.location.buffer_id();
if let Some(buffer) = self.buffers.get_mut(buffer_id) {
if !buffer.is_loaded() {
let buf_bytes = buffer.unloaded_bytes().unwrap_or(0);
tracing::info!(
"ensure_chunk_loaded_at: loading buffer {} ({} bytes) for offset {}",
buffer_id,
buf_bytes,
offset
);
if let Err(e) = buffer.load(&*self.fs) {
tracing::warn!("Failed to load chunk at offset {offset}: {e}");
}
}
}
}
}
/// Check if this is a large file with lazy loading enabled
pub fn is_large_file(&self) -> bool {
self.large_file
}
/// Check if line feeds have been scanned for this large file.
/// When true, `line_count()` returns exact values.
pub fn has_line_feed_scan(&self) -> bool {
self.line_feeds_scanned
}
/// Get the raw piece tree leaves (for storing alongside scan chunks).
pub fn piece_tree_leaves(&self) -> Vec<crate::model::piece_tree::LeafData> {
self.piece_tree.get_leaves()
}
/// Prepare work items for an incremental line scan.
///
/// First splits any oversized leaves in the piece tree so every leaf is
/// at most `LOAD_CHUNK_SIZE` bytes. Then returns one work item per leaf.
/// After scanning, `get_text_range_mut` will never need to split a scanned
/// leaf (it's already chunk-sized), so line-feed counts are preserved.
///
/// Returns `(chunks, total_bytes)`.
pub fn prepare_line_scan(&mut self) -> (Vec<LineScanChunk>, usize) {
// Pre-split the tree so every leaf ≤ LOAD_CHUNK_SIZE.
self.piece_tree.split_leaves_to_chunk_size(LOAD_CHUNK_SIZE);
let leaves = self.piece_tree.get_leaves();
let total_bytes: usize = leaves.iter().map(|l| l.bytes).sum();
let mut chunks = Vec::new();
for (idx, leaf) in leaves.iter().enumerate() {
chunks.push(LineScanChunk {
leaf_index: idx,
byte_len: leaf.bytes,
already_known: leaf.line_feed_cnt.is_some(),
});
}
(chunks, total_bytes)
}
/// Initialize a chunked search scan over this buffer's piece tree.
///
/// Used for in-editor Ctrl+F (incremental, yields to the event loop
/// between chunks) and for searching dirty buffers during project grep.
/// For searching files on disk, use `FileSystem::search_file` instead.
pub fn search_scan_init(
&mut self,
regex: regex::bytes::Regex,
max_matches: usize,
query_len: usize,
) -> ChunkedSearchState {
let (chunks, total_bytes) = self.prepare_line_scan();
ChunkedSearchState {
chunks,
next_chunk: 0,
next_doc_offset: 0,
total_bytes,
scanned_bytes: 0,
regex,
matches: Vec::new(),
overlap_tail: Vec::new(),
overlap_doc_offset: 0,
max_matches,
capped: false,
query_len,
running_line: 1,
}
}
/// Process one chunk of a chunked search scan.
///
/// Loads the next chunk via `get_text_range_mut`, prepends overlap from
/// the previous chunk, runs the regex, and appends matches to `state`
/// with line/column/context computed on the fly from the loaded bytes.
///
/// Line numbers are tracked incrementally via `running_line` — each
/// chunk counts newlines in its non-overlap portion to advance the
/// counter for the next chunk, and matches use an incremental cursor
/// so total line-counting work is O(chunk_size), not O(chunk × matches).
///
/// Returns `Ok(true)` if there are more chunks to process, `Ok(false)`
/// when the scan is complete.
///
/// TODO: For concurrent/parallel search (searching multiple files at once),
/// chunks would need to return chunk-relative line numbers and have them
/// fixed up with each file's starting line offset after all chunks complete.
pub fn search_scan_next_chunk(
&mut self,
state: &mut ChunkedSearchState,
) -> std::io::Result<bool> {
if state.is_done() {
return Ok(false);
}
let chunk_info = state.chunks[state.next_chunk].clone();
let doc_offset = state.next_doc_offset;
state.next_chunk += 1;
state.scanned_bytes += chunk_info.byte_len;
state.next_doc_offset += chunk_info.byte_len;
// Load the chunk bytes
let chunk_bytes = self
.get_text_range_mut(doc_offset, chunk_info.byte_len)
.map_err(std::io::Error::other)?;
// Build search buffer: overlap tail + new chunk
let overlap_len = state.overlap_tail.len();
let mut search_buf = Vec::with_capacity(overlap_len + chunk_bytes.len());
search_buf.extend_from_slice(&state.overlap_tail);
search_buf.extend_from_slice(&chunk_bytes);
let buf_doc_offset = if overlap_len > 0 {
state.overlap_doc_offset
} else {
doc_offset
};
// Line number at buf_doc_offset: running_line tracks the line at
// doc_offset (start of new chunk data). Count newlines in the overlap
// prefix to get the line at the start of the full search_buf.
let newlines_in_overlap = search_buf[..overlap_len]
.iter()
.filter(|&&b| b == b'\n')
.count();
let mut line_at = state.running_line - newlines_in_overlap;
let mut counted_to = 0usize;
// Run regex on the combined buffer
for m in state.regex.find_iter(&search_buf) {
// Skip matches entirely within the overlap (already found)
if overlap_len > 0 && m.end() <= overlap_len {
continue;
}
if state.matches.len() >= state.max_matches {
state.capped = true;
break;
}
// Advance line counter incrementally to this match
line_at += search_buf[counted_to..m.start()]
.iter()
.filter(|&&b| b == b'\n')
.count();
counted_to = m.start();
// Find line boundaries in search_buf for context
let line_start = search_buf[..m.start()]
.iter()
.rposition(|&b| b == b'\n')
.map(|p| p + 1)
.unwrap_or(0);
let line_end = search_buf[m.start()..]
.iter()
.position(|&b| b == b'\n')
.map(|p| m.start() + p)
.unwrap_or(search_buf.len());
let match_doc_offset = buf_doc_offset + m.start();
let match_len = m.end() - m.start();
let column = m.start() - line_start + 1;
let context = String::from_utf8_lossy(&search_buf[line_start..line_end]).into_owned();
state.matches.push(SearchMatch {
byte_offset: match_doc_offset,
length: match_len,
line: line_at,
column,
context,
});
}
// Advance running_line by newlines in the new (non-overlap) chunk data
let newlines_in_chunk = chunk_bytes.iter().filter(|&&b| b == b'\n').count();
state.running_line += newlines_in_chunk;
// Save overlap tail for next chunk
let max_overlap = state.query_len.max(256).min(chunk_bytes.len());
let tail_start = chunk_bytes.len().saturating_sub(max_overlap);
state.overlap_tail = chunk_bytes[tail_start..].to_vec();
state.overlap_doc_offset = doc_offset + tail_start;
Ok(!state.is_done())
}
/// Run a complete chunked search over the piece tree (all chunks).
///
/// Synchronous variant — used for dirty buffer snapshots in project
/// grep and in tests. For on-disk files, use `FileSystem::search_file`.
pub fn search_scan_all(
&mut self,
regex: regex::bytes::Regex,
max_matches: usize,
query_len: usize,
) -> std::io::Result<ChunkedSearchState> {
let mut state = self.search_scan_init(regex, max_matches, query_len);
while self.search_scan_next_chunk(&mut state)? {}
Ok(state)
}
/// Build a hybrid search plan from the piece tree.
///
/// Extracts regions (unloaded file ranges + loaded in-memory data) that
/// can be searched independently. The plan is `Send` so it can be
/// executed on a background thread via `HybridSearchPlan::execute`.
///
/// Returns `None` if the buffer has no file path (caller should fall
/// back to `search_scan_all`).
pub fn search_hybrid_plan(&mut self) -> Option<HybridSearchPlan> {
let file_path = self.file_path.clone()?;
self.piece_tree.split_leaves_to_chunk_size(LOAD_CHUNK_SIZE);
let leaves = self.piece_tree.get_leaves();
let mut regions: Vec<SearchRegion> = Vec::new();
let mut doc_offset = 0usize;
for leaf in &leaves {
let buf = self.buffers.get(leaf.location.buffer_id());
let is_unloaded_stored = matches!(
(&leaf.location, buf),
(
BufferLocation::Stored(_),
Some(StringBuffer {
data: BufferData::Unloaded { .. },
..
}),
)
);
if is_unloaded_stored {
let file_offset = match buf.unwrap().data {
BufferData::Unloaded {
file_offset: fo, ..
} => fo + leaf.offset,
_ => unreachable!(),
};
// Merge with previous unloaded region if contiguous
if let Some(SearchRegion::Unloaded {
file_offset: prev_fo,
bytes: prev_bytes,
..
}) = regions.last_mut()
{
if *prev_fo + *prev_bytes == file_offset {
*prev_bytes += leaf.bytes;
doc_offset += leaf.bytes;
continue;
}
}
regions.push(SearchRegion::Unloaded {
file_offset,
bytes: leaf.bytes,
doc_offset,
});
} else {
let data = match buf.and_then(|b| b.get_data()) {
Some(full) => {
let end = (leaf.offset + leaf.bytes).min(full.len());
full[leaf.offset..end].to_vec()
}
None => match self.get_text_range_mut(doc_offset, leaf.bytes) {
Ok(d) => d,
Err(_) => {
doc_offset += leaf.bytes;
continue;
}
},
};
// Merge with previous loaded region
if let Some(SearchRegion::Loaded {
data: prev_data, ..
}) = regions.last_mut()
{
prev_data.extend_from_slice(&data);
doc_offset += leaf.bytes;
continue;
}
regions.push(SearchRegion::Loaded { data, doc_offset });
}
doc_offset += leaf.bytes;
}
Some(HybridSearchPlan { file_path, regions })
}
/// Hybrid search: uses `fs.search_file` for unloaded piece-tree regions
/// (searches where the data lives, no network transfer) and in-memory regex
/// for loaded/edited regions. Handles overlap at region boundaries.
///
/// For a huge remote file with a small local edit, this avoids transferring
/// the entire file — only match metadata crosses the network.
///
/// Falls back to `search_scan_all` when the buffer has no file path or is
/// fully loaded.
pub fn search_hybrid(
&mut self,
pattern: &str,
opts: &FileSearchOptions,
regex: Regex,
max_matches: usize,
query_len: usize,
) -> io::Result<Vec<SearchMatch>> {
let plan = match self.search_hybrid_plan() {
Some(p) => p,
None => {
let state = self.search_scan_all(regex, max_matches, query_len)?;
return Ok(state.matches);
}
};
plan.execute(&*self.fs, pattern, opts, ®ex, max_matches, query_len)
}
/// Count `\n` bytes in a single leaf.
///
/// Uses `count_line_feeds_in_range` for unloaded buffers, which remote
/// filesystem implementations can override to count server-side.
pub fn scan_leaf(&self, leaf: &crate::model::piece_tree::LeafData) -> std::io::Result<usize> {
let buffer_id = leaf.location.buffer_id();
let buffer = self
.buffers
.get(buffer_id)
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "buffer not found"))?;
let count = match &buffer.data {
crate::model::piece_tree::BufferData::Loaded { data, .. } => {
let end = (leaf.offset + leaf.bytes).min(data.len());
data[leaf.offset..end]
.iter()
.filter(|&&b| b == b'\n')
.count()
}
crate::model::piece_tree::BufferData::Unloaded {
file_path,
file_offset,
..
} => {
let read_offset = *file_offset as u64 + leaf.offset as u64;
self.fs
.count_line_feeds_in_range(file_path, read_offset, leaf.bytes)?
}
};
Ok(count)
}
/// Return the I/O parameters for an unloaded leaf, or `None` if loaded.
///
/// Used by the incremental scan to distinguish leaves that can be counted
/// in-memory (via `scan_leaf`) from those that need filesystem I/O.
pub fn leaf_io_params(
&self,
leaf: &crate::model::piece_tree::LeafData,
) -> Option<(std::path::PathBuf, u64, usize)> {
let buffer_id = leaf.location.buffer_id();
let buffer = self.buffers.get(buffer_id)?;
match &buffer.data {
crate::model::piece_tree::BufferData::Loaded { .. } => None,
crate::model::piece_tree::BufferData::Unloaded {
file_path,
file_offset,
..
} => {
let read_offset = *file_offset as u64 + leaf.offset as u64;
Some((file_path.clone(), read_offset, leaf.bytes))
}
}
}
/// Get a reference to the string buffers (for parallel scanning).
pub fn buffer_slice(&self) -> &[StringBuffer] {
&self.buffers
}
/// Apply the results of an incremental line scan.
pub fn apply_scan_updates(&mut self, updates: &[(usize, usize)]) {
self.piece_tree.update_leaf_line_feeds(updates);
self.line_feeds_scanned = true;
}
/// After an incremental line-feed scan completes, rebuild the tree so that
/// `saved_root` and the current tree share `Arc` pointers for unedited
/// subtrees. This makes `diff_since_saved()` O(edited regions) instead of
/// O(file size).
pub fn rebuild_with_pristine_saved_root(&mut self, scan_updates: &[(usize, usize)]) {
let file_size = match self.saved_file_size {
Some(s) => s,
None => {
// Fallback: no saved file size means we can't build a pristine
// tree. Just apply updates the old way.
self.apply_scan_updates(scan_updates);
return;
}
};
// --- Walk the current tree to extract deletions and insertions ---
let total = self.total_bytes();
// Deletions: gaps in Stored coverage (orig_offset, len).
let mut deletions: Vec<(usize, usize)> = Vec::new();
// Insertions: (post_delete_offset, location, buf_offset, bytes, lf_cnt).
// post_delete_offset = cumulative surviving Stored bytes before this point.
let mut insertions: Vec<(usize, BufferLocation, usize, usize, Option<usize>)> = Vec::new();
let mut orig_cursor: usize = 0;
let mut stored_bytes_in_doc: usize = 0;
for piece in self.piece_tree.iter_pieces_in_range(0, total) {
match piece.location {
BufferLocation::Stored(_) => {
if piece.buffer_offset > orig_cursor {
deletions.push((orig_cursor, piece.buffer_offset - orig_cursor));
}
orig_cursor = piece.buffer_offset + piece.bytes;
stored_bytes_in_doc += piece.bytes;
}
BufferLocation::Added(id) => {
// Check if this Added buffer was created by loading a chunk
// from the stored file (via get_text_range_mut chunk loading).
// If so, treat it as stored content, not a user edit.
if let Some(file_off) = self.buffers.get(id).and_then(|b| b.stored_file_offset)
{
if file_off > orig_cursor {
deletions.push((orig_cursor, file_off - orig_cursor));
}
orig_cursor = file_off + piece.bytes;
stored_bytes_in_doc += piece.bytes;
} else {
insertions.push((
stored_bytes_in_doc,
piece.location,
piece.buffer_offset,
piece.bytes,
piece.line_feed_cnt,
));
}
}
}
}
// Trailing deletion.
if orig_cursor < file_size {
deletions.push((orig_cursor, file_size - orig_cursor));
}
// --- Build pristine tree (full original file, pre-split, with lf counts) ---
let mut pristine = if file_size > 0 {
PieceTree::new(BufferLocation::Stored(0), 0, file_size, None)
} else {
PieceTree::empty()
};
pristine.split_leaves_to_chunk_size(LOAD_CHUNK_SIZE);
pristine.update_leaf_line_feeds(scan_updates);
// Snapshot the pristine tree as saved_root.
self.saved_root = pristine.root();
// If no edits, the pristine tree IS the current tree.
if deletions.is_empty() && insertions.is_empty() {
self.piece_tree = pristine;
self.line_feeds_scanned = true;
return;
}
// --- Replay edits onto a clone of the pristine tree ---
let mut tree = pristine;
// Apply deletions from HIGH to LOW offset so earlier offsets stay valid.
deletions.sort_by(|a, b| b.0.cmp(&a.0));
for &(offset, len) in &deletions {
tree.delete(offset, len, &self.buffers);
}
// Apply insertions from LOW to HIGH. Each insertion shifts subsequent
// offsets by its byte count, tracked via insert_delta.
let mut insert_delta: usize = 0;
for &(offset, location, buf_offset, bytes, lf_cnt) in &insertions {
tree.insert(
offset + insert_delta,
location,
buf_offset,
bytes,
lf_cnt,
&self.buffers,
);
insert_delta += bytes;
}
// Path-copy insert/delete may split Stored leaves whose data is
// Unloaded, producing fragments with line_feed_cnt = None
// (compute_line_feeds_static can't read unloaded data). Fix them up
// by scanning any remaining None leaves.
let leaves = tree.get_leaves();
let mut fixups: Vec<(usize, usize)> = Vec::new();
for (idx, leaf) in leaves.iter().enumerate() {
if leaf.line_feed_cnt.is_none() {
if let Ok(count) = self.scan_leaf(leaf) {
fixups.push((idx, count));
}
}
}
if !fixups.is_empty() {
tree.update_leaf_line_feeds_path_copy(&fixups);
}
self.piece_tree = tree;
self.line_feeds_scanned = true;
}
/// Resolve the exact byte offset for a given line number (0-indexed).
///
/// Uses the tree's line feed counts to find the piece containing the target line,
/// then loads/reads that piece's data to find the exact newline position.
/// This works even when buffers are unloaded (large file with scanned line index).
pub fn resolve_line_byte_offset(&mut self, target_line: usize) -> Option<usize> {
if target_line == 0 {
return Some(0);
}
// Use tree metadata to find the piece containing the target line
let (doc_offset, buffer_id, piece_offset, piece_bytes, lines_before) =
self.piece_tree.piece_info_for_line(target_line)?;
// We need to find the (target_line - lines_before)-th newline within this piece
let lines_to_skip = target_line - lines_before;
// Get the piece data — either from loaded buffer or read from disk
let buffer = self.buffers.get(buffer_id)?;
let piece_data: Vec<u8> = match &buffer.data {
crate::model::piece_tree::BufferData::Loaded { data, .. } => {
let end = (piece_offset + piece_bytes).min(data.len());
data[piece_offset..end].to_vec()
}
crate::model::piece_tree::BufferData::Unloaded {
file_path,
file_offset,
..
} => {
let read_offset = *file_offset as u64 + piece_offset as u64;
self.fs
.read_range(file_path, read_offset, piece_bytes)
.ok()?
}
};
// Count newlines to find the target line start
let mut newlines_found = 0;
for (i, &byte) in piece_data.iter().enumerate() {
if byte == b'\n' {
newlines_found += 1;
if newlines_found == lines_to_skip {
// The target line starts right after this newline
return Some(doc_offset + i + 1);
}
}
}
// If we didn't find enough newlines, the line starts in the next piece
// Return the end of this piece as an approximation
Some(doc_offset + piece_bytes)
}
/// Get the saved file size (size of the file on disk after last load/save)
/// For large files, this is used during recovery to know the expected original file size.
/// Returns None for new unsaved buffers.
pub fn original_file_size(&self) -> Option<usize> {
// Return the tracked saved file size - this is updated when the file is
// loaded or saved, so it always reflects the current file on disk.
self.saved_file_size
}
/// Get recovery chunks for this buffer (only modified portions)
///
/// For large files, this returns only the pieces that come from Added buffers
/// (i.e., the modifications), not the original file content. This allows
/// efficient incremental recovery without reading/writing the entire file.
///
/// Returns: Vec of (original_file_offset, data) for each modified chunk
/// The offset is the position in the ORIGINAL file where this chunk should be inserted.
pub fn get_recovery_chunks(&self) -> Vec<(usize, Vec<u8>)> {
use crate::model::piece_tree::BufferLocation;
let mut chunks = Vec::new();
let total = self.total_bytes();
// Track cumulative bytes from Stored pieces as we iterate.
// This gives us the original file offset for Added pieces.
// The key insight: Added pieces should be inserted at the position
// corresponding to where they appear relative to Stored content,
// not their position in the current document.
let mut stored_bytes_before = 0;
for piece in self.piece_tree.iter_pieces_in_range(0, total) {
match piece.location {
BufferLocation::Stored(_) => {
// Accumulate stored bytes to track position in original file
stored_bytes_before += piece.bytes;
}
BufferLocation::Added(buffer_id) => {
if let Some(buffer) = self.buffers.iter().find(|b| b.id == buffer_id) {
// Skip buffers that originate from the original file
// (loaded by chunk_split_and_load for viewport display).
// These have stored_file_offset set and are not user edits.
//
// Why Added and not Stored? The piece tree only has two
// variants: Stored and Added. chunk_split_and_load marks
// loaded chunks as Added(new_id) because
// rebuild_with_pristine_saved_root interprets Stored
// pieces' buffer_offset as a position in the original
// file — but a chunk buffer starts at offset 0, so using
// Stored would corrupt the rebuild logic. We rely on
// stored_file_offset instead to distinguish "loaded from
// disk" from "user edit". A third BufferLocation variant
// (e.g. LoadedChunk) would make this distinction explicit
// in the type system rather than requiring this runtime
// check.
if buffer.stored_file_offset.is_some() {
stored_bytes_before += piece.bytes;
continue;
}
// Get the data from the buffer if loaded
if let Some(data) = buffer.get_data() {
// Extract just the portion this piece references
let start = piece.buffer_offset;
let end = start + piece.bytes;
if end <= data.len() {
// Use stored_bytes_before as the original file offset.
// This is where this insertion should go relative to
// the original file content.
chunks.push((stored_bytes_before, data[start..end].to_vec()));
}
}
}
}
}
}
chunks
}
/// Check if this buffer contains binary content
pub fn is_binary(&self) -> bool {
self.is_binary
}
/// Get the line ending format for this buffer
pub fn line_ending(&self) -> LineEnding {
self.line_ending
}
/// Set the line ending format for this buffer
///
/// This marks the buffer as modified since the line ending format has changed.
/// On save, the buffer content will be converted to the new format.
pub fn set_line_ending(&mut self, line_ending: LineEnding) {
self.line_ending = line_ending;
self.mark_content_modified();
}
/// Set the default line ending format for a new/empty buffer
///
/// Unlike `set_line_ending`, this does NOT mark the buffer as modified.
/// This should be used when initializing a new buffer with a configured default.
pub fn set_default_line_ending(&mut self, line_ending: LineEnding) {
self.line_ending = line_ending;
self.original_line_ending = line_ending;
}
/// Get the encoding format for this buffer
pub fn encoding(&self) -> Encoding {
self.encoding
}
/// Set the encoding format for this buffer
///
/// This marks the buffer as modified since the encoding format has changed.
/// On save, the buffer content will be converted to the new encoding.
pub fn set_encoding(&mut self, encoding: Encoding) {
self.encoding = encoding;
self.mark_content_modified();
}
/// Set the default encoding format for a new/empty buffer
///
/// Unlike `set_encoding`, this does NOT mark the buffer as modified.
/// This should be used when initializing a new buffer with a configured default.
pub fn set_default_encoding(&mut self, encoding: Encoding) {
self.encoding = encoding;
self.original_encoding = encoding;
}
/// Detect the line ending format from a sample of bytes
///
/// Uses majority voting: counts CRLF, LF-only, and CR-only occurrences
/// and returns the most common format.
pub fn detect_line_ending(bytes: &[u8]) -> LineEnding {
// Only check the first 8KB for line ending detection (same as binary detection)
let check_len = bytes.len().min(8 * 1024);
let sample = &bytes[..check_len];
let mut crlf_count = 0;
let mut lf_only_count = 0;
let mut cr_only_count = 0;
let mut i = 0;
while i < sample.len() {
if sample[i] == b'\r' {
// Check if this is CRLF
if i + 1 < sample.len() && sample[i + 1] == b'\n' {
crlf_count += 1;
i += 2; // Skip both \r and \n
continue;
} else {
// CR only (old Mac format)
cr_only_count += 1;
}
} else if sample[i] == b'\n' {
// LF only (Unix format)
lf_only_count += 1;
}
i += 1;
}
// Use majority voting to determine line ending
if crlf_count > lf_only_count && crlf_count > cr_only_count {
LineEnding::CRLF
} else if cr_only_count > lf_only_count && cr_only_count > crlf_count {
LineEnding::CR
} else {
// Default to LF if no clear winner or if LF wins
LineEnding::LF
}
}
/// Detect the text encoding from a sample of bytes
///
/// Delegates to the encoding module. Use `detect_encoding_or_binary`
/// when you need to know if the content should be treated as binary.
pub fn detect_encoding(bytes: &[u8]) -> Encoding {
encoding::detect_encoding(bytes)
}
/// Detect the text encoding and whether content is binary.
///
/// Returns (Encoding, is_binary) where:
/// - Encoding is the detected encoding (or default if binary)
/// - is_binary is true if the content should be treated as raw binary
///
/// Delegates to the encoding module for detection logic.
pub fn detect_encoding_or_binary(bytes: &[u8], truncated: bool) -> (Encoding, bool) {
encoding::detect_encoding_or_binary(bytes, truncated)
}
/// Detect encoding and convert bytes to UTF-8
///
/// Returns the detected encoding and the UTF-8 converted content.
/// This is the core function for normalizing file content to UTF-8 on load.
pub fn detect_and_convert_encoding(bytes: &[u8]) -> (Encoding, Vec<u8>) {
encoding::detect_and_convert(bytes)
}
/// Convert UTF-8 content to the specified encoding for saving
///
/// Used when saving files to convert internal UTF-8 representation
/// back to the original (or user-selected) encoding.
/// Note: This does NOT add BOM - the BOM is handled separately in build_write_recipe.
pub fn convert_to_encoding(utf8_bytes: &[u8], target_encoding: Encoding) -> Vec<u8> {
encoding::convert_from_utf8(utf8_bytes, target_encoding)
}
/// Normalize line endings in the given bytes to LF only
///
/// Converts CRLF (\r\n) and CR (\r) to LF (\n) for internal representation.
/// This makes editing and cursor movement simpler while preserving the
/// original format for saving.
#[allow(dead_code)] // Kept for tests and potential future use
pub fn normalize_line_endings(bytes: Vec<u8>) -> Vec<u8> {
let mut normalized = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'\r' {
// Check if this is CRLF
if i + 1 < bytes.len() && bytes[i + 1] == b'\n' {
// CRLF -> LF
normalized.push(b'\n');
i += 2; // Skip both \r and \n
continue;
} else {
// CR only -> LF
normalized.push(b'\n');
}
} else {
// Copy byte as-is
normalized.push(bytes[i]);
}
i += 1;
}
normalized
}
/// Convert line endings from any source format to any target format
///
/// This first normalizes all line endings to LF, then converts to the target format.
/// Used when saving files after the user has changed the line ending format.
fn convert_line_endings_to(bytes: &[u8], target_ending: LineEnding) -> Vec<u8> {
// First pass: normalize everything to LF
let mut normalized = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'\r' {
// Check if this is CRLF
if i + 1 < bytes.len() && bytes[i + 1] == b'\n' {
// CRLF -> LF
normalized.push(b'\n');
i += 2;
continue;
} else {
// CR only -> LF
normalized.push(b'\n');
}
} else {
normalized.push(bytes[i]);
}
i += 1;
}
// If target is LF, we're done
if target_ending == LineEnding::LF {
return normalized;
}
// Second pass: convert LF to target format
let replacement = target_ending.as_str().as_bytes();
let mut result = Vec::with_capacity(normalized.len() + normalized.len() / 10);
for byte in normalized {
if byte == b'\n' {
result.extend_from_slice(replacement);
} else {
result.push(byte);
}
}
result
}
/// Get text for a specific line
pub fn get_line(&self, line: usize) -> Option<Vec<u8>> {
let (start, end) = self.piece_tree.line_range(line, &self.buffers)?;
let bytes = if let Some(end_offset) = end {
end_offset.saturating_sub(start)
} else {
self.total_bytes().saturating_sub(start)
};
self.get_text_range(start, bytes)
}
/// Get the byte offset where a line starts
pub fn line_start_offset(&self, line: usize) -> Option<usize> {
let (start, _) = self.piece_tree.line_range(line, &self.buffers)?;
Some(start)
}
/// Get piece information at a byte offset
pub fn piece_info_at_offset(&self, offset: usize) -> Option<PieceInfo> {
self.piece_tree.find_by_offset(offset)
}
/// Get tree statistics for debugging
pub fn stats(&self) -> TreeStats {
self.piece_tree.stats()
}
// Search and Replace Operations
/// Find the next occurrence of a pattern, with wrap-around
pub fn find_next(&self, pattern: &str, start_pos: usize) -> Option<usize> {
if pattern.is_empty() {
return None;
}
let pattern_bytes = pattern.as_bytes();
let buffer_len = self.len();
// Search from start_pos to end
if start_pos < buffer_len {
if let Some(offset) = self.find_pattern(start_pos, buffer_len, pattern_bytes) {
return Some(offset);
}
}
// Wrap around: search from beginning to start_pos
if start_pos > 0 {
if let Some(offset) = self.find_pattern(0, start_pos, pattern_bytes) {
return Some(offset);
}
}
None
}
/// Find the next occurrence of a pattern within an optional range
/// If range is None, searches the entire buffer with wrap-around (same as find_next)
/// If range is Some, searches only within that range without wrap-around
pub fn find_next_in_range(
&self,
pattern: &str,
start_pos: usize,
range: Option<Range<usize>>,
) -> Option<usize> {
if pattern.is_empty() {
return None;
}
if let Some(search_range) = range {
// Search within range only, no wrap-around
let pattern_bytes = pattern.as_bytes();
let search_start = start_pos.max(search_range.start);
let search_end = search_range.end.min(self.len());
if search_start < search_end {
self.find_pattern(search_start, search_end, pattern_bytes)
} else {
None
}
} else {
// No range specified, use normal find_next with wrap-around
self.find_next(pattern, start_pos)
}
}
/// Find pattern in a byte range using overlapping chunks
fn find_pattern(&self, start: usize, end: usize, pattern: &[u8]) -> Option<usize> {
if pattern.is_empty() || start >= end {
return None;
}
const CHUNK_SIZE: usize = 65536; // 64KB chunks
let overlap = pattern.len().saturating_sub(1).max(1);
// Use the overlapping chunks iterator for efficient streaming search
let chunks = OverlappingChunks::new(self, start, end, CHUNK_SIZE, overlap);
for chunk in chunks {
// Search the entire chunk buffer
if let Some(pos) = Self::find_in_bytes(&chunk.buffer, pattern) {
let match_end = pos + pattern.len();
// Only report if match ENDS in or after the valid zone
// This ensures patterns spanning boundaries are found exactly once
if match_end > chunk.valid_start {
let absolute_pos = chunk.absolute_pos + pos;
// Verify the match doesn't extend beyond our search range
if absolute_pos + pattern.len() <= end {
return Some(absolute_pos);
}
}
}
}
None
}
/// Simple byte pattern search using naive algorithm
fn find_in_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() || needle.len() > haystack.len() {
return None;
}
(0..=haystack.len() - needle.len()).find(|&i| &haystack[i..i + needle.len()] == needle)
}
/// Find the next occurrence of a regex pattern, with wrap-around
pub fn find_next_regex(&self, regex: &Regex, start_pos: usize) -> Option<usize> {
let buffer_len = self.len();
// Search from start_pos to end
if start_pos < buffer_len {
if let Some(offset) = self.find_regex(start_pos, buffer_len, regex) {
return Some(offset);
}
}
// Wrap around: search from beginning to start_pos
if start_pos > 0 {
if let Some(offset) = self.find_regex(0, start_pos, regex) {
return Some(offset);
}
}
None
}
/// Find the next occurrence of a regex pattern within an optional range
pub fn find_next_regex_in_range(
&self,
regex: &Regex,
start_pos: usize,
range: Option<Range<usize>>,
) -> Option<usize> {
if let Some(search_range) = range {
let search_start = start_pos.max(search_range.start);
let search_end = search_range.end.min(self.len());
if search_start < search_end {
self.find_regex(search_start, search_end, regex)
} else {
None
}
} else {
self.find_next_regex(regex, start_pos)
}
}
/// Find regex pattern in a byte range using overlapping chunks
fn find_regex(&self, start: usize, end: usize, regex: &Regex) -> Option<usize> {
if start >= end {
return None;
}
const CHUNK_SIZE: usize = 1048576; // 1MB chunks
const OVERLAP: usize = 4096; // 4KB overlap for regex
// Use the overlapping chunks iterator for efficient streaming search
// This fixes the critical bug where regex patterns spanning chunk boundaries were missed
let chunks = OverlappingChunks::new(self, start, end, CHUNK_SIZE, OVERLAP);
for chunk in chunks {
// Search the entire chunk buffer
if let Some(mat) = regex.find(&chunk.buffer) {
let match_end = mat.end();
// Only report if match ENDS in or after the valid zone
// This ensures patterns spanning boundaries are found exactly once
if match_end > chunk.valid_start {
let absolute_pos = chunk.absolute_pos + mat.start();
// Verify the match doesn't extend beyond our search range
let match_len = mat.end() - mat.start();
if absolute_pos + match_len <= end {
return Some(absolute_pos);
}
}
}
}
None
}
/// Replace a range with replacement text
pub fn replace_range(&mut self, range: Range<usize>, replacement: &str) -> bool {
if range.start >= self.len() {
return false;
}
let end = range.end.min(self.len());
if end > range.start {
self.delete_bytes(range.start, end - range.start);
}
if !replacement.is_empty() {
self.insert(range.start, replacement);
}
true
}
/// Find and replace the next occurrence of a pattern
pub fn replace_next(
&mut self,
pattern: &str,
replacement: &str,
start_pos: usize,
range: Option<Range<usize>>,
) -> Option<usize> {
if let Some(pos) = self.find_next_in_range(pattern, start_pos, range.clone()) {
self.replace_range(pos..pos + pattern.len(), replacement);
Some(pos)
} else {
None
}
}
/// Replace all occurrences of a pattern with replacement text
pub fn replace_all(&mut self, pattern: &str, replacement: &str) -> usize {
if pattern.is_empty() {
return 0;
}
let mut count = 0;
let mut pos = 0;
// Keep searching and replacing
// Note: we search forward from last replacement to handle growth/shrinkage
// Find next occurrence (no wrap-around for replace_all)
while let Some(found_pos) = self.find_next_in_range(pattern, pos, Some(0..self.len())) {
self.replace_range(found_pos..found_pos + pattern.len(), replacement);
count += 1;
// Move past the replacement
pos = found_pos + replacement.len();
// If we're at or past the end, stop
if pos >= self.len() {
break;
}
}
count
}
/// Replace all occurrences of a regex pattern with replacement text
pub fn replace_all_regex(&mut self, regex: &Regex, replacement: &str) -> Result<usize> {
let mut count = 0;
let mut pos = 0;
while let Some(found_pos) = self.find_next_regex_in_range(regex, pos, Some(0..self.len())) {
// Get the match to find its length
let text = self
.get_text_range_mut(found_pos, self.len() - found_pos)
.context("Failed to read text for regex match")?;
if let Some(mat) = regex.find(&text) {
self.replace_range(found_pos..found_pos + mat.len(), replacement);
count += 1;
pos = found_pos + replacement.len();
if pos >= self.len() {
break;
}
} else {
break;
}
}
Ok(count)
}
// LSP Support (UTF-16 conversions)
/// Convert byte position to (line, column) in bytes
pub fn position_to_line_col(&self, byte_pos: usize) -> (usize, usize) {
self.offset_to_position(byte_pos)
.map(|pos| (pos.line, pos.column))
.unwrap_or_else(|| (byte_pos / 80, 0)) // Estimate if metadata unavailable
}
/// Convert (line, character) to byte position - 0-indexed
/// character is in BYTES, not UTF-16 code units
/// Optimized to use single line_range() call instead of two
pub fn line_col_to_position(&self, line: usize, character: usize) -> usize {
if let Some((start, end)) = self.piece_tree.line_range(line, &self.buffers) {
// Calculate line length from the range
let line_len = if let Some(end_offset) = end {
end_offset.saturating_sub(start)
} else {
self.total_bytes().saturating_sub(start)
};
let byte_offset = character.min(line_len);
start + byte_offset
} else {
// Line doesn't exist, return end of buffer
self.len()
}
}
/// Convert byte position to LSP position (line, UTF-16 code units)
/// LSP protocol uses UTF-16 code units for character offsets
pub fn position_to_lsp_position(&self, byte_pos: usize) -> (usize, usize) {
let (line, column_bytes) = self
.offset_to_position(byte_pos)
.map(|pos| (pos.line, pos.column))
.unwrap_or_else(|| (byte_pos / 80, 0)); // Estimate if metadata unavailable
// Get the line content
if let Some(line_bytes) = self.get_line(line) {
// Convert byte offset to UTF-16 code units
let text_before = &line_bytes[..column_bytes.min(line_bytes.len())];
let text_str = String::from_utf8_lossy(text_before);
let utf16_offset = text_str.encode_utf16().count();
(line, utf16_offset)
} else {
(line, 0)
}
}
/// Convert LSP position (line, UTF-16 code units) to byte position
/// LSP uses UTF-16 code units for character offsets, not bytes
/// Optimized to use single line_range() call instead of two
pub fn lsp_position_to_byte(&self, line: usize, utf16_offset: usize) -> usize {
if let Some((line_start, end)) = self.piece_tree.line_range(line, &self.buffers) {
// Calculate line length and get line content
let line_len = if let Some(end_offset) = end {
end_offset.saturating_sub(line_start)
} else {
self.total_bytes().saturating_sub(line_start)
};
if line_len > 0 {
// If data is unloaded, return line_start as fallback
let Some(line_bytes) = self.get_text_range(line_start, line_len) else {
return line_start;
};
let line_str = String::from_utf8_lossy(&line_bytes);
// Convert UTF-16 offset to byte offset
let mut utf16_count = 0;
let mut byte_offset = 0;
for ch in line_str.chars() {
if utf16_count >= utf16_offset {
break;
}
utf16_count += ch.len_utf16();
byte_offset += ch.len_utf8();
}
line_start + byte_offset
} else {
line_start
}
} else {
// Line doesn't exist, return end of buffer
self.len()
}
}
// Navigation helpers
/// Find the previous character boundary (UTF-8 aware)
pub fn prev_char_boundary(&self, pos: usize) -> usize {
if pos == 0 {
return 0;
}
// Get a few bytes before pos to find the character boundary
let start = pos.saturating_sub(4);
let Some(bytes) = self.get_text_range(start, pos - start) else {
// Data unloaded, return pos as fallback
return pos;
};
// Walk backwards to find a UTF-8 leading byte
for i in (0..bytes.len()).rev() {
let byte = bytes[i];
// Check if this is a UTF-8 leading byte (not a continuation byte)
if (byte & 0b1100_0000) != 0b1000_0000 {
return start + i;
}
}
// Fallback
pos.saturating_sub(1)
}
/// Find the next character boundary (UTF-8 aware)
pub fn next_char_boundary(&self, pos: usize) -> usize {
let len = self.len();
if pos >= len {
return len;
}
// Get a few bytes after pos to find the character boundary
let end = (pos + 5).min(len);
let Some(bytes) = self.get_text_range(pos, end - pos) else {
// Data unloaded, return pos as fallback
return pos;
};
// Start from index 1 (we want the NEXT boundary)
for (i, &byte) in bytes.iter().enumerate().skip(1) {
// Check if this is a UTF-8 leading byte (not a continuation byte)
if (byte & 0b1100_0000) != 0b1000_0000 {
return pos + i;
}
}
// If we got here, we're at the end or found no boundary in the range
end
}
/// Check if a byte is a UTF-8 continuation byte (not at a char boundary)
/// UTF-8 continuation bytes have the pattern 10xxxxxx (0x80-0xBF)
/// This is the same check that str::is_char_boundary uses internally.
#[inline]
fn is_utf8_continuation_byte(byte: u8) -> bool {
(byte & 0b1100_0000) == 0b1000_0000
}
/// Snap position to a valid UTF-8 character boundary
/// If already at a boundary, returns the same position.
/// Otherwise, moves to the previous valid boundary.
pub fn snap_to_char_boundary(&self, pos: usize) -> usize {
let len = self.len();
if pos == 0 || pos >= len {
return pos.min(len);
}
// Get the byte at pos to check if we're at a character boundary
let Some(bytes) = self.get_text_range(pos, 1) else {
// Data unloaded, return pos as fallback
return pos;
};
// A position is at a char boundary if the byte there is NOT a continuation byte
if !Self::is_utf8_continuation_byte(bytes[0]) {
// Already at a character boundary
return pos;
}
// Not at a boundary, find the previous one
self.prev_char_boundary(pos)
}
/// Find the previous grapheme cluster boundary (for proper cursor movement with combining characters)
///
/// This handles complex scripts like Thai where multiple Unicode code points
/// form a single visual character (grapheme cluster). For example, Thai "ที่"
/// is 3 code points but 1 grapheme cluster.
///
/// The lookahead window starts at 32 bytes but grows whenever the
/// returned boundary sits at the start of the chunk — that is, whenever
/// the chunk might not contain the full grapheme. This matters for ZWJ
/// emoji sequences and Zalgo strings with many combining marks, which
/// can easily exceed 32 bytes.
pub fn prev_grapheme_boundary(&self, pos: usize) -> usize {
if pos == 0 {
return 0;
}
let mut lookback: usize = 32;
loop {
// IMPORTANT: Align start to a valid character boundary to avoid invalid UTF-8
// when get_text_range starts mid-character
let raw_start = pos.saturating_sub(lookback);
let start = if raw_start == 0 {
0
} else {
// Find the character boundary at or before raw_start
self.prev_char_boundary(raw_start + 1)
};
let Some(bytes) = self.get_text_range(start, pos - start) else {
// Data unloaded, fall back to char boundary
return self.prev_char_boundary(pos);
};
let text = match std::str::from_utf8(&bytes) {
Ok(s) => s,
Err(e) => {
// Still got invalid UTF-8 (shouldn't happen after alignment)
// Try using just the valid portion
let valid_bytes = &bytes[..e.valid_up_to()];
match std::str::from_utf8(valid_bytes) {
Ok(s) if !s.is_empty() => s,
_ => return self.prev_char_boundary(pos),
}
}
};
// Use shared grapheme utility with relative position
let rel_pos = pos - start;
let new_rel_pos = grapheme::prev_grapheme_boundary(text, rel_pos);
// If the returned boundary is at the start of our chunk, the
// grapheme may extend further back. Only trust the answer when
// either we already reached the beginning of the buffer or the
// boundary sits strictly inside the chunk.
if new_rel_pos > 0 || start == 0 {
return start + new_rel_pos;
}
// Expand the lookback window and retry. Cap at the full buffer.
if lookback >= pos {
return 0;
}
lookback = lookback.saturating_mul(2);
}
}
/// Find the next grapheme cluster boundary (for proper cursor movement with combining characters)
///
/// This handles complex scripts like Thai where multiple Unicode code points
/// form a single visual character (grapheme cluster). For example, Thai "ที่"
/// is 3 code points but 1 grapheme cluster.
///
/// The lookahead window grows whenever the first grapheme reaches the
/// end of the chunk — otherwise ZWJ emoji and Zalgo strings whose byte
/// length exceeds the initial 32-byte window would be split mid-cluster.
pub fn next_grapheme_boundary(&self, pos: usize) -> usize {
let len = self.len();
if pos >= len {
return len;
}
let mut lookahead: usize = 32;
loop {
let end = (pos + lookahead).min(len);
let Some(bytes) = self.get_text_range(pos, end - pos) else {
// Data unloaded, fall back to char boundary
return self.next_char_boundary(pos);
};
// Convert to UTF-8 string, handling the case where we might have
// grabbed bytes that end mid-character (truncate to valid UTF-8)
let text = match std::str::from_utf8(&bytes) {
Ok(s) => s,
Err(e) => {
// The bytes end in an incomplete UTF-8 sequence
// Use only the valid portion (which includes at least the first grapheme)
let valid_bytes = &bytes[..e.valid_up_to()];
match std::str::from_utf8(valid_bytes) {
Ok(s) if !s.is_empty() => s,
_ => return self.next_char_boundary(pos),
}
}
};
let new_rel_pos = grapheme::next_grapheme_boundary(text, 0);
// If the first grapheme reaches the end of our chunk and there
// is more buffer left beyond it, the grapheme may extend further.
// Expand the window and retry.
if new_rel_pos == text.len() && end < len {
if lookahead >= len - pos {
return len;
}
lookahead = lookahead.saturating_mul(2);
continue;
}
return pos + new_rel_pos;
}
}
/// Find the previous word boundary
pub fn prev_word_boundary(&self, pos: usize) -> usize {
if pos == 0 {
return 0;
}
// Get some text before pos
let start = pos.saturating_sub(256).max(0);
let Some(bytes) = self.get_text_range(start, pos - start) else {
// Data unloaded, return pos as fallback
return pos;
};
let text = String::from_utf8_lossy(&bytes);
let mut found_word_char = false;
let chars: Vec<char> = text.chars().collect();
for i in (0..chars.len()).rev() {
let ch = chars[i];
let is_word_char = ch.is_alphanumeric() || ch == '_';
if found_word_char && !is_word_char {
// We've transitioned from word to non-word
// Calculate the byte position
let byte_offset: usize = chars[0..=i].iter().map(|c| c.len_utf8()).sum();
return start + byte_offset;
}
if is_word_char {
found_word_char = true;
}
}
0
}
/// Find the next word boundary
pub fn next_word_boundary(&self, pos: usize) -> usize {
let len = self.len();
if pos >= len {
return len;
}
// Get some text after pos
let end = (pos + 256).min(len);
let Some(bytes) = self.get_text_range(pos, end - pos) else {
// Data unloaded, return pos as fallback
return pos;
};
let text = String::from_utf8_lossy(&bytes);
let mut found_word_char = false;
let mut byte_offset = 0;
for ch in text.chars() {
let is_word_char = ch.is_alphanumeric() || ch == '_';
if found_word_char && !is_word_char {
// We've transitioned from word to non-word
return pos + byte_offset;
}
if is_word_char {
found_word_char = true;
}
byte_offset += ch.len_utf8();
}
len
}
/// Create a line iterator starting at the given byte position
///
/// This iterator lazily loads chunks as needed, never scanning the entire file.
/// For large files with unloaded buffers, chunks are loaded on-demand (1MB at a time).
pub fn line_iterator(
&mut self,
byte_pos: usize,
estimated_line_length: usize,
) -> LineIterator<'_> {
LineIterator::new(self, byte_pos, estimated_line_length)
}
/// Iterate over lines starting from a given byte offset, with line numbers
///
/// This is a more efficient alternative to using line_iterator() + offset_to_position()
/// because it calculates line numbers incrementally during iteration by accumulating
/// line_feed_cnt from pieces (which is already tracked in the piece tree).
///
/// Returns: Iterator yielding (byte_offset, content, line_number: Option<usize>)
/// - line_number is Some(n) for small files with line metadata
/// - line_number is None for large files without line metadata
///
/// # Performance
/// - O(1) per line for line number calculation (vs O(log n) per line with offset_to_position)
/// - Uses single source of truth: piece tree's existing line_feed_cnt metadata
pub fn iter_lines_from(
&mut self,
byte_pos: usize,
max_lines: usize,
) -> Result<TextBufferLineIterator> {
TextBufferLineIterator::new(self, byte_pos, max_lines)
}
// Legacy API methods for backwards compatibility
/// Get the line number for a given byte offset
///
/// Returns exact line number if metadata available, otherwise estimates based on bytes.
///
/// # Behavior by File Size:
/// - **Small files (< 1MB)**: Returns exact line number from piece tree's `line_starts` metadata
/// - **Large files (≥ 1MB)**: Returns estimated line number using `byte_offset / estimated_line_length`
///
/// Large files don't maintain line metadata for performance reasons. The estimation
/// uses the configured `estimated_line_length` (default 80 bytes).
pub fn get_line_number(&self, byte_offset: usize) -> usize {
self.offset_to_position(byte_offset)
.map(|pos| pos.line)
.unwrap_or_else(|| {
// Estimate line number based on configured average line length
byte_offset / self.config.estimated_line_length
})
}
/// Get the configured estimated line length for approximate line number calculations.
pub fn estimated_line_length(&self) -> usize {
self.config.estimated_line_length
}
/// Get the starting line number at a byte offset (used for viewport rendering)
///
/// # Line Cache Architecture (Post-Refactoring):
///
/// The concept of a separate "line cache" is **now obsolete**. After the refactoring,
/// line tracking is integrated directly into the piece tree via:
/// ```rust
/// BufferData::Loaded {
/// data: Vec<u8>,
/// line_starts: Option<Vec<usize>> // None = large file mode (no line metadata)
/// }
/// ```
///
/// ## Why This Method Still Exists:
/// The rendering code needs to know what line number to display in the margin at the
/// top of the viewport. This method returns that line number, handling both small
/// and large file modes transparently.
///
/// ## Small vs Large File Modes:
/// - **Small files**: `line_starts = Some(vec)` → returns exact line number from metadata
/// - **Large files**: `line_starts = None` → returns estimated line number (byte_offset / estimated_line_length)
///
/// ## Legacy Line Cache Methods:
/// These methods are now no-ops and can be removed in a future cleanup:
/// - `invalidate_line_cache_from()` - No-op (piece tree updates automatically)
/// - `handle_line_cache_insertion()` - No-op (piece tree updates automatically)
/// - `handle_line_cache_deletion()` - No-op (piece tree updates automatically)
/// - `clear_line_cache()` - No-op (can't clear piece tree metadata)
///
/// ## Bug Fix (2025-11):
/// Previously this method always returned `0`, causing line numbers in the margin
/// to always show 1, 2, 3... regardless of scroll position. Now it correctly returns
/// the actual line number at `start_byte`.
pub fn populate_line_cache(&mut self, start_byte: usize, _line_count: usize) -> usize {
// No-op for cache population: LineIndex maintains all line starts automatically
// But we need to return the actual line number at start_byte for rendering
self.get_line_number(start_byte)
}
/// Get cached byte offset for line (compatibility method)
pub fn get_cached_byte_offset_for_line(&self, line_number: usize) -> Option<usize> {
self.line_start_offset(line_number)
}
/// Invalidate line cache from offset (no-op in new implementation)
pub fn invalidate_line_cache_from(&mut self, _byte_offset: usize) {
// No-op: LineIndex updates automatically
}
/// Handle line cache insertion (no-op in new implementation)
pub fn handle_line_cache_insertion(&mut self, _byte_offset: usize, _bytes_inserted: usize) {
// No-op: LineIndex updates automatically during insert
}
/// Handle line cache deletion (no-op in new implementation)
pub fn handle_line_cache_deletion(&mut self, _byte_offset: usize, _bytes_deleted: usize) {
// No-op: LineIndex updates automatically during delete
}
/// Clear line cache (no-op in new implementation)
pub fn clear_line_cache(&mut self) {
// No-op: LineIndex can't be cleared
}
// Test helper methods
/// Create a buffer from a string for testing
#[cfg(test)]
pub fn from_str_test(s: &str) -> Self {
Self::from_bytes(
s.as_bytes().to_vec(),
std::sync::Arc::new(crate::model::filesystem::StdFileSystem),
)
}
/// Create a new empty buffer for testing
#[cfg(test)]
pub fn new_test() -> Self {
Self::empty(std::sync::Arc::new(crate::model::filesystem::StdFileSystem))
}
}
/// Type alias for backwards compatibility
pub type Buffer = TextBuffer;
// Re-export LineIterator from the line_iterator module
pub use crate::primitives::line_iterator::LineIterator;
// ============================================================================
// Overlapping Chunks Iterator for Efficient Search
// ============================================================================
/// Information about a chunk of data for pattern matching
#[derive(Debug)]
pub struct ChunkInfo {
/// The buffer containing this chunk's data (includes overlap from previous chunk)
pub buffer: Vec<u8>,
/// Absolute position in the document where this buffer starts
pub absolute_pos: usize,
/// Offset within buffer where "new" data starts (valid match zone)
/// Matches starting before this offset were already checked in the previous chunk
pub valid_start: usize,
}
/// Iterator that yields overlapping chunks for pattern matching
///
/// This iterator implements the VSCode/Sublime approach: pull overlapping chunks
/// from the underlying piece tree and use standard search algorithms on them.
///
/// # Algorithm
///
/// ```text
/// Chunk 1: [------------ valid -----------]
/// Chunk 2: [overlap][---- valid ----]
/// Chunk 3: [overlap][-- valid --]
///
/// Only matches starting in the "valid" zone are reported to avoid duplicates.
/// ```
///
/// # Example
///
/// ```ignore
/// let chunks = OverlappingChunks::new(&text_buffer, start, end, 4096, pattern.len()-1);
/// for chunk in chunks {
/// // Search only starting from chunk.valid_start
/// if let Some(pos) = search(&chunk.buffer[chunk.valid_start..]) {
/// let absolute_pos = chunk.absolute_pos + chunk.valid_start + pos;
/// return Some(absolute_pos);
/// }
/// }
/// ```
pub struct OverlappingChunks<'a> {
piece_iter: PieceRangeIter,
buffers: &'a [StringBuffer],
// Reusable chunk buffer that we fill from pieces
buffer: Vec<u8>,
buffer_absolute_pos: usize,
// Current state
current_pos: usize,
end_pos: usize,
// Configuration
chunk_size: usize,
overlap: usize,
// Track first chunk special case
first_chunk: bool,
// Cached piece data for incremental reading
current_piece_data: Option<Vec<u8>>,
current_piece_offset: usize,
}
impl<'a> OverlappingChunks<'a> {
/// Create a new overlapping chunks iterator
///
/// # Arguments
///
/// * `text_buffer` - The text buffer to iterate over
/// * `start` - Start position in the document
/// * `end` - End position in the document (exclusive)
/// * `chunk_size` - Target size for each chunk (excluding overlap)
/// * `overlap` - Number of bytes to overlap between chunks
///
/// # Recommendations
///
/// * For literal string search: `chunk_size=65536, overlap=pattern.len()-1`
/// * For regex search: `chunk_size=1048576, overlap=4096`
pub fn new(
text_buffer: &'a TextBuffer,
start: usize,
end: usize,
chunk_size: usize,
overlap: usize,
) -> Self {
let piece_iter = text_buffer.piece_tree.iter_pieces_in_range(start, end);
Self {
piece_iter,
buffers: &text_buffer.buffers,
buffer: Vec::with_capacity(chunk_size + overlap),
buffer_absolute_pos: start,
current_pos: start,
end_pos: end,
chunk_size,
overlap,
first_chunk: true,
current_piece_data: None,
current_piece_offset: 0,
}
}
/// Read one byte from the piece iterator
fn read_byte(&mut self) -> Option<u8> {
loop {
// If we have cached piece data, read from it
if let Some(ref data) = self.current_piece_data {
if self.current_piece_offset < data.len() {
let byte = data[self.current_piece_offset];
self.current_piece_offset += 1;
self.current_pos += 1;
return Some(byte);
} else {
// Exhausted current piece, move to next
self.current_piece_data = None;
self.current_piece_offset = 0;
}
}
// Get next piece
if let Some(piece_view) = self.piece_iter.next() {
let buffer_id = piece_view.location.buffer_id();
if let Some(buffer) = self.buffers.get(buffer_id) {
// Extract the relevant slice from this piece
let piece_start_in_doc = piece_view.doc_offset;
let piece_end_in_doc = piece_view.doc_offset + piece_view.bytes;
// Clip to our search range
let read_start = self.current_pos.max(piece_start_in_doc);
let read_end = self.end_pos.min(piece_end_in_doc);
if read_end > read_start {
let offset_in_piece = read_start - piece_start_in_doc;
let bytes_to_read = read_end - read_start;
let buffer_start = piece_view.buffer_offset + offset_in_piece;
let buffer_end = buffer_start + bytes_to_read;
if let Some(data) = buffer.get_data() {
if buffer_end <= data.len() {
// Cache this piece's data
self.current_piece_data =
Some(data[buffer_start..buffer_end].to_vec());
self.current_piece_offset = 0;
continue;
}
}
}
}
}
// No more data
return None;
}
}
/// Fill the buffer with the next chunk of data
fn fill_next_chunk(&mut self) -> bool {
if self.first_chunk {
// First chunk: fill up to chunk_size
self.first_chunk = false;
while self.buffer.len() < self.chunk_size && self.current_pos < self.end_pos {
if let Some(byte) = self.read_byte() {
self.buffer.push(byte);
} else {
break;
}
}
!self.buffer.is_empty()
} else {
// Subsequent chunks: keep overlap, fill chunk_size NEW bytes
if self.current_pos >= self.end_pos {
return false;
}
// Keep overlap bytes at the end
if self.buffer.len() > self.overlap {
let drain_amount = self.buffer.len() - self.overlap;
self.buffer.drain(0..drain_amount);
self.buffer_absolute_pos += drain_amount;
}
// Fill chunk_size NEW bytes (in addition to overlap)
let before_len = self.buffer.len();
let target_len = self.overlap + self.chunk_size;
while self.buffer.len() < target_len && self.current_pos < self.end_pos {
if let Some(byte) = self.read_byte() {
self.buffer.push(byte);
} else {
break;
}
}
// Return true if we added new data
self.buffer.len() > before_len
}
}
}
impl<'a> Iterator for OverlappingChunks<'a> {
type Item = ChunkInfo;
fn next(&mut self) -> Option<Self::Item> {
// Track if this is the first chunk before filling
let is_first = self.buffer_absolute_pos == self.current_pos;
if !self.fill_next_chunk() {
return None;
}
// First chunk: all data is valid (no overlap from previous)
// Subsequent chunks: overlap bytes are not valid (already checked)
let valid_start = if is_first {
0
} else {
self.overlap.min(self.buffer.len())
};
Some(ChunkInfo {
buffer: self.buffer.clone(),
absolute_pos: self.buffer_absolute_pos,
valid_start,
})
}
}
/// A region in a hybrid search plan — either an unloaded file range or
/// in-memory data from the piece tree.
#[derive(Debug)]
pub(crate) enum SearchRegion {
/// Contiguous range on the original file that hasn't been loaded.
Unloaded {
file_offset: usize,
bytes: usize,
doc_offset: usize,
},
/// In-memory data (loaded original content or user edits).
Loaded { data: Vec<u8>, doc_offset: usize },
}
/// A plan for hybrid search — extracted from a `TextBuffer`'s piece tree
/// on the main thread, executable on any thread.
///
/// For a large remote file with a small edit, the plan captures the few
/// loaded regions (small) and unloaded file ranges (coordinates only).
/// `execute()` then searches unloaded regions via `fs.search_file` (no data
/// transfer) and loaded regions with in-memory regex.
#[derive(Debug)]
pub struct HybridSearchPlan {
pub(crate) file_path: PathBuf,
pub(crate) regions: Vec<SearchRegion>,
}
impl HybridSearchPlan {
/// Execute the search plan. Can run on any thread — only needs a
/// `FileSystem` reference for unloaded region searches.
pub fn execute(
&self,
fs: &dyn FileSystem,
pattern: &str,
opts: &FileSearchOptions,
regex: &Regex,
max_matches: usize,
query_len: usize,
) -> io::Result<Vec<SearchMatch>> {
if self.regions.is_empty() {
return Ok(vec![]);
}
// Fast path: single unloaded region → search whole file
if self.regions.len() == 1 {
if let SearchRegion::Unloaded { .. } = &self.regions[0] {
let mut cursor = FileSearchCursor::new();
let mut all_matches = Vec::new();
while !cursor.done && all_matches.len() < max_matches {
let batch = fs.search_file(&self.file_path, pattern, opts, &mut cursor)?;
all_matches.extend(batch);
}
all_matches.truncate(max_matches);
return Ok(all_matches);
}
}
let overlap_size = query_len.max(256);
let mut all_matches: Vec<SearchMatch> = Vec::new();
let mut running_line: usize = 1;
let mut prev_tail: Vec<u8> = Vec::new();
for region in &self.regions {
if all_matches.len() >= max_matches {
break;
}
let remaining = max_matches - all_matches.len();
match region {
SearchRegion::Unloaded {
file_offset,
bytes,
doc_offset: region_doc_offset,
} => {
// Boundary overlap: prev_tail + start of unloaded region
if !prev_tail.is_empty() {
let overlap_read = (*bytes).min(overlap_size);
if let Ok(head) =
fs.read_range(&self.file_path, *file_offset as u64, overlap_read)
{
let boundary = search_boundary_overlap(
&prev_tail,
&head,
*region_doc_offset - prev_tail.len(),
running_line,
regex,
remaining,
);
all_matches.extend(boundary);
}
}
// Search unloaded range via fs.search_file
let mut opts_bounded = opts.clone();
opts_bounded.max_matches = remaining.saturating_sub(all_matches.len());
let mut cursor = FileSearchCursor::for_range(
*file_offset,
*file_offset + *bytes,
running_line,
);
while !cursor.done && all_matches.len() < max_matches {
let mut batch =
fs.search_file(&self.file_path, pattern, &opts_bounded, &mut cursor)?;
// Remap byte_offset from file-relative to doc-relative
for m in &mut batch {
m.byte_offset = *region_doc_offset + (m.byte_offset - *file_offset);
}
all_matches.extend(batch);
}
running_line = cursor.running_line;
// Save tail for next boundary
if *bytes >= overlap_size {
let tail_off = *file_offset + *bytes - overlap_size;
prev_tail = fs
.read_range(&self.file_path, tail_off as u64, overlap_size)
.unwrap_or_default();
} else {
prev_tail = fs
.read_range(&self.file_path, *file_offset as u64, *bytes)
.unwrap_or_default();
}
}
SearchRegion::Loaded {
data,
doc_offset: region_doc_offset,
} => {
// Build search buffer: overlap tail + loaded data
let mut search_buf = Vec::with_capacity(prev_tail.len() + data.len());
search_buf.extend_from_slice(&prev_tail);
search_buf.extend_from_slice(data);
let overlap_len = prev_tail.len();
let buf_doc_offset = if overlap_len > 0 {
*region_doc_offset - overlap_len
} else {
*region_doc_offset
};
let newlines_in_overlap = search_buf[..overlap_len]
.iter()
.filter(|&&b| b == b'\n')
.count();
let mut line_at = running_line.saturating_sub(newlines_in_overlap);
let mut counted_to = 0usize;
for m in regex.find_iter(&search_buf) {
if overlap_len > 0 && m.end() <= overlap_len {
continue;
}
if all_matches.len() >= max_matches {
break;
}
line_at += search_buf[counted_to..m.start()]
.iter()
.filter(|&&b| b == b'\n')
.count();
counted_to = m.start();
let line_start = search_buf[..m.start()]
.iter()
.rposition(|&b| b == b'\n')
.map(|p| p + 1)
.unwrap_or(0);
let line_end = search_buf[m.start()..]
.iter()
.position(|&b| b == b'\n')
.map(|p| m.start() + p)
.unwrap_or(search_buf.len());
let match_doc_offset = buf_doc_offset + m.start();
let column = m.start() - line_start + 1;
let context =
String::from_utf8_lossy(&search_buf[line_start..line_end]).into_owned();
all_matches.push(SearchMatch {
byte_offset: match_doc_offset,
length: m.end() - m.start(),
line: line_at,
column,
context,
});
}
running_line += data.iter().filter(|&&b| b == b'\n').count();
let tail_start = data.len().saturating_sub(overlap_size);
prev_tail = data[tail_start..].to_vec();
}
}
}
all_matches.truncate(max_matches);
Ok(all_matches)
}
}
/// Search the overlap zone between two regions for matches that span the
/// boundary. `prev_tail` is the tail of the previous region, `next_head`
/// is the head of the next region. `doc_offset` is the document byte
/// offset of `prev_tail[0]`. Only matches that cross the boundary (start
/// in tail, end in head) are returned — pure-tail matches were already found.
fn search_boundary_overlap(
prev_tail: &[u8],
next_head: &[u8],
doc_offset: usize,
running_line: usize,
regex: &Regex,
max_matches: usize,
) -> Vec<SearchMatch> {
let mut buf = Vec::with_capacity(prev_tail.len() + next_head.len());
buf.extend_from_slice(prev_tail);
buf.extend_from_slice(next_head);
let overlap_len = prev_tail.len();
let newlines_before = prev_tail.iter().filter(|&&b| b == b'\n').count();
let mut line_at = running_line.saturating_sub(newlines_before);
let mut counted_to = 0usize;
let mut matches = Vec::new();
for m in regex.find_iter(&buf) {
// Only keep matches that cross the boundary
if m.start() < overlap_len && m.end() > overlap_len {
if matches.len() >= max_matches {
break;
}
line_at += buf[counted_to..m.start()]
.iter()
.filter(|&&b| b == b'\n')
.count();
counted_to = m.start();
let line_start = buf[..m.start()]
.iter()
.rposition(|&b| b == b'\n')
.map(|p| p + 1)
.unwrap_or(0);
let line_end = buf[m.start()..]
.iter()
.position(|&b| b == b'\n')
.map(|p| m.start() + p)
.unwrap_or(buf.len());
let column = m.start() - line_start + 1;
let context = String::from_utf8_lossy(&buf[line_start..line_end]).into_owned();
matches.push(SearchMatch {
byte_offset: doc_offset + m.start(),
length: m.end() - m.start(),
line: line_at,
column,
context,
});
}
}
matches
}
#[cfg(test)]
mod tests {
use crate::model::filesystem::StdFileSystem;
use std::sync::Arc;
fn test_fs() -> Arc<dyn crate::model::filesystem::FileSystem + Send + Sync> {
Arc::new(StdFileSystem)
}
use super::*;
#[test]
fn test_empty_buffer() {
let buffer = TextBuffer::empty(test_fs());
assert_eq!(buffer.total_bytes(), 0);
assert_eq!(buffer.line_count(), Some(1)); // Empty doc has 1 line
}
#[test]
fn test_line_positions_multiline() {
let buffer = TextBuffer::from_bytes(b"Hello\nNew Line\nWorld!".to_vec(), test_fs());
// Check line count
assert_eq!(buffer.line_count(), Some(3));
// Check line starts
assert_eq!(buffer.line_start_offset(0), Some(0)); // "Hello\n" starts at 0
assert_eq!(buffer.line_start_offset(1), Some(6)); // "New Line\n" starts at 6
assert_eq!(buffer.line_start_offset(2), Some(15)); // "World!" starts at 15
// Check offset_to_position
assert_eq!(buffer.offset_to_position(0).unwrap().line, 0); // Start of "Hello"
assert_eq!(buffer.offset_to_position(5).unwrap().line, 0); // End of "Hello" (before \n)
assert_eq!(buffer.offset_to_position(6).unwrap().line, 1); // Start of "New Line"
assert_eq!(buffer.offset_to_position(14).unwrap().line, 1); // End of "New Line" (before \n)
assert_eq!(buffer.offset_to_position(15).unwrap().line, 2); // Start of "World!"
// Check line_col_to_position
assert_eq!(buffer.line_col_to_position(0, 5), 5); // End of line 0
assert_eq!(buffer.line_col_to_position(1, 0), 6); // Start of line 1
assert_eq!(buffer.line_col_to_position(1, 8), 14); // End of line 1
assert_eq!(buffer.line_col_to_position(2, 0), 15); // Start of line 2
}
#[test]
fn test_new_from_content() {
let buffer = TextBuffer::from_bytes(b"hello\nworld".to_vec(), test_fs());
assert_eq!(buffer.total_bytes(), 11);
assert_eq!(buffer.line_count(), Some(2));
}
#[test]
fn test_get_all_text() {
let buffer = TextBuffer::from_bytes(b"hello\nworld".to_vec(), test_fs());
assert_eq!(buffer.get_all_text().unwrap(), b"hello\nworld");
}
#[test]
fn test_insert_at_start() {
let mut buffer = TextBuffer::from_bytes(b"world".to_vec(), test_fs());
buffer.insert_bytes(0, b"hello ".to_vec());
assert_eq!(buffer.get_all_text().unwrap(), b"hello world");
assert_eq!(buffer.total_bytes(), 11);
}
#[test]
fn test_insert_in_middle() {
let mut buffer = TextBuffer::from_bytes(b"helloworld".to_vec(), test_fs());
buffer.insert_bytes(5, b" ".to_vec());
assert_eq!(buffer.get_all_text().unwrap(), b"hello world");
assert_eq!(buffer.total_bytes(), 11);
}
#[test]
fn test_insert_at_end() {
let mut buffer = TextBuffer::from_bytes(b"hello".to_vec(), test_fs());
buffer.insert_bytes(5, b" world".to_vec());
assert_eq!(buffer.get_all_text().unwrap(), b"hello world");
assert_eq!(buffer.total_bytes(), 11);
}
#[test]
fn test_insert_with_newlines() {
let mut buffer = TextBuffer::from_bytes(b"hello".to_vec(), test_fs());
buffer.insert_bytes(5, b"\nworld\ntest".to_vec());
assert_eq!(buffer.get_all_text().unwrap(), b"hello\nworld\ntest");
assert_eq!(buffer.line_count(), Some(3));
}
#[test]
fn test_delete_from_start() {
let mut buffer = TextBuffer::from_bytes(b"hello world".to_vec(), test_fs());
buffer.delete_bytes(0, 6);
assert_eq!(buffer.get_all_text().unwrap(), b"world");
assert_eq!(buffer.total_bytes(), 5);
}
#[test]
fn test_delete_from_middle() {
let mut buffer = TextBuffer::from_bytes(b"hello world".to_vec(), test_fs());
buffer.delete_bytes(5, 1);
assert_eq!(buffer.get_all_text().unwrap(), b"helloworld");
assert_eq!(buffer.total_bytes(), 10);
}
#[test]
fn test_delete_from_end() {
let mut buffer = TextBuffer::from_bytes(b"hello world".to_vec(), test_fs());
buffer.delete_bytes(6, 5);
assert_eq!(buffer.get_all_text().unwrap(), b"hello ");
assert_eq!(buffer.total_bytes(), 6);
}
#[test]
fn test_delete_with_newlines() {
let mut buffer = TextBuffer::from_bytes(b"hello\nworld\ntest".to_vec(), test_fs());
buffer.delete_bytes(5, 7); // Delete "\nworld\n"
assert_eq!(buffer.get_all_text().unwrap(), b"hellotest");
assert_eq!(buffer.line_count(), Some(1));
}
#[test]
fn test_offset_position_conversions() {
let buffer = TextBuffer::from_bytes(b"hello\nworld\ntest".to_vec(), test_fs());
let pos = buffer.offset_to_position(0);
assert_eq!(pos, Some(Position { line: 0, column: 0 }));
let pos = buffer.offset_to_position(6);
assert_eq!(pos, Some(Position { line: 1, column: 0 }));
let offset = buffer.position_to_offset(Position { line: 1, column: 0 });
assert_eq!(offset, 6);
}
#[test]
fn test_insert_at_position() {
let mut buffer = TextBuffer::from_bytes(b"hello\nworld".to_vec(), test_fs());
buffer.insert_at_position(Position { line: 1, column: 0 }, b"beautiful ".to_vec());
assert_eq!(buffer.get_all_text().unwrap(), b"hello\nbeautiful world");
}
#[test]
fn test_delete_range() {
let mut buffer = TextBuffer::from_bytes(b"hello\nworld\ntest".to_vec(), test_fs());
let start = Position { line: 0, column: 5 };
let end = Position { line: 2, column: 0 };
buffer.delete_range(start, end);
assert_eq!(buffer.get_all_text().unwrap(), b"hellotest");
}
#[test]
fn test_get_line() {
let buffer = TextBuffer::from_bytes(b"hello\nworld\ntest".to_vec(), test_fs());
assert_eq!(buffer.get_line(0), Some(b"hello\n".to_vec()));
assert_eq!(buffer.get_line(1), Some(b"world\n".to_vec()));
assert_eq!(buffer.get_line(2), Some(b"test".to_vec()));
assert_eq!(buffer.get_line(3), None);
}
#[test]
fn test_multiple_operations() {
let mut buffer = TextBuffer::from_bytes(b"line1\nline2\nline3".to_vec(), test_fs());
buffer.insert_bytes(0, b"start\n".to_vec());
assert_eq!(buffer.line_count(), Some(4));
buffer.delete_bytes(6, 6); // Delete "line1\n"
assert_eq!(buffer.line_count(), Some(3));
buffer.insert_bytes(6, b"new\n".to_vec());
assert_eq!(buffer.line_count(), Some(4));
let text = buffer.get_all_text().unwrap();
assert_eq!(text, b"start\nnew\nline2\nline3");
}
#[test]
fn test_get_text_range() {
let buffer = TextBuffer::from_bytes(b"hello world".to_vec(), test_fs());
assert_eq!(buffer.get_text_range(0, 5), Some(b"hello".to_vec()));
assert_eq!(buffer.get_text_range(6, 5), Some(b"world".to_vec()));
assert_eq!(buffer.get_text_range(0, 11), Some(b"hello world".to_vec()));
}
#[test]
fn test_empty_operations() {
let mut buffer = TextBuffer::from_bytes(b"hello".to_vec(), test_fs());
buffer.insert_bytes(2, Vec::new());
assert_eq!(buffer.get_all_text().unwrap(), b"hello");
buffer.delete_bytes(2, 0);
assert_eq!(buffer.get_all_text().unwrap(), b"hello");
}
#[test]
fn test_sequential_inserts_at_beginning() {
// Regression test for piece tree duplicate insertion bug
let mut buffer = TextBuffer::from_bytes(b"initial\ntext".to_vec(), test_fs());
// Delete all
buffer.delete_bytes(0, 12);
assert_eq!(buffer.get_all_text().unwrap(), b"");
// Insert 'a' at 0
buffer.insert_bytes(0, vec![b'a']);
assert_eq!(buffer.get_all_text().unwrap(), b"a");
// Insert 'b' at 0 (should give "ba")
buffer.insert_bytes(0, vec![b'b']);
assert_eq!(buffer.get_all_text().unwrap(), b"ba");
}
// ===== Phase 1-3: Large File Support Tests =====
mod large_file_support {
use super::*;
use crate::model::piece_tree::StringBuffer;
use std::fs::File;
use std::io::Write;
use tempfile::TempDir;
// Phase 1: Option<usize> Type Safety Tests
#[test]
fn test_line_feed_count_is_some_for_loaded_buffer() {
let buffer = StringBuffer::new(0, b"hello\nworld\ntest".to_vec());
assert_eq!(buffer.line_feed_count(), Some(2));
}
#[test]
fn test_line_feed_count_is_none_for_unloaded_buffer() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("test.txt");
let buffer = StringBuffer::new_unloaded(0, file_path, 0, 100);
assert_eq!(buffer.line_feed_count(), None);
}
#[test]
fn test_line_count_is_some_for_small_buffer() {
let buffer = TextBuffer::from_bytes(b"hello\nworld\ntest".to_vec(), test_fs());
assert_eq!(buffer.line_count(), Some(3));
}
#[test]
fn test_piece_tree_works_with_none_line_count() {
// Create a buffer with no line count information
let buffer = StringBuffer::new_loaded(0, b"hello\nworld".to_vec(), false);
assert_eq!(buffer.line_feed_count(), None);
// Create piece tree without line feed count
use crate::model::piece_tree::{BufferLocation, PieceTree};
let tree = PieceTree::new(BufferLocation::Stored(0), 0, 11, None);
// line_count should return None
assert_eq!(tree.line_count(), None);
}
// Phase 2: BufferData Enum Tests
#[test]
fn test_buffer_data_loaded_variant() {
let data = b"hello world".to_vec();
let buffer = StringBuffer::new_loaded(0, data.clone(), true);
assert!(buffer.is_loaded());
assert_eq!(buffer.get_data(), Some(&data[..]));
assert!(buffer.get_line_starts().is_some());
}
#[test]
fn test_buffer_data_loaded_without_line_starts() {
let data = b"hello\nworld".to_vec();
let buffer = StringBuffer::new_loaded(0, data.clone(), false);
assert!(buffer.is_loaded());
assert_eq!(buffer.get_data(), Some(&data[..]));
assert_eq!(buffer.get_line_starts(), None); // No line indexing
}
#[test]
fn test_buffer_data_unloaded_variant() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("test.txt");
let buffer = StringBuffer::new_unloaded(0, file_path.clone(), 0, 100);
assert!(!buffer.is_loaded());
assert_eq!(buffer.get_data(), None);
assert_eq!(buffer.get_line_starts(), None);
}
#[test]
fn test_buffer_load_method() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("test.txt");
// Create test file
let test_data = b"hello world";
File::create(&file_path)
.unwrap()
.write_all(test_data)
.unwrap();
// Create unloaded buffer
let mut buffer = StringBuffer::new_unloaded(0, file_path, 0, test_data.len());
assert!(!buffer.is_loaded());
// Load the buffer using local filesystem
let fs = crate::model::filesystem::StdFileSystem;
buffer.load(&fs).unwrap();
// Now it should be loaded
assert!(buffer.is_loaded());
assert_eq!(buffer.get_data(), Some(&test_data[..]));
}
#[test]
fn test_string_buffer_new_vs_new_loaded() {
let data = b"hello\nworld".to_vec();
// StringBuffer::new should compute line starts
let buf1 = StringBuffer::new(0, data.clone());
assert!(buf1.is_loaded());
assert!(buf1.get_line_starts().is_some());
assert_eq!(buf1.line_feed_count(), Some(1));
// StringBuffer::new_loaded with compute_lines=false should not
let buf2 = StringBuffer::new_loaded(0, data.clone(), false);
assert!(buf2.is_loaded());
assert_eq!(buf2.get_line_starts(), None);
assert_eq!(buf2.line_feed_count(), None);
}
// Phase 3: Large File Detection Tests
#[test]
fn test_load_small_file_eager_loading() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("small.txt");
// Create a small file (10 bytes < 100MB threshold)
let test_data = b"hello\ntest";
File::create(&file_path)
.unwrap()
.write_all(test_data)
.unwrap();
// Load with default threshold
let buffer = TextBuffer::load_from_file(&file_path, 0, test_fs()).unwrap();
// Should be eagerly loaded (not large_file mode)
assert!(!buffer.large_file);
assert_eq!(buffer.total_bytes(), test_data.len());
assert_eq!(buffer.line_count(), Some(2)); // Has line indexing
assert_eq!(buffer.get_all_text().unwrap(), test_data);
// The buffer should be loaded
assert!(buffer.buffers[0].is_loaded());
}
#[test]
fn test_load_large_file_lazy_loading() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("large.txt");
// Create a "large" file by using a small threshold
let test_data = b"hello\nworld\ntest";
File::create(&file_path)
.unwrap()
.write_all(test_data)
.unwrap();
// Load with threshold of 10 bytes (file is 17 bytes, so it's "large")
let buffer = TextBuffer::load_from_file(&file_path, 10, test_fs()).unwrap();
// Should be in large_file mode
assert!(buffer.large_file);
assert_eq!(buffer.total_bytes(), test_data.len());
// Should NOT have line indexing
assert_eq!(buffer.line_count(), None);
// The buffer should be unloaded
assert!(!buffer.buffers[0].is_loaded());
assert_eq!(buffer.buffers[0].get_data(), None);
}
/// Test that reproduces issue #657: Search on large plain text files
///
/// The bug: When a large file is opened with lazy loading, buffer.to_string()
/// returns None because some buffers are unloaded. This causes search to fail
/// with "Buffer not fully loaded" error.
///
/// The fix: Use get_text_range_mut() which loads the buffer on demand.
#[test]
fn test_issue_657_search_on_large_file_unloaded_buffer() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("large_search_test.txt");
// Create test content with a searchable string
let test_data = b"line1\nline2\nSEARCH_TARGET\nline4\nline5";
File::create(&file_path)
.unwrap()
.write_all(test_data)
.unwrap();
// Load with small threshold to force lazy loading
let mut buffer = TextBuffer::load_from_file(&file_path, 10, test_fs()).unwrap();
// Verify we're in large file mode with unloaded buffer
assert!(buffer.large_file, "Buffer should be in large file mode");
assert!(
!buffer.buffers[0].is_loaded(),
"Buffer should be unloaded initially"
);
// REPRODUCE THE BUG: to_string() returns None for unloaded buffers
// This is what the old perform_search() code did, causing the error
assert!(
buffer.to_string().is_none(),
"BUG REPRODUCED: to_string() returns None for unloaded buffer"
);
// THE FIX: get_text_range_mut() loads the buffer on demand
let total_bytes = buffer.len();
let content = buffer.get_text_range_mut(0, total_bytes).unwrap();
let content_str = String::from_utf8_lossy(&content);
// Verify the content is now available and contains our search target
assert!(
content_str.contains("SEARCH_TARGET"),
"FIX WORKS: get_text_range_mut() loaded the buffer and found the search target"
);
// After loading, to_string() should also work
assert!(
buffer.to_string().is_some(),
"After get_text_range_mut(), to_string() should work"
);
}
#[test]
fn test_large_file_threshold_boundary() {
let temp_dir = TempDir::new().unwrap();
// Test exactly at threshold
let file_path = temp_dir.path().join("at_threshold.txt");
let test_data = vec![b'x'; 100];
File::create(&file_path)
.unwrap()
.write_all(&test_data)
.unwrap();
// Load with threshold of 100 bytes - should be large file (>= threshold)
let buffer = TextBuffer::load_from_file(&file_path, 100, test_fs()).unwrap();
assert!(buffer.large_file);
// Test just below threshold
let file_path2 = temp_dir.path().join("below_threshold.txt");
let test_data2 = vec![b'x'; 99];
File::create(&file_path2)
.unwrap()
.write_all(&test_data2)
.unwrap();
// Load with threshold of 100 bytes - should be small file (< threshold)
let buffer2 = TextBuffer::load_from_file(&file_path2, 100, test_fs()).unwrap();
assert!(!buffer2.large_file);
}
#[test]
fn test_large_file_default_threshold() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("test.txt");
// Create a small file
File::create(&file_path)
.unwrap()
.write_all(b"hello")
.unwrap();
// Load with threshold 0 - should use DEFAULT_LARGE_FILE_THRESHOLD
let buffer = TextBuffer::load_from_file(&file_path, 0, test_fs()).unwrap();
// 5 bytes < 100MB, so should not be large file
assert!(!buffer.large_file);
}
#[test]
fn test_large_file_has_correct_piece_tree_structure() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("large.txt");
let test_data = b"hello world";
File::create(&file_path)
.unwrap()
.write_all(test_data)
.unwrap();
// Load as large file
let buffer = TextBuffer::load_from_file(&file_path, 5, test_fs()).unwrap();
// Should have correct total bytes
assert_eq!(buffer.total_bytes(), test_data.len());
// Should have 1 buffer
assert_eq!(buffer.buffers.len(), 1);
// Buffer should be unloaded
assert!(!buffer.buffers[0].is_loaded());
}
#[test]
fn test_empty_large_file() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("empty.txt");
// Create an empty file
File::create(&file_path).unwrap();
// Load as large file
let buffer = TextBuffer::load_from_file(&file_path, 0, test_fs()).unwrap();
// Empty file is handled gracefully
assert_eq!(buffer.total_bytes(), 0);
assert!(buffer.is_empty());
}
#[test]
fn test_large_file_basic_api_operations() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("large_test.txt");
// Create a test file with known content
let test_data = b"line1\nline2\nline3\nline4\n";
File::create(&file_path)
.unwrap()
.write_all(test_data)
.unwrap();
// Load as large file (use small threshold to trigger large file mode)
let mut buffer = TextBuffer::load_from_file(&file_path, 10, test_fs()).unwrap();
// Verify it's in large file mode
assert!(buffer.large_file);
assert_eq!(buffer.line_count(), None); // No line indexing
// Test basic access functions
assert_eq!(buffer.total_bytes(), test_data.len());
assert!(!buffer.is_empty());
assert_eq!(buffer.len(), test_data.len());
// Test reading operations using get_text_range_mut (lazy loads on demand)
let range_result = buffer.get_text_range_mut(0, 5).unwrap();
assert_eq!(range_result, b"line1");
let range_result2 = buffer.get_text_range_mut(6, 5).unwrap();
assert_eq!(range_result2, b"line2");
// Test get_all_text (via get_text_range after lazy loading)
let all_text = buffer.get_all_text().unwrap();
assert_eq!(all_text, test_data);
// Test slice_bytes method
assert_eq!(buffer.slice_bytes(0..5), b"line1");
// Test basic editing operations
// Insert at offset 0
buffer.insert_bytes(0, b"prefix_".to_vec());
assert_eq!(buffer.total_bytes(), test_data.len() + 7);
assert!(buffer.is_modified());
// Verify the insertion worked
let text_after_insert = buffer.get_all_text().unwrap();
assert_eq!(&text_after_insert[0..7], b"prefix_");
assert_eq!(&text_after_insert[7..12], b"line1");
// Delete some bytes
buffer.delete_bytes(0, 7);
assert_eq!(buffer.total_bytes(), test_data.len());
// Verify deletion worked - should be back to original
let text_after_delete = buffer.get_all_text().unwrap();
assert_eq!(text_after_delete, test_data);
// Insert at end
let end_offset = buffer.total_bytes();
buffer.insert_bytes(end_offset, b"suffix".to_vec());
assert_eq!(buffer.total_bytes(), test_data.len() + 6);
// Verify end insertion
let final_text = buffer.get_all_text().unwrap();
assert!(final_text.ends_with(b"suffix"));
assert_eq!(&final_text[0..test_data.len()], test_data);
// Test offset_to_position
// Note: Without line indexing, position tracking is limited
// but byte-level operations still work
let pos = buffer.offset_to_position(0).unwrap();
assert_eq!(pos.column, 0);
// Test position_to_offset
let offset = buffer.position_to_offset(Position { line: 0, column: 0 });
assert_eq!(offset, 0);
// Test replace operations
let replace_result = buffer.replace_range(0..5, "START");
assert!(replace_result);
let text_after_replace = buffer.get_all_text().unwrap();
assert!(text_after_replace.starts_with(b"START"));
}
#[test]
fn test_large_file_chunk_based_loading() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("huge.txt");
// Create a file larger than LOAD_CHUNK_SIZE (1MB)
// We'll create a 3MB file with a repeating pattern so we can verify chunks
let chunk_size = LOAD_CHUNK_SIZE; // 1MB
let file_size = chunk_size * 3; // 3MB
// Pattern: "AAAA...AAAA" (1MB of A's), "BBBB...BBBB" (1MB of B's), "CCCC...CCCC" (1MB of C's)
let mut file = File::create(&file_path).unwrap();
file.write_all(&vec![b'A'; chunk_size]).unwrap();
file.write_all(&vec![b'B'; chunk_size]).unwrap();
file.write_all(&vec![b'C'; chunk_size]).unwrap();
file.flush().unwrap();
// Load as large file (use threshold of 1 byte to ensure large file mode)
let mut buffer = TextBuffer::load_from_file(&file_path, 1, test_fs()).unwrap();
// Verify it's in large file mode
assert!(buffer.large_file);
assert_eq!(buffer.total_bytes(), file_size);
// Buffer should be unloaded initially
assert!(!buffer.buffers[0].is_loaded());
// Read from the first chunk (should load only first 1MB)
let first_chunk_data = buffer.get_text_range_mut(0, 1024).unwrap();
assert_eq!(first_chunk_data.len(), 1024);
assert!(first_chunk_data.iter().all(|&b| b == b'A'));
// Read from the middle chunk (offset = 1MB, should load second 1MB)
let second_chunk_data = buffer.get_text_range_mut(chunk_size, 1024).unwrap();
assert_eq!(second_chunk_data.len(), 1024);
assert!(second_chunk_data.iter().all(|&b| b == b'B'));
// Read from the last chunk (offset = 2MB, should load third 1MB)
let third_chunk_data = buffer.get_text_range_mut(chunk_size * 2, 1024).unwrap();
assert_eq!(third_chunk_data.len(), 1024);
assert!(third_chunk_data.iter().all(|&b| b == b'C'));
// Verify we can read across chunk boundaries
// Read from middle of first chunk to middle of second chunk
let cross_chunk_offset = chunk_size - 512;
let cross_chunk_data = buffer.get_text_range_mut(cross_chunk_offset, 1024).unwrap();
assert_eq!(cross_chunk_data.len(), 1024);
// First 512 bytes should be 'A', next 512 bytes should be 'B'
assert!(cross_chunk_data[..512].iter().all(|&b| b == b'A'));
assert!(cross_chunk_data[512..].iter().all(|&b| b == b'B'));
// After chunk-based loading, verify the piece tree has been split
// The number of buffers should be greater than 1 (original + chunks)
assert!(
buffer.buffers.len() > 1,
"Expected multiple buffers after chunk-based loading, got {}",
buffer.buffers.len()
);
// Test that editing still works after chunk-based loading
buffer.insert_bytes(0, b"PREFIX".to_vec());
assert_eq!(buffer.total_bytes(), file_size + 6);
let after_insert = buffer.get_text_range_mut(0, 6).unwrap();
assert_eq!(after_insert, b"PREFIX");
// Verify the original data is still there after the prefix
let after_prefix = buffer.get_text_range_mut(6, 10).unwrap();
assert!(after_prefix.iter().all(|&b| b == b'A'));
// Most importantly: validate the entire buffer content matches the original file
// Create a fresh buffer to read the original file
let mut buffer2 = TextBuffer::load_from_file(&file_path, 1, test_fs()).unwrap();
// Read the entire file in chunks and verify each chunk
let chunk_read_size = 64 * 1024; // Read in 64KB chunks for efficiency
let mut offset = 0;
while offset < file_size {
let bytes_to_read = chunk_read_size.min(file_size - offset);
let chunk_data = buffer2.get_text_range_mut(offset, bytes_to_read).unwrap();
// Determine which section of the file we're reading
let first_mb_end = chunk_size;
let second_mb_end = chunk_size * 2;
// Validate the data based on which MB section we're in
for (i, &byte) in chunk_data.iter().enumerate() {
let file_offset = offset + i;
let expected = if file_offset < first_mb_end {
b'A'
} else if file_offset < second_mb_end {
b'B'
} else {
b'C'
};
assert_eq!(
byte, expected,
"Mismatch at file offset {}: expected {}, got {}",
file_offset, expected as char, byte as char
);
}
offset += bytes_to_read;
}
}
/// Test that save_to_file works correctly with partially loaded large files
/// This is a regression test for a bug where saving would silently produce
/// an empty file if any buffer regions were still unloaded.
#[test]
fn test_large_file_incremental_save() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("large_save_test.txt");
// Create a small file but use tiny threshold to trigger large file mode
let chunk_size = 1000; // 1KB chunks
let file_size = chunk_size * 2; // 2KB total
let mut file = File::create(&file_path).unwrap();
// First half: 'A' repeated
file.write_all(&vec![b'A'; chunk_size]).unwrap();
// Second half: 'B' repeated
file.write_all(&vec![b'B'; chunk_size]).unwrap();
file.flush().unwrap();
// Load as large file (threshold of 100 bytes)
let mut buffer = TextBuffer::load_from_file(&file_path, 100, test_fs()).unwrap();
assert!(buffer.large_file);
assert_eq!(buffer.total_bytes(), file_size);
// Only read from the beginning - this loads only a small region
let first_bytes = buffer.get_text_range_mut(0, 50).unwrap();
assert!(first_bytes.iter().all(|&b| b == b'A'));
// Make an edit at the beginning
buffer.insert_bytes(0, b"PREFIX_".to_vec());
// Save to a new file (to avoid issues with reading while writing same file)
let save_path = temp_dir.path().join("saved.txt");
buffer.save_to_file(&save_path).unwrap();
// Verify the saved file
let saved_content = std::fs::read(&save_path).unwrap();
// Check total size: original + "PREFIX_" (7 bytes)
assert_eq!(
saved_content.len(),
file_size + 7,
"Saved file should be {} bytes, got {}",
file_size + 7,
saved_content.len()
);
// Check prefix
assert_eq!(&saved_content[..7], b"PREFIX_", "Should start with PREFIX_");
// Check that first chunk (after prefix) contains A's
assert!(
saved_content[7..100].iter().all(|&b| b == b'A'),
"First chunk after prefix should be A's"
);
// Check that second chunk contains B's (this was unloaded!)
let second_chunk_start = 7 + chunk_size;
assert!(
saved_content[second_chunk_start..second_chunk_start + 100]
.iter()
.all(|&b| b == b'B'),
"Second chunk should be B's (was unloaded, should be preserved)"
);
}
/// Test that save_to_file handles edits at multiple positions
#[test]
fn test_large_file_save_with_multiple_edits() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("multi_edit.txt");
// Create a ~5KB file with numbered lines for easier verification
let mut content = Vec::new();
for i in 0..100 {
content.extend_from_slice(
format!("Line {:04}: padding to make it longer\n", i).as_bytes(),
);
}
let original_len = content.len();
std::fs::write(&file_path, &content).unwrap();
// Load as large file (threshold of 500 bytes)
let mut buffer = TextBuffer::load_from_file(&file_path, 500, test_fs()).unwrap();
assert!(
buffer.line_count().is_none(),
"Should be in large file mode"
);
// Edit at the beginning
buffer.insert_bytes(0, b"[START]".to_vec());
// Edit somewhere in the middle (load that region first)
let mid_offset = original_len / 2;
let _mid_bytes = buffer.get_text_range_mut(mid_offset + 7, 10).unwrap(); // +7 for our insert
buffer.insert_bytes(mid_offset + 7, b"[MIDDLE]".to_vec());
// Save
let save_path = temp_dir.path().join("multi_edit_saved.txt");
buffer.save_to_file(&save_path).unwrap();
// Verify
let saved = std::fs::read_to_string(&save_path).unwrap();
assert!(
saved.starts_with("[START]Line 0000"),
"Should start with our edit"
);
assert!(saved.contains("[MIDDLE]"), "Should contain middle edit");
assert!(saved.contains("Line 0099"), "Should preserve end of file");
// Verify total length
let expected_len = original_len + 7 + 8; // [START] + [MIDDLE]
assert_eq!(
saved.len(),
expected_len,
"Length should be original + edits"
);
}
}
// ===== Offset to Position Tests =====
// These tests focus on the offset_to_position correctness
#[test]
fn test_offset_to_position_simple() {
// Create a buffer with known line structure
// Line 0: "a\n" (bytes 0-1, newline at 1)
// Line 1: "b\n" (bytes 2-3, newline at 3)
// Line 2: "c\n" (bytes 4-5, newline at 5)
// Line 3: "d" (bytes 6, no newline)
let content = b"a\nb\nc\nd";
let buffer = TextBuffer::from_bytes(content.to_vec(), test_fs());
// Verify specific positions
let pos = buffer
.offset_to_position(0)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 0, "Byte 0 should be on line 0");
assert_eq!(pos.column, 0);
let pos = buffer
.offset_to_position(1)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 0, "Byte 1 (newline) should be on line 0");
assert_eq!(pos.column, 1);
let pos = buffer
.offset_to_position(2)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 1, "Byte 2 should be on line 1");
assert_eq!(pos.column, 0);
let pos = buffer
.offset_to_position(3)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 1, "Byte 3 (newline) should be on line 1");
assert_eq!(pos.column, 1);
let pos = buffer
.offset_to_position(4)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 2, "Byte 4 should be on line 2");
assert_eq!(pos.column, 0);
let pos = buffer
.offset_to_position(6)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 3, "Byte 6 should be on line 3");
assert_eq!(pos.column, 0);
}
#[test]
fn test_offset_to_position_after_insert() {
// Start with simple content
let mut buffer = TextBuffer::from_bytes(b"a\nb\n".to_vec(), test_fs());
// Insert at position 2 (start of line 1)
buffer.insert_at_position(Position { line: 1, column: 0 }, b"x\n".to_vec());
// After insert, buffer should be: "a\nx\nb\n"
// Line 0: "a\n" (bytes 0-1)
// Line 1: "x\n" (bytes 2-3)
// Line 2: "b\n" (bytes 4-5)
let pos = buffer
.offset_to_position(0)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 0, "Byte 0 should still be on line 0");
let pos = buffer
.offset_to_position(2)
.expect("small buffer should have line metadata");
assert_eq!(
pos.line, 1,
"Byte 2 (start of inserted line) should be on line 1"
);
let pos = buffer
.offset_to_position(4)
.expect("small buffer should have line metadata");
assert_eq!(
pos.line, 2,
"Byte 4 (start of 'b') should be on line 2 after insert"
);
}
#[test]
fn test_offset_to_position_empty_lines() {
// Test with empty lines: "\n\n\n"
let buffer = TextBuffer::from_bytes(b"\n\n\n".to_vec(), test_fs());
// Line 0: "\n" (byte 0)
// Line 1: "\n" (byte 1)
// Line 2: "\n" (byte 2)
// Line 3: "" (empty, after last newline)
let pos = buffer
.offset_to_position(0)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 0, "Byte 0 should be on line 0");
let pos = buffer
.offset_to_position(1)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 1, "Byte 1 should be on line 1");
let pos = buffer
.offset_to_position(2)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 2, "Byte 2 should be on line 2");
let pos = buffer
.offset_to_position(3)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 3, "Byte 3 (EOF) should be on line 3");
}
#[test]
fn test_offset_to_position_long_lines() {
// Test with long lines to ensure it's not just line counting
let mut content = Vec::new();
content.extend_from_slice(b"aaaaaaaaaa\n"); // Line 0: 11 bytes (10 'a's + newline)
content.extend_from_slice(b"bbbbbbbbbb\n"); // Line 1: 11 bytes
content.extend_from_slice(b"cccccccccc"); // Line 2: 10 bytes (no newline)
let buffer = TextBuffer::from_bytes(content.clone(), test_fs());
// Test positions at start of each line
let pos = buffer
.offset_to_position(0)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 0, "Byte 0 should be on line 0");
assert_eq!(pos.column, 0);
let pos = buffer
.offset_to_position(11)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 1, "Byte 11 (start of line 1) should be on line 1");
assert_eq!(pos.column, 0);
let pos = buffer
.offset_to_position(22)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 2, "Byte 22 (start of line 2) should be on line 2");
assert_eq!(pos.column, 0);
// Test mid-line positions
let pos = buffer
.offset_to_position(5)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 0, "Byte 5 should be on line 0");
assert_eq!(pos.column, 5);
let pos = buffer
.offset_to_position(16)
.expect("small buffer should have line metadata");
assert_eq!(pos.line, 1, "Byte 16 should be on line 1");
assert_eq!(pos.column, 5);
}
#[test]
fn test_line_iterator_with_offset_to_position() {
// This combines line iterator with offset_to_position to find issues
let mut buffer = TextBuffer::from_bytes(b"line0\nline1\nline2\n".to_vec(), test_fs());
// Test creating line iterator at various positions
for byte_pos in 0..=buffer.len() {
let iter = buffer.line_iterator(byte_pos, 80);
let iter_pos = iter.current_position();
let expected_line = buffer
.offset_to_position(byte_pos)
.expect("small buffer should have line metadata")
.line;
let expected_line_start = buffer.position_to_offset(Position {
line: expected_line,
column: 0,
});
assert_eq!(
iter_pos, expected_line_start,
"LineIterator at byte {} should position at line start {} but got {}",
byte_pos, expected_line_start, iter_pos
);
}
}
#[test]
fn test_piece_tree_line_count_after_insert() {
// Debug the piece tree structure after insert
let mut buffer = TextBuffer::from_bytes(b"a\nb\n".to_vec(), test_fs());
// Insert at line 1, column 0
buffer.insert_at_position(Position { line: 1, column: 0 }, b"x\n".to_vec());
// Manually verify line counts
let content = buffer.slice_bytes(0..buffer.len());
let newline_count = content.iter().filter(|&&b| b == b'\n').count();
let expected_line_count = newline_count + 1;
let actual_line_count = buffer.line_count();
assert_eq!(
actual_line_count,
Some(expected_line_count),
"Line count mismatch after insert"
);
}
#[test]
fn test_position_to_lsp_position_after_modification() {
// This test demonstrates a bug in the piece tree's offset_to_position
// where column calculation is incorrect after buffer modifications.
// The position_to_lsp_position function works around this by using
// line_start_offset to calculate the column correctly.
// Initial content: "fn foo(val: i32) {\n val + 1\n}\n"
let initial = b"fn foo(val: i32) {\n val + 1\n}\n";
let mut buffer = TextBuffer::from_bytes(initial.to_vec(), test_fs());
// Verify initial positions work correctly
// Position 23 is 'v' of second "val" on line 1
let (line, char) = buffer.position_to_lsp_position(23);
assert_eq!(line, 1, "Initial: position 23 should be on line 1");
assert_eq!(char, 4, "Initial: position 23 should be at char 4");
// Simulate rename: delete "val" at position 23 (line 1, char 4) and insert "value"
// Position 23 = line 1, char 4; Position 26 = line 1, char 7
buffer.delete_range(
Position { line: 1, column: 4 },
Position { line: 1, column: 7 },
);
buffer.insert_bytes(23, b"value".to_vec()); // Insert "value"
// Also rename the first occurrence
// Position 7 = line 0, char 7; Position 10 = line 0, char 10
buffer.delete_range(
Position { line: 0, column: 7 },
Position {
line: 0,
column: 10,
},
);
buffer.insert_bytes(7, b"value".to_vec()); // Insert "value"
// Buffer is now: "fn foo(value: i32) {\n value + 1\n}\n"
let content = String::from_utf8_lossy(&buffer.get_all_text().unwrap()).to_string();
assert_eq!(content, "fn foo(value: i32) {\n value + 1\n}\n");
// Position 25 is now 'v' of second "value" on line 1
// Line 0: "fn foo(value: i32) {\n" = 21 chars (positions 0-20)
// Line 1: " value + 1\n" starts at position 21
// Position 25 = 21 + 4 = line 1, char 4
// The workaround in position_to_lsp_position should give correct result
let (line, char) = buffer.position_to_lsp_position(25);
assert_eq!(
line, 1,
"After modification: position 25 should be on line 1"
);
assert_eq!(
char, 4,
"After modification: position 25 should be at char 4"
);
// Also verify position 21 (start of line 1) works
let (line, char) = buffer.position_to_lsp_position(21);
assert_eq!(line, 1, "Position 21 should be on line 1");
assert_eq!(char, 0, "Position 21 should be at char 0 (start of line)");
}
#[test]
fn test_detect_crlf() {
assert_eq!(
TextBuffer::detect_line_ending(b"hello\r\nworld\r\n"),
LineEnding::CRLF
);
}
#[test]
fn test_detect_lf() {
assert_eq!(
TextBuffer::detect_line_ending(b"hello\nworld\n"),
LineEnding::LF
);
}
#[test]
fn test_normalize_crlf() {
let input = b"hello\r\nworld\r\n".to_vec();
let output = TextBuffer::normalize_line_endings(input);
assert_eq!(output, b"hello\nworld\n");
}
#[test]
fn test_normalize_empty() {
let input = Vec::new();
let output = TextBuffer::normalize_line_endings(input);
assert_eq!(output, Vec::<u8>::new());
}
/// Regression test: get_all_text() returns empty for large files with unloaded regions
///
/// This was the root cause of a bug where recovery auto-save would save 0 bytes
/// for large files, causing data loss on crash recovery.
///
/// The fix is to use get_text_range_mut() which handles lazy loading.
#[test]
fn test_get_all_text_returns_empty_for_unloaded_buffers() {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("large_test.txt");
// Create a 50KB file
let original_content = "X".repeat(50_000);
std::fs::write(&file_path, &original_content).unwrap();
// Load with small threshold to trigger large file mode
let mut buffer = TextBuffer::load_from_file(&file_path, 1024, test_fs()).unwrap();
assert!(buffer.large_file, "Should be in large file mode");
assert!(!buffer.buffers[0].is_loaded(), "Buffer should be unloaded");
// Make a small edit
buffer.insert_bytes(0, b"EDITED: ".to_vec());
// get_all_text() now returns None for unloaded buffers instead of empty
// This is the correct behavior - it signals that content is not available
let content_immutable = buffer.get_all_text();
// get_all_text() returns None because it uses get_text_range() which
// returns None for unloaded regions
assert!(
content_immutable.is_none(),
"get_all_text() should return None for large files with unloaded regions. \
Got Some({} bytes) instead of None.",
content_immutable.as_ref().map(|c| c.len()).unwrap_or(0)
);
// CORRECT BEHAVIOR: get_text_range_mut() handles lazy loading
let total = buffer.total_bytes();
let content_lazy = buffer.get_text_range_mut(0, total).unwrap();
assert_eq!(
content_lazy.len(),
50_000 + 8,
"get_text_range_mut() should return all content with lazy loading"
);
assert!(
String::from_utf8_lossy(&content_lazy).starts_with("EDITED: "),
"Content should start with our edit"
);
}
// ===== Line Ending Conversion Tests =====
mod line_ending_conversion {
use super::*;
#[test]
fn test_convert_lf_to_crlf() {
let input = b"Line 1\nLine 2\nLine 3\n";
let result = TextBuffer::convert_line_endings_to(input, LineEnding::CRLF);
assert_eq!(result, b"Line 1\r\nLine 2\r\nLine 3\r\n");
}
#[test]
fn test_convert_crlf_to_lf() {
let input = b"Line 1\r\nLine 2\r\nLine 3\r\n";
let result = TextBuffer::convert_line_endings_to(input, LineEnding::LF);
assert_eq!(result, b"Line 1\nLine 2\nLine 3\n");
}
#[test]
fn test_convert_cr_to_lf() {
let input = b"Line 1\rLine 2\rLine 3\r";
let result = TextBuffer::convert_line_endings_to(input, LineEnding::LF);
assert_eq!(result, b"Line 1\nLine 2\nLine 3\n");
}
#[test]
fn test_convert_mixed_to_crlf() {
// Mixed line endings: LF, CRLF, CR
let input = b"Line 1\nLine 2\r\nLine 3\r";
let result = TextBuffer::convert_line_endings_to(input, LineEnding::CRLF);
assert_eq!(result, b"Line 1\r\nLine 2\r\nLine 3\r\n");
}
#[test]
fn test_convert_lf_to_lf_is_noop() {
let input = b"Line 1\nLine 2\nLine 3\n";
let result = TextBuffer::convert_line_endings_to(input, LineEnding::LF);
assert_eq!(result, input.to_vec());
}
#[test]
fn test_convert_empty_content() {
let input = b"";
let result = TextBuffer::convert_line_endings_to(input, LineEnding::CRLF);
assert_eq!(result, b"".to_vec());
}
#[test]
fn test_convert_no_line_endings() {
let input = b"No line endings here";
let result = TextBuffer::convert_line_endings_to(input, LineEnding::CRLF);
assert_eq!(result, b"No line endings here".to_vec());
}
#[test]
fn test_set_line_ending_marks_modified() {
let mut buffer = TextBuffer::from_bytes(b"Hello\nWorld\n".to_vec(), test_fs());
assert!(!buffer.is_modified());
buffer.set_line_ending(LineEnding::CRLF);
assert!(buffer.is_modified());
}
#[test]
fn test_set_default_line_ending_does_not_mark_modified() {
let mut buffer = TextBuffer::empty(test_fs());
assert!(!buffer.is_modified());
buffer.set_default_line_ending(LineEnding::CRLF);
assert!(!buffer.is_modified());
assert_eq!(buffer.line_ending(), LineEnding::CRLF);
}
#[test]
fn test_save_to_file_converts_lf_to_crlf() {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("test_lf_to_crlf.txt");
// Create a file with LF line endings
let original_content = b"Line 1\nLine 2\nLine 3\n";
std::fs::write(&file_path, original_content).unwrap();
// Load the file
let mut buffer =
TextBuffer::load_from_file(&file_path, DEFAULT_LARGE_FILE_THRESHOLD, test_fs())
.unwrap();
assert_eq!(buffer.line_ending(), LineEnding::LF);
// Change line ending to CRLF
buffer.set_line_ending(LineEnding::CRLF);
assert_eq!(buffer.line_ending(), LineEnding::CRLF);
assert!(buffer.is_modified());
// Save the file
buffer.save_to_file(&file_path).unwrap();
// Read back and verify CRLF
let saved_bytes = std::fs::read(&file_path).unwrap();
assert_eq!(&saved_bytes, b"Line 1\r\nLine 2\r\nLine 3\r\n");
}
#[test]
fn test_save_to_file_converts_crlf_to_lf() {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("test_crlf_to_lf.txt");
// Create a file with CRLF line endings
let original_content = b"Line 1\r\nLine 2\r\nLine 3\r\n";
std::fs::write(&file_path, original_content).unwrap();
// Load the file
let mut buffer =
TextBuffer::load_from_file(&file_path, DEFAULT_LARGE_FILE_THRESHOLD, test_fs())
.unwrap();
assert_eq!(buffer.line_ending(), LineEnding::CRLF);
// Change line ending to LF
buffer.set_line_ending(LineEnding::LF);
assert_eq!(buffer.line_ending(), LineEnding::LF);
assert!(buffer.is_modified());
// Save the file
buffer.save_to_file(&file_path).unwrap();
// Read back and verify LF (no CRLF)
let saved_bytes = std::fs::read(&file_path).unwrap();
assert_eq!(&saved_bytes, b"Line 1\nLine 2\nLine 3\n");
}
#[test]
#[cfg(unix)]
fn test_save_to_unwritable_file() -> anyhow::Result<()> {
// Root (uid 0) bypasses Unix file permission checks, so these
// permission-denied tests are meaningless when running as root.
if unsafe { libc::getuid() } == 0 {
eprintln!("Skipping test: root bypasses file permission checks");
return Ok(());
}
use std::fs::Permissions;
use std::os::unix::fs::PermissionsExt;
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let unwritable_dir = temp_dir.path().join("unwritable_dir");
std::fs::create_dir(&unwritable_dir)?;
let file_path = unwritable_dir.join("unwritable.txt");
std::fs::write(&file_path, "original content")?;
// Make directory unwritable to prevent rename/temp file creation
std::fs::set_permissions(&unwritable_dir, Permissions::from_mode(0o555))?;
let mut buffer = TextBuffer::from_bytes(b"new content".to_vec(), test_fs());
let result = buffer.save_to_file(&file_path);
// Verify that it returns SudoSaveRequired
match result {
Err(e) => {
if let Some(sudo_err) = e.downcast_ref::<SudoSaveRequired>() {
assert_eq!(sudo_err.dest_path, file_path);
assert!(sudo_err.temp_path.exists());
// Cleanup temp file
drop(std::fs::remove_file(&sudo_err.temp_path));
} else {
panic!("Expected SudoSaveRequired error, got: {:?}", e);
}
}
Ok(_) => panic!("Expected error, but save succeeded"),
}
Ok(())
}
#[test]
#[cfg(unix)]
fn test_save_to_unwritable_directory() -> anyhow::Result<()> {
// Root (uid 0) bypasses Unix file permission checks, so these
// permission-denied tests are meaningless when running as root.
if unsafe { libc::getuid() } == 0 {
eprintln!("Skipping test: root bypasses file permission checks");
return Ok(());
}
use std::fs::Permissions;
use std::os::unix::fs::PermissionsExt;
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let unwritable_dir = temp_dir.path().join("unwritable_dir");
std::fs::create_dir(&unwritable_dir)?;
let file_path = unwritable_dir.join("test.txt");
// Make directory unwritable (no write allowed)
std::fs::set_permissions(&unwritable_dir, Permissions::from_mode(0o555))?;
let mut buffer = TextBuffer::from_bytes(b"content".to_vec(), test_fs());
let result = buffer.save_to_file(&file_path);
match result {
Err(e) => {
if let Some(sudo_err) = e.downcast_ref::<SudoSaveRequired>() {
assert_eq!(sudo_err.dest_path, file_path);
assert!(sudo_err.temp_path.exists());
// It should be in /tmp because the directory was not writable
assert!(sudo_err.temp_path.starts_with(std::env::temp_dir()));
// Cleanup
drop(std::fs::remove_file(&sudo_err.temp_path));
} else {
panic!("Expected SudoSaveRequired error, got: {:?}", e);
}
}
Ok(_) => panic!("Expected error, but save succeeded"),
}
Ok(())
}
}
mod large_file_encoding_tests {
use super::*;
#[test]
fn test_large_file_encoding_confirmation_display() {
let confirmation = LargeFileEncodingConfirmation {
path: PathBuf::from("/test/file.txt"),
file_size: 150 * 1024 * 1024, // 150 MB
encoding: Encoding::ShiftJis,
};
let display = format!("{}", confirmation);
assert!(display.contains("150 MB"), "Display: {}", display);
assert!(display.contains("Shift-JIS"), "Display: {}", display);
assert!(
display.contains("requires full load"),
"Display: {}",
display
);
}
#[test]
fn test_large_file_encoding_confirmation_equality() {
let a = LargeFileEncodingConfirmation {
path: PathBuf::from("/test/file.txt"),
file_size: 100 * 1024 * 1024,
encoding: Encoding::Gb18030,
};
let b = LargeFileEncodingConfirmation {
path: PathBuf::from("/test/file.txt"),
file_size: 100 * 1024 * 1024,
encoding: Encoding::Gb18030,
};
let c = LargeFileEncodingConfirmation {
path: PathBuf::from("/test/other.txt"),
file_size: 100 * 1024 * 1024,
encoding: Encoding::Gb18030,
};
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn test_encoding_requires_confirmation() {
// Resynchronizable encodings should NOT require confirmation
assert!(!Encoding::Utf8.requires_full_file_load());
assert!(!Encoding::Utf8Bom.requires_full_file_load());
assert!(!Encoding::Ascii.requires_full_file_load());
assert!(!Encoding::Latin1.requires_full_file_load());
assert!(!Encoding::Windows1252.requires_full_file_load());
assert!(!Encoding::Windows1250.requires_full_file_load());
assert!(!Encoding::Windows1251.requires_full_file_load());
assert!(!Encoding::Utf16Le.requires_full_file_load());
assert!(!Encoding::Utf16Be.requires_full_file_load());
// Non-resynchronizable CJK encodings SHOULD require confirmation
assert!(Encoding::Gb18030.requires_full_file_load());
assert!(Encoding::Gbk.requires_full_file_load());
assert!(Encoding::ShiftJis.requires_full_file_load());
assert!(Encoding::EucKr.requires_full_file_load());
}
#[test]
fn test_check_large_file_encoding_small_file() {
use tempfile::NamedTempFile;
// Create a small file (well under threshold)
let temp = NamedTempFile::new().unwrap();
std::fs::write(temp.path(), b"hello world").unwrap();
let result = TextBuffer::check_large_file_encoding(temp.path(), test_fs()).unwrap();
assert!(
result.is_none(),
"Small files should not require confirmation"
);
}
#[test]
fn test_large_file_encoding_error_downcast() {
// Verify that LargeFileEncodingConfirmation can be used as an anyhow error
let confirmation = LargeFileEncodingConfirmation {
path: PathBuf::from("/test/file.txt"),
file_size: 200 * 1024 * 1024,
encoding: Encoding::EucKr,
};
let error: anyhow::Error = confirmation.clone().into();
let downcast = error.downcast_ref::<LargeFileEncodingConfirmation>();
assert!(downcast.is_some());
assert_eq!(downcast.unwrap().encoding, Encoding::EucKr);
}
}
mod rebuild_pristine_saved_root_tests {
use super::*;
use crate::model::piece_tree::BufferLocation;
use std::sync::Arc;
/// Create a large-file-mode TextBuffer from raw bytes, simulating what
/// `load_from_file` does for files above the large-file threshold.
fn large_file_buffer(content: &[u8]) -> TextBuffer {
let fs: Arc<dyn crate::model::filesystem::FileSystem + Send + Sync> =
Arc::new(crate::model::filesystem::StdFileSystem);
let bytes = content.len();
let buffer =
crate::model::piece_tree::StringBuffer::new_loaded(0, content.to_vec(), false);
let piece_tree = if bytes > 0 {
crate::model::piece_tree::PieceTree::new(BufferLocation::Stored(0), 0, bytes, None)
} else {
crate::model::piece_tree::PieceTree::empty()
};
let saved_root = piece_tree.root();
TextBuffer {
fs,
piece_tree,
saved_root,
buffers: vec![buffer],
next_buffer_id: 1,
file_path: None,
modified: false,
recovery_pending: false,
large_file: true,
line_feeds_scanned: false,
is_binary: false,
line_ending: LineEnding::LF,
original_line_ending: LineEnding::LF,
encoding: Encoding::Utf8,
original_encoding: Encoding::Utf8,
saved_file_size: Some(bytes),
version: 0,
config: BufferConfig::default(),
}
}
/// Simulate prepare_line_scan + scanning: pre-split and compute lf counts.
fn scan_line_feeds(buf: &mut TextBuffer) -> Vec<(usize, usize)> {
buf.piece_tree.split_leaves_to_chunk_size(LOAD_CHUNK_SIZE);
let leaves = buf.piece_tree.get_leaves();
let mut updates = Vec::new();
for (idx, leaf) in leaves.iter().enumerate() {
if leaf.line_feed_cnt.is_some() {
continue;
}
let count = buf.scan_leaf(leaf).unwrap();
updates.push((idx, count));
}
updates
}
/// Generate a repeating pattern with newlines for testing.
fn make_content(size: usize) -> Vec<u8> {
let line = b"abcdefghij0123456789ABCDEFGHIJ0123456789abcdefghij0123456789ABCDEFGHIJ\n";
let mut out = Vec::with_capacity(size);
while out.len() < size {
let remaining = size - out.len();
let take = remaining.min(line.len());
out.extend_from_slice(&line[..take]);
}
out
}
#[test]
fn test_no_edits_arc_ptr_eq() {
let content = make_content(2 * 1024 * 1024);
let expected_lf = content.iter().filter(|&&b| b == b'\n').count();
let mut buf = large_file_buffer(&content);
// Before scan, line_count should be None (large file, no indexing).
assert!(buf.line_count().is_none());
let updates = scan_line_feeds(&mut buf);
buf.rebuild_with_pristine_saved_root(&updates);
// After rebuild, line_count must be Some (exact).
assert_eq!(buf.line_count(), Some(expected_lf + 1));
// After rebuild with no edits, roots should be identical (Arc::ptr_eq).
assert!(Arc::ptr_eq(&buf.saved_root, &buf.piece_tree.root()));
let diff = buf.diff_since_saved();
assert!(diff.equal);
assert!(buf.line_feeds_scanned);
assert_eq!(buf.get_all_text().unwrap(), content);
}
#[test]
fn test_single_insertion() {
let content = make_content(2 * 1024 * 1024);
let mut buf = large_file_buffer(&content);
let updates = scan_line_feeds(&mut buf);
// Insert some text in the middle.
let insert_offset = 1_000_000;
let insert_text = b"INSERTED_TEXT\n";
buf.insert_bytes(insert_offset, insert_text.to_vec());
buf.rebuild_with_pristine_saved_root(&updates);
// Content should match the shadow model.
let mut expected = content.clone();
expected.splice(insert_offset..insert_offset, insert_text.iter().copied());
assert_eq!(buf.get_all_text().unwrap(), expected);
// line_count must be Some (exact) after rebuild, even with edits.
let expected_lf = expected.iter().filter(|&&b| b == b'\n').count();
assert_eq!(buf.line_count(), Some(expected_lf + 1));
// Diff should NOT be equal.
let diff = buf.diff_since_saved();
assert!(!diff.equal);
assert!(!diff.byte_ranges.is_empty());
}
/// After rebuild + insert near EOF, diff byte_ranges must be
/// document-absolute. The bug: `with_doc_offsets` assigned consecutive
/// offsets from 0 to the collected leaves, missing skipped (shared)
/// subtrees' bytes.
#[test]
fn test_diff_byte_ranges_are_document_absolute_after_eof_insert() {
let content = make_content(4 * 1024 * 1024); // 4MB → 4 chunks at 1MB each
let mut buf = large_file_buffer(&content);
let updates = scan_line_feeds(&mut buf);
buf.rebuild_with_pristine_saved_root(&updates);
// Insert 5 bytes near EOF (last 100 bytes of the file).
let insert_offset = content.len() - 100;
buf.insert_bytes(insert_offset, b"HELLO".to_vec());
let diff = buf.diff_since_saved();
assert!(!diff.equal, "diff should detect the insertion");
assert!(
!diff.byte_ranges.is_empty(),
"byte_ranges should not be empty"
);
// byte_ranges must be near the end of the document, not near 0.
let first_range = &diff.byte_ranges[0];
assert!(
first_range.start >= content.len() - 200,
"byte_ranges should be document-absolute (near EOF): got {:?}, expected near {}",
first_range,
insert_offset,
);
}
#[test]
fn test_single_deletion() {
let content = make_content(2 * 1024 * 1024);
let mut buf = large_file_buffer(&content);
let updates = scan_line_feeds(&mut buf);
// Delete a range.
let del_start = 500_000;
let del_len = 1000;
buf.delete_bytes(del_start, del_len);
buf.rebuild_with_pristine_saved_root(&updates);
let mut expected = content.clone();
expected.drain(del_start..del_start + del_len);
assert_eq!(buf.get_all_text().unwrap(), expected);
let diff = buf.diff_since_saved();
assert!(!diff.equal);
}
#[test]
fn test_insert_and_delete() {
let content = make_content(2 * 1024 * 1024);
let mut buf = large_file_buffer(&content);
let updates = scan_line_feeds(&mut buf);
// Delete near the start, insert near the end.
let del_start = 100_000;
let del_len = 500;
buf.delete_bytes(del_start, del_len);
let insert_offset = 1_500_000; // in the post-delete document
let insert_text = b"NEW_CONTENT\n";
buf.insert_bytes(insert_offset, insert_text.to_vec());
buf.rebuild_with_pristine_saved_root(&updates);
// Build expected content.
let mut expected = content.clone();
expected.drain(del_start..del_start + del_len);
expected.splice(insert_offset..insert_offset, insert_text.iter().copied());
assert_eq!(buf.get_all_text().unwrap(), expected);
let diff = buf.diff_since_saved();
assert!(!diff.equal);
}
#[test]
fn test_multiple_scattered_edits() {
let content = make_content(3 * 1024 * 1024);
let mut buf = large_file_buffer(&content);
let updates = scan_line_feeds(&mut buf);
let mut expected = content.clone();
// Apply several edits across chunk boundaries, tracking the shadow model.
// Edit 1: delete at offset 100k
buf.delete_bytes(100_000, 200);
expected.drain(100_000..100_200);
// Edit 2: insert at offset 500k (in current doc, which shifted)
buf.insert_bytes(500_000, b"AAAA\n".to_vec());
expected.splice(500_000..500_000, b"AAAA\n".iter().copied());
// Edit 3: delete at offset 2M
buf.delete_bytes(2_000_000, 300);
expected.drain(2_000_000..2_000_300);
// Edit 4: insert at offset 1M
buf.insert_bytes(1_000_000, b"BBBB\n".to_vec());
expected.splice(1_000_000..1_000_000, b"BBBB\n".iter().copied());
buf.rebuild_with_pristine_saved_root(&updates);
assert_eq!(buf.get_all_text().unwrap(), expected);
let diff = buf.diff_since_saved();
assert!(!diff.equal);
}
#[test]
fn test_content_preserved_after_rebuild() {
// Verify that get_all_text matches before and after rebuild for
// a buffer with edits.
let content = make_content(2 * 1024 * 1024);
let mut buf = large_file_buffer(&content);
let updates = scan_line_feeds(&mut buf);
buf.insert_bytes(0, b"HEADER\n".to_vec());
buf.delete_bytes(1_000_000, 500);
let text_before = buf.get_all_text().unwrap();
buf.rebuild_with_pristine_saved_root(&updates);
let text_after = buf.get_all_text().unwrap();
assert_eq!(text_before, text_after);
}
/// Create a large-file-mode TextBuffer backed by an actual file on disk
/// (Unloaded buffer), matching the real `load_from_file` code path.
fn large_file_buffer_unloaded(path: &std::path::Path, file_size: usize) -> TextBuffer {
let fs: Arc<dyn crate::model::filesystem::FileSystem + Send + Sync> =
Arc::new(crate::model::filesystem::StdFileSystem);
let buffer = crate::model::piece_tree::StringBuffer::new_unloaded(
0,
path.to_path_buf(),
0,
file_size,
);
let piece_tree = if file_size > 0 {
crate::model::piece_tree::PieceTree::new(
BufferLocation::Stored(0),
0,
file_size,
None,
)
} else {
crate::model::piece_tree::PieceTree::empty()
};
let saved_root = piece_tree.root();
TextBuffer {
fs,
piece_tree,
saved_root,
buffers: vec![buffer],
next_buffer_id: 1,
file_path: Some(path.to_path_buf()),
modified: false,
recovery_pending: false,
large_file: true,
line_feeds_scanned: false,
is_binary: false,
line_ending: LineEnding::LF,
original_line_ending: LineEnding::LF,
encoding: Encoding::Utf8,
original_encoding: Encoding::Utf8,
saved_file_size: Some(file_size),
version: 0,
config: BufferConfig::default(),
}
}
#[test]
fn test_unloaded_buffer_no_edits_line_count() {
let content = make_content(2 * 1024 * 1024);
let expected_lf = content.iter().filter(|&&b| b == b'\n').count();
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), &content).unwrap();
let mut buf = large_file_buffer_unloaded(tmp.path(), content.len());
assert!(
buf.line_count().is_none(),
"before scan, line_count should be None"
);
let updates = scan_line_feeds(&mut buf);
buf.rebuild_with_pristine_saved_root(&updates);
assert_eq!(
buf.line_count(),
Some(expected_lf + 1),
"after rebuild, line_count must be exact"
);
assert!(buf.line_feeds_scanned);
}
#[test]
fn test_unloaded_buffer_with_edits_line_count() {
let content = make_content(2 * 1024 * 1024);
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), &content).unwrap();
let mut buf = large_file_buffer_unloaded(tmp.path(), content.len());
let updates = scan_line_feeds(&mut buf);
// Insert text in the middle (creates an Added piece).
let insert_text = b"INSERTED\n";
buf.insert_bytes(1_000_000, insert_text.to_vec());
buf.rebuild_with_pristine_saved_root(&updates);
let mut expected = content.clone();
expected.splice(1_000_000..1_000_000, insert_text.iter().copied());
let expected_lf = expected.iter().filter(|&&b| b == b'\n').count();
assert_eq!(
buf.line_count(),
Some(expected_lf + 1),
"after rebuild with edits, line_count must be exact"
);
assert!(buf.line_feeds_scanned);
}
/// After rebuild, diff_since_saved should visit a small number of nodes
/// proportional to edit regions, NOT the full tree. This catches
/// regressions where Arc pointers are accidentally destroyed (e.g. by
/// flattening and rebuilding the tree).
#[test]
fn test_diff_efficiency_after_rebuild() {
// Use 32MB so the tree has ~32 leaves (at 1MB chunk size),
// making the efficiency difference between O(log N) and O(N) clear.
let content = make_content(32 * 1024 * 1024);
let mut buf = large_file_buffer(&content);
let updates = scan_line_feeds(&mut buf);
// Insert a small piece of text in one chunk.
buf.insert_bytes(1_000_000, b"HELLO".to_vec());
buf.rebuild_with_pristine_saved_root(&updates);
let diff = buf.diff_since_saved();
assert!(!diff.equal);
let total_leaves = buf.piece_tree.get_leaves().len();
// The diff should visit far fewer nodes than the total tree.
// With path-copying, only the path from root to the edited leaf
// (and its immediate neighbours) should be visited — roughly
// O(log N) nodes, not O(N).
assert!(
diff.nodes_visited < total_leaves,
"diff visited {} nodes but tree has {} leaves — \
Arc::ptr_eq short-circuiting is not working",
diff.nodes_visited,
total_leaves,
);
}
/// After rebuild_with_pristine_saved_root, loading a small viewport
/// range must NOT cause the entire original file buffer to be loaded.
/// This is a regression test for a bug where the pristine tree's 1MB
/// pieces all referenced Stored(0) (the whole-file buffer). Because
/// piece_view.bytes (1MB) <= LOAD_CHUNK_SIZE, get_text_range_mut took
/// the "load_small_buffer" path, calling load() on the 814MB buffer.
#[test]
fn test_viewport_load_after_rebuild_does_not_load_entire_file() {
use std::sync::atomic::{AtomicUsize, Ordering};
/// Filesystem wrapper that tracks the largest read_range call.
struct TrackingFs {
inner: crate::model::filesystem::StdFileSystem,
max_read_range_len: Arc<AtomicUsize>,
}
impl crate::model::filesystem::FileSystem for TrackingFs {
fn read_file(&self, path: &Path) -> std::io::Result<Vec<u8>> {
self.inner.read_file(path)
}
fn read_range(
&self,
path: &Path,
offset: u64,
len: usize,
) -> std::io::Result<Vec<u8>> {
self.max_read_range_len.fetch_max(len, Ordering::SeqCst);
self.inner.read_range(path, offset, len)
}
fn write_file(&self, path: &Path, data: &[u8]) -> std::io::Result<()> {
self.inner.write_file(path, data)
}
fn create_file(
&self,
path: &Path,
) -> std::io::Result<Box<dyn crate::model::filesystem::FileWriter>>
{
self.inner.create_file(path)
}
fn open_file(
&self,
path: &Path,
) -> std::io::Result<Box<dyn crate::model::filesystem::FileReader>>
{
self.inner.open_file(path)
}
fn open_file_for_write(
&self,
path: &Path,
) -> std::io::Result<Box<dyn crate::model::filesystem::FileWriter>>
{
self.inner.open_file_for_write(path)
}
fn open_file_for_append(
&self,
path: &Path,
) -> std::io::Result<Box<dyn crate::model::filesystem::FileWriter>>
{
self.inner.open_file_for_append(path)
}
fn set_file_length(&self, path: &Path, len: u64) -> std::io::Result<()> {
self.inner.set_file_length(path, len)
}
fn rename(&self, from: &Path, to: &Path) -> std::io::Result<()> {
self.inner.rename(from, to)
}
fn copy(&self, from: &Path, to: &Path) -> std::io::Result<u64> {
self.inner.copy(from, to)
}
fn remove_file(&self, path: &Path) -> std::io::Result<()> {
self.inner.remove_file(path)
}
fn remove_dir(&self, path: &Path) -> std::io::Result<()> {
self.inner.remove_dir(path)
}
fn metadata(
&self,
path: &Path,
) -> std::io::Result<crate::model::filesystem::FileMetadata> {
self.inner.metadata(path)
}
fn symlink_metadata(
&self,
path: &Path,
) -> std::io::Result<crate::model::filesystem::FileMetadata> {
self.inner.symlink_metadata(path)
}
fn is_dir(&self, path: &Path) -> std::io::Result<bool> {
self.inner.is_dir(path)
}
fn is_file(&self, path: &Path) -> std::io::Result<bool> {
self.inner.is_file(path)
}
fn set_permissions(
&self,
path: &Path,
permissions: &crate::model::filesystem::FilePermissions,
) -> std::io::Result<()> {
self.inner.set_permissions(path, permissions)
}
fn is_owner(&self, path: &Path) -> bool {
self.inner.is_owner(path)
}
fn read_dir(
&self,
path: &Path,
) -> std::io::Result<Vec<crate::model::filesystem::DirEntry>> {
self.inner.read_dir(path)
}
fn create_dir(&self, path: &Path) -> std::io::Result<()> {
self.inner.create_dir(path)
}
fn create_dir_all(&self, path: &Path) -> std::io::Result<()> {
self.inner.create_dir_all(path)
}
fn canonicalize(&self, path: &Path) -> std::io::Result<PathBuf> {
self.inner.canonicalize(path)
}
fn current_uid(&self) -> u32 {
self.inner.current_uid()
}
fn sudo_write(
&self,
path: &Path,
data: &[u8],
mode: u32,
uid: u32,
gid: u32,
) -> std::io::Result<()> {
self.inner.sudo_write(path, data, mode, uid, gid)
}
fn search_file(
&self,
path: &Path,
pattern: &str,
opts: &crate::model::filesystem::FileSearchOptions,
cursor: &mut crate::model::filesystem::FileSearchCursor,
) -> std::io::Result<Vec<SearchMatch>> {
crate::model::filesystem::default_search_file(
&self.inner,
path,
pattern,
opts,
cursor,
)
}
fn walk_files(
&self,
root: &Path,
skip_dirs: &[&str],
cancel: &std::sync::atomic::AtomicBool,
on_file: &mut dyn FnMut(&Path, &str) -> bool,
) -> std::io::Result<()> {
self.inner.walk_files(root, skip_dirs, cancel, on_file)
}
}
// Create a 3MB file with newlines (3 chunks at LOAD_CHUNK_SIZE=1MB).
let file_size = LOAD_CHUNK_SIZE * 3;
let content = make_content(file_size);
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), &content).unwrap();
let max_read = Arc::new(AtomicUsize::new(0));
let fs: Arc<dyn crate::model::filesystem::FileSystem + Send + Sync> =
Arc::new(TrackingFs {
inner: crate::model::filesystem::StdFileSystem,
max_read_range_len: max_read.clone(),
});
// Build an unloaded large-file buffer with the tracking FS.
let buffer = crate::model::piece_tree::StringBuffer::new_unloaded(
0,
tmp.path().to_path_buf(),
0,
file_size,
);
let piece_tree = PieceTree::new(BufferLocation::Stored(0), 0, file_size, None);
let saved_root = piece_tree.root();
let mut buf = TextBuffer {
fs,
piece_tree,
saved_root,
buffers: vec![buffer],
next_buffer_id: 1,
file_path: Some(tmp.path().to_path_buf()),
modified: false,
recovery_pending: false,
large_file: true,
line_feeds_scanned: false,
is_binary: false,
line_ending: LineEnding::LF,
original_line_ending: LineEnding::LF,
encoding: Encoding::Utf8,
original_encoding: Encoding::Utf8,
saved_file_size: Some(file_size),
version: 0,
config: BufferConfig::default(),
};
// Load a small viewport in the middle (forces chunk splitting).
let viewport_offset = LOAD_CHUNK_SIZE + 100; // somewhere in chunk 2
buf.get_text_range_mut(viewport_offset, 4096).unwrap();
// Run the line-feed scan and rebuild the pristine tree.
let updates = scan_line_feeds(&mut buf);
buf.rebuild_with_pristine_saved_root(&updates);
// Reset the tracker — we only care about reads AFTER the rebuild.
max_read.store(0, Ordering::SeqCst);
// Load the same viewport range again.
buf.get_text_range_mut(viewport_offset, 4096).unwrap();
let largest_read = max_read.load(Ordering::SeqCst);
assert!(
largest_read <= LOAD_CHUNK_SIZE,
"After rebuild, loading a viewport triggered a read of {} bytes \
(file_size={}). This means the entire Stored buffer is being \
loaded instead of just the needed chunk.",
largest_read,
file_size,
);
}
/// After rebuild_with_pristine_saved_root, loading a viewport must not
/// destroy the line feed counts on pieces. The chunk-split path in
/// get_text_range_mut calls split_at_offset, which invokes
/// compute_line_feeds_static — returning None for unloaded buffers.
/// This turns exact line numbers back into byte-based estimates.
#[test]
fn test_viewport_load_after_rebuild_preserves_line_counts() {
let file_size = LOAD_CHUNK_SIZE * 3;
let content = make_content(file_size);
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), &content).unwrap();
let mut buf = large_file_buffer_unloaded(tmp.path(), content.len());
// Scan + rebuild so every leaf has a known line_feed_cnt.
let updates = scan_line_feeds(&mut buf);
buf.rebuild_with_pristine_saved_root(&updates);
let line_count_before = buf.piece_tree.line_count();
assert!(
line_count_before.is_some(),
"line_count must be Some after rebuild"
);
// Load a viewport that starts in the MIDDLE of a piece, forcing
// split_at_offset (not just replace_buffer_reference).
let mid_piece_offset = LOAD_CHUNK_SIZE + LOAD_CHUNK_SIZE / 2;
buf.get_text_range_mut(mid_piece_offset, 4096).unwrap();
let line_count_after = buf.piece_tree.line_count();
assert!(
line_count_after.is_some(),
"line_count must still be Some after viewport load \
(was {:?} before, now {:?})",
line_count_before,
line_count_after,
);
assert_eq!(
line_count_before, line_count_after,
"line_count must not change after viewport load"
);
}
/// Same test but with Unloaded data (the fixup path).
#[test]
fn test_diff_efficiency_after_rebuild_unloaded() {
let content = make_content(32 * 1024 * 1024);
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), &content).unwrap();
let mut buf = large_file_buffer_unloaded(tmp.path(), content.len());
let updates = scan_line_feeds(&mut buf);
buf.insert_bytes(1_000_000, b"HELLO".to_vec());
buf.rebuild_with_pristine_saved_root(&updates);
let diff = buf.diff_since_saved();
assert!(!diff.equal);
let total_leaves = buf.piece_tree.get_leaves().len();
assert!(
diff.nodes_visited < total_leaves,
"diff visited {} nodes but tree has {} leaves — \
Arc::ptr_eq short-circuiting is not working (unloaded path)",
diff.nodes_visited,
total_leaves,
);
}
}
mod chunked_search {
use super::*;
fn make_buffer(content: &[u8]) -> TextBuffer {
TextBuffer::from_bytes(content.to_vec(), test_fs())
}
fn make_regex(pattern: &str) -> regex::bytes::Regex {
regex::bytes::Regex::new(pattern).unwrap()
}
#[test]
fn single_chunk_line_col_context() {
let mut buf = make_buffer(b"hello world\nfoo bar\nbaz quux\n");
let state = buf.search_scan_all(make_regex("bar"), 100, 3).unwrap();
assert_eq!(state.matches.len(), 1);
let m = &state.matches[0];
assert_eq!(m.line, 2);
assert_eq!(m.column, 5); // "foo bar" → 'b' at column 5
assert_eq!(m.context, "foo bar");
assert_eq!(m.byte_offset, 16); // "hello world\nfoo " = 16 bytes
assert_eq!(m.length, 3);
}
#[test]
fn multiple_matches_correct_lines() {
let mut buf = make_buffer(b"aaa\nbbb\nccc\naaa\n");
let state = buf.search_scan_all(make_regex("aaa"), 100, 3).unwrap();
assert_eq!(state.matches.len(), 2);
assert_eq!(state.matches[0].line, 1);
assert_eq!(state.matches[0].context, "aaa");
assert_eq!(state.matches[1].line, 4);
assert_eq!(state.matches[1].context, "aaa");
}
#[test]
fn match_on_last_line_no_trailing_newline() {
let mut buf = make_buffer(b"line1\nline2\ntarget");
let state = buf.search_scan_all(make_regex("target"), 100, 6).unwrap();
assert_eq!(state.matches.len(), 1);
let m = &state.matches[0];
assert_eq!(m.line, 3);
assert_eq!(m.column, 1);
assert_eq!(m.context, "target");
}
#[test]
fn match_at_first_byte() {
let mut buf = make_buffer(b"target\nother\n");
let state = buf.search_scan_all(make_regex("target"), 100, 6).unwrap();
assert_eq!(state.matches.len(), 1);
let m = &state.matches[0];
assert_eq!(m.line, 1);
assert_eq!(m.column, 1);
assert_eq!(m.byte_offset, 0);
}
#[test]
fn max_matches_caps() {
let mut buf = make_buffer(b"a\na\na\na\na\n");
let state = buf.search_scan_all(make_regex("a"), 3, 1).unwrap();
assert_eq!(state.matches.len(), 3);
assert!(state.capped);
}
#[test]
fn case_insensitive_regex() {
let mut buf = make_buffer(b"Hello\nhello\nHELLO\n");
let state = buf
.search_scan_all(make_regex("(?i)hello"), 100, 5)
.unwrap();
assert_eq!(state.matches.len(), 3);
assert_eq!(state.matches[0].line, 1);
assert_eq!(state.matches[1].line, 2);
assert_eq!(state.matches[2].line, 3);
}
#[test]
fn whole_word_boundary() {
let mut buf = make_buffer(b"foobar\nfoo bar\nfoo\n");
let state = buf.search_scan_all(make_regex(r"\bfoo\b"), 100, 3).unwrap();
assert_eq!(state.matches.len(), 2);
assert_eq!(state.matches[0].line, 2);
assert_eq!(state.matches[0].column, 1);
assert_eq!(state.matches[1].line, 3);
}
/// Force multi-chunk processing by creating a large file buffer
/// with small piece-tree leaves, then verify line numbers are
/// correct across chunk boundaries.
#[test]
fn multi_chunk_line_numbers_correct() {
// Build content: 100 lines of "line_NNN\n"
let mut content = Vec::new();
for i in 1..=100 {
content.extend_from_slice(format!("line_{:03}\n", i).as_bytes());
}
// Load as a "large file" with tiny threshold to force multiple
// piece-tree leaves (chunks).
let temp_dir = tempfile::TempDir::new().unwrap();
let path = temp_dir.path().join("test.txt");
std::fs::write(&path, &content).unwrap();
let mut buffer = TextBuffer::load_from_file(&path, 10, test_fs()).unwrap();
let state = buffer
.search_scan_all(make_regex("line_050"), 100, 8)
.unwrap();
assert_eq!(state.matches.len(), 1);
let m = &state.matches[0];
assert_eq!(m.line, 50);
assert_eq!(m.column, 1);
assert_eq!(m.context, "line_050");
}
/// Verify that matches near chunk boundaries don't produce
/// duplicate results (overlap deduplication).
#[test]
fn multi_chunk_no_duplicate_matches() {
let mut content = Vec::new();
for i in 1..=100 {
content.extend_from_slice(format!("word_{:03}\n", i).as_bytes());
}
let temp_dir = tempfile::TempDir::new().unwrap();
let path = temp_dir.path().join("test.txt");
std::fs::write(&path, &content).unwrap();
let mut buffer = TextBuffer::load_from_file(&path, 10, test_fs()).unwrap();
// Search for a pattern that appears exactly once per line
let state = buffer.search_scan_all(make_regex("word_"), 200, 5).unwrap();
assert_eq!(
state.matches.len(),
100,
"Should find exactly 100 matches (one per line), no duplicates"
);
// Verify line numbers are sequential 1..=100
for (i, m) in state.matches.iter().enumerate() {
assert_eq!(
m.line,
i + 1,
"Match {} should be on line {}, got {}",
i,
i + 1,
m.line
);
}
}
/// The reviewer's counter-example: verify line counting when
/// overlap contains part of a line that continues into the
/// next chunk.
#[test]
fn overlap_mid_line_line_numbers() {
// Create content where a line spans a chunk boundary.
// Use a large-file load with tiny threshold to force chunking.
let mut content = Vec::new();
content.extend_from_slice(b"short\n");
// A long line that will span chunk boundaries
content.extend_from_slice(b"AAAA_");
for _ in 0..50 {
content.extend_from_slice(b"BBBBBBBBBB"); // 500 bytes of B
}
content.extend_from_slice(b"_TARGET_HERE\n");
content.extend_from_slice(b"after\n");
let temp_dir = tempfile::TempDir::new().unwrap();
let path = temp_dir.path().join("test.txt");
std::fs::write(&path, &content).unwrap();
let mut buffer = TextBuffer::load_from_file(&path, 10, test_fs()).unwrap();
let state = buffer
.search_scan_all(make_regex("TARGET_HERE"), 100, 11)
.unwrap();
assert_eq!(state.matches.len(), 1);
let m = &state.matches[0];
assert_eq!(m.line, 2, "TARGET_HERE is on line 2 (the long line)");
assert_eq!(m.length, 11);
// Also check "after" is on line 3
let state2 = buffer.search_scan_all(make_regex("after"), 100, 5).unwrap();
assert_eq!(state2.matches.len(), 1);
assert_eq!(state2.matches[0].line, 3);
}
/// Verify correct results when a match spans the overlap/chunk
/// boundary (starts in overlap tail, ends in new chunk).
#[test]
fn match_spanning_chunk_boundary() {
// Create content where "SPLIT" can appear at the boundary
let mut content = Vec::new();
content.extend_from_slice(b"line1\n");
// Pad to push "SPLIT" near a chunk boundary
for _ in 0..60 {
content.extend_from_slice(b"XXXXXXXXXX"); // 600 bytes
}
content.extend_from_slice(b"SPLIT\n");
content.extend_from_slice(b"end\n");
let temp_dir = tempfile::TempDir::new().unwrap();
let path = temp_dir.path().join("test.txt");
std::fs::write(&path, &content).unwrap();
let mut buffer = TextBuffer::load_from_file(&path, 10, test_fs()).unwrap();
let state = buffer.search_scan_all(make_regex("SPLIT"), 100, 5).unwrap();
assert_eq!(state.matches.len(), 1, "SPLIT should be found exactly once");
assert_eq!(state.matches[0].line, 2); // Still on line 2 (the long X line)
}
#[test]
fn empty_buffer_no_matches() {
let mut buf = make_buffer(b"");
let state = buf.search_scan_all(make_regex("anything"), 100, 8).unwrap();
assert!(state.matches.is_empty());
assert!(!state.capped);
}
#[test]
fn single_line_no_newline() {
let mut buf = make_buffer(b"hello world");
let state = buf.search_scan_all(make_regex("world"), 100, 5).unwrap();
assert_eq!(state.matches.len(), 1);
let m = &state.matches[0];
assert_eq!(m.line, 1);
assert_eq!(m.column, 7);
assert_eq!(m.context, "hello world");
}
/// Verify that multiple matches on the same line get the same
/// line number and correct columns.
#[test]
fn multiple_matches_same_line() {
let mut buf = make_buffer(b"aa bb aa cc aa\nother\n");
let state = buf.search_scan_all(make_regex("aa"), 100, 2).unwrap();
assert_eq!(state.matches.len(), 3);
for m in &state.matches {
assert_eq!(m.line, 1);
assert_eq!(m.context, "aa bb aa cc aa");
}
assert_eq!(state.matches[0].column, 1);
assert_eq!(state.matches[1].column, 7);
assert_eq!(state.matches[2].column, 13);
}
}
mod hybrid_search {
use super::*;
fn make_regex(pattern: &str) -> regex::bytes::Regex {
regex::bytes::Regex::new(pattern).unwrap()
}
fn make_opts() -> crate::model::filesystem::FileSearchOptions {
crate::model::filesystem::FileSearchOptions {
fixed_string: false,
case_sensitive: true,
whole_word: false,
max_matches: 100,
}
}
/// Hybrid search on a fully-loaded small buffer should produce
/// the same results as search_scan_all.
#[test]
fn hybrid_matches_scan_all_for_loaded_buffer() {
let content = b"foo bar baz\nfoo again\nlast line\n";
let mut buf = TextBuffer::from_bytes(content.to_vec(), test_fs());
let regex = make_regex("foo");
let opts = make_opts();
let hybrid = buf
.search_hybrid("foo", &opts, regex.clone(), 100, 3)
.unwrap();
let scan = buf.search_scan_all(regex, 100, 3).unwrap();
assert_eq!(hybrid.len(), scan.matches.len());
for (h, s) in hybrid.iter().zip(scan.matches.iter()) {
assert_eq!(h.byte_offset, s.byte_offset);
assert_eq!(h.line, s.line);
assert_eq!(h.column, s.column);
assert_eq!(h.length, s.length);
assert_eq!(h.context, s.context);
}
}
/// Hybrid search on a file-backed buffer (large file with unloaded
/// regions) should find matches using fs.search_file.
#[test]
fn hybrid_finds_matches_in_unloaded_regions() {
let temp_dir = tempfile::TempDir::new().unwrap();
let path = temp_dir.path().join("big.txt");
// Create a file with known content
let mut content = Vec::new();
for i in 0..100 {
content.extend_from_slice(format!("line {:03}\n", i).as_bytes());
}
std::fs::write(&path, &content).unwrap();
// Load as a large file (unloaded mode)
let mut buf = TextBuffer::load_from_file(&path, 10, test_fs()).unwrap();
// Verify some leaves are unloaded
let leaves = buf.piece_tree.get_leaves();
let has_unloaded = leaves.iter().any(|l| {
matches!(l.location, BufferLocation::Stored(_))
&& buf
.buffers
.get(l.location.buffer_id())
.map(|b| !b.is_loaded())
.unwrap_or(false)
});
let regex = make_regex("line 050");
let opts = make_opts();
let matches = buf.search_hybrid("line 050", &opts, regex, 100, 8).unwrap();
assert_eq!(matches.len(), 1);
assert_eq!(matches[0].line, 51); // 1-based
assert!(matches[0].context.contains("line 050"));
// If the buffer had unloaded regions, hybrid search used fs.search_file
if has_unloaded {
// Just verify it worked — the match was found without loading everything
}
}
/// Hybrid search on a dirty buffer should find matches in both
/// edited (loaded) and unedited (unloaded) regions.
#[test]
fn hybrid_dirty_buffer_finds_all_matches() {
let temp_dir = tempfile::TempDir::new().unwrap();
let path = temp_dir.path().join("dirty.txt");
let mut content = Vec::new();
for i in 0..50 {
content.extend_from_slice(format!("target {:02}\n", i).as_bytes());
}
std::fs::write(&path, &content).unwrap();
let mut buf = TextBuffer::load_from_file(&path, 10, test_fs()).unwrap();
// Make a small edit near the beginning — insert "target XX" at position 0
buf.insert(0, "target XX\n");
let regex = make_regex("target");
let opts = make_opts();
let matches = buf.search_hybrid("target", &opts, regex, 200, 6).unwrap();
// Should find the inserted "target XX" plus all 50 original "target NN"
assert_eq!(matches.len(), 51);
// First match should be the inserted one
assert!(matches[0].context.contains("target XX"));
}
/// Boundary match: pattern spans loaded→unloaded boundary.
#[test]
fn hybrid_boundary_match() {
let temp_dir = tempfile::TempDir::new().unwrap();
let path = temp_dir.path().join("boundary.txt");
// File content: "AAAAABBBBB" (no newlines)
let content = b"AAAAABBBBB";
std::fs::write(&path, content).unwrap();
let mut buf = TextBuffer::from_bytes(content.to_vec(), test_fs());
buf.rename_file_path(path);
let regex = make_regex("AAAAABBBBB");
let opts = make_opts();
let matches = buf
.search_hybrid("AAAAABBBBB", &opts, regex, 100, 10)
.unwrap();
assert_eq!(matches.len(), 1);
assert_eq!(matches[0].byte_offset, 0);
}
/// Max matches limit is respected.
#[test]
fn hybrid_max_matches_respected() {
let content = b"aaa\naaa\naaa\naaa\naaa\n";
let mut buf = TextBuffer::from_bytes(content.to_vec(), test_fs());
let regex = make_regex("aaa");
let opts = crate::model::filesystem::FileSearchOptions {
max_matches: 3,
..make_opts()
};
let matches = buf.search_hybrid("aaa", &opts, regex, 3, 3).unwrap();
assert!(matches.len() <= 3);
}
}
mod boundary_overlap {
use super::*;
fn make_regex(pattern: &str) -> regex::bytes::Regex {
regex::bytes::Regex::new(pattern).unwrap()
}
#[test]
fn empty_prev_tail_returns_nothing() {
let matches = search_boundary_overlap(b"", b"hello", 0, 1, &make_regex("hello"), 100);
assert!(matches.is_empty());
}
#[test]
fn pure_tail_match_skipped() {
// "foo" is entirely in prev_tail — should NOT be returned
let matches =
search_boundary_overlap(b"foo bar", b" baz", 0, 1, &make_regex("foo"), 100);
assert!(matches.is_empty());
}
#[test]
fn cross_boundary_match_found() {
// "SPLIT" spans: prev_tail="...SPL", next_head="IT..."
let matches =
search_boundary_overlap(b"xxSPL", b"ITyy", 0, 1, &make_regex("SPLIT"), 100);
assert_eq!(matches.len(), 1);
assert_eq!(matches[0].byte_offset, 2);
assert_eq!(matches[0].length, 5);
}
#[test]
fn pure_head_match_skipped() {
// "baz" is entirely in next_head — should NOT be returned
// (it starts at offset 4 which is >= overlap_len 3)
let matches = search_boundary_overlap(b"foo", b" baz", 0, 1, &make_regex("baz"), 100);
assert!(matches.is_empty());
}
#[test]
fn line_number_tracking() {
// prev_tail has a newline; running_line=5 means "line 5 at
// the boundary". The newline in the tail means SPLIT starts
// on line 5 (the boundary line).
let matches =
search_boundary_overlap(b"line1\nSPL", b"IT end", 0, 5, &make_regex("SPLIT"), 100);
assert_eq!(matches.len(), 1);
assert_eq!(matches[0].line, 5);
}
#[test]
fn max_matches_respected() {
// Two cross-boundary matches but max is 1
let matches = search_boundary_overlap(b"aXb", b"Xc", 0, 1, &make_regex("X"), 1);
assert!(matches.len() <= 1);
}
}
}
#[cfg(test)]
mod property_tests {
use crate::model::filesystem::StdFileSystem;
use std::sync::Arc;
fn test_fs() -> Arc<dyn crate::model::filesystem::FileSystem + Send + Sync> {
Arc::new(StdFileSystem)
}
use super::*;
use proptest::prelude::*;
// Generate text with some newlines
fn text_with_newlines() -> impl Strategy<Value = Vec<u8>> {
prop::collection::vec(
prop_oneof![(b'a'..=b'z').prop_map(|c| c), Just(b'\n'),],
0..100,
)
}
// Strategy to generate operations
#[derive(Debug, Clone)]
enum Operation {
Insert { offset: usize, text: Vec<u8> },
Delete { offset: usize, bytes: usize },
}
fn operation_strategy() -> impl Strategy<Value = Vec<Operation>> {
prop::collection::vec(
prop_oneof![
(0usize..200, text_with_newlines())
.prop_map(|(offset, text)| { Operation::Insert { offset, text } }),
(0usize..200, 1usize..50)
.prop_map(|(offset, bytes)| { Operation::Delete { offset, bytes } }),
],
0..50,
)
}
proptest! {
#[test]
fn prop_line_count_consistent(text in text_with_newlines()) {
let buffer = TextBuffer::from_bytes(text.clone(), test_fs());
let newline_count = text.iter().filter(|&&b| b == b'\n').count();
prop_assert_eq!(buffer.line_count(), Some(newline_count + 1));
}
#[test]
fn prop_get_all_text_matches_original(text in text_with_newlines()) {
let buffer = TextBuffer::from_bytes(text.clone(), test_fs());
prop_assert_eq!(buffer.get_all_text().unwrap(), text);
}
#[test]
fn prop_insert_increases_size(
text in text_with_newlines(),
offset in 0usize..100,
insert_text in text_with_newlines()
) {
let mut buffer = TextBuffer::from_bytes(text, test_fs());
let initial_bytes = buffer.total_bytes();
let offset = offset.min(buffer.total_bytes());
buffer.insert_bytes(offset, insert_text.clone());
prop_assert_eq!(buffer.total_bytes(), initial_bytes + insert_text.len());
}
#[test]
fn prop_delete_decreases_size(
text in text_with_newlines(),
offset in 0usize..100,
delete_bytes in 1usize..50
) {
if text.is_empty() {
return Ok(());
}
let mut buffer = TextBuffer::from_bytes(text, test_fs());
let initial_bytes = buffer.total_bytes();
let offset = offset.min(buffer.total_bytes());
let delete_bytes = delete_bytes.min(buffer.total_bytes() - offset);
if delete_bytes == 0 {
return Ok(());
}
buffer.delete_bytes(offset, delete_bytes);
prop_assert_eq!(buffer.total_bytes(), initial_bytes - delete_bytes);
}
#[test]
fn prop_insert_then_delete_restores_original(
text in text_with_newlines(),
offset in 0usize..100,
insert_text in text_with_newlines()
) {
let mut buffer = TextBuffer::from_bytes(text.clone(), test_fs());
let offset = offset.min(buffer.total_bytes());
buffer.insert_bytes(offset, insert_text.clone());
buffer.delete_bytes(offset, insert_text.len());
prop_assert_eq!(buffer.get_all_text().unwrap(), text);
}
#[test]
fn prop_offset_position_roundtrip(text in text_with_newlines()) {
let buffer = TextBuffer::from_bytes(text.clone(), test_fs());
for offset in 0..text.len() {
let pos = buffer.offset_to_position(offset).expect("offset_to_position should succeed for valid offset");
let back = buffer.position_to_offset(pos);
prop_assert_eq!(back, offset, "Failed roundtrip for offset {}", offset);
}
}
#[test]
fn prop_get_text_range_valid(
text in text_with_newlines(),
offset in 0usize..100,
length in 1usize..50
) {
if text.is_empty() {
return Ok(());
}
let buffer = TextBuffer::from_bytes(text.clone(), test_fs());
let offset = offset.min(buffer.total_bytes());
let length = length.min(buffer.total_bytes() - offset);
if length == 0 {
return Ok(());
}
let result = buffer.get_text_range(offset, length);
prop_assert_eq!(result, Some(text[offset..offset + length].to_vec()));
}
#[test]
fn prop_operations_maintain_consistency(operations in operation_strategy()) {
let mut buffer = TextBuffer::from_bytes(b"initial\ntext".to_vec(), test_fs());
let mut expected_text = b"initial\ntext".to_vec();
for op in operations {
match op {
Operation::Insert { offset, text } => {
let offset = offset.min(buffer.total_bytes());
buffer.insert_bytes(offset, text.clone());
// Update expected
let offset = offset.min(expected_text.len());
expected_text.splice(offset..offset, text);
}
Operation::Delete { offset, bytes } => {
if offset < buffer.total_bytes() {
let bytes = bytes.min(buffer.total_bytes() - offset);
buffer.delete_bytes(offset, bytes);
// Update expected
if offset < expected_text.len() {
let bytes = bytes.min(expected_text.len() - offset);
expected_text.drain(offset..offset + bytes);
}
}
}
}
}
prop_assert_eq!(buffer.get_all_text().unwrap(), expected_text);
}
#[test]
fn prop_line_count_never_zero(operations in operation_strategy()) {
let mut buffer = TextBuffer::from_bytes(b"test".to_vec(), test_fs());
for op in operations {
match op {
Operation::Insert { offset, text } => {
let offset = offset.min(buffer.total_bytes());
buffer.insert_bytes(offset, text);
}
Operation::Delete { offset, bytes } => {
buffer.delete_bytes(offset, bytes);
}
}
// Document always has at least 1 line
prop_assert!(buffer.line_count().unwrap_or(1) >= 1);
}
}
#[test]
fn prop_total_bytes_never_negative(operations in operation_strategy()) {
let mut buffer = TextBuffer::from_bytes(b"test".to_vec(), test_fs());
for op in operations {
match op {
Operation::Insert { offset, text } => {
let offset = offset.min(buffer.total_bytes());
buffer.insert_bytes(offset, text);
}
Operation::Delete { offset, bytes } => {
buffer.delete_bytes(offset, bytes);
}
}
// Bytes should never overflow
prop_assert!(buffer.total_bytes() < 10_000_000);
}
}
#[test]
fn prop_piece_tree_and_line_index_stay_synced(operations in operation_strategy()) {
let mut buffer = TextBuffer::from_bytes(b"line1\nline2\nline3".to_vec(), test_fs());
for op in operations {
match op {
Operation::Insert { offset, text } => {
let offset = offset.min(buffer.total_bytes());
buffer.insert_bytes(offset, text);
}
Operation::Delete { offset, bytes } => {
buffer.delete_bytes(offset, bytes);
}
}
// Verify we can still convert between offsets and positions
if buffer.total_bytes() > 0 {
let mid_offset = buffer.total_bytes() / 2;
if let Some(pos) = buffer.offset_to_position(mid_offset) {
let back = buffer.position_to_offset(pos);
// Should be able to roundtrip
prop_assert!(back <= buffer.total_bytes());
}
}
}
}
#[test]
fn prop_write_recipe_matches_content(text in text_with_newlines()) {
let buffer = TextBuffer::from_bytes(text.clone(), test_fs());
let recipe = buffer.build_write_recipe().expect("build_write_recipe should succeed");
// Apply the recipe to get the output
let output = apply_recipe(&buffer, &recipe);
prop_assert_eq!(output, text, "Recipe output should match original content");
}
#[test]
fn prop_write_recipe_after_edits(
initial_text in text_with_newlines(),
operations in operation_strategy()
) {
let mut buffer = TextBuffer::from_bytes(initial_text, test_fs());
// Apply random operations
for op in operations {
match op {
Operation::Insert { offset, text } => {
let offset = offset.min(buffer.total_bytes());
buffer.insert_bytes(offset, text);
}
Operation::Delete { offset, bytes } => {
if offset < buffer.total_bytes() {
let bytes = bytes.min(buffer.total_bytes() - offset);
if bytes > 0 {
buffer.delete_bytes(offset, bytes);
}
}
}
}
}
// Build recipe and verify it matches buffer content
let expected = buffer.get_all_text().unwrap();
let recipe = buffer.build_write_recipe().expect("build_write_recipe should succeed");
let output = apply_recipe(&buffer, &recipe);
prop_assert_eq!(output, expected, "Recipe output should match buffer content after edits");
}
#[test]
fn prop_write_recipe_copy_ops_valid(
text in prop::collection::vec(prop_oneof![(b'a'..=b'z').prop_map(|c| c), Just(b'\n')], 10..200),
edit_offset in 0usize..100,
edit_text in text_with_newlines()
) {
use tempfile::TempDir;
// Create a temp file with initial content
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("test.txt");
std::fs::write(&file_path, &text).unwrap();
// Load the file (creates unloaded buffer regions)
let mut buffer = TextBuffer::load_from_file(&file_path, 1024 * 1024, test_fs()).unwrap();
// Make an edit in the middle
let edit_offset = edit_offset.min(buffer.total_bytes());
buffer.insert_bytes(edit_offset, edit_text.clone());
// Build recipe - should have Copy ops for unmodified regions
let recipe = buffer.build_write_recipe().expect("build_write_recipe should succeed");
// Verify recipe produces correct output
let expected = buffer.get_all_text().unwrap();
let output = apply_recipe(&buffer, &recipe);
prop_assert_eq!(output, expected, "Recipe with Copy ops should match buffer content");
// Verify we have at least some Copy ops if the file was large enough
// (Copy ops reference unloaded regions from the original file)
if text.len() > 100 && edit_offset > 10 {
let has_copy = recipe.actions.iter().any(|a| matches!(a, RecipeAction::Copy { .. }));
// Note: We don't assert this because line ending conversion or other factors
// might cause all Insert ops, which is valid behavior
let _ = has_copy;
}
}
}
/// Helper to apply a WriteRecipe and return the resulting bytes
fn apply_recipe(buffer: &TextBuffer, recipe: &WriteRecipe) -> Vec<u8> {
let mut output = Vec::new();
for action in &recipe.actions {
match action {
RecipeAction::Copy { offset, len } => {
if let Some(src_path) = &recipe.src_path {
let data = buffer
.fs
.read_range(src_path, *offset, *len as usize)
.expect("read_range should succeed for Copy op");
output.extend_from_slice(&data);
} else {
panic!("Copy action without source path");
}
}
RecipeAction::Insert { index } => {
output.extend_from_slice(&recipe.insert_data[*index]);
}
}
}
output
}
/// Helper to check if bytes are detected as binary
fn is_detected_as_binary(bytes: &[u8]) -> bool {
TextBuffer::detect_encoding_or_binary(bytes, false).1
}
#[test]
fn test_detect_binary_text_files() {
// Plain text should not be detected as binary
assert!(!is_detected_as_binary(b"Hello, world!"));
assert!(!is_detected_as_binary(b"Line 1\nLine 2\nLine 3"));
assert!(!is_detected_as_binary(b"Tabs\tand\tnewlines\n"));
assert!(!is_detected_as_binary(b"Carriage return\r\n"));
// Empty content is not binary
assert!(!is_detected_as_binary(b""));
// ANSI CSI escape sequences should be treated as text
assert!(!is_detected_as_binary(b"\x1b[31mRed text\x1b[0m"));
}
#[test]
fn test_detect_binary_binary_files() {
// Null bytes indicate binary
assert!(is_detected_as_binary(b"Hello\x00World"));
assert!(is_detected_as_binary(b"\x00"));
// Non-printable control characters (except tab, newline, CR, form feed, vertical tab)
assert!(is_detected_as_binary(b"Text with \x01 control char"));
assert!(is_detected_as_binary(b"\x02\x03\x04"));
// DEL character (0x7F)
assert!(is_detected_as_binary(b"Text with DEL\x7F"));
}
#[test]
fn test_detect_binary_png_file() {
// PNG file signature: 89 50 4E 47 0D 0A 1A 0A
// The 0x1A byte (substitute character) is a control character that triggers binary detection
let png_header: &[u8] = &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
assert!(is_detected_as_binary(png_header));
// Simulate a PNG file with more data after header
let mut png_data = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
png_data.extend_from_slice(b"\x00\x00\x00\x0DIHDR"); // IHDR chunk with null bytes
assert!(is_detected_as_binary(&png_data));
}
#[test]
fn test_detect_binary_other_image_formats() {
// JPEG signature: FF D8 FF
let jpeg_header: &[u8] = &[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10];
assert!(is_detected_as_binary(jpeg_header));
// GIF signature: GIF89a or GIF87a - contains valid ASCII but typically followed by binary
// GIF header is ASCII but the LSD (Logical Screen Descriptor) contains binary
let gif_data: &[u8] = &[
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, // GIF89a
0x01, 0x00, 0x01, 0x00, // Width=1, Height=1 (little endian)
0x00, // Packed byte
0x00, // Background color index
0x00, // Pixel aspect ratio
];
// The null bytes in the dimensions trigger binary detection
assert!(is_detected_as_binary(gif_data));
// BMP signature: BM followed by file size (usually contains null bytes)
let bmp_header: &[u8] = &[0x42, 0x4D, 0x00, 0x00, 0x00, 0x00];
assert!(is_detected_as_binary(bmp_header));
}
#[test]
fn test_detect_binary_executable_formats() {
// ELF signature (Linux executables)
let elf_header: &[u8] = &[0x7F, 0x45, 0x4C, 0x46, 0x02, 0x01, 0x01, 0x00];
assert!(is_detected_as_binary(elf_header));
// Mach-O signature (macOS executables) - magic + cpu type/subtype contain null bytes
let macho_header: &[u8] = &[0xCF, 0xFA, 0xED, 0xFE, 0x07, 0x00, 0x00, 0x01];
assert!(is_detected_as_binary(macho_header));
// PE/COFF (Windows executables) - MZ header
let pe_header: &[u8] = &[0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00];
assert!(is_detected_as_binary(pe_header));
}
}
/// Line data with optional line number
#[derive(Debug, Clone)]
pub struct LineData {
/// Byte offset where this line starts in the document
pub byte_offset: usize,
/// Line content (without trailing newline)
pub content: String,
/// Whether this line ends with a newline
pub has_newline: bool,
/// Line number (None for large files without line metadata)
pub line_number: Option<usize>,
}
/// Iterator over lines in a TextBuffer that efficiently tracks line numbers
/// using piece tree metadata (single source of truth)
pub struct TextBufferLineIterator {
/// Collected lines (we collect all at once since we need mutable access to load chunks)
lines: Vec<LineData>,
/// Current index in the lines vector
current_index: usize,
/// Whether there are more lines after these
pub has_more: bool,
}
impl TextBufferLineIterator {
pub(crate) fn new(buffer: &mut TextBuffer, byte_pos: usize, max_lines: usize) -> Result<Self> {
let buffer_len = buffer.len();
if byte_pos >= buffer_len {
return Ok(Self {
lines: Vec::new(),
current_index: 0,
has_more: false,
});
}
// Check if buffer has line metadata (None for large files > 1MB)
let has_line_metadata = buffer.line_count().is_some();
// Determine starting line number by querying piece tree once
// (only if we have line metadata)
let mut current_line = if has_line_metadata {
buffer.offset_to_position(byte_pos).map(|pos| pos.line)
} else {
None
};
let mut lines = Vec::with_capacity(max_lines);
let mut current_offset = byte_pos;
let estimated_line_length = 80; // Use default estimate
// Collect lines by scanning forward
for _ in 0..max_lines {
if current_offset >= buffer_len {
break;
}
let line_start = current_offset;
let line_number = current_line;
// Estimate how many bytes to load for this line
let estimated_max_line_length = estimated_line_length * 3;
let bytes_to_scan = estimated_max_line_length.min(buffer_len - current_offset);
// Load chunk (this handles lazy loading)
let chunk = buffer.get_text_range_mut(current_offset, bytes_to_scan)?;
// Scan for newline
let mut line_len = 0;
let mut found_newline = false;
for &byte in chunk.iter() {
line_len += 1;
if byte == b'\n' {
found_newline = true;
break;
}
}
// Handle long lines (rare case)
if !found_newline && current_offset + line_len < buffer_len {
// Line is longer than expected, load more data
let remaining = buffer_len - current_offset - line_len;
let additional_bytes = estimated_max_line_length.min(remaining);
let more_chunk =
buffer.get_text_range_mut(current_offset + line_len, additional_bytes)?;
let mut extended_chunk = chunk;
extended_chunk.extend_from_slice(&more_chunk);
for &byte in more_chunk.iter() {
line_len += 1;
if byte == b'\n' {
found_newline = true;
break;
}
}
let line_string = String::from_utf8_lossy(&extended_chunk[..line_len]).into_owned();
let has_newline = line_string.ends_with('\n');
let content = if has_newline {
line_string[..line_string.len() - 1].to_string()
} else {
line_string
};
lines.push(LineData {
byte_offset: line_start,
content,
has_newline,
line_number,
});
current_offset += line_len;
if has_line_metadata && found_newline {
current_line = current_line.map(|n| n + 1);
}
continue;
}
// Normal case
let line_string = String::from_utf8_lossy(&chunk[..line_len]).into_owned();
let has_newline = line_string.ends_with('\n');
let content = if has_newline {
line_string[..line_string.len() - 1].to_string()
} else {
line_string
};
lines.push(LineData {
byte_offset: line_start,
content,
has_newline,
line_number,
});
current_offset += line_len;
// Increment line number if we have metadata and found a newline
if has_line_metadata && found_newline {
current_line = current_line.map(|n| n + 1);
}
}
// Check if there are more lines
let has_more = current_offset < buffer_len;
Ok(Self {
lines,
current_index: 0,
has_more,
})
}
}
impl Iterator for TextBufferLineIterator {
type Item = LineData;
fn next(&mut self) -> Option<Self::Item> {
if self.current_index < self.lines.len() {
let line = self.lines[self.current_index].clone();
self.current_index += 1;
Some(line)
} else {
None
}
}
}