1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
use ;
use Add;
use Cow;
/// Maximum pixel size in bytes supported by stack-buffer operations.
///
/// This must be at least as large as the largest pixel type in the library
/// (currently `RgbaF64` at 32 bytes). The value of 64 provides a comfortable
/// margin for custom pixel types.
pub const MAX_PIXEL_SIZE: usize = 64;
/// A fixed-size array abstraction used to represent homogeneous multi-channel pixel layouts.
///
/// This is a crate-internal sealed helper. The only external implementation is `[T; N]`.
/// Computes the sum of channel sizes at compile time.
const
/// A fixed-layout byte-addressable primitive suitable to appear as a
/// channel of a [`HomogeneousPixel`].
///
/// `PlainChannel` is the channel-role sibling of [`PlainPixel`]: it
/// describes the byte-layout-only subset of `PlainPixel`'s contract
/// — what you need to round-trip a value through `&[u8]` — without
/// the pixel-role items (`CHANNELS`, `DIM`, `cast_slice`, endian
/// helpers) that only make sense for a semantic pixel unit.
///
/// Role split:
///
/// - **Channel role** (`PlainChannel`): a scalar component with a
/// stable byte layout. Implemented by primitives `u{8,16,32,64}`,
/// `i{8,16,32,64}`, and — crucially — `f32` / `f64`. Raw floats
/// are first-class channels but never first-class pixels.
/// - **Pixel role** (`PlainPixel`): a semantic pixel unit. Extends
/// `PlainChannel` because byte layout is role-blind — a pixel's
/// bytes are pixel bytes whether you query them as the pixel or
/// as a one-element channel stream (design principle §9).
///
/// # Safety
///
/// 1. **Stable memory layout.** `size_of::<Self>() == SIZE` and the
/// bit pattern of `&self` is a contiguous `SIZE`-byte region with
/// no padding.
/// 2. **Valid for any bit pattern.** Any `[u8; SIZE]` is a valid
/// value of `Self`. (`f32` NaN bit patterns are valid — no UB to
/// construct — even though they may not represent meaningful
/// channel intensities.)
/// 3. **Round-trippable through `&[u8]`.**
/// `from_bytes(self.as_bytes()) == Some(self)` for every
/// `self: Self`.
pub unsafe
/// The `PlainPixel` trait defines a pixel type with a fixed number of channels
/// designed for byte conversion and storage.
///
/// `PlainPixel` is the pixel-role sibling of [`PlainChannel`]: it
/// extends the byte-layout channel contract with the pixel-level
/// items (`CHANNELS`, `DIM`, endian helpers, `cast_slice`) that
/// only make sense for a semantic pixel unit. The supertrait
/// relation is correct because byte layout is role-blind (design
/// principle §9).
///
/// # Safety
///
/// Implementers of this trait must guarantee the following invariants:
///
/// 1. **Memory Layout**: The type must have a well-defined, stable memory layout
/// that is compatible with byte-level operations. This typically means:
/// - No padding bytes between fields (use `#[repr(C)]` or `#[repr(packed)]`)
/// - All fields must be `Copy` types with predictable byte representations
///
/// 2. **Channel Consistency**: The `DIM` constant must accurately reflect the number
/// of logical channels in the pixel, and `channel_sizes()` must return a vector
/// with exactly `DIM` elements where each element represents the size in bytes
/// of the corresponding channel.
///
/// 3. **Byte Conversion Safety**: The type must be safe to transmute to/from byte
/// arrays. This means:
/// - No invalid bit patterns that would cause undefined behavior
/// - All possible byte combinations must be values the type can hold without UB
/// (e.g. `f32` NaN bit patterns are valid — no UB to construct — even though
/// they may not represent meaningful pixel intensities)
/// - The size of the type must equal the sum of all channel sizes
///
/// 4. **Endianness Handling**: The type must handle endianness conversion correctly
/// in `as_bytes_le()` and `as_bytes_be()` methods, ensuring data integrity
/// across different architectures.
///
/// Violating these invariants may result in undefined behavior, data corruption,
/// or memory safety issues.
pub unsafe
/// A pixel type that has a well-defined all-zero value.
///
/// Implement this when your pixel type can be safely zero-initialized.
/// All standard fovea pixel types implement `ZeroablePixel`, enabling
/// [`Image::zero`](crate::image::Image::zero).
// ──────────────────────────────────────────────────────────────────────────
// Origin-invariant pixel role
// ──────────────────────────────────────────────────────────────────────────
/// Marker trait for pixel types whose semantic interpretation is
/// **invariant under translation of the image origin**.
///
/// If `P: OriginInvariantPixel`, then a region of interest taken from an
/// `Image<P>` can be represented as an [`ImageView`](crate::image::ImageView)
/// with `Pixel = P` without changing what `P` means at local coordinates.
/// Cropping moves *where* the data lives; it does not change *what* each
/// pixel is.
///
/// # What it gates
///
/// This marker is the bound on ordinary, same-pixel-type region access:
/// [`SubView`](crate::image::SubView) (`roi`, `tiles`, `sliding_windows`)
/// and [`SubViewMut`](crate::image::SubViewMut) (`roi_mut`). Each of those
/// APIs translates the local origin, so each is only sound when the pixel
/// type's meaning survives that translation. Random access
/// ([`ImageView`](crate::image::ImageView)) and row access
/// ([`RasterImage`](crate::image::RasterImage)) are **not** gated — they do
/// not move the origin and stay available for every `T: Copy`.
///
/// # Why a separate trait (Philosophy §2, §3)
///
/// Origin-invariance is its own axis, orthogonal to the existing pixel
/// roles, and each trait adds exactly one guarantee:
///
/// - [`PlainPixel`] guarantees *byte layout* — it says nothing about
/// whether meaning depends on position. A coordinate-dependent pixel can
/// still have a perfectly stable layout.
/// - [`HomogeneousPixel`] guarantees *channel shape*.
/// - [`LinearSpace`] guarantees that *interpolation is meaningful*. That is
/// about mixing values across positions; this is about moving the origin.
///
/// The trait deliberately does **not** extend [`PlainPixel`]: ROI safety is
/// a semantic property, not a layout one. `bool` — the pixel type of
/// [`BinaryImage`](crate::image::BinaryImage) — is origin-invariant yet is
/// not part of the plain-layout pixel family.
///
/// # Safe trait (Philosophy §11)
///
/// `OriginInvariantPixel` is a **safe** trait. A wrong impl does not cause
/// undefined behaviour or reinterpret bytes; it only re-admits a region API
/// whose result would be semantically misleading. Per "if it can be written
/// without unsafe, it must be," the obligation lives in this documentation
/// rather than in an `unsafe` contract. Compare [`PlainPixel`], which is
/// `unsafe` precisely because a wrong impl reinterprets memory.
///
/// # Implementors and non-implementors
///
/// Implemented by every shipped pixel type whose meaning is independent of
/// `(x, y)`: the `Mono*`, `MonoA*`, `Rgb*` / `Bgr*`, `Srgb*`,
/// [`Indexed8`](crate::pixel::Indexed8), and [`Label32`](crate::pixel::Label32)
/// families, plus `bool`.
///
/// It is **not** implemented for raw channel primitives (`u8`, `u16`,
/// `f32`, …): those are channels, not pixels (Philosophy §9). It is also the
/// opt-out point for coordinate-dependent pixels such as Bayer CFA mosaics
/// (ADR-0037): an ROI at an odd origin shifts the 2×2 mosaic phase, so
/// returning the same pattern type would lie about the data. Such pixels
/// remain usable as [`ImageView`](crate::image::ImageView) /
/// [`RasterImage`](crate::image::RasterImage) storage and reach for named,
/// phase-aware ROI APIs instead.
///
/// The design is recorded in ADR-0051; the ROI/tiling split it builds on is
/// ADR-0017.
///
/// # Examples
///
/// Ordinary ROI works for an origin-invariant pixel such as
/// [`Mono8`](crate::pixel::Mono8):
///
/// ```
/// use fovea::Rectangle;
/// use fovea::image::{Image, ImageView, SubView};
/// use fovea::pixel::Mono8;
///
/// let img = Image::fill(4, 4, Mono8::new(7));
/// let roi = img.roi(Rectangle::new((1, 1), (2, 2))).unwrap();
/// assert_eq!(roi.pixel_at(0, 0), Mono8::new(7));
/// ```
///
/// A `Copy` pixel whose meaning depends on image coordinates does **not**
/// implement `OriginInvariantPixel`, so ordinary `roi()` fails to *compile* —
/// the misuse is rejected by the type system, never at runtime:
///
/// ```compile_fail
/// use fovea::Rectangle;
/// use fovea::image::{Image, SubView};
///
/// // A `Copy` pixel whose meaning depends on the image origin (think Bayer
/// // CFA phase). It deliberately does not implement `OriginInvariantPixel`.
/// #[derive(Clone, Copy)]
/// struct OriginDependent(u8);
///
/// let img = Image::fill(4, 4, OriginDependent(0));
/// // ERROR: `OriginDependent: OriginInvariantPixel` is not satisfied.
/// let _ = img.roi(Rectangle::new((0, 0), (2, 2)));
/// ```
/// Implements the safe [`OriginInvariantPixel`] marker for each listed
/// pixel type.
///
/// The pixel-family modules use this to opt their origin-invariant types
/// into ordinary [`SubView`](crate::image::SubView) /
/// [`SubViewMut`](crate::image::SubViewMut) access without repeating the
/// empty impl by hand. Membership is the whole specification: a
/// coordinate-dependent pixel (e.g. a future Bayer CFA type, ADR-0037) is
/// simply left off the list and therefore never gains ordinary `roi()`.
///
/// Const-generic families (`Mono<BITS>`, `Rgb<BITS>`, …) implement the
/// marker by hand next to their other generic impls, since this macro takes
/// concrete types only.
pub use impl_origin_invariant_pixel;
// ──────────────────────────────────────────────────────────────────────────
// Label pixel role
// ──────────────────────────────────────────────────────────────────────────
/// A pixel type whose values name connected-component labels.
///
/// `LabelPixel` is the pixel-role trait that gates label-image
/// producers and consumers in this crate (notably
/// [`connected_components`](crate::analyze::components::connected_components)
/// and [`Labeling`](crate::analyze::components::Labeling)).
///
/// # Contract
///
/// - [`Self::zero()`](ZeroablePixel::zero) is the canonical
/// **background** label — the value the labeling engine writes to
/// every non-foreground pixel.
/// - The set of *foreground* labels is `1 ..= MAX_LABEL`. The labeling
/// engine never produces a label outside that range; if pass 1 would
/// need to, it returns [`Error::LabelOverflow`](crate::Error::LabelOverflow).
/// - [`from_label_index`](Self::from_label_index) and
/// [`to_label_index`](Self::to_label_index) must round-trip the entire
/// foreground range: for every `i in 1..=MAX_LABEL`,
/// `from_label_index(i).unwrap().to_label_index() == i`.
///
/// # Safe trait
///
/// `LabelPixel` is a **safe** trait. A wrong impl produces numerically
/// wrong labels or a wrong [`LabelOverflow`](crate::Error::LabelOverflow)
/// boundary, never undefined behaviour. Compare [`PlainPixel`], which is
/// `unsafe` because a wrong impl reinterprets bytes. Philosophy §11
/// ("if it can be written without unsafe, it must be") therefore keeps
/// the trait safe and pushes the correctness obligation to the
/// implementor's documentation.
///
/// # Deliberate non-extension
///
/// `LabelPixel` does **not** extend [`LinearPixel`], [`BoundedChannel`],
/// [`WhiteChannel`], [`LinearChannel`], [`LinearSpace`], or
/// [`FromLinear`]. Labels are not intensities — averaging two labels,
/// gamma-converting them, inverting them, or thresholding them is
/// meaningless. Excluding those traits is the type-level fence that
/// makes such operations *fail to compile* on label images
/// (Philosophy §1). Label-image capacity is exposed via
/// [`MAX_LABEL`](Self::MAX_LABEL) instead — a different,
/// label-specific concept from `BoundedChannel::MAX`.
// ─────────────────────────────────────────────────────────────────────────────
// Integral-image source/accumulator gating
// ─────────────────────────────────────────────────────────────────────────────
//
// These traits gate the *valid combinations* of source pixel `Self` and
// accumulator pixel `A` for the summed-area-table engines in
// [`crate::analyze::integral`]. Both traits are **safe** — see the rationale
// in the [module-level doc on `IntegralPixel`](IntegralPixel).
//
// The pre-flight overflow check in `analyze::integral::preflight` reads
// `max_integral_value()` / `max_integral_squared_value()` to decide whether
// the chosen accumulator can hold the worst-case sum for the given image
// dimensions. The check is `O(1)`; the inner loop has zero
// per-pixel overhead.
/// Connects a pixel type to a valid integral-image accumulator pixel.
///
/// Implementing this trait declares that `Self` can be losslessly projected
/// into an accumulator pixel of type `A` for the purposes of computing a
/// summed-area table.
///
/// # Correctness contract — not a soundness contract
///
/// Unlike [`PlainPixel`] (which is `unsafe` because a wrong impl
/// reinterprets bytes), `IntegralPixel` is a *safe* trait. A wrong
/// [`max_integral_value`](Self::max_integral_value) does not cause UB; it
/// causes the pre-flight overflow check
/// ([`analyze::integral`](crate::analyze::integral)) to return a
/// **numerically wrong** answer (the check may pass when the accumulator
/// would actually saturate, producing a silently incorrect integral image).
/// Implementors must therefore guarantee that `max_integral_value()` is a
/// **tight upper bound** on every value `to_integral()` can produce.
///
/// Design principle §11: if it can be written without unsafe, it must be.
/// This trait is safe because the contract is a numerical bound, not a
/// layout claim.
///
/// # Float convention
///
/// For float-source pixels (e.g. `MonoF32`, `RgbF32`) the implementation
/// assumes the conventional `[0.0, 1.0]` value range. `max_integral_value`
/// therefore returns the accumulator-pixel value `1.0` on each channel.
/// Callers whose float data lies outside `[0, 1]` must either rescale
/// before calling the integral-image engine, or implement the trait on a
/// newtype that documents its own range. The library reports the
/// convention; it does not silently rescale (design principle §8).
///
/// # See also
///
/// - [`IntegralSquaredPixel`] — parallel trait for sum-of-squares.
/// Connects a pixel type to a valid *squared* integral-image accumulator.
///
/// Parallel to [`IntegralPixel`]; gates the sum-of-squares engine
/// ([`integral_squared_image`](crate::analyze::integral::integral_squared_image)).
/// The per-pixel range is the squared range of the source (e.g.
/// `255² = 65_025` for `Mono8`), so the accumulator-pixel set is
/// strictly tighter than for the non-squared trait — there is no
/// `Mono8 → Mono32` impl here, only `Mono8 → Mono64` and
/// `Mono8 → MonoF64`.
///
/// The correctness contract and float convention match those of
/// [`IntegralPixel`]; see that trait's documentation.
/// Pixel-channel types that carry an intrinsic, type-defined maximum
/// representable value.
///
/// This is the counterpart of [`ZeroablePixel`]: where `ZeroablePixel::zero`
/// provides the *zero* of a channel, `BoundedChannel::MAX` provides the
/// *saturated-bright* end of the channel's range (i.e. the value the
/// library treats as "fully saturated / white / opaque").
///
/// Implemented for every integer channel type the library ships
/// (`u8`/`u16`/`u32`/`u64`, `i8`/`i16`/`i32`/`i64`, and their
/// `Saturating<_>` wrappers).
///
/// # Not Implemented for Floats
///
/// `f32` and `f64` deliberately do **not** implement `BoundedChannel`.
/// Floating-point pixels do not have an intrinsic maximum in this
/// library — the convention that "1.0 is white" is a downstream
/// assumption that belongs at the call site, not in the type system.
/// Operations that require a channel-level maximum (e.g. [`Invert`] on a
/// homogeneous pixel type) therefore refuse to compile for float-channel
/// pixels. Users who want float inversion must name their range
/// assumption explicitly (see `PixelMap`).
///
/// [`Invert`]: crate::transform::Invert
///
/// # Example
///
/// ```
/// # use fovea::pixel::BoundedChannel;
/// assert_eq!(<u8 as BoundedChannel>::MAX, 255);
/// assert_eq!(<u16 as BoundedChannel>::MAX, u16::MAX);
/// ```
///
/// # Rationale
///
/// Centralising the bound on a trait keeps the operation open to
/// user pixel types and avoids duplicating a `MAX` constant in
/// per-type impls.
/// Pixel types that declare, for every channel slot, the value that
/// represents "fully saturated" under this pixel type's invariant.
///
/// This is the pixel-level counterpart of [`BoundedChannel`]: where
/// `BoundedChannel::MAX` is a property of a **channel data type**
/// (`Saturating<u16>::MAX = 65535`), `WhiteChannel::white_channel()` is
/// a property of the **pixel type** — which, for reduced-range pixels
/// like [`Mono<BITS>`](crate::pixel::Mono), may be strictly less than
/// the channel type's storage maximum.
///
/// Operations that write a "saturated" channel value back into a
/// homogeneous pixel (`Invert`, `BinaryThreshold`, `BinaryThresholdInv`)
/// bind on this trait to preserve the pixel's invariant.
///
/// # Why this is distinct from `BoundedChannel`
///
/// `Mono<BITS>` uses `Saturating<u16>` as its channel type, but
/// maintains the stronger invariant that the raw channel value fits in
/// `BITS` bits. `<Saturating<u16> as BoundedChannel>::MAX` is `65535`;
/// the pixel-level "white" for `Mono<10>` is `1023`. Writing `65535`
/// back into a `Mono<10>` via `from_channels` (a layout-only primitive)
/// would silently violate the pixel's invariant. `WhiteChannel` exists
/// so strategies can ask "what does *this pixel* consider white" rather
/// than "what is the channel type's storage maximum" — and so the
/// reduced-range pixel can override the answer.
///
/// # Not implemented for float-channel pixels
///
/// Float-channel pixels (`MonoF32`, `RgbF32`, …) deliberately do not
/// implement `WhiteChannel`. Floating-point pixels have no intrinsic
/// "white" in this library — the `[0.0, 1.0]` convention is a
/// downstream assumption that belongs at the call site, not in the type
/// system (Philosophy §8 — "Surface information, don't decide").
///
/// # Rationale
///
/// Separating the channel-storage maximum from the pixel-level
/// "white" lets reduced-range pixels (`Mono<BITS>`) preserve their
/// invariant when strategies like `Invert` write a saturated value
/// back through `from_channels`.
/// A pixel type that supports linear interpolation.
///
/// Mathematically, this trait defines a linear map from `Self` into `Output`:
/// - `scale` performs scalar multiplication: `s · v`
/// - `Output` supports addition (forms a vector space with scalar multiplication)
/// - `blend` computes affine combinations: `(1-α)·a + α·b`
///
/// # Linear Space Assumption
///
/// This trait **assumes that linear interpolation is mathematically meaningful**
/// for the pixel values. This is true for:
/// - Linear RGB/RGBA values
/// - Raw sensor intensity values (Mono8, Mono16, etc.)
/// - Floating-point linear light values
///
/// This is **NOT valid** for:
/// - Hue values (cyclic space: blending 10° and 350° should give ~0°, not 180°)
/// - Gamma-encoded sRGB (convert to linear first)
/// - Any cyclical or non-Euclidean value space
///
/// Users working with non-linear spaces are responsible for converting to a
/// linear representation before using `blend`.
///
/// # Output Type
///
/// The `Output` type may differ from `Self` to allow intermediate precision.
/// For example, scaling a `u8` by 0.5 produces a fractional result that cannot
/// be represented in `u8`. Implementations may use a higher-precision type
/// (like `f32`) for `Output`, or round back to the original type.
/// A channel — one numeric axis of a pixel — that supports linear
/// combinations over the scalar field `S`.
///
/// `LinearChannel` is the arithmetic substrate the derive macro uses
/// when composing a pixel's accumulator from its channel fields. User
/// code that operates on whole pixels binds on [`LinearPixel`], not
/// `LinearChannel`.
///
/// Implemented by every integer channel primitive (`u8`…`u64`,
/// `i8`…`i64`), their `Saturating<_>` wrappers, and the float
/// primitives (`f32`, `f64`). Pixel-named types (`Mono8`, `Rgb8`,
/// `MonoF32`, …) implement [`LinearPixel`], not `LinearChannel`.
///
/// # Example
///
/// ```
/// # use fovea::pixel::LinearChannel;
/// let x = <u8 as LinearChannel<f32>>::scale(&100u8, 0.5);
/// assert_eq!(x, 50.0f32);
/// ```
/// Converts a linear-space accumulator value back to a storage pixel,
/// applying rounding and clamping as appropriate.
///
/// This trait replaces `Into<P>` in algorithm bounds (like bilinear resize)
/// because the conversion from accumulator to storage pixel is intentionally
/// lossy (rounding, clamping) and the orphan rule prevents implementing
/// `From<f32> for u8`.
/// Blanket identity: any type can be "converted" from itself.
/// Marker trait asserting that a pixel type's values live in a linear mathematical
/// space where interpolation (affine combination) is meaningful.
///
/// This is true for:
/// - Linear RGB/RGBA values
/// - Raw sensor intensity values (Mono8, Mono16, etc.)
/// - Floating-point linear light values
///
/// This is **NOT valid** for:
/// - Hue values (cyclic space: blending 10° and 350° should give ~0°, not 180°)
/// - Gamma-encoded sRGB (convert to linear first)
/// - Any cyclical or non-Euclidean value space
///
/// # Status
///
/// This trait is **required by interpolation algorithms** — notably the
/// [`Bilinear`](crate::transform::Bilinear) resize strategy and the
/// [`blend`] helper above. Algorithms that need to mix pixel values
/// across positions (resize, optical flow warps, alpha compositing in a
/// non-linear-aware path) should bound on `LinearSpace`, not the broader
/// [`LinearPixel`].
///
/// All standard pixel types that derive or implement `LinearPixel` also implement
/// `LinearSpace`. If you have a non-linear pixel type that needs `scale()` for
/// internal use but should *not* be passed to interpolation algorithms, implement
/// `LinearPixel` manually without implementing `LinearSpace`.
/// Affine combination (linear interpolation): `(1-alpha)·a + alpha·b`
///
/// When `alpha = 0`, returns `a` (scaled to `Accumulator`).
/// When `alpha = 1`, returns `b` (scaled to `Accumulator`).
/// When `alpha = 0.5`, returns the midpoint.
/// # Safety
///
/// Implementers must guarantee, in addition to `PlainPixel` requirements:
///
/// 1. **Uniform Channels**: The pixel must genuinely consist of `CHANNEL_COUNT`
/// channels, all of type `Channel`. You cannot "reinterpret" the bytes as
/// a different channel decomposition (e.g., treating Rgba8 as two u32s).
///
/// 2. **Exact Memory Layout**: The pixel's memory layout must be exactly
/// `[Channel; CHANNEL_COUNT]` with no padding between channels.
///
/// 3. **Channel Ordering**: The channel order in memory must match the semantic
/// order implied by the pixel type (e.g., Rgb8 stores R at offset 0, G at 1, B at 2).
///
/// The compile-time size assertion catches size mismatches but cannot verify
/// semantic correctness. Incorrect implementations may cause:
/// - Wrong values returned from `channel()` / `to_channels()`
/// - Data corruption in planar ↔ interleaved conversions
/// - Undefined behavior in downstream code relying on channel semantics
pub unsafe