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
use regex::RegexBuilder;
use std::collections::BTreeSet;
use std::str::FromStr;
use ErrorKind;
#[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)
}
}