use crate::ErrorKind;
use regex::RegexBuilder;
use std::{collections::BTreeSet, str::FromStr};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RegexFlag {
CaseInsensitive,
Global,
GreedySwap,
IgnoreWhitespaces,
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct RegexFlags(BTreeSet<RegexFlag>);
impl RegexFlags {
pub fn apply(&self, builder: &mut RegexBuilder) {
builder.case_insensitive(self.0.contains(&RegexFlag::CaseInsensitive));
builder.swap_greed(self.0.contains(&RegexFlag::GreedySwap));
builder.ignore_whitespace(self.0.contains(&RegexFlag::IgnoreWhitespaces));
}
pub fn is_global(&self) -> bool {
self.0.contains(&RegexFlag::Global)
}
}
impl<I: IntoIterator<Item = RegexFlag>> From<I> for RegexFlags {
fn from(i: I) -> Self {
RegexFlags(i.into_iter().collect())
}
}
impl FromStr for RegexFlags {
type Err = ErrorKind;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.chars()
.map(|c| match c {
'i' => Ok(RegexFlag::CaseInsensitive),
'g' => Ok(RegexFlag::Global),
'U' => Ok(RegexFlag::GreedySwap),
'x' => Ok(RegexFlag::IgnoreWhitespaces),
c => Err(ErrorKind::UnknownFlag(c)),
})
.collect::<Result<_, _>>()
.map(RegexFlags)
}
}