1use core::convert::TryFrom;
2
3use crate::parser::{LazyArray16, Stream};
4use crate::GlyphId;
5
6/// A [format 4](https://docs.microsoft.com/en-us/typography/opentype/spec/cmap#format-4-segment-mapping-to-delta-values)
7/// subtable.
8#[derive(Clone, Copy)]
9pub struct Subtable4<'a> {
10 start_codes: LazyArray16<'a, u16>,
11 end_codes: LazyArray16<'a, u16>,
12 id_deltas: LazyArray16<'a, i16>,
13 id_range_offsets: LazyArray16<'a, u16>,
14 id_range_offset_pos: usize,
15 // The whole subtable data.
16 data: &'a [u8],
17}
18
19impl<'a> Subtable4<'a> {
20 /// Parses a subtable from raw data.
21 pub fn parse(data: &'a [u8]) -> Option<Self> {
22 let mut s = Stream::new(data);
23 s.advance(6); // format + length + language
24 let seg_count_x2 = s.read::<u16>()?;
25 if seg_count_x2 < 2 {
26 return None;
27 }
28
29 let seg_count = seg_count_x2 / 2;
30 s.advance(6); // searchRange + entrySelector + rangeShift
31
32 let end_codes = s.read_array16::<u16>(seg_count)?;
33 s.skip::<u16>(); // reservedPad
34 let start_codes = s.read_array16::<u16>(seg_count)?;
35 let id_deltas = s.read_array16::<i16>(seg_count)?;
36 let id_range_offset_pos = s.offset();
37 let id_range_offsets = s.read_array16::<u16>(seg_count)?;
38
39 Some(Self {
40 start_codes,
41 end_codes,
42 id_deltas,
43 id_range_offsets,
44 id_range_offset_pos,
45 data,
46 })
47 }
48
49 /// Returns a glyph index for a code point.
50 ///
51 /// Returns `None` when `code_point` is larger than `u16`.
52 pub fn glyph_index(&self, code_point: u32) -> Option<GlyphId> {
53 // This subtable supports code points only in a u16 range.
54 let code_point = u16::try_from(code_point).ok()?;
55
56 // A custom binary search.
57 let mut start = 0;
58 let mut end = self.start_codes.len();
59 while end > start {
60 let index = (start + end) / 2;
61 let end_value = self.end_codes.get(index)?;
62 if end_value >= code_point {
63 let start_value = self.start_codes.get(index)?;
64 if start_value > code_point {
65 end = index;
66 } else {
67 let id_range_offset = self.id_range_offsets.get(index)?;
68 let id_delta = self.id_deltas.get(index)?;
69 if id_range_offset == 0 {
70 return Some(GlyphId(code_point.wrapping_add(id_delta as u16)));
71 } else if id_range_offset == 0xFFFF {
72 // Some malformed fonts have 0xFFFF as the last offset,
73 // which is invalid and should be ignored.
74 return None;
75 }
76
77 let delta = (u32::from(code_point) - u32::from(start_value)) * 2;
78 let delta = u16::try_from(delta).ok()?;
79
80 let id_range_offset_pos =
81 (self.id_range_offset_pos + usize::from(index) * 2) as u16;
82 let pos = id_range_offset_pos.wrapping_add(delta);
83 let pos = pos.wrapping_add(id_range_offset);
84
85 let glyph_array_value: u16 = Stream::read_at(self.data, usize::from(pos))?;
86
87 // 0 indicates missing glyph.
88 if glyph_array_value == 0 {
89 return None;
90 }
91
92 let glyph_id = (glyph_array_value as i16).wrapping_add(id_delta);
93 return u16::try_from(glyph_id).ok().map(GlyphId);
94 }
95 } else {
96 start = index + 1;
97 }
98 }
99
100 None
101 }
102
103 /// Calls `f` for each codepoint defined in this table.
104 pub fn codepoints(&self, mut f: impl FnMut(u32)) {
105 for (start, end) in self.start_codes.into_iter().zip(self.end_codes) {
106 // OxFFFF value is special and indicates codes end.
107 if start == end && start == 0xFFFF {
108 break;
109 }
110
111 for code_point in start..=end {
112 f(u32::from(code_point));
113 }
114 }
115 }
116}
117
118impl core::fmt::Debug for Subtable4<'_> {
119 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
120 write!(f, "Subtable4 {{ ... }}")
121 }
122}
123