djs_model/id.rs
1//! Typed Discord [snowflake] IDs.
2//!
3//! Every Discord resource is identified by a 64-bit *snowflake*. djs-rs represents them with a
4//! single generic type, [`Id<T>`], where `T` is a zero-sized **marker** describing what the ID
5//! points at (see [`marker`]). Type aliases such as [`UserId`] and [`ChannelId`] make signatures
6//! readable:
7//!
8//! ```
9//! use djs_model::id::{ChannelId, UserId};
10//!
11//! fn send_to(channel: ChannelId) -> u64 {
12//! channel.get()
13//! }
14//!
15//! let channel = ChannelId::new(1_234_567_890_123_456_789);
16//! assert_eq!(send_to(channel), 1_234_567_890_123_456_789);
17//!
18//! let user = UserId::new(80_351_110_224_678_912);
19//! // send_to(user); // ❌ does not compile: a user ID is not a channel ID
20//! # let _ = user;
21//! ```
22//!
23//! # Memory layout
24//!
25//! `Id<T>` wraps a [`NonZeroU64`] (Discord never issues the ID `0`), so both `Id<T>` and
26//! `Option<Id<T>>` are exactly 8 bytes.
27//!
28//! # Serialization
29//!
30//! Discord transmits snowflakes as JSON **strings** (`"80351110224678912"`) to avoid precision
31//! loss in JavaScript. `Id<T>` serializes to a string and deserializes from either a string or an
32//! integer.
33//!
34//! discord.js counterpart: the `Snowflake` string type and `SnowflakeUtil`.
35//!
36//! [snowflake]: https://docs.discord.com/developers/reference#snowflakes
37
38use core::{
39 cmp::Ordering,
40 fmt,
41 hash::{Hash, Hasher},
42 marker::PhantomData,
43 num::NonZeroU64,
44 str::FromStr,
45};
46
47use serde::{
48 Deserialize, Deserializer, Serialize, Serializer,
49 de::{Error as DeError, Unexpected, Visitor},
50};
51
52use crate::util::Timestamp;
53
54/// The Discord epoch — the first second of 2015 — in milliseconds since the Unix epoch.
55///
56/// Snowflake timestamps are stored relative to this instant.
57pub const DISCORD_EPOCH_MS: u64 = 1_420_070_400_000;
58
59/// A typed Discord snowflake ID.
60///
61/// `T` is a marker type from [`marker`] that prevents mixing different kinds of IDs at compile
62/// time. Use the aliases in this module ([`UserId`], [`GuildId`], …) rather than spelling out
63/// `Id<UserMarker>`.
64///
65/// IDs are ordered chronologically: an ID created later always compares greater.
66///
67/// discord.js counterpart: `Snowflake` (a string in discord.js).
68///
69/// # Examples
70///
71/// ```
72/// use djs_model::id::GuildId;
73///
74/// let id: GuildId = "175928847299117063".parse().unwrap();
75/// assert_eq!(id.get(), 175_928_847_299_117_063);
76/// assert_eq!(id.to_string(), "175928847299117063");
77///
78/// // Snowflakes embed their creation time.
79/// assert_eq!(id.timestamp_ms(), 1_462_015_105_796);
80/// ```
81pub struct Id<T> {
82 value: NonZeroU64,
83 // `fn() -> T` keeps `Id<T>` `Send + Sync + Unpin` regardless of `T` and avoids drop-check
84 // implications: no `T` is ever stored.
85 marker: PhantomData<fn() -> T>,
86}
87
88impl<T> Id<T> {
89 /// Creates an ID from a raw non-zero value.
90 ///
91 /// discord.js counterpart: none (a `Snowflake` is a string in discord.js).
92 ///
93 /// # Panics
94 ///
95 /// Panics if `value` is `0`. Use [`Id::new_checked`] for fallible construction.
96 ///
97 /// # Examples
98 ///
99 /// ```
100 /// use djs_model::id::UserId;
101 ///
102 /// const BOT_OWNER: UserId = UserId::new(80_351_110_224_678_912);
103 /// assert_eq!(BOT_OWNER.get(), 80_351_110_224_678_912);
104 /// ```
105 #[must_use]
106 #[track_caller]
107 pub const fn new(value: u64) -> Self {
108 match Self::new_checked(value) {
109 Some(id) => id,
110 None => panic!("snowflake IDs must be non-zero"),
111 }
112 }
113
114 /// Creates an ID from a raw value, returning `None` if it is `0`.
115 ///
116 /// discord.js counterpart: none (a `Snowflake` is a string in discord.js).
117 ///
118 /// # Examples
119 ///
120 /// ```
121 /// use djs_model::id::UserId;
122 ///
123 /// assert!(UserId::new_checked(0).is_none());
124 /// assert!(UserId::new_checked(1).is_some());
125 /// ```
126 #[must_use]
127 pub const fn new_checked(value: u64) -> Option<Self> {
128 match NonZeroU64::new(value) {
129 Some(value) => Some(Self::from_nonzero(value)),
130 None => None,
131 }
132 }
133
134 /// Creates an ID from a [`NonZeroU64`]. This can never fail.
135 ///
136 /// discord.js counterpart: none (a `Snowflake` is a string in discord.js).
137 #[must_use]
138 pub const fn from_nonzero(value: NonZeroU64) -> Self {
139 Self {
140 value,
141 marker: PhantomData,
142 }
143 }
144
145 /// Returns the raw value of the ID.
146 ///
147 /// discord.js counterpart: none (a `Snowflake` is a string in discord.js).
148 #[must_use]
149 pub const fn get(self) -> u64 {
150 self.value.get()
151 }
152
153 /// Returns the raw value of the ID as a [`NonZeroU64`].
154 ///
155 /// discord.js counterpart: none (a `Snowflake` is a string in discord.js).
156 #[must_use]
157 pub const fn into_nonzero(self) -> NonZeroU64 {
158 self.value
159 }
160
161 /// Reinterprets this ID as an ID of another kind.
162 ///
163 /// Some Discord resources deliberately share IDs — for example the `@everyone` role of a
164 /// guild has the same ID as the guild itself. `cast` makes such conversions explicit.
165 ///
166 /// discord.js counterpart: none (a `Snowflake` is a string in discord.js).
167 ///
168 /// # Examples
169 ///
170 /// ```
171 /// use djs_model::id::{GuildId, RoleId};
172 ///
173 /// let guild = GuildId::new(175_928_847_299_117_063);
174 /// let everyone: RoleId = guild.cast();
175 /// assert_eq!(everyone.get(), guild.get());
176 /// ```
177 #[must_use]
178 pub const fn cast<U>(self) -> Id<U> {
179 Id::from_nonzero(self.value)
180 }
181
182 /// Returns the creation time encoded in the snowflake, in milliseconds since the Unix epoch.
183 ///
184 /// discord.js counterpart: `SnowflakeUtil.timestampFrom`.
185 #[must_use]
186 pub const fn timestamp_ms(self) -> u64 {
187 (self.get() >> 22) + DISCORD_EPOCH_MS
188 }
189
190 /// Returns the creation time encoded in the snowflake.
191 ///
192 /// discord.js counterpart: the `createdAt` / `createdTimestamp` getters on structures.
193 ///
194 /// # Examples
195 ///
196 /// ```
197 /// use djs_model::id::UserId;
198 ///
199 /// let id = UserId::new(80_351_110_224_678_912);
200 /// assert_eq!(id.timestamp().to_string(), "2015-08-10T17:26:37.529000+00:00");
201 /// ```
202 #[must_use]
203 #[expect(
204 clippy::cast_possible_wrap,
205 reason = "a snowflake timestamp is at most 2^42 ms after the Discord epoch, far below i64::MAX µs"
206 )]
207 pub const fn timestamp(self) -> Timestamp {
208 Timestamp::from_unix_micros(self.timestamp_ms() as i64 * 1_000)
209 }
210
211 /// Returns the internal worker ID encoded in the snowflake (5 bits).
212 ///
213 /// discord.js counterpart: `SnowflakeUtil.deconstruct`'s `workerId` (`@sapphire/snowflake`).
214 #[must_use]
215 pub const fn worker_id(self) -> u8 {
216 ((self.get() & 0x003E_0000) >> 17) as u8
217 }
218
219 /// Returns the internal process ID encoded in the snowflake (5 bits).
220 ///
221 /// discord.js counterpart: `SnowflakeUtil.deconstruct`'s `processId` (`@sapphire/snowflake`).
222 #[must_use]
223 pub const fn process_id(self) -> u8 {
224 ((self.get() & 0x0001_F000) >> 12) as u8
225 }
226
227 /// Returns the per-process increment encoded in the snowflake (12 bits).
228 ///
229 /// discord.js counterpart: `SnowflakeUtil.deconstruct`'s `increment` (`@sapphire/snowflake`).
230 #[must_use]
231 pub const fn increment(self) -> u16 {
232 (self.get() & 0x0FFF) as u16
233 }
234
235 /// Creates the smallest ID that could have been generated at `unix_ms`
236 /// (milliseconds since the Unix epoch).
237 ///
238 /// This is useful for paginating REST endpoints by time (`before` / `after` parameters).
239 /// Returns `None` if `unix_ms` is at or before the Discord epoch (the ID would be `0`) or so
240 /// far in the future that the timestamp does not fit in a snowflake.
241 ///
242 /// discord.js counterpart: `SnowflakeUtil.generate({ timestamp })`.
243 ///
244 /// # Examples
245 ///
246 /// ```
247 /// use djs_model::id::MessageId;
248 ///
249 /// let id = MessageId::from_timestamp_ms(1_462_015_105_796).unwrap();
250 /// assert_eq!(id.timestamp_ms(), 1_462_015_105_796);
251 /// ```
252 #[must_use]
253 pub const fn from_timestamp_ms(unix_ms: u64) -> Option<Self> {
254 if unix_ms <= DISCORD_EPOCH_MS {
255 return None;
256 }
257 let since_epoch = unix_ms - DISCORD_EPOCH_MS;
258 if since_epoch >= 1 << 42 {
259 return None;
260 }
261 Self::new_checked(since_epoch << 22)
262 }
263}
264
265// Manual impls: deriving would add unnecessary `T: Trait` bounds on the marker.
266
267impl<T> Clone for Id<T> {
268 fn clone(&self) -> Self {
269 *self
270 }
271}
272
273impl<T> Copy for Id<T> {}
274
275impl<T> PartialEq for Id<T> {
276 fn eq(&self, other: &Self) -> bool {
277 self.value == other.value
278 }
279}
280
281impl<T> Eq for Id<T> {}
282
283impl<T> PartialOrd for Id<T> {
284 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
285 Some(self.cmp(other))
286 }
287}
288
289impl<T> Ord for Id<T> {
290 fn cmp(&self, other: &Self) -> Ordering {
291 self.value.cmp(&other.value)
292 }
293}
294
295impl<T> Hash for Id<T> {
296 fn hash<H: Hasher>(&self, state: &mut H) {
297 // Hash exactly like a `u64` so `Id<T>` can be looked up with hashers specialised for
298 // integers.
299 state.write_u64(self.get());
300 }
301}
302
303impl<T> fmt::Debug for Id<T> {
304 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305 let marker = core::any::type_name::<T>();
306 let marker = marker.rsplit("::").next().unwrap_or(marker);
307 write!(f, "Id<{marker}>({})", self.value)
308 }
309}
310
311impl<T> fmt::Display for Id<T> {
312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313 fmt::Display::fmt(&self.value, f)
314 }
315}
316
317impl<T> From<NonZeroU64> for Id<T> {
318 fn from(value: NonZeroU64) -> Self {
319 Self::from_nonzero(value)
320 }
321}
322
323impl<T> From<Id<T>> for NonZeroU64 {
324 fn from(id: Id<T>) -> Self {
325 id.value
326 }
327}
328
329impl<T> From<Id<T>> for u64 {
330 fn from(id: Id<T>) -> Self {
331 id.get()
332 }
333}
334
335impl<T> TryFrom<u64> for Id<T> {
336 type Error = ParseIdError;
337
338 fn try_from(value: u64) -> Result<Self, Self::Error> {
339 Self::new_checked(value).ok_or(ParseIdError {
340 kind: ParseIdErrorKind::Zero,
341 })
342 }
343}
344
345impl<T> FromStr for Id<T> {
346 type Err = ParseIdError;
347
348 fn from_str(s: &str) -> Result<Self, Self::Err> {
349 let value: u64 = s.parse().map_err(|_| ParseIdError {
350 kind: ParseIdErrorKind::NotAnInteger,
351 })?;
352 Self::try_from(value)
353 }
354}
355
356/// The error returned when parsing an [`Id`] from a string or integer fails.
357///
358/// discord.js counterpart: none (discord.js keeps IDs as strings).
359#[derive(Clone, Debug, PartialEq, Eq)]
360pub struct ParseIdError {
361 kind: ParseIdErrorKind,
362}
363
364#[derive(Clone, Copy, Debug, PartialEq, Eq)]
365enum ParseIdErrorKind {
366 NotAnInteger,
367 Zero,
368}
369
370impl ParseIdError {
371 /// Returns `true` if parsing failed because the value was `0`.
372 ///
373 /// discord.js counterpart: none (a `Snowflake` is a string in discord.js).
374 #[must_use]
375 pub fn is_zero(&self) -> bool {
376 self.kind == ParseIdErrorKind::Zero
377 }
378}
379
380impl fmt::Display for ParseIdError {
381 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382 f.write_str(match self.kind {
383 ParseIdErrorKind::NotAnInteger => "snowflake ID is not a valid unsigned 64-bit integer",
384 ParseIdErrorKind::Zero => "snowflake ID must be non-zero",
385 })
386 }
387}
388
389impl core::error::Error for ParseIdError {}
390
391impl<T> Serialize for Id<T> {
392 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
393 // `collect_str` lets serializers such as serde_json write the digits directly without an
394 // intermediate `String` allocation.
395 serializer.collect_str(&self.value)
396 }
397}
398
399impl<'de, T> Deserialize<'de> for Id<T> {
400 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
401 deserializer.deserialize_any(IdVisitor(PhantomData))
402 }
403}
404
405struct IdVisitor<T>(PhantomData<fn() -> T>);
406
407impl<T> Visitor<'_> for IdVisitor<T> {
408 type Value = Id<T>;
409
410 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411 f.write_str("a non-zero snowflake ID as a string or integer")
412 }
413
414 fn visit_u64<E: DeError>(self, value: u64) -> Result<Self::Value, E> {
415 Id::new_checked(value).ok_or_else(|| E::invalid_value(Unexpected::Unsigned(0), &self))
416 }
417
418 fn visit_i64<E: DeError>(self, value: i64) -> Result<Self::Value, E> {
419 u64::try_from(value)
420 .map_err(|_| E::invalid_value(Unexpected::Signed(value), &self))
421 .and_then(|value| self.visit_u64(value))
422 }
423
424 fn visit_str<E: DeError>(self, value: &str) -> Result<Self::Value, E> {
425 value
426 .parse()
427 .map_err(|_| E::invalid_value(Unexpected::Str(value), &self))
428 }
429}
430
431/// Marker types for [`Id`].
432///
433/// Markers are uninhabited enums: they exist only at the type level and are never constructed.
434pub mod marker {
435 macro_rules! markers {
436 ($($(#[$meta:meta])* $marker:ident => $alias:ident,)*) => {
437 $(
438 $(#[$meta])*
439 #[doc = ""]
440 #[doc = concat!("Usually used through the [`", stringify!($alias), "`](super::", stringify!($alias), ") alias.")]
441 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
442 pub enum $marker {}
443 )*
444
445 /// Type aliases are generated next to the markers.
446 pub(super) mod aliases {
447 $(
448 #[doc = concat!("ID of a resource marked by [`", stringify!($marker), "`](super::", stringify!($marker), ").")]
449 pub type $alias = super::super::Id<super::$marker>;
450 )*
451 }
452 };
453 }
454
455 markers! {
456 /// Marker for [application](https://docs.discord.com/developers/resources/application) IDs.
457 ApplicationMarker => ApplicationId,
458 /// Marker for message [attachment](https://docs.discord.com/developers/resources/message#attachment-object) IDs.
459 AttachmentMarker => AttachmentId,
460 /// Marker for [audit log entry](https://docs.discord.com/developers/resources/audit-log) IDs.
461 AuditLogEntryMarker => AuditLogEntryId,
462 /// Marker for [auto moderation rule](https://docs.discord.com/developers/resources/auto-moderation) IDs.
463 AutoModerationRuleMarker => AutoModerationRuleId,
464 /// Marker for [channel](https://docs.discord.com/developers/resources/channel) IDs
465 /// (including threads, which are channels).
466 ChannelMarker => ChannelId,
467 /// Marker for [application command](https://docs.discord.com/developers/interactions/application-commands) IDs.
468 CommandMarker => CommandId,
469 /// Marker for application command version IDs.
470 CommandVersionMarker => CommandVersionId,
471 /// Marker for [emoji](https://docs.discord.com/developers/resources/emoji) IDs.
472 EmojiMarker => EmojiId,
473 /// Marker for [entitlement](https://docs.discord.com/developers/resources/entitlement) IDs.
474 EntitlementMarker => EntitlementId,
475 /// Marker for IDs whose kind is not known or varies (for example audit log target IDs).
476 GenericMarker => GenericId,
477 /// Marker for [guild](https://docs.discord.com/developers/resources/guild) IDs.
478 GuildMarker => GuildId,
479 /// Marker for guild [integration](https://docs.discord.com/developers/resources/guild#integration-object) IDs.
480 IntegrationMarker => IntegrationId,
481 /// Marker for [interaction](https://docs.discord.com/developers/interactions/receiving-and-responding) IDs.
482 InteractionMarker => InteractionId,
483 /// Marker for [lobby](https://docs.discord.com/developers/resources/lobby) IDs.
484 LobbyMarker => LobbyId,
485 /// Marker for [message](https://docs.discord.com/developers/resources/message) IDs.
486 MessageMarker => MessageId,
487 /// Marker for [role](https://docs.discord.com/developers/topics/permissions#role-object) IDs.
488 RoleMarker => RoleId,
489 /// Marker for [guild scheduled event](https://docs.discord.com/developers/resources/guild-scheduled-event) IDs.
490 ScheduledEventMarker => ScheduledEventId,
491 /// Marker for [SKU](https://docs.discord.com/developers/resources/sku) IDs.
492 SkuMarker => SkuId,
493 /// Marker for [soundboard sound](https://docs.discord.com/developers/resources/soundboard) IDs.
494 SoundboardSoundMarker => SoundboardSoundId,
495 /// Marker for [stage instance](https://docs.discord.com/developers/resources/stage-instance) IDs.
496 StageInstanceMarker => StageInstanceId,
497 /// Marker for [sticker](https://docs.discord.com/developers/resources/sticker) IDs.
498 StickerMarker => StickerId,
499 /// Marker for sticker pack IDs.
500 StickerPackMarker => StickerPackId,
501 /// Marker for [subscription](https://docs.discord.com/developers/resources/subscription) IDs.
502 SubscriptionMarker => SubscriptionId,
503 /// Marker for forum/media channel [tag](https://docs.discord.com/developers/resources/channel#forum-tag-object) IDs.
504 TagMarker => TagId,
505 /// Marker for [team](https://docs.discord.com/developers/topics/teams) IDs.
506 TeamMarker => TeamId,
507 /// Marker for [user](https://docs.discord.com/developers/resources/user) IDs.
508 UserMarker => UserId,
509 /// Marker for [webhook](https://docs.discord.com/developers/resources/webhook) IDs.
510 WebhookMarker => WebhookId,
511 }
512}
513
514pub use marker::aliases::*;
515
516#[cfg(test)]
517mod tests {
518 use super::*;
519
520 #[test]
521 fn layout() {
522 assert_eq!(size_of::<UserId>(), 8);
523 assert_eq!(size_of::<Option<UserId>>(), 8);
524 }
525
526 #[test]
527 fn snowflake_parts() {
528 // Example snowflake from the Discord API documentation.
529 let id = UserId::new(175_928_847_299_117_063);
530 assert_eq!(id.timestamp_ms(), 1_462_015_105_796);
531 assert_eq!(id.worker_id(), 1);
532 assert_eq!(id.process_id(), 0);
533 assert_eq!(id.increment(), 7);
534 }
535
536 #[test]
537 fn from_timestamp_round_trip() {
538 let id = MessageId::from_timestamp_ms(1_462_015_105_796).unwrap();
539 assert_eq!(id.timestamp_ms(), 1_462_015_105_796);
540 assert_eq!(id.increment(), 0);
541 assert!(MessageId::from_timestamp_ms(DISCORD_EPOCH_MS).is_none());
542 assert!(MessageId::from_timestamp_ms(0).is_none());
543 assert!(MessageId::from_timestamp_ms(u64::MAX).is_none());
544 }
545
546 #[test]
547 fn parse() {
548 assert_eq!("1".parse::<GuildId>().unwrap().get(), 1);
549 assert!("0".parse::<GuildId>().unwrap_err().is_zero());
550 assert!(!"abc".parse::<GuildId>().unwrap_err().is_zero());
551 assert!("-1".parse::<GuildId>().is_err());
552 assert!("18446744073709551616".parse::<GuildId>().is_err());
553 }
554
555 #[test]
556 fn debug_and_display() {
557 let id = ChannelId::new(42);
558 assert_eq!(format!("{id:?}"), "Id<ChannelMarker>(42)");
559 assert_eq!(id.to_string(), "42");
560 }
561
562 #[test]
563 fn ordering_is_chronological() {
564 assert!(UserId::new(1) < UserId::new(2));
565 }
566}