use unicode_normalization::UnicodeNormalization as _;
use unicode_normalization::char::is_combining_mark;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum StringMatch {
#[default]
Start,
Contains,
Exact,
}
impl StringMatch {
#[must_use]
pub fn from_modifier(modifier: Option<&str>) -> Option<Self> {
match modifier {
None => Some(Self::Start),
Some("contains") => Some(Self::Contains),
Some("exact") => Some(Self::Exact),
Some(_) => None,
}
}
#[must_use]
pub const fn modifier(self) -> Option<&'static str> {
match self {
Self::Start => None,
Self::Contains => Some("contains"),
Self::Exact => Some("exact"),
}
}
#[must_use]
pub fn matches(self, field: &str, value: &str) -> bool {
match self {
Self::Start => fold(field).starts_with(&fold(value)),
Self::Contains => fold(field).contains(&fold(value)),
Self::Exact => field == value,
}
}
}
#[must_use]
pub fn fold(text: &str) -> String {
let mut folded = String::with_capacity(text.len());
let mut gap = false;
for character in text
.nfd()
.filter(|character| !is_combining_mark(*character))
{
if character.is_whitespace() {
gap = true;
} else if character.is_alphanumeric() {
if gap && !folded.is_empty() {
folded.push(' ');
}
gap = false;
folded.extend(character.to_lowercase());
}
}
folded
}