forked from yeslogic/allsorts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cff.rs
3504 lines (3206 loc) · 101 KB
/
cff.rs
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
//! CFF font handling.
//!
//! Refer to [Technical Note #5176](http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5176.CFF.pdf)
//! for more information.
use std::convert::{TryFrom, TryInto};
use std::iter;
use std::marker::PhantomData;
use byteorder::{BigEndian, ByteOrder};
use itertools::Itertools;
use lazy_static::lazy_static;
use num_traits as num;
use crate::binary::read::{
CheckIndex, ReadArray, ReadArrayCow, ReadBinary, ReadBinaryDep, ReadCtxt, ReadFrom, ReadScope,
ReadUnchecked,
};
use crate::binary::write::{WriteBinary, WriteBinaryDep, WriteBuffer, WriteContext, WriteCounter};
use crate::binary::{I16Be, I32Be, U16Be, U24Be, U32Be, U8};
use crate::error::{ParseError, WriteError};
mod charstring;
#[cfg(feature = "outline")]
pub mod outline;
mod subset;
// CFF Spec: An operator may be preceded by up to a maximum of 48 operands.
const MAX_OPERANDS: usize = 48;
const OPERAND_ZERO: [Operand; 1] = [Operand::Integer(0)];
const OFFSET_ZERO: [Operand; 1] = [Operand::Offset(0)];
const DEFAULT_UNDERLINE_POSITION: [Operand; 1] = [Operand::Integer(-100)];
const DEFAULT_UNDERLINE_THICKNESS: [Operand; 1] = [Operand::Integer(50)];
const DEFAULT_CHARSTRING_TYPE: [Operand; 1] = [Operand::Integer(2)];
lazy_static! {
static ref DEFAULT_FONT_MATRIX: [Operand; 6] = {
let real_0_001 = Operand::Real(Real(vec![0x0a, 0x00, 0x1f])); // 0.001
[
real_0_001.clone(),
Operand::Integer(0),
Operand::Integer(0),
real_0_001,
Operand::Integer(0),
Operand::Integer(0),
]
};
}
const DEFAULT_BBOX: [Operand; 4] = [
Operand::Integer(0),
Operand::Integer(0),
Operand::Integer(0),
Operand::Integer(0),
];
const DEFAULT_CID_COUNT: [Operand; 1] = [Operand::Integer(8720)];
const DEFAULT_BLUE_SHIFT: [Operand; 1] = [Operand::Integer(7)];
const DEFAULT_BLUE_FUZZ: [Operand; 1] = [Operand::Integer(1)];
lazy_static! {
static ref DEFAULT_BLUE_SCALE: [Operand; 1] =
[Operand::Real(Real(vec![0x0a, 0x03, 0x96, 0x25, 0xff]))]; // 0.039625
static ref DEFAULT_EXPANSION_FACTOR: [Operand; 1] =
[Operand::Real(Real(vec![0x0a, 0x06, 0xff]))]; // 0.06
}
const ISO_ADOBE_LAST_SID: u16 = 228;
const ADOBE: &[u8] = b"Adobe";
const IDENTITY: &[u8] = b"Identity";
pub use subset::SubsetCFF;
/// Top level representation of a CFF font file, typically read from a CFF OpenType table.
///
/// Refer to Technical Note #5176
#[derive(Clone)]
pub struct CFF<'a> {
pub header: Header,
pub name_index: Index<'a>,
pub string_index: MaybeOwnedIndex<'a>,
pub global_subr_index: MaybeOwnedIndex<'a>,
pub fonts: Vec<Font<'a>>,
}
/// CFF Font Header described in Section 6 of Technical Note #5176
#[derive(Clone, Debug, PartialEq)]
pub struct Header {
pub major: u8,
pub minor: u8,
pub hdr_size: u8,
pub off_size: u8,
}
/// A CFF INDEX described in Section 5 of Technical Note #5176
#[derive(Clone)]
pub struct Index<'a> {
pub count: usize,
off_size: u8,
offset_array: &'a [u8],
data_array: &'a [u8],
}
/// A single font within a CFF file
#[derive(Clone)]
pub struct Font<'a> {
pub top_dict: TopDict,
pub char_strings_index: MaybeOwnedIndex<'a>,
pub charset: Charset<'a>,
pub data: CFFVariant<'a>,
}
#[derive(Clone)]
pub enum MaybeOwnedIndex<'a> {
Borrowed(Index<'a>),
Owned(owned::Index),
}
pub struct MaybeOwnedIndexIterator<'a> {
data: &'a MaybeOwnedIndex<'a>,
index: usize,
}
/// A list of errors that can occur when interpreting CFF CharStrings.
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum CFFError {
ParseError(ParseError),
InvalidOperator,
UnsupportedOperator,
MissingEndChar,
DataAfterEndChar,
NestingLimitReached,
ArgumentsStackLimitReached,
InvalidArgumentsStackLength,
BboxOverflow,
MissingMoveTo,
InvalidSubroutineIndex,
NoLocalSubroutines,
InvalidSeacCode,
}
mod owned {
use super::{TryFrom, U16Be, WriteBinary, WriteContext, WriteError, U8};
#[derive(Clone)]
pub struct Index {
pub(super) data: Vec<Vec<u8>>,
}
impl WriteBinary<&Self> for Index {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, index: &Index) -> Result<(), WriteError> {
let count = u16::try_from(index.data.len())?;
U16Be::write(ctxt, count)?;
if count == 0 {
return Ok(());
}
let mut offset = 1; // INDEX offsets start at 1
let mut offsets = Vec::with_capacity(index.data.len() + 1);
for data in &index.data {
offsets.push(offset);
offset += data.len();
}
offsets.push(offset);
let (off_size, offset_array) = super::serialise_offset_array(offsets)?;
U8::write(ctxt, off_size)?;
ctxt.write_bytes(&offset_array)?;
for data in &index.data {
ctxt.write_bytes(data)?;
}
Ok(())
}
}
impl Index {
pub(super) fn read_object(&self, index: usize) -> Option<&[u8]> {
self.data.get(index).map(|data| data.as_slice())
}
}
}
#[derive(Clone)]
pub enum CFFVariant<'a> {
CID(CIDData<'a>),
Type1(Type1Data<'a>),
}
#[derive(Clone)]
pub struct CIDData<'a> {
pub font_dict_index: MaybeOwnedIndex<'a>,
pub private_dicts: Vec<PrivateDict>,
/// An optional local subroutine index per Private DICT.
pub local_subr_indices: Vec<Option<MaybeOwnedIndex<'a>>>,
pub fd_select: FDSelect<'a>,
}
pub struct CIDDataOffsets {
pub font_dict_index: usize,
pub fd_select: usize,
}
#[derive(Clone)]
pub struct Type1Data<'a> {
pub encoding: Encoding<'a>,
pub private_dict: PrivateDict,
pub local_subr_index: Option<MaybeOwnedIndex<'a>>,
}
pub struct Type1DataOffsets {
pub custom_encoding: Option<usize>,
pub private_dict: usize,
pub private_dict_len: usize,
}
// Encoding data is located via the offset operand to the Encoding operator in the Top DICT. Only
// one Encoding operator can be specified per font except for CIDFonts which specify no encoding.
#[derive(Clone)]
pub enum Encoding<'a> {
Standard,
Expert,
Custom(CustomEncoding<'a>),
}
#[derive(Clone)]
pub enum Charset<'a> {
ISOAdobe,
Expert,
ExpertSubset,
Custom(CustomCharset<'a>),
}
#[derive(Clone)]
pub enum CustomEncoding<'a> {
Format0 {
codes: ReadArray<'a, U8>,
},
Format1 {
ranges: ReadArray<'a, Range<u8, u8>>,
},
}
// A string id in the font
type SID = u16;
#[derive(Clone)]
pub enum CustomCharset<'a> {
Format0 {
glyphs: ReadArrayCow<'a, U16Be>,
},
Format1 {
ranges: ReadArrayCow<'a, Range<SID, u8>>,
},
Format2 {
ranges: ReadArrayCow<'a, Range<SID, u16>>,
},
}
/// A Range from `first` to `first + n_left`
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Range<F, N> {
pub first: F,
pub n_left: N,
}
/// A CFF DICT described in Section 4 of Technical Note #5176
#[derive(Debug, PartialEq, Clone)]
pub struct Dict<T>
where
T: DictDefault,
{
dict: Vec<(Operator, Vec<Operand>)>,
default: PhantomData<T>,
}
/// The default values of a DICT
pub trait DictDefault {
/// Returns the default operand(s) if any for the supplied `op`.
fn default(op: Operator) -> Option<&'static [Operand]>;
}
#[derive(Debug, PartialEq, Clone)]
pub struct TopDictDefault;
#[derive(Debug, PartialEq, Clone)]
pub struct FontDictDefault;
#[derive(Debug, PartialEq, Clone)]
pub struct PrivateDictDefault;
pub type TopDict = Dict<TopDictDefault>;
pub type FontDict = Dict<FontDictDefault>;
pub type PrivateDict = Dict<PrivateDictDefault>;
/// A collection of offset changes to a `Dict`
///
/// `DictDelta` only accepts Operators with offsets as operands.
#[derive(Debug, PartialEq, Clone)]
pub struct DictDelta {
dict: Vec<(Operator, Vec<Operand>)>,
}
/// Font DICT select as described in Section 19 of Technical Note #5176
#[derive(Clone, Debug)]
pub enum FDSelect<'a> {
Format0 {
glyph_font_dict_indices: ReadArrayCow<'a, U8>,
},
// Formats 1 and 2 are not defined
Format3 {
ranges: ReadArrayCow<'a, Range<u16, u8>>,
sentinel: u16,
},
}
/// CFF DICT operator
#[derive(Debug, PartialEq)]
enum Op {
Operator(Operator),
Operand(Operand),
}
/// CFF operand to an operator
#[derive(Debug, PartialEq, Clone)]
pub enum Operand {
Integer(i32),
Offset(i32),
Real(Real),
}
// This representation of real values seems a little sub-optimal since most values are likely to be
// only a few bytes. In practice we probably won't need to handle many of these values so it's
// probably not an issue. If it does impact performance, perhaps consider using the smallvec crate.
#[derive(Debug, PartialEq, Clone)]
pub struct Real(Vec<u8>);
#[repr(u16)]
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Operator {
Version = 0,
Notice = 1,
FullName = 2,
FamilyName = 3,
Weight = 4,
FontBBox = 5,
BlueValues = 6,
OtherBlues = 7,
FamilyBlues = 8,
FamilyOtherBlues = 9,
StdHW = 10,
StdVW = 11,
UniqueID = 13,
XUID = 14,
Charset = 15,
Encoding = 16,
CharStrings = 17,
Private = 18,
Subrs = 19,
DefaultWidthX = 20,
NominalWidthX = 21,
Copyright = op2(0),
IsFixedPitch = op2(1),
ItalicAngle = op2(2),
UnderlinePosition = op2(3),
UnderlineThickness = op2(4),
PaintType = op2(5),
CharstringType = op2(6),
FontMatrix = op2(7),
StrokeWidth = op2(8),
BlueScale = op2(9),
BlueShift = op2(10),
BlueFuzz = op2(11),
StemSnapH = op2(12),
StemSnapV = op2(13),
ForceBold = op2(14),
LanguageGroup = op2(17),
ExpansionFactor = op2(18),
InitialRandomSeed = op2(19),
SyntheticBase = op2(20),
PostScript = op2(21),
BaseFontName = op2(22),
BaseFontBlend = op2(23),
ROS = op2(30),
CIDFontVersion = op2(31),
CIDFontRevision = op2(32),
CIDFontType = op2(33),
CIDCount = op2(34),
UIDBase = op2(35),
FDArray = op2(36),
FDSelect = op2(37),
FontName = op2(38),
}
const fn op2(value: u8) -> u16 {
(12 << 8) | (value as u16)
}
impl<'b> ReadBinary for CFF<'b> {
type HostType<'a> = CFF<'a>;
fn read<'a>(ctxt: &mut ReadCtxt<'a>) -> Result<Self::HostType<'a>, ParseError> {
// Get a scope that starts at the beginning of the CFF data. This is needed for reading
// data that is specified as an offset from the start of the data later.
let scope = ctxt.scope();
let header = ctxt.read::<Header>()?;
let name_index = ctxt.read::<Index<'_>>()?;
let top_dict_index = ctxt.read::<Index<'_>>()?;
let string_index = ctxt.read::<Index<'_>>()?;
let global_subr_index = ctxt.read::<Index<'_>>().map(MaybeOwnedIndex::Borrowed)?;
let mut fonts = Vec::with_capacity(name_index.count);
for font_index in 0..name_index.count {
let top_dict = top_dict_index.read::<TopDict>(font_index)?;
// CharStrings index
let offset = top_dict
.get_i32(Operator::CharStrings)
.unwrap_or(Err(ParseError::MissingValue))?;
let char_strings_index = scope.offset(usize::try_from(offset)?).read::<Index<'_>>()?;
// The Top DICT begins with the SyntheticBase and ROS operators
// for synthetic and CIDFonts, respectively. Regular Type 1 fonts
// begin with some other operator.
let data = match top_dict.first_operator() {
Some(Operator::ROS) => {
let cid_data = read_cid_data(&scope, &top_dict, char_strings_index.count)?;
CFFVariant::CID(cid_data)
}
Some(Operator::SyntheticBase) => {
return Err(ParseError::NotImplemented);
}
Some(_) => {
let (private_dict, private_dict_offset) = top_dict.read_private_dict(&scope)?;
let local_subr_index =
read_local_subr_index(&scope, &private_dict, private_dict_offset)?
.map(MaybeOwnedIndex::Borrowed);
let encoding = read_encoding(&scope, &top_dict)?;
CFFVariant::Type1(Type1Data {
encoding,
private_dict,
local_subr_index,
})
}
None => return Err(ParseError::MissingValue),
};
let charset = read_charset(&scope, &top_dict, char_strings_index.count)?;
fonts.push(Font {
top_dict,
char_strings_index: MaybeOwnedIndex::Borrowed(char_strings_index),
charset,
data,
});
}
Ok(CFF {
header,
name_index,
string_index: MaybeOwnedIndex::Borrowed(string_index),
global_subr_index,
fonts,
})
}
}
impl<'a> WriteBinary<&Self> for CFF<'a> {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, cff: &CFF<'a>) -> Result<(), WriteError> {
Header::write(ctxt, &cff.header)?;
Index::write(ctxt, &cff.name_index)?;
let top_dicts = cff.fonts.iter().map(|font| &font.top_dict).collect_vec();
let top_dict_index_length =
Index::calculate_size::<TopDict, _>(top_dicts.as_slice(), DictDelta::new())?;
let top_dict_index_placeholder = ctxt.reserve::<Index<'_>, _>(top_dict_index_length)?;
MaybeOwnedIndex::write(ctxt, &cff.string_index)?;
MaybeOwnedIndex::write(ctxt, &cff.global_subr_index)?;
// Collect Top DICT deltas now that we know the offsets to other items in the DICT
let mut top_dict_deltas = vec![DictDelta::new(); cff.fonts.len()];
for (font, top_dict_delta) in cff.fonts.iter().zip(top_dict_deltas.iter_mut()) {
top_dict_delta.push_offset(Operator::CharStrings, i32::try_from(ctxt.bytes_written())?);
MaybeOwnedIndex::write(ctxt, &font.char_strings_index)?;
match &font.charset {
Charset::ISOAdobe => top_dict_delta.push_offset(Operator::Charset, 0),
Charset::Expert => top_dict_delta.push_offset(Operator::Charset, 1),
Charset::ExpertSubset => top_dict_delta.push_offset(Operator::Charset, 2),
Charset::Custom(custom) => {
top_dict_delta
.push_offset(Operator::Charset, i32::try_from(ctxt.bytes_written())?);
CustomCharset::write(ctxt, custom)?;
}
}
write_cff_variant(ctxt, &font.data, top_dict_delta)?;
}
// Write out the Top DICTs with the updated offsets
let mut top_dict_data = WriteBuffer::new();
let mut offsets = Vec::with_capacity(cff.fonts.len());
for (font, top_dict_delta) in cff.fonts.iter().zip(top_dict_deltas.into_iter()) {
offsets.push(top_dict_data.bytes_written() + 1); // +1 because INDEX offsets start at 1
TopDict::write_dep(&mut top_dict_data, &font.top_dict, top_dict_delta)?;
}
offsets.push(top_dict_data.bytes_written() + 1); // Add the extra offset at the end
let (off_size, offset_array) = serialise_offset_array(offsets)?;
// Fill in the Top DICT INDEX placeholder
let top_dict_index = Index {
count: cff.fonts.len(),
off_size,
offset_array: &offset_array,
data_array: top_dict_data.bytes(),
};
ctxt.write_placeholder(top_dict_index_placeholder, &top_dict_index)?;
Ok(())
}
}
impl<'a> CFF<'a> {
/// Read a string with the given SID from the String INDEX
pub fn read_string(&self, sid: SID) -> Result<String, ParseError> {
read_string_index_string(&self.string_index, sid)
}
}
/// Read a string with the given SID from the String INDEX
fn read_string_index_string(
string_index: &MaybeOwnedIndex<'_>,
sid: SID,
) -> Result<String, ParseError> {
let sid = usize::from(sid);
// When the client needs to determine the string that corresponds to a particular SID it
// performs the following: test if SID is in standard range then fetch from internal table,
// otherwise, fetch string from the String INDEX using a value of (SID – nStdStrings) as
// the index
if let Some(string) = STANDARD_STRINGS.get(sid) {
Ok(string.to_string())
} else {
let bytes = string_index
.read_object(sid - STANDARD_STRINGS.len())
.ok_or(ParseError::BadIndex)?;
String::from_utf8(bytes.to_vec()).map_err(|_utf8_err| ParseError::BadValue)
}
}
impl ReadBinary for Header {
type HostType<'b> = Self;
fn read<'a>(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
// From section 6 of Technical Note #5176:
// Implementations reading font set files must include code to check version numbers so
// that if and when the format and therefore the version number changes, older
// implementations will reject newer versions gracefully. If the major version number is
// understood by an implementation it can safely proceed with reading the font. The minor
// version number indicates extensions to the format that are undetectable by
// implementations that do not support them although they will be unable to take advantage
// of these extensions.
let major = ctxt.read_u8()?;
ctxt.check(major == 1)?;
let minor = ctxt.read_u8()?;
let hdr_size = ctxt.read_u8()?;
let off_size = ctxt.read_u8()?;
if hdr_size < 4 {
return Err(ParseError::BadValue);
}
if off_size < 1 || off_size > 4 {
return Err(ParseError::BadValue);
}
let _unknown = ctxt.read_slice((hdr_size - 4) as usize)?;
Ok(Header {
major,
minor,
hdr_size,
off_size,
})
}
}
impl WriteBinary<&Self> for Header {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, header: &Header) -> Result<(), WriteError> {
U8::write(ctxt, header.major)?;
U8::write(ctxt, header.minor)?;
// Any data between the header and the Name INDEX will have been discarded.
// So the size will always be 4 bytes.
U8::write(ctxt, 4)?; // hdr_size
U8::write(ctxt, header.off_size)?;
Ok(())
}
}
impl<'b> ReadBinary for Index<'b> {
type HostType<'a> = Index<'a>;
fn read<'a>(ctxt: &mut ReadCtxt<'a>) -> Result<Self::HostType<'a>, ParseError> {
let count = usize::from(ctxt.read_u16be()?);
if count > 0 {
let off_size = ctxt.read_u8()?;
if off_size < 1 || off_size > 4 {
return Err(ParseError::BadValue);
}
let offset_array_size = (count + 1) * usize::from(off_size);
let offset_array = ctxt.read_slice(offset_array_size)?;
let last_offset_index = lookup_offset_index(off_size, offset_array, count);
if last_offset_index < 1 {
return Err(ParseError::BadValue);
}
let data_array_size = last_offset_index - 1;
let data_array = ctxt.read_slice(data_array_size)?;
Ok(Index {
count,
off_size,
offset_array,
data_array,
})
} else {
// count == 0
Ok(Index {
count,
off_size: 1,
offset_array: &[],
data_array: &[],
})
}
}
}
impl<'a> WriteBinary<&Self> for Index<'a> {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, index: &Index<'a>) -> Result<(), WriteError> {
U16Be::write(ctxt, u16::try_from(index.count)?)?;
if index.count == 0 {
return Ok(());
}
U8::write(ctxt, index.off_size)?;
ctxt.write_bytes(index.offset_array)?;
ctxt.write_bytes(index.data_array)?;
Ok(())
}
}
impl<'a> WriteBinary<&Self> for MaybeOwnedIndex<'a> {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, index: &MaybeOwnedIndex<'a>) -> Result<(), WriteError> {
match index {
MaybeOwnedIndex::Borrowed(index) => Index::write(ctxt, index),
MaybeOwnedIndex::Owned(index) => owned::Index::write(ctxt, index),
}
}
}
impl<T> ReadBinary for Dict<T>
where
T: DictDefault,
{
type HostType<'b> = Self;
fn read<'a>(ctxt: &mut ReadCtxt<'a>) -> Result<Self::HostType<'a>, ParseError> {
let mut dict = Vec::new();
let mut operands = Vec::new();
while ctxt.bytes_available() {
match Op::read(ctxt)? {
Op::Operator(operator) => {
integer_to_offset(operator, &mut operands);
dict.push((operator, operands.clone()));
operands.clear();
}
Op::Operand(operand) => {
operands.push(operand);
if operands.len() > MAX_OPERANDS {
return Err(ParseError::LimitExceeded);
}
}
}
}
Ok(Dict {
dict,
default: PhantomData,
})
}
}
fn offset_size(value: usize) -> Option<u8> {
match value {
0..=0xFF => Some(1),
0x100..=0xFFFF => Some(2),
0x1_0000..=0xFF_FFFF => Some(3),
0x100_0000..=0xFFFF_FFFF => Some(4),
_ => None,
}
}
// Special case handling for operands that are offsets. This function swaps them from an
// Integer to an Offset. This is later used when writing operands.
fn integer_to_offset(operator: Operator, operands: &mut [Operand]) {
match (operator, &operands) {
// Encodings 0..=1 indicate predefined encodings and are not offsets
(Operator::Encoding, [Operand::Integer(offset)]) if *offset > 1 => {
operands[0] = Operand::Offset(*offset);
}
(Operator::Charset, [Operand::Integer(offset)])
| (Operator::CharStrings, [Operand::Integer(offset)])
| (Operator::Subrs, [Operand::Integer(offset)])
| (Operator::FDArray, [Operand::Integer(offset)])
| (Operator::FDSelect, [Operand::Integer(offset)]) => {
operands[0] = Operand::Offset(*offset);
}
(Operator::Private, [Operand::Integer(length), Operand::Integer(offset)]) => {
let offset = *offset; // This is a work around an ownership issue
operands[0] = Operand::Offset(*length);
operands[1] = Operand::Offset(offset);
}
_ => {}
}
}
impl<T> WriteBinaryDep<&Self> for Dict<T>
where
T: DictDefault,
{
type Args = DictDelta;
type Output = usize; // The length of the written Dict
fn write_dep<C: WriteContext>(
ctxt: &mut C,
dict: &Dict<T>,
delta: DictDelta,
) -> Result<Self::Output, WriteError> {
let offset = ctxt.bytes_written();
for (operator, operands) in dict.iter() {
let mut operands = operands.as_slice();
// Replace operands with delta operands if present otherwise skip if operands match
// default. We never skip operands pulled from the delta DICT as these are offsets and
// always need to be written in order to make the size of the DICT predictable.
if let Some(delta_operands) = delta.get(*operator) {
operands = delta_operands;
} else if T::default(*operator)
.map(|defaults| defaults == operands)
.unwrap_or(false)
{
continue;
}
for operand in operands {
Operand::write(ctxt, operand)?;
}
Operator::write(ctxt, *operator)?;
}
Ok(ctxt.bytes_written() - offset)
}
}
impl ReadBinary for Op {
type HostType<'b> = Self;
fn read<'a>(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
let b0 = ctxt.read_u8()?;
match b0 {
0..=11 | 13..=21 => ok_operator(u16::from(b0).try_into().unwrap()), // NOTE(unwrap): Safe due to pattern
12 => ok_operator(op2(ctxt.read_u8()?).try_into()?),
28 => {
let num = ctxt.read_i16be()?;
Ok(Op::Operand(Operand::Integer(i32::from(num))))
}
29 => ok_int(ctxt.read_i32be()?),
30 => ok_real(ctxt.read_until_nibble(0xF)?),
32..=246 => ok_int(i32::from(b0) - 139),
247..=250 => {
let b1 = ctxt.read_u8()?;
ok_int((i32::from(b0) - 247) * 256 + i32::from(b1) + 108)
}
251..=254 => {
let b1 = ctxt.read_u8()?;
ok_int(-(i32::from(b0) - 251) * 256 - i32::from(b1) - 108)
}
22..=27 | 31 | 255 => Err(ParseError::BadValue), // reserved
}
}
}
impl WriteBinary<Self> for Operator {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, op: Operator) -> Result<(), WriteError> {
let value = op as u16;
if value > 0xFF {
U16Be::write(ctxt, value)?;
} else {
U8::write(ctxt, value as u8)?;
}
Ok(())
}
}
impl WriteBinary<&Self> for Operand {
type Output = ();
// Refer to Table 3 Operand Encoding in section 4 of Technical Note #5176 for details on the
// integer encoding scheme.
fn write<C: WriteContext>(ctxt: &mut C, op: &Operand) -> Result<(), WriteError> {
match op {
Operand::Integer(val) => match *val {
// NOTE: Casts are safe due to patterns limiting range
-107..=107 => {
U8::write(ctxt, (val + 139) as u8)?;
}
108..=1131 => {
let val = *val - 108;
U8::write(ctxt, ((val >> 8) + 247) as u8)?;
U8::write(ctxt, val as u8)?;
}
-1131..=-108 => {
let val = -*val - 108;
U8::write(ctxt, ((val >> 8) + 251) as u8)?;
U8::write(ctxt, val as u8)?;
}
-32768..=32767 => {
U8::write(ctxt, 28)?;
I16Be::write(ctxt, *val as i16)?
}
_ => {
U8::write(ctxt, 29)?;
I32Be::write(ctxt, *val)?
}
},
Operand::Offset(val) => {
U8::write(ctxt, 29)?;
// Offsets are always encoded using the i32 representation to make their size
// predictable.
I32Be::write(ctxt, *val)?;
}
Operand::Real(Real(val)) => {
U8::write(ctxt, 30)?;
ctxt.write_bytes(val)?;
}
}
Ok(())
}
}
fn ok_operator(op: Operator) -> Result<Op, ParseError> {
Ok(Op::Operator(op))
}
fn ok_int(num: i32) -> Result<Op, ParseError> {
Ok(Op::Operand(Operand::Integer(num)))
}
fn ok_real(slice: &[u8]) -> Result<Op, ParseError> {
Ok(Op::Operand(Operand::Real(Real(slice.to_owned()))))
}
impl ReadFrom for Range<u8, u8> {
type ReadType = (U8, U8);
fn from((first, n_left): (u8, u8)) -> Self {
Range { first, n_left }
}
}
impl WriteBinary for Range<u8, u8> {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, range: Self) -> Result<(), WriteError> {
U8::write(ctxt, range.first)?;
U8::write(ctxt, range.n_left)?;
Ok(())
}
}
impl ReadFrom for Range<SID, u8> {
type ReadType = (U16Be, U8);
fn from((first, n_left): (SID, u8)) -> Self {
Range { first, n_left }
}
}
impl WriteBinary for Range<SID, u8> {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, range: Self) -> Result<(), WriteError> {
U16Be::write(ctxt, range.first)?;
U8::write(ctxt, range.n_left)?;
Ok(())
}
}
impl ReadFrom for Range<SID, u16> {
type ReadType = (U16Be, U16Be);
fn from((first, n_left): (SID, u16)) -> Self {
Range { first, n_left }
}
}
impl WriteBinary for Range<SID, u16> {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, range: Self) -> Result<(), WriteError> {
U16Be::write(ctxt, range.first)?;
U16Be::write(ctxt, range.n_left)?;
Ok(())
}
}
impl<F, N> Range<F, N>
where
N: num::Unsigned + Copy,
usize: From<N>,
{
pub fn len(&self) -> usize {
usize::from(self.n_left) + 1
}
}
// TODO: Make these generic. Requires Rust stabilisation of the Step trait or its replacement.
// https://doc.rust-lang.org/core/iter/trait.Step.html
impl Range<SID, u8> {
pub fn iter(&self) -> impl Iterator<Item = SID> {
let last = self.first + SID::from(self.n_left);
self.first..=last
}
}
impl Range<SID, u16> {
pub fn iter(&self) -> impl Iterator<Item = SID> {
let last = self.first + self.n_left;
self.first..=last
}
}
impl<'b> ReadBinary for CustomEncoding<'b> {
type HostType<'a> = CustomEncoding<'a>;
fn read<'a>(ctxt: &mut ReadCtxt<'a>) -> Result<Self::HostType<'a>, ParseError> {
// First byte indicates the format of the encoding data
match ctxt.read::<U8>()? {
0 => {
let ncodes = ctxt.read::<U8>()?;
let codes = ctxt.read_array::<U8>(usize::from(ncodes))?;
Ok(CustomEncoding::Format0 { codes })
}
1 => {
let nranges = ctxt.read::<U8>()?;
let ranges = ctxt.read_array::<Range<u8, u8>>(usize::from(nranges))?;
Ok(CustomEncoding::Format1 { ranges })
}
// The CFF spec notes:
// A few fonts have multiply-encoded glyphs which are not supported directly by any of
// the above formats. This situation is indicated by setting the high-order bit in the
// format byte and supplementing the encoding.
//
// This is not handed as it is not expected that these will be encountered in CFF in
// OTF files.
format if format & 0x80 == 0x80 => Err(ParseError::NotImplemented),
_ => Err(ParseError::BadValue),
}
}
}
impl<'a> WriteBinary<&Self> for CustomEncoding<'a> {
type Output = ();
fn write<C: WriteContext>(ctxt: &mut C, encoding: &Self) -> Result<(), WriteError> {
match encoding {
CustomEncoding::Format0 { codes } => {
U8::write(ctxt, 0)?; // format
U8::write(ctxt, u8::try_from(codes.len())?)?;
<&ReadArray<'_, _>>::write(ctxt, codes)?;