1use crate::error::{ParseError, RawTag};
10use crate::reader::{be_u16_at, be_u32_at, Reader};
11use alloc::vec::Vec;
12use font_types::F2Dot14;
13
14pub(crate) const TAG: RawTag = *b"gvar";
15
16const EMBEDDED_PEAK: u16 = 0x8000;
17const INTERMEDIATE_REGION: u16 = 0x4000;
18const PRIVATE_POINTS: u16 = 0x2000;
19const SHARED_POINTS: u16 = 0x8000;
20const LONG_OFFSETS: u16 = 0x0001;
21
22const DELTAS_SIZE_MASK: u8 = 0xC0;
23const DELTAS_ONE_BYTE: u8 = 0x00;
24const DELTAS_ARE_WORDS: u8 = 0x40;
25const DELTAS_ARE_ZERO: u8 = 0x80;
26const DELTAS_ARE_LONGS: u8 = 0xC0;
27const DELTA_RUN_COUNT_MASK: u8 = 0x3F;
28
29const POINTS_ARE_WORDS: u8 = 0x80;
30const POINT_RUN_COUNT_MASK: u8 = 0x7F;
31
32#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct TupleVariation {
38 pub peak: Vec<F2Dot14>,
40 pub shared_peak_index: u16,
42 pub start: Option<Vec<F2Dot14>>,
44 pub end: Option<Vec<F2Dot14>>,
46 pub point_numbers: Option<Vec<u16>>,
48 pub x_deltas: Vec<i32>,
50 pub y_deltas: Vec<i32>,
52}
53
54impl TupleVariation {
55 #[must_use]
57 pub const fn has_private_points(&self) -> bool {
58 self.point_numbers.is_some()
59 }
60}
61
62#[derive(Debug, Clone, Copy)]
64pub struct GvarTable<'a> {
65 data: &'a [u8],
66 axis_count: u16,
67 glyph_count: u16,
68 long_offsets: bool,
69 glyph_data_array_offset: u32,
70 offsets_array_at: usize,
71 shared_tuples_offset: u32,
72 shared_tuple_count: u16,
73}
74
75impl<'a> GvarTable<'a> {
76 pub fn parse(data: &'a [u8], glyph_count: u16) -> Result<Self, ParseError> {
84 if data.len() < 20 {
85 return Err(ParseError::TruncatedTable {
86 tag: TAG,
87 expected: 20,
88 got: data.len(),
89 });
90 }
91 let axis_count = be_u16_at(data, 4, TAG)?;
92 let shared_tuple_count = be_u16_at(data, 6, TAG)?;
93 let shared_tuples_offset = be_u32_at(data, 8, TAG)?;
94 let glyph_data_array_offset = be_u32_at(data, 16, TAG)?;
95 let flags = be_u16_at(data, 14, TAG)?;
96 let long_offsets = flags & LONG_OFFSETS != 0;
97 if axis_count == 0 {
98 return Err(ParseError::InvalidGlyphFormat);
99 }
100 let offsets_array_at = 20usize;
101 let offsets_len = (usize::from(glyph_count) + 1)
102 .checked_mul(if long_offsets { 4 } else { 2 })
103 .ok_or(ParseError::InvalidGlyphFormat)?;
104 let needed = offsets_array_at
105 .checked_add(offsets_len)
106 .ok_or(ParseError::InvalidGlyphFormat)?;
107 if data.len() < needed {
108 return Err(ParseError::TruncatedTable {
109 tag: TAG,
110 expected: needed,
111 got: data.len(),
112 });
113 }
114 Ok(Self {
115 data,
116 axis_count,
117 glyph_count,
118 long_offsets,
119 glyph_data_array_offset,
120 offsets_array_at,
121 shared_tuples_offset,
122 shared_tuple_count,
123 })
124 }
125
126 fn glyph_offset(&self, i: u16) -> Result<usize, ParseError> {
130 if self.long_offsets {
131 let v = be_u32_at(self.data, self.offsets_array_at + usize::from(i) * 4, TAG)?;
132 usize::try_from(v).map_err(|_| ParseError::InvalidGlyphFormat)
133 } else {
134 let v = be_u16_at(self.data, self.offsets_array_at + usize::from(i) * 2, TAG)?;
135 usize::from(v)
136 .checked_mul(2)
137 .ok_or(ParseError::InvalidGlyphFormat)
138 }
139 }
140
141 #[must_use]
143 pub fn as_bytes(&self) -> &'a [u8] {
144 self.data
145 }
146
147 #[must_use]
149 pub const fn axis_count(&self) -> u16 {
150 self.axis_count
151 }
152
153 pub fn shared_tuples(&self) -> Result<Vec<Vec<F2Dot14>>, ParseError> {
158 let mut out = Vec::with_capacity(usize::from(self.shared_tuple_count));
159 let mut r = Reader::within(
160 self.data,
161 usize::try_from(self.shared_tuples_offset)
162 .map_err(|_| ParseError::InvalidGlyphFormat)?,
163 self.data.len(),
164 TAG,
165 );
166 for _ in 0..self.shared_tuple_count {
167 let mut tuple = Vec::with_capacity(usize::from(self.axis_count));
168 for _ in 0..self.axis_count {
169 tuple.push(F2Dot14::from_bits(r.i16()?));
170 }
171 out.push(tuple);
172 }
173 Ok(out)
174 }
175
176 fn glyph_data_range(&self, gid: u16) -> Result<Option<core::ops::Range<usize>>, ParseError> {
179 if gid >= self.glyph_count {
180 return Ok(None);
181 }
182 let base = usize::try_from(self.glyph_data_array_offset)
183 .map_err(|_| ParseError::InvalidGlyphFormat)?;
184 let next = gid.checked_add(1).ok_or(ParseError::InvalidGlyphFormat)?;
185 let start = base
186 .checked_add(self.glyph_offset(gid)?)
187 .ok_or(ParseError::InvalidGlyphFormat)?;
188 let end = base
189 .checked_add(self.glyph_offset(next)?)
190 .ok_or(ParseError::InvalidGlyphFormat)?;
191 if end >= start && end <= self.data.len() {
192 if start == end {
193 Ok(None)
194 } else {
195 Ok(Some(start..end))
196 }
197 } else {
198 Err(ParseError::InvalidGlyphFormat)
199 }
200 }
201
202 pub fn glyph_deltas(
213 &self,
214 gid: u16,
215 point_count: u16,
216 ) -> Result<Vec<TupleVariation>, ParseError> {
217 let mut tuples = Vec::new();
218 let Some(range) = self.glyph_data_range(gid)? else {
219 return Ok(tuples);
220 };
221 let data = crate::reader::slice_at(self.data, range.start, range.end - range.start, TAG)?;
222 if data.len() < 4 {
223 return Err(ParseError::InvalidGlyphFormat);
224 }
225 let tuple_var_count = be_u16_at(data, 0, TAG)?;
226 let count = usize::from(tuple_var_count & 0x0FFF);
227 let has_shared_points = tuple_var_count & SHARED_POINTS != 0;
228 let data_offset = usize::from(be_u16_at(data, 2, TAG)?);
229 if data_offset > data.len() {
230 return Err(ParseError::InvalidGlyphFormat);
231 }
232 let mut hr = Reader::within(data, 4, data_offset, TAG);
234 let mut sr_pos = data_offset;
235 let mut shared_points: Option<Vec<u16>> = None;
237 if has_shared_points {
238 let mut pr = Reader::within(data, sr_pos, data.len(), TAG);
239 let pts = read_packed_points(&mut pr, usize::from(point_count))?;
240 sr_pos = sr_pos.saturating_add(pr.pos());
241 shared_points = Some(pts);
242 }
243 let shared_tuples = self.shared_tuples()?;
244 for _ in 0..count {
245 let variation_data_size = usize::from(hr.u16()?);
247 let tuple_index = hr.u16()?;
248 let axis = usize::from(self.axis_count);
249 let (peak, shared_peak_index) = if tuple_index & EMBEDDED_PEAK != 0 {
250 let mut peak = Vec::with_capacity(axis);
251 for _ in 0..axis {
252 peak.push(F2Dot14::from_bits(hr.i16()?));
253 }
254 (peak, u16::MAX)
255 } else {
256 let idx = tuple_index & 0x0FFF;
257 let peak = shared_tuples
258 .get(usize::from(idx))
259 .cloned()
260 .unwrap_or_default();
261 (peak, idx)
262 };
263 let (start, end) = if tuple_index & INTERMEDIATE_REGION != 0 {
264 let mut s = Vec::with_capacity(axis);
265 for _ in 0..axis {
266 s.push(F2Dot14::from_bits(hr.i16()?));
267 }
268 let mut e = Vec::with_capacity(axis);
269 for _ in 0..axis {
270 e.push(F2Dot14::from_bits(hr.i16()?));
271 }
272 (Some(s), Some(e))
273 } else {
274 (None, None)
275 };
276 let window = crate::reader::slice_at(data, sr_pos, variation_data_size, TAG)?;
278 sr_pos += variation_data_size;
279 let mut tr = Reader::new(window, TAG);
280 let point_numbers = if tuple_index & PRIVATE_POINTS != 0 {
282 Some(read_packed_points(&mut tr, usize::from(point_count))?)
283 } else {
284 shared_points.clone()
285 };
286 let n = point_numbers
287 .as_ref()
288 .map_or(usize::from(point_count), Vec::len);
289 let x = read_packed_deltas(&mut tr, n)?;
290 let y = read_packed_deltas(&mut tr, n)?;
291 tuples.push(TupleVariation {
292 peak,
293 shared_peak_index,
294 start,
295 end,
296 point_numbers,
297 x_deltas: x,
298 y_deltas: y,
299 });
300 }
301 Ok(tuples)
302 }
303}
304
305fn read_packed_points(r: &mut Reader<'_>, outline_points: usize) -> Result<Vec<u16>, ParseError> {
308 let first = r.u8()?;
309 if first == 0 {
310 let n = outline_points.min(usize::from(u16::MAX));
311 return (0..n)
312 .map(u16::try_from)
313 .collect::<Result<Vec<u16>, _>>()
314 .map_err(|_| ParseError::InvalidGlyphFormat);
315 }
316 let count = if first & POINTS_ARE_WORDS != 0 {
317 let hi = usize::from(first & POINT_RUN_COUNT_MASK);
318 (hi << 8 | usize::from(r.u8()?)) + 1
319 } else {
320 usize::from(first) + 1
321 };
322 if count > outline_points {
323 return Err(ParseError::InvalidGlyphFormat);
324 }
325 let mut pts = Vec::with_capacity(count);
326 let mut cur: u32 = 0;
327 while pts.len() < count {
328 let control = r.u8()?;
329 let run_len = usize::from(control & POINT_RUN_COUNT_MASK) + 1;
330 for _ in 0..run_len {
331 if pts.len() >= count {
332 return Err(ParseError::InvalidGlyphFormat);
333 }
334 let inc = if control & POINTS_ARE_WORDS != 0 {
335 u32::from(r.u16()?)
336 } else {
337 u32::from(r.u8()?)
338 };
339 cur = cur.saturating_add(inc);
340 let idx = u16::try_from(cur).map_err(|_| ParseError::InvalidGlyphFormat)?;
341 pts.push(idx);
342 }
343 }
344 Ok(pts)
345}
346
347fn read_packed_deltas(r: &mut Reader<'_>, count: usize) -> Result<Vec<i32>, ParseError> {
350 let mut out = Vec::with_capacity(count);
351 while out.len() < count {
352 let control = r.u8()?;
353 let run_len = usize::from(control & DELTA_RUN_COUNT_MASK) + 1;
354 for _ in 0..run_len {
355 if out.len() >= count {
356 return Err(ParseError::InvalidGlyphFormat);
357 }
358 match control & DELTAS_SIZE_MASK {
359 DELTAS_ONE_BYTE => out.push(i32::from(r.i8()?)),
360 DELTAS_ARE_WORDS => out.push(i32::from(r.i16()?)),
361 DELTAS_ARE_ZERO => out.push(0),
362 DELTAS_ARE_LONGS => out.push(r.i32()?),
363 _ => return Err(ParseError::InvalidGlyphFormat),
364 }
365 }
366 }
367 Ok(out)
368}
369
370#[cfg(test)]
371mod tests {
372 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
373
374 use super::{GvarTable, TupleVariation};
375 use crate::error::ParseError;
376 use alloc::vec;
377 use alloc::vec::Vec;
378 use font_types::F2Dot14;
379
380 fn gvar() -> Vec<u8> {
386 let ser0: [u8; 9] = [
389 0x00, 0x01, 50, 50, 0x83, 0x01, 5, 5, 0x83, ];
395 let gid0: [u8; 17] = [
396 0x80, 0x01, 0x00, 0x08, 0x00, 0x09, 0x00, 0x00, ser0[0], ser0[1], ser0[2], ser0[3], ser0[4], ser0[5], ser0[6], ser0[7], ser0[8],
401 ];
402 let ser2: [u8; 9] = [
405 0x01, 0x00, 0x00, 0x00, 0x03, 0x01, 10, 20, 0x81, ];
411 let mut gid2: Vec<u8> = Vec::new();
412 gid2.extend_from_slice(&0x0001u16.to_be_bytes()); gid2.extend_from_slice(&14u16.to_be_bytes());
416 gid2.extend_from_slice(&(ser2.len() as u16).to_be_bytes()); gid2.extend_from_slice(&0xE000u16.to_be_bytes()); gid2.extend_from_slice(&0x2000i16.to_be_bytes()); gid2.extend_from_slice(&0x1000i16.to_be_bytes()); gid2.extend_from_slice(&0x3000i16.to_be_bytes()); gid2.extend_from_slice(&ser2);
422 debug_assert_eq!(gid2.len(), 14 + ser2.len());
423 if gid2.len() % 2 != 0 {
424 gid2.push(0);
425 }
426 let mut d = Vec::new();
429 d.extend_from_slice(&0x0001_0000u32.to_be_bytes()); d.extend_from_slice(&1u16.to_be_bytes()); d.extend_from_slice(&1u16.to_be_bytes()); d.extend_from_slice(&28u32.to_be_bytes()); d.extend_from_slice(&3u16.to_be_bytes()); d.extend_from_slice(&0u16.to_be_bytes()); d.extend_from_slice(&32u32.to_be_bytes()); let end = (17 + 1 + gid2.len()) as u16; for v in [0u16, 9, 9, end / 2] {
439 d.extend_from_slice(&v.to_be_bytes());
440 }
441 d.extend_from_slice(&0x4000i16.to_be_bytes());
443 d.extend_from_slice(&[0u8; 2]);
444 d.extend_from_slice(&gid0);
445 if d.len() % 2 != 0 {
446 d.push(0); }
448 d.extend_from_slice(&gid2);
449 if d.len() % 2 != 0 {
450 d.push(0);
451 }
452 d
453 }
454
455 #[test]
456 fn header_offsets_and_shared_tuples() {
457 let d = gvar();
458 let t = GvarTable::parse(&d, 3).unwrap();
459 assert_eq!(t.axis_count(), 1);
460 let shared = t.shared_tuples().unwrap();
461 assert_eq!(shared.len(), 1);
462 assert_eq!(shared[0][0].to_bits(), 0x4000);
463 }
464
465 #[test]
466 fn shared_points_tuple() {
467 let d = gvar();
468 let t = GvarTable::parse(&d, 3).unwrap();
469 let tuples: Vec<TupleVariation> = t.glyph_deltas(0, 6).unwrap();
470 assert_eq!(tuples.len(), 1);
471 let t0 = &tuples[0];
472 assert_eq!(
474 t0.point_numbers.as_deref(),
475 Some(&[0u16, 1, 2, 3, 4, 5][..])
476 );
477 assert_eq!(t0.x_deltas, vec![50, 50, 0, 0, 0, 0]);
478 assert_eq!(t0.y_deltas, vec![5, 5, 0, 0, 0, 0]);
479 assert_eq!(t0.shared_peak_index, 0);
481 assert_eq!(t0.peak, vec![F2Dot14::from_bits(0x4000)]);
482 assert!(t0.start.is_none());
483 assert!(t.glyph_deltas(1, 6).unwrap().is_empty());
485 }
486
487 #[test]
488 fn private_points_embedded_peak_intermediate() {
489 let d = gvar();
490 let t = GvarTable::parse(&d, 3).unwrap();
491 let tuples = t.glyph_deltas(2, 6).unwrap();
492 assert_eq!(tuples.len(), 1);
493 let t2 = &tuples[0];
494 assert!(t2.has_private_points());
495 assert_eq!(t2.point_numbers, Some(vec![0, 3]));
496 assert_eq!(t2.x_deltas, vec![10, 20]);
497 assert_eq!(t2.y_deltas, vec![0, 0]);
498 assert_eq!(t2.shared_peak_index, u16::MAX);
499 assert_eq!(t2.peak, vec![F2Dot14::from_bits(0x2000)]);
500 assert_eq!(t2.start.as_ref().map(|s| s[0].to_bits()), Some(0x1000));
501 assert_eq!(t2.end.as_ref().map(|s| s[0].to_bits()), Some(0x3000));
502 }
503
504 #[test]
505 fn errors() {
506 assert!(matches!(
508 GvarTable::parse(&[0u8; 19], 3),
509 Err(ParseError::TruncatedTable { .. })
510 ));
511 let mut d = gvar();
513 d[4..6].copy_from_slice(&0u16.to_be_bytes());
514 assert_eq!(
515 GvarTable::parse(&d, 3).unwrap_err(),
516 ParseError::InvalidGlyphFormat
517 );
518 let d = gvar();
520 assert!(matches!(
521 GvarTable::parse(&d, 200),
522 Err(ParseError::TruncatedTable { .. })
523 ));
524 let d = gvar();
526 let t = GvarTable::parse(&d, 3).unwrap();
527 assert!(t.glyph_deltas(9, 6).unwrap().is_empty());
528 let mut d = gvar();
531 let n = d.len();
532 d.truncate(n - 5);
533 let t = GvarTable::parse(&d, 3).unwrap();
534 assert_eq!(
535 t.glyph_deltas(2, 6).unwrap_err(),
536 ParseError::InvalidGlyphFormat
537 );
538 }
539}