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