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`]).
9
10mod sample_sealed {
11    pub trait Sealed {}
12    impl Sealed for u8 {}
13    impl Sealed for u16 {}
14}
15
16/// A pixel-sample storage primitive: `u8` (8-bit) or `u16` (10/12/16-bit, high-bit-depth).
17///
18/// Sealed — only `u8` and `u16` implement it. The supertrait bounds are chosen so that `P::Sample`
19/// transitively gives buffer types everything they need (copy, zero-fill via `Default`, ordering)
20/// without callers repeating `where P::Sample: …` clauses. The storage width is available as
21/// `size_of::<Self>()`; a stream's *coded* bit depth (e.g. 10 or 12) is a separate codec concern
22/// carried elsewhere (see `gamut_color::BitDepth`).
23pub trait Sample:
24    sample_sealed::Sealed + Copy + Default + Ord + core::fmt::Debug + 'static
25{
26}
27
28impl Sample for u8 {}
29impl Sample for u16 {}
30
31/// The colour interpretation of a pixel's channels.
32///
33/// Distinguishes layouts that share a channel count: [`ColorModel::Rgba`] and [`ColorModel::Cmyk`]
34/// are both four channels but must never be interchanged, and [`ColorModel::Gray`],
35/// [`ColorModel::Bilevel`], and [`ColorModel::Indexed`] are all one channel with different meanings.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37#[non_exhaustive]
38pub enum ColorModel {
39    /// Single luminance channel.
40    Gray,
41    /// Luminance plus an alpha channel.
42    GrayAlpha,
43    /// Red, green, blue.
44    Rgb,
45    /// Red, green, blue, alpha (unassociated).
46    Rgba,
47    /// Cyan, magenta, yellow, black ink separations.
48    Cmyk,
49    /// One channel, `0` = black and any non-zero value = white (a 1-bit image carried as one byte
50    /// per pixel).
51    Bilevel,
52    /// One channel of indices into a separate colour palette.
53    Indexed,
54}
55
56mod pixel_sealed {
57    pub trait Sealed {}
58}
59
60/// Compile-time description of one interleaved pixel layout.
61///
62/// Sealed: implemented only by the zero-sized marker types in this module. A buffer is branded with
63/// a `Pixel` type so its channel count, sample primitive, and colour model are known statically;
64/// codecs implement [`crate::EncodeImage<P>`] / [`crate::DecodeImage<P>`] for exactly the `P` they
65/// support, making an unsupported format a compile error.
66pub trait Pixel: pixel_sealed::Sealed + Copy + 'static {
67    /// The storage primitive of each sample (`u8` or `u16`).
68    type Sample: Sample;
69    /// Samples per pixel.
70    const CHANNELS: usize;
71    /// The colour interpretation of those samples.
72    const MODEL: ColorModel;
73    /// Bytes one pixel occupies in an interleaved buffer (`CHANNELS * size_of::<Sample>()`).
74    const BYTES_PER_PIXEL: usize = Self::CHANNELS * core::mem::size_of::<Self::Sample>();
75}
76
77/// Defines a zero-sized pixel marker and its [`Pixel`] impl from a compact table.
78macro_rules! define_pixels {
79    ($(
80        $(#[$meta:meta])*
81        $name:ident => $sample:ty, $channels:expr, $model:expr;
82    )*) => {
83        $(
84            $(#[$meta])*
85            #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86            pub struct $name;
87
88            impl pixel_sealed::Sealed for $name {}
89            impl Pixel for $name {
90                type Sample = $sample;
91                const CHANNELS: usize = $channels;
92                const MODEL: ColorModel = $model;
93            }
94        )*
95    };
96}
97
98define_pixels! {
99    /// 8-bit grayscale: one luminance byte per pixel.
100    Gray8 => u8, 1, ColorModel::Gray;
101    /// 8-bit bilevel: one byte per pixel, `0` = black and non-zero = white. Distinct from [`Gray8`]
102    /// so a grayscale buffer cannot be mistaken for a 1-bit image.
103    Bilevel => u8, 1, ColorModel::Bilevel;
104    /// 8-bit palette indices: one index byte per pixel into a separate colour table. Distinct from
105    /// [`Gray8`] so indices cannot be mistaken for luminance.
106    Indexed8 => u8, 1, ColorModel::Indexed;
107    /// 8-bit RGB: three interleaved bytes per pixel, row-major.
108    Rgb8 => u8, 3, ColorModel::Rgb;
109    /// 8-bit RGBA: four interleaved bytes per pixel (unassociated alpha).
110    Rgba8 => u8, 4, ColorModel::Rgba;
111    /// 8-bit CMYK: four interleaved ink bytes per pixel. Distinct from [`Rgba8`] despite the shared
112    /// channel count.
113    Cmyk8 => u8, 4, ColorModel::Cmyk;
114    /// 8-bit grayscale + alpha: two interleaved bytes per pixel (luminance, then unassociated
115    /// alpha). The PNG "greyscale with alpha" colour type.
116    GrayAlpha8 => u8, 2, ColorModel::GrayAlpha;
117    /// 16-bit grayscale: one `u16` luminance sample per pixel (high-bit-depth).
118    Gray16 => u16, 1, ColorModel::Gray;
119    /// 16-bit RGB: three interleaved `u16` samples per pixel (high-bit-depth).
120    Rgb16 => u16, 3, ColorModel::Rgb;
121    /// 16-bit RGBA: four interleaved `u16` samples per pixel (high-bit-depth).
122    Rgba16 => u16, 4, ColorModel::Rgba;
123    /// 16-bit grayscale + alpha: two interleaved `u16` samples per pixel (luminance, then
124    /// unassociated alpha; high-bit-depth).
125    GrayAlpha16 => u16, 2, ColorModel::GrayAlpha;
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn pixel_layout_constants() {
134        assert_eq!((Gray8::CHANNELS, Gray8::BYTES_PER_PIXEL), (1, 1));
135        assert_eq!(Gray8::MODEL, ColorModel::Gray);
136        assert_eq!((Bilevel::CHANNELS, Bilevel::BYTES_PER_PIXEL), (1, 1));
137        assert_eq!(Bilevel::MODEL, ColorModel::Bilevel);
138        assert_eq!((Indexed8::CHANNELS, Indexed8::BYTES_PER_PIXEL), (1, 1));
139        assert_eq!(Indexed8::MODEL, ColorModel::Indexed);
140        assert_eq!((Rgb8::CHANNELS, Rgb8::BYTES_PER_PIXEL), (3, 3));
141        assert_eq!(Rgb8::MODEL, ColorModel::Rgb);
142        assert_eq!((Rgba8::CHANNELS, Rgba8::BYTES_PER_PIXEL), (4, 4));
143        assert_eq!(Rgba8::MODEL, ColorModel::Rgba);
144        assert_eq!((Cmyk8::CHANNELS, Cmyk8::BYTES_PER_PIXEL), (4, 4));
145        assert_eq!(Cmyk8::MODEL, ColorModel::Cmyk);
146        assert_eq!((GrayAlpha8::CHANNELS, GrayAlpha8::BYTES_PER_PIXEL), (2, 2));
147        assert_eq!(GrayAlpha8::MODEL, ColorModel::GrayAlpha);
148        assert_eq!((Gray16::CHANNELS, Gray16::BYTES_PER_PIXEL), (1, 2));
149        assert_eq!((Rgb16::CHANNELS, Rgb16::BYTES_PER_PIXEL), (3, 6));
150        assert_eq!((Rgba16::CHANNELS, Rgba16::BYTES_PER_PIXEL), (4, 8));
151        assert_eq!(
152            (GrayAlpha16::CHANNELS, GrayAlpha16::BYTES_PER_PIXEL),
153            (2, 4)
154        );
155        assert_eq!(GrayAlpha16::MODEL, ColorModel::GrayAlpha);
156    }
157
158    #[test]
159    fn distinct_models_share_channel_count() {
160        // Exactly the footgun the type system now prevents: same shape, different meaning.
161        assert_eq!(Rgba8::CHANNELS, Cmyk8::CHANNELS);
162        assert_ne!(Rgba8::MODEL, Cmyk8::MODEL);
163        assert_eq!(Gray8::CHANNELS, Indexed8::CHANNELS);
164        assert_ne!(Gray8::MODEL, Indexed8::MODEL);
165        assert_ne!(Gray8::MODEL, Bilevel::MODEL);
166    }
167}