Skip to main content

lb_tantivy/query/
empty_query.rs

1use super::Scorer;
2use crate::docset::TERMINATED;
3use crate::index::SegmentReader;
4use crate::query::explanation::does_not_match;
5use crate::query::{EnableScoring, Explanation, Query, Weight};
6use crate::{DocId, DocSet, Score, Searcher};
7
8/// `EmptyQuery` is a dummy `Query` in which no document matches.
9///
10/// It is useful for tests and handling edge cases.
11#[derive(Clone, Debug)]
12pub struct EmptyQuery;
13
14impl Query for EmptyQuery {
15    fn weight(&self, _enable_scoring: EnableScoring<'_>) -> crate::Result<Box<dyn Weight>> {
16        Ok(Box::new(EmptyWeight))
17    }
18
19    fn count(&self, _searcher: &Searcher) -> crate::Result<usize> {
20        Ok(0)
21    }
22}
23
24/// `EmptyWeight` is a dummy `Weight` in which no document matches.
25///
26/// It is useful for tests and handling edge cases.
27pub struct EmptyWeight;
28impl Weight for EmptyWeight {
29    fn scorer(&self, _reader: &SegmentReader, _boost: Score) -> crate::Result<Box<dyn Scorer>> {
30        Ok(Box::new(EmptyScorer))
31    }
32
33    fn explain(&self, _reader: &SegmentReader, doc: DocId) -> crate::Result<Explanation> {
34        Err(does_not_match(doc))
35    }
36}
37
38/// `EmptyScorer` is a dummy `Scorer` in which no document matches.
39///
40/// It is useful for tests and handling edge cases.
41pub struct EmptyScorer;
42
43impl DocSet for EmptyScorer {
44    fn advance(&mut self) -> DocId {
45        TERMINATED
46    }
47
48    fn doc(&self) -> DocId {
49        TERMINATED
50    }
51
52    fn size_hint(&self) -> u32 {
53        0
54    }
55}
56
57impl Scorer for EmptyScorer {
58    fn score(&mut self) -> Score {
59        0.0
60    }
61}
62
63#[cfg(test)]
64mod tests {
65    use crate::docset::TERMINATED;
66    use crate::query::EmptyScorer;
67    use crate::DocSet;
68
69    #[test]
70    fn test_empty_scorer() {
71        let mut empty_scorer = EmptyScorer;
72        assert_eq!(empty_scorer.doc(), TERMINATED);
73        assert_eq!(empty_scorer.advance(), TERMINATED);
74        assert_eq!(empty_scorer.doc(), TERMINATED);
75    }
76}