1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use std::cmp::Ordering;

use tantivy::{DocAddress, DocId, SegmentLocalId, SegmentReader};

use super::topk::Scored;

/// A trait that allows defining arbitrary conditions to be checked
/// before considering a matching document for inclusion in the
/// top results.
pub trait ConditionForSegment<T>: Clone {
    type Type: CheckCondition<T>;
    fn for_segment(&self, reader: &SegmentReader) -> Self::Type;
}

impl<T, C, F> ConditionForSegment<T> for F
where
    F: Clone + Fn(&SegmentReader) -> C,
    C: CheckCondition<T>,
{
    type Type = C;
    fn for_segment(&self, reader: &SegmentReader) -> Self::Type {
        (self)(reader)
    }
}

impl<T> ConditionForSegment<T> for bool {
    type Type = bool;
    fn for_segment(&self, _reader: &SegmentReader) -> Self::Type {
        *self
    }
}

impl<T> ConditionForSegment<T> for (T, DocAddress)
where
    T: 'static + PartialOrd + Copy,
{
    type Type = Self;
    fn for_segment(&self, _reader: &SegmentReader) -> Self::Type {
        *self
    }
}

/// The condition that gets checked before collection. In order for
/// a document to appear in the results it must first return true
/// for `check`.
pub trait CheckCondition<T>: 'static + Clone {
    fn check(&self, segment_id: SegmentLocalId, doc_id: DocId, score: T, ascending: bool) -> bool;
}

impl<T> CheckCondition<T> for bool {
    fn check(&self, _: SegmentLocalId, _: DocId, _: T, _: bool) -> bool {
        *self
    }
}

impl<F, T> CheckCondition<T> for F
where
    F: 'static + Clone + Fn(SegmentLocalId, DocId, T, bool) -> bool,
{
    fn check(&self, segment_id: SegmentLocalId, doc_id: DocId, score: T, ascending: bool) -> bool {
        (self)(segment_id, doc_id, score, ascending)
    }
}

impl<T> CheckCondition<T> for (T, DocAddress)
where
    T: 'static + PartialOrd + Copy,
{
    fn check(&self, segment_id: SegmentLocalId, doc_id: DocId, score: T, ascending: bool) -> bool {
        let wanted = if ascending {
            Ordering::Less
        } else {
            Ordering::Greater
        };

        Scored::new(self.0, self.1).cmp(&Scored::new(score, DocAddress(segment_id, doc_id)))
            == wanted
    }
}