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