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
use std::ops::Index;
use std::sync::Arc;
use std::collections::HashMap;
use util::typemap::Key;
use regex::Captures;
pub struct Parameters {
text: String,
matches: Vec<Option<(usize, usize)>>,
names: Arc<HashMap<String, usize>>,
}
impl Parameters {
pub(crate) fn new(names: Arc<HashMap<String, usize>>, text: &str, captures: Captures) -> Self {
Self {
names,
text: text.into(),
matches: captures
.iter()
.map(|capture| capture.map(|m| (m.start(), m.end())))
.collect(),
}
}
pub fn get(&self, index: usize) -> Option<&str> {
self.matches
.get(index + 1)
.and_then(|m| m.map(|(start, end)| &self.text[start..end]))
}
pub fn name(&self, name: &str) -> Option<&str> {
self.names.get(name).and_then(|&i| self.get(i - 1))
}
}
impl Key for Parameters {
type Value = Self;
}
impl Index<usize> for Parameters {
type Output = str;
fn index(&self, index: usize) -> &Self::Output {
self.get(index)
.unwrap_or_else(|| panic!("no parameter at index '{}'", index))
}
}
impl<'b> Index<&'b str> for Parameters {
type Output = str;
fn index<'a>(&'a self, name: &str) -> &'a str {
self.name(name)
.unwrap_or_else(|| panic!("no parameter named '{}'", name))
}
}