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
// el.rs        Pixel format.
//
// Copyright (c) 2018-2022  Douglas P Lau
// Copyright (c) 2019-2020  Jeron Aldaron Lau
//
//! Module for `pix::el` items
use crate::chan::{Alpha, Channel, Gamma, Linear, Premultiplied};
use crate::matte::Matte;
use crate::ops::Blend;
use crate::private::Sealed;
use crate::rgb::Rgb;
use crate::ColorModel;
use std::any::TypeId;
use std::fmt::Debug;
use std::marker::PhantomData;

/// Pixel [channel], [color model], [alpha] and [gamma] mode.
///
/// A pixel can be converted to another format using the [convert] method.
///
/// [alpha]: ../chan/trait.Alpha.html
/// [channel]: ../chan/trait.Channel.html
/// [color model]: ../trait.ColorModel.html
/// [convert]: #method.convert
/// [gamma]: ../chan/trait.Gamma.html
///
/// ### Type Alias Naming Scheme
///
/// * _Gamma_: `S` for [sRGB] gamma encoding; [linear] if omitted.
/// * _Color model_: [`Rgb`] / [`Bgr`] / [`Gray`] / [`Cmy`] / [`Hsv`] /
///                  [`Hsl`] / [`Hwb`] / [`YCbCr`] / [`Matte`].
/// * _Alpha_: `a` to include alpha channel enabling translucent pixels.
/// * _Bit depth_: `8` / `16` / `32` for 8-bit integer, 16-bit integer and
///   32-bit floating-point [channels].
/// * _Alpha mode_: `p` for [premultiplied]; [straight] if omitted.
///
/// [`bgr`]: ../bgr/struct.Bgr.html
/// [channels]: ../chan/trait.Channel.html
/// [`cmy`]: ../cmy/struct.Cmy.html
/// [`gray`]: ../gray/struct.Gray.html
/// [`hsl`]: ../hsl/struct.Hsl.html
/// [`hsv`]: ../hsv/struct.Hsv.html
/// [`hwb`]: ../hwb/struct.Hwb.html
/// [linear]: ../chan/struct.Linear.html
/// [`matte`]: ../matte/struct.Matte.html
/// [premultiplied]: ../chan/struct.Premultiplied.html
/// [`Rgb`]: ../rgb/struct.Rgb.html
/// [sRGB]: ../chan/struct.Srgb.html
/// [straight]: ../chan/struct.Straight.html
/// [`YCbCr`]: ../ycc/struct.YCbCr.html
///
/// This trait is *sealed*, and cannot be implemented outside of this crate.
pub trait Pixel: Clone + Copy + Debug + Default + PartialEq + Sealed {
    /// Channel type
    type Chan: Channel;

    /// Color model
    type Model: ColorModel;

    /// Alpha mode
    type Alpha: Alpha;

    /// Gamma mode
    type Gamma: Gamma;

    /// Make a pixel from a slice of channels.
    fn from_channels(ch: &[Self::Chan]) -> Self;

    /// Convert from a pixel with a different bit depth.
    fn from_bit_depth<P>(p: P) -> Self
    where
        P: Pixel,
        Self::Chan: From<P::Chan>;

    /// Get the channels.
    fn channels(&self) -> &[Self::Chan];

    /// Get the channels mutably.
    fn channels_mut(&mut self) -> &mut [Self::Chan];

    /// Get the first channel.
    fn one(self) -> Self::Chan {
        *self.channels().get(0).unwrap_or(&Self::Chan::MAX)
    }

    /// Get a mutable reference to the first channel
    fn one_mut(&mut self) -> &mut Self::Chan {
        &mut self.channels_mut()[0]
    }

    /// Get the second channel.
    fn two(self) -> Self::Chan {
        *self.channels().get(1).unwrap_or(&Self::Chan::MAX)
    }

    /// Get a mutable reference to the second channel
    fn two_mut(&mut self) -> &mut Self::Chan {
        &mut self.channels_mut()[1]
    }

    /// Get the third channel.
    fn three(self) -> Self::Chan {
        *self.channels().get(2).unwrap_or(&Self::Chan::MAX)
    }

    /// Get a mutable reference to the third channel
    fn three_mut(&mut self) -> &mut Self::Chan {
        &mut self.channels_mut()[2]
    }

    /// Get the fourth channel.
    fn four(self) -> Self::Chan {
        *self.channels().get(3).unwrap_or(&Self::Chan::MAX)
    }

    /// Get a mutable reference to the fourth channel
    fn four_mut(&mut self) -> &mut Self::Chan {
        &mut self.channels_mut()[3]
    }

    /// Get the *alpha* channel.
    ///
    /// # Example: Get Alpha
    /// ```
    /// use pix::chan::Ch16;
    /// use pix::el::Pixel;
    /// use pix::gray::Graya16;
    ///
    /// let p = Graya16::new(0x7090, 0x6010);
    /// assert_eq!(p.alpha(), Ch16::new(0x6010));
    /// ```
    fn alpha(self) -> Self::Chan {
        let chan = self.channels();
        *chan.get(Self::Model::ALPHA).unwrap_or(&Self::Chan::MAX)
    }

    /// Get a mutable reference to the *alpha* channel.
    ///
    /// # Panics
    ///
    /// Panics if the pixel does not contain an alpha channel.
    ///
    /// # Example: Set Alpha
    /// ```
    /// use pix::chan::Ch8;
    /// use pix::el::Pixel;
    /// use pix::rgb::Rgba8;
    ///
    /// let mut p = Rgba8::new(0xFF, 0x40, 0x80, 0xA5);
    /// *p.alpha_mut() = Ch8::new(0x4B);
    /// assert_eq!(p.alpha(), Ch8::new(0x4B));
    /// ```
    fn alpha_mut(&mut self) -> &mut Self::Chan {
        let chan = self.channels_mut();
        chan.get_mut(Self::Model::ALPHA).unwrap()
    }

    /// Convert a pixel to another format
    ///
    /// * `D` Destination format.
    fn convert<D>(self) -> D
    where
        D: Pixel,
        D::Chan: From<Self::Chan>,
    {
        if TypeId::of::<Self::Model>() == TypeId::of::<D::Model>() {
            convert_same_model::<D, Self>(self)
        } else {
            convert_thru_rgba::<D, Self>(self)
        }
    }

    /// Copy a color to a pixel slice
    fn copy_color(dst: &mut [Self], clr: &Self) {
        for d in dst.iter_mut() {
            *d = *clr;
        }
    }

    /// Copy a slice to another
    fn copy_slice(dst: &mut [Self], src: &[Self]) {
        for (d, s) in dst.iter_mut().zip(src) {
            *d = *s;
        }
    }

    /// Composite a color with a pixel slice
    fn composite_color<O>(dst: &mut [Self], clr: &Self, op: O)
    where
        Self: Pixel<Alpha = Premultiplied, Gamma = Linear>,
        O: Blend,
    {
        for d in dst.iter_mut() {
            d.composite_channels(clr, op);
        }
    }

    /// Composite matte with color to destination pixel slice
    fn composite_matte<M, O>(dst: &mut [Self], src: &[M], clr: &Self, op: O)
    where
        Self: Pixel<Alpha = Premultiplied, Gamma = Linear>,
        M: Pixel<Chan = Self::Chan, Model = Matte, Gamma = Linear>,
        O: Blend,
    {
        for (d, s) in dst.iter_mut().zip(src) {
            d.composite_channels_alpha(clr, op, &s.alpha());
        }
    }

    /// Composite two slices of pixels
    fn composite_slice<O>(dst: &mut [Self], src: &[Self], op: O)
    where
        Self: Pixel<Alpha = Premultiplied, Gamma = Linear>,
        O: Blend,
    {
        for (d, s) in dst.iter_mut().zip(src) {
            d.composite_channels(s, op);
        }
    }

    /// Composite the channels of two pixels
    fn composite_channels<O>(&mut self, src: &Self, op: O)
    where
        Self: Pixel<Alpha = Premultiplied, Gamma = Linear>,
        O: Blend,
    {
        let da1 = Self::Chan::MAX - self.alpha();
        let sa1 = Self::Chan::MAX - src.alpha();
        // circular channels
        let d_chan = &mut self.channels_mut()[Self::Model::CIRCULAR];
        let s_chan = &src.channels()[Self::Model::CIRCULAR];
        d_chan
            .iter_mut()
            .zip(s_chan)
            .for_each(|(d, s)| circ_composite(d, da1, *s, sa1, op));
        // linear channels
        let d_chan = &mut self.channels_mut()[Self::Model::LINEAR];
        let s_chan = &src.channels()[Self::Model::LINEAR];
        d_chan
            .iter_mut()
            .zip(s_chan)
            .for_each(|(d, s)| O::composite(d, da1, s, sa1));
        O::composite(self.alpha_mut(), da1, &src.alpha(), sa1);
    }

    /// Composite the channels of two pixels with alpha
    fn composite_channels_alpha<O>(
        &mut self,
        src: &Self,
        op: O,
        alpha: &Self::Chan,
    ) where
        Self: Pixel<Alpha = Premultiplied, Gamma = Linear>,
        O: Blend,
    {
        let da1 = Self::Chan::MAX - self.alpha();
        let sa1 = Self::Chan::MAX - *alpha;
        // circular channels
        let d_chan = &mut self.channels_mut()[Self::Model::CIRCULAR];
        let s_chan = &src.channels()[Self::Model::CIRCULAR];
        d_chan
            .iter_mut()
            .zip(s_chan)
            .for_each(|(d, s)| circ_composite(d, da1, *s * *alpha, sa1, op));
        // linear channels
        let d_chan = &mut self.channels_mut()[Self::Model::LINEAR];
        let s_chan = &src.channels()[Self::Model::LINEAR];
        d_chan
            .iter_mut()
            .zip(s_chan)
            .for_each(|(d, s)| O::composite(d, da1, &(*s * *alpha), sa1));
        O::composite(self.alpha_mut(), da1, &(src.alpha() * *alpha), sa1);
    }
}

/// Calculate composite for a circular channel
#[inline]
fn circ_composite<C, O>(d: &mut C, da1: C, mut s: C, sa1: C, _op: O)
where
    C: Channel,
    O: Blend,
{
    // Circular channels are not premultiplied, so here's the algorithm:
    // 1. Calcualte `t`, ranging from MIN (dst) to MAX (src), using composite
    let mut t = C::MIN;
    O::composite(&mut t, da1, &(C::MAX - sa1), sa1);
    // 2. If difference > 180 degrees, rotate both by 180 degrees
    let rotate = s.max(*d) - s.min(*d) > C::MID;
    if rotate {
        if s > *d {
            s = s - C::MID;
            *d = *d + C::MID;
        } else {
            s = s + C::MID;
            *d = *d - C::MID;
        }
    }
    // 3. Lerp between src and dest.
    *d = d.lerp(s, t);
    // 4. If rotated, rotate by 180 degrees
    if rotate {
        if *d < C::MID {
            *d = *d + C::MID;
        } else {
            *d = *d - C::MID;
        }
    }
}

/// Rgba pixel type for color model conversions
pub type PixRgba<P> =
    Pix4<<P as Pixel>::Chan, Rgb, <P as Pixel>::Alpha, <P as Pixel>::Gamma>;

/// Convert a pixel to another format with the same color model.
///
/// * `D` Destination pixel format.
/// * `S` Source pixel format.
/// * `src` Source pixel.
fn convert_same_model<D, S>(src: S) -> D
where
    D: Pixel,
    S: Pixel,
    D::Chan: From<S::Chan>,
{
    let mut dst = D::from_bit_depth(src);
    if TypeId::of::<S::Alpha>() != TypeId::of::<D::Alpha>()
        || TypeId::of::<S::Gamma>() != TypeId::of::<D::Gamma>()
    {
        let alpha = dst.alpha();
        let channels = dst.channels_mut();
        convert_alpha_gamma::<D, S>(channels, alpha);
    }
    dst
}

/// Convert *alpha* / *gamma* to another pixel format
fn convert_alpha_gamma<D, S>(channels: &mut [D::Chan], alpha: D::Chan)
where
    D: Pixel,
    S: Pixel,
{
    for c in channels[D::Model::LINEAR].iter_mut() {
        *c = S::Gamma::to_linear(*c);
        if TypeId::of::<S::Alpha>() != TypeId::of::<D::Alpha>() {
            *c = S::Alpha::decode(*c, alpha);
            *c = D::Alpha::encode(*c, alpha);
        }
        *c = D::Gamma::from_linear(*c);
    }
}

/// Convert a pixel to another format thru RGBA.
///
/// * `D` Destination pixel format.
/// * `S` Source pixel format.
/// * `src` Source pixel.
fn convert_thru_rgba<D, S>(src: S) -> D
where
    D: Pixel,
    S: Pixel,
    D::Chan: From<S::Chan>,
{
    let rgba = S::Model::into_rgba::<S>(src);
    let rgba = convert_same_model::<PixRgba<D>, PixRgba<S>>(rgba);
    D::Model::from_rgba::<D>(rgba)
}

/// [Pixel] with one [channel] in its [color model].
///
/// [channel]: ../chan/trait.Channel.html
/// [color model]: ../trait.ColorModel.html
/// [pixel]: trait.Pixel.html
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[repr(C)]
pub struct Pix1<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    channels: [C; 1],
    _model: PhantomData<M>,
    _alpha: PhantomData<A>,
    _gamma: PhantomData<G>,
}

impl<C, M, A, G> Pix1<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    /// Create a one-channel color.
    ///
    /// ## Example
    /// ```
    /// use pix::gray::Gray8;
    ///
    /// let opaque_gray = Gray8::new(128);
    /// ```
    pub fn new<H>(one: H) -> Self
    where
        C: From<H>,
    {
        let channels = [C::from(one); 1];
        Pix1 {
            channels,
            _model: PhantomData,
            _alpha: PhantomData,
            _gamma: PhantomData,
        }
    }
}

impl<C, M, A, G> Pixel for Pix1<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    type Chan = C;
    type Model = M;
    type Alpha = A;
    type Gamma = G;

    fn from_channels(ch: &[C]) -> Self {
        let one = ch[0];
        Self::new::<C>(one)
    }

    fn from_bit_depth<P>(p: P) -> Self
    where
        P: Pixel,
        Self::Chan: From<P::Chan>,
    {
        debug_assert_eq!(TypeId::of::<Self::Model>(), TypeId::of::<P::Model>());
        let one = Self::Chan::from(p.one());
        Self::new::<Self::Chan>(one)
    }

    fn channels(&self) -> &[Self::Chan] {
        &self.channels
    }

    fn channels_mut(&mut self) -> &mut [Self::Chan] {
        &mut self.channels
    }
}

/// [Pixel] with two [channel]s in its [color model].
///
/// [channel]: ../chan/trait.Channel.html
/// [color model]: ../trait.ColorModel.html
/// [pixel]: trait.Pixel.html
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[repr(C)]
pub struct Pix2<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    channels: [C; 2],
    _model: PhantomData<M>,
    _alpha: PhantomData<A>,
    _gamma: PhantomData<G>,
}

impl<C, M, A, G> Pix2<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    /// Create a two-channel color.
    ///
    /// ## Example
    /// ```
    /// use pix::gray::Graya8;
    ///
    /// let translucent_gray = Graya8::new(128, 200);
    /// ```
    pub fn new<H>(one: H, two: H) -> Self
    where
        C: From<H>,
    {
        let one = C::from(one);
        let two = C::from(two);
        let channels = [one, two];
        Pix2 {
            channels,
            _model: PhantomData,
            _alpha: PhantomData,
            _gamma: PhantomData,
        }
    }
}

impl<C, M, A, G> Pixel for Pix2<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    type Chan = C;
    type Model = M;
    type Alpha = A;
    type Gamma = G;

    fn from_channels(ch: &[C]) -> Self {
        let one = ch[0];
        let two = ch[1];
        Self::new::<C>(one, two)
    }

    fn from_bit_depth<P>(p: P) -> Self
    where
        P: Pixel,
        Self::Chan: From<P::Chan>,
    {
        debug_assert_eq!(TypeId::of::<Self::Model>(), TypeId::of::<P::Model>());
        let one = Self::Chan::from(p.one());
        let two = Self::Chan::from(p.two());
        Self::new::<Self::Chan>(one, two)
    }

    fn channels(&self) -> &[Self::Chan] {
        &self.channels
    }

    fn channels_mut(&mut self) -> &mut [Self::Chan] {
        &mut self.channels
    }
}

/// [Pixel] with three [channel]s in its [color model].
///
/// [channel]: ../chan/trait.Channel.html
/// [color model]: ../trait.ColorModel.html
/// [pixel]: trait.Pixel.html
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[repr(C)]
pub struct Pix3<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    channels: [C; 3],
    _model: PhantomData<M>,
    _alpha: PhantomData<A>,
    _gamma: PhantomData<G>,
}

impl<C, M, A, G> Pix3<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    /// Create a three-channel color.
    ///
    /// ## Example
    /// ```
    /// use pix::rgb::Rgb8;
    ///
    /// let rgb = Rgb8::new(128, 200, 255);
    /// ```
    pub fn new<H>(one: H, two: H, three: H) -> Self
    where
        C: From<H>,
    {
        let one = C::from(one);
        let two = C::from(two);
        let three = C::from(three);
        let channels = [one, two, three];
        Pix3 {
            channels,
            _model: PhantomData,
            _alpha: PhantomData,
            _gamma: PhantomData,
        }
    }
}

impl<C, M, A, G> Pixel for Pix3<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    type Chan = C;
    type Model = M;
    type Alpha = A;
    type Gamma = G;

    fn from_channels(ch: &[C]) -> Self {
        let one = ch[0];
        let two = ch[1];
        let three = ch[2];
        Self::new::<C>(one, two, three)
    }

    fn from_bit_depth<P>(p: P) -> Self
    where
        P: Pixel,
        Self::Chan: From<P::Chan>,
    {
        debug_assert_eq!(TypeId::of::<Self::Model>(), TypeId::of::<P::Model>());
        let one = Self::Chan::from(p.one());
        let two = Self::Chan::from(p.two());
        let three = Self::Chan::from(p.three());
        Self::new::<Self::Chan>(one, two, three)
    }

    fn channels(&self) -> &[Self::Chan] {
        &self.channels
    }

    fn channels_mut(&mut self) -> &mut [Self::Chan] {
        &mut self.channels
    }
}

/// [Pixel] with four [channel]s in its [color model].
///
/// [channel]: ../chan/trait.Channel.html
/// [color model]: ../trait.ColorModel.html
/// [pixel]: trait.Pixel.html
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[repr(C)]
pub struct Pix4<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    channels: [C; 4],
    _model: PhantomData<M>,
    _alpha: PhantomData<A>,
    _gamma: PhantomData<G>,
}

impl<C, M, A, G> Pix4<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    /// Create a four-channel color.
    ///
    /// ## Example
    /// ```
    /// use pix::rgb::Rgba8;
    ///
    /// let rgba = Rgba8::new(128, 200, 255, 128);
    /// ```
    pub fn new<H>(one: H, two: H, three: H, four: H) -> Self
    where
        C: From<H>,
    {
        let one = C::from(one);
        let two = C::from(two);
        let three = C::from(three);
        let four = C::from(four);
        let channels = [one, two, three, four];
        Pix4 {
            channels,
            _model: PhantomData,
            _alpha: PhantomData,
            _gamma: PhantomData,
        }
    }
}

impl<C, M, A, G> Pixel for Pix4<C, M, A, G>
where
    C: Channel,
    M: ColorModel,
    A: Alpha,
    G: Gamma,
{
    type Chan = C;
    type Model = M;
    type Alpha = A;
    type Gamma = G;

    fn from_channels(ch: &[C]) -> Self {
        let one = ch[0];
        let two = ch[1];
        let three = ch[2];
        let four = ch[3];
        Self::new::<C>(one, two, three, four)
    }

    fn from_bit_depth<P>(p: P) -> Self
    where
        P: Pixel,
        Self::Chan: From<P::Chan>,
    {
        debug_assert_eq!(TypeId::of::<Self::Model>(), TypeId::of::<P::Model>());
        let one = Self::Chan::from(p.one());
        let two = Self::Chan::from(p.two());
        let three = Self::Chan::from(p.three());
        let four = Self::Chan::from(p.four());
        Self::new::<Self::Chan>(one, two, three, four)
    }

    fn channels(&self) -> &[Self::Chan] {
        &self.channels
    }

    fn channels_mut(&mut self) -> &mut [Self::Chan] {
        &mut self.channels
    }
}

#[cfg(test)]
mod test {
    use crate::el::*;
    use crate::gray::*;
    use crate::matte::*;
    use crate::rgb::*;

    #[test]
    fn check_sizes() {
        assert_eq!(std::mem::size_of::<Matte8>(), 1);
        assert_eq!(std::mem::size_of::<Matte16>(), 2);
        assert_eq!(std::mem::size_of::<Matte32>(), 4);
        assert_eq!(std::mem::size_of::<SGray8>(), 1);
        assert_eq!(std::mem::size_of::<SGray16>(), 2);
        assert_eq!(std::mem::size_of::<SGray32>(), 4);
        assert_eq!(std::mem::size_of::<SGraya8>(), 2);
        assert_eq!(std::mem::size_of::<SGraya16>(), 4);
        assert_eq!(std::mem::size_of::<SGraya32>(), 8);
        assert_eq!(std::mem::size_of::<Rgb8>(), 3);
        assert_eq!(std::mem::size_of::<Rgb16>(), 6);
        assert_eq!(std::mem::size_of::<Rgb32>(), 12);
        assert_eq!(std::mem::size_of::<Rgba8>(), 4);
        assert_eq!(std::mem::size_of::<Rgba16>(), 8);
        assert_eq!(std::mem::size_of::<Rgba32>(), 16);
    }

    #[test]
    fn gray_to_rgb() {
        assert_eq!(SRgb8::new(0xD9, 0xD9, 0xD9), SGray8::new(0xD9).convert(),);
        assert_eq!(
            SRgb8::new(0x33, 0x33, 0x33),
            SGray16::new(0x337F).convert(),
        );
        assert_eq!(SRgb8::new(0x40, 0x40, 0x40), SGray32::new(0.25).convert(),);
        assert_eq!(
            SRgb16::new(0x2929, 0x2929, 0x2929),
            SGray8::new(0x29).convert(),
        );
        assert_eq!(
            SRgb16::new(0x5593, 0x5593, 0x5593),
            SGray16::new(0x5593).convert(),
        );
        assert_eq!(
            SRgb16::new(0xFFFF, 0xFFFF, 0xFFFF),
            SGray32::new(1.0).convert(),
        );
        assert_eq!(
            SRgb32::new(0.5019608, 0.5019608, 0.5019608),
            SGray8::new(0x80).convert(),
        );
        assert_eq!(
            SRgb32::new(0.75001144, 0.75001144, 0.75001144),
            SGray16::new(0xC000).convert(),
        );
        assert_eq!(SRgb32::new(0.33, 0.33, 0.33), SGray32::new(0.33).convert(),);
    }

    #[test]
    fn linear_to_srgb() {
        assert_eq!(
            SRgb8::new(0xEF, 0x8C, 0xC7),
            Rgb8::new(0xDC, 0x43, 0x91).convert()
        );
        assert_eq!(
            SRgb8::new(0x66, 0xF4, 0xB5),
            Rgb16::new(0x2205, 0xE699, 0x7654).convert()
        );
        assert_eq!(
            SRgb8::new(0xBC, 0x89, 0xE0),
            Rgb32::new(0.5, 0.25, 0.75).convert()
        );
    }

    #[test]
    fn srgb_to_linear() {
        assert_eq!(
            Rgb8::new(0xDC, 0x43, 0x92),
            SRgb8::new(0xEF, 0x8C, 0xC7).convert(),
        );
        assert_eq!(
            Rgb8::new(0x22, 0xE7, 0x76),
            SRgb16::new(0x6673, 0xF453, 0xB593).convert(),
        );
        assert_eq!(
            Rgb8::new(0x37, 0x0D, 0x85),
            SRgb32::new(0.5, 0.25, 0.75).convert(),
        );
    }

    #[test]
    fn straight_to_premultiplied() {
        assert_eq!(
            Rgba8p::new(0x10, 0x20, 0x40, 0x80),
            Rgba8::new(0x20, 0x40, 0x80, 0x80).convert(),
        );
        assert_eq!(
            Rgba8p::new(0x04, 0x10, 0x20, 0x40),
            Rgba16::new(0x1000, 0x4000, 0x8000, 0x4000).convert(),
        );
        assert_eq!(
            Rgba8p::new(0x60, 0xBF, 0x8F, 0xBF),
            Rgba32::new(0.5, 1.0, 0.75, 0.75).convert(),
        );
    }

    #[test]
    fn premultiplied_to_straight() {
        assert_eq!(
            Rgba8::new(0x40, 0x80, 0xFF, 0x80),
            Rgba8p::new(0x20, 0x40, 0x80, 0x80).convert(),
        );
        assert_eq!(
            Rgba8::new(0x40, 0xFF, 0x80, 0x40),
            Rgba16p::new(0x1000, 0x4000, 0x2000, 0x4000).convert(),
        );
        assert_eq!(
            Rgba8::new(0xAB, 0x55, 0xFF, 0xBF),
            Rgba32p::new(0.5, 0.25, 0.75, 0.75).convert(),
        );
    }

    #[test]
    fn straight_to_premultiplied_srgb() {
        assert_eq!(
            SRgba8p::new(0x16, 0x2A, 0x5C, 0x80),
            SRgba8::new(0x20, 0x40, 0x80, 0x80).convert(),
        );
        assert_eq!(
            SRgba8p::new(0x0D, 0x1C, 0x40, 0x40),
            SRgba16::new(0x2000, 0x4000, 0x8000, 0x4000).convert(),
        );
        assert_eq!(
            SRgba8p::new(0x70, 0xE0, 0xA7, 0xBF),
            SRgba32::new(0.5, 1.0, 0.75, 0.75).convert(),
        );
    }
}