1use super::simd;
13use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
14use std::io::{self, Read, Write};
15
16pub const HORIZONTAL_BP128_BLOCK_SIZE: usize = 128;
18
19pub const SMALL_BLOCK_SIZE: usize = 32;
21
22pub const SMALL_BLOCK_THRESHOLD: usize = 256;
24
25pub fn pack_block(
27 values: &[u32; HORIZONTAL_BP128_BLOCK_SIZE],
28 bit_width: u8,
29 output: &mut Vec<u8>,
30) {
31 if bit_width == 0 {
32 return;
33 }
34
35 let bytes_needed = (HORIZONTAL_BP128_BLOCK_SIZE * bit_width as usize).div_ceil(8);
36 let start = output.len();
37 output.resize(start + bytes_needed, 0);
38
39 let mut bit_pos = 0usize;
40 for &value in values {
41 let byte_idx = start + bit_pos / 8;
42 let bit_offset = bit_pos % 8;
43
44 let mut remaining_bits = bit_width as usize;
46 let mut val = value;
47 let mut current_byte_idx = byte_idx;
48 let mut current_bit_offset = bit_offset;
49
50 while remaining_bits > 0 {
51 let bits_in_byte = (8 - current_bit_offset).min(remaining_bits);
52 let mask = ((1u32 << bits_in_byte) - 1) as u8;
53 output[current_byte_idx] |= ((val as u8) & mask) << current_bit_offset;
54 val >>= bits_in_byte;
55 remaining_bits -= bits_in_byte;
56 current_byte_idx += 1;
57 current_bit_offset = 0;
58 }
59
60 bit_pos += bit_width as usize;
61 }
62}
63
64pub fn unpack_block(input: &[u8], bit_width: u8, output: &mut [u32; HORIZONTAL_BP128_BLOCK_SIZE]) {
67 if bit_width == 0 {
68 output.fill(0);
69 return;
70 }
71
72 match bit_width {
74 8 => simd::unpack_8bit(input, output, HORIZONTAL_BP128_BLOCK_SIZE),
75 16 => simd::unpack_16bit(input, output, HORIZONTAL_BP128_BLOCK_SIZE),
76 32 => simd::unpack_32bit(input, output, HORIZONTAL_BP128_BLOCK_SIZE),
77 _ => unpack_block_generic(input, bit_width, output),
78 }
79}
80
81#[inline]
84fn unpack_block_generic(
85 input: &[u8],
86 bit_width: u8,
87 output: &mut [u32; HORIZONTAL_BP128_BLOCK_SIZE],
88) {
89 let mask = (1u64 << bit_width) - 1;
90 let bit_width_usize = bit_width as usize;
91 let mut bit_pos = 0usize;
92
93 let input_ptr = input.as_ptr();
97
98 for out in output.iter_mut() {
99 let byte_idx = bit_pos >> 3; let bit_offset = bit_pos & 7; let word = unsafe { (input_ptr.add(byte_idx) as *const u64).read_unaligned() };
105
106 *out = ((word >> bit_offset) & mask) as u32;
107 bit_pos += bit_width_usize;
108 }
109}
110
111#[inline]
114pub fn unpack_block_n(input: &[u8], bit_width: u8, output: &mut [u32], n: usize) {
115 if bit_width == 0 {
116 output[..n].fill(0);
117 return;
118 }
119
120 let mask = (1u64 << bit_width) - 1;
121 let bit_width_usize = bit_width as usize;
122 let mut bit_pos = 0usize;
123 let input_ptr = input.as_ptr();
124
125 for out in output[..n].iter_mut() {
126 let byte_idx = bit_pos >> 3;
127 let bit_offset = bit_pos & 7;
128
129 let word = unsafe { (input_ptr.add(byte_idx) as *const u64).read_unaligned() };
131
132 *out = ((word >> bit_offset) & mask) as u32;
133 bit_pos += bit_width_usize;
134 }
135}
136
137#[inline]
140pub fn binary_search_block(block: &[u32], target: u32) -> usize {
141 match block.binary_search(&target) {
142 Ok(idx) => idx,
143 Err(idx) => idx,
144 }
145}
146
147#[allow(dead_code)]
151#[inline]
152fn prefix_sum_8(deltas: &mut [u32; 8]) {
153 for i in (1..8).rev() {
155 deltas[i] = deltas[i].wrapping_add(deltas[i - 1]);
156 }
157 for i in (2..8).rev() {
159 deltas[i] = deltas[i].wrapping_add(deltas[i - 2]);
160 }
161 for i in (4..8).rev() {
163 deltas[i] = deltas[i].wrapping_add(deltas[i - 4]);
164 }
165}
166
167#[derive(Debug, Clone)]
169pub struct HorizontalBP128Block {
170 pub doc_deltas: Vec<u8>,
172 pub doc_bit_width: u8,
174 pub term_freqs: Vec<u8>,
176 pub tf_bit_width: u8,
178 pub first_doc_id: u32,
180 pub last_doc_id: u32,
182 pub num_docs: u16,
184 pub max_tf: u32,
186 pub max_block_score: f32,
189}
190
191impl HorizontalBP128Block {
192 pub fn serialize<W: Write>(&self, writer: &mut W) -> io::Result<()> {
194 writer.write_u32::<LittleEndian>(self.first_doc_id)?;
195 writer.write_u32::<LittleEndian>(self.last_doc_id)?;
196 writer.write_u16::<LittleEndian>(self.num_docs)?;
197 writer.write_u8(self.doc_bit_width)?;
198 writer.write_u8(self.tf_bit_width)?;
199 writer.write_u32::<LittleEndian>(self.max_tf)?;
200 writer.write_f32::<LittleEndian>(self.max_block_score)?;
201
202 writer.write_u16::<LittleEndian>(self.doc_deltas.len() as u16)?;
204 writer.write_all(&self.doc_deltas)?;
205
206 writer.write_u16::<LittleEndian>(self.term_freqs.len() as u16)?;
208 writer.write_all(&self.term_freqs)?;
209
210 Ok(())
211 }
212
213 pub fn deserialize<R: Read>(reader: &mut R) -> io::Result<Self> {
215 let first_doc_id = reader.read_u32::<LittleEndian>()?;
216 let last_doc_id = reader.read_u32::<LittleEndian>()?;
217 let num_docs = reader.read_u16::<LittleEndian>()?;
218 let doc_bit_width = reader.read_u8()?;
219 let tf_bit_width = reader.read_u8()?;
220 let max_tf = reader.read_u32::<LittleEndian>()?;
221 let max_block_score = reader.read_f32::<LittleEndian>()?;
222
223 let doc_deltas_len = reader.read_u16::<LittleEndian>()? as usize;
224 let mut doc_deltas = vec![0u8; doc_deltas_len];
225 reader.read_exact(&mut doc_deltas)?;
226
227 let term_freqs_len = reader.read_u16::<LittleEndian>()? as usize;
228 let mut term_freqs = vec![0u8; term_freqs_len];
229 reader.read_exact(&mut term_freqs)?;
230
231 Ok(Self {
232 doc_deltas,
233 doc_bit_width,
234 term_freqs,
235 tf_bit_width,
236 first_doc_id,
237 last_doc_id,
238 num_docs,
239 max_tf,
240 max_block_score,
241 })
242 }
243
244 pub fn decode_doc_ids(&self) -> Vec<u32> {
246 if self.num_docs == 0 {
247 return Vec::new();
248 }
249
250 let count = self.num_docs as usize;
251 let mut deltas = [0u32; HORIZONTAL_BP128_BLOCK_SIZE];
252 unpack_block(&self.doc_deltas, self.doc_bit_width, &mut deltas);
253
254 let mut output = [0u32; HORIZONTAL_BP128_BLOCK_SIZE];
255 simd::delta_decode(&mut output, &deltas, self.first_doc_id, count);
256
257 output[..count].to_vec()
258 }
259
260 pub fn decode_term_freqs(&self) -> Vec<u32> {
262 if self.num_docs == 0 {
263 return Vec::new();
264 }
265
266 let mut tfs = [0u32; HORIZONTAL_BP128_BLOCK_SIZE];
267 unpack_block(&self.term_freqs, self.tf_bit_width, &mut tfs);
268
269 tfs[..self.num_docs as usize]
271 .iter()
272 .map(|&tf| tf + 1)
273 .collect()
274 }
275}
276
277#[derive(Debug, Clone)]
279pub struct HorizontalBP128PostingList {
280 pub blocks: Vec<HorizontalBP128Block>,
282 pub doc_count: u32,
284 pub max_score: f32,
286}
287
288impl HorizontalBP128PostingList {
289 pub fn from_postings(doc_ids: &[u32], term_freqs: &[u32], idf: f32) -> Self {
291 assert_eq!(doc_ids.len(), term_freqs.len());
292
293 if doc_ids.is_empty() {
294 return Self {
295 blocks: Vec::new(),
296 doc_count: 0,
297 max_score: 0.0,
298 };
299 }
300
301 let mut blocks = Vec::new();
302 let mut max_score = 0.0f32;
303 let mut i = 0;
304
305 while i < doc_ids.len() {
306 let block_end = (i + HORIZONTAL_BP128_BLOCK_SIZE).min(doc_ids.len());
307 let block_docs = &doc_ids[i..block_end];
308 let block_tfs = &term_freqs[i..block_end];
309
310 let block = Self::create_block(block_docs, block_tfs, idf);
311 max_score = max_score.max(block.max_block_score);
312 blocks.push(block);
313
314 i = block_end;
315 }
316
317 Self {
318 blocks,
319 doc_count: doc_ids.len() as u32,
320 max_score,
321 }
322 }
323
324 const K1: f32 = 1.2;
326 const B: f32 = 0.75;
327
328 #[inline]
331 pub fn compute_bm25f_upper_bound(max_tf: u32, idf: f32, field_boost: f32) -> f32 {
332 let tf = max_tf as f32;
333 let min_length_norm = 1.0 - Self::B;
336 let tf_norm =
337 (tf * field_boost * (Self::K1 + 1.0)) / (tf * field_boost + Self::K1 * min_length_norm);
338 idf * tf_norm
339 }
340
341 fn create_block(doc_ids: &[u32], term_freqs: &[u32], idf: f32) -> HorizontalBP128Block {
342 let num_docs = doc_ids.len();
343 let first_doc_id = doc_ids[0];
344 let last_doc_id = *doc_ids.last().unwrap();
345
346 let mut deltas = [0u32; HORIZONTAL_BP128_BLOCK_SIZE];
348 let mut max_delta = 0u32;
349 for j in 1..num_docs {
350 let delta = doc_ids[j] - doc_ids[j - 1] - 1;
351 deltas[j - 1] = delta;
352 max_delta = max_delta.max(delta);
353 }
354
355 let mut tfs = [0u32; HORIZONTAL_BP128_BLOCK_SIZE];
357 let mut max_tf = 0u32;
358
359 for (j, &tf) in term_freqs.iter().enumerate() {
360 tfs[j] = tf - 1; max_tf = max_tf.max(tf);
362 }
363
364 let max_block_score = Self::compute_bm25f_upper_bound(max_tf, idf, 1.0);
367
368 let doc_bit_width = simd::bits_needed(max_delta);
369 let tf_bit_width = simd::bits_needed(max_tf.saturating_sub(1)); let mut doc_deltas = Vec::new();
372 pack_block(&deltas, doc_bit_width, &mut doc_deltas);
373
374 let mut term_freqs_packed = Vec::new();
375 pack_block(&tfs, tf_bit_width, &mut term_freqs_packed);
376
377 HorizontalBP128Block {
378 doc_deltas,
379 doc_bit_width,
380 term_freqs: term_freqs_packed,
381 tf_bit_width,
382 first_doc_id,
383 last_doc_id,
384 num_docs: num_docs as u16,
385 max_tf,
386 max_block_score,
387 }
388 }
389
390 pub fn serialize<W: Write>(&self, writer: &mut W) -> io::Result<()> {
392 writer.write_u32::<LittleEndian>(self.doc_count)?;
393 writer.write_f32::<LittleEndian>(self.max_score)?;
394 writer.write_u32::<LittleEndian>(self.blocks.len() as u32)?;
395
396 for block in &self.blocks {
397 block.serialize(writer)?;
398 }
399
400 Ok(())
401 }
402
403 pub fn deserialize<R: Read>(reader: &mut R) -> io::Result<Self> {
405 let doc_count = reader.read_u32::<LittleEndian>()?;
406 let max_score = reader.read_f32::<LittleEndian>()?;
407 let num_blocks = reader.read_u32::<LittleEndian>()? as usize;
408
409 let mut blocks = Vec::with_capacity(num_blocks);
410 for _ in 0..num_blocks {
411 blocks.push(HorizontalBP128Block::deserialize(reader)?);
412 }
413
414 Ok(Self {
415 blocks,
416 doc_count,
417 max_score,
418 })
419 }
420
421 pub fn iterator(&self) -> HorizontalBP128Iterator<'_> {
423 HorizontalBP128Iterator::new(self)
424 }
425}
426
427pub struct HorizontalBP128Iterator<'a> {
429 posting_list: &'a HorizontalBP128PostingList,
430 current_block: usize,
432 block_doc_ids: Vec<u32>,
434 block_term_freqs: Vec<u32>,
436 pos_in_block: usize,
438 exhausted: bool,
440}
441
442impl<'a> HorizontalBP128Iterator<'a> {
443 pub fn new(posting_list: &'a HorizontalBP128PostingList) -> Self {
444 let mut iter = Self {
445 posting_list,
446 current_block: 0,
447 block_doc_ids: Vec::new(),
448 block_term_freqs: Vec::new(),
449 pos_in_block: 0,
450 exhausted: posting_list.blocks.is_empty(),
451 };
452
453 if !iter.exhausted {
454 iter.decode_current_block();
455 }
456
457 iter
458 }
459
460 fn decode_current_block(&mut self) {
461 let block = &self.posting_list.blocks[self.current_block];
462 self.block_doc_ids = block.decode_doc_ids();
463 self.block_term_freqs = block.decode_term_freqs();
464 self.pos_in_block = 0;
465 }
466
467 pub fn doc(&self) -> u32 {
469 if self.exhausted {
470 u32::MAX
471 } else {
472 self.block_doc_ids[self.pos_in_block]
473 }
474 }
475
476 pub fn term_freq(&self) -> u32 {
478 if self.exhausted {
479 0
480 } else {
481 self.block_term_freqs[self.pos_in_block]
482 }
483 }
484
485 pub fn advance(&mut self) -> u32 {
487 if self.exhausted {
488 return u32::MAX;
489 }
490
491 self.pos_in_block += 1;
492
493 if self.pos_in_block >= self.block_doc_ids.len() {
494 self.current_block += 1;
495 if self.current_block >= self.posting_list.blocks.len() {
496 self.exhausted = true;
497 return u32::MAX;
498 }
499 self.decode_current_block();
500 }
501
502 self.doc()
503 }
504
505 pub fn seek(&mut self, target: u32) -> u32 {
507 if self.exhausted {
508 return u32::MAX;
509 }
510
511 let block_idx = self.posting_list.blocks[self.current_block..].binary_search_by(|block| {
513 if block.last_doc_id < target {
514 std::cmp::Ordering::Less
515 } else if block.first_doc_id > target {
516 std::cmp::Ordering::Greater
517 } else {
518 std::cmp::Ordering::Equal
519 }
520 });
521
522 let target_block = match block_idx {
523 Ok(idx) => self.current_block + idx,
524 Err(idx) => {
525 if self.current_block + idx >= self.posting_list.blocks.len() {
526 self.exhausted = true;
527 return u32::MAX;
528 }
529 self.current_block + idx
530 }
531 };
532
533 if target_block != self.current_block {
535 self.current_block = target_block;
536 self.decode_current_block();
537 } else if self.block_doc_ids.is_empty() {
538 self.decode_current_block();
539 }
540
541 let pos = binary_search_block(&self.block_doc_ids[self.pos_in_block..], target);
543 self.pos_in_block += pos;
544
545 if self.pos_in_block >= self.block_doc_ids.len() {
546 self.current_block += 1;
548 if self.current_block >= self.posting_list.blocks.len() {
549 self.exhausted = true;
550 return u32::MAX;
551 }
552 self.decode_current_block();
553 }
554
555 self.doc()
556 }
557
558 pub fn max_remaining_score(&self) -> f32 {
560 if self.exhausted {
561 return 0.0;
562 }
563
564 self.posting_list.blocks[self.current_block..]
565 .iter()
566 .map(|b| b.max_block_score)
567 .fold(0.0f32, |a, b| a.max(b))
568 }
569
570 pub fn skip_to_block_with_doc(&mut self, target: u32) -> Option<(u32, f32)> {
572 while self.current_block < self.posting_list.blocks.len() {
573 let block = &self.posting_list.blocks[self.current_block];
574 if block.last_doc_id >= target {
575 return Some((block.first_doc_id, block.max_block_score));
576 }
577 self.current_block += 1;
578 }
579 self.exhausted = true;
580 None
581 }
582
583 pub fn current_block_max_score(&self) -> f32 {
585 if self.exhausted {
586 0.0
587 } else {
588 self.posting_list.blocks[self.current_block].max_block_score
589 }
590 }
591
592 pub fn current_block_max_tf(&self) -> u32 {
594 if self.exhausted {
595 0
596 } else {
597 self.posting_list.blocks[self.current_block].max_tf
598 }
599 }
600}
601
602#[cfg(test)]
603mod tests {
604 use super::*;
605
606 #[test]
607 fn test_bits_needed() {
608 assert_eq!(simd::bits_needed(0), 0);
609 assert_eq!(simd::bits_needed(1), 1);
610 assert_eq!(simd::bits_needed(2), 2);
611 assert_eq!(simd::bits_needed(3), 2);
612 assert_eq!(simd::bits_needed(255), 8);
613 assert_eq!(simd::bits_needed(256), 9);
614 }
615
616 #[test]
617 fn test_pack_unpack() {
618 let mut values = [0u32; HORIZONTAL_BP128_BLOCK_SIZE];
619 for (i, value) in values.iter_mut().enumerate() {
620 *value = (i * 3) as u32;
621 }
622
623 let max_val = values.iter().max().copied().unwrap();
624 let bit_width = simd::bits_needed(max_val);
625
626 let mut packed = Vec::new();
627 pack_block(&values, bit_width, &mut packed);
628
629 let mut unpacked = [0u32; HORIZONTAL_BP128_BLOCK_SIZE];
630 unpack_block(&packed, bit_width, &mut unpacked);
631
632 assert_eq!(values, unpacked);
633 }
634
635 #[test]
636 fn test_bitpacked_posting_list() {
637 let doc_ids: Vec<u32> = (0..200).map(|i| i * 2).collect();
638 let term_freqs: Vec<u32> = (0..200).map(|i| (i % 10) + 1).collect();
639
640 let posting_list = HorizontalBP128PostingList::from_postings(&doc_ids, &term_freqs, 1.0);
641
642 assert_eq!(posting_list.doc_count, 200);
643 assert_eq!(posting_list.blocks.len(), 2); let mut iter = posting_list.iterator();
647 for (i, &expected_doc) in doc_ids.iter().enumerate() {
648 assert_eq!(iter.doc(), expected_doc, "Mismatch at position {}", i);
649 assert_eq!(iter.term_freq(), term_freqs[i]);
650 if i < doc_ids.len() - 1 {
651 iter.advance();
652 }
653 }
654 }
655
656 #[test]
657 fn test_bitpacked_seek() {
658 let doc_ids: Vec<u32> = vec![10, 20, 30, 100, 200, 300, 1000, 2000];
659 let term_freqs: Vec<u32> = vec![1, 2, 3, 4, 5, 6, 7, 8];
660
661 let posting_list = HorizontalBP128PostingList::from_postings(&doc_ids, &term_freqs, 1.0);
662 let mut iter = posting_list.iterator();
663
664 assert_eq!(iter.seek(25), 30);
665 assert_eq!(iter.seek(100), 100);
666 assert_eq!(iter.seek(500), 1000);
667 assert_eq!(iter.seek(3000), u32::MAX);
668 }
669
670 #[test]
671 fn test_serialization() {
672 let doc_ids: Vec<u32> = (0..50).map(|i| i * 3).collect();
673 let term_freqs: Vec<u32> = (0..50).map(|_| 1).collect();
674
675 let posting_list = HorizontalBP128PostingList::from_postings(&doc_ids, &term_freqs, 1.5);
676
677 let mut buffer = Vec::new();
678 posting_list.serialize(&mut buffer).unwrap();
679
680 let restored = HorizontalBP128PostingList::deserialize(&mut &buffer[..]).unwrap();
681
682 assert_eq!(restored.doc_count, posting_list.doc_count);
683 assert_eq!(restored.blocks.len(), posting_list.blocks.len());
684
685 let mut iter1 = posting_list.iterator();
687 let mut iter2 = restored.iterator();
688
689 while iter1.doc() != u32::MAX {
690 assert_eq!(iter1.doc(), iter2.doc());
691 assert_eq!(iter1.term_freq(), iter2.term_freq());
692 iter1.advance();
693 iter2.advance();
694 }
695 }
696
697 #[test]
698 fn test_hillis_steele_prefix_sum() {
699 let mut deltas = [1u32, 2, 3, 4, 5, 6, 7, 8];
701 prefix_sum_8(&mut deltas);
702 assert_eq!(deltas, [1, 3, 6, 10, 15, 21, 28, 36]);
704
705 let deltas2 = [0u32; 16]; let mut output2 = [0u32; 16];
708 simd::delta_decode(&mut output2, &deltas2, 100, 8);
709 assert_eq!(&output2[..8], &[100, 101, 102, 103, 104, 105, 106, 107]);
711
712 let deltas3 = [1u32, 0, 2, 0, 4, 0, 0, 0];
715 let mut output3 = [0u32; 8];
716 simd::delta_decode(&mut output3, &deltas3, 10, 8);
717 assert_eq!(&output3[..8], &[10, 12, 13, 16, 17, 22, 23, 24]);
719 }
720
721 #[test]
722 fn test_delta_decode_large_block() {
723 let doc_ids: Vec<u32> = (0..128).map(|i| i * 5 + 100).collect();
725 let term_freqs: Vec<u32> = vec![1; 128];
726
727 let posting_list = HorizontalBP128PostingList::from_postings(&doc_ids, &term_freqs, 1.0);
728 let decoded = posting_list.blocks[0].decode_doc_ids();
729
730 assert_eq!(decoded.len(), 128);
731 for (i, (&expected, &actual)) in doc_ids.iter().zip(decoded.iter()).enumerate() {
732 assert_eq!(expected, actual, "Mismatch at position {}", i);
733 }
734 }
735}