1use crate::structures::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 let mut output = vec![0u32; self.num_docs as usize];
247 self.decode_doc_ids_into(&mut output);
248 output
249 }
250
251 #[inline]
253 pub fn decode_doc_ids_into(&self, output: &mut [u32]) -> usize {
254 let count = self.num_docs as usize;
255 if count == 0 {
256 return 0;
257 }
258
259 simd::unpack_delta_decode(
261 &self.doc_deltas,
262 self.doc_bit_width,
263 output,
264 self.first_doc_id,
265 count,
266 );
267
268 count
269 }
270
271 pub fn decode_term_freqs(&self) -> Vec<u32> {
273 let mut output = vec![0u32; self.num_docs as usize];
274 self.decode_term_freqs_into(&mut output);
275 output
276 }
277
278 #[inline]
280 pub fn decode_term_freqs_into(&self, output: &mut [u32]) -> usize {
281 let count = self.num_docs as usize;
282 if count == 0 {
283 return 0;
284 }
285
286 unpack_block_n(&self.term_freqs, self.tf_bit_width, output, count);
288
289 simd::add_one(output, count);
291
292 count
293 }
294}
295
296#[derive(Debug, Clone)]
298pub struct HorizontalBP128PostingList {
299 pub blocks: Vec<HorizontalBP128Block>,
301 pub doc_count: u32,
303 pub max_score: f32,
305}
306
307impl HorizontalBP128PostingList {
308 pub fn from_postings(doc_ids: &[u32], term_freqs: &[u32], idf: f32) -> Self {
310 assert_eq!(doc_ids.len(), term_freqs.len());
311
312 if doc_ids.is_empty() {
313 return Self {
314 blocks: Vec::new(),
315 doc_count: 0,
316 max_score: 0.0,
317 };
318 }
319
320 let mut blocks = Vec::new();
321 let mut max_score = 0.0f32;
322 let mut i = 0;
323
324 while i < doc_ids.len() {
325 let block_end = (i + HORIZONTAL_BP128_BLOCK_SIZE).min(doc_ids.len());
326 let block_docs = &doc_ids[i..block_end];
327 let block_tfs = &term_freqs[i..block_end];
328
329 let block = Self::create_block(block_docs, block_tfs, idf);
330 max_score = max_score.max(block.max_block_score);
331 blocks.push(block);
332
333 i = block_end;
334 }
335
336 Self {
337 blocks,
338 doc_count: doc_ids.len() as u32,
339 max_score,
340 }
341 }
342
343 fn create_block(doc_ids: &[u32], term_freqs: &[u32], idf: f32) -> HorizontalBP128Block {
344 use crate::query::bm25_upper_bound;
345
346 let num_docs = doc_ids.len();
347 let first_doc_id = doc_ids[0];
348 let last_doc_id = *doc_ids.last().unwrap();
349
350 let mut deltas = [0u32; HORIZONTAL_BP128_BLOCK_SIZE];
352 let mut max_delta = 0u32;
353 for j in 1..num_docs {
354 let delta = doc_ids[j] - doc_ids[j - 1] - 1;
355 deltas[j - 1] = delta;
356 max_delta = max_delta.max(delta);
357 }
358
359 let mut tfs = [0u32; HORIZONTAL_BP128_BLOCK_SIZE];
361 let mut max_tf = 0u32;
362
363 for (j, &tf) in term_freqs.iter().enumerate() {
364 tfs[j] = tf - 1; max_tf = max_tf.max(tf);
366 }
367
368 let max_block_score = bm25_upper_bound(max_tf as f32, idf);
370
371 let doc_bit_width = simd::bits_needed(max_delta);
372 let tf_bit_width = simd::bits_needed(max_tf.saturating_sub(1)); let mut doc_deltas = Vec::new();
375 pack_block(&deltas, doc_bit_width, &mut doc_deltas);
376
377 let mut term_freqs_packed = Vec::new();
378 pack_block(&tfs, tf_bit_width, &mut term_freqs_packed);
379
380 HorizontalBP128Block {
381 doc_deltas,
382 doc_bit_width,
383 term_freqs: term_freqs_packed,
384 tf_bit_width,
385 first_doc_id,
386 last_doc_id,
387 num_docs: num_docs as u16,
388 max_tf,
389 max_block_score,
390 }
391 }
392
393 pub fn serialize<W: Write>(&self, writer: &mut W) -> io::Result<()> {
395 writer.write_u32::<LittleEndian>(self.doc_count)?;
396 writer.write_f32::<LittleEndian>(self.max_score)?;
397 writer.write_u32::<LittleEndian>(self.blocks.len() as u32)?;
398
399 for block in &self.blocks {
400 block.serialize(writer)?;
401 }
402
403 Ok(())
404 }
405
406 pub fn deserialize<R: Read>(reader: &mut R) -> io::Result<Self> {
408 let doc_count = reader.read_u32::<LittleEndian>()?;
409 let max_score = reader.read_f32::<LittleEndian>()?;
410 let num_blocks = reader.read_u32::<LittleEndian>()? as usize;
411
412 let mut blocks = Vec::with_capacity(num_blocks);
413 for _ in 0..num_blocks {
414 blocks.push(HorizontalBP128Block::deserialize(reader)?);
415 }
416
417 Ok(Self {
418 blocks,
419 doc_count,
420 max_score,
421 })
422 }
423
424 pub fn iterator(&self) -> HorizontalBP128Iterator<'_> {
426 HorizontalBP128Iterator::new(self)
427 }
428}
429
430pub struct HorizontalBP128Iterator<'a> {
432 posting_list: &'a HorizontalBP128PostingList,
433 current_block: usize,
435 current_block_len: usize,
437 block_doc_ids: Vec<u32>,
439 block_term_freqs: Vec<u32>,
441 pos_in_block: usize,
443 exhausted: bool,
445}
446
447impl<'a> HorizontalBP128Iterator<'a> {
448 pub fn new(posting_list: &'a HorizontalBP128PostingList) -> Self {
449 let mut iter = Self {
451 posting_list,
452 current_block: 0,
453 current_block_len: 0,
454 block_doc_ids: vec![0u32; HORIZONTAL_BP128_BLOCK_SIZE],
455 block_term_freqs: vec![0u32; HORIZONTAL_BP128_BLOCK_SIZE],
456 pos_in_block: 0,
457 exhausted: posting_list.blocks.is_empty(),
458 };
459
460 if !iter.exhausted {
461 iter.decode_current_block();
462 }
463
464 iter
465 }
466
467 #[inline]
468 fn decode_current_block(&mut self) {
469 let block = &self.posting_list.blocks[self.current_block];
470 self.current_block_len = block.decode_doc_ids_into(&mut self.block_doc_ids);
472 block.decode_term_freqs_into(&mut self.block_term_freqs);
473 self.pos_in_block = 0;
474 }
475
476 #[inline]
478 pub fn doc(&self) -> u32 {
479 if self.exhausted {
480 u32::MAX
481 } else {
482 self.block_doc_ids[self.pos_in_block]
483 }
484 }
485
486 #[inline]
488 pub fn term_freq(&self) -> u32 {
489 if self.exhausted {
490 0
491 } else {
492 self.block_term_freqs[self.pos_in_block]
493 }
494 }
495
496 #[inline]
498 pub fn advance(&mut self) -> u32 {
499 if self.exhausted {
500 return u32::MAX;
501 }
502
503 self.pos_in_block += 1;
504
505 if self.pos_in_block >= self.current_block_len {
506 self.current_block += 1;
507 if self.current_block >= self.posting_list.blocks.len() {
508 self.exhausted = true;
509 return u32::MAX;
510 }
511 self.decode_current_block();
512 }
513
514 self.doc()
515 }
516
517 pub fn seek(&mut self, target: u32) -> u32 {
519 if self.exhausted {
520 return u32::MAX;
521 }
522
523 let block_idx = self.posting_list.blocks[self.current_block..].binary_search_by(|block| {
525 if block.last_doc_id < target {
526 std::cmp::Ordering::Less
527 } else if block.first_doc_id > target {
528 std::cmp::Ordering::Greater
529 } else {
530 std::cmp::Ordering::Equal
531 }
532 });
533
534 let target_block = match block_idx {
535 Ok(idx) => self.current_block + idx,
536 Err(idx) => {
537 if self.current_block + idx >= self.posting_list.blocks.len() {
538 self.exhausted = true;
539 return u32::MAX;
540 }
541 self.current_block + idx
542 }
543 };
544
545 if target_block != self.current_block {
547 self.current_block = target_block;
548 self.decode_current_block();
549 } else if self.current_block_len == 0 {
550 self.decode_current_block();
551 }
552
553 let pos = binary_search_block(
555 &self.block_doc_ids[self.pos_in_block..self.current_block_len],
556 target,
557 );
558 self.pos_in_block += pos;
559
560 if self.pos_in_block >= self.current_block_len {
561 self.current_block += 1;
563 if self.current_block >= self.posting_list.blocks.len() {
564 self.exhausted = true;
565 return u32::MAX;
566 }
567 self.decode_current_block();
568 }
569
570 self.doc()
571 }
572
573 pub fn max_remaining_score(&self) -> f32 {
575 if self.exhausted {
576 return 0.0;
577 }
578
579 self.posting_list.blocks[self.current_block..]
580 .iter()
581 .map(|b| b.max_block_score)
582 .fold(0.0f32, |a, b| a.max(b))
583 }
584
585 pub fn skip_to_block_with_doc(&mut self, target: u32) -> Option<(u32, f32)> {
587 while self.current_block < self.posting_list.blocks.len() {
588 let block = &self.posting_list.blocks[self.current_block];
589 if block.last_doc_id >= target {
590 return Some((block.first_doc_id, block.max_block_score));
591 }
592 self.current_block += 1;
593 }
594 self.exhausted = true;
595 None
596 }
597
598 pub fn current_block_max_score(&self) -> f32 {
600 if self.exhausted {
601 0.0
602 } else {
603 self.posting_list.blocks[self.current_block].max_block_score
604 }
605 }
606
607 pub fn current_block_max_tf(&self) -> u32 {
609 if self.exhausted {
610 0
611 } else {
612 self.posting_list.blocks[self.current_block].max_tf
613 }
614 }
615}
616
617#[cfg(test)]
618mod tests {
619 use super::*;
620
621 #[test]
622 fn test_bits_needed() {
623 assert_eq!(simd::bits_needed(0), 0);
624 assert_eq!(simd::bits_needed(1), 1);
625 assert_eq!(simd::bits_needed(2), 2);
626 assert_eq!(simd::bits_needed(3), 2);
627 assert_eq!(simd::bits_needed(255), 8);
628 assert_eq!(simd::bits_needed(256), 9);
629 }
630
631 #[test]
632 fn test_pack_unpack() {
633 let mut values = [0u32; HORIZONTAL_BP128_BLOCK_SIZE];
634 for (i, value) in values.iter_mut().enumerate() {
635 *value = (i * 3) as u32;
636 }
637
638 let max_val = values.iter().max().copied().unwrap();
639 let bit_width = simd::bits_needed(max_val);
640
641 let mut packed = Vec::new();
642 pack_block(&values, bit_width, &mut packed);
643
644 let mut unpacked = [0u32; HORIZONTAL_BP128_BLOCK_SIZE];
645 unpack_block(&packed, bit_width, &mut unpacked);
646
647 assert_eq!(values, unpacked);
648 }
649
650 #[test]
651 fn test_bitpacked_posting_list() {
652 let doc_ids: Vec<u32> = (0..200).map(|i| i * 2).collect();
653 let term_freqs: Vec<u32> = (0..200).map(|i| (i % 10) + 1).collect();
654
655 let posting_list = HorizontalBP128PostingList::from_postings(&doc_ids, &term_freqs, 1.0);
656
657 assert_eq!(posting_list.doc_count, 200);
658 assert_eq!(posting_list.blocks.len(), 2); let mut iter = posting_list.iterator();
662 for (i, &expected_doc) in doc_ids.iter().enumerate() {
663 assert_eq!(iter.doc(), expected_doc, "Mismatch at position {}", i);
664 assert_eq!(iter.term_freq(), term_freqs[i]);
665 if i < doc_ids.len() - 1 {
666 iter.advance();
667 }
668 }
669 }
670
671 #[test]
672 fn test_bitpacked_seek() {
673 let doc_ids: Vec<u32> = vec![10, 20, 30, 100, 200, 300, 1000, 2000];
674 let term_freqs: Vec<u32> = vec![1, 2, 3, 4, 5, 6, 7, 8];
675
676 let posting_list = HorizontalBP128PostingList::from_postings(&doc_ids, &term_freqs, 1.0);
677 let mut iter = posting_list.iterator();
678
679 assert_eq!(iter.seek(25), 30);
680 assert_eq!(iter.seek(100), 100);
681 assert_eq!(iter.seek(500), 1000);
682 assert_eq!(iter.seek(3000), u32::MAX);
683 }
684
685 #[test]
686 fn test_serialization() {
687 let doc_ids: Vec<u32> = (0..50).map(|i| i * 3).collect();
688 let term_freqs: Vec<u32> = (0..50).map(|_| 1).collect();
689
690 let posting_list = HorizontalBP128PostingList::from_postings(&doc_ids, &term_freqs, 1.5);
691
692 let mut buffer = Vec::new();
693 posting_list.serialize(&mut buffer).unwrap();
694
695 let restored = HorizontalBP128PostingList::deserialize(&mut &buffer[..]).unwrap();
696
697 assert_eq!(restored.doc_count, posting_list.doc_count);
698 assert_eq!(restored.blocks.len(), posting_list.blocks.len());
699
700 let mut iter1 = posting_list.iterator();
702 let mut iter2 = restored.iterator();
703
704 while iter1.doc() != u32::MAX {
705 assert_eq!(iter1.doc(), iter2.doc());
706 assert_eq!(iter1.term_freq(), iter2.term_freq());
707 iter1.advance();
708 iter2.advance();
709 }
710 }
711
712 #[test]
713 fn test_hillis_steele_prefix_sum() {
714 let mut deltas = [1u32, 2, 3, 4, 5, 6, 7, 8];
716 prefix_sum_8(&mut deltas);
717 assert_eq!(deltas, [1, 3, 6, 10, 15, 21, 28, 36]);
719
720 let deltas2 = [0u32; 16]; let mut output2 = [0u32; 16];
723 simd::delta_decode(&mut output2, &deltas2, 100, 8);
724 assert_eq!(&output2[..8], &[100, 101, 102, 103, 104, 105, 106, 107]);
726
727 let deltas3 = [1u32, 0, 2, 0, 4, 0, 0, 0];
730 let mut output3 = [0u32; 8];
731 simd::delta_decode(&mut output3, &deltas3, 10, 8);
732 assert_eq!(&output3[..8], &[10, 12, 13, 16, 17, 22, 23, 24]);
734 }
735
736 #[test]
737 fn test_delta_decode_large_block() {
738 let doc_ids: Vec<u32> = (0..128).map(|i| i * 5 + 100).collect();
740 let term_freqs: Vec<u32> = vec![1; 128];
741
742 let posting_list = HorizontalBP128PostingList::from_postings(&doc_ids, &term_freqs, 1.0);
743 let decoded = posting_list.blocks[0].decode_doc_ids();
744
745 assert_eq!(decoded.len(), 128);
746 for (i, (&expected, &actual)) in doc_ids.iter().zip(decoded.iter()).enumerate() {
747 assert_eq!(expected, actual, "Mismatch at position {}", i);
748 }
749 }
750}