Skip to main content

read_fonts/generated/
generated_variations.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<'a> MinByteRange<'a> for TupleVariationHeader<'a> {
9    fn min_byte_range(&self) -> Range<usize> {
10        0..self.intermediate_end_tuple_byte_range().end
11    }
12    fn min_table_bytes(&self) -> &'a [u8] {
13        let range = self.min_byte_range();
14        self.offset_data().as_bytes().get(range).unwrap_or_default()
15    }
16}
17
18impl ReadArgs for TupleVariationHeader<'_> {
19    type Args = u16;
20}
21
22impl<'a> FontRead<'a> for TupleVariationHeader<'a> {
23    fn read_with_args(data: FontData<'a>, args: u16) -> Result<Self, ReadError> {
24        let axis_count = args;
25
26        #[allow(clippy::absurd_extreme_comparisons)]
27        if data.len() < Self::MIN_SIZE {
28            return Err(ReadError::OutOfBounds);
29        }
30        let Some(data) = TableDataRef::new(data.as_bytes()) else {
31            return Err(ReadError::OutOfBounds);
32        };
33        Ok(Self { data, axis_count })
34    }
35}
36
37impl<'a> TupleVariationHeader<'a> {
38    /// A constructor that requires additional arguments.
39    ///
40    /// This type requires some external state in order to be
41    /// parsed.
42    pub fn read(data: FontData<'a>, axis_count: u16) -> Result<Self, ReadError> {
43        let args = axis_count;
44        Self::read_with_args(data, args)
45    }
46}
47
48/// The fields at the start of the table, which are read directly.
49#[derive(Clone, Copy, bytemuck :: AnyBitPattern)]
50#[repr(C, packed)]
51#[doc(hidden)]
52pub struct TupleVariationHeaderFixedHeader {
53    pub variation_data_size: BigEndian<u16>,
54    pub tuple_index: BigEndian<TupleIndex>,
55}
56
57#[allow(clippy::absurd_extreme_comparisons)]
58const _: () = assert!(
59    std::mem::size_of::<TupleVariationHeaderFixedHeader>() <= TupleVariationHeader::MIN_SIZE
60);
61
62/// [TupleVariationHeader](https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#tuplevariationheader)
63#[derive(Clone)]
64pub struct TupleVariationHeader<'a> {
65    data: TableDataRef<'a, TupleVariationHeaderFixedHeader>,
66    axis_count: u16,
67}
68
69#[allow(clippy::needless_lifetimes)]
70impl<'a> TupleVariationHeader<'a> {
71    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + TupleIndex::RAW_BYTE_LEN);
72    basic_table_impls!(impl_the_methods);
73
74    /// The size in bytes of the serialized data for this tuple
75    /// variation table.
76    pub fn variation_data_size(&self) -> u16 {
77        self.data.header().variation_data_size.get()
78    }
79
80    /// A packed field. The high 4 bits are flags (see below). The low
81    /// 12 bits are an index into a shared tuple records array.
82    pub fn tuple_index(&self) -> TupleIndex {
83        self.data.header().tuple_index.get()
84    }
85
86    pub(crate) fn axis_count(&self) -> u16 {
87        self.axis_count
88    }
89
90    pub fn variation_data_size_byte_range(&self) -> Range<usize> {
91        let start = 0usize;
92        let end = start.saturating_add(u16::RAW_BYTE_LEN);
93        start..end
94    }
95
96    pub fn tuple_index_byte_range(&self) -> Range<usize> {
97        let start = self.variation_data_size_byte_range().end;
98        let end = start.saturating_add(TupleIndex::RAW_BYTE_LEN);
99        start..end
100    }
101
102    pub fn peak_tuple_byte_range(&self) -> Range<usize> {
103        let tuple_index = self.tuple_index();
104        let axis_count = self.axis_count();
105        let start = self.tuple_index_byte_range().end;
106        let end = start.saturating_add(
107            (TupleIndex::tuple_len(tuple_index, axis_count, 0_usize))
108                .saturating_mul(F2Dot14::RAW_BYTE_LEN),
109        );
110        start..end
111    }
112
113    pub fn intermediate_start_tuple_byte_range(&self) -> Range<usize> {
114        let tuple_index = self.tuple_index();
115        let axis_count = self.axis_count();
116        let start = self.peak_tuple_byte_range().end;
117        let end = start.saturating_add(
118            (TupleIndex::tuple_len(tuple_index, axis_count, 1_usize))
119                .saturating_mul(F2Dot14::RAW_BYTE_LEN),
120        );
121        start..end
122    }
123
124    pub fn intermediate_end_tuple_byte_range(&self) -> Range<usize> {
125        let tuple_index = self.tuple_index();
126        let axis_count = self.axis_count();
127        let start = self.intermediate_start_tuple_byte_range().end;
128        let end = start.saturating_add(
129            (TupleIndex::tuple_len(tuple_index, axis_count, 1_usize))
130                .saturating_mul(F2Dot14::RAW_BYTE_LEN),
131        );
132        start..end
133    }
134}
135
136const _: () = assert!(FontData::default_data_long_enough(
137    TupleVariationHeader::MIN_SIZE
138));
139
140impl Default for TupleVariationHeader<'_> {
141    fn default() -> Self {
142        Self {
143            data: TableDataRef::new(FontData::default_table_data().as_bytes())
144                .unwrap_or_else(|| unreachable!("the default data covers MIN_SIZE")),
145            axis_count: Default::default(),
146        }
147    }
148}
149
150/// A [Tuple Record](https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#tuple-records)
151///
152/// The tuple variation store formats reference regions within the font’s
153/// variation space using tuple records. A tuple record identifies a position
154/// in terms of normalized coordinates, which use F2DOT14 values.
155#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
156pub struct Tuple<'a> {
157    /// Coordinate array specifying a position within the font’s variation space.
158    ///
159    /// The number of elements must match the axisCount specified in the
160    /// 'fvar' table.
161    pub values: &'a [BigEndian<F2Dot14>],
162}
163
164impl<'a> Tuple<'a> {
165    /// Coordinate array specifying a position within the font’s variation space.
166    ///
167    /// The number of elements must match the axisCount specified in the
168    /// 'fvar' table.
169    pub fn values(&self) -> &'a [BigEndian<F2Dot14>] {
170        self.values
171    }
172}
173
174impl ReadArgs for Tuple<'_> {
175    type Args = u16;
176}
177
178impl ComputeSize for Tuple<'_> {
179    #[allow(clippy::needless_question_mark)]
180    fn compute_size(args: u16) -> Result<usize, ReadError> {
181        let axis_count = args;
182        Ok((transforms::to_usize(axis_count)).saturating_mul(F2Dot14::RAW_BYTE_LEN))
183    }
184}
185
186impl<'a> FontRead<'a> for Tuple<'a> {
187    fn read_with_args(data: FontData<'a>, args: u16) -> Result<Self, ReadError> {
188        let mut cursor = data.cursor();
189        let axis_count = args;
190        Ok(Self {
191            values: cursor.read_array(transforms::to_usize(axis_count))?,
192        })
193    }
194}
195
196crate::impl_font_read_at!(Tuple<'a>);
197
198#[allow(clippy::needless_lifetimes)]
199impl<'a> Tuple<'a> {
200    /// A constructor that requires additional arguments.
201    ///
202    /// This type requires some external state in order to be
203    /// parsed.
204    pub fn read(data: FontData<'a>, axis_count: u16) -> Result<Self, ReadError> {
205        let args = axis_count;
206        Self::read_with_args(data, args)
207    }
208}
209
210impl Format<u8> for DeltaSetIndexMapFormat0<'_> {
211    const FORMAT: u8 = 0;
212}
213
214impl<'a> MinByteRange<'a> for DeltaSetIndexMapFormat0<'a> {
215    fn min_byte_range(&self) -> Range<usize> {
216        0..self.map_data_byte_range().end
217    }
218    fn min_table_bytes(&self) -> &'a [u8] {
219        let range = self.min_byte_range();
220        self.offset_data().as_bytes().get(range).unwrap_or_default()
221    }
222}
223
224impl ReadArgs for DeltaSetIndexMapFormat0<'_> {
225    type Args = ();
226}
227
228impl<'a> FontRead<'a> for DeltaSetIndexMapFormat0<'a> {
229    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
230        #[allow(clippy::absurd_extreme_comparisons)]
231        if data.len() < Self::MIN_SIZE {
232            return Err(ReadError::OutOfBounds);
233        }
234        let Some(data) = TableDataRef::new(data.as_bytes()) else {
235            return Err(ReadError::OutOfBounds);
236        };
237        Ok(Self { data })
238    }
239}
240
241/// The fields at the start of the table, which are read directly.
242#[derive(Clone, Copy, bytemuck :: AnyBitPattern)]
243#[repr(C, packed)]
244#[doc(hidden)]
245pub struct DeltaSetIndexMapFormat0FixedHeader {
246    pub format: u8,
247    pub entry_format: BigEndian<EntryFormat>,
248    pub map_count: BigEndian<u16>,
249}
250
251#[allow(clippy::absurd_extreme_comparisons)]
252const _: () = assert!(
253    std::mem::size_of::<DeltaSetIndexMapFormat0FixedHeader>() <= DeltaSetIndexMapFormat0::MIN_SIZE
254);
255
256/// The [DeltaSetIndexMap](https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#associating-target-items-to-variation-data) table format 0
257#[derive(Clone)]
258pub struct DeltaSetIndexMapFormat0<'a> {
259    data: TableDataRef<'a, DeltaSetIndexMapFormat0FixedHeader>,
260}
261
262#[allow(clippy::needless_lifetimes)]
263impl<'a> DeltaSetIndexMapFormat0<'a> {
264    pub const MIN_SIZE: usize = (u8::RAW_BYTE_LEN + EntryFormat::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
265    basic_table_impls!(impl_the_methods);
266
267    /// DeltaSetIndexMap format: set to 0.
268    pub fn format(&self) -> u8 {
269        self.data.header().format
270    }
271
272    /// A packed field that describes the compressed representation of
273    /// delta-set indices. See details below.
274    pub fn entry_format(&self) -> EntryFormat {
275        self.data.header().entry_format.get()
276    }
277
278    /// The number of mapping entries.
279    pub fn map_count(&self) -> u16 {
280        self.data.header().map_count.get()
281    }
282
283    /// The delta-set index mapping data. See details below.
284    pub fn map_data(&self) -> &'a [u8] {
285        let range = self.map_data_byte_range();
286        self.offset_data()
287            .read_array(range)
288            .ok()
289            .unwrap_or_default()
290    }
291
292    pub fn format_byte_range(&self) -> Range<usize> {
293        let start = 0usize;
294        let end = start.saturating_add(u8::RAW_BYTE_LEN);
295        start..end
296    }
297
298    pub fn entry_format_byte_range(&self) -> Range<usize> {
299        let start = self.format_byte_range().end;
300        let end = start.saturating_add(EntryFormat::RAW_BYTE_LEN);
301        start..end
302    }
303
304    pub fn map_count_byte_range(&self) -> Range<usize> {
305        let start = self.entry_format_byte_range().end;
306        let end = start.saturating_add(u16::RAW_BYTE_LEN);
307        start..end
308    }
309
310    pub fn map_data_byte_range(&self) -> Range<usize> {
311        let entry_format = self.entry_format();
312        let map_count = self.map_count();
313        let start = self.map_count_byte_range().end;
314        let end = start.saturating_add(
315            (EntryFormat::map_size(entry_format, map_count)).saturating_mul(u8::RAW_BYTE_LEN),
316        );
317        start..end
318    }
319}
320
321const _: () = assert!(FontData::default_data_long_enough(
322    DeltaSetIndexMapFormat0::MIN_SIZE
323));
324
325impl Default for DeltaSetIndexMapFormat0<'_> {
326    fn default() -> Self {
327        Self {
328            data: TableDataRef::new(FontData::default_table_data().as_bytes())
329                .unwrap_or_else(|| unreachable!("the default data covers MIN_SIZE")),
330        }
331    }
332}
333
334impl Format<u8> for DeltaSetIndexMapFormat1<'_> {
335    const FORMAT: u8 = 1;
336}
337
338impl<'a> MinByteRange<'a> for DeltaSetIndexMapFormat1<'a> {
339    fn min_byte_range(&self) -> Range<usize> {
340        0..self.map_data_byte_range().end
341    }
342    fn min_table_bytes(&self) -> &'a [u8] {
343        let range = self.min_byte_range();
344        self.offset_data().as_bytes().get(range).unwrap_or_default()
345    }
346}
347
348impl ReadArgs for DeltaSetIndexMapFormat1<'_> {
349    type Args = ();
350}
351
352impl<'a> FontRead<'a> for DeltaSetIndexMapFormat1<'a> {
353    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
354        #[allow(clippy::absurd_extreme_comparisons)]
355        if data.len() < Self::MIN_SIZE {
356            return Err(ReadError::OutOfBounds);
357        }
358        let Some(data) = TableDataRef::new(data.as_bytes()) else {
359            return Err(ReadError::OutOfBounds);
360        };
361        Ok(Self { data })
362    }
363}
364
365/// The fields at the start of the table, which are read directly.
366#[derive(Clone, Copy, bytemuck :: AnyBitPattern)]
367#[repr(C, packed)]
368#[doc(hidden)]
369pub struct DeltaSetIndexMapFormat1FixedHeader {
370    pub format: u8,
371    pub entry_format: BigEndian<EntryFormat>,
372    pub map_count: BigEndian<u32>,
373}
374
375#[allow(clippy::absurd_extreme_comparisons)]
376const _: () = assert!(
377    std::mem::size_of::<DeltaSetIndexMapFormat1FixedHeader>() <= DeltaSetIndexMapFormat1::MIN_SIZE
378);
379
380/// The [DeltaSetIndexMap](https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#associating-target-items-to-variation-data) table format 1
381#[derive(Clone)]
382pub struct DeltaSetIndexMapFormat1<'a> {
383    data: TableDataRef<'a, DeltaSetIndexMapFormat1FixedHeader>,
384}
385
386#[allow(clippy::needless_lifetimes)]
387impl<'a> DeltaSetIndexMapFormat1<'a> {
388    pub const MIN_SIZE: usize = (u8::RAW_BYTE_LEN + EntryFormat::RAW_BYTE_LEN + u32::RAW_BYTE_LEN);
389    basic_table_impls!(impl_the_methods);
390
391    /// DeltaSetIndexMap format: set to 1.
392    pub fn format(&self) -> u8 {
393        self.data.header().format
394    }
395
396    /// A packed field that describes the compressed representation of
397    /// delta-set indices. See details below.
398    pub fn entry_format(&self) -> EntryFormat {
399        self.data.header().entry_format.get()
400    }
401
402    /// The number of mapping entries.
403    pub fn map_count(&self) -> u32 {
404        self.data.header().map_count.get()
405    }
406
407    /// The delta-set index mapping data. See details below.
408    pub fn map_data(&self) -> &'a [u8] {
409        let range = self.map_data_byte_range();
410        self.offset_data()
411            .read_array(range)
412            .ok()
413            .unwrap_or_default()
414    }
415
416    pub fn format_byte_range(&self) -> Range<usize> {
417        let start = 0usize;
418        let end = start.saturating_add(u8::RAW_BYTE_LEN);
419        start..end
420    }
421
422    pub fn entry_format_byte_range(&self) -> Range<usize> {
423        let start = self.format_byte_range().end;
424        let end = start.saturating_add(EntryFormat::RAW_BYTE_LEN);
425        start..end
426    }
427
428    pub fn map_count_byte_range(&self) -> Range<usize> {
429        let start = self.entry_format_byte_range().end;
430        let end = start.saturating_add(u32::RAW_BYTE_LEN);
431        start..end
432    }
433
434    pub fn map_data_byte_range(&self) -> Range<usize> {
435        let entry_format = self.entry_format();
436        let map_count = self.map_count();
437        let start = self.map_count_byte_range().end;
438        let end = start.saturating_add(
439            (EntryFormat::map_size(entry_format, map_count)).saturating_mul(u8::RAW_BYTE_LEN),
440        );
441        start..end
442    }
443}
444
445const _: () = assert!(FontData::default_data_long_enough(
446    DeltaSetIndexMapFormat1::MIN_SIZE
447));
448
449impl Default for DeltaSetIndexMapFormat1<'_> {
450    fn default() -> Self {
451        Self {
452            data: TableDataRef::new(FontData::default_format_1_u8_table_data().as_bytes())
453                .unwrap_or_else(|| unreachable!("the default data covers MIN_SIZE")),
454        }
455    }
456}
457
458/// The [DeltaSetIndexMap](https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#associating-target-items-to-variation-data) table
459#[derive(Clone)]
460pub enum DeltaSetIndexMap<'a> {
461    Format0(DeltaSetIndexMapFormat0<'a>),
462    Format1(DeltaSetIndexMapFormat1<'a>),
463}
464
465impl Default for DeltaSetIndexMap<'_> {
466    fn default() -> Self {
467        Self::Format0(Default::default())
468    }
469}
470
471impl<'a> DeltaSetIndexMap<'a> {
472    ///Return the `FontData` used to resolve offsets for this table.
473    pub fn offset_data(&self) -> FontData<'a> {
474        match self {
475            Self::Format0(item) => item.offset_data(),
476            Self::Format1(item) => item.offset_data(),
477        }
478    }
479
480    /// DeltaSetIndexMap format: set to 0.
481    pub fn format(&self) -> u8 {
482        match self {
483            Self::Format0(item) => item.format(),
484            Self::Format1(item) => item.format(),
485        }
486    }
487
488    /// A packed field that describes the compressed representation of
489    /// delta-set indices. See details below.
490    pub fn entry_format(&self) -> EntryFormat {
491        match self {
492            Self::Format0(item) => item.entry_format(),
493            Self::Format1(item) => item.entry_format(),
494        }
495    }
496
497    /// The delta-set index mapping data. See details below.
498    pub fn map_data(&self) -> &'a [u8] {
499        match self {
500            Self::Format0(item) => item.map_data(),
501            Self::Format1(item) => item.map_data(),
502        }
503    }
504}
505
506impl ReadArgs for DeltaSetIndexMap<'_> {
507    type Args = ();
508}
509
510impl<'a> FontRead<'a> for DeltaSetIndexMap<'a> {
511    #[inline]
512    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
513        let format: u8 = data.read_at(0usize)?;
514        match format {
515            DeltaSetIndexMapFormat0::FORMAT => Ok(Self::Format0(FontRead::read(data)?)),
516            DeltaSetIndexMapFormat1::FORMAT => Ok(Self::Format1(FontRead::read(data)?)),
517            other => Err(ReadError::InvalidFormat(other.into())),
518        }
519    }
520}
521
522impl<'a> MinByteRange<'a> for DeltaSetIndexMap<'a> {
523    fn min_byte_range(&self) -> Range<usize> {
524        match self {
525            Self::Format0(item) => item.min_byte_range(),
526            Self::Format1(item) => item.min_byte_range(),
527        }
528    }
529    fn min_table_bytes(&self) -> &'a [u8] {
530        match self {
531            Self::Format0(item) => item.min_table_bytes(),
532            Self::Format1(item) => item.min_table_bytes(),
533        }
534    }
535}
536
537/// Entry format for a [DeltaSetIndexMap].
538#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
539#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
540#[repr(transparent)]
541pub struct EntryFormat {
542    bits: u8,
543}
544
545impl EntryFormat {
546    /// Mask for the low 4 bits, which give the count of bits minus one that are used in each entry for the inner-level index.
547    pub const INNER_INDEX_BIT_COUNT_MASK: Self = Self { bits: 0x0F };
548
549    /// Mask for bits that indicate the size in bytes minus one of each entry.
550    pub const MAP_ENTRY_SIZE_MASK: Self = Self { bits: 0x30 };
551}
552
553impl EntryFormat {
554    ///  Returns an empty set of flags.
555    #[inline]
556    pub const fn empty() -> Self {
557        Self { bits: 0 }
558    }
559
560    /// Returns the set containing all flags.
561    #[inline]
562    pub const fn all() -> Self {
563        Self {
564            bits: Self::INNER_INDEX_BIT_COUNT_MASK.bits | Self::MAP_ENTRY_SIZE_MASK.bits,
565        }
566    }
567
568    /// Returns the raw value of the flags currently stored.
569    #[inline]
570    pub const fn bits(&self) -> u8 {
571        self.bits
572    }
573
574    /// Convert from underlying bit representation, unless that
575    /// representation contains bits that do not correspond to a flag.
576    #[inline]
577    pub const fn from_bits(bits: u8) -> Option<Self> {
578        if (bits & !Self::all().bits()) == 0 {
579            Some(Self { bits })
580        } else {
581            None
582        }
583    }
584
585    /// Convert from underlying bit representation, dropping any bits
586    /// that do not correspond to flags.
587    #[inline]
588    pub const fn from_bits_truncate(bits: u8) -> Self {
589        Self {
590            bits: bits & Self::all().bits,
591        }
592    }
593
594    /// Returns `true` if no flags are currently stored.
595    #[inline]
596    pub const fn is_empty(&self) -> bool {
597        self.bits() == Self::empty().bits()
598    }
599
600    /// Returns `true` if there are flags common to both `self` and `other`.
601    #[inline]
602    pub const fn intersects(&self, other: Self) -> bool {
603        !(Self {
604            bits: self.bits & other.bits,
605        })
606        .is_empty()
607    }
608
609    /// Returns `true` if all of the flags in `other` are contained within `self`.
610    #[inline]
611    pub const fn contains(&self, other: Self) -> bool {
612        (self.bits & other.bits) == other.bits
613    }
614
615    /// Inserts the specified flags in-place.
616    #[inline]
617    pub fn insert(&mut self, other: Self) {
618        self.bits |= other.bits;
619    }
620
621    /// Removes the specified flags in-place.
622    #[inline]
623    pub fn remove(&mut self, other: Self) {
624        self.bits &= !other.bits;
625    }
626
627    /// Toggles the specified flags in-place.
628    #[inline]
629    pub fn toggle(&mut self, other: Self) {
630        self.bits ^= other.bits;
631    }
632
633    /// Returns the intersection between the flags in `self` and
634    /// `other`.
635    ///
636    /// Specifically, the returned set contains only the flags which are
637    /// present in *both* `self` *and* `other`.
638    ///
639    /// This is equivalent to using the `&` operator (e.g.
640    /// [`ops::BitAnd`]), as in `flags & other`.
641    ///
642    /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
643    #[inline]
644    #[must_use]
645    pub const fn intersection(self, other: Self) -> Self {
646        Self {
647            bits: self.bits & other.bits,
648        }
649    }
650
651    /// Returns the union of between the flags in `self` and `other`.
652    ///
653    /// Specifically, the returned set contains all flags which are
654    /// present in *either* `self` *or* `other`, including any which are
655    /// present in both.
656    ///
657    /// This is equivalent to using the `|` operator (e.g.
658    /// [`ops::BitOr`]), as in `flags | other`.
659    ///
660    /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
661    #[inline]
662    #[must_use]
663    pub const fn union(self, other: Self) -> Self {
664        Self {
665            bits: self.bits | other.bits,
666        }
667    }
668
669    /// Returns the difference between the flags in `self` and `other`.
670    ///
671    /// Specifically, the returned set contains all flags present in
672    /// `self`, except for the ones present in `other`.
673    ///
674    /// It is also conceptually equivalent to the "bit-clear" operation:
675    /// `flags & !other` (and this syntax is also supported).
676    ///
677    /// This is equivalent to using the `-` operator (e.g.
678    /// [`ops::Sub`]), as in `flags - other`.
679    ///
680    /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
681    #[inline]
682    #[must_use]
683    pub const fn difference(self, other: Self) -> Self {
684        Self {
685            bits: self.bits & !other.bits,
686        }
687    }
688}
689
690impl std::ops::BitOr for EntryFormat {
691    type Output = Self;
692
693    /// Returns the union of the two sets of flags.
694    #[inline]
695    fn bitor(self, other: EntryFormat) -> Self {
696        Self {
697            bits: self.bits | other.bits,
698        }
699    }
700}
701
702impl std::ops::BitOrAssign for EntryFormat {
703    /// Adds the set of flags.
704    #[inline]
705    fn bitor_assign(&mut self, other: Self) {
706        self.bits |= other.bits;
707    }
708}
709
710impl std::ops::BitXor for EntryFormat {
711    type Output = Self;
712
713    /// Returns the left flags, but with all the right flags toggled.
714    #[inline]
715    fn bitxor(self, other: Self) -> Self {
716        Self {
717            bits: self.bits ^ other.bits,
718        }
719    }
720}
721
722impl std::ops::BitXorAssign for EntryFormat {
723    /// Toggles the set of flags.
724    #[inline]
725    fn bitxor_assign(&mut self, other: Self) {
726        self.bits ^= other.bits;
727    }
728}
729
730impl std::ops::BitAnd for EntryFormat {
731    type Output = Self;
732
733    /// Returns the intersection between the two sets of flags.
734    #[inline]
735    fn bitand(self, other: Self) -> Self {
736        Self {
737            bits: self.bits & other.bits,
738        }
739    }
740}
741
742impl std::ops::BitAndAssign for EntryFormat {
743    /// Disables all flags disabled in the set.
744    #[inline]
745    fn bitand_assign(&mut self, other: Self) {
746        self.bits &= other.bits;
747    }
748}
749
750impl std::ops::Sub for EntryFormat {
751    type Output = Self;
752
753    /// Returns the set difference of the two sets of flags.
754    #[inline]
755    fn sub(self, other: Self) -> Self {
756        Self {
757            bits: self.bits & !other.bits,
758        }
759    }
760}
761
762impl std::ops::SubAssign for EntryFormat {
763    /// Disables all flags enabled in the set.
764    #[inline]
765    fn sub_assign(&mut self, other: Self) {
766        self.bits &= !other.bits;
767    }
768}
769
770impl std::ops::Not for EntryFormat {
771    type Output = Self;
772
773    /// Returns the complement of this set of flags.
774    #[inline]
775    fn not(self) -> Self {
776        Self { bits: !self.bits } & Self::all()
777    }
778}
779
780impl std::fmt::Debug for EntryFormat {
781    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
782        let members: &[(&str, Self)] = &[
783            (
784                "INNER_INDEX_BIT_COUNT_MASK",
785                Self::INNER_INDEX_BIT_COUNT_MASK,
786            ),
787            ("MAP_ENTRY_SIZE_MASK", Self::MAP_ENTRY_SIZE_MASK),
788        ];
789        let mut first = true;
790        for (name, value) in members {
791            if self.contains(*value) {
792                if !first {
793                    f.write_str(" | ")?;
794                }
795                first = false;
796                f.write_str(name)?;
797            }
798        }
799        if first {
800            f.write_str("(empty)")?;
801        }
802        Ok(())
803    }
804}
805
806impl std::fmt::Binary for EntryFormat {
807    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
808        std::fmt::Binary::fmt(&self.bits, f)
809    }
810}
811
812impl std::fmt::Octal for EntryFormat {
813    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
814        std::fmt::Octal::fmt(&self.bits, f)
815    }
816}
817
818impl std::fmt::LowerHex for EntryFormat {
819    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
820        std::fmt::LowerHex::fmt(&self.bits, f)
821    }
822}
823
824impl std::fmt::UpperHex for EntryFormat {
825    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
826        std::fmt::UpperHex::fmt(&self.bits, f)
827    }
828}
829
830impl font_types::Scalar for EntryFormat {
831    type Raw = <u8 as font_types::Scalar>::Raw;
832    fn to_raw(self) -> Self::Raw {
833        self.bits().to_raw()
834    }
835    fn from_raw(raw: Self::Raw) -> Self {
836        let t = <u8>::from_raw(raw);
837        Self::from_bits_truncate(t)
838    }
839}
840
841impl<'a> MinByteRange<'a> for VariationRegionList<'a> {
842    fn min_byte_range(&self) -> Range<usize> {
843        0..self.variation_regions_byte_range().end
844    }
845    fn min_table_bytes(&self) -> &'a [u8] {
846        let range = self.min_byte_range();
847        self.offset_data().as_bytes().get(range).unwrap_or_default()
848    }
849}
850
851impl ReadArgs for VariationRegionList<'_> {
852    type Args = ();
853}
854
855impl<'a> FontRead<'a> for VariationRegionList<'a> {
856    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
857        #[allow(clippy::absurd_extreme_comparisons)]
858        if data.len() < Self::MIN_SIZE {
859            return Err(ReadError::OutOfBounds);
860        }
861        let Some(data) = TableDataRef::new(data.as_bytes()) else {
862            return Err(ReadError::OutOfBounds);
863        };
864        Ok(Self { data })
865    }
866}
867
868/// The fields at the start of the table, which are read directly.
869#[derive(Clone, Copy, bytemuck :: AnyBitPattern)]
870#[repr(C, packed)]
871#[doc(hidden)]
872pub struct VariationRegionListFixedHeader {
873    pub axis_count: BigEndian<u16>,
874    pub region_count: BigEndian<u16>,
875}
876
877#[allow(clippy::absurd_extreme_comparisons)]
878const _: () =
879    assert!(std::mem::size_of::<VariationRegionListFixedHeader>() <= VariationRegionList::MIN_SIZE);
880
881/// The [VariationRegionList](https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#variation-regions) table
882#[derive(Clone)]
883pub struct VariationRegionList<'a> {
884    data: TableDataRef<'a, VariationRegionListFixedHeader>,
885}
886
887#[allow(clippy::needless_lifetimes)]
888impl<'a> VariationRegionList<'a> {
889    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
890    basic_table_impls!(impl_the_methods);
891
892    /// The number of variation axes for this font. This must be the
893    /// same number as axisCount in the 'fvar' table.
894    pub fn axis_count(&self) -> u16 {
895        self.data.header().axis_count.get()
896    }
897
898    /// The number of variation region tables in the variation region
899    /// list. Must be less than 32,768.
900    pub fn region_count(&self) -> u16 {
901        self.data.header().region_count.get()
902    }
903
904    /// Array of variation regions.
905    pub fn variation_regions(&self) -> ComputedArray<'a, VariationRegion<'a>> {
906        let range = self.variation_regions_byte_range();
907        ComputedArray::new(self.offset_data(), range, self.axis_count()).unwrap_or_default()
908    }
909
910    pub fn axis_count_byte_range(&self) -> Range<usize> {
911        let start = 0usize;
912        let end = start.saturating_add(u16::RAW_BYTE_LEN);
913        start..end
914    }
915
916    pub fn region_count_byte_range(&self) -> Range<usize> {
917        let start = self.axis_count_byte_range().end;
918        let end = start.saturating_add(u16::RAW_BYTE_LEN);
919        start..end
920    }
921
922    pub fn variation_regions_byte_range(&self) -> Range<usize> {
923        let region_count = self.region_count();
924        let start = self.region_count_byte_range().end;
925        let end = start.saturating_add((transforms::to_usize(region_count)).saturating_mul(
926            <VariationRegion as ComputeSize>::compute_size(self.axis_count()).unwrap_or(0),
927        ));
928        start..end
929    }
930}
931
932const _: () = assert!(FontData::default_data_long_enough(
933    VariationRegionList::MIN_SIZE
934));
935
936impl Default for VariationRegionList<'_> {
937    fn default() -> Self {
938        Self {
939            data: TableDataRef::new(FontData::default_table_data().as_bytes())
940                .unwrap_or_else(|| unreachable!("the default data covers MIN_SIZE")),
941        }
942    }
943}
944
945/// The [VariationRegion](https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#variation-regions) record
946#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
947pub struct VariationRegion<'a> {
948    /// Array of region axis coordinates records, in the order of axes
949    /// given in the 'fvar' table.
950    pub region_axes: &'a [RegionAxisCoordinates],
951}
952
953impl<'a> VariationRegion<'a> {
954    /// Array of region axis coordinates records, in the order of axes
955    /// given in the 'fvar' table.
956    pub fn region_axes(&self) -> &'a [RegionAxisCoordinates] {
957        self.region_axes
958    }
959}
960
961impl ReadArgs for VariationRegion<'_> {
962    type Args = u16;
963}
964
965impl ComputeSize for VariationRegion<'_> {
966    #[allow(clippy::needless_question_mark)]
967    fn compute_size(args: u16) -> Result<usize, ReadError> {
968        let axis_count = args;
969        Ok((transforms::to_usize(axis_count)).saturating_mul(RegionAxisCoordinates::RAW_BYTE_LEN))
970    }
971}
972
973impl<'a> FontRead<'a> for VariationRegion<'a> {
974    fn read_with_args(data: FontData<'a>, args: u16) -> Result<Self, ReadError> {
975        let mut cursor = data.cursor();
976        let axis_count = args;
977        Ok(Self {
978            region_axes: cursor.read_array(transforms::to_usize(axis_count))?,
979        })
980    }
981}
982
983crate::impl_font_read_at!(VariationRegion<'a>);
984
985#[allow(clippy::needless_lifetimes)]
986impl<'a> VariationRegion<'a> {
987    /// A constructor that requires additional arguments.
988    ///
989    /// This type requires some external state in order to be
990    /// parsed.
991    pub fn read(data: FontData<'a>, axis_count: u16) -> Result<Self, ReadError> {
992        let args = axis_count;
993        Self::read_with_args(data, args)
994    }
995}
996
997/// The [RegionAxisCoordinates](https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#variation-regions) record
998#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
999#[repr(C)]
1000#[repr(packed)]
1001pub struct RegionAxisCoordinates {
1002    /// The region start coordinate value for the current axis.
1003    pub start_coord: BigEndian<F2Dot14>,
1004    /// The region peak coordinate value for the current axis.
1005    pub peak_coord: BigEndian<F2Dot14>,
1006    /// The region end coordinate value for the current axis.
1007    pub end_coord: BigEndian<F2Dot14>,
1008}
1009
1010impl RegionAxisCoordinates {
1011    /// The region start coordinate value for the current axis.
1012    pub fn start_coord(&self) -> F2Dot14 {
1013        self.start_coord.get()
1014    }
1015
1016    /// The region peak coordinate value for the current axis.
1017    pub fn peak_coord(&self) -> F2Dot14 {
1018        self.peak_coord.get()
1019    }
1020
1021    /// The region end coordinate value for the current axis.
1022    pub fn end_coord(&self) -> F2Dot14 {
1023        self.end_coord.get()
1024    }
1025}
1026
1027impl FixedSize for RegionAxisCoordinates {
1028    const RAW_BYTE_LEN: usize =
1029        F2Dot14::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN;
1030}
1031
1032impl<'a> MinByteRange<'a> for ItemVariationStore<'a> {
1033    fn min_byte_range(&self) -> Range<usize> {
1034        0..self.item_variation_data_offsets_byte_range().end
1035    }
1036    fn min_table_bytes(&self) -> &'a [u8] {
1037        let range = self.min_byte_range();
1038        self.offset_data().as_bytes().get(range).unwrap_or_default()
1039    }
1040}
1041
1042impl ReadArgs for ItemVariationStore<'_> {
1043    type Args = ();
1044}
1045
1046impl<'a> FontRead<'a> for ItemVariationStore<'a> {
1047    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
1048        #[allow(clippy::absurd_extreme_comparisons)]
1049        if data.len() < Self::MIN_SIZE {
1050            return Err(ReadError::OutOfBounds);
1051        }
1052        let Some(data) = TableDataRef::new(data.as_bytes()) else {
1053            return Err(ReadError::OutOfBounds);
1054        };
1055        Ok(Self { data })
1056    }
1057}
1058
1059/// The fields at the start of the table, which are read directly.
1060#[derive(Clone, Copy, bytemuck :: AnyBitPattern)]
1061#[repr(C, packed)]
1062#[doc(hidden)]
1063pub struct ItemVariationStoreFixedHeader {
1064    pub format: BigEndian<u16>,
1065    pub variation_region_list_offset: BigEndian<Offset32>,
1066    pub item_variation_data_count: BigEndian<u16>,
1067}
1068
1069#[allow(clippy::absurd_extreme_comparisons)]
1070const _: () =
1071    assert!(std::mem::size_of::<ItemVariationStoreFixedHeader>() <= ItemVariationStore::MIN_SIZE);
1072
1073/// The [ItemVariationStore](https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#item-variation-store-header-and-item-variation-data-subtables) table
1074#[derive(Clone)]
1075pub struct ItemVariationStore<'a> {
1076    data: TableDataRef<'a, ItemVariationStoreFixedHeader>,
1077}
1078
1079#[allow(clippy::needless_lifetimes)]
1080impl<'a> ItemVariationStore<'a> {
1081    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + Offset32::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
1082    basic_table_impls!(impl_the_methods);
1083
1084    /// Format— set to 1
1085    pub fn format(&self) -> u16 {
1086        self.data.header().format.get()
1087    }
1088
1089    /// Offset in bytes from the start of the item variation store to
1090    /// the variation region list.
1091    pub fn variation_region_list_offset(&self) -> Offset32 {
1092        self.data.header().variation_region_list_offset.get()
1093    }
1094
1095    /// Attempt to resolve [`variation_region_list_offset`][Self::variation_region_list_offset].
1096    pub fn variation_region_list(&self) -> Result<VariationRegionList<'a>, ReadError> {
1097        let data = self.offset_data();
1098        self.variation_region_list_offset().resolve(data)
1099    }
1100
1101    /// The number of item variation data subtables.
1102    pub fn item_variation_data_count(&self) -> u16 {
1103        self.data.header().item_variation_data_count.get()
1104    }
1105
1106    /// Offsets in bytes from the start of the item variation store to
1107    /// each item variation data subtable.
1108    pub fn item_variation_data_offsets(&self) -> &'a [BigEndian<Nullable<Offset32>>] {
1109        let range = self.item_variation_data_offsets_byte_range();
1110        self.offset_data()
1111            .read_array(range)
1112            .ok()
1113            .unwrap_or_default()
1114    }
1115
1116    /// A dynamically resolving wrapper for [`item_variation_data_offsets`][Self::item_variation_data_offsets].
1117    pub fn item_variation_data(
1118        &self,
1119    ) -> ArrayOfNullableOffsets<'a, ItemVariationData<'a>, Offset32> {
1120        let data = self.offset_data();
1121        let offsets = self.item_variation_data_offsets();
1122        ArrayOfNullableOffsets::new(offsets, data, ())
1123    }
1124
1125    pub fn format_byte_range(&self) -> Range<usize> {
1126        let start = 0usize;
1127        let end = start.saturating_add(u16::RAW_BYTE_LEN);
1128        start..end
1129    }
1130
1131    pub fn variation_region_list_offset_byte_range(&self) -> Range<usize> {
1132        let start = self.format_byte_range().end;
1133        let end = start.saturating_add(Offset32::RAW_BYTE_LEN);
1134        start..end
1135    }
1136
1137    pub fn item_variation_data_count_byte_range(&self) -> Range<usize> {
1138        let start = self.variation_region_list_offset_byte_range().end;
1139        let end = start.saturating_add(u16::RAW_BYTE_LEN);
1140        start..end
1141    }
1142
1143    pub fn item_variation_data_offsets_byte_range(&self) -> Range<usize> {
1144        let item_variation_data_count = self.item_variation_data_count();
1145        let start = self.item_variation_data_count_byte_range().end;
1146        let end = start.saturating_add(
1147            (transforms::to_usize(item_variation_data_count))
1148                .saturating_mul(Offset32::RAW_BYTE_LEN),
1149        );
1150        start..end
1151    }
1152}
1153
1154const _: () = assert!(FontData::default_data_long_enough(
1155    ItemVariationStore::MIN_SIZE
1156));
1157
1158impl Default for ItemVariationStore<'_> {
1159    fn default() -> Self {
1160        Self {
1161            data: TableDataRef::new(FontData::default_table_data().as_bytes())
1162                .unwrap_or_else(|| unreachable!("the default data covers MIN_SIZE")),
1163        }
1164    }
1165}
1166
1167impl<'a> MinByteRange<'a> for ItemVariationData<'a> {
1168    fn min_byte_range(&self) -> Range<usize> {
1169        0..self.delta_sets_byte_range().end
1170    }
1171    fn min_table_bytes(&self) -> &'a [u8] {
1172        let range = self.min_byte_range();
1173        self.offset_data().as_bytes().get(range).unwrap_or_default()
1174    }
1175}
1176
1177impl ReadArgs for ItemVariationData<'_> {
1178    type Args = ();
1179}
1180
1181impl<'a> FontRead<'a> for ItemVariationData<'a> {
1182    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
1183        #[allow(clippy::absurd_extreme_comparisons)]
1184        if data.len() < Self::MIN_SIZE {
1185            return Err(ReadError::OutOfBounds);
1186        }
1187        let Some(data) = TableDataRef::new(data.as_bytes()) else {
1188            return Err(ReadError::OutOfBounds);
1189        };
1190        Ok(Self { data })
1191    }
1192}
1193
1194/// The fields at the start of the table, which are read directly.
1195#[derive(Clone, Copy, bytemuck :: AnyBitPattern)]
1196#[repr(C, packed)]
1197#[doc(hidden)]
1198pub struct ItemVariationDataFixedHeader {
1199    pub item_count: BigEndian<u16>,
1200    pub word_delta_count: BigEndian<u16>,
1201    pub region_index_count: BigEndian<u16>,
1202}
1203
1204#[allow(clippy::absurd_extreme_comparisons)]
1205const _: () =
1206    assert!(std::mem::size_of::<ItemVariationDataFixedHeader>() <= ItemVariationData::MIN_SIZE);
1207
1208/// The [ItemVariationData](https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#item-variation-store-header-and-item-variation-data-subtables) subtable
1209#[derive(Clone)]
1210pub struct ItemVariationData<'a> {
1211    data: TableDataRef<'a, ItemVariationDataFixedHeader>,
1212}
1213
1214#[allow(clippy::needless_lifetimes)]
1215impl<'a> ItemVariationData<'a> {
1216    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
1217    basic_table_impls!(impl_the_methods);
1218
1219    /// The number of delta sets for distinct items.
1220    pub fn item_count(&self) -> u16 {
1221        self.data.header().item_count.get()
1222    }
1223
1224    /// A packed field: the high bit is a flag—see details below.
1225    pub fn word_delta_count(&self) -> u16 {
1226        self.data.header().word_delta_count.get()
1227    }
1228
1229    /// The number of variation regions referenced.
1230    pub fn region_index_count(&self) -> u16 {
1231        self.data.header().region_index_count.get()
1232    }
1233
1234    /// Array of indices into the variation region list for the regions
1235    /// referenced by this item variation data table.
1236    pub fn region_indexes(&self) -> &'a [BigEndian<u16>] {
1237        let range = self.region_indexes_byte_range();
1238        self.offset_data()
1239            .read_array(range)
1240            .ok()
1241            .unwrap_or_default()
1242    }
1243
1244    /// Delta-set rows.
1245    pub fn delta_sets(&self) -> &'a [u8] {
1246        let range = self.delta_sets_byte_range();
1247        self.offset_data()
1248            .read_array(range)
1249            .ok()
1250            .unwrap_or_default()
1251    }
1252
1253    pub fn item_count_byte_range(&self) -> Range<usize> {
1254        let start = 0usize;
1255        let end = start.saturating_add(u16::RAW_BYTE_LEN);
1256        start..end
1257    }
1258
1259    pub fn word_delta_count_byte_range(&self) -> Range<usize> {
1260        let start = self.item_count_byte_range().end;
1261        let end = start.saturating_add(u16::RAW_BYTE_LEN);
1262        start..end
1263    }
1264
1265    pub fn region_index_count_byte_range(&self) -> Range<usize> {
1266        let start = self.word_delta_count_byte_range().end;
1267        let end = start.saturating_add(u16::RAW_BYTE_LEN);
1268        start..end
1269    }
1270
1271    pub fn region_indexes_byte_range(&self) -> Range<usize> {
1272        let region_index_count = self.region_index_count();
1273        let start = self.region_index_count_byte_range().end;
1274        let end = start.saturating_add(
1275            (transforms::to_usize(region_index_count)).saturating_mul(u16::RAW_BYTE_LEN),
1276        );
1277        start..end
1278    }
1279
1280    pub fn delta_sets_byte_range(&self) -> Range<usize> {
1281        let item_count = self.item_count();
1282        let word_delta_count = self.word_delta_count();
1283        let region_index_count = self.region_index_count();
1284        let start = self.region_indexes_byte_range().end;
1285        let end = start.saturating_add(
1286            (ItemVariationData::delta_sets_len(item_count, word_delta_count, region_index_count))
1287                .saturating_mul(u8::RAW_BYTE_LEN),
1288        );
1289        start..end
1290    }
1291}
1292
1293const _: () = assert!(FontData::default_data_long_enough(
1294    ItemVariationData::MIN_SIZE
1295));
1296
1297impl Default for ItemVariationData<'_> {
1298    fn default() -> Self {
1299        Self {
1300            data: TableDataRef::new(FontData::default_table_data().as_bytes())
1301                .unwrap_or_else(|| unreachable!("the default data covers MIN_SIZE")),
1302        }
1303    }
1304}