f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
//! Tests with Carlito, an open font with the metrics of Calibri, and with copies of it that the
//! tests change in memory.

use std::path::Path;

use super::{
    Decoration, FaceOrigin, FamilyName, FontDb, FontError, FontId, FontMetrics, KerningSource,
    LineMetrics, Os2Metrics, OutlineError, PathCommand, ScriptMetrics, version_number,
};

pub(crate) const CARLITO: &[u8] = include_bytes!(concat!(
    env!(
        "F_OFFICE_UNIT_TEST_FONTS",
        "set F_OFFICE_UNIT_TEST_FONTS to the folder of the test fonts, which holds Carlito-Regular.ttf"
    ),
    "/Carlito-Regular.ttf"
));

fn name(name: &str) -> FamilyName {
    FamilyName::new(name)
}

fn fonts_folder() -> &'static Path {
    Path::new(env!(
        "F_OFFICE_UNIT_TEST_FONTS",
        "set F_OFFICE_UNIT_TEST_FONTS to the folder of the test fonts, which holds Carlito-Regular.ttf"
    ))
}

fn read_u16(data: &[u8], at: usize) -> u16 {
    u16::from_be_bytes([data[at], data[at + 1]])
}

fn read_u32(data: &[u8], at: usize) -> u32 {
    u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]])
}

/// Returns the position of the table record for `tag` in the table directory.
fn table_record(data: &[u8], tag: [u8; 4]) -> usize {
    let count = usize::from(read_u16(data, 4));
    (0..count)
        .map(|index| 12 + 16 * index)
        .find(|&at| data[at..at + 4] == tag)
        .unwrap()
}

fn table_offset(data: &[u8], tag: [u8; 4]) -> usize {
    read_u32(data, table_record(data, tag) + 8) as usize
}

fn write_u16(data: &mut [u8], at: usize, value: u16) {
    data[at..at + 2].copy_from_slice(&value.to_be_bytes());
}

/// Returns Carlito with one table renamed, so that the font seems to lack it.
pub(crate) fn without_table(tag: [u8; 4]) -> Vec<u8> {
    let mut data = CARLITO.to_vec();
    let at = table_record(&data, tag);
    data[at..at + 4].copy_from_slice(b"zzzz");
    data
}

/// Returns Carlito with the record of one table at offset 0, which lists no table.
pub(crate) fn with_table_at_offset_zero(tag: [u8; 4]) -> Vec<u8> {
    let mut data = CARLITO.to_vec();
    let at = table_record(&data, tag) + 8;
    data[at..at + 4].copy_from_slice(&0_u32.to_be_bytes());
    data
}

/// Returns Carlito with another weight class and italic bit in `OS/2`.
pub(crate) fn with_style(weight: u16, italic: bool) -> Vec<u8> {
    let mut data = CARLITO.to_vec();
    let os2 = table_offset(&data, *b"OS/2");
    write_u16(&mut data, os2 + 4, weight);
    write_u16(&mut data, os2 + 62, u16::from(italic));
    data
}

/// Returns a font collection that holds Carlito `count` times.
pub(crate) fn collection(count: u32) -> Vec<u8> {
    collection_after(count, 0)
}

/// Returns a font collection that holds Carlito `count` times, with `gap` zero bytes between
/// the collection's header and Carlito's table directory.
pub(crate) fn collection_after(count: u32, gap: u32) -> Vec<u8> {
    let header_len = 12 + 4 * count + gap;
    let mut data = b"ttcf".to_vec();
    data.extend(0x0001_0000_u32.to_be_bytes());
    data.extend(count.to_be_bytes());
    for _ in 0..count {
        data.extend(header_len.to_be_bytes());
    }
    data.extend(vec![0; usize::try_from(gap).unwrap()]);
    let mut font = CARLITO.to_vec();
    for index in 0..usize::from(read_u16(&font, 4)) {
        let at = 12 + 16 * index + 8;
        let offset = read_u32(&font, at) + header_len;
        font[at..at + 4].copy_from_slice(&offset.to_be_bytes());
    }
    data.extend(font);
    data
}

/// Returns Carlito with a `kern` table that holds `pairs` in one horizontal format 0
/// subtable, and a second, cross-stream subtable that kerns every pair by 1000.
pub(crate) fn with_kern(pairs: &[(u16, u16, i16)]) -> Vec<u8> {
    let subtable = |coverage: u16, pairs: &[(u16, u16, i16)]| {
        let mut out = Vec::new();
        let count = u16::try_from(pairs.len()).unwrap();
        out.extend(0_u16.to_be_bytes());
        out.extend((14 + 6 * count).to_be_bytes());
        out.extend(coverage.to_be_bytes());
        out.extend(count.to_be_bytes());
        out.extend([0_u8; 6]);
        for (left, right, value) in pairs {
            out.extend(left.to_be_bytes());
            out.extend(right.to_be_bytes());
            out.extend(value.to_be_bytes());
        }
        out
    };
    let mut kern = vec![0, 0, 0, 2];
    kern.extend(subtable(0x0001, pairs));
    let cross: Vec<(u16, u16, i16)> = pairs.iter().map(|(l, r, _)| (*l, *r, 1000)).collect();
    kern.extend(subtable(0x0005, &cross));
    let font = CARLITO;
    let count = usize::from(read_u16(font, 4));
    let mut records: Vec<Vec<u8>> = (0..count)
        .map(|index| {
            let at = 12 + 16 * index;
            let mut record = font[at..at + 16].to_vec();
            let offset = read_u32(font, at + 8) + 16;
            record[8..12].copy_from_slice(&offset.to_be_bytes());
            record
        })
        .collect();
    let body = &font[12 + 16 * count..];
    let padding = (4 - body.len() % 4) % 4;
    let kern_offset = u32::try_from(12 + 16 * (count + 1) + body.len() + padding).unwrap();
    let mut record = b"kern".to_vec();
    record.extend(0_u32.to_be_bytes());
    record.extend(kern_offset.to_be_bytes());
    record.extend(u32::try_from(kern.len()).unwrap().to_be_bytes());
    records.push(record);
    records.sort_by(|a, b| a[..4].cmp(&b[..4]));
    let mut data = font[..4].to_vec();
    data.extend(u16::try_from(count + 1).unwrap().to_be_bytes());
    data.extend(&font[6..12]);
    data.extend(records.concat());
    data.extend(body);
    data.extend(vec![0; padding]);
    data.extend(kern);
    data
}

fn database(fonts: &[Vec<u8>]) -> FontDb {
    let mut db = FontDb::new();
    for font in fonts {
        db.add_font(font.clone()).unwrap();
    }
    db
}

#[test]
fn adds_one_face_and_counts_it() {
    let mut db = FontDb::new();
    assert!(db.is_empty());
    assert_eq!(db.len(), 0);
    assert_eq!(
        db.add_font(CARLITO.to_vec()),
        Ok(vec![FontId::from_index(0)])
    );
    assert!(!db.is_empty());
    assert_eq!(db.len(), 1);
}

#[test]
fn ids_continue_across_fonts() {
    let mut db = FontDb::new();
    db.add_font(CARLITO.to_vec()).unwrap();
    let data: std::sync::Arc<[u8]> = CARLITO.into();
    assert_eq!(db.add_font(data), Ok(vec![FontId::from_index(1)]));
    let ids: Vec<u32> = db.faces().map(|(id, _)| id.index()).collect();
    assert_eq!(ids, [0, 1]);
}

#[test]
fn index_round_trips() {
    assert_eq!(FontId::from_index(7).index(), 7);
}

#[test]
fn a_font_without_a_math_table_has_no_limits_and_no_display_variants() {
    let db = database(&[CARLITO.to_vec()]);
    // A face without the table, and an unknown face.
    for font in [FontId::from_index(0), FontId::from_index(5)] {
        assert_eq!(db.math_limits(font), None);
        assert_eq!(db.math_radical(font), None);
        assert_eq!(db.display_variant(font, 3), None);
        assert_eq!(db.italic_correction(font, 3), None);
    }
}

#[test]
fn a_face_is_light_only_when_both_of_its_weights_are_below_bold() {
    // Carlito with a weight class of 400 and the PANOSE weight of a black face.
    let mut black = with_style(400, false);
    let os2 = table_offset(&black, *b"OS/2");
    if let Some(byte) = black.get_mut(os2 + 34) {
        *byte = 10;
    }
    let db = database(&[CARLITO.to_vec(), with_style(700, false), black]);
    let light = |index| db.info(FontId::from_index(index)).unwrap().light();
    assert!(light(0));
    assert!(!light(1));
    assert!(!light(2));
    assert_eq!(db.info(FontId::from_index(2)).unwrap().panose_weight, 10);
}

#[test]
fn reads_the_number_of_a_version_string() {
    assert_eq!(version_number("Version 7.06.1"), "7.06.1");
    assert_eq!(version_number("Version 7.12.1; F-Office"), "7.12.1");
}

#[test]
fn reads_names_and_style() {
    let db = database(&[CARLITO.to_vec()]);
    let info = db.info(FontId::from_index(0)).unwrap();
    assert_eq!(info.family, "Carlito");
    assert_eq!(info.subfamily, "Regular");
    assert_eq!(info.family_names, ["Carlito"]);
    assert_eq!(info.weight, 400);
    assert!(!info.italic);
}

#[test]
fn reads_metrics_as_stored() {
    let db = database(&[CARLITO.to_vec()]);
    let expected = FontMetrics {
        units_per_em: 2048,
        hhea: LineMetrics {
            ascender: 1950,
            descender: -550,
            line_gap: 0,
        },
        os2: Some(Os2Metrics {
            average_width: 1048,
            typo: LineMetrics {
                ascender: 1536,
                descender: -512,
                line_gap: 452,
            },
            win_ascent: 1950,
            win_descent: 550,
            use_typo_metrics: false,
            x_height: Some(978),
            cap_height: Some(1314),
            strikeout: Decoration {
                position: 512,
                thickness: 134,
            },
            subscript: ScriptMetrics {
                x_size: 1433,
                y_size: 1331,
                x_offset: 0,
                y_offset: 286,
            },
            superscript: ScriptMetrics {
                x_size: 1433,
                y_size: 1331,
                x_offset: 0,
                y_offset: 976,
            },
            east_asian: false,
        }),
        underline: Some(Decoration {
            position: -103,
            thickness: 194,
        }),
    };
    assert_eq!(db.metrics(FontId::from_index(0)), Some(&expected));
}

#[test]
fn reads_the_use_typo_metrics_bit() {
    let mut data = CARLITO.to_vec();
    let os2 = table_offset(&data, *b"OS/2");
    write_u16(&mut data, os2 + 62, 1 << 7);
    let db = database(&[data]);
    let os2 = db.metrics(FontId::from_index(0)).unwrap().os2.unwrap();
    assert!(os2.use_typo_metrics);
}

#[test]
fn unknown_ids_return_none() {
    let db = database(&[CARLITO.to_vec()]);
    assert_eq!(db.info(FontId::from_index(1)), None);
    assert_eq!(db.metrics(FontId::from_index(1)), None);
}

#[test]
fn rejects_data_that_is_not_a_font() {
    let mut db = FontDb::new();
    assert_eq!(
        db.add_font(b"not a font".to_vec()),
        Err(FontError::NotAFont)
    );
    assert!(db.is_empty());
}

#[test]
fn rejects_faces_without_the_tables_it_needs() {
    let mut db = FontDb::new();
    assert_eq!(
        db.add_font(without_table(*b"hhea")),
        Err(FontError::BadTable("hhea"))
    );
    assert_eq!(
        db.add_font(without_table(*b"hmtx")),
        Err(FontError::BadTable("hmtx"))
    );
    assert!(db.add_font(without_table(*b"head")).is_err());
    assert!(db.is_empty());
}

#[test]
fn rejects_zero_units_per_em() {
    let mut data = CARLITO.to_vec();
    let head = table_offset(&data, *b"head");
    write_u16(&mut data, head + 18, 0);
    let mut db = FontDb::new();
    assert_eq!(db.add_font(data), Err(FontError::BadTable("head")));
}

#[test]
fn adds_every_face_of_a_collection() {
    let mut db = FontDb::new();
    let ids = db.add_font(collection(2)).unwrap();
    assert_eq!(ids, [FontId::from_index(0), FontId::from_index(1)]);
    assert_eq!(db.info(ids[1]).unwrap().family, "Carlito");
}

#[test]
fn returns_the_file_bytes_and_index_of_each_face() {
    let mut db = FontDb::new();
    let file = collection(2);
    let ids = db.add_font(file.clone()).unwrap();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let (first, first_index) = db.data(ids[0]).unwrap();
    let (second, second_index) = db.data(ids[1]).unwrap();
    assert_eq!((&first[..], first_index), (&file[..], 0));
    assert_eq!(second_index, 1);
    assert!(std::ptr::eq(first.as_ptr(), second.as_ptr()));
    assert_eq!(
        db.data(carlito).map(|(data, index)| (&data[..], index)),
        Some((CARLITO, 0))
    );
    assert_eq!(db.data(FontId::from_index(3)), None);
}

#[test]
fn reads_built_in_bytes_as_given_bytes_without_a_copy() {
    let mut db = FontDb::new();
    let built_in = db.add_static(CARLITO).unwrap()[0];
    let given = db.add_font(CARLITO.to_vec()).unwrap()[0];
    assert_eq!(db.info(built_in), db.info(given));
    assert_eq!(db.metrics(built_in), db.metrics(given));
    assert_eq!(db.origin(built_in), Some(FaceOrigin::BuiltIn));
    assert_eq!(db.origin(given), Some(FaceOrigin::Caller));
    let (data, index) = db.data(built_in).unwrap();
    assert!(std::ptr::eq(data.as_ptr(), CARLITO.as_ptr()) && index == 0);
    assert_eq!(
        db.device_width(built_in, 0x21, 13),
        db.device_width(given, 0x21, 13)
    );
}

#[test]
fn adds_no_built_in_face_of_bytes_that_are_no_font() {
    let mut db = FontDb::new();
    assert!(db.add_static(&CARLITO[..100]).is_err());
    assert_eq!(db.len(), 0);
}

#[test]
fn takes_the_callers_face_over_an_equal_built_in_face() {
    let mut db = FontDb::new();
    let built_in = db.add_static(CARLITO).unwrap()[0];
    assert_eq!(db.query(&name("Carlito"), false, false), Some(built_in));
    let given = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let info = db.info(given).unwrap().clone();
    let postscript = info.postscript_name.unwrap();
    for family in ["Carlito", &postscript, &info.full_names[0]] {
        assert_eq!(
            db.query(&name(family), false, false),
            Some(given),
            "{family}"
        );
    }
}

#[test]
fn reads_style_from_head_without_os2() {
    let mut data = without_table(*b"OS/2");
    let db = database(std::slice::from_ref(&data));
    let id = FontId::from_index(0);
    assert_eq!(db.metrics(id).unwrap().os2, None);
    assert_eq!(db.info(id).unwrap().weight, 400);
    assert!(!db.info(id).unwrap().italic);

    let head = table_offset(&data, *b"head");
    write_u16(&mut data, head + 44, 0b11);
    let db = database(&[data]);
    assert_eq!(db.info(id).unwrap().weight, 700);
    assert!(db.info(id).unwrap().italic);
}

#[test]
fn has_no_underline_without_post() {
    let db = database(&[without_table(*b"post")]);
    assert_eq!(db.metrics(FontId::from_index(0)).unwrap().underline, None);
}

#[test]
fn query_ignores_case_and_never_substitutes() {
    let db = database(&[CARLITO.to_vec()]);
    let id = Some(FontId::from_index(0));
    assert_eq!(db.query(&name("carlito"), false, false), id);
    assert_eq!(db.query(&name("CARLITO"), true, true), id);
    assert_eq!(db.query(&name("Calibri"), false, false), None);
    assert_eq!(db.query(&name("Carlit"), false, false), None);
}

#[test]
fn query_prefers_the_exact_style() {
    let db = database(&[
        with_style(400, false),
        with_style(700, false),
        with_style(400, true),
        with_style(700, true),
    ]);
    let id = |index| Some(FontId::from_index(index));
    assert_eq!(db.query(&name("Carlito"), false, false), id(0));
    assert_eq!(db.query(&name("Carlito"), true, false), id(1));
    assert_eq!(db.query(&name("Carlito"), false, true), id(2));
    assert_eq!(db.query(&name("Carlito"), true, true), id(3));
}

#[test]
fn query_filters_faces_before_it_selects_a_style_or_a_name() {
    let db = database(&[with_style(400, false), with_style(700, false)]);
    let regular = Some(FontId::from_index(0));
    assert_eq!(
        db.query_with(&name("Carlito"), true, false, |_, face| face.weight == 400),
        regular
    );
    assert_eq!(
        db.query_with(&name("Carlito"), true, false, |_, _| false),
        None
    );
    assert_eq!(
        db.query_with(&name("Carlito-Regular"), true, false, |_, face| face.weight
            == 400),
        regular
    );
    assert_eq!(
        db.query_with(&name("Carlito-Regular"), false, false, |_, _| false),
        None
    );
}

#[test]
fn query_prefers_italic_then_the_closest_weight_then_the_first_face() {
    let db = database(&[
        with_style(600, false),
        with_style(300, false),
        with_style(300, true),
        with_style(300, false),
    ]);
    let id = |index| Some(FontId::from_index(index));
    assert_eq!(db.query(&name("Carlito"), true, false), id(0));
    assert_eq!(db.query(&name("Carlito"), false, false), id(1));
    assert_eq!(db.query(&name("Carlito"), true, true), id(2));
}

#[test]
fn adds_the_fonts_of_files() {
    let mut db = FontDb::new();
    let ids = db
        .add_files(&[fonts_folder().join("Carlito-Regular.ttf")])
        .unwrap();
    assert_eq!(ids, [FontId::from_index(0)]);
    assert_eq!(db.info(ids[0]).unwrap().family, "Carlito");
}

#[test]
fn names_a_file_that_is_not_a_font_file() {
    let mut db = FontDb::new();
    let license = fonts_folder().join("Carlito-OFL.txt");
    let not_added = db.add_files(std::slice::from_ref(&license)).unwrap_err();
    assert_eq!(not_added.path, license);
    assert!(matches!(
        not_added.cause,
        crate::NotAddedCause::NotAFontFile
    ));
    assert!(not_added.to_string().contains("Carlito-OFL.txt"));
    assert!(std::error::Error::source(&not_added).is_none());
    assert_eq!(
        std::io::Error::from(not_added).kind(),
        std::io::ErrorKind::InvalidData
    );
    assert_eq!(db.len(), 0);
}

#[test]
fn names_a_font_file_that_cannot_be_read() {
    let missing = fonts_folder().join("missing.ttf");
    let not_added = FontDb::new()
        .add_files(std::slice::from_ref(&missing))
        .unwrap_err();
    assert!(matches!(
        &not_added.cause,
        crate::NotAddedCause::Unreadable(error) if error.kind() == std::io::ErrorKind::NotFound
    ));
    assert!(not_added.to_string().contains("missing.ttf cannot be read"));
    assert!(std::error::Error::source(&not_added).is_some());
    assert_eq!(
        std::io::Error::from(not_added).kind(),
        std::io::ErrorKind::NotFound
    );
}

#[test]
fn errors_and_the_database_print() {
    assert_eq!(
        FontError::NotAFont.to_string(),
        "the data is not an OpenType font"
    );
    assert_eq!(
        FontError::BadTable("hhea").to_string(),
        "the font's hhea table is missing or malformed"
    );
    assert_eq!(
        FontError::TooManyFaces.to_string(),
        "the font database is full"
    );
    let outline_errors = [
        OutlineError::UnknownFont,
        OutlineError::UnknownGlyph,
        OutlineError::NoOutlines,
        OutlineError::Unreadable,
    ];
    assert_eq!(
        outline_errors.map(|error| error.to_string()),
        [
            "the font database has no such font",
            "the font has no such glyph",
            "the font has no glyph outlines",
            "the glyph's outline does not read",
        ]
    );
    let db = database(&[CARLITO.to_vec()]);
    assert_eq!(
        format!("{db:?}"),
        "FontDb { faces: 1, descriptions: 0, .. }"
    );
}

/// Returns the smallest box around every point of an outline, as x min, y min, x max, y max.
fn bounds(commands: &[PathCommand]) -> (f32, f32, f32, f32) {
    let points = commands.iter().flat_map(|command| match *command {
        PathCommand::MoveTo(p) | PathCommand::LineTo(p) => vec![p],
        PathCommand::QuadTo(c, p) => vec![c, p],
        PathCommand::CubicTo(c0, c1, p) => vec![c0, c1, p],
        PathCommand::Close => vec![],
    });
    points.fold(
        (f32::MAX, f32::MAX, f32::MIN, f32::MIN),
        |(x0, y0, x1, y1), p| (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)),
    )
}

fn contours(commands: &[PathCommand]) -> usize {
    commands
        .iter()
        .filter(|command| **command == PathCommand::Close)
        .count()
}

#[test]
fn maps_characters_to_glyphs() {
    let db = database(&[CARLITO.to_vec()]);
    let id = FontId::from_index(0);
    let glyphs: Vec<Option<u32>> = ['A', 'H', ' ', 'g', 'é']
        .into_iter()
        .map(|ch| db.glyph_id(id, ch))
        .collect();
    assert_eq!(glyphs, [Some(3), Some(15), Some(2), Some(93), Some(2007)]);
    assert_eq!(db.glyph_id(id, '\u{10FFFD}'), None);
    assert_eq!(db.glyph_id(FontId::from_index(1), 'A'), None);
}

#[test]
fn reads_advances_from_hmtx() {
    let db = database(&[CARLITO.to_vec()]);
    let id = FontId::from_index(0);
    assert_eq!(db.advance(id, 3), Some(1185));
    assert_eq!(db.advance(id, 15), Some(1276));
    assert_eq!(db.advance(id, 2), Some(463));
    assert_eq!(db.advance(id, 2782), Some(463));
    assert_eq!(db.advance(id, 2783), None);
    assert_eq!(db.advance(FontId::from_index(1), 3), None);
}

fn carlito_outline(glyph: u32) -> Vec<PathCommand> {
    database(&[CARLITO.to_vec()])
        .outline(FontId::from_index(0), glyph)
        .unwrap()
}

#[test]
fn draws_outlines_in_font_units() {
    let h = carlito_outline(15);
    assert!(matches!(h.first(), Some(PathCommand::MoveTo(_))));
    assert_eq!(h.last(), Some(&PathCommand::Close));
    assert_eq!(contours(&h), 1);
    assert_eq!(bounds(&h), (140.0, 0.0, 1136.0, 1314.0));
}

#[test]
fn draws_every_contour() {
    let a = carlito_outline(3);
    assert_eq!(contours(&a), 2);
    assert_eq!(bounds(&a), (8.0, 0.0, 1178.0, 1314.0));
}

#[test]
fn draws_curves_and_descenders() {
    let g = carlito_outline(93);
    assert!(
        g.iter()
            .any(|command| matches!(command, PathCommand::QuadTo(..)))
    );
    assert_eq!(bounds(&g), (64.0, -352.0, 928.0, 994.0));
}

#[test]
fn draws_composite_glyphs() {
    assert_eq!(bounds(&carlito_outline(2007)), (75.0, -14.0, 945.0, 1399.0));
}

/// Returns Carlito with the data of `glyph` running past the end of `glyf`, as its `loca` gives
/// it, so that the glyph's outline does not read.
fn with_unreadable_glyph(glyph: usize) -> Vec<u8> {
    let mut data = CARLITO.to_vec();
    let head = table_offset(&data, *b"head");
    let loca = table_offset(&data, *b"loca");
    let past_glyf = read_u32(&data, table_record(&data, *b"glyf") + 12) + 4;
    // `indexToLocFormat` of `head`: 1 for offsets in bytes, 0 for offsets in halves.
    if read_u16(&data, head + 50) == 1 {
        let at = loca + 4 * (glyph + 1);
        data[at..at + 4].copy_from_slice(&past_glyf.to_be_bytes());
    } else {
        let halves = u16::try_from(past_glyf / 2).unwrap();
        write_u16(&mut data, loca + 2 * (glyph + 1), halves);
    }
    data
}

#[test]
fn names_why_a_glyph_that_the_font_has_has_no_outline() {
    let db = database(&[without_table(*b"glyf"), with_unreadable_glyph(15)]);
    let (bare, broken) = (FontId::from_index(0), FontId::from_index(1));
    assert_eq!(db.outline(bare, 15), Err(OutlineError::NoOutlines));
    assert_eq!(db.outline(broken, 15), Err(OutlineError::Unreadable));
    assert_eq!(
        db.outline(broken, 3).map(|outline| contours(&outline)),
        Ok(2)
    );
}

#[test]
fn outlines_of_empty_and_missing_glyphs() {
    let db = database(&[CARLITO.to_vec()]);
    let id = FontId::from_index(0);
    assert_eq!(db.outline(id, 2), Ok(vec![]));
    assert_eq!(db.outline(id, 2783), Err(OutlineError::UnknownGlyph));
    assert_eq!(
        db.outline(FontId::from_index(1), 15),
        Err(OutlineError::UnknownFont)
    );
}

/// Writes `name` into every record of `name_id` in the `name` table. The new name must not be
/// longer than the old one.
fn rename(data: &mut [u8], name_id: u16, name: &str) {
    let table = table_offset(data, *b"name");
    let count = usize::from(read_u16(data, table + 2));
    let storage = table + usize::from(read_u16(data, table + 4));
    let encoded: Vec<u8> = name.encode_utf16().flat_map(u16::to_be_bytes).collect();
    for record in (0..count).map(|index| table + 6 + 12 * index) {
        if read_u16(data, record + 6) == name_id {
            assert!(encoded.len() <= usize::from(read_u16(data, record + 8)));
            let at = storage + usize::from(read_u16(data, record + 10));
            data[at..at + encoded.len()].copy_from_slice(&encoded);
            write_u16(data, record + 8, u16::try_from(encoded.len()).unwrap());
        }
    }
}

/// Returns Carlito with another style, PostScript name and, when given, family name.
fn named(weight: u16, italic: bool, family: Option<&str>, postscript: &str) -> Vec<u8> {
    let mut data = with_style(weight, italic);
    rename(&mut data, 6, postscript);
    if let Some(family) = family {
        rename(&mut data, 1, family);
    }
    data
}

#[test]
fn reads_the_postscript_name() {
    let db = database(&[
        CARLITO.to_vec(),
        named(700, false, Some("Xarlito"), "X-Bold"),
    ]);
    let info = |index| db.info(FontId::from_index(index)).unwrap();
    assert_eq!(info(0).postscript_name.as_deref(), Some("Carlito-Regular"));
    assert_eq!(info(1).postscript_name.as_deref(), Some("X-Bold"));
    assert_eq!(info(1).family, "Xarlito");
}

#[test]
fn a_face_without_names_has_empty_names() {
    let db = database(&[without_table(*b"name")]);
    let info = db.info(FontId::from_index(0)).unwrap();
    assert_eq!(info.family, "");
    assert_eq!(info.subfamily, "");
    assert_eq!(info.family_names, [] as [String; 0]);
    assert_eq!(info.postscript_name, None);
    assert_eq!(db.query(&name("Carlito-Regular"), false, false), None);
}

#[test]
fn query_finds_a_face_by_its_postscript_name() {
    let db = database(&[
        named(400, false, None, "Carlito-Regular"),
        named(700, false, None, "Carlito-Bold"),
    ]);
    let id = |index| Some(FontId::from_index(index));
    assert_eq!(db.query(&name("carlito-regular"), false, false), id(0));
    assert_eq!(db.query(&name("CARLITO-BOLD"), true, false), id(1));
    assert_eq!(db.query(&name("Carlito-Book"), false, false), None);
}

#[test]
fn query_by_postscript_name_prefers_the_requested_style_in_the_style_group() {
    let db = database(&[
        named(400, false, None, "Carlito-Regular"),
        named(700, false, None, "Carlito-Bold"),
        named(400, true, Some("Xarlito"), "Xarlito-Italic"),
    ]);
    let id = |index| Some(FontId::from_index(index));
    assert_eq!(db.query(&name("Carlito-Regular"), true, false), id(1));
    assert_eq!(db.query(&name("Carlito-Bold"), false, false), id(0));
    // Neither face of the group is italic, and the italic face is in another group.
    assert_eq!(db.query(&name("Carlito-Regular"), false, true), id(0));
    assert_eq!(db.query(&name("Carlito-Bold"), true, true), id(1));
}

#[test]
fn query_finds_a_face_by_its_full_name_whatever_the_style() {
    let mut bold = named(700, false, Some("Xarlito"), "Xarlito-Bold");
    rename(&mut bold, 4, "Xarlito Bold");
    let db = database(&[named(400, false, Some("Xarlito"), "Xarlito"), bold]);
    let id = |index| Some(FontId::from_index(index));
    assert!(
        db.info(FontId::from_index(1))
            .unwrap()
            .full_names
            .contains(&"Xarlito Bold".to_owned())
    );
    // The family name still finds the face of the requested style.
    assert_eq!(db.query(&name("Xarlito"), false, false), id(0));
    // The full name finds its own face, also for a run that is not bold.
    assert_eq!(db.query(&name("xarlito bold"), false, false), id(1));
    assert_eq!(db.query(&name("Xarlito Bold"), true, true), id(1));
    assert_eq!(db.query(&name("Xarlito Black"), false, false), None);
}

#[test]
fn query_by_postscript_name_counts_bold_from_weight_600() {
    let semi_bold = database(&[
        named(400, false, None, "Carlito-Regular"),
        named(600, false, None, "Carlito-Semi"),
    ]);
    assert_eq!(
        semi_bold.query(&name("Carlito-Regular"), true, false),
        Some(FontId::from_index(1))
    );
    let medium = database(&[
        named(400, false, None, "Carlito-Regular"),
        named(599, false, None, "Carlito-Semi"),
    ]);
    assert_eq!(
        medium.query(&name("Carlito-Regular"), true, false),
        Some(FontId::from_index(0))
    );
    assert_eq!(
        medium.query(&name("Carlito-Semi"), false, false),
        Some(FontId::from_index(0))
    );
}

/// Returns Carlito as a face of the family "Carlit" whose typographic family (name ID 16) is
/// "Carlito", as Aptos Display is a face of "Aptos Display" in the typographic family "Aptos".
fn in_typographic_family() -> Vec<u8> {
    let mut data = CARLITO.to_vec();
    rename(&mut data, 1, "Carlit");
    let table = table_offset(&data, *b"name");
    let count = usize::from(read_u16(&data, table + 2));
    for record in (0..count).map(|index| table + 6 + 12 * index) {
        if read_u16(&data, record + 6) == 4 {
            write_u16(&mut data, record + 6, 16);
        }
    }
    rename(&mut data, 16, "Carlito");
    data
}

#[test]
fn query_prefers_the_face_whose_family_name_is_the_requested_one() {
    let db = database(&[in_typographic_family(), CARLITO.to_vec()]);
    assert!(
        db.info(FontId::from_index(0))
            .unwrap()
            .family_names
            .contains(&"Carlito".to_owned())
    );
    assert_eq!(
        db.query(&name("Carlito"), false, false),
        Some(FontId::from_index(1))
    );
    assert_eq!(
        db.query(&name("Carlit"), false, false),
        Some(FontId::from_index(0))
    );
    // Alone, the face still belongs to its typographic family, but only as the last step of
    // `query`, after the steps by name, so that a format can try its stand-ins between them.
    let alone = database(&[in_typographic_family()]);
    assert_eq!(
        alone.query(&name("Carlito"), false, false),
        Some(FontId::from_index(0))
    );
    assert_eq!(
        alone.query_with(&name("Carlito"), false, false, |_, _| true),
        None
    );
    assert_eq!(
        alone.query_typographic_with(&name("Carlito"), false, false, |_, _| true),
        Some(FontId::from_index(0))
    );
    assert_eq!(
        db.query_typographic_with(&name("Carlito"), false, false, |_, _| true),
        Some(FontId::from_index(1))
    );
}

#[test]
fn query_matches_family_names_before_postscript_names() {
    let db = database(&[
        named(700, false, Some("Xarlito"), "Carlito"),
        CARLITO.to_vec(),
    ]);
    assert_eq!(
        db.query(&name("Carlito"), true, false),
        Some(FontId::from_index(1))
    );
    assert_eq!(
        db.query(&name("Xarlito"), false, false),
        Some(FontId::from_index(0))
    );
}

/// A copy of a font whose table `from` is renamed `to`, which must keep the table directory in
/// order.
fn renamed_table(font: &[u8], from: [u8; 4], to: [u8; 4]) -> Vec<u8> {
    let mut data = font.to_vec();
    let count = usize::from(read_u16(font, 4));
    for index in 0..count {
        let at = 12 + 16 * index;
        if data[at..at + 4] == from {
            data[at..at + 4].copy_from_slice(&to);
        }
    }
    data
}

#[test]
fn kerning_reads_the_kern_feature_of_gpos_before_the_kern_table() {
    // The values come from a separate reader of Carlito's `GPOS` table.
    let fonts = database(&[CARLITO.to_vec()]);
    let id = FontId::from_index(0);
    let glyph = |c| fonts.glyph_id(id, c).unwrap();
    let kern = |fonts: &FontDb, pair: &str| {
        let mut chars = pair.chars();
        let (left, right) = (chars.next().unwrap(), chars.next().unwrap());
        fonts.kerning(id, glyph(left), glyph(right))
    };
    assert_eq!(kern(&fonts, "AV"), -89);
    assert_eq!(kern(&fonts, "VA"), -96);
    assert_eq!(kern(&fonts, "To"), -182);
    assert_eq!(kern(&fonts, "  "), 0);
    // A `kern` table does not count while `GPOS` has the feature.
    let pair = (
        u16::try_from(glyph('A')).unwrap(),
        u16::try_from(glyph('V')).unwrap(),
        -120,
    );
    let both = database(&[with_kern(&[pair])]);
    assert_eq!(kern(&both, "AV"), -89);
    assert_eq!(fonts.kerning_source(id), KerningSource::Gpos);
    assert_eq!(both.kerning_source(id), KerningSource::Gpos);
}

#[test]
fn kerning_sums_horizontal_pairs_from_the_kern_table() {
    let plain = database(&[renamed_table(CARLITO, *b"GPOS", *b"GPOT")]);
    let id = FontId::from_index(0);
    let a = plain.glyph_id(id, 'A').unwrap();
    let v = plain.glyph_id(id, 'V').unwrap();
    assert_eq!(plain.kerning(id, a, v), 0);
    let pair = (u16::try_from(a).unwrap(), u16::try_from(v).unwrap(), -120);
    let kerned = database(&[renamed_table(&with_kern(&[pair]), *b"GPOS", *b"GPOT")]);
    assert_eq!(kerned.kerning(id, a, v), -120);
    assert_eq!(kerned.kerning(id, v, a), 0);
    assert_eq!(kerned.kerning(FontId::from_index(7), a, v), 0);
    assert_eq!(kerned.advance(id, a), plain.advance(id, a));
}

#[test]
fn a_face_without_the_kern_feature_of_gpos_takes_its_kerning_from_the_kern_table() {
    let id = FontId::from_index(0);
    let plain = database(&[renamed_table(CARLITO, *b"GPOS", *b"GPOT")]);
    let kerned = database(&[renamed_table(
        &with_kern(&[(1, 2, -120)]),
        *b"GPOS",
        *b"GPOT",
    )]);
    // With or without the table, and for an unknown face.
    assert_eq!(kerned.kerning_source(id), KerningSource::KernTable);
    assert_eq!(plain.kerning_source(id), KerningSource::KernTable);
    let unknown = FontId::from_index(7);
    assert_eq!(kerned.kerning_source(unknown), KerningSource::KernTable);
}

/// Carlito's glyphs of `A` and `V`, and three databases of Carlito: with its `GPOS` only, with
/// its `GPOS` and a `kern` table that kerns the pair by -120, and with that `kern` table only.
fn kerning_sources() -> ((u32, u32), [FontDb; 3]) {
    let gpos_only = database(&[CARLITO.to_vec()]);
    let glyph = |c| gpos_only.glyph_id(FontId::from_index(0), c).unwrap();
    let (a, v) = (glyph('A'), glyph('V'));
    let pair = (u16::try_from(a).unwrap(), u16::try_from(v).unwrap(), -120);
    let both = database(&[with_kern(&[pair])]);
    let table_only = database(&[renamed_table(&with_kern(&[pair]), *b"GPOS", *b"GPOT")]);
    ((a, v), [gpos_only, both, table_only])
}

#[test]
fn reads_each_kerning_source_of_a_face_on_its_own() {
    let ((a, v), [gpos_only, both, table_only]) = kerning_sources();
    let kerning = |fonts: &FontDb, source| fonts.kerning_from(FontId::from_index(0), a, v, source);
    // Each source gives its own value, and 0 when the face lacks it.
    assert_eq!(kerning(&both, KerningSource::Gpos), -89);
    assert_eq!(kerning(&both, KerningSource::KernTable), -120);
    assert_eq!(kerning(&gpos_only, KerningSource::KernTable), 0);
    assert_eq!(kerning(&table_only, KerningSource::Gpos), 0);
    assert_eq!(kerning(&table_only, KerningSource::KernTable), -120);
}

#[test]
fn tells_whether_a_face_has_a_kern_table_whatever_its_gpos_holds() {
    let (_, [gpos_only, both, table_only]) = kerning_sources();
    let id = FontId::from_index(0);
    assert!(both.has_kern_table(id));
    assert!(table_only.has_kern_table(id));
    assert!(!gpos_only.has_kern_table(id));
    assert!(!both.has_kern_table(FontId::from_index(7)));
}

/// The ligatures of `text` in Carlito as (start, length, advance of the ligature).
fn carlito_ligatures(fonts: &FontDb, text: &str) -> Vec<(usize, usize, Option<u16>)> {
    let id = FontId::from_index(0);
    let glyphs: Vec<u32> = text
        .chars()
        .map(|c| fonts.glyph_id(id, c).unwrap())
        .collect();
    fonts
        .ligatures(id, &glyphs)
        .iter()
        .map(|l| (l.start, l.len, fonts.advance(id, l.glyph)))
        .collect()
}

#[test]
fn joins_standard_ligatures_with_the_longest_first() {
    let fonts = database(&[CARLITO.to_vec()]);
    // Carlito's "ffi" is 1,654 units wide and its "ff" 1,195, against 1,720 and 1,250 for the
    // single letters.
    assert_eq!(
        carlito_ligatures(&fonts, "office"),
        vec![(1, 3, Some(1654))]
    );
    assert_eq!(carlito_ligatures(&fonts, "off"), vec![(1, 2, Some(1195))]);
    assert_eq!(
        carlito_ligatures(&fonts, "fit flat"),
        vec![(0, 2, Some(1084)), (4, 2, Some(1084))]
    );
    assert_eq!(carlito_ligatures(&fonts, "abc"), vec![]);
    assert_eq!(carlito_ligatures(&fonts, "f"), vec![]);
    assert_eq!(fonts.ligatures(FontId::from_index(3), &[1, 2]), vec![]);
}

#[test]
fn a_font_without_a_gsub_table_has_no_ligatures() {
    let mut data = CARLITO.to_vec();
    let at = table_record(&data, *b"GSUB");
    data[at..at + 4].copy_from_slice(b"XSUB");
    let fonts = database(&[data]);
    assert_eq!(carlito_ligatures(&fonts, "office"), vec![]);
}

/// Checks that the database keeps the answer `own` under `key` of a face's `store`, and that
/// the next answer comes from the store: an entry put there in its place changes the answer.
fn assert_kept(
    store: &std::sync::Mutex<std::collections::BTreeMap<(u16, u16), Option<i32>>>,
    key: (u16, u16),
    own: Option<i32>,
    answer: impl Fn() -> Option<i32>,
) {
    assert_eq!(store.lock().unwrap().get(&key), Some(&own), "{key:?}");
    let other = own.map(|value| value + 1);
    store.lock().unwrap().insert(key, other);
    assert_eq!(answer(), other, "{key:?}");
}

#[test]
fn gives_the_bi_level_advance_of_the_faces_instructions() {
    let fonts = database(&[CARLITO.to_vec()]);
    let id = FontId::from_index(0);
    let mut hinter = f_office_truetype::Hinter::new(CARLITO, 0, 1000).unwrap();
    for ch in ['i', 'm', 'W'] {
        let glyph = fonts.glyph_id(id, ch).unwrap();
        let own = hinter.advance(u16::try_from(glyph).unwrap()).ok();
        assert_eq!(fonts.bi_level_advance(id, glyph, 1000), own, "{ch}");
        let key = (1000, u16::try_from(glyph).unwrap());
        assert_kept(&fonts.face(id).unwrap().bi_level, key, own, || {
            fonts.bi_level_advance(id, glyph, 1000)
        });
    }
    // A glyph past the font's glyphs, a glyph ID past 16 bits, or an unknown face: none.
    assert_eq!(fonts.bi_level_advance(id, 60_000, 1000), None);
    assert_eq!(fonts.bi_level_advance(id, 70_000, 1000), None);
    assert_eq!(fonts.bi_level_advance(FontId::from_index(5), 1, 1000), None);
}

#[test]
fn keeps_a_hinter_for_each_of_the_last_sizes_with_the_answers_of_a_new_hinter() {
    use crate::bilevel::MOST_KEPT_HINTERS;
    use f_office_truetype::Hinter;
    let fonts = database(&[CARLITO.to_vec()]);
    let id = FontId::from_index(0);
    let more = u16::try_from(MOST_KEPT_HINTERS).unwrap() + 2;
    let sizes: Vec<u16> = (10..10 + more).collect();
    // Each glyph at every size, one size after another, so that the first sizes go from the
    // lists and come back with a new hinter.
    for ch in ['i', 'm', 'W'] {
        let glyph = fonts.glyph_id(id, ch).unwrap();
        let short = u16::try_from(glyph).unwrap();
        for &ppem in &sizes {
            let advance = Hinter::new(CARLITO, 0, ppem).unwrap().advance(short);
            assert_eq!(
                fonts.bi_level_advance(id, glyph, ppem),
                advance.ok(),
                "{ch} {ppem}"
            );
            let width = Hinter::device(CARLITO, 0, ppem)
                .unwrap()
                .device_width(short);
            assert_eq!(
                fonts.device_width(id, glyph, ppem),
                width.ok(),
                "{ch} {ppem}"
            );
        }
    }
    let face = fonts.face(id).unwrap();
    let last = sizes
        .get(sizes.len() - MOST_KEPT_HINTERS..)
        .unwrap()
        .to_vec();
    assert_eq!(face.bi_level_hinters.lock().unwrap().sizes(), last);
    assert_eq!(face.device_hinters.lock().unwrap().sizes(), last);
}

#[test]
fn hints_one_size_on_several_threads_with_the_answers_of_a_new_hinter() {
    use crate::bilevel::MOST_KEPT_HINTERS;
    use f_office_truetype::Hinter;
    let fonts = database(&[CARLITO.to_vec()]);
    let id = FontId::from_index(0);
    let ppem = 17;
    let mut fresh = Hinter::device(CARLITO, 0, ppem).unwrap();
    let glyphs: Vec<u32> = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        .chars()
        .map(|ch| fonts.glyph_id(id, ch).unwrap())
        .collect();
    let expected: Vec<Option<i32>> = glyphs
        .iter()
        .map(|&glyph| fresh.device_width(u16::try_from(glyph).unwrap()).ok())
        .collect();
    // Each thread asks for every fourth glyph, so that the threads hint the size at once.
    std::thread::scope(|scope| {
        for first in 0..4 {
            let (fonts, glyphs, expected) = (&fonts, &glyphs, &expected);
            scope.spawn(move || {
                for (glyph, want) in glyphs.iter().zip(expected).skip(first).step_by(4) {
                    assert_eq!(fonts.device_width(id, *glyph, ppem), *want, "{glyph}");
                }
            });
        }
    });
    let sizes = fonts
        .face(id)
        .unwrap()
        .device_hinters
        .lock()
        .unwrap()
        .sizes();
    assert!(
        !sizes.is_empty() && sizes.len() <= MOST_KEPT_HINTERS.min(4),
        "{sizes:?}"
    );
    assert!(sizes.iter().all(|&size| size == ppem), "{sizes:?}");
}

#[test]
fn gives_the_device_width_of_the_faces_instructions() {
    let fonts = database(&[CARLITO.to_vec()]);
    let id = FontId::from_index(0);
    let mut hinter = f_office_truetype::Hinter::device(CARLITO, 0, 44).unwrap();
    for ch in ['i', 'm', 'W'] {
        let glyph = fonts.glyph_id(id, ch).unwrap();
        let own = hinter.device_width(u16::try_from(glyph).unwrap()).ok();
        assert!(own.is_some_and(|width| width > 0), "{ch}");
        assert_eq!(fonts.device_width(id, glyph, 44), own, "{ch}");
        let key = (44, u16::try_from(glyph).unwrap());
        assert_kept(&fonts.face(id).unwrap().device, key, own, || {
            fonts.device_width(id, glyph, 44)
        });
    }
    assert_eq!(fonts.device_width(id, 60_000, 44), None);
    assert_eq!(fonts.device_width(id, 70_000, 44), None);
    assert_eq!(fonts.device_width(FontId::from_index(5), 1, 44), None);
}

#[cfg(feature = "woff2")]
mod woff2_tests {
    use super::{CARLITO, FontDb, FontError, read_u16, read_u32};

    fn push_base128(out: &mut Vec<u8>, mut value: u32) {
        let mut buf = [0u8; 5];
        let mut len = 0;
        loop {
            buf[len] = (value & 0x7f) as u8;
            value >>= 7;
            len += 1;
            if value == 0 {
                break;
            }
        }
        for i in (0..len).rev() {
            let byte = buf[i] | if i > 0 { 0x80 } else { 0 };
            out.push(byte);
        }
    }

    struct BitWriter {
        bytes: Vec<u8>,
        acc: u64,
        bits: u32,
    }

    impl BitWriter {
        fn new() -> Self {
            Self {
                bytes: Vec::new(),
                acc: 0,
                bits: 0,
            }
        }

        fn push(&mut self, value: u64, count: u32) {
            self.acc |= (value & ((1u64 << count) - 1)) << self.bits;
            self.bits += count;
            while self.bits >= 8 {
                self.bytes.push((self.acc & 0xff) as u8);
                self.acc >>= 8;
                self.bits -= 8;
            }
        }

        fn align_byte(&mut self) {
            if self.bits > 0 {
                self.bytes.push((self.acc & 0xff) as u8);
                self.acc = 0;
                self.bits = 0;
            }
        }
    }

    /// Wraps raw bytes in an RFC 7932 Brotli stream of uncompressed metablocks.
    fn brotli_uncompressed(data: &[u8]) -> Vec<u8> {
        let mut bits = BitWriter::new();
        bits.push(0, 1); // WBITS = 16
        for chunk in data.chunks(65_536) {
            let mlen_minus_1 = u64::try_from(chunk.len() - 1).unwrap();
            bits.push(0, 1); // ISLAST = 0
            bits.push(0, 2); // MNIBBLES = 4 nibbles (16 bits)
            bits.push(mlen_minus_1, 16);
            bits.push(1, 1); // ISUNCOMPRESSED = 1
            bits.align_byte();
            bits.bytes.extend_from_slice(chunk);
        }
        bits.push(1, 1); // ISLAST = 1
        bits.push(1, 1); // ISLASTEMPTY = 1
        bits.align_byte();
        bits.bytes
    }

    /// Encodes a single-face SFNT font into a valid WOFF2 container with untransformed tables.
    fn wrap_sfnt_as_woff2(sfnt: &[u8]) -> Vec<u8> {
        let num_tables = read_u16(sfnt, 4);
        let mut directory = Vec::new();
        let mut raw_stream = Vec::new();
        let mut sfnt_size = 12u32 + 16u32 * u32::from(num_tables);

        for i in 0..usize::from(num_tables) {
            let rec = 12 + i * 16;
            let tag = &sfnt[rec..rec + 4];
            let offset = read_u32(sfnt, rec + 8) as usize;
            let length = read_u32(sfnt, rec + 12);
            let is_glyf_or_loca = tag == b"glyf" || tag == b"loca";
            let flags = if is_glyf_or_loca { 0xc0 | 63 } else { 63 };
            directory.push(flags);
            directory.extend_from_slice(tag);
            push_base128(&mut directory, length);
            raw_stream.extend_from_slice(&sfnt[offset..offset + length as usize]);
            sfnt_size += (length + 3) & !3;
        }

        let compressed = brotli_uncompressed(&raw_stream);
        let total_len = (48 + directory.len() + compressed.len() + 3) & !3;

        let mut out = Vec::with_capacity(total_len);
        out.extend_from_slice(b"wOF2");
        out.extend_from_slice(&sfnt[0..4]);
        out.extend_from_slice(&u32::try_from(total_len).unwrap().to_be_bytes());
        out.extend_from_slice(&num_tables.to_be_bytes());
        out.extend_from_slice(&0u16.to_be_bytes());
        out.extend_from_slice(&sfnt_size.to_be_bytes());
        out.extend_from_slice(&u32::try_from(compressed.len()).unwrap().to_be_bytes());
        out.extend_from_slice(&[0u8; 24]); // major/minor, meta*, priv*
        out.extend_from_slice(&directory);
        out.extend_from_slice(&compressed);
        while out.len() < total_len {
            out.push(0);
        }
        out
    }

    #[test]
    fn loads_woff2_with_identical_metrics_and_advances() {
        let woff2 = wrap_sfnt_as_woff2(CARLITO);
        assert!(woff2.starts_with(b"wOF2"));

        let mut raw_db = FontDb::new();
        let raw_ids = raw_db.add_font(CARLITO).unwrap();

        let mut woff2_db = FontDb::new();
        let woff2_ids = woff2_db.add_font(woff2).unwrap();

        assert_eq!(woff2_ids.len(), raw_ids.len());
        assert_eq!(woff2_db.info(woff2_ids[0]), raw_db.info(raw_ids[0]));
        assert_eq!(woff2_db.metrics(woff2_ids[0]), raw_db.metrics(raw_ids[0]));
        for ch in ['A', 'g', 'W', '0'] {
            let g_raw = raw_db.glyph_id(raw_ids[0], ch).unwrap();
            let g_woff2 = woff2_db.glyph_id(woff2_ids[0], ch).unwrap();
            assert_eq!(g_woff2, g_raw, "glyph_id mismatch for {ch}");
            assert_eq!(
                woff2_db.advance(woff2_ids[0], g_woff2),
                raw_db.advance(raw_ids[0], g_raw),
                "advance mismatch for {ch}"
            );
        }
    }

    #[test]
    fn rejects_corrupt_woff2_as_not_a_font() {
        let mut db = FontDb::new();
        assert_eq!(
            db.add_font(b"wOF2corrupt".as_slice()),
            Err(FontError::NotAFont)
        );
        assert!(db.is_empty());
    }
}