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
use std::fmt;
use std::fmt::Write;

/// Defines whether a term in a query must be present,
/// should be present or must be not present.
#[derive(Debug, Clone, Hash, Copy, Eq, PartialEq)]
pub enum Occur {
    /// For a given document to be considered for scoring,
    /// at least one of the document with the Should or the Must
    /// Occur constraint must be within the document.
    Should,
    /// Document without the term are excluded from the search.
    Must,
    /// Document that contain the term are excluded from the
    /// search.
    MustNot,
}

impl Occur {
    /// Returns the one-char prefix symbol for this `Occur`.
    /// - `Should` => '?',
    /// - `Must` => '+'
    /// - `Not` => '-'
    fn to_char(self) -> char {
        match self {
            Occur::Should => '?',
            Occur::Must => '+',
            Occur::MustNot => '-',
        }
    }

    /// Compose two occur values.
    pub fn compose(left: Occur, right: Occur) -> Occur {
        match (left, right) {
            (Occur::Should, _) => right,
            (Occur::Must, Occur::MustNot) => Occur::MustNot,
            (Occur::Must, _) => Occur::Must,
            (Occur::MustNot, Occur::MustNot) => Occur::Must,
            (Occur::MustNot, _) => Occur::MustNot,
        }
    }
}

impl fmt::Display for Occur {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_char(self.to_char())
    }
}

#[cfg(test)]
mod test {
    use crate::Occur;

    #[test]
    fn test_occur_compose() {
        assert_eq!(Occur::compose(Occur::Should, Occur::Should), Occur::Should);
        assert_eq!(Occur::compose(Occur::Should, Occur::Must), Occur::Must);
        assert_eq!(
            Occur::compose(Occur::Should, Occur::MustNot),
            Occur::MustNot
        );
        assert_eq!(Occur::compose(Occur::Must, Occur::Should), Occur::Must);
        assert_eq!(Occur::compose(Occur::Must, Occur::Must), Occur::Must);
        assert_eq!(Occur::compose(Occur::Must, Occur::MustNot), Occur::MustNot);
        assert_eq!(
            Occur::compose(Occur::MustNot, Occur::Should),
            Occur::MustNot
        );
        assert_eq!(Occur::compose(Occur::MustNot, Occur::Must), Occur::MustNot);
        assert_eq!(Occur::compose(Occur::MustNot, Occur::MustNot), Occur::Must);
    }
}