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
//! `glyf` — glyph data (TrueType outlines + composite references).
//!
//! Each glyph starts with a 10-byte header
//! `(numberOfContours: i16, xMin, yMin, xMax, yMax: i16)`. A negative
//! `numberOfContours` indicates a composite glyph; otherwise the body
//! holds simple TT outline data.
//!
//! Spec: Microsoft OpenType `glyf` (TrueType outlines and composites).
use crate::outline::{derive_bbox, BBox, Contour, Point, TtOutline};
use crate::parser::{read_i16, read_u16, read_u8};
use crate::tables::loca::LocaTable;
use crate::Error;
const MAX_COMPOSITE_DEPTH: u8 = 16;
// --- simple-glyph flag bits (per spec table) -------------------------------
const FLAG_ON_CURVE: u8 = 0x01;
const FLAG_X_SHORT: u8 = 0x02;
const FLAG_Y_SHORT: u8 = 0x04;
const FLAG_REPEAT: u8 = 0x08;
/// When X_SHORT: bit set ⇒ x is positive. When NOT X_SHORT: bit set
/// ⇒ x repeats previous x (delta == 0).
const FLAG_X_SAME_OR_POS: u8 = 0x10;
const FLAG_Y_SAME_OR_POS: u8 = 0x20;
// Bit 6 reserved, bit 7 OVERLAP (no effect on geometry).
// --- composite-glyph flag bits ---------------------------------------------
const C_ARG_1_AND_2_ARE_WORDS: u16 = 0x0001;
const C_ARGS_ARE_XY_VALUES: u16 = 0x0002;
// 0x0004 ROUND_XY_TO_GRID - hinting only
const C_WE_HAVE_A_SCALE: u16 = 0x0008;
const C_MORE_COMPONENTS: u16 = 0x0020;
const C_WE_HAVE_AN_X_AND_Y_SCALE: u16 = 0x0040;
const C_WE_HAVE_A_TWO_BY_TWO: u16 = 0x0080;
const C_WE_HAVE_INSTRUCTIONS: u16 = 0x0100;
/// `USE_MY_METRICS` (bit 9). Does not affect outline *geometry*, but per
/// §5.3.4 it forces the composite's advance width and side bearings to
/// equal the referenced component's — surfaced through
/// [`GlyfTable::use_my_metrics_glyph`] so the `Font` metric accessors can
/// honour it. When more than one component sets it, the **last** wins.
const C_USE_MY_METRICS: u16 = 0x0200;
// 0x0200 USE_MY_METRICS and 0x0400 OVERLAP_COMPOUND do not affect outline
// geometry. The two offset-interpretation flags below DO: per the `glyf`
// "Composite glyph description" §, when the offset vector form is used
// (ARGS_ARE_XY_VALUES set), SCALED_COMPONENT_OFFSET means the (x, y)
// offset is in the component's pre-transform coordinate system and the 2×2
// scale/transform is applied to it before it is added to the child points;
// UNSCALED_COMPONENT_OFFSET (and the recommended default when neither is
// set) means the offset is in the parent coordinate system and the
// transform is NOT applied. A font that sets both is invalid and falls
// back to the default (unscaled) behaviour.
const C_SCALED_COMPONENT_OFFSET: u16 = 0x0800;
const C_UNSCALED_COMPONENT_OFFSET: u16 = 0x1000;
#[derive(Debug, Clone)]
pub struct GlyfTable<'a> {
bytes: &'a [u8],
}
impl<'a> GlyfTable<'a> {
pub fn new(bytes: &'a [u8]) -> Self {
Self { bytes }
}
pub fn raw(&self) -> &'a [u8] {
self.bytes
}
/// Bounding box from a glyph's 10-byte header. Returns `None` if the
/// range is too short to hold a header.
pub fn bbox(&self, range: core::ops::Range<usize>) -> Option<BBox> {
let body = self.bytes.get(range.clone())?;
if body.len() < 10 {
return None;
}
Some(BBox {
x_min: read_i16(body, 2).ok()?,
y_min: read_i16(body, 4).ok()?,
x_max: read_i16(body, 6).ok()?,
y_max: read_i16(body, 8).ok()?,
})
}
/// Decode a glyph outline (simple or composite). `loca` is needed to
/// resolve composite references; `depth` guards against runaway
/// recursion.
pub fn glyph_outline(
&self,
range: core::ops::Range<usize>,
loca: &LocaTable<'a>,
depth: u8,
) -> Result<TtOutline, Error> {
if depth >= MAX_COMPOSITE_DEPTH {
return Err(Error::CompositeTooDeep);
}
let body = self.bytes.get(range).ok_or(Error::BadOffset)?;
if body.len() < 10 {
return Ok(TtOutline::default());
}
let n_contours = read_i16(body, 0)?;
let bbox = BBox {
x_min: read_i16(body, 2)?,
y_min: read_i16(body, 4)?,
x_max: read_i16(body, 6)?,
y_max: read_i16(body, 8)?,
};
let payload = &body[10..];
if n_contours >= 0 {
decode_simple(payload, n_contours as u16, bbox)
} else {
self.decode_composite(payload, loca, depth, None, None)
}
}
/// Count the component entries in a composite glyph body (the payload
/// after the 10-byte header). Used by the variable-font path to size
/// the per-component gvar delta vector before decoding.
///
/// Returns `Ok(0)` for a glyph that is not composite (`numberOfContours
/// >= 0`) or empty.
pub fn composite_component_count(&self, range: core::ops::Range<usize>) -> Result<u16, Error> {
let body = self.bytes.get(range).ok_or(Error::BadOffset)?;
if body.len() < 10 {
return Ok(0);
}
if read_i16(body, 0)? >= 0 {
return Ok(0);
}
let bytes = &body[10..];
let mut off = 0usize;
let mut count: u16 = 0;
loop {
if off + 4 > bytes.len() {
return Err(Error::BadStructure("composite truncated"));
}
let flags = read_u16(bytes, off)?;
off += 4;
count = count.saturating_add(1);
// Advance past arg1/arg2.
off += if flags & C_ARG_1_AND_2_ARE_WORDS != 0 {
4
} else {
2
};
// Advance past the transform, if any.
if flags & C_WE_HAVE_A_SCALE != 0 {
off += 2;
} else if flags & C_WE_HAVE_AN_X_AND_Y_SCALE != 0 {
off += 4;
} else if flags & C_WE_HAVE_A_TWO_BY_TWO != 0 {
off += 8;
}
if off > bytes.len() {
return Err(Error::BadStructure("composite component truncated"));
}
if flags & C_MORE_COMPONENTS == 0 {
break;
}
}
Ok(count)
}
/// For a composite glyph body (`range` covers the whole glyph record),
/// return the glyph index of the **last** component carrying the
/// `USE_MY_METRICS` flag (§5.3.4) — the component whose `hmtx` advance
/// width and side bearings the composite as a whole should adopt.
///
/// Returns `Ok(None)` for a simple glyph, an empty glyph, or a
/// composite where no component sets the flag (in which case the
/// composite uses its own `hmtx` entry). The spec resolves multiple
/// flagged components to the last one.
pub fn use_my_metrics_glyph(
&self,
range: core::ops::Range<usize>,
) -> Result<Option<u16>, Error> {
let body = self.bytes.get(range).ok_or(Error::BadOffset)?;
if body.len() < 10 {
return Ok(None);
}
if read_i16(body, 0)? >= 0 {
return Ok(None); // simple glyph
}
let bytes = &body[10..];
let mut off = 0usize;
let mut found: Option<u16> = None;
loop {
if off + 4 > bytes.len() {
return Err(Error::BadStructure("composite truncated"));
}
let flags = read_u16(bytes, off)?;
let glyph_index = read_u16(bytes, off + 2)?;
off += 4;
if flags & C_USE_MY_METRICS != 0 {
// Last one wins, so keep overwriting.
found = Some(glyph_index);
}
off += if flags & C_ARG_1_AND_2_ARE_WORDS != 0 {
4
} else {
2
};
if flags & C_WE_HAVE_A_SCALE != 0 {
off += 2;
} else if flags & C_WE_HAVE_AN_X_AND_Y_SCALE != 0 {
off += 4;
} else if flags & C_WE_HAVE_A_TWO_BY_TWO != 0 {
off += 8;
}
if off > bytes.len() {
return Err(Error::BadStructure("composite component truncated"));
}
if flags & C_MORE_COMPONENTS == 0 {
break;
}
}
Ok(found)
}
/// Decode a composite glyph outline with per-component gvar placement
/// deltas applied (ISO/IEC 14496-22:2019 §7.3.4.3). `component_deltas`
/// holds one `(dx, dy)` per component, in component order; index `i`'s
/// delta is added to component `i`'s `argument1` / `argument2` X / Y
/// offset, but **only** when that component uses the `ARGS_ARE_XY_VALUES`
/// placement form (point-matched components take no delta per the
/// spec). If the component offset is scaled (`SCALED_COMPONENT_OFFSET`),
/// the delta-adjusted offset is what the 2×2 transform scales.
///
/// `child_resolver` resolves each referenced component glyph's own
/// outline by `(glyph_index, depth)`. §7.3.4.3 mandates that
/// processing "begin with the most deeply-nested" glyphs: each
/// component glyph carries its own gvar entry and must be decoded
/// **with its own variation applied** before being placed. The
/// resolver lets the `Font` layer (which owns gvar + the coordinate
/// vector) recurse per-component; a runaway-recursion guard at
/// `MAX_COMPOSITE_DEPTH` is enforced here against `depth`.
pub fn glyph_outline_var(
&self,
range: core::ops::Range<usize>,
loca: &LocaTable<'a>,
depth: u8,
component_deltas: &[(i32, i32)],
child_resolver: &dyn Fn(u16, u8) -> Result<TtOutline, Error>,
) -> Result<TtOutline, Error> {
if depth >= MAX_COMPOSITE_DEPTH {
return Err(Error::CompositeTooDeep);
}
let body = self.bytes.get(range).ok_or(Error::BadOffset)?;
if body.len() < 10 {
return Ok(TtOutline::default());
}
let n_contours = read_i16(body, 0)?;
if n_contours >= 0 {
// Not composite — caller should not have routed here, but be
// defensive and decode the static simple outline.
let bbox = BBox {
x_min: read_i16(body, 2)?,
y_min: read_i16(body, 4)?,
x_max: read_i16(body, 6)?,
y_max: read_i16(body, 8)?,
};
return decode_simple(&body[10..], n_contours as u16, bbox);
}
self.decode_composite(
&body[10..],
loca,
depth,
Some(component_deltas),
Some(child_resolver),
)
}
fn decode_composite(
&self,
bytes: &[u8],
loca: &LocaTable<'a>,
depth: u8,
component_deltas: Option<&[(i32, i32)]>,
child_resolver: Option<&dyn Fn(u16, u8) -> Result<TtOutline, Error>>,
) -> Result<TtOutline, Error> {
let mut out = TtOutline::default();
let mut off = 0usize;
let mut component_index = 0usize;
loop {
if off + 4 > bytes.len() {
return Err(Error::BadStructure("composite truncated"));
}
let flags = read_u16(bytes, off)?;
let glyph_index = read_u16(bytes, off + 2)?;
off += 4;
// Decode arg1 / arg2.
let (arg1, arg2);
if flags & C_ARG_1_AND_2_ARE_WORDS != 0 {
if off + 4 > bytes.len() {
return Err(Error::BadStructure("composite arg words truncated"));
}
arg1 = read_i16(bytes, off)? as i32;
arg2 = read_i16(bytes, off + 2)? as i32;
off += 4;
} else {
if off + 2 > bytes.len() {
return Err(Error::BadStructure("composite arg bytes truncated"));
}
arg1 = bytes[off] as i8 as i32;
arg2 = bytes[off + 1] as i8 as i32;
off += 2;
}
// Decode 2x2 transform.
let (xx, xy, yx, yy);
if flags & C_WE_HAVE_A_SCALE != 0 {
if off + 2 > bytes.len() {
return Err(Error::BadStructure("composite scale truncated"));
}
let s = f2dot14(read_i16(bytes, off)?);
xx = s;
yy = s;
xy = 0.0;
yx = 0.0;
off += 2;
} else if flags & C_WE_HAVE_AN_X_AND_Y_SCALE != 0 {
if off + 4 > bytes.len() {
return Err(Error::BadStructure("composite x/y scale truncated"));
}
xx = f2dot14(read_i16(bytes, off)?);
yy = f2dot14(read_i16(bytes, off + 2)?);
xy = 0.0;
yx = 0.0;
off += 4;
} else if flags & C_WE_HAVE_A_TWO_BY_TWO != 0 {
if off + 8 > bytes.len() {
return Err(Error::BadStructure("composite 2x2 truncated"));
}
xx = f2dot14(read_i16(bytes, off)?);
xy = f2dot14(read_i16(bytes, off + 2)?);
yx = f2dot14(read_i16(bytes, off + 4)?);
yy = f2dot14(read_i16(bytes, off + 6)?);
off += 8;
} else {
xx = 1.0;
xy = 0.0;
yx = 0.0;
yy = 1.0;
}
// Resolve the component glyph's outline. §7.3.4.3: each
// component glyph carries its own gvar entry and must be
// decoded with its own variation applied ("processing must
// begin with the most deeply-nested" glyphs). When a
// `child_resolver` is supplied (the variable-font path), it
// recurses through the `Font` layer so the child's own gvar
// deltas are applied; otherwise (static path) we decode the
// child outline directly.
let child = match child_resolver {
Some(resolve) => resolve(glyph_index, depth + 1)?,
None => {
let child_range = loca.glyph_range(glyph_index)?;
self.glyph_outline(child_range, loca, depth + 1)?
}
};
// §7.3.4.3: the per-component placement delta is added to the
// component's argument1/argument2 X/Y offsets, but only for
// the ARGS_ARE_XY_VALUES form. Point-matched components keep
// their default placement.
let (cdx, cdy) = component_deltas
.and_then(|d| d.get(component_index).copied())
.unwrap_or((0, 0));
component_index += 1;
if flags & C_ARGS_ARE_XY_VALUES != 0 {
// Offset-vector placement. argument1/argument2 are an
// (x, y) translation in design units; the gvar delta is
// folded into them *before* any component-offset scaling.
let arg1 = arg1 + cdx;
let arg2 = arg2 + cdy;
let scale_offset = flags & C_SCALED_COMPONENT_OFFSET != 0
&& flags & C_UNSCALED_COMPONENT_OFFSET == 0;
let (dx, dy) = if scale_offset {
// SCALED_COMPONENT_OFFSET: the offset is in the
// component's coordinate system, so the 2×2 transform
// applies to it before it is added to the (already
// transformed) child points. Transforming the offset
// and then translating by it is equivalent to letting
// `append_transformed` add the transformed offset, so
// we pre-transform (arg1, arg2) here and feed the
// result as the post-transform translation.
let fx = arg1 as f32;
let fy = arg2 as f32;
let tx = (fx * xx + fy * yx).round() as i32;
let ty = (fx * xy + fy * yy).round() as i32;
(tx, ty)
} else {
// UNSCALED_COMPONENT_OFFSET / default: offset is in the
// parent coordinate system, untransformed.
(arg1, arg2)
};
out.append_transformed(&child, xx, xy, yx, yy, dx, dy);
} else {
// Point-matching placement. argument1 is a point number in
// the parent (the contours accumulated from previous
// components, re-numbered); argument2 is a point number in
// the child (its own pre-renumber numbering). The child is
// transformed first, then translated so child point arg2
// coincides with parent point arg1.
let child_t = child.transformed(xx, xy, yx, yy);
let parent_pt = out.flat_point(arg1 as usize);
let child_pt = child_t.flat_point(arg2 as usize);
match (parent_pt, child_pt) {
(Some(pp), Some(cp)) => {
let dx = pp.x as i32 - cp.x as i32;
let dy = pp.y as i32 - cp.y as i32;
out.append_translated(&child_t, dx, dy);
}
_ => {
// A referenced point index that lands outside the
// real (non-phantom) point set — typically a
// phantom-point reference, which needs hmtx/vmtx
// metrics we don't thread through the outline
// resolver. Fall back to zero-offset placement so
// the contours still appear rather than dropping
// the component entirely.
out.append_translated(&child_t, 0, 0);
}
}
}
if flags & C_MORE_COMPONENTS == 0 {
if flags & C_WE_HAVE_INSTRUCTIONS != 0 {
// Skip the instruction stream entirely. Format:
// u16 numInstr, then numInstr bytes of bytecode.
if off + 2 <= bytes.len() {
// numInstr + bytecode left unread; we don't run it.
}
}
break;
}
}
Ok(out)
}
}
fn f2dot14(raw: i16) -> f32 {
raw as f32 / 16384.0
}
fn decode_simple(bytes: &[u8], n_contours: u16, bbox: BBox) -> Result<TtOutline, Error> {
if n_contours == 0 {
return Ok(TtOutline {
contours: Vec::new(),
bounds: Some(bbox),
});
}
let mut off = 0usize;
if bytes.len() < (n_contours as usize) * 2 + 2 {
return Err(Error::BadStructure("simple glyph truncated"));
}
// endPtsOfContours[n] u16
let mut end_pts = Vec::with_capacity(n_contours as usize);
for _ in 0..n_contours {
end_pts.push(read_u16(bytes, off)?);
off += 2;
}
// §5.3.3: endPtsOfContours holds the last point index of each contour
// and its entries increase across the array, so the final entry is the
// largest index and `numPoints` = last + 1. A malformed font can ship a
// non-monotonic array where an earlier endpoint exceeds the last; without
// this guard the per-contour carve below would index the coordinate
// arrays (sized to `n_points`) out of bounds. Reject a decreasing step so
// every endpoint is guaranteed < n_points.
for w in end_pts.windows(2) {
if w[1] < w[0] {
return Err(Error::BadStructure(
"simple glyph endPtsOfContours not monotonic",
));
}
}
let n_points = (*end_pts.last().unwrap() as usize) + 1;
// instructionLength (u16) + that many bytes of bytecode.
let inst_len = read_u16(bytes, off)? as usize;
off += 2;
if off + inst_len > bytes.len() {
return Err(Error::BadStructure("simple glyph instructions truncated"));
}
off += inst_len;
// Flags array — variable length due to FLAG_REPEAT.
let mut flags = Vec::with_capacity(n_points);
while flags.len() < n_points {
if off >= bytes.len() {
return Err(Error::BadStructure("simple glyph flags truncated"));
}
let f = bytes[off];
off += 1;
flags.push(f);
if f & FLAG_REPEAT != 0 {
if off >= bytes.len() {
return Err(Error::BadStructure("simple glyph flag repeat truncated"));
}
let rep = bytes[off];
off += 1;
for _ in 0..rep {
if flags.len() >= n_points {
break;
}
flags.push(f);
}
}
}
if flags.len() != n_points {
return Err(Error::BadStructure("simple glyph flag count mismatch"));
}
// x coordinates.
let mut xs = Vec::with_capacity(n_points);
let mut acc: i32 = 0;
for &f in &flags {
let dx = read_coord(bytes, &mut off, f & FLAG_X_SHORT, f & FLAG_X_SAME_OR_POS)?;
acc += dx;
xs.push(clamp_i16(acc));
}
// y coordinates.
let mut ys = Vec::with_capacity(n_points);
acc = 0;
for &f in &flags {
let dy = read_coord(bytes, &mut off, f & FLAG_Y_SHORT, f & FLAG_Y_SAME_OR_POS)?;
acc += dy;
ys.push(clamp_i16(acc));
}
// Carve into contours.
let mut contours = Vec::with_capacity(n_contours as usize);
let mut start = 0usize;
for &end in &end_pts {
let end = end as usize;
let mut c = Contour {
points: Vec::with_capacity(end - start + 1),
};
for i in start..=end {
c.points.push(Point {
x: xs[i],
y: ys[i],
on_curve: flags[i] & FLAG_ON_CURVE != 0,
});
}
contours.push(c);
start = end + 1;
}
let bounds = derive_bbox(&contours).or(Some(bbox));
Ok(TtOutline { contours, bounds })
}
fn read_coord(bytes: &[u8], off: &mut usize, short: u8, same_or_pos: u8) -> Result<i32, Error> {
if short != 0 {
let v = read_u8(bytes, *off)?;
*off += 1;
Ok(if same_or_pos != 0 {
v as i32
} else {
-(v as i32)
})
} else if same_or_pos != 0 {
// Repeat previous value: delta 0.
Ok(0)
} else {
let v = read_i16(bytes, *off)? as i32;
*off += 2;
Ok(v)
}
}
fn clamp_i16(v: i32) -> i16 {
v.clamp(i16::MIN as i32, i16::MAX as i32) as i16
}
#[cfg(test)]
mod tests {
use super::*;
/// Build a single-contour triangle: (0,0)→(100,0)→(50,100), all
/// on-curve. Returns the full glyph bytes (10-byte header + body).
fn build_triangle() -> Vec<u8> {
let mut g = Vec::new();
// header: 1 contour, bbox 0..100, 0..100
g.extend_from_slice(&1i16.to_be_bytes());
g.extend_from_slice(&0i16.to_be_bytes());
g.extend_from_slice(&0i16.to_be_bytes());
g.extend_from_slice(&100i16.to_be_bytes());
g.extend_from_slice(&100i16.to_be_bytes());
// endPtsOfContours
g.extend_from_slice(&2u16.to_be_bytes());
// instructionLength = 0
g.extend_from_slice(&0u16.to_be_bytes());
// 3 flag bytes (all on-curve).
g.extend_from_slice(&[FLAG_ON_CURVE, FLAG_ON_CURVE, FLAG_ON_CURVE]);
// x coords (i16 each): 0, 100, 50 -> deltas 0, 100, -50
g.extend_from_slice(&0i16.to_be_bytes());
g.extend_from_slice(&100i16.to_be_bytes());
g.extend_from_slice(&(-50i16).to_be_bytes());
// y coords: 0, 0, 100 -> deltas 0, 0, 100
g.extend_from_slice(&0i16.to_be_bytes());
g.extend_from_slice(&0i16.to_be_bytes());
g.extend_from_slice(&100i16.to_be_bytes());
g
}
#[test]
fn decodes_simple_triangle() {
let g = build_triangle();
// Build a one-glyph loca for self-reference (won't be read).
let mut loca_bytes = Vec::new();
loca_bytes.extend_from_slice(&0u32.to_be_bytes());
loca_bytes.extend_from_slice(&(g.len() as u32).to_be_bytes());
let loca = LocaTable::parse(&loca_bytes, 1, 1).unwrap();
let glyf = GlyfTable::new(&g);
let out = glyf.glyph_outline(0..g.len(), &loca, 0).unwrap();
assert_eq!(out.contours.len(), 1);
assert_eq!(out.contours[0].points.len(), 3);
assert_eq!(out.contours[0].points[0].x, 0);
assert_eq!(out.contours[0].points[1].x, 100);
assert_eq!(out.contours[0].points[2].x, 50);
assert_eq!(out.contours[0].points[2].y, 100);
assert!(out.contours[0].points.iter().all(|p| p.on_curve));
}
/// §5.3.3: endPtsOfContours entries increase across the array, so the
/// last is the largest point index and `numPoints = last + 1`. A
/// malformed font can ship a non-monotonic array where an earlier
/// contour's endpoint exceeds the final one; `numPoints` then
/// under-counts and the per-contour carve would index the coordinate
/// arrays out of bounds. The decoder must reject it rather than panic.
#[test]
fn rejects_non_monotonic_end_pts() {
// 2-contour simple glyph. endPtsOfContours = [33, 5]: the final
// entry (5) sizes the point arrays to 6, but contour 0 claims to
// end at point 33 -> would read xs[33] out of a 6-element Vec.
let mut g = Vec::new();
g.extend_from_slice(&2i16.to_be_bytes()); // numberOfContours
g.extend_from_slice(&0i16.to_be_bytes()); // xMin
g.extend_from_slice(&0i16.to_be_bytes()); // yMin
g.extend_from_slice(&0i16.to_be_bytes()); // xMax
g.extend_from_slice(&0i16.to_be_bytes()); // yMax
g.extend_from_slice(&33u16.to_be_bytes()); // endPts[0]
g.extend_from_slice(&5u16.to_be_bytes()); // endPts[1] < endPts[0]
g.extend_from_slice(&0u16.to_be_bytes()); // instructionLength
// (guard fires before any flags/coords are consulted)
let mut loca_bytes = Vec::new();
loca_bytes.extend_from_slice(&0u32.to_be_bytes());
loca_bytes.extend_from_slice(&(g.len() as u32).to_be_bytes());
let loca = LocaTable::parse(&loca_bytes, 1, 1).unwrap();
let glyf = GlyfTable::new(&g);
let r = glyf.glyph_outline(0..g.len(), &loca, 0);
assert!(
matches!(r, Err(Error::BadStructure(_))),
"non-monotonic endPtsOfContours must be rejected, got {r:?}"
);
}
#[test]
fn decodes_composite_translates_child() {
// Two glyphs in a synthetic glyf: glyph 0 = simple triangle,
// glyph 1 = composite translating glyph 0 by (+1000, +2000).
let triangle = build_triangle();
let mut composite = Vec::new();
// header: -1 contour (composite), zero bbox
composite.extend_from_slice(&(-1i16).to_be_bytes());
composite.extend_from_slice(&0i16.to_be_bytes());
composite.extend_from_slice(&0i16.to_be_bytes());
composite.extend_from_slice(&0i16.to_be_bytes());
composite.extend_from_slice(&0i16.to_be_bytes());
// flags = ARGS_ARE_XY_VALUES | ARG_1_AND_2_ARE_WORDS
let flags = C_ARGS_ARE_XY_VALUES | C_ARG_1_AND_2_ARE_WORDS;
composite.extend_from_slice(&flags.to_be_bytes());
// glyphIndex = 0
composite.extend_from_slice(&0u16.to_be_bytes());
// arg1=1000 arg2=2000 (i16 each)
composite.extend_from_slice(&1000i16.to_be_bytes());
composite.extend_from_slice(&2000i16.to_be_bytes());
// Stitch glyf = triangle | composite, build loca.
let glyf_bytes: Vec<u8> = [triangle.as_slice(), composite.as_slice()].concat();
let tri_len = triangle.len() as u32;
let total = glyf_bytes.len() as u32;
let mut loca_bytes = Vec::new();
for v in [0u32, tri_len, total] {
loca_bytes.extend_from_slice(&v.to_be_bytes());
}
let loca = LocaTable::parse(&loca_bytes, 2, 1).unwrap();
let glyf = GlyfTable::new(&glyf_bytes);
// Decode composite (glyph 1).
let comp_range = (tri_len as usize)..(total as usize);
let out = glyf.glyph_outline(comp_range, &loca, 0).unwrap();
assert_eq!(out.contours.len(), 1);
let p0 = out.contours[0].points[0];
assert_eq!((p0.x, p0.y), (1000, 2000));
let p1 = out.contours[0].points[1];
assert_eq!((p1.x, p1.y), (1100, 2000));
let p2 = out.contours[0].points[2];
assert_eq!((p2.x, p2.y), (1050, 2100));
}
/// A minimal composite-glyph body referencing exactly one child
/// glyph at the given index (no XY offset, no transform, no MORE
/// components). Used to build long composite chains for the
/// depth-limit tests.
fn build_composite_referencing(child_index: u16) -> Vec<u8> {
let mut g = Vec::new();
// header: -1 contour (composite), zero bbox.
g.extend_from_slice(&(-1i16).to_be_bytes());
g.extend_from_slice(&0i16.to_be_bytes());
g.extend_from_slice(&0i16.to_be_bytes());
g.extend_from_slice(&0i16.to_be_bytes());
g.extend_from_slice(&0i16.to_be_bytes());
// flags: ARGS_ARE_XY_VALUES; arg1/arg2 are bytes (no
// ARG_1_AND_2_ARE_WORDS bit), so 2 bytes follow for offsets.
let flags = C_ARGS_ARE_XY_VALUES;
g.extend_from_slice(&flags.to_be_bytes());
g.extend_from_slice(&child_index.to_be_bytes());
// arg1=0 arg2=0 (i8 each)
g.push(0);
g.push(0);
g
}
/// A composite-glyph chain `0 -> 1 -> 2 -> ... -> N-1 -> triangle`
/// of total depth `N` must succeed when N <= MAX_COMPOSITE_DEPTH
/// and must fail with `CompositeTooDeep` when N exceeds it.
/// MAX_COMPOSITE_DEPTH is currently 16; we walk a 16-link chain
/// (passes) and then a 17-link chain (fails) so the boundary is
/// pinned on both sides.
///
/// The chain layout in `glyf`:
/// glyph 0 = triangle (leaf)
/// glyph 1 = composite referencing glyph 0
/// glyph 2 = composite referencing glyph 1
/// …
/// glyph K = composite referencing glyph K-1
fn build_chained_glyf(depth: usize) -> (Vec<u8>, Vec<u32>) {
// Glyph 0 is the triangle leaf.
let triangle = build_triangle();
let mut glyf = triangle.clone();
let mut offsets: Vec<u32> = vec![0, triangle.len() as u32];
// Glyphs 1..=depth each reference the previous glyph.
for k in 1..=depth {
let comp = build_composite_referencing((k - 1) as u16);
glyf.extend_from_slice(&comp);
offsets.push(glyf.len() as u32);
}
(glyf, offsets)
}
#[test]
fn composite_chain_at_max_depth_succeeds() {
// The depth guard fires when `depth >= MAX_COMPOSITE_DEPTH`,
// and the root call enters at depth=0. So a chain whose
// outermost composite is glyph `MAX_COMPOSITE_DEPTH - 1` walks
// depths 0..=MAX_COMPOSITE_DEPTH-1 — the last depth tested is
// `MAX_COMPOSITE_DEPTH - 1`, which still passes the `<` check.
// The next deeper chain (one more link) would push the leaf
// call to depth=MAX_COMPOSITE_DEPTH and trip the guard.
let depth = (MAX_COMPOSITE_DEPTH as usize) - 1;
let (glyf_bytes, offsets) = build_chained_glyf(depth);
let mut loca_bytes = Vec::new();
for v in &offsets {
loca_bytes.extend_from_slice(&v.to_be_bytes());
}
let num_glyphs = (offsets.len() - 1) as u16;
let loca = LocaTable::parse(&loca_bytes, num_glyphs, 1).unwrap();
let glyf = GlyfTable::new(&glyf_bytes);
// Decode the outermost composite (glyph `depth`).
let top_start = offsets[depth] as usize;
let top_end = offsets[depth + 1] as usize;
let out = glyf
.glyph_outline(top_start..top_end, &loca, 0)
.expect("16-deep chain must decode");
// The leaf triangle has three on-curve points.
assert_eq!(out.contours.len(), 1);
assert_eq!(out.contours[0].points.len(), 3);
}
#[test]
fn composite_chain_over_max_depth_returns_composite_too_deep() {
// Outermost composite is glyph `MAX_COMPOSITE_DEPTH`; decoding
// it pushes the leaf call to depth = MAX_COMPOSITE_DEPTH, which
// trips the `>=` guard immediately and rejects.
let depth = MAX_COMPOSITE_DEPTH as usize;
let (glyf_bytes, offsets) = build_chained_glyf(depth);
let mut loca_bytes = Vec::new();
for v in &offsets {
loca_bytes.extend_from_slice(&v.to_be_bytes());
}
let num_glyphs = (offsets.len() - 1) as u16;
let loca = LocaTable::parse(&loca_bytes, num_glyphs, 1).unwrap();
let glyf = GlyfTable::new(&glyf_bytes);
let top_start = offsets[depth] as usize;
let top_end = offsets[depth + 1] as usize;
let err = glyf
.glyph_outline(top_start..top_end, &loca, 0)
.expect_err("17-deep chain must reject");
assert_eq!(err, Error::CompositeTooDeep);
}
/// A malicious / corrupted font in which a composite glyph
/// references itself (or a cycle including itself) must terminate
/// with `CompositeTooDeep` rather than recursing until stack
/// overflow. The depth guard at MAX_COMPOSITE_DEPTH = 16 caps the
/// cycle at 16 frames.
/// SCALED_COMPONENT_OFFSET: the offset vector is expressed in the
/// component's own coordinate system, so the 2×2 scale applies to it.
/// Here the child triangle is scaled 2× and offset by (10, 20). With
/// SCALED the effective translation is (20, 40); with UNSCALED it would
/// be (10, 20). Both forms are exercised to pin the difference.
fn build_scaled_offset_composite(child_index: u16, scaled: bool) -> Vec<u8> {
let mut g = Vec::new();
g.extend_from_slice(&(-1i16).to_be_bytes());
g.extend_from_slice(&0i16.to_be_bytes());
g.extend_from_slice(&0i16.to_be_bytes());
g.extend_from_slice(&0i16.to_be_bytes());
g.extend_from_slice(&0i16.to_be_bytes());
// flags: ARGS_ARE_XY_VALUES | WE_HAVE_A_SCALE | offset-mode bit.
let mut flags = C_ARGS_ARE_XY_VALUES | C_WE_HAVE_A_SCALE;
flags |= if scaled {
C_SCALED_COMPONENT_OFFSET
} else {
C_UNSCALED_COMPONENT_OFFSET
};
g.extend_from_slice(&flags.to_be_bytes());
g.extend_from_slice(&child_index.to_be_bytes());
// arg1=10 arg2=20 (i8 each, no ARG_1_AND_2_ARE_WORDS).
g.push(10i8 as u8);
g.push(20i8 as u8);
// F2DOT14 scale = 2.0 -> 2 * 16384 = 32768 which overflows i16,
// so use 1.5 (24576) to keep a representable signed value and a
// clean arithmetic check.
g.extend_from_slice(&24576i16.to_be_bytes());
g
}
#[test]
fn scaled_component_offset_transforms_the_offset_vector() {
let triangle = build_triangle(); // points (0,0) (100,0) (50,100)
// SCALED form.
let scaled = build_scaled_offset_composite(0, true);
let glyf_bytes: Vec<u8> = [triangle.as_slice(), scaled.as_slice()].concat();
let tri_len = triangle.len() as u32;
let total = glyf_bytes.len() as u32;
let mut loca_bytes = Vec::new();
for v in [0u32, tri_len, total] {
loca_bytes.extend_from_slice(&v.to_be_bytes());
}
let loca = LocaTable::parse(&loca_bytes, 2, 1).unwrap();
let glyf = GlyfTable::new(&glyf_bytes);
let out = glyf
.glyph_outline(tri_len as usize..total as usize, &loca, 0)
.unwrap();
// Child scaled 1.5×: (0,0)->(0,0), (100,0)->(150,0), (50,100)->(75,150).
// SCALED offset: (10,20) transformed by 1.5 = (15, 30).
let p = &out.contours[0].points;
assert_eq!((p[0].x, p[0].y), (15, 30));
assert_eq!((p[1].x, p[1].y), (165, 30));
assert_eq!((p[2].x, p[2].y), (90, 180));
}
#[test]
fn unscaled_component_offset_leaves_the_offset_vector_raw() {
let triangle = build_triangle();
let unscaled = build_scaled_offset_composite(0, false);
let glyf_bytes: Vec<u8> = [triangle.as_slice(), unscaled.as_slice()].concat();
let tri_len = triangle.len() as u32;
let total = glyf_bytes.len() as u32;
let mut loca_bytes = Vec::new();
for v in [0u32, tri_len, total] {
loca_bytes.extend_from_slice(&v.to_be_bytes());
}
let loca = LocaTable::parse(&loca_bytes, 2, 1).unwrap();
let glyf = GlyfTable::new(&glyf_bytes);
let out = glyf
.glyph_outline(tri_len as usize..total as usize, &loca, 0)
.unwrap();
// Child scaled 1.5×, offset applied raw (10, 20).
let p = &out.contours[0].points;
assert_eq!((p[0].x, p[0].y), (10, 20));
assert_eq!((p[1].x, p[1].y), (160, 20));
assert_eq!((p[2].x, p[2].y), (85, 170));
}
/// Point-matching placement (ARGS_ARE_XY_VALUES cleared). The parent
/// already incorporates one triangle component (points 0,1,2 at
/// (0,0),(100,0),(50,100)). A second component (another triangle)
/// aligns its own point 0 (child (0,0)) onto parent point 1
/// ((100,0)), so the offset is (100, 0).
#[test]
fn point_matching_aligns_child_point_onto_parent_point() {
let triangle = build_triangle();
// Composite with two components, both triangles (glyph 0).
let mut composite = Vec::new();
composite.extend_from_slice(&(-1i16).to_be_bytes());
for _ in 0..4 {
composite.extend_from_slice(&0i16.to_be_bytes());
}
// Component 1: XY offset (0,0), MORE_COMPONENTS set so a second
// component follows. First component must use ARGS_ARE_XY_VALUES.
let c1_flags = C_ARGS_ARE_XY_VALUES | C_MORE_COMPONENTS;
composite.extend_from_slice(&c1_flags.to_be_bytes());
composite.extend_from_slice(&0u16.to_be_bytes()); // child = glyph 0
composite.push(0); // arg1 = 0
composite.push(0); // arg2 = 0
// Component 2: point-matching. arg1 = parent point 1, arg2 = child
// point 0. No ARGS_ARE_XY_VALUES bit -> point match.
let c2_flags = 0u16; // no XY-values, no more components
composite.extend_from_slice(&c2_flags.to_be_bytes());
composite.extend_from_slice(&0u16.to_be_bytes()); // child = glyph 0
composite.push(1); // arg1 = parent point index 1
composite.push(0); // arg2 = child point index 0
let glyf_bytes: Vec<u8> = [triangle.as_slice(), composite.as_slice()].concat();
let tri_len = triangle.len() as u32;
let total = glyf_bytes.len() as u32;
let mut loca_bytes = Vec::new();
for v in [0u32, tri_len, total] {
loca_bytes.extend_from_slice(&v.to_be_bytes());
}
let loca = LocaTable::parse(&loca_bytes, 2, 1).unwrap();
let glyf = GlyfTable::new(&glyf_bytes);
let out = glyf
.glyph_outline(tri_len as usize..total as usize, &loca, 0)
.unwrap();
assert_eq!(out.contours.len(), 2);
// First component placed at origin.
let a = &out.contours[0].points;
assert_eq!((a[0].x, a[0].y), (0, 0));
assert_eq!((a[1].x, a[1].y), (100, 0));
// Second component aligned so child point 0 sits on parent point 1
// (100,0): offset = (100,0).
let b = &out.contours[1].points;
assert_eq!((b[0].x, b[0].y), (100, 0));
assert_eq!((b[1].x, b[1].y), (200, 0));
assert_eq!((b[2].x, b[2].y), (150, 100));
}
/// A point-matching component that references a point index past the
/// real point set (a phantom-point reference we can't resolve without
/// metrics) falls back to zero-offset placement rather than dropping
/// the component.
#[test]
fn point_matching_out_of_range_falls_back_to_zero_offset() {
let triangle = build_triangle();
let mut composite = Vec::new();
composite.extend_from_slice(&(-1i16).to_be_bytes());
for _ in 0..4 {
composite.extend_from_slice(&0i16.to_be_bytes());
}
// Single point-matching component referencing parent point 0 — but
// the parent is empty (no prior component), so point 0 is
// out-of-range and we fall back to (0,0).
let flags = 0u16;
composite.extend_from_slice(&flags.to_be_bytes());
composite.extend_from_slice(&0u16.to_be_bytes());
composite.push(0); // arg1 = parent point 0 (none exist yet)
composite.push(0); // arg2 = child point 0
let glyf_bytes: Vec<u8> = [triangle.as_slice(), composite.as_slice()].concat();
let tri_len = triangle.len() as u32;
let total = glyf_bytes.len() as u32;
let mut loca_bytes = Vec::new();
for v in [0u32, tri_len, total] {
loca_bytes.extend_from_slice(&v.to_be_bytes());
}
let loca = LocaTable::parse(&loca_bytes, 2, 1).unwrap();
let glyf = GlyfTable::new(&glyf_bytes);
let out = glyf
.glyph_outline(tri_len as usize..total as usize, &loca, 0)
.unwrap();
assert_eq!(out.contours.len(), 1);
let p = &out.contours[0].points;
assert_eq!((p[0].x, p[0].y), (0, 0));
assert_eq!((p[1].x, p[1].y), (100, 0));
}
#[test]
fn composite_self_cycle_terminates_with_composite_too_deep() {
// Two glyphs:
// glyph 0 = triangle (innocent bystander, used only so loca
// has a valid first entry; the self-cycling glyph
// below is glyph 1).
// glyph 1 = composite referencing glyph 1 (itself).
let triangle = build_triangle();
let self_cycle = build_composite_referencing(1);
let mut glyf = triangle.clone();
let tri_len = glyf.len() as u32;
glyf.extend_from_slice(&self_cycle);
let total = glyf.len() as u32;
let mut loca_bytes = Vec::new();
for v in [0u32, tri_len, total] {
loca_bytes.extend_from_slice(&v.to_be_bytes());
}
let loca = LocaTable::parse(&loca_bytes, 2, 1).unwrap();
let glyf_t = GlyfTable::new(&glyf);
let err = glyf_t
.glyph_outline(tri_len as usize..total as usize, &loca, 0)
.expect_err("self-cycle must reject, not stack-overflow");
assert_eq!(err, Error::CompositeTooDeep);
}
/// Build a two-component composite "é"-shape glyph: component 0 is
/// glyph 0 (triangle) at offset (0,0), component 1 is glyph 0 at
/// offset (`c1x`, `c1y`). Both use ARGS_ARE_XY_VALUES word args, no
/// transform. Mirrors the §7.3.4.3 example layout (a base + accent
/// composite with two XY-placed components).
fn build_two_component_composite(c1x: i16, c1y: i16) -> Vec<u8> {
let mut g = Vec::new();
g.extend_from_slice(&(-1i16).to_be_bytes());
for _ in 0..4 {
g.extend_from_slice(&0i16.to_be_bytes());
}
// Component 0: XY offset (0,0), MORE_COMPONENTS set.
let c0 = C_ARGS_ARE_XY_VALUES | C_ARG_1_AND_2_ARE_WORDS | C_MORE_COMPONENTS;
g.extend_from_slice(&c0.to_be_bytes());
g.extend_from_slice(&0u16.to_be_bytes()); // child = glyph 0
g.extend_from_slice(&0i16.to_be_bytes()); // arg1
g.extend_from_slice(&0i16.to_be_bytes()); // arg2
// Component 1: XY offset (c1x, c1y), last component.
let c1 = C_ARGS_ARE_XY_VALUES | C_ARG_1_AND_2_ARE_WORDS;
g.extend_from_slice(&c1.to_be_bytes());
g.extend_from_slice(&0u16.to_be_bytes()); // child = glyph 0
g.extend_from_slice(&c1x.to_be_bytes());
g.extend_from_slice(&c1y.to_be_bytes());
g
}
#[test]
fn composite_component_count_walks_all_entries() {
let triangle = build_triangle();
let composite = build_two_component_composite(286, 0);
let glyf_bytes: Vec<u8> = [triangle.as_slice(), composite.as_slice()].concat();
let tri_len = triangle.len();
let total = glyf_bytes.len();
let glyf = GlyfTable::new(&glyf_bytes);
// Composite has 2 components.
assert_eq!(glyf.composite_component_count(tri_len..total).unwrap(), 2);
// A simple glyph reports 0.
assert_eq!(glyf.composite_component_count(0..tri_len).unwrap(), 0);
}
/// §7.3.4.3: a per-component placement delta is added to the
/// component's argument1/argument2 X/Y offset for the
/// ARGS_ARE_XY_VALUES form. Component 0 keeps (0,0); component 1's
/// default offset (286, 0) plus a delta of (54, 0) lands the second
/// triangle at X = 340.
#[test]
fn composite_var_folds_component_delta_into_offset() {
let triangle = build_triangle(); // points (0,0) (100,0) (50,100)
let composite = build_two_component_composite(286, 0);
let glyf_bytes: Vec<u8> = [triangle.as_slice(), composite.as_slice()].concat();
let tri_len = triangle.len() as u32;
let total = glyf_bytes.len() as u32;
let mut loca_bytes = Vec::new();
for v in [0u32, tri_len, total] {
loca_bytes.extend_from_slice(&v.to_be_bytes());
}
let loca = LocaTable::parse(&loca_bytes, 2, 1).unwrap();
let glyf = GlyfTable::new(&glyf_bytes);
// Component-0 delta (0,0); component-1 delta (54,0).
let deltas = [(0i32, 0i32), (54i32, 0i32)];
// Static child resolver: components decode without their own var.
let resolve = |gid: u16, depth: u8| {
let r = loca.glyph_range(gid)?;
glyf.glyph_outline(r, &loca, depth)
};
let out = glyf
.glyph_outline_var(
tri_len as usize..total as usize,
&loca,
0,
&deltas,
&resolve,
)
.unwrap();
assert_eq!(out.contours.len(), 2);
// Component 0 sits at the origin unchanged.
let a = &out.contours[0].points;
assert_eq!((a[0].x, a[0].y), (0, 0));
// Component 1: default offset 286 + delta 54 = 340.
let b = &out.contours[1].points;
assert_eq!((b[0].x, b[0].y), (340, 0));
assert_eq!((b[1].x, b[1].y), (440, 0));
assert_eq!((b[2].x, b[2].y), (390, 100));
}
/// With an empty / all-zero delta slice the variable composite path
/// reproduces the static placement exactly.
#[test]
fn composite_var_zero_deltas_matches_static() {
let triangle = build_triangle();
let composite = build_two_component_composite(286, 0);
let glyf_bytes: Vec<u8> = [triangle.as_slice(), composite.as_slice()].concat();
let tri_len = triangle.len() as u32;
let total = glyf_bytes.len() as u32;
let mut loca_bytes = Vec::new();
for v in [0u32, tri_len, total] {
loca_bytes.extend_from_slice(&v.to_be_bytes());
}
let loca = LocaTable::parse(&loca_bytes, 2, 1).unwrap();
let glyf = GlyfTable::new(&glyf_bytes);
let r = tri_len as usize..total as usize;
let resolve = |gid: u16, depth: u8| {
let rr = loca.glyph_range(gid)?;
glyf.glyph_outline(rr, &loca, depth)
};
let var = glyf
.glyph_outline_var(r.clone(), &loca, 0, &[(0, 0), (0, 0)], &resolve)
.unwrap();
let stat = glyf.glyph_outline(r, &loca, 0).unwrap();
assert_eq!(var, stat);
}
/// §7.3.4.3: point-matched components (ARGS_ARE_XY_VALUES clear) take
/// no delta. A delta supplied for such a component must be ignored.
#[test]
fn composite_var_point_matched_component_ignores_delta() {
let triangle = build_triangle();
// Composite: component 0 XY-placed (gets delta), component 1
// point-matched (must NOT get a delta).
let mut composite = Vec::new();
composite.extend_from_slice(&(-1i16).to_be_bytes());
for _ in 0..4 {
composite.extend_from_slice(&0i16.to_be_bytes());
}
let c0 = C_ARGS_ARE_XY_VALUES | C_MORE_COMPONENTS;
composite.extend_from_slice(&c0.to_be_bytes());
composite.extend_from_slice(&0u16.to_be_bytes());
composite.push(0); // arg1
composite.push(0); // arg2
let c1 = 0u16; // point-matched, last component
composite.extend_from_slice(&c1.to_be_bytes());
composite.extend_from_slice(&0u16.to_be_bytes());
composite.push(1); // arg1 = parent point 1
composite.push(0); // arg2 = child point 0
let glyf_bytes: Vec<u8> = [triangle.as_slice(), composite.as_slice()].concat();
let tri_len = triangle.len() as u32;
let total = glyf_bytes.len() as u32;
let mut loca_bytes = Vec::new();
for v in [0u32, tri_len, total] {
loca_bytes.extend_from_slice(&v.to_be_bytes());
}
let loca = LocaTable::parse(&loca_bytes, 2, 1).unwrap();
let glyf = GlyfTable::new(&glyf_bytes);
// Component 0 delta (5,0); component 1 delta (999,999) must be
// ignored because it is point-matched.
let deltas = [(5i32, 0i32), (999i32, 999i32)];
let resolve = |gid: u16, depth: u8| {
let r = loca.glyph_range(gid)?;
glyf.glyph_outline(r, &loca, depth)
};
let out = glyf
.glyph_outline_var(
tri_len as usize..total as usize,
&loca,
0,
&deltas,
&resolve,
)
.unwrap();
assert_eq!(out.contours.len(), 2);
// Component 0 shifted by its (5,0) delta from the origin.
let a = &out.contours[0].points;
assert_eq!((a[0].x, a[0].y), (5, 0));
// Component 1 point-matched: child point 0 aligns onto parent
// point 1 (component 0's point 1 = (105, 0)), with NO 999 shift.
let b = &out.contours[1].points;
assert_eq!((b[0].x, b[0].y), (105, 0));
}
/// Build a composite glyph body with two components: glyph 7 (no
/// metrics flag) followed by glyph `flagged`, the latter carrying
/// `USE_MY_METRICS`. Returns the whole glyph record (header + body).
fn build_composite_use_my_metrics(flagged: u16) -> Vec<u8> {
let mut g = Vec::new();
g.extend_from_slice(&(-1i16).to_be_bytes()); // numberOfContours < 0
for _ in 0..4 {
g.extend_from_slice(&0i16.to_be_bytes()); // bbox
}
// Component 0: glyph 7, XY values, more components follow.
g.extend_from_slice(&(C_ARGS_ARE_XY_VALUES | C_MORE_COMPONENTS).to_be_bytes());
g.extend_from_slice(&7u16.to_be_bytes());
g.push(0);
g.push(0);
// Component 1: `flagged`, USE_MY_METRICS, last component.
g.extend_from_slice(&(C_ARGS_ARE_XY_VALUES | C_USE_MY_METRICS).to_be_bytes());
g.extend_from_slice(&flagged.to_be_bytes());
g.push(0);
g.push(0);
g
}
#[test]
fn use_my_metrics_returns_flagged_component() {
let body = build_composite_use_my_metrics(42);
let glyf = GlyfTable::new(&body);
let g = glyf.use_my_metrics_glyph(0..body.len()).unwrap();
assert_eq!(g, Some(42));
}
#[test]
fn use_my_metrics_none_without_flag() {
// A composite with both components un-flagged.
let mut g = Vec::new();
g.extend_from_slice(&(-1i16).to_be_bytes());
for _ in 0..4 {
g.extend_from_slice(&0i16.to_be_bytes());
}
g.extend_from_slice(&C_ARGS_ARE_XY_VALUES.to_be_bytes()); // no flag, no more
g.extend_from_slice(&7u16.to_be_bytes());
g.push(0);
g.push(0);
let glyf = GlyfTable::new(&g);
assert_eq!(glyf.use_my_metrics_glyph(0..g.len()).unwrap(), None);
}
#[test]
fn use_my_metrics_last_flagged_wins() {
// Two flagged components: glyph 5 then glyph 9; the last wins.
let mut g = Vec::new();
g.extend_from_slice(&(-1i16).to_be_bytes());
for _ in 0..4 {
g.extend_from_slice(&0i16.to_be_bytes());
}
g.extend_from_slice(
&(C_ARGS_ARE_XY_VALUES | C_USE_MY_METRICS | C_MORE_COMPONENTS).to_be_bytes(),
);
g.extend_from_slice(&5u16.to_be_bytes());
g.push(0);
g.push(0);
g.extend_from_slice(&(C_ARGS_ARE_XY_VALUES | C_USE_MY_METRICS).to_be_bytes());
g.extend_from_slice(&9u16.to_be_bytes());
g.push(0);
g.push(0);
let glyf = GlyfTable::new(&g);
assert_eq!(glyf.use_my_metrics_glyph(0..g.len()).unwrap(), Some(9));
}
#[test]
fn use_my_metrics_none_for_simple_glyph() {
let triangle = build_triangle();
let glyf = GlyfTable::new(&triangle);
assert_eq!(glyf.use_my_metrics_glyph(0..triangle.len()).unwrap(), None);
}
}