forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBb8521ccTahinli9 hours ago4437 commits

lib.rs599 lines, 22.0 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
336impl Image {
337 /// `(width, height)`.
338 pub fn dimensions(&self) -> (u32, u32) {
339 (self.width, self.height)
340 }
341
342 /// Packed 8-bit R,G,B, dropping any alpha channel.
343 pub fn to_rgb8(&self) -> Vec<u8> {
344 let n = (self.width as usize) * (self.height as usize);
345 let mut out = Vec::with_capacity(n * 3);
346 match &self.pixels {
347 Pixels::L8(d) => d.iter().for_each(|&l| out.extend_from_slice(&[l, l, l])),
348 Pixels::La8(d) => d
349 .as_chunks::<2>().0.iter()
350 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0]])),
351 Pixels::Rgb8(d) => out.extend_from_slice(d),
352 Pixels::Rgba8(d) => d
353 .as_chunks::<4>().0.iter()
354 .for_each(|p| out.extend_from_slice(&p[..3])),
355 Pixels::L16(d) => d.iter().for_each(|&l| {
356 let l = narrow(l);
357 out.extend_from_slice(&[l, l, l]);
358 }),
359 Pixels::La16(d) => d.as_chunks::<2>().0.iter().for_each(|p| {
360 let l = narrow(p[0]);
361 out.extend_from_slice(&[l, l, l]);
362 }),
363 Pixels::Rgb16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
364 Pixels::Rgba16(d) => d
365 .as_chunks::<4>().0.iter()
366 .for_each(|p| out.extend(p[..3].iter().map(|&s| narrow(s)))),
367 }
368 out
369 }
370
371 /// Packed 8-bit R,G,B,A; opaque where the source had no alpha.
372 pub fn to_rgba8(&self) -> Vec<u8> {
373 let n = (self.width as usize) * (self.height as usize);
374 let mut out = Vec::with_capacity(n * 4);
375 match &self.pixels {
376 Pixels::L8(d) => d
377 .iter()
378 .for_each(|&l| out.extend_from_slice(&[l, l, l, 255])),
379 Pixels::La8(d) => d
380 .as_chunks::<2>().0.iter()
381 .for_each(|p| out.extend_from_slice(&[p[0], p[0], p[0], p[1]])),
382 Pixels::Rgb8(d) => d
383 .as_chunks::<3>().0.iter()
384 .for_each(|p| out.extend_from_slice(&[p[0], p[1], p[2], 255])),
385 Pixels::Rgba8(d) => out.extend_from_slice(d),
386 Pixels::L16(d) => d.iter().for_each(|&l| {
387 let l = narrow(l);
388 out.extend_from_slice(&[l, l, l, 255]);
389 }),
390 Pixels::La16(d) => d.as_chunks::<2>().0.iter().for_each(|p| {
391 let l = narrow(p[0]);
392 out.extend_from_slice(&[l, l, l, narrow(p[1])]);
393 }),
394 Pixels::Rgb16(d) => d.as_chunks::<3>().0.iter().for_each(|p| {
395 out.extend_from_slice(&[narrow(p[0]), narrow(p[1]), narrow(p[2]), 255]);
396 }),
397 Pixels::Rgba16(d) => d.iter().for_each(|&s| out.push(narrow(s))),
398 }
399 out
400 }
401
402 /// The image as an [`ec_core::VideoFrame`], packed RGB8 or RGBA8.
403 ///
404 /// The natural bridge for a caller that composes stills and decoded video
405 /// in one pipeline: alpha survives when the file had it, rather than being
406 /// silently dropped on the way to a frame.
407 pub fn to_video_frame(&self) -> Result<VideoFrame> {
408 let (format, data) = if self.pixels.has_alpha() {
409 (PixelFormat::Rgba8, self.to_rgba8())
410 } else {
411 (PixelFormat::Rgb8, self.to_rgb8())
412 };
413 let stride = (self.width as usize) * if self.pixels.has_alpha() { 4 } else { 3 };
414 VideoFrame::try_new(
415 format,
416 self.width,
417 self.height,
418 vec![Plane::new(data, stride)],
419 )
420 }
421}
422
423/// Dimensions and format from a header alone — the whole file is not decoded.
424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
425pub struct Info {
426 /// Which format the bytes are in.
427 pub format: ImageFormat,
428 /// Width in pixels.
429 pub width: u32,
430 /// Height in pixels.
431 pub height: u32,
432 /// EXIF orientation 1..=8 (1 when the file carries none). Reported, not applied.
433 pub orientation: u8,
434}
435
436fn format_of(data: &[u8]) -> Result<ImageFormat> {
437 ImageFormat::guess(data).ok_or_else(|| {
438 Error::unsupported(
439 "image",
440 "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data",
441 )
442 })
443}
444
445/// Decode `data`, guessing the format from its leading bytes.
446pub fn decode(data: &[u8]) -> Result<Image> {
447 decode_with_limits(data, Limits::default())
448}
449
450/// [`decode`] with caller-chosen [`Limits`].
451pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> {
452 match format_of(data)? {
453 ImageFormat::Png => png::decode(data, limits),
454 ImageFormat::Jpeg => jpeg::decode(data, limits),
455 ImageFormat::WebP => webp::decode(data, limits),
456 ImageFormat::Gif => gif::decode(data, limits),
457 ImageFormat::Bmp => bmp::decode(data, limits),
458 ImageFormat::Tiff => tiff::decode(data, limits),
459 }
460}
461
462/// Format, dimensions and EXIF orientation from the header alone, without
463/// decoding the pixels.
464///
465/// The whole of `data` is read as header. To look at a bounded prefix or a
466/// stream instead, use [`probe`] or [`probe_reader`].
467pub fn info(data: &[u8]) -> Result<Info> {
468 match format_of(data)? {
469 ImageFormat::Png => png::info(data),
470 ImageFormat::Jpeg => jpeg::info(data),
471 ImageFormat::WebP => webp::info(data),
472 ImageFormat::Gif => gif::info(data),
473 ImageFormat::Bmp => bmp::info(data),
474 ImageFormat::Tiff => tiff::info(data),
475 }
476}
477
478/// One picture of an animation, already composited onto the canvas.
479///
480/// A frame is the whole canvas, not the sub-rectangle the file stored, because
481/// every consumer of an animation draws whole pictures.
482#[derive(Debug, Clone, PartialEq)]
483pub struct AnimationFrame {
484 /// The canvas at this point in the animation.
485 pub image: Image,
486 /// How long the frame is shown, in `delay_num / delay_den` seconds.
487 pub delay_num: u32,
488 /// The denominator of that delay; GIF counts hundredths of a second.
489 pub delay_den: u32,
490}
491
492/// Every frame of an animation, composited.
493///
494/// A format that cannot animate -- and a single-picture file in one that can
495/// -- returns exactly one frame, with a zero delay, so a caller that wants
496/// frames never needs to know which format it holds.
497pub fn decode_animation(data: &[u8]) -> Result<Vec<AnimationFrame>> {
498 decode_animation_with_limits(data, Limits::default())
499}
500
501/// [`decode_animation`] with caller-chosen [`Limits`].
502///
503/// The limits bound every frame and the whole composite, so a caller with a
504/// tighter memory budget than the default can lower them here.
505pub fn decode_animation_with_limits(data: &[u8], limits: Limits) -> Result<Vec<AnimationFrame>> {
506 match format_of(data)? {
507 ImageFormat::Gif => gif::decode_animation(data, limits),
508 ImageFormat::WebP if webp::is_animated(data) => webp::decode_frames(data, limits),
509 _ => Ok(vec![AnimationFrame {
510 image: decode_with_limits(data, limits)?,
511 delay_num: 0,
512 delay_den: 100,
513 }]),
514 }
515}
516
517/// Read and decode the file at `path`.
518pub fn open(path: impl AsRef<std::path::Path>) -> Result<Image> {
519 let data = std::fs::read(path).map_err(Error::Io)?;
520 decode(&data)
521}
522
523#[cfg(test)]
524mod tests {
525 use super::*;
526
527 #[test]
528 fn guess_reads_signatures_not_extensions() {
529 assert_eq!(
530 ImageFormat::guess(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0]),
531 Some(ImageFormat::Png)
532 );
533 assert_eq!(
534 ImageFormat::guess(&[0xff, 0xd8, 0xff, 0xe0]),
535 Some(ImageFormat::Jpeg)
536 );
537 let mut webp = b"RIFF\0\0\0\0WEBPVP8 ".to_vec();
538 webp.push(0);
539 assert_eq!(ImageFormat::guess(&webp), Some(ImageFormat::WebP));
540 assert_eq!(ImageFormat::guess(b"RIFF\0\0\0\0WAVEfmt "), None);
541 assert_eq!(ImageFormat::guess(b""), None);
542 }
543
544 #[test]
545 fn sample_conversion_round_trips_through_eight_bits() {
546 for v in 0..=255u8 {
547 assert_eq!(narrow(u16::from(v) * 257), v, "{v}");
548 }
549 assert_eq!(narrow(0), 0);
550 assert_eq!(narrow(u16::MAX), 255);
551 assert_eq!(narrow(32768), 128);
552 }
553
554 #[test]
555 fn limits_refuse_before_allocating() {
556 let limits = Limits::default();
557 assert!(limits.check(1920, 1080).is_ok());
558 assert!(limits.check(0, 10).is_err());
559 assert!(limits.check(100_000, 100_000).is_err());
560 }
561
562 #[test]
563 fn check_output_names_the_picture_and_refuses_past_the_budget() {
564 let limits = Limits::default();
565 assert_eq!(limits.max_alloc, 512 << 20);
566 assert!(limits.check_output(12000, 12000, 3).is_ok());
567 let err = limits.check_output(12000, 12000, 4).expect_err("576 MB is past 512 MiB");
568 let text = format!("{err}");
569 assert!(text.contains("12000x12000"), "{text}");
570 assert!(text.contains("536870912"), "{text}");
571 }
572
573 #[test]
574 fn check_bytes_refuses_past_max_alloc_before_a_frame_size_carries_it() {
575 let limits = Limits::default();
576 assert!(limits.check_bytes("test", Some(1024)).is_ok());
577 assert!(limits.check_bytes("test", Some(limits.max_alloc + 1)).is_err());
578 assert!(limits.check_bytes("test", None).is_err());
579 }
580
581 #[test]
582 fn alloc_budget_refuses_once_repeated_spends_cross_the_total() {
583 // The class this guards: no single spend is ever over budget on its
584 // own, but a canvas cloned once per animation frame is.
585 let limits = Limits::default();
586 let mut budget = AllocBudget::default();
587 let per_frame = limits.max_total_alloc / 4;
588 for i in 0..4 {
589 assert!(
590 budget.spend(&limits, "frame", per_frame).is_ok(),
591 "frame {i} alone is within budget"
592 );
593 }
594 assert!(
595 budget.spend(&limits, "frame", per_frame).is_err(),
596 "a fifth frame the same size crosses the total"
597 );
598 }
599}