Skip to main content

djs_model/gateway/
shard_id.rs

1use core::fmt;
2
3use serde::{
4    Deserialize, Deserializer, Serialize, Serializer,
5    de::{Error as DeError, SeqAccess, Visitor},
6    ser::SerializeTuple,
7};
8
9/// Identifies a [shard](https://docs.discord.com/developers/events/gateway#sharding): its number
10/// and the total number of shards.
11///
12/// Discord sends this as a two-element array, `[shard_id, num_shards]`. A guild belongs to shard
13/// `(guild_id >> 22) % total` — see [`ShardId::for_guild`].
14///
15/// # Invariants
16///
17/// `total` is at least 1 and `number < total`.
18///
19/// discord.js counterpart: `shard` / `shardCount` client options and `ShardClientUtil`.
20///
21/// # Examples
22///
23/// ```
24/// use djs_model::{gateway::ShardId, id::GuildId};
25///
26/// let shard = ShardId::new(0, 1);
27/// assert_eq!(shard.to_string(), "[0, 1]");
28///
29/// let guild = GuildId::new(175_928_847_299_117_063);
30/// assert_eq!(ShardId::for_guild(guild, 4).number(), 0);
31/// ```
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
33pub struct ShardId {
34    number: u32,
35    total: u32,
36}
37
38impl ShardId {
39    /// The single shard of a bot that does not shard: `[0, 1]`.
40    pub const ONE: Self = Self::new(0, 1);
41
42    /// Creates a shard ID.
43    ///
44    /// discord.js counterpart: `ShardClientUtil.shardIdForGuildId`'s numbers.
45    ///
46    /// # Panics
47    ///
48    /// Panics if `total` is `0` or `number >= total`.
49    #[must_use]
50    #[track_caller]
51    pub const fn new(number: u32, total: u32) -> Self {
52        match Self::new_checked(number, total) {
53            Some(shard) => shard,
54            None => panic!("shard number must be less than the (non-zero) shard total"),
55        }
56    }
57
58    /// Creates a shard ID, returning `None` if `total` is `0` or `number >= total`.
59    ///
60    /// discord.js counterpart: none (discord.js keeps shard IDs as numbers).
61    #[must_use]
62    pub const fn new_checked(number: u32, total: u32) -> Option<Self> {
63        if number < total {
64            Some(Self { number, total })
65        } else {
66            None
67        }
68    }
69
70    /// Returns the shard that handles events of `guild` when there are `total` shards.
71    ///
72    /// Uses Discord's sharding formula, `shard_id = (guild_id >> 22) % num_shards`.
73    ///
74    /// # Panics
75    ///
76    /// Panics if `total` is `0`.
77    #[must_use]
78    #[track_caller]
79    #[expect(
80        clippy::cast_possible_truncation,
81        reason = "result is < total, which is a u32"
82    )]
83    pub const fn for_guild(guild: crate::id::GuildId, total: u32) -> Self {
84        assert!(total > 0, "shard total must be non-zero");
85        Self::new(((guild.get() >> 22) % total as u64) as u32, total)
86    }
87
88    /// Returns the shard number (zero-based).
89    ///
90    /// discord.js counterpart: `WebSocketShard#id` (`@discordjs/ws`).
91    #[must_use]
92    pub const fn number(self) -> u32 {
93        self.number
94    }
95
96    /// Returns the total number of shards.
97    ///
98    /// discord.js counterpart: `ShardClientUtil#count`.
99    #[must_use]
100    pub const fn total(self) -> u32 {
101        self.total
102    }
103}
104
105/// Formats as `[number, total]`.
106impl fmt::Display for ShardId {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        write!(f, "[{}, {}]", self.number, self.total)
109    }
110}
111
112impl Serialize for ShardId {
113    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
114        let mut tuple = serializer.serialize_tuple(2)?;
115        tuple.serialize_element(&self.number)?;
116        tuple.serialize_element(&self.total)?;
117        tuple.end()
118    }
119}
120
121impl<'de> Deserialize<'de> for ShardId {
122    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
123        struct ShardIdVisitor;
124
125        impl<'de> Visitor<'de> for ShardIdVisitor {
126            type Value = ShardId;
127
128            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129                f.write_str("a [shard_id, num_shards] array")
130            }
131
132            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<ShardId, A::Error> {
133                let number = seq
134                    .next_element()?
135                    .ok_or_else(|| A::Error::invalid_length(0, &self))?;
136                let total = seq
137                    .next_element()?
138                    .ok_or_else(|| A::Error::invalid_length(1, &self))?;
139                if seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
140                    return Err(A::Error::invalid_length(3, &self));
141                }
142                ShardId::new_checked(number, total)
143                    .ok_or_else(|| A::Error::custom("shard number must be less than shard total"))
144            }
145        }
146
147        deserializer.deserialize_tuple(2, ShardIdVisitor)
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[test]
156    fn serde() {
157        let shard: ShardId = serde_json::from_str("[3, 8]").unwrap();
158        assert_eq!((shard.number(), shard.total()), (3, 8));
159        assert_eq!(serde_json::to_string(&shard).unwrap(), "[3,8]");
160        assert!(serde_json::from_str::<ShardId>("[8, 8]").is_err());
161        assert!(serde_json::from_str::<ShardId>("[0, 0]").is_err());
162        assert!(serde_json::from_str::<ShardId>("[0]").is_err());
163        assert!(serde_json::from_str::<ShardId>("[0, 1, 2]").is_err());
164    }
165
166    #[test]
167    fn checked() {
168        assert!(ShardId::new_checked(0, 0).is_none());
169        assert!(ShardId::new_checked(1, 1).is_none());
170        assert_eq!(ShardId::new_checked(0, 1), Some(ShardId::ONE));
171    }
172}