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
use std::fmt::Alignment;

use lazy_regex::regex;

use crate::{Error, Result};

#[derive(Debug)]
pub(crate) struct Parameter<'s> {
    pub position: Option<ParameterPosition<'s>>,
    pub hint: DisplayHint,
}

impl<'s> Parameter<'s> {
    pub(crate) fn parse(param: &'s str) -> Result<Self> {
        let re = regex!(
            r"((?<position>\d+)|(?<named>[\d\w]+))?(:(?<align>[<\^>])?(?<sign>\+)?(?<alternate>#)?(?<zero_pad>0)?(?<width>\d+)?(\.(?<precision>\d+))?(?<type>[b\?exopeEX])?)?"
        );

        let captures = re.captures(&param);

        if captures.is_none() {
            return Ok(Self {
                position: None,
                hint: DisplayHint {
                    align: None,
                    sign: false,
                    alternate: false,
                    zero_pad: false,
                    width: None,
                    precision: None,
                    ty: DisplayType::Display,
                },
            });
        }

        // Unwrap safety: returned earlier if captures is none.
        let captures = captures.unwrap();

        let position = if let Some(p) = captures.name("position") {
            Some(ParameterPosition::Positional(p.as_str().parse().unwrap()))
        } else if let Some(n) = captures.name("named") {
            Some(ParameterPosition::Named(n.as_str()))
        } else {
            None
        };

        let align = captures.name("align").and_then(|a| {
            Some(match a.as_str() {
                "<" => Alignment::Left,
                "^" => Alignment::Center,
                ">" => Alignment::Right,
                _ => unreachable!("Regex should only capture valid values"),
            })
        });

        let sign = captures.name("sign").is_some();
        let alternate = captures.name("alternate").is_some();
        let zero_pad = captures.name("zero_pad").is_some();
        let width = captures
            .name("width")
            .and_then(|w| Some(w.as_str().parse().unwrap()));
        let precision = captures
            .name("precision")
            .and_then(|w| Some(w.as_str().parse().unwrap()));
        let ty = captures
            .name("type")
            .and_then(|ty| {
                Some(match ty.as_str() {
                    "b" => DisplayType::Binary,
                    "?" => DisplayType::Debug,
                    "e" => DisplayType::LowerExp,
                    "x" => DisplayType::LowerHex,
                    "o" => DisplayType::Octal,
                    "p" => DisplayType::Pointer,
                    "E" => DisplayType::UpperExp,
                    "X" => DisplayType::UpperHex,
                    _ => unreachable!("Regex should only capture valid values"),
                })
            })
            .unwrap_or(DisplayType::Display);

        Ok(Self {
            position,
            hint: DisplayHint {
                align,
                sign,
                alternate,
                zero_pad,
                width,
                precision,
                ty,
            },
        })
    }
}

#[derive(Debug)]
pub enum ParameterPosition<'s> {
    Positional(usize),
    Named(&'s str),
}

#[derive(Debug)]
pub enum DisplayType {
    Binary,
    Debug,
    Display,
    LowerExp,
    LowerHex,
    Octal,
    Pointer,
    UpperExp,
    UpperHex,
}

#[derive(Debug)]
pub struct DisplayHint {
    pub align: Option<std::fmt::Alignment>,
    pub sign: bool,
    pub alternate: bool,
    pub zero_pad: bool,
    pub width: Option<usize>,
    pub precision: Option<usize>,
    pub ty: DisplayType,
}

pub(crate) enum FormatStringFragment<'s> {
    Parameter(Parameter<'s>),
    Error(&'s str, Error),
    Escaped(char),
    Literal(&'s str),
}

pub(crate) struct FormatStringFragmentIterator<'s> {
    format_string: &'s str,
}

impl<'s> FormatStringFragmentIterator<'s> {
    pub fn new(format_string: &'s str) -> Self {
        Self { format_string }
    }
}

impl<'s> Iterator for FormatStringFragmentIterator<'s> {
    type Item = FormatStringFragment<'s>;

    fn next(&mut self) -> Option<Self::Item> {
        // Exhausted iterator
        if self.format_string.is_empty() {
            return None;
        }

        // Escaped opening braces.
        if self.format_string.starts_with("{{") {
            self.format_string = self.format_string.get(2..).unwrap_or("");
            return Some(FormatStringFragment::Escaped('{'));
        }

        // Non-escaped opening brace, try to find closing brace or error.
        if self.format_string.starts_with('{') {
            return match self.format_string.find('}') {
                Some(index) => {
                    let hint = &self.format_string[1..index];
                    self.format_string = self.format_string.get(index + 1..).unwrap_or("");
                    Some(FormatStringFragment::Parameter(
                        Parameter::parse(hint).unwrap(),
                    ))
                }
                None => {
                    let result = self.format_string;
                    self.format_string = "";
                    Some(FormatStringFragment::Error(
                        result,
                        Error::Custom("Malformed format string: missing closing brace"),
                    ))
                }
            };
        }

        // Regular literal.
        match self.format_string.find('{') {
            // Found opening brace, return substring until the brace and update self to start at brace.
            Some(index) => {
                let result = &self.format_string[..index];
                self.format_string = &self.format_string[index..];
                Some(FormatStringFragment::Literal(result))
            }
            // No opening brace, return entire format string.
            None => {
                let result = self.format_string;
                self.format_string = "";
                Some(FormatStringFragment::Literal(result))
            }
        }
    }
}