dynfmt/
curly.rs

1//! Implementation for simple format strings using curly braces.
2//!
3//! See [`SimpleCurlyFormat`] for more information.
4//!
5//! [`SimpleCurlyFormat`]: struct.SimpleCurlyFormat.html
6
7use regex::{CaptureMatches, Captures, Regex};
8
9use crate::{ArgumentResult, ArgumentSpec, Error, Format, Position};
10
11lazy_static::lazy_static! {
12/// The regular expression used for parsing simple curly format strings.
13    static 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/// Format argument iterator for [`SimpleCurlyFormat`].
33///
34/// [`SimpleCurlyFormat`]: struct.SimpleCurlyFormat.html
35#[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/// Format implementation for simple curly brace based format strings.
57///
58/// This syntax is a subset of what Python 3, Rust, .NET and many logging libraries use. Each
59/// argument is formated in display mode.
60///
61///   1. `{}`: Refers to the next positional argument.
62///   2. `{0}`: Refers to the argument at index `0`.
63///   3. `{name}`: Refers to the named argument with key `"name"`.
64///
65/// # Example
66///
67/// ```rust
68/// use dynfmt::{Format, SimpleCurlyFormat};
69///
70/// let formatted = SimpleCurlyFormat.format("hello, {}", &["world"]);
71/// assert_eq!("hello, world", formatted.expect("formatting failed"));
72/// ```
73#[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}