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