Skip to main content

read_fonts/generated/
generated_avar.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 Avar<'a> {
9    fn min_byte_range(&self) -> Range<usize> {
10        0..self.axis_segment_maps_byte_range().end
11    }
12    fn min_table_bytes(&self) -> &'a [u8] {
13        let range = self.min_byte_range();
14        self.data.as_bytes().get(range).unwrap_or_default()
15    }
16}
17
18impl TopLevelTable for Avar<'_> {
19    /// `avar`
20    const TAG: Tag = Tag::new(b"avar");
21}
22
23impl<'a> FontRead<'a> for Avar<'a> {
24    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
25        #[allow(clippy::absurd_extreme_comparisons)]
26        if data.len() < Self::MIN_SIZE {
27            return Err(ReadError::OutOfBounds);
28        }
29        Ok(Self { data })
30    }
31}
32
33/// The [avar (Axis Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/avar) table
34#[derive(Clone)]
35pub struct Avar<'a> {
36    data: FontData<'a>,
37}
38
39#[allow(clippy::needless_lifetimes)]
40impl<'a> Avar<'a> {
41    pub const MIN_SIZE: usize = (MajorMinor::RAW_BYTE_LEN + u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
42    basic_table_impls!(impl_the_methods);
43
44    /// Major version number of the axis variations table — set to 1 or 2.
45    /// Minor version number of the axis variations table — set to 0.
46    pub fn version(&self) -> MajorMinor {
47        let range = self.version_byte_range();
48        self.data.read_at(range.start).ok().unwrap()
49    }
50
51    /// The number of variation axes for this font. This must be the same number as axisCount in the 'fvar' table.
52    pub fn axis_count(&self) -> u16 {
53        let range = self.axis_count_byte_range();
54        self.data.read_at(range.start).ok().unwrap()
55    }
56
57    /// The segment maps array — one segment map for each axis, in the order of axes specified in the 'fvar' table.
58    pub fn axis_segment_maps(&self) -> VarLenArray<'a, SegmentMaps<'a>> {
59        let range = self.axis_segment_maps_byte_range();
60        self.data
61            .split_off(range.start)
62            .and_then(|d| VarLenArray::read(d).ok())
63            .unwrap_or_default()
64    }
65
66    /// Offset to DeltaSetIndexMap table (may be NULL).
67    pub fn axis_index_map_offset(&self) -> Option<Nullable<Offset32>> {
68        let range = self.axis_index_map_offset_byte_range();
69        (!range.is_empty())
70            .then(|| self.data.read_at(range.start).ok())
71            .flatten()
72    }
73
74    /// Attempt to resolve [`axis_index_map_offset`][Self::axis_index_map_offset].
75    pub fn axis_index_map(&self) -> Option<Result<DeltaSetIndexMap<'a>, ReadError>> {
76        let data = self.data;
77        self.axis_index_map_offset().map(|x| x.resolve(data))?
78    }
79
80    /// Offset to ItemVariationStore (may be NULL).
81    pub fn var_store_offset(&self) -> Option<Nullable<Offset32>> {
82        let range = self.var_store_offset_byte_range();
83        (!range.is_empty())
84            .then(|| self.data.read_at(range.start).ok())
85            .flatten()
86    }
87
88    /// Attempt to resolve [`var_store_offset`][Self::var_store_offset].
89    pub fn var_store(&self) -> Option<Result<ItemVariationStore<'a>, ReadError>> {
90        let data = self.data;
91        self.var_store_offset().map(|x| x.resolve(data))?
92    }
93
94    pub fn version_byte_range(&self) -> Range<usize> {
95        let start = 0;
96        let end = start + MajorMinor::RAW_BYTE_LEN;
97        start..end
98    }
99
100    pub fn _reserved_byte_range(&self) -> Range<usize> {
101        let start = self.version_byte_range().end;
102        let end = start + u16::RAW_BYTE_LEN;
103        start..end
104    }
105
106    pub fn axis_count_byte_range(&self) -> Range<usize> {
107        let start = self._reserved_byte_range().end;
108        let end = start + u16::RAW_BYTE_LEN;
109        start..end
110    }
111
112    pub fn axis_segment_maps_byte_range(&self) -> Range<usize> {
113        let axis_count = self.axis_count();
114        let start = self.axis_count_byte_range().end;
115        let end = start + {
116            let data = self.data.split_off(start).unwrap_or_default();
117            <SegmentMaps as VarSize>::total_len_for_count(data, transforms::to_usize(axis_count))
118                .unwrap_or(0)
119        };
120        start..end
121    }
122
123    pub fn axis_index_map_offset_byte_range(&self) -> Range<usize> {
124        let start = self.axis_segment_maps_byte_range().end;
125        let end = if self.version().compatible((2u16, 0u16)) {
126            start + Offset32::RAW_BYTE_LEN
127        } else {
128            start
129        };
130        start..end
131    }
132
133    pub fn var_store_offset_byte_range(&self) -> Range<usize> {
134        let start = self.axis_index_map_offset_byte_range().end;
135        let end = if self.version().compatible((2u16, 0u16)) {
136            start + Offset32::RAW_BYTE_LEN
137        } else {
138            start
139        };
140        start..end
141    }
142}
143
144const _: () = assert!(FontData::default_data_long_enough(Avar::MIN_SIZE));
145
146impl Default for Avar<'_> {
147    fn default() -> Self {
148        Self {
149            data: FontData::default_table_data(),
150        }
151    }
152}
153
154#[cfg(feature = "experimental_traverse")]
155impl<'a> SomeTable<'a> for Avar<'a> {
156    fn type_name(&self) -> &str {
157        "Avar"
158    }
159    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
160        match idx {
161            0usize => Some(Field::new("version", self.version())),
162            1usize => Some(Field::new("axis_count", self.axis_count())),
163            2usize => Some(Field::new(
164                "axis_segment_maps",
165                traversal::FieldType::var_array(
166                    "SegmentMaps",
167                    self.axis_segment_maps(),
168                    self.offset_data(),
169                ),
170            )),
171            3usize if self.version().compatible((2u16, 0u16)) => Some(Field::new(
172                "axis_index_map_offset",
173                FieldType::offset(self.axis_index_map_offset().unwrap(), self.axis_index_map()),
174            )),
175            4usize if self.version().compatible((2u16, 0u16)) => Some(Field::new(
176                "var_store_offset",
177                FieldType::offset(self.var_store_offset().unwrap(), self.var_store()),
178            )),
179            _ => None,
180        }
181    }
182}
183
184#[cfg(feature = "experimental_traverse")]
185#[allow(clippy::needless_lifetimes)]
186impl<'a> std::fmt::Debug for Avar<'a> {
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        (self as &dyn SomeTable<'a>).fmt(f)
189    }
190}
191
192/// [SegmentMaps](https://learn.microsoft.com/en-us/typography/opentype/spec/avar#table-formats) record
193#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
194pub struct SegmentMaps<'a> {
195    /// The number of correspondence pairs for this axis.
196    pub position_map_count: BigEndian<u16>,
197    /// The array of axis value map records for this axis.
198    pub axis_value_maps: &'a [AxisValueMap],
199}
200
201impl<'a> SegmentMaps<'a> {
202    /// The number of correspondence pairs for this axis.
203    pub fn position_map_count(&self) -> u16 {
204        self.position_map_count.get()
205    }
206
207    /// The array of axis value map records for this axis.
208    pub fn axis_value_maps(&self) -> &'a [AxisValueMap] {
209        self.axis_value_maps
210    }
211}
212
213#[cfg(feature = "experimental_traverse")]
214impl<'a> SomeRecord<'a> for SegmentMaps<'a> {
215    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
216        RecordResolver {
217            name: "SegmentMaps",
218            get_field: Box::new(move |idx, _data| match idx {
219                0usize => Some(Field::new("position_map_count", self.position_map_count())),
220                1usize => Some(Field::new(
221                    "axis_value_maps",
222                    traversal::FieldType::array_of_records(
223                        stringify!(AxisValueMap),
224                        self.axis_value_maps(),
225                        _data,
226                    ),
227                )),
228                _ => None,
229            }),
230            data,
231        }
232    }
233}
234
235/// [AxisValueMap](https://learn.microsoft.com/en-us/typography/opentype/spec/avar#table-formats) record
236#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
237#[repr(C)]
238#[repr(packed)]
239pub struct AxisValueMap {
240    /// A normalized coordinate value obtained using default normalization.
241    pub from_coordinate: BigEndian<F2Dot14>,
242    /// The modified, normalized coordinate value.
243    pub to_coordinate: BigEndian<F2Dot14>,
244}
245
246impl AxisValueMap {
247    /// A normalized coordinate value obtained using default normalization.
248    pub fn from_coordinate(&self) -> F2Dot14 {
249        self.from_coordinate.get()
250    }
251
252    /// The modified, normalized coordinate value.
253    pub fn to_coordinate(&self) -> F2Dot14 {
254        self.to_coordinate.get()
255    }
256}
257
258impl FixedSize for AxisValueMap {
259    const RAW_BYTE_LEN: usize = F2Dot14::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN;
260}
261
262#[cfg(feature = "experimental_traverse")]
263impl<'a> SomeRecord<'a> for AxisValueMap {
264    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
265        RecordResolver {
266            name: "AxisValueMap",
267            get_field: Box::new(move |idx, _data| match idx {
268                0usize => Some(Field::new("from_coordinate", self.from_coordinate())),
269                1usize => Some(Field::new("to_coordinate", self.to_coordinate())),
270                _ => None,
271            }),
272            data,
273        }
274    }
275}