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