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