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
171// C ABI values — permanent, append-only (issue #242). A change here is an ABI break, not a
172// refactor, so the pins are compile-time: editing a discriminant fails the defining crate's
173// build rather than a later test run.
174const _: () = {
175    assert!(ColorModel::Gray as u32 == 0);
176    assert!(ColorModel::GrayAlpha as u32 == 1);
177    assert!(ColorModel::Rgb as u32 == 2);
178    assert!(ColorModel::Rgba as u32 == 3);
179    assert!(ColorModel::Cmyk as u32 == 4);
180    assert!(ColorModel::Bilevel as u32 == 5);
181    assert!(ColorModel::Indexed as u32 == 6);
182
183    assert!(PixelFormat::Gray8 as u32 == 0);
184    assert!(PixelFormat::Bilevel as u32 == 1);
185    assert!(PixelFormat::Indexed8 as u32 == 2);
186    assert!(PixelFormat::Rgb8 as u32 == 3);
187    assert!(PixelFormat::Rgba8 as u32 == 4);
188    assert!(PixelFormat::Cmyk8 as u32 == 5);
189    assert!(PixelFormat::GrayAlpha8 as u32 == 6);
190    assert!(PixelFormat::Gray16 as u32 == 7);
191    assert!(PixelFormat::Rgb16 as u32 == 8);
192    assert!(PixelFormat::Rgba16 as u32 == 9);
193    assert!(PixelFormat::GrayAlpha16 as u32 == 10);
194};
195
196mod pixel_sealed {
197    pub trait Sealed {}
198}
199
200/// Compile-time description of one interleaved pixel layout.
201///
202/// Sealed: implemented only by the zero-sized marker types in this module. A buffer is branded with
203/// a `Pixel` type so its channel count, sample primitive, and colour model are known statically;
204/// codecs implement [`crate::EncodeImage<P>`] / [`crate::DecodeImage<P>`] for exactly the `P` they
205/// support, making an unsupported format a compile error.
206pub trait Pixel: pixel_sealed::Sealed + Copy + 'static {
207    /// The storage primitive of each sample (`u8` or `u16`).
208    type Sample: Sample;
209    /// The runtime tag identifying this layout (see [`PixelFormat`]).
210    const FORMAT: PixelFormat;
211    /// Samples per pixel.
212    const CHANNELS: usize;
213    /// The colour interpretation of those samples.
214    const MODEL: ColorModel;
215    /// Bytes one pixel occupies in an interleaved buffer (`CHANNELS * size_of::<Sample>()`).
216    const BYTES_PER_PIXEL: usize = Self::CHANNELS * core::mem::size_of::<Self::Sample>();
217}
218
219/// Defines a zero-sized pixel marker and its [`Pixel`] impl from a compact table.
220macro_rules! define_pixels {
221    ($(
222        $(#[$meta:meta])*
223        $name:ident => $sample:ty, $channels:expr, $model:expr;
224    )*) => {
225        $(
226            $(#[$meta])*
227            #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
228            pub struct $name;
229
230            impl pixel_sealed::Sealed for $name {}
231            impl Pixel for $name {
232                type Sample = $sample;
233                const FORMAT: PixelFormat = PixelFormat::$name;
234                const CHANNELS: usize = $channels;
235                const MODEL: ColorModel = $model;
236            }
237        )*
238    };
239}
240
241define_pixels! {
242    /// 8-bit grayscale: one luminance byte per pixel.
243    Gray8 => u8, 1, ColorModel::Gray;
244    /// 8-bit bilevel: one byte per pixel, `0` = black and non-zero = white. Distinct from [`Gray8`]
245    /// so a grayscale buffer cannot be mistaken for a 1-bit image.
246    Bilevel => u8, 1, ColorModel::Bilevel;
247    /// 8-bit palette indices: one index byte per pixel into a separate colour table. Distinct from
248    /// [`Gray8`] so indices cannot be mistaken for luminance.
249    Indexed8 => u8, 1, ColorModel::Indexed;
250    /// 8-bit RGB: three interleaved bytes per pixel, row-major.
251    Rgb8 => u8, 3, ColorModel::Rgb;
252    /// 8-bit RGBA: four interleaved bytes per pixel (unassociated alpha).
253    Rgba8 => u8, 4, ColorModel::Rgba;
254    /// 8-bit CMYK: four interleaved ink bytes per pixel. Distinct from [`Rgba8`] despite the shared
255    /// channel count.
256    Cmyk8 => u8, 4, ColorModel::Cmyk;
257    /// 8-bit grayscale + alpha: two interleaved bytes per pixel (luminance, then unassociated
258    /// alpha). The PNG "greyscale with alpha" colour type.
259    GrayAlpha8 => u8, 2, ColorModel::GrayAlpha;
260    /// 16-bit grayscale: one `u16` luminance sample per pixel (high-bit-depth).
261    Gray16 => u16, 1, ColorModel::Gray;
262    /// 16-bit RGB: three interleaved `u16` samples per pixel (high-bit-depth).
263    Rgb16 => u16, 3, ColorModel::Rgb;
264    /// 16-bit RGBA: four interleaved `u16` samples per pixel (high-bit-depth).
265    Rgba16 => u16, 4, ColorModel::Rgba;
266    /// 16-bit grayscale + alpha: two interleaved `u16` samples per pixel (luminance, then
267    /// unassociated alpha; high-bit-depth).
268    GrayAlpha16 => u16, 2, ColorModel::GrayAlpha;
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    #[test]
276    fn pixel_layout_constants() {
277        assert_eq!((Gray8::CHANNELS, Gray8::BYTES_PER_PIXEL), (1, 1));
278        assert_eq!(Gray8::MODEL, ColorModel::Gray);
279        assert_eq!((Bilevel::CHANNELS, Bilevel::BYTES_PER_PIXEL), (1, 1));
280        assert_eq!(Bilevel::MODEL, ColorModel::Bilevel);
281        assert_eq!((Indexed8::CHANNELS, Indexed8::BYTES_PER_PIXEL), (1, 1));
282        assert_eq!(Indexed8::MODEL, ColorModel::Indexed);
283        assert_eq!((Rgb8::CHANNELS, Rgb8::BYTES_PER_PIXEL), (3, 3));
284        assert_eq!(Rgb8::MODEL, ColorModel::Rgb);
285        assert_eq!((Rgba8::CHANNELS, Rgba8::BYTES_PER_PIXEL), (4, 4));
286        assert_eq!(Rgba8::MODEL, ColorModel::Rgba);
287        assert_eq!((Cmyk8::CHANNELS, Cmyk8::BYTES_PER_PIXEL), (4, 4));
288        assert_eq!(Cmyk8::MODEL, ColorModel::Cmyk);
289        assert_eq!((GrayAlpha8::CHANNELS, GrayAlpha8::BYTES_PER_PIXEL), (2, 2));
290        assert_eq!(GrayAlpha8::MODEL, ColorModel::GrayAlpha);
291        assert_eq!((Gray16::CHANNELS, Gray16::BYTES_PER_PIXEL), (1, 2));
292        assert_eq!((Rgb16::CHANNELS, Rgb16::BYTES_PER_PIXEL), (3, 6));
293        assert_eq!((Rgba16::CHANNELS, Rgba16::BYTES_PER_PIXEL), (4, 8));
294        assert_eq!(
295            (GrayAlpha16::CHANNELS, GrayAlpha16::BYTES_PER_PIXEL),
296            (2, 4)
297        );
298        assert_eq!(GrayAlpha16::MODEL, ColorModel::GrayAlpha);
299    }
300
301    /// `P::FORMAT`'s runtime accessors must agree with `P`'s compile-time constants. The 11
302    /// markers vary in every dimension, so any constant-replacement mutant in an accessor is
303    /// killed by at least one instantiation.
304    fn assert_format_matches<P: Pixel>() {
305        assert_eq!(P::FORMAT.channels(), P::CHANNELS);
306        assert_eq!(P::FORMAT.color_model(), P::MODEL);
307        assert_eq!(P::FORMAT.bytes_per_pixel(), P::BYTES_PER_PIXEL);
308        assert_eq!(
309            P::FORMAT.bytes_per_sample(),
310            core::mem::size_of::<P::Sample>()
311        );
312    }
313
314    #[test]
315    fn pixel_format_mirrors_marker_constants() {
316        assert_format_matches::<Gray8>();
317        assert_format_matches::<Bilevel>();
318        assert_format_matches::<Indexed8>();
319        assert_format_matches::<Rgb8>();
320        assert_format_matches::<Rgba8>();
321        assert_format_matches::<Cmyk8>();
322        assert_format_matches::<GrayAlpha8>();
323        assert_format_matches::<Gray16>();
324        assert_format_matches::<Rgb16>();
325        assert_format_matches::<Rgba16>();
326        assert_format_matches::<GrayAlpha16>();
327    }
328
329    #[test]
330    fn pixel_format_all_is_the_distinct_marker_set() {
331        let formats = [
332            Gray8::FORMAT,
333            Bilevel::FORMAT,
334            Indexed8::FORMAT,
335            Rgb8::FORMAT,
336            Rgba8::FORMAT,
337            Cmyk8::FORMAT,
338            GrayAlpha8::FORMAT,
339            Gray16::FORMAT,
340            Rgb16::FORMAT,
341            Rgba16::FORMAT,
342            GrayAlpha16::FORMAT,
343        ];
344        assert_eq!(PixelFormat::ALL, formats);
345        for (i, a) in PixelFormat::ALL.iter().enumerate() {
346            for b in &PixelFormat::ALL[i + 1..] {
347                assert_ne!(a, b);
348            }
349        }
350    }
351
352    #[test]
353    fn distinct_models_share_channel_count() {
354        // Exactly the footgun the type system now prevents: same shape, different meaning.
355        assert_eq!(Rgba8::CHANNELS, Cmyk8::CHANNELS);
356        assert_ne!(Rgba8::MODEL, Cmyk8::MODEL);
357        assert_eq!(Gray8::CHANNELS, Indexed8::CHANNELS);
358        assert_ne!(Gray8::MODEL, Indexed8::MODEL);
359        assert_ne!(Gray8::MODEL, Bilevel::MODEL);
360    }
361}