1use std::cmp::Ordering;
4use std::collections::BinaryHeap;
5
6use crate::segment::SegmentReader;
7use crate::structures::TERMINATED;
8use crate::{DocId, Result, Score};
9
10use super::Query;
11
12#[derive(Debug, Clone, PartialEq, Eq, Hash)]
16pub struct DocAddress {
17 segment_id_raw: u128,
19 pub doc_id: DocId,
21}
22
23impl DocAddress {
24 pub fn new(segment_id: u128, doc_id: DocId) -> Self {
25 Self {
26 segment_id_raw: segment_id,
27 doc_id,
28 }
29 }
30
31 pub fn segment_id(&self) -> String {
33 format!("{:032x}", self.segment_id_raw)
34 }
35
36 pub fn segment_id_u128(&self) -> Option<u128> {
38 Some(self.segment_id_raw)
39 }
40}
41
42impl serde::Serialize for DocAddress {
43 fn serialize<S: serde::Serializer>(
44 &self,
45 serializer: S,
46 ) -> std::result::Result<S::Ok, S::Error> {
47 use serde::ser::SerializeStruct;
48 let mut s = serializer.serialize_struct("DocAddress", 2)?;
49 s.serialize_field("segment_id", &format!("{:032x}", self.segment_id_raw))?;
50 s.serialize_field("doc_id", &self.doc_id)?;
51 s.end()
52 }
53}
54
55impl<'de> serde::Deserialize<'de> for DocAddress {
56 fn deserialize<D: serde::Deserializer<'de>>(
57 deserializer: D,
58 ) -> std::result::Result<Self, D::Error> {
59 #[derive(serde::Deserialize)]
60 struct Helper {
61 segment_id: String,
62 doc_id: DocId,
63 }
64 let h = Helper::deserialize(deserializer)?;
65 let raw = u128::from_str_radix(&h.segment_id, 16).map_err(serde::de::Error::custom)?;
66 Ok(DocAddress {
67 segment_id_raw: raw,
68 doc_id: h.doc_id,
69 })
70 }
71}
72
73#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
77pub struct ScoredPosition {
78 pub position: u32,
80 pub score: f32,
82}
83
84impl ScoredPosition {
85 pub fn new(position: u32, score: f32) -> Self {
86 Self { position, score }
87 }
88}
89
90#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
92pub struct SearchResult {
93 pub doc_id: DocId,
94 pub score: Score,
95 #[serde(default, skip_serializing_if = "is_zero_u128")]
97 pub segment_id: u128,
98 #[serde(default, skip_serializing_if = "Vec::is_empty")]
101 pub positions: Vec<(u32, Vec<ScoredPosition>)>,
102}
103
104fn is_zero_u128(v: &u128) -> bool {
105 *v == 0
106}
107
108pub(crate) fn compare_search_results_desc(a: &SearchResult, b: &SearchResult) -> Ordering {
110 b.score
111 .total_cmp(&a.score)
112 .then_with(|| a.segment_id.cmp(&b.segment_id))
113 .then_with(|| a.doc_id.cmp(&b.doc_id))
114}
115
116#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
118pub struct MatchedField {
119 pub field_id: u32,
121 pub ordinals: Vec<u32>,
124}
125
126impl SearchResult {
127 pub fn extract_ordinals(&self) -> Vec<MatchedField> {
131 use rustc_hash::FxHashSet;
132
133 self.positions
134 .iter()
135 .map(|(field_id, scored_positions)| {
136 let mut ordinals: FxHashSet<u32> = FxHashSet::default();
137 for sp in scored_positions {
138 let ordinal = if sp.position > 0xFFFFF {
142 sp.position >> 20
143 } else {
144 sp.position
145 };
146 ordinals.insert(ordinal);
147 }
148 let mut ordinals: Vec<u32> = ordinals.into_iter().collect();
149 ordinals.sort_unstable();
150 MatchedField {
151 field_id: *field_id,
152 ordinals,
153 }
154 })
155 .collect()
156 }
157
158 pub fn field_positions(&self, field_id: u32) -> Option<&[ScoredPosition]> {
160 self.positions
161 .iter()
162 .find(|(fid, _)| *fid == field_id)
163 .map(|(_, positions)| positions.as_slice())
164 }
165}
166
167#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
169pub struct SearchHit {
170 pub address: DocAddress,
172 pub score: Score,
173 #[serde(default, skip_serializing_if = "Vec::is_empty")]
175 pub matched_fields: Vec<MatchedField>,
176}
177
178#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
180pub struct SearchResponse {
181 pub hits: Vec<SearchHit>,
182 pub total_hits: u32,
183}
184
185impl PartialEq for SearchResult {
186 fn eq(&self, other: &Self) -> bool {
187 self.score.to_bits() == other.score.to_bits()
188 && self.segment_id == other.segment_id
189 && self.doc_id == other.doc_id
190 }
191}
192
193impl Eq for SearchResult {}
194
195impl PartialOrd for SearchResult {
196 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
197 Some(self.cmp(other))
198 }
199}
200
201impl Ord for SearchResult {
202 fn cmp(&self, other: &Self) -> Ordering {
203 other
204 .score
205 .total_cmp(&self.score)
206 .then_with(|| self.segment_id.cmp(&other.segment_id))
207 .then_with(|| self.doc_id.cmp(&other.doc_id))
208 }
209}
210
211pub trait Collector {
216 fn collect(&mut self, doc_id: DocId, score: Score, positions: &[(u32, Vec<ScoredPosition>)]);
219
220 fn would_collect(&self, _doc_id: DocId, _score: Score) -> bool {
225 true
226 }
227
228 fn collect_owned(&mut self, doc_id: DocId, score: Score, positions: super::MatchedPositions) {
231 self.collect(doc_id, score, &positions);
232 }
233
234 fn needs_positions(&self) -> bool {
236 false
237 }
238}
239
240pub struct TopKCollector {
242 heap: BinaryHeap<SearchResult>,
243 k: usize,
244 collect_positions: bool,
245 total_seen: u32,
247}
248
249const MAX_INITIAL_TOP_K_CAPACITY: usize = 8 * 1024;
254
255impl TopKCollector {
256 pub fn new(k: usize) -> Self {
257 Self {
258 heap: BinaryHeap::with_capacity(k.min(MAX_INITIAL_TOP_K_CAPACITY)),
259 k,
260 collect_positions: false,
261 total_seen: 0,
262 }
263 }
264
265 pub fn with_positions(k: usize) -> Self {
267 Self {
268 heap: BinaryHeap::with_capacity(k.min(MAX_INITIAL_TOP_K_CAPACITY)),
269 k,
270 collect_positions: true,
271 total_seen: 0,
272 }
273 }
274
275 pub fn total_seen(&self) -> u32 {
277 self.total_seen
278 }
279
280 pub fn into_sorted_results(self) -> Vec<SearchResult> {
281 let mut results: Vec<_> = self.heap.into_vec();
282 results.sort_unstable_by(compare_search_results_desc);
283 results
284 }
285
286 pub fn into_results_with_count(self) -> (Vec<SearchResult>, u32) {
288 let total = self.total_seen;
289 (self.into_sorted_results(), total)
290 }
291}
292
293impl Collector for TopKCollector {
294 fn collect(&mut self, doc_id: DocId, score: Score, positions: &[(u32, Vec<ScoredPosition>)]) {
295 self.total_seen = self.total_seen.saturating_add(1);
296
297 if !self.would_collect(doc_id, score) {
301 return;
302 }
303
304 let positions = if self.collect_positions {
305 positions.to_vec()
306 } else {
307 Vec::new()
308 };
309
310 if self.heap.len() >= self.k {
311 self.heap.pop();
312 }
313 self.heap.push(SearchResult {
314 doc_id,
315 score,
316 segment_id: 0,
317 positions,
318 });
319 }
320
321 fn would_collect(&self, doc_id: DocId, score: Score) -> bool {
322 self.k > 0
323 && (self.heap.len() < self.k
324 || self.heap.peek().is_some_and(|min| {
325 score.total_cmp(&min.score).is_gt()
326 || (score.total_cmp(&min.score).is_eq() && doc_id < min.doc_id)
327 }))
328 }
329
330 fn collect_owned(&mut self, doc_id: DocId, score: Score, positions: super::MatchedPositions) {
331 self.total_seen = self.total_seen.saturating_add(1);
332
333 if !self.would_collect(doc_id, score) {
334 return;
335 }
336
337 if self.heap.len() >= self.k {
338 self.heap.pop();
339 }
340 self.heap.push(SearchResult {
341 doc_id,
342 score,
343 segment_id: 0,
344 positions: if self.collect_positions {
345 positions
346 } else {
347 Vec::new()
348 },
349 });
350 }
351
352 fn needs_positions(&self) -> bool {
353 self.collect_positions
354 }
355}
356
357#[derive(Default)]
359pub struct CountCollector {
360 count: u64,
361}
362
363impl CountCollector {
364 pub fn new() -> Self {
365 Self { count: 0 }
366 }
367
368 pub fn count(&self) -> u64 {
370 self.count
371 }
372}
373
374impl Collector for CountCollector {
375 #[inline]
376 fn collect(
377 &mut self,
378 _doc_id: DocId,
379 _score: Score,
380 _positions: &[(u32, Vec<ScoredPosition>)],
381 ) {
382 self.count += 1;
383 }
384}
385
386pub async fn search_segment_with_count(
388 reader: &SegmentReader,
389 query: &dyn Query,
390 limit: usize,
391) -> Result<(Vec<SearchResult>, u32)> {
392 let segment_limit = limit.min(reader.num_docs() as usize);
393 let mut collector = TopKCollector::new(segment_limit);
394 collect_segment_with_limit(reader, query, &mut collector, segment_limit).await?;
395 Ok(collector.into_results_with_count())
396}
397
398pub async fn search_segment_with_positions_and_count(
400 reader: &SegmentReader,
401 query: &dyn Query,
402 limit: usize,
403) -> Result<(Vec<SearchResult>, u32)> {
404 let segment_limit = limit.min(reader.num_docs() as usize);
405 let mut collector = TopKCollector::with_positions(segment_limit);
406 collect_segment_with_limit(reader, query, &mut collector, segment_limit).await?;
407 Ok(collector.into_results_with_count())
408}
409
410fn positions_for_next_collector(
415 positions: &mut Option<super::MatchedPositions>,
416 remaining_consumers: &mut usize,
417) -> super::MatchedPositions {
418 assert!(
419 *remaining_consumers > 0,
420 "position consumer count underflow"
421 );
422 *remaining_consumers -= 1;
423 if *remaining_consumers == 0 {
424 positions
425 .take()
426 .expect("owned positions must remain for the final collector")
427 } else {
428 positions
429 .as_ref()
430 .cloned()
431 .expect("owned positions must remain while collectors are pending")
432 }
433}
434
435impl<A: Collector, B: Collector> Collector for (&mut A, &mut B) {
437 fn collect(&mut self, doc_id: DocId, score: Score, positions: &[(u32, Vec<ScoredPosition>)]) {
438 self.0.collect(doc_id, score, positions);
439 self.1.collect(doc_id, score, positions);
440 }
441 fn needs_positions(&self) -> bool {
442 self.0.needs_positions() || self.1.needs_positions()
443 }
444 fn would_collect(&self, doc_id: DocId, score: Score) -> bool {
445 (self.0.needs_positions() && self.0.would_collect(doc_id, score))
446 || (self.1.needs_positions() && self.1.would_collect(doc_id, score))
447 }
448 fn collect_owned(&mut self, doc_id: DocId, score: Score, positions: super::MatchedPositions) {
449 let wants = [
450 self.0.needs_positions() && self.0.would_collect(doc_id, score),
451 self.1.needs_positions() && self.1.would_collect(doc_id, score),
452 ];
453 let mut remaining = wants.iter().filter(|&&want| want).count();
454 let mut positions = Some(positions);
455
456 if wants[0] {
457 self.0.collect_owned(
458 doc_id,
459 score,
460 positions_for_next_collector(&mut positions, &mut remaining),
461 );
462 } else {
463 self.0.collect(doc_id, score, &[]);
464 }
465 if wants[1] {
466 self.1.collect_owned(
467 doc_id,
468 score,
469 positions_for_next_collector(&mut positions, &mut remaining),
470 );
471 } else {
472 self.1.collect(doc_id, score, &[]);
473 }
474 }
475}
476
477impl<A: Collector, B: Collector, C: Collector> Collector for (&mut A, &mut B, &mut C) {
479 fn collect(&mut self, doc_id: DocId, score: Score, positions: &[(u32, Vec<ScoredPosition>)]) {
480 self.0.collect(doc_id, score, positions);
481 self.1.collect(doc_id, score, positions);
482 self.2.collect(doc_id, score, positions);
483 }
484 fn needs_positions(&self) -> bool {
485 self.0.needs_positions() || self.1.needs_positions() || self.2.needs_positions()
486 }
487 fn would_collect(&self, doc_id: DocId, score: Score) -> bool {
488 (self.0.needs_positions() && self.0.would_collect(doc_id, score))
489 || (self.1.needs_positions() && self.1.would_collect(doc_id, score))
490 || (self.2.needs_positions() && self.2.would_collect(doc_id, score))
491 }
492 fn collect_owned(&mut self, doc_id: DocId, score: Score, positions: super::MatchedPositions) {
493 let wants = [
494 self.0.needs_positions() && self.0.would_collect(doc_id, score),
495 self.1.needs_positions() && self.1.would_collect(doc_id, score),
496 self.2.needs_positions() && self.2.would_collect(doc_id, score),
497 ];
498 let mut remaining = wants.iter().filter(|&&want| want).count();
499 let mut positions = Some(positions);
500
501 if wants[0] {
502 self.0.collect_owned(
503 doc_id,
504 score,
505 positions_for_next_collector(&mut positions, &mut remaining),
506 );
507 } else {
508 self.0.collect(doc_id, score, &[]);
509 }
510 if wants[1] {
511 self.1.collect_owned(
512 doc_id,
513 score,
514 positions_for_next_collector(&mut positions, &mut remaining),
515 );
516 } else {
517 self.1.collect(doc_id, score, &[]);
518 }
519 if wants[2] {
520 self.2.collect_owned(
521 doc_id,
522 score,
523 positions_for_next_collector(&mut positions, &mut remaining),
524 );
525 } else {
526 self.2.collect(doc_id, score, &[]);
527 }
528 }
529}
530
531pub async fn collect_segment<C: Collector>(
549 reader: &SegmentReader,
550 query: &dyn Query,
551 collector: &mut C,
552) -> Result<()> {
553 collect_segment_with_limit(reader, query, collector, usize::MAX / 2).await
555}
556
557pub async fn collect_segment_with_limit<C: Collector>(
566 reader: &SegmentReader,
567 query: &dyn Query,
568 collector: &mut C,
569 limit: usize,
570) -> Result<()> {
571 collect_segment_with_limit_seeded(reader, query, collector, limit, 0.0).await
572}
573
574pub async fn collect_segment_with_limit_seeded<C: Collector>(
579 reader: &SegmentReader,
580 query: &dyn Query,
581 collector: &mut C,
582 limit: usize,
583 initial_threshold: f32,
584) -> Result<()> {
585 let options = super::ScorerOptions {
586 collect_positions: collector.needs_positions(),
587 initial_threshold,
588 shared_threshold: None,
589 };
590 let mut scorer = query.scorer_with_options(reader, limit, options).await?;
591 drive_scorer(scorer.as_mut(), collector);
592 Ok(())
593}
594
595fn drive_scorer<C: Collector>(scorer: &mut dyn super::Scorer, collector: &mut C) {
597 let needs_positions = collector.needs_positions();
598 let mut doc = scorer.doc();
599 while doc != TERMINATED {
600 let score = scorer.score();
601 if needs_positions && collector.would_collect(doc, score) {
602 let positions = scorer.matched_positions().unwrap_or_default();
603 collector.collect_owned(doc, score, positions);
604 } else {
605 collector.collect(doc, score, &[]);
606 }
607 doc = scorer.advance();
608 }
609}
610
611#[cfg(feature = "sync")]
615pub fn search_segment_with_count_sync(
616 reader: &SegmentReader,
617 query: &dyn Query,
618 limit: usize,
619) -> Result<(Vec<SearchResult>, u32)> {
620 let segment_limit = limit.min(reader.num_docs() as usize);
621 let mut collector = TopKCollector::new(segment_limit);
622 collect_segment_with_limit_sync(reader, query, &mut collector, segment_limit)?;
623 Ok(collector.into_results_with_count())
624}
625
626#[cfg(feature = "sync")]
628pub fn search_segment_with_positions_and_count_sync(
629 reader: &SegmentReader,
630 query: &dyn Query,
631 limit: usize,
632) -> Result<(Vec<SearchResult>, u32)> {
633 let segment_limit = limit.min(reader.num_docs() as usize);
634 let mut collector = TopKCollector::with_positions(segment_limit);
635 collect_segment_with_limit_sync(reader, query, &mut collector, segment_limit)?;
636 Ok(collector.into_results_with_count())
637}
638
639#[cfg(feature = "sync")]
641pub fn collect_segment_with_limit_sync<C: Collector>(
642 reader: &SegmentReader,
643 query: &dyn Query,
644 collector: &mut C,
645 limit: usize,
646) -> Result<()> {
647 collect_segment_with_limit_seeded_sync(reader, query, collector, limit, 0.0)
648}
649
650#[cfg(feature = "sync")]
653pub fn collect_segment_with_limit_seeded_sync<C: Collector>(
654 reader: &SegmentReader,
655 query: &dyn Query,
656 collector: &mut C,
657 limit: usize,
658 initial_threshold: f32,
659) -> Result<()> {
660 let options = super::ScorerOptions {
661 collect_positions: collector.needs_positions(),
662 initial_threshold,
663 shared_threshold: None,
664 };
665 let mut scorer = query.scorer_sync_with_options(reader, limit, options)?;
666 drive_scorer(scorer.as_mut(), collector);
667 Ok(())
668}
669
670#[cfg(feature = "sync")]
677pub fn search_segment_seeded_sync(
678 reader: &SegmentReader,
679 query: &dyn Query,
680 limit: usize,
681 collect_positions: bool,
682 initial_threshold: f32,
683) -> Result<(Vec<SearchResult>, u32)> {
684 let segment_limit = limit.min(reader.num_docs() as usize);
685 let mut collector = if collect_positions {
686 TopKCollector::with_positions(segment_limit)
687 } else {
688 TopKCollector::new(segment_limit)
689 };
690 collect_segment_with_limit_seeded_sync(
691 reader,
692 query,
693 &mut collector,
694 segment_limit,
695 initial_threshold,
696 )?;
697 Ok(collector.into_results_with_count())
698}
699
700#[cfg(feature = "sync")]
702pub fn search_segment_shared_sync(
703 reader: &SegmentReader,
704 query: &dyn Query,
705 limit: usize,
706 collect_positions: bool,
707 shared_threshold: super::SharedThreshold,
708) -> Result<(Vec<SearchResult>, u32)> {
709 let segment_limit = limit.min(reader.num_docs() as usize);
710 let mut collector = if collect_positions {
711 TopKCollector::with_positions(segment_limit)
712 } else {
713 TopKCollector::new(segment_limit)
714 };
715 let options = super::ScorerOptions {
716 collect_positions,
717 initial_threshold: shared_threshold.get(),
718 shared_threshold: Some(shared_threshold),
719 };
720 let mut scorer = query.scorer_sync_with_options(reader, segment_limit, options)?;
721 drive_scorer(scorer.as_mut(), &mut collector);
722 Ok(collector.into_results_with_count())
723}
724
725pub async fn search_segment_seeded(
727 reader: &SegmentReader,
728 query: &dyn Query,
729 limit: usize,
730 collect_positions: bool,
731 initial_threshold: f32,
732) -> Result<(Vec<SearchResult>, u32)> {
733 let segment_limit = limit.min(reader.num_docs() as usize);
734 let mut collector = if collect_positions {
735 TopKCollector::with_positions(segment_limit)
736 } else {
737 TopKCollector::new(segment_limit)
738 };
739 collect_segment_with_limit_seeded(
740 reader,
741 query,
742 &mut collector,
743 segment_limit,
744 initial_threshold,
745 )
746 .await?;
747 Ok(collector.into_results_with_count())
748}
749
750pub async fn search_segment_shared(
752 reader: &SegmentReader,
753 query: &dyn Query,
754 limit: usize,
755 collect_positions: bool,
756 shared_threshold: super::SharedThreshold,
757) -> Result<(Vec<SearchResult>, u32)> {
758 let segment_limit = limit.min(reader.num_docs() as usize);
759 let mut collector = if collect_positions {
760 TopKCollector::with_positions(segment_limit)
761 } else {
762 TopKCollector::new(segment_limit)
763 };
764 let options = super::ScorerOptions {
765 collect_positions,
766 initial_threshold: shared_threshold.get(),
767 shared_threshold: Some(shared_threshold),
768 };
769 let mut scorer = query
770 .scorer_with_options(reader, segment_limit, options)
771 .await?;
772 drive_scorer(scorer.as_mut(), &mut collector);
773 Ok(collector.into_results_with_count())
774}
775
776#[cfg(test)]
777mod tests {
778 use super::*;
779 use std::sync::Arc;
780 use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
781
782 #[derive(Default)]
783 struct OwnedPositionCollector {
784 owned_calls: usize,
785 borrowed_calls: usize,
786 positions: super::super::MatchedPositions,
787 }
788
789 impl Collector for OwnedPositionCollector {
790 fn collect(
791 &mut self,
792 _doc_id: DocId,
793 _score: Score,
794 positions: &[(u32, Vec<ScoredPosition>)],
795 ) {
796 self.borrowed_calls += 1;
797 self.positions = positions.to_vec();
798 }
799
800 fn collect_owned(
801 &mut self,
802 _doc_id: DocId,
803 _score: Score,
804 positions: super::super::MatchedPositions,
805 ) {
806 self.owned_calls += 1;
807 self.positions = positions;
808 }
809
810 fn needs_positions(&self) -> bool {
811 true
812 }
813 }
814
815 struct PositionCountingScorer {
816 index: usize,
817 position_calls: Arc<AtomicUsize>,
818 }
819
820 impl super::super::DocSet for PositionCountingScorer {
821 fn doc(&self) -> DocId {
822 if self.index < 3 {
823 self.index as DocId
824 } else {
825 TERMINATED
826 }
827 }
828
829 fn advance(&mut self) -> DocId {
830 self.index += 1;
831 self.doc()
832 }
833
834 fn seek(&mut self, target: DocId) -> DocId {
835 self.index = target.min(3) as usize;
836 self.doc()
837 }
838
839 fn size_hint(&self) -> u32 {
840 3u32.saturating_sub(self.index as u32)
841 }
842 }
843
844 impl super::super::Scorer for PositionCountingScorer {
845 fn score(&self) -> Score {
846 [10.0, 1.0, 2.0][self.index]
847 }
848
849 fn matched_positions(&self) -> Option<super::super::MatchedPositions> {
850 self.position_calls.fetch_add(1, AtomicOrdering::Relaxed);
851 Some(vec![(7, vec![ScoredPosition::new(self.index as u32, 1.0)])])
852 }
853 }
854
855 #[test]
856 fn test_top_k_collector() {
857 let mut collector = TopKCollector::new(3);
858
859 collector.collect(0, 1.0, &[]);
860 collector.collect(1, 3.0, &[]);
861 collector.collect(2, 2.0, &[]);
862 collector.collect(3, 4.0, &[]);
863 collector.collect(4, 0.5, &[]);
864
865 let results = collector.into_sorted_results();
866
867 assert_eq!(results.len(), 3);
868 assert_eq!(results[0].doc_id, 3); assert_eq!(results[1].doc_id, 1); assert_eq!(results[2].doc_id, 2); }
872
873 #[test]
874 fn top_k_zero_retains_no_results() {
875 let mut collector = TopKCollector::new(0);
876 collector.collect(1, 1.0, &[]);
877
878 assert!(collector.into_sorted_results().is_empty());
879 }
880
881 #[test]
882 fn huge_top_k_does_not_trigger_a_huge_initial_allocation() {
883 let collector = TopKCollector::new(usize::MAX);
884
885 assert!(collector.heap.capacity() <= MAX_INITIAL_TOP_K_CAPACITY);
886 }
887
888 #[test]
889 fn positions_are_only_materialized_for_competitive_hits() {
890 let calls = Arc::new(AtomicUsize::new(0));
891 let mut scorer = PositionCountingScorer {
892 index: 0,
893 position_calls: Arc::clone(&calls),
894 };
895 let mut collector = TopKCollector::with_positions(1);
896
897 drive_scorer(&mut scorer, &mut collector);
898
899 assert_eq!(calls.load(AtomicOrdering::Relaxed), 1);
900 assert_eq!(collector.total_seen(), 3);
901 let results = collector.into_sorted_results();
902 assert_eq!(results.len(), 1);
903 assert_eq!(results[0].doc_id, 0);
904 assert_eq!(results[0].positions[0].0, 7);
905 }
906
907 #[test]
908 fn tuple_moves_owned_positions_to_single_position_collector() {
909 let mut positions = OwnedPositionCollector::default();
910 let mut count = CountCollector::new();
911 let input = vec![(7, vec![ScoredPosition::new(3, 1.0)])];
912 let input_ptr = input[0].1.as_ptr();
913
914 (&mut positions, &mut count).collect_owned(11, 2.0, input);
915
916 assert_eq!(positions.owned_calls, 1);
917 assert_eq!(positions.borrowed_calls, 0);
918 assert_eq!(positions.positions[0].1.as_ptr(), input_ptr);
919 assert_eq!(count.count(), 1);
920 }
921
922 #[test]
923 fn tuple_clones_for_all_but_final_position_collector() {
924 let mut first = OwnedPositionCollector::default();
925 let mut second = OwnedPositionCollector::default();
926 let mut count = CountCollector::new();
927 let input = vec![(7, vec![ScoredPosition::new(3, 1.0)])];
928 let input_ptr = input[0].1.as_ptr();
929
930 (&mut first, &mut count, &mut second).collect_owned(11, 2.0, input);
931
932 assert_eq!((first.owned_calls, first.borrowed_calls), (1, 0));
933 assert_eq!((second.owned_calls, second.borrowed_calls), (1, 0));
934 assert_ne!(first.positions[0].1.as_ptr(), input_ptr);
935 assert_eq!(second.positions[0].1.as_ptr(), input_ptr);
936 assert_eq!(count.count(), 1);
937 }
938
939 #[test]
940 fn test_count_collector() {
941 let mut collector = CountCollector::new();
942
943 collector.collect(0, 1.0, &[]);
944 collector.collect(1, 2.0, &[]);
945 collector.collect(2, 3.0, &[]);
946
947 assert_eq!(collector.count(), 3);
948 }
949
950 #[test]
951 fn test_multi_collector() {
952 let mut top_k = TopKCollector::new(2);
953 let mut count = CountCollector::new();
954
955 for (doc_id, score) in [(0, 1.0), (1, 3.0), (2, 2.0), (3, 4.0), (4, 0.5)] {
957 top_k.collect(doc_id, score, &[]);
958 count.collect(doc_id, score, &[]);
959 }
960
961 assert_eq!(count.count(), 5);
963
964 let results = top_k.into_sorted_results();
966 assert_eq!(results.len(), 2);
967 assert_eq!(results[0].doc_id, 3); assert_eq!(results[1].doc_id, 1); }
970}