djs_model/gateway/
shard_id.rs1use core::fmt;
2
3use serde::{
4 Deserialize, Deserializer, Serialize, Serializer,
5 de::{Error as DeError, SeqAccess, Visitor},
6 ser::SerializeTuple,
7};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
33pub struct ShardId {
34 number: u32,
35 total: u32,
36}
37
38impl ShardId {
39 pub const ONE: Self = Self::new(0, 1);
41
42 #[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 #[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 #[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 #[must_use]
92 pub const fn number(self) -> u32 {
93 self.number
94 }
95
96 #[must_use]
100 pub const fn total(self) -> u32 {
101 self.total
102 }
103}
104
105impl 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}