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
use regex::{CaptureMatches, Captures, Regex};
use crate::{ArgumentResult, ArgumentSpec, Error, Format, Position};
lazy_static::lazy_static! {
static ref PYTHON_RE: Regex = Regex::new(r"\{(?P<key>\w+)?\}").unwrap();
}
fn parse_position(key: &str) -> Position<'_> {
key.parse()
.map(Position::Index)
.unwrap_or_else(|_| Position::Key(key))
}
fn parse_next(captures: Captures<'_>) -> ArgumentSpec<'_> {
let position = captures
.name("key")
.map(|m| parse_position(m.as_str()))
.unwrap_or_else(|| Position::Auto);
let group = captures.get(0).unwrap();
ArgumentSpec::new(group.start(), group.end()).with_position(position)
}
#[derive(Debug)]
pub struct SimpleCurlyIter<'f> {
captures: CaptureMatches<'static, 'f>,
}
impl<'f> SimpleCurlyIter<'f> {
fn new(format: &'f str) -> Self {
SimpleCurlyIter {
captures: PYTHON_RE.captures_iter(format),
}
}
}
impl<'f> Iterator for SimpleCurlyIter<'f> {
type Item = ArgumentResult<'f>;
fn next(&mut self) -> Option<Self::Item> {
self.captures.next().map(|capture| Ok(parse_next(capture)))
}
}
#[derive(Debug)]
pub struct SimpleCurlyFormat;
impl<'f> Format<'f> for SimpleCurlyFormat {
type Iter = SimpleCurlyIter<'f>;
fn iter_args(&self, format: &'f str) -> Result<Self::Iter, Error<'f>> {
Ok(SimpleCurlyIter::new(format))
}
}