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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
use regex::{Captures, Match};
use std::convert::{TryFrom, TryInto};
use std::slice::Iter;
use crate::argument::{Argument, Segment};
use crate::map::Map;
use crate::value::FormattableValue;
use crate::{Align, Format, Pad, Precision, Repr, Sign, Specifier, Width};
pub trait ConvertToSize {
fn convert(&self) -> Result<usize, ()>;
}
impl<T> ConvertToSize for T
where
for<'t> &'t T: TryInto<usize, Error = ()>,
{
fn convert(&self) -> Result<usize, ()> {
self.try_into()
}
}
pub trait ValueSource<V>
where
V: FormattableValue,
{
fn next_value(&mut self) -> Option<&V>;
fn lookup_value_by_index(&self, idx: usize) -> Option<&V>;
fn lookup_value_by_name(&self, name: &str) -> Option<&V>;
}
trait Parseable<'m, V, S>
where
V: FormattableValue + ConvertToSize,
S: ValueSource<V>,
Self: Sized,
{
fn parse(capture: Option<Match<'m>>, value_src: &mut S) -> Result<Self, ()>;
}
impl<'m, V, S, T> Parseable<'m, V, S> for T
where
V: FormattableValue + ConvertToSize,
S: ValueSource<V>,
T: Sized + TryFrom<&'m str, Error = ()>,
{
fn parse(capture: Option<Match<'m>>, _: &mut S) -> Result<Self, ()> {
capture.map(|m| m.as_str()).unwrap_or("").try_into()
}
}
fn parse_size<'m, V, S>(text: &str, value_src: &S) -> Result<usize, ()>
where
V: FormattableValue + ConvertToSize,
S: ValueSource<V>,
{
if text.ends_with('$') {
let text = &text[..text.len() - 1];
let value = if text.as_bytes()[0].is_ascii_digit() {
text.parse()
.ok()
.and_then(|idx| value_src.lookup_value_by_index(idx))
} else {
value_src.lookup_value_by_name(text)
};
value.ok_or(()).and_then(ConvertToSize::convert)
} else {
text.parse().map_err(|_| ())
}
}
impl<'m, V, S> Parseable<'m, V, S> for Width
where
V: FormattableValue + ConvertToSize,
S: ValueSource<V>,
{
fn parse(capture: Option<Match<'m>>, value_src: &mut S) -> Result<Self, ()> {
match capture.map(|m| m.as_str()).unwrap_or("") {
"" => Ok(Width::Auto),
s @ _ => parse_size(s, value_src).map(|width| Width::AtLeast { width }),
}
}
}
impl<'m, V, S> Parseable<'m, V, S> for Precision
where
V: FormattableValue + ConvertToSize,
S: ValueSource<V>,
{
fn parse(capture: Option<Match<'m>>, value_src: &mut S) -> Result<Self, ()> {
match capture.map(|m| m.as_str()).unwrap_or("") {
"" => Ok(Precision::Auto),
"*" => value_src
.next_value()
.ok_or(())
.and_then(ConvertToSize::convert)
.map(|precision| Precision::Exactly { precision }),
s @ _ => parse_size(s, value_src).map(|precision| Precision::Exactly { precision }),
}
}
}
macro_rules! SPEC_REGEX_FRAG {
() => { r"
(?P<align>[<^>])?
(?P<sign>\+)?
(?P<repr>\#)?
(?P<pad>0)?
(?P<width>
(?:\d+\$?)|(?:[[:alpha:]][[:alnum:]]*\$)
)?
(?:\.(?P<precision>
(?:\d+\$?)|(?:[[:alpha:]][[:alnum:]]*\$)|\*
))?
(?P<format>[?oxXbeE])?
" };
}
fn parse_specifier_captures<V, S>(captures: &Captures, value_src: &mut S) -> Result<Specifier, ()>
where
V: FormattableValue + ConvertToSize,
S: ValueSource<V>,
{
Ok(Specifier {
align: Align::parse(captures.name("align"), value_src)?,
sign: Sign::parse(captures.name("sign"), value_src)?,
repr: Repr::parse(captures.name("repr"), value_src)?,
pad: Pad::parse(captures.name("pad"), value_src)?,
width: Width::parse(captures.name("width"), value_src)?,
precision: Precision::parse(captures.name("precision"), value_src)?,
format: Format::parse(captures.name("format"), value_src)?,
})
}
pub fn parse_specifier<V, S>(spec_str: &str, value_src: &mut S) -> Result<Specifier, ()>
where
V: FormattableValue + ConvertToSize,
S: ValueSource<V>,
{
use lazy_static::lazy_static;
use regex::Regex;
lazy_static! {
static ref SPEC_RE: Regex = Regex::new(concat!(r"(?x) ^", SPEC_REGEX_FRAG!())).unwrap();
}
match SPEC_RE.captures(spec_str) {
None => Err(()),
Some(captures) => parse_specifier_captures(&captures, value_src)
}
}
pub struct Parser<'p, V, M>
where
V: FormattableValue + ConvertToSize,
M: Map<str, V>,
{
unparsed: &'p str,
parsed_len: usize,
positional: &'p [V],
named: &'p M,
positional_iter: Iter<'p, V>,
}
impl<'p, V, M> Parser<'p, V, M>
where
V: FormattableValue + ConvertToSize,
M: Map<str, V>,
{
pub fn new(format: &'p str, positional: &'p [V], named: &'p M) -> Self {
Parser {
unparsed: format,
parsed_len: 0,
positional,
named,
positional_iter: positional.iter(),
}
}
fn advance_and_return<T>(&mut self, advance_by: usize, result: T) -> T {
self.unparsed = &self.unparsed[advance_by..];
self.parsed_len += advance_by;
result
}
fn error(&mut self) -> Result<Segment<'p, V>, usize> {
self.unparsed = "";
Err(self.parsed_len)
}
fn text_segment(&mut self, len: usize) -> Segment<'p, V> {
self.advance_and_return(len, Segment::Text(&self.unparsed[..len]))
}
fn parse_braces(&mut self) -> Result<Segment<'p, V>, usize> {
if self.unparsed.len() < 2 {
self.error()
} else if self.unparsed.as_bytes()[0] == self.unparsed.as_bytes()[1] {
Ok(self.advance_and_return(2, Segment::Text(&self.unparsed[..1])))
} else {
self.parse_argument()
}
}
fn parse_argument(&mut self) -> Result<Segment<'p, V>, usize> {
use lazy_static::lazy_static;
use regex::Regex;
lazy_static! {
static ref ARG_RE: Regex = Regex::new(
concat!(
r"(?x)
^
\{
(?:(?P<index>\d+)|(?P<name>[[:alpha:]][[:alnum:]]*))?
(?:
:
",
SPEC_REGEX_FRAG!(),
r"
)?
\}"
)
)
.unwrap();
}
match ARG_RE.captures(self.unparsed) {
None => self.error(),
Some(captures) => match parse_specifier_captures(&captures, self) {
Ok(specifier) => self
.lookup_value(&captures)
.ok_or(())
.and_then(|value| Argument::new(specifier, value))
.map(|arg| {
self.advance_and_return(
captures.get(0).unwrap().end(),
Segment::Argument(arg),
)
})
.or_else(|_| self.error()),
Err(_) => self.error(),
},
}
}
fn next_value(&mut self) -> Option<&'p V> {
self.positional_iter.next()
}
fn lookup_value_by_index(&self, idx: usize) -> Option<&'p V> {
self.positional.get(idx)
}
fn lookup_value_by_name(&self, name: &str) -> Option<&'p V> {
self.named.get(name)
}
fn lookup_value(&mut self, captures: &Captures) -> Option<&'p V> {
if let Some(idx) = captures.name("index") {
idx.as_str()
.parse::<usize>()
.ok()
.and_then(|idx| self.lookup_value_by_index(idx))
} else if let Some(name) = captures.name("name") {
self.lookup_value_by_name(name.as_str())
} else {
self.next_value()
}
}
}
impl<'p, V, M> ValueSource<V> for Parser<'p, V, M>
where
V: FormattableValue + ConvertToSize,
M: Map<str, V>,
{
fn next_value(&mut self) -> Option<&V> {
(self as &mut Parser<'p, V, M>).next_value()
}
fn lookup_value_by_index(&self, idx: usize) -> Option<&V> {
(self as &Parser<'p, V, M>).lookup_value_by_index(idx)
}
fn lookup_value_by_name(&self, name: &str) -> Option<&V> {
(self as &Parser<'p, V, M>).lookup_value_by_name(name)
}
}
impl<'p, V, M> Iterator for Parser<'p, V, M>
where
V: FormattableValue + ConvertToSize,
M: Map<str, V>,
{
type Item = Result<Segment<'p, V>, usize>;
fn next(&mut self) -> Option<Self::Item> {
static BRACES: &[char] = &['{', '}'];
if self.unparsed.len() == 0 {
return None;
}
match self.unparsed.find(BRACES) {
None => Some(Ok(self.text_segment(self.unparsed.len()))),
Some(0) => Some(self.parse_braces()),
Some(brace_idx) => Some(Ok(self.text_segment(brace_idx))),
}
}
}