logo
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
//! `post` table parsing and writing.

use std::str;

use crate::binary::read::{ReadArray, ReadBinary, ReadCtxt};
use crate::binary::write::{WriteBinary, WriteContext};
use crate::binary::{I16Be, I32Be, U16Be, U32Be, U8};
use crate::error::{ParseError, WriteError};

pub struct PostTable<'a> {
    pub header: Header,
    pub opt_sub_table: Option<SubTable<'a>>,
}

pub struct Header {
    pub version: i32,
    pub italic_angle: i32,
    pub underline_position: i16,
    pub underline_thickness: i16,
    pub is_fixed_pitch: u32,
    pub min_mem_type_42: u32,
    pub max_mem_type_42: u32,
    pub min_mem_type_1: u32,
    pub max_mem_type_1: u32,
}

pub struct SubTable<'a> {
    pub num_glyphs: u16,
    pub glyph_name_index: ReadArray<'a, U16Be>,
    pub names: Vec<PascalString<'a>>,
}

#[derive(Clone)]
pub struct PascalString<'a> {
    pub bytes: &'a [u8],
}

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

    fn read(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
        let version = ctxt.read_i32be()?;
        let italic_angle = ctxt.read_i32be()?;
        let underline_position = ctxt.read_i16be()?;
        let underline_thickness = ctxt.read_i16be()?;
        let is_fixed_pitch = ctxt.read_u32be()?;
        let min_mem_type_42 = ctxt.read_u32be()?;
        let max_mem_type_42 = ctxt.read_u32be()?;
        let min_mem_type_1 = ctxt.read_u32be()?;
        let max_mem_type_1 = ctxt.read_u32be()?;

        Ok(Header {
            version,
            italic_angle,
            underline_position,
            underline_thickness,
            is_fixed_pitch,
            min_mem_type_42,
            max_mem_type_42,
            min_mem_type_1,
            max_mem_type_1,
        })
    }
}

impl<'a> WriteBinary<&Self> for Header {
    type Output = ();

    fn write<C: WriteContext>(ctxt: &mut C, table: &Header) -> Result<(), WriteError> {
        I32Be::write(ctxt, table.version)?;
        I32Be::write(ctxt, table.italic_angle)?;
        I16Be::write(ctxt, table.underline_position)?;
        I16Be::write(ctxt, table.underline_thickness)?;
        U32Be::write(ctxt, table.is_fixed_pitch)?;
        U32Be::write(ctxt, table.min_mem_type_42)?;
        U32Be::write(ctxt, table.max_mem_type_42)?;
        U32Be::write(ctxt, table.min_mem_type_1)?;
        U32Be::write(ctxt, table.max_mem_type_1)?;

        Ok(())
    }
}

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

    fn read(ctxt: &mut ReadCtxt<'a>) -> Result<Self, ParseError> {
        let header = ctxt.read::<Header>()?;
        let opt_sub_table = match header.version {
            0x00020000 => {
                // May include some Format 1 glyphs
                let num_glyphs = ctxt.read_u16be()?;
                let glyph_name_index = ctxt.read_array(usize::from(num_glyphs))?;

                // Find the largest index used and use that to determine how many names to read
                let names_to_read = glyph_name_index.iter().max().map_or(0, |max| {
                    (usize::from(max) + 1).saturating_sub(FORMAT_1_NAMES.len())
                });

                // Read the names
                let mut names = Vec::with_capacity(names_to_read);
                for _ in 0..names_to_read {
                    let length = ctxt.read_u8()?;
                    let bytes = ctxt.read_slice(usize::from(length))?;
                    names.push(PascalString { bytes });
                }

                Some(SubTable {
                    num_glyphs,
                    glyph_name_index,
                    names,
                })
            }
            // TODO Handle post version 1.0, 2.5, 3.0
            0x00010000 | 0x00025000 | 0x00030000 => None,
            _ => return Err(ParseError::BadVersion),
        };

        Ok(PostTable {
            header,
            opt_sub_table,
        })
    }
}

impl<'a> WriteBinary<&Self> for PostTable<'a> {
    type Output = ();

    fn write<C: WriteContext>(ctxt: &mut C, table: &PostTable<'a>) -> Result<(), WriteError> {
        Header::write(ctxt, &table.header)?;
        if let Some(sub_table) = &table.opt_sub_table {
            SubTable::write(ctxt, sub_table)?;
        }

        Ok(())
    }
}

impl<'a> WriteBinary<&Self> for SubTable<'a> {
    type Output = ();

    fn write<C: WriteContext>(ctxt: &mut C, table: &SubTable<'a>) -> Result<(), WriteError> {
        U16Be::write(ctxt, table.num_glyphs)?;
        <&ReadArray<'_, _>>::write(ctxt, &table.glyph_name_index)?;
        for name in &table.names {
            PascalString::write(ctxt, name)?;
        }

        Ok(())
    }
}

impl<'a> WriteBinary<&Self> for PascalString<'a> {
    type Output = ();

    fn write<C: WriteContext>(ctxt: &mut C, string: &PascalString<'a>) -> Result<(), WriteError> {
        if string.bytes.len() <= usize::from(std::u8::MAX) {
            // cast is safe due to check above
            U8::write(ctxt, string.bytes.len() as u8)?;
            ctxt.write_bytes(string.bytes)?;
            Ok(())
        } else {
            Err(WriteError::BadValue)
        }
    }
}

impl<'a> PostTable<'a> {
    /// Retrieve the glyph name for the supplied `glyph_index`.
    ///
    /// **Note:** Some fonts map more than one glyph to the same name so don't assume names are
    /// unique.
    pub fn glyph_name(&self, glyph_index: u16) -> Result<Option<&'a str>, ParseError> {
        if let Some(sub_table) = &self.opt_sub_table {
            if glyph_index >= sub_table.num_glyphs {
                return Ok(None);
            }
        }

        match &self.header.version {
            0x00010000 if usize::from(glyph_index) < FORMAT_1_NAMES.len() => {
                let name = FORMAT_1_NAMES[usize::from(glyph_index)];
                Ok(Some(name))
            }
            0x00020000 => match &self.opt_sub_table {
                Some(sub_table) => {
                    let name_index = sub_table
                        .glyph_name_index
                        .get_item(usize::from(glyph_index));

                    if usize::from(name_index) < FORMAT_1_NAMES.len() {
                        Ok(Some(FORMAT_1_NAMES[usize::from(name_index)]))
                    } else {
                        let index = usize::from(name_index) - FORMAT_1_NAMES.len();
                        let pascal_string = &sub_table.names[index];

                        match str::from_utf8(pascal_string.bytes) {
                            Ok(name) => Ok(Some(name)),
                            Err(_) => Err(ParseError::BadValue),
                        }
                    }
                }
                // If the table is version 2, the sub-table should exist
                None => Err(ParseError::BadValue),
            },
            _ => Ok(None),
        }
    }
}

static FORMAT_1_NAMES: &'static [&'static str; 258] = &[
    ".notdef",
    ".null",
    "nonmarkingreturn",
    "space",
    "exclam",
    "quotedbl",
    "numbersign",
    "dollar",
    "percent",
    "ampersand",
    "quotesingle",
    "parenleft",
    "parenright",
    "asterisk",
    "plus",
    "comma",
    "hyphen",
    "period",
    "slash",
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine",
    "colon",
    "semicolon",
    "less",
    "equal",
    "greater",
    "question",
    "at",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "bracketleft",
    "backslash",
    "bracketright",
    "asciicircum",
    "underscore",
    "grave",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
    "braceleft",
    "bar",
    "braceright",
    "asciitilde",
    "Adieresis",
    "Aring",
    "Ccedilla",
    "Eacute",
    "Ntilde",
    "Odieresis",
    "Udieresis",
    "aacute",
    "agrave",
    "acircumflex",
    "adieresis",
    "atilde",
    "aring",
    "ccedilla",
    "eacute",
    "egrave",
    "ecircumflex",
    "edieresis",
    "iacute",
    "igrave",
    "icircumflex",
    "idieresis",
    "ntilde",
    "oacute",
    "ograve",
    "ocircumflex",
    "odieresis",
    "otilde",
    "uacute",
    "ugrave",
    "ucircumflex",
    "udieresis",
    "dagger",
    "degree",
    "cent",
    "sterling",
    "section",
    "bullet",
    "paragraph",
    "germandbls",
    "registered",
    "copyright",
    "trademark",
    "acute",
    "dieresis",
    "notequal",
    "AE",
    "Oslash",
    "infinity",
    "plusminus",
    "lessequal",
    "greaterequal",
    "yen",
    "mu",
    "partialdiff",
    "summation",
    "product",
    "pi",
    "integral",
    "ordfeminine",
    "ordmasculine",
    "Omega",
    "ae",
    "oslash",
    "questiondown",
    "exclamdown",
    "logicalnot",
    "radical",
    "florin",
    "approxequal",
    "Delta",
    "guillemotleft",
    "guillemotright",
    "ellipsis",
    "nonbreakingspace",
    "Agrave",
    "Atilde",
    "Otilde",
    "OE",
    "oe",
    "endash",
    "emdash",
    "quotedblleft",
    "quotedblright",
    "quoteleft",
    "quoteright",
    "divide",
    "lozenge",
    "ydieresis",
    "Ydieresis",
    "fraction",
    "currency",
    "guilsinglleft",
    "guilsinglright",
    "fi",
    "fl",
    "daggerdbl",
    "periodcentered",
    "quotesinglbase",
    "quotedblbase",
    "perthousand",
    "Acircumflex",
    "Ecircumflex",
    "Aacute",
    "Edieresis",
    "Egrave",
    "Iacute",
    "Icircumflex",
    "Idieresis",
    "Igrave",
    "Oacute",
    "Ocircumflex",
    "apple",
    "Ograve",
    "Uacute",
    "Ucircumflex",
    "Ugrave",
    "dotlessi",
    "circumflex",
    "tilde",
    "macron",
    "breve",
    "dotaccent",
    "ring",
    "cedilla",
    "hungarumlaut",
    "ogonek",
    "caron",
    "Lslash",
    "lslash",
    "Scaron",
    "scaron",
    "Zcaron",
    "zcaron",
    "brokenbar",
    "Eth",
    "eth",
    "Yacute",
    "yacute",
    "Thorn",
    "thorn",
    "minus",
    "multiply",
    "onesuperior",
    "twosuperior",
    "threesuperior",
    "onehalf",
    "onequarter",
    "threequarters",
    "franc",
    "Gbreve",
    "gbreve",
    "Idotaccent",
    "Scedilla",
    "scedilla",
    "Cacute",
    "cacute",
    "Ccaron",
    "ccaron",
    "dcroat",
];

#[cfg(test)]
mod tests {
    use super::*;
    use crate::binary::read::ReadScope;
    use crate::binary::write::WriteBuffer;

    #[test]
    fn duplicate_glyph_names() {
        // Test for post table that maps multiple glyphs to the same name index. Before a fix was
        // implemented this table failed to parse.
        let post_data = include_bytes!("../tests/fonts/opentype/post.bin");
        let post = ReadScope::new(post_data)
            .read::<PostTable<'_>>()
            .expect("unable to parse post table");
        match post.opt_sub_table {
            Some(ref sub_table) => assert_eq!(sub_table.names.len(), 1872),
            None => panic!("expected post table to have a sub-table"),
        }

        // These map to the same index (397)
        assert_eq!(post.glyph_name(257).unwrap().unwrap(), "Ldot");
        assert_eq!(post.glyph_name(1442).unwrap().unwrap(), "Ldot");
    }

    fn build_post_with_unused_names() -> Result<Vec<u8>, WriteError> {
        // Build a post table with unused name entries
        let mut w = WriteBuffer::new();
        let header = Header {
            version: 0x00020000,
            italic_angle: 0,
            underline_position: 0,
            underline_thickness: 0,
            is_fixed_pitch: 0,
            min_mem_type_42: 0,
            max_mem_type_42: 0,
            min_mem_type_1: 0,
            max_mem_type_1: 0,
        };

        Header::write(&mut w, &header)?;

        let num_glyphs = 10u16;
        U16Be::write(&mut w, num_glyphs)?;

        // Write name indexes that have unused names between each used entry
        U16Be::write(&mut w, 0u16)?; // .notdef
        for i in 0..(num_glyphs - 1) {
            U16Be::write(&mut w, i * 2 + 258)?;
        }
        // Write the names
        for i in 1..num_glyphs {
            // Write a real entry
            let name = format!("gid{}", i);
            let string = PascalString {
                bytes: name.as_bytes(),
            };
            PascalString::write(&mut w, &string)?;

            // Then the unused one in between
            let name = format!("unused{}", i);
            let string = PascalString {
                bytes: name.as_bytes(),
            };
            PascalString::write(&mut w, &string)?;
        }

        Ok(w.into_inner())
    }

    #[test]
    fn unused_glyph_names() {
        let post_data = build_post_with_unused_names().expect("unable to build post table");
        let post = ReadScope::new(&post_data)
            .read::<PostTable<'_>>()
            .expect("unable to parse post table");
        let num_glyphs = post.opt_sub_table.as_ref().unwrap().num_glyphs;
        for i in 0..num_glyphs {
            let expected = if i == 0 {
                String::from(".notdef")
            } else {
                format!("gid{}", i)
            };
            assert_eq!(post.glyph_name(i).unwrap().unwrap(), &expected);
        }
    }
}