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
use std::{
    error::Error,
    fmt::{Display, Formatter, Result as FmtResult},
    num::ParseIntError,
};

/// Parsing a mention failed due to invalid syntax.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParseMentionError<'a> {
    /// ID portion of the mention isn't a u64.
    IdNotU64 {
        /// String that could not be parsed into a u64.
        found: &'a str,
        /// Reason for the error.
        source: ParseIntError,
    },
    /// Leading arrow (`<`) is not present.
    LeadingArrow {
        /// Character that was instead found where the leading arrow should be.
        found: Option<char>,
    },
    /// One or more parts of the mention are missing.
    ///
    /// For example, an emoji mention - `<:name:id>` - has two parts: the `name`
    /// and the `id`, separated by the sigil (`:`). If the second sigil denoting
    /// the second part can't be found, then it is missing.
    PartMissing {
        /// Number of parts that are expected.
        expected: usize,
        /// Number of parts that have been found.
        found: usize,
    },
    /// Mention's sigil is not present.
    ///
    /// Users, for example, have the sigil `@`.
    Sigil {
        /// Possible sigils that were expected for the mention type.
        expected: &'a [&'a str],
        /// Character that was instead found where the sigil should be.
        found: Option<char>,
    },
    /// Trailing arrow (`>`) is not present.
    TrailingArrow {
        /// Character that was instead found where the trailing arrow should be.
        found: Option<char>,
    },
}

impl Display for ParseMentionError<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match self {
            Self::IdNotU64 { found, .. } => f.write_fmt(format_args!(
                "id portion ('{}') of mention is not a u64",
                found,
            )),
            Self::LeadingArrow { found } => {
                f.write_str("expected to find a leading arrow ('<') but instead ")?;

                if let Some(c) = found {
                    f.write_fmt(format_args!("found '{}'", c))
                } else {
                    f.write_str("found nothing")
                }
            }
            Self::PartMissing { expected, found } => f.write_fmt(format_args!(
                "
                    expected {} parts but only found {}",
                expected, found,
            )),
            Self::Sigil { expected, found } => {
                f.write_str("expected to find a mention sigil (")?;

                for (idx, sigil) in expected.iter().enumerate() {
                    f.write_fmt(format_args!("'{}'", sigil))?;

                    if idx < expected.len() - 1 {
                        f.write_str(", ")?;
                    }
                }

                f.write_str(") but instead found ")?;

                if let Some(c) = found {
                    f.write_fmt(format_args!("'{}'", c))
                } else {
                    f.write_str("nothing")
                }
            }
            Self::TrailingArrow { found } => {
                f.write_str("expected to find a trailing arrow ('>') but instead ")?;

                if let Some(c) = found {
                    f.write_fmt(format_args!("found '{}'", c))
                } else {
                    f.write_str("found nothing")
                }
            }
        }
    }
}

impl Error for ParseMentionError<'_> {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::IdNotU64 { source, .. } => Some(source),
            Self::LeadingArrow { .. }
            | Self::PartMissing { .. }
            | Self::Sigil { .. }
            | Self::TrailingArrow { .. } => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::ParseMentionError;
    use static_assertions::{assert_fields, assert_impl_all};
    use std::{error::Error, fmt::Debug};

    assert_fields!(ParseMentionError::IdNotU64: found, source);
    assert_fields!(ParseMentionError::LeadingArrow: found);
    assert_fields!(ParseMentionError::Sigil: expected, found);
    assert_fields!(ParseMentionError::TrailingArrow: found);
    assert_impl_all!(ParseMentionError<'_>: Clone, Debug, Error, Eq, PartialEq, Send, Sync);

    #[test]
    fn test_display() {
        let mut expected = "id portion ('abcd') of mention is not a u64";
        assert_eq!(
            expected,
            ParseMentionError::IdNotU64 {
                found: "abcd",
                source: "abcd".parse::<u64>().unwrap_err(),
            }
            .to_string(),
        );
        expected = "expected to find a leading arrow ('<') but instead found 'a'";
        assert_eq!(
            expected,
            ParseMentionError::LeadingArrow { found: Some('a') }.to_string(),
        );

        expected = "expected to find a leading arrow ('<') but instead found nothing";
        assert_eq!(
            expected,
            ParseMentionError::LeadingArrow { found: None }.to_string(),
        );

        expected = "expected to find a mention sigil ('@') but instead found '#'";
        assert_eq!(
            expected,
            ParseMentionError::Sigil {
                expected: &["@"],
                found: Some('#')
            }
            .to_string(),
        );

        expected = "expected to find a mention sigil ('@') but instead found nothing";
        assert_eq!(
            expected,
            ParseMentionError::Sigil {
                expected: &["@"],
                found: None
            }
            .to_string(),
        );

        expected = "expected to find a mention sigil ('@!', '@') but instead found '#'";
        assert_eq!(
            expected,
            ParseMentionError::Sigil {
                expected: &["@!", "@"],
                found: Some('#'),
            }
            .to_string(),
        );

        expected = "expected to find a mention sigil ('@!', '@') but instead found nothing";
        assert_eq!(
            expected,
            ParseMentionError::Sigil {
                expected: &["@!", "@"],
                found: None
            }
            .to_string(),
        );

        expected = "expected to find a trailing arrow ('>') but instead found 'a'";
        assert_eq!(
            expected,
            ParseMentionError::TrailingArrow { found: Some('a') }.to_string(),
        );

        expected = "expected to find a trailing arrow ('>') but instead found nothing";
        assert_eq!(
            expected,
            ParseMentionError::TrailingArrow { found: None }.to_string(),
        );
    }
}