Skip to main content

font_parse/tables/
cmap.rs

1//! `cmap` — character-to-glyph mapping (formats 0, 4, 6, 12).
2
3use crate::error::{ParseError, RawTag};
4use alloc::vec::Vec;
5use font_types::{BigEndian, GlyphId};
6
7pub(crate) const TAG: RawTag = *b"cmap";
8
9/// Subtable header size.
10const SUB_HEADER: usize = 4;
11/// Encoding record size.
12const RECORD: usize = 8;
13
14/// A `cmap` encoding record: platform/encoding id plus subtable offset.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct EncodingRecord {
17    /// Platform id (0 Unicode, 1 Macintosh, 3 Microsoft, …).
18    pub platform_id: u16,
19    /// Encoding id (platform-specific; e.g. 1 = BMP, 10 = UCS-4).
20    pub encoding_id: u16,
21    /// Offset of the subtable from the `cmap` table start.
22    pub offset: u32,
23}
24
25impl EncodingRecord {
26    /// True for encodings that carry a Unicode character mapping.
27    #[must_use]
28    pub const fn is_unicode(self) -> bool {
29        self.platform_id == 0
30            || (self.platform_id == 3 && (self.encoding_id == 1 || self.encoding_id == 10))
31    }
32}
33
34/// Zero-copy view over the `cmap` table.
35///
36/// The header and encoding records are validated eagerly; subtables are
37/// decoded lazily. Lookups via [`codepoint`](Self::codepoint) are total:
38/// unsupported or malformed subtables are skipped in favor of the next
39/// candidate record (typed access is available through
40/// [`subtable`](Self::subtable)).
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct Cmap<'a> {
43    data: &'a [u8],
44    records: &'a [u8],
45}
46
47impl<'a> Cmap<'a> {
48    /// Parse and validate the `cmap` header + encoding records.
49    ///
50    /// # Errors
51    /// [`ParseError::TruncatedTable`] when header or records are truncated;
52    /// [`ParseError::InvalidGlyphFormat`] when the record count is
53    /// inconsistent with the table length.
54    pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
55        if data.len() < SUB_HEADER {
56            return Err(ParseError::TruncatedTable {
57                tag: TAG,
58                expected: SUB_HEADER,
59                got: data.len(),
60            });
61        }
62        let num_tables = crate::reader::be_u16_at(data, 2, TAG)?;
63        let end = 4 + usize::from(num_tables)
64            .checked_mul(RECORD)
65            .ok_or(ParseError::InvalidGlyphFormat)?;
66        if end > data.len() {
67            return Err(ParseError::TruncatedTable {
68                tag: TAG,
69                expected: end,
70                got: data.len(),
71            });
72        }
73        // Every record's offset must at least point inside the table.
74        for i in 0..usize::from(num_tables) {
75            let at = 4 + i * RECORD;
76            let offset = crate::reader::be_u32_at(data, at + 4, TAG)?;
77            let inside = usize::try_from(offset)
78                .map(|o| o.checked_add(SUB_HEADER).is_some_and(|e| e <= data.len()))
79                .unwrap_or(false);
80            if !inside {
81                return Err(ParseError::InvalidGlyphFormat);
82            }
83        }
84        Ok(Self {
85            data,
86            records: crate::reader::slice_at(data, 4, end - 4, TAG)?,
87        })
88    }
89
90    /// Raw table bytes.
91    #[must_use]
92    pub fn as_bytes(&self) -> &'a [u8] {
93        self.data
94    }
95
96    /// The encoding records, in table order.
97    pub fn records(&self) -> Vec<EncodingRecord> {
98        let mut out = Vec::new();
99        for chunk in self.records.chunks_exact(RECORD) {
100            let platform_id = chunk
101                .get(0..2)
102                .and_then(BigEndian::<u16>::from_slice)
103                .map_or(0, |b| b.get());
104            let encoding_id = chunk
105                .get(2..4)
106                .and_then(BigEndian::<u16>::from_slice)
107                .map_or(0, |b| b.get());
108            let offset = chunk
109                .get(4..8)
110                .and_then(BigEndian::<u32>::from_slice)
111                .map_or(0, |b| b.get());
112            out.push(EncodingRecord {
113                platform_id,
114                encoding_id,
115                offset,
116            });
117        }
118        out
119    }
120
121    /// Decode the subtable referenced by record `index`.
122    ///
123    /// # Errors
124    /// [`ParseError::InvalidCmapFormat`] for formats this parser does not
125    /// implement (2, 8, 10, 13, 14) or invalid format numbers;
126    /// [`ParseError::TruncatedTable`] / [`ParseError::InvalidGlyphFormat`]
127    /// for malformed subtables.
128    pub fn subtable(&self, index: usize) -> Result<CmapSubtable<'a>, ParseError> {
129        let record = *self
130            .records()
131            .get(index)
132            .ok_or(ParseError::InvalidGlyphFormat)?;
133        let at = usize::try_from(record.offset).map_err(|_| ParseError::InvalidGlyphFormat)?;
134        let data = self.data.get(at..).ok_or(ParseError::InvalidGlyphFormat)?;
135        CmapSubtable::parse(data)
136    }
137
138    /// Map a Unicode scalar to a glyph id.
139    ///
140    /// Candidates are scanned in spec-preference order (UCS-4 subtables
141    /// before BMP before platform-0 catch-alls); the first subtable that
142    /// both decodes and maps the codepoint wins. Returns `None` when no
143    /// Unicode subtable maps the character. Never panics: malformed or
144    /// unsupported subtables are skipped.
145    #[must_use]
146    pub fn codepoint(&self, c: char) -> Option<GlyphId> {
147        self.codepoint_u32(u32::from(c))
148    }
149
150    /// [`codepoint`](Self::codepoint) for a raw codepoint value.
151    #[must_use]
152    pub fn codepoint_u32(&self, cp: u32) -> Option<GlyphId> {
153        // Candidates in spec-preference order (UCS-4 subtables before BMP
154        // before platform-0 catch-alls); stable sort keeps table order for
155        // ties. Malformed or unsupported subtables are skipped.
156        let mut candidates: Vec<(u8, usize)> = self
157            .records()
158            .iter()
159            .enumerate()
160            .filter(|(_, r)| r.is_unicode())
161            .map(|(i, r)| (preference(r.platform_id, r.encoding_id), i))
162            .collect();
163        candidates.sort_by_key(|c| core::cmp::Reverse(c.0));
164        for (_, i) in candidates {
165            if let Ok(sub) = self.subtable(i) {
166                if let Some(gid) = sub.lookup(cp) {
167                    return Some(GlyphId::new(u32::from(gid)));
168                }
169            }
170        }
171        None
172    }
173}
174
175/// Lookup preference score for a Unicode-capable encoding record; higher
176/// wins. (3, 10) UCS-4 outranks platform-0 outranks (3, 1) BMP.
177fn preference(platform: u16, encoding: u16) -> u8 {
178    match (platform, encoding) {
179        (3, 10) => 6,
180        (0, _) => 5,
181        (3, 1) => 4,
182        _ => 0,
183    }
184}
185
186/// A decoded `cmap` subtable.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub enum CmapSubtable<'a> {
189    /// Byte encoding table (format 0).
190    Format0(Format0<'a>),
191    /// Segment mapping to delta values (format 4).
192    Format4(Format4<'a>),
193    /// Trimmed table mapping (format 6).
194    Format6(Format6<'a>),
195    /// Segmented coverage (format 12).
196    Format12(Format12<'a>),
197}
198
199impl<'a> CmapSubtable<'a> {
200    /// Decode a subtable by its format field.
201    ///
202    /// # Errors
203    /// [`ParseError::InvalidCmapFormat`] for unsupported/invalid formats;
204    /// format-specific parse errors otherwise.
205    pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
206        if data.len() < 2 {
207            return Err(ParseError::TruncatedTable {
208                tag: TAG,
209                expected: 2,
210                got: data.len(),
211            });
212        }
213        match crate::reader::be_u16_at(data, 0, TAG)? {
214            0 => Ok(Self::Format0(Format0::parse(data)?)),
215            4 => Ok(Self::Format4(Format4::parse(data)?)),
216            6 => Ok(Self::Format6(Format6::parse(data)?)),
217            12 => Ok(Self::Format12(Format12::parse(data)?)),
218            other => Err(ParseError::InvalidCmapFormat(other)),
219        }
220    }
221
222    /// Map a codepoint to a raw glyph id (`None` = not mapped).
223    #[must_use]
224    pub fn lookup(&self, cp: u32) -> Option<u16> {
225        match self {
226            Self::Format0(t) => t.lookup(cp),
227            Self::Format4(t) => t.lookup(cp),
228            Self::Format6(t) => t.lookup(cp),
229            Self::Format12(t) => t.lookup(cp),
230        }
231    }
232}
233
234/// Format 0 — byte encoding table: 256 direct glyph ids.
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub struct Format0<'a> {
237    glyph_array: &'a [u8],
238}
239
240impl<'a> Format0<'a> {
241    fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
242        // 6-byte header + 256 bytes.
243        if data.len() < 6 + 256 {
244            return Err(ParseError::TruncatedTable {
245                tag: TAG,
246                expected: 6 + 256,
247                got: data.len(),
248            });
249        }
250        Ok(Self {
251            glyph_array: crate::reader::slice_at(data, 6, 256, TAG)?,
252        })
253    }
254
255    fn lookup(&self, cp: u32) -> Option<u16> {
256        if cp < 256 {
257            self.glyph_array.get(cp as usize).map(|&g| u16::from(g))
258        } else {
259            None
260        }
261    }
262}
263
264/// Format 4 — segment mapping to delta values (BMP).
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266pub struct Format4<'a> {
267    data: &'a [u8],
268    seg_count: usize,
269    /// Offset of the `endCode` array.
270    ends: usize,
271    /// Offset of the `startCode` array.
272    starts: usize,
273    /// Offset of the `idDelta` array.
274    deltas: usize,
275    /// Offset of the `idRangeOffset` array.
276    ranges: usize,
277}
278
279impl<'a> Format4<'a> {
280    fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
281        if data.len() < 14 {
282            return Err(ParseError::TruncatedTable {
283                tag: TAG,
284                expected: 14,
285                got: data.len(),
286            });
287        }
288        let seg_count_x2 = crate::reader::be_u16_at(data, 6, TAG)?;
289        if seg_count_x2 == 0 || seg_count_x2 % 2 != 0 {
290            return Err(ParseError::InvalidGlyphFormat);
291        }
292        let seg_count = usize::from(seg_count_x2 / 2);
293        let ends = 14;
294        let starts = ends + seg_count * 2 + 2; // reservedPad u16 in between
295        let deltas = starts + seg_count * 2;
296        let ranges = deltas + seg_count * 2;
297        // The glyphIndexArray may be empty; require the four arrays to fit.
298        let needed = ranges + seg_count * 2;
299        if data.len() < needed {
300            return Err(ParseError::TruncatedTable {
301                tag: TAG,
302                expected: needed,
303                got: data.len(),
304            });
305        }
306        Ok(Self {
307            data,
308            seg_count,
309            ends,
310            starts,
311            deltas,
312            ranges,
313        })
314    }
315
316    fn lookup(&self, cp: u32) -> Option<u16> {
317        if cp > 0xFFFF {
318            return None;
319        }
320        let cp16 = cp as u16;
321        // endCodes are sorted ascending; find the first segment whose end
322        // code is >= cp, then confirm cp >= startCode.
323        let seg = self.segment_for(cp16)?;
324        let start =
325            crate::reader::be_u16_at(self.data, self.starts + seg * 2, TAG).unwrap_or(u16::MAX);
326        if cp16 < start {
327            return None;
328        }
329        let range_offset =
330            crate::reader::be_u16_at(self.data, self.ranges + seg * 2, TAG).unwrap_or(0);
331        let glyph = if range_offset == 0 {
332            let delta =
333                crate::reader::be_u16_at(self.data, self.deltas + seg * 2, TAG).unwrap_or(0);
334            cp16.wrapping_add(delta)
335        } else {
336            // glyphIndexArray address, relative to the idRangeOffset[seg]
337            // slot, in u16 units (spec: idRangeOffset/2 + cp - start + seg -
338            // segCount).
339            let rel = (usize::from(range_offset) / 2)
340                .checked_add(cp16.wrapping_sub(start) as usize)?
341                .checked_add(seg)?
342                .checked_sub(self.seg_count)?;
343            let slot = self.ranges + rel * 2;
344            crate::reader::be_u16_at(self.data, slot, TAG).unwrap_or(0)
345        };
346        (glyph != 0).then_some(glyph)
347    }
348
349    fn segment_for(&self, cp: u16) -> Option<usize> {
350        // Binary search: last segment with endCode >= cp.
351        let mut lo = 0;
352        let mut hi = self.seg_count;
353        while lo < hi {
354            let mid = (lo + hi) / 2;
355            let end = crate::reader::be_u16_at(self.data, self.ends + mid * 2, TAG).ok()?;
356            if end < cp {
357                lo = mid + 1;
358            } else {
359                hi = mid;
360            }
361        }
362        (lo < self.seg_count).then_some(lo)
363    }
364}
365
366/// Format 6 — trimmed table mapping: a contiguous firstCode window.
367#[derive(Debug, Clone, Copy, PartialEq, Eq)]
368pub struct Format6<'a> {
369    first_code: u16,
370    glyph_array: &'a [u8],
371}
372
373impl<'a> Format6<'a> {
374    fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
375        if data.len() < 10 {
376            return Err(ParseError::TruncatedTable {
377                tag: TAG,
378                expected: 10,
379                got: data.len(),
380            });
381        }
382        let first_code = crate::reader::be_u16_at(data, 6, TAG)?;
383        let entry_count = crate::reader::be_u16_at(data, 8, TAG)?;
384        let needed = 10 + usize::from(entry_count) * 2;
385        if data.len() < needed {
386            return Err(ParseError::TruncatedTable {
387                tag: TAG,
388                expected: needed,
389                got: data.len(),
390            });
391        }
392        Ok(Self {
393            first_code,
394            glyph_array: crate::reader::slice_at(data, 10, usize::from(entry_count) * 2, TAG)?,
395        })
396    }
397
398    fn lookup(&self, cp: u32) -> Option<u16> {
399        let cp = u16::try_from(cp).ok()?;
400        let idx = cp.checked_sub(self.first_code)?;
401        let idx = usize::from(idx);
402        if idx < self.glyph_array.len() / 2 {
403            crate::reader::be_u16_at(self.glyph_array, idx * 2, TAG).ok()
404        } else {
405            None
406        }
407    }
408}
409
410/// Format 12 — segmented coverage: sorted (start, end, startGlyphId) groups.
411#[derive(Debug, Clone, Copy, PartialEq, Eq)]
412pub struct Format12<'a> {
413    groups: &'a [u8],
414}
415
416impl<'a> Format12<'a> {
417    fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
418        if data.len() < 16 {
419            return Err(ParseError::TruncatedTable {
420                tag: TAG,
421                expected: 16,
422                got: data.len(),
423            });
424        }
425        let n_groups = crate::reader::be_u32_at(data, 12, TAG)?;
426        let n = usize::try_from(n_groups).map_err(|_| ParseError::InvalidGlyphFormat)?;
427        // Overflow guard first, then slice_at validates the group array
428        // against the buffer.
429        n.checked_mul(12)
430            .and_then(|v| v.checked_add(16))
431            .ok_or(ParseError::InvalidGlyphFormat)?;
432        Ok(Self {
433            groups: crate::reader::slice_at(data, 16, n * 12, TAG)?,
434        })
435    }
436
437    fn lookup(&self, cp: u32) -> Option<u16> {
438        // Binary search over sorted group starts: last group with
439        // startCharCode <= cp, then check the end.
440        let n = self.groups.len() / 12;
441        let mut lo = 0;
442        let mut hi = n;
443        while lo < hi {
444            let mid = (lo + hi) / 2;
445            let start = crate::reader::be_u32_at(self.groups, mid * 12, TAG).ok()?;
446            if start <= cp {
447                lo = mid + 1;
448            } else {
449                hi = mid;
450            }
451        }
452        if lo == 0 {
453            return None;
454        }
455        let g = lo - 1;
456        let start = crate::reader::be_u32_at(self.groups, g * 12, TAG).ok()?;
457        let end = crate::reader::be_u32_at(self.groups, g * 12 + 4, TAG).ok()?;
458        if cp < start || cp > end {
459            return None;
460        }
461        let start_gid = crate::reader::be_u32_at(self.groups, g * 12 + 8, TAG).ok()?;
462        let gid = start_gid.checked_add(cp - start)?;
463        u16::try_from(gid).ok()
464    }
465}
466
467#[cfg(test)]
468mod tests {
469    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
470    use super::{Cmap, CmapSubtable};
471    use crate::error::ParseError;
472
473    // Test harness: assertions legitimately panic; the lib target stays
474    // lint-clean.
475
476    use alloc::vec;
477    use alloc::vec::Vec;
478
479    /// A minimal format 4 subtable with three segments:
480    /// U+0041..U+0041 -> +2 (gid 67), U+0061..U+007A -> direct array,
481    /// U+FFFF terminator (notdef). Array layout per spec.
482    fn format4() -> Vec<u8> {
483        let seg_count = 3u16;
484        let mut d = Vec::new();
485        d.extend_from_slice(&4u16.to_be_bytes()); // format
486        d.extend_from_slice(&32u16.to_be_bytes()); // length: 14 + 3*2*4 + 2
487        d.extend_from_slice(&0u16.to_be_bytes()); // language
488        d.extend_from_slice(&(seg_count * 2).to_be_bytes()); // segCountX2
489        d.extend_from_slice(&4u16.to_be_bytes()); // searchRange
490        d.extend_from_slice(&1u16.to_be_bytes()); // entrySelector
491        d.extend_from_slice(&2u16.to_be_bytes()); // rangeShift
492                                                  // endCode[]
493        d.extend_from_slice(&0x0041u16.to_be_bytes());
494        d.extend_from_slice(&0x007Au16.to_be_bytes());
495        d.extend_from_slice(&0xFFFFu16.to_be_bytes());
496        d.extend_from_slice(&0u16.to_be_bytes()); // reservedPad
497                                                  // startCode[]
498        d.extend_from_slice(&0x0041u16.to_be_bytes());
499        d.extend_from_slice(&0x0061u16.to_be_bytes());
500        d.extend_from_slice(&0xFFFFu16.to_be_bytes());
501        // idDelta[]
502        d.extend_from_slice(&2u16.to_be_bytes()); // 0x41 + 2 = 0x43
503        d.extend_from_slice(&0u16.to_be_bytes()); // via array
504        d.extend_from_slice(&1u16.to_be_bytes()); // 0xFFFF + 1 = 0 -> notdef
505                                                  // idRangeOffset[]
506        d.extend_from_slice(&0u16.to_be_bytes());
507        // Segment 1 (a..z) points into glyphIndexArray: rel = ro/2 + (cp -
508        // start) + seg - segCount must land at array[cp - 0x61]; with the
509        // array starting 6 bytes past the ranges slot for seg 1, ro = 10.
510        d.extend_from_slice(&10u16.to_be_bytes());
511        d.extend_from_slice(&0u16.to_be_bytes());
512        // glyphIndexArray for segment 1: a..z -> gid 1 + (c - a)
513        d.extend_from_slice(&[0, 1, 0, 2, 0, 3]);
514        d
515    }
516
517    #[test]
518    fn format4_delta_and_array() {
519        let d = format4();
520        let sub = CmapSubtable::parse(&d).unwrap();
521        assert!(matches!(sub, CmapSubtable::Format4(_)));
522        assert_eq!(sub.lookup(0x41), Some(0x43)); // delta path
523        assert_eq!(sub.lookup(0x61), Some(1)); // array path
524        assert_eq!(sub.lookup(0x63), Some(3));
525        assert_eq!(sub.lookup(0x40), None); // before first segment
526        assert_eq!(sub.lookup(0x5A), None); // between segments (Z < a)
527        assert_eq!(sub.lookup(0x1_0000), None); // above BMP
528    }
529
530    fn format0() -> Vec<u8> {
531        let mut d = vec![0u8; 262];
532        d[0..2].copy_from_slice(&0u16.to_be_bytes());
533        d[6 + 65] = 7; // 'A' -> gid 7
534        d[6 + 0x7F] = 9;
535        d
536    }
537
538    #[test]
539    fn format0_lookup() {
540        let d = format0();
541        let sub = CmapSubtable::parse(&d).unwrap();
542        assert_eq!(sub.lookup(65), Some(7));
543        assert_eq!(sub.lookup(0x7F), Some(9));
544        assert_eq!(sub.lookup(66), Some(0));
545        assert_eq!(sub.lookup(256), None);
546        assert_eq!(sub.lookup(u32::MAX), None);
547    }
548
549    fn format6() -> Vec<u8> {
550        let mut d = Vec::new();
551        d.extend_from_slice(&6u16.to_be_bytes());
552        d.extend_from_slice(&16u16.to_be_bytes()); // length
553        d.extend_from_slice(&0u16.to_be_bytes());
554        d.extend_from_slice(&0x0300u16.to_be_bytes()); // firstCode
555        d.extend_from_slice(&3u16.to_be_bytes()); // entryCount
556        d.extend_from_slice(&10u16.to_be_bytes());
557        d.extend_from_slice(&11u16.to_be_bytes());
558        d.extend_from_slice(&12u16.to_be_bytes());
559        d
560    }
561
562    #[test]
563    fn format6_lookup() {
564        let d = format6();
565        let sub = CmapSubtable::parse(&d).unwrap();
566        assert_eq!(sub.lookup(0x300), Some(10));
567        assert_eq!(sub.lookup(0x302), Some(12));
568        assert_eq!(sub.lookup(0x2FF), None);
569        assert_eq!(sub.lookup(0x303), None);
570        assert_eq!(sub.lookup(0x10300), None);
571    }
572
573    fn format12() -> Vec<u8> {
574        let mut d = Vec::new();
575        d.extend_from_slice(&12u16.to_be_bytes());
576        d.extend_from_slice(&0u16.to_be_bytes()); // reserved
577        d.extend_from_slice(&28u32.to_be_bytes()); // length
578        d.extend_from_slice(&0u32.to_be_bytes()); // language
579        d.extend_from_slice(&2u32.to_be_bytes()); // nGroups
580        d.extend_from_slice(&0x1_0000u32.to_be_bytes()); // start
581        d.extend_from_slice(&0x1_00FFu32.to_be_bytes()); // end
582        d.extend_from_slice(&100u32.to_be_bytes()); // startGlyphId
583        d.extend_from_slice(&0x2_0000u32.to_be_bytes());
584        d.extend_from_slice(&0x2_0000u32.to_be_bytes());
585        d.extend_from_slice(&200u32.to_be_bytes());
586        d
587    }
588
589    #[test]
590    fn format12_groups() {
591        let d = format12();
592        let sub = CmapSubtable::parse(&d).unwrap();
593        assert_eq!(sub.lookup(0x1_0000), Some(100));
594        assert_eq!(sub.lookup(0x1_00FF), Some(100 + 0xFF));
595        assert_eq!(sub.lookup(0x2_0000), Some(200));
596        assert_eq!(sub.lookup(0xFFFF), None);
597        assert_eq!(sub.lookup(0x1_0100), None);
598        assert_eq!(sub.lookup(0x3_0000), None);
599    }
600
601    #[test]
602    fn unsupported_format() {
603        let mut d = vec![0u8; 32];
604        d[0..2].copy_from_slice(&14u16.to_be_bytes());
605        assert_eq!(
606            CmapSubtable::parse(&d),
607            Err(ParseError::InvalidCmapFormat(14))
608        );
609        // A format-0 subtable shorter than the 262-byte layout.
610        assert_eq!(
611            CmapSubtable::parse(&[0, 0]),
612            Err(ParseError::TruncatedTable {
613                tag: *b"cmap",
614                expected: 262,
615                got: 2
616            })
617        );
618        // One-byte table: truncation before the format field.
619        assert_eq!(
620            CmapSubtable::parse(&[0]),
621            Err(ParseError::TruncatedTable {
622                tag: *b"cmap",
623                expected: 2,
624                got: 1
625            })
626        );
627        // format 4 with odd segCountX2.
628        let mut d = format4();
629        d[6..8].copy_from_slice(&3u16.to_be_bytes());
630        assert_eq!(CmapSubtable::parse(&d), Err(ParseError::InvalidGlyphFormat));
631    }
632
633    #[test]
634    fn cmap_header_and_records() {
635        let sub = format4();
636        let mut d = Vec::new();
637        d.extend_from_slice(&0u16.to_be_bytes()); // version
638        d.extend_from_slice(&2u16.to_be_bytes()); // numTables
639                                                  // Record 0: (0, 3) Unicode BMP -> format 4 at offset 4 + 16 = 20.
640        d.extend_from_slice(&0u16.to_be_bytes());
641        d.extend_from_slice(&3u16.to_be_bytes());
642        d.extend_from_slice(&20u32.to_be_bytes());
643        // Record 1: (3, 1) -> same subtable.
644        d.extend_from_slice(&3u16.to_be_bytes());
645        d.extend_from_slice(&1u16.to_be_bytes());
646        d.extend_from_slice(&20u32.to_be_bytes());
647        let base = d.len();
648        d.extend_from_slice(&sub);
649        assert_eq!(base, 20);
650        let cmap = Cmap::parse(&d).unwrap();
651        let recs = cmap.records();
652        assert_eq!(recs.len(), 2);
653        assert_eq!(
654            recs[0],
655            super::EncodingRecord {
656                platform_id: 0,
657                encoding_id: 3,
658                offset: 20
659            }
660        );
661        assert!(recs[1].is_unicode());
662        assert_eq!(
663            cmap.codepoint('A').map(font_types::GlyphId::to_u32),
664            Some(0x43)
665        );
666        assert_eq!(
667            cmap.codepoint('a').map(font_types::GlyphId::to_u32),
668            Some(1)
669        );
670        assert_eq!(cmap.codepoint('\u{1F600}'), None);
671        let sub0 = cmap.subtable(0).unwrap();
672        assert!(matches!(sub0, CmapSubtable::Format4(_)));
673    }
674
675    #[test]
676    fn cmap_header_errors() {
677        assert_eq!(
678            Cmap::parse(&[0, 0, 0]),
679            Err(ParseError::TruncatedTable {
680                tag: *b"cmap",
681                expected: 4,
682                got: 3
683            })
684        );
685        // numTables beyond the buffer.
686        let mut d = vec![0u8; 12];
687        d[2..4].copy_from_slice(&2u16.to_be_bytes());
688        assert_eq!(
689            Cmap::parse(&d),
690            Err(ParseError::TruncatedTable {
691                tag: *b"cmap",
692                expected: 20,
693                got: 12
694            })
695        );
696        // Record offset past the table.
697        let mut d = vec![0u8; 20];
698        d[2..4].copy_from_slice(&1u16.to_be_bytes());
699        d[8..12].copy_from_slice(&500u32.to_be_bytes());
700        assert_eq!(Cmap::parse(&d), Err(ParseError::InvalidGlyphFormat));
701        // subtable out of range index.
702        let cmap = Cmap::parse(&d);
703        assert!(cmap.is_err() || cmap.unwrap().subtable(9).is_err());
704    }
705}