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
#[cfg(feature = "outline")]
mod outline;
use std::convert::TryFrom;
use std::iter;
use bitflags::bitflags;
use itertools::Itertools;
use log::warn;
use crate::binary::read::{ReadBinary, ReadBinaryDep, ReadCtxt, ReadFrom, ReadScope};
use crate::binary::write::{WriteBinary, WriteBinaryDep, WriteContext};
use crate::binary::{word_align, I16Be, U16Be, I8, U8};
use crate::error::{ParseError, WriteError};
use crate::tables::loca::{owned, LocaTable};
use crate::tables::{F2Dot14, IndexToLocFormat};
bitflags! {
#[rustfmt::skip]
pub struct SimpleGlyphFlag: u8 {
const ON_CURVE_POINT = 0b00000001;
const X_SHORT_VECTOR = 0b00000010;
const Y_SHORT_VECTOR = 0b00000100;
const REPEAT_FLAG = 0b00001000;
const X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR = 0b00010000;
const Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR = 0b00100000;
}
}
bitflags! {
pub struct CompositeGlyphFlag: u16 {
const ARG_1_AND_2_ARE_WORDS = 0x0001;
const ARGS_ARE_XY_VALUES = 0x0002;
const ROUND_XY_TO_GRID = 0x0004;
const WE_HAVE_A_SCALE = 0x0008;
const MORE_COMPONENTS = 0x0020;
const WE_HAVE_AN_X_AND_Y_SCALE = 0x0040;
const WE_HAVE_A_TWO_BY_TWO = 0x0080;
const WE_HAVE_INSTRUCTIONS = 0x0100;
const USE_MY_METRICS = 0x0200;
const OVERLAP_COMPOUND = 0x0400;
const SCALED_COMPONENT_OFFSET = 0x0800;
const UNSCALED_COMPONENT_OFFSET = 0x1000;
}
}
#[derive(Debug, PartialEq)]
pub struct GlyfTable<'a> {
pub records: Vec<GlyfRecord<'a>>,
}
#[derive(Debug, PartialEq, Clone)]
pub enum GlyfRecord<'a> {
Empty,
Present {
number_of_contours: i16,
scope: ReadScope<'a>,
},
Parsed(Glyph<'a>),
}
#[derive(Debug, PartialEq, Clone)]
pub struct Glyph<'a> {
pub number_of_contours: i16,
pub bounding_box: BoundingBox,
pub data: GlyphData<'a>,
}
#[derive(Debug, PartialEq, Clone)]
pub enum GlyphData<'a> {
Simple(SimpleGlyph<'a>),
Composite {
glyphs: Vec<CompositeGlyph>,
instructions: &'a [u8],
},
}
#[derive(Debug, PartialEq, Clone)]
pub struct SimpleGlyph<'a> {
pub end_pts_of_contours: Vec<u16>,
pub instructions: &'a [u8],
pub flags: Vec<SimpleGlyphFlag>,
pub coordinates: Vec<Point>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct CompositeGlyph {
pub flags: CompositeGlyphFlag,
pub glyph_index: u16,
pub argument1: CompositeGlyphArgument,
pub argument2: CompositeGlyphArgument,
pub scale: Option<CompositeGlyphScale>,
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum CompositeGlyphArgument {
U8(u8),
I8(i8),
U16(u16),
I16(i16),
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum CompositeGlyphScale {
Scale(F2Dot14),
XY { x_scale: F2Dot14, y_scale: F2Dot14 },
Matrix([[F2Dot14; 2]; 2]),
}
pub struct CompositeGlyphs {
pub glyphs: Vec<CompositeGlyph>,
pub have_instructions: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Point(pub i16, pub i16);
#[derive(Debug, PartialEq, Clone)]
pub struct BoundingBox {
pub x_min: i16,
pub x_max: i16,
pub y_min: i16,
pub y_max: i16,
}
impl<'a> ReadBinaryDep<'a> for GlyfTable<'a> {
type Args = &'a LocaTable<'a>;
type HostType = Self;
fn read_dep(ctxt: &mut ReadCtxt<'a>, loca: Self::Args) -> Result<Self, ParseError> {
if loca.offsets.len() < 2 {
return Err(ParseError::BadIndex);
}
let glyph_records = loca
.offsets
.iter()
.tuple_windows()
.map(|(start, end)| match end.checked_sub(start) {
Some(0) => Ok(GlyfRecord::Empty),
Some(length) => {
let offset = usize::try_from(start)?;
let glyph_scope = ctxt.scope().offset_length(offset, usize::try_from(length)?);
match glyph_scope {
Ok(scope) => {
let number_of_contours = scope.read::<I16Be>()?;
Ok(GlyfRecord::Present {
number_of_contours,
scope,
})
}
Err(ParseError::BadEof) => {
warn!("glyph length out of bounds, trying to parse");
let scope = ctxt.scope().offset(offset);
scope.read::<Glyph<'_>>().map(GlyfRecord::Parsed)
}
Err(err) => Err(err),
}
}
None => Err(ParseError::BadOffset),
})
.collect::<Result<Vec<_>, _>>()?;
Ok(GlyfTable {
records: glyph_records,
})
}
}
impl<'a> WriteBinaryDep<Self> for GlyfTable<'a> {
type Output = owned::LocaTable;
type Args = IndexToLocFormat;
fn write_dep<C: WriteContext>(
ctxt: &mut C,
table: GlyfTable<'a>,
index_to_loc_format: IndexToLocFormat,
) -> Result<Self::Output, WriteError> {
let mut offsets: Vec<u32> = Vec::with_capacity(table.records.len() + 1);
let start = ctxt.bytes_written();
for record in table.records {
let offset = ctxt.bytes_written();
offsets.push(u32::try_from(ctxt.bytes_written() - start)?);
match record {
GlyfRecord::Empty => (),
GlyfRecord::Present { scope, .. } => ReadScope::write(ctxt, scope)?,
GlyfRecord::Parsed(glyph) => Glyph::write(ctxt, glyph)?,
}
if index_to_loc_format == IndexToLocFormat::Short {
let length = ctxt.bytes_written() - offset;
let padded_length = word_align(length);
ctxt.write_zeros(padded_length - length)?;
}
}
offsets.push(u32::try_from(ctxt.bytes_written() - start)?);
Ok(owned::LocaTable { offsets })
}
}
impl<'a> ReadBinary<'a> for Glyph<'a> {
type HostType = Self;
fn read(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
let number_of_contours = ctxt.read_i16be()?;
let bounding_box = ctxt.read::<BoundingBox>()?;
if number_of_contours >= 0 {
let glyph = ctxt.read_dep::<SimpleGlyph<'_>>(number_of_contours as u16)?;
Ok(Glyph {
number_of_contours,
bounding_box,
data: GlyphData::Simple(glyph),
})
} else {
let glyphs = ctxt.read::<CompositeGlyphs>()?;
let instruction_length = if glyphs.have_instructions {
usize::from(ctxt.read::<U16Be>()?)
} else {
0
};
let instructions = ctxt.read_slice(instruction_length)?;
Ok(Glyph {
number_of_contours,
bounding_box,
data: GlyphData::Composite {
glyphs: glyphs.glyphs,
instructions,
},
})
}
}
}
impl<'a> WriteBinary for Glyph<'a> {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, glyph: Glyph<'a>) -> Result<(), WriteError> {
I16Be::write(ctxt, glyph.number_of_contours)?;
BoundingBox::write(ctxt, glyph.bounding_box)?;
match glyph.data {
GlyphData::Simple(simple_glyph) => SimpleGlyph::write(ctxt, simple_glyph)?,
GlyphData::Composite {
glyphs,
instructions,
} => {
let mut has_instructions = false;
for glyph in glyphs {
has_instructions |= glyph.flags.we_have_instructions();
CompositeGlyph::write(ctxt, glyph)?;
}
if has_instructions {
U16Be::write(ctxt, u16::try_from(instructions.len())?)?;
ctxt.write_bytes(instructions)?;
}
}
}
Ok(())
}
}
impl<'a> SimpleGlyph<'a> {
pub fn contours(&self) -> impl Iterator<Item = &[Point]> {
self.end_pts_of_contours.iter().scan(0, move |i, &end| {
let start = *i;
let end = usize::from(end);
*i = end + 1;
self.coordinates.get(start..=end)
})
}
pub fn contour_flags(&self) -> impl Iterator<Item = &[SimpleGlyphFlag]> {
self.end_pts_of_contours.iter().scan(0, move |i, &end| {
let start = *i;
let end = usize::from(end);
*i = end + 1;
self.flags.get(start..=end)
})
}
}
impl<'a> ReadBinaryDep<'a> for SimpleGlyph<'a> {
type Args = u16;
type HostType = Self;
fn read_dep(
ctxt: &mut ReadCtxt<'a>,
number_of_contours: Self::Args,
) -> Result<Self, ParseError> {
let number_of_contours = usize::from(number_of_contours);
let end_pts_of_contours = ctxt.read_array::<U16Be>(number_of_contours)?.to_vec();
let instruction_length = ctxt.read::<U16Be>()?;
let instructions = ctxt.read_slice(usize::from(instruction_length))?;
let number_of_coordinates = end_pts_of_contours
.last()
.map_or(0, |&last| usize::from(last) + 1);
let mut flags = Vec::with_capacity(number_of_contours);
while flags.len() < number_of_coordinates {
let flag = ctxt.read::<SimpleGlyphFlag>()?;
if flag.is_repeated() {
let count = usize::from(ctxt.read::<U8>()?) + 1;
let repeat = iter::repeat(flag).take(count);
flags.extend(repeat)
} else {
flags.push(flag);
}
}
let mut coordinates = flags
.iter()
.map(|flag| {
if flag.x_is_short() {
ctxt.read::<U8>()
.map(|val| i16::from(val) * flag.x_short_sign())
} else if flag.x_is_same_or_positive() {
Ok(0)
} else {
ctxt.read::<I16Be>()
}
.map(|x| Point(x, 0))
})
.collect::<Result<Vec<_>, _>>()?;
let mut prev_point = Point(0, 0);
for (flag, point) in flags.iter().zip(coordinates.iter_mut()) {
let y = if flag.y_is_short() {
ctxt.read::<U8>()
.map(|val| i16::from(val) * flag.y_short_sign())?
} else if flag.y_is_same_or_positive() {
0
} else {
ctxt.read::<I16Be>()?
};
prev_point = Point(prev_point.0 + point.0, prev_point.1 + y);
*point = prev_point
}
Ok(SimpleGlyph {
end_pts_of_contours,
instructions,
flags,
coordinates,
})
}
}
impl<'a> WriteBinary for SimpleGlyph<'a> {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, glyph: SimpleGlyph<'_>) -> Result<(), WriteError> {
assert!(glyph.flags.len() == glyph.coordinates.len());
ctxt.write_vec::<U16Be>(glyph.end_pts_of_contours)?;
U16Be::write(ctxt, u16::try_from(glyph.instructions.len())?)?;
ctxt.write_bytes(&glyph.instructions)?;
let mask = SimpleGlyphFlag::ON_CURVE_POINT;
for flag in glyph.flags {
U8::write(ctxt, (flag & mask).bits())?;
}
let mut prev_x = 0;
for Point(x, _) in &glyph.coordinates {
let delta_x = x - prev_x;
I16Be::write(ctxt, delta_x)?;
prev_x = *x;
}
let mut prev_y = 0;
for Point(_, y) in &glyph.coordinates {
let delta_y = y - prev_y;
I16Be::write(ctxt, delta_y)?;
prev_y = *y;
}
Ok(())
}
}
impl<'a> ReadFrom<'a> for SimpleGlyphFlag {
type ReadType = U8;
fn from(flag: u8) -> Self {
SimpleGlyphFlag::from_bits_truncate(flag)
}
}
impl<'a> ReadBinary<'a> for CompositeGlyphs {
type HostType = Self;
fn read(ctxt: &mut ReadCtxt<'_>) -> Result<Self, ParseError> {
let mut have_instructions = false;
let mut glyphs = Vec::new();
loop {
let flags = ctxt.read::<CompositeGlyphFlag>()?;
let data = ctxt.read_dep::<CompositeGlyph>(flags)?;
if flags.we_have_instructions() {
have_instructions = true;
}
glyphs.push(data);
if !flags.more_components() {
break;
}
}
Ok(CompositeGlyphs {
glyphs,
have_instructions,
})
}
}
impl SimpleGlyphFlag {
pub fn is_on_curve(self) -> bool {
self & Self::ON_CURVE_POINT == Self::ON_CURVE_POINT
}
pub fn x_is_short(self) -> bool {
self & Self::X_SHORT_VECTOR == Self::X_SHORT_VECTOR
}
pub fn y_is_short(self) -> bool {
self & Self::Y_SHORT_VECTOR == Self::Y_SHORT_VECTOR
}
pub fn is_repeated(self) -> bool {
self & Self::REPEAT_FLAG == Self::REPEAT_FLAG
}
pub fn x_short_sign(self) -> i16 {
if self.x_is_same_or_positive() {
1
} else {
-1
}
}
pub fn y_short_sign(self) -> i16 {
if self.y_is_same_or_positive() {
1
} else {
-1
}
}
pub fn x_is_same_or_positive(self) -> bool {
self & Self::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR
== Self::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR
}
pub fn y_is_same_or_positive(self) -> bool {
self & Self::Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR
== Self::Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR
}
}
impl<'a> ReadFrom<'a> for CompositeGlyphFlag {
type ReadType = U16Be;
fn from(flag: u16) -> Self {
CompositeGlyphFlag::from_bits_truncate(flag)
}
}
impl<'a> ReadBinaryDep<'a> for CompositeGlyphArgument {
type Args = CompositeGlyphFlag;
type HostType = Self;
fn read_dep(ctxt: &mut ReadCtxt<'a>, flags: Self::Args) -> Result<Self, ParseError> {
let arg = match (flags.arg_1_and_2_are_words(), flags.args_are_xy_values()) {
(true, true) => CompositeGlyphArgument::I16(ctxt.read_i16be()?),
(true, false) => CompositeGlyphArgument::U16(ctxt.read_u16be()?),
(false, true) => CompositeGlyphArgument::I8(ctxt.read_i8()?),
(false, false) => CompositeGlyphArgument::U8(ctxt.read_u8()?),
};
Ok(arg)
}
}
impl<'a> WriteBinary for CompositeGlyphArgument {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, arg: CompositeGlyphArgument) -> Result<(), WriteError> {
match arg {
CompositeGlyphArgument::U8(val) => U8::write(ctxt, val),
CompositeGlyphArgument::I8(val) => I8::write(ctxt, val),
CompositeGlyphArgument::U16(val) => U16Be::write(ctxt, val),
CompositeGlyphArgument::I16(val) => I16Be::write(ctxt, val),
}
}
}
impl<'a> ReadBinaryDep<'a> for CompositeGlyph {
type Args = CompositeGlyphFlag;
type HostType = Self;
fn read_dep(ctxt: &mut ReadCtxt<'a>, flags: Self::Args) -> Result<Self, ParseError> {
let glyph_index = ctxt.read_u16be()?;
let argument1 = ctxt.read_dep::<CompositeGlyphArgument>(flags)?;
let argument2 = ctxt.read_dep::<CompositeGlyphArgument>(flags)?;
let scale = if flags.we_have_a_scale() {
Some(CompositeGlyphScale::Scale(ctxt.read::<F2Dot14>()?))
} else if flags.we_have_an_x_and_y_scale() {
Some(CompositeGlyphScale::XY {
x_scale: ctxt.read::<F2Dot14>()?,
y_scale: ctxt.read::<F2Dot14>()?,
})
} else if flags.we_have_a_two_by_two() {
Some(CompositeGlyphScale::Matrix([
[ctxt.read::<F2Dot14>()?, ctxt.read::<F2Dot14>()?],
[ctxt.read::<F2Dot14>()?, ctxt.read::<F2Dot14>()?],
]))
} else {
None
};
Ok(CompositeGlyph {
flags,
glyph_index,
argument1,
argument2,
scale,
})
}
}
impl<'a> WriteBinary for CompositeGlyph {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, glyph: CompositeGlyph) -> Result<(), WriteError> {
U16Be::write(ctxt, glyph.flags.bits())?;
U16Be::write(ctxt, glyph.glyph_index)?;
CompositeGlyphArgument::write(ctxt, glyph.argument1)?;
CompositeGlyphArgument::write(ctxt, glyph.argument2)?;
if let Some(scale) = glyph.scale {
CompositeGlyphScale::write(ctxt, scale)?;
}
Ok(())
}
}
impl<'a> WriteBinary for CompositeGlyphScale {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, scale: CompositeGlyphScale) -> Result<(), WriteError> {
match scale {
CompositeGlyphScale::Scale(scale) => F2Dot14::write(ctxt, scale)?,
CompositeGlyphScale::XY { x_scale, y_scale } => {
F2Dot14::write(ctxt, x_scale)?;
F2Dot14::write(ctxt, y_scale)?;
}
CompositeGlyphScale::Matrix(matrix) => {
F2Dot14::write(ctxt, matrix[0][0])?;
F2Dot14::write(ctxt, matrix[0][1])?;
F2Dot14::write(ctxt, matrix[1][0])?;
F2Dot14::write(ctxt, matrix[1][1])?;
}
}
Ok(())
}
}
impl<'a> ReadBinary<'a> for BoundingBox {
type HostType = Self;
fn read(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
let x_min = ctxt.read::<I16Be>()?;
let y_min = ctxt.read::<I16Be>()?;
let x_max = ctxt.read::<I16Be>()?;
let y_max = ctxt.read::<I16Be>()?;
Ok(BoundingBox {
x_min,
y_min,
x_max,
y_max,
})
}
}
impl<'a> WriteBinary for BoundingBox {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, bbox: BoundingBox) -> Result<(), WriteError> {
I16Be::write(ctxt, bbox.x_min)?;
I16Be::write(ctxt, bbox.y_min)?;
I16Be::write(ctxt, bbox.x_max)?;
I16Be::write(ctxt, bbox.y_max)?;
Ok(())
}
}
struct SubsetGlyph<'a> {
old_id: u16,
record: GlyfRecord<'a>,
}
fn add_glyph(glyph_ids: &mut Vec<u16>, record: &mut GlyfRecord<'_>) {
match record {
GlyfRecord::Parsed(Glyph {
data: GlyphData::Composite { glyphs, .. },
..
}) => {
for composite_glyph in glyphs.iter_mut() {
let new_id = glyph_ids
.iter()
.position(|&id| id == composite_glyph.glyph_index)
.unwrap_or_else(|| {
let new_id = glyph_ids.len();
glyph_ids.push(composite_glyph.glyph_index);
new_id
});
composite_glyph.glyph_index = new_id as u16;
}
}
_ => unreachable!(),
}
}
impl<'a> GlyfTable<'a> {
pub fn subset(&self, glyph_ids: &[u16]) -> Result<(GlyfTable<'a>, Vec<u16>), ParseError> {
let mut glyph_ids = glyph_ids.to_vec();
let mut records = Vec::with_capacity(glyph_ids.len());
let mut i = 0;
while i < glyph_ids.len() {
let glyph_id = glyph_ids[i];
let mut record = self
.records
.get(usize::from(glyph_id))
.ok_or(ParseError::BadIndex)?
.clone();
if record.is_composite() {
record.parse()?;
add_glyph(&mut glyph_ids, &mut record);
}
records.push(SubsetGlyph {
old_id: glyph_id,
record,
});
i += 1;
}
let mut new_to_old_id = vec![0u16; records.len()];
let records = records
.into_iter()
.enumerate()
.map(|(new_id, subset_record)| {
new_to_old_id[new_id] = subset_record.old_id;
subset_record.record
})
.collect();
Ok((GlyfTable { records }, new_to_old_id))
}
pub fn get_parsed_glyph(&mut self, glyph_index: u16) -> Result<Option<&Glyph<'_>>, ParseError> {
let record = self
.records
.get_mut(usize::from(glyph_index))
.ok_or_else(|| ParseError::BadIndex)?;
record.parse()?;
match record {
GlyfRecord::Empty => return Ok(None),
GlyfRecord::Parsed(glyph) => Ok(Some(glyph)),
GlyfRecord::Present { .. } => unreachable!("glyph should be parsed"),
}
}
}
impl<'a> GlyfRecord<'a> {
pub fn number_of_contours(&self) -> i16 {
match self {
GlyfRecord::Empty => 0,
GlyfRecord::Present {
number_of_contours, ..
} => *number_of_contours,
GlyfRecord::Parsed(glyph) => glyph.number_of_contours,
}
}
pub fn is_composite(&self) -> bool {
self.number_of_contours() < 0
}
pub fn parse(&mut self) -> Result<(), ParseError> {
if let GlyfRecord::Present { scope, .. } = self {
*self = scope.read::<Glyph<'_>>().map(GlyfRecord::Parsed)?;
}
Ok(())
}
}
impl CompositeGlyphFlag {
pub fn arg_1_and_2_are_words(self) -> bool {
self & Self::ARG_1_AND_2_ARE_WORDS == Self::ARG_1_AND_2_ARE_WORDS
}
pub fn args_are_xy_values(self) -> bool {
self & Self::ARGS_ARE_XY_VALUES == Self::ARGS_ARE_XY_VALUES
}
pub fn we_have_a_scale(self) -> bool {
self & Self::WE_HAVE_A_SCALE == Self::WE_HAVE_A_SCALE
}
pub fn we_have_an_x_and_y_scale(self) -> bool {
self & Self::WE_HAVE_AN_X_AND_Y_SCALE == Self::WE_HAVE_AN_X_AND_Y_SCALE
}
pub fn we_have_a_two_by_two(self) -> bool {
self & Self::WE_HAVE_A_TWO_BY_TWO == Self::WE_HAVE_A_TWO_BY_TWO
}
pub fn more_components(self) -> bool {
self & Self::MORE_COMPONENTS == Self::MORE_COMPONENTS
}
pub fn we_have_instructions(self) -> bool {
self & Self::WE_HAVE_INSTRUCTIONS == Self::WE_HAVE_INSTRUCTIONS
}
}
impl BoundingBox {
pub fn from_points(points: &[Point]) -> Self {
assert!(!points.is_empty());
let Point(initial_x, initial_y) = points[0];
let initial = BoundingBox {
x_min: initial_x,
x_max: initial_x,
y_min: initial_y,
y_max: initial_y,
};
points
.iter()
.fold(initial, |mut bounding_box, &Point(x, y)| {
if x < bounding_box.x_min {
bounding_box.x_min = x
}
if x > bounding_box.x_max {
bounding_box.x_max = x
}
if y < bounding_box.y_min {
bounding_box.y_min = y
}
if y > bounding_box.y_max {
bounding_box.y_max = y
}
bounding_box
})
}
}
impl<'a> SimpleGlyph<'a> {
pub fn bounding_box(&self) -> BoundingBox {
BoundingBox::from_points(&self.coordinates)
}
}
impl From<CompositeGlyphArgument> for i32 {
fn from(arg: CompositeGlyphArgument) -> Self {
match arg {
CompositeGlyphArgument::U8(value) => i32::from(value),
CompositeGlyphArgument::I8(value) => i32::from(value),
CompositeGlyphArgument::U16(value) => i32::from(value),
CompositeGlyphArgument::I16(value) => i32::from(value),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::binary::write::WriteBuffer;
pub(super) fn simple_glyph_fixture() -> Glyph<'static> {
let simple_glyph = SimpleGlyph {
end_pts_of_contours: vec![8],
instructions: &[],
flags: vec![
SimpleGlyphFlag::ON_CURVE_POINT
| SimpleGlyphFlag::Y_SHORT_VECTOR
| SimpleGlyphFlag::Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR,
SimpleGlyphFlag::X_SHORT_VECTOR
| SimpleGlyphFlag::Y_SHORT_VECTOR
| SimpleGlyphFlag::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR,
SimpleGlyphFlag::ON_CURVE_POINT
| SimpleGlyphFlag::X_SHORT_VECTOR
| SimpleGlyphFlag::Y_SHORT_VECTOR
| SimpleGlyphFlag::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR,
SimpleGlyphFlag::X_SHORT_VECTOR
| SimpleGlyphFlag::Y_SHORT_VECTOR
| SimpleGlyphFlag::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR,
SimpleGlyphFlag::ON_CURVE_POINT
| SimpleGlyphFlag::X_SHORT_VECTOR
| SimpleGlyphFlag::Y_SHORT_VECTOR
| SimpleGlyphFlag::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR,
SimpleGlyphFlag::X_SHORT_VECTOR | SimpleGlyphFlag::Y_SHORT_VECTOR,
SimpleGlyphFlag::ON_CURVE_POINT
| SimpleGlyphFlag::X_SHORT_VECTOR
| SimpleGlyphFlag::Y_SHORT_VECTOR,
SimpleGlyphFlag::X_SHORT_VECTOR | SimpleGlyphFlag::Y_SHORT_VECTOR,
SimpleGlyphFlag::ON_CURVE_POINT
| SimpleGlyphFlag::X_SHORT_VECTOR
| SimpleGlyphFlag::Y_SHORT_VECTOR,
],
coordinates: vec![
Point(433, 77),
Point(499, 30),
Point(625, 2),
Point(756, -27),
Point(915, -31),
Point(891, -47),
Point(862, -60),
Point(832, -73),
Point(819, -103),
],
};
Glyph {
number_of_contours: 1,
bounding_box: BoundingBox {
x_min: 60,
x_max: 915,
y_min: -105,
y_max: 702,
},
data: GlyphData::Simple(simple_glyph),
}
}
pub(super) fn composite_glyph_fixture(instructions: &'static [u8]) -> Glyph<'static> {
Glyph {
number_of_contours: -1,
bounding_box: BoundingBox {
x_min: 205,
x_max: 4514,
y_min: 0,
y_max: 1434,
},
data: GlyphData::Composite {
glyphs: vec![
CompositeGlyph {
flags: CompositeGlyphFlag::ARG_1_AND_2_ARE_WORDS
| CompositeGlyphFlag::ARGS_ARE_XY_VALUES
| CompositeGlyphFlag::ROUND_XY_TO_GRID
| CompositeGlyphFlag::MORE_COMPONENTS
| CompositeGlyphFlag::UNSCALED_COMPONENT_OFFSET,
glyph_index: 5,
argument1: CompositeGlyphArgument::I16(3453),
argument2: CompositeGlyphArgument::I16(0),
scale: None,
},
CompositeGlyph {
flags: CompositeGlyphFlag::ARG_1_AND_2_ARE_WORDS
| CompositeGlyphFlag::ARGS_ARE_XY_VALUES
| CompositeGlyphFlag::ROUND_XY_TO_GRID
| CompositeGlyphFlag::MORE_COMPONENTS
| CompositeGlyphFlag::UNSCALED_COMPONENT_OFFSET,
glyph_index: 4,
argument1: CompositeGlyphArgument::I16(2773),
argument2: CompositeGlyphArgument::I16(0),
scale: None,
},
CompositeGlyph {
flags: CompositeGlyphFlag::ARG_1_AND_2_ARE_WORDS
| CompositeGlyphFlag::ARGS_ARE_XY_VALUES
| CompositeGlyphFlag::ROUND_XY_TO_GRID
| CompositeGlyphFlag::MORE_COMPONENTS
| CompositeGlyphFlag::UNSCALED_COMPONENT_OFFSET,
glyph_index: 3,
argument1: CompositeGlyphArgument::I16(1182),
argument2: CompositeGlyphArgument::I16(0),
scale: None,
},
CompositeGlyph {
flags: CompositeGlyphFlag::ARG_1_AND_2_ARE_WORDS
| CompositeGlyphFlag::ARGS_ARE_XY_VALUES
| CompositeGlyphFlag::ROUND_XY_TO_GRID
| CompositeGlyphFlag::UNSCALED_COMPONENT_OFFSET
| CompositeGlyphFlag::WE_HAVE_INSTRUCTIONS,
glyph_index: 2,
argument1: CompositeGlyphArgument::I16(205),
argument2: CompositeGlyphArgument::I16(0),
scale: None,
},
],
instructions,
},
}
}
#[test]
fn test_point_bounding_box() {
let points = [Point(1761, 565), Point(2007, 565), Point(1884, 1032)];
let expected = BoundingBox {
x_min: 1761,
y_min: 565,
x_max: 2007,
y_max: 1032,
};
assert_eq!(BoundingBox::from_points(&points), expected);
}
#[test]
fn write_glyf_table_loca_sanity_check() {
let glyf = GlyfTable {
records: vec![GlyfRecord::Empty, GlyfRecord::Empty],
};
let num_glyphs = glyf.records.len();
let mut buffer = WriteBuffer::new();
let loca = GlyfTable::write_dep(&mut buffer, glyf, IndexToLocFormat::Long).unwrap();
assert_eq!(loca.offsets.len(), num_glyphs + 1);
}
#[test]
fn write_composite_glyf_instructions() {
let glyph = composite_glyph_fixture(&[1, 2, 3, 4]);
let mut buffer = WriteBuffer::new();
Glyph::write(&mut buffer, glyph).unwrap();
match ReadScope::new(buffer.bytes()).read::<Glyph<'_>>() {
Ok(Glyph {
data: GlyphData::Composite { instructions, .. },
..
}) => assert_eq!(instructions, vec![1, 2, 3, 4].as_slice()),
_ => panic!("did not read back expected instructions"),
}
}
#[test]
fn read_glyph_offsets_correctly() {
let glyph = simple_glyph_fixture();
let mut buffer = WriteBuffer::new();
buffer.write_zeros(4).unwrap();
Glyph::write(&mut buffer, glyph).unwrap();
let glyph_data = buffer.into_inner();
let mut buffer = WriteBuffer::new();
let loca = owned::LocaTable {
offsets: vec![4, 4, glyph_data.len() as u32 - 4],
};
owned::LocaTable::write_dep(&mut buffer, loca, IndexToLocFormat::Long)
.expect("unable to generate loca");
let loca_data = buffer.into_inner();
let num_glyphs = 2;
let loca = ReadScope::new(&loca_data)
.read_dep::<LocaTable<'_>>((num_glyphs, IndexToLocFormat::Long))
.expect("unable to read loca");
let glyf = ReadScope::new(&glyph_data)
.read_dep::<GlyfTable<'_>>(&loca)
.expect("unable to read glyf");
assert_eq!(glyf.records.len(), 2);
assert_eq!(&glyf.records[0], &GlyfRecord::Empty);
let glyph = &glyf.records[1];
assert_eq!(glyph.number_of_contours(), 1);
}
#[test]
fn simple_glyph_with_zero_contours() {
let glyph_data = &[
0, 0,
];
let expected = SimpleGlyph {
end_pts_of_contours: vec![],
instructions: &[],
flags: vec![],
coordinates: vec![],
};
let glyph = ReadScope::new(glyph_data)
.read_dep::<SimpleGlyph<'_>>(0)
.unwrap();
assert_eq!(glyph, expected);
}
#[test]
fn write_simple_glyph_with_zero_contours() {
let glyph = SimpleGlyph {
end_pts_of_contours: vec![],
instructions: &[],
flags: vec![],
coordinates: vec![],
};
let mut buffer = WriteBuffer::new();
assert!(SimpleGlyph::write(&mut buffer, glyph).is_ok());
}
#[test]
fn read_glyph_with_incorrect_loca_length() {
let glyph = simple_glyph_fixture();
let mut buffer = WriteBuffer::new();
Glyph::write(&mut buffer, glyph).unwrap();
let glyph_data = buffer.into_inner();
let mut buffer = WriteBuffer::new();
let loca = owned::LocaTable {
offsets: vec![0, 0, glyph_data.len() as u32 + 1],
};
owned::LocaTable::write_dep(&mut buffer, loca, IndexToLocFormat::Long)
.expect("unable to generate loca");
let loca_data = buffer.into_inner();
let num_glyphs = 2;
let loca = ReadScope::new(&loca_data)
.read_dep::<LocaTable<'_>>((num_glyphs, IndexToLocFormat::Long))
.expect("unable to read loca");
assert!(ReadScope::new(&glyph_data)
.read_dep::<GlyfTable<'_>>(&loca)
.is_ok())
}
#[test]
fn write_composite_glyph_with_empty_instructions() {
let glyph = composite_glyph_fixture(&[]);
let mut buffer = WriteBuffer::new();
Glyph::write(&mut buffer, glyph).unwrap();
match ReadScope::new(buffer.bytes()).read::<Glyph<'_>>() {
Ok(Glyph {
data: GlyphData::Composite { instructions, .. },
..
}) => assert_eq!(instructions, &[]),
Ok(_) => panic!("did not read back expected glyph"),
Err(_) => panic!("unable to read back glyph"),
}
}
}