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`).
25///
26/// [`Sample::MAX_VALUE`] and the two full-range conversions are what lets [`crate::convert`] do
27/// depth-generic arithmetic: every sample width maps onto one canonical 16-bit working range, so
28/// the conversion engine is written once rather than once per width.
29pub trait Sample:
30 sample_sealed::Sealed + Copy + Default + Ord + core::fmt::Debug + 'static
31{
32 /// The all-ones value for this width: fully opaque alpha, or white.
33 const MAX_VALUE: Self;
34
35 /// Widens this sample onto the canonical full-range 16-bit working scale.
36 ///
37 /// Exact and reversible: [`Sample::MAX_VALUE`] maps to `u16::MAX` and `0` maps to `0`, with no
38 /// value left unreachable. For `u8` this is the `× 0x101` rescale PNG specifies for sample-depth
39 /// expansion (3rd edition, §13.12); for `u16` it is the identity.
40 fn to_full_range_u16(self) -> u16;
41
42 /// Narrows a canonical full-range 16-bit working value back to this width, rounding to nearest.
43 ///
44 /// The inverse of [`Sample::to_full_range_u16`] — lossless for values that round-trip, and
45 /// half-up rounded otherwise. For `u16` it is the identity.
46 fn from_full_range_u16(value: u16) -> Self;
47}
48
49impl Sample for u8 {
50 const MAX_VALUE: Self = u8::MAX;
51
52 fn to_full_range_u16(self) -> u16 {
53 // PNG 3rd edition §13.12 sample-depth rescaling: replicating the byte (v * 0x101) spreads
54 // 0..=255 exactly onto 0..=65535, so 0xFF becomes 0xFFFF rather than 0xFF00.
55 u16::from(self) * 0x101
56 }
57
58 fn from_full_range_u16(value: u16) -> Self {
59 // round(value * 255 / 65535), half up. The +HALF addend before the division is what makes
60 // this round to nearest rather than truncate, so 8-bit values survive a widen/narrow
61 // round-trip unchanged.
62 ((u32::from(value) * 255 + 32_767) / 65_535) as u8
63 }
64}
65
66impl Sample for u16 {
67 const MAX_VALUE: Self = u16::MAX;
68
69 fn to_full_range_u16(self) -> u16 {
70 self
71 }
72
73 fn from_full_range_u16(value: u16) -> Self {
74 value
75 }
76}
77
78/// The colour interpretation of a pixel's channels.
79///
80/// Distinguishes layouts that share a channel count: [`ColorModel::Rgba`] and [`ColorModel::Cmyk`]
81/// are both four channels but must never be interchanged, and [`ColorModel::Gray`],
82/// [`ColorModel::Bilevel`], and [`ColorModel::Indexed`] are all one channel with different meanings.
83///
84/// Discriminants are explicit and permanent — they are C ABI values (issue #242); new variants
85/// append.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
87#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
88#[non_exhaustive]
89#[repr(u32)]
90pub enum ColorModel {
91 /// Single luminance channel.
92 Gray = 0,
93 /// Luminance plus an alpha channel.
94 GrayAlpha = 1,
95 /// Red, green, blue.
96 Rgb = 2,
97 /// Red, green, blue, alpha (unassociated).
98 Rgba = 3,
99 /// Cyan, magenta, yellow, black ink separations.
100 Cmyk = 4,
101 /// One channel, `0` = black and any non-zero value = white (a 1-bit image carried as one byte
102 /// per pixel).
103 Bilevel = 5,
104 /// One channel of indices into a separate colour palette.
105 Indexed = 6,
106}
107
108/// Runtime tag for the closed set of [`Pixel`] marker types — one variant per marker.
109///
110/// The FFI/dispatch mirror of the compile-time `Pixel` matrix (issue #242): where the type
111/// system selects a codec impl through the marker type, a boundary that only has runtime
112/// information (a C caller, a plugin registry) selects the same layout by tag and dispatches to
113/// the monomorphized impl. [`PixelFormat::ALL`] enumerates the matrix, as a slice, for tooling
114/// that generates such dispatch.
115///
116/// Discriminants are explicit and permanent — they are C ABI values; new variants append.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118#[non_exhaustive]
119#[repr(u32)]
120pub enum PixelFormat {
121 /// Tag for [`Gray8`].
122 Gray8 = 0,
123 /// Tag for [`Bilevel`].
124 Bilevel = 1,
125 /// Tag for [`Indexed8`].
126 Indexed8 = 2,
127 /// Tag for [`Rgb8`].
128 Rgb8 = 3,
129 /// Tag for [`Rgba8`].
130 Rgba8 = 4,
131 /// Tag for [`Cmyk8`].
132 Cmyk8 = 5,
133 /// Tag for [`GrayAlpha8`].
134 GrayAlpha8 = 6,
135 /// Tag for [`Gray16`].
136 Gray16 = 7,
137 /// Tag for [`Rgb16`].
138 Rgb16 = 8,
139 /// Tag for [`Rgba16`].
140 Rgba16 = 9,
141 /// Tag for [`GrayAlpha16`].
142 GrayAlpha16 = 10,
143}
144
145impl PixelFormat {
146 /// Every pixel format, in discriminant order — the full codec × layout monomorphization
147 /// matrix for tooling that enumerates it (each entry is some marker's [`Pixel::FORMAT`]).
148 ///
149 /// A slice rather than a fixed-length array, like every other `ALL` in the workspace: the
150 /// enum is `#[non_exhaustive]` and appends variants, and appending to a slice changes its
151 /// contents, never its type. Read the count from `ALL.len()` at runtime.
152 pub const ALL: &'static [PixelFormat] = &[
153 PixelFormat::Gray8,
154 PixelFormat::Bilevel,
155 PixelFormat::Indexed8,
156 PixelFormat::Rgb8,
157 PixelFormat::Rgba8,
158 PixelFormat::Cmyk8,
159 PixelFormat::GrayAlpha8,
160 PixelFormat::Gray16,
161 PixelFormat::Rgb16,
162 PixelFormat::Rgba16,
163 PixelFormat::GrayAlpha16,
164 ];
165
166 /// Samples per pixel; the runtime mirror of [`Pixel::CHANNELS`].
167 #[must_use]
168 pub const fn channels(self) -> usize {
169 match self {
170 PixelFormat::Gray8
171 | PixelFormat::Bilevel
172 | PixelFormat::Indexed8
173 | PixelFormat::Gray16 => 1,
174 PixelFormat::GrayAlpha8 | PixelFormat::GrayAlpha16 => 2,
175 PixelFormat::Rgb8 | PixelFormat::Rgb16 => 3,
176 PixelFormat::Rgba8 | PixelFormat::Cmyk8 | PixelFormat::Rgba16 => 4,
177 }
178 }
179
180 /// The colour interpretation of the samples; the runtime mirror of [`Pixel::MODEL`].
181 #[must_use]
182 pub const fn color_model(self) -> ColorModel {
183 match self {
184 PixelFormat::Gray8 | PixelFormat::Gray16 => ColorModel::Gray,
185 PixelFormat::Bilevel => ColorModel::Bilevel,
186 PixelFormat::Indexed8 => ColorModel::Indexed,
187 PixelFormat::Rgb8 | PixelFormat::Rgb16 => ColorModel::Rgb,
188 PixelFormat::Rgba8 | PixelFormat::Rgba16 => ColorModel::Rgba,
189 PixelFormat::Cmyk8 => ColorModel::Cmyk,
190 PixelFormat::GrayAlpha8 | PixelFormat::GrayAlpha16 => ColorModel::GrayAlpha,
191 }
192 }
193
194 /// Bytes per sample of the storage primitive (`1` for `u8` layouts, `2` for `u16`); the
195 /// runtime mirror of `size_of::<`[`Pixel::Sample`]`>()`.
196 #[must_use]
197 pub const fn bytes_per_sample(self) -> usize {
198 match self {
199 PixelFormat::Gray8
200 | PixelFormat::Bilevel
201 | PixelFormat::Indexed8
202 | PixelFormat::Rgb8
203 | PixelFormat::Rgba8
204 | PixelFormat::Cmyk8
205 | PixelFormat::GrayAlpha8 => 1,
206 PixelFormat::Gray16
207 | PixelFormat::Rgb16
208 | PixelFormat::Rgba16
209 | PixelFormat::GrayAlpha16 => 2,
210 }
211 }
212
213 /// Bytes one pixel occupies in an interleaved buffer; the runtime mirror of
214 /// [`Pixel::BYTES_PER_PIXEL`].
215 #[must_use]
216 pub const fn bytes_per_pixel(self) -> usize {
217 self.channels() * self.bytes_per_sample()
218 }
219}
220
221// C ABI values — permanent, append-only (issue #242). A change here is an ABI break, not a
222// refactor, so the pins are compile-time: editing a discriminant fails the defining crate's
223// build rather than a later test run.
224const _: () = {
225 assert!(ColorModel::Gray as u32 == 0);
226 assert!(ColorModel::GrayAlpha as u32 == 1);
227 assert!(ColorModel::Rgb as u32 == 2);
228 assert!(ColorModel::Rgba as u32 == 3);
229 assert!(ColorModel::Cmyk as u32 == 4);
230 assert!(ColorModel::Bilevel as u32 == 5);
231 assert!(ColorModel::Indexed as u32 == 6);
232
233 assert!(PixelFormat::Gray8 as u32 == 0);
234 assert!(PixelFormat::Bilevel as u32 == 1);
235 assert!(PixelFormat::Indexed8 as u32 == 2);
236 assert!(PixelFormat::Rgb8 as u32 == 3);
237 assert!(PixelFormat::Rgba8 as u32 == 4);
238 assert!(PixelFormat::Cmyk8 as u32 == 5);
239 assert!(PixelFormat::GrayAlpha8 as u32 == 6);
240 assert!(PixelFormat::Gray16 as u32 == 7);
241 assert!(PixelFormat::Rgb16 as u32 == 8);
242 assert!(PixelFormat::Rgba16 as u32 == 9);
243 assert!(PixelFormat::GrayAlpha16 as u32 == 10);
244};
245
246mod pixel_sealed {
247 pub trait Sealed {}
248}
249
250/// Compile-time description of one interleaved pixel layout.
251///
252/// Sealed: implemented only by the zero-sized marker types in this module. A buffer is branded with
253/// a `Pixel` type so its channel count, sample primitive, and colour model are known statically;
254/// codecs implement [`crate::EncodeImage<P>`] / [`crate::DecodeImage<P>`] for exactly the `P` they
255/// support, making an unsupported format a compile error.
256pub trait Pixel: pixel_sealed::Sealed + Copy + 'static {
257 /// The storage primitive of each sample (`u8` or `u16`).
258 type Sample: Sample;
259 /// The runtime tag identifying this layout (see [`PixelFormat`]).
260 const FORMAT: PixelFormat;
261 /// Samples per pixel.
262 const CHANNELS: usize;
263 /// The colour interpretation of those samples.
264 const MODEL: ColorModel;
265 /// Bytes one pixel occupies in an interleaved buffer (`CHANNELS * size_of::<Sample>()`).
266 const BYTES_PER_PIXEL: usize = Self::CHANNELS * core::mem::size_of::<Self::Sample>();
267}
268
269/// Defines a zero-sized pixel marker and its [`Pixel`] impl from a compact table.
270macro_rules! define_pixels {
271 ($(
272 $(#[$meta:meta])*
273 $name:ident => $sample:ty, $channels:expr, $model:expr;
274 )*) => {
275 $(
276 $(#[$meta])*
277 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
278 pub struct $name;
279
280 impl pixel_sealed::Sealed for $name {}
281 impl Pixel for $name {
282 type Sample = $sample;
283 const FORMAT: PixelFormat = PixelFormat::$name;
284 const CHANNELS: usize = $channels;
285 const MODEL: ColorModel = $model;
286 }
287 )*
288 };
289}
290
291define_pixels! {
292 /// 8-bit grayscale: one luminance byte per pixel.
293 Gray8 => u8, 1, ColorModel::Gray;
294 /// 8-bit bilevel: one byte per pixel, `0` = black and non-zero = white. Distinct from [`Gray8`]
295 /// so a grayscale buffer cannot be mistaken for a 1-bit image.
296 Bilevel => u8, 1, ColorModel::Bilevel;
297 /// 8-bit palette indices: one index byte per pixel into a separate colour table. Distinct from
298 /// [`Gray8`] so indices cannot be mistaken for luminance.
299 Indexed8 => u8, 1, ColorModel::Indexed;
300 /// 8-bit RGB: three interleaved bytes per pixel, row-major.
301 Rgb8 => u8, 3, ColorModel::Rgb;
302 /// 8-bit RGBA: four interleaved bytes per pixel (unassociated alpha).
303 Rgba8 => u8, 4, ColorModel::Rgba;
304 /// 8-bit CMYK: four interleaved ink bytes per pixel. Distinct from [`Rgba8`] despite the shared
305 /// channel count.
306 Cmyk8 => u8, 4, ColorModel::Cmyk;
307 /// 8-bit grayscale + alpha: two interleaved bytes per pixel (luminance, then unassociated
308 /// alpha). The PNG "greyscale with alpha" colour type.
309 GrayAlpha8 => u8, 2, ColorModel::GrayAlpha;
310 /// 16-bit grayscale: one `u16` luminance sample per pixel (high-bit-depth).
311 Gray16 => u16, 1, ColorModel::Gray;
312 /// 16-bit RGB: three interleaved `u16` samples per pixel (high-bit-depth).
313 Rgb16 => u16, 3, ColorModel::Rgb;
314 /// 16-bit RGBA: four interleaved `u16` samples per pixel (high-bit-depth).
315 Rgba16 => u16, 4, ColorModel::Rgba;
316 /// 16-bit grayscale + alpha: two interleaved `u16` samples per pixel (luminance, then
317 /// unassociated alpha; high-bit-depth).
318 GrayAlpha16 => u16, 2, ColorModel::GrayAlpha;
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 #[test]
326 fn pixel_layout_constants() {
327 assert_eq!((Gray8::CHANNELS, Gray8::BYTES_PER_PIXEL), (1, 1));
328 assert_eq!(Gray8::MODEL, ColorModel::Gray);
329 assert_eq!((Bilevel::CHANNELS, Bilevel::BYTES_PER_PIXEL), (1, 1));
330 assert_eq!(Bilevel::MODEL, ColorModel::Bilevel);
331 assert_eq!((Indexed8::CHANNELS, Indexed8::BYTES_PER_PIXEL), (1, 1));
332 assert_eq!(Indexed8::MODEL, ColorModel::Indexed);
333 assert_eq!((Rgb8::CHANNELS, Rgb8::BYTES_PER_PIXEL), (3, 3));
334 assert_eq!(Rgb8::MODEL, ColorModel::Rgb);
335 assert_eq!((Rgba8::CHANNELS, Rgba8::BYTES_PER_PIXEL), (4, 4));
336 assert_eq!(Rgba8::MODEL, ColorModel::Rgba);
337 assert_eq!((Cmyk8::CHANNELS, Cmyk8::BYTES_PER_PIXEL), (4, 4));
338 assert_eq!(Cmyk8::MODEL, ColorModel::Cmyk);
339 assert_eq!((GrayAlpha8::CHANNELS, GrayAlpha8::BYTES_PER_PIXEL), (2, 2));
340 assert_eq!(GrayAlpha8::MODEL, ColorModel::GrayAlpha);
341 assert_eq!((Gray16::CHANNELS, Gray16::BYTES_PER_PIXEL), (1, 2));
342 assert_eq!((Rgb16::CHANNELS, Rgb16::BYTES_PER_PIXEL), (3, 6));
343 assert_eq!((Rgba16::CHANNELS, Rgba16::BYTES_PER_PIXEL), (4, 8));
344 assert_eq!(
345 (GrayAlpha16::CHANNELS, GrayAlpha16::BYTES_PER_PIXEL),
346 (2, 4)
347 );
348 assert_eq!(GrayAlpha16::MODEL, ColorModel::GrayAlpha);
349 }
350
351 /// `P::FORMAT`'s runtime accessors must agree with `P`'s compile-time constants. The 11
352 /// markers vary in every dimension, so any constant-replacement mutant in an accessor is
353 /// killed by at least one instantiation.
354 fn assert_format_matches<P: Pixel>() {
355 assert_eq!(P::FORMAT.channels(), P::CHANNELS);
356 assert_eq!(P::FORMAT.color_model(), P::MODEL);
357 assert_eq!(P::FORMAT.bytes_per_pixel(), P::BYTES_PER_PIXEL);
358 assert_eq!(
359 P::FORMAT.bytes_per_sample(),
360 core::mem::size_of::<P::Sample>()
361 );
362 }
363
364 #[test]
365 fn pixel_format_mirrors_marker_constants() {
366 assert_format_matches::<Gray8>();
367 assert_format_matches::<Bilevel>();
368 assert_format_matches::<Indexed8>();
369 assert_format_matches::<Rgb8>();
370 assert_format_matches::<Rgba8>();
371 assert_format_matches::<Cmyk8>();
372 assert_format_matches::<GrayAlpha8>();
373 assert_format_matches::<Gray16>();
374 assert_format_matches::<Rgb16>();
375 assert_format_matches::<Rgba16>();
376 assert_format_matches::<GrayAlpha16>();
377 }
378
379 #[test]
380 fn pixel_format_all_is_the_distinct_marker_set() {
381 let formats = [
382 Gray8::FORMAT,
383 Bilevel::FORMAT,
384 Indexed8::FORMAT,
385 Rgb8::FORMAT,
386 Rgba8::FORMAT,
387 Cmyk8::FORMAT,
388 GrayAlpha8::FORMAT,
389 Gray16::FORMAT,
390 Rgb16::FORMAT,
391 Rgba16::FORMAT,
392 GrayAlpha16::FORMAT,
393 ];
394 assert_eq!(PixelFormat::ALL, formats.as_slice());
395 for (i, a) in PixelFormat::ALL.iter().enumerate() {
396 for b in &PixelFormat::ALL[i + 1..] {
397 assert_ne!(a, b);
398 }
399 }
400 }
401
402 #[test]
403 fn pixel_format_all_is_a_slice_of_every_variant_in_discriminant_order() {
404 // Ascription: reverting `ALL` to a fixed-length array fails to compile here (#629).
405 let all: &'static [PixelFormat] = PixelFormat::ALL;
406 // Contiguous from 0 in order: no gap, duplicate or reordering.
407 for (i, format) in all.iter().enumerate() {
408 assert_eq!(*format as usize, i, "{format:?} is out of place");
409 }
410 // Discriminants append, so the newest variant has the highest one and must close the
411 // slice. In-crate this match is exhaustive despite `#[non_exhaustive]`: appending a
412 // variant fails to compile until it is named newest, and then fails above until listed.
413 let is_newest = |format: PixelFormat| match format {
414 PixelFormat::GrayAlpha16 => true,
415 PixelFormat::Gray8
416 | PixelFormat::Bilevel
417 | PixelFormat::Indexed8
418 | PixelFormat::Rgb8
419 | PixelFormat::Rgba8
420 | PixelFormat::Cmyk8
421 | PixelFormat::GrayAlpha8
422 | PixelFormat::Gray16
423 | PixelFormat::Rgb16
424 | PixelFormat::Rgba16 => false,
425 };
426 assert!(all.last().is_some_and(|&last| is_newest(last)));
427 }
428
429 #[test]
430 fn u8_widens_by_byte_replication() {
431 // PNG §13.12: the byte is replicated, not shifted. Endpoints and a midpoint pin the scale.
432 assert_eq!(0u8.to_full_range_u16(), 0);
433 assert_eq!(1u8.to_full_range_u16(), 0x0101);
434 assert_eq!(128u8.to_full_range_u16(), 0x8080);
435 assert_eq!(u8::MAX.to_full_range_u16(), u16::MAX);
436 assert_eq!(u8::MAX_VALUE, 255);
437 }
438
439 #[test]
440 fn u8_narrows_round_to_nearest() {
441 // The rounding boundary sits between 128 and 129 (128/257 = 0.498, 129/257 = 0.502), so a
442 // truncating implementation and an off-by-one addend both fail here.
443 assert_eq!(u8::from_full_range_u16(0), 0);
444 assert_eq!(u8::from_full_range_u16(128), 0);
445 assert_eq!(u8::from_full_range_u16(129), 1);
446 assert_eq!(u8::from_full_range_u16(257), 1);
447 assert_eq!(u8::from_full_range_u16(u16::MAX), 255);
448 }
449
450 #[test]
451 fn u8_survives_a_widen_narrow_round_trip() {
452 // Every 8-bit value must be recovered exactly; this is what makes an 8 -> 16 -> 8 decode
453 // path lossless and is the property the two constants above jointly guarantee.
454 for value in 0..=u8::MAX {
455 assert_eq!(u8::from_full_range_u16(value.to_full_range_u16()), value);
456 }
457 }
458
459 #[test]
460 fn u16_conversions_are_the_identity() {
461 for value in [0u16, 1, 0x8080, 40_000, u16::MAX] {
462 assert_eq!(value.to_full_range_u16(), value);
463 assert_eq!(u16::from_full_range_u16(value), value);
464 }
465 assert_eq!(u16::MAX_VALUE, 65_535);
466 }
467
468 #[test]
469 fn distinct_models_share_channel_count() {
470 // Exactly the footgun the type system now prevents: same shape, different meaning.
471 assert_eq!(Rgba8::CHANNELS, Cmyk8::CHANNELS);
472 assert_ne!(Rgba8::MODEL, Cmyk8::MODEL);
473 assert_eq!(Gray8::CHANNELS, Indexed8::CHANNELS);
474 assert_ne!(Gray8::MODEL, Indexed8::MODEL);
475 assert_ne!(Gray8::MODEL, Bilevel::MODEL);
476 }
477}