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
#![deny(missing_docs)]

//! Bitmap fonts in `EBLC`/`EBDT` and `CBLC`/`CBDT` tables.

use core::convert::TryFrom;
use core::fmt;
use alloc::vec::Vec;
use alloc::boxed::Box;

use bitreader::{BitReader, BitReaderError};

use super::BitDepth;
use crate::binary::read::{
    CheckIndex, ReadArray, ReadBinary, ReadBinaryDep, ReadCtxt, ReadFixedSizeDep, ReadFrom,
    ReadScope,
};
use crate::binary::{U16Be, U32Be, I8, U8};
use crate::bitmap::{
    Bitmap, BitmapGlyph, BitmapMetrics, EmbeddedBitmap, EmbeddedMetrics, EncapsulatedBitmap,
    EncapsulatedFormat, Metrics,
};
use crate::error::ParseError;
use crate::size;

/// Flag in `BitmapInfo` `flags` indicating the direction of small glyph metrics is horizontal.
///
/// https://docs.microsoft.com/en-us/typography/opentype/spec/eblc#bitmap-flags
const HORIZONTAL_METRICS: i8 = 1;

/// Flag in `BitmapInfo` `flags` indicating the direction of small glyph metrics is vertical.
///
/// https://docs.microsoft.com/en-us/typography/opentype/spec/eblc#bitmap-flags
const VERTICAL_METRICS: i8 = 2;

/// `CBLC` — Color Bitmap Location Table
pub struct CBLCTable<'a> {
    /// Major version of this table.
    ///
    /// 2 for `EBLC`, 3, for `CBLC`
    pub major_version: u16,
    /// Minor version of this table.
    pub minor_version: u16,
    /// Array of "strikes" available for this font.
    pub bitmap_sizes: Vec<BitmapSize<'a>>,
}

/// A description of a "strike" of bitmap data.
pub struct BitmapSize<'a> {
    /// Bitmap information.
    pub inner: BitmapInfo,
    /// Index sub-table records.
    index_sub_table_records: ReadArray<'a, IndexSubTableRecord>,
    /// Index sub-tables, one for each record.
    index_sub_tables: Vec<IndexSubTable<'a>>,
}

#[allow(missing_docs)]
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SbitLineMetrics {
    pub ascender: i8,
    pub descender: i8,
    pub width_max: u8,
    pub caret_slope_numerator: i8,
    pub caret_slope_denominator: i8,
    pub caret_offset: i8,
    pub min_origin_sb: i8,
    pub min_advance_sb: i8,
    pub max_before_bl: i8,
    pub min_after_bl: i8,
    pub pad1: i8,
    pub pad2: i8,
}

/// Subset of BitmapSize that includes common fields.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct BitmapInfo {
    /// Line metrics for text rendered horizontally.
    pub hori: SbitLineMetrics,
    /// Line metrics for text rendered vertically.
    pub vert: SbitLineMetrics,
    /// Lowest glyph index for this size.
    pub start_glyph_index: u16,
    /// Highest glyph index for this size.
    pub end_glyph_index: u16,
    /// Horizontal pixels per em.
    pub ppem_x: u8,
    /// Vertical pixels per em.
    pub ppem_y: u8,
    /// Bit depth.
    ///
    /// In addition to already defined bitDepth values 1, 2, 4, and 8 supported by `EBDT` the value
    /// of 32 is used to identify color bitmaps with 8 bit per channel RGBA channels in `CBDT`.
    pub bit_depth: BitDepth,
    /// Vertical or horizontal.
    pub flags: i8,
}

/// Sub table record of `BitmapSize` describing a range of glyphs and the location of the sub
/// table.
struct IndexSubTableRecord {
    /// First glyph ID of this range.
    pub first_glyph_index: u16,
    /// Last glyph ID of this range (inclusive).
    pub last_glyph_index: u16,
    // Add to indexSubTableArrayOffset to get offset from beginning of EBLC.
    additional_offset_to_index_sub_table: u32,
}

/// An index sub table of a `BitmapSize` describing the image format and location.
///
/// The `IndexSubTable` provides the offset within `CBDT` where the bitmap data for a range of
/// glyphs (described by `IndexSubTableRecord`) can be found, optionally with metrics for the whole
/// range of glyphs as well, depending on the format.
enum IndexSubTable<'a> {
    /// IndexSubTable1: variable-metrics glyphs with 4-byte offsets.
    Format1 {
        /// Format of EBDT image data.
        image_format: ImageFormat,
        /// Offset to image data in EBDT table.
        image_data_offset: u32,
        /// Offsets into `EBDT` for bitmap data.
        ///
        /// The actual offset for a glyph is `image_data_offset` + the value read from this
        /// array.
        offsets: ReadArray<'a, U32Be>,
    },
    /// IndexSubTable2: all glyphs have identical metrics.
    Format2 {
        /// Format of EBDT image data.
        image_format: ImageFormat,
        /// Offset to image data in EBDT table.
        image_data_offset: u32,
        /// The size of the data for each bitmap.
        image_size: u32,
        /// Metrics for all glyphs in this range.
        big_metrics: BigGlyphMetrics,
    },
    /// IndexSubTable3: variable-metrics glyphs with 2-byte offsets.
    Format3 {
        /// Format of EBDT image data.
        image_format: ImageFormat,
        /// Offset to image data in EBDT table.
        image_data_offset: u32,
        /// Offsets into `EBDT` for bitmap data.
        ///
        /// The actual offset for a glyph is `image_data_offset` + the value read from this
        /// array.
        offsets: ReadArray<'a, U16Be>,
    },
    /// IndexSubTable4: variable-metrics glyphs with sparse glyph codes.
    Format4 {
        /// Format of EBDT image data.
        image_format: ImageFormat,
        /// Offset to image data in EBDT table.
        image_data_offset: u32,
        /// Array of ranges.
        glyph_array: ReadArray<'a, GlyphOffsetPair>,
    },
    /// IndexSubTable5: constant-metrics glyphs with sparse glyph codes.
    Format5 {
        /// Format of EBDT image data.
        image_format: ImageFormat,
        /// Offset to image data in EBDT table.
        image_data_offset: u32,
        /// All glyphs have the same data size.
        image_size: u32,
        /// All glyphs have the same metrics.
        big_metrics: BigGlyphMetrics,
        /// One per glyph, sorted by glyph ID.
        glyph_id_array: ReadArray<'a, U16Be>,
    },
}

/// Valid image formats
#[allow(missing_docs)]
#[derive(Copy, Clone)]
pub enum ImageFormat {
    Format1,
    Format2,
    Format5,
    Format6,
    Format7,
    Format8,
    Format9,
    Format17,
    Format18,
    Format19,
}

#[allow(missing_docs)]
#[derive(Debug, Copy, Clone)]
pub struct SmallGlyphMetrics {
    pub height: u8,
    pub width: u8,
    pub bearing_x: i8,
    pub bearing_y: i8,
    pub advance: u8,
}

#[allow(missing_docs)]
#[derive(Debug, Copy, Clone)]
pub struct BigGlyphMetrics {
    pub height: u8,
    pub width: u8,
    pub hori_bearing_x: i8,
    pub hori_bearing_y: i8,
    pub hori_advance: u8,
    pub vert_bearing_x: i8,
    pub vert_bearing_y: i8,
    pub vert_advance: u8,
}

/// The direction of small glyph metrics when present.
enum MetricsDirection {
    Horizontal,
    Vertical,
    Unknown,
}

/// Record indicating the offset in `EBDT` for a specific glyph id.
struct GlyphOffsetPair {
    /// Glyph ID of glyph present.
    pub glyph_id: u16,
    /// Location in EBDT.
    pub offset: u16,
}

/// `CBDT` — Color Bitmap Data Table
pub struct CBDTTable<'a> {
    /// Major version of this table.
    ///
    /// 2 for `EBDT`, 3, for `CBDT`
    pub major_version: u16,
    /// Minor version of this table.
    pub minor_version: u16,
    /// The raw data of the whole `CBDT` table.
    data: ReadScope<'a>,
}

/// Record corresponding to data read from `CBDT`.
pub enum GlyphBitmapData<'a> {
    /// Format 1: small metrics, byte-aligned data.
    Format1 {
        /// Metrics information for the glyph.
        small_metrics: SmallGlyphMetrics,
        /// Byte-aligned bitmap data.
        data: &'a [u8],
    },
    /// Format 2: small metrics, bit-aligned data.
    Format2 {
        /// Metrics information for the glyph.
        small_metrics: SmallGlyphMetrics,
        /// Bit-aligned bitmap data.
        data: &'a [u8],
    },
    // Format3 (obsolete, not in OpenType spec)
    // Format4 (not supported by OpenType, Apple specific)
    /// Format 5: metrics in EBLC, bit-aligned image data only.
    Format5 {
        /// Metrics information for the glyph.
        big_metrics: BigGlyphMetrics,
        /// Bit-aligned bitmap data.
        data: &'a [u8],
    },
    /// Format 6: big metrics, byte-aligned data.
    Format6 {
        /// Metrics information for the glyph.
        big_metrics: BigGlyphMetrics,
        /// Byte-aligned bitmap data.
        data: &'a [u8],
    },
    /// Format7: big metrics, bit-aligned data.
    Format7 {
        /// Metrics information for the glyph.
        big_metrics: BigGlyphMetrics,
        /// Bit-aligned bitmap data.
        data: &'a [u8],
    },
    /// Format 8: small metrics, component data.
    Format8 {
        /// Metrics information for the glyph.
        small_metrics: SmallGlyphMetrics,
        /// Array of EbdtComponent records.
        components: ReadArray<'a, EbdtComponent>,
    },
    /// Format 9: big metrics, component data.
    Format9 {
        /// Metrics information for the glyph.
        big_metrics: BigGlyphMetrics,
        /// Array of EbdtComponent records.
        components: ReadArray<'a, EbdtComponent>,
    },
    // 10-16 are not defined
    /// Format 17: small metrics, PNG image data.
    Format17 {
        /// Metrics information for the glyph.
        small_metrics: SmallGlyphMetrics,
        /// Raw PNG data
        data: &'a [u8],
    },
    /// Format 18: big metrics, PNG image data.
    Format18 {
        /// Metrics information for the glyph.
        big_metrics: BigGlyphMetrics,
        /// Raw PNG data
        data: &'a [u8],
    },
    /// Format 19: metrics in CBLC table, PNG image data.
    Format19 {
        /// Metrics information for the glyph.
        big_metrics: BigGlyphMetrics,
        /// Raw PNG data
        data: &'a [u8],
    },
}

/// The EbdtComponent record is used in glyph bitmap data formats 8 and 9.
pub struct EbdtComponent {
    /// Component glyph ID
    pub glyph_id: u16,
    /// Position of component left
    pub x_offset: i8,
    /// Position of component top
    pub y_offset: i8,
}

/// Result of `find_strike`.
pub struct MatchingStrike<'a, 'b> {
    pub(crate) bitmap_size: &'a BitmapSize<'b>,
    index_subtable_index: usize,
}

/// Lookup a glyph in the supplied strike.
///
/// * `glyph_id` is the glyph to lookup.
/// * `matching_strike` the strike to lookup the bitmap in. Acquired via
///   [find_strike](./struct.CBLCTable.html#method.find_strike).
/// * `cbdt` is a reference to the colour bitmap data table.
///
/// The returned `GlyphBitmapData` contains metrics and data for the bitmap, if found.
///
/// **Note:** that some fonts may contain bitmaps with `0x0` dimensions, so be prepared to handle
/// those.
pub fn lookup<'a, 'b>(
    glyph_id: u16,
    matching_strike: &MatchingStrike<'_, '_>,
    cbdt: &CBDTTable<'b>,
) -> Result<Option<GlyphBitmapData<'b>>, ParseError> {
    let index_sub_table_header: &IndexSubTableRecord = &matching_strike
        .bitmap_size
        .index_sub_table_records
        .get_item(matching_strike.index_subtable_index);
    match &matching_strike.bitmap_size.index_sub_tables[matching_strike.index_subtable_index] {
        IndexSubTable::Format1 {
            image_format,
            image_data_offset,
            offsets,
        } => {
            // Should not underflow because find_strike picked a strike that contains this glyph
            let glyph_index = usize::from(glyph_id - index_sub_table_header.first_glyph_index);
            offsets.check_index(glyph_index + 1)?;
            let start = usize::try_from(offsets.get_item(glyph_index))?;
            let end = usize::try_from(offsets.get_item(glyph_index + 1))?;
            let length = end - start;

            if length == 0 {
                // A small number of missing glyphs can be efficiently represented in formats 1 or
                // 3 by having the offset for the missing glyph be followed by the same offset for
                // the next glyph, thus indicating a data size of zero.
                return Ok(None);
            }

            let offset = usize::try_from(*image_data_offset)? + start;
            let mut ctxt = cbdt.data.offset_length(offset, length)?.ctxt();
            let bitmap = ctxt.read_dep::<ImageFormat>((*image_format, None))?;
            Ok(Some(bitmap))
        }
        IndexSubTable::Format2 {
            image_format,
            image_data_offset,
            image_size,
            big_metrics,
        } => {
            let glyph_index = u32::from(glyph_id - index_sub_table_header.first_glyph_index);
            let offset = usize::try_from(image_data_offset + (glyph_index * image_size))?;
            let mut ctxt = cbdt
                .data
                .offset_length(offset, usize::try_from(*image_size)?)?
                .ctxt();
            let bitmap = ctxt.read_dep::<ImageFormat>((*image_format, Some(*big_metrics)))?;
            Ok(Some(bitmap))
        }
        IndexSubTable::Format3 {
            image_format,
            image_data_offset,
            offsets,
        } => {
            // Should not underflow because find_strike picked a strike that contains this glyph
            let glyph_index = usize::from(glyph_id - index_sub_table_header.first_glyph_index);
            offsets.check_index(glyph_index + 1)?;
            let start = usize::from(offsets.get_item(glyph_index));
            let end = usize::from(offsets.get_item(glyph_index + 1));
            let length = end - start;

            if length == 0 {
                // A small number of missing glyphs can be efficiently represented in formats 1 or
                // 3 by having the offset for the missing glyph be followed by the same offset for
                // the next glyph, thus indicating a data size of zero.
                return Ok(None);
            }

            let offset = usize::try_from(*image_data_offset)? + start;
            let mut ctxt = cbdt.data.offset_length(offset, length)?.ctxt();
            let bitmap = ctxt.read_dep::<ImageFormat>((*image_format, None))?;
            Ok(Some(bitmap))
        }
        IndexSubTable::Format4 {
            image_format,
            image_data_offset,
            glyph_array,
        } => {
            // Try to find the desired glyph in the offset pairs
            for (glyph_index, glyph_offset_pair) in glyph_array.iter().enumerate() {
                if glyph_offset_pair.glyph_id == glyph_id {
                    let offset = usize::try_from(*image_data_offset)?
                        + usize::from(glyph_offset_pair.offset);

                    // Get the next pair to determine how big the image data for this glyph is
                    glyph_array.check_index(glyph_index + 1)?;
                    let end = glyph_array.get_item(glyph_index + 1);
                    let length = usize::from(end.offset - glyph_offset_pair.offset);
                    let mut ctxt = cbdt.data.offset_length(offset, length)?.ctxt();
                    let bitmap = ctxt.read_dep::<ImageFormat>((*image_format, None))?;
                    return Ok(Some(bitmap));
                } else if glyph_offset_pair.glyph_id > glyph_id {
                    // Pairs are supposed to be ordered by glyph id so if we're past the one we're
                    // looking for it won't be found.
                    return Ok(None);
                }
            }

            Ok(None)
        }
        IndexSubTable::Format5 {
            image_format,
            image_data_offset,
            image_size,
            big_metrics,
            glyph_id_array,
        } => {
            // Try to find the desired glyph in the list of glyphs covered by this index
            for (glyph_index, this_glyph_id) in glyph_id_array.iter().enumerate() {
                if this_glyph_id == glyph_id {
                    // Found
                    // cast is safe because glyph_id_array num_glyphs is a u32
                    let offset =
                        usize::try_from(image_data_offset + (glyph_index as u32 * image_size))?;
                    let mut ctxt = cbdt
                        .data
                        .offset_length(offset, usize::try_from(*image_size)?)?
                        .ctxt();
                    let bitmap =
                        ctxt.read_dep::<ImageFormat>((*image_format, Some(*big_metrics)))?;
                    return Ok(Some(bitmap));
                } else if this_glyph_id > glyph_id {
                    // Array is meant to be ordered by glyph id so if we're past the one we're
                    // looking for it won't be found.
                    return Ok(None);
                }
            }

            Ok(None)
        }
    }
}

impl<'a> ReadBinaryDep<'a> for ImageFormat {
    type Args = (ImageFormat, Option<BigGlyphMetrics>);
    type HostType = GlyphBitmapData<'a>;

    fn read_dep(
        ctxt: &mut ReadCtxt<'a>,
        (format, metrics): Self::Args,
    ) -> Result<Self::HostType, ParseError> {
        match format {
            ImageFormat::Format1 => {
                let small_metrics = ctxt.read::<SmallGlyphMetrics>()?;
                let data = ctxt.scope().data();

                Ok(GlyphBitmapData::Format1 {
                    small_metrics,
                    data,
                })
            }
            ImageFormat::Format2 => {
                let small_metrics = ctxt.read::<SmallGlyphMetrics>()?;
                let data = ctxt.scope().data();

                Ok(GlyphBitmapData::Format2 {
                    small_metrics,
                    data,
                })
            }
            ImageFormat::Format5 => Ok(GlyphBitmapData::Format5 {
                big_metrics: metrics.ok_or(ParseError::MissingValue)?,
                data: ctxt.scope().data(),
            }),
            ImageFormat::Format6 => {
                let big_metrics = ctxt.read::<BigGlyphMetrics>()?;
                let data = ctxt.scope().data();

                Ok(GlyphBitmapData::Format6 { big_metrics, data })
            }
            ImageFormat::Format7 => {
                let big_metrics = ctxt.read::<BigGlyphMetrics>()?;
                let data = ctxt.scope().data();

                Ok(GlyphBitmapData::Format7 { big_metrics, data })
            }
            ImageFormat::Format8 => {
                let small_metrics = ctxt.read::<SmallGlyphMetrics>()?;
                let _pad = ctxt.read_u8()?;
                let num_components = usize::from(ctxt.read_u16be()?);
                let components = ctxt.read_array::<EbdtComponent>(num_components)?;

                Ok(GlyphBitmapData::Format8 {
                    small_metrics,
                    components,
                })
            }
            ImageFormat::Format9 => {
                let big_metrics = ctxt.read::<BigGlyphMetrics>()?;
                let num_components = usize::from(ctxt.read_u16be()?);
                let components = ctxt.read_array::<EbdtComponent>(num_components)?;

                Ok(GlyphBitmapData::Format9 {
                    big_metrics,
                    components,
                })
            }
            ImageFormat::Format17 => {
                let small_metrics = ctxt.read::<SmallGlyphMetrics>()?;
                let data_len = usize::try_from(ctxt.read_u32be()?)?;
                let data = ctxt.read_slice(data_len)?;

                Ok(GlyphBitmapData::Format17 {
                    small_metrics,
                    data,
                })
            }
            ImageFormat::Format18 => {
                let big_metrics = ctxt.read::<BigGlyphMetrics>()?;
                let data_len = usize::try_from(ctxt.read_u32be()?)?;
                let data = ctxt.read_slice(data_len)?;

                Ok(GlyphBitmapData::Format18 { big_metrics, data })
            }
            ImageFormat::Format19 => {
                let data_len = usize::try_from(ctxt.read_u32be()?)?;
                let data = ctxt.read_slice(data_len)?;

                Ok(GlyphBitmapData::Format19 {
                    big_metrics: metrics.ok_or(ParseError::MissingValue)?,
                    data,
                })
            }
        }
    }
}

impl<'a> CBLCTable<'a> {
    /// Find a strike matching the supplied criteria.
    ///
    /// * `glyph_id` is the glyph to lookup.
    /// * `target_ppem` is the desired size. If an exact match can't be found the nearest one will
    ///    be returned, favouring being oversize vs. undersized.
    /// * `max_bit_depth` is the maximum accepted bit depth of the bitmap to return. If you accept
    ///   all bit depths then use `BitDepth::ThirtyTwo`.
    pub fn find_strike(
        &self,
        glyph_id: u16,
        target_ppem: u8,
        max_bit_depth: BitDepth,
    ) -> Option<MatchingStrike<'_, 'a>> {
        // Find a strike that contains the glyph we want, then find one with an appropriate size
        let candidates = self.bitmap_sizes.iter().filter_map(|bitmap_size| {
            bitmap_size
                .index_sub_table_index(glyph_id)
                .and_then(|index| {
                    if bitmap_size.inner.bit_depth <= max_bit_depth {
                        Some((bitmap_size, index))
                    } else {
                        // Strike has higher bit depth than max_bit_depth
                        None
                    }
                })
        });

        // Pick a candidate that maximises size and bit depth according to `size_ppem` and `max_bit_depth`.
        let size_ppem = i16::from(target_ppem);
        let mut best: Option<(i16, &BitmapSize<'a>, usize)> = None;

        for (bitmap_size, index) in candidates {
            let difference = i16::from(bitmap_size.inner.ppem_x) - size_ppem;
            match best {
                Some((current_best_difference, current_best_bitmap_size, _))
                    if same_size_higher_bit_depth(
                        difference,
                        current_best_difference,
                        bitmap_size.inner.bit_depth,
                        current_best_bitmap_size.inner.bit_depth,
                    ) =>
                {
                    best = Some((difference, bitmap_size, index))
                }
                Some((current_best_difference, _, _))
                    if super::bigger_or_closer_to_zero(difference, current_best_difference) =>
                {
                    best = Some((difference, bitmap_size, index))
                }
                None => best = Some((difference, bitmap_size, index)),
                _ => (),
            }
        }

        best.map(|(_, bitmap_size, index)| MatchingStrike {
            bitmap_size,
            index_subtable_index: index,
        })
    }
}

fn same_size_higher_bit_depth(
    difference: i16,
    current_best_difference: i16,
    candiate_bit_depth: BitDepth,
    current_best_bit_depth: BitDepth,
) -> bool {
    difference == current_best_difference && candiate_bit_depth > current_best_bit_depth
}

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

    fn read(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
        let table = ctxt.scope();

        let major_version = ctxt.read_u16be()?;
        // version 2 is EBLT, version 3 is CBLC, 3 is backward compatible but defines additional
        // formats and bit depth.
        ctxt.check_version(major_version >= 2 && major_version <= 3)?;
        let minor_version = ctxt.read_u16be()?;
        let num_sizes = ctxt.read_u32be()?;
        let bitmap_sizes = ctxt
            .read_array_dep::<BitmapSize<'_>>(usize::try_from(num_sizes)?, table)?
            .iter_res()
            .collect::<Result<Vec<_>, _>>()?;

        Ok(CBLCTable {
            major_version,
            minor_version,
            bitmap_sizes,
        })
    }
}

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

    fn read(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
        // The locators in the CBLC table are relative to the start of the CBDT table.
        // So we hold on to a scope at the start of the table for later use.
        let data = ctxt.scope();
        let major_version = ctxt.read_u16be()?;
        // version 2 is EBLT, version 3 is CBLC, 3 is backward compatible but defines additional
        // formats and bit depth.
        ctxt.check_version(major_version >= 2 && major_version <= 3)?;
        let minor_version = ctxt.read_u16be()?;
        Ok(CBDTTable {
            major_version,
            minor_version,
            data,
        })
    }
}

impl<'a> BitmapSize<'a> {
    /// Returns the index of the index sub table for the supplied glyph, if found.
    fn index_sub_table_index(&self, glyph_id: u16) -> Option<usize> {
        // The startGlyphIndex and endGlyphIndex describe the minimum and maximum glyph IDs in the
        // strike, but a strike does not necessarily contain bitmaps for all glyph IDs in this
        // range. The IndexSubTables determine which glyphs are actually present in the CBDT table.
        // https://docs.microsoft.com/en-us/typography/opentype/spec/eblc#sbitlinemetrics
        if (self.inner.start_glyph_index..=self.inner.end_glyph_index).contains(&glyph_id) {
            self.index_sub_table_records
                .iter()
                .position(|record| record.contains_glyph(glyph_id))
        } else {
            None
        }
    }
}

impl<'a, 'b> MatchingStrike<'a, 'b> {
    /// Returns the bit depth of this `MatchingStrike`.
    pub fn bit_depth(&self) -> BitDepth {
        self.bitmap_size.inner.bit_depth
    }
}

impl<'a> ReadBinaryDep<'a> for BitmapSize<'a> {
    type Args = ReadScope<'a>;
    type HostType = Self;

    fn read_dep(ctxt: &mut ReadCtxt<'a>, cblc_scope: Self::Args) -> Result<Self, ParseError> {
        let index_sub_table_array_offset = usize::try_from(ctxt.read_u32be()?)?;
        let _index_tables_size = ctxt.read_u32be()?;
        let number_of_index_sub_tables = ctxt.read_u32be()?;
        let _color_ref = ctxt.read_u32be()?; // Not used; set to 0.
        let hori = ctxt.read::<SbitLineMetrics>()?;
        let vert = ctxt.read::<SbitLineMetrics>()?;
        let start_glyph_index = ctxt.read_u16be()?;
        let end_glyph_index = ctxt.read_u16be()?;
        let ppem_x = ctxt.read_u8()?;
        let ppem_y = ctxt.read_u8()?;
        let bit_depth = BitDepth::try_from(ctxt.read_u8()?)?;
        let flags = ctxt.read_i8()?;

        // Read the index sub tables
        let index_sub_table_records: ReadArray<'_, IndexSubTableRecord> = cblc_scope
            .offset(index_sub_table_array_offset)
            .ctxt()
            .read_array::<IndexSubTableRecord>(usize::try_from(number_of_index_sub_tables)?)?;
        let mut index_sub_tables = Vec::with_capacity(usize::try_from(number_of_index_sub_tables)?);
        for index_sub_table_record in index_sub_table_records.iter() {
            let offset = index_sub_table_array_offset
                .checked_add(usize::try_from(
                    index_sub_table_record.additional_offset_to_index_sub_table,
                )?)
                .ok_or(ParseError::BadOffset)?;
            // Read the index sub table
            let index_sub_table = cblc_scope
                .offset(offset)
                .ctxt()
                .read_dep::<IndexSubTable<'_>>((
                    index_sub_table_record.first_glyph_index,
                    index_sub_table_record.last_glyph_index,
                ))?;
            index_sub_tables.push(index_sub_table);
        }

        Ok(BitmapSize {
            inner: BitmapInfo {
                hori,
                vert,
                start_glyph_index,
                end_glyph_index,
                ppem_x,
                ppem_y,
                bit_depth,
                flags,
            },
            index_sub_table_records,
            index_sub_tables,
        })
    }
}

impl<'a> ReadFixedSizeDep<'a> for BitmapSize<'a> {
    fn size(_: Self::Args) -> usize {
        // Offset32         indexSubTableArrayOffset
        // uint32           indexTablesSize
        // uint32           numberofIndexSubTables
        // uint32           colorRef
        (4 * size::U32)
        // SbitLineMetrics  hori
        // SbitLineMetrics  vert
        + (2 * SbitLineMetrics::size(()))
        // uint16           startGlyphIndex
        // uint16           endGlyphIndex
        + (2 * size::U16)
        // uint8            ppemX
        // uint8            ppemY
        // uint8            bitDepth
        // int8             flags
        + 4
    }
}

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

    fn read(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
        let ascender = ctxt.read_i8()?;
        let descender = ctxt.read_i8()?;
        let width_max = ctxt.read_u8()?;
        let caret_slope_numerator = ctxt.read_i8()?;
        let caret_slope_denominator = ctxt.read_i8()?;
        let caret_offset = ctxt.read_i8()?;
        let min_origin_sb = ctxt.read_i8()?;
        let min_advance_sb = ctxt.read_i8()?;
        let max_before_bl = ctxt.read_i8()?;
        let min_after_bl = ctxt.read_i8()?;
        let pad1 = ctxt.read_i8()?;
        let pad2 = ctxt.read_i8()?;

        Ok(SbitLineMetrics {
            ascender,
            descender,
            width_max,
            caret_slope_numerator,
            caret_slope_denominator,
            caret_offset,
            min_origin_sb,
            min_advance_sb,
            max_before_bl,
            min_after_bl,
            pad1,
            pad2,
        })
    }
}

impl<'a> ReadFixedSizeDep<'a> for SbitLineMetrics {
    fn size(_scope: Self::Args) -> usize {
        // 12 fields, all 1 byte
        12
    }
}

impl TryFrom<u8> for BitDepth {
    type Error = ParseError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            1 => Ok(BitDepth::One),
            2 => Ok(BitDepth::Two),
            4 => Ok(BitDepth::Four),
            8 => Ok(BitDepth::Eight),
            32 => Ok(BitDepth::ThirtyTwo),
            _ => Err(ParseError::BadValue),
        }
    }
}

impl<'a> IndexSubTableRecord {
    fn contains_glyph(&self, glyph_id: u16) -> bool {
        (self.first_glyph_index..=self.last_glyph_index).contains(&glyph_id)
    }
}

impl<'a> ReadFrom<'a> for IndexSubTableRecord {
    type ReadType = (U16Be, U16Be, U32Be);

    fn from(
        (first_glyph_index, last_glyph_index, additional_offset_to_index_sub_table): (
            u16,
            u16,
            u32,
        ),
    ) -> Self {
        IndexSubTableRecord {
            first_glyph_index,
            last_glyph_index,
            additional_offset_to_index_sub_table,
        }
    }
}

impl<'a> ReadBinaryDep<'a> for IndexSubTable<'a> {
    type Args = (u16, u16);
    type HostType = Self;

    fn read_dep(
        ctxt: &mut ReadCtxt<'a>,
        (first_glyph_index, last_glyph_index): (u16, u16),
    ) -> Result<Self, ParseError> {
        let index_format = ctxt.read_u16be()?;
        let image_format = ImageFormat::try_from(ctxt.read_u16be()?)?;
        let image_data_offset = ctxt.read_u32be()?;

        match index_format {
            1 => {
                // +1 for last_glyph_index being inclusive,
                // +1 for there being an extra record at the end
                let offsets = ctxt.read_array::<U32Be>(usize::from(
                    last_glyph_index - first_glyph_index + 1 + 1,
                ))?;
                Ok(IndexSubTable::Format1 {
                    image_format,
                    image_data_offset,
                    offsets,
                })
            }
            2 => {
                let image_size = ctxt.read_u32be()?;
                let big_metrics = ctxt.read::<BigGlyphMetrics>()?;
                Ok(IndexSubTable::Format2 {
                    image_format,
                    image_data_offset,
                    image_size,
                    big_metrics,
                })
            }
            3 => {
                // +1 for last_glyph_index being inclusive,
                // +1 for there being an extra record at the end
                let offsets = ctxt.read_array::<U16Be>(usize::from(
                    last_glyph_index - first_glyph_index + 1 + 1,
                ))?;
                Ok(IndexSubTable::Format3 {
                    image_format,
                    image_data_offset,
                    offsets,
                })
            }
            4 => {
                let num_glyphs = ctxt.read_u32be()?;
                let glyph_array =
                    ctxt.read_array::<GlyphOffsetPair>(usize::try_from(num_glyphs + 1)?)?;
                Ok(IndexSubTable::Format4 {
                    image_format,
                    image_data_offset,
                    glyph_array,
                })
            }
            5 => {
                let image_size = ctxt.read_u32be()?;
                let big_metrics = ctxt.read::<BigGlyphMetrics>()?;
                let num_glyphs = ctxt.read_u32be()?;
                let glyph_id_array = ctxt.read_array::<U16Be>(usize::try_from(num_glyphs)?)?;
                Ok(IndexSubTable::Format5 {
                    image_format,
                    image_data_offset,
                    image_size,
                    big_metrics,
                    glyph_id_array,
                })
            }
            _ => Err(ParseError::BadValue),
        }
    }
}

impl<'a> ReadFrom<'a> for SmallGlyphMetrics {
    type ReadType = ((U8, U8), (I8, I8, U8));

    fn from(((height, width), (bearing_x, bearing_y, advance)): ((u8, u8), (i8, i8, u8))) -> Self {
        SmallGlyphMetrics {
            height,
            width,
            bearing_x,
            bearing_y,
            advance,
        }
    }
}

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

    fn read(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
        let height = ctxt.read_u8()?;
        let width = ctxt.read_u8()?;
        let hori_bearing_x = ctxt.read_i8()?;
        let hori_bearing_y = ctxt.read_i8()?;
        let hori_advance = ctxt.read_u8()?;
        let vert_bearing_x = ctxt.read_i8()?;
        let vert_bearing_y = ctxt.read_i8()?;
        let vert_advance = ctxt.read_u8()?;

        Ok(BigGlyphMetrics {
            height,
            width,
            hori_bearing_x,
            hori_bearing_y,
            hori_advance,
            vert_bearing_x,
            vert_bearing_y,
            vert_advance,
        })
    }
}

impl<'a> ReadFixedSizeDep<'a> for BigGlyphMetrics {
    fn size(_scope: Self::Args) -> usize {
        // 8 fields, all 1 byte
        8
    }
}

impl<'a> ReadFrom<'a> for GlyphOffsetPair {
    type ReadType = (U16Be, U16Be);

    fn from((glyph_id, offset): (u16, u16)) -> Self {
        GlyphOffsetPair { glyph_id, offset }
    }
}

impl<'a> ReadFrom<'a> for EbdtComponent {
    type ReadType = (U16Be, I8, I8);

    fn from((glyph_id, x_offset, y_offset): (u16, i8, i8)) -> Self {
        EbdtComponent {
            glyph_id,
            x_offset,
            y_offset,
        }
    }
}

impl TryFrom<u16> for ImageFormat {
    type Error = ParseError;

    fn try_from(value: u16) -> Result<Self, Self::Error> {
        match value {
            1 => Ok(ImageFormat::Format1),
            2 => Ok(ImageFormat::Format2),
            5 => Ok(ImageFormat::Format5),
            6 => Ok(ImageFormat::Format6),
            7 => Ok(ImageFormat::Format7),
            8 => Ok(ImageFormat::Format8),
            9 => Ok(ImageFormat::Format9),
            17 => Ok(ImageFormat::Format17),
            18 => Ok(ImageFormat::Format18),
            19 => Ok(ImageFormat::Format19),
            _ => Err(ParseError::BadValue),
        }
    }
}

impl<'a> TryFrom<(&BitmapInfo, GlyphBitmapData<'a>)> for BitmapGlyph {
    type Error = ParseError;

    fn try_from((info, glyph): (&BitmapInfo, GlyphBitmapData<'a>)) -> Result<Self, Self::Error> {
        let res = match glyph {
            // Format 1: small metrics, byte-aligned data.
            GlyphBitmapData::Format1 {
                small_metrics,
                data,
            } => {
                let data = bgra_to_rgba(info.bit_depth, data.to_vec())?;
                let metrics = EmbeddedMetrics::try_from((info, &small_metrics))?;
                BitmapGlyph {
                    bitmap: Bitmap::Embedded(EmbeddedBitmap {
                        format: info.bit_depth,
                        width: small_metrics.width,
                        height: small_metrics.height,
                        data: Box::from(data),
                    }),
                    metrics: Metrics::Embedded(metrics),
                    ppem_x: Some(u16::from(info.ppem_x)),
                    ppem_y: Some(u16::from(info.ppem_y)),
                }
            }
            // Format 2: small metrics, bit-aligned data.
            GlyphBitmapData::Format2 {
                small_metrics,
                data,
            } => {
                let metrics = EmbeddedMetrics::try_from((info, &small_metrics))?;
                let unpacked = unpack_bit_aligned_data(
                    info.bit_depth,
                    small_metrics.width,
                    small_metrics.height,
                    data,
                )
                .map_err(parse_error_from_bitreader_error)
                .and_then(|data| bgra_to_rgba(info.bit_depth, data))?;
                BitmapGlyph {
                    bitmap: Bitmap::Embedded(EmbeddedBitmap {
                        format: info.bit_depth,
                        width: small_metrics.width,
                        height: small_metrics.height,
                        data: unpacked.into(),
                    }),
                    metrics: Metrics::Embedded(metrics),
                    ppem_x: Some(u16::from(info.ppem_x)),
                    ppem_y: Some(u16::from(info.ppem_y)),
                }
            }
            // Format 5: metrics in EBLC, bit-aligned image data only.
            GlyphBitmapData::Format5 { big_metrics, data } => {
                let metrics = EmbeddedMetrics::try_from((info, &big_metrics))?;
                let unpacked = unpack_bit_aligned_data(
                    info.bit_depth,
                    big_metrics.width,
                    big_metrics.height,
                    data,
                )
                .map_err(parse_error_from_bitreader_error)
                .and_then(|data| bgra_to_rgba(info.bit_depth, data))?;
                BitmapGlyph {
                    bitmap: Bitmap::Embedded(EmbeddedBitmap {
                        format: info.bit_depth,
                        width: big_metrics.width,
                        height: big_metrics.height,
                        data: unpacked.into(),
                    }),
                    metrics: Metrics::Embedded(metrics),
                    ppem_x: Some(u16::from(info.ppem_x)),
                    ppem_y: Some(u16::from(info.ppem_y)),
                }
            }
            // Format 6: big metrics, byte-aligned data.
            GlyphBitmapData::Format6 { big_metrics, data } => {
                let data = bgra_to_rgba(info.bit_depth, data.to_vec())?;
                let metrics = EmbeddedMetrics::try_from((info, &big_metrics))?;
                BitmapGlyph {
                    bitmap: Bitmap::Embedded(EmbeddedBitmap {
                        format: info.bit_depth,
                        width: big_metrics.width,
                        height: big_metrics.height,
                        data: Box::from(data),
                    }),
                    metrics: Metrics::Embedded(metrics),
                    ppem_x: Some(u16::from(info.ppem_x)),
                    ppem_y: Some(u16::from(info.ppem_y)),
                }
            }
            // Format7: big metrics, bit-aligned data.
            GlyphBitmapData::Format7 { big_metrics, data } => {
                let metrics = EmbeddedMetrics::try_from((info, &big_metrics))?;
                let unpacked = unpack_bit_aligned_data(
                    info.bit_depth,
                    big_metrics.width,
                    big_metrics.height,
                    data,
                )
                .map_err(parse_error_from_bitreader_error)
                .and_then(|data| bgra_to_rgba(info.bit_depth, data))?;
                BitmapGlyph {
                    bitmap: Bitmap::Embedded(EmbeddedBitmap {
                        format: info.bit_depth,
                        width: big_metrics.width,
                        height: big_metrics.height,
                        data: unpacked.into(),
                    }),
                    metrics: Metrics::Embedded(metrics),
                    ppem_x: Some(u16::from(info.ppem_x)),
                    ppem_y: Some(u16::from(info.ppem_y)),
                }
            }
            // Format 8: small metrics, component data.
            GlyphBitmapData::Format8 { .. } => return Err(ParseError::NotImplemented),
            // Format 9: big metrics, component data.
            GlyphBitmapData::Format9 { .. } => return Err(ParseError::NotImplemented),
            // Format 17: small metrics, PNG image data.
            GlyphBitmapData::Format17 {
                small_metrics,
                data,
            } => {
                let metrics = EmbeddedMetrics::try_from((info, &small_metrics))?;
                let bitmap = EncapsulatedBitmap {
                    format: EncapsulatedFormat::Png,
                    data: Box::from(data),
                };
                BitmapGlyph {
                    bitmap: Bitmap::Encapsulated(bitmap),
                    metrics: Metrics::Embedded(metrics),
                    ppem_x: Some(u16::from(info.ppem_x)),
                    ppem_y: Some(u16::from(info.ppem_y)),
                }
            }
            // Format 18: big metrics, PNG image data.
            // Format 19: metrics in CBLC table, PNG image data.
            GlyphBitmapData::Format18 { big_metrics, data }
            | GlyphBitmapData::Format19 { big_metrics, data } => {
                let metrics = EmbeddedMetrics::try_from((info, &big_metrics))?;
                let bitmap = EncapsulatedBitmap {
                    format: EncapsulatedFormat::Png,
                    data: Box::from(data),
                };
                BitmapGlyph {
                    bitmap: Bitmap::Encapsulated(bitmap),
                    metrics: Metrics::Embedded(metrics),
                    ppem_x: Some(u16::from(info.ppem_x)),
                    ppem_y: Some(u16::from(info.ppem_y)),
                }
            }
        };

        Ok(res)
    }
}

impl<'a> GlyphBitmapData<'a> {
    /// The width of the bitmap.
    pub fn width(&self) -> u8 {
        match self {
            GlyphBitmapData::Format1 {
                small_metrics: SmallGlyphMetrics { width, .. },
                ..
            } => *width,
            GlyphBitmapData::Format2 {
                small_metrics: SmallGlyphMetrics { width, .. },
                ..
            } => *width,
            GlyphBitmapData::Format5 {
                big_metrics: BigGlyphMetrics { width, .. },
                ..
            } => *width,
            GlyphBitmapData::Format6 {
                big_metrics: BigGlyphMetrics { width, .. },
                ..
            } => *width,
            GlyphBitmapData::Format7 {
                big_metrics: BigGlyphMetrics { width, .. },
                ..
            } => *width,
            GlyphBitmapData::Format8 {
                small_metrics: SmallGlyphMetrics { width, .. },
                ..
            } => *width,
            GlyphBitmapData::Format9 {
                big_metrics: BigGlyphMetrics { width, .. },
                ..
            } => *width,
            GlyphBitmapData::Format17 {
                small_metrics: SmallGlyphMetrics { width, .. },
                ..
            } => *width,
            GlyphBitmapData::Format18 {
                big_metrics: BigGlyphMetrics { width, .. },
                ..
            } => *width,
            GlyphBitmapData::Format19 {
                big_metrics: BigGlyphMetrics { width, .. },
                ..
            } => *width,
        }
    }

    /// The height of the bitmap.
    pub fn height(&self) -> u8 {
        match self {
            GlyphBitmapData::Format1 {
                small_metrics: SmallGlyphMetrics { height, .. },
                ..
            } => *height,
            GlyphBitmapData::Format2 {
                small_metrics: SmallGlyphMetrics { height, .. },
                ..
            } => *height,
            GlyphBitmapData::Format5 {
                big_metrics: BigGlyphMetrics { height, .. },
                ..
            } => *height,
            GlyphBitmapData::Format6 {
                big_metrics: BigGlyphMetrics { height, .. },
                ..
            } => *height,
            GlyphBitmapData::Format7 {
                big_metrics: BigGlyphMetrics { height, .. },
                ..
            } => *height,
            GlyphBitmapData::Format8 {
                small_metrics: SmallGlyphMetrics { height, .. },
                ..
            } => *height,
            GlyphBitmapData::Format9 {
                big_metrics: BigGlyphMetrics { height, .. },
                ..
            } => *height,
            GlyphBitmapData::Format17 {
                small_metrics: SmallGlyphMetrics { height, .. },
                ..
            } => *height,
            GlyphBitmapData::Format18 {
                big_metrics: BigGlyphMetrics { height, .. },
                ..
            } => *height,
            GlyphBitmapData::Format19 {
                big_metrics: BigGlyphMetrics { height, .. },
                ..
            } => *height,
        }
    }
}

impl<'a> fmt::Debug for GlyphBitmapData<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GlyphBitmapData::Format1 {
                small_metrics,
                data,
            } => f
                .debug_struct("GlyphBitmapData::Format1")
                .field("small_metrics", &small_metrics)
                .field("data", &format_args!("[{} bytes]", data.len()))
                .finish(),
            GlyphBitmapData::Format2 {
                small_metrics,
                data,
            } => f
                .debug_struct("GlyphBitmapData::Format2")
                .field("small_metrics", &small_metrics)
                .field("data", &format_args!("[{} bytes]", data.len()))
                .finish(),
            GlyphBitmapData::Format5 { big_metrics, data } => f
                .debug_struct("GlyphBitmapData::Format5")
                .field("big_metrics", &big_metrics)
                .field("data", &format_args!("[{} bytes]", data.len()))
                .finish(),
            GlyphBitmapData::Format6 { big_metrics, data } => f
                .debug_struct("GlyphBitmapData::Format6")
                .field("big_metrics", &big_metrics)
                .field("data", &format_args!("[{} bytes]", data.len()))
                .finish(),
            GlyphBitmapData::Format7 { big_metrics, data } => f
                .debug_struct("GlyphBitmapData::Format7")
                .field("big_metrics", &big_metrics)
                .field("data", &format_args!("[{} bytes]", data.len()))
                .finish(),
            GlyphBitmapData::Format8 { small_metrics, .. } => f
                .debug_struct("GlyphBitmapData::Format8")
                .field("small_metrics", &small_metrics)
                .finish(),
            GlyphBitmapData::Format9 { big_metrics, .. } => f
                .debug_struct("GlyphBitmapData::Format9")
                .field("big_metrics", &big_metrics)
                .finish(),
            GlyphBitmapData::Format17 {
                small_metrics,
                data,
            } => f
                .debug_struct("GlyphBitmapData::Format17")
                .field("small_metrics", &small_metrics)
                .field("data", &format_args!("[{} bytes]", data.len()))
                .finish(),
            GlyphBitmapData::Format18 { big_metrics, data } => f
                .debug_struct("GlyphBitmapData::Format18")
                .field("big_metrics", &big_metrics)
                .field("data", &format_args!("[{} bytes]", data.len()))
                .finish(),
            GlyphBitmapData::Format19 { big_metrics, data } => f
                .debug_struct("GlyphBitmapData::Format19")
                .field("big_metrics", &big_metrics)
                .field("data", &format_args!("[{} bytes]", data.len()))
                .finish(),
        }
    }
}

impl TryFrom<(&BitmapInfo, &SmallGlyphMetrics)> for EmbeddedMetrics {
    type Error = ParseError;

    fn try_from(
        (info, small_metrics): (&BitmapInfo, &SmallGlyphMetrics),
    ) -> Result<Self, Self::Error> {
        match info.small_glyph_metrics_direction() {
            MetricsDirection::Horizontal | MetricsDirection::Unknown => EmbeddedMetrics::new(
                info.ppem_x,
                info.ppem_y,
                Some(BitmapMetrics {
                    origin_offset_x: i16::from(small_metrics.bearing_x),
                    // Convert from offset to the top of the image to bottom
                    origin_offset_y: i16::from(small_metrics.bearing_y)
                        - i16::from(small_metrics.height),
                    advance: small_metrics.advance,
                    ascender: info.hori.ascender,
                    descender: info.hori.descender,
                }),
                None,
            ),
            MetricsDirection::Vertical => EmbeddedMetrics::new(
                info.ppem_x,
                info.ppem_y,
                None,
                Some(BitmapMetrics {
                    origin_offset_x: i16::from(small_metrics.bearing_x),
                    // Convert from offset to the top of the image to bottom
                    origin_offset_y: i16::from(small_metrics.bearing_y)
                        - i16::from(small_metrics.height),
                    advance: small_metrics.advance,
                    ascender: info.vert.ascender,
                    descender: info.vert.descender,
                }),
            ),
        }
    }
}

impl TryFrom<(&BitmapInfo, &BigGlyphMetrics)> for EmbeddedMetrics {
    type Error = ParseError;

    fn try_from((info, big_metrics): (&BitmapInfo, &BigGlyphMetrics)) -> Result<Self, Self::Error> {
        EmbeddedMetrics::new(
            info.ppem_x,
            info.ppem_y,
            Some(BitmapMetrics {
                origin_offset_x: i16::from(big_metrics.hori_bearing_x),
                origin_offset_y: i16::from(big_metrics.hori_bearing_y)
                    - i16::from(big_metrics.height),
                advance: big_metrics.hori_advance,
                ascender: info.hori.ascender,
                descender: info.hori.descender,
            }),
            Some(BitmapMetrics {
                origin_offset_x: i16::from(big_metrics.vert_bearing_x),
                origin_offset_y: i16::from(big_metrics.vert_bearing_y)
                    - i16::from(big_metrics.height),
                advance: big_metrics.vert_advance,
                ascender: info.vert.ascender,
                descender: info.vert.descender,
            }),
        )
    }
}

impl BitmapInfo {
    fn small_glyph_metrics_direction(&self) -> MetricsDirection {
        if self.flags & HORIZONTAL_METRICS == HORIZONTAL_METRICS {
            MetricsDirection::Horizontal
        } else if self.flags & VERTICAL_METRICS == VERTICAL_METRICS {
            MetricsDirection::Vertical
        } else {
            MetricsDirection::Unknown
        }
    }
}

fn unpack_bit_aligned_data(
    bit_depth: BitDepth,
    width: u8,
    height: u8,
    data: &[u8],
) -> Result<Vec<u8>, BitReaderError> {
    let bits_per_row = bit_depth as usize * usize::from(width);
    let whole_bytes_per_row = bits_per_row >> 3;
    let remaining_bits = (bits_per_row & 7) as u8;
    let bytes_per_row = whole_bytes_per_row + if remaining_bits != 0 { 1 } else { 0 };

    let mut offset = 0;
    let mut image_data = vec![0u8; usize::from(height) * bytes_per_row];
    let mut reader = BitReader::new(data);
    for _ in 0..height {
        // Read whole bytes, then the remainder
        for byte in image_data[offset..(offset + whole_bytes_per_row)].iter_mut() {
            *byte = reader.read_u8(8)?;
        }
        offset += whole_bytes_per_row;
        if remaining_bits != 0 {
            let byte = reader.read_u8(remaining_bits)?;
            image_data[offset] = byte << (8 - remaining_bits);
            offset += 1;
        }
    }

    Ok(image_data)
}

fn parse_error_from_bitreader_error(err: BitReaderError) -> ParseError {
    match err {
        BitReaderError::NotEnoughData { .. } => ParseError::BadEof,
        BitReaderError::TooManyBitsForType { .. } => {
            // This should only happen as a result of programmer error as we only call bitreader
            // with values <= 8.
            unreachable!("{}", err)
        }
    }
}

fn bgra_to_rgba(bit_depth: BitDepth, mut data: Vec<u8>) -> Result<Vec<u8>, ParseError> {
    match bit_depth {
        BitDepth::One | BitDepth::Two | BitDepth::Four | BitDepth::Eight => Ok(data),
        BitDepth::ThirtyTwo => {
            if data.len() % 4 != 0 {
                return Err(ParseError::BadEof);
            }
            data.chunks_exact_mut(4).for_each(|chunk| chunk.swap(0, 2));
            Ok(data)
        }
    }
}

#[cfg(test)]
mod tests {
    use itertools::Itertools;
    use alloc::borrow::Borrow;

    use super::*;
    use crate::font_data::FontData;
    use crate::tables::FontTableProvider;
    use crate::tag;

    #[test]
    fn test_parse_cblc() {
        let cblc_data = include_bytes!("../../tests/fonts/opentype/CBLC.bin");
        let cblc = ReadScope::new(&cblc_data).read::<CBLCTable<'_>>().unwrap();

        let strikes = &cblc.bitmap_sizes;
        assert_eq!(strikes.len(), 1);
        assert_eq!(strikes[0].index_sub_tables.len(), 3);
        let ranges = strikes[0]
            .index_sub_table_records
            .iter()
            .map(|rec| rec.first_glyph_index..=rec.last_glyph_index)
            .collect::<Vec<_>>();
        assert_eq!(ranges, &[4..=17, 19..=1316, 1354..=3112]);
    }

    #[test]
    fn test_parse_eblc() {
        let buffer = include_bytes!("../../tests/fonts/opentype/TerminusTTF-4.47.0.ttf");
        let scope = ReadScope::new(&buffer);
        let font_file = scope
            .read::<FontData<'_>>()
            .expect("unable to parse font file");
        let table_provider = font_file
            .table_provider(0)
            .expect("unable to create font provider");
        let table = table_provider
            .table_data(tag::EBLC)
            .expect("no EBLC table")
            .expect("no EBLC table");
        let scope = ReadScope::new(table.borrow());
        let eblc = scope.read::<CBLCTable<'_>>().unwrap();

        let strikes = &eblc.bitmap_sizes;
        assert_eq!(strikes.len(), 9);
    }

    #[test]
    fn test_lookup_eblc() {
        let buffer = include_bytes!("../../tests/fonts/opentype/TerminusTTF-4.47.0.ttf");
        let scope = ReadScope::new(&buffer);
        let font_file = scope
            .read::<FontData<'_>>()
            .expect("unable to parse font file");
        let table_provider = font_file
            .table_provider(0)
            .expect("unable to create font provider");
        let table = table_provider
            .table_data(tag::EBLC)
            .expect("no EBLC table")
            .expect("no EBLC table");
        let scope = ReadScope::new(table.borrow());
        let eblc = scope.read::<CBLCTable<'_>>().unwrap();
        let table = table_provider
            .table_data(tag::EBDT)
            .expect("no EBDT table")
            .expect("no EBDT table");
        let scope = ReadScope::new(table.borrow());
        let ebdt = scope.read::<CBDTTable<'_>>().unwrap();

        // Font has strikes in 12 14 16 18 20 22 24 28 32 ppem
        // Glyph 10 is ampersand
        let strike = eblc
            .find_strike(10, 30, BitDepth::ThirtyTwo)
            .expect("no matching strike");
        let res = lookup(10, &strike, &ebdt).expect("error looking up glyph");
        match res {
            Some(GlyphBitmapData::Format5 { data, .. }) => assert_eq!(data.len(), 64),
            _ => panic!("expected GlyphBitmapData::Format5 got something else"),
        }
    }

    #[test]
    fn test_lookup_cblc() {
        // Test tables are from Noto Color Emoji
        let cblc_data = include_bytes!("../../tests/fonts/opentype/CBLC.bin");
        let cblc = ReadScope::new(&cblc_data).read::<CBLCTable<'_>>().unwrap();
        let cbdt_data = include_bytes!("../../tests/fonts/opentype/CBDT.bin");
        let cbdt = ReadScope::new(&cbdt_data).read::<CBDTTable<'_>>().unwrap();

        // Glyph 1077 is Nerd Face U+1F913
        let strike = cblc
            .find_strike(1077, 30, BitDepth::ThirtyTwo)
            .expect("no matching strike");
        let res = lookup(1077, &strike, &cbdt).expect("error looking up glyph");
        match res {
            Some(GlyphBitmapData::Format17 {
                data,
                small_metrics: SmallGlyphMetrics { width, height, .. },
            }) => {
                assert_eq!((width, height), (136, 128));
                assert_eq!(&data[1..4], b"PNG");
            }
            _ => panic!("expected PNG data got something else"),
        }

        // Repeat the lookup with a lower max bit depth, should now fail to find suitable strike
        assert!(cblc.find_strike(1077, 30, BitDepth::Four).is_none());
    }

    #[test]
    fn test_unpack_bit_aligned_data() {
        let data = &[0xD3, 0xAA, 0x70];
        let expected = &[0xD3, 0x80, 0xA9, 0xC0];
        let actual = unpack_bit_aligned_data(BitDepth::Two, 5, 2, data).unwrap();
        assert_eq!(&actual, expected);
    }

    #[test]
    fn test_bgra_to_rgba_no_change() {
        let original = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let actual = bgra_to_rgba(BitDepth::One, original.clone()).unwrap();
        assert_eq!(actual, original);
    }

    #[test]
    fn test_bgra_to_rgba_reorder() {
        let data = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let expected = &[3, 2, 1, 4, 7, 6, 5, 8];
        let actual = bgra_to_rgba(BitDepth::ThirtyTwo, data).unwrap();
        assert_eq!(&actual, expected);
    }

    #[test]
    fn test_bgra_to_rgba_too_short() {
        let data = vec![1, 2, 3, 4, 5, 6, 7];
        let res = bgra_to_rgba(BitDepth::ThirtyTwo, data);
        assert_eq!(res, Err(ParseError::BadEof));
    }
}