Skip to main content

gamut_core/
pixel.rs

1//! Compile-time pixel vocabulary: the [`Sample`] storage primitives, the [`ColorModel`] tag, and
2//! the sealed [`Pixel`] trait with one zero-sized marker per supported interleaved layout.
3//!
4//! These types brand the otherwise-opaque sample buffers in [`crate::ImageRef`] / [`crate::ImageBuf`]
5//! so a layout mismatch — handing CMYK bytes to an RGBA encoder, or grayscale luminance where
6//! palette indices are expected — is a compile error rather than a runtime length check. The markers
7//! carry no data; they exist only to select an encoder/decoder impl and to expose the layout
8//! constants ([`Pixel::CHANNELS`], [`Pixel::MODEL`], [`Pixel::BYTES_PER_PIXEL`]). The
9//! [`PixelFormat`] tag is the runtime mirror of that closed marker set for boundaries that
10//! dispatch dynamically (FFI, plugin registries).
11
12mod sample_sealed {
13    pub trait Sealed {}
14    impl Sealed for u8 {}
15    impl Sealed for u16 {}
16}
17
18/// A pixel-sample storage primitive: `u8` (8-bit) or `u16` (10/12/16-bit, high-bit-depth).
19///
20/// Sealed — only `u8` and `u16` implement it. The supertrait bounds are chosen so that `P::Sample`
21/// transitively gives buffer types everything they need (copy, zero-fill via `Default`, ordering)
22/// without callers repeating `where P::Sample: …` clauses. The storage width is available as
23/// `size_of::<Self>()`; a stream's *coded* bit depth (e.g. 10 or 12) is a separate codec concern
24/// carried elsewhere (see `gamut_color::BitDepth`).
25pub trait Sample:
26    sample_sealed::Sealed + Copy + Default + Ord + core::fmt::Debug + 'static
27{
28}
29
30impl Sample for u8 {}
31impl Sample for u16 {}
32
33/// The colour interpretation of a pixel's channels.
34///
35/// Distinguishes layouts that share a channel count: [`ColorModel::Rgba`] and [`ColorModel::Cmyk`]
36/// are both four channels but must never be interchanged, and [`ColorModel::Gray`],
37/// [`ColorModel::Bilevel`], and [`ColorModel::Indexed`] are all one channel with different meanings.
38///
39/// Discriminants are explicit and permanent — they are C ABI values (issue #242); new variants
40/// append.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42#[non_exhaustive]
43#[repr(u32)]
44pub enum ColorModel {
45    /// Single luminance channel.
46    Gray = 0,
47    /// Luminance plus an alpha channel.
48    GrayAlpha = 1,
49    /// Red, green, blue.
50    Rgb = 2,
51    /// Red, green, blue, alpha (unassociated).
52    Rgba = 3,
53    /// Cyan, magenta, yellow, black ink separations.
54    Cmyk = 4,
55    /// One channel, `0` = black and any non-zero value = white (a 1-bit image carried as one byte
56    /// per pixel).
57    Bilevel = 5,
58    /// One channel of indices into a separate colour palette.
59    Indexed = 6,
60}
61
62/// Runtime tag for the closed set of [`Pixel`] marker types — one variant per marker.
63///
64/// The FFI/dispatch mirror of the compile-time `Pixel` matrix (issue #242): where the type
65/// system selects a codec impl through the marker type, a boundary that only has runtime
66/// information (a C caller, a plugin registry) selects the same layout by tag and dispatches to
67/// the monomorphized impl. [`PixelFormat::ALL`] enumerates the matrix for tooling that generates
68/// such dispatch.
69///
70/// Discriminants are explicit and permanent — they are C ABI values; new variants append.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72#[non_exhaustive]
73#[repr(u32)]
74pub enum PixelFormat {
75    /// Tag for [`Gray8`].
76    Gray8 = 0,
77    /// Tag for [`Bilevel`].
78    Bilevel = 1,
79    /// Tag for [`Indexed8`].
80    Indexed8 = 2,
81    /// Tag for [`Rgb8`].
82    Rgb8 = 3,
83    /// Tag for [`Rgba8`].
84    Rgba8 = 4,
85    /// Tag for [`Cmyk8`].
86    Cmyk8 = 5,
87    /// Tag for [`GrayAlpha8`].
88    GrayAlpha8 = 6,
89    /// Tag for [`Gray16`].
90    Gray16 = 7,
91    /// Tag for [`Rgb16`].
92    Rgb16 = 8,
93    /// Tag for [`Rgba16`].
94    Rgba16 = 9,
95    /// Tag for [`GrayAlpha16`].
96    GrayAlpha16 = 10,
97}
98
99impl PixelFormat {
100    /// Every pixel format, in discriminant order — the full codec × layout monomorphization
101    /// matrix for tooling that enumerates it (each entry is some marker's [`Pixel::FORMAT`]).
102    pub const ALL: [PixelFormat; 11] = [
103        PixelFormat::Gray8,
104        PixelFormat::Bilevel,
105        PixelFormat::Indexed8,
106        PixelFormat::Rgb8,
107        PixelFormat::Rgba8,
108        PixelFormat::Cmyk8,
109        PixelFormat::GrayAlpha8,
110        PixelFormat::Gray16,
111        PixelFormat::Rgb16,
112        PixelFormat::Rgba16,
113        PixelFormat::GrayAlpha16,
114    ];
115
116    /// Samples per pixel; the runtime mirror of [`Pixel::CHANNELS`].
117    #[must_use]
118    pub const fn channels(self) -> usize {
119        match self {
120            PixelFormat::Gray8
121            | PixelFormat::Bilevel
122            | PixelFormat::Indexed8
123            | PixelFormat::Gray16 => 1,
124            PixelFormat::GrayAlpha8 | PixelFormat::GrayAlpha16 => 2,
125            PixelFormat::Rgb8 | PixelFormat::Rgb16 => 3,
126            PixelFormat::Rgba8 | PixelFormat::Cmyk8 | PixelFormat::Rgba16 => 4,
127        }
128    }
129
130    /// The colour interpretation of the samples; the runtime mirror of [`Pixel::MODEL`].
131    #[must_use]
132    pub const fn color_model(self) -> ColorModel {
133        match self {
134            PixelFormat::Gray8 | PixelFormat::Gray16 => ColorModel::Gray,
135            PixelFormat::Bilevel => ColorModel::Bilevel,
136            PixelFormat::Indexed8 => ColorModel::Indexed,
137            PixelFormat::Rgb8 | PixelFormat::Rgb16 => ColorModel::Rgb,
138            PixelFormat::Rgba8 | PixelFormat::Rgba16 => ColorModel::Rgba,
139            PixelFormat::Cmyk8 => ColorModel::Cmyk,
140            PixelFormat::GrayAlpha8 | PixelFormat::GrayAlpha16 => ColorModel::GrayAlpha,
141        }
142    }
143
144    /// Bytes per sample of the storage primitive (`1` for `u8` layouts, `2` for `u16`); the
145    /// runtime mirror of `size_of::<`[`Pixel::Sample`]`>()`.
146    #[must_use]
147    pub const fn bytes_per_sample(self) -> usize {
148        match self {
149            PixelFormat::Gray8
150            | PixelFormat::Bilevel
151            | PixelFormat::Indexed8
152            | PixelFormat::Rgb8
153            | PixelFormat::Rgba8
154            | PixelFormat::Cmyk8
155            | PixelFormat::GrayAlpha8 => 1,
156            PixelFormat::Gray16
157            | PixelFormat::Rgb16
158            | PixelFormat::Rgba16
159            | PixelFormat::GrayAlpha16 => 2,
160        }
161    }
162
163    /// Bytes one pixel occupies in an interleaved buffer; the runtime mirror of
164    /// [`Pixel::BYTES_PER_PIXEL`].
165    #[must_use]
166    pub const fn bytes_per_pixel(self) -> usize {
167        self.channels() * self.bytes_per_sample()
168    }
169}
170
171mod pixel_sealed {
172    pub trait Sealed {}
173}
174
175/// Compile-time description of one interleaved pixel layout.
176///
177/// Sealed: implemented only by the zero-sized marker types in this module. A buffer is branded with
178/// a `Pixel` type so its channel count, sample primitive, and colour model are known statically;
179/// codecs implement [`crate::EncodeImage<P>`] / [`crate::DecodeImage<P>`] for exactly the `P` they
180/// support, making an unsupported format a compile error.
181pub trait Pixel: pixel_sealed::Sealed + Copy + 'static {
182    /// The storage primitive of each sample (`u8` or `u16`).
183    type Sample: Sample;
184    /// The runtime tag identifying this layout (see [`PixelFormat`]).
185    const FORMAT: PixelFormat;
186    /// Samples per pixel.
187    const CHANNELS: usize;
188    /// The colour interpretation of those samples.
189    const MODEL: ColorModel;
190    /// Bytes one pixel occupies in an interleaved buffer (`CHANNELS * size_of::<Sample>()`).
191    const BYTES_PER_PIXEL: usize = Self::CHANNELS * core::mem::size_of::<Self::Sample>();
192}
193
194/// Defines a zero-sized pixel marker and its [`Pixel`] impl from a compact table.
195macro_rules! define_pixels {
196    ($(
197        $(#[$meta:meta])*
198        $name:ident => $sample:ty, $channels:expr, $model:expr;
199    )*) => {
200        $(
201            $(#[$meta])*
202            #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
203            pub struct $name;
204
205            impl pixel_sealed::Sealed for $name {}
206            impl Pixel for $name {
207                type Sample = $sample;
208                const FORMAT: PixelFormat = PixelFormat::$name;
209                const CHANNELS: usize = $channels;
210                const MODEL: ColorModel = $model;
211            }
212        )*
213    };
214}
215
216define_pixels! {
217    /// 8-bit grayscale: one luminance byte per pixel.
218    Gray8 => u8, 1, ColorModel::Gray;
219    /// 8-bit bilevel: one byte per pixel, `0` = black and non-zero = white. Distinct from [`Gray8`]
220    /// so a grayscale buffer cannot be mistaken for a 1-bit image.
221    Bilevel => u8, 1, ColorModel::Bilevel;
222    /// 8-bit palette indices: one index byte per pixel into a separate colour table. Distinct from
223    /// [`Gray8`] so indices cannot be mistaken for luminance.
224    Indexed8 => u8, 1, ColorModel::Indexed;
225    /// 8-bit RGB: three interleaved bytes per pixel, row-major.
226    Rgb8 => u8, 3, ColorModel::Rgb;
227    /// 8-bit RGBA: four interleaved bytes per pixel (unassociated alpha).
228    Rgba8 => u8, 4, ColorModel::Rgba;
229    /// 8-bit CMYK: four interleaved ink bytes per pixel. Distinct from [`Rgba8`] despite the shared
230    /// channel count.
231    Cmyk8 => u8, 4, ColorModel::Cmyk;
232    /// 8-bit grayscale + alpha: two interleaved bytes per pixel (luminance, then unassociated
233    /// alpha). The PNG "greyscale with alpha" colour type.
234    GrayAlpha8 => u8, 2, ColorModel::GrayAlpha;
235    /// 16-bit grayscale: one `u16` luminance sample per pixel (high-bit-depth).
236    Gray16 => u16, 1, ColorModel::Gray;
237    /// 16-bit RGB: three interleaved `u16` samples per pixel (high-bit-depth).
238    Rgb16 => u16, 3, ColorModel::Rgb;
239    /// 16-bit RGBA: four interleaved `u16` samples per pixel (high-bit-depth).
240    Rgba16 => u16, 4, ColorModel::Rgba;
241    /// 16-bit grayscale + alpha: two interleaved `u16` samples per pixel (luminance, then
242    /// unassociated alpha; high-bit-depth).
243    GrayAlpha16 => u16, 2, ColorModel::GrayAlpha;
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    #[test]
251    fn pixel_layout_constants() {
252        assert_eq!((Gray8::CHANNELS, Gray8::BYTES_PER_PIXEL), (1, 1));
253        assert_eq!(Gray8::MODEL, ColorModel::Gray);
254        assert_eq!((Bilevel::CHANNELS, Bilevel::BYTES_PER_PIXEL), (1, 1));
255        assert_eq!(Bilevel::MODEL, ColorModel::Bilevel);
256        assert_eq!((Indexed8::CHANNELS, Indexed8::BYTES_PER_PIXEL), (1, 1));
257        assert_eq!(Indexed8::MODEL, ColorModel::Indexed);
258        assert_eq!((Rgb8::CHANNELS, Rgb8::BYTES_PER_PIXEL), (3, 3));
259        assert_eq!(Rgb8::MODEL, ColorModel::Rgb);
260        assert_eq!((Rgba8::CHANNELS, Rgba8::BYTES_PER_PIXEL), (4, 4));
261        assert_eq!(Rgba8::MODEL, ColorModel::Rgba);
262        assert_eq!((Cmyk8::CHANNELS, Cmyk8::BYTES_PER_PIXEL), (4, 4));
263        assert_eq!(Cmyk8::MODEL, ColorModel::Cmyk);
264        assert_eq!((GrayAlpha8::CHANNELS, GrayAlpha8::BYTES_PER_PIXEL), (2, 2));
265        assert_eq!(GrayAlpha8::MODEL, ColorModel::GrayAlpha);
266        assert_eq!((Gray16::CHANNELS, Gray16::BYTES_PER_PIXEL), (1, 2));
267        assert_eq!((Rgb16::CHANNELS, Rgb16::BYTES_PER_PIXEL), (3, 6));
268        assert_eq!((Rgba16::CHANNELS, Rgba16::BYTES_PER_PIXEL), (4, 8));
269        assert_eq!(
270            (GrayAlpha16::CHANNELS, GrayAlpha16::BYTES_PER_PIXEL),
271            (2, 4)
272        );
273        assert_eq!(GrayAlpha16::MODEL, ColorModel::GrayAlpha);
274    }
275
276    /// `P::FORMAT`'s runtime accessors must agree with `P`'s compile-time constants. The 11
277    /// markers vary in every dimension, so any constant-replacement mutant in an accessor is
278    /// killed by at least one instantiation.
279    fn assert_format_matches<P: Pixel>() {
280        assert_eq!(P::FORMAT.channels(), P::CHANNELS);
281        assert_eq!(P::FORMAT.color_model(), P::MODEL);
282        assert_eq!(P::FORMAT.bytes_per_pixel(), P::BYTES_PER_PIXEL);
283        assert_eq!(
284            P::FORMAT.bytes_per_sample(),
285            core::mem::size_of::<P::Sample>()
286        );
287    }
288
289    #[test]
290    fn pixel_format_mirrors_marker_constants() {
291        assert_format_matches::<Gray8>();
292        assert_format_matches::<Bilevel>();
293        assert_format_matches::<Indexed8>();
294        assert_format_matches::<Rgb8>();
295        assert_format_matches::<Rgba8>();
296        assert_format_matches::<Cmyk8>();
297        assert_format_matches::<GrayAlpha8>();
298        assert_format_matches::<Gray16>();
299        assert_format_matches::<Rgb16>();
300        assert_format_matches::<Rgba16>();
301        assert_format_matches::<GrayAlpha16>();
302    }
303
304    #[test]
305    fn pixel_format_all_is_the_distinct_marker_set() {
306        let formats = [
307            Gray8::FORMAT,
308            Bilevel::FORMAT,
309            Indexed8::FORMAT,
310            Rgb8::FORMAT,
311            Rgba8::FORMAT,
312            Cmyk8::FORMAT,
313            GrayAlpha8::FORMAT,
314            Gray16::FORMAT,
315            Rgb16::FORMAT,
316            Rgba16::FORMAT,
317            GrayAlpha16::FORMAT,
318        ];
319        assert_eq!(PixelFormat::ALL, formats);
320        for (i, a) in PixelFormat::ALL.iter().enumerate() {
321            for b in &PixelFormat::ALL[i + 1..] {
322                assert_ne!(a, b);
323            }
324        }
325    }
326
327    #[test]
328    fn pixel_format_discriminants_are_locked() {
329        // C ABI values — permanent, append-only. A change here is an ABI break, not a refactor.
330        let expected: [(PixelFormat, u32); 11] = [
331            (PixelFormat::Gray8, 0),
332            (PixelFormat::Bilevel, 1),
333            (PixelFormat::Indexed8, 2),
334            (PixelFormat::Rgb8, 3),
335            (PixelFormat::Rgba8, 4),
336            (PixelFormat::Cmyk8, 5),
337            (PixelFormat::GrayAlpha8, 6),
338            (PixelFormat::Gray16, 7),
339            (PixelFormat::Rgb16, 8),
340            (PixelFormat::Rgba16, 9),
341            (PixelFormat::GrayAlpha16, 10),
342        ];
343        for (format, value) in expected {
344            assert_eq!(format as u32, value);
345        }
346    }
347
348    #[test]
349    fn color_model_discriminants_are_locked() {
350        // C ABI values — permanent, append-only. A change here is an ABI break, not a refactor.
351        let expected: [(ColorModel, u32); 7] = [
352            (ColorModel::Gray, 0),
353            (ColorModel::GrayAlpha, 1),
354            (ColorModel::Rgb, 2),
355            (ColorModel::Rgba, 3),
356            (ColorModel::Cmyk, 4),
357            (ColorModel::Bilevel, 5),
358            (ColorModel::Indexed, 6),
359        ];
360        for (model, value) in expected {
361            assert_eq!(model as u32, value);
362        }
363    }
364
365    #[test]
366    fn distinct_models_share_channel_count() {
367        // Exactly the footgun the type system now prevents: same shape, different meaning.
368        assert_eq!(Rgba8::CHANNELS, Cmyk8::CHANNELS);
369        assert_ne!(Rgba8::MODEL, Cmyk8::MODEL);
370        assert_eq!(Gray8::CHANNELS, Indexed8::CHANNELS);
371        assert_ne!(Gray8::MODEL, Indexed8::MODEL);
372        assert_ne!(Gray8::MODEL, Bilevel::MODEL);
373    }
374}