1use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
9use std::io::{self, Cursor, Read, Write};
10
11use super::config::WeightQuantization;
12use crate::DocId;
13use crate::structures::postings::TERMINATED;
14use crate::structures::simd;
15
16pub const BLOCK_SIZE: usize = 128;
17
18#[derive(Debug, Clone, Copy)]
19pub struct BlockHeader {
20 pub count: u16,
21 pub doc_id_bits: u8,
22 pub ordinal_bits: u8,
23 pub weight_quant: WeightQuantization,
24 pub first_doc_id: DocId,
25 pub max_weight: f32,
26}
27
28impl BlockHeader {
29 pub const SIZE: usize = 16;
30
31 pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
32 w.write_u16::<LittleEndian>(self.count)?;
33 w.write_u8(self.doc_id_bits)?;
34 w.write_u8(self.ordinal_bits)?;
35 w.write_u8(self.weight_quant as u8)?;
36 w.write_u8(0)?;
37 w.write_u16::<LittleEndian>(0)?;
38 w.write_u32::<LittleEndian>(self.first_doc_id)?;
39 w.write_f32::<LittleEndian>(self.max_weight)?;
40 Ok(())
41 }
42
43 pub fn read<R: Read>(r: &mut R) -> io::Result<Self> {
44 let count = r.read_u16::<LittleEndian>()?;
45 let doc_id_bits = r.read_u8()?;
46 let ordinal_bits = r.read_u8()?;
47 let weight_quant_byte = r.read_u8()?;
48 let _ = r.read_u8()?;
49 let _ = r.read_u16::<LittleEndian>()?;
50 let first_doc_id = r.read_u32::<LittleEndian>()?;
51 let max_weight = r.read_f32::<LittleEndian>()?;
52
53 let weight_quant = WeightQuantization::from_u8(weight_quant_byte)
54 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Invalid weight quant"))?;
55
56 Ok(Self {
57 count,
58 doc_id_bits,
59 ordinal_bits,
60 weight_quant,
61 first_doc_id,
62 max_weight,
63 })
64 }
65}
66
67#[derive(Debug, Clone)]
68pub struct SparseBlock {
69 pub header: BlockHeader,
70 pub doc_ids_data: Vec<u8>,
71 pub ordinals_data: Vec<u8>,
72 pub weights_data: Vec<u8>,
73}
74
75impl SparseBlock {
76 pub fn from_postings(
77 postings: &[(DocId, u16, f32)],
78 weight_quant: WeightQuantization,
79 ) -> io::Result<Self> {
80 assert!(!postings.is_empty() && postings.len() <= BLOCK_SIZE);
81
82 let count = postings.len();
83 let first_doc_id = postings[0].0;
84
85 let mut deltas = Vec::with_capacity(count);
87 let mut prev = first_doc_id;
88 for &(doc_id, _, _) in postings {
89 deltas.push(doc_id.saturating_sub(prev));
90 prev = doc_id;
91 }
92 deltas[0] = 0;
93
94 let doc_id_bits = find_optimal_bit_width(&deltas[1..]);
95 let ordinals: Vec<u16> = postings.iter().map(|(_, o, _)| *o).collect();
96 let max_ordinal = ordinals.iter().copied().max().unwrap_or(0);
97 let ordinal_bits = if max_ordinal == 0 {
98 0
99 } else {
100 bits_needed_u16(max_ordinal)
101 };
102
103 let weights: Vec<f32> = postings.iter().map(|(_, _, w)| *w).collect();
104 let max_weight = weights.iter().copied().fold(0.0f32, f32::max);
105
106 let doc_ids_data = pack_bit_array(&deltas[1..], doc_id_bits);
107 let ordinals_data = if ordinal_bits > 0 {
108 pack_bit_array_u16(&ordinals, ordinal_bits)
109 } else {
110 Vec::new()
111 };
112 let weights_data = encode_weights(&weights, weight_quant)?;
113
114 Ok(Self {
115 header: BlockHeader {
116 count: count as u16,
117 doc_id_bits,
118 ordinal_bits,
119 weight_quant,
120 first_doc_id,
121 max_weight,
122 },
123 doc_ids_data,
124 ordinals_data,
125 weights_data,
126 })
127 }
128
129 pub fn decode_doc_ids(&self) -> Vec<DocId> {
130 let count = self.header.count as usize;
131 let mut doc_ids = Vec::with_capacity(count);
132 doc_ids.push(self.header.first_doc_id);
133
134 if count > 1 {
135 let deltas = unpack_bit_array(&self.doc_ids_data, self.header.doc_id_bits, count - 1);
136 let mut prev = self.header.first_doc_id;
137 for delta in deltas {
138 prev += delta;
139 doc_ids.push(prev);
140 }
141 }
142 doc_ids
143 }
144
145 pub fn decode_ordinals(&self) -> Vec<u16> {
146 let count = self.header.count as usize;
147 if self.header.ordinal_bits == 0 {
148 vec![0u16; count]
149 } else {
150 unpack_bit_array_u16(&self.ordinals_data, self.header.ordinal_bits, count)
151 }
152 }
153
154 pub fn decode_weights(&self) -> Vec<f32> {
155 decode_weights(
156 &self.weights_data,
157 self.header.weight_quant,
158 self.header.count as usize,
159 )
160 }
161
162 pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
163 self.header.write(w)?;
164 w.write_u16::<LittleEndian>(self.doc_ids_data.len() as u16)?;
165 w.write_u16::<LittleEndian>(self.ordinals_data.len() as u16)?;
166 w.write_u16::<LittleEndian>(self.weights_data.len() as u16)?;
167 w.write_u16::<LittleEndian>(0)?;
168 w.write_all(&self.doc_ids_data)?;
169 w.write_all(&self.ordinals_data)?;
170 w.write_all(&self.weights_data)?;
171 Ok(())
172 }
173
174 pub fn read<R: Read>(r: &mut R) -> io::Result<Self> {
175 let header = BlockHeader::read(r)?;
176 let doc_ids_len = r.read_u16::<LittleEndian>()? as usize;
177 let ordinals_len = r.read_u16::<LittleEndian>()? as usize;
178 let weights_len = r.read_u16::<LittleEndian>()? as usize;
179 let _ = r.read_u16::<LittleEndian>()?;
180
181 let mut doc_ids_data = vec![0u8; doc_ids_len];
182 r.read_exact(&mut doc_ids_data)?;
183 let mut ordinals_data = vec![0u8; ordinals_len];
184 r.read_exact(&mut ordinals_data)?;
185 let mut weights_data = vec![0u8; weights_len];
186 r.read_exact(&mut weights_data)?;
187
188 Ok(Self {
189 header,
190 doc_ids_data,
191 ordinals_data,
192 weights_data,
193 })
194 }
195
196 pub fn with_doc_offset(&self, doc_offset: u32) -> Self {
202 Self {
203 header: BlockHeader {
204 first_doc_id: self.header.first_doc_id + doc_offset,
205 ..self.header
206 },
207 doc_ids_data: self.doc_ids_data.clone(),
208 ordinals_data: self.ordinals_data.clone(),
209 weights_data: self.weights_data.clone(),
210 }
211 }
212}
213
214#[derive(Debug, Clone)]
219pub struct BlockSparsePostingList {
220 pub doc_count: u32,
221 pub blocks: Vec<SparseBlock>,
222}
223
224impl BlockSparsePostingList {
225 pub fn from_postings_with_block_size(
227 postings: &[(DocId, u16, f32)],
228 weight_quant: WeightQuantization,
229 block_size: usize,
230 ) -> io::Result<Self> {
231 if postings.is_empty() {
232 return Ok(Self {
233 doc_count: 0,
234 blocks: Vec::new(),
235 });
236 }
237
238 let block_size = block_size.max(16); let mut blocks = Vec::new();
240 for chunk in postings.chunks(block_size) {
241 blocks.push(SparseBlock::from_postings(chunk, weight_quant)?);
242 }
243
244 let mut unique_docs = 1u32;
249 for i in 1..postings.len() {
250 if postings[i].0 != postings[i - 1].0 {
251 unique_docs += 1;
252 }
253 }
254
255 Ok(Self {
256 doc_count: unique_docs,
257 blocks,
258 })
259 }
260
261 pub fn from_postings(
263 postings: &[(DocId, u16, f32)],
264 weight_quant: WeightQuantization,
265 ) -> io::Result<Self> {
266 Self::from_postings_with_block_size(postings, weight_quant, BLOCK_SIZE)
267 }
268
269 pub fn doc_count(&self) -> u32 {
270 self.doc_count
271 }
272
273 pub fn num_blocks(&self) -> usize {
274 self.blocks.len()
275 }
276
277 pub fn global_max_weight(&self) -> f32 {
278 self.blocks
279 .iter()
280 .map(|b| b.header.max_weight)
281 .fold(0.0f32, f32::max)
282 }
283
284 pub fn block_max_weight(&self, block_idx: usize) -> Option<f32> {
285 self.blocks.get(block_idx).map(|b| b.header.max_weight)
286 }
287
288 pub fn size_bytes(&self) -> usize {
290 use std::mem::size_of;
291
292 let header_size = size_of::<u32>() * 2; let blocks_size: usize = self
294 .blocks
295 .iter()
296 .map(|b| {
297 size_of::<BlockHeader>()
298 + b.doc_ids_data.len()
299 + b.ordinals_data.len()
300 + b.weights_data.len()
301 })
302 .sum();
303 header_size + blocks_size
304 }
305
306 pub fn iterator(&self) -> BlockSparsePostingIterator<'_> {
307 BlockSparsePostingIterator::new(self)
308 }
309
310 pub fn serialize<W: Write>(&self, w: &mut W) -> io::Result<()> {
319 use super::SparseSkipEntry;
320
321 w.write_u32::<LittleEndian>(self.doc_count)?;
322 w.write_f32::<LittleEndian>(self.global_max_weight())?;
323 w.write_u32::<LittleEndian>(self.blocks.len() as u32)?;
324
325 let mut block_bytes: Vec<Vec<u8>> = Vec::with_capacity(self.blocks.len());
327 for block in &self.blocks {
328 let mut buf = Vec::new();
329 block.write(&mut buf)?;
330 block_bytes.push(buf);
331 }
332
333 let mut offset = 0u32;
335 for (block, bytes) in self.blocks.iter().zip(block_bytes.iter()) {
336 let doc_ids = block.decode_doc_ids();
337 let first_doc = doc_ids.first().copied().unwrap_or(0);
338 let last_doc = doc_ids.last().copied().unwrap_or(0);
339 let length = bytes.len() as u32;
340
341 let entry =
342 SparseSkipEntry::new(first_doc, last_doc, offset, length, block.header.max_weight);
343 entry.write(w)?;
344 offset += length;
345 }
346
347 for bytes in block_bytes {
349 w.write_all(&bytes)?;
350 }
351
352 Ok(())
353 }
354
355 pub fn deserialize<R: Read>(r: &mut R) -> io::Result<Self> {
358 use super::SparseSkipEntry;
359
360 let doc_count = r.read_u32::<LittleEndian>()?;
361 let _global_max_weight = r.read_f32::<LittleEndian>()?;
362 let num_blocks = r.read_u32::<LittleEndian>()? as usize;
363
364 for _ in 0..num_blocks {
366 let _ = SparseSkipEntry::read(r)?;
367 }
368
369 let mut blocks = Vec::with_capacity(num_blocks);
371 for _ in 0..num_blocks {
372 blocks.push(SparseBlock::read(r)?);
373 }
374 Ok(Self { doc_count, blocks })
375 }
376
377 pub fn deserialize_header<R: Read>(
380 r: &mut R,
381 ) -> io::Result<(u32, f32, Vec<super::SparseSkipEntry>, usize)> {
382 use super::SparseSkipEntry;
383
384 let doc_count = r.read_u32::<LittleEndian>()?;
385 let global_max_weight = r.read_f32::<LittleEndian>()?;
386 let num_blocks = r.read_u32::<LittleEndian>()? as usize;
387
388 let mut entries = Vec::with_capacity(num_blocks);
389 for _ in 0..num_blocks {
390 entries.push(SparseSkipEntry::read(r)?);
391 }
392
393 let header_size = 4 + 4 + 4 + num_blocks * SparseSkipEntry::SIZE;
395
396 Ok((doc_count, global_max_weight, entries, header_size))
397 }
398
399 pub fn decode_all(&self) -> Vec<(DocId, u16, f32)> {
400 let mut result = Vec::with_capacity(self.doc_count as usize);
401 for block in &self.blocks {
402 let doc_ids = block.decode_doc_ids();
403 let ordinals = block.decode_ordinals();
404 let weights = block.decode_weights();
405 for i in 0..block.header.count as usize {
406 result.push((doc_ids[i], ordinals[i], weights[i]));
407 }
408 }
409 result
410 }
411
412 pub fn merge_with_offsets(lists: &[(&BlockSparsePostingList, u32)]) -> Self {
423 if lists.is_empty() {
424 return Self {
425 doc_count: 0,
426 blocks: Vec::new(),
427 };
428 }
429
430 let total_blocks: usize = lists.iter().map(|(pl, _)| pl.blocks.len()).sum();
432 let total_docs: u32 = lists.iter().map(|(pl, _)| pl.doc_count).sum();
433
434 let mut merged_blocks = Vec::with_capacity(total_blocks);
435
436 for (posting_list, doc_offset) in lists {
438 for block in &posting_list.blocks {
439 merged_blocks.push(block.with_doc_offset(*doc_offset));
440 }
441 }
442
443 Self {
444 doc_count: total_docs,
445 blocks: merged_blocks,
446 }
447 }
448
449 fn find_block(&self, target: DocId) -> Option<usize> {
450 let mut lo = 0;
451 let mut hi = self.blocks.len();
452 while lo < hi {
453 let mid = lo + (hi - lo) / 2;
454 let block = &self.blocks[mid];
455 let doc_ids = block.decode_doc_ids();
456 let last_doc = doc_ids.last().copied().unwrap_or(block.header.first_doc_id);
457 if last_doc < target {
458 lo = mid + 1;
459 } else {
460 hi = mid;
461 }
462 }
463 if lo < self.blocks.len() {
464 Some(lo)
465 } else {
466 None
467 }
468 }
469}
470
471pub struct BlockSparsePostingIterator<'a> {
476 posting_list: &'a BlockSparsePostingList,
477 block_idx: usize,
478 in_block_idx: usize,
479 current_doc_ids: Vec<DocId>,
480 current_weights: Vec<f32>,
481 exhausted: bool,
482}
483
484impl<'a> BlockSparsePostingIterator<'a> {
485 fn new(posting_list: &'a BlockSparsePostingList) -> Self {
486 let mut iter = Self {
487 posting_list,
488 block_idx: 0,
489 in_block_idx: 0,
490 current_doc_ids: Vec::new(),
491 current_weights: Vec::new(),
492 exhausted: posting_list.blocks.is_empty(),
493 };
494 if !iter.exhausted {
495 iter.load_block(0);
496 }
497 iter
498 }
499
500 fn load_block(&mut self, block_idx: usize) {
501 if let Some(block) = self.posting_list.blocks.get(block_idx) {
502 self.current_doc_ids = block.decode_doc_ids();
503 self.current_weights = block.decode_weights();
504 self.block_idx = block_idx;
505 self.in_block_idx = 0;
506 }
507 }
508
509 pub fn doc(&self) -> DocId {
510 if self.exhausted {
511 TERMINATED
512 } else {
513 self.current_doc_ids
514 .get(self.in_block_idx)
515 .copied()
516 .unwrap_or(TERMINATED)
517 }
518 }
519
520 pub fn weight(&self) -> f32 {
521 self.current_weights
522 .get(self.in_block_idx)
523 .copied()
524 .unwrap_or(0.0)
525 }
526
527 pub fn ordinal(&self) -> u16 {
528 if let Some(block) = self.posting_list.blocks.get(self.block_idx) {
529 let ordinals = block.decode_ordinals();
530 ordinals.get(self.in_block_idx).copied().unwrap_or(0)
531 } else {
532 0
533 }
534 }
535
536 pub fn advance(&mut self) -> DocId {
537 if self.exhausted {
538 return TERMINATED;
539 }
540 self.in_block_idx += 1;
541 if self.in_block_idx >= self.current_doc_ids.len() {
542 self.block_idx += 1;
543 if self.block_idx >= self.posting_list.blocks.len() {
544 self.exhausted = true;
545 } else {
546 self.load_block(self.block_idx);
547 }
548 }
549 self.doc()
550 }
551
552 pub fn seek(&mut self, target: DocId) -> DocId {
553 if self.exhausted {
554 return TERMINATED;
555 }
556 if self.doc() >= target {
557 return self.doc();
558 }
559
560 if let Some(&last_doc) = self.current_doc_ids.last()
562 && last_doc >= target
563 {
564 while !self.exhausted && self.doc() < target {
565 self.in_block_idx += 1;
566 if self.in_block_idx >= self.current_doc_ids.len() {
567 self.block_idx += 1;
568 if self.block_idx >= self.posting_list.blocks.len() {
569 self.exhausted = true;
570 } else {
571 self.load_block(self.block_idx);
572 }
573 }
574 }
575 return self.doc();
576 }
577
578 if let Some(block_idx) = self.posting_list.find_block(target) {
580 self.load_block(block_idx);
581 while self.in_block_idx < self.current_doc_ids.len()
582 && self.current_doc_ids[self.in_block_idx] < target
583 {
584 self.in_block_idx += 1;
585 }
586 if self.in_block_idx >= self.current_doc_ids.len() {
587 self.block_idx += 1;
588 if self.block_idx >= self.posting_list.blocks.len() {
589 self.exhausted = true;
590 } else {
591 self.load_block(self.block_idx);
592 }
593 }
594 } else {
595 self.exhausted = true;
596 }
597 self.doc()
598 }
599
600 pub fn is_exhausted(&self) -> bool {
601 self.exhausted
602 }
603
604 pub fn current_block_max_weight(&self) -> f32 {
605 self.posting_list
606 .blocks
607 .get(self.block_idx)
608 .map(|b| b.header.max_weight)
609 .unwrap_or(0.0)
610 }
611
612 pub fn current_block_max_contribution(&self, query_weight: f32) -> f32 {
613 query_weight * self.current_block_max_weight()
614 }
615}
616
617fn find_optimal_bit_width(values: &[u32]) -> u8 {
622 if values.is_empty() {
623 return 0;
624 }
625 let max_val = values.iter().copied().max().unwrap_or(0);
626 simd::bits_needed(max_val)
627}
628
629fn bits_needed_u16(val: u16) -> u8 {
630 if val == 0 {
631 0
632 } else {
633 16 - val.leading_zeros() as u8
634 }
635}
636
637fn pack_bit_array(values: &[u32], bits: u8) -> Vec<u8> {
638 if bits == 0 || values.is_empty() {
639 return Vec::new();
640 }
641 let total_bytes = (values.len() * bits as usize).div_ceil(8);
642 let mut result = vec![0u8; total_bytes];
643 let mut bit_pos = 0usize;
644 for &val in values {
645 pack_value(&mut result, bit_pos, val & ((1u32 << bits) - 1), bits);
646 bit_pos += bits as usize;
647 }
648 result
649}
650
651fn pack_bit_array_u16(values: &[u16], bits: u8) -> Vec<u8> {
652 if bits == 0 || values.is_empty() {
653 return Vec::new();
654 }
655 let total_bytes = (values.len() * bits as usize).div_ceil(8);
656 let mut result = vec![0u8; total_bytes];
657 let mut bit_pos = 0usize;
658 for &val in values {
659 pack_value(
660 &mut result,
661 bit_pos,
662 (val as u32) & ((1u32 << bits) - 1),
663 bits,
664 );
665 bit_pos += bits as usize;
666 }
667 result
668}
669
670#[inline]
671fn pack_value(data: &mut [u8], bit_pos: usize, val: u32, bits: u8) {
672 let mut remaining = bits as usize;
673 let mut val = val;
674 let mut byte = bit_pos / 8;
675 let mut offset = bit_pos % 8;
676 while remaining > 0 {
677 let space = 8 - offset;
678 let to_write = remaining.min(space);
679 let mask = (1u32 << to_write) - 1;
680 data[byte] |= ((val & mask) as u8) << offset;
681 val >>= to_write;
682 remaining -= to_write;
683 byte += 1;
684 offset = 0;
685 }
686}
687
688fn unpack_bit_array(data: &[u8], bits: u8, count: usize) -> Vec<u32> {
689 if bits == 0 || count == 0 {
690 return vec![0; count];
691 }
692 let mut result = Vec::with_capacity(count);
693 let mut bit_pos = 0usize;
694 for _ in 0..count {
695 result.push(unpack_value(data, bit_pos, bits));
696 bit_pos += bits as usize;
697 }
698 result
699}
700
701fn unpack_bit_array_u16(data: &[u8], bits: u8, count: usize) -> Vec<u16> {
702 if bits == 0 || count == 0 {
703 return vec![0; count];
704 }
705 let mut result = Vec::with_capacity(count);
706 let mut bit_pos = 0usize;
707 for _ in 0..count {
708 result.push(unpack_value(data, bit_pos, bits) as u16);
709 bit_pos += bits as usize;
710 }
711 result
712}
713
714#[inline]
715fn unpack_value(data: &[u8], bit_pos: usize, bits: u8) -> u32 {
716 let mut val = 0u32;
717 let mut remaining = bits as usize;
718 let mut byte = bit_pos / 8;
719 let mut offset = bit_pos % 8;
720 let mut shift = 0;
721 while remaining > 0 {
722 let space = 8 - offset;
723 let to_read = remaining.min(space);
724 let mask = (1u8 << to_read) - 1;
725 val |= (((data.get(byte).copied().unwrap_or(0) >> offset) & mask) as u32) << shift;
726 remaining -= to_read;
727 shift += to_read;
728 byte += 1;
729 offset = 0;
730 }
731 val
732}
733
734fn encode_weights(weights: &[f32], quant: WeightQuantization) -> io::Result<Vec<u8>> {
739 let mut data = Vec::new();
740 match quant {
741 WeightQuantization::Float32 => {
742 for &w in weights {
743 data.write_f32::<LittleEndian>(w)?;
744 }
745 }
746 WeightQuantization::Float16 => {
747 use half::f16;
748 for &w in weights {
749 data.write_u16::<LittleEndian>(f16::from_f32(w).to_bits())?;
750 }
751 }
752 WeightQuantization::UInt8 => {
753 let min = weights.iter().copied().fold(f32::INFINITY, f32::min);
754 let max = weights.iter().copied().fold(f32::NEG_INFINITY, f32::max);
755 let range = max - min;
756 let scale = if range < f32::EPSILON {
757 1.0
758 } else {
759 range / 255.0
760 };
761 data.write_f32::<LittleEndian>(scale)?;
762 data.write_f32::<LittleEndian>(min)?;
763 for &w in weights {
764 data.write_u8(((w - min) / scale).round() as u8)?;
765 }
766 }
767 WeightQuantization::UInt4 => {
768 let min = weights.iter().copied().fold(f32::INFINITY, f32::min);
769 let max = weights.iter().copied().fold(f32::NEG_INFINITY, f32::max);
770 let range = max - min;
771 let scale = if range < f32::EPSILON {
772 1.0
773 } else {
774 range / 15.0
775 };
776 data.write_f32::<LittleEndian>(scale)?;
777 data.write_f32::<LittleEndian>(min)?;
778 let mut i = 0;
779 while i < weights.len() {
780 let q1 = ((weights[i] - min) / scale).round() as u8 & 0x0F;
781 let q2 = if i + 1 < weights.len() {
782 ((weights[i + 1] - min) / scale).round() as u8 & 0x0F
783 } else {
784 0
785 };
786 data.write_u8((q2 << 4) | q1)?;
787 i += 2;
788 }
789 }
790 }
791 Ok(data)
792}
793
794fn decode_weights(data: &[u8], quant: WeightQuantization, count: usize) -> Vec<f32> {
795 let mut cursor = Cursor::new(data);
796 let mut weights = Vec::with_capacity(count);
797 match quant {
798 WeightQuantization::Float32 => {
799 for _ in 0..count {
800 weights.push(cursor.read_f32::<LittleEndian>().unwrap_or(0.0));
801 }
802 }
803 WeightQuantization::Float16 => {
804 use half::f16;
805 for _ in 0..count {
806 let bits = cursor.read_u16::<LittleEndian>().unwrap_or(0);
807 weights.push(f16::from_bits(bits).to_f32());
808 }
809 }
810 WeightQuantization::UInt8 => {
811 let scale = cursor.read_f32::<LittleEndian>().unwrap_or(1.0);
812 let min = cursor.read_f32::<LittleEndian>().unwrap_or(0.0);
813 for _ in 0..count {
814 let q = cursor.read_u8().unwrap_or(0);
815 weights.push(q as f32 * scale + min);
816 }
817 }
818 WeightQuantization::UInt4 => {
819 let scale = cursor.read_f32::<LittleEndian>().unwrap_or(1.0);
820 let min = cursor.read_f32::<LittleEndian>().unwrap_or(0.0);
821 let mut i = 0;
822 while i < count {
823 let byte = cursor.read_u8().unwrap_or(0);
824 weights.push((byte & 0x0F) as f32 * scale + min);
825 i += 1;
826 if i < count {
827 weights.push((byte >> 4) as f32 * scale + min);
828 i += 1;
829 }
830 }
831 }
832 }
833 weights
834}
835
836#[cfg(test)]
837mod tests {
838 use super::*;
839
840 #[test]
841 fn test_block_roundtrip() {
842 let postings = vec![
843 (10u32, 0u16, 1.5f32),
844 (15, 0, 2.0),
845 (20, 1, 0.5),
846 (100, 0, 3.0),
847 ];
848 let block = SparseBlock::from_postings(&postings, WeightQuantization::Float32).unwrap();
849
850 assert_eq!(block.decode_doc_ids(), vec![10, 15, 20, 100]);
851 assert_eq!(block.decode_ordinals(), vec![0, 0, 1, 0]);
852 let weights = block.decode_weights();
853 assert!((weights[0] - 1.5).abs() < 0.01);
854 }
855
856 #[test]
857 fn test_posting_list() {
858 let postings: Vec<(DocId, u16, f32)> =
859 (0..300).map(|i| (i * 2, 0, i as f32 * 0.1)).collect();
860 let list =
861 BlockSparsePostingList::from_postings(&postings, WeightQuantization::Float32).unwrap();
862
863 assert_eq!(list.doc_count(), 300);
864 assert_eq!(list.num_blocks(), 3);
865
866 let mut iter = list.iterator();
867 assert_eq!(iter.doc(), 0);
868 iter.advance();
869 assert_eq!(iter.doc(), 2);
870 }
871
872 #[test]
873 fn test_serialization() {
874 let postings = vec![(1u32, 0u16, 0.5f32), (10, 1, 1.5), (100, 0, 2.5)];
875 let list =
876 BlockSparsePostingList::from_postings(&postings, WeightQuantization::UInt8).unwrap();
877
878 let mut buf = Vec::new();
879 list.serialize(&mut buf).unwrap();
880 let list2 = BlockSparsePostingList::deserialize(&mut Cursor::new(&buf)).unwrap();
881
882 assert_eq!(list.doc_count(), list2.doc_count());
883 }
884
885 #[test]
886 fn test_seek() {
887 let postings: Vec<(DocId, u16, f32)> = (0..500).map(|i| (i * 3, 0, i as f32)).collect();
888 let list =
889 BlockSparsePostingList::from_postings(&postings, WeightQuantization::Float32).unwrap();
890
891 let mut iter = list.iterator();
892 assert_eq!(iter.seek(300), 300);
893 assert_eq!(iter.seek(301), 303);
894 assert_eq!(iter.seek(2000), TERMINATED);
895 }
896
897 #[test]
898 fn test_merge_with_offsets() {
899 let postings1: Vec<(DocId, u16, f32)> = vec![(0, 0, 1.0), (5, 0, 2.0), (10, 1, 3.0)];
901 let list1 =
902 BlockSparsePostingList::from_postings(&postings1, WeightQuantization::Float32).unwrap();
903
904 let postings2: Vec<(DocId, u16, f32)> = vec![(0, 0, 4.0), (3, 1, 5.0), (7, 0, 6.0)];
906 let list2 =
907 BlockSparsePostingList::from_postings(&postings2, WeightQuantization::Float32).unwrap();
908
909 let merged = BlockSparsePostingList::merge_with_offsets(&[(&list1, 0), (&list2, 100)]);
911
912 assert_eq!(merged.doc_count(), 6);
913
914 let decoded = merged.decode_all();
916 assert_eq!(decoded.len(), 6);
917
918 assert_eq!(decoded[0].0, 0);
920 assert_eq!(decoded[1].0, 5);
921 assert_eq!(decoded[2].0, 10);
922
923 assert_eq!(decoded[3].0, 100); assert_eq!(decoded[4].0, 103); assert_eq!(decoded[5].0, 107); assert!((decoded[0].2 - 1.0).abs() < 0.01);
930 assert!((decoded[3].2 - 4.0).abs() < 0.01);
931
932 assert_eq!(decoded[2].1, 1); assert_eq!(decoded[4].1, 1); }
936
937 #[test]
938 fn test_merge_with_offsets_multi_block() {
939 let postings1: Vec<(DocId, u16, f32)> = (0..200).map(|i| (i * 2, 0, i as f32)).collect();
941 let list1 =
942 BlockSparsePostingList::from_postings(&postings1, WeightQuantization::Float32).unwrap();
943 assert!(list1.num_blocks() > 1, "Should have multiple blocks");
944
945 let postings2: Vec<(DocId, u16, f32)> = (0..150).map(|i| (i * 3, 1, i as f32)).collect();
946 let list2 =
947 BlockSparsePostingList::from_postings(&postings2, WeightQuantization::Float32).unwrap();
948
949 let merged = BlockSparsePostingList::merge_with_offsets(&[(&list1, 0), (&list2, 1000)]);
951
952 assert_eq!(merged.doc_count(), 350);
953 assert_eq!(merged.num_blocks(), list1.num_blocks() + list2.num_blocks());
954
955 let mut iter = merged.iterator();
957
958 assert_eq!(iter.doc(), 0);
960
961 let doc = iter.seek(1000);
963 assert_eq!(doc, 1000); iter.advance();
967 assert_eq!(iter.doc(), 1003); }
969
970 #[test]
971 fn test_merge_with_offsets_serialize_roundtrip() {
972 let postings1: Vec<(DocId, u16, f32)> = vec![(0, 0, 1.0), (5, 0, 2.0), (10, 1, 3.0)];
974 let list1 =
975 BlockSparsePostingList::from_postings(&postings1, WeightQuantization::Float32).unwrap();
976
977 let postings2: Vec<(DocId, u16, f32)> = vec![(0, 0, 4.0), (3, 1, 5.0), (7, 0, 6.0)];
978 let list2 =
979 BlockSparsePostingList::from_postings(&postings2, WeightQuantization::Float32).unwrap();
980
981 let merged = BlockSparsePostingList::merge_with_offsets(&[(&list1, 0), (&list2, 100)]);
983
984 let mut bytes = Vec::new();
986 merged.serialize(&mut bytes).unwrap();
987
988 let mut cursor = std::io::Cursor::new(&bytes);
990 let loaded = BlockSparsePostingList::deserialize(&mut cursor).unwrap();
991
992 let decoded = loaded.decode_all();
994 assert_eq!(decoded.len(), 6);
995
996 assert_eq!(decoded[0].0, 0);
998 assert_eq!(decoded[1].0, 5);
999 assert_eq!(decoded[2].0, 10);
1000
1001 assert_eq!(decoded[3].0, 100, "First doc of seg2 should be 0+100=100");
1003 assert_eq!(decoded[4].0, 103, "Second doc of seg2 should be 3+100=103");
1004 assert_eq!(decoded[5].0, 107, "Third doc of seg2 should be 7+100=107");
1005
1006 let mut iter = loaded.iterator();
1008 assert_eq!(iter.doc(), 0);
1009 iter.advance();
1010 assert_eq!(iter.doc(), 5);
1011 iter.advance();
1012 assert_eq!(iter.doc(), 10);
1013 iter.advance();
1014 assert_eq!(iter.doc(), 100);
1015 iter.advance();
1016 assert_eq!(iter.doc(), 103);
1017 iter.advance();
1018 assert_eq!(iter.doc(), 107);
1019 }
1020
1021 #[test]
1022 fn test_merge_seek_after_roundtrip() {
1023 let postings1: Vec<(DocId, u16, f32)> = (0..200).map(|i| (i * 2, 0, 1.0)).collect();
1025 let list1 =
1026 BlockSparsePostingList::from_postings(&postings1, WeightQuantization::Float32).unwrap();
1027
1028 let postings2: Vec<(DocId, u16, f32)> = (0..150).map(|i| (i * 3, 0, 2.0)).collect();
1029 let list2 =
1030 BlockSparsePostingList::from_postings(&postings2, WeightQuantization::Float32).unwrap();
1031
1032 let merged = BlockSparsePostingList::merge_with_offsets(&[(&list1, 0), (&list2, 1000)]);
1034
1035 let mut bytes = Vec::new();
1037 merged.serialize(&mut bytes).unwrap();
1038 let loaded =
1039 BlockSparsePostingList::deserialize(&mut std::io::Cursor::new(&bytes)).unwrap();
1040
1041 let mut iter = loaded.iterator();
1043
1044 let doc = iter.seek(100);
1046 assert_eq!(doc, 100, "Seek to 100 in segment 1");
1047
1048 let doc = iter.seek(1000);
1050 assert_eq!(doc, 1000, "Seek to 1000 (first doc of segment 2)");
1051
1052 let doc = iter.seek(1050);
1054 assert!(
1055 doc >= 1050,
1056 "Seek to 1050 should find doc >= 1050, got {}",
1057 doc
1058 );
1059
1060 let doc = iter.seek(500);
1062 assert!(
1063 doc >= 1050,
1064 "Seek backwards should not go back, got {}",
1065 doc
1066 );
1067
1068 let mut iter2 = loaded.iterator();
1070
1071 let mut count = 0;
1073 let mut prev_doc = 0;
1074 while iter2.doc() != super::TERMINATED {
1075 let current = iter2.doc();
1076 if count > 0 {
1077 assert!(
1078 current > prev_doc,
1079 "Docs should be monotonically increasing: {} vs {}",
1080 prev_doc,
1081 current
1082 );
1083 }
1084 prev_doc = current;
1085 iter2.advance();
1086 count += 1;
1087 }
1088 assert_eq!(count, 350, "Should have 350 total docs");
1089 }
1090
1091 #[test]
1092 fn test_doc_count_multi_value() {
1093 let postings: Vec<(DocId, u16, f32)> = vec![
1096 (0, 0, 1.0),
1097 (0, 1, 1.5),
1098 (0, 2, 2.0),
1099 (5, 0, 3.0),
1100 (5, 1, 3.5),
1101 (10, 0, 4.0),
1102 ];
1103 let list =
1104 BlockSparsePostingList::from_postings(&postings, WeightQuantization::Float32).unwrap();
1105
1106 assert_eq!(list.doc_count(), 3);
1108
1109 let decoded = list.decode_all();
1111 assert_eq!(decoded.len(), 6);
1112 }
1113
1114 #[test]
1115 fn test_doc_count_single_value() {
1116 let postings: Vec<(DocId, u16, f32)> =
1118 vec![(0, 0, 1.0), (5, 0, 2.0), (10, 0, 3.0), (15, 0, 4.0)];
1119 let list =
1120 BlockSparsePostingList::from_postings(&postings, WeightQuantization::Float32).unwrap();
1121
1122 assert_eq!(list.doc_count(), 4);
1124 }
1125
1126 #[test]
1127 fn test_doc_count_multi_value_serialization_roundtrip() {
1128 let postings: Vec<(DocId, u16, f32)> =
1130 vec![(0, 0, 1.0), (0, 1, 1.5), (5, 0, 2.0), (5, 1, 2.5)];
1131 let list =
1132 BlockSparsePostingList::from_postings(&postings, WeightQuantization::Float32).unwrap();
1133 assert_eq!(list.doc_count(), 2);
1134
1135 let mut buf = Vec::new();
1136 list.serialize(&mut buf).unwrap();
1137 let loaded = BlockSparsePostingList::deserialize(&mut Cursor::new(&buf)).unwrap();
1138 assert_eq!(loaded.doc_count(), 2);
1139 }
1140
1141 #[test]
1142 fn test_merge_preserves_weights_and_ordinals() {
1143 let postings1: Vec<(DocId, u16, f32)> = vec![(0, 0, 1.5), (5, 1, 2.5), (10, 2, 3.5)];
1145 let list1 =
1146 BlockSparsePostingList::from_postings(&postings1, WeightQuantization::Float32).unwrap();
1147
1148 let postings2: Vec<(DocId, u16, f32)> = vec![(0, 0, 4.5), (3, 1, 5.5), (7, 3, 6.5)];
1149 let list2 =
1150 BlockSparsePostingList::from_postings(&postings2, WeightQuantization::Float32).unwrap();
1151
1152 let merged = BlockSparsePostingList::merge_with_offsets(&[(&list1, 0), (&list2, 100)]);
1154
1155 let mut bytes = Vec::new();
1157 merged.serialize(&mut bytes).unwrap();
1158 let loaded =
1159 BlockSparsePostingList::deserialize(&mut std::io::Cursor::new(&bytes)).unwrap();
1160
1161 let mut iter = loaded.iterator();
1163
1164 assert_eq!(iter.doc(), 0);
1166 assert!(
1167 (iter.weight() - 1.5).abs() < 0.01,
1168 "Weight should be 1.5, got {}",
1169 iter.weight()
1170 );
1171 assert_eq!(iter.ordinal(), 0);
1172
1173 iter.advance();
1174 assert_eq!(iter.doc(), 5);
1175 assert!(
1176 (iter.weight() - 2.5).abs() < 0.01,
1177 "Weight should be 2.5, got {}",
1178 iter.weight()
1179 );
1180 assert_eq!(iter.ordinal(), 1);
1181
1182 iter.advance();
1183 assert_eq!(iter.doc(), 10);
1184 assert!(
1185 (iter.weight() - 3.5).abs() < 0.01,
1186 "Weight should be 3.5, got {}",
1187 iter.weight()
1188 );
1189 assert_eq!(iter.ordinal(), 2);
1190
1191 iter.advance();
1193 assert_eq!(iter.doc(), 100);
1194 assert!(
1195 (iter.weight() - 4.5).abs() < 0.01,
1196 "Weight should be 4.5, got {}",
1197 iter.weight()
1198 );
1199 assert_eq!(iter.ordinal(), 0);
1200
1201 iter.advance();
1202 assert_eq!(iter.doc(), 103);
1203 assert!(
1204 (iter.weight() - 5.5).abs() < 0.01,
1205 "Weight should be 5.5, got {}",
1206 iter.weight()
1207 );
1208 assert_eq!(iter.ordinal(), 1);
1209
1210 iter.advance();
1211 assert_eq!(iter.doc(), 107);
1212 assert!(
1213 (iter.weight() - 6.5).abs() < 0.01,
1214 "Weight should be 6.5, got {}",
1215 iter.weight()
1216 );
1217 assert_eq!(iter.ordinal(), 3);
1218
1219 iter.advance();
1221 assert_eq!(iter.doc(), super::TERMINATED);
1222 }
1223
1224 #[test]
1225 fn test_merge_global_max_weight() {
1226 let postings1: Vec<(DocId, u16, f32)> = vec![
1228 (0, 0, 3.0),
1229 (1, 0, 7.0), (2, 0, 2.0),
1231 ];
1232 let list1 =
1233 BlockSparsePostingList::from_postings(&postings1, WeightQuantization::Float32).unwrap();
1234
1235 let postings2: Vec<(DocId, u16, f32)> = vec![
1236 (0, 0, 5.0),
1237 (1, 0, 4.0),
1238 (2, 0, 6.0), ];
1240 let list2 =
1241 BlockSparsePostingList::from_postings(&postings2, WeightQuantization::Float32).unwrap();
1242
1243 assert!((list1.global_max_weight() - 7.0).abs() < 0.01);
1245 assert!((list2.global_max_weight() - 6.0).abs() < 0.01);
1246
1247 let merged = BlockSparsePostingList::merge_with_offsets(&[(&list1, 0), (&list2, 100)]);
1249
1250 assert!(
1252 (merged.global_max_weight() - 7.0).abs() < 0.01,
1253 "Global max should be 7.0, got {}",
1254 merged.global_max_weight()
1255 );
1256
1257 let mut bytes = Vec::new();
1259 merged.serialize(&mut bytes).unwrap();
1260 let loaded =
1261 BlockSparsePostingList::deserialize(&mut std::io::Cursor::new(&bytes)).unwrap();
1262
1263 assert!(
1264 (loaded.global_max_weight() - 7.0).abs() < 0.01,
1265 "After roundtrip, global max should still be 7.0, got {}",
1266 loaded.global_max_weight()
1267 );
1268 }
1269
1270 #[test]
1271 fn test_scoring_simulation_after_merge() {
1272 let postings1: Vec<(DocId, u16, f32)> = vec![
1274 (0, 0, 0.5), (5, 0, 0.8), ];
1277 let list1 =
1278 BlockSparsePostingList::from_postings(&postings1, WeightQuantization::Float32).unwrap();
1279
1280 let postings2: Vec<(DocId, u16, f32)> = vec![
1281 (0, 0, 0.6), (3, 0, 0.9), ];
1284 let list2 =
1285 BlockSparsePostingList::from_postings(&postings2, WeightQuantization::Float32).unwrap();
1286
1287 let merged = BlockSparsePostingList::merge_with_offsets(&[(&list1, 0), (&list2, 100)]);
1289
1290 let mut bytes = Vec::new();
1292 merged.serialize(&mut bytes).unwrap();
1293 let loaded =
1294 BlockSparsePostingList::deserialize(&mut std::io::Cursor::new(&bytes)).unwrap();
1295
1296 let query_weight = 2.0f32;
1298 let mut iter = loaded.iterator();
1299
1300 assert_eq!(iter.doc(), 0);
1303 let score = query_weight * iter.weight();
1304 assert!(
1305 (score - 1.0).abs() < 0.01,
1306 "Doc 0 score should be 1.0, got {}",
1307 score
1308 );
1309
1310 iter.advance();
1311 assert_eq!(iter.doc(), 5);
1313 let score = query_weight * iter.weight();
1314 assert!(
1315 (score - 1.6).abs() < 0.01,
1316 "Doc 5 score should be 1.6, got {}",
1317 score
1318 );
1319
1320 iter.advance();
1321 assert_eq!(iter.doc(), 100);
1323 let score = query_weight * iter.weight();
1324 assert!(
1325 (score - 1.2).abs() < 0.01,
1326 "Doc 100 score should be 1.2, got {}",
1327 score
1328 );
1329
1330 iter.advance();
1331 assert_eq!(iter.doc(), 103);
1333 let score = query_weight * iter.weight();
1334 assert!(
1335 (score - 1.8).abs() < 0.01,
1336 "Doc 103 score should be 1.8, got {}",
1337 score
1338 );
1339 }
1340}