Skip to main content

read_fonts/generated/
generated_glyf.rs

1// THIS FILE IS AUTOGENERATED.
2// Any changes to this file will be overwritten.
3// For more information about how codegen works, see font-codegen/README.md
4
5#[allow(unused_imports)]
6use crate::codegen_prelude::*;
7
8impl TopLevelTable for Glyf<'_> {
9    /// `glyf`
10    const TAG: Tag = Tag::new(b"glyf");
11}
12
13impl ReadArgs for Glyf<'_> {
14    type Args = ();
15}
16
17impl<'a> FontRead<'a> for Glyf<'a> {
18    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
19        #[allow(clippy::absurd_extreme_comparisons)]
20        if data.len() < Self::MIN_SIZE {
21            return Err(ReadError::OutOfBounds);
22        }
23        let Some(data) = TableDataRef::new(data.as_bytes()) else {
24            return Err(ReadError::OutOfBounds);
25        };
26        Ok(Self { data })
27    }
28}
29
30/// The fields at the start of the table, which are read directly.
31#[derive(Clone, Copy, bytemuck :: AnyBitPattern)]
32#[repr(C, packed)]
33#[doc(hidden)]
34pub struct GlyfFixedHeader {}
35
36#[allow(clippy::absurd_extreme_comparisons)]
37const _: () = assert!(std::mem::size_of::<GlyfFixedHeader>() <= Glyf::MIN_SIZE);
38
39/// The [glyf (Glyph Data)](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf) table
40#[derive(Clone)]
41pub struct Glyf<'a> {
42    data: TableDataRef<'a, GlyfFixedHeader>,
43}
44
45#[allow(clippy::needless_lifetimes)]
46impl<'a> Glyf<'a> {
47    pub const MIN_SIZE: usize = 0;
48    basic_table_impls!(impl_the_methods);
49}
50
51#[allow(clippy::absurd_extreme_comparisons)]
52const _: () = assert!(FontData::default_data_long_enough(Glyf::MIN_SIZE));
53
54impl Default for Glyf<'_> {
55    fn default() -> Self {
56        Self {
57            data: TableDataRef::new(FontData::default_table_data().as_bytes())
58                .unwrap_or_else(|| unreachable!("the default data covers MIN_SIZE")),
59        }
60    }
61}
62
63impl<'a> MinByteRange<'a> for SimpleGlyph<'a> {
64    fn min_byte_range(&self) -> Range<usize> {
65        0..self.glyph_data_byte_range().end
66    }
67    fn min_table_bytes(&self) -> &'a [u8] {
68        let range = self.min_byte_range();
69        self.offset_data().as_bytes().get(range).unwrap_or_default()
70    }
71}
72
73impl ReadArgs for SimpleGlyph<'_> {
74    type Args = ();
75}
76
77impl<'a> FontRead<'a> for SimpleGlyph<'a> {
78    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
79        #[allow(clippy::absurd_extreme_comparisons)]
80        if data.len() < Self::MIN_SIZE {
81            return Err(ReadError::OutOfBounds);
82        }
83        let Some(data) = TableDataRef::new(data.as_bytes()) else {
84            return Err(ReadError::OutOfBounds);
85        };
86        Ok(Self { data })
87    }
88}
89
90/// The fields at the start of the table, which are read directly.
91#[derive(Clone, Copy, bytemuck :: AnyBitPattern)]
92#[repr(C, packed)]
93#[doc(hidden)]
94pub struct SimpleGlyphFixedHeader {
95    pub number_of_contours: BigEndian<i16>,
96    pub x_min: BigEndian<i16>,
97    pub y_min: BigEndian<i16>,
98    pub x_max: BigEndian<i16>,
99    pub y_max: BigEndian<i16>,
100}
101
102#[allow(clippy::absurd_extreme_comparisons)]
103const _: () = assert!(std::mem::size_of::<SimpleGlyphFixedHeader>() <= SimpleGlyph::MIN_SIZE);
104
105/// The [Glyph Header](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#glyph-headers)
106#[derive(Clone)]
107pub struct SimpleGlyph<'a> {
108    data: TableDataRef<'a, SimpleGlyphFixedHeader>,
109}
110
111#[allow(clippy::needless_lifetimes)]
112impl<'a> SimpleGlyph<'a> {
113    pub const MIN_SIZE: usize = (i16::RAW_BYTE_LEN
114        + i16::RAW_BYTE_LEN
115        + i16::RAW_BYTE_LEN
116        + i16::RAW_BYTE_LEN
117        + i16::RAW_BYTE_LEN
118        + u16::RAW_BYTE_LEN);
119    basic_table_impls!(impl_the_methods);
120
121    /// If the number of contours is greater than or equal to zero,
122    /// this is a simple glyph. If negative, this is a composite glyph
123    /// — the value -1 should be used for composite glyphs.
124    pub fn number_of_contours(&self) -> i16 {
125        self.data.header().number_of_contours.get()
126    }
127
128    /// Minimum x for coordinate data.
129    pub fn x_min(&self) -> i16 {
130        self.data.header().x_min.get()
131    }
132
133    /// Minimum y for coordinate data.
134    pub fn y_min(&self) -> i16 {
135        self.data.header().y_min.get()
136    }
137
138    /// Maximum x for coordinate data.
139    pub fn x_max(&self) -> i16 {
140        self.data.header().x_max.get()
141    }
142
143    /// Maximum y for coordinate data.
144    pub fn y_max(&self) -> i16 {
145        self.data.header().y_max.get()
146    }
147
148    /// Array of point indices for the last point of each contour,
149    /// in increasing numeric order
150    pub fn end_pts_of_contours(&self) -> &'a [BigEndian<u16>] {
151        let range = self.end_pts_of_contours_byte_range();
152        self.offset_data()
153            .read_array(range)
154            .ok()
155            .unwrap_or_default()
156    }
157
158    /// Total number of bytes for instructions. If instructionLength is
159    /// zero, no instructions are present for this glyph, and this
160    /// field is followed directly by the flags field.
161    pub fn instruction_length(&self) -> u16 {
162        let range = self.instruction_length_byte_range();
163        self.offset_data()
164            .read_at(range.start)
165            .ok()
166            .unwrap_or_default()
167    }
168
169    /// Array of instruction byte code for the glyph.
170    pub fn instructions(&self) -> &'a [u8] {
171        let range = self.instructions_byte_range();
172        self.offset_data()
173            .read_array(range)
174            .ok()
175            .unwrap_or_default()
176    }
177
178    /// the raw data for flags & x/y coordinates
179    pub fn glyph_data(&self) -> &'a [u8] {
180        let range = self.glyph_data_byte_range();
181        self.offset_data()
182            .read_array(range)
183            .ok()
184            .unwrap_or_default()
185    }
186
187    pub fn number_of_contours_byte_range(&self) -> Range<usize> {
188        let start = 0;
189        let end = start + i16::RAW_BYTE_LEN;
190        start..end
191    }
192
193    pub fn x_min_byte_range(&self) -> Range<usize> {
194        let start = self.number_of_contours_byte_range().end;
195        let end = start + i16::RAW_BYTE_LEN;
196        start..end
197    }
198
199    pub fn y_min_byte_range(&self) -> Range<usize> {
200        let start = self.x_min_byte_range().end;
201        let end = start + i16::RAW_BYTE_LEN;
202        start..end
203    }
204
205    pub fn x_max_byte_range(&self) -> Range<usize> {
206        let start = self.y_min_byte_range().end;
207        let end = start + i16::RAW_BYTE_LEN;
208        start..end
209    }
210
211    pub fn y_max_byte_range(&self) -> Range<usize> {
212        let start = self.x_max_byte_range().end;
213        let end = start + i16::RAW_BYTE_LEN;
214        start..end
215    }
216
217    pub fn end_pts_of_contours_byte_range(&self) -> Range<usize> {
218        let number_of_contours = self.number_of_contours();
219        let start = self.y_max_byte_range().end;
220        let end =
221            start + (transforms::to_usize(number_of_contours)).saturating_mul(u16::RAW_BYTE_LEN);
222        start..end
223    }
224
225    pub fn instruction_length_byte_range(&self) -> Range<usize> {
226        let start = self.end_pts_of_contours_byte_range().end;
227        let end = start + u16::RAW_BYTE_LEN;
228        start..end
229    }
230
231    pub fn instructions_byte_range(&self) -> Range<usize> {
232        let instruction_length = self.instruction_length();
233        let start = self.instruction_length_byte_range().end;
234        let end =
235            start + (transforms::to_usize(instruction_length)).saturating_mul(u8::RAW_BYTE_LEN);
236        start..end
237    }
238
239    pub fn glyph_data_byte_range(&self) -> Range<usize> {
240        let start = self.instructions_byte_range().end;
241        let end = start
242            + self.offset_data().len().saturating_sub(start) / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
243        start..end
244    }
245}
246
247const _: () = assert!(FontData::default_data_long_enough(SimpleGlyph::MIN_SIZE));
248
249impl Default for SimpleGlyph<'_> {
250    fn default() -> Self {
251        Self {
252            data: TableDataRef::new(FontData::default_table_data().as_bytes())
253                .unwrap_or_else(|| unreachable!("the default data covers MIN_SIZE")),
254        }
255    }
256}
257
258/// Flags used in [SimpleGlyph]
259#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
260#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
261#[repr(transparent)]
262pub struct SimpleGlyphFlags {
263    bits: u8,
264}
265
266impl SimpleGlyphFlags {
267    /// Bit 0: If set, the point is on the curve; otherwise, it is off
268    /// the curve.
269    pub const ON_CURVE_POINT: Self = Self { bits: 0x01 };
270
271    /// Bit 1: If set, the corresponding x-coordinate is 1 byte long,
272    /// and the sign is determined by the
273    /// X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR flag. If not set, its
274    /// interpretation depends on the
275    /// X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR flag: If that other flag
276    /// is set, the x-coordinate is the same as the previous
277    /// x-coordinate, and no element is added to the xCoordinates
278    /// array. If both flags are not set, the corresponding element in
279    /// the xCoordinates array is two bytes and interpreted as a signed
280    /// integer. See the description of the
281    /// X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR flag for additional
282    /// information.
283    pub const X_SHORT_VECTOR: Self = Self { bits: 0x02 };
284
285    /// Bit 2: If set, the corresponding y-coordinate is 1 byte long,
286    /// and the sign is determined by the
287    /// Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR flag. If not set, its
288    /// interpretation depends on the
289    /// Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR flag: If that other flag
290    /// is set, the y-coordinate is the same as the previous
291    /// y-coordinate, and no element is added to the yCoordinates
292    /// array. If both flags are not set, the corresponding element in
293    /// the yCoordinates array is two bytes and interpreted as a signed
294    /// integer. See the description of the
295    /// Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR flag for additional
296    /// information.
297    pub const Y_SHORT_VECTOR: Self = Self { bits: 0x04 };
298
299    /// Bit 3: If set, the next byte (read as unsigned) specifies the
300    /// number of additional times this flag byte is to be repeated in
301    /// the logical flags array — that is, the number of additional
302    /// logical flag entries inserted after this entry. (In the
303    /// expanded logical array, this bit is ignored.) In this way, the
304    /// number of flags listed can be smaller than the number of points
305    /// in the glyph description.
306    pub const REPEAT_FLAG: Self = Self { bits: 0x08 };
307
308    /// Bit 4: This flag has two meanings, depending on how the
309    /// X_SHORT_VECTOR flag is set. If X_SHORT_VECTOR is set, this bit
310    /// describes the sign of the value, with 1 equalling positive and
311    /// 0 negative. If X_SHORT_VECTOR is not set and this bit is set,
312    /// then the current x-coordinate is the same as the previous
313    /// x-coordinate. If X_SHORT_VECTOR is not set and this bit is also
314    /// not set, the current x-coordinate is a signed 16-bit delta
315    /// vector.
316    pub const X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR: Self = Self { bits: 0x10 };
317
318    /// Bit 5: This flag has two meanings, depending on how the
319    /// Y_SHORT_VECTOR flag is set. If Y_SHORT_VECTOR is set, this bit
320    /// describes the sign of the value, with 1 equalling positive and
321    /// 0 negative. If Y_SHORT_VECTOR is not set and this bit is set,
322    /// then the current y-coordinate is the same as the previous
323    /// y-coordinate. If Y_SHORT_VECTOR is not set and this bit is also
324    /// not set, the current y-coordinate is a signed 16-bit delta
325    /// vector.
326    pub const Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR: Self = Self { bits: 0x20 };
327
328    /// Bit 6: If set, contours in the glyph description may overlap.
329    /// Use of this flag is not required in OpenType — that is, it is
330    /// valid to have contours overlap without having this flag set. It
331    /// may affect behaviors in some platforms, however. (See the
332    /// discussion of “Overlapping contours” in Apple’s
333    /// specification for details regarding behavior in Apple
334    /// platforms.) When used, it must be set on the first flag byte
335    /// for the glyph. See additional details below.
336    pub const OVERLAP_SIMPLE: Self = Self { bits: 0x40 };
337
338    /// Bit 7: Off-curve point belongs to a cubic-Bezier segment in GLYF
339    /// (ISO/IEC 14496-22:2026, 5.2.8).
340    pub const CUBIC: Self = Self { bits: 0x80 };
341}
342
343impl SimpleGlyphFlags {
344    ///  Returns an empty set of flags.
345    #[inline]
346    pub const fn empty() -> Self {
347        Self { bits: 0 }
348    }
349
350    /// Returns the set containing all flags.
351    #[inline]
352    pub const fn all() -> Self {
353        Self {
354            bits: Self::ON_CURVE_POINT.bits
355                | Self::X_SHORT_VECTOR.bits
356                | Self::Y_SHORT_VECTOR.bits
357                | Self::REPEAT_FLAG.bits
358                | Self::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR.bits
359                | Self::Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR.bits
360                | Self::OVERLAP_SIMPLE.bits
361                | Self::CUBIC.bits,
362        }
363    }
364
365    /// Returns the raw value of the flags currently stored.
366    #[inline]
367    pub const fn bits(&self) -> u8 {
368        self.bits
369    }
370
371    /// Convert from underlying bit representation, unless that
372    /// representation contains bits that do not correspond to a flag.
373    #[inline]
374    pub const fn from_bits(bits: u8) -> Option<Self> {
375        if (bits & !Self::all().bits()) == 0 {
376            Some(Self { bits })
377        } else {
378            None
379        }
380    }
381
382    /// Convert from underlying bit representation, dropping any bits
383    /// that do not correspond to flags.
384    #[inline]
385    pub const fn from_bits_truncate(bits: u8) -> Self {
386        Self {
387            bits: bits & Self::all().bits,
388        }
389    }
390
391    /// Returns `true` if no flags are currently stored.
392    #[inline]
393    pub const fn is_empty(&self) -> bool {
394        self.bits() == Self::empty().bits()
395    }
396
397    /// Returns `true` if there are flags common to both `self` and `other`.
398    #[inline]
399    pub const fn intersects(&self, other: Self) -> bool {
400        !(Self {
401            bits: self.bits & other.bits,
402        })
403        .is_empty()
404    }
405
406    /// Returns `true` if all of the flags in `other` are contained within `self`.
407    #[inline]
408    pub const fn contains(&self, other: Self) -> bool {
409        (self.bits & other.bits) == other.bits
410    }
411
412    /// Inserts the specified flags in-place.
413    #[inline]
414    pub fn insert(&mut self, other: Self) {
415        self.bits |= other.bits;
416    }
417
418    /// Removes the specified flags in-place.
419    #[inline]
420    pub fn remove(&mut self, other: Self) {
421        self.bits &= !other.bits;
422    }
423
424    /// Toggles the specified flags in-place.
425    #[inline]
426    pub fn toggle(&mut self, other: Self) {
427        self.bits ^= other.bits;
428    }
429
430    /// Returns the intersection between the flags in `self` and
431    /// `other`.
432    ///
433    /// Specifically, the returned set contains only the flags which are
434    /// present in *both* `self` *and* `other`.
435    ///
436    /// This is equivalent to using the `&` operator (e.g.
437    /// [`ops::BitAnd`]), as in `flags & other`.
438    ///
439    /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
440    #[inline]
441    #[must_use]
442    pub const fn intersection(self, other: Self) -> Self {
443        Self {
444            bits: self.bits & other.bits,
445        }
446    }
447
448    /// Returns the union of between the flags in `self` and `other`.
449    ///
450    /// Specifically, the returned set contains all flags which are
451    /// present in *either* `self` *or* `other`, including any which are
452    /// present in both.
453    ///
454    /// This is equivalent to using the `|` operator (e.g.
455    /// [`ops::BitOr`]), as in `flags | other`.
456    ///
457    /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
458    #[inline]
459    #[must_use]
460    pub const fn union(self, other: Self) -> Self {
461        Self {
462            bits: self.bits | other.bits,
463        }
464    }
465
466    /// Returns the difference between the flags in `self` and `other`.
467    ///
468    /// Specifically, the returned set contains all flags present in
469    /// `self`, except for the ones present in `other`.
470    ///
471    /// It is also conceptually equivalent to the "bit-clear" operation:
472    /// `flags & !other` (and this syntax is also supported).
473    ///
474    /// This is equivalent to using the `-` operator (e.g.
475    /// [`ops::Sub`]), as in `flags - other`.
476    ///
477    /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
478    #[inline]
479    #[must_use]
480    pub const fn difference(self, other: Self) -> Self {
481        Self {
482            bits: self.bits & !other.bits,
483        }
484    }
485}
486
487impl std::ops::BitOr for SimpleGlyphFlags {
488    type Output = Self;
489
490    /// Returns the union of the two sets of flags.
491    #[inline]
492    fn bitor(self, other: SimpleGlyphFlags) -> Self {
493        Self {
494            bits: self.bits | other.bits,
495        }
496    }
497}
498
499impl std::ops::BitOrAssign for SimpleGlyphFlags {
500    /// Adds the set of flags.
501    #[inline]
502    fn bitor_assign(&mut self, other: Self) {
503        self.bits |= other.bits;
504    }
505}
506
507impl std::ops::BitXor for SimpleGlyphFlags {
508    type Output = Self;
509
510    /// Returns the left flags, but with all the right flags toggled.
511    #[inline]
512    fn bitxor(self, other: Self) -> Self {
513        Self {
514            bits: self.bits ^ other.bits,
515        }
516    }
517}
518
519impl std::ops::BitXorAssign for SimpleGlyphFlags {
520    /// Toggles the set of flags.
521    #[inline]
522    fn bitxor_assign(&mut self, other: Self) {
523        self.bits ^= other.bits;
524    }
525}
526
527impl std::ops::BitAnd for SimpleGlyphFlags {
528    type Output = Self;
529
530    /// Returns the intersection between the two sets of flags.
531    #[inline]
532    fn bitand(self, other: Self) -> Self {
533        Self {
534            bits: self.bits & other.bits,
535        }
536    }
537}
538
539impl std::ops::BitAndAssign for SimpleGlyphFlags {
540    /// Disables all flags disabled in the set.
541    #[inline]
542    fn bitand_assign(&mut self, other: Self) {
543        self.bits &= other.bits;
544    }
545}
546
547impl std::ops::Sub for SimpleGlyphFlags {
548    type Output = Self;
549
550    /// Returns the set difference of the two sets of flags.
551    #[inline]
552    fn sub(self, other: Self) -> Self {
553        Self {
554            bits: self.bits & !other.bits,
555        }
556    }
557}
558
559impl std::ops::SubAssign for SimpleGlyphFlags {
560    /// Disables all flags enabled in the set.
561    #[inline]
562    fn sub_assign(&mut self, other: Self) {
563        self.bits &= !other.bits;
564    }
565}
566
567impl std::ops::Not for SimpleGlyphFlags {
568    type Output = Self;
569
570    /// Returns the complement of this set of flags.
571    #[inline]
572    fn not(self) -> Self {
573        Self { bits: !self.bits } & Self::all()
574    }
575}
576
577impl std::fmt::Debug for SimpleGlyphFlags {
578    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
579        let members: &[(&str, Self)] = &[
580            ("ON_CURVE_POINT", Self::ON_CURVE_POINT),
581            ("X_SHORT_VECTOR", Self::X_SHORT_VECTOR),
582            ("Y_SHORT_VECTOR", Self::Y_SHORT_VECTOR),
583            ("REPEAT_FLAG", Self::REPEAT_FLAG),
584            (
585                "X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR",
586                Self::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR,
587            ),
588            (
589                "Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR",
590                Self::Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR,
591            ),
592            ("OVERLAP_SIMPLE", Self::OVERLAP_SIMPLE),
593            ("CUBIC", Self::CUBIC),
594        ];
595        let mut first = true;
596        for (name, value) in members {
597            if self.contains(*value) {
598                if !first {
599                    f.write_str(" | ")?;
600                }
601                first = false;
602                f.write_str(name)?;
603            }
604        }
605        if first {
606            f.write_str("(empty)")?;
607        }
608        Ok(())
609    }
610}
611
612impl std::fmt::Binary for SimpleGlyphFlags {
613    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
614        std::fmt::Binary::fmt(&self.bits, f)
615    }
616}
617
618impl std::fmt::Octal for SimpleGlyphFlags {
619    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
620        std::fmt::Octal::fmt(&self.bits, f)
621    }
622}
623
624impl std::fmt::LowerHex for SimpleGlyphFlags {
625    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
626        std::fmt::LowerHex::fmt(&self.bits, f)
627    }
628}
629
630impl std::fmt::UpperHex for SimpleGlyphFlags {
631    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
632        std::fmt::UpperHex::fmt(&self.bits, f)
633    }
634}
635
636impl font_types::Scalar for SimpleGlyphFlags {
637    type Raw = <u8 as font_types::Scalar>::Raw;
638    fn to_raw(self) -> Self::Raw {
639        self.bits().to_raw()
640    }
641    fn from_raw(raw: Self::Raw) -> Self {
642        let t = <u8>::from_raw(raw);
643        Self::from_bits_truncate(t)
644    }
645}
646
647impl<'a> MinByteRange<'a> for CompositeGlyph<'a> {
648    fn min_byte_range(&self) -> Range<usize> {
649        0..self.component_data_byte_range().end
650    }
651    fn min_table_bytes(&self) -> &'a [u8] {
652        let range = self.min_byte_range();
653        self.offset_data().as_bytes().get(range).unwrap_or_default()
654    }
655}
656
657impl ReadArgs for CompositeGlyph<'_> {
658    type Args = ();
659}
660
661impl<'a> FontRead<'a> for CompositeGlyph<'a> {
662    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
663        #[allow(clippy::absurd_extreme_comparisons)]
664        if data.len() < Self::MIN_SIZE {
665            return Err(ReadError::OutOfBounds);
666        }
667        let Some(data) = TableDataRef::new(data.as_bytes()) else {
668            return Err(ReadError::OutOfBounds);
669        };
670        Ok(Self { data })
671    }
672}
673
674/// The fields at the start of the table, which are read directly.
675#[derive(Clone, Copy, bytemuck :: AnyBitPattern)]
676#[repr(C, packed)]
677#[doc(hidden)]
678pub struct CompositeGlyphFixedHeader {
679    pub number_of_contours: BigEndian<i16>,
680    pub x_min: BigEndian<i16>,
681    pub y_min: BigEndian<i16>,
682    pub x_max: BigEndian<i16>,
683    pub y_max: BigEndian<i16>,
684}
685
686#[allow(clippy::absurd_extreme_comparisons)]
687const _: () = assert!(std::mem::size_of::<CompositeGlyphFixedHeader>() <= CompositeGlyph::MIN_SIZE);
688
689/// [CompositeGlyph](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#glyph-headers)
690#[derive(Clone)]
691pub struct CompositeGlyph<'a> {
692    data: TableDataRef<'a, CompositeGlyphFixedHeader>,
693}
694
695#[allow(clippy::needless_lifetimes)]
696impl<'a> CompositeGlyph<'a> {
697    pub const MIN_SIZE: usize = (i16::RAW_BYTE_LEN
698        + i16::RAW_BYTE_LEN
699        + i16::RAW_BYTE_LEN
700        + i16::RAW_BYTE_LEN
701        + i16::RAW_BYTE_LEN);
702    basic_table_impls!(impl_the_methods);
703
704    /// If the number of contours is greater than or equal to zero,
705    /// this is a simple glyph. If negative, this is a composite glyph
706    /// — the value -1 should be used for composite glyphs.
707    pub fn number_of_contours(&self) -> i16 {
708        self.data.header().number_of_contours.get()
709    }
710
711    /// Minimum x for coordinate data.
712    pub fn x_min(&self) -> i16 {
713        self.data.header().x_min.get()
714    }
715
716    /// Minimum y for coordinate data.
717    pub fn y_min(&self) -> i16 {
718        self.data.header().y_min.get()
719    }
720
721    /// Maximum x for coordinate data.
722    pub fn x_max(&self) -> i16 {
723        self.data.header().x_max.get()
724    }
725
726    /// Maximum y for coordinate data.
727    pub fn y_max(&self) -> i16 {
728        self.data.header().y_max.get()
729    }
730
731    /// component flag
732    /// glyph index of component
733    pub fn component_data(&self) -> &'a [u8] {
734        let range = self.component_data_byte_range();
735        self.offset_data()
736            .read_array(range)
737            .ok()
738            .unwrap_or_default()
739    }
740
741    pub fn number_of_contours_byte_range(&self) -> Range<usize> {
742        let start = 0;
743        let end = start + i16::RAW_BYTE_LEN;
744        start..end
745    }
746
747    pub fn x_min_byte_range(&self) -> Range<usize> {
748        let start = self.number_of_contours_byte_range().end;
749        let end = start + i16::RAW_BYTE_LEN;
750        start..end
751    }
752
753    pub fn y_min_byte_range(&self) -> Range<usize> {
754        let start = self.x_min_byte_range().end;
755        let end = start + i16::RAW_BYTE_LEN;
756        start..end
757    }
758
759    pub fn x_max_byte_range(&self) -> Range<usize> {
760        let start = self.y_min_byte_range().end;
761        let end = start + i16::RAW_BYTE_LEN;
762        start..end
763    }
764
765    pub fn y_max_byte_range(&self) -> Range<usize> {
766        let start = self.x_max_byte_range().end;
767        let end = start + i16::RAW_BYTE_LEN;
768        start..end
769    }
770
771    pub fn component_data_byte_range(&self) -> Range<usize> {
772        let start = self.y_max_byte_range().end;
773        let end = start
774            + self.offset_data().len().saturating_sub(start) / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
775        start..end
776    }
777}
778
779const _: () = assert!(FontData::default_data_long_enough(CompositeGlyph::MIN_SIZE));
780
781impl Default for CompositeGlyph<'_> {
782    fn default() -> Self {
783        Self {
784            data: TableDataRef::new(FontData::default_table_data().as_bytes())
785                .unwrap_or_else(|| unreachable!("the default data covers MIN_SIZE")),
786        }
787    }
788}
789
790/// Flags used in [CompositeGlyph]
791#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
792#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
793#[repr(transparent)]
794pub struct CompositeGlyphFlags {
795    bits: u16,
796}
797
798impl CompositeGlyphFlags {
799    /// Bit 0: If this is set, the arguments are 16-bit (uint16 or
800    /// int16); otherwise, they are bytes (uint8 or int8).
801    pub const ARG_1_AND_2_ARE_WORDS: Self = Self { bits: 0x0001 };
802
803    /// Bit 1: If this is set, the arguments are signed xy values,
804    /// otherwise, they are unsigned point numbers.
805    pub const ARGS_ARE_XY_VALUES: Self = Self { bits: 0x0002 };
806
807    /// Bit 2: If set and ARGS_ARE_XY_VALUES is also set, the xy values
808    /// are rounded to the nearest grid line. Ignored if
809    /// ARGS_ARE_XY_VALUES is not set.
810    pub const ROUND_XY_TO_GRID: Self = Self { bits: 0x0004 };
811
812    /// Bit 3: This indicates that there is a simple scale for the
813    /// component. Otherwise, scale = 1.0.
814    pub const WE_HAVE_A_SCALE: Self = Self { bits: 0x0008 };
815
816    /// Bit 5: Indicates at least one more glyph after this one.
817    pub const MORE_COMPONENTS: Self = Self { bits: 0x0020 };
818
819    /// Bit 6: The x direction will use a different scale from the y
820    /// direction.
821    pub const WE_HAVE_AN_X_AND_Y_SCALE: Self = Self { bits: 0x0040 };
822
823    /// Bit 7: There is a 2 by 2 transformation that will be used to
824    /// scale the component.
825    pub const WE_HAVE_A_TWO_BY_TWO: Self = Self { bits: 0x0080 };
826
827    /// Bit 8: Following the last component are instructions for the
828    /// composite character.
829    pub const WE_HAVE_INSTRUCTIONS: Self = Self { bits: 0x0100 };
830
831    /// Bit 9: If set, this forces the aw and lsb (and rsb) for the
832    /// composite to be equal to those from this component glyph. This
833    /// works for hinted and unhinted glyphs.
834    pub const USE_MY_METRICS: Self = Self { bits: 0x0200 };
835
836    /// Bit 10: If set, the components of the compound glyph overlap.
837    /// Use of this flag is not required in OpenType — that is, it is
838    /// valid to have components overlap without having this flag set.
839    /// It may affect behaviors in some platforms, however. (See
840    /// Apple’s specification for details regarding behavior in Apple
841    /// platforms.) When used, it must be set on the flag word for the
842    /// first component. See additional remarks, above, for the similar
843    /// OVERLAP_SIMPLE flag used in simple-glyph descriptions.
844    pub const OVERLAP_COMPOUND: Self = Self { bits: 0x0400 };
845
846    /// Bit 11: The composite is designed to have the component offset
847    /// scaled. Ignored if ARGS_ARE_XY_VALUES is not set.
848    pub const SCALED_COMPONENT_OFFSET: Self = Self { bits: 0x0800 };
849
850    /// Bit 12: The composite is designed not to have the component
851    /// offset scaled. Ignored if ARGS_ARE_XY_VALUES is not set.
852    pub const UNSCALED_COMPONENT_OFFSET: Self = Self { bits: 0x1000 };
853
854    /// Bit 13: The component glyph identifier uses 24-bit encoding in GLYF
855    /// (ISO/IEC 14496-22:2026, 5.2.8).
856    pub const GID_IS_24_BIT: Self = Self { bits: 0x2000 };
857}
858
859impl CompositeGlyphFlags {
860    ///  Returns an empty set of flags.
861    #[inline]
862    pub const fn empty() -> Self {
863        Self { bits: 0 }
864    }
865
866    /// Returns the set containing all flags.
867    #[inline]
868    pub const fn all() -> Self {
869        Self {
870            bits: Self::ARG_1_AND_2_ARE_WORDS.bits
871                | Self::ARGS_ARE_XY_VALUES.bits
872                | Self::ROUND_XY_TO_GRID.bits
873                | Self::WE_HAVE_A_SCALE.bits
874                | Self::MORE_COMPONENTS.bits
875                | Self::WE_HAVE_AN_X_AND_Y_SCALE.bits
876                | Self::WE_HAVE_A_TWO_BY_TWO.bits
877                | Self::WE_HAVE_INSTRUCTIONS.bits
878                | Self::USE_MY_METRICS.bits
879                | Self::OVERLAP_COMPOUND.bits
880                | Self::SCALED_COMPONENT_OFFSET.bits
881                | Self::UNSCALED_COMPONENT_OFFSET.bits
882                | Self::GID_IS_24_BIT.bits,
883        }
884    }
885
886    /// Returns the raw value of the flags currently stored.
887    #[inline]
888    pub const fn bits(&self) -> u16 {
889        self.bits
890    }
891
892    /// Convert from underlying bit representation, unless that
893    /// representation contains bits that do not correspond to a flag.
894    #[inline]
895    pub const fn from_bits(bits: u16) -> Option<Self> {
896        if (bits & !Self::all().bits()) == 0 {
897            Some(Self { bits })
898        } else {
899            None
900        }
901    }
902
903    /// Convert from underlying bit representation, dropping any bits
904    /// that do not correspond to flags.
905    #[inline]
906    pub const fn from_bits_truncate(bits: u16) -> Self {
907        Self {
908            bits: bits & Self::all().bits,
909        }
910    }
911
912    /// Returns `true` if no flags are currently stored.
913    #[inline]
914    pub const fn is_empty(&self) -> bool {
915        self.bits() == Self::empty().bits()
916    }
917
918    /// Returns `true` if there are flags common to both `self` and `other`.
919    #[inline]
920    pub const fn intersects(&self, other: Self) -> bool {
921        !(Self {
922            bits: self.bits & other.bits,
923        })
924        .is_empty()
925    }
926
927    /// Returns `true` if all of the flags in `other` are contained within `self`.
928    #[inline]
929    pub const fn contains(&self, other: Self) -> bool {
930        (self.bits & other.bits) == other.bits
931    }
932
933    /// Inserts the specified flags in-place.
934    #[inline]
935    pub fn insert(&mut self, other: Self) {
936        self.bits |= other.bits;
937    }
938
939    /// Removes the specified flags in-place.
940    #[inline]
941    pub fn remove(&mut self, other: Self) {
942        self.bits &= !other.bits;
943    }
944
945    /// Toggles the specified flags in-place.
946    #[inline]
947    pub fn toggle(&mut self, other: Self) {
948        self.bits ^= other.bits;
949    }
950
951    /// Returns the intersection between the flags in `self` and
952    /// `other`.
953    ///
954    /// Specifically, the returned set contains only the flags which are
955    /// present in *both* `self` *and* `other`.
956    ///
957    /// This is equivalent to using the `&` operator (e.g.
958    /// [`ops::BitAnd`]), as in `flags & other`.
959    ///
960    /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
961    #[inline]
962    #[must_use]
963    pub const fn intersection(self, other: Self) -> Self {
964        Self {
965            bits: self.bits & other.bits,
966        }
967    }
968
969    /// Returns the union of between the flags in `self` and `other`.
970    ///
971    /// Specifically, the returned set contains all flags which are
972    /// present in *either* `self` *or* `other`, including any which are
973    /// present in both.
974    ///
975    /// This is equivalent to using the `|` operator (e.g.
976    /// [`ops::BitOr`]), as in `flags | other`.
977    ///
978    /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
979    #[inline]
980    #[must_use]
981    pub const fn union(self, other: Self) -> Self {
982        Self {
983            bits: self.bits | other.bits,
984        }
985    }
986
987    /// Returns the difference between the flags in `self` and `other`.
988    ///
989    /// Specifically, the returned set contains all flags present in
990    /// `self`, except for the ones present in `other`.
991    ///
992    /// It is also conceptually equivalent to the "bit-clear" operation:
993    /// `flags & !other` (and this syntax is also supported).
994    ///
995    /// This is equivalent to using the `-` operator (e.g.
996    /// [`ops::Sub`]), as in `flags - other`.
997    ///
998    /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
999    #[inline]
1000    #[must_use]
1001    pub const fn difference(self, other: Self) -> Self {
1002        Self {
1003            bits: self.bits & !other.bits,
1004        }
1005    }
1006}
1007
1008impl std::ops::BitOr for CompositeGlyphFlags {
1009    type Output = Self;
1010
1011    /// Returns the union of the two sets of flags.
1012    #[inline]
1013    fn bitor(self, other: CompositeGlyphFlags) -> Self {
1014        Self {
1015            bits: self.bits | other.bits,
1016        }
1017    }
1018}
1019
1020impl std::ops::BitOrAssign for CompositeGlyphFlags {
1021    /// Adds the set of flags.
1022    #[inline]
1023    fn bitor_assign(&mut self, other: Self) {
1024        self.bits |= other.bits;
1025    }
1026}
1027
1028impl std::ops::BitXor for CompositeGlyphFlags {
1029    type Output = Self;
1030
1031    /// Returns the left flags, but with all the right flags toggled.
1032    #[inline]
1033    fn bitxor(self, other: Self) -> Self {
1034        Self {
1035            bits: self.bits ^ other.bits,
1036        }
1037    }
1038}
1039
1040impl std::ops::BitXorAssign for CompositeGlyphFlags {
1041    /// Toggles the set of flags.
1042    #[inline]
1043    fn bitxor_assign(&mut self, other: Self) {
1044        self.bits ^= other.bits;
1045    }
1046}
1047
1048impl std::ops::BitAnd for CompositeGlyphFlags {
1049    type Output = Self;
1050
1051    /// Returns the intersection between the two sets of flags.
1052    #[inline]
1053    fn bitand(self, other: Self) -> Self {
1054        Self {
1055            bits: self.bits & other.bits,
1056        }
1057    }
1058}
1059
1060impl std::ops::BitAndAssign for CompositeGlyphFlags {
1061    /// Disables all flags disabled in the set.
1062    #[inline]
1063    fn bitand_assign(&mut self, other: Self) {
1064        self.bits &= other.bits;
1065    }
1066}
1067
1068impl std::ops::Sub for CompositeGlyphFlags {
1069    type Output = Self;
1070
1071    /// Returns the set difference of the two sets of flags.
1072    #[inline]
1073    fn sub(self, other: Self) -> Self {
1074        Self {
1075            bits: self.bits & !other.bits,
1076        }
1077    }
1078}
1079
1080impl std::ops::SubAssign for CompositeGlyphFlags {
1081    /// Disables all flags enabled in the set.
1082    #[inline]
1083    fn sub_assign(&mut self, other: Self) {
1084        self.bits &= !other.bits;
1085    }
1086}
1087
1088impl std::ops::Not for CompositeGlyphFlags {
1089    type Output = Self;
1090
1091    /// Returns the complement of this set of flags.
1092    #[inline]
1093    fn not(self) -> Self {
1094        Self { bits: !self.bits } & Self::all()
1095    }
1096}
1097
1098impl std::fmt::Debug for CompositeGlyphFlags {
1099    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1100        let members: &[(&str, Self)] = &[
1101            ("ARG_1_AND_2_ARE_WORDS", Self::ARG_1_AND_2_ARE_WORDS),
1102            ("ARGS_ARE_XY_VALUES", Self::ARGS_ARE_XY_VALUES),
1103            ("ROUND_XY_TO_GRID", Self::ROUND_XY_TO_GRID),
1104            ("WE_HAVE_A_SCALE", Self::WE_HAVE_A_SCALE),
1105            ("MORE_COMPONENTS", Self::MORE_COMPONENTS),
1106            ("WE_HAVE_AN_X_AND_Y_SCALE", Self::WE_HAVE_AN_X_AND_Y_SCALE),
1107            ("WE_HAVE_A_TWO_BY_TWO", Self::WE_HAVE_A_TWO_BY_TWO),
1108            ("WE_HAVE_INSTRUCTIONS", Self::WE_HAVE_INSTRUCTIONS),
1109            ("USE_MY_METRICS", Self::USE_MY_METRICS),
1110            ("OVERLAP_COMPOUND", Self::OVERLAP_COMPOUND),
1111            ("SCALED_COMPONENT_OFFSET", Self::SCALED_COMPONENT_OFFSET),
1112            ("UNSCALED_COMPONENT_OFFSET", Self::UNSCALED_COMPONENT_OFFSET),
1113            ("GID_IS_24_BIT", Self::GID_IS_24_BIT),
1114        ];
1115        let mut first = true;
1116        for (name, value) in members {
1117            if self.contains(*value) {
1118                if !first {
1119                    f.write_str(" | ")?;
1120                }
1121                first = false;
1122                f.write_str(name)?;
1123            }
1124        }
1125        if first {
1126            f.write_str("(empty)")?;
1127        }
1128        Ok(())
1129    }
1130}
1131
1132impl std::fmt::Binary for CompositeGlyphFlags {
1133    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1134        std::fmt::Binary::fmt(&self.bits, f)
1135    }
1136}
1137
1138impl std::fmt::Octal for CompositeGlyphFlags {
1139    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1140        std::fmt::Octal::fmt(&self.bits, f)
1141    }
1142}
1143
1144impl std::fmt::LowerHex for CompositeGlyphFlags {
1145    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1146        std::fmt::LowerHex::fmt(&self.bits, f)
1147    }
1148}
1149
1150impl std::fmt::UpperHex for CompositeGlyphFlags {
1151    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1152        std::fmt::UpperHex::fmt(&self.bits, f)
1153    }
1154}
1155
1156impl font_types::Scalar for CompositeGlyphFlags {
1157    type Raw = <u16 as font_types::Scalar>::Raw;
1158    fn to_raw(self) -> Self::Raw {
1159        self.bits().to_raw()
1160    }
1161    fn from_raw(raw: Self::Raw) -> Self {
1162        let t = <u16>::from_raw(raw);
1163        Self::from_bits_truncate(t)
1164    }
1165}
1166
1167/// Simple or composite glyph.
1168#[derive(Clone)]
1169pub enum Glyph<'a> {
1170    Simple(SimpleGlyph<'a>),
1171    Composite(CompositeGlyph<'a>),
1172}
1173
1174impl Default for Glyph<'_> {
1175    fn default() -> Self {
1176        Self::Simple(Default::default())
1177    }
1178}
1179
1180impl<'a> Glyph<'a> {
1181    ///Return the `FontData` used to resolve offsets for this table.
1182    pub fn offset_data(&self) -> FontData<'a> {
1183        match self {
1184            Self::Simple(item) => item.offset_data(),
1185            Self::Composite(item) => item.offset_data(),
1186        }
1187    }
1188
1189    /// If the number of contours is greater than or equal to zero,
1190    /// this is a simple glyph. If negative, this is a composite glyph
1191    /// — the value -1 should be used for composite glyphs.
1192    pub fn number_of_contours(&self) -> i16 {
1193        match self {
1194            Self::Simple(item) => item.number_of_contours(),
1195            Self::Composite(item) => item.number_of_contours(),
1196        }
1197    }
1198
1199    /// Minimum x for coordinate data.
1200    pub fn x_min(&self) -> i16 {
1201        match self {
1202            Self::Simple(item) => item.x_min(),
1203            Self::Composite(item) => item.x_min(),
1204        }
1205    }
1206
1207    /// Minimum y for coordinate data.
1208    pub fn y_min(&self) -> i16 {
1209        match self {
1210            Self::Simple(item) => item.y_min(),
1211            Self::Composite(item) => item.y_min(),
1212        }
1213    }
1214
1215    /// Maximum x for coordinate data.
1216    pub fn x_max(&self) -> i16 {
1217        match self {
1218            Self::Simple(item) => item.x_max(),
1219            Self::Composite(item) => item.x_max(),
1220        }
1221    }
1222
1223    /// Maximum y for coordinate data.
1224    pub fn y_max(&self) -> i16 {
1225        match self {
1226            Self::Simple(item) => item.y_max(),
1227            Self::Composite(item) => item.y_max(),
1228        }
1229    }
1230}
1231
1232impl ReadArgs for Glyph<'_> {
1233    type Args = ();
1234}
1235
1236impl<'a> FontRead<'a> for Glyph<'a> {
1237    #[inline]
1238    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
1239        let format: i16 = data.read_at(0usize)?;
1240
1241        #[allow(clippy::redundant_guards)]
1242        match format {
1243            format if format >= 0 => Ok(Self::Simple(FontRead::read(data)?)),
1244            format if format < 0 => Ok(Self::Composite(FontRead::read(data)?)),
1245            other => Err(ReadError::InvalidFormat(other.into())),
1246        }
1247    }
1248}
1249
1250impl<'a> MinByteRange<'a> for Glyph<'a> {
1251    fn min_byte_range(&self) -> Range<usize> {
1252        match self {
1253            Self::Simple(item) => item.min_byte_range(),
1254            Self::Composite(item) => item.min_byte_range(),
1255        }
1256    }
1257    fn min_table_bytes(&self) -> &'a [u8] {
1258        match self {
1259            Self::Simple(item) => item.min_table_bytes(),
1260            Self::Composite(item) => item.min_table_bytes(),
1261        }
1262    }
1263}