Skip to main content

gamut_core/
lib.rs

1//! Core traits, image buffers, dimensions, and error types shared across the gamut codecs.
2//!
3//! This crate is dependency-free with respect to the format crates: every codec in the
4//! workspace builds on the [`EncodeImage`] / [`DecodeImage`] traits, the branded [`ImageRef`] /
5//! [`ImageBuf`] buffers, and the [`Error`] type defined here, so that callers get a single,
6//! consistent error surface regardless of format.
7//!
8//! # Scope and design notes
9//!
10//! The surface is deliberately small and frozen; the following are intentional decisions rather
11//! than omissions:
12//!
13//! - **Interleaved `u8` / `u16` layouts only.** [`Sample`] is sealed over `u8` and `u16`; planar
14//!   layouts and codec-side concerns such as coded bit depth live in `gamut-color`
15//!   (`gamut_color::Planar8`, `gamut_color::BitDepth`), not here.
16//! - **Open where growth is additive, sealed where it must not be.** [`Error`] and [`ColorModel`]
17//!   are `#[non_exhaustive]` so variants can be added without a breaking change, while [`Pixel`]
18//!   and [`Sample`] are sealed — the set of pixel layouts is closed and only this crate defines it.
19//! - **Static classifications, optional diagnostics.** [`Error::InvalidInput`] /
20//!   [`Error::Unsupported`] retain their allocation-free `&'static str` payloads and public shape.
21//!   Producers can wrap any error in [`Error::Context`] to attach an origin, byte offset, or owned
22//!   detail without changing its [`ErrorKind`]. [`Error::Io`] preserves the underlying
23//!   [`std::io::Error`] so transport failures stay distinguishable from malformed input.
24//! - **The length invariant lives on the buffers, not on [`Dimensions`].** [`Dimensions`] is a plain
25//!   value type with public fields; non-emptiness and `len == width * height * channels` are
26//!   enforced once, at [`ImageRef::new`] / [`ImageBuf::new`], so codecs receive a known-good buffer.
27//! - **Byte accounting shares its shape and law, not its walks.** [`segment::Segment`] is generic
28//!   over each format's own `kind` enum and [`segment::covers`] is the one "tiles `0..len`"
29//!   predicate; the walks that produce the segments stay format-specific.
30//!
31//! # Example
32//!
33//! Drive any codec through the shared [`EncodeImage`] trait, handing it a branded, already-validated
34//! [`ImageRef`]:
35//!
36//! ```
37//! use gamut_core::{Dimensions, EncodeImage, ImageRef, Pixel, Result, Rgb8};
38//!
39//! // A toy encoder; a real codec would compress `image.as_samples()` instead of copying it.
40//! struct RawEncoder;
41//! impl EncodeImage<Rgb8> for RawEncoder {
42//!     fn encode_image(&self, image: ImageRef<'_, Rgb8>, out: &mut Vec<u8>) -> Result<usize> {
43//!         let start = out.len();
44//!         out.extend_from_slice(image.as_samples()); // input is pre-validated by `ImageRef::new`
45//!         Ok(out.len() - start)
46//!     }
47//! }
48//!
49//! let dims = Dimensions::new(2, 2).unwrap();
50//! let pixels = vec![0u8; dims.sample_count(Rgb8::CHANNELS).unwrap()];
51//! let image = ImageRef::<Rgb8>::new(&pixels, dims).unwrap();
52//!
53//! let mut out = Vec::new();
54//! let written = RawEncoder.encode_image(image, &mut out).unwrap();
55//! assert_eq!(written, 2 * 2 * 3);
56//! ```
57#![forbid(unsafe_code)]
58
59// Compiles README.md's code blocks as doctests; exists only while rustdoc collects them.
60#[cfg(doctest)]
61#[doc = include_str!("../README.md")]
62struct ReadmeDoctests;
63
64pub mod convert;
65
66mod image;
67// Executable laws for the conversion engine, shared by this crate's property tests and the
68// out-of-tree fuzz tier (`test-support`). Not part of the stable API; see `docs/testing.md`.
69// A plain comment, not `///`: outer docs here would make rustdoc resolve the module's own `//!`
70// intra-doc links from the crate root, where its items are not in scope.
71#[cfg(any(test, feature = "test-support"))]
72#[doc(hidden)]
73pub mod invariants;
74pub mod luminance;
75mod pixel;
76pub mod segment;
77
78pub use image::{ImageBuf, ImageRef};
79pub use pixel::{
80    Bilevel, Cmyk8, ColorModel, Gray8, Gray16, GrayAlpha8, GrayAlpha16, Indexed8, Pixel,
81    PixelFormat, Rgb8, Rgb16, Rgba8, Rgba16, Sample,
82};
83
84/// Stable classification of a gamut error, independent of any diagnostic context around it.
85///
86/// The discriminants are permanent and append-only so the classification remains mechanically
87/// portable to the C status surface.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89#[non_exhaustive]
90#[repr(u32)]
91pub enum ErrorKind {
92    /// The input data was malformed, truncated, or otherwise invalid.
93    InvalidInput = 1,
94    /// The requested format, profile, or feature is unsupported.
95    Unsupported = 2,
96    /// An underlying I/O operation failed.
97    Io = 3,
98}
99
100const _: () = {
101    assert!(ErrorKind::InvalidInput as u32 == 1);
102    assert!(ErrorKind::Unsupported as u32 == 2);
103    assert!(ErrorKind::Io as u32 == 3);
104};
105
106/// Structured diagnostic information attached to an [`Error`].
107///
108/// Callers normally inspect this through [`Error::origin`], [`Error::byte_offset`], and
109/// [`Error::detail`]. The fields stay private so more optional context can be added without
110/// changing the construction contract.
111#[derive(Debug)]
112#[non_exhaustive]
113pub struct Diagnostic {
114    source: Error,
115    origin: Option<&'static str>,
116    byte_offset: Option<u64>,
117    detail: Option<Box<str>>,
118}
119
120impl Diagnostic {
121    /// The underlying classified error.
122    #[must_use]
123    pub fn source_error(&self) -> &Error {
124        &self.source
125    }
126
127    /// The Cargo package or format layer that produced the error, when known.
128    #[must_use]
129    pub fn origin(&self) -> Option<&'static str> {
130        self.origin
131    }
132
133    /// The byte offset relative to the producing parser's immediate input, when known.
134    #[must_use]
135    pub fn byte_offset(&self) -> Option<u64> {
136        self.byte_offset
137    }
138
139    /// Dynamic diagnostic detail retained from an underlying parser or backend, when available.
140    #[must_use]
141    pub fn detail(&self) -> Option<&str> {
142        self.detail.as_deref()
143    }
144}
145
146impl core::fmt::Display for Diagnostic {
147    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
148        write!(f, "{}", self.source)?;
149        if self.origin.is_some() || self.byte_offset.is_some() {
150            f.write_str(" [")?;
151            if let Some(origin) = self.origin {
152                write!(f, "origin: {origin}")?;
153                if self.byte_offset.is_some() {
154                    f.write_str(", ")?;
155                }
156            }
157            if let Some(offset) = self.byte_offset {
158                write!(f, "byte offset: {offset}")?;
159            }
160            f.write_str("]")?;
161        }
162        if let Some(detail) = &self.detail {
163            write!(f, ": {detail}")?;
164        }
165        Ok(())
166    }
167}
168
169impl std::error::Error for Diagnostic {
170    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
171        Some(&self.source)
172    }
173}
174
175/// Errors produced by gamut encoders and decoders.
176///
177/// Marked `#[non_exhaustive]` so additional variants can be added as formats land without a
178/// breaking change.
179#[derive(Debug, thiserror::Error)]
180#[non_exhaustive]
181pub enum Error {
182    /// The input data was malformed, truncated, or otherwise not valid for the format.
183    #[error("invalid input: {0}")]
184    InvalidInput(&'static str),
185    /// The requested format, profile, or feature is not yet supported.
186    #[error("unsupported: {0}")]
187    Unsupported(&'static str),
188    /// An underlying I/O operation failed while reading from a stream-backed source.
189    ///
190    /// Distinct from [`Error::InvalidInput`]: this reports the *transport* failing (a disk
191    /// error, an interrupted read), not the bytes being malformed, so batch pipelines can retry
192    /// or surface it instead of misclassifying the file as corrupt.
193    #[error("i/o error: {0}")]
194    Io(#[from] std::io::Error),
195    /// An existing error enriched with optional structured diagnostic context.
196    ///
197    /// The payload is boxed so adding context does not inflate the allocation-free legacy
198    /// variants. Context is allocated only while constructing an error, never on a successful
199    /// codec path.
200    #[error("{0}")]
201    Context(#[source] Box<Diagnostic>),
202}
203
204impl Error {
205    /// Constructs an invalid-input error attributed to `origin`.
206    ///
207    /// Direct [`Error::InvalidInput`] construction remains the allocation-free compatibility
208    /// path. This constructor is for producers that opt into structured diagnostics.
209    #[must_use]
210    pub fn invalid_input(origin: &'static str, message: &'static str) -> Self {
211        Self::InvalidInput(message).with_origin(origin)
212    }
213
214    /// Constructs an unsupported-feature error attributed to `origin`.
215    ///
216    /// Direct [`Error::Unsupported`] construction remains the allocation-free compatibility path.
217    #[must_use]
218    pub fn unsupported(origin: &'static str, message: &'static str) -> Self {
219        Self::Unsupported(message).with_origin(origin)
220    }
221
222    /// Returns the stable classification of this error, looking through diagnostic context.
223    #[must_use]
224    pub fn kind(&self) -> ErrorKind {
225        match self {
226            Self::InvalidInput(_) => ErrorKind::InvalidInput,
227            Self::Unsupported(_) => ErrorKind::Unsupported,
228            Self::Io(_) => ErrorKind::Io,
229            Self::Context(diagnostic) => diagnostic.source.kind(),
230        }
231    }
232
233    /// Returns the allocation-free static message carried by a legacy error, when present.
234    ///
235    /// Context does not change the message. [`Error::Io`] has no static message because its text
236    /// belongs to the underlying [`std::io::Error`].
237    #[must_use]
238    pub fn static_message(&self) -> Option<&'static str> {
239        match self {
240            Self::InvalidInput(message) | Self::Unsupported(message) => Some(message),
241            Self::Io(_) => None,
242            Self::Context(diagnostic) => diagnostic.source.static_message(),
243        }
244    }
245
246    /// Returns the Cargo package or format layer that produced the error, when known.
247    #[must_use]
248    pub fn origin(&self) -> Option<&'static str> {
249        match self {
250            Self::Context(diagnostic) => diagnostic.origin(),
251            _ => None,
252        }
253    }
254
255    /// Returns the byte offset relative to the producing parser's immediate input, when known.
256    #[must_use]
257    pub fn byte_offset(&self) -> Option<u64> {
258        match self {
259            Self::Context(diagnostic) => diagnostic.byte_offset(),
260            _ => None,
261        }
262    }
263
264    /// Returns dynamic diagnostic detail retained from an underlying parser or backend.
265    #[must_use]
266    pub fn detail(&self) -> Option<&str> {
267        match self {
268            Self::Context(diagnostic) => diagnostic.detail(),
269            _ => None,
270        }
271    }
272
273    /// Attaches the producing Cargo package or format layer if no origin is already present.
274    #[must_use]
275    pub fn with_origin(self, origin: &'static str) -> Self {
276        self.with_diagnostic(|diagnostic| {
277            if diagnostic.origin.is_none() {
278                diagnostic.origin = Some(origin);
279            }
280        })
281    }
282
283    /// Attaches a byte offset if no offset is already present.
284    ///
285    /// The offset is relative to the immediate input accepted by the parser that reports it.
286    #[must_use]
287    pub fn with_byte_offset(self, byte_offset: u64) -> Self {
288        self.with_diagnostic(|diagnostic| {
289            if diagnostic.byte_offset.is_none() {
290                diagnostic.byte_offset = Some(byte_offset);
291            }
292        })
293    }
294
295    /// Attaches owned dynamic detail if no detail is already present.
296    ///
297    /// This is the opt-in allocating path; static-only callers can keep constructing
298    /// [`Error::InvalidInput`] and [`Error::Unsupported`] directly.
299    #[must_use]
300    pub fn with_detail(self, detail: impl Into<Box<str>>) -> Self {
301        self.with_diagnostic(|diagnostic| {
302            if diagnostic.detail.is_none() {
303                diagnostic.detail = Some(detail.into());
304            }
305        })
306    }
307
308    fn with_diagnostic(self, update: impl FnOnce(&mut Diagnostic)) -> Self {
309        match self {
310            Self::Context(mut diagnostic) => {
311                update(&mut diagnostic);
312                Self::Context(diagnostic)
313            }
314            source => {
315                let mut diagnostic = Diagnostic {
316                    source,
317                    origin: None,
318                    byte_offset: None,
319                    detail: None,
320                };
321                update(&mut diagnostic);
322                Self::Context(Box::new(diagnostic))
323            }
324        }
325    }
326}
327
328/// Convenience result type for gamut operations.
329pub type Result<T> = core::result::Result<T, Error>;
330
331/// Width and height of an image, in pixels.
332///
333/// `#[repr(C)]`: the layout — `width` then `height`, two `u32`s — is a public guarantee so the
334/// value can cross the C ABI boundary as-is (issue #242).
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
336#[repr(C)]
337pub struct Dimensions {
338    /// Image width in pixels.
339    pub width: u32,
340    /// Image height in pixels.
341    pub height: u32,
342}
343
344impl Dimensions {
345    /// Creates dimensions, rejecting a zero width or height.
346    ///
347    /// The fields stay public for ergonomic struct literals; this constructor is the validated
348    /// path that buffer types ([`crate::ImageRef`]) and codecs use so an empty image is caught
349    /// once, at the boundary, rather than re-checked in every encoder.
350    ///
351    /// # Errors
352    ///
353    /// Returns [`Error::InvalidInput`] if either dimension is zero.
354    pub fn new(width: u32, height: u32) -> Result<Self> {
355        if width == 0 || height == 0 {
356            return Err(Error::InvalidInput("zero-sized image").with_origin(env!("CARGO_PKG_NAME")));
357        }
358        Ok(Self { width, height })
359    }
360
361    /// The pixel count `width * height`, or `None` if it overflows `usize`.
362    #[must_use]
363    pub fn num_pixels(self) -> Option<usize> {
364        (self.width as usize).checked_mul(self.height as usize)
365    }
366
367    /// The sample count for an interleaved buffer of `channels` samples per pixel
368    /// (`width * height * channels`), or `None` on overflow. The length an [`crate::ImageRef`]
369    /// validates against.
370    #[must_use]
371    pub fn sample_count(self, channels: usize) -> Option<usize> {
372        self.num_pixels()?.checked_mul(channels)
373    }
374
375    /// Whether either dimension is zero.
376    #[must_use]
377    pub fn is_empty(self) -> bool {
378        self.width == 0 || self.height == 0
379    }
380}
381
382/// Encodes an [`ImageRef`] of a specific pixel layout `P` into a compressed byte stream.
383///
384/// A codec implements this once per pixel layout it supports (`impl EncodeImage<Rgb8> for …`,
385/// `impl EncodeImage<Cmyk8> for …`, …), so asking it to encode an unsupported layout is a compile
386/// error rather than a runtime `Unsupported`. The input is pre-validated by [`ImageRef::new`], so an
387/// implementation never re-checks the buffer length. Bytes are appended to `out` to keep callers
388/// that reuse a scratch buffer allocation-conscious.
389pub trait EncodeImage<P: Pixel> {
390    /// Encode `image` into `out` (appended), returning the number of bytes written.
391    ///
392    /// # Errors
393    ///
394    /// Returns [`Error::Unsupported`] if the requested encoder configuration is not implemented, or
395    /// [`Error::InvalidInput`] if the image violates a format constraint (e.g. a dimension limit).
396    fn encode_image(&self, image: ImageRef<'_, P>, out: &mut Vec<u8>) -> Result<usize>;
397
398    /// Encode `image` into a fresh [`Vec`], returning the encoded bytes.
399    ///
400    /// A convenience over [`EncodeImage::encode_image`] for callers that just want the bytes;
401    /// reach for `encode_image` with a reused `&mut Vec<u8>` when encoding many images and you want
402    /// to amortise the allocation.
403    ///
404    /// # Errors
405    ///
406    /// As [`EncodeImage::encode_image`].
407    fn encode_to_vec(&self, image: ImageRef<'_, P>) -> Result<Vec<u8>> {
408        let mut out = Vec::new();
409        self.encode_image(image, &mut out)?;
410        Ok(out)
411    }
412}
413
414/// Decodes a compressed byte stream into an owned [`ImageBuf`] of pixel layout `P`.
415///
416/// `P` selects the layout the caller wants back; a codec implements this for each layout it can
417/// present (converting internally as needed, e.g. grayscale → [`Rgb8`]). Returning an owned
418/// [`ImageBuf`] keeps the dimensions, samples, and layout brand together so the result can't be
419/// misinterpreted.
420pub trait DecodeImage<P: Pixel> {
421    /// Decode `data` into a fresh [`ImageBuf`].
422    ///
423    /// # Errors
424    ///
425    /// Returns [`Error::InvalidInput`] if `data` is malformed, or [`Error::Unsupported`] if it uses
426    /// a feature that is not implemented or cannot be presented as `P`.
427    fn decode_image(&self, data: &[u8]) -> Result<ImageBuf<P>>;
428
429    /// Decode `data` into `dst`, reusing its allocation when possible.
430    ///
431    /// The default implementation always replaces the buffer (`*dst = self.decode_image(data)?`). A
432    /// codec may override it to reuse `dst`'s sample storage — via [`ImageBuf::as_mut_samples`] —
433    /// across repeated calls whose decoded dimensions match `dst`'s, falling back to replacement
434    /// otherwise. Either way `dst` holds the decoded image on success.
435    ///
436    /// # Errors
437    ///
438    /// As [`DecodeImage::decode_image`].
439    fn decode_image_into(&self, data: &[u8], dst: &mut ImageBuf<P>) -> Result<()> {
440        *dst = self.decode_image(data)?;
441        Ok(())
442    }
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448
449    #[test]
450    fn error_displays_and_dimensions_fields() {
451        assert!(!Error::Unsupported("x").to_string().is_empty());
452        assert!(!Error::InvalidInput("y").to_string().is_empty());
453        let d = Dimensions {
454            width: 1920,
455            height: 1080,
456        };
457        assert_eq!(d.width, 1920);
458        assert_eq!(d.height, 1080);
459    }
460
461    #[test]
462    fn io_error_converts_and_displays() {
463        // `#[from]` gives the `?`-friendly conversion; the Display must surface the source.
464        let io = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "short read");
465        let err: Error = io.into();
466        assert!(matches!(err, Error::Io(_)));
467        assert!(err.to_string().contains("short read"));
468    }
469
470    #[test]
471    fn legacy_error_variants_keep_their_public_shape() {
472        let invalid = Error::InvalidInput("bad bytes");
473        let unsupported = Error::Unsupported("future profile");
474        assert!(matches!(invalid, Error::InvalidInput("bad bytes")));
475        assert!(matches!(unsupported, Error::Unsupported("future profile")));
476        assert_eq!(invalid.kind(), ErrorKind::InvalidInput);
477        assert_eq!(unsupported.kind(), ErrorKind::Unsupported);
478        assert_eq!(invalid.static_message(), Some("bad bytes"));
479        assert_eq!(unsupported.static_message(), Some("future profile"));
480        assert_eq!(invalid.origin(), None);
481    }
482
483    #[test]
484    fn context_is_structured_first_write_wins_and_keeps_the_source() {
485        use std::error::Error as _;
486
487        let err = Error::InvalidInput("bad box")
488            .with_origin("gamut-isobmff")
489            .with_origin("gamut-avif")
490            .with_byte_offset(17)
491            .with_byte_offset(99)
492            .with_detail("declared size exceeds input")
493            .with_detail("replacement");
494
495        assert_eq!(err.kind(), ErrorKind::InvalidInput);
496        assert_eq!(err.static_message(), Some("bad box"));
497        assert_eq!(err.origin(), Some("gamut-isobmff"));
498        assert_eq!(err.byte_offset(), Some(17));
499        assert_eq!(err.detail(), Some("declared size exceeds input"));
500        assert_eq!(
501            err.to_string(),
502            "invalid input: bad box [origin: gamut-isobmff, byte offset: 17]: declared size exceeds input"
503        );
504
505        let diagnostic = match &err {
506            Error::Context(diagnostic) => diagnostic,
507            other => panic!("expected contextual error, got {other:?}"),
508        };
509        assert!(matches!(
510            diagnostic.source_error(),
511            Error::InvalidInput("bad box")
512        ));
513        assert!(err.source().is_some());
514    }
515
516    #[test]
517    fn partial_context_displays_without_empty_separators() {
518        assert_eq!(
519            Error::Unsupported("future profile")
520                .with_byte_offset(3)
521                .to_string(),
522            "unsupported: future profile [byte offset: 3]"
523        );
524        assert_eq!(
525            Error::InvalidInput("bad bytes")
526                .with_detail("decoder rejected marker")
527                .to_string(),
528            "invalid input: bad bytes: decoder rejected marker"
529        );
530        assert_eq!(
531            Error::unsupported("gamut-test", "future profile").to_string(),
532            "unsupported: future profile [origin: gamut-test]"
533        );
534    }
535
536    #[test]
537    fn contextual_io_keeps_its_kind_and_source_chain() {
538        use std::error::Error as _;
539
540        let err = Error::Io(std::io::Error::other("disk on fire"))
541            .with_origin("gamut-ifd")
542            .with_byte_offset(4096);
543        assert_eq!(err.kind(), ErrorKind::Io);
544        assert_eq!(err.static_message(), None);
545        assert_eq!(err.origin(), Some("gamut-ifd"));
546        assert_eq!(err.byte_offset(), Some(4096));
547        let diagnostic = err.source().expect("diagnostic source");
548        let io = diagnostic.source().expect("io source");
549        assert_eq!(io.to_string(), "i/o error: disk on fire");
550    }
551
552    #[test]
553    fn errors_remain_send_and_sync() {
554        fn assert_send_sync<T: Send + Sync>() {}
555        assert_send_sync::<Error>();
556    }
557
558    #[test]
559    fn dimensions_new_rejects_zero() {
560        assert!(Dimensions::new(0, 4).is_err());
561        assert!(Dimensions::new(4, 0).is_err());
562        assert!(Dimensions::new(0, 0).is_err());
563        let d = Dimensions::new(4, 3).unwrap();
564        assert_eq!((d.width, d.height), (4, 3));
565    }
566
567    #[test]
568    fn dimensions_pixel_and_sample_counts() {
569        let d = Dimensions {
570            width: 4,
571            height: 3,
572        };
573        assert_eq!(d.num_pixels(), Some(12));
574        assert_eq!(d.sample_count(3), Some(36));
575        assert_eq!(d.sample_count(1), Some(12));
576        assert!(!d.is_empty());
577    }
578
579    #[test]
580    fn dimensions_is_empty() {
581        assert!(
582            Dimensions {
583                width: 0,
584                height: 5
585            }
586            .is_empty()
587        );
588        assert!(
589            Dimensions {
590                width: 5,
591                height: 0
592            }
593            .is_empty()
594        );
595        assert!(
596            !Dimensions {
597                width: 5,
598                height: 5
599            }
600            .is_empty()
601        );
602    }
603
604    #[test]
605    fn dimensions_sample_count_overflow_is_none() {
606        // 65535*65535 fits in a 32-bit usize, so num_pixels is Some on every target...
607        let d = Dimensions {
608            width: 0xFFFF,
609            height: 0xFFFF,
610        };
611        assert_eq!(d.num_pixels(), Some(0xFFFF * 0xFFFF));
612        // ...but scaling by usize::MAX channels overflows on any platform.
613        assert_eq!(d.sample_count(usize::MAX), None);
614    }
615}
616
617#[cfg(test)]
618mod trait_tests {
619    use super::*;
620
621    /// A trivial codec: encodes by copying the samples out, decodes a fixed 1x1 gray pixel.
622    /// Exists only to exercise the trait defaults and object-safety.
623    struct Trivial;
624
625    impl EncodeImage<Gray8> for Trivial {
626        fn encode_image(&self, image: ImageRef<'_, Gray8>, out: &mut Vec<u8>) -> Result<usize> {
627            out.extend_from_slice(image.as_samples());
628            Ok(image.as_samples().len())
629        }
630    }
631
632    impl DecodeImage<Gray8> for Trivial {
633        fn decode_image(&self, _data: &[u8]) -> Result<ImageBuf<Gray8>> {
634            ImageBuf::<Gray8>::new(vec![42u8], Dimensions::new(1, 1)?)
635        }
636    }
637
638    /// A codec that always fails, to exercise error propagation through provided methods.
639    struct Failing;
640
641    impl EncodeImage<Gray8> for Failing {
642        fn encode_image(&self, _image: ImageRef<'_, Gray8>, _out: &mut Vec<u8>) -> Result<usize> {
643            Err(Error::Unsupported("nope"))
644        }
645    }
646
647    #[test]
648    fn encode_image_appends_and_counts() {
649        let img = ImageBuf::<Gray8>::new(vec![1, 2, 3, 4], Dimensions::new(2, 2).unwrap()).unwrap();
650        let mut out = vec![0xFF];
651        let n = Trivial.encode_image(img.as_ref(), &mut out).unwrap();
652        assert_eq!(n, 4);
653        assert_eq!(out, vec![0xFF, 1, 2, 3, 4]);
654    }
655
656    #[test]
657    fn encode_to_vec_returns_fresh_exact_bytes() {
658        let img = ImageBuf::<Gray8>::new(vec![1, 2, 3, 4], Dimensions::new(2, 2).unwrap()).unwrap();
659        // A fresh Vec holding exactly the encoded bytes — no leading scratch, unlike encode_image
660        // which appends. Asserting exact contents kills an "Ok(Vec::new())" mutant.
661        assert_eq!(
662            Trivial.encode_to_vec(img.as_ref()).unwrap(),
663            vec![1, 2, 3, 4]
664        );
665    }
666
667    #[test]
668    fn encode_to_vec_propagates_errors() {
669        let img = ImageBuf::<Gray8>::new(vec![0], Dimensions::new(1, 1).unwrap()).unwrap();
670        // The default must surface encode_image's error rather than swallow it into an empty Vec.
671        assert!(Failing.encode_to_vec(img.as_ref()).is_err());
672    }
673
674    #[test]
675    fn decode_image_into_default_forwards() {
676        let mut dst = ImageBuf::<Gray8>::zeroed(Dimensions::new(1, 1).unwrap()).unwrap();
677        Trivial.decode_image_into(&[], &mut dst).unwrap();
678        assert_eq!(dst.as_samples(), &[42]);
679    }
680
681    #[test]
682    fn traits_are_object_safe() {
683        // Compiles and runs only while both traits stay object-safe (e.g. for `Box<dyn …>`).
684        let enc: &dyn EncodeImage<Gray8> = &Trivial;
685        let dec: &dyn DecodeImage<Gray8> = &Trivial;
686        let img = ImageBuf::<Gray8>::new(vec![7u8], Dimensions::new(1, 1).unwrap()).unwrap();
687        let mut out = Vec::new();
688        assert_eq!(enc.encode_image(img.as_ref(), &mut out).unwrap(), 1);
689        assert_eq!(dec.decode_image(&[]).unwrap().as_samples(), &[42]);
690    }
691}