Skip to main content

djs_model/util/
image_data.rs

1//! [`ImageData`]: an image sent inline in a request body as a data URI (D-113).
2
3use core::fmt;
4
5use bytes::Bytes;
6use compact_str::CompactString;
7use serde::{Serialize, Serializer};
8
9/// An image sent inside a JSON request body, as an
10/// [image data URI](https://docs.discord.com/developers/reference#image-data)
11/// (`data:image/png;base64,iVBORw0…`).
12///
13/// Used by every request field that takes an image: avatars, banners, guild, role and group
14/// DM icons, emojis, … The image is kept as [`Bytes`] and only base64-encoded while the body
15/// is serialized, straight into the output without an intermediate string.
16///
17/// discord.js counterpart: the `BufferResolvable | Base64Resolvable` image options (resolved
18/// by `DataResolver.resolveImage`).
19///
20/// # Examples
21///
22/// ```
23/// use djs_model::util::ImageData;
24///
25/// // A (truncated) PNG: the media type is read from the file signature.
26/// let png = ImageData::new(&b"\x89PNG\r\n\x1a\n"[..]).unwrap();
27/// assert_eq!(png.content_type(), "image/png");
28/// assert_eq!(png.to_string(), "data:image/png;base64,iVBORw0KGgo=");
29///
30/// let svg = ImageData::with_content_type("<svg/>", "image/svg+xml");
31/// assert_eq!(serde_json::to_string(&svg).unwrap(), r#""data:image/svg+xml;base64,PHN2Zy8+""#);
32///
33/// assert!(ImageData::new("not an image").is_err());
34/// ```
35#[derive(Clone, PartialEq, Eq, Hash)]
36pub struct ImageData {
37    data: Bytes,
38    content_type: CompactString,
39}
40
41impl ImageData {
42    /// An image whose [media type](https://en.wikipedia.org/wiki/Media_type) is detected from
43    /// its file signature: PNG, JPEG, GIF, WebP or AVIF.
44    ///
45    /// `data` can be anything that converts into [`Bytes`] without copying: a `Vec<u8>`, a
46    /// `&'static [u8]`, …
47    ///
48    /// discord.js counterpart: `BufferResolvable` and `Base64Resolvable`, as image options take them.
49    ///
50    /// # Errors
51    ///
52    /// [`ImageDataError`] when `data` does not start with one of those signatures; use
53    /// [`with_content_type`](Self::with_content_type) for other formats.
54    pub fn new(data: impl Into<Bytes>) -> Result<Self, ImageDataError> {
55        let data = data.into();
56        let content_type = detect(&data).ok_or(ImageDataError)?;
57        Ok(Self {
58            data,
59            content_type: CompactString::const_new(content_type),
60        })
61    }
62
63    /// An image of the given media type (e.g. `image/png`), which is not checked.
64    ///
65    /// discord.js counterpart: `BufferResolvable` and `Base64Resolvable`, as image options take them.
66    #[must_use]
67    pub fn with_content_type(
68        data: impl Into<Bytes>,
69        content_type: impl Into<CompactString>,
70    ) -> Self {
71        Self {
72            data: data.into(),
73            content_type: content_type.into(),
74        }
75    }
76
77    /// The image file's contents.
78    ///
79    /// discord.js counterpart: none (discord.js turns images into data URIs internally).
80    #[must_use]
81    pub const fn data(&self) -> &Bytes {
82        &self.data
83    }
84
85    /// The image's media type (e.g. `image/png`).
86    ///
87    /// discord.js counterpart: none (discord.js detects the type internally).
88    #[must_use]
89    pub fn content_type(&self) -> &str {
90        &self.content_type
91    }
92}
93
94/// Writes the data URI.
95impl fmt::Display for ImageData {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        f.write_str("data:")?;
98        f.write_str(&self.content_type)?;
99        f.write_str(";base64,")?;
100        write_base64(&self.data, f)
101    }
102}
103
104/// Shows the media type and the size, not the contents.
105impl fmt::Debug for ImageData {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        f.debug_struct("ImageData")
108            .field("content_type", &self.content_type)
109            .field("len", &self.data.len())
110            .finish()
111    }
112}
113
114impl Serialize for ImageData {
115    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
116        serializer.collect_str(self)
117    }
118}
119
120/// The error of [`ImageData::new`]: the data is not a PNG, JPEG, GIF, WebP or AVIF image.
121///
122/// discord.js counterpart: none (discord.js accepts any buffer and lets Discord refuse it).
123#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
124#[non_exhaustive]
125pub struct ImageDataError;
126
127impl fmt::Display for ImageDataError {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.write_str("unknown image format (expected PNG, JPEG, GIF, WebP or AVIF)")
130    }
131}
132
133impl core::error::Error for ImageDataError {}
134
135/// The media type of `data` from its file signature.
136fn detect(data: &[u8]) -> Option<&'static str> {
137    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
138        Some("image/png")
139    } else if data.starts_with(b"\xff\xd8\xff") {
140        Some("image/jpeg")
141    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
142        Some("image/gif")
143    } else if data.starts_with(b"RIFF") && data.get(8..12) == Some(b"WEBP") {
144        Some("image/webp")
145    } else if data.get(4..8) == Some(b"ftyp") && matches!(data.get(8..12), Some(b"avif" | b"avis"))
146    {
147        Some("image/avif")
148    } else {
149        None
150    }
151}
152
153const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
154
155/// Input bytes encoded per `write_str` call (a multiple of 3, so only the last call pads).
156const CHUNK: usize = 768;
157
158/// Writes `data` as standard, padded base64 ([RFC 4648 §4](https://www.rfc-editor.org/rfc/rfc4648#section-4)).
159pub(super) fn write_base64(data: &[u8], out: &mut impl fmt::Write) -> fmt::Result {
160    let mut buffer = [0_u8; CHUNK / 3 * 4];
161    for chunk in data.chunks(CHUNK) {
162        let (groups, rest) = chunk.as_chunks::<3>();
163        let mut len = 0;
164        for &[a, b, c] in groups {
165            buffer[len..len + 4].copy_from_slice(&quad([a, b, c], 4));
166            len += 4;
167        }
168        match *rest {
169            [a] => buffer[len..len + 4].copy_from_slice(&quad([a, 0, 0], 2)),
170            [a, b] => buffer[len..len + 4].copy_from_slice(&quad([a, b, 0], 3)),
171            _ => {}
172        }
173        if !rest.is_empty() {
174            len += 4;
175        }
176        // The buffer only ever holds ASCII from `ALPHABET` and `=`.
177        let text = core::str::from_utf8(&buffer[..len]).map_err(|_| fmt::Error)?;
178        out.write_str(text)?;
179    }
180    Ok(())
181}
182
183/// Encodes three bytes as four characters, of which the first `significant` are data and
184/// the rest padding.
185fn quad([a, b, c]: [u8; 3], significant: usize) -> [u8; 4] {
186    let n = u32::from(a) << 16 | u32::from(b) << 8 | u32::from(c);
187    let mut out = [b'='; 4];
188    for (i, char) in out.iter_mut().enumerate().take(significant) {
189        // `i < 4`, so the shift is at most 18 and the index below 64.
190        let shift = 18 - 6 * i;
191        *char = ALPHABET[(n >> shift & 0x3f) as usize];
192    }
193    out
194}
195
196#[cfg(test)]
197mod tests {
198    use core::fmt::Write as _;
199
200    use super::*;
201
202    fn base64(data: &[u8]) -> String {
203        let mut out = String::new();
204        write_base64(data, &mut out).unwrap();
205        out
206    }
207
208    /// A slow, obviously correct encoder to compare against.
209    fn reference(data: &[u8]) -> String {
210        let bits = data.iter().fold(String::new(), |mut bits, byte| {
211            write!(bits, "{byte:08b}").unwrap();
212            bits
213        });
214        let mut out: String = bits
215            .as_bytes()
216            .chunks(6)
217            .map(|six| {
218                let six = format!("{:0<6}", core::str::from_utf8(six).unwrap());
219                char::from(ALPHABET[usize::from_str_radix(&six, 2).unwrap()])
220            })
221            .collect();
222        while !out.len().is_multiple_of(4) {
223            out.push('=');
224        }
225        out
226    }
227
228    #[test]
229    fn rfc_4648_vectors() {
230        for (input, output) in [
231            ("", ""),
232            ("f", "Zg=="),
233            ("fo", "Zm8="),
234            ("foo", "Zm9v"),
235            ("foob", "Zm9vYg=="),
236            ("fooba", "Zm9vYmE="),
237            ("foobar", "Zm9vYmFy"),
238        ] {
239            assert_eq!(base64(input.as_bytes()), output, "{input:?}");
240        }
241    }
242
243    #[test]
244    fn matches_the_reference_across_chunk_boundaries() {
245        let data: Vec<u8> = (0..=u8::MAX).cycle().take(CHUNK * 3 + 2).collect();
246        for len in [
247            0,
248            1,
249            2,
250            3,
251            CHUNK - 1,
252            CHUNK,
253            CHUNK + 1,
254            CHUNK * 2 + 2,
255            data.len(),
256        ] {
257            assert_eq!(base64(&data[..len]), reference(&data[..len]), "len {len}");
258        }
259    }
260
261    #[test]
262    fn detects_signatures() {
263        let detected = |data: &[u8]| ImageData::new(data.to_vec()).map(|image| image.content_type);
264        assert_eq!(detected(b"\xff\xd8\xff\xe0").unwrap(), "image/jpeg");
265        assert_eq!(detected(b"GIF89a...").unwrap(), "image/gif");
266        assert_eq!(detected(b"RIFF\0\0\0\0WEBPVP8 ").unwrap(), "image/webp");
267        assert_eq!(detected(b"\0\0\0\x1cftypavif").unwrap(), "image/avif");
268        assert_eq!(detected(b"RIFF\0\0\0\0WAVE"), Err(ImageDataError));
269        assert_eq!(detected(b""), Err(ImageDataError));
270    }
271
272    #[test]
273    fn debug_hides_the_contents() {
274        let image = ImageData::with_content_type(&b"secret pixels"[..], "image/png");
275        assert_eq!(
276            format!("{image:?}"),
277            r#"ImageData { content_type: "image/png", len: 13 }"#
278        );
279    }
280}