1use crate::error::{ParseError, RawTag};
4use crate::reader::Reader;
5use alloc::vec::Vec;
6use font_types::{F2Dot14, GlyphId};
7
8pub(crate) const TAG: RawTag = *b"glyf";
9
10pub(crate) const FLAG_ON_CURVE: u8 = 0x01;
12pub(crate) const FLAG_X_SHORT: u8 = 0x02;
14pub(crate) const FLAG_Y_SHORT: u8 = 0x04;
16pub(crate) const FLAG_REPEAT: u8 = 0x08;
18pub(crate) const FLAG_X_SAME_OR_POS: u8 = 0x10;
20pub(crate) const FLAG_Y_SAME_OR_POS: u8 = 0x20;
22#[cfg(feature = "woff2")]
24pub(crate) const FLAG_OVERLAP_SIMPLE: u8 = 0x40;
25
26pub(crate) const ARG_1_AND_2_ARE_WORDS: u16 = 0x0001;
28pub(crate) const ARGS_ARE_XY_VALUES: u16 = 0x0002;
30pub(crate) const MORE_COMPONENTS: u16 = 0x0020;
32pub(crate) const WE_HAVE_A_SCALE: u16 = 0x0008;
34pub(crate) const WE_HAVE_AN_X_AND_Y_SCALE: u16 = 0x0040;
36pub(crate) const WE_HAVE_A_TWO_BY_TWO: u16 = 0x0080;
38#[cfg(feature = "woff2")]
40pub(crate) const WE_HAVE_INSTRUCTIONS: u16 = 0x0100;
41
42pub(crate) const MAX_COMPONENT_DEPTH: u8 = 16;
45pub(crate) const MAX_OUTLINE_POINTS: usize = 1 << 20;
48
49#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct OutlinePoint {
52 pub x: f32,
54 pub y: f32,
56 pub on_curve: bool,
58}
59
60#[derive(Debug, Clone, PartialEq)]
62pub struct Contour {
63 pub points: Vec<OutlinePoint>,
65}
66
67#[derive(Debug, Clone, PartialEq, Default)]
71pub struct GlyphOutline {
72 pub contours: Vec<Contour>,
74}
75
76impl GlyphOutline {
77 #[must_use]
79 pub fn point_count(&self) -> usize {
80 self.contours.iter().map(|c| c.points.len()).sum()
81 }
82
83 #[must_use]
85 pub fn is_empty(&self) -> bool {
86 self.contours.is_empty()
87 }
88}
89
90#[derive(Debug, Clone, Copy)]
92pub enum GlyphRef<'a> {
93 Simple(SimpleGlyph<'a>),
95 Composite(CompositeGlyph<'a>),
97}
98
99impl<'a> GlyphRef<'a> {
100 pub fn parse(data: &'a [u8]) -> Result<Option<Self>, ParseError> {
108 if data.is_empty() {
109 return Ok(None);
110 }
111 if data.len() < 10 {
112 return Err(ParseError::TruncatedTable {
113 tag: TAG,
114 expected: 10,
115 got: data.len(),
116 });
117 }
118 let n_contours = crate::reader::be_i16_at(data, 0, TAG)?;
119 if n_contours >= 0 {
120 Ok(Some(Self::Simple(SimpleGlyph::parse(data)?)))
121 } else if n_contours == -1 {
122 Ok(Some(Self::Composite(CompositeGlyph::parse(data)?)))
123 } else {
124 Err(ParseError::InvalidGlyphFormat)
125 }
126 }
127
128 pub fn bounds(&self) -> Result<[i16; 4], ParseError> {
133 match self {
134 Self::Simple(g) => g.bounds(),
135 Self::Composite(g) => g.bounds(),
136 }
137 }
138}
139
140#[derive(Debug, Clone, Copy)]
142pub struct SimpleGlyph<'a> {
143 data: &'a [u8],
144 n_contours: u16,
145}
146
147impl<'a> SimpleGlyph<'a> {
148 fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
149 let n = crate::reader::be_u16_at(data, 0, TAG)?;
150 Ok(Self {
151 data,
152 n_contours: n,
153 })
154 }
155
156 #[must_use]
158 pub fn as_bytes(&self) -> &'a [u8] {
159 self.data
160 }
161
162 #[must_use]
164 pub const fn num_contours(&self) -> u16 {
165 self.n_contours
166 }
167
168 pub fn bounds(&self) -> Result<[i16; 4], ParseError> {
173 Ok([
174 crate::reader::be_i16_at(self.data, 2, TAG)?,
175 crate::reader::be_i16_at(self.data, 4, TAG)?,
176 crate::reader::be_i16_at(self.data, 6, TAG)?,
177 crate::reader::be_i16_at(self.data, 8, TAG)?,
178 ])
179 }
180
181 pub fn end_points(&self) -> Result<Vec<u16>, ParseError> {
186 let n = usize::from(self.n_contours);
187 let at = 10usize;
188 let end = at
189 .checked_add(n * 2)
190 .ok_or(ParseError::InvalidGlyphFormat)?;
191 if self.data.len() < end {
192 return Err(ParseError::TruncatedTable {
193 tag: TAG,
194 expected: end,
195 got: self.data.len(),
196 });
197 }
198 let mut out = Vec::with_capacity(n);
199 for i in 0..n {
200 out.push(crate::reader::be_u16_at(self.data, at + i * 2, TAG)?);
201 }
202 Ok(out)
203 }
204
205 pub fn points(&self) -> Result<Vec<OutlinePoint>, ParseError> {
211 let mut r = Reader::new(self.data, TAG);
212 r.skip(10)?;
213 let ends = self.end_points()?;
214 let n_points = ends.last().map_or(0, |&e| usize::from(e) + 1);
215 r.skip(ends.len() * 2)?;
216 let instr_len = usize::from(r.u16()?);
218 r.skip(instr_len)?;
219 let mut flags = Vec::with_capacity(n_points);
221 while flags.len() < n_points {
222 let flag = r.u8()?;
223 flags.push(flag);
224 if flag & FLAG_REPEAT != 0 {
225 let repeat = usize::from(r.u8()?);
226 for _ in 0..repeat {
227 if flags.len() >= n_points {
228 return Err(ParseError::InvalidGlyphFormat);
229 }
230 flags.push(flag);
231 }
232 }
233 }
234 let mut xs = Vec::with_capacity(n_points);
236 let mut x: i32 = 0;
237 for &flag in &flags {
238 if flag & FLAG_X_SHORT != 0 {
239 let d = i32::from(r.u8()?);
240 x += if flag & FLAG_X_SAME_OR_POS != 0 {
241 d
242 } else {
243 -d
244 };
245 } else if flag & FLAG_X_SAME_OR_POS == 0 {
246 x += i32::from(r.i16()?);
247 }
248 xs.push(x);
249 }
250 let mut pts = Vec::with_capacity(n_points);
252 let mut y: i32 = 0;
253 for (i, &flag) in flags.iter().enumerate() {
254 if flag & FLAG_Y_SHORT != 0 {
255 let d = i32::from(r.u8()?);
256 y += if flag & FLAG_Y_SAME_OR_POS != 0 {
257 d
258 } else {
259 -d
260 };
261 } else if flag & FLAG_Y_SAME_OR_POS == 0 {
262 y += i32::from(r.i16()?);
263 }
264 if i >= MAX_OUTLINE_POINTS {
265 return Err(ParseError::InvalidGlyphFormat);
266 }
267 let x = *xs.get(i).unwrap_or(&0);
268 pts.push(OutlinePoint {
269 x: x as f32,
270 y: y as f32,
271 on_curve: flag & FLAG_ON_CURVE != 0,
272 });
273 }
274 Ok(pts)
275 }
276
277 pub fn outline(&self) -> Result<GlyphOutline, ParseError> {
282 let pts = self.points()?;
283 let ends = self.end_points()?;
284 let mut contours = Vec::with_capacity(ends.len());
285 let mut start = 0usize;
286 for &e in &ends {
287 let end = usize::from(e) + 1;
288 if end > pts.len() || start > end {
289 return Err(ParseError::InvalidGlyphFormat);
290 }
291 let slice = pts.get(start..end).ok_or(ParseError::InvalidGlyphFormat)?;
292 contours.push(Contour {
293 points: slice.to_vec(),
294 });
295 start = end;
296 }
297 Ok(GlyphOutline { contours })
298 }
299}
300
301#[derive(Debug, Clone, Copy, PartialEq)]
303pub struct Component {
304 pub glyph: GlyphId,
306 pub flags: u16,
308 pub args: (i32, i32),
311 pub transform: [f32; 4],
313}
314
315impl Component {
316 #[must_use]
318 pub const fn args_are_offsets(&self) -> bool {
319 self.flags & ARGS_ARE_XY_VALUES != 0
320 }
321}
322
323#[derive(Debug, Clone, Copy)]
325pub struct CompositeGlyph<'a> {
326 data: &'a [u8],
327}
328
329impl<'a> CompositeGlyph<'a> {
330 fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
331 Ok(Self { data })
332 }
333
334 #[must_use]
336 pub fn as_bytes(&self) -> &'a [u8] {
337 self.data
338 }
339
340 pub fn bounds(&self) -> Result<[i16; 4], ParseError> {
345 Ok([
346 crate::reader::be_i16_at(self.data, 2, TAG)?,
347 crate::reader::be_i16_at(self.data, 4, TAG)?,
348 crate::reader::be_i16_at(self.data, 6, TAG)?,
349 crate::reader::be_i16_at(self.data, 8, TAG)?,
350 ])
351 }
352
353 pub fn components(&self) -> Result<Vec<Component>, ParseError> {
359 let mut r = Reader::new(self.data, TAG);
360 r.skip(10)?;
361 let mut out = Vec::new();
362 loop {
363 if out.len() > MAX_OUTLINE_POINTS {
364 return Err(ParseError::InvalidGlyphFormat);
365 }
366 let flags = r.u16()?;
367 let glyph = GlyphId::new(u32::from(r.u16()?));
368 let (a1, a2) = if flags & ARG_1_AND_2_ARE_WORDS != 0 {
369 (i32::from(r.i16()?), i32::from(r.i16()?))
370 } else {
371 (i32::from(r.i8()?), i32::from(r.i8()?))
372 };
373 let scale = |r: &mut Reader<'a>| -> Result<F2Dot14, ParseError> { r.f2dot14() };
374 let transform = if flags & WE_HAVE_A_SCALE != 0 {
375 let a = scale(&mut r)?;
376 [a.to_f32(), 0.0, 0.0, a.to_f32()]
377 } else if flags & WE_HAVE_AN_X_AND_Y_SCALE != 0 {
378 let a = scale(&mut r)?;
379 let d = scale(&mut r)?;
380 [a.to_f32(), 0.0, 0.0, d.to_f32()]
381 } else if flags & WE_HAVE_A_TWO_BY_TWO != 0 {
382 let a = scale(&mut r)?;
383 let b = scale(&mut r)?;
384 let c = scale(&mut r)?;
385 let d = scale(&mut r)?;
386 [a.to_f32(), b.to_f32(), c.to_f32(), d.to_f32()]
387 } else {
388 [1.0, 0.0, 0.0, 1.0]
389 };
390 out.push(Component {
391 glyph,
392 flags,
393 args: (a1, a2),
394 transform,
395 });
396 if flags & MORE_COMPONENTS == 0 {
397 break;
398 }
399 }
400 Ok(out)
401 }
402}
403
404#[cfg(test)]
405mod tests {
406 #![allow(
407 clippy::unwrap_used,
408 clippy::expect_used,
409 clippy::indexing_slicing,
410 clippy::panic
411 )]
412
413 use super::{Component, GlyphOutline, GlyphRef, OutlinePoint, SimpleGlyph};
414 use crate::error::ParseError;
415 use alloc::vec;
416 use alloc::vec::Vec;
417 use font_types::GlyphId;
418
419 fn triangle() -> Vec<u8> {
422 let mut d = Vec::new();
423 d.extend_from_slice(&1i16.to_be_bytes()); d.extend_from_slice(&0i16.to_be_bytes());
425 d.extend_from_slice(&100i16.to_be_bytes());
426 d.extend_from_slice(&300i16.to_be_bytes());
427 d.extend_from_slice(&200i16.to_be_bytes());
428 d.extend_from_slice(&2u16.to_be_bytes()); d.extend_from_slice(&0u16.to_be_bytes()); d.extend_from_slice(&[0x37, 0x37, 0x17]);
433 d.extend_from_slice(&[100, 0, 100]);
435 d.extend_from_slice(&[0, 200, 200]);
437 d
438 }
439
440 #[test]
441 fn simple_glyph_points_and_contours() {
442 let d = triangle();
443 let g = GlyphRef::parse(&d).unwrap().unwrap();
444 let super::GlyphRef::Simple(simple) = g else {
445 panic!("expected simple glyph");
446 };
447 assert_eq!(simple.num_contours(), 1);
448 assert_eq!(simple.bounds().unwrap(), [0, 100, 300, 200]);
449 assert_eq!(simple.end_points().unwrap(), vec![2]);
450 let pts = simple.points().unwrap();
451 assert_eq!(
452 pts,
453 vec![
454 OutlinePoint {
455 x: 100.0,
456 y: 0.0,
457 on_curve: true
458 },
459 OutlinePoint {
460 x: 100.0,
461 y: 200.0,
462 on_curve: true
463 },
464 OutlinePoint {
465 x: 200.0,
466 y: 0.0,
467 on_curve: true
468 },
469 ]
470 );
471 let outline: GlyphOutline = simple.outline().unwrap();
472 assert_eq!(outline.contours.len(), 1);
473 assert_eq!(outline.point_count(), 3);
474 }
475
476 #[test]
477 fn repeat_flags_and_off_curve() {
478 let mut g = Vec::new();
480 g.extend_from_slice(&1i16.to_be_bytes());
481 g.extend_from_slice(&0i16.to_be_bytes());
482 g.extend_from_slice(&0i16.to_be_bytes());
483 g.extend_from_slice(&200i16.to_be_bytes());
484 g.extend_from_slice(&100i16.to_be_bytes());
485 g.extend_from_slice(&1u16.to_be_bytes()); g.extend_from_slice(&0u16.to_be_bytes());
487 g.extend_from_slice(&[0x3F, 1]);
489 g.extend_from_slice(&[100, 100]); g.extend_from_slice(&[200, 200]); let glyph = GlyphRef::parse(&g).unwrap().unwrap();
492 let super::GlyphRef::Simple(simple) = glyph else {
493 panic!("expected simple");
494 };
495 let pts = simple.points().unwrap();
496 assert_eq!(
498 pts,
499 vec![
500 OutlinePoint {
501 x: 100.0,
502 y: 200.0,
503 on_curve: true
504 },
505 OutlinePoint {
506 x: 200.0,
507 y: 400.0,
508 on_curve: true
509 },
510 ]
511 );
512 }
513
514 #[test]
515 fn composite_components_and_flags() {
516 let mut d = Vec::new();
519 d.extend_from_slice(&(-1i16).to_be_bytes());
520 d.extend_from_slice(&0i16.to_be_bytes());
521 d.extend_from_slice(&0i16.to_be_bytes());
522 d.extend_from_slice(&400i16.to_be_bytes());
523 d.extend_from_slice(&400i16.to_be_bytes());
524 let flags: u16 = 0x0001 | 0x0080;
526 d.extend_from_slice(&(flags | 0x0100u16).to_be_bytes()); d.extend_from_slice(&7u16.to_be_bytes());
528 d.extend_from_slice(&3i16.to_be_bytes()); d.extend_from_slice(&9i16.to_be_bytes());
530 d.extend_from_slice(&0x4000i16.to_be_bytes());
532 d.extend_from_slice(&0i16.to_be_bytes());
533 d.extend_from_slice(&0i16.to_be_bytes());
534 d.extend_from_slice(&0x2000i16.to_be_bytes());
535 d.extend_from_slice(&2u16.to_be_bytes()); d.extend_from_slice(&[0xAA, 0xBB]);
537 let glyph = GlyphRef::parse(&d).unwrap().unwrap();
538 let super::GlyphRef::Composite(composite) = glyph else {
539 panic!("expected composite");
540 };
541 let comps: Vec<Component> = composite.components().unwrap();
542 assert_eq!(comps.len(), 1);
543 let c = comps[0];
544 assert_eq!(c.glyph, GlyphId::new(7));
545 assert!(!c.args_are_offsets());
546 assert_eq!(c.args, (3, 9));
547 assert!((c.transform[0] - 1.0).abs() < 1e-6);
548 assert!((c.transform[3] - 0.5).abs() < 1e-6);
549 assert_eq!(composite.bounds().unwrap(), [0, 0, 400, 400]);
550 }
551
552 #[test]
553 fn malformed_records() {
554 let mut d = Vec::new();
556 d.extend_from_slice(&(-3i16).to_be_bytes());
557 d.extend_from_slice(&[0u8; 9]);
558 assert!(matches!(
559 GlyphRef::parse(&d),
560 Err(ParseError::InvalidGlyphFormat)
561 ));
562 assert!(matches!(
564 GlyphRef::parse(&[0, 1, 0]),
565 Err(ParseError::TruncatedTable { .. })
566 ));
567 assert!(GlyphRef::parse(&[]).unwrap().is_none());
569 let mut g = triangle();
571 g[10..12].copy_from_slice(&50u16.to_be_bytes()); let glyph = GlyphRef::parse(&g).unwrap().unwrap();
573 let super::GlyphRef::Simple(simple) = glyph else {
574 panic!("expected simple");
575 };
576 assert!(simple.points().is_err()); let _ = SimpleGlyph::parse(&g).unwrap().num_contours();
578 }
579}