logo
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
//! Parsing and writing of the `cmap` table.
//!
//! > This table defines the mapping of character codes to the glyph index values used in the font.
//! > It may contain more than one subtable, in order to support more than one character encoding
//! > scheme.
//!
//! — <https://docs.microsoft.com/en-us/typography/opentype/spec/cmap>

pub(crate) mod subset;

use std::collections::HashMap;
use std::convert::TryFrom;

use itertools::izip;

use crate::binary::read::{
    CheckIndex, ReadArray, ReadArrayIter, ReadBinary, ReadCtxt, ReadFrom, ReadScope,
};
use crate::binary::write::{WriteBinary, WriteContext};
use crate::binary::{I16Be, U16Be, U32Be, U8};
use crate::error::{ParseError, WriteError};
use crate::size;

use self::owned::CmapSubtable as OwnedCmapSubtable;

const SUB_HEADER_SIZE: usize = 4 * 2;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct PlatformId(pub u16);

impl PlatformId {
    pub const UNICODE: PlatformId = PlatformId(0);
    pub const MACINTOSH: PlatformId = PlatformId(1);
    pub const WINDOWS: PlatformId = PlatformId(3);
    pub const CUSTOM: PlatformId = PlatformId(4);
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct EncodingId(pub u16);

impl EncodingId {
    pub const WINDOWS_SYMBOL: EncodingId = EncodingId(0);
    pub const WINDOWS_UNICODE_BMP_UCS2: EncodingId = EncodingId(1);
    pub const WINDOWS_SHIFT_JIS: EncodingId = EncodingId(2);
    pub const WINDOWS_PRC: EncodingId = EncodingId(3);
    pub const WINDOWS_BIG5: EncodingId = EncodingId(4);
    pub const WINDOWS_WANSUNG: EncodingId = EncodingId(5);
    pub const WINDOWS_JOHAB: EncodingId = EncodingId(6);
    // pub const WINDOWS_RESERVED: EncodingId = EncodingId(7);
    // pub const WINDOWS_RESERVED: EncodingId = EncodingId(8);
    // pub const WINDOWS_RESERVED: EncodingId = EncodingId(9);
    pub const WINDOWS_UNICODE_UCS4: EncodingId = EncodingId(10);

    pub const MACINTOSH_APPLE_ROMAN: EncodingId = EncodingId(0);
    pub const MACINTOSH_UNICODE_UCS4: EncodingId = EncodingId(4);

    /// Unicode 2.0 and onwards semantics, Unicode BMP only
    pub const UNICODE_BMP: EncodingId = EncodingId(3);
    /// Unicode 2.0 and onwards semantics, Unicode full repertoire
    pub const UNICODE_FULL: EncodingId = EncodingId(4);
}

pub struct Cmap<'a> {
    pub scope: ReadScope<'a>,
    encoding_records: ReadArray<'a, EncodingRecord>,
}

#[derive(Copy, Clone)]
pub struct EncodingRecord {
    pub platform_id: PlatformId,
    pub encoding_id: EncodingId,
    pub offset: u32,
}

pub enum CmapSubtable<'a> {
    Format0 {
        language: u16,
        glyph_id_array: ReadArray<'a, U8>,
    },
    Format2 {
        language: u16,
        sub_header_keys: ReadArray<'a, U16Be>,
        sub_headers: ReadArray<'a, SubHeader>,
        sub_headers_scope: ReadScope<'a>,
    },
    Format4(CmapSubtableFormat4<'a>),
    Format6 {
        language: u16,
        first_code: u16,
        glyph_id_array: ReadArray<'a, U16Be>,
    },
    Format10 {
        language: u32,
        start_char_code: u32,
        glyph_id_array: ReadArray<'a, U16Be>,
    },
    Format12 {
        language: u32,
        groups: ReadArray<'a, SequentialMapGroup>,
    },
}

// cmap subtable format 2 sub-header
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Hash)]
pub struct SubHeader {
    first_code: u16,
    entry_count: u16,
    id_delta: i16,
    id_range_offset: u16,
}

#[derive(Debug, Clone)]
pub struct CmapSubtableFormat4<'a> {
    pub language: u16,
    pub end_codes: ReadArray<'a, U16Be>,
    pub start_codes: ReadArray<'a, U16Be>,
    pub id_deltas: ReadArray<'a, I16Be>,
    pub id_range_offsets: ReadArray<'a, U16Be>,
    pub glyph_id_array: ReadArray<'a, U16Be>,
}

#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Hash)]
struct Format4Calculator {
    seg_count: u16,
}

#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Hash)]
pub struct SequentialMapGroup {
    pub(crate) start_char_code: u32,
    pub(crate) end_char_code: u32,
    pub(crate) start_glyph_id: u32,
}

impl<'a> ReadBinary<'a> for Cmap<'a> {
    type HostType = Self;

    fn read(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
        let scope = ctxt.scope();
        let version = ctxt.read_u16be()?;
        ctxt.check(version == 0)?;
        let num_tables = usize::from(ctxt.read_u16be()?);
        let encoding_records = ctxt.read_array::<EncodingRecord>(num_tables)?;
        Ok(Cmap {
            scope,
            encoding_records,
        })
    }
}

impl<'a> ReadFrom<'a> for EncodingRecord {
    type ReadType = (U16Be, U16Be, U32Be);
    fn from((platform_id, encoding_id, offset): (u16, u16, u32)) -> Self {
        EncodingRecord {
            platform_id: PlatformId(platform_id),
            encoding_id: EncodingId(encoding_id),
            offset,
        }
    }
}

impl<'a> ReadBinary<'a> for CmapSubtable<'a> {
    type HostType = Self;

    fn read(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
        let subtable_format = ctxt.read_u16be()?;
        match subtable_format {
            0 => {
                let length = usize::from(ctxt.read_u16be()?);
                ctxt.check(length >= 3 * size::U16 + 256)?;
                let language = ctxt.read_u16be()?;
                let glyph_id_array = ctxt.read_array::<U8>(256)?;
                Ok(CmapSubtable::Format0 {
                    language,
                    glyph_id_array,
                })
            }
            2 => {
                let _length = usize::from(ctxt.read_u16be()?);
                let language = ctxt.read_u16be()?;
                let sub_header_keys = ctxt.read_array::<U16Be>(256)?;

                // value is subHeader index × 8.
                // NOTE(unwrap): Safe because sub_header_keys has a non-zero length
                let max_sub_header_index =
                    sub_header_keys.iter().map(|value| value / 8).max().unwrap();
                let sub_headers_scope = ctxt.scope();
                let sub_headers =
                    ctxt.read_array::<SubHeader>(usize::from(max_sub_header_index) + 1)?;

                Ok(CmapSubtable::Format2 {
                    language,
                    sub_header_keys,
                    sub_headers,
                    sub_headers_scope,
                })
            }
            4 => {
                let length = usize::from(ctxt.read_u16be()?);
                let language = ctxt.read_u16be()?;
                let seg_count_x2 = usize::from(ctxt.read_u16be()?);
                ctxt.check((seg_count_x2 & 1) == 0)?;
                let seg_count = seg_count_x2 >> 1;
                let _search_range = ctxt.read_u16be()?;
                let _entry_selector = ctxt.read_u16be()?;
                let _range_shift = ctxt.read_u16be()?;
                let end_codes = ctxt.read_array::<U16Be>(seg_count)?;
                let _reserved_pad = ctxt.read_u16be()?;
                let start_codes = ctxt.read_array::<U16Be>(seg_count)?;
                let id_deltas = ctxt.read_array::<I16Be>(seg_count)?;
                let id_range_offsets = ctxt.read_array::<U16Be>(seg_count)?;
                ctxt.check(length >= (8 + (4 * seg_count)) * size::U16)?;
                let remaining = length - ((8 + (4 * seg_count)) * size::U16);
                ctxt.check((remaining & 1) == 0)?;
                let num_indices = remaining >> 1;
                let glyph_id_array = ctxt.read_array::<U16Be>(num_indices)?;
                Ok(CmapSubtable::Format4(CmapSubtableFormat4 {
                    language,
                    end_codes,
                    start_codes,
                    id_deltas,
                    id_range_offsets,
                    glyph_id_array,
                }))
            }
            6 => {
                let _length = ctxt.read_u16be()?;
                let language = ctxt.read_u16be()?;
                let first_code = ctxt.read_u16be()?;
                let entry_count = usize::from(ctxt.read_u16be()?);
                let glyph_id_array = ctxt.read_array::<U16Be>(entry_count)?;
                Ok(CmapSubtable::Format6 {
                    language,
                    first_code,
                    glyph_id_array,
                })
            }
            10 => {
                let reserved = ctxt.read_u16be()?;
                ctxt.check(reserved == 0)?;
                let _length = ctxt.read_u32be()?;
                let language = ctxt.read_u32be()?;
                let start_char_code = ctxt.read_u32be()?;
                let num_chars = usize::try_from(ctxt.read_u32be()?)?;
                let glyph_id_array = ctxt.read_array::<U16Be>(num_chars)?;
                Ok(CmapSubtable::Format10 {
                    language,
                    start_char_code,
                    glyph_id_array,
                })
            }
            12 => {
                let reserved = ctxt.read_u16be()?;
                ctxt.check(reserved == 0)?;
                let _length = ctxt.read_u32be()?;
                let language = ctxt.read_u32be()?;
                let num_groups = usize::try_from(ctxt.read_u32be()?)?;
                let groups = ctxt.read_array::<SequentialMapGroup>(num_groups)?;
                Ok(CmapSubtable::Format12 { language, groups })
            }
            _ => Err(ParseError::BadVersion),
        }
    }
}

impl<'a> WriteBinary<&Self> for CmapSubtable<'a> {
    type Output = ();

    fn write<C: WriteContext>(ctxt: &mut C, table: &CmapSubtable<'a>) -> Result<(), WriteError> {
        match table {
            CmapSubtable::Format0 {
                language,
                glyph_id_array,
            } => {
                U16Be::write(ctxt, 0u16)?; // format
                U16Be::write(ctxt, u16::try_from(3 * size::U16 + glyph_id_array.len())?)?; // length
                U16Be::write(ctxt, *language)?;
                <&ReadArray<'_, _>>::write(ctxt, glyph_id_array)?;
            }
            CmapSubtable::Format2 { .. } => {
                // Not implemented for now. Format 2 is rarely seen in the wild and would generally
                // not be generated for a subset font (the most common path for font writing)
                return Err(WriteError::NotImplemented);
            }
            CmapSubtable::Format4(CmapSubtableFormat4 {
                language,
                end_codes,
                start_codes,
                id_deltas,
                id_range_offsets,
                glyph_id_array,
            }) => {
                let start = ctxt.bytes_written();
                let calc = Format4Calculator {
                    seg_count: u16::try_from(start_codes.len())?,
                };

                U16Be::write(ctxt, 4u16)?; // format
                let length = ctxt.placeholder::<U16Be, _>()?;
                U16Be::write(ctxt, *language)?;
                U16Be::write(ctxt, calc.seg_count_x2())?;
                U16Be::write(ctxt, calc.search_range())?;
                U16Be::write(ctxt, calc.entry_selector())?;
                U16Be::write(ctxt, calc.range_shift())?;
                <&ReadArray<'_, _>>::write(ctxt, end_codes)?;
                U16Be::write(ctxt, 0u16)?; // reserved_pad
                <&ReadArray<'_, _>>::write(ctxt, start_codes)?;
                <&ReadArray<'_, _>>::write(ctxt, id_deltas)?;
                <&ReadArray<'_, _>>::write(ctxt, id_range_offsets)?;
                <&ReadArray<'_, _>>::write(ctxt, glyph_id_array)?;
                ctxt.write_placeholder(length, u16::try_from(ctxt.bytes_written() - start)?)?;
            }
            CmapSubtable::Format6 {
                language,
                first_code,
                glyph_id_array,
            } => {
                let start = ctxt.bytes_written();

                U16Be::write(ctxt, 6u16)?; // format
                let length = ctxt.placeholder::<U16Be, _>()?;
                U16Be::write(ctxt, *language)?;
                U16Be::write(ctxt, *first_code)?;
                U16Be::write(ctxt, u16::try_from(glyph_id_array.len())?)?;
                <&ReadArray<'_, _>>::write(ctxt, glyph_id_array)?;
                ctxt.write_placeholder(length, u16::try_from(ctxt.bytes_written() - start)?)?;
            }
            CmapSubtable::Format10 {
                language,
                start_char_code,
                glyph_id_array,
            } => {
                let start = ctxt.bytes_written();

                U16Be::write(ctxt, 10u16)?; // format
                U16Be::write(ctxt, 0u16)?; // reserved
                let length = ctxt.placeholder::<U32Be, _>()?;
                U32Be::write(ctxt, *language)?;
                U32Be::write(ctxt, *start_char_code)?;
                U32Be::write(ctxt, u32::try_from(glyph_id_array.len())?)?;
                <&ReadArray<'_, _>>::write(ctxt, glyph_id_array)?;
                ctxt.write_placeholder(length, u32::try_from(ctxt.bytes_written() - start)?)?;
            }
            CmapSubtable::Format12 { language, groups } => {
                let start = ctxt.bytes_written();

                U16Be::write(ctxt, 12u16)?; // format
                U16Be::write(ctxt, 0u16)?; // reserved
                let length = ctxt.placeholder::<U32Be, _>()?;
                U32Be::write(ctxt, *language)?;
                U32Be::write(ctxt, u32::try_from(groups.len())?)?;
                <&ReadArray<'_, _>>::write(ctxt, groups)?;
                ctxt.write_placeholder(length, u32::try_from(ctxt.bytes_written() - start)?)?;
            }
        }

        Ok(())
    }
}

impl<'a, 'b> Format4 for &'a CmapSubtableFormat4<'b> {
    type U16Iter = ReadArrayIter<'b, U16Be>;
    type I16Iter = ReadArrayIter<'b, I16Be>;

    fn end_codes(self) -> Self::U16Iter {
        self.end_codes.iter()
    }

    fn start_codes(self) -> Self::U16Iter {
        self.start_codes.iter()
    }

    fn id_deltas(self) -> Self::I16Iter {
        self.id_deltas.iter()
    }

    fn id_range_offsets(self) -> Self::U16Iter {
        self.id_range_offsets.iter()
    }

    fn glyph_id_array_get(self, index: usize) -> Result<u16, ParseError> {
        self.glyph_id_array
            .check_index(index)
            .map(|()| self.glyph_id_array.get_item(index))
    }
}

impl Format4Calculator {
    fn seg_count_x2(self) -> u16 {
        2 * self.seg_count
    }

    fn search_range(self) -> u16 {
        2 * (2u16.pow((self.seg_count as f64).log2().floor() as u32))
    }

    fn entry_selector(self) -> u16 {
        (self.search_range() as f64 / 2.).log2() as u16
    }

    fn range_shift(self) -> u16 {
        2 * self.seg_count - self.search_range()
    }
}

impl<'a> ReadFrom<'a> for SubHeader {
    type ReadType = ((U16Be, U16Be), (I16Be, U16Be));
    fn from(
        ((first_code, entry_count), (id_delta, id_range_offset)): ((u16, u16), (i16, u16)),
    ) -> Self {
        SubHeader {
            first_code,
            entry_count,
            id_delta,
            id_range_offset,
        }
    }
}

impl SubHeader {
    fn contains(&self, value: u16) -> bool {
        (self.first_code..self.first_code + self.entry_count).contains(&value)
    }

    fn glyph_index_sub_array<'a>(
        &self,
        index: usize,
        sub_headers_scope: &ReadScope<'a>,
    ) -> Result<ReadArray<'a, U16Be>, ParseError> {
        let sub_header_offset = index * SUB_HEADER_SIZE;

        let glyph_index_sub_array = if self.entry_count > 0 {
            let entry_count = usize::from(self.entry_count);
            // The value of the idRangeOffset is the number of bytes past the actual
            // location of the idRangeOffset word where the glyphIndexArray element
            // corresponding to firstCode appears.
            // https://docs.microsoft.com/en-us/typography/opentype/spec/cmap#format-2-high-byte-mapping-through-table
            //
            // So we take the size of the SubHeader and subtract 2 for the size of the
            // id_range_offset field.
            let first_glpyh_index_offset =
                sub_header_offset + SUB_HEADER_SIZE - 2 + usize::from(self.id_range_offset);
            sub_headers_scope
                .offset(first_glpyh_index_offset)
                .ctxt()
                .read_array::<U16Be>(entry_count)?
        } else {
            ReadArray::empty()
        };

        Ok(glyph_index_sub_array)
    }
}

impl<'a> ReadFrom<'a> for SequentialMapGroup {
    type ReadType = (U32Be, U32Be, U32Be);
    fn from((start_char_code, end_char_code, start_glyph_id): (u32, u32, u32)) -> Self {
        SequentialMapGroup {
            start_char_code,
            end_char_code,
            start_glyph_id,
        }
    }
}

impl WriteBinary for SequentialMapGroup {
    type Output = ();

    fn write<C: WriteContext>(ctxt: &mut C, group: SequentialMapGroup) -> Result<(), WriteError> {
        U32Be::write(ctxt, group.start_char_code)?;
        U32Be::write(ctxt, group.end_char_code)?;
        U32Be::write(ctxt, group.start_glyph_id)?;

        Ok(())
    }
}

impl<'a> Cmap<'a> {
    /// Find the first encoding record for the given `platform_id`
    pub fn find_subtable_for_platform(&self, platform_id: PlatformId) -> Option<EncodingRecord> {
        self.encoding_records
            .iter()
            .find(|record| record.platform_id == platform_id)
    }

    /// Find the first encoding record for the given `platform_id` and `encoding_id`
    pub fn find_subtable(
        &self,
        platform_id: PlatformId,
        encoding_id: EncodingId,
    ) -> Option<EncodingRecord> {
        self.encoding_records
            .iter()
            .find(|record| record.platform_id == platform_id && record.encoding_id == encoding_id)
    }

    pub fn encoding_records(&self) -> impl Iterator<Item = EncodingRecord> + 'a {
        self.encoding_records.iter()
    }
}

impl<'a> CmapSubtable<'a> {
    // NOTE: `owned::CmapSubtable` contains a duplicate of this
    pub fn map_glyph(&self, ch: u32) -> Result<Option<u16>, ParseError> {
        match *self {
            CmapSubtable::Format0 {
                ref glyph_id_array, ..
            } => {
                let index = usize::try_from(ch)?;
                if index < glyph_id_array.len() {
                    let glyph_id = glyph_id_array.get_item(index);
                    Ok(Some(u16::from(glyph_id)))
                } else {
                    Ok(None)
                }
            }
            CmapSubtable::Format2 {
                ref sub_header_keys,
                ref sub_headers,
                ref sub_headers_scope,
                ..
            } => {
                let high_byte = ((ch >> 8) & 0xff) as u8;
                let low_byte = ((ch) & 0xff) as u8;

                let header_index_byte = {
                    let low_byte = usize::from(low_byte);
                    if high_byte == 0
                        && sub_header_keys
                            .check_index(low_byte)
                            .map(|_| sub_header_keys.get_item(low_byte))?
                            == 0
                    {
                        low_byte
                    } else {
                        usize::from(high_byte)
                    }
                };

                let sub_header_key = usize::from(
                    // value is subHeader index × 8.
                    sub_header_keys
                        .check_index(header_index_byte)
                        .map(|_| sub_header_keys.get_item(header_index_byte))?
                        / 8,
                );
                let sub_header = sub_headers
                    .check_index(sub_header_key)
                    .map(|_| sub_headers.get_item(sub_header_key))?;

                if !sub_header.contains(u16::from(low_byte)) {
                    return Ok(Some(0));
                }
                let glyph_id_index = u16::from(low_byte) - sub_header.first_code;

                let glyph_index_sub_array =
                    sub_header.glyph_index_sub_array(sub_header_key, sub_headers_scope)?;
                let mut glyph_id = glyph_index_sub_array
                    .check_index(usize::from(glyph_id_index))
                    .map(|_| glyph_index_sub_array.get_item(usize::from(glyph_id_index)))?;

                if glyph_id != 0 {
                    // The idDelta arithmetic is modulo 65536.
                    glyph_id = ((glyph_id as isize + sub_header.id_delta as isize) & 0xffff) as u16
                }

                Ok(Some(glyph_id))
            }
            CmapSubtable::Format4(ref format4) => format4.map_glyph(ch),
            CmapSubtable::Format6 {
                first_code,
                ref glyph_id_array,
                ..
            } => {
                let first_code = u32::from(first_code);
                if first_code <= ch {
                    let index = usize::try_from(ch - first_code)?;
                    if index < glyph_id_array.len() {
                        let glyph_id = glyph_id_array.get_item(index);
                        Ok(Some(glyph_id))
                    } else {
                        Ok(None)
                    }
                } else {
                    Ok(None)
                }
            }
            CmapSubtable::Format10 {
                start_char_code,
                ref glyph_id_array,
                ..
            } => {
                if ch >= start_char_code {
                    let index = usize::try_from(ch - start_char_code)?;
                    if index < glyph_id_array.len() {
                        let glyph_id = glyph_id_array.get_item(index);
                        Ok(Some(glyph_id))
                    } else {
                        Ok(None)
                    }
                } else {
                    Ok(None)
                }
            }
            CmapSubtable::Format12 { ref groups, .. } => {
                for group in groups {
                    if group.start_char_code <= ch && ch <= group.end_char_code {
                        let glyph_id = group.start_glyph_id + (ch - group.start_char_code);
                        return Ok(Some(u16::try_from(glyph_id)?));
                    }
                }
                Ok(None)
            }
        }
    }

    /// Returns an `owned::CmapSubtable`. Will only return `None` if `self` is
    /// `CmapSubtable::Format2` as support for converting from this format is not yet implemented.
    pub fn to_owned(&self) -> Option<OwnedCmapSubtable> {
        match self {
            CmapSubtable::Format0 {
                language,
                glyph_id_array,
            } => Some(OwnedCmapSubtable::Format0 {
                language: *language,
                glyph_id_array: {
                    let mut uninitialized = [0_u8; 256];
                    for (target, source) in uninitialized.iter_mut().zip(glyph_id_array.iter()) {
                        *target = source;
                    }
                    Box::new(uninitialized)
                },
            }),
            // It's unlikely that a sub-table using format 2 would be selected for mappings as most
            // fonts that contain format 2 would probably contain a platform/encoding combination
            // that uses a different format, which would be selected first. As a result support
            // for it is not yet implemented.
            CmapSubtable::Format2 { .. } => None,
            CmapSubtable::Format4(CmapSubtableFormat4 {
                language,
                end_codes,
                start_codes,
                id_deltas,
                id_range_offsets,
                glyph_id_array,
            }) => Some(OwnedCmapSubtable::Format4(owned::CmapSubtableFormat4 {
                language: *language,
                end_codes: end_codes.to_vec(),
                start_codes: start_codes.to_vec(),
                id_deltas: id_deltas.to_vec(),
                id_range_offsets: id_range_offsets.to_vec(),
                glyph_id_array: glyph_id_array.to_vec(),
            })),
            CmapSubtable::Format6 {
                language,
                first_code,
                glyph_id_array,
            } => Some(OwnedCmapSubtable::Format6 {
                language: *language,
                first_code: *first_code,
                glyph_id_array: glyph_id_array.to_vec(),
            }),
            CmapSubtable::Format10 {
                language,
                start_char_code,
                glyph_id_array,
            } => Some(OwnedCmapSubtable::Format10 {
                language: *language,
                start_char_code: *start_char_code,
                glyph_id_array: glyph_id_array.to_vec(),
            }),
            CmapSubtable::Format12 { language, groups } => {
                Some(OwnedCmapSubtable::Format12(owned::CmapSubtableFormat12 {
                    language: *language,
                    groups: groups.to_vec(),
                }))
            }
        }
    }

    /// Extract all the mappings from the sub-table.
    ///
    /// The returned `HashMap` maps glyph indexes to char codes. If more than one char code maps to
    /// the same glyph, the `HashMap` will contain the **first** mapping encountered. Also note that
    /// the char code is not necessarily Unicode. It depends on on the encoding of the cmap
    /// sub-table.
    ///
    /// This method primarily exists to support [GlyphNames](crate::glyph_info::GlyphNames).
    pub(crate) fn mappings(&self) -> Result<HashMap<u16, u32>, ParseError> {
        let mut mappings = HashMap::with_capacity(self.size_hint());
        self.mappings_fn(|ch, gid| {
            mappings.entry(gid).or_insert(ch);
        })?;
        Ok(mappings)
    }

    /// Extract all the mappings from the sub-table.
    pub fn mappings_fn(&self, mut callback: impl FnMut(u32, u16)) -> Result<(), ParseError> {
        match self {
            CmapSubtable::Format0 {
                language: _,
                glyph_id_array,
            } => {
                for (ch, gid) in glyph_id_array.iter().enumerate() {
                    // cast is safe as format 0 can only contain 256 glyphs
                    callback(ch as u32, u16::from(gid))
                }
            }
            CmapSubtable::Format2 {
                sub_header_keys,
                sub_headers,
                sub_headers_scope,
                ..
            } => {
                for high_byte in 0u8..=255 {
                    let sub_header_key = usize::from(
                        // value is subHeader index × 8.
                        sub_header_keys
                            .check_index(usize::from(high_byte))
                            .map(|_| sub_header_keys.get_item(usize::from(high_byte)))?
                            / 8,
                    );
                    let sub_header = sub_headers
                        .check_index(sub_header_key)
                        .map(|_| sub_headers.get_item(sub_header_key))?;

                    // TODO: Reduce duplication
                    if sub_header_key == 0 {
                        if !sub_header.contains(u16::from(high_byte)) {
                            continue; // .notdef
                        }

                        let glyph_id_index = u16::from(high_byte) - sub_header.first_code;

                        let glyph_index_sub_array =
                            sub_header.glyph_index_sub_array(sub_header_key, sub_headers_scope)?;
                        let mut glyph_id = glyph_index_sub_array
                            .check_index(usize::from(glyph_id_index))
                            .map(|_| glyph_index_sub_array.get_item(usize::from(glyph_id_index)))?;

                        if glyph_id != 0 {
                            // The idDelta arithmetic is modulo 65536.
                            glyph_id =
                                ((glyph_id as isize + sub_header.id_delta as isize) & 0xffff) as u16
                        }
                        callback(u32::from(high_byte), glyph_id);
                    } else {
                        for glyph_id_index in 0..sub_header.entry_count {
                            // FIXME: u8/u16
                            let low_byte = glyph_id_index + sub_header.first_code;

                            let glyph_index_sub_array = sub_header
                                .glyph_index_sub_array(sub_header_key, sub_headers_scope)?;
                            let mut glyph_id = glyph_index_sub_array
                                .check_index(usize::from(glyph_id_index))
                                .map(|_| {
                                    glyph_index_sub_array.get_item(usize::from(glyph_id_index))
                                })?;

                            if glyph_id != 0 {
                                // The idDelta arithmetic is modulo 65536.
                                glyph_id = ((glyph_id as isize + sub_header.id_delta as isize)
                                    & 0xffff) as u16
                            }
                            callback((u32::from(high_byte) << 8) | u32::from(low_byte), glyph_id);
                        }
                    }
                }
            }
            CmapSubtable::Format4(format4) => format4.mappings_fn(callback)?,
            CmapSubtable::Format6 {
                language: _,
                first_code,
                glyph_id_array,
            } => {
                for (index, gid) in glyph_id_array.iter().enumerate() {
                    // cast is safe as the entryCount of the glyphIdArray is a 16-bit value
                    callback(u32::from(*first_code) + index as u32, gid)
                }
            }
            CmapSubtable::Format10 {
                language: _,
                start_char_code,
                glyph_id_array,
            } => {
                for (index, gid) in glyph_id_array.iter().enumerate() {
                    let index = u32::try_from(index)?;
                    callback(*start_char_code + index, gid)
                }
            }
            CmapSubtable::Format12 { groups, .. } => {
                for record in groups.iter() {
                    for (i, ch) in (record.start_char_code..=record.end_char_code).enumerate() {
                        callback(
                            ch,
                            u16::try_from(record.start_glyph_id)? + u16::try_from(i)?,
                        )
                    }
                }
            }
        }

        Ok(())
    }

    /// A hint as to the number of mappings contained in this sub-table.
    ///
    /// For some formats it will be the exact size, for others it will be underestimated.
    pub(crate) fn size_hint(&self) -> usize {
        match self {
            CmapSubtable::Format0 { glyph_id_array, .. } => glyph_id_array.len(),
            CmapSubtable::Format2 { .. } => 0, // TODO: Implement if needed in mappings_fn
            CmapSubtable::Format4(CmapSubtableFormat4 { glyph_id_array, .. }) => {
                glyph_id_array.len()
            }
            CmapSubtable::Format6 { glyph_id_array, .. } => glyph_id_array.len(),
            CmapSubtable::Format10 { glyph_id_array, .. } => glyph_id_array.len(),
            CmapSubtable::Format12 { groups, .. } => groups
                .iter()
                .map(|group| {
                    let start_char_code = group.start_char_code as usize;
                    let end_char_code = group.end_char_code as usize;
                    end_char_code.saturating_sub(start_char_code)
                })
                .sum(),
        }
    }
}

trait Format4 {
    type U16Iter: ExactSizeIterator<Item = u16>;
    type I16Iter: ExactSizeIterator<Item = i16>;

    fn end_codes(self) -> Self::U16Iter;
    fn start_codes(self) -> Self::U16Iter;
    fn id_deltas(self) -> Self::I16Iter;
    fn id_range_offsets(self) -> Self::U16Iter;
    fn glyph_id_array_get(self, index: usize) -> Result<u16, ParseError>;

    fn map_glyph(self, ch: u32) -> Result<Option<u16>, ParseError>
    where
        Self: Sized + Copy,
    {
        // Format 4 sub-tables can only map a 16-bit character range
        let ch = u16::try_from(ch)?;
        let zipped = izip!(
            self.start_codes(),
            self.end_codes(),
            self.id_deltas(),
            self.id_range_offsets()
        );
        for (i, (start_code, end_code, id_delta, id_range_offset)) in zipped.enumerate() {
            // Find segment that contains `ch`
            if start_code <= ch && ch <= end_code {
                // This segment contains ch
                let glyph_id = self.glyph_id_for_id_range_offset(
                    id_range_offset,
                    ch,
                    id_delta,
                    i,
                    ch - start_code,
                )?;
                return Ok(Some(glyph_id));
            }
        }
        Ok(None)
    }

    fn mappings_fn(self, mut callback: impl FnMut(u32, u16)) -> Result<(), ParseError>
    where
        Self: Sized + Copy,
    {
        let zipped = izip!(
            self.start_codes(),
            self.end_codes(),
            self.id_deltas(),
            self.id_range_offsets()
        );
        for (i, (start_code, end_code, id_delta, id_range_offset)) in zipped.enumerate() {
            for (offset_from_start, ch) in (start_code..=end_code).enumerate() {
                let glyph_id = self.glyph_id_for_id_range_offset(
                    id_range_offset,
                    ch,
                    id_delta,
                    i,
                    offset_from_start as u16,
                )?;
                callback(u32::from(ch), glyph_id)
            }
        }

        Ok(())
    }

    fn glyph_id_for_id_range_offset(
        self,
        mut id_range_offset: u16,
        ch: u16,
        id_delta: i16,
        segment_index: usize,
        start_code_offset: u16,
    ) -> Result<u16, ParseError>
    where
        Self: Sized + Copy,
    {
        // Work around Fontographer bug
        // https://github.com/adobe-type-tools/afdko/blob/01a35dacc9e8d1735b7f752f3232d38c34e6f843/c/shared/source/ttread/ttread.c#L1885
        if id_range_offset == 0xFFFF {
            id_range_offset = 0;
        }

        if id_range_offset == 0 {
            // If the idRangeOffset is 0, the idDelta value is added directly to
            // the character code offset (i.e. idDelta[i] + c) to get the
            // corresponding glyph index. The idDelta arithmetic is modulo 65536.
            Ok(((i32::from(ch) + i32::from(id_delta)) & 0xFFFF) as u16)
        } else {
            let index = offset_to_index(
                segment_index,
                id_range_offset,
                start_code_offset,
                self.id_range_offsets().len(),
            )?;
            let glyph_id = self.glyph_id_array_get(index)?;
            Ok(((i32::from(glyph_id) + i32::from(id_delta)) & 0xFFFF) as u16)
        }
    }
}

// For converting cmap format 4 offsets to indexes into the glyph id array.
fn offset_to_index(
    i: usize,
    id_range_offset: u16,
    start_code_offset: u16,
    id_range_offsets_len: usize,
) -> Result<usize, ParseError> {
    // Offset into `id_range_offsets` that `i` represents, * 2 for 16-bit values in the array.
    // cast is safe as i is segment index, which is a u16
    let offset_in_id_range_offsets = u32::from(id_range_offset) + i as u32 * 2;
    // Offset into `glyph_id_array` is offset from `start_code` of `ch` * 2 for 16-bit glyph ids.
    let glyph_id_offset = offset_in_id_range_offsets + u32::from(start_code_offset) * 2;
    // Bounds check, cast is safe as id_range_offsets has max segCount items, a 16-bit value.
    if glyph_id_offset >= id_range_offsets_len as u32 * 2 && (glyph_id_offset & 1) == 0 {
        // Turn the offsets into an index
        Ok(((glyph_id_offset >> 1) as usize) - id_range_offsets_len)
    } else {
        return Err(ParseError::BadIndex);
    }
}

pub mod owned {
    use super::{
        size, EncodingId, Format4, Format4Calculator, I16Be, ParseError, PlatformId,
        SequentialMapGroup, TryFrom, U16Be, U32Be, WriteBinary, WriteContext, WriteError,
    };

    #[derive(Debug, Clone, PartialEq)]
    pub struct Cmap {
        pub encoding_records: Vec<EncodingRecord>,
    }

    #[derive(Debug, Clone, PartialEq)]
    pub struct EncodingRecord {
        pub platform_id: PlatformId,
        pub encoding_id: EncodingId,
        pub sub_table: CmapSubtable,
    }

    #[derive(Debug, Clone, PartialEq)]
    pub enum CmapSubtable {
        Format0 {
            language: u16,
            glyph_id_array: Box<[u8; 256]>,
        },
        Format4(CmapSubtableFormat4),
        Format6 {
            language: u16,
            first_code: u16,
            glyph_id_array: Vec<u16>,
        },
        Format10 {
            language: u32,
            start_char_code: u32,
            glyph_id_array: Vec<u16>,
        },
        Format12(CmapSubtableFormat12),
    }

    #[derive(Debug, Clone, PartialEq)]
    pub struct CmapSubtableFormat4 {
        pub language: u16,
        pub end_codes: Vec<u16>,
        pub start_codes: Vec<u16>,
        pub id_deltas: Vec<i16>,
        pub id_range_offsets: Vec<u16>,
        pub glyph_id_array: Vec<u16>,
    }

    #[derive(Debug, Clone, PartialEq)]
    pub struct CmapSubtableFormat12 {
        pub language: u32,
        pub groups: Vec<SequentialMapGroup>,
    }

    impl CmapSubtable {
        pub fn map_glyph(&self, ch: u32) -> Result<Option<u16>, ParseError> {
            // NOTE: Currently a duplicate of `super::CmapSubtable::map_glyph`
            match *self {
                CmapSubtable::Format0 {
                    ref glyph_id_array, ..
                } => {
                    let index = usize::try_from(ch)?;
                    if index < glyph_id_array.len() {
                        let glyph_id = glyph_id_array[index];
                        Ok(Some(u16::from(glyph_id)))
                    } else {
                        Ok(None)
                    }
                }
                CmapSubtable::Format4(ref format4) => format4.map_glyph(ch),
                CmapSubtable::Format6 {
                    first_code,
                    ref glyph_id_array,
                    ..
                } => {
                    let first_code = u32::from(first_code);
                    if first_code <= ch {
                        let index = usize::try_from(ch - first_code)?;
                        if index < glyph_id_array.len() {
                            let glyph_id = glyph_id_array[index];
                            Ok(Some(glyph_id))
                        } else {
                            Ok(None)
                        }
                    } else {
                        Ok(None)
                    }
                }
                CmapSubtable::Format10 {
                    start_char_code,
                    ref glyph_id_array,
                    ..
                } => {
                    if ch >= start_char_code {
                        let index = usize::try_from(ch - start_char_code)?;
                        if index < glyph_id_array.len() {
                            let glyph_id = glyph_id_array[index];
                            Ok(Some(glyph_id))
                        } else {
                            Ok(None)
                        }
                    } else {
                        Ok(None)
                    }
                }
                CmapSubtable::Format12(CmapSubtableFormat12 { ref groups, .. }) => {
                    for group in groups {
                        if group.start_char_code <= ch && ch <= group.end_char_code {
                            let glyph_id = group.start_glyph_id + (ch - group.start_char_code);
                            return Ok(Some(u16::try_from(glyph_id)?));
                        }
                    }
                    Ok(None)
                }
            }
        }
    }

    impl<'a> Format4 for &'a CmapSubtableFormat4 {
        type U16Iter = std::iter::Copied<std::slice::Iter<'a, u16>>;
        type I16Iter = std::iter::Copied<std::slice::Iter<'a, i16>>;

        fn end_codes(self) -> Self::U16Iter {
            self.end_codes.iter().copied()
        }

        fn start_codes(self) -> Self::U16Iter {
            self.start_codes.iter().copied()
        }

        fn id_deltas(self) -> Self::I16Iter {
            self.id_deltas.iter().copied()
        }

        fn id_range_offsets(self) -> Self::U16Iter {
            self.id_range_offsets.iter().copied()
        }

        fn glyph_id_array_get(self, index: usize) -> Result<u16, ParseError> {
            self.glyph_id_array
                .get(index)
                .copied()
                .ok_or(ParseError::BadIndex)
        }
    }

    impl<'a> WriteBinary<Self> for Cmap {
        type Output = ();

        fn write<C: WriteContext>(ctxt: &mut C, table: Cmap) -> Result<(), WriteError> {
            let start = ctxt.bytes_written();
            U16Be::write(ctxt, 0u16)?; // version
            U16Be::write(ctxt, u16::try_from(table.encoding_records.len())?)?;

            // encoding records
            let mut offsets = Vec::with_capacity(table.encoding_records.len());
            for record in &table.encoding_records {
                U16Be::write(ctxt, record.platform_id.0)?;
                U16Be::write(ctxt, record.encoding_id.0)?;
                let offset = ctxt.placeholder::<U32Be, _>()?;
                offsets.push(offset);
            }

            // sub-tables
            for (record, placeholder) in table.encoding_records.into_iter().zip(offsets.into_iter())
            {
                let offset = u32::try_from(ctxt.bytes_written() - start)?;
                CmapSubtable::write(ctxt, record.sub_table)?;
                ctxt.write_placeholder(placeholder, offset)?;
            }

            Ok(())
        }
    }

    impl<'a> WriteBinary<Self> for CmapSubtable {
        type Output = ();

        fn write<C: WriteContext>(ctxt: &mut C, table: CmapSubtable) -> Result<(), WriteError> {
            match table {
                CmapSubtable::Format0 {
                    language,
                    glyph_id_array,
                } => {
                    U16Be::write(ctxt, 0u16)?; // format
                    U16Be::write(ctxt, u16::try_from(3 * size::U16 + glyph_id_array.len())?)?; // length
                    U16Be::write(ctxt, language)?;
                    ctxt.write_bytes(glyph_id_array.as_ref())?;
                }
                CmapSubtable::Format4(CmapSubtableFormat4 {
                    language,
                    end_codes,
                    start_codes,
                    id_deltas,
                    id_range_offsets,
                    glyph_id_array,
                }) => {
                    let start = ctxt.bytes_written();
                    let calc = Format4Calculator {
                        seg_count: u16::try_from(start_codes.len())?,
                    };

                    U16Be::write(ctxt, 4u16)?; // format
                    let length = ctxt.placeholder::<U16Be, _>()?;
                    U16Be::write(ctxt, language)?;
                    U16Be::write(ctxt, calc.seg_count_x2())?;
                    U16Be::write(ctxt, calc.search_range())?;
                    U16Be::write(ctxt, calc.entry_selector())?;
                    U16Be::write(ctxt, calc.range_shift())?;
                    ctxt.write_vec::<U16Be>(end_codes)?;
                    U16Be::write(ctxt, 0u16)?; // reserved_pad
                    ctxt.write_vec::<U16Be>(start_codes)?;
                    ctxt.write_vec::<I16Be>(id_deltas)?;
                    ctxt.write_vec::<U16Be>(id_range_offsets)?;
                    ctxt.write_vec::<U16Be>(glyph_id_array)?;
                    ctxt.write_placeholder(length, u16::try_from(ctxt.bytes_written() - start)?)?;
                }
                CmapSubtable::Format6 {
                    language,
                    first_code,
                    glyph_id_array,
                } => {
                    let start = ctxt.bytes_written();

                    U16Be::write(ctxt, 6u16)?; // format
                    let length = ctxt.placeholder::<U16Be, _>()?;
                    U16Be::write(ctxt, language)?;
                    U16Be::write(ctxt, first_code)?;
                    U16Be::write(ctxt, u16::try_from(glyph_id_array.len())?)?;
                    ctxt.write_vec::<U16Be>(glyph_id_array)?;
                    ctxt.write_placeholder(length, u16::try_from(ctxt.bytes_written() - start)?)?;
                }
                CmapSubtable::Format10 {
                    language,
                    start_char_code,
                    glyph_id_array,
                } => {
                    let start = ctxt.bytes_written();

                    U16Be::write(ctxt, 10u16)?; // format
                    U16Be::write(ctxt, 0u16)?; // reserved
                    let length = ctxt.placeholder::<U32Be, _>()?;
                    U32Be::write(ctxt, language)?;
                    U32Be::write(ctxt, start_char_code)?;
                    U32Be::write(ctxt, u32::try_from(glyph_id_array.len())?)?;
                    ctxt.write_vec::<U16Be>(glyph_id_array)?;
                    ctxt.write_placeholder(length, u32::try_from(ctxt.bytes_written() - start)?)?;
                }
                CmapSubtable::Format12(CmapSubtableFormat12 { language, groups }) => {
                    let start = ctxt.bytes_written();

                    U16Be::write(ctxt, 12u16)?; // format
                    U16Be::write(ctxt, 0u16)?; // reserved
                    let length = ctxt.placeholder::<U32Be, _>()?;
                    U32Be::write(ctxt, language)?;
                    U32Be::write(ctxt, u32::try_from(groups.len())?)?;
                    ctxt.write_vec::<SequentialMapGroup>(groups)?;
                    ctxt.write_placeholder(length, u32::try_from(ctxt.bytes_written() - start)?)?;
                }
            }

            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tables::{OpenTypeData, OpenTypeFont};
    use crate::tag;
    use crate::tests::read_fixture;
    use std::path::Path;

    #[test]
    fn test_calculator() {
        let calc = Format4Calculator { seg_count: 39 };
        assert_eq!(calc.seg_count_x2(), 78);
        assert_eq!(calc.search_range(), 64);
        assert_eq!(calc.entry_selector(), 5);
        assert_eq!(calc.range_shift(), 14);
    }

    #[test]
    fn offset_to_index_start() {
        let i = 0;
        let id_range_offset = 4;
        let start_code_offset = 0;
        let id_range_offsets_len = 2;

        let index = offset_to_index(i, id_range_offset, start_code_offset, id_range_offsets_len);
        assert_eq!(index, Ok(0));
    }

    #[test]
    fn offset_to_index_near_end() {
        let i = 0;
        let id_range_offset = 4;
        let start_code_offset = 222;
        let id_range_offsets_len = 2;

        let index = offset_to_index(i, id_range_offset, start_code_offset, id_range_offsets_len);
        assert_eq!(index, Ok(222));
    }

    fn with_cmap_subtable<P: AsRef<Path>>(
        path: P,
        platform: PlatformId,
        encoding: EncodingId,
        f: impl Fn(CmapSubtable<'_>),
    ) {
        let font_buffer = read_fixture(path);
        let opentype_file = ReadScope::new(&font_buffer)
            .read::<OpenTypeFont<'_>>()
            .unwrap();
        let ttf = match opentype_file.data {
            OpenTypeData::Single(offset_table) => offset_table,
            OpenTypeData::Collection(_) => panic!("expected a TTF font"),
        };
        let cmap = ttf
            .read_table(&opentype_file.scope, tag::CMAP)
            .unwrap()
            .unwrap()
            .read::<Cmap<'_>>()
            .unwrap();
        let encoding_record = cmap.find_subtable(platform, encoding).unwrap();
        let cmap_subtable = cmap
            .scope
            .offset(usize::try_from(encoding_record.offset).unwrap())
            .read::<CmapSubtable<'_>>()
            .unwrap();
        f(cmap_subtable);
    }

    #[test]
    fn test_mappings_format0() {
        with_cmap_subtable(
            "tests/fonts/opentype/TwitterColorEmoji-SVGinOT.ttf",
            PlatformId::MACINTOSH,
            EncodingId::MACINTOSH_APPLE_ROMAN,
            |cmap_subtable| {
                match cmap_subtable {
                    CmapSubtable::Format0 { .. } => {}
                    _ => {
                        panic!("expected CmapSubtable::Format0");
                    }
                };

                let mappings = cmap_subtable.mappings().unwrap();
                let copyright = cmap_subtable.map_glyph('©' as u32).unwrap().unwrap();
                assert_eq!(mappings[&copyright], '©' as u32);
            },
        );
    }

    #[test]
    #[cfg(feature = "prince")]
    fn test_mappings_format2() {
        with_cmap_subtable(
            "../../../tests/data/fonts/HardGothicNormal.ttf",
            PlatformId::WINDOWS,
            EncodingId::WINDOWS_BIG5,
            |cmap_subtable| {
                if !matches!(cmap_subtable, CmapSubtable::Format2 { .. }) {
                    panic!("expected CmapSubtable::Format2");
                }

                let mappings = cmap_subtable.mappings().unwrap();
                // This would be a good place for non-ASCII idents when we're on 1.53 or newer
                // let 世 = cmap_subtable.map_glyph(12).unwrap().unwrap(); // 世 U+4E16
                // let 丈 = cmap_subtable.map_glyph(6).unwrap().unwrap(); // 丈 U+4E08
                let a = cmap_subtable.map_glyph(13).unwrap().unwrap(); // 丕 U+4E15
                let b = cmap_subtable.map_glyph(44).unwrap().unwrap(); // 乾 U+4E7E
                assert_eq!(mappings[&a], 13);
                assert_eq!(mappings[&b], 44);
            },
        );
    }

    #[test]
    #[cfg(feature = "prince")]
    fn test_mappings_format2_chao_yan_ze_cu_hei_tif() {
        with_cmap_subtable(
            "../../../tests/data/fonts/big5/ChaoYanZeCuHeiTif-1.ttf",
            PlatformId::WINDOWS,
            EncodingId::WINDOWS_BIG5,
            |cmap_subtable| {
                if !matches!(cmap_subtable, CmapSubtable::Format2 { .. }) {
                    panic!("expected CmapSubtable::Format2");
                }

                // This is checking that one and two-byte characters work as well as certain
                // entries that should not be present are absent (E.g. 0x220). This test was
                // added after `mappings_fn` for cmap format 2 was written. Prior to the change
                // many entries (such as 0x220) were included that should not have been.
                let mappings = cmap_subtable.mappings().unwrap();
                assert_eq!(mappings[&85], 0x54);
                assert_eq!(mappings[&461], 0xA26F);
                assert!(mappings.values().find(|&&ch| ch == 0x220).is_none());
            },
        );
    }

    #[test]
    fn test_mappings_format4() {
        with_cmap_subtable(
            "tests/fonts/opentype/TwitterColorEmoji-SVGinOT.ttf",
            PlatformId::UNICODE,
            EncodingId(3),
            |cmap_subtable| {
                match cmap_subtable {
                    CmapSubtable::Format4 { .. } => {}
                    _ => {
                        panic!("expected CmapSubtable::Format4");
                    }
                };

                let mappings = cmap_subtable.mappings().unwrap();
                // Format 4 can only represent 16-bit chars (Basic Multilingual Plane)
                let soccer_ball = cmap_subtable.map_glyph('⚽' as u32).unwrap().unwrap();
                let double_exclamation = cmap_subtable.map_glyph('‼' as u32).unwrap().unwrap();
                assert_eq!(mappings[&soccer_ball], '⚽' as u32);
                assert_eq!(mappings[&double_exclamation], '‼' as u32);
            },
        );
    }

    #[test]
    fn test_mappings_format6() {
        with_cmap_subtable(
            "tests/fonts/opentype/Klei.otf",
            PlatformId::MACINTOSH,
            EncodingId::MACINTOSH_APPLE_ROMAN,
            |cmap_subtable| {
                match cmap_subtable {
                    CmapSubtable::Format6 { .. } => {}
                    _ => {
                        panic!("expected CmapSubtable::Format6");
                    }
                };

                let mappings = cmap_subtable.mappings().unwrap();
                let a = cmap_subtable.map_glyph('a' as u32).unwrap().unwrap();
                let caron = cmap_subtable.map_glyph(255).unwrap().unwrap();
                assert_eq!(mappings[&a], 'a' as u32);
                assert_eq!(mappings[&caron], 255);
            },
        );
    }

    #[test]
    fn test_mappings_format12() {
        with_cmap_subtable(
            "tests/fonts/opentype/TwitterColorEmoji-SVGinOT.ttf",
            PlatformId::WINDOWS,
            EncodingId::WINDOWS_UNICODE_UCS4,
            |cmap_subtable| {
                match cmap_subtable {
                    CmapSubtable::Format12 { .. } => {}
                    _ => {
                        panic!("expected CmapSubtable::Format12");
                    }
                };

                let mappings = cmap_subtable.mappings().unwrap();
                // Format 12 uses 32-bit chars so can map all of Unicode
                let dove = cmap_subtable.map_glyph('🕊' as u32).unwrap().unwrap();
                let nerd_face = cmap_subtable.map_glyph('🤓' as u32).unwrap().unwrap();
                assert_eq!(mappings[&dove], '🕊' as u32);
                assert_eq!(mappings[&nerd_face], '🤓' as u32);
            },
        );
    }
}