ril 0.10.3

Rust Imaging Library: A performant and high-level image processing crate for Rust
Documentation
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
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
//! Encloses pixel-related traits and pixel type implementations.

use crate::{
    encodings::ColorType,
    image::OverlayMode,
    Error::{DecodingError, InvalidHexCode, InvalidPaletteIndex, UnsupportedColorType},
    Result,
};
use std::{
    borrow::Cow,
    fmt::{self, Debug, Formatter},
    hash::Hash,
    ops::Not,
};

mod sealed {
    use super::{BitPixel, Dynamic, NoOp, PalettedRgb, PalettedRgba, Rgb, Rgba, L};
    pub trait Sealed {}

    macro_rules! sealed {
        ($($t:ty)+) => {
            $(impl Sealed for $t {})+
        };
    }

    pub trait MaybeSealed {
        const SEALED: bool = false;
    }

    impl<P: Sealed> MaybeSealed for P {
        const SEALED: bool = true;
    }

    sealed!(NoOp BitPixel L Rgb Rgba Dynamic PalettedRgb<'_> PalettedRgba<'_>);
}

pub use sealed::MaybeSealed;

/// Represents any type of pixel in an image.
///
/// Generally speaking, the values enclosed inside of each pixel are designed to be immutable.
pub trait Pixel:
    Copy + Clone + Debug + Default + PartialEq + Eq + Hash + Not<Output = Self> + MaybeSealed
{
    /// The color type of the pixel.
    const COLOR_TYPE: ColorType;

    /// The bit depth of the pixel.
    const BIT_DEPTH: u8;

    /// The type of a single component in the pixel.
    type Subpixel: Copy + Into<usize>;

    /// The resolved color type of the palette. This is `Self` for non-paletted pixels.
    type Color: Pixel;

    /// The iterator type this pixel uses.
    type Data: IntoIterator<Item = u8> + AsRef<[u8]>;

    /// Resolves the color type of this pixel at runtime. This is used for dynamic color types.
    /// If you are certain the pixel is not dynamic, you can use the [`Self::COLOR_TYPE`] constant
    /// instead.
    fn color_type(&self) -> ColorType {
        Self::COLOR_TYPE
    }

    /// The luminance of the pixel.
    #[must_use]
    fn luminance(&self) -> u8
    where
        Self: Into<L>,
    {
        let L(value) = (*self).into();

        value
    }

    /// Maps the pixel's components and returns a new pixel with the mapped components.
    ///
    /// Alpha is intentionally mapped separately. If no alpha component exists, the alpha function
    /// is ignored.
    #[must_use]
    fn map_subpixels<F, A>(self, f: F, a: A) -> Self
    where
        F: Fn(Self::Subpixel) -> Self::Subpixel,
        A: Fn(Self::Subpixel) -> Self::Subpixel;

    /// Creates this pixel from the given color type, bit depth, and data. This may require a lossy
    /// conversion.
    ///
    /// # Errors
    /// * If the color type is not supported by the pixel type.
    /// * An error occurs when trying to convert the data to the pixel type.
    fn from_raw_parts(color_type: ColorType, bit_depth: u8, data: &[u8]) -> Result<Self> {
        Self::from_raw_parts_paletted::<NoOp>(color_type, bit_depth, data, None)
    }

    /// Creates this pixel from the given color type, bit depth, data, and possibly a color palette.
    /// This may require a lossy xonversion.
    ///
    /// A palette should be supplied if the color type is paletted, else `None`.
    ///
    /// # Errors
    /// * If the color type is not supported by the pixel type.
    /// * An error occurs when trying to convert the data to the pixel type.
    #[allow(unused_variables)]
    fn from_raw_parts_paletted<P: Pixel>(
        color_type: ColorType,
        bit_depth: u8,
        data: &[u8],
        palette: Option<&[P]>,
    ) -> Result<Self> {
        if color_type != Self::COLOR_TYPE {
            return Err(UnsupportedColorType);
        }
        if bit_depth != Self::BIT_DEPTH {
            return Err(UnsupportedColorType);
        }
        Ok(Self::from_bytes(data))
    }

    // noinspection RsConstantConditionIf
    /// Creates this pixel from the given palette and index, but the conversion is done at runtime.
    ///
    /// # Errors
    /// * The pixel index is invalid/out of bounds.
    /// * If the color type is not supported by the pixel type.
    /// * An error occurs when trying to convert the data to the pixel type.
    fn from_arbitrary_palette<P: Pixel>(palette: &[P], index: usize) -> Result<Self> {
        let pixel = palette.get(index).ok_or(InvalidPaletteIndex)?;

        if P::SEALED && P::COLOR_TYPE == ColorType::Dynamic {
            // SAFETY: upheld by the `Sealed` trait
            Ok(Self::from_dynamic(unsafe { *(pixel as *const P).cast() }))
        } else {
            Self::from_raw_parts(P::COLOR_TYPE, P::BIT_DEPTH, pixel.as_bytes().as_ref())
        }
    }

    /// Creates this pixel from a raw bytes. This is used internally and is unchecked - it panics
    /// if the data is not of the correct length.
    fn from_bytes(bytes: &[u8]) -> Self;

    /// Turns this pixel into bytes.
    fn as_bytes(&self) -> Self::Data;

    /// Merges this pixel with the given overlay pixel, taking into account alpha.
    #[must_use]
    fn merge(self, other: Self) -> Self {
        other
    }

    /// Overlays this pixel with the given overlay pixel, abiding by the given overlay mode.
    #[must_use]
    fn overlay(self, other: Self, mode: OverlayMode) -> Self {
        match mode {
            OverlayMode::Replace => other,
            OverlayMode::Merge => self.merge(other),
        }
    }

    /// Merges this pixel with the given overlay pixel, where the alpha of the overlay pixel is
    /// known. This is used in anti-aliasing.
    #[must_use]
    fn merge_with_alpha(self, other: Self, alpha: u8) -> Self;

    /// Overlays this pixel with the given overlay pixel, abiding by the given overlay mode with
    /// the given alpha.
    ///
    /// This is used in anti-aliasing.
    #[must_use]
    fn overlay_with_alpha(self, other: Self, mode: OverlayMode, alpha: u8) -> Self {
        match mode {
            OverlayMode::Replace => other,
            OverlayMode::Merge => self.merge_with_alpha(other, alpha),
        }
    }

    /// Creates this pixel from any dynamic pixel, dynamically at runtime. Different from the
    /// From/Into traits.
    #[allow(unused_variables)]
    #[must_use]
    fn from_dynamic(dynamic: Dynamic) -> Self {
        panic!("cannot convert from dynamic pixel for this pixel type");
    }

    /// Returns this pixel as RGB despite its type. This can panic on some pixel types, you must
    /// be sure this pixel is able to be converted into RGB before using this.
    ///
    /// You should use [`Rgb::from`] or ensure that the pixel is [`TrueColor`], as they are safer
    /// methods, checked at compile time. This is primarily used for internal purposes, for example when an encoder
    /// can guarantee that a pixel is convertable into RGB.
    ///
    /// # Panics
    /// * If the pixel is not convertable into RGB.
    fn as_rgb(&self) -> Rgb;

    /// Returns this pixel as RGBA despite its type. This can panic on some pixel types, you must
    /// be sure this pixel is able to be converted into RGBA before using this.
    ///
    /// You should use [`Rgba::from`] or ensure that the pixel is [`TrueColor`], as they are safer
    /// methods, checked at compile time. This is primarily used for internal purposes, for example
    /// when an encoder can guarantee that a pixel is convertable into RGBA.
    ///
    /// # Panics
    /// * If the pixel is not convertable into RGBA.
    fn as_rgba(&self) -> Rgba;
}

/// Represents a pixel that supports alpha, or transparency values.
pub trait Alpha: Pixel {
    /// Returns the alpha, or opacity level of the pixel.
    ///
    /// This is a value between 0 and 255.
    /// 0 is completely transparent, and 255 is completely opaque.
    #[must_use]
    fn alpha(&self) -> u8;

    /// Clones this pixel with the given alpha value.
    #[must_use]
    fn with_alpha(self, alpha: u8) -> Self;
}

/// Represents a pixel that can be modulated, i.e. transformed in hue, saturation, and brightness.
pub trait Modulate: Pixel {
    /// Modulates this pixel with the given hue, saturation, and brightness values.
    #[must_use]
    fn modulate(self, hue: f64, saturation: f64, brightness: f64) -> Self;
}

/// A pixel type that does and stores nothing. This pixel type is useless and will behave weirdly
/// with your code. This is usually only used for internal or polyfill purposes.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct NoOp;

/// Extension of [`NoOp`], used for internal purposes only. This is a ZST that implements
/// `Into<u8>`.
#[derive(Copy, Clone)]
pub struct NoOpSubpixel;

impl From<NoOpSubpixel> for usize {
    fn from(_: NoOpSubpixel) -> Self {
        0
    }
}

impl Pixel for NoOp {
    const COLOR_TYPE: ColorType = ColorType::L;
    const BIT_DEPTH: u8 = 0;

    type Subpixel = NoOpSubpixel;
    type Color = Self;
    type Data = [u8; 0];

    fn map_subpixels<F, A>(self, _f: F, _a: A) -> Self
    where
        F: Fn(Self::Subpixel) -> Self::Subpixel,
        A: Fn(Self::Subpixel) -> Self::Subpixel,
    {
        Self
    }

    fn from_bytes(_bytes: &[u8]) -> Self {
        Self
    }

    fn as_bytes(&self) -> Self::Data {
        []
    }

    fn merge_with_alpha(self, _other: Self, _alpha: u8) -> Self {
        Self
    }

    fn from_dynamic(_dynamic: Dynamic) -> Self {
        Self
    }

    fn as_rgb(&self) -> Rgb {
        panic!("NoOp is a private pixel type and should not be used")
    }

    fn as_rgba(&self) -> Rgba {
        panic!("NoOp is a private pixel type and should not be used")
    }
}

impl Not for NoOp {
    type Output = Self;

    fn not(self) -> Self::Output {
        Self
    }
}

impl Alpha for NoOp {
    fn alpha(&self) -> u8 {
        255
    }

    fn with_alpha(self, _alpha: u8) -> Self {
        Self
    }
}

impl TrueColor for NoOp {
    fn as_rgb_tuple(&self) -> (u8, u8, u8) {
        (0, 0, 0)
    }

    fn as_rgba_tuple(&self) -> (u8, u8, u8, u8) {
        (0, 0, 0, 0)
    }

    fn from_rgb_tuple(_: (u8, u8, u8)) -> Self {
        Self
    }

    fn from_rgba_tuple(_: (u8, u8, u8, u8)) -> Self {
        Self
    }

    fn into_rgb(self) -> Rgb {
        Rgb::default()
    }

    fn into_rgba(self) -> Rgba {
        Rgba::default()
    }
}

macro_rules! propagate_palette {
    ($p:expr, $data:expr) => {{
        if let Some(palette) = $p {
            return Self::from_arbitrary_palette(palette, $data[0] as usize);
        }
    }};
}

/// Represents a single-bit pixel that represents either a pixel that is on or off.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct BitPixel(
    /// Whether the pixel is on.
    pub bool,
);

impl BitPixel {
    /// Returns a new `BitPixel` with the given value.
    #[must_use]
    pub const fn new(value: bool) -> Self {
        Self(value)
    }

    /// Returns the value of the pixel.
    #[must_use]
    pub const fn value(&self) -> bool {
        self.0
    }

    /// Returns a new `BitPixel` that is on.
    #[must_use]
    pub const fn on() -> Self {
        Self(true)
    }

    /// Returns a new `BitPixel` that is off.
    #[must_use]
    pub const fn off() -> Self {
        Self(false)
    }
}

macro_rules! force_into_impl {
    () => {
        fn as_rgb(&self) -> Rgb {
            (*self).into()
        }

        fn as_rgba(&self) -> Rgba {
            (*self).into()
        }
    };
}

impl Pixel for BitPixel {
    const COLOR_TYPE: ColorType = ColorType::L;
    const BIT_DEPTH: u8 = 1;

    type Subpixel = bool;
    type Color = Self;
    type Data = [u8; 1];

    fn map_subpixels<F, A>(self, f: F, _: A) -> Self
    where
        F: Fn(Self::Subpixel) -> Self::Subpixel,
        A: Fn(Self::Subpixel) -> Self::Subpixel,
    {
        Self(f(self.0))
    }

    fn from_raw_parts_paletted<P: Pixel>(
        color_type: ColorType,
        bit_depth: u8,
        data: &[u8],
        palette: Option<&[P]>,
    ) -> Result<Self> {
        propagate_palette!(palette, data);
        // Before, this supported L, however this implicit conversion is not supported anymore
        // as the result will be completely different
        match (color_type, bit_depth, data.is_empty()) {
            (_, 1, false) => Ok(Self(data[0] != 0)),
            _ => Err(UnsupportedColorType),
        }
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        Self(bytes[0] > 127)
    }

    fn as_bytes(&self) -> Self::Data {
        [if self.0 { 255 } else { 0 }]
    }

    fn merge_with_alpha(self, other: Self, alpha: u8) -> Self {
        if alpha < 128 {
            self
        } else {
            other
        }
    }

    fn from_dynamic(dynamic: Dynamic) -> Self {
        match dynamic {
            Dynamic::BitPixel(value) => value,
            Dynamic::L(value) => value.into(),
            Dynamic::Rgb(value) => value.into(),
            Dynamic::Rgba(value) => value.into(),
        }
    }

    force_into_impl!();
}

impl Not for BitPixel {
    type Output = Self;

    fn not(self) -> Self::Output {
        Self(!self.0)
    }
}

macro_rules! scale_subpixels {
    ($src_depth:expr, $target_depth:expr, $data:expr) => {{
        if $src_depth == $target_depth {
            Cow::from($data)
        } else {
            if !$src_depth.is_power_of_two() {
                return Err(DecodingError(format!(
                    "source depth {} is not a power of two",
                    $src_depth
                )));
            }
            debug_assert!(
                $target_depth.is_power_of_two(),
                "target depth {} is not a power of two",
                $target_depth,
            );

            if $src_depth <= 8 && $target_depth <= 8 {
                Cow::from(if $src_depth < $target_depth {
                    let scale = $target_depth / $src_depth;
                    $data.iter().map(|n| *n * scale).collect::<Vec<_>>()
                } else {
                    let scale = $src_depth / $target_depth;
                    $data.iter().map(|n| *n / scale).collect::<Vec<_>>()
                })
            } else if $src_depth < $target_depth {
                let scale = $target_depth as usize / $src_depth as usize;
                let mut result = Vec::with_capacity($data.len() * scale);

                for n in $data {
                    result.extend((*n as usize * scale).to_be_bytes());
                }

                Cow::from(result)
            } else {
                let scale = $src_depth as usize / $target_depth as usize;
                let mut result = Vec::with_capacity($data.len() / scale);

                for chunk in $data.chunks_exact(scale) {
                    let sum = chunk
                        .iter()
                        .rev()
                        .enumerate()
                        .map(|(i, &x)| (x as usize) << (8 * i))
                        .sum::<usize>();
                    result.push((sum / scale) as u8);
                }

                Cow::from(result)
            }
        }
    }};
}

macro_rules! propagate_data {
    ($data:expr, $expected:expr) => {{
        if $data.len() < $expected {
            return Err(DecodingError(format!(
                "malformed pixel data for {}: expected at least {} component(s) but received {}",
                std::any::type_name::<Self>(),
                $expected,
                $data.len(),
            )));
        }
    }};
    ($data:expr) => {{
        propagate_data!($data, Self::COLOR_TYPE.channels());
    }};
}

/// Represents an L, or luminance pixel that is stored as only one single
/// number representing how bright, or intense, the pixel is.
///
/// This can be thought of as the "unit channel" as this represents only
/// a single channel in which other pixel types can be composed of.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct L(
    /// The luminance value of the pixel, between 0 and 255.
    pub u8,
);

impl Pixel for L {
    const COLOR_TYPE: ColorType = ColorType::L;
    const BIT_DEPTH: u8 = 8;

    type Subpixel = u8;
    type Color = Self;
    type Data = [u8; 1];

    fn map_subpixels<F, A>(self, f: F, _: A) -> Self
    where
        F: Fn(Self::Subpixel) -> Self::Subpixel,
        A: Fn(Self::Subpixel) -> Self::Subpixel,
    {
        Self(f(self.0))
    }

    fn from_raw_parts_paletted<P: Pixel>(
        color_type: ColorType,
        bit_depth: u8,
        data: &[u8],
        palette: Option<&[P]>,
    ) -> Result<Self> {
        propagate_palette!(palette, data);

        let data = scale_subpixels!(bit_depth, Self::BIT_DEPTH, data);
        propagate_data!(data);

        match color_type {
            // Currently, losing alpha implicitly is allowed, but I may change my mind about this
            // in the future.
            ColorType::L | ColorType::LA => Ok(Self(data[0])),
            _ => Err(UnsupportedColorType),
        }
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        Self(bytes[0])
    }

    fn as_bytes(&self) -> Self::Data {
        [self.0]
    }

    #[allow(clippy::cast_lossless)]
    fn merge_with_alpha(self, other: Self, alpha: u8) -> Self {
        let alpha = alpha as f32 / 255.;
        let base_l = self.0 as f32 / 255.;
        let overlay_l = other.0 as f32 / 255.;

        let a_diff = 1. - alpha;
        let a = a_diff.mul_add(255., alpha);
        let l = (a_diff * 255.).mul_add(base_l, alpha * overlay_l) / a;

        Self((l * 255.) as u8)
    }

    fn from_dynamic(dynamic: Dynamic) -> Self {
        match dynamic {
            Dynamic::L(value) => value,
            Dynamic::BitPixel(value) => value.into(),
            Dynamic::Rgb(value) => value.into(),
            Dynamic::Rgba(value) => value.into(),
        }
    }

    force_into_impl!();
}

impl Not for L {
    type Output = Self;

    fn not(self) -> Self::Output {
        Self(!self.0)
    }
}

impl L {
    /// Creates a new L pixel with the given luminance value.
    #[must_use]
    pub const fn new(l: u8) -> Self {
        Self(l)
    }

    /// Returns the luminance value of the pixel.
    #[must_use]
    pub const fn value(&self) -> u8 {
        self.0
    }
}

/// Represents an RGB pixel.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Rgb {
    /// The red component of the pixel.
    pub r: u8,
    /// The green component of the pixel.
    pub g: u8,
    /// The blue component of the pixel.
    pub b: u8,
}

impl Pixel for Rgb {
    const COLOR_TYPE: ColorType = ColorType::Rgb;
    const BIT_DEPTH: u8 = 8;

    type Subpixel = u8;
    type Color = Self;
    type Data = [u8; 3];

    fn map_subpixels<F, A>(self, f: F, _: A) -> Self
    where
        F: Fn(Self::Subpixel) -> Self::Subpixel,
        A: Fn(Self::Subpixel) -> Self::Subpixel,
    {
        Self {
            r: f(self.r),
            g: f(self.g),
            b: f(self.b),
        }
    }

    fn from_raw_parts_paletted<P: Pixel>(
        color_type: ColorType,
        bit_depth: u8,
        data: &[u8],
        palette: Option<&[P]>,
    ) -> Result<Self> {
        propagate_palette!(palette, data);
        let data = scale_subpixels!(bit_depth, Self::BIT_DEPTH, data);

        match color_type {
            ColorType::Rgb | ColorType::Rgba => {
                propagate_data!(data, 3);
                Ok(Self {
                    r: data[0],
                    g: data[1],
                    b: data[2],
                })
            }
            ColorType::L | ColorType::LA => {
                propagate_data!(data, 1);
                Ok(Self {
                    r: data[0],
                    g: data[0],
                    b: data[0],
                })
            }
            _ => Err(UnsupportedColorType),
        }
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        Self {
            r: bytes[0],
            g: bytes[1],
            b: bytes[2],
        }
    }

    fn as_bytes(&self) -> Self::Data {
        [self.r, self.g, self.b]
    }

    fn merge_with_alpha(self, other: Self, alpha: u8) -> Self {
        Rgba::from_rgb(self)
            .merge_with_alpha(Rgba::from_rgb(other), alpha)
            .into()
    }

    fn from_dynamic(dynamic: Dynamic) -> Self {
        match dynamic {
            Dynamic::Rgb(value) => value,
            Dynamic::Rgba(value) => value.into(),
            Dynamic::BitPixel(value) => value.into(),
            Dynamic::L(value) => value.into(),
        }
    }

    force_into_impl!();
}

impl Not for Rgb {
    type Output = Self;

    #[allow(clippy::borrow_as_ptr, clippy::cast_ptr_alignment, clippy::ptr_as_ptr)]
    fn not(self) -> Self::Output {
        // SAFETY:
        //   * `(self, 0)` ensures we can cast to `u32` without UB
        //   * this function is intended to simply invert all 24 bits of the pixel,
        //     which is exactly what this does
        unsafe { *(&(!*(&(self, 0u8) as *const _ as *const u32)) as *const _ as *const Self) }
    }
}

impl Rgb {
    /// Creates a new RGB pixel.
    #[must_use]
    pub const fn new(r: u8, g: u8, b: u8) -> Self {
        Self { r, g, b }
    }

    /// Parses an RGB pixel from a hex value.
    ///
    /// The hex value can be in one of the following formats:
    /// - RRGGBB
    /// - RGB
    ///
    /// These can be optionally padded with #, for example "#FF0000" is the same as as "FF0000".
    ///
    /// # Errors
    /// * Received a malformed hex code.
    pub fn from_hex(hex: impl AsRef<str>) -> Result<Self> {
        let hex = hex.as_ref();

        // Strip # from the hex code
        let hex = hex.strip_prefix('#').unwrap_or(hex);

        // Expand the hex code to 6 characters
        //
        // We can use .len() instead of .chars().count() since it's both faster
        // performance-wise and also because characters of a hex-string will never
        // take up more than one byte.
        let hex = if hex.len() == 3 {
            let mut expanded = String::with_capacity(6);

            for c in hex.chars() {
                expanded.push(c);
                expanded.push(c);
            }

            expanded
        } else if hex.len() != 6 {
            return Err(InvalidHexCode(hex.to_string()));
        } else {
            hex.to_string()
        };

        let err = |_| InvalidHexCode(hex.to_string());

        Ok(Self {
            r: u8::from_str_radix(&hex[0..2], 16).map_err(err)?,
            g: u8::from_str_radix(&hex[2..4], 16).map_err(err)?,
            b: u8::from_str_radix(&hex[4..6], 16).map_err(err)?,
        })
    }

    /// Creates a completely black pixel.
    #[must_use]
    pub const fn black() -> Self {
        Self::new(0, 0, 0)
    }

    /// Creates a completely white pixel.
    #[must_use]
    pub const fn white() -> Self {
        Self::new(255, 255, 255)
    }
}

/// Represents an RGBA pixel.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Rgba {
    /// The red component of the pixel.
    pub r: u8,
    /// The green component of the pixel.
    pub g: u8,
    /// The blue component of the pixel.
    pub b: u8,
    /// The alpha component of the pixel.
    pub a: u8,
}

impl Pixel for Rgba {
    const COLOR_TYPE: ColorType = ColorType::Rgba;
    const BIT_DEPTH: u8 = 8;

    type Subpixel = u8;
    type Color = Self;
    type Data = [u8; 4];

    fn map_subpixels<F, A>(self, f: F, a: A) -> Self
    where
        F: Fn(Self::Subpixel) -> Self::Subpixel,
        A: Fn(Self::Subpixel) -> Self::Subpixel,
    {
        Self {
            r: f(self.r),
            g: f(self.g),
            b: f(self.b),
            a: a(self.a),
        }
    }

    fn from_raw_parts_paletted<P: Pixel>(
        color_type: ColorType,
        bit_depth: u8,
        data: &[u8],
        palette: Option<&[P]>,
    ) -> Result<Self> {
        propagate_palette!(palette, data);
        let data = scale_subpixels!(bit_depth, Self::BIT_DEPTH, data);

        match color_type {
            ColorType::Rgb => {
                propagate_data!(data, 3);
                Ok(Self {
                    r: data[0],
                    g: data[1],
                    b: data[2],
                    a: 255,
                })
            }
            ColorType::Rgba => {
                propagate_data!(data, 4);
                Ok(Self {
                    r: data[0],
                    g: data[1],
                    b: data[2],
                    a: data[3],
                })
            }
            ColorType::L => {
                propagate_data!(data, 1);
                Ok(Self {
                    r: data[0],
                    g: data[0],
                    b: data[0],
                    a: 255,
                })
            }
            ColorType::LA => {
                propagate_data!(data, 2);
                Ok(Self {
                    r: data[0],
                    g: data[0],
                    b: data[0],
                    a: data[1],
                })
            }
            _ => Err(UnsupportedColorType),
        }
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        Self {
            r: bytes[0],
            g: bytes[1],
            b: bytes[2],
            a: bytes[3],
        }
    }

    fn as_bytes(&self) -> Self::Data {
        [self.r, self.g, self.b, self.a]
    }

    // TODO: SIMD could speed this up significantly
    #[allow(clippy::cast_lossless)]
    fn merge(self, other: Self) -> Self {
        // Optimize for common cases
        if other.a == 255 {
            return other;
        } else if other.a == 0 {
            return self;
        }

        let (base_r, base_g, base_b, base_a) = (
            self.r as f32 / 255.,
            self.g as f32 / 255.,
            self.b as f32 / 255.,
            self.a as f32 / 255.,
        );

        let (overlay_r, overlay_g, overlay_b, overlay_a) = (
            other.r as f32 / 255.,
            other.g as f32 / 255.,
            other.b as f32 / 255.,
            other.a as f32 / 255.,
        );

        let a_diff = 1. - overlay_a;
        let a = a_diff.mul_add(base_a, overlay_a);

        let a_ratio = a_diff * base_a;
        let r = a_ratio.mul_add(base_r, overlay_a * overlay_r) / a;
        let g = a_ratio.mul_add(base_g, overlay_a * overlay_g) / a;
        let b = a_ratio.mul_add(base_b, overlay_a * overlay_b) / a;

        Self {
            r: (r * 255.) as u8,
            g: (g * 255.) as u8,
            b: (b * 255.) as u8,
            a: (a * 255.) as u8,
        }
    }

    #[allow(clippy::cast_lossless)]
    fn merge_with_alpha(self, other: Self, alpha: u8) -> Self {
        self.merge(other.with_alpha((other.a as f32 * (alpha as f32 / 255.)) as u8))
    }

    fn overlay_with_alpha(self, other: Self, mode: OverlayMode, alpha: u8) -> Self {
        match mode {
            OverlayMode::Replace => other.with_alpha(alpha),
            OverlayMode::Merge => self.merge_with_alpha(other, alpha),
        }
    }

    fn from_dynamic(dynamic: Dynamic) -> Self {
        match dynamic {
            Dynamic::Rgba(value) => value,
            Dynamic::Rgb(value) => value.into(),
            Dynamic::L(value) => value.into(),
            Dynamic::BitPixel(value) => value.into(),
        }
    }

    force_into_impl!();
}

impl Alpha for Rgba {
    fn alpha(&self) -> u8 {
        self.a
    }

    fn with_alpha(mut self, alpha: u8) -> Self {
        self.a = alpha;
        self
    }
}

impl Rgba {
    /// Creates a new RGBA pixel.
    #[must_use]
    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }

    /// Creates an opaque pixel from an RGB pixel.
    #[must_use]
    pub const fn from_rgb(Rgb { r, g, b }: Rgb) -> Self {
        Self::new(r, g, b, 255)
    }

    /// Parses an RGBA pixel from a hex value.
    ///
    /// The hex value can be in one of the following formats:
    /// - RRGGBBAA
    /// - RRGGBB
    /// - RGBA
    /// - RGB
    ///
    /// These can be optionally padded with #, for example "#FF0000" is the same as as "FF0000".
    ///
    /// # Errors
    /// * Received a malformed hex code.
    pub fn from_hex(hex: &str) -> Result<Self> {
        let hex = hex.strip_prefix('#').unwrap_or(hex);

        match hex.len() {
            3 | 6 => Rgb::from_hex(hex).map(Self::from_rgb),
            len @ (4 | 8) => {
                let hex = if len == 4 {
                    let mut expanded = String::with_capacity(8);

                    for c in hex.chars() {
                        expanded.push(c);
                        expanded.push(c);
                    }

                    expanded
                } else {
                    hex.to_string()
                };

                let err = |_| InvalidHexCode(hex.to_string());

                Ok(Self {
                    r: u8::from_str_radix(&hex[0..2], 16).map_err(err)?,
                    g: u8::from_str_radix(&hex[2..4], 16).map_err(err)?,
                    b: u8::from_str_radix(&hex[4..6], 16).map_err(err)?,
                    a: u8::from_str_radix(&hex[6..8], 16).map_err(err)?,
                })
            }
            _ => Err(InvalidHexCode(hex.to_string())),
        }
    }

    /// Creates a completely transparent pixel.
    #[must_use]
    pub const fn transparent() -> Self {
        Self::new(0, 0, 0, 0)
    }

    /// Creates an opaque black pixel.
    #[must_use]
    pub const fn black() -> Self {
        Self::new(0, 0, 0, 255)
    }

    /// Creates an opaque white pixel.
    #[must_use]
    pub const fn white() -> Self {
        Self::new(255, 255, 255, 255)
    }
}

impl Not for Rgba {
    type Output = Self;

    fn not(self) -> Self::Output {
        Self {
            r: !self.r,
            g: !self.g,
            b: !self.b,
            a: !self.a,
        }
    }
}

/// Represents a subpixel of a dynamic pixel.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DynamicSubpixel {
    /// A u8 subpixel.
    U8(u8),
    /// A boolean subpixel.
    Bool(bool),
}

macro_rules! impl_num_op {
    ($err:literal; $self:expr, $other:expr; $a:ident, $b:ident; $out:expr) => {{
        match ($self, $other) {
            (DynamicSubpixel::U8($a), DynamicSubpixel::U8($b)) => DynamicSubpixel::U8($out),
            (DynamicSubpixel::Bool(_), DynamicSubpixel::Bool(_)) => panic!(
                "cannot {} DynamicPixel boolean variants. You should try converting to a \
                    concrete pixel type so these runtime panics are not triggered.",
                $err,
            ),
            _ => panic!(
                "cannot {} different or incompatible DynamicSubpixel variants. You should \
                    try converting to a concrete pixel type so these runtime panics are not \
                    triggered.",
                $err,
            ),
        }
    }};
}

impl std::ops::Add for DynamicSubpixel {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        impl_num_op!("add"; self, other; a, b; a + b)
    }
}

impl std::ops::AddAssign for DynamicSubpixel {
    fn add_assign(&mut self, other: Self) {
        *self = *self + other;
    }
}

impl std::ops::Sub for DynamicSubpixel {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        impl_num_op!("subtract"; self, other; a, b; a - b)
    }
}

impl std::ops::SubAssign for DynamicSubpixel {
    fn sub_assign(&mut self, other: Self) {
        *self = *self - other;
    }
}

impl std::ops::Mul for DynamicSubpixel {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        impl_num_op!("multiply"; self, other; a, b; a * b)
    }
}

impl std::ops::MulAssign for DynamicSubpixel {
    fn mul_assign(&mut self, other: Self) {
        *self = *self * other;
    }
}

impl std::ops::Div for DynamicSubpixel {
    type Output = Self;

    fn div(self, other: Self) -> Self {
        impl_num_op!("divide"; self, other; a, b; a / b)
    }
}

impl std::ops::DivAssign for DynamicSubpixel {
    fn div_assign(&mut self, other: Self) {
        *self = *self / other;
    }
}

impl std::ops::Rem for DynamicSubpixel {
    type Output = Self;
    fn rem(self, other: Self) -> Self {
        impl_num_op!("remainder"; self, other; a, b; a % b)
    }
}

impl std::ops::RemAssign for DynamicSubpixel {
    fn rem_assign(&mut self, other: Self) {
        *self = *self % other;
    }
}

impl num_traits::SaturatingAdd for DynamicSubpixel {
    fn saturating_add(&self, v: &Self) -> Self {
        impl_num_op!("saturating_add"; self, v; a, b; a.saturating_add(b))
    }
}

impl num_traits::SaturatingSub for DynamicSubpixel {
    fn saturating_sub(&self, v: &Self) -> Self {
        impl_num_op!("saturating_sub"; self, v; a, b; a.saturating_sub(b))
    }
}

impl num_traits::SaturatingMul for DynamicSubpixel {
    fn saturating_mul(&self, v: &Self) -> Self {
        impl_num_op!("saturating_mul"; self, v; a, b; a.saturating_mul(b))
    }
}

impl From<DynamicSubpixel> for usize {
    fn from(v: DynamicSubpixel) -> Self {
        match v {
            DynamicSubpixel::U8(v) => v.into(),
            DynamicSubpixel::Bool(v) => v.into(),
        }
    }
}

/// Represents a pixel type that is dynamically resolved.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Dynamic {
    BitPixel(BitPixel),
    L(L),
    Rgb(Rgb),
    Rgba(Rgba),
}

impl Default for Dynamic {
    fn default() -> Self {
        panic!(
            "Dynamic pixel type must be known, try using a concrete pixel type instead so these \
                runtime panics are not triggered."
        );
    }
}

impl Pixel for Dynamic {
    const COLOR_TYPE: ColorType = ColorType::Dynamic;
    const BIT_DEPTH: u8 = 8;

    type Subpixel = DynamicSubpixel;
    type Color = Self;
    type Data = Vec<u8>;

    fn color_type(&self) -> ColorType {
        match self {
            Self::BitPixel(_) | Self::L(_) => ColorType::L,
            Self::Rgb(_) => ColorType::Rgb,
            Self::Rgba(_) => ColorType::Rgba,
        }
    }

    // noinspection ALL
    fn map_subpixels<F, A>(self, f: F, a: A) -> Self
    where
        F: Fn(Self::Subpixel) -> Self::Subpixel,
        A: Fn(Self::Subpixel) -> Self::Subpixel,
    {
        macro_rules! subpixel {
            ($pixel:expr, $variant:ident) => {{
                ($pixel).map_subpixels(
                    |pixel| match f(DynamicSubpixel::$variant(pixel)) {
                        DynamicSubpixel::$variant(pixel) => pixel,
                        _ => panic!("dynamic subpixel map returned something different"),
                    },
                    |alpha| match a(DynamicSubpixel::$variant(alpha)) {
                        DynamicSubpixel::$variant(alpha) => alpha,
                        _ => panic!("dynamic subpixel map returned something different"),
                    },
                )
            }};
        }

        match self {
            Self::BitPixel(pixel) => Self::BitPixel(subpixel!(pixel, Bool)),
            Self::L(pixel) => Self::L(subpixel!(pixel, U8)),
            Self::Rgb(pixel) => Self::Rgb(subpixel!(pixel, U8)),
            Self::Rgba(pixel) => Self::Rgba(subpixel!(pixel, U8)),
        }
    }

    fn from_raw_parts_paletted<P: Pixel>(
        color_type: ColorType,
        bit_depth: u8,
        data: &[u8],
        palette: Option<&[P]>,
    ) -> Result<Self> {
        propagate_palette!(palette, data);

        Ok(if bit_depth == 1 {
            propagate_data!(data, 1);
            Self::BitPixel(BitPixel(data[0] != 0))
        } else {
            let data = scale_subpixels!(bit_depth, Self::BIT_DEPTH, data);

            match color_type {
                ColorType::L | ColorType::LA => {
                    propagate_data!(data, 1);
                    Self::L(L(data[0]))
                }
                ColorType::Rgb => {
                    propagate_data!(data, 3);
                    Self::Rgb(Rgb {
                        r: data[0],
                        g: data[1],
                        b: data[2],
                    })
                }
                ColorType::Rgba => {
                    propagate_data!(data, 4);
                    Self::Rgba(Rgba {
                        r: data[0],
                        g: data[1],
                        b: data[2],
                        a: data[3],
                    })
                }
                _ => return Err(UnsupportedColorType),
            }
        })
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        match bytes.len() {
            1 => Self::L(Pixel::from_bytes(bytes)),
            3 => Self::Rgb(Pixel::from_bytes(bytes)),
            4 => Self::Rgba(Pixel::from_bytes(bytes)),
            _ => panic!("Invalid pixel data length"),
        }
    }

    fn as_bytes(&self) -> Self::Data {
        match self {
            Self::BitPixel(pixel) => pixel.as_bytes().to_vec(),
            Self::L(pixel) => pixel.as_bytes().to_vec(),
            Self::Rgb(pixel) => pixel.as_bytes().to_vec(),
            Self::Rgba(pixel) => pixel.as_bytes().to_vec(),
        }
    }

    fn merge_with_alpha(self, other: Self, alpha: u8) -> Self {
        match (self, other) {
            (Self::BitPixel(pixel), Self::BitPixel(other)) => {
                Self::BitPixel(pixel.merge_with_alpha(other, alpha))
            }
            (Self::L(pixel), Self::L(other)) => Self::L(pixel.merge_with_alpha(other, alpha)),
            (Self::Rgb(pixel), Self::Rgb(other)) => Self::Rgb(pixel.merge_with_alpha(other, alpha)),
            (Self::Rgba(pixel), Self::Rgba(other)) => {
                Self::Rgba(pixel.merge_with_alpha(other, alpha))
            }
            _ => panic!("Cannot overlay two foreign pixel types"),
        }
    }

    fn from_dynamic(dynamic: Dynamic) -> Self {
        dynamic
    }

    force_into_impl!();
}

impl Not for Dynamic {
    type Output = Self;

    fn not(self) -> Self::Output {
        match self {
            Self::BitPixel(pixel) => Self::BitPixel(!pixel),
            Self::L(pixel) => Self::L(!pixel),
            Self::Rgb(pixel) => Self::Rgb(!pixel),
            Self::Rgba(pixel) => Self::Rgba(!pixel),
        }
    }
}

impl Alpha for Dynamic {
    fn alpha(&self) -> u8 {
        match self {
            Self::Rgba(pixel) => pixel.alpha(),
            _ => 255,
        }
    }

    fn with_alpha(self, alpha: u8) -> Self {
        match self {
            Self::Rgba(pixel) => Self::Rgba(pixel.with_alpha(alpha)),
            pixel => pixel,
        }
    }
}

impl Dynamic {
    /// Creates a new dynamic pixel...dynamically, from a concrete pixel.
    ///
    /// # Errors
    /// * The pixel type is not supported.
    pub fn from_pixel<P: Pixel>(pixel: P) -> Result<Self> {
        Self::from_raw_parts(pixel.color_type(), P::BIT_DEPTH, pixel.as_bytes().as_ref())
    }
}

macro_rules! impl_dynamic {
    ($($t:ident),+) => {
        $(
            impl From<Dynamic> for $t {
                fn from(pixel: Dynamic) -> Self {
                    match pixel {
                        Dynamic::BitPixel(pixel) => pixel.into(),
                        Dynamic::L(pixel) => pixel.into(),
                        Dynamic::Rgb(pixel) => pixel.into(),
                        Dynamic::Rgba(pixel) => pixel.into(),
                    }
                }
            }

            impl From<$t> for Dynamic {
                fn from(pixel: $t) -> Self {
                    Dynamic::$t(pixel)
                }
            }
        )+
    };
}

impl_dynamic!(BitPixel, L, Rgb, Rgba);

impl From<Rgb> for BitPixel {
    fn from(rgb: Rgb) -> Self {
        Self(rgb.luminance() > 127)
    }
}

impl From<Rgba> for BitPixel {
    fn from(rgba: Rgba) -> Self {
        Self(rgba.luminance() > 127)
    }
}

macro_rules! impl_from_bitpixel {
    ($($t:ident),+) => {
        $(
            impl From<BitPixel> for $t {
                fn from(pixel: BitPixel) -> Self {
                    if pixel.value() {
                        <$t>::white()
                    } else {
                        <$t>::black()
                    }
                }
            }
        )+
    };
}

impl_from_bitpixel!(Rgb, Rgba);

impl From<BitPixel> for L {
    fn from(bit: BitPixel) -> Self {
        Self(if bit.value() { 255 } else { 0 })
    }
}

impl From<L> for BitPixel {
    fn from(l: L) -> Self {
        Self(l.value() > 127)
    }
}

impl From<Rgb> for L {
    fn from(Rgb { r, g, b }: Rgb) -> Self {
        #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
        Self(f32::from(b).mul_add(0.114, f32::from(r).mul_add(0.299, f32::from(g) * 0.587)) as u8)
    }
}

impl From<Rgba> for L {
    fn from(rgba: Rgba) -> Self {
        Self(Rgb::from(rgba).luminance())
    }
}

impl From<L> for Rgb {
    fn from(L(l): L) -> Self {
        Self { r: l, g: l, b: l }
    }
}

impl From<L> for Rgba {
    fn from(L(l): L) -> Self {
        Self {
            r: l,
            g: l,
            b: l,
            a: 255,
        }
    }
}

impl From<Rgba> for Rgb {
    fn from(Rgba { r, g, b, .. }: Rgba) -> Self {
        Self { r, g, b }
    }
}

impl From<Rgb> for Rgba {
    fn from(Rgb { r, g, b }: Rgb) -> Self {
        Self { r, g, b, a: 255 }
    }
}

/// A trait representing all pixels that can be safely represented as either RGB or RGBA true color.
pub trait TrueColor: Pixel {
    /// Returns the pixel as an (r, g, b) tuple.
    fn as_rgb_tuple(&self) -> (u8, u8, u8);

    /// Returns the pixel as an (r, g, b, a) tuple.
    fn as_rgba_tuple(&self) -> (u8, u8, u8, u8);

    /// Creates a new pixel from an (r, g, b) tuple.
    fn from_rgb_tuple(rgb: (u8, u8, u8)) -> Self;

    /// Creates a new pixel from an (r, g, b, a) tuple.
    fn from_rgba_tuple(rgba: (u8, u8, u8, u8)) -> Self;

    /// Returns the pixel casted into an Rgb pixel.
    fn into_rgb(self) -> Rgb;

    /// Returns the pixel casted into an Rgba pixel.
    fn into_rgba(self) -> Rgba;
}

#[allow(clippy::trait_duplication_in_bounds)]
impl<P: Pixel + Copy + From<Rgb> + From<Rgba> + Into<Rgb> + Into<Rgba>> TrueColor for P {
    fn as_rgb_tuple(&self) -> (u8, u8, u8) {
        let Rgb { r, g, b } = (*self).into();

        (r, g, b)
    }

    fn as_rgba_tuple(&self) -> (u8, u8, u8, u8) {
        let Rgba { r, g, b, a } = (*self).into();

        (r, g, b, a)
    }

    fn from_rgb_tuple((r, g, b): (u8, u8, u8)) -> Self {
        From::<Rgb>::from(Rgb { r, g, b })
    }

    fn from_rgba_tuple((r, g, b, a): (u8, u8, u8, u8)) -> Self {
        From::<Rgba>::from(Rgba { r, g, b, a })
    }

    fn into_rgb(self) -> Rgb {
        self.into()
    }

    fn into_rgba(self) -> Rgba {
        self.into()
    }
}

#[allow(dead_code)]
pub(crate) unsafe fn assume_pixel_from_palette<'p, P, Index: Into<usize>>(
    palette: &'p [P::Color],
    index: Index,
) -> Result<P>
where
    P: 'p + Pixel,
{
    macro_rules! unsafe_cast {
        ($t:ty => $out:ty) => {{
            let length = palette.len();
            let ptr = palette.as_ptr().cast::<$t>();
            // SAFETY: upheld by the caller
            let palette = std::slice::from_raw_parts(ptr, length);

            // SAFETY: mostly upheld by the caller, but transmute_copy can be used since all Pixels
            // implement Copy.
            Ok(std::mem::transmute_copy(&<$out>::from_palette(
                palette,
                index.into() as u8,
            )))
        }};
    }

    match P::COLOR_TYPE {
        ColorType::PaletteRgb => unsafe_cast!(Rgb => PalettedRgb),
        ColorType::PaletteRgba => unsafe_cast!(Rgba => PalettedRgba),
        _ => P::from_arbitrary_palette(palette, index.into()),
    }
}

/// A trait representing a paletted pixel. [`Pixel::Subpixel`] is the type of the palette index.
///
/// The generic lifetime parameter `'p` represents the lifetime of a palette the type will hold a
/// reference to.
pub trait Paletted<'p>: Pixel
where
    Self: 'p,
{
    /// Creates this pixel from the given palette and index. For unpaletted pixels, use
    /// [`Pixel::from_arbitrary_palette`] instead.
    ///
    /// # Errors
    /// * The pixel index is invalid/out of bounds.
    /// * If the color type is not supported by the pixel type.
    /// * An error occurs when trying to convert the data to the pixel type.
    fn from_palette(palette: &'p [Self::Color], index: Self::Subpixel) -> Self;

    /// Returns the palette lookup as a slice.
    fn palette(&self) -> &'p [Self::Color];

    /// Returns the index in the palette this pixel is of.
    fn palette_index(&self) -> Self::Subpixel;

    /// Resolves the color of the pixel. Because invalid palette values are supposed to be
    /// propagated prior to calling this, this will panic
    // TODO: this could potentially just use an index to avoid the expect
    fn color(&self) -> Self::Color {
        *self
            .palette()
            .get(self.palette_index().into())
            .expect("invalid palette index")
    }

    /// Resolves the color of the pixel. Invalid palette values *should* be propagated prior to
    /// to calling this, but it isn't guaranteed, for example if the palette pixel was manually
    /// initialized.
    ///
    /// This results in undefined behavior if the palette index is invalid.
    ///
    /// # Safety
    /// * The palette index must be valid.
    unsafe fn color_unchecked(&self) -> Self::Color {
        *self.palette().get_unchecked(self.palette_index().into())
    }
}

macro_rules! impl_palette_default {
    ($($t:ty),+) => {
        $(
            impl Default for $t {
                fn default() -> Self {
                    panic!("cannot use default for paletted pixel");
                }
            }
        )+
    }
}

macro_rules! try_palette {
    ($self:ident, $action:literal, $filter:expr) => {{
        Self {
            index: $self.palette().iter().position($filter).unwrap_or_else(|| {
                panic!(
                    "could not find a color in the palette with the same value once {}, \
                     try converting this pixel or image to a true color format first. paletted \
                     pixels can only transform to other colors in the same palette.",
                    $action,
                )
            }) as u8,
            palette: $self.palette,
        }
    }};
}

macro_rules! panic_unpaletted {
    () => {{
        panic!(
            "currently, pixels are resolved independent from other pixels, meaning that RIL \
                cannot quantize non-paletted pixels into a palette, since it must be aware of all \
                other pixels in the image. Consider manually quantizing the image, or using a \
                non-paletted pixel format, such as RGBA, instead - RIL can automatically flatten \
                paletted images into true color images, but not the opposite.",
        )
    }};
}

macro_rules! impl_palette_cast {
    ($t:ty: $($f:ty)+) => {
        $(
            impl From<$t> for $f {
                fn from(pixel: $t) -> Self {
                    pixel.color().into()
                }
            }
        )+
    };
}

// Suffixed with an 8 to indicate that it's an 8-bit palette
macro_rules! impl_palette8 {
    ($name:ident: $color_type:ident $cast:ident $tgt:ty) => {
        #[derive(Copy, Clone, PartialEq, Eq, Hash)]
        #[doc = concat!(
            "Represents a paletted pixel, holding an index to a palette of ",
            stringify!($tgt),
            " colors represented as a `&'p [",
            stringify!($tgt),
            "]`, where `'p` is the lifetime of the palette.",
        )]
        pub struct $name<'p> {
            pub index: u8,
            palette: &'p [$tgt],
        }

        impl fmt::Debug for $name<'_> {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                f.debug_struct(stringify!($name))
                    .field("index", &self.index)
                    .finish()
            }
        }

        impl_palette_default!($name<'_>);

        impl Pixel for $name<'_> {
            const COLOR_TYPE: ColorType = ColorType::$color_type;
            const BIT_DEPTH: u8 = 8;

            type Subpixel = u8;
            type Color = $tgt;
            type Data = [u8; 1];

            fn map_subpixels<F, A>(self, f: F, a: A) -> Self
            where
                F: Fn(Self::Subpixel) -> Self::Subpixel,
                A: Fn(Self::Subpixel) -> Self::Subpixel,
            {
                let target = &self.color().map_subpixels(f, a);

                try_palette!(self, "mapped", |color| color == target)
            }

            fn from_raw_parts_paletted<P: Pixel>(
                _color_type: ColorType,
                _bit_depth: u8,
                _data: &[u8],
                _palette: Option<&[P]>,
            ) -> Result<Self> {
                panic_unpaletted!()
            }

            fn from_bytes(_bytes: &[u8]) -> Self {
                panic!("cannot initialize a paletted pixel without being aware of its palette")
            }

            fn as_bytes(&self) -> Self::Data {
                [self.index]
            }

            fn merge_with_alpha(self, other: Self, alpha: u8) -> Self {
                let target = &self.color().merge_with_alpha(other.color(), alpha);

                try_palette!(self, "merged", |color| color == target)
            }

            fn from_dynamic(_dynamic: Dynamic) -> Self {
                todo!("implement dynamic palettes")
            }

            force_into_impl!();
        }

        impl<'p> Paletted<'p> for $name<'p> {
            fn from_palette(palette: &'p [Self::Color], index: Self::Subpixel) -> Self {
                Self {
                    index: usize::from(index) as u8,
                    palette,
                }
            }

            fn palette(&self) -> &'p [Self::Color] {
                self.palette
            }

            fn palette_index(&self) -> u8 {
                self.index
            }
        }

        impl<'p> Not for $name<'p> {
            type Output = Self;

            fn not(self) -> Self::Output {
                let target = &!self.color();

                try_palette!(self, "inverted", |color| color == target)
            }
        }

        impl_palette_cast!($name<'_>: Rgb Rgba L BitPixel Dynamic);
    }
}

impl_palette8!(PalettedRgb: PaletteRgb into_rgb Rgb);
impl_palette8!(PalettedRgba: PaletteRgba into_rgba Rgba);