ttf_parser/tables/cmap/
format6.rs

1use core::convert::TryFrom;
2
3use crate::parser::{LazyArray16, Stream};
4use crate::GlyphId;
5
6/// A [format 6](https://docs.microsoft.com/en-us/typography/opentype/spec/cmap#format-6-trimmed-table-mapping)
7/// subtable.
8#[derive(Clone, Copy, Debug)]
9pub struct Subtable6<'a> {
10    /// First character code of subrange.
11    pub first_code_point: u16,
12    /// Array of glyph indexes for character codes in the range.
13    pub glyphs: LazyArray16<'a, GlyphId>,
14}
15
16impl<'a> Subtable6<'a> {
17    /// Parses a subtable from raw data.
18    pub fn parse(data: &'a [u8]) -> Option<Self> {
19        let mut s = Stream::new(data);
20        s.skip::<u16>(); // format
21        s.skip::<u16>(); // length
22        s.skip::<u16>(); // language
23        let first_code_point = s.read::<u16>()?;
24        let count = s.read::<u16>()?;
25        let glyphs = s.read_array16::<GlyphId>(count)?;
26        Some(Self {
27            first_code_point,
28            glyphs,
29        })
30    }
31
32    /// Returns a glyph index for a code point.
33    ///
34    /// Returns `None` when `code_point` is larger than `u16`.
35    pub fn glyph_index(&self, code_point: u32) -> Option<GlyphId> {
36        // This subtable supports code points only in a u16 range.
37        let code_point = u16::try_from(code_point).ok()?;
38        let idx = code_point.checked_sub(self.first_code_point)?;
39        self.glyphs.get(idx)
40    }
41
42    /// Calls `f` for each codepoint defined in this table.
43    pub fn codepoints(&self, mut f: impl FnMut(u32)) {
44        for i in 0..self.glyphs.len() {
45            if let Some(code_point) = self.first_code_point.checked_add(i) {
46                f(u32::from(code_point));
47            }
48        }
49    }
50}