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

use unicode_normalization::UnicodeNormalization;

#[cfg(feature = "literals")]
use super::is_not_dtext;
use super::{ascii, is_not_atext, is_not_qcontent, AddrSpec};

/// A error that can occur when parsing or creating an address specification.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct ParseError(pub(super) &'static str, pub(super) usize);

impl ParseError {
    /// Returns a static error message.
    #[inline]
    pub fn message(&self) -> &'static str {
        self.0
    }

    /// Returns the index where the error occurred.
    #[inline]
    pub fn index(&self) -> usize {
        self.1
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "parse error at index {}: {}",
            self.message(),
            self.index()
        )
    }
}

pub struct Parser<'a> {
    input: &'a str,
    original_length: usize,
}

impl<'a> Parser<'a> {
    #[inline]
    pub fn new(address: &'a str) -> Parser<'a> {
        Parser {
            input: address,
            original_length: address.len(),
        }
    }

    #[inline]
    pub fn parse(&mut self) -> Result<AddrSpec, ParseError> {
        let local_part = self.parse_local_part()?;
        self.parse_at()?;
        let (domain, literal) = self.parse_domain()?;
        self.parse_end()?;
        Ok(AddrSpec {
            local_part,
            domain: (domain, literal),
        })
    }

    #[inline]
    fn parse_at(&mut self) -> Result<(), ParseError> {
        if !self.input.starts_with('@') {
            return Err(ParseError(
                "expected '@'",
                self.original_length - self.input.len(),
            ));
        }
        self.input = &self.input[1..];
        Ok(())
    }

    #[inline]
    fn parse_local_part(&mut self) -> Result<String, ParseError> {
        if self.input.is_empty() {
            return Err(ParseError("missing local part", 0));
        }
        if !self.input.starts_with('"') {
            return Ok(self
                .parse_dot_atom("empty local part", "empty label in local part")?
                .nfc()
                .collect());
        }
        Ok(self
            .parse_quoted_string(
                "invalid character in quoted local part",
                "expected '\"' for quoted local part",
            )?
            .nfc()
            .collect())
    }

    #[inline]
    fn parse_dot_atom(
        &mut self,
        empty_error_text: &'static str,
        empty_label_error_text: &'static str,
    ) -> Result<&str, ParseError> {
        let length = self.input.find(is_not_atext).unwrap_or(self.input.len());

        let domain = &self.input[..length];
        if domain.is_empty() {
            return Err(ParseError(empty_error_text, 0));
        }
        if domain.starts_with('.') {
            return Err(ParseError(empty_label_error_text, 0));
        }
        if domain.ends_with('.') {
            return Err(ParseError(empty_label_error_text, length));
        }
        if let Some(index) = domain.find("..") {
            return Err(ParseError(empty_label_error_text, index));
        }

        self.input = &self.input[length..];
        Ok(domain)
    }

    #[inline]
    fn parse_quoted_string(
        &mut self,
        invalid_character_error_text: &'static str,
        expected_quote_error_text: &'static str,
    ) -> Result<String, ParseError> {
        let mut escaped = false;
        for (mut length, chr) in self.input[1..].as_bytes().iter().enumerate() {
            if escaped {
                escaped = false;
            } else if *chr == b'\\' {
                escaped = true;
            } else if *chr == b'"' {
                length += 1;
                let local_part = &self.input[1..length];
                if let Some(index) = local_part.find(is_not_qcontent) {
                    return Err(ParseError(invalid_character_error_text, index));
                }
                self.input = &self.input[length + 1..];
                return Ok(ascii::unescape('\\', local_part));
            }
        }
        Err(ParseError(expected_quote_error_text, self.input.len()))
    }

    #[inline]
    fn parse_domain(&mut self) -> Result<(String, bool), ParseError> {
        if self.input.is_empty() {
            return Err(ParseError(
                "missing domain",
                self.original_length - self.input.len(),
            ));
        }
        #[cfg(feature = "literals")]
        if self.input.starts_with('[') {
            return Ok((self.parse_literal_domain()?.nfc().collect(), true));
        }
        Ok((
            self.parse_dot_atom("empty domain", "empty label in domain")?
                .nfc()
                .collect(),
            false,
        ))
    }

    #[cfg(feature = "literals")]
    #[inline]
    fn parse_literal_domain(&mut self) -> Result<&str, ParseError> {
        let length = self.input[1..]
            .find(is_not_dtext)
            .unwrap_or(self.input.len() - 1)
            + 1;

        if !self.input[length..].starts_with(']') {
            return Err(ParseError("expected ']' for literal domain", length));
        }
        let domain = &self.input[1..length];
        self.input = &self.input[length + 1..];
        Ok(domain)
    }

    #[inline]
    fn parse_end(&self) -> Result<(), ParseError> {
        if self.input.is_empty() {
            return Ok(());
        }
        Err(ParseError("expected end of address", self.input.len()))
    }
}