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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
//! Matcher that can be applied on a list of [OccurrenceRef].
use std::fmt::{self, Display};
use winnow::combinator::{alt, empty, preceded, separated_pair};
use winnow::prelude::*;
use super::ParseMatcherError;
use crate::primitives::parse::parse_occurrence_ref;
use crate::primitives::{Occurrence, OccurrenceRef};
/// A matcher that matches against a [OccurrenceRef].
#[derive(Debug, Clone, PartialEq)]
pub enum OccurrenceMatcher {
Exact(Occurrence),
Range(Occurrence, Occurrence),
None,
Any,
}
impl OccurrenceMatcher {
/// Creates a new [OccurrenceMatcher].
///
/// # Errors
///
/// This function fails if the given expression is not a valid
/// occurrence matcher.
///
/// # Example
///
/// ```rust
/// use pica_record::matcher::OccurrenceMatcher;
///
/// let _matcher = OccurrenceMatcher::new("/01")?;
/// let _matcher = OccurrenceMatcher::new("/01-09")?;
/// let _matcher = OccurrenceMatcher::new("/001")?;
/// let _matcher = OccurrenceMatcher::new("/*")?;
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn new(matcher: &str) -> Result<Self, ParseMatcherError> {
parse_occurrence_matcher.parse(matcher.as_bytes()).map_err(
|_| {
ParseMatcherError(format!(
"invalid occurrence matcher '{matcher}'"
))
},
)
}
/// Returns `true` if the given occurrence matches against the
/// matcher.
///
/// # Example
///
/// ```rust
/// use pica_record::matcher::OccurrenceMatcher;
/// use pica_record::primitives::OccurrenceRef;
///
/// let matcher = OccurrenceMatcher::new("/01-03")?;
/// assert!(matcher.is_match(Some(&OccurrenceRef::new("02")?)));
/// assert!(!matcher.is_match(Some(&OccurrenceRef::new("04")?)));
///
/// let matcher = OccurrenceMatcher::new("/*")?;
/// assert!(matcher.is_match(None));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn is_match(&self, other: Option<&OccurrenceRef>) -> bool {
match other {
None => matches!(self, Self::Any | Self::None),
Some(occ) => match self {
Self::Any => true,
Self::None => occ == b"00",
Self::Exact(rhs) => occ == rhs,
Self::Range(min, max) => {
(occ.as_bytes() >= min.as_bytes())
&& (occ.as_bytes() <= max.as_bytes())
}
},
}
}
}
impl Display for OccurrenceMatcher {
/// Formats a [OccurrenceMatcher] as a human-readable string.
///
/// # Example
///
/// ```rust
/// use pica_record::matcher::OccurrenceMatcher;
///
/// let matcher = OccurrenceMatcher::new("/01-03")?;
/// assert_eq!(matcher.to_string(), "/01-03");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Exact(o) => write!(f, "/{o}")?,
Self::Range(min, max) => write!(f, "/{min}-{max}")?,
Self::Any => write!(f, "/*")?,
Self::None => (),
}
Ok(())
}
}
#[inline]
fn parse_occurrence_matcher_inner(
i: &mut &[u8],
) -> PResult<Occurrence> {
parse_occurrence_ref.map(Occurrence::from).parse_next(i)
}
#[inline]
fn parse_occurrence_matcher_exact(
i: &mut &[u8],
) -> PResult<OccurrenceMatcher> {
parse_occurrence_matcher_inner
.verify(|occurrence| occurrence.as_bytes() != b"00")
.map(OccurrenceMatcher::Exact)
.parse_next(i)
}
#[inline]
fn parse_occurrence_matcher_range(
i: &mut &[u8],
) -> PResult<OccurrenceMatcher> {
separated_pair(
parse_occurrence_matcher_inner,
'-',
parse_occurrence_matcher_inner,
)
.verify(|(min, max)| min.len() == max.len() && min < max)
.map(|(min, max)| OccurrenceMatcher::Range(min, max))
.parse_next(i)
}
pub(crate) fn parse_occurrence_matcher(
i: &mut &[u8],
) -> PResult<OccurrenceMatcher> {
alt((
preceded(
'/',
alt((
parse_occurrence_matcher_range,
parse_occurrence_matcher_exact,
"00".value(OccurrenceMatcher::None),
"*".value(OccurrenceMatcher::Any),
)),
),
empty.value(OccurrenceMatcher::None),
))
.parse_next(i)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_occurrence_matcher() -> anyhow::Result<()> {
macro_rules! parse_success {
($i:expr, $o:expr) => {
let o = parse_occurrence_matcher
.parse($i.as_bytes())
.unwrap();
assert_eq!(o.to_string(), $i);
assert_eq!(o, $o);
};
}
parse_success!("", OccurrenceMatcher::None);
parse_success!("/*", OccurrenceMatcher::Any);
parse_success!(
"/01",
OccurrenceMatcher::Exact(Occurrence::new("01")?)
);
parse_success!(
"/999",
OccurrenceMatcher::Exact(Occurrence::new("999")?)
);
parse_success!(
"/01-99",
OccurrenceMatcher::Range(
Occurrence::new("01")?,
Occurrence::new("99")?
)
);
parse_success!(
"/01-99",
OccurrenceMatcher::Range(
Occurrence::new("01")?,
Occurrence::new("99")?
)
);
assert_eq!(
parse_occurrence_matcher.parse(b"/00").unwrap(),
OccurrenceMatcher::None
);
Ok(())
}
}