oxideav-ttf 0.1.7

Pure-Rust TrueType font parser for the oxideav framework — sfnt + cmap + glyf + hmtx + GSUB ligatures + GPOS kerning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! `post` — PostScript metadata + glyph names.
//!
//! Decoded per ISO/IEC 14496-22:2019 §5.2.10 / MS Learn `otspec-post`
//! (`docs/text/opentype/otspec-post.html`). The fixed 32-byte header
//! is identical across every version and carries `italicAngle`,
//! underline geometry, the `isFixedPitch` boolean, and the four
//! PostScript memory-usage hints. After the header the layout
//! diverges per `version`:
//!
//! - **`0x00010000` (v1.0)** — no trailing data. The font is asserted
//!   to contain exactly the 258 glyphs of the standard Macintosh
//!   TrueType font in the standard order; glyph names are looked up
//!   from the system Macintosh glyph table by glyph id.
//! - **`0x00020000` (v2.0)** — `uint16 numGlyphs` + `uint16
//!   glyphNameIndex[numGlyphs]` + Pascal-format `stringData[…]`. Each
//!   glyph id selects an index `nameIdx`. If `nameIdx < 258` the
//!   glyph name is the corresponding standard Macintosh name; if
//!   `nameIdx >= 258` the name is the `(nameIdx - 258)`th Pascal
//!   string in `stringData`.
//! - **`0x00025000` (v2.5, deprecated)** — `uint16 numGlyphs` +
//!   `int8 offset[numGlyphs]`. For each glyph id `gid` the standard
//!   Macintosh glyph index is `gid + offset[gid]`. Used by legacy
//!   fonts whose glyph set is a permutation or subset of the
//!   standard Macintosh order.
//! - **`0x00030000` (v3.0)** — no trailing data, no glyph names.
//!   Required form for CFF v1 outline fonts; permitted for any font
//!   that does not wish to publish glyph names.
//!
//! Spec v4.0 is defined by Apple for non-OpenType use and is out of
//! scope per §5.2.10 ("not supported in OpenType"); it is rejected
//! here as an unsupported version.
//!
//! ## Standard-Macintosh-glyph-name list (gap)
//!
//! ISO §5.2.10.1 defers to "Reference [2]" (Apple's TrueType
//! Reference Manual, Chap 6 — the on-line `RM06/Chap6post.html`
//! page) for the list of the 258 standard Macintosh glyph names. The
//! MS Learn `otspec-post` page does the same. That reference is the
//! sole canonical source of the 258-name array and is not yet
//! staged in `docs/text/opentype/`. Until it is, this module:
//!
//! - decodes the post-table **structure** for all four versions
//!   (header + numGlyphs + index array + Pascal strings);
//! - exposes the per-glyph name index ([`GlyphNameRef::StandardMac`]
//!   `{ index }`) and the per-glyph Pascal string
//!   ([`GlyphNameRef::Custom`] `(&str)`) so a caller that supplies its
//!   own 258-name array can resolve names today;
//! - returns `None` from the convenience
//!   [`Font::glyph_name`](crate::Font::glyph_name) accessor whenever
//!   the resolution would require a standard Macintosh name, with
//!   the `Some(name)` path returning Pascal strings unchanged.
//!
//! Once the 258-name list is staged a single-commit follow-up adds
//! `STANDARD_MAC_GLYPH_NAMES: [&str; 258]` and turns the `StandardMac`
//! branch into a real `Some(&str)`. The decoder layout below is the
//! foundation that follow-up plugs into.

use crate::parser::{read_i16, read_i32, read_u16, read_u32, read_u8};
use crate::Error;

/// `post` table tag (`b"post"`).
pub const POST_TABLE_TAG: [u8; 4] = *b"post";

/// Fixed 32-byte common header length.
pub const POST_HEADER_LEN: usize = 32;

/// Version 1.0 (`0x00010000`). All names come from the standard
/// Macintosh order, addressed by glyph id.
pub const POST_VERSION_10: u32 = 0x0001_0000;

/// Version 2.0 (`0x00020000`). The most common form: per-glyph index
/// into the standard-Mac set or the local Pascal-string pool.
pub const POST_VERSION_20: u32 = 0x0002_0000;

/// Version 2.5 (`0x00025000`, deprecated). Per-glyph signed `int8`
/// offset into the standard-Macintosh glyph order.
pub const POST_VERSION_25: u32 = 0x0002_5000;

/// Version 3.0 (`0x00030000`). No glyph names; the only form
/// permitted for CFF v1 fonts.
pub const POST_VERSION_30: u32 = 0x0003_0000;

/// Inclusive upper bound on the standard-Macintosh glyph-name index
/// space. `glyphNameIndex` values strictly below this address the
/// 258-name standard set; values at or above it address the Pascal
/// string pool offset by this constant.
pub const STANDARD_MAC_GLYPH_COUNT: u16 = 258;

/// Maximum length of a v2.0 PostScript glyph name in bytes, per
/// §5.2.10.2: "Names must be no longer than 63 characters; some older
/// implementations can assume a length limit of 31 characters." This
/// is a tolerance ceiling — names up to and including 63 bytes are
/// accepted; longer names are tolerated (the Pascal length byte is
/// itself a `u8`, capping at 255) but flagged through
/// [`PostTable::has_oversize_glyph_name`] so callers can downgrade
/// gracefully.
pub const RECOMMENDED_GLYPH_NAME_MAX_LEN: usize = 63;

/// Parsed `post` table. The common header is always populated;
/// `format` carries the version-dependent trailing data.
#[derive(Debug, Clone)]
pub struct PostTable {
    /// Raw `Version16Dot16` from the header. Preserved verbatim so
    /// callers that want to introspect the exact published version
    /// (e.g. to distinguish v1.0 from v2.0 explicitly) can do so;
    /// typed `format` covers the structural reading.
    pub version_raw: u32,
    /// Italic angle in counter-clockwise degrees from the vertical.
    /// `0.0` for upright; negative for forward-slanted (the common
    /// case).
    pub italic_angle: f32,
    /// Suggested y-coordinate of the top of the underline.
    pub underline_position: i16,
    /// Suggested underline thickness.
    pub underline_thickness: i16,
    /// `true` when the font is monospaced (header `isFixedPitch`
    /// `!= 0`), `false` for proportionally-spaced fonts.
    pub is_fixed_pitch: bool,
    /// PostScript memory-management hints. Set to `0` when the font
    /// foundry did not measure them.
    pub min_mem_type42: u32,
    /// See [`PostTable::min_mem_type42`].
    pub max_mem_type42: u32,
    /// See [`PostTable::min_mem_type42`].
    pub min_mem_type1: u32,
    /// See [`PostTable::min_mem_type42`].
    pub max_mem_type1: u32,
    /// Version-specific tail.
    pub format: PostFormat,
}

/// Version-dependent trailing data.
#[derive(Debug, Clone)]
pub enum PostFormat {
    /// v1.0: no trailing data. The font claims to be the standard
    /// Macintosh 258-glyph layout.
    Version10,
    /// v2.0: per-glyph `(name_index, optional Pascal string)` table.
    Version20(PostV20),
    /// v2.5 (deprecated): per-glyph signed offset into the standard
    /// Macintosh order.
    Version25(PostV25),
    /// v3.0: no glyph names at all.
    Version30,
}

/// Version 2.0 trailing data — index array + Pascal-string pool.
#[derive(Debug, Clone)]
pub struct PostV20 {
    /// `numGlyphs` — must match `maxp.numGlyphs`. Preserved verbatim
    /// so callers can sanity-check against `maxp`.
    pub num_glyphs: u16,
    /// `glyphNameIndex[numGlyphs]` — per-glyph index into either the
    /// standard Macintosh 258-name set or the Pascal-string pool.
    pub glyph_name_indices: Vec<u16>,
    /// Pascal strings extracted from `stringData`, in publication
    /// order. Index `k` here corresponds to the v2.0 lookup rule
    /// "subtract 258 from `nameIndex` and use that as the array
    /// index"; that is, `pascal_strings[k]` is the name a
    /// `glyphNameIndex` value of `258 + k` selects.
    pub pascal_strings: Vec<String>,
    /// `true` when at least one Pascal string exceeds the §5.2.10.2
    /// recommended 63-byte cap. Names are kept verbatim regardless;
    /// the flag exists so callers that need strict conformance can
    /// detect it without re-scanning.
    pub has_oversize_glyph_name: bool,
    /// `true` when at least one Pascal string contains a byte outside
    /// the §5.2.10.2 allow-set (`A..Z`, `a..z`, `0..9`, `.`, `_`).
    /// Such names still decode (they are interpreted as ASCII bytes
    /// because the §5.2.10.2 wording requires ASCII) but flagged so
    /// strict consumers can reject the font.
    pub has_non_conformant_glyph_name: bool,
}

/// Version 2.5 trailing data — per-glyph signed offset into the
/// standard Macintosh order.
#[derive(Debug, Clone)]
pub struct PostV25 {
    /// `numGlyphs` — must match `maxp.numGlyphs`.
    pub num_glyphs: u16,
    /// `offset[numGlyphs]` — signed delta from this font's glyph id
    /// to the standard Macintosh order. Per §5.2.10.3 the standard
    /// glyph index is `glyph_id + offset[glyph_id]`.
    pub offsets: Vec<i8>,
}

/// Resolved name of a single glyph as carried by `post`.
///
/// Callers consume this via [`PostTable::glyph_name_ref`]. The
/// `StandardMac { index }` variant is the bridge for the pending
/// 258-name list (docs gap #1277). Once the list is staged a
/// `standard_mac_glyph_name(index)` helper can synthesise a
/// `&'static str` from the index; until then the index itself is
/// surfaced verbatim so tooling can either bring its own 258-name
/// array or treat the glyph as unnamed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphNameRef<'a> {
    /// The glyph's name is the `index`th entry of the 258-name
    /// standard Macintosh glyph order. `index < 258` is guaranteed.
    StandardMac { index: u16 },
    /// The glyph's name is the font-supplied Pascal string. Already
    /// trimmed of its length byte.
    Custom(&'a str),
}

impl PostTable {
    /// Parse the `post` table from its slice. Returns `BadStructure`
    /// for unrecognised versions and `UnexpectedEof` for truncated
    /// arrays.
    pub fn parse(bytes: &[u8]) -> Result<Self, Error> {
        if bytes.len() < POST_HEADER_LEN {
            return Err(Error::UnexpectedEof);
        }
        let version_raw = read_u32(bytes, 0)?;
        let italic_raw = read_i32(bytes, 4)?;
        let italic_angle = italic_raw as f32 / 65536.0;
        let underline_position = read_i16(bytes, 8)?;
        let underline_thickness = read_i16(bytes, 10)?;
        let is_fixed_pitch = read_u32(bytes, 12)? != 0;
        let min_mem_type42 = read_u32(bytes, 16)?;
        let max_mem_type42 = read_u32(bytes, 20)?;
        let min_mem_type1 = read_u32(bytes, 24)?;
        let max_mem_type1 = read_u32(bytes, 28)?;

        let tail = &bytes[POST_HEADER_LEN..];
        let format = match version_raw {
            POST_VERSION_10 => PostFormat::Version10,
            POST_VERSION_20 => PostFormat::Version20(parse_v20(tail)?),
            POST_VERSION_25 => PostFormat::Version25(parse_v25(tail)?),
            POST_VERSION_30 => PostFormat::Version30,
            _ => return Err(Error::BadStructure("post: unsupported version")),
        };

        Ok(Self {
            version_raw,
            italic_angle,
            underline_position,
            underline_thickness,
            is_fixed_pitch,
            min_mem_type42,
            max_mem_type42,
            min_mem_type1,
            max_mem_type1,
            format,
        })
    }

    /// `true` when the table carries any glyph-name information
    /// (v1.0, v2.0, or v2.5). v3.0 returns `false`.
    pub fn has_glyph_names(&self) -> bool {
        !matches!(self.format, PostFormat::Version30)
    }

    /// `true` when at least one v2.0 Pascal string exceeds the
    /// §5.2.10.2 recommended 63-byte limit. `false` for every other
    /// version.
    pub fn has_oversize_glyph_name(&self) -> bool {
        match &self.format {
            PostFormat::Version20(v) => v.has_oversize_glyph_name,
            _ => false,
        }
    }

    /// `true` when at least one v2.0 Pascal string contains a byte
    /// outside the §5.2.10.2 allow-set. `false` for every other
    /// version.
    pub fn has_non_conformant_glyph_name(&self) -> bool {
        match &self.format {
            PostFormat::Version20(v) => v.has_non_conformant_glyph_name,
            _ => false,
        }
    }

    /// Number of distinct Pascal strings in the v2.0 string pool, or
    /// `0` for every other version.
    pub fn pascal_string_count(&self) -> usize {
        match &self.format {
            PostFormat::Version20(v) => v.pascal_strings.len(),
            _ => 0,
        }
    }

    /// Look up the `gid`th glyph's name reference.
    ///
    /// Returns `None` when:
    /// - the table is v3.0 (no names at all);
    /// - `gid` is out of range for the v2.0 / v2.5 array;
    /// - the v2.0 `glyphNameIndex[gid]` selects a Pascal string the
    ///   pool does not actually contain (malformed font; preserved
    ///   as `None` rather than treated as a parse error so a single
    ///   bad glyph does not poison the whole table);
    /// - the v2.5 offset overflows `u16` (likewise malformed).
    ///
    /// For v1.0 every `gid < 258` yields
    /// `Some(GlyphNameRef::StandardMac { index: gid })`; for v1.0 the
    /// numGlyphs upper bound is not encoded inside `post` so the
    /// caller is responsible for keeping `gid` below `maxp.numGlyphs`.
    pub fn glyph_name_ref(&self, gid: u16) -> Option<GlyphNameRef<'_>> {
        match &self.format {
            PostFormat::Version10 => {
                if gid < STANDARD_MAC_GLYPH_COUNT {
                    Some(GlyphNameRef::StandardMac { index: gid })
                } else {
                    None
                }
            }
            PostFormat::Version20(v) => {
                let idx = *v.glyph_name_indices.get(gid as usize)?;
                if idx < STANDARD_MAC_GLYPH_COUNT {
                    Some(GlyphNameRef::StandardMac { index: idx })
                } else {
                    let pi = (idx - STANDARD_MAC_GLYPH_COUNT) as usize;
                    v.pascal_strings
                        .get(pi)
                        .map(|s| GlyphNameRef::Custom(s.as_str()))
                }
            }
            PostFormat::Version25(v) => {
                let off = *v.offsets.get(gid as usize)?;
                // Standard glyph index = gid + offset; reject if it
                // falls outside `[0, 258)`.
                let std = i32::from(gid) + i32::from(off);
                if (0..i32::from(STANDARD_MAC_GLYPH_COUNT)).contains(&std) {
                    Some(GlyphNameRef::StandardMac { index: std as u16 })
                } else {
                    None
                }
            }
            PostFormat::Version30 => None,
        }
    }

    /// Convenience: the v2.0 Pascal string for a glyph, if the font
    /// names it through a custom string. Returns `None` for the
    /// `StandardMac` indices, for missing glyph ids, and for every
    /// non-v2.0 version.
    pub fn custom_glyph_name(&self, gid: u16) -> Option<&str> {
        match self.glyph_name_ref(gid)? {
            GlyphNameRef::Custom(s) => Some(s),
            GlyphNameRef::StandardMac { .. } => None,
        }
    }
}

fn parse_v20(tail: &[u8]) -> Result<PostV20, Error> {
    if tail.len() < 2 {
        return Err(Error::UnexpectedEof);
    }
    let num_glyphs = read_u16(tail, 0)?;
    let idx_bytes_len = 2usize
        .checked_mul(num_glyphs as usize)
        .ok_or(Error::BadStructure("post v2.0: numGlyphs overflow"))?;
    let idx_end = 2usize
        .checked_add(idx_bytes_len)
        .ok_or(Error::BadStructure("post v2.0: numGlyphs overflow"))?;
    if tail.len() < idx_end {
        return Err(Error::UnexpectedEof);
    }
    let mut glyph_name_indices = Vec::with_capacity(num_glyphs as usize);
    let mut max_pascal_referenced: i32 = -1;
    for i in 0..num_glyphs as usize {
        let v = read_u16(tail, 2 + i * 2)?;
        if v >= STANDARD_MAC_GLYPH_COUNT {
            let pi = (v - STANDARD_MAC_GLYPH_COUNT) as i32;
            if pi > max_pascal_referenced {
                max_pascal_referenced = pi;
            }
        }
        glyph_name_indices.push(v);
    }

    // Pascal strings extend from `idx_end` to the end of the table.
    let pool = &tail[idx_end..];
    let mut pascal_strings: Vec<String> = Vec::new();
    let mut has_oversize_glyph_name = false;
    let mut has_non_conformant_glyph_name = false;
    let mut p = 0usize;
    while p < pool.len() {
        let len = read_u8(pool, p)? as usize;
        p += 1;
        if p + len > pool.len() {
            return Err(Error::UnexpectedEof);
        }
        let raw = &pool[p..p + len];
        if len > RECOMMENDED_GLYPH_NAME_MAX_LEN {
            has_oversize_glyph_name = true;
        }
        if !raw.iter().all(|b| is_conformant_glyph_name_byte(*b)) {
            has_non_conformant_glyph_name = true;
        }
        // Per §5.2.10.2 names are ASCII; for non-conformant bytes we
        // still keep the byte values (clamped into a `String` via
        // `from_utf8_lossy`) so caller diagnostics can see them.
        let s = match std::str::from_utf8(raw) {
            Ok(s) => s.to_string(),
            Err(_) => String::from_utf8_lossy(raw).into_owned(),
        };
        pascal_strings.push(s);
        p += len;
    }

    // §5.2.10.2 worked example: glyphNameIndex[408] == 262 selects
    // pascal_strings[4]. A font that references a Pascal index its
    // pool cannot satisfy is malformed; `glyph_name_ref` returns
    // `None` for those gids, but we accept the parse so the
    // well-formed glyphs still decode.
    let _ = max_pascal_referenced;

    Ok(PostV20 {
        num_glyphs,
        glyph_name_indices,
        pascal_strings,
        has_oversize_glyph_name,
        has_non_conformant_glyph_name,
    })
}

fn parse_v25(tail: &[u8]) -> Result<PostV25, Error> {
    if tail.len() < 2 {
        return Err(Error::UnexpectedEof);
    }
    let num_glyphs = read_u16(tail, 0)?;
    let needed = 2usize
        .checked_add(num_glyphs as usize)
        .ok_or(Error::BadStructure("post v2.5: numGlyphs overflow"))?;
    if tail.len() < needed {
        return Err(Error::UnexpectedEof);
    }
    let mut offsets = Vec::with_capacity(num_glyphs as usize);
    for i in 0..num_glyphs as usize {
        offsets.push(tail[2 + i] as i8);
    }
    Ok(PostV25 {
        num_glyphs,
        offsets,
    })
}

fn is_conformant_glyph_name_byte(b: u8) -> bool {
    // §5.2.10.2 glyph-name allow-set: A..Z, a..z, 0..9, '.' (0x2E),
    // '_' (0x5F).
    b.is_ascii_uppercase() || b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'_'
}

#[cfg(test)]
mod tests {
    use super::*;

    fn header(version: u32) -> Vec<u8> {
        let mut b = vec![0u8; POST_HEADER_LEN];
        b[0..4].copy_from_slice(&version.to_be_bytes());
        // italicAngle = -10.0 (Fixed: -10 * 65536)
        b[4..8].copy_from_slice(&((-10i32) << 16).to_be_bytes());
        b[8..10].copy_from_slice(&(-100i16).to_be_bytes());
        b[10..12].copy_from_slice(&50i16.to_be_bytes());
        b[12..16].copy_from_slice(&1u32.to_be_bytes());
        b[16..20].copy_from_slice(&0u32.to_be_bytes());
        b[20..24].copy_from_slice(&0u32.to_be_bytes());
        b[24..28].copy_from_slice(&0u32.to_be_bytes());
        b[28..32].copy_from_slice(&0u32.to_be_bytes());
        b
    }

    #[test]
    fn parses_minimal_v3_header() {
        let b = header(POST_VERSION_30);
        let p = PostTable::parse(&b).unwrap();
        assert_eq!(p.version_raw, POST_VERSION_30);
        assert!((p.italic_angle - (-10.0)).abs() < 0.001);
        assert_eq!(p.underline_position, -100);
        assert_eq!(p.underline_thickness, 50);
        assert!(p.is_fixed_pitch);
        assert!(matches!(p.format, PostFormat::Version30));
        assert!(!p.has_glyph_names());
        assert!(p.glyph_name_ref(0).is_none());
    }

    #[test]
    fn parses_v10_returns_standard_mac_indices() {
        let b = header(POST_VERSION_10);
        let p = PostTable::parse(&b).unwrap();
        assert!(matches!(p.format, PostFormat::Version10));
        assert!(p.has_glyph_names());
        assert_eq!(
            p.glyph_name_ref(0),
            Some(GlyphNameRef::StandardMac { index: 0 })
        );
        assert_eq!(
            p.glyph_name_ref(217),
            Some(GlyphNameRef::StandardMac { index: 217 })
        );
        // gid == 258 is out of the standard set; v1.0 cannot name it.
        assert!(p.glyph_name_ref(258).is_none());
    }

    /// §5.2.10.2 worked example: glyphNameIndex[302] is 217 → standard
    /// Macintosh entry 217; glyphNameIndex[408] is 262 → fifth Pascal
    /// string (index 4).
    #[test]
    fn v20_resolves_spec_worked_example() {
        let num_glyphs: u16 = 409;
        let mut tail = Vec::new();
        tail.extend_from_slice(&num_glyphs.to_be_bytes());
        for gid in 0..num_glyphs {
            let idx: u16 = match gid {
                302 => 217,
                408 => 262, // 258 + 4 → pascal_strings[4]
                _ => 0,     // .notdef placeholder
            };
            tail.extend_from_slice(&idx.to_be_bytes());
        }
        // Pascal pool: 5 strings.
        for name in ["one", "two", "three", "four", "weird"] {
            tail.push(name.len() as u8);
            tail.extend_from_slice(name.as_bytes());
        }

        let mut bytes = header(POST_VERSION_20);
        bytes.extend_from_slice(&tail);
        let p = PostTable::parse(&bytes).unwrap();
        assert!(p.has_glyph_names());
        assert_eq!(p.pascal_string_count(), 5);
        assert_eq!(
            p.glyph_name_ref(302),
            Some(GlyphNameRef::StandardMac { index: 217 })
        );
        assert_eq!(p.glyph_name_ref(408), Some(GlyphNameRef::Custom("weird")));
        assert_eq!(p.custom_glyph_name(408), Some("weird"));
        assert!(p.custom_glyph_name(302).is_none());
    }

    #[test]
    fn v20_pascal_pool_indices_are_zero_based() {
        // First custom Pascal string is `nameIndex == 258`.
        let num_glyphs: u16 = 2;
        let mut tail = Vec::new();
        tail.extend_from_slice(&num_glyphs.to_be_bytes());
        tail.extend_from_slice(&258u16.to_be_bytes()); // gid 0 -> "Alpha"
        tail.extend_from_slice(&259u16.to_be_bytes()); // gid 1 -> "Beta"
        for name in ["Alpha", "Beta"] {
            tail.push(name.len() as u8);
            tail.extend_from_slice(name.as_bytes());
        }
        let mut bytes = header(POST_VERSION_20);
        bytes.extend_from_slice(&tail);
        let p = PostTable::parse(&bytes).unwrap();
        assert_eq!(p.glyph_name_ref(0), Some(GlyphNameRef::Custom("Alpha")));
        assert_eq!(p.glyph_name_ref(1), Some(GlyphNameRef::Custom("Beta")));
    }

    #[test]
    fn v20_rejects_truncated_pascal_string() {
        // Length byte claims 5 chars, only 3 follow.
        let num_glyphs: u16 = 1;
        let mut tail = Vec::new();
        tail.extend_from_slice(&num_glyphs.to_be_bytes());
        tail.extend_from_slice(&258u16.to_be_bytes());
        tail.push(5); // claim 5 bytes
        tail.extend_from_slice(b"abc");
        let mut bytes = header(POST_VERSION_20);
        bytes.extend_from_slice(&tail);
        assert!(matches!(
            PostTable::parse(&bytes),
            Err(Error::UnexpectedEof)
        ));
    }

    #[test]
    fn v20_flags_oversize_and_non_conformant_names() {
        // 1 glyph naming index, 1 oversize name (64 chars of 'a') and
        // 1 non-conformant name (contains '/').
        let num_glyphs: u16 = 2;
        let mut tail = Vec::new();
        tail.extend_from_slice(&num_glyphs.to_be_bytes());
        tail.extend_from_slice(&258u16.to_be_bytes()); // -> pool[0] (oversize)
        tail.extend_from_slice(&259u16.to_be_bytes()); // -> pool[1] (non-conformant)
        let oversize = "a".repeat(64);
        tail.push(oversize.len() as u8);
        tail.extend_from_slice(oversize.as_bytes());
        let bad = "weird/name";
        tail.push(bad.len() as u8);
        tail.extend_from_slice(bad.as_bytes());
        let mut bytes = header(POST_VERSION_20);
        bytes.extend_from_slice(&tail);
        let p = PostTable::parse(&bytes).unwrap();
        assert!(p.has_oversize_glyph_name());
        assert!(p.has_non_conformant_glyph_name());
    }

    #[test]
    fn v25_resolves_signed_offset_into_standard_set() {
        // §5.2.10.3 worked example: 3 glyphs (font ids 0, 1, 2) =
        // standard ids 36, 37, 38 (A, B, C in standard order). Each
        // offset is +36.
        let num_glyphs: u16 = 3;
        let mut tail = Vec::new();
        tail.extend_from_slice(&num_glyphs.to_be_bytes());
        tail.push(36i8 as u8);
        tail.push(36i8 as u8);
        tail.push(36i8 as u8);
        let mut bytes = header(POST_VERSION_25);
        bytes.extend_from_slice(&tail);
        let p = PostTable::parse(&bytes).unwrap();
        assert!(p.has_glyph_names());
        assert_eq!(
            p.glyph_name_ref(0),
            Some(GlyphNameRef::StandardMac { index: 36 })
        );
        assert_eq!(
            p.glyph_name_ref(1),
            Some(GlyphNameRef::StandardMac { index: 37 })
        );
        assert_eq!(
            p.glyph_name_ref(2),
            Some(GlyphNameRef::StandardMac { index: 38 })
        );
    }

    #[test]
    fn v25_negative_offset_below_zero_yields_none() {
        // gid 0 with offset -1 would map to standard index -1; reject.
        let num_glyphs: u16 = 1;
        let mut tail = Vec::new();
        tail.extend_from_slice(&num_glyphs.to_be_bytes());
        tail.push((-1i8) as u8);
        let mut bytes = header(POST_VERSION_25);
        bytes.extend_from_slice(&tail);
        let p = PostTable::parse(&bytes).unwrap();
        assert!(p.glyph_name_ref(0).is_none());
    }

    #[test]
    fn v25_offset_past_standard_set_yields_none() {
        // gid 0 with offset 257 maps to standard index 257 → still
        // legal. gid 0 with offset 127 + gid 250 with offset 127 maps
        // to 377 → out of range.
        let num_glyphs: u16 = 251;
        let mut tail = Vec::new();
        tail.extend_from_slice(&num_glyphs.to_be_bytes());
        for _ in 0..num_glyphs {
            tail.push(127i8 as u8);
        }
        let mut bytes = header(POST_VERSION_25);
        bytes.extend_from_slice(&tail);
        let p = PostTable::parse(&bytes).unwrap();
        // gid 0 + 127 = 127 (in range).
        assert_eq!(
            p.glyph_name_ref(0),
            Some(GlyphNameRef::StandardMac { index: 127 })
        );
        // gid 250 + 127 = 377 (out of [0,258)).
        assert!(p.glyph_name_ref(250).is_none());
    }

    #[test]
    fn rejects_unknown_version() {
        // Apple v4.0 is "not supported in OpenType" per §5.2.10.
        let b = header(0x0004_0000);
        assert!(matches!(PostTable::parse(&b), Err(Error::BadStructure(_))));
    }

    #[test]
    fn rejects_short_header() {
        let b = vec![0u8; 31];
        assert!(matches!(PostTable::parse(&b), Err(Error::UnexpectedEof)));
    }

    #[test]
    fn v20_truncated_index_array_rejected() {
        // numGlyphs=2 but only 2 bytes of index data (need 4).
        let mut tail = Vec::new();
        tail.extend_from_slice(&2u16.to_be_bytes());
        tail.extend_from_slice(&0u16.to_be_bytes()); // only one entry
        let mut bytes = header(POST_VERSION_20);
        bytes.extend_from_slice(&tail);
        assert!(matches!(
            PostTable::parse(&bytes),
            Err(Error::UnexpectedEof)
        ));
    }

    #[test]
    fn v20_pascal_index_out_of_pool_decodes_glyph_as_none() {
        // glyphNameIndex == 258 but no Pascal strings present.
        let num_glyphs: u16 = 1;
        let mut tail = Vec::new();
        tail.extend_from_slice(&num_glyphs.to_be_bytes());
        tail.extend_from_slice(&258u16.to_be_bytes());
        // No string-data bytes.
        let mut bytes = header(POST_VERSION_20);
        bytes.extend_from_slice(&tail);
        let p = PostTable::parse(&bytes).unwrap();
        assert!(p.glyph_name_ref(0).is_none());
    }

    #[test]
    fn version_constants_sanity() {
        assert_eq!(POST_VERSION_10, 0x0001_0000);
        assert_eq!(POST_VERSION_20, 0x0002_0000);
        assert_eq!(POST_VERSION_25, 0x0002_5000);
        assert_eq!(POST_VERSION_30, 0x0003_0000);
        assert_eq!(STANDARD_MAC_GLYPH_COUNT, 258);
        assert_eq!(POST_HEADER_LEN, 32);
    }
}