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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
use super::{MentionIter, MentionType, ParseMentionError};
use std::str::Chars;
use twilight_model::id::{ChannelId, EmojiId, RoleId, UserId};

/// Parse mentions out of buffers.
///
/// While the syntax of mentions will be validated and the IDs within them
/// parsed, they won't be validated as being proper snowflakes or as real IDs in
/// use.
///
/// **Note** that this trait is sealed and is not meant to be manually
/// implemented.
pub trait ParseMention: private::Sealed {
    /// Leading sigil(s) of the mention after the leading arrow (`<`).
    ///
    /// In a channel mention, the sigil is `#`. In the case of a user mention,
    /// the sigil may be either `@` or `@!`.
    const SIGILS: &'static [&'static str];

    /// Parse a mention out of a buffer.
    ///
    /// This will not search the buffer for a mention and will instead treat the
    /// entire buffer as a mention.
    ///
    /// # Examples
    ///
    /// ```
    /// use twilight_mention::ParseMention;
    /// use twilight_model::id::{ChannelId, UserId};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// assert_eq!(ChannelId(123), ChannelId::parse("<#123>")?);
    /// assert_eq!(UserId(456), UserId::parse("<@456>")?);
    /// assert!(ChannelId::parse("not a mention").is_err());
    /// # Ok(()) }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`ParseMentionError::LeadingArrow`] if the leading arrow is not
    /// present.
    ///
    /// Returns [`ParseMentionError::Sigil`] if the mention type's sigil is not
    /// present after the leading arrow.
    ///
    /// Returns [`ParseMentionError::TrailingArrow`] if the trailing arrow is
    /// not present after the ID.
    fn parse(buf: &str) -> Result<Self, ParseMentionError<'_>>
    where
        Self: Sized;

    /// Search a buffer for mentions and parse out any that are encountered.
    ///
    /// Unlike [`parse`], this will not error if anything that is indicative of
    /// a mention is encountered but did not successfully parse, such as a `<`
    /// but with no trailing mention sigil.
    ///
    /// [`parse`]: Self::parse
    #[must_use = "you must use the iterator to lazily parse mentions"]
    fn iter(buf: &str) -> MentionIter<'_, Self>
    where
        Self: Sized,
    {
        MentionIter::new(buf)
    }
}

impl ParseMention for ChannelId {
    const SIGILS: &'static [&'static str] = &["#"];

    fn parse(buf: &str) -> Result<Self, ParseMentionError<'_>>
    where
        Self: Sized,
    {
        parse_id(buf, Self::SIGILS).map(|(id, _)| ChannelId(id))
    }
}

impl ParseMention for EmojiId {
    const SIGILS: &'static [&'static str] = &[":"];

    fn parse(buf: &str) -> Result<Self, ParseMentionError<'_>>
    where
        Self: Sized,
    {
        parse_id(buf, Self::SIGILS).map(|(id, _)| EmojiId(id))
    }
}

impl ParseMention for MentionType {
    /// Sigils for any type of mention.
    ///
    /// Contains all of the sigils of every other type of mention.
    const SIGILS: &'static [&'static str] = &["#", ":", "@&", "@!", "@"];

    fn parse(buf: &str) -> Result<Self, ParseMentionError<'_>>
    where
        Self: Sized,
    {
        let (id, found) = parse_id(buf, Self::SIGILS)?;

        for sigil in ChannelId::SIGILS {
            if *sigil == found {
                return Ok(MentionType::Channel(ChannelId(id)));
            }
        }

        for sigil in EmojiId::SIGILS {
            if *sigil == found {
                return Ok(MentionType::Emoji(EmojiId(id)));
            }
        }

        for sigil in RoleId::SIGILS {
            if *sigil == found {
                return Ok(MentionType::Role(RoleId(id)));
            }
        }

        for sigil in UserId::SIGILS {
            if *sigil == found {
                return Ok(MentionType::User(UserId(id)));
            }
        }

        unreachable!("mention type must have been found");
    }
}

impl ParseMention for RoleId {
    const SIGILS: &'static [&'static str] = &["@&"];

    fn parse(buf: &str) -> Result<Self, ParseMentionError<'_>>
    where
        Self: Sized,
    {
        parse_id(buf, Self::SIGILS).map(|(id, _)| RoleId(id))
    }
}

impl ParseMention for UserId {
    /// Sigils for User ID mentions.
    ///
    /// Unlike other IDs, user IDs have two possible sigils: `@!` and `@`.
    const SIGILS: &'static [&'static str] = &["@!", "@"];

    fn parse(buf: &str) -> Result<Self, ParseMentionError<'_>>
    where
        Self: Sized,
    {
        parse_id(buf, Self::SIGILS).map(|(id, _)| UserId(id))
    }
}

/// # Errors
///
/// Returns [`ParseMentionError::LeadingArrow`] if the leading arrow is not
/// present.
///
/// Returns [`ParseMentionError::Sigil`] if the mention type's sigil is not
/// present after the leading arrow.
///
/// Returns [`ParseMentionError::TrailingArrow`] if the trailing arrow is not
/// present after the ID.
fn parse_id<'a>(
    buf: &'a str,
    sigils: &'a [&'a str],
) -> Result<(u64, &'a str), ParseMentionError<'a>> {
    let mut chars = buf.chars();

    let c = chars.next();

    if c.map_or(true, |c| c != '<') {
        return Err(ParseMentionError::LeadingArrow { found: c });
    }

    let maybe_sigil = sigils.iter().find(|sigil| {
        if chars.as_str().starts_with(*sigil) {
            for _ in 0..sigil.chars().count() {
                chars.next();
            }

            return true;
        }

        false
    });

    let sigil = if let Some(sigil) = maybe_sigil {
        *sigil
    } else {
        return Err(ParseMentionError::Sigil {
            expected: sigils,
            found: chars.next(),
        });
    };

    if sigil == ":" && !emoji_sigil_present(&mut chars) {
        return Err(ParseMentionError::PartMissing {
            found: 1,
            expected: 2,
        });
    }

    let remaining = chars
        .as_str()
        .find('>')
        .and_then(|idx| chars.as_str().get(..idx))
        .ok_or(ParseMentionError::TrailingArrow { found: None })?;

    remaining
        .parse()
        .map(|id| (id, sigil))
        .map_err(|source| ParseMentionError::IdNotU64 {
            found: remaining,
            source,
        })
}

// Don't use `Iterator::skip_while` so we can mutate `chars` in-place;
// `skip_while` is consuming.
fn emoji_sigil_present(chars: &mut Chars<'_>) -> bool {
    for c in chars {
        if c == ':' {
            return true;
        }
    }

    false
}

/// Rust doesn't allow leaking private implementations, but if we make the trait
/// public in a private scope then it gets by the restriction and doesn't allow
/// Sealed to be named.
///
/// Yes, this is the correct way of sealing a trait:
///
/// <https://rust-lang.github.io/api-guidelines/future-proofing.html>
mod private {
    use super::super::MentionType;
    use twilight_model::id::{ChannelId, EmojiId, RoleId, UserId};

    pub trait Sealed {}

    impl Sealed for ChannelId {}
    impl Sealed for EmojiId {}
    impl Sealed for MentionType {}
    impl Sealed for RoleId {}
    impl Sealed for UserId {}
}

#[cfg(test)]
mod tests {
    use super::{
        super::{MentionType, ParseMentionError},
        private::Sealed,
        ParseMention,
    };
    use static_assertions::assert_impl_all;
    use twilight_model::id::{ChannelId, EmojiId, RoleId, UserId};

    assert_impl_all!(ChannelId: ParseMention, Sealed);
    assert_impl_all!(EmojiId: ParseMention, Sealed);
    assert_impl_all!(MentionType: ParseMention, Sealed);
    assert_impl_all!(RoleId: ParseMention, Sealed);
    assert_impl_all!(UserId: ParseMention, Sealed);

    #[test]
    fn test_sigils() {
        assert_eq!(&["#"], ChannelId::SIGILS);
        assert_eq!(&[":"], EmojiId::SIGILS);
        assert_eq!(&["#", ":", "@&", "@!", "@"], MentionType::SIGILS);
        assert_eq!(&["@&"], RoleId::SIGILS);
        assert_eq!(&["@!", "@"], UserId::SIGILS);
    }

    #[test]
    fn test_parse_channel_id() {
        assert_eq!(ChannelId(123), ChannelId::parse("<#123>").unwrap());
        assert_eq!(
            ParseMentionError::Sigil {
                expected: &["#"],
                found: Some('@'),
            },
            ChannelId::parse("<@123>").unwrap_err(),
        );
    }

    #[test]
    fn test_parse_emoji_id() {
        assert_eq!(EmojiId(123), EmojiId::parse("<:name:123>").unwrap());
        assert_eq!(
            ParseMentionError::Sigil {
                expected: &[":"],
                found: Some('@'),
            },
            EmojiId::parse("<@123>").unwrap_err(),
        );
    }

    #[test]
    fn test_parse_mention_type() {
        assert_eq!(
            MentionType::Channel(ChannelId(123)),
            MentionType::parse("<#123>").unwrap()
        );
        assert_eq!(
            MentionType::Emoji(EmojiId(123)),
            MentionType::parse("<:name:123>").unwrap()
        );
        assert_eq!(
            MentionType::Role(RoleId(123)),
            MentionType::parse("<@&123>").unwrap()
        );
        assert_eq!(
            MentionType::User(UserId(123)),
            MentionType::parse("<@123>").unwrap()
        );
        assert_eq!(
            ParseMentionError::Sigil {
                expected: &["#", ":", "@&", "@!", "@"],
                found: Some(';'),
            },
            MentionType::parse("<;123>").unwrap_err(),
        );
    }

    #[test]
    fn test_parse_role_id() {
        assert_eq!(RoleId(123), RoleId::parse("<@&123>").unwrap());
        assert_eq!(
            ParseMentionError::Sigil {
                expected: &["@&"],
                found: Some('@'),
            },
            RoleId::parse("<@123>").unwrap_err(),
        );
    }

    #[test]
    fn test_parse_user_id() {
        assert_eq!(UserId(123), UserId::parse("<@123>").unwrap());
        assert_eq!(
            ParseMentionError::IdNotU64 {
                found: "&123",
                source: "&123".parse::<u64>().unwrap_err(),
            },
            UserId::parse("<@&123>").unwrap_err(),
        );
    }

    #[test]
    fn test_parse_id_wrong_sigil() {
        assert_eq!(
            ParseMentionError::Sigil {
                expected: &["@"],
                found: Some('#'),
            },
            super::parse_id("<#123>", &["@"]).unwrap_err(),
        );
        assert_eq!(
            ParseMentionError::Sigil {
                expected: &["#"],
                found: None,
            },
            super::parse_id("<", &["#"]).unwrap_err(),
        );
        assert_eq!(
            ParseMentionError::Sigil {
                expected: &["#"],
                found: None,
            },
            super::parse_id("<", &["#"]).unwrap_err(),
        );
    }
}