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 error messages.** [`Error::InvalidInput`] / [`Error::Unsupported`] carry `&'static
20//! str`; dynamic context is deferred and can be added later as a new `#[non_exhaustive]` variant.
21//! [`Error::Io`] is the one dynamic exception: it wraps the underlying [`std::io::Error`] so a
22//! transport failure (a disk read error while parsing from a stream-backed source) stays
23//! 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//!
28//! # Example
29//!
30//! Drive any codec through the shared [`EncodeImage`] trait, handing it a branded, already-validated
31//! [`ImageRef`]:
32//!
33//! ```
34//! use gamut_core::{Dimensions, EncodeImage, ImageRef, Pixel, Result, Rgb8};
35//!
36//! // A toy encoder; a real codec would compress `image.as_samples()` instead of copying it.
37//! struct RawEncoder;
38//! impl EncodeImage<Rgb8> for RawEncoder {
39//! fn encode_image(&self, image: ImageRef<'_, Rgb8>, out: &mut Vec<u8>) -> Result<usize> {
40//! let start = out.len();
41//! out.extend_from_slice(image.as_samples()); // input is pre-validated by `ImageRef::new`
42//! Ok(out.len() - start)
43//! }
44//! }
45//!
46//! let dims = Dimensions::new(2, 2).unwrap();
47//! let pixels = vec![0u8; dims.sample_count(Rgb8::CHANNELS).unwrap()];
48//! let image = ImageRef::<Rgb8>::new(&pixels, dims).unwrap();
49//!
50//! let mut out = Vec::new();
51//! let written = RawEncoder.encode_image(image, &mut out).unwrap();
52//! assert_eq!(written, 2 * 2 * 3);
53//! ```
54#![forbid(unsafe_code)]
55
56mod image;
57pub mod luminance;
58mod pixel;
59
60pub use image::{ImageBuf, ImageRef};
61pub use pixel::{
62 Bilevel, Cmyk8, ColorModel, Gray8, Gray16, GrayAlpha8, GrayAlpha16, Indexed8, Pixel,
63 PixelFormat, Rgb8, Rgb16, Rgba8, Rgba16, Sample,
64};
65
66/// Errors produced by gamut encoders and decoders.
67///
68/// Marked `#[non_exhaustive]` so additional variants can be added as formats land without a
69/// breaking change.
70#[derive(Debug, thiserror::Error)]
71#[non_exhaustive]
72pub enum Error {
73 /// The input data was malformed, truncated, or otherwise not valid for the format.
74 #[error("invalid input: {0}")]
75 InvalidInput(&'static str),
76 /// The requested format, profile, or feature is not yet supported.
77 #[error("unsupported: {0}")]
78 Unsupported(&'static str),
79 /// An underlying I/O operation failed while reading from a stream-backed source.
80 ///
81 /// Distinct from [`Error::InvalidInput`]: this reports the *transport* failing (a disk
82 /// error, an interrupted read), not the bytes being malformed, so batch pipelines can retry
83 /// or surface it instead of misclassifying the file as corrupt.
84 #[error("i/o error: {0}")]
85 Io(#[from] std::io::Error),
86}
87
88/// Convenience result type for gamut operations.
89pub type Result<T> = core::result::Result<T, Error>;
90
91/// Width and height of an image, in pixels.
92///
93/// `#[repr(C)]`: the layout — `width` then `height`, two `u32`s — is a public guarantee so the
94/// value can cross the C ABI boundary as-is (issue #242).
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
96#[repr(C)]
97pub struct Dimensions {
98 /// Image width in pixels.
99 pub width: u32,
100 /// Image height in pixels.
101 pub height: u32,
102}
103
104impl Dimensions {
105 /// Creates dimensions, rejecting a zero width or height.
106 ///
107 /// The fields stay public for ergonomic struct literals; this constructor is the validated
108 /// path that buffer types ([`crate::ImageRef`]) and codecs use so an empty image is caught
109 /// once, at the boundary, rather than re-checked in every encoder.
110 ///
111 /// # Errors
112 ///
113 /// Returns [`Error::InvalidInput`] if either dimension is zero.
114 pub fn new(width: u32, height: u32) -> Result<Self> {
115 if width == 0 || height == 0 {
116 return Err(Error::InvalidInput("zero-sized image"));
117 }
118 Ok(Self { width, height })
119 }
120
121 /// The pixel count `width * height`, or `None` if it overflows `usize`.
122 #[must_use]
123 pub fn num_pixels(self) -> Option<usize> {
124 (self.width as usize).checked_mul(self.height as usize)
125 }
126
127 /// The sample count for an interleaved buffer of `channels` samples per pixel
128 /// (`width * height * channels`), or `None` on overflow. The length an [`crate::ImageRef`]
129 /// validates against.
130 #[must_use]
131 pub fn sample_count(self, channels: usize) -> Option<usize> {
132 self.num_pixels()?.checked_mul(channels)
133 }
134
135 /// Whether either dimension is zero.
136 #[must_use]
137 pub fn is_empty(self) -> bool {
138 self.width == 0 || self.height == 0
139 }
140}
141
142/// Encodes an [`ImageRef`] of a specific pixel layout `P` into a compressed byte stream.
143///
144/// A codec implements this once per pixel layout it supports (`impl EncodeImage<Rgb8> for …`,
145/// `impl EncodeImage<Cmyk8> for …`, …), so asking it to encode an unsupported layout is a compile
146/// error rather than a runtime `Unsupported`. The input is pre-validated by [`ImageRef::new`], so an
147/// implementation never re-checks the buffer length. Bytes are appended to `out` to keep callers
148/// that reuse a scratch buffer allocation-conscious.
149pub trait EncodeImage<P: Pixel> {
150 /// Encode `image` into `out` (appended), returning the number of bytes written.
151 ///
152 /// # Errors
153 ///
154 /// Returns [`Error::Unsupported`] if the requested encoder configuration is not implemented, or
155 /// [`Error::InvalidInput`] if the image violates a format constraint (e.g. a dimension limit).
156 fn encode_image(&self, image: ImageRef<'_, P>, out: &mut Vec<u8>) -> Result<usize>;
157
158 /// Encode `image` into a fresh [`Vec`], returning the encoded bytes.
159 ///
160 /// A convenience over [`EncodeImage::encode_image`] for callers that just want the bytes;
161 /// reach for `encode_image` with a reused `&mut Vec<u8>` when encoding many images and you want
162 /// to amortise the allocation.
163 ///
164 /// # Errors
165 ///
166 /// As [`EncodeImage::encode_image`].
167 fn encode_to_vec(&self, image: ImageRef<'_, P>) -> Result<Vec<u8>> {
168 let mut out = Vec::new();
169 self.encode_image(image, &mut out)?;
170 Ok(out)
171 }
172}
173
174/// Decodes a compressed byte stream into an owned [`ImageBuf`] of pixel layout `P`.
175///
176/// `P` selects the layout the caller wants back; a codec implements this for each layout it can
177/// present (converting internally as needed, e.g. grayscale → [`Rgb8`]). Returning an owned
178/// [`ImageBuf`] keeps the dimensions, samples, and layout brand together so the result can't be
179/// misinterpreted.
180pub trait DecodeImage<P: Pixel> {
181 /// Decode `data` into a fresh [`ImageBuf`].
182 ///
183 /// # Errors
184 ///
185 /// Returns [`Error::InvalidInput`] if `data` is malformed, or [`Error::Unsupported`] if it uses
186 /// a feature that is not implemented or cannot be presented as `P`.
187 fn decode_image(&self, data: &[u8]) -> Result<ImageBuf<P>>;
188
189 /// Decode `data` into `dst`, reusing its allocation when possible.
190 ///
191 /// The default implementation always replaces the buffer (`*dst = self.decode_image(data)?`). A
192 /// codec may override it to reuse `dst`'s sample storage — via [`ImageBuf::as_mut_samples`] —
193 /// across repeated calls whose decoded dimensions match `dst`'s, falling back to replacement
194 /// otherwise. Either way `dst` holds the decoded image on success.
195 ///
196 /// # Errors
197 ///
198 /// As [`DecodeImage::decode_image`].
199 fn decode_image_into(&self, data: &[u8], dst: &mut ImageBuf<P>) -> Result<()> {
200 *dst = self.decode_image(data)?;
201 Ok(())
202 }
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 #[test]
210 fn error_displays_and_dimensions_fields() {
211 assert!(!Error::Unsupported("x").to_string().is_empty());
212 assert!(!Error::InvalidInput("y").to_string().is_empty());
213 let d = Dimensions {
214 width: 1920,
215 height: 1080,
216 };
217 assert_eq!(d.width, 1920);
218 assert_eq!(d.height, 1080);
219 }
220
221 #[test]
222 fn io_error_converts_and_displays() {
223 // `#[from]` gives the `?`-friendly conversion; the Display must surface the source.
224 let io = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "short read");
225 let err: Error = io.into();
226 assert!(matches!(err, Error::Io(_)));
227 assert!(err.to_string().contains("short read"));
228 }
229
230 #[test]
231 fn dimensions_new_rejects_zero() {
232 assert!(Dimensions::new(0, 4).is_err());
233 assert!(Dimensions::new(4, 0).is_err());
234 assert!(Dimensions::new(0, 0).is_err());
235 let d = Dimensions::new(4, 3).unwrap();
236 assert_eq!((d.width, d.height), (4, 3));
237 }
238
239 #[test]
240 fn dimensions_pixel_and_sample_counts() {
241 let d = Dimensions {
242 width: 4,
243 height: 3,
244 };
245 assert_eq!(d.num_pixels(), Some(12));
246 assert_eq!(d.sample_count(3), Some(36));
247 assert_eq!(d.sample_count(1), Some(12));
248 assert!(!d.is_empty());
249 }
250
251 #[test]
252 fn dimensions_is_empty() {
253 assert!(
254 Dimensions {
255 width: 0,
256 height: 5
257 }
258 .is_empty()
259 );
260 assert!(
261 Dimensions {
262 width: 5,
263 height: 0
264 }
265 .is_empty()
266 );
267 assert!(
268 !Dimensions {
269 width: 5,
270 height: 5
271 }
272 .is_empty()
273 );
274 }
275
276 #[test]
277 fn dimensions_sample_count_overflow_is_none() {
278 // 65535*65535 fits in a 32-bit usize, so num_pixels is Some on every target...
279 let d = Dimensions {
280 width: 0xFFFF,
281 height: 0xFFFF,
282 };
283 assert_eq!(d.num_pixels(), Some(0xFFFF * 0xFFFF));
284 // ...but scaling by usize::MAX channels overflows on any platform.
285 assert_eq!(d.sample_count(usize::MAX), None);
286 }
287}
288
289#[cfg(test)]
290mod trait_tests {
291 use super::*;
292
293 /// A trivial codec: encodes by copying the samples out, decodes a fixed 1x1 gray pixel.
294 /// Exists only to exercise the trait defaults and object-safety.
295 struct Trivial;
296
297 impl EncodeImage<Gray8> for Trivial {
298 fn encode_image(&self, image: ImageRef<'_, Gray8>, out: &mut Vec<u8>) -> Result<usize> {
299 out.extend_from_slice(image.as_samples());
300 Ok(image.as_samples().len())
301 }
302 }
303
304 impl DecodeImage<Gray8> for Trivial {
305 fn decode_image(&self, _data: &[u8]) -> Result<ImageBuf<Gray8>> {
306 ImageBuf::<Gray8>::new(vec![42u8], Dimensions::new(1, 1)?)
307 }
308 }
309
310 /// A codec that always fails, to exercise error propagation through provided methods.
311 struct Failing;
312
313 impl EncodeImage<Gray8> for Failing {
314 fn encode_image(&self, _image: ImageRef<'_, Gray8>, _out: &mut Vec<u8>) -> Result<usize> {
315 Err(Error::Unsupported("nope"))
316 }
317 }
318
319 #[test]
320 fn encode_image_appends_and_counts() {
321 let img = ImageBuf::<Gray8>::new(vec![1, 2, 3, 4], Dimensions::new(2, 2).unwrap()).unwrap();
322 let mut out = vec![0xFF];
323 let n = Trivial.encode_image(img.as_ref(), &mut out).unwrap();
324 assert_eq!(n, 4);
325 assert_eq!(out, vec![0xFF, 1, 2, 3, 4]);
326 }
327
328 #[test]
329 fn encode_to_vec_returns_fresh_exact_bytes() {
330 let img = ImageBuf::<Gray8>::new(vec![1, 2, 3, 4], Dimensions::new(2, 2).unwrap()).unwrap();
331 // A fresh Vec holding exactly the encoded bytes — no leading scratch, unlike encode_image
332 // which appends. Asserting exact contents kills an "Ok(Vec::new())" mutant.
333 assert_eq!(
334 Trivial.encode_to_vec(img.as_ref()).unwrap(),
335 vec![1, 2, 3, 4]
336 );
337 }
338
339 #[test]
340 fn encode_to_vec_propagates_errors() {
341 let img = ImageBuf::<Gray8>::new(vec![0], Dimensions::new(1, 1).unwrap()).unwrap();
342 // The default must surface encode_image's error rather than swallow it into an empty Vec.
343 assert!(Failing.encode_to_vec(img.as_ref()).is_err());
344 }
345
346 #[test]
347 fn decode_image_into_default_forwards() {
348 let mut dst = ImageBuf::<Gray8>::zeroed(Dimensions::new(1, 1).unwrap()).unwrap();
349 Trivial.decode_image_into(&[], &mut dst).unwrap();
350 assert_eq!(dst.as_samples(), &[42]);
351 }
352
353 #[test]
354 fn traits_are_object_safe() {
355 // Compiles and runs only while both traits stay object-safe (e.g. for `Box<dyn …>`).
356 let enc: &dyn EncodeImage<Gray8> = &Trivial;
357 let dec: &dyn DecodeImage<Gray8> = &Trivial;
358 let img = ImageBuf::<Gray8>::new(vec![7u8], Dimensions::new(1, 1).unwrap()).unwrap();
359 let mut out = Vec::new();
360 assert_eq!(enc.encode_image(img.as_ref(), &mut out).unwrap(), 1);
361 assert_eq!(dec.decode_image(&[]).unwrap().as_samples(), &[42]);
362 }
363}