zencodec 0.1.14

Shared traits and types for zen* image codecs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! Resource limits for codec operations.
//!
//! [`ResourceLimits`] defines caps on resource usage. [`LimitExceeded`]
//! is returned when a check fails. Use the `check_*` methods for
//! parse-time rejection (fastest — reject before any pixel work).

/// Threading policy for codec operations.
///
/// Controls how many threads a codec may use. Codecs report their
/// supported range via
/// [`EncodeCapabilities::threads_supported_range()`](crate::EncodeCapabilities::threads_supported_range)
/// and [`DecodeCapabilities::threads_supported_range()`](crate::DecodeCapabilities::threads_supported_range).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ThreadingPolicy {
    /// Force single-threaded operation.
    ///
    /// Useful for deterministic output or constrained environments.
    SingleThread,

    /// Use at most `max_threads` threads. If the codec would need more,
    /// fall back to single-threaded.
    LimitOrSingle {
        /// Maximum thread count before falling back to single-threaded.
        max_threads: u16,
    },

    /// Prefer at most `preferred_max_threads` threads, but the codec
    /// may use more if it needs to.
    LimitOrAny {
        /// Preferred maximum thread count (advisory, not enforced).
        preferred_max_threads: u16,
    },

    /// Let the codec pick a reasonable thread count based on available
    /// parallelism (typically half of available cores or similar).
    Balanced,

    /// No thread limit. Use as many threads as the codec wants.
    #[default]
    Unlimited,
}

/// Resource limits for encode/decode operations.
///
/// Used to prevent DoS attacks and resource exhaustion. All fields are optional;
/// `None` means no limit for that resource.
///
/// Codecs enforce what they can — not all codecs support all limit types.
/// Use the `check_*` methods for caller-side validation before decode/encode.
///
/// # Example
///
/// ```
/// use zencodec::ResourceLimits;
///
/// let limits = ResourceLimits::none()
///     .with_max_pixels(100_000_000)
///     .with_max_memory(512 * 1024 * 1024);
/// ```
///
/// Typical usage with a decoder:
///
/// ```ignore
/// // Parse-time rejection (before any pixel work)
/// let info = config.probe_header(data)?;
/// limits.check_image_info(&info)?;
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResourceLimits {
    /// Maximum pixels in a single frame (width × height).
    ///
    /// This is a **per-frame** limit. For animations, each frame is checked
    /// independently. To limit the cumulative pixel count across all frames,
    /// use [`max_total_pixels`](Self::max_total_pixels).
    pub max_pixels: Option<u64>,
    /// Maximum memory allocation in bytes.
    pub max_memory_bytes: Option<u64>,
    /// Maximum encoded output size in bytes (encode only).
    pub max_output_bytes: Option<u64>,
    /// Maximum image width in pixels.
    pub max_width: Option<u32>,
    /// Maximum image height in pixels.
    pub max_height: Option<u32>,
    /// Maximum input data size in bytes (decode only).
    pub max_input_bytes: Option<u64>,
    /// Maximum number of animation frames.
    pub max_frames: Option<u32>,
    /// Maximum total animation duration in milliseconds.
    pub max_animation_ms: Option<u64>,
    /// Maximum pixels across **all frames** (width × height × frame_count).
    ///
    /// A 1000×1000 animation with 200 frames has 200 million total pixels.
    /// [`max_pixels`](Self::max_pixels) would pass each 1M-pixel frame
    /// individually — this field catches the cumulative cost.
    ///
    /// Checked by [`check_image_info`](Self::check_image_info) when
    /// `frame_count` is known; for unknown frame counts, use
    /// [`check_total_pixels`](Self::check_total_pixels) incrementally.
    pub max_total_pixels: Option<u64>,
    /// Threading policy for the codec.
    ///
    /// Defaults to [`ThreadingPolicy::Unlimited`].
    pub threading: ThreadingPolicy,
}

// All primitives, no pointers — but Option<u64> niche optimization and
// enum discriminant alignment can differ between 32-bit and 64-bit.
#[cfg(target_pointer_width = "64")]
const _: () = assert!(core::mem::size_of::<ResourceLimits>() == 128);

impl Default for ResourceLimits {
    fn default() -> Self {
        Self {
            max_pixels: None,
            max_memory_bytes: None,
            max_output_bytes: None,
            max_width: None,
            max_height: None,
            max_input_bytes: None,
            max_frames: None,
            max_animation_ms: None,
            max_total_pixels: None,
            threading: ThreadingPolicy::Unlimited,
        }
    }
}

impl ResourceLimits {
    /// No limits (all fields `None`), unlimited threading.
    pub fn none() -> Self {
        Self::default()
    }

    /// Set maximum total pixels.
    pub fn with_max_pixels(mut self, max: u64) -> Self {
        self.max_pixels = Some(max);
        self
    }

    /// Set maximum memory allocation in bytes.
    pub fn with_max_memory(mut self, bytes: u64) -> Self {
        self.max_memory_bytes = Some(bytes);
        self
    }

    /// Set maximum encoded output size in bytes.
    pub fn with_max_output(mut self, bytes: u64) -> Self {
        self.max_output_bytes = Some(bytes);
        self
    }

    /// Set maximum image width in pixels.
    pub fn with_max_width(mut self, width: u32) -> Self {
        self.max_width = Some(width);
        self
    }

    /// Set maximum image height in pixels.
    pub fn with_max_height(mut self, height: u32) -> Self {
        self.max_height = Some(height);
        self
    }

    /// Set maximum input data size in bytes (decode only).
    pub fn with_max_input_bytes(mut self, bytes: u64) -> Self {
        self.max_input_bytes = Some(bytes);
        self
    }

    /// Set maximum number of animation frames.
    pub fn with_max_frames(mut self, frames: u32) -> Self {
        self.max_frames = Some(frames);
        self
    }

    /// Set maximum total animation duration in milliseconds.
    pub fn with_max_animation_ms(mut self, ms: u64) -> Self {
        self.max_animation_ms = Some(ms);
        self
    }

    /// Set maximum total pixels across all frames.
    pub fn with_max_total_pixels(mut self, max: u64) -> Self {
        self.max_total_pixels = Some(max);
        self
    }

    /// Set threading policy.
    pub fn with_threading(mut self, policy: ThreadingPolicy) -> Self {
        self.threading = policy;
        self
    }

    /// Current threading policy.
    pub fn threading(&self) -> ThreadingPolicy {
        self.threading
    }

    /// Whether any limits are set (including non-default threading).
    pub fn has_any(&self) -> bool {
        self.max_pixels.is_some()
            || self.max_memory_bytes.is_some()
            || self.max_output_bytes.is_some()
            || self.max_width.is_some()
            || self.max_height.is_some()
            || self.max_input_bytes.is_some()
            || self.max_frames.is_some()
            || self.max_animation_ms.is_some()
            || self.max_total_pixels.is_some()
            || self.threading != ThreadingPolicy::Unlimited
    }

    // --- Validation methods ---

    /// Check image dimensions against `max_width`, `max_height`, and `max_pixels`.
    pub fn check_dimensions(&self, width: u32, height: u32) -> Result<(), LimitExceeded> {
        if let Some(max) = self.max_width
            && width > max
        {
            return Err(LimitExceeded::Width { actual: width, max });
        }
        if let Some(max) = self.max_height
            && height > max
        {
            return Err(LimitExceeded::Height {
                actual: height,
                max,
            });
        }
        if let Some(max) = self.max_pixels {
            let pixels = width as u64 * height as u64;
            if pixels > max {
                return Err(LimitExceeded::Pixels {
                    actual: pixels,
                    max,
                });
            }
        }
        Ok(())
    }

    /// Check a memory estimate against `max_memory_bytes`.
    pub fn check_memory(&self, bytes: u64) -> Result<(), LimitExceeded> {
        if let Some(max) = self.max_memory_bytes
            && bytes > max
        {
            return Err(LimitExceeded::Memory { actual: bytes, max });
        }
        Ok(())
    }

    /// Check input data size against `max_input_bytes`.
    pub fn check_input_size(&self, bytes: u64) -> Result<(), LimitExceeded> {
        if let Some(max) = self.max_input_bytes
            && bytes > max
        {
            return Err(LimitExceeded::InputSize { actual: bytes, max });
        }
        Ok(())
    }

    /// Check encoded output size against `max_output_bytes`.
    pub fn check_output_size(&self, bytes: u64) -> Result<(), LimitExceeded> {
        if let Some(max) = self.max_output_bytes
            && bytes > max
        {
            return Err(LimitExceeded::OutputSize { actual: bytes, max });
        }
        Ok(())
    }

    /// Check frame count against `max_frames`.
    pub fn check_frames(&self, count: u32) -> Result<(), LimitExceeded> {
        if let Some(max) = self.max_frames
            && count > max
        {
            return Err(LimitExceeded::Frames { actual: count, max });
        }
        Ok(())
    }

    /// Check animation duration against `max_animation_ms`.
    pub fn check_animation_ms(&self, ms: u64) -> Result<(), LimitExceeded> {
        if let Some(max) = self.max_animation_ms
            && ms > max
        {
            return Err(LimitExceeded::Duration { actual: ms, max });
        }
        Ok(())
    }

    /// Check total pixels across all frames against `max_total_pixels`.
    pub fn check_total_pixels(&self, total: u64) -> Result<(), LimitExceeded> {
        if let Some(max) = self.max_total_pixels
            && total > max
        {
            return Err(LimitExceeded::TotalPixels { actual: total, max });
        }
        Ok(())
    }

    /// Check [`ImageInfo`](crate::ImageInfo) from `probe_header()` against all
    /// applicable limits. This is the fastest rejection point — call it
    /// immediately after probing, before any pixel work.
    ///
    /// Checks: `max_width`, `max_height`, `max_pixels`, `max_frames`,
    /// `max_total_pixels`.
    pub fn check_image_info(&self, info: &crate::ImageInfo) -> Result<(), LimitExceeded> {
        self.check_dimensions(info.width, info.height)?;
        if let Some(max) = self.max_frames
            && let Some(count) = info.frame_count()
            && count > max
        {
            return Err(LimitExceeded::Frames { actual: count, max });
        }
        if let Some(max) = self.max_total_pixels
            && let Some(count) = info.frame_count()
        {
            let total = info.width as u64 * info.height as u64 * count as u64;
            if total > max {
                return Err(LimitExceeded::TotalPixels { actual: total, max });
            }
        }
        Ok(())
    }

    /// Check [`OutputInfo`](crate::decode::OutputInfo) against dimension limits.
    ///
    /// Checks: `max_width`, `max_height`, `max_pixels`.
    pub fn check_output_info(&self, info: &crate::OutputInfo) -> Result<(), LimitExceeded> {
        self.check_dimensions(info.width, info.height)
    }
}

/// A resource limit was exceeded.
///
/// Returned by [`ResourceLimits::check_dimensions()`] and related methods.
/// Each variant carries the actual value and the limit that was exceeded,
/// enabling useful error messages.
///
/// Implements [`core::error::Error`] so codecs can wrap it in their own
/// error types.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum LimitExceeded {
    /// Image width exceeded `max_width`.
    Width {
        /// Actual width.
        actual: u32,
        /// Maximum allowed.
        max: u32,
    },
    /// Image height exceeded `max_height`.
    Height {
        /// Actual height.
        actual: u32,
        /// Maximum allowed.
        max: u32,
    },
    /// Pixel count exceeded `max_pixels`.
    Pixels {
        /// Actual pixel count.
        actual: u64,
        /// Maximum allowed.
        max: u64,
    },
    /// Memory exceeded `max_memory_bytes`.
    Memory {
        /// Estimated memory in bytes.
        actual: u64,
        /// Maximum allowed.
        max: u64,
    },
    /// Input data size exceeded `max_input_bytes`.
    InputSize {
        /// Actual input size in bytes.
        actual: u64,
        /// Maximum allowed.
        max: u64,
    },
    /// Encoded output exceeded `max_output_bytes`.
    OutputSize {
        /// Actual or estimated output size in bytes.
        actual: u64,
        /// Maximum allowed.
        max: u64,
    },
    /// Frame count exceeded `max_frames`.
    Frames {
        /// Actual frame count.
        actual: u32,
        /// Maximum allowed.
        max: u32,
    },
    /// Animation duration exceeded `max_animation_ms`.
    Duration {
        /// Actual duration in milliseconds.
        actual: u64,
        /// Maximum allowed.
        max: u64,
    },
    /// Total pixels across all frames exceeded `max_total_pixels`.
    TotalPixels {
        /// Actual total pixel count (width × height × frames).
        actual: u64,
        /// Maximum allowed.
        max: u64,
    },
}

impl core::fmt::Display for LimitExceeded {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Width { actual, max } => write!(f, "width {actual} exceeds limit {max}"),
            Self::Height { actual, max } => write!(f, "height {actual} exceeds limit {max}"),
            Self::Pixels { actual, max } => {
                write!(f, "pixel count {actual} exceeds limit {max}")
            }
            Self::Memory { actual, max } => {
                write!(f, "memory {actual} bytes exceeds limit {max}")
            }
            Self::InputSize { actual, max } => {
                write!(f, "input size {actual} bytes exceeds limit {max}")
            }
            Self::OutputSize { actual, max } => {
                write!(f, "output size {actual} bytes exceeds limit {max}")
            }
            Self::Frames { actual, max } => {
                write!(f, "frame count {actual} exceeds limit {max}")
            }
            Self::Duration { actual, max } => {
                write!(f, "duration {actual}ms exceeds limit {max}ms")
            }
            Self::TotalPixels { actual, max } => {
                write!(f, "total pixels {actual} exceeds limit {max}")
            }
        }
    }
}

impl core::error::Error for LimitExceeded {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_has_no_limits() {
        let limits = ResourceLimits::none();
        assert!(!limits.has_any());
    }

    #[test]
    fn builder_sets_limits() {
        let limits = ResourceLimits::none()
            .with_max_pixels(1_000_000)
            .with_max_memory(512 * 1024 * 1024);
        assert!(limits.has_any());
        assert_eq!(limits.max_pixels, Some(1_000_000));
        assert_eq!(limits.max_memory_bytes, Some(512 * 1024 * 1024));
        assert!(limits.max_output_bytes.is_none());
    }

    #[test]
    fn animation_limits() {
        let limits = ResourceLimits::none()
            .with_max_frames(100)
            .with_max_animation_ms(30_000);
        assert!(limits.has_any());
        assert_eq!(limits.max_frames, Some(100));
        assert_eq!(limits.max_animation_ms, Some(30_000));
    }

    #[test]
    fn has_any_includes_animation_fields() {
        let limits = ResourceLimits::none().with_max_frames(10);
        assert!(limits.has_any());

        let limits = ResourceLimits::none().with_max_animation_ms(5000);
        assert!(limits.has_any());
    }

    #[test]
    fn threading_policy_default() {
        let limits = ResourceLimits::none();
        assert_eq!(limits.threading(), ThreadingPolicy::Unlimited);
        assert!(!limits.has_any());
    }

    #[test]
    fn threading_policy_single_thread() {
        let limits = ResourceLimits::none().with_threading(ThreadingPolicy::SingleThread);
        assert!(limits.has_any());
        assert_eq!(limits.threading(), ThreadingPolicy::SingleThread);
    }

    #[test]
    fn threading_policy_limit_or_single() {
        let limits = ResourceLimits::none()
            .with_threading(ThreadingPolicy::LimitOrSingle { max_threads: 4 });
        assert!(limits.has_any());
        assert_eq!(
            limits.threading(),
            ThreadingPolicy::LimitOrSingle { max_threads: 4 }
        );
    }

    #[test]
    fn threading_policy_balanced() {
        let limits = ResourceLimits::none().with_threading(ThreadingPolicy::Balanced);
        assert!(limits.has_any());
    }

    // --- Validation tests ---

    #[test]
    fn check_dimensions_pass() {
        let limits = ResourceLimits::none()
            .with_max_width(1920)
            .with_max_height(1080)
            .with_max_pixels(2_073_600);
        assert!(limits.check_dimensions(1920, 1080).is_ok());
        assert!(limits.check_dimensions(100, 100).is_ok());
    }

    #[test]
    fn check_dimensions_width_exceeded() {
        let limits = ResourceLimits::none().with_max_width(1920);
        let err = limits.check_dimensions(1921, 1080).unwrap_err();
        assert_eq!(
            err,
            LimitExceeded::Width {
                actual: 1921,
                max: 1920
            }
        );
    }

    #[test]
    fn check_dimensions_height_exceeded() {
        let limits = ResourceLimits::none().with_max_height(1080);
        let err = limits.check_dimensions(1920, 1081).unwrap_err();
        assert_eq!(
            err,
            LimitExceeded::Height {
                actual: 1081,
                max: 1080
            }
        );
    }

    #[test]
    fn check_dimensions_pixels_exceeded() {
        let limits = ResourceLimits::none().with_max_pixels(1_000_000);
        let err = limits.check_dimensions(1001, 1000).unwrap_err();
        assert_eq!(
            err,
            LimitExceeded::Pixels {
                actual: 1_001_000,
                max: 1_000_000
            }
        );
    }

    #[test]
    fn check_dimensions_no_limits_always_passes() {
        let limits = ResourceLimits::none();
        assert!(limits.check_dimensions(100_000, 100_000).is_ok());
    }

    #[test]
    fn check_memory_pass_and_fail() {
        let limits = ResourceLimits::none().with_max_memory(512 * 1024 * 1024);
        assert!(limits.check_memory(256 * 1024 * 1024).is_ok());
        let err = limits.check_memory(1024 * 1024 * 1024).unwrap_err();
        assert!(matches!(err, LimitExceeded::Memory { .. }));
    }

    #[test]
    fn check_input_size_pass_and_fail() {
        let limits = ResourceLimits::none().with_max_input_bytes(10 * 1024 * 1024);
        assert!(limits.check_input_size(5 * 1024 * 1024).is_ok());
        let err = limits.check_input_size(20 * 1024 * 1024).unwrap_err();
        assert!(matches!(err, LimitExceeded::InputSize { .. }));
    }

    #[test]
    fn check_output_size_pass_and_fail() {
        let limits = ResourceLimits::none().with_max_output(1024);
        assert!(limits.check_output_size(512).is_ok());
        let err = limits.check_output_size(2048).unwrap_err();
        assert!(matches!(err, LimitExceeded::OutputSize { .. }));
    }

    #[test]
    fn check_frames_pass_and_fail() {
        let limits = ResourceLimits::none().with_max_frames(100);
        assert!(limits.check_frames(50).is_ok());
        let err = limits.check_frames(200).unwrap_err();
        assert_eq!(
            err,
            LimitExceeded::Frames {
                actual: 200,
                max: 100
            }
        );
    }

    #[test]
    fn check_animation_ms_pass_and_fail() {
        let limits = ResourceLimits::none().with_max_animation_ms(30_000);
        assert!(limits.check_animation_ms(15_000).is_ok());
        let err = limits.check_animation_ms(60_000).unwrap_err();
        assert!(matches!(err, LimitExceeded::Duration { .. }));
    }

    #[test]
    fn check_image_info_dimensions_and_frames() {
        use crate::{ImageFormat, ImageInfo};
        let limits = ResourceLimits::none()
            .with_max_width(4096)
            .with_max_pixels(16_000_000)
            .with_max_frames(100);

        let info = ImageInfo::new(3840, 2160, ImageFormat::Avif).with_sequence(
            crate::ImageSequence::Animation {
                frame_count: Some(50),
                loop_count: None,
                random_access: false,
            },
        );
        assert!(limits.check_image_info(&info).is_ok());

        let big = ImageInfo::new(5000, 4000, ImageFormat::Jpeg);
        let err = limits.check_image_info(&big).unwrap_err();
        assert!(matches!(err, LimitExceeded::Width { .. }));

        let many_frames = ImageInfo::new(100, 100, ImageFormat::Gif).with_sequence(
            crate::ImageSequence::Animation {
                frame_count: Some(200),
                loop_count: None,
                random_access: false,
            },
        );
        let err = limits.check_image_info(&many_frames).unwrap_err();
        assert_eq!(
            err,
            LimitExceeded::Frames {
                actual: 200,
                max: 100
            }
        );
    }

    #[test]
    fn limit_exceeded_display() {
        use alloc::format;
        let err = LimitExceeded::Width {
            actual: 5000,
            max: 4096,
        };
        assert_eq!(format!("{err}"), "width 5000 exceeds limit 4096");

        let err = LimitExceeded::InputSize {
            actual: 20_000_000,
            max: 10_000_000,
        };
        assert_eq!(
            format!("{err}"),
            "input size 20000000 bytes exceeds limit 10000000"
        );

        let err = LimitExceeded::Duration {
            actual: 60_000,
            max: 30_000,
        };
        assert_eq!(format!("{err}"), "duration 60000ms exceeds limit 30000ms");
    }

    #[test]
    fn limit_exceeded_is_error() {
        fn assert_error<E: core::error::Error>(_: &E) {}
        let err = LimitExceeded::Width {
            actual: 5000,
            max: 4096,
        };
        assert_error(&err);
    }

    #[test]
    fn total_pixels_builder_and_has_any() {
        let limits = ResourceLimits::none().with_max_total_pixels(100_000_000);
        assert!(limits.has_any());
        assert_eq!(limits.max_total_pixels, Some(100_000_000));
    }

    #[test]
    fn check_total_pixels_pass_and_fail() {
        let limits = ResourceLimits::none().with_max_total_pixels(50_000_000);
        assert!(limits.check_total_pixels(50_000_000).is_ok());
        let err = limits.check_total_pixels(50_000_001).unwrap_err();
        assert_eq!(
            err,
            LimitExceeded::TotalPixels {
                actual: 50_000_001,
                max: 50_000_000
            }
        );
    }

    #[test]
    fn check_total_pixels_no_limit() {
        let limits = ResourceLimits::none();
        assert!(limits.check_total_pixels(u64::MAX).is_ok());
    }

    #[test]
    fn check_image_info_total_pixels() {
        use crate::{ImageFormat, ImageInfo};
        // 1000×1000 × 200 frames = 200M pixels, limit 100M
        let limits = ResourceLimits::none().with_max_total_pixels(100_000_000);
        let info = ImageInfo::new(1000, 1000, ImageFormat::Gif).with_sequence(
            crate::ImageSequence::Animation {
                frame_count: Some(200),
                loop_count: None,
                random_access: false,
            },
        );
        let err = limits.check_image_info(&info).unwrap_err();
        assert_eq!(
            err,
            LimitExceeded::TotalPixels {
                actual: 200_000_000,
                max: 100_000_000
            }
        );
    }

    #[test]
    fn check_image_info_total_pixels_pass() {
        use crate::{ImageFormat, ImageInfo};
        let limits = ResourceLimits::none().with_max_total_pixels(100_000_000);
        let info = ImageInfo::new(1000, 1000, ImageFormat::Gif).with_sequence(
            crate::ImageSequence::Animation {
                frame_count: Some(100),
                loop_count: None,
                random_access: false,
            },
        );
        assert!(limits.check_image_info(&info).is_ok());
    }

    #[test]
    fn check_image_info_total_pixels_still_image() {
        use crate::{ImageFormat, ImageInfo};
        // Still image: frame_count() returns Some(1), so total = w*h*1
        let limits = ResourceLimits::none().with_max_total_pixels(1_000_000);
        let info = ImageInfo::new(1000, 1000, ImageFormat::Jpeg);
        assert!(limits.check_image_info(&info).is_ok());

        // Just over: 1001×1000×1 = 1_001_000 > 1_000_000
        let info = ImageInfo::new(1001, 1000, ImageFormat::Jpeg);
        let err = limits.check_image_info(&info).unwrap_err();
        assert_eq!(
            err,
            LimitExceeded::TotalPixels {
                actual: 1_001_000,
                max: 1_000_000
            }
        );
    }

    #[test]
    fn total_pixels_display() {
        use alloc::format;
        let err = LimitExceeded::TotalPixels {
            actual: 200_000_000,
            max: 100_000_000,
        };
        assert_eq!(
            format!("{err}"),
            "total pixels 200000000 exceeds limit 100000000"
        );
    }
}