1use regex::{CaptureMatches, Captures, Regex};
8
9use crate::{ArgumentResult, ArgumentSpec, Error, Format, Position};
10
11lazy_static::lazy_static! {
12static ref PYTHON_RE: Regex = Regex::new(r"\{(?P<key>\w+)?\}").unwrap();
14}
15
16fn parse_position(key: &str) -> Position<'_> {
17 key.parse()
18 .map(Position::Index)
19 .unwrap_or_else(|_| Position::Key(key))
20}
21
22fn parse_next(captures: Captures<'_>) -> ArgumentSpec<'_> {
23 let position = captures
24 .name("key")
25 .map(|m| parse_position(m.as_str()))
26 .unwrap_or_else(|| Position::Auto);
27
28 let group = captures.get(0).unwrap();
29 ArgumentSpec::new(group.start(), group.end()).with_position(position)
30}
31
32#[derive(Debug)]
36pub struct SimpleCurlyIter<'f> {
37 captures: CaptureMatches<'static, 'f>,
38}
39
40impl<'f> SimpleCurlyIter<'f> {
41 fn new(format: &'f str) -> Self {
42 SimpleCurlyIter {
43 captures: PYTHON_RE.captures_iter(format),
44 }
45 }
46}
47
48impl<'f> Iterator for SimpleCurlyIter<'f> {
49 type Item = ArgumentResult<'f>;
50
51 fn next(&mut self) -> Option<Self::Item> {
52 self.captures.next().map(|capture| Ok(parse_next(capture)))
53 }
54}
55
56#[derive(Debug)]
74pub struct SimpleCurlyFormat;
75
76impl<'f> Format<'f> for SimpleCurlyFormat {
77 type Iter = SimpleCurlyIter<'f>;
78
79 fn iter_args(&self, format: &'f str) -> Result<Self::Iter, Error<'f>> {
80 Ok(SimpleCurlyIter::new(format))
81 }
82}