twilight_mention/parse/mod.rs
1//! Parse mentions out of strings.
2//!
3//! Included is a trait over select IDs that can be mentioned and an iterator
4//! to lazily parse mentions.
5//!
6//! There is also the [`MentionType`]: it's an enum wrapping all possible types
7//! of mentions and works just like the individual IDs and [`Timestamp`].
8//!
9//! While the syntax of mentions will be validated and the IDs within them
10//! parsed, they won't be validated as being proper snowflakes or as real IDs in
11//! use.
12//!
13//! # Examples
14//!
15//! Parse IDs out of strings that you know is just a mention:
16//!
17//! ```
18//! use twilight_mention::ParseMention;
19//! use twilight_model::id::{
20//! marker::{ChannelMarker, EmojiMarker, RoleMarker},
21//! Id,
22//! };
23//!
24//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
25//! assert_eq!(Id::<EmojiMarker>::new(123), Id::parse("<:name:123>")?);
26//! assert_eq!(Id::<RoleMarker>::new(456), Id::parse("<@&456>")?);
27//! assert!(Id::<ChannelMarker>::parse("<#notamention>").is_err());
28//! # Ok(()) }
29//! ```
30//!
31//! Iterate over the user mentions in a buffer:
32//!
33//! ```
34//! use twilight_mention::ParseMention;
35//! use twilight_model::id::{marker::UserMarker, Id};
36//!
37//! let mut iter = Id::<UserMarker>::iter("these <@123> are <#456> mentions <@789>");
38//! assert!(matches!(iter.next(), Some((user, _, _)) if user.get() == 123));
39//! assert!(matches!(iter.next(), Some((user, _, _)) if user.get() == 789));
40//! assert!(iter.next().is_none());
41//! ```
42//!
43//! Parse a timestamp:
44//!
45//! ```
46//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
47//! use twilight_mention::{
48//! parse::ParseMention,
49//! timestamp::{Timestamp, TimestampStyle},
50//! };
51//!
52//! let expected_timestamp = Timestamp::new(1_600_000_000, Some(TimestampStyle::RelativeTime));
53//! assert_eq!(expected_timestamp, Timestamp::parse("<t:1600000000:R>")?);
54//! # Ok(()) }
55//! ```
56//!
57//! [`Timestamp`]: crate::timestamp::Timestamp
58
59mod error;
60mod r#impl;
61mod iter;
62
63use crate::{timestamp::Timestamp, Mention};
64
65pub use self::{
66 error::{ParseMentionError, ParseMentionErrorType},
67 iter::MentionIter,
68 r#impl::ParseMention,
69};
70
71use std::fmt::{Display, Formatter, Result as FmtResult};
72use twilight_model::id::{
73 marker::{ChannelMarker, EmojiMarker, RoleMarker, UserMarker},
74 Id,
75};
76
77/// Any type of mention.
78///
79/// Contains variants for every possible kind of mention. Can be used with
80/// [`ParseMention`] and iterated over just like any other mention.
81///
82/// # Examples
83///
84/// Parse any type of mention out of a string:
85///
86/// ```
87/// use twilight_mention::{
88/// parse::{MentionType, ParseMention},
89/// timestamp::Timestamp,
90/// };
91/// use twilight_model::id::{
92/// marker::{ChannelMarker, RoleMarker, UserMarker},
93/// Id,
94/// };
95///
96/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
97/// assert_eq!(
98/// MentionType::Channel(Id::<ChannelMarker>::new(123)),
99/// MentionType::parse("<#123>")?,
100/// );
101/// assert_eq!(
102/// MentionType::Role(Id::<RoleMarker>::new(123)),
103/// MentionType::parse("<@&123>")?,
104/// );
105///
106/// let timestamp = Timestamp::new(123, None);
107/// assert_eq!(
108/// MentionType::Timestamp(timestamp),
109/// MentionType::parse("<t:123>")?
110/// );
111/// # Ok(()) }
112/// ```
113///
114/// Iterate over all types of mentions in a buffer:
115///
116/// ```
117/// use twilight_mention::{
118/// parse::{MentionType, ParseMention},
119/// timestamp::Timestamp,
120/// };
121///
122/// let buf = "channel <#12> emoji <:name:34> role <@&56> timestamp <t:1624047978> user <@78>";
123///
124/// let mut iter = MentionType::iter(buf);
125/// assert!(matches!(iter.next(), Some((MentionType::Channel(channel), _, _)) if channel.get() == 12));
126/// assert!(matches!(iter.next(), Some((MentionType::Emoji(emoji), _, _)) if emoji.get() == 34));
127/// assert!(matches!(iter.next(), Some((MentionType::Role(role), _, _)) if role.get() == 56));
128/// assert!(matches!(
129/// iter.next(),
130/// Some((MentionType::Timestamp(timestamp), _, _))
131/// if timestamp.unix() == 1_624_047_978 && timestamp.style().is_none()
132/// ));
133/// assert!(matches!(iter.next(), Some((MentionType::User(user), _, _)) if user.get() == 78));
134/// assert!(iter.next().is_none());
135/// ```
136#[derive(Clone, Copy, Debug, Eq, PartialEq)]
137#[non_exhaustive]
138pub enum MentionType {
139 /// Channel mention.
140 Channel(Id<ChannelMarker>),
141 /// Emoji mention.
142 Emoji(Id<EmojiMarker>),
143 /// Role mention.
144 Role(Id<RoleMarker>),
145 /// Timestamp mention.
146 Timestamp(Timestamp),
147 /// User mention.
148 User(Id<UserMarker>),
149}
150
151impl Display for MentionType {
152 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
153 match self {
154 Self::Channel(id) => Display::fmt(id, f),
155 Self::Emoji(id) => Display::fmt(id, f),
156 Self::Role(id) => Display::fmt(id, f),
157 Self::Timestamp(timestamp) => Display::fmt(×tamp.mention(), f),
158 Self::User(id) => Display::fmt(id, f),
159 }
160 }
161}