moxcms 0.8.1

Simple Color Management in 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
/*
 * // Copyright (c) Radzivon Bartoshyk 2/2025. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
use crate::chad::BRADFORD_D;
use crate::cicp::{
    CicpColorPrimaries, ColorPrimaries, MatrixCoefficients, TransferCharacteristics,
};
use crate::dat::ColorDateTime;
use crate::err::CmsError;
use crate::matrix::{Matrix3f, Xyz};
use crate::reader::s15_fixed16_number_to_float;
use crate::safe_math::{SafeAdd, SafeMul};
use crate::tag::{TAG_SIZE, Tag};
use crate::trc::ToneReprCurve;
use crate::{Chromaticity, Layout, Matrix3d, Vector3d, XyY, Xyzd, adapt_to_d50_d};
use std::io::Read;

const MAX_PROFILE_SIZE: usize = 1024 * 1024 * 10; // 10 MB max, for Fogra39 etc

#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProfileSignature {
    Acsp,
}

impl TryFrom<u32> for ProfileSignature {
    type Error = CmsError;
    #[inline]
    fn try_from(value: u32) -> Result<Self, Self::Error> {
        if value == u32::from_ne_bytes(*b"acsp").to_be() {
            return Ok(ProfileSignature::Acsp);
        }
        Err(CmsError::InvalidProfile)
    }
}

impl From<ProfileSignature> for u32 {
    #[inline]
    fn from(value: ProfileSignature) -> Self {
        match value {
            ProfileSignature::Acsp => u32::from_ne_bytes(*b"acsp").to_be(),
        }
    }
}

#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Ord, PartialOrd)]
pub enum ProfileVersion {
    V2_0 = 0x02000000,
    V2_1 = 0x02100000,
    V2_2 = 0x02200000,
    V2_3 = 0x02300000,
    V2_4 = 0x02400000,
    V4_0 = 0x04000000,
    V4_1 = 0x04100000,
    V4_2 = 0x04200000,
    V4_3 = 0x04300000,
    #[default]
    V4_4 = 0x04400000,
    Unknown,
}

impl TryFrom<u32> for ProfileVersion {
    type Error = CmsError;
    fn try_from(value: u32) -> Result<Self, Self::Error> {
        // First try exact match for known versions
        match value {
            0x02000000 => return Ok(ProfileVersion::V2_0),
            0x02100000 => return Ok(ProfileVersion::V2_1),
            0x02200000 => return Ok(ProfileVersion::V2_2),
            0x02300000 => return Ok(ProfileVersion::V2_3),
            0x02400000 => return Ok(ProfileVersion::V2_4),
            0x04000000 => return Ok(ProfileVersion::V4_0),
            0x04100000 => return Ok(ProfileVersion::V4_1),
            0x04200000 => return Ok(ProfileVersion::V4_2),
            0x04300000 => return Ok(ProfileVersion::V4_3),
            0x04400000 => return Ok(ProfileVersion::V4_4),
            _ => {}
        }

        // Extract major version (first byte) for range matching
        // ICC version format: major.minor.bugfix.zero in bytes [0][1][2][3]
        let major = (value >> 24) & 0xFF;
        let minor = (value >> 20) & 0x0F;

        // Accept profiles with patch versions (e.g., v2.0.2, v3.4, v4.2.9)
        // but reject invalid versions (v0.x) and unsupported versions (v5.x+ / ICC MAX)
        match major {
            0 => {
                // Version 0.x is invalid - reject
                Err(CmsError::InvalidProfile)
            }
            2 => {
                // v2.x - map to the appropriate v2 minor version or highest known
                match minor {
                    0 => Ok(ProfileVersion::V2_0),
                    1 => Ok(ProfileVersion::V2_1),
                    2 => Ok(ProfileVersion::V2_2),
                    3 => Ok(ProfileVersion::V2_3),
                    _ => Ok(ProfileVersion::V2_4), // Higher minor versions -> v2.4
                }
            }
            3 => {
                // v3.x (rare but exists) - treat as v2.4 (functionally similar)
                Ok(ProfileVersion::V2_4)
            }
            4 => {
                // v4.x - map to the appropriate v4 minor version or highest known
                match minor {
                    0 => Ok(ProfileVersion::V4_0),
                    1 => Ok(ProfileVersion::V4_1),
                    2 => Ok(ProfileVersion::V4_2),
                    3 => Ok(ProfileVersion::V4_3),
                    _ => Ok(ProfileVersion::V4_4), // Higher minor versions -> v4.4
                }
            }
            _ => {
                // v5.x+ (ICC MAX) and other unknown versions - reject
                // ICC MAX has different white point requirements and would produce wrong colors
                Err(CmsError::InvalidProfile)
            }
        }
    }
}

impl From<ProfileVersion> for u32 {
    fn from(value: ProfileVersion) -> Self {
        match value {
            ProfileVersion::V2_0 => 0x02000000,
            ProfileVersion::V2_1 => 0x02100000,
            ProfileVersion::V2_2 => 0x02200000,
            ProfileVersion::V2_3 => 0x02300000,
            ProfileVersion::V2_4 => 0x02400000,
            ProfileVersion::V4_0 => 0x04000000,
            ProfileVersion::V4_1 => 0x04100000,
            ProfileVersion::V4_2 => 0x04200000,
            ProfileVersion::V4_3 => 0x04300000,
            ProfileVersion::V4_4 => 0x04400000,
            ProfileVersion::Unknown => 0x02000000,
        }
    }
}

#[repr(u32)]
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Default, Hash)]
pub enum DataColorSpace {
    #[default]
    Xyz,
    Lab,
    Luv,
    YCbr,
    Yxy,
    Rgb,
    Gray,
    Hsv,
    Hls,
    Cmyk,
    Cmy,
    Color2,
    Color3,
    Color4,
    Color5,
    Color6,
    Color7,
    Color8,
    Color9,
    Color10,
    Color11,
    Color12,
    Color13,
    Color14,
    Color15,
}

impl DataColorSpace {
    #[inline]
    pub fn check_layout(self, layout: Layout) -> Result<(), CmsError> {
        let unsupported: bool = match self {
            DataColorSpace::Xyz => layout != Layout::Rgb,
            DataColorSpace::Lab => layout != Layout::Rgb && layout != Layout::Rgba,
            DataColorSpace::Luv => layout != Layout::Rgb,
            DataColorSpace::YCbr => layout != Layout::Rgb,
            DataColorSpace::Yxy => layout != Layout::Rgb,
            DataColorSpace::Rgb => layout != Layout::Rgb && layout != Layout::Rgba,
            DataColorSpace::Gray => layout != Layout::Gray && layout != Layout::GrayAlpha,
            DataColorSpace::Hsv => layout != Layout::Rgb,
            DataColorSpace::Hls => layout != Layout::Rgb,
            DataColorSpace::Cmyk => layout != Layout::Rgba,
            DataColorSpace::Cmy => layout != Layout::Rgb,
            DataColorSpace::Color2 => layout != Layout::GrayAlpha,
            DataColorSpace::Color3 => layout != Layout::Rgb,
            DataColorSpace::Color4 => layout != Layout::Rgba,
            DataColorSpace::Color5 => layout != Layout::Inks5,
            DataColorSpace::Color6 => layout != Layout::Inks6,
            DataColorSpace::Color7 => layout != Layout::Inks7,
            DataColorSpace::Color8 => layout != Layout::Inks8,
            DataColorSpace::Color9 => layout != Layout::Inks9,
            DataColorSpace::Color10 => layout != Layout::Inks10,
            DataColorSpace::Color11 => layout != Layout::Inks11,
            DataColorSpace::Color12 => layout != Layout::Inks12,
            DataColorSpace::Color13 => layout != Layout::Inks13,
            DataColorSpace::Color14 => layout != Layout::Inks14,
            DataColorSpace::Color15 => layout != Layout::Inks15,
        };
        if unsupported {
            Err(CmsError::InvalidLayout)
        } else {
            Ok(())
        }
    }

    pub(crate) fn is_three_channels(self) -> bool {
        matches!(
            self,
            DataColorSpace::Xyz
                | DataColorSpace::Lab
                | DataColorSpace::Luv
                | DataColorSpace::YCbr
                | DataColorSpace::Yxy
                | DataColorSpace::Rgb
                | DataColorSpace::Hsv
                | DataColorSpace::Hls
                | DataColorSpace::Cmy
                | DataColorSpace::Color3
        )
    }
}

#[repr(u32)]
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Default)]
pub enum ProfileClass {
    InputDevice,
    #[default]
    DisplayDevice,
    OutputDevice,
    DeviceLink,
    ColorSpace,
    Abstract,
    Named,
}

impl TryFrom<u32> for ProfileClass {
    type Error = CmsError;
    fn try_from(value: u32) -> Result<Self, Self::Error> {
        if value == u32::from_ne_bytes(*b"scnr").to_be() {
            return Ok(ProfileClass::InputDevice);
        } else if value == u32::from_ne_bytes(*b"mntr").to_be() {
            return Ok(ProfileClass::DisplayDevice);
        } else if value == u32::from_ne_bytes(*b"prtr").to_be() {
            return Ok(ProfileClass::OutputDevice);
        } else if value == u32::from_ne_bytes(*b"link").to_be() {
            return Ok(ProfileClass::DeviceLink);
        } else if value == u32::from_ne_bytes(*b"spac").to_be() {
            return Ok(ProfileClass::ColorSpace);
        } else if value == u32::from_ne_bytes(*b"abst").to_be() {
            return Ok(ProfileClass::Abstract);
        } else if value == u32::from_ne_bytes(*b"nmcl").to_be() {
            return Ok(ProfileClass::Named);
        }
        Err(CmsError::InvalidProfile)
    }
}

impl From<ProfileClass> for u32 {
    fn from(val: ProfileClass) -> Self {
        match val {
            ProfileClass::InputDevice => u32::from_ne_bytes(*b"scnr").to_be(),
            ProfileClass::DisplayDevice => u32::from_ne_bytes(*b"mntr").to_be(),
            ProfileClass::OutputDevice => u32::from_ne_bytes(*b"prtr").to_be(),
            ProfileClass::DeviceLink => u32::from_ne_bytes(*b"link").to_be(),
            ProfileClass::ColorSpace => u32::from_ne_bytes(*b"spac").to_be(),
            ProfileClass::Abstract => u32::from_ne_bytes(*b"abst").to_be(),
            ProfileClass::Named => u32::from_ne_bytes(*b"nmcl").to_be(),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum LutStore {
    Store8(Vec<u8>),
    Store16(Vec<u16>),
}

#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum LutType {
    Lut8,
    Lut16,
    LutMab,
    LutMba,
}

impl TryFrom<u32> for LutType {
    type Error = CmsError;
    fn try_from(value: u32) -> Result<Self, Self::Error> {
        if value == u32::from_ne_bytes(*b"mft1").to_be() {
            return Ok(LutType::Lut8);
        } else if value == u32::from_ne_bytes(*b"mft2").to_be() {
            return Ok(LutType::Lut16);
        } else if value == u32::from_ne_bytes(*b"mAB ").to_be() {
            return Ok(LutType::LutMab);
        } else if value == u32::from_ne_bytes(*b"mBA ").to_be() {
            return Ok(LutType::LutMba);
        }
        Err(CmsError::InvalidProfile)
    }
}

impl From<LutType> for u32 {
    fn from(val: LutType) -> Self {
        match val {
            LutType::Lut8 => u32::from_ne_bytes(*b"mft1").to_be(),
            LutType::Lut16 => u32::from_ne_bytes(*b"mft2").to_be(),
            LutType::LutMab => u32::from_ne_bytes(*b"mAB ").to_be(),
            LutType::LutMba => u32::from_ne_bytes(*b"mBA ").to_be(),
        }
    }
}

impl TryFrom<u32> for DataColorSpace {
    type Error = CmsError;
    fn try_from(value: u32) -> Result<Self, Self::Error> {
        if value == u32::from_ne_bytes(*b"XYZ ").to_be() {
            return Ok(DataColorSpace::Xyz);
        } else if value == u32::from_ne_bytes(*b"Lab ").to_be() {
            return Ok(DataColorSpace::Lab);
        } else if value == u32::from_ne_bytes(*b"Luv ").to_be() {
            return Ok(DataColorSpace::Luv);
        } else if value == u32::from_ne_bytes(*b"YCbr").to_be() {
            return Ok(DataColorSpace::YCbr);
        } else if value == u32::from_ne_bytes(*b"Yxy ").to_be() {
            return Ok(DataColorSpace::Yxy);
        } else if value == u32::from_ne_bytes(*b"RGB ").to_be() {
            return Ok(DataColorSpace::Rgb);
        } else if value == u32::from_ne_bytes(*b"GRAY").to_be() {
            return Ok(DataColorSpace::Gray);
        } else if value == u32::from_ne_bytes(*b"HSV ").to_be() {
            return Ok(DataColorSpace::Hsv);
        } else if value == u32::from_ne_bytes(*b"HLS ").to_be() {
            return Ok(DataColorSpace::Hls);
        } else if value == u32::from_ne_bytes(*b"CMYK").to_be() {
            return Ok(DataColorSpace::Cmyk);
        } else if value == u32::from_ne_bytes(*b"CMY ").to_be() {
            return Ok(DataColorSpace::Cmy);
        } else if value == u32::from_ne_bytes(*b"2CLR").to_be() {
            return Ok(DataColorSpace::Color2);
        } else if value == u32::from_ne_bytes(*b"3CLR").to_be() {
            return Ok(DataColorSpace::Color3);
        } else if value == u32::from_ne_bytes(*b"4CLR").to_be() {
            return Ok(DataColorSpace::Color4);
        } else if value == u32::from_ne_bytes(*b"5CLR").to_be() {
            return Ok(DataColorSpace::Color5);
        } else if value == u32::from_ne_bytes(*b"6CLR").to_be() {
            return Ok(DataColorSpace::Color6);
        } else if value == u32::from_ne_bytes(*b"7CLR").to_be() {
            return Ok(DataColorSpace::Color7);
        } else if value == u32::from_ne_bytes(*b"8CLR").to_be() {
            return Ok(DataColorSpace::Color8);
        } else if value == u32::from_ne_bytes(*b"9CLR").to_be() {
            return Ok(DataColorSpace::Color9);
        } else if value == u32::from_ne_bytes(*b"ACLR").to_be() {
            return Ok(DataColorSpace::Color10);
        } else if value == u32::from_ne_bytes(*b"BCLR").to_be() {
            return Ok(DataColorSpace::Color11);
        } else if value == u32::from_ne_bytes(*b"CCLR").to_be() {
            return Ok(DataColorSpace::Color12);
        } else if value == u32::from_ne_bytes(*b"DCLR").to_be() {
            return Ok(DataColorSpace::Color13);
        } else if value == u32::from_ne_bytes(*b"ECLR").to_be() {
            return Ok(DataColorSpace::Color14);
        } else if value == u32::from_ne_bytes(*b"FCLR").to_be() {
            return Ok(DataColorSpace::Color15);
        }
        Err(CmsError::InvalidProfile)
    }
}

impl From<DataColorSpace> for u32 {
    fn from(val: DataColorSpace) -> Self {
        match val {
            DataColorSpace::Xyz => u32::from_ne_bytes(*b"XYZ ").to_be(),
            DataColorSpace::Lab => u32::from_ne_bytes(*b"Lab ").to_be(),
            DataColorSpace::Luv => u32::from_ne_bytes(*b"Luv ").to_be(),
            DataColorSpace::YCbr => u32::from_ne_bytes(*b"YCbr").to_be(),
            DataColorSpace::Yxy => u32::from_ne_bytes(*b"Yxy ").to_be(),
            DataColorSpace::Rgb => u32::from_ne_bytes(*b"RGB ").to_be(),
            DataColorSpace::Gray => u32::from_ne_bytes(*b"GRAY").to_be(),
            DataColorSpace::Hsv => u32::from_ne_bytes(*b"HSV ").to_be(),
            DataColorSpace::Hls => u32::from_ne_bytes(*b"HLS ").to_be(),
            DataColorSpace::Cmyk => u32::from_ne_bytes(*b"CMYK").to_be(),
            DataColorSpace::Cmy => u32::from_ne_bytes(*b"CMY ").to_be(),
            DataColorSpace::Color2 => u32::from_ne_bytes(*b"2CLR").to_be(),
            DataColorSpace::Color3 => u32::from_ne_bytes(*b"3CLR").to_be(),
            DataColorSpace::Color4 => u32::from_ne_bytes(*b"4CLR").to_be(),
            DataColorSpace::Color5 => u32::from_ne_bytes(*b"5CLR").to_be(),
            DataColorSpace::Color6 => u32::from_ne_bytes(*b"6CLR").to_be(),
            DataColorSpace::Color7 => u32::from_ne_bytes(*b"7CLR").to_be(),
            DataColorSpace::Color8 => u32::from_ne_bytes(*b"8CLR").to_be(),
            DataColorSpace::Color9 => u32::from_ne_bytes(*b"9CLR").to_be(),
            DataColorSpace::Color10 => u32::from_ne_bytes(*b"ACLR").to_be(),
            DataColorSpace::Color11 => u32::from_ne_bytes(*b"BCLR").to_be(),
            DataColorSpace::Color12 => u32::from_ne_bytes(*b"CCLR").to_be(),
            DataColorSpace::Color13 => u32::from_ne_bytes(*b"DCLR").to_be(),
            DataColorSpace::Color14 => u32::from_ne_bytes(*b"ECLR").to_be(),
            DataColorSpace::Color15 => u32::from_ne_bytes(*b"FCLR").to_be(),
        }
    }
}

#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
pub enum TechnologySignatures {
    FilmScanner,
    DigitalCamera,
    ReflectiveScanner,
    InkJetPrinter,
    ThermalWaxPrinter,
    ElectrophotographicPrinter,
    ElectrostaticPrinter,
    DyeSublimationPrinter,
    PhotographicPaperPrinter,
    FilmWriter,
    VideoMonitor,
    VideoCamera,
    ProjectionTelevision,
    CathodeRayTubeDisplay,
    PassiveMatrixDisplay,
    ActiveMatrixDisplay,
    LiquidCrystalDisplay,
    OrganicLedDisplay,
    PhotoCd,
    PhotographicImageSetter,
    Gravure,
    OffsetLithography,
    Silkscreen,
    Flexography,
    MotionPictureFilmScanner,
    MotionPictureFilmRecorder,
    DigitalMotionPictureCamera,
    DigitalCinemaProjector,
    Unknown(u32),
}

impl From<u32> for TechnologySignatures {
    fn from(value: u32) -> Self {
        if value == u32::from_ne_bytes(*b"fscn").to_be() {
            return TechnologySignatures::FilmScanner;
        } else if value == u32::from_ne_bytes(*b"dcam").to_be() {
            return TechnologySignatures::DigitalCamera;
        } else if value == u32::from_ne_bytes(*b"rscn").to_be() {
            return TechnologySignatures::ReflectiveScanner;
        } else if value == u32::from_ne_bytes(*b"ijet").to_be() {
            return TechnologySignatures::InkJetPrinter;
        } else if value == u32::from_ne_bytes(*b"twax").to_be() {
            return TechnologySignatures::ThermalWaxPrinter;
        } else if value == u32::from_ne_bytes(*b"epho").to_be() {
            return TechnologySignatures::ElectrophotographicPrinter;
        } else if value == u32::from_ne_bytes(*b"esta").to_be() {
            return TechnologySignatures::ElectrostaticPrinter;
        } else if value == u32::from_ne_bytes(*b"dsub").to_be() {
            return TechnologySignatures::DyeSublimationPrinter;
        } else if value == u32::from_ne_bytes(*b"rpho").to_be() {
            return TechnologySignatures::PhotographicPaperPrinter;
        } else if value == u32::from_ne_bytes(*b"fprn").to_be() {
            return TechnologySignatures::FilmWriter;
        } else if value == u32::from_ne_bytes(*b"vidm").to_be() {
            return TechnologySignatures::VideoMonitor;
        } else if value == u32::from_ne_bytes(*b"vidc").to_be() {
            return TechnologySignatures::VideoCamera;
        } else if value == u32::from_ne_bytes(*b"pjtv").to_be() {
            return TechnologySignatures::ProjectionTelevision;
        } else if value == u32::from_ne_bytes(*b"CRT ").to_be() {
            return TechnologySignatures::CathodeRayTubeDisplay;
        } else if value == u32::from_ne_bytes(*b"PMD ").to_be() {
            return TechnologySignatures::PassiveMatrixDisplay;
        } else if value == u32::from_ne_bytes(*b"AMD ").to_be() {
            return TechnologySignatures::ActiveMatrixDisplay;
        } else if value == u32::from_ne_bytes(*b"LCD ").to_be() {
            return TechnologySignatures::LiquidCrystalDisplay;
        } else if value == u32::from_ne_bytes(*b"OLED").to_be() {
            return TechnologySignatures::OrganicLedDisplay;
        } else if value == u32::from_ne_bytes(*b"KPCD").to_be() {
            return TechnologySignatures::PhotoCd;
        } else if value == u32::from_ne_bytes(*b"imgs").to_be() {
            return TechnologySignatures::PhotographicImageSetter;
        } else if value == u32::from_ne_bytes(*b"grav").to_be() {
            return TechnologySignatures::Gravure;
        } else if value == u32::from_ne_bytes(*b"offs").to_be() {
            return TechnologySignatures::OffsetLithography;
        } else if value == u32::from_ne_bytes(*b"silk").to_be() {
            return TechnologySignatures::Silkscreen;
        } else if value == u32::from_ne_bytes(*b"flex").to_be() {
            return TechnologySignatures::Flexography;
        } else if value == u32::from_ne_bytes(*b"mpfs").to_be() {
            return TechnologySignatures::MotionPictureFilmScanner;
        } else if value == u32::from_ne_bytes(*b"mpfr").to_be() {
            return TechnologySignatures::MotionPictureFilmRecorder;
        } else if value == u32::from_ne_bytes(*b"dmpc").to_be() {
            return TechnologySignatures::DigitalMotionPictureCamera;
        } else if value == u32::from_ne_bytes(*b"dcpj").to_be() {
            return TechnologySignatures::DigitalCinemaProjector;
        }
        TechnologySignatures::Unknown(value)
    }
}

#[derive(Debug, Clone)]
pub enum LutWarehouse {
    Lut(LutDataType),
    Multidimensional(LutMultidimensionalType),
}

impl PartialEq for LutWarehouse {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (LutWarehouse::Lut(a), LutWarehouse::Lut(b)) => a == b,
            (LutWarehouse::Multidimensional(a), LutWarehouse::Multidimensional(b)) => a == b,
            _ => false, // Different variants are not equal
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct LutDataType {
    // used by lut8Type/lut16Type (mft2) only
    pub num_input_channels: u8,
    pub num_output_channels: u8,
    pub num_clut_grid_points: u8,
    pub matrix: Matrix3d,
    pub num_input_table_entries: u16,
    pub num_output_table_entries: u16,
    pub input_table: LutStore,
    pub clut_table: LutStore,
    pub output_table: LutStore,
    pub lut_type: LutType,
}

impl LutDataType {
    pub(crate) fn has_same_kind(&self) -> bool {
        matches!(
            (&self.input_table, &self.clut_table, &self.output_table),
            (
                LutStore::Store8(_),
                LutStore::Store8(_),
                LutStore::Store8(_)
            ) | (
                LutStore::Store16(_),
                LutStore::Store16(_),
                LutStore::Store16(_)
            )
        )
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct LutMultidimensionalType {
    pub num_input_channels: u8,
    pub num_output_channels: u8,
    pub grid_points: [u8; 16],
    pub clut: Option<LutStore>,
    pub a_curves: Vec<ToneReprCurve>,
    pub b_curves: Vec<ToneReprCurve>,
    pub m_curves: Vec<ToneReprCurve>,
    pub matrix: Matrix3d,
    pub bias: Vector3d,
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Default, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum RenderingIntent {
    AbsoluteColorimetric = 3,
    Saturation = 2,
    RelativeColorimetric = 1,
    #[default]
    Perceptual = 0,
}

impl TryFrom<u32> for RenderingIntent {
    type Error = CmsError;

    #[inline]
    fn try_from(value: u32) -> Result<Self, Self::Error> {
        // Rendering intent is a big-endian u32 at bytes 64-67 with valid
        // values 0-3. Non-conforming profiles (e.g. old Linotype "Lino"
        // v2.1 profiles with byte-swapped values) may have invalid values.
        // Default to Perceptual rather than rejecting the entire profile,
        // since this field is advisory — moxcms uses TransformOptions for
        // actual LUT selection.
        match value {
            0 => Ok(RenderingIntent::Perceptual),
            1 => Ok(RenderingIntent::RelativeColorimetric),
            2 => Ok(RenderingIntent::Saturation),
            3 => Ok(RenderingIntent::AbsoluteColorimetric),
            _ => Ok(RenderingIntent::Perceptual),
        }
    }
}

impl From<RenderingIntent> for u32 {
    #[inline]
    fn from(value: RenderingIntent) -> Self {
        match value {
            RenderingIntent::AbsoluteColorimetric => 3,
            RenderingIntent::Saturation => 2,
            RenderingIntent::RelativeColorimetric => 1,
            RenderingIntent::Perceptual => 0,
        }
    }
}

/// ICC Header
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub(crate) struct ProfileHeader {
    pub size: u32,                         // Size of the profile (computed)
    pub cmm_type: u32,                     // Preferred CMM type (ignored)
    pub version: ProfileVersion,           // Version (4.3 or 4.4 if CICP is included)
    pub profile_class: ProfileClass,       // Display device profile
    pub data_color_space: DataColorSpace,  // RGB input color space
    pub pcs: DataColorSpace,               // Profile connection space
    pub creation_date_time: ColorDateTime, // Date and time
    pub signature: ProfileSignature,       // Profile signature
    pub platform: u32,                     // Platform target (ignored)
    pub flags: u32,                        // Flags (not embedded, can be used independently)
    pub device_manufacturer: u32,          // Device manufacturer (ignored)
    pub device_model: u32,                 // Device model (ignored)
    pub device_attributes: [u8; 8],        // Device attributes (ignored)
    pub rendering_intent: RenderingIntent, // Relative colorimetric rendering intent
    pub illuminant: Xyz,                   // D50 standard illuminant X
    pub creator: u32,                      // Profile creator (ignored)
    pub profile_id: [u8; 16],              // Profile id checksum (ignored)
    pub reserved: [u8; 28],                // Reserved (ignored)
    pub tag_count: u32,                    // Technically not part of header, but required
}

impl ProfileHeader {
    #[allow(dead_code)]
    pub(crate) fn new(size: u32) -> Self {
        Self {
            size,
            cmm_type: 0,
            version: ProfileVersion::V4_3,
            profile_class: ProfileClass::DisplayDevice,
            data_color_space: DataColorSpace::Rgb,
            pcs: DataColorSpace::Xyz,
            creation_date_time: ColorDateTime::default(),
            signature: ProfileSignature::Acsp,
            platform: 0,
            flags: 0x00000000,
            device_manufacturer: 0,
            device_model: 0,
            device_attributes: [0; 8],
            rendering_intent: RenderingIntent::Perceptual,
            illuminant: Chromaticity::D50.to_xyz(),
            creator: 0,
            profile_id: [0; 16],
            reserved: [0; 28],
            tag_count: 0,
        }
    }

    /// Creates profile from the buffer
    pub(crate) fn new_from_slice(slice: &[u8]) -> Result<Self, CmsError> {
        if slice.len() < size_of::<ProfileHeader>() {
            return Err(CmsError::InvalidProfile);
        }
        let mut cursor = std::io::Cursor::new(slice);
        let mut buffer = [0u8; size_of::<ProfileHeader>()];
        cursor
            .read_exact(&mut buffer)
            .map_err(|_| CmsError::InvalidProfile)?;

        let header = Self {
            size: u32::from_be_bytes(buffer[0..4].try_into().unwrap()),
            cmm_type: u32::from_be_bytes(buffer[4..8].try_into().unwrap()),
            version: ProfileVersion::try_from(u32::from_be_bytes(
                buffer[8..12].try_into().unwrap(),
            ))?,
            profile_class: ProfileClass::try_from(u32::from_be_bytes(
                buffer[12..16].try_into().unwrap(),
            ))?,
            data_color_space: DataColorSpace::try_from(u32::from_be_bytes(
                buffer[16..20].try_into().unwrap(),
            ))?,
            pcs: DataColorSpace::try_from(u32::from_be_bytes(buffer[20..24].try_into().unwrap()))?,
            creation_date_time: ColorDateTime::new_from_slice(buffer[24..36].try_into().unwrap())?,
            signature: ProfileSignature::try_from(u32::from_be_bytes(
                buffer[36..40].try_into().unwrap(),
            ))?,
            platform: u32::from_be_bytes(buffer[40..44].try_into().unwrap()),
            flags: u32::from_be_bytes(buffer[44..48].try_into().unwrap()),
            device_manufacturer: u32::from_be_bytes(buffer[48..52].try_into().unwrap()),
            device_model: u32::from_be_bytes(buffer[52..56].try_into().unwrap()),
            device_attributes: buffer[56..64].try_into().unwrap(),
            rendering_intent: RenderingIntent::try_from(u32::from_be_bytes(
                buffer[64..68].try_into().unwrap(),
            ))?,
            illuminant: Xyz::new(
                s15_fixed16_number_to_float(i32::from_be_bytes(buffer[68..72].try_into().unwrap())),
                s15_fixed16_number_to_float(i32::from_be_bytes(buffer[72..76].try_into().unwrap())),
                s15_fixed16_number_to_float(i32::from_be_bytes(buffer[76..80].try_into().unwrap())),
            ),
            creator: u32::from_be_bytes(buffer[80..84].try_into().unwrap()),
            profile_id: buffer[84..100].try_into().unwrap(),
            reserved: buffer[100..128].try_into().unwrap(),
            tag_count: u32::from_be_bytes(buffer[128..132].try_into().unwrap()),
        };
        Ok(header)
    }
}

/// A [Coding Independent Code Point](https://en.wikipedia.org/wiki/Coding-independent_code_points).
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct CicpProfile {
    pub color_primaries: CicpColorPrimaries,
    pub transfer_characteristics: TransferCharacteristics,
    pub matrix_coefficients: MatrixCoefficients,
    pub full_range: bool,
}

#[derive(Debug, Clone)]
pub struct LocalizableString {
    /// An ISO 639-1 value is expected; any text w. more than two symbols will be truncated
    pub language: String,
    /// An ISO 3166-1 value is expected; any text w. more than two symbols will be truncated
    pub country: String,
    pub value: String,
}

impl LocalizableString {
    /// Creates new localizable string
    ///
    /// # Arguments
    ///
    /// * `language`: an ISO 639-1 value is expected, any text more than 2 symbols will be truncated
    /// * `country`: an ISO 3166-1 value is expected, any text more than 2 symbols will be truncated
    /// * `value`: String value
    ///
    pub fn new(language: String, country: String, value: String) -> Self {
        Self {
            language,
            country,
            value,
        }
    }
}

#[derive(Debug, Clone)]
pub struct DescriptionString {
    pub ascii_string: String,
    pub unicode_language_code: u32,
    pub unicode_string: String,
    pub script_code_code: i8,
    pub mac_string: String,
}

#[derive(Debug, Clone)]
pub enum ProfileText {
    PlainString(String),
    Localizable(Vec<LocalizableString>),
    Description(DescriptionString),
}

impl ProfileText {
    pub(crate) fn has_values(&self) -> bool {
        match self {
            ProfileText::PlainString(_) => true,
            ProfileText::Localizable(lc) => !lc.is_empty(),
            ProfileText::Description(_) => true,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum StandardObserver {
    D50,
    D65,
    Unknown,
}

impl From<u32> for StandardObserver {
    fn from(value: u32) -> Self {
        if value == 1 {
            return StandardObserver::D50;
        } else if value == 2 {
            return StandardObserver::D65;
        }
        StandardObserver::Unknown
    }
}

impl From<StandardObserver> for u32 {
    fn from(value: StandardObserver) -> Self {
        match value {
            StandardObserver::D50 => 1,
            StandardObserver::D65 => 2,
            StandardObserver::Unknown => 0,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct ViewingConditions {
    pub illuminant: Xyz,
    pub surround: Xyz,
    pub observer: StandardObserver,
}

#[derive(Debug, Clone, Copy)]
pub enum MeasurementGeometry {
    Unknown,
    /// 0°:45° or 45°:0°
    D45to45,
    /// 0°:d or d:0°
    D0to0,
}

impl From<u32> for MeasurementGeometry {
    fn from(value: u32) -> Self {
        if value == 1 {
            Self::D45to45
        } else if value == 2 {
            Self::D0to0
        } else {
            Self::Unknown
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum StandardIlluminant {
    Unknown,
    D50,
    D65,
    D93,
    F2,
    D55,
    A,
    EquiPower,
    F8,
}

impl From<u32> for StandardIlluminant {
    fn from(value: u32) -> Self {
        match value {
            1 => StandardIlluminant::D50,
            2 => StandardIlluminant::D65,
            3 => StandardIlluminant::D93,
            4 => StandardIlluminant::F2,
            5 => StandardIlluminant::D55,
            6 => StandardIlluminant::A,
            7 => StandardIlluminant::EquiPower,
            8 => StandardIlluminant::F8,
            _ => Self::Unknown,
        }
    }
}

impl From<StandardIlluminant> for u32 {
    fn from(value: StandardIlluminant) -> Self {
        match value {
            StandardIlluminant::Unknown => 0u32,
            StandardIlluminant::D50 => 1u32,
            StandardIlluminant::D65 => 2u32,
            StandardIlluminant::D93 => 3,
            StandardIlluminant::F2 => 4,
            StandardIlluminant::D55 => 5,
            StandardIlluminant::A => 6,
            StandardIlluminant::EquiPower => 7,
            StandardIlluminant::F8 => 8,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Measurement {
    pub observer: StandardObserver,
    pub backing: Xyz,
    pub geometry: MeasurementGeometry,
    pub flare: f32,
    pub illuminant: StandardIlluminant,
}

/// ICC Profile representation
#[repr(C)]
#[derive(Debug, Clone, Default)]
pub struct ColorProfile {
    pub pcs: DataColorSpace,
    pub color_space: DataColorSpace,
    pub profile_class: ProfileClass,
    pub rendering_intent: RenderingIntent,
    pub red_colorant: Xyzd,
    pub green_colorant: Xyzd,
    pub blue_colorant: Xyzd,
    pub white_point: Xyzd,
    pub black_point: Option<Xyzd>,
    pub media_white_point: Option<Xyzd>,
    pub luminance: Option<Xyzd>,
    pub measurement: Option<Measurement>,
    pub red_trc: Option<ToneReprCurve>,
    pub green_trc: Option<ToneReprCurve>,
    pub blue_trc: Option<ToneReprCurve>,
    pub gray_trc: Option<ToneReprCurve>,
    pub cicp: Option<CicpProfile>,
    pub chromatic_adaptation: Option<Matrix3d>,
    pub lut_a_to_b_perceptual: Option<LutWarehouse>,
    pub lut_a_to_b_colorimetric: Option<LutWarehouse>,
    pub lut_a_to_b_saturation: Option<LutWarehouse>,
    pub lut_b_to_a_perceptual: Option<LutWarehouse>,
    pub lut_b_to_a_colorimetric: Option<LutWarehouse>,
    pub lut_b_to_a_saturation: Option<LutWarehouse>,
    pub gamut: Option<LutWarehouse>,
    pub copyright: Option<ProfileText>,
    pub description: Option<ProfileText>,
    pub device_manufacturer: Option<ProfileText>,
    pub device_model: Option<ProfileText>,
    pub char_target: Option<ProfileText>,
    pub viewing_conditions: Option<ViewingConditions>,
    pub viewing_conditions_description: Option<ProfileText>,
    pub technology: Option<TechnologySignatures>,
    pub calibration_date: Option<ColorDateTime>,
    pub creation_date_time: ColorDateTime,
    /// Version for internal and viewing purposes only.
    /// On encoding this is computable property which will set at least V4.
    pub(crate) version_internal: ProfileVersion,
}

#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Hash)]
pub struct ParsingOptions {
    // Maximum allowed profile size in bytes
    pub max_profile_size: usize,
    // Maximum allowed CLUT size in bytes
    pub max_allowed_clut_size: usize,
    // Maximum allowed TRC size in elements count
    pub max_allowed_trc_size: usize,
}

impl Default for ParsingOptions {
    fn default() -> Self {
        Self {
            max_profile_size: MAX_PROFILE_SIZE,
            max_allowed_clut_size: 10_000_000,
            max_allowed_trc_size: 40_000,
        }
    }
}

impl ColorProfile {
    /// Returns profile version
    pub fn version(&self) -> ProfileVersion {
        self.version_internal
    }

    pub fn new_from_slice(slice: &[u8]) -> Result<Self, CmsError> {
        Self::new_from_slice_with_options(slice, Default::default())
    }

    pub fn new_from_slice_with_options(
        slice: &[u8],
        options: ParsingOptions,
    ) -> Result<Self, CmsError> {
        let header = ProfileHeader::new_from_slice(slice)?;
        let tags_count = header.tag_count as usize;
        if slice.len() >= options.max_profile_size {
            return Err(CmsError::InvalidProfile);
        }
        let tags_end = tags_count
            .safe_mul(TAG_SIZE)?
            .safe_add(size_of::<ProfileHeader>())?;
        if slice.len() < tags_end {
            return Err(CmsError::InvalidProfile);
        }
        let tags_slice = &slice[size_of::<ProfileHeader>()..tags_end];
        let mut profile = ColorProfile {
            rendering_intent: header.rendering_intent,
            pcs: header.pcs,
            profile_class: header.profile_class,
            color_space: header.data_color_space,
            white_point: header.illuminant.to_xyzd(),
            version_internal: header.version,
            creation_date_time: header.creation_date_time,
            ..Default::default()
        };
        let color_space = profile.color_space;
        for tag in tags_slice.chunks_exact(TAG_SIZE) {
            let tag_value = u32::from_be_bytes([tag[0], tag[1], tag[2], tag[3]]);
            let tag_entry = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]);
            let tag_size = u32::from_be_bytes([tag[8], tag[9], tag[10], tag[11]]) as usize;
            // Just ignore unknown tags
            if let Ok(tag) = Tag::try_from(tag_value) {
                match tag {
                    Tag::RedXyz => {
                        if color_space == DataColorSpace::Rgb {
                            profile.red_colorant =
                                Self::read_xyz_tag(slice, tag_entry as usize, tag_size)?;
                        }
                    }
                    Tag::GreenXyz => {
                        if color_space == DataColorSpace::Rgb {
                            profile.green_colorant =
                                Self::read_xyz_tag(slice, tag_entry as usize, tag_size)?;
                        }
                    }
                    Tag::BlueXyz => {
                        if color_space == DataColorSpace::Rgb {
                            profile.blue_colorant =
                                Self::read_xyz_tag(slice, tag_entry as usize, tag_size)?;
                        }
                    }
                    Tag::RedToneReproduction => {
                        if color_space == DataColorSpace::Rgb {
                            profile.red_trc = Self::read_trc_tag_s(
                                slice,
                                tag_entry as usize,
                                tag_size,
                                &options,
                            )?;
                        }
                    }
                    Tag::GreenToneReproduction => {
                        if color_space == DataColorSpace::Rgb {
                            profile.green_trc = Self::read_trc_tag_s(
                                slice,
                                tag_entry as usize,
                                tag_size,
                                &options,
                            )?;
                        }
                    }
                    Tag::BlueToneReproduction => {
                        if color_space == DataColorSpace::Rgb {
                            profile.blue_trc = Self::read_trc_tag_s(
                                slice,
                                tag_entry as usize,
                                tag_size,
                                &options,
                            )?;
                        }
                    }
                    Tag::GreyToneReproduction => {
                        if color_space == DataColorSpace::Gray {
                            profile.gray_trc = Self::read_trc_tag_s(
                                slice,
                                tag_entry as usize,
                                tag_size,
                                &options,
                            )?;
                        }
                    }
                    Tag::MediaWhitePoint => {
                        profile.media_white_point =
                            Self::read_xyz_tag(slice, tag_entry as usize, tag_size).map(Some)?;
                    }
                    Tag::Luminance => {
                        profile.luminance =
                            Self::read_xyz_tag(slice, tag_entry as usize, tag_size).map(Some)?;
                    }
                    Tag::Measurement => {
                        profile.measurement =
                            Self::read_meas_tag(slice, tag_entry as usize, tag_size)?;
                    }
                    Tag::CodeIndependentPoints => {
                        // This tag may be present when the data colour space in the profile header is RGB, YCbCr, or XYZ, and the
                        // profile class in the profile header is Input or Display. The tag shall not be present for other data colour spaces
                        // or profile classes indicated in the profile header.
                        if (profile.profile_class == ProfileClass::InputDevice
                            || profile.profile_class == ProfileClass::DisplayDevice)
                            && (profile.color_space == DataColorSpace::Rgb
                                || profile.color_space == DataColorSpace::YCbr
                                || profile.color_space == DataColorSpace::Xyz)
                        {
                            profile.cicp =
                                Self::read_cicp_tag(slice, tag_entry as usize, tag_size)?;
                        }
                    }
                    Tag::ChromaticAdaptation => {
                        profile.chromatic_adaptation =
                            Self::read_chad_tag(slice, tag_entry as usize, tag_size)?;
                    }
                    Tag::BlackPoint => {
                        profile.black_point =
                            Self::read_xyz_tag(slice, tag_entry as usize, tag_size).map(Some)?
                    }
                    Tag::DeviceToPcsLutPerceptual => {
                        profile.lut_a_to_b_perceptual =
                            Self::read_lut_tag(slice, tag_entry, tag_size, &options)?;
                    }
                    Tag::DeviceToPcsLutColorimetric => {
                        profile.lut_a_to_b_colorimetric =
                            Self::read_lut_tag(slice, tag_entry, tag_size, &options)?;
                    }
                    Tag::DeviceToPcsLutSaturation => {
                        profile.lut_a_to_b_saturation =
                            Self::read_lut_tag(slice, tag_entry, tag_size, &options)?;
                    }
                    Tag::PcsToDeviceLutPerceptual => {
                        profile.lut_b_to_a_perceptual =
                            Self::read_lut_tag(slice, tag_entry, tag_size, &options)?;
                    }
                    Tag::PcsToDeviceLutColorimetric => {
                        profile.lut_b_to_a_colorimetric =
                            Self::read_lut_tag(slice, tag_entry, tag_size, &options)?;
                    }
                    Tag::PcsToDeviceLutSaturation => {
                        profile.lut_b_to_a_saturation =
                            Self::read_lut_tag(slice, tag_entry, tag_size, &options)?;
                    }
                    Tag::Gamut => {
                        profile.gamut = Self::read_lut_tag(slice, tag_entry, tag_size, &options)?;
                    }
                    Tag::Copyright => {
                        profile.copyright =
                            Self::read_string_tag(slice, tag_entry as usize, tag_size)?;
                    }
                    Tag::ProfileDescription => {
                        profile.description =
                            Self::read_string_tag(slice, tag_entry as usize, tag_size)?;
                    }
                    Tag::ViewingConditionsDescription => {
                        profile.viewing_conditions_description =
                            Self::read_string_tag(slice, tag_entry as usize, tag_size)?;
                    }
                    Tag::DeviceModel => {
                        profile.device_model =
                            Self::read_string_tag(slice, tag_entry as usize, tag_size)?;
                    }
                    Tag::DeviceManufacturer => {
                        profile.device_manufacturer =
                            Self::read_string_tag(slice, tag_entry as usize, tag_size)?;
                    }
                    Tag::CharTarget => {
                        profile.char_target =
                            Self::read_string_tag(slice, tag_entry as usize, tag_size)?;
                    }
                    Tag::Chromaticity => {}
                    Tag::ObserverConditions => {
                        profile.viewing_conditions =
                            Self::read_viewing_conditions(slice, tag_entry as usize, tag_size)?;
                    }
                    Tag::Technology => {
                        profile.technology =
                            Self::read_tech_tag(slice, tag_entry as usize, tag_size)?;
                    }
                    Tag::CalibrationDateTime => {
                        profile.calibration_date =
                            Self::read_date_time_tag(slice, tag_entry as usize, tag_size)?;
                    }
                }
            }
        }

        Ok(profile)
    }
}

impl ColorProfile {
    #[inline]
    pub fn colorant_matrix(&self) -> Matrix3d {
        Matrix3d {
            v: [
                [
                    self.red_colorant.x,
                    self.green_colorant.x,
                    self.blue_colorant.x,
                ],
                [
                    self.red_colorant.y,
                    self.green_colorant.y,
                    self.blue_colorant.y,
                ],
                [
                    self.red_colorant.z,
                    self.green_colorant.z,
                    self.blue_colorant.z,
                ],
            ],
        }
    }

    /// Computes colorants matrix. Returns not transposed matrix.
    ///
    /// To work on `const` context this method does have restrictions.
    /// If invalid values were provided it may return invalid matrix or NaNs.
    pub const fn colorants_matrix(white_point: XyY, primaries: ColorPrimaries) -> Matrix3d {
        let red_xyz = primaries.red.to_xyzd();
        let green_xyz = primaries.green.to_xyzd();
        let blue_xyz = primaries.blue.to_xyzd();

        let xyz_matrix = Matrix3d {
            v: [
                [red_xyz.x, green_xyz.x, blue_xyz.x],
                [red_xyz.y, green_xyz.y, blue_xyz.y],
                [red_xyz.z, green_xyz.z, blue_xyz.z],
            ],
        };
        let colorants = ColorProfile::rgb_to_xyz_d(xyz_matrix, white_point.to_xyzd());
        adapt_to_d50_d(colorants, white_point)
    }

    /// Updates RGB triple colorimetry from 3 [Chromaticity] and white point
    /// This will nullify CICP.
    pub const fn update_rgb_colorimetry(&mut self, white_point: XyY, primaries: ColorPrimaries) {
        self.cicp = None;
        let red_xyz = primaries.red.to_xyzd();
        let green_xyz = primaries.green.to_xyzd();
        let blue_xyz = primaries.blue.to_xyzd();

        self.chromatic_adaptation = Some(BRADFORD_D);
        self.update_rgb_colorimetry_triplet(white_point, red_xyz, green_xyz, blue_xyz)
    }

    /// Updates RGB triple colorimetry from 3 [Xyzd] and white point
    ///
    /// To work on `const` context this method does have restrictions.
    /// If invalid values were provided it may return invalid matrix or NaNs.
    ///
    /// This will void CICP tag.
    pub const fn update_rgb_colorimetry_triplet(
        &mut self,
        white_point: XyY,
        red_xyz: Xyzd,
        green_xyz: Xyzd,
        blue_xyz: Xyzd,
    ) {
        self.cicp = None;
        let xyz_matrix = Matrix3d {
            v: [
                [red_xyz.x, green_xyz.x, blue_xyz.x],
                [red_xyz.y, green_xyz.y, blue_xyz.y],
                [red_xyz.z, green_xyz.z, blue_xyz.z],
            ],
        };
        let colorants = ColorProfile::rgb_to_xyz_d(xyz_matrix, white_point.to_xyzd());
        let colorants = adapt_to_d50_d(colorants, white_point);

        self.update_colorants(colorants);
    }

    pub(crate) const fn update_colorants(&mut self, colorants: Matrix3d) {
        // note: there's a transpose type of operation going on here
        self.red_colorant.x = colorants.v[0][0];
        self.red_colorant.y = colorants.v[1][0];
        self.red_colorant.z = colorants.v[2][0];
        self.green_colorant.x = colorants.v[0][1];
        self.green_colorant.y = colorants.v[1][1];
        self.green_colorant.z = colorants.v[2][1];
        self.blue_colorant.x = colorants.v[0][2];
        self.blue_colorant.y = colorants.v[1][2];
        self.blue_colorant.z = colorants.v[2][2];
    }

    /// Updates RGB triple colorimetry from CICP
    pub fn update_rgb_colorimetry_from_cicp(&mut self, cicp: CicpProfile) -> bool {
        if !cicp.color_primaries.has_chromaticity()
            || !cicp.transfer_characteristics.has_transfer_curve()
        {
            return false;
        }
        let primaries_xy: ColorPrimaries = match cicp.color_primaries.try_into() {
            Ok(primaries) => primaries,
            Err(_) => return false,
        };
        let white_point: Chromaticity = match cicp.color_primaries.white_point() {
            Ok(v) => v,
            Err(_) => return false,
        };
        self.update_rgb_colorimetry(white_point.to_xyyb(), primaries_xy);
        self.cicp = Some(cicp);

        let red_trc: ToneReprCurve = match cicp.transfer_characteristics.try_into() {
            Ok(trc) => trc,
            Err(_) => return false,
        };
        self.green_trc = Some(red_trc.clone());
        self.blue_trc = Some(red_trc.clone());
        self.red_trc = Some(red_trc);
        false
    }

    pub const fn rgb_to_xyz(xyz_matrix: Matrix3f, wp: Xyz) -> Matrix3f {
        let xyz_inverse = xyz_matrix.inverse();
        let s = xyz_inverse.mul_vector(wp.to_vector());
        let mut v = xyz_matrix.mul_row_vector::<0>(s);
        v = v.mul_row_vector::<1>(s);
        v.mul_row_vector::<2>(s)
    }

    /// If Primaries is invalid will return invalid matrix on const context.
    /// This assumes not transposed matrix and returns not transposed matrix.
    pub const fn rgb_to_xyz_d(xyz_matrix: Matrix3d, wp: Xyzd) -> Matrix3d {
        let xyz_inverse = xyz_matrix.inverse();
        let s = xyz_inverse.mul_vector(wp.to_vector_d());
        let mut v = xyz_matrix.mul_row_vector::<0>(s);
        v = v.mul_row_vector::<1>(s);
        v = v.mul_row_vector::<2>(s);
        v
    }

    /// Returns the RGB to XYZ transformation matrix.
    ///
    /// Per ICC.1:2022-05 Section F.3, the computational model is:
    ///   connection = colorantMatrix × linear_rgb
    ///
    /// The colorant tags (rXYZ, gXYZ, bXYZ) are used directly as matrix columns.
    /// This matches skcms and lcms2 behavior.
    pub fn rgb_to_xyz_matrix(&self) -> Matrix3d {
        self.colorant_matrix()
    }

    /// Computes transform matrix RGB -> XYZ -> RGB
    /// Current profile is used as source, other as destination
    pub fn transform_matrix(&self, dest: &ColorProfile) -> Matrix3d {
        let source = self.rgb_to_xyz_matrix();
        let dst = dest.rgb_to_xyz_matrix();
        let dest_inverse = dst.inverse();
        dest_inverse.mat_mul(source)
    }

    /// Returns volume of colors stored in profile
    pub fn profile_volume(&self) -> Option<f32> {
        let red_prim = self.red_colorant;
        let green_prim = self.green_colorant;
        let blue_prim = self.blue_colorant;
        let tetrahedral_vertices = Matrix3d {
            v: [
                [red_prim.x, red_prim.y, red_prim.z],
                [green_prim.x, green_prim.y, green_prim.z],
                [blue_prim.x, blue_prim.y, blue_prim.z],
            ],
        };
        let det = tetrahedral_vertices.determinant()?;
        Some((det / 6.0f64) as f32)
    }

    #[allow(unused)]
    pub(crate) fn has_device_to_pcs_lut(&self) -> bool {
        self.lut_a_to_b_perceptual.is_some()
            || self.lut_a_to_b_saturation.is_some()
            || self.lut_a_to_b_colorimetric.is_some()
    }

    #[allow(unused)]
    pub(crate) fn has_pcs_to_device_lut(&self) -> bool {
        self.lut_b_to_a_perceptual.is_some()
            || self.lut_b_to_a_saturation.is_some()
            || self.lut_b_to_a_colorimetric.is_some()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn test_gray() {
        if let Ok(gray_icc) = fs::read("./assets/Generic Gray Gamma 2.2 Profile.icc") {
            let f_p = ColorProfile::new_from_slice(&gray_icc).unwrap();
            assert!(f_p.gray_trc.is_some());
        }
    }

    #[test]
    fn test_perceptual() {
        if let Ok(srgb_perceptual_icc) = fs::read("./assets/srgb_perceptual.icc") {
            let f_p = ColorProfile::new_from_slice(&srgb_perceptual_icc).unwrap();
            assert_eq!(f_p.pcs, DataColorSpace::Lab);
            assert_eq!(f_p.color_space, DataColorSpace::Rgb);
            assert_eq!(f_p.version(), ProfileVersion::V4_2);
            assert!(f_p.lut_a_to_b_perceptual.is_some());
            assert!(f_p.lut_b_to_a_perceptual.is_some());
        }
    }

    #[test]
    fn test_us_swop_coated() {
        if let Ok(us_swop_coated) = fs::read("./assets/us_swop_coated.icc") {
            let f_p = ColorProfile::new_from_slice(&us_swop_coated).unwrap();
            assert_eq!(f_p.pcs, DataColorSpace::Lab);
            assert_eq!(f_p.color_space, DataColorSpace::Cmyk);
            assert_eq!(f_p.version(), ProfileVersion::V2_0);

            assert!(f_p.lut_a_to_b_perceptual.is_some());
            assert!(f_p.lut_b_to_a_perceptual.is_some());

            assert!(f_p.lut_a_to_b_colorimetric.is_some());
            assert!(f_p.lut_b_to_a_colorimetric.is_some());

            assert!(f_p.gamut.is_some());

            assert!(f_p.copyright.is_some());
            assert!(f_p.description.is_some());
        }
    }

    #[test]
    fn test_matrix_shaper() {
        if let Ok(matrix_shaper) = fs::read("./assets/Display P3.icc") {
            let f_p = ColorProfile::new_from_slice(&matrix_shaper).unwrap();
            assert_eq!(f_p.pcs, DataColorSpace::Xyz);
            assert_eq!(f_p.color_space, DataColorSpace::Rgb);
            assert_eq!(f_p.version(), ProfileVersion::V4_0);

            assert!(f_p.red_trc.is_some());
            assert!(f_p.blue_trc.is_some());
            assert!(f_p.green_trc.is_some());

            assert_ne!(f_p.red_colorant, Xyzd::default());
            assert_ne!(f_p.blue_colorant, Xyzd::default());
            assert_ne!(f_p.green_colorant, Xyzd::default());

            assert!(f_p.copyright.is_some());
            assert!(f_p.description.is_some());
        }
    }

    /// Verify rgb_to_xyz_matrix returns colorant_matrix directly per ICC.1:2022-05 F.3.
    ///
    /// SM245B.icc is a V2 Samsung monitor profile with D65 colorants and no CHAD tag.
    /// Source: https://skia.googlesource.com/skcms/+/refs/heads/main/profiles/misc/SM245B.icc
    #[test]
    fn test_rgb_to_xyz_matrix_equals_colorant_matrix() {
        // Test with SM245B.icc (D65 colorants, no CHAD tag)
        if let Ok(icc_data) = fs::read("./assets/SM245B.icc") {
            if let Ok(profile) = ColorProfile::new_from_slice(&icc_data) {
                let rgb_to_xyz = profile.rgb_to_xyz_matrix();
                let colorants = profile.colorant_matrix();

                for i in 0..3 {
                    for j in 0..3 {
                        assert!(
                            (rgb_to_xyz.v[i][j] - colorants.v[i][j]).abs() < 1e-10,
                            "rgb_to_xyz_matrix should equal colorant_matrix at [{i}][{j}]"
                        );
                    }
                }
            }
        }

        // Also verify with sRGB
        let srgb = ColorProfile::new_srgb();
        let rgb_to_xyz = srgb.rgb_to_xyz_matrix();
        let colorants = srgb.colorant_matrix();

        for i in 0..3 {
            for j in 0..3 {
                assert!(
                    (rgb_to_xyz.v[i][j] - colorants.v[i][j]).abs() < 1e-10,
                    "sRGB: rgb_to_xyz_matrix should equal colorant_matrix at [{i}][{j}]"
                );
            }
        }
    }

    #[test]
    fn test_profile_version_parsing_standard() {
        // Standard versions should work
        assert_eq!(
            ProfileVersion::try_from(0x02000000).unwrap(),
            ProfileVersion::V2_0
        );
        assert_eq!(
            ProfileVersion::try_from(0x02400000).unwrap(),
            ProfileVersion::V2_4
        );
        assert_eq!(
            ProfileVersion::try_from(0x04000000).unwrap(),
            ProfileVersion::V4_0
        );
        assert_eq!(
            ProfileVersion::try_from(0x04400000).unwrap(),
            ProfileVersion::V4_4
        );
    }

    #[test]
    fn test_profile_version_parsing_patch_versions() {
        // Patch versions found in real ICC profiles should be accepted

        // v2.0.2 (SM245B.icc) - minor bugfix version
        assert!(
            ProfileVersion::try_from(0x02020000).is_ok(),
            "v2.0.2 should be accepted"
        );

        // v3.4 (ibm-t61.icc, new.icc) - intermediate version
        assert!(
            ProfileVersion::try_from(0x03400000).is_ok(),
            "v3.4 should be accepted"
        );

        // v4.2.9 (lcms_samsung_syncmaster.icc) - patch version
        assert!(
            ProfileVersion::try_from(0x04290000).is_ok(),
            "v4.2.9 should be accepted"
        );
    }

    #[test]
    fn test_profile_version_parsing_rejected() {
        // Invalid and unsupported versions should be rejected

        // v0.0 - invalid version (no such ICC spec exists)
        assert!(
            ProfileVersion::try_from(0x00000000).is_err(),
            "v0.0 should be rejected"
        );

        // v5.0 (iccMAX) - reject because it has different white point requirements
        assert!(
            ProfileVersion::try_from(0x05000000).is_err(),
            "v5.0 should be rejected"
        );

        // v6.0 - future/unknown version
        assert!(
            ProfileVersion::try_from(0x06000000).is_err(),
            "v6.0 should be rejected"
        );
    }

    #[test]
    fn test_profile_version_v4_4_mapping() {
        // V4.4 should map to V4_4, not V4_3 (regression test for typo)
        assert_eq!(
            ProfileVersion::try_from(0x04400000).unwrap(),
            ProfileVersion::V4_4
        );
    }

    #[test]
    fn test_rendering_intent_invalid_defaults_to_perceptual() {
        // Valid values are 0-3. Invalid values default to Perceptual
        // rather than rejecting the profile.
        assert_eq!(
            RenderingIntent::try_from(0x01000000).unwrap(),
            RenderingIntent::Perceptual
        );
        assert_eq!(
            RenderingIntent::try_from(0x04000000).unwrap(),
            RenderingIntent::Perceptual
        );
        assert_eq!(
            RenderingIntent::try_from(0xFFFFFFFF).unwrap(),
            RenderingIntent::Perceptual
        );
    }

    /// Parse a profile with a non-conforming rendering intent value.
    /// Synthesized from SM245B.icc with bytes 64-67 set to 0x01000000
    /// (byte-swapped, as found in old Linotype "Lino" profiles).
    /// The invalid value should default to Perceptual per our policy.
    #[test]
    fn test_invalid_rendering_intent_defaults_to_perceptual() {
        let icc_data =
            fs::read("./assets/swapped_intent.icc").expect("swapped_intent.icc test asset");
        let profile = ColorProfile::new_from_slice(&icc_data)
            .expect("Profile with invalid rendering intent should parse");
        assert_eq!(profile.rendering_intent, RenderingIntent::Perceptual);
        // Verify the rest of the profile parsed correctly
        assert_eq!(profile.color_space, DataColorSpace::Rgb);
        assert!(profile.red_trc.is_some());
        assert!(profile.green_trc.is_some());
        assert!(profile.blue_trc.is_some());
        let dst = ColorProfile::new_srgb();
        let transform = profile
            .create_transform_8bit(Layout::Rgba, &dst, Layout::Rgba, Default::default())
            .expect("Should create transform from profile with defaulted intent");
        let src = [128u8, 128, 128, 255];
        let mut out = [0u8; 4];
        transform.transform(&src, &mut out).unwrap();
        assert_eq!(out[3], 255, "Alpha should be preserved");
    }

    /// v4 profile with correct mluc description tag should parse as
    /// Localizable (regression: ensure desc-tolerance doesn't break mluc).
    #[test]
    fn test_v4_mluc_description_parses_as_localizable() {
        let icc_data = fs::read("./assets/Display P3.icc").expect("Display P3.icc test asset");
        let profile =
            ColorProfile::new_from_slice(&icc_data).expect("Display P3 profile should parse");
        assert_eq!(profile.version(), ProfileVersion::V4_0);
        let desc = profile
            .description
            .clone()
            .expect("description should be present");
        match desc {
            super::ProfileText::Localizable(records) => {
                assert!(!records.is_empty(), "mluc should have at least one record");
                assert!(
                    records[0].value.contains("Display P3"),
                    "mluc should contain 'Display P3', got: {}",
                    records[0].value
                );
            }
            other => panic!("v4 mluc should parse as Localizable, got {:?}", other),
        }
    }

    /// v4 profile with non-conforming truncated desc tag should parse.
    /// Synthesized from Display P3.icc with the mluc tag replaced by a
    /// minimal desc tag (ASCII only, no Unicode/ScriptCode sections).
    #[test]
    fn test_v4_truncated_desc_tag() {
        let icc_data =
            fs::read("./assets/truncated_desc_v4.icc").expect("truncated_desc_v4.icc test asset");
        let profile = ColorProfile::new_from_slice(&icc_data)
            .expect("v4 profile with truncated desc should parse");
        assert_eq!(profile.version(), ProfileVersion::V4_0);
        assert_eq!(profile.color_space, DataColorSpace::Rgb);
        let desc = profile
            .description
            .clone()
            .expect("description should be present");
        match desc {
            ProfileText::Description(d) => {
                assert!(
                    d.ascii_string.contains("Display P3"),
                    "desc should contain 'Display P3', got: {}",
                    d.ascii_string
                );
            }
            other => panic!(
                "v4 truncated desc should parse as Description, got {:?}",
                other
            ),
        }
        let dst = ColorProfile::new_srgb();
        let transform = profile
            .create_transform_8bit(Layout::Rgba, &dst, Layout::Rgba, Default::default())
            .expect("Should create transform from v4 profile with truncated desc");
        let src = [128u8, 128, 128, 255];
        let mut out = [0u8; 4];
        transform.transform(&src, &mut out).unwrap();
        assert_eq!(out[3], 255, "Alpha should be preserved");
    }
}