forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB24666c0Tahinli6 days ago3938 commits

lib.rs637 lines, 23.6 KiBHistoryRawDownload
1//! Still-image decoding: PNG, JPEG, WebP, GIF, BMP and TIFF.
2//!
3//! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the
4//! format from the leading bytes and hands back an [`Image`]: dimensions, a
5//! [`Pixels`] buffer in the file's own colour form, and the [`Metadata`] the
6//! file declared about it (gamma, sRGB intent, EXIF orientation).
7//!
8//! Contracts worth knowing before implementing against this crate:
9//!
10//! - Metadata is *parsed and exposed, never applied*. A JPEG that says it was
11//! shot sideways decodes to the pixels as stored, with
12//! [`Metadata::orientation`] set; a PNG's gamma is reported, not rendered.
13//! Rotating or gamma-correcting behind the caller's back would make a
14//! round-trip through this crate lossy in a way no caller asked for.
15//! - Sample depth survives: a 16-bit PNG decodes to a 16-bit [`Pixels`]
16//! variant. [`Image::to_rgb8`] and friends convert on demand.
17//! - Refusals are [`ec_core::Error::Unsupported`] naming *what* and *why* —
18//! an animated WebP and a CMYK JPEG each say so rather than producing a
19//! plausible-looking wrong picture.
20//! - Truncated or corrupt input is an error, never a panic and never an
21//! unbounded allocation: [`Limits`] bounds pixel count before any buffer is
22//! sized from header fields.
23//!
24//! No async, no unsafe, no external dependencies beyond the family's own
25//! [`ec_core`] and [`ec_inflate`].
26
27#![forbid(unsafe_code)]
28#![warn(missing_docs)]
29// Coefficient positions, macroblock columns and prediction samples are indices
30// in every specification these decoders implement; iterating them by index is
31// what keeps the code readable against the text it comes from.
32#![allow(clippy::needless_range_loop)]
33
34pub mod bmp;
35pub mod gif;
36pub mod jpeg;
37pub mod png;
38pub mod tiff;
39mod upsample;
40pub mod gif_encode;
41pub mod png_encode;
42pub mod transform;
43pub mod webp;
44
45mod exif;
46mod probe;
47
48pub use probe::{probe, probe_reader, PROBE_LIMIT};
49
50use ec_core::{PixelFormat, Plane, VideoFrame};
51
52// The family's error taxonomy is this crate's too, and a caller that has to
53// name a decode failure needs it in scope.
54pub use ec_core::{Error, Result};
55
56/// The formats this crate decodes.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum ImageFormat {
59 /// Portable Network Graphics (W3C PNG, RFC 2083).
60 Png,
61 /// JFIF/EXIF JPEG (ITU-T T.81 baseline and progressive).
62 Jpeg,
63 /// WebP: a RIFF container over VP8 (lossy) or VP8L (lossless).
64 WebP,
65 /// GIF, still or animated (GIF87a and GIF89a).
66 Gif,
67 /// Windows BMP (device-independent bitmap).
68 Bmp,
69 /// TIFF, the tag-directory format.
70 Tiff,
71}
72
73impl ImageFormat {
74 /// The format whose signature `data` starts with, if any.
75 ///
76 /// This is what `with_guessed_format` means: content, not file extension.
77 pub fn guess(data: &[u8]) -> Option<ImageFormat> {
78 if data.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
79 Some(ImageFormat::Png)
80 } else if data.starts_with(&[0xff, 0xd8, 0xff]) {
81 Some(ImageFormat::Jpeg)
82 } else if data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP" {
83 Some(ImageFormat::WebP)
84 } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
85 Some(ImageFormat::Gif)
86 } else if is_bmp(data) {
87 Some(ImageFormat::Bmp)
88 } else if data.starts_with(b"II\x2a\x00")
89 || data.starts_with(b"MM\x00\x2a")
90 || data.starts_with(b"II\x2b\x00")
91 || data.starts_with(b"MM\x00\x2b")
92 {
93 // 42 is classic TIFF and 43 is BigTIFF; the second is recognised
94 // here so that the decoder can refuse it by name rather than
95 // leaving the file unidentified.
96 Some(ImageFormat::Tiff)
97 } else {
98 None
99 }
100 }
101
102 /// The usual lowercase extension, for diagnostics.
103 pub fn extension(&self) -> &'static str {
104 match self {
105 ImageFormat::Png => "png",
106 ImageFormat::Jpeg => "jpg",
107 ImageFormat::WebP => "webp",
108 ImageFormat::Gif => "gif",
109 ImageFormat::Bmp => "bmp",
110 ImageFormat::Tiff => "tiff",
111 }
112 }
113}
114
115/// Whether `data` opens like a BMP.
116///
117/// "BM" is two bytes, which half the files on a disk could start with by
118/// accident, so the guess also asks the file header to agree with itself: the
119/// declared info-header length must be one the format defines, and the pixel
120/// data must start after the headers.
121fn is_bmp(data: &[u8]) -> bool {
122 if !data.starts_with(b"BM") || data.len() < 18 {
123 return false;
124 }
125 let u32_at =
126 |at: usize| u32::from_le_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]);
127 let offset = u32_at(10) as usize;
128 let info_size = u32_at(14) as usize;
129 matches!(info_size, 12 | 16 | 40 | 52 | 56 | 64 | 108 | 124) && offset >= 14 + info_size
130}
131
132/// The default decode budget for one buffer, in bytes: 512 MiB, the same default the `image`
133/// crate applies. [`decode`] and [`decode_animation`] refuse any picture whose decoded output
134/// (width x height x bytes per pixel) is larger; [`decode_with_limits`] lets a caller raise it.
135pub const DEFAULT_MAX_ALLOC: usize = 512 << 20;
136
137/// Bounds applied before any buffer is sized from a header field.
138///
139/// A three-byte dimension field can ask for a 68-gigapixel allocation; this is
140/// the trust boundary that says no first. The default admits everything the
141/// formats themselves can express up to 2^28 pixels — comfortably past 8K
142/// (33 Mpx) — and refuses a decoded picture past [`DEFAULT_MAX_ALLOC`] bytes.
143#[derive(Debug, Clone, Copy)]
144pub struct Limits {
145 /// Largest `width * height` accepted.
146 pub max_pixels: u64,
147 /// Largest single decompressed buffer accepted, in bytes. The decoded picture
148 /// is the buffer that matters most; see [`Limits::check_output`].
149 pub max_alloc: usize,
150 /// Largest total bytes accepted across every frame of one decode call.
151 ///
152 /// A single frame can pass [`Limits::check_bytes`] on its own and still
153 /// be a bomb once a frame or segment count multiplies it — GIF and WebP
154 /// both composite onto a full canvas per frame, and a stripped or tiled
155 /// TIFF decompresses many segments per call, so a file whose parts each
156 /// look small on their own can still retain gigabytes nothing ever
157 /// checked one buffer at a time. [`AllocBudget`] enforces this across a
158 /// decode call.
159 pub max_total_alloc: usize,
160}
161
162impl Default for Limits {
163 fn default() -> Self {
164 Limits {
165 max_pixels: 1 << 28,
166 max_alloc: DEFAULT_MAX_ALLOC,
167 max_total_alloc: 1 << 32,
168 }
169 }
170}
171
172impl Limits {
173 /// Check a header's dimensions before they size anything.
174 pub fn check(&self, width: u32, height: u32) -> Result<()> {
175 if width == 0 || height == 0 {
176 return Err(Error::corrupt(format!("{width}x{height} image")));
177 }
178 let pixels = u64::from(width) * u64::from(height);
179 if pixels > self.max_pixels {
180 return Err(Error::unsupported(
181 format!("{width}x{height} image"),
182 format!("{pixels} pixels is past the {} limit", self.max_pixels),
183 ));
184 }
185 Ok(())
186 }
187
188 /// Check a decoded picture, `width * height * bytes_per_pixel`, before anything is sized
189 /// from it. A refusal names the dimensions and the budget, and comes before any pixel work.
190 pub fn check_output(&self, width: u32, height: u32, bytes_per_pixel: usize) -> Result<usize> {
191 self.check(width, height)?;
192 let what = format!("{width}x{height} image");
193 let bytes = (width as usize)
194 .checked_mul(height as usize)
195 .and_then(|p| p.checked_mul(bytes_per_pixel))
196 .ok_or_else(|| Error::corrupt(format!("{what}: size overflows usize")))?;
197 if bytes > self.max_alloc {
198 return Err(Error::unsupported(
199 what,
200 format!(
201 "{bytes} bytes of decoded pixels past the {} byte budget \
202 (512 MiB by default; decode_with_limits raises it)",
203 self.max_alloc
204 ),
205 ));
206 }
207 Ok(bytes)
208 }
209
210 /// Check a byte count computed from header-declared fields (a frame's or
211 /// strip's `width * height * bpp`, a palette size, a chunk length) before it
212 /// sizes a single allocation. `what` names the buffer for the error.
213 pub fn check_bytes(&self, what: &str, bytes: Option<usize>) -> Result<usize> {
214 let bytes =
215 bytes.ok_or_else(|| Error::corrupt(format!("{what}: size overflows usize")))?;
216 if bytes > self.max_alloc {
217 return Err(Error::unsupported(
218 what.to_string(),
219 format!("{bytes} bytes past the {} allocation limit", self.max_alloc),
220 ));
221 }
222 Ok(bytes)
223 }
224}
225
226/// Accumulates bytes spent across every frame or segment of one decode call
227/// and refuses once the running total crosses [`Limits::max_total_alloc`] —
228/// the guard for `frame_count x canvas` or `segment_count x segment_size`,
229/// which [`Limits::check_bytes`] alone never sees since it only ever looks
230/// at one buffer at a time.
231#[derive(Debug, Default)]
232pub struct AllocBudget(usize);
233
234impl AllocBudget {
235 /// Spend `bytes` from the budget, refusing once the running total passes
236 /// `limits.max_total_alloc`.
237 pub fn spend(&mut self, limits: &Limits, what: &str, bytes: usize) -> Result<()> {
238 self.0 = self
239 .0
240 .checked_add(bytes)
241 .ok_or_else(|| Error::corrupt(format!("{what}: total size overflows usize")))?;
242 if self.0 > limits.max_total_alloc {
243 return Err(Error::unsupported(
244 what.to_string(),
245 format!(
246 "{} total decoded bytes past the {} limit",
247 self.0, limits.max_total_alloc
248 ),
249 ));
250 }
251 Ok(())
252 }
253}
254
255/// What a file said about its own pixels, parsed but not applied.
256#[derive(Debug, Clone, Copy, Default, PartialEq)]
257pub struct Metadata {
258 /// PNG `gAMA`: the gamma the file was authored at.
259 pub gamma: Option<f64>,
260 /// PNG `sRGB`: rendering intent 0..=3, meaning the file is sRGB.
261 pub srgb_intent: Option<u8>,
262 /// EXIF orientation tag 1..=8, from a JPEG APP1, a PNG `eXIf` or a WebP `EXIF` chunk.
263 ///
264 /// Exposed, never applied — the same choice the incumbent `image` crate
265 /// makes, so a caller swapping between them sees the same pixels.
266 pub orientation: Option<u8>,
267}
268
269/// A decoded image's samples, in the file's own colour form.
270#[derive(Debug, Clone, PartialEq, Eq)]
271pub enum Pixels {
272 /// 8-bit grayscale.
273 L8(Vec<u8>),
274 /// 8-bit grayscale + alpha.
275 La8(Vec<u8>),
276 /// 8-bit R,G,B.
277 Rgb8(Vec<u8>),
278 /// 8-bit R,G,B,A.
279 Rgba8(Vec<u8>),
280 /// 16-bit grayscale.
281 L16(Vec<u16>),
282 /// 16-bit grayscale + alpha.
283 La16(Vec<u16>),
284 /// 16-bit R,G,B.
285 Rgb16(Vec<u16>),
286 /// 16-bit R,G,B,A.
287 Rgba16(Vec<u16>),
288}
289
290impl Pixels {
291 /// Samples per pixel.
292 pub fn channels(&self) -> usize {
293 match self {
294 Pixels::L8(_) | Pixels::L16(_) => 1,
295 Pixels::La8(_) | Pixels::La16(_) => 2,
296 Pixels::Rgb8(_) | Pixels::Rgb16(_) => 3,
297 Pixels::Rgba8(_) | Pixels::Rgba16(_) => 4,
298 }
299 }
300
301 /// Bits per sample: 8 or 16.
302 pub fn bit_depth(&self) -> u8 {
303 match self {
304 Pixels::L8(_) | Pixels::La8(_) | Pixels::Rgb8(_) | Pixels::Rgba8(_) => 8,
305 _ => 16,
306 }
307 }
308
309 /// True when the samples carry an alpha channel.
310 pub fn has_alpha(&self) -> bool {
311 matches!(
312 self,
313 Pixels::La8(_) | Pixels::Rgba8(_) | Pixels::La16(_) | Pixels::Rgba16(_)
314 )
315 }
316}
317
318/// A decoded still image.
319#[derive(Debug, Clone, PartialEq)]
320pub struct Image {
321 /// Width in pixels.
322 pub width: u32,
323 /// Height in pixels.
324 pub height: u32,
325 /// The samples.
326 pub pixels: Pixels,
327 /// What the file declared about them.
328 pub meta: Metadata,
329}
330
331/// Rounding-correct 16-bit sample down to 8 bits: `round(v * 255 / 65535)`.
332fn narrow(v: u16) -> u8 {
333 ((u32::from(v) + 128) / 257) as u8
334}
335
336/// 8-bit sample widened to 16: `v * 65535 / 255`, exact.
337fn widen(v: u8) -> u16 {
338 u16::from(v) * 257
339}
340
341impl Image {
342 /// `(width, height)`.
343 pub fn dimensions(&self) -> (u32, u32) {
344 (self.width, self.height)
345 }
346
347 /// Packed 8-bit R,G,B, dropping any alpha channel.
348 pub fn to_rgb8(&self) -> Vec<u8> {
349 let n = (self.width as usize) * (self.height as usize);
350 let mut out = Vec::with_capacity(n * 3);
351 match &self.pixels {
352 Pixels::L8(d) => d.iter().for_each(|&l| out.extend_from_slice(&[l, l, l])),
353 Pixels::La8(d) => d
354 .as_chunks::<2>().0.iter()
355 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0]])),
356 Pixels::Rgb8(d) => out.extend_from_slice(d),
357 Pixels::Rgba8(d) => d
358 .as_chunks::<4>().0.iter()
359 .for_each(|p| out.extend_from_slice(&p[..3])),
360 Pixels::L16(d) => d.iter().for_each(|&l| {
361 let l = narrow(l);
362 out.extend_from_slice(&[l, l, l]);
363 }),
364 Pixels::La16(d) => d.as_chunks::<2>().0.iter().for_each(|p| {
365 let l = narrow(p[0]);
366 out.extend_from_slice(&[l, l, l]);
367 }),
368 Pixels::Rgb16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
369 Pixels::Rgba16(d) => d
370 .as_chunks::<4>().0.iter()
371 .for_each(|p| out.extend(p[..3].iter().map(|&s| narrow(s)))),
372 }
373 out
374 }
375
376 /// Packed 8-bit R,G,B,A; opaque where the source had no alpha.
377 pub fn to_rgba8(&self) -> Vec<u8> {
378 let n = (self.width as usize) * (self.height as usize);
379 let mut out = Vec::with_capacity(n * 4);
380 match &self.pixels {
381 Pixels::L8(d) => d
382 .iter()
383 .for_each(|&l| out.extend_from_slice(&[l, l, l, 255])),
384 Pixels::La8(d) => d
385 .as_chunks::<2>().0.iter()
386 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0], p[1]])),
387 Pixels::Rgb8(d) => d
388 .as_chunks::<3>().0.iter()
389 .for_each(|p| out.extend_from_slice(&[p[0], p[1], p[2], 255])),
390 Pixels::Rgba8(d) => out.extend_from_slice(d),
391 Pixels::L16(d) => d.iter().for_each(|&l| {
392 let l = narrow(l);
393 out.extend_from_slice(&[l, l, l, 255]);
394 }),
395 Pixels::La16(d) => d.as_chunks::<2>().0.iter().for_each(|p| {
396 let l = narrow(p[0]);
397 out.extend_from_slice(&[l, l, l, narrow(p[1])]);
398 }),
399 Pixels::Rgb16(d) => d.as_chunks::<3>().0.iter().for_each(|p| {
400 out.extend_from_slice(&[narrow(p[0]), narrow(p[1]), narrow(p[2]), 255]);
401 }),
402 Pixels::Rgba16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
403 }
404 out
405 }
406
407 /// Packed 16-bit R,G,B — 8-bit sources widened exactly (`v * 257`).
408 pub fn to_rgb16(&self) -> Vec<u16> {
409 match &self.pixels {
410 Pixels::Rgb16(d) => d.clone(),
411 Pixels::Rgba16(d) => d.as_chunks::<4>().0.iter().flat_map(|p| p[..3].to_vec()).collect(),
412 Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l]).collect(),
413 Pixels::La16(d) => d.as_chunks::<2>().0.iter().flat_map(|p| [p[0], p[0], p[0]]).collect(),
414 _ => self.to_rgb8().into_iter().map(widen).collect(),
415 }
416 }
417
418 /// Packed 16-bit R,G,B,A; opaque where the source had no alpha.
419 pub fn to_rgba16(&self) -> Vec<u16> {
420 match &self.pixels {
421 Pixels::Rgba16(d) => d.clone(),
422 Pixels::Rgb16(d) => d
423 .as_chunks::<3>().0.iter()
424 .flat_map(|p| [p[0], p[1], p[2], u16::MAX])
425 .collect(),
426 Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l, u16::MAX]).collect(),
427 Pixels::La16(d) => d
428 .as_chunks::<2>().0.iter()
429 .flat_map(|p| [p[0], p[0], p[0], p[1]])
430 .collect(),
431 _ => self.to_rgba8().into_iter().map(widen).collect(),
432 }
433 }
434
435 /// The image as an [`ec_core::VideoFrame`], packed RGB8 or RGBA8.
436 ///
437 /// The natural bridge for a caller that composes stills and decoded video
438 /// in one pipeline: alpha survives when the file had it, rather than being
439 /// silently dropped on the way to a frame.
440 pub fn to_video_frame(&self) -> Result<VideoFrame> {
441 let (format, data) = if self.pixels.has_alpha() {
442 (PixelFormat::Rgba8, self.to_rgba8())
443 } else {
444 (PixelFormat::Rgb8, self.to_rgb8())
445 };
446 let stride = (self.width as usize) * if self.pixels.has_alpha() { 4 } else { 3 };
447 VideoFrame::try_new(
448 format,
449 self.width,
450 self.height,
451 vec![Plane::new(data, stride)],
452 )
453 }
454}
455
456/// Dimensions and format from a header alone — the whole file is not decoded.
457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
458pub struct Info {
459 /// Which format the bytes are in.
460 pub format: ImageFormat,
461 /// Width in pixels.
462 pub width: u32,
463 /// Height in pixels.
464 pub height: u32,
465 /// EXIF orientation 1..=8 (1 when the file carries none). Reported, not applied.
466 pub orientation: u8,
467}
468
469/// Decode `data`, guessing the format from its leading bytes.
470pub fn decode(data: &[u8]) -> Result<Image> {
471 decode_with_limits(data, Limits::default())
472}
473
474/// [`decode`] with caller-chosen [`Limits`].
475pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> {
476 match ImageFormat::guess(data) {
477 Some(ImageFormat::Png) => png::decode(data, limits),
478 Some(ImageFormat::Jpeg) => jpeg::decode(data, limits),
479 Some(ImageFormat::WebP) => webp::decode(data, limits),
480 Some(ImageFormat::Gif) => gif::decode(data, limits),
481 Some(ImageFormat::Bmp) => bmp::decode(data, limits),
482 Some(ImageFormat::Tiff) => tiff::decode(data, limits),
483 None => Err(Error::unsupported(
484 "image",
485 "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data",
486 )),
487 }
488}
489
490/// Format, dimensions and EXIF orientation from the header alone, without
491/// decoding the pixels.
492///
493/// The whole of `data` is read as header. To look at a bounded prefix or a
494/// stream instead, use [`probe`] or [`probe_reader`].
495pub fn info(data: &[u8]) -> Result<Info> {
496 match ImageFormat::guess(data) {
497 Some(ImageFormat::Png) => png::info(data),
498 Some(ImageFormat::Jpeg) => jpeg::info(data),
499 Some(ImageFormat::WebP) => webp::info(data),
500 Some(ImageFormat::Gif) => gif::info(data),
501 Some(ImageFormat::Bmp) => bmp::info(data),
502 Some(ImageFormat::Tiff) => tiff::info(data),
503 None => Err(Error::unsupported(
504 "image",
505 "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data",
506 )),
507 }
508}
509
510/// One picture of an animation, already composited onto the canvas.
511///
512/// A frame is the whole canvas, not the sub-rectangle the file stored, because
513/// every consumer of an animation draws whole pictures.
514#[derive(Debug, Clone, PartialEq)]
515pub struct AnimationFrame {
516 /// The canvas at this point in the animation.
517 pub image: Image,
518 /// How long the frame is shown, in `delay_num / delay_den` seconds.
519 pub delay_num: u32,
520 /// The denominator of that delay; GIF counts hundredths of a second.
521 pub delay_den: u32,
522}
523
524/// Every frame of an animation, composited.
525///
526/// A format that cannot animate -- and a single-picture file in one that can
527/// -- returns exactly one frame, with a zero delay, so a caller that wants
528/// frames never needs to know which format it holds.
529pub fn decode_animation(data: &[u8]) -> Result<Vec<AnimationFrame>> {
530 decode_animation_with_limits(data, Limits::default())
531}
532
533/// [`decode_animation`] with caller-chosen [`Limits`].
534///
535/// The limits bound every frame and the whole composite, so a caller with a
536/// tighter memory budget than the default can lower them here.
537pub fn decode_animation_with_limits(data: &[u8], limits: Limits) -> Result<Vec<AnimationFrame>> {
538 match ImageFormat::guess(data) {
539 Some(ImageFormat::Gif) => gif::decode_animation(data, limits),
540 Some(ImageFormat::WebP) if webp::is_animated(data) => webp::decode_frames(data, limits),
541 _ => Ok(vec![AnimationFrame {
542 image: decode_with_limits(data, limits)?,
543 delay_num: 0,
544 delay_den: 100,
545 }]),
546 }
547}
548
549/// Read and decode the file at `path`.
550pub fn open(path: impl AsRef<std::path::Path>) -> Result<Image> {
551 let data = std::fs::read(path).map_err(Error::Io)?;
552 decode(&data)
553}
554
555/// Read the file at `path` and report its header dimensions.
556pub fn open_info(path: impl AsRef<std::path::Path>) -> Result<Info> {
557 let data = std::fs::read(path).map_err(Error::Io)?;
558 info(&data)
559}
560
561#[cfg(test)]
562mod tests {
563 use super::*;
564
565 #[test]
566 fn guess_reads_signatures_not_extensions() {
567 assert_eq!(
568 ImageFormat::guess(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0]),
569 Some(ImageFormat::Png)
570 );
571 assert_eq!(
572 ImageFormat::guess(&[0xff, 0xd8, 0xff, 0xe0]),
573 Some(ImageFormat::Jpeg)
574 );
575 let mut webp = b"RIFF\0\0\0\0WEBPVP8 ".to_vec();
576 webp.push(0);
577 assert_eq!(ImageFormat::guess(&webp), Some(ImageFormat::WebP));
578 assert_eq!(ImageFormat::guess(b"RIFF\0\0\0\0WAVEfmt "), None);
579 assert_eq!(ImageFormat::guess(b""), None);
580 }
581
582 #[test]
583 fn sample_conversion_round_trips_through_eight_bits() {
584 for v in 0..=255u8 {
585 assert_eq!(narrow(widen(v)), v, "{v}");
586 }
587 assert_eq!(narrow(0), 0);
588 assert_eq!(narrow(u16::MAX), 255);
589 assert_eq!(narrow(32768), 128);
590 }
591
592 #[test]
593 fn limits_refuse_before_allocating() {
594 let limits = Limits::default();
595 assert!(limits.check(1920, 1080).is_ok());
596 assert!(limits.check(0, 10).is_err());
597 assert!(limits.check(100_000, 100_000).is_err());
598 }
599
600 #[test]
601 fn check_output_names_the_picture_and_refuses_past_the_budget() {
602 let limits = Limits::default();
603 assert_eq!(limits.max_alloc, 512 << 20);
604 assert!(limits.check_output(12000, 12000, 3).is_ok());
605 let err = limits.check_output(12000, 12000, 4).expect_err("576 MB is past 512 MiB");
606 let text = format!("{err}");
607 assert!(text.contains("12000x12000"), "{text}");
608 assert!(text.contains("536870912"), "{text}");
609 }
610
611 #[test]
612 fn check_bytes_refuses_past_max_alloc_before_a_frame_size_carries_it() {
613 let limits = Limits::default();
614 assert!(limits.check_bytes("test", Some(1024)).is_ok());
615 assert!(limits.check_bytes("test", Some(limits.max_alloc + 1)).is_err());
616 assert!(limits.check_bytes("test", None).is_err());
617 }
618
619 #[test]
620 fn alloc_budget_refuses_once_repeated_spends_cross_the_total() {
621 // The class this guards: no single spend is ever over budget on its
622 // own, but a canvas cloned once per animation frame is.
623 let limits = Limits::default();
624 let mut budget = AllocBudget::default();
625 let per_frame = limits.max_total_alloc / 4;
626 for i in 0..4 {
627 assert!(
628 budget.spend(&limits, "frame", per_frame).is_ok(),
629 "frame {i} alone is within budget"
630 );
631 }
632 assert!(
633 budget.spend(&limits, "frame", per_frame).is_err(),
634 "a fifth frame the same size crosses the total"
635 );
636 }
637}