bearing 0.1.0-alpha.5

A Rust port of Apache Lucene
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
// SPDX-License-Identifier: Apache-2.0
//! Shared term hashing infrastructure for per-field term accumulation.
//!
//! [`TermsHashPerFieldTrait`] matches Java's abstract `TermsHashPerField`
//! class. It provides default implementations of `add()`,
//! `init_stream_slices()`, and `position_stream_slice()` that handle term
//! interning, stream allocation, and cursor positioning. Implementors supply
//! `new_term()`/`add_term()` callbacks for encoding postings data.
//!
//! [`TermsHashPerField`] is the base struct holding shared state (term hash,
//! stream cursors, write methods). It is embedded in each implementor via
//! the `base()`/`base_mut()` accessors.
//!
//! Implementors:
//! - [`FreqProxTermsWriterPerField`] — doc/freq/position/offset encoding

use std::fmt;
use std::io;
use std::mem;

use crate::codecs::fields_producer::{NO_MORE_DOCS, PostingsEnumProducer};
use crate::document::{IndexOptions, TermOffset};
use crate::util::byte_block_pool::{ByteBlockPool, ByteSlicePool, FIRST_LEVEL_SIZE};
use crate::util::bytes_ref_hash::BytesRefHash;

// ---------------------------------------------------------------------------
// ParallelPostingsArray / FreqProxPostingsArray — per-term posting metadata
// ---------------------------------------------------------------------------

/// Bytes per posting in the base array (3 ints = 12 bytes).
pub(crate) const BYTES_PER_POSTING: usize = 3 * mem::size_of::<i32>();

/// Computes a grow size matching Java's `ArrayUtil.oversize`.
pub(crate) fn oversize(min_size: usize, bytes_per_posting: usize) -> usize {
    let extra = min_size >> 3;
    let new_size = min_size + extra;
    let remainder = new_size % bytes_per_posting;
    if remainder != 0 {
        new_size + bytes_per_posting - remainder
    } else {
        new_size
    }
}

/// Base struct-of-arrays for per-term posting metadata.
///
/// Each array is indexed by term ID. The arrays grow together via [`grow`](Self::grow).
#[derive(Debug)]
pub(crate) struct ParallelPostingsArray {
    /// Maps term ID to the term's text start in the `BytesRefHash` pool.
    pub text_starts: Vec<i32>,
    /// Maps term ID to the current stream address offset.
    pub address_offset: Vec<i32>,
    /// Maps term ID to the stream start offset in the byte pool.
    pub byte_starts: Vec<i32>,
}

impl ParallelPostingsArray {
    /// Creates a new array with the given initial capacity.
    pub(crate) fn new(size: usize) -> Self {
        Self {
            text_starts: vec![0; size],
            address_offset: vec![0; size],
            byte_starts: vec![0; size],
        }
    }

    /// Returns the current capacity.
    pub(crate) fn size(&self) -> usize {
        self.text_starts.len()
    }

    /// Returns bytes per posting (for grow size calculation).
    pub(crate) fn bytes_per_posting(&self) -> usize {
        BYTES_PER_POSTING
    }

    /// Grows the arrays to accommodate at least one more entry.
    /// Returns a new array with data copied from `self`.
    #[expect(dead_code)]
    pub(crate) fn grow(&self) -> Self {
        let new_size = oversize(self.size() + 1, self.bytes_per_posting());
        let mut new_array = Self::new(new_size);
        self.copy_to(&mut new_array, self.size());
        new_array
    }

    /// Copies `num_to_copy` elements from `self` into `to_array`.
    pub(crate) fn copy_to(&self, to_array: &mut ParallelPostingsArray, num_to_copy: usize) {
        to_array.text_starts[..num_to_copy].copy_from_slice(&self.text_starts[..num_to_copy]);
        to_array.address_offset[..num_to_copy].copy_from_slice(&self.address_offset[..num_to_copy]);
        to_array.byte_starts[..num_to_copy].copy_from_slice(&self.byte_starts[..num_to_copy]);
    }
}

/// Extended postings array with frequency and proximity fields.
///
/// Adds per-term tracking for document IDs, frequencies, positions,
/// and offsets on top of the base [`ParallelPostingsArray`].
#[derive(Debug)]
pub(crate) struct FreqProxPostingsArray {
    /// Base arrays (text starts, address offsets, byte starts).
    pub base: ParallelPostingsArray,
    /// Term frequency in the current document (only if `has_freq`).
    pub term_freqs: Option<Vec<i32>>,
    /// Last doc ID where each term occurred.
    pub last_doc_ids: Vec<i32>,
    /// Encoded doc code for the prior document.
    pub last_doc_codes: Vec<i32>,
    /// Last position where each term occurred (only if `has_prox`).
    pub last_positions: Option<Vec<i32>>,
    /// Last end offset where each term occurred (only if `has_offsets`).
    pub last_offsets: Option<Vec<i32>>,
}

impl FreqProxPostingsArray {
    /// Creates a new array with the given capacity and feature flags.
    pub(crate) fn new(
        size: usize,
        write_freqs: bool,
        write_prox: bool,
        write_offsets: bool,
    ) -> Self {
        let term_freqs = if write_freqs {
            Some(vec![0; size])
        } else {
            None
        };
        let last_positions = if write_prox {
            Some(vec![0; size])
        } else {
            assert!(!write_offsets);
            None
        };
        let last_offsets = if write_offsets {
            Some(vec![0; size])
        } else {
            None
        };
        Self {
            base: ParallelPostingsArray::new(size),
            term_freqs,
            last_doc_ids: vec![0; size],
            last_doc_codes: vec![0; size],
            last_positions,
            last_offsets,
        }
    }

    /// Returns the current capacity.
    pub(crate) fn size(&self) -> usize {
        self.base.size()
    }

    /// Returns bytes per posting (base + extended fields).
    pub(crate) fn bytes_per_posting(&self) -> usize {
        let mut bytes = self.base.bytes_per_posting();
        // lastDocIDs + lastDocCodes always present
        bytes += 2 * mem::size_of::<i32>();
        if self.term_freqs.is_some() {
            bytes += mem::size_of::<i32>();
        }
        if self.last_positions.is_some() {
            bytes += mem::size_of::<i32>();
        }
        if self.last_offsets.is_some() {
            bytes += mem::size_of::<i32>();
        }
        bytes
    }

    /// Grows the arrays to accommodate at least one more entry.
    pub(crate) fn grow(&self) -> Self {
        let new_size = oversize(self.size() + 1, self.bytes_per_posting());
        let mut new_array = Self::new(
            new_size,
            self.term_freqs.is_some(),
            self.last_positions.is_some(),
            self.last_offsets.is_some(),
        );
        self.copy_to(&mut new_array, self.size());
        new_array
    }

    /// Copies `num_to_copy` elements from `self` into `to_array`.
    pub(crate) fn copy_to(&self, to_array: &mut FreqProxPostingsArray, num_to_copy: usize) {
        self.base.copy_to(&mut to_array.base, num_to_copy);

        to_array.last_doc_ids[..num_to_copy].copy_from_slice(&self.last_doc_ids[..num_to_copy]);
        to_array.last_doc_codes[..num_to_copy].copy_from_slice(&self.last_doc_codes[..num_to_copy]);
        if let (Some(from), Some(to)) = (&self.last_positions, &mut to_array.last_positions) {
            to[..num_to_copy].copy_from_slice(&from[..num_to_copy]);
        }
        if let (Some(from), Some(to)) = (&self.last_offsets, &mut to_array.last_offsets) {
            to[..num_to_copy].copy_from_slice(&from[..num_to_copy]);
        }
        if let (Some(from), Some(to)) = (&self.term_freqs, &mut to_array.term_freqs) {
            to[..num_to_copy].copy_from_slice(&from[..num_to_copy]);
        }
    }
}

// ---------------------------------------------------------------------------
// TermsHash / TermsHashPerField
// ---------------------------------------------------------------------------

/// Initial capacity for the BytesRefHash.
const HASH_INIT_SIZE: usize = 4;

/// Shared pool storage for all TermsHashPerField instances in a segment.
///
/// Owns the int pool (stream address table) and `ByteBlockPool` that all
/// per-field writers share for posting stream data. In Java, this is
/// `TermsHash` which `FreqProxTermsWriter` extends.
pub(crate) struct TermsHash {
    /// Flat table of byte-pool write offsets, indexed by stream address.
    pub(crate) int_pool: Vec<i32>,
    pub(crate) byte_pool: ByteBlockPool,
}

impl TermsHash {
    /// Creates a new `TermsHash` with initialized pools.
    pub(crate) fn new() -> Self {
        Self {
            int_pool: Vec::with_capacity(8192),
            byte_pool: ByteBlockPool::new(32 * 1024),
        }
    }

    /// Resets both pools for reuse. Releases backing storage if capacity
    /// exceeds 64 KB to avoid pinning memory from worst-case documents.
    pub(crate) fn reset(&mut self) {
        const BYTE_POOL_SHRINK_THRESHOLD: usize = 64 * 1024;
        const INT_POOL_SHRINK_THRESHOLD: usize = BYTE_POOL_SHRINK_THRESHOLD / mem::size_of::<i32>();

        if self.byte_pool.data.capacity() > BYTE_POOL_SHRINK_THRESHOLD {
            self.byte_pool.data = Vec::with_capacity(BYTE_POOL_SHRINK_THRESHOLD);
        } else {
            self.byte_pool.reset();
        }
        if self.int_pool.capacity() > INT_POOL_SHRINK_THRESHOLD {
            self.int_pool = Vec::with_capacity(INT_POOL_SHRINK_THRESHOLD);
        } else {
            self.int_pool.clear();
        }
    }
}

impl Default for TermsHash {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for TermsHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TermsHash")
            .field("int_pool_len", &self.int_pool.len())
            .field("byte_pool_len", &self.byte_pool.data.len())
            .finish()
    }
}

impl mem_dbg::MemSize for TermsHash {
    fn mem_size_rec(
        &self,
        flags: mem_dbg::SizeFlags,
        refs: &mut mem_dbg::HashMap<usize, usize>,
    ) -> usize {
        self.int_pool.len() * mem::size_of::<i32>() + self.byte_pool.mem_size_rec(flags, refs)
    }
}

/// Per-field term processing for the inverted index.
///
/// Deduplicates terms, allocates byte stream slices, and provides write methods.
/// Stream addresses are stored in `int_pool` entries. Each term gets
/// `stream_count` consecutive int slots holding the current write address for
/// each stream.
///
/// Pools are owned by [`TermsHash`] and passed to methods that need them.
pub(crate) struct TermsHashPerField {
    /// Direct offset into the flat `int_pool` for the current term's stream addresses.
    pub(crate) stream_address_offset: usize,
    pub(crate) stream_count: usize,
    field_name: String,
    pub(crate) bytes_hash: BytesRefHash,
    sorted_term_ids: Option<Vec<i32>>,
    pub(crate) last_doc_id: i32, // assertion-only
}

impl TermsHashPerField {
    /// Creates a new `TermsHashPerField`.
    ///
    /// `stream_count` is the number of byte streams per term: 1 for doc(+freq),
    /// 2 when positions/offsets are also indexed.
    pub(crate) fn new(
        stream_count: usize,
        field_name: String,
        index_options: IndexOptions,
    ) -> Self {
        assert!(index_options != IndexOptions::None);

        let bytes_hash = BytesRefHash::new(HASH_INIT_SIZE);

        Self {
            stream_address_offset: 0,
            stream_count,
            field_name,
            bytes_hash,
            sorted_term_ids: None,
            last_doc_id: -1,
        }
    }

    /// Clears the term hash and resets state for reuse.
    pub(crate) fn reset(&mut self) {
        self.bytes_hash.clear();
        self.sorted_term_ids = None;
    }

    /// Collapses the hash table and sorts term IDs lexicographically.
    ///
    /// Must not be called twice without a [`reset`](Self::reset) in between.
    pub(crate) fn sort_terms(&mut self, byte_pool: &ByteBlockPool) {
        assert!(self.sorted_term_ids.is_none());
        self.sorted_term_ids = Some(self.bytes_hash.sort(byte_pool));
    }

    /// Returns the sorted term IDs. [`sort_terms`](Self::sort_terms) must be
    /// called first.
    pub(crate) fn sorted_term_ids(&self) -> &[i32] {
        self.sorted_term_ids
            .as_ref()
            .expect("sort_terms not called")
    }

    /// Returns the number of unique terms.
    pub(crate) fn num_terms(&self) -> usize {
        self.bytes_hash.size()
    }

    /// Returns the field name.
    pub(crate) fn field_name(&self) -> &str {
        &self.field_name
    }

    /// Returns the bytes for a given term ID (from the shared byte pool).
    pub(crate) fn term_bytes<'a>(&self, byte_pool: &'a ByteBlockPool, term_id: usize) -> &'a [u8] {
        self.bytes_hash.get(byte_pool, term_id)
    }

    /// Write a single byte to the given stream for the current term.
    pub(crate) fn write_byte(&mut self, terms_hash: &mut TermsHash, stream: usize, b: u8) {
        let stream_address = self.stream_address_offset + stream;
        let upto = terms_hash.int_pool[stream_address] as usize;
        if terms_hash.byte_pool.data[upto] != 0 {
            // End of slice; allocate a new one
            let new_offset = ByteSlicePool::alloc_slice(&mut terms_hash.byte_pool, upto);
            terms_hash.int_pool[stream_address] = new_offset as i32;
            terms_hash.byte_pool.data[new_offset] = b;
            terms_hash.int_pool[stream_address] += 1;
        } else {
            terms_hash.byte_pool.data[upto] = b;
            terms_hash.int_pool[stream_address] += 1;
        }
    }

    /// Write multiple bytes to the given stream for the current term.
    #[expect(dead_code)]
    pub(crate) fn write_bytes(&mut self, terms_hash: &mut TermsHash, stream: usize, data: &[u8]) {
        let end = data.len();
        let stream_address = self.stream_address_offset + stream;
        let mut upto = terms_hash.int_pool[stream_address] as usize;
        let mut offset = 0;

        // Write into current slice while there's room
        while terms_hash.byte_pool.data[upto] == 0 && offset < end {
            terms_hash.byte_pool.data[upto] = data[offset];
            upto += 1;
            offset += 1;
            terms_hash.int_pool[stream_address] += 1;
        }

        // If we still have data, grow slices as needed
        while offset < end {
            let (new_slice_offset, slice_length) =
                ByteSlicePool::alloc_known_size_slice(&mut terms_hash.byte_pool, upto);
            let write_length = (slice_length - 1).min(end - offset);
            terms_hash.byte_pool.data[new_slice_offset..new_slice_offset + write_length]
                .copy_from_slice(&data[offset..offset + write_length]);
            upto = new_slice_offset + write_length;
            offset += write_length;
            terms_hash.int_pool[stream_address] = upto as i32;
        }
    }

    /// Write a variable-length encoded integer to the given stream.
    pub(crate) fn write_v_int(&mut self, terms_hash: &mut TermsHash, stream: usize, mut i: i32) {
        assert!(stream < self.stream_count);
        while (i & !0x7F) != 0 {
            self.write_byte(terms_hash, stream, ((i & 0x7F) | 0x80) as u8);
            i = ((i as u32) >> 7) as i32;
        }
        self.write_byte(terms_hash, stream, i as u8);
    }
}

impl fmt::Debug for TermsHashPerField {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TermsHashPerField")
            .field("field_name", &self.field_name)
            .field("stream_count", &self.stream_count)
            .field("num_terms", &self.bytes_hash.size())
            .finish()
    }
}

// ---------------------------------------------------------------------------
// TermsHashPerFieldTrait
// ---------------------------------------------------------------------------

/// Abstract per-field term processing trait.
///
/// Matches Java's abstract `TermsHashPerField` class. Implementors provide
/// access to their base struct and postings array, plus `new_term`/`add_term`
/// callbacks. Default methods implement the concrete `add()`,
/// `init_stream_slices()`, and `position_stream_slice()` logic from Java.
pub(crate) trait TermsHashPerFieldTrait {
    /// Access the base `TermsHashPerField` (shared fields).
    fn base(&self) -> &TermsHashPerField;

    /// Mutable access to the base `TermsHashPerField`.
    fn base_mut(&mut self) -> &mut TermsHashPerField;

    /// Access the `ParallelPostingsArray` base of the concrete postings array.
    fn postings_array_base(&self) -> &ParallelPostingsArray;

    /// Mutable access to the `ParallelPostingsArray` base.
    fn postings_array_base_mut(&mut self) -> &mut ParallelPostingsArray;

    /// Ensure the postings array can hold `term_id`. Grows if needed.
    fn ensure_postings_capacity(&mut self, term_id: usize);

    /// Called when a term is seen for the first time.
    fn new_term(&mut self, terms_hash: &mut TermsHash, term_id: usize, doc_id: i32);

    /// Called when a previously seen term is seen again.
    fn add_term(&mut self, terms_hash: &mut TermsHash, term_id: usize, doc_id: i32);

    /// Primary entry point: intern term bytes, allocate/position streams,
    /// dispatch to `new_term`/`add_term`.
    ///
    /// `term_byte_pool` is the shared pool for term text (from the accumulator).
    /// `terms_hash` holds the per-consumer stream pools for postings data.
    ///
    /// Returns the (positive) term ID.
    fn add(
        &mut self,
        term_byte_pool: &mut ByteBlockPool,
        terms_hash: &mut TermsHash,
        term_bytes: &[u8],
        doc_id: i32,
    ) -> usize {
        {
            let base = self.base_mut();
            debug_assert!(doc_id >= base.last_doc_id);
            base.last_doc_id = doc_id;
        }

        let term_id = self.base_mut().bytes_hash.add(term_byte_pool, term_bytes);

        if term_id >= 0 {
            let tid = term_id as usize;
            self.init_stream_slices(terms_hash, tid, doc_id);
            tid
        } else {
            let tid = ((-term_id) - 1) as usize;
            self.position_stream_slice(terms_hash, tid, doc_id);
            tid
        }
    }

    /// Secondary entry point for pre-interned terms (term vectors).
    fn add_by_text_start(&mut self, terms_hash: &mut TermsHash, text_start: i32, doc_id: i32) {
        let term_id = self.base_mut().bytes_hash.add_by_pool_offset(text_start);

        if term_id >= 0 {
            let tid = term_id as usize;
            self.init_stream_slices(terms_hash, tid, doc_id);
        } else {
            let tid = ((-term_id) - 1) as usize;
            self.position_stream_slice(terms_hash, tid, doc_id);
        }
    }

    /// Allocate stream slices for a new term.
    fn init_stream_slices(&mut self, terms_hash: &mut TermsHash, term_id: usize, doc_id: i32) {
        // Ensure postings array has capacity for this term
        self.ensure_postings_capacity(term_id);

        // Set text_starts
        let byte_start = self.base().bytes_hash.byte_start(term_id);
        self.postings_array_base_mut().text_starts[term_id] = byte_start;

        let stream_count = self.base().stream_count;

        let stream_address_offset = terms_hash.int_pool.len();
        terms_hash
            .int_pool
            .resize(stream_address_offset + stream_count, 0);

        self.base_mut().stream_address_offset = stream_address_offset;

        self.postings_array_base_mut().address_offset[term_id] = stream_address_offset as i32;

        for i in 0..stream_count {
            let upto = ByteSlicePool::new_slice(&mut terms_hash.byte_pool, FIRST_LEVEL_SIZE);
            terms_hash.int_pool[stream_address_offset + i] = upto as i32;
        }

        let byte_starts = terms_hash.int_pool[stream_address_offset];
        self.postings_array_base_mut().byte_starts[term_id] = byte_starts;

        self.new_term(terms_hash, term_id, doc_id);
    }

    /// Position stream cursors for an existing term, then dispatch to `add_term`.
    fn position_stream_slice(&mut self, terms_hash: &mut TermsHash, term_id: usize, doc_id: i32) {
        let int_start = self.postings_array_base().address_offset[term_id] as usize;
        self.base_mut().stream_address_offset = int_start;

        self.add_term(terms_hash, term_id, doc_id);
    }
}

// ---------------------------------------------------------------------------
// FreqProxTermsWriterPerField
// ---------------------------------------------------------------------------

/// Concrete per-field posting writer for frequency and proximity data.
///
/// Extends `TermsHashPerField` via composition. Implements the `newTerm` and
/// `addTerm` logic that encodes doc IDs, frequencies, positions, and offsets
/// into the byte pool streams.
/// One document's entry in a decoded term's posting list.
///
/// Positions are stored in a separate flat buffer; `pos_start` and `pos_count`
/// index into that buffer.
#[derive(Debug, Clone, Copy)]
pub(crate) struct DecodedDoc {
    pub doc_id: i32,
    pub freq: i32,
    pub pos_start: u32,
}

/// Reusable buffers for decoded term postings.
///
/// Avoids per-term allocation by reusing flat buffers across calls to
/// `decode_term_into`. Each [`DecodedDoc`] entry indexes into the flat
/// `positions` buffer.
pub(crate) struct DecodedPostings {
    /// Per-document metadata.
    pub docs: Vec<DecodedDoc>,
    /// Flat positions buffer; docs reference ranges via `pos_start`/`pos_count`.
    pub positions: Vec<i32>,
    /// Flat offsets buffer, parallel to `positions`. Empty when offsets not indexed.
    pub offsets: Vec<TermOffset>,
}

/// Buffer capacity threshold in bytes. Buffers larger than this are replaced
/// to allow the OS to reclaim the pages.
const DECODED_SHRINK_THRESHOLD: usize = 4096;

impl DecodedPostings {
    /// Creates new empty buffers.
    pub fn new() -> Self {
        Self {
            docs: Vec::new(),
            positions: Vec::new(),
            offsets: Vec::new(),
        }
    }

    /// Clears for reuse. Shrinks buffers that have grown beyond the threshold.
    pub fn clear(&mut self) {
        self.docs.clear();
        if self.docs.capacity() * mem::size_of::<DecodedDoc>() > DECODED_SHRINK_THRESHOLD {
            self.docs = Vec::new();
        }
        self.positions.clear();
        if self.positions.capacity() * mem::size_of::<i32>() > DECODED_SHRINK_THRESHOLD {
            self.positions = Vec::new();
        }
        self.offsets.clear();
        if self.offsets.capacity() * mem::size_of::<TermOffset>() > DECODED_SHRINK_THRESHOLD {
            self.offsets = Vec::new();
        }
    }
}

/// [`PostingsEnumProducer`] that owns a [`DecodedPostings`] and iterates
/// over its contents.
pub(crate) struct BufferedPostingsEnum {
    decoded: DecodedPostings,
    doc_freq: i32,
    total_term_freq: i64,
    doc_idx: usize,
    pos_idx: usize,
}

impl BufferedPostingsEnum {
    /// Creates a new enum from owned decoded postings data.
    pub fn new(decoded: DecodedPostings, has_freqs: bool) -> Self {
        let doc_freq = decoded.docs.len() as i32;
        let total_term_freq = if has_freqs {
            decoded.docs.iter().map(|d| d.freq as i64).sum()
        } else {
            -1
        };
        Self {
            decoded,
            doc_freq,
            total_term_freq,
            doc_idx: 0,
            pos_idx: 0,
        }
    }

    fn current_doc(&self) -> &DecodedDoc {
        &self.decoded.docs[self.doc_idx - 1]
    }
}

impl PostingsEnumProducer for BufferedPostingsEnum {
    fn doc_freq(&self) -> i32 {
        self.doc_freq
    }

    fn total_term_freq(&self) -> i64 {
        self.total_term_freq
    }

    fn next_doc(&mut self) -> io::Result<i32> {
        if self.doc_idx >= self.decoded.docs.len() {
            return Ok(NO_MORE_DOCS);
        }
        let doc_id = self.decoded.docs[self.doc_idx].doc_id;
        self.pos_idx = 0;
        self.doc_idx += 1;
        Ok(doc_id)
    }

    fn freq(&self) -> i32 {
        self.current_doc().freq
    }

    fn next_position(&mut self) -> io::Result<i32> {
        let doc = self.current_doc();
        let abs_idx = doc.pos_start as usize + self.pos_idx;
        let pos = self.decoded.positions[abs_idx];
        self.pos_idx += 1;
        Ok(pos)
    }

    fn offset(&self) -> Option<TermOffset> {
        if self.decoded.offsets.is_empty() {
            return None;
        }
        let doc = self.current_doc();
        let abs_idx = doc.pos_start as usize + self.pos_idx - 1;
        Some(self.decoded.offsets[abs_idx])
    }

    fn payload(&self) -> Option<&[u8]> {
        None
    }
}

///
/// Stream 0: doc codes and frequencies
/// Stream 1: position codes, offsets, and payloads (when has_prox)
pub(crate) struct FreqProxTermsWriterPerField {
    /// Base term hash functionality (BytesRefHash, stream cursors).
    pub base: TermsHashPerField,
    /// Per-term posting metadata arrays.
    pub postings_array: FreqProxPostingsArray,
    /// What information is indexed for this field.
    pub index_options: IndexOptions,
    /// Whether this field indexes term frequencies.
    pub has_freq: bool,
    /// Whether this field indexes positions.
    pub has_prox: bool,
    /// Whether this field indexes offsets.
    pub has_offsets: bool,
    /// Whether any token had a payload in the current segment.
    pub saw_payloads: bool,
    /// Tracks max term frequency across all terms for the current document.
    pub max_term_frequency: i32,
    /// Tracks unique term count for the current document.
    pub unique_term_count: i32,
    // Current token state — set before calling trait add(), read by new_term/add_term.
    pub(crate) current_position: i32,
    pub(crate) current_offset: TermOffset,
}

impl FreqProxTermsWriterPerField {
    /// Creates a new `FreqProxTermsWriterPerField`.
    pub(crate) fn new(field_name: String, index_options: IndexOptions) -> Self {
        let has_freq = index_options >= IndexOptions::DocsAndFreqs;
        let has_prox = index_options >= IndexOptions::DocsAndFreqsAndPositions;
        let has_offsets = index_options >= IndexOptions::DocsAndFreqsAndPositionsAndOffsets;

        let stream_count = if has_prox { 2 } else { 1 };

        let base = TermsHashPerField::new(stream_count, field_name, index_options);

        let postings_array = FreqProxPostingsArray::new(2, has_freq, has_prox, has_offsets);

        Self {
            base,
            postings_array,
            index_options,
            has_freq,
            has_prox,
            has_offsets,
            saw_payloads: false,
            max_term_frequency: 0,
            unique_term_count: 0,
            current_position: 0,
            current_offset: TermOffset::default(),
        }
    }

    /// Add a term occurrence for the given document.
    ///
    /// `term_byte_pool` is the shared pool for term text (from the accumulator).
    /// `terms_hash` holds the per-consumer stream pools.
    ///
    /// The caller must set `current_position`, `current_start_offset`, and
    /// `current_offset_length` before calling this method.
    pub(crate) fn add(
        &mut self,
        term_byte_pool: &mut ByteBlockPool,
        terms_hash: &mut TermsHash,
        term_bytes: &[u8],
        doc_id: i32,
    ) -> io::Result<usize> {
        let tid = TermsHashPerFieldTrait::add(self, term_byte_pool, terms_hash, term_bytes, doc_id);
        Ok(tid)
    }

    /// Convenience: sets position/offset state and calls `add()`.
    #[cfg(test)]
    pub(crate) fn add_at(
        &mut self,
        term_byte_pool: &mut ByteBlockPool,
        terms_hash: &mut TermsHash,
        term_bytes: &[u8],
        doc_id: i32,
        pos: TermPosition,
    ) -> io::Result<usize> {
        self.current_position = pos.position;
        self.current_offset = pos.offset;
        self.add(term_byte_pool, terms_hash, term_bytes, doc_id)
    }

    /// Resets this per-field state.
    #[expect(dead_code)]
    pub(crate) fn reset(&mut self) {
        self.base.reset();
    }

    /// Finish adding all instances of this field to the current document.
    #[expect(dead_code)]
    pub(crate) fn finish(&self) {
        // No-op — TV chaining is handled at the consumer level.
    }

    /// Returns the number of unique terms.
    pub(crate) fn num_terms(&self) -> usize {
        self.base.num_terms()
    }

    /// Sort terms lexicographically.
    pub(crate) fn sort_terms(&mut self, byte_pool: &ByteBlockPool) {
        self.base.sort_terms(byte_pool);
    }

    /// Returns sorted term IDs.
    pub(crate) fn sorted_term_ids(&self) -> &[i32] {
        self.base.sorted_term_ids()
    }

    /// Returns the bytes for a given term ID.
    pub(crate) fn term_bytes<'a>(&self, byte_pool: &'a ByteBlockPool, term_id: usize) -> &'a [u8] {
        self.base.term_bytes(byte_pool, term_id)
    }

    /// Flushes the pending (last) document for every term into stream 0.
    ///
    /// Must be called before reading back postings data. Writes the
    /// remaining `last_doc_codes` and `term_freqs` for each term.
    pub(crate) fn flush_pending_docs(&mut self, terms_hash: &mut TermsHash) {
        let num_terms = self.base.num_terms();
        for term_id in 0..num_terms {
            // Position the stream cursor for this term
            let int_start = self.postings_array.base.address_offset[term_id] as usize;
            self.base.stream_address_offset = int_start;

            if !self.has_freq {
                // DOCS only: write last doc code
                let code = self.postings_array.last_doc_codes[term_id];
                self.base.write_v_int(terms_hash, 0, code);
            } else {
                let freq = self.postings_array.term_freqs.as_ref().unwrap()[term_id];
                let code = self.postings_array.last_doc_codes[term_id];
                if freq == 1 {
                    self.base.write_v_int(terms_hash, 0, code | 1);
                } else {
                    self.base.write_v_int(terms_hash, 0, code);
                    self.base.write_v_int(terms_hash, 0, freq);
                }
            }
        }
    }

    /// Decodes one term's postings from the shared pools into reusable buffers.
    ///
    /// Reads the Lucene-style `(doc_delta << 1) | freq_is_1` encoding
    /// from stream 0 and `position << 1` from stream 1.
    pub(crate) fn decode_term_into(
        &self,
        terms_hash: &TermsHash,
        term_id: usize,
        buf: &mut DecodedPostings,
    ) -> io::Result<()> {
        use crate::util::byte_block_pool::ByteSliceReader;

        buf.clear();

        let (start, end) = self.get_stream_range(&terms_hash.int_pool, term_id, 0);
        let mut reader = ByteSliceReader::new(&terms_hash.byte_pool, start, end);

        let mut pos_reader = if self.has_prox {
            let (ps, pe) = self.get_stream_range(&terms_hash.int_pool, term_id, 1);
            Some(ByteSliceReader::new(&terms_hash.byte_pool, ps, pe))
        } else {
            None
        };

        let mut last_doc_id = 0;

        while !reader.eof() {
            let code = reader.read_vint()?;
            let (doc_delta, freq);

            if !self.has_freq {
                // DOCS only: code is plain doc delta
                doc_delta = code;
                freq = 1;
            } else {
                // doc_delta << 1 | freq_is_1
                doc_delta = code >> 1;
                if (code & 1) != 0 {
                    freq = 1;
                } else {
                    freq = reader.read_vint()?;
                }
            }

            let doc_id = last_doc_id + doc_delta;
            last_doc_id = doc_id;

            let pos_start = buf.positions.len() as u32;

            if let Some(ref mut pr) = pos_reader {
                let mut last_pos = 0;
                let mut last_start_offset = 0u32;
                for _ in 0..freq {
                    let prox_code = pr.read_vint()?;
                    // proxCode = positionDelta << 1 (no payload support)
                    let pos_delta = prox_code >> 1;
                    let pos = last_pos + pos_delta;
                    buf.positions.push(pos);
                    last_pos = pos;

                    if self.has_offsets {
                        let start_offset_delta = pr.read_vint()? as u32;
                        let length = pr.read_vint()? as u16;
                        let start = last_start_offset + start_offset_delta;
                        buf.offsets.push(TermOffset { start, length });
                        last_start_offset = start;
                    }
                }
            }

            buf.docs.push(DecodedDoc {
                doc_id,
                freq,
                pos_start,
            });
        }

        Ok(())
    }

    /// Returns the stream range for constructing a reader.
    pub(crate) fn get_stream_range(
        &self,
        int_pool: &[i32],
        term_id: usize,
        stream: usize,
    ) -> (usize, usize) {
        assert!(stream < self.base.stream_count);
        let address_offset = self.postings_array.base.address_offset[term_id] as usize;
        let end = int_pool[address_offset + stream] as usize;
        let start =
            self.postings_array.base.byte_starts[term_id] as usize + stream * FIRST_LEVEL_SIZE;
        (start, end)
    }
}

impl fmt::Debug for FreqProxTermsWriterPerField {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FreqProxTermsWriterPerField")
            .field("field_name", &self.base.field_name)
            .field("num_terms", &self.base.bytes_hash.size())
            .field("has_freq", &self.has_freq)
            .field("has_prox", &self.has_prox)
            .field("has_offsets", &self.has_offsets)
            .finish()
    }
}

impl mem_dbg::MemSize for FreqProxTermsWriterPerField {
    fn mem_size_rec(
        &self,
        flags: mem_dbg::SizeFlags,
        refs: &mut mem_dbg::HashMap<usize, usize>,
    ) -> usize {
        mem::size_of::<Self>()
            + self.base.bytes_hash.mem_size_rec(flags, refs)
            + self.postings_array.size() * self.postings_array.bytes_per_posting()
    }
}

impl TermsHashPerFieldTrait for FreqProxTermsWriterPerField {
    fn base(&self) -> &TermsHashPerField {
        &self.base
    }

    fn base_mut(&mut self) -> &mut TermsHashPerField {
        &mut self.base
    }

    fn postings_array_base(&self) -> &ParallelPostingsArray {
        &self.postings_array.base
    }

    fn postings_array_base_mut(&mut self) -> &mut ParallelPostingsArray {
        &mut self.postings_array.base
    }

    fn ensure_postings_capacity(&mut self, term_id: usize) {
        while term_id >= self.postings_array.size() {
            let grown = self.postings_array.grow();
            self.postings_array = grown;
        }
    }

    fn new_term(&mut self, terms_hash: &mut TermsHash, term_id: usize, doc_id: i32) {
        let position = self.current_position;
        let start_offset = self.current_offset.start as i32;
        let offset_length = self.current_offset.length;

        let postings = &mut self.postings_array;

        postings.last_doc_ids[term_id] = doc_id;
        if !self.has_freq {
            postings.last_doc_codes[term_id] = doc_id;
            self.max_term_frequency = self.max_term_frequency.max(1);
        } else {
            postings.last_doc_codes[term_id] = doc_id << 1;
            postings.term_freqs.as_mut().unwrap()[term_id] = 1;
            if self.has_prox {
                self.base.write_v_int(terms_hash, 1, position << 1);
                postings.last_positions.as_mut().unwrap()[term_id] = position;
                if self.has_offsets {
                    postings.last_offsets.as_mut().unwrap()[term_id] = 0;
                    self.base.write_v_int(terms_hash, 1, start_offset);
                    self.base.write_v_int(terms_hash, 1, offset_length as i32);
                    postings.last_offsets.as_mut().unwrap()[term_id] = start_offset;
                }
            }
            self.max_term_frequency = self
                .max_term_frequency
                .max(postings.term_freqs.as_ref().unwrap()[term_id]);
        }
        self.unique_term_count += 1;
    }

    fn add_term(&mut self, terms_hash: &mut TermsHash, term_id: usize, doc_id: i32) {
        let position = self.current_position;
        let start_offset = self.current_offset.start as i32;
        let offset_length = self.current_offset.length;

        let postings = &mut self.postings_array;

        if !self.has_freq {
            if doc_id != postings.last_doc_ids[term_id] {
                assert!(doc_id > postings.last_doc_ids[term_id]);
                self.base
                    .write_v_int(terms_hash, 0, postings.last_doc_codes[term_id]);
                postings.last_doc_codes[term_id] = doc_id - postings.last_doc_ids[term_id];
                postings.last_doc_ids[term_id] = doc_id;
                self.unique_term_count += 1;
            }
        } else if doc_id != postings.last_doc_ids[term_id] {
            assert!(doc_id > postings.last_doc_ids[term_id]);
            if postings.term_freqs.as_ref().unwrap()[term_id] == 1 {
                self.base
                    .write_v_int(terms_hash, 0, postings.last_doc_codes[term_id] | 1);
            } else {
                self.base
                    .write_v_int(terms_hash, 0, postings.last_doc_codes[term_id]);
                self.base.write_v_int(
                    terms_hash,
                    0,
                    postings.term_freqs.as_ref().unwrap()[term_id],
                );
            }

            postings.term_freqs.as_mut().unwrap()[term_id] = 1;
            self.max_term_frequency = self.max_term_frequency.max(1);
            postings.last_doc_codes[term_id] = (doc_id - postings.last_doc_ids[term_id]) << 1;
            postings.last_doc_ids[term_id] = doc_id;
            if self.has_prox {
                self.base.write_v_int(terms_hash, 1, position << 1);
                postings.last_positions.as_mut().unwrap()[term_id] = position;
                if self.has_offsets {
                    postings.last_offsets.as_mut().unwrap()[term_id] = 0;
                    self.base.write_v_int(terms_hash, 1, start_offset);
                    self.base.write_v_int(terms_hash, 1, offset_length as i32);
                    postings.last_offsets.as_mut().unwrap()[term_id] = start_offset;
                }
            }
            self.unique_term_count += 1;
        } else {
            // Same document
            let freq = postings.term_freqs.as_mut().unwrap();
            freq[term_id] = freq[term_id]
                .checked_add(1)
                .expect("term frequency overflow");
            self.max_term_frequency = self.max_term_frequency.max(freq[term_id]);
            if self.has_prox {
                let last_pos = postings.last_positions.as_ref().unwrap()[term_id];
                self.base
                    .write_v_int(terms_hash, 1, (position - last_pos) << 1);
                postings.last_positions.as_mut().unwrap()[term_id] = position;
                if self.has_offsets {
                    let last_offset = postings.last_offsets.as_ref().unwrap()[term_id];
                    self.base
                        .write_v_int(terms_hash, 1, start_offset - last_offset);
                    self.base.write_v_int(terms_hash, 1, offset_length as i32);
                    postings.last_offsets.as_mut().unwrap()[term_id] = start_offset;
                }
            }
        }
    }
}

/// Position and character offset for a term occurrence.
#[cfg(test)]
pub(crate) struct TermPosition {
    position: i32,
    offset: TermOffset,
}

#[cfg(test)]
impl TermPosition {
    fn new(position: i32, start: u32, length: u16) -> Self {
        Self {
            position,
            offset: TermOffset { start, length },
        }
    }
}

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

    use crate::util::byte_block_pool::ByteSliceReader;
    use assertables::*;

    /// Helper to read a VInt from a byte slice reader.
    fn read_vint(reader: &mut ByteSliceReader<'_>) -> i32 {
        reader.read_vint().unwrap()
    }

    fn new_term_pool() -> ByteBlockPool {
        ByteBlockPool::new(32 * 1024)
    }

    #[test]
    fn test_single_term_single_doc() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field =
            FreqProxTermsWriterPerField::new("body".to_string(), IndexOptions::DocsAndFreqs);

        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(0, 0, 5u16),
            )
            .unwrap();

        assert_eq!(field.num_terms(), 1);
        assert_eq!(field.term_bytes(&term_pool, 0), b"hello");
    }

    #[test]
    fn test_duplicate_term_same_doc() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field = FreqProxTermsWriterPerField::new(
            "body".to_string(),
            IndexOptions::DocsAndFreqsAndPositions,
        );

        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(0, 0, 5u16),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(1, 6, 5),
            )
            .unwrap();

        assert_eq!(field.num_terms(), 1);
        // Freq should be 2
        assert_eq!(field.postings_array.term_freqs.as_ref().unwrap()[0], 2);
    }

    #[test]
    fn test_multiple_terms() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field =
            FreqProxTermsWriterPerField::new("body".to_string(), IndexOptions::DocsAndFreqs);

        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(0, 0, 5u16),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"world",
                0,
                TermPosition::new(1, 6, 5),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(2, 12, 5),
            )
            .unwrap();

        assert_eq!(field.num_terms(), 2);
        // "hello" freq should be 2
        let hello_id = field.base.bytes_hash.find(&term_pool, b"hello");
        assert_ge!(hello_id, 0);
        assert_eq!(
            field.postings_array.term_freqs.as_ref().unwrap()[hello_id as usize],
            2
        );
    }

    #[test]
    fn test_term_across_documents() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field = FreqProxTermsWriterPerField::new(
            "body".to_string(),
            IndexOptions::DocsAndFreqsAndPositions,
        );

        // Doc 0: "hello world"
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(0, 0, 5u16),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"world",
                0,
                TermPosition::new(1, 6, 5),
            )
            .unwrap();

        // Doc 1: "hello"
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                1,
                TermPosition::new(0, 0, 5),
            )
            .unwrap();

        assert_eq!(field.num_terms(), 2);

        // Read back the doc/freq stream for "hello" (stream 0)
        let hello_id = field.base.bytes_hash.find(&term_pool, b"hello") as usize;
        let (start, end) = field.get_stream_range(&th.int_pool, hello_id, 0);
        let mut reader = ByteSliceReader::new(&th.byte_pool, start, end);

        // First doc: code = 0 << 1 = 0, freq = 1 → encoded as (0 | 1) = 1
        let code = read_vint(&mut reader);
        assert_eq!(code, 1); // doc_delta=0 << 1 | 1 (freq=1 packed)

        // Second doc hasn't been flushed yet (it's the current pending doc)
        assert!(reader.eof());
    }

    #[test]
    fn test_sort_terms_lexicographic() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field =
            FreqProxTermsWriterPerField::new("body".to_string(), IndexOptions::DocsAndFreqs);

        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"cherry",
                0,
                TermPosition::new(0, 0, 6u16),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"apple",
                0,
                TermPosition::new(1, 7, 5),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"banana",
                0,
                TermPosition::new(2, 13, 6),
            )
            .unwrap();

        field.sort_terms(&term_pool);
        let sorted = field.sorted_term_ids();
        assert_len_eq_x!(sorted, 3);

        assert_eq!(field.term_bytes(&term_pool, sorted[0] as usize), b"apple");
        assert_eq!(field.term_bytes(&term_pool, sorted[1] as usize), b"banana");
        assert_eq!(field.term_bytes(&term_pool, sorted[2] as usize), b"cherry");
    }

    #[test]
    fn test_docs_only_no_freq() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field = FreqProxTermsWriterPerField::new("tags".to_string(), IndexOptions::Docs);

        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"tag1",
                0,
                TermPosition::new(0, 0, 4u16),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"tag1",
                1,
                TermPosition::new(0, 0, 4u16),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"tag1",
                2,
                TermPosition::new(0, 0, 4u16),
            )
            .unwrap();

        assert_eq!(field.num_terms(), 1);
        assert!(!field.has_freq);

        // Read stream 0 — should have doc codes
        let tid = field.base.bytes_hash.find(&term_pool, b"tag1") as usize;
        let (start, end) = field.get_stream_range(&th.int_pool, tid, 0);
        let mut reader = ByteSliceReader::new(&th.byte_pool, start, end);

        // Doc 0 encoded, doc 1 delta encoded (1-0=1)
        let code0 = read_vint(&mut reader);
        assert_eq!(code0, 0); // doc 0
        let code1 = read_vint(&mut reader);
        assert_eq!(code1, 1); // delta: 1-0=1
        // Doc 2 is still pending (not flushed)
    }

    #[test]
    fn test_positions_stream() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field = FreqProxTermsWriterPerField::new(
            "body".to_string(),
            IndexOptions::DocsAndFreqsAndPositions,
        );

        // "hello" appears at positions 0 and 3 in doc 0
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(0, 0, 5u16),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"other",
                0,
                TermPosition::new(1, 6, 5),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"stuff",
                0,
                TermPosition::new(2, 12, 5),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(3, 18, 5),
            )
            .unwrap();

        let hello_id = field.base.bytes_hash.find(&term_pool, b"hello") as usize;

        // Read position stream (stream 1)
        let (start, end) = field.get_stream_range(&th.int_pool, hello_id, 1);
        let mut reader = ByteSliceReader::new(&th.byte_pool, start, end);

        // Position 0: proxCode = 0 << 1 = 0 (no payload)
        let pos0 = read_vint(&mut reader);
        assert_eq!(pos0, 0); // position 0 << 1

        // Position 3: proxCode = (3 - 0) << 1 = 6 (delta from last position)
        let pos1 = read_vint(&mut reader);
        assert_eq!(pos1, 6); // delta 3 << 1
    }

    #[test]
    fn test_multi_doc_freq_encoding() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field =
            FreqProxTermsWriterPerField::new("body".to_string(), IndexOptions::DocsAndFreqs);

        // Doc 0: "hello" x3
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(0, 0, 5u16),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(1, 6, 5),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(2, 12, 5),
            )
            .unwrap();

        // Doc 1: "hello" x1
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                1,
                TermPosition::new(0, 0, 5),
            )
            .unwrap();

        // Doc 2: "hello" x2
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                2,
                TermPosition::new(0, 0, 5),
            )
            .unwrap();
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                2,
                TermPosition::new(1, 6, 5),
            )
            .unwrap();

        let hello_id = field.base.bytes_hash.find(&term_pool, b"hello") as usize;
        let (start, end) = field.get_stream_range(&th.int_pool, hello_id, 0);
        let mut reader = ByteSliceReader::new(&th.byte_pool, start, end);

        // Doc 0: delta=0, freq=3 → docCode = 0<<1 = 0, then freq=3
        let doc0_code = read_vint(&mut reader);
        assert_eq!(doc0_code, 0); // 0 << 1
        let doc0_freq = read_vint(&mut reader);
        assert_eq!(doc0_freq, 3);

        // Doc 1: delta=1, freq=1 → docCode = 1<<1|1 = 3 (freq packed)
        let doc1_code = read_vint(&mut reader);
        assert_eq!(doc1_code, 3); // (1 << 1) | 1

        // Doc 2 is still pending (current doc, not yet flushed)
        assert!(reader.eof());
    }

    #[test]
    fn test_max_term_frequency_tracking() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field =
            FreqProxTermsWriterPerField::new("body".to_string(), IndexOptions::DocsAndFreqs);

        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"a",
                0,
                TermPosition::new(0, 0, 1u16),
            )
            .unwrap();
        field
            .add_at(&mut term_pool, &mut th, b"b", 0, TermPosition::new(1, 2, 1))
            .unwrap();
        field
            .add_at(&mut term_pool, &mut th, b"a", 0, TermPosition::new(2, 4, 1))
            .unwrap();
        field
            .add_at(&mut term_pool, &mut th, b"a", 0, TermPosition::new(3, 6, 1))
            .unwrap();

        assert_eq!(field.max_term_frequency, 3); // "a" appeared 3 times
    }

    #[test]
    fn test_unique_term_count_tracking() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field =
            FreqProxTermsWriterPerField::new("body".to_string(), IndexOptions::DocsAndFreqs);

        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"a",
                0,
                TermPosition::new(0, 0, 1u16),
            )
            .unwrap();
        field
            .add_at(&mut term_pool, &mut th, b"b", 0, TermPosition::new(1, 2, 1))
            .unwrap();
        field
            .add_at(&mut term_pool, &mut th, b"a", 0, TermPosition::new(2, 4, 1))
            .unwrap();

        assert_eq!(field.unique_term_count, 2);
    }

    #[test]
    fn test_oversize_aligns_to_bytes_per_posting() {
        // When remainder != 0, oversize rounds up
        let result = oversize(3, 12);
        assert_eq!(result % 12, 0);
        assert_ge!(result, 3);
    }

    #[test]
    fn test_terms_hash_reset() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field =
            FreqProxTermsWriterPerField::new("body".to_string(), IndexOptions::DocsAndFreqs);
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(0, 0, 5u16),
            )
            .unwrap();

        th.reset();
        // After reset, pools are cleared — new terms can be added
        let mut field2 =
            FreqProxTermsWriterPerField::new("body".to_string(), IndexOptions::DocsAndFreqs);
        field2
            .add_at(
                &mut term_pool,
                &mut th,
                b"world",
                0,
                TermPosition::new(0, 0, 5),
            )
            .unwrap();
        assert_eq!(field2.num_terms(), 1);
    }

    #[test]
    fn test_terms_hash_default() {
        let th = TermsHash::default();
        assert_eq!(th.int_pool.len(), 0);
    }

    #[test]
    fn test_terms_hash_debug() {
        let th = TermsHash::new();
        let debug = format!("{th:?}");
        assert_contains!(debug, "TermsHash");
        assert_contains!(debug, "int_pool_len");
    }

    #[test]
    fn test_terms_hash_per_field_debug() {
        let thpf = TermsHashPerField::new(1, "body".to_string(), IndexOptions::DocsAndFreqs);
        let debug = format!("{thpf:?}");
        assert_contains!(debug, "TermsHashPerField");
        assert_contains!(debug, "body");
    }

    #[test]
    fn test_freq_prox_debug() {
        let field =
            FreqProxTermsWriterPerField::new("body".to_string(), IndexOptions::DocsAndFreqs);
        let debug = format!("{field:?}");
        assert_contains!(debug, "FreqProxTermsWriterPerField");
        assert_contains!(debug, "body");
        assert_contains!(debug, "has_freq");
    }

    #[test]
    fn test_freq_prox_mem_size() {
        use mem_dbg::{MemSize, SizeFlags};
        let field =
            FreqProxTermsWriterPerField::new("body".to_string(), IndexOptions::DocsAndFreqs);
        let size = field.mem_size(SizeFlags::CAPACITY);
        assert_gt!(size, 0);
    }

    #[test]
    fn test_positions_and_offsets() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field = FreqProxTermsWriterPerField::new(
            "body".to_string(),
            IndexOptions::DocsAndFreqsAndPositionsAndOffsets,
        );

        // "hello" at position 0 with offsets [0, 5)
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(0, 0, 5u16),
            )
            .unwrap();
        // "hello" at position 3 with offsets [18, 23)
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(3, 18, 5),
            )
            .unwrap();

        assert_eq!(field.num_terms(), 1);
        assert!(field.has_offsets);

        let hello_id = field.base.bytes_hash.find(&term_pool, b"hello") as usize;

        // Read prox stream (stream 1) — positions and offsets interleaved
        let (start, end) = field.get_stream_range(&th.int_pool, hello_id, 1);
        let mut reader = ByteSliceReader::new(&th.byte_pool, start, end);

        // Position 0: proxCode = 0 << 1 = 0
        let pos0 = read_vint(&mut reader);
        assert_eq!(pos0, 0);
        // Offset for position 0: start_offset = 0, length = 5
        let off0_start = read_vint(&mut reader);
        assert_eq!(off0_start, 0);
        let off0_len = read_vint(&mut reader);
        assert_eq!(off0_len, 5);

        // Position 3: delta = (3 - 0) << 1 = 6
        let pos1 = read_vint(&mut reader);
        assert_eq!(pos1, 6);
        // Offset for position 3: start_offset delta = 18 - 0 = 18, length = 5
        let off1_start_delta = read_vint(&mut reader);
        assert_eq!(off1_start_delta, 18);
        let off1_len = read_vint(&mut reader);
        assert_eq!(off1_len, 5);
    }

    #[test]
    fn test_offsets_across_documents() {
        let mut term_pool = new_term_pool();
        let mut th = TermsHash::new();
        let mut field = FreqProxTermsWriterPerField::new(
            "body".to_string(),
            IndexOptions::DocsAndFreqsAndPositionsAndOffsets,
        );

        // Doc 0: "hello" at pos 0, offsets [0, 5)
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                0,
                TermPosition::new(0, 0, 5u16),
            )
            .unwrap();
        // Doc 1: "hello" at pos 0, offsets [0, 5) — offsets reset per new doc
        field
            .add_at(
                &mut term_pool,
                &mut th,
                b"hello",
                1,
                TermPosition::new(0, 0, 5),
            )
            .unwrap();

        let hello_id = field.base.bytes_hash.find(&term_pool, b"hello") as usize;

        // Read prox stream — doc 0 prox data should be there
        let (start, end) = field.get_stream_range(&th.int_pool, hello_id, 1);
        let mut reader = ByteSliceReader::new(&th.byte_pool, start, end);

        // Doc 0, position 0
        let pos0 = read_vint(&mut reader);
        assert_eq!(pos0, 0);
        let off_start = read_vint(&mut reader);
        assert_eq!(off_start, 0);
        let off_len = read_vint(&mut reader);
        assert_eq!(off_len, 5);

        // Doc 1, position 0 — offset reset to 0 for new doc
        let pos1 = read_vint(&mut reader);
        assert_eq!(pos1, 0);
        let off1_start = read_vint(&mut reader);
        assert_eq!(off1_start, 0);
        let off1_len = read_vint(&mut reader);
        assert_eq!(off1_len, 5);
    }

    #[test]
    fn test_buffered_postings_enum_returns_offsets() {
        let mut decoded = DecodedPostings::new();
        decoded.docs.push(DecodedDoc {
            doc_id: 0,
            freq: 2,
            pos_start: 0,
        });
        decoded.positions.extend_from_slice(&[0, 5]);
        decoded.offsets.extend_from_slice(&[
            TermOffset {
                start: 0,
                length: 5,
            },
            TermOffset {
                start: 6,
                length: 5,
            },
        ]);

        let mut pe = BufferedPostingsEnum::new(decoded, true);
        assert_eq!(pe.next_doc().unwrap(), 0);
        assert_eq!(pe.freq(), 2);

        assert_eq!(pe.next_position().unwrap(), 0);
        assert_eq!(
            pe.offset(),
            Some(TermOffset {
                start: 0,
                length: 5
            })
        );

        assert_eq!(pe.next_position().unwrap(), 5);
        assert_eq!(
            pe.offset(),
            Some(TermOffset {
                start: 6,
                length: 5
            })
        );
    }

    #[test]
    fn test_buffered_postings_enum_no_offsets() {
        let mut decoded = DecodedPostings::new();
        decoded.docs.push(DecodedDoc {
            doc_id: 0,
            freq: 1,
            pos_start: 0,
        });
        decoded.positions.push(0);
        // No offsets added

        let mut pe = BufferedPostingsEnum::new(decoded, true);
        assert_eq!(pe.next_doc().unwrap(), 0);
        assert_eq!(pe.next_position().unwrap(), 0);
        assert_none!(pe.offset());
    }
}