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 { first_code_point, glyphs })
27    }
28
29    /// Returns a glyph index for a code point.
30    ///
31    /// Returns `None` when `code_point` is larger than `u16`.
32    pub fn glyph_index(&self, code_point: u32) -> Option<GlyphId> {
33        // This subtable supports code points only in a u16 range.
34        let code_point = u16::try_from(code_point).ok()?;
35        let idx = code_point.checked_sub(self.first_code_point)?;
36        self.glyphs.get(idx)
37    }
38
39    /// Calls `f` for each codepoint defined in this table.
40    pub fn codepoints(&self, mut f: impl FnMut(u32)) {
41        for i in 0..self.glyphs.len() {
42            if let Some(code_point) = self.first_code_point.checked_add(i) {
43                f(u32::from(code_point));
44            }
45        }
46    }
47}