Skip to main content

djs_model/util/
image_hash.rs

1//! Compact storage for Discord image hashes.
2
3use core::{fmt, str::FromStr};
4
5use serde::{
6    Deserialize, Deserializer, Serialize, Serializer,
7    de::{Error as DeError, Visitor},
8};
9
10/// The hash of an image on Discord's CDN — avatars, icons, banners, splashes and so on.
11///
12/// Discord sends image hashes as 32 hexadecimal characters, prefixed with `a_` when the image
13/// is animated (for example `a_1269e74af4df7417b13759eae50c83dc`). Instead of keeping that
14/// 34-byte string on the heap, `ImageHash` stores the decoded 16 bytes plus an animation flag:
15/// it is 17 bytes, `Copy`, and `Option<ImageHash>` is also 17 bytes.
16///
17/// Formatting with [`Display`](fmt::Display) reproduces the original string, which is what
18/// [CDN URLs](https://docs.discord.com/developers/reference#image-formatting) need.
19///
20/// discord.js counterpart: none (a string in discord.js).
21///
22/// # Examples
23///
24/// ```
25/// use djs_model::util::ImageHash;
26///
27/// let hash: ImageHash = "a_1269e74af4df7417b13759eae50c83dc".parse().unwrap();
28/// assert!(hash.is_animated());
29/// assert_eq!(hash.to_string(), "a_1269e74af4df7417b13759eae50c83dc");
30/// ```
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub struct ImageHash {
33    bytes: [u8; 16],
34    animated: bool,
35}
36
37impl ImageHash {
38    /// Creates an image hash from its raw 16 bytes.
39    ///
40    /// discord.js counterpart: none (a string in discord.js).
41    #[must_use]
42    pub const fn new(bytes: [u8; 16], animated: bool) -> Self {
43        Self { bytes, animated }
44    }
45
46    /// Returns the raw 16 bytes of the hash.
47    ///
48    /// discord.js counterpart: none (a string in discord.js).
49    #[must_use]
50    pub const fn bytes(self) -> [u8; 16] {
51        self.bytes
52    }
53
54    /// Returns `true` if the image is animated (the hash had an `a_` prefix).
55    ///
56    /// Animated images are available as GIF (and WebP/AVIF animations) on the CDN.
57    ///
58    /// discord.js counterpart: the `a_` check `User#avatarURL` makes.
59    #[must_use]
60    pub const fn is_animated(self) -> bool {
61        self.animated
62    }
63
64    /// Parses an image hash such as `a_1269e74af4df7417b13759eae50c83dc`.
65    ///
66    /// Both lowercase and uppercase hexadecimal digits are accepted.
67    ///
68    /// discord.js counterpart: none (a string in discord.js).
69    ///
70    /// # Errors
71    ///
72    /// Returns [`ParseImageHashError`] if the input is not 32 hexadecimal characters with an
73    /// optional `a_` prefix.
74    pub const fn parse(input: &str) -> Result<Self, ParseImageHashError> {
75        let mut bytes = input.as_bytes();
76        let animated = matches!(bytes, [b'a', b'_', ..]);
77        if animated {
78            bytes = bytes.split_at(2).1;
79        }
80        if bytes.len() != 32 {
81            return Err(ParseImageHashError(()));
82        }
83
84        let mut out = [0_u8; 16];
85        let mut i = 0;
86        while i < 16 {
87            let (Some(high), Some(low)) = (hex_value(bytes[i * 2]), hex_value(bytes[i * 2 + 1]))
88            else {
89                return Err(ParseImageHashError(()));
90            };
91            out[i] = (high << 4) | low;
92            i += 1;
93        }
94        Ok(Self::new(out, animated))
95    }
96}
97
98const fn hex_value(byte: u8) -> Option<u8> {
99    match byte {
100        b'0'..=b'9' => Some(byte - b'0'),
101        b'a'..=b'f' => Some(byte - b'a' + 10),
102        b'A'..=b'F' => Some(byte - b'A' + 10),
103        _ => None,
104    }
105}
106
107impl FromStr for ImageHash {
108    type Err = ParseImageHashError;
109
110    fn from_str(s: &str) -> Result<Self, Self::Err> {
111        Self::parse(s)
112    }
113}
114
115/// Formats the hash exactly as Discord sends it: lowercase hex with an `a_` prefix if animated.
116impl fmt::Display for ImageHash {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        const HEX: &[u8; 16] = b"0123456789abcdef";
119        let mut buffer = [0_u8; 34];
120        let start = if self.animated {
121            buffer[0] = b'a';
122            buffer[1] = b'_';
123            2
124        } else {
125            0
126        };
127        for (i, byte) in self.bytes.iter().enumerate() {
128            buffer[start + i * 2] = HEX[usize::from(byte >> 4)];
129            buffer[start + i * 2 + 1] = HEX[usize::from(byte & 0x0F)];
130        }
131        let text = core::str::from_utf8(&buffer[..start + 32]).map_err(|_| fmt::Error)?;
132        f.write_str(text)
133    }
134}
135
136/// The error returned when parsing an [`ImageHash`] fails.
137///
138/// discord.js counterpart: none (discord.js keeps image hashes as strings).
139#[derive(Clone, Debug, PartialEq, Eq)]
140pub struct ParseImageHashError(());
141
142impl fmt::Display for ParseImageHashError {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        f.write_str("image hash must be 32 hexadecimal characters with an optional `a_` prefix")
145    }
146}
147
148impl core::error::Error for ParseImageHashError {}
149
150impl Serialize for ImageHash {
151    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
152        serializer.collect_str(self)
153    }
154}
155
156impl<'de> Deserialize<'de> for ImageHash {
157    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
158        struct ImageHashVisitor;
159
160        impl Visitor<'_> for ImageHashVisitor {
161            type Value = ImageHash;
162
163            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164                f.write_str("an image hash string")
165            }
166
167            fn visit_str<E: DeError>(self, value: &str) -> Result<Self::Value, E> {
168                ImageHash::parse(value).map_err(E::custom)
169            }
170        }
171
172        deserializer.deserialize_str(ImageHashVisitor)
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    #[test]
181    fn layout() {
182        assert_eq!(size_of::<ImageHash>(), 17);
183        assert_eq!(size_of::<Option<ImageHash>>(), 17);
184    }
185
186    #[test]
187    fn round_trip() {
188        for input in [
189            "1269e74af4df7417b13759eae50c83dc",
190            "a_1269e74af4df7417b13759eae50c83dc",
191            "00000000000000000000000000000000",
192            "ffffffffffffffffffffffffffffffff",
193        ] {
194            assert_eq!(input.parse::<ImageHash>().unwrap().to_string(), input);
195        }
196    }
197
198    #[test]
199    fn uppercase_is_normalised() {
200        let hash: ImageHash = "1269E74AF4DF7417B13759EAE50C83DC".parse().unwrap();
201        assert_eq!(hash.to_string(), "1269e74af4df7417b13759eae50c83dc");
202    }
203
204    #[test]
205    fn rejects_invalid() {
206        for input in [
207            "",
208            "a_",
209            "1269e74af4df7417b13759eae50c83d",
210            "1269e74af4df7417b13759eae50c83dcc",
211            "1269e74af4df7417b13759eae50c83dg",
212            "b_1269e74af4df7417b13759eae50c83dc",
213        ] {
214            assert!(
215                input.parse::<ImageHash>().is_err(),
216                "{input:?} should be rejected"
217            );
218        }
219    }
220}