1use std::{
23 fmt,
24 ops::Deref,
25 path::PathBuf,
26 sync::{Arc, Weak},
27};
28
29use rustc_hash::FxHashMap;
30
31#[cfg(not(target_arch = "wasm32"))]
32#[cfg(feature = "animation")]
33pub mod animation;
34#[cfg(not(target_arch = "wasm32"))]
35mod cache;
36#[cfg(not(target_arch = "wasm32"))]
37pub use cache::{CacheHeaders, DEFAULT_DISK_CACHE_SIZE, DiskCache, Fetched, Lookup, Validators};
38#[cfg(not(target_arch = "wasm32"))]
39mod decoded;
40#[cfg(not(target_arch = "wasm32"))]
41pub mod loader;
42mod memory;
43mod natural;
44#[cfg(not(target_arch = "wasm32"))]
45pub use decoded::{Decoded, Decoder, Done, Frames, Images, Key, Request, Target, Want};
46pub use memory::{Budget, Lease, MemoryCache, bucket, budget, default_budget, wanted};
47pub use natural::Natural;
48
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
55pub enum AssetBase {
56 Http(String),
58 Directory(PathBuf),
60 Directories(Vec<PathBuf>),
64}
65
66type Bytes = dyn AsRef<[u8]> + Send + Sync;
67
68#[derive(Clone)]
71pub struct ImageData {
72 bytes: Arc<Bytes>,
73 rgba: Option<Arc<Rgba>>,
76}
77
78impl ImageData {
79 pub fn new(bytes: impl AsRef<[u8]> + Send + Sync + 'static) -> Self {
82 Self {
83 bytes: Arc::new(bytes),
84 rgba: None,
85 }
86 }
87
88 pub(crate) fn from_rgba(
97 width: u32,
98 height: u32,
99 pixels: impl AsRef<[u8]> + Send + Sync + 'static,
100 ) -> Self {
101 let len = pixels.as_ref().len();
102 assert!(
103 width > 0 && height > 0 && len as u64 == u64::from(width) * u64::from(height) * 4,
104 "an RGBA image of {width}x{height} pixels takes {} bytes, not {len}",
105 u64::from(width) * u64::from(height) * 4
106 );
107 let rgba = Arc::new(Rgba {
108 width,
109 height,
110 pixels: Box::new(pixels),
111 png: std::sync::OnceLock::new(),
112 });
113 Self {
114 bytes: rgba.clone(),
115 rgba: Some(rgba),
116 }
117 }
118
119 pub fn bytes(&self) -> &[u8] {
122 (*self.bytes).as_ref()
123 }
124
125 pub fn rgba(&self) -> Option<(u32, u32, &[u8])> {
128 self.rgba
129 .as_deref()
130 .map(|r| (r.width, r.height, (*r.pixels).as_ref()))
131 }
132
133 fn downgrade(&self) -> Weak<Bytes> {
134 Arc::downgrade(&self.bytes)
135 }
136}
137
138struct Rgba {
141 width: u32,
142 height: u32,
143 pixels: Box<Bytes>,
144 png: std::sync::OnceLock<Vec<u8>>,
145}
146
147impl AsRef<[u8]> for Rgba {
148 fn as_ref(&self) -> &[u8] {
149 self.png
150 .get_or_init(|| stored_png(self.width, self.height, (*self.pixels).as_ref()))
151 }
152}
153
154fn stored_png(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
157 fn crc32(parts: &[&[u8]]) -> u32 {
158 static TABLE: std::sync::LazyLock<[u32; 256]> = std::sync::LazyLock::new(|| {
159 std::array::from_fn(|n| {
160 (0..8).fold(n as u32, |c, _| {
161 if c & 1 == 1 {
162 0xedb8_8320 ^ (c >> 1)
163 } else {
164 c >> 1
165 }
166 })
167 })
168 });
169 !parts.iter().flat_map(|p| p.iter()).fold(!0u32, |c, &b| {
170 TABLE[((c ^ u32::from(b)) & 0xff) as usize] ^ (c >> 8)
171 })
172 }
173 fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
174 out.extend_from_slice(&(data.len() as u32).to_be_bytes());
175 out.extend_from_slice(kind);
176 out.extend_from_slice(data);
177 out.extend_from_slice(&crc32(&[kind, data]).to_be_bytes());
178 }
179 let row = width as usize * 4;
180 let raw_len = (row + 1) * height as usize;
182 let mut zlib = Vec::with_capacity(raw_len + raw_len / 0xffff * 5 + 16);
183 zlib.extend_from_slice(&[0x78, 0x01]);
184 let (mut a, mut b) = (1u32, 0u32);
185 let mut raw = rgba
186 .chunks_exact(row)
187 .flat_map(|r| std::iter::once(&0u8).chain(r.iter()));
188 let mut left = raw_len;
189 while left > 0 {
190 let n = left.min(0xffff);
191 left -= n;
192 zlib.push(u8::from(left == 0));
193 zlib.extend_from_slice(&(n as u16).to_le_bytes());
194 zlib.extend_from_slice(&(!(n as u16)).to_le_bytes());
195 for &byte in raw.by_ref().take(n) {
196 zlib.push(byte);
197 a = (a + u32::from(byte)) % 65521;
198 b = (b + a) % 65521;
199 }
200 }
201 zlib.extend_from_slice(&((b << 16) | a).to_be_bytes());
202 let mut out = Vec::with_capacity(zlib.len() + 64);
203 out.extend_from_slice(b"\x89PNG\r\n\x1a\n");
204 let mut ihdr = [0u8; 13];
205 ihdr[..4].copy_from_slice(&width.to_be_bytes());
206 ihdr[4..8].copy_from_slice(&height.to_be_bytes());
207 ihdr[8..].copy_from_slice(&[8, 6, 0, 0, 0]);
208 chunk(&mut out, b"IHDR", &ihdr);
209 chunk(&mut out, b"IDAT", &zlib);
210 chunk(&mut out, b"IEND", &[]);
211 out
212}
213
214pub(crate) fn rgba_key() -> String {
219 use std::{
220 fmt::Write,
221 hash::BuildHasher,
222 sync::atomic::{AtomicU64, Ordering},
223 };
224 static NEXT: AtomicU64 = AtomicU64::new(0);
225 static SEED: std::sync::LazyLock<std::hash::RandomState> =
226 std::sync::LazyLock::new(std::hash::RandomState::new);
227 let n = NEXT.fetch_add(1, Ordering::Relaxed);
228 let mut key = String::from("data:image/png;nsh-key=");
229 let _ = write!(key, "{:016x}{n:016x}", SEED.hash_one(n));
230 key
231}
232
233impl Default for ImageData {
234 fn default() -> Self {
236 Self::new(Vec::new())
237 }
238}
239
240impl Deref for ImageData {
241 type Target = [u8];
242
243 fn deref(&self) -> &[u8] {
244 self.bytes()
245 }
246}
247
248impl AsRef<[u8]> for ImageData {
249 fn as_ref(&self) -> &[u8] {
250 self.bytes()
251 }
252}
253
254impl From<Vec<u8>> for ImageData {
255 fn from(bytes: Vec<u8>) -> Self {
256 Self::new(bytes)
257 }
258}
259
260impl PartialEq for ImageData {
261 fn eq(&self, other: &Self) -> bool {
262 std::ptr::addr_eq(Arc::as_ptr(&self.bytes), Arc::as_ptr(&other.bytes))
263 }
264}
265
266impl fmt::Debug for ImageData {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 match self.rgba() {
269 Some((w, h, _)) => write!(f, "ImageData({w}x{h} RGBA)"),
270 None => write!(f, "ImageData({} bytes)", self.bytes().len()),
271 }
272 }
273}
274
275pub fn decode_data_uri(uri: &str) -> Result<(&str, Vec<u8>), String> {
279 let rest = uri.strip_prefix("data:").ok_or("not a data: URI")?;
280 let (meta, data) = rest.split_once(',').ok_or("malformed data: URI")?;
281 match meta.strip_suffix(";base64") {
282 Some(mime) => Ok((mime, base64(data)?)),
283 None => Ok((meta, percent_decode(data))),
284 }
285}
286
287pub(crate) fn data_key(mime: &str, bytes: &[u8]) -> String {
293 use std::fmt::Write;
294
295 use sha2::Digest;
296 let digest = sha2::Sha256::digest(bytes);
297 let mime = mime.split(';').next().unwrap_or_default();
298 let mut key = format!("data:{mime};nsh-key=");
299 for b in &digest[..16] {
300 let _ = write!(key, "{b:02x}");
301 }
302 key
303}
304
305fn base64(s: &str) -> Result<Vec<u8>, String> {
306 let value = |c: u8| match c {
307 b'A'..=b'Z' => Some(c - b'A'),
308 b'a'..=b'z' => Some(c - b'a' + 26),
309 b'0'..=b'9' => Some(c - b'0' + 52),
310 b'+' | b'-' => Some(62),
311 b'/' | b'_' => Some(63),
312 _ => None,
313 };
314 let mut out = Vec::with_capacity(s.len() / 4 * 3 + 2);
315 let (mut acc, mut bits) = (0u32, 0);
316 for c in s.bytes() {
317 if c == b'=' || c.is_ascii_whitespace() {
318 continue;
319 }
320 let v = value(c).ok_or("invalid base64 in a data: URI")?;
321 acc = (acc << 6) | u32::from(v);
322 bits += 6;
323 if bits >= 8 {
324 bits -= 8;
325 out.push((acc >> bits) as u8);
326 }
327 }
328 Ok(out)
329}
330
331fn percent_decode(s: &str) -> Vec<u8> {
332 let bytes = s.as_bytes();
333 let hex = |b: u8| (b as char).to_digit(16);
334 let mut out = Vec::with_capacity(bytes.len());
335 let mut i = 0;
336 while i < bytes.len() {
337 match (
338 bytes[i],
339 bytes.get(i + 1).and_then(|&b| hex(b)),
340 bytes.get(i + 2).and_then(|&b| hex(b)),
341 ) {
342 (b'%', Some(h), Some(l)) => {
343 out.push((h * 16 + l) as u8);
344 i += 3;
345 }
346 (b, _, _) => {
347 out.push(b);
348 i += 1;
349 }
350 }
351 }
352 out
353}
354
355#[derive(Default)]
361pub struct InlineImages {
362 map: FxHashMap<Arc<str>, Vec<Weak<Bytes>>>,
365}
366
367impl InlineImages {
368 pub fn register(&mut self, source: &crate::ImageSource) -> bool {
371 let Some(data) = &source.data else {
372 return false;
373 };
374 let held = self.map.entry(source.uri.clone()).or_default();
375 let new = !held.iter().any(|w| w.strong_count() > 0);
376 let ptr = Arc::as_ptr(&data.bytes);
377 if !held.iter().any(|w| std::ptr::addr_eq(w.as_ptr(), ptr)) {
378 held.push(data.downgrade());
379 }
380 new
381 }
382
383 pub fn get(&self, uri: &str) -> Option<ImageData> {
385 self.map
386 .get(uri)?
387 .iter()
388 .find_map(Weak::upgrade)
389 .map(|bytes| ImageData { bytes, rgba: None })
390 }
391
392 pub fn prune(&mut self) -> Vec<Arc<str>> {
395 let mut gone = Vec::new();
396 self.map.retain(|uri, held| {
397 held.retain(|w| w.strong_count() > 0);
398 if held.is_empty() {
399 gone.push(uri.clone());
400 }
401 !held.is_empty()
402 });
403 gone
404 }
405}
406
407pub fn density(uri: &str) -> f32 {
409 let uri = if uri.starts_with("http://") || uri.starts_with("https://") {
410 uri.split_once(['?', '#']).map_or(uri, |(path, _)| path)
411 } else {
412 uri
413 };
414 let name = uri.rsplit(['/', '\\']).next().unwrap_or(uri);
415 let stem = name.rsplit_once('.').map_or(name, |(stem, _)| stem);
416 stem.rsplit_once('@')
417 .and_then(|(_, s)| s.strip_suffix('x'))
418 .and_then(|n| n.parse::<f32>().ok())
419 .filter(|n| *n > 0.0)
420 .unwrap_or(1.0)
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426 use crate::ImageSource;
427
428 #[test]
429 fn decodes_base64_and_percent_encoded_uris() {
430 assert_eq!(
431 decode_data_uri("data:image/png;base64,aGk=").unwrap(),
432 ("image/png", b"hi".to_vec())
433 );
434 assert_eq!(
436 decode_data_uri("data:;base64,_-8 \n").unwrap().1,
437 vec![0xff, 0xef]
438 );
439 assert_eq!(
440 decode_data_uri("data:image/svg+xml,%3Csvg%3E%zz").unwrap(),
441 ("image/svg+xml", b"<svg>%zz".to_vec())
442 );
443 assert!(decode_data_uri("data:nocomma").is_err());
444 assert!(decode_data_uri("data:;base64,a*b").is_err());
445 assert!(decode_data_uri("https://example.com/a.png").is_err());
446 }
447
448 #[test]
449 fn data_sources_are_decoded_once_under_a_short_key() {
450 let uri = format!("data:image/png;charset=x;base64,{}", "QUJD".repeat(1000));
451 let source = ImageSource {
452 uri: uri.as_str().into(),
453 ..ImageSource::default()
454 }
455 .inline();
456 let data = source.data.clone().unwrap();
457 assert_eq!(data.len(), 3000);
458 assert!(source.uri.starts_with("data:image/png;nsh-key="));
459 assert_eq!(source.uri.len(), "data:image/png;nsh-key=".len() + 32);
460 let again = ImageSource {
462 uri: uri.as_str().into(),
463 ..ImageSource::default()
464 }
465 .inline();
466 assert_eq!(again.uri, source.uri);
467 let other = ImageSource {
468 uri: "data:image/png;base64,QUJE".into(),
469 ..ImageSource::default()
470 }
471 .inline();
472 assert_ne!(other.uri, source.uri);
473 let forged = ImageSource {
475 uri: source.uri.clone(),
476 ..ImageSource::default()
477 }
478 .inline();
479 assert_eq!(&*forged.uri, "data:,");
480 assert!(forged.data.is_none());
481 let remote = ImageSource {
483 uri: "https://x.org/a.png".into(),
484 ..ImageSource::default()
485 }
486 .inline();
487 assert_eq!(&*remote.uri, "https://x.org/a.png");
488 assert!(remote.data.is_none());
489 let bad = ImageSource {
490 uri: "data:nocomma".into(),
491 ..ImageSource::default()
492 }
493 .inline();
494 assert_eq!(&*bad.uri, "data:,");
495 assert!(bad.data.is_none());
496 }
497
498 #[test]
499 fn rgba_sources_keep_their_pixels_under_a_unique_key() {
500 let pixels: Arc<[u8]> = (0..3 * 2 * 4).map(|i| i as u8).collect();
501 let src = crate::element::ImageSrc::rgba(3, 2, pixels.clone());
502 let again = crate::element::ImageSrc::rgba(3, 2, pixels.clone());
503 assert_ne!(src.uri, again.uri);
506 assert!(src.uri.starts_with("data:image/png;nsh-key="));
507 assert_eq!(src.size, Some((3.0, 2.0)));
508 let sized = src.clone().size(crate::geometry::size_pt(1.5, 1.0));
509 assert_eq!(sized.size, Some((1.5, 1.0)));
510 assert_eq!(sized.uri, src.uri);
511 assert_eq!(sized.data, src.data);
512 let data = sized.data.clone().unwrap();
513 let (w, h, rgba) = data.rgba().unwrap();
514 assert_eq!((w, h), (3, 2));
515 assert!(std::ptr::eq(rgba, &*pixels));
516 assert_eq!(format!("{data:?}"), "ImageData(3x2 RGBA)");
517 let forged = ImageSource {
518 uri: src.uri.to_arc(),
519 ..ImageSource::default()
520 }
521 .inline();
522 assert_eq!(&*forged.uri, "data:,");
523 assert_eq!(&data.bytes()[..8], b"\x89PNG\r\n\x1a\n");
525 assert_eq!(
526 crate::image::Natural::of(data.bytes()),
527 Some(crate::image::Natural::Pixels(3, 2))
528 );
529 }
530
531 #[test]
532 #[should_panic(expected = "takes 24 bytes, not 23")]
533 fn rgba_sources_check_their_length() {
534 crate::element::ImageSrc::rgba(3, 2, vec![0u8; 23]);
535 }
536
537 #[cfg(feature = "svg")]
538 #[test]
539 fn rgba_sources_encode_to_a_png_that_decodes_to_them() {
540 let (w, h) = (130u32, 140u32);
542 let pixels: Vec<u8> = (0..w * h)
543 .flat_map(|i| [(i % 251) as u8, (i % 13) as u8, (i / 256) as u8, 255])
544 .collect();
545 let data = crate::ImageData::from_rgba(w, h, pixels.clone());
546 let png = resvg::tiny_skia::Pixmap::decode_png(data.bytes()).unwrap();
547 assert_eq!((png.width(), png.height()), (w, h));
548 assert_eq!(png.data(), &pixels[..]);
549 }
550
551 #[test]
552 fn inline_images_live_as_long_as_their_sources() {
553 let mut images = InlineImages::default();
554 let source = ImageSource {
555 uri: "blob:nsh://app/1".into(),
556 data: Some(ImageData::new(vec![1u8, 2, 3])),
557 ..ImageSource::default()
558 };
559 assert!(images.register(&source));
560 assert!(!images.register(&source.clone()));
561 assert_eq!(images.get("blob:nsh://app/1").unwrap().bytes(), &[1, 2, 3]);
562 assert!(images.prune().is_empty());
563 drop(source);
564 assert!(images.get("blob:nsh://app/1").is_none());
565 assert_eq!(images.prune(), vec![Arc::<str>::from("blob:nsh://app/1")]);
566 assert!(!images.register(&ImageSource {
567 uri: "https://x.org/a.png".into(),
568 ..ImageSource::default()
569 }));
570 let a = ImageSource::default().with_bytes("image/png", vec![7u8].into());
573 let b = ImageSource::default().with_bytes("image/png", vec![7u8].into());
574 assert_eq!(a.uri, b.uri);
575 assert!(images.register(&a));
576 assert!(!images.register(&b));
577 drop(a);
578 assert!(images.prune().is_empty());
579 assert_eq!(images.get(&b.uri).unwrap().bytes(), &[7]);
580 }
581}