forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBe18142dTahinli7 hours ago4543 commits

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