1use core::fmt;
4
5use bytes::Bytes;
6use compact_str::CompactString;
7use serde::{Serialize, Serializer};
8
9#[derive(Clone, PartialEq, Eq, Hash)]
36pub struct ImageData {
37 data: Bytes,
38 content_type: CompactString,
39}
40
41impl ImageData {
42 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 #[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 #[must_use]
81 pub const fn data(&self) -> &Bytes {
82 &self.data
83 }
84
85 #[must_use]
89 pub fn content_type(&self) -> &str {
90 &self.content_type
91 }
92}
93
94impl 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
104impl 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#[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
135fn 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
155const CHUNK: usize = 768;
157
158pub(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 let text = core::str::from_utf8(&buffer[..len]).map_err(|_| fmt::Error)?;
178 out.write_str(text)?;
179 }
180 Ok(())
181}
182
183fn 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 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 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}