Skip to main content

read_fonts/tables/
varc.rs

1//! the [VARC (Variable Composite/Component)](https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md) table
2
3pub use super::layout::{Condition, CoverageTable};
4use super::variations::PackedDeltas;
5pub use crate::ps::cff::index::Index2;
6use crate::types::{F2Dot14, Matrix};
7
8#[cfg(feature = "libm")]
9#[allow(unused_imports)]
10use core_maths::*;
11
12include!("../../generated/generated_varc.rs");
13
14/// Let's us call self.something().get(i) instead of get(self.something(), i)
15trait Get<'a> {
16    fn get(self, nth: usize) -> Result<&'a [u8], ReadError>;
17}
18
19impl<'a> Get<'a> for Option<Result<Index2<'a>, ReadError>> {
20    fn get(self, nth: usize) -> Result<&'a [u8], ReadError> {
21        self.transpose()?
22            .ok_or(ReadError::NullOffset)
23            .and_then(|index| index.get(nth).ok_or(ReadError::OutOfBounds))
24    }
25}
26
27impl Varc<'_> {
28    /// Friendlier accessor than directly using raw data via [Index2]
29    pub fn axis_indices(&self, nth: usize) -> Result<PackedDeltas<'_>, ReadError> {
30        let raw = self.axis_indices_list().get(nth)?;
31        Ok(PackedDeltas::consume_all(raw.into()))
32    }
33
34    /// Friendlier accessor than directly using raw data via [Index2]
35    ///
36    /// nth would typically be obtained by looking up a [GlyphId] in [Self::coverage].
37    pub fn glyph(&self, nth: usize) -> Result<VarcGlyph<'_>, ReadError> {
38        let raw = Some(self.var_composite_glyphs()).get(nth)?;
39        Ok(VarcGlyph {
40            table: self,
41            data: raw.into(),
42        })
43    }
44}
45
46impl SparseVariationRegion<'_> {
47    /// Computes a floating point scalar value for this sparse region and the
48    /// specified normalized variation coordinates.
49    pub fn compute_scalar_f32(&self, coords: &[F2Dot14]) -> f32 {
50        let mut scalar = 1.0f32;
51        for axis in self.axis_coordinates().iter() {
52            let Ok(axis) = axis else {
53                return 0.0;
54            };
55            let peak = axis.peak();
56            if peak == F2Dot14::ZERO {
57                continue;
58            }
59            let axis_index = axis.axis_index() as usize;
60            let coord = coords.get(axis_index).copied().unwrap_or(F2Dot14::ZERO);
61            if coord == peak {
62                continue;
63            }
64            if coord == F2Dot14::ZERO {
65                return 0.0;
66            }
67            let start = axis.start();
68            let end = axis.end();
69            if start > peak || peak > end || (start < F2Dot14::ZERO && end > F2Dot14::ZERO) {
70                continue;
71            }
72            if coord < start || coord > end {
73                return 0.0;
74            } else if coord < peak {
75                // Use raw bits - scale factors cancel in the ratio
76                let numerat = coord.to_bits() - start.to_bits();
77                if numerat == 0 {
78                    return 0.0;
79                }
80                let denom = peak.to_bits() - start.to_bits();
81                scalar *= numerat as f32 / denom as f32;
82            } else {
83                // Use raw bits - scale factors cancel in the ratio
84                let numerat = end.to_bits() - coord.to_bits();
85                if numerat == 0 {
86                    return 0.0;
87                }
88                let denom = end.to_bits() - peak.to_bits();
89                scalar *= numerat as f32 / denom as f32;
90            }
91        }
92        scalar
93    }
94}
95
96/// A VARC glyph doesn't have any root level attributes, it's just a list of components
97///
98/// <https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md#variable-composite-description>
99pub struct VarcGlyph<'a> {
100    table: &'a Varc<'a>,
101    data: FontData<'a>,
102}
103
104impl<'a> VarcGlyph<'a> {
105    /// <https://github.com/fonttools/fonttools/blob/5e6b12d12fa08abafbeb7570f47707fbedf69a45/Lib/fontTools/ttLib/tables/otTables.py#L404-L409>
106    pub fn components(&self) -> impl Iterator<Item = Result<VarcComponent<'a>, ReadError>> {
107        VarcComponentIter {
108            table: self.table,
109            cursor: self.data.cursor(),
110        }
111    }
112}
113
114struct VarcComponentIter<'a> {
115    table: &'a Varc<'a>,
116    cursor: Cursor<'a>,
117}
118
119impl<'a> Iterator for VarcComponentIter<'a> {
120    type Item = Result<VarcComponent<'a>, ReadError>;
121
122    fn next(&mut self) -> Option<Self::Item> {
123        if self.cursor.is_empty() {
124            return None;
125        }
126        Some(VarcComponent::parse(self.table, &mut self.cursor))
127    }
128}
129
130pub struct VarcComponent<'a> {
131    flags: VarcFlags,
132    gid: GlyphId,
133    condition_index: Option<u32>,
134    axis_indices_index: Option<u32>,
135    axis_values: Option<PackedDeltas<'a>>,
136    axis_values_var_index: Option<u32>,
137    transform_var_index: Option<u32>,
138    transform: DecomposedTransform,
139}
140
141impl<'a> VarcComponent<'a> {
142    /// Requires access to VARC fields to fully parse.
143    ///
144    ///  * HarfBuzz [VarComponent::get_path_at](https://github.com/harfbuzz/harfbuzz/blob/0c2f5ecd51d11e32836ee136a1bc765d650a4ec0/src/OT/Var/VARC/VARC.cc#L132)
145    fn parse(table: &Varc, cursor: &mut Cursor<'a>) -> Result<Self, ReadError> {
146        let raw_flags = cursor.read_u32_var()?;
147        let flags = VarcFlags::from_bits_truncate(raw_flags);
148        // Ref https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md#variable-component-record
149
150        // This is a GlyphID16 if GID_IS_24BIT bit of flags is clear, else GlyphID24.
151        let gid = if flags.contains(VarcFlags::GID_IS_24BIT) {
152            GlyphId::new(cursor.read::<Uint24>()?.to_u32())
153        } else {
154            GlyphId::from(cursor.read::<u16>()?)
155        };
156
157        let condition_index = if flags.contains(VarcFlags::HAVE_CONDITION) {
158            Some(cursor.read_u32_var()?)
159        } else {
160            None
161        };
162
163        let (axis_indices_index, axis_values) = if flags.contains(VarcFlags::HAVE_AXES) {
164            // <https://github.com/harfbuzz/harfbuzz/blob/0c2f5ecd51d11e32836ee136a1bc765d650a4ec0/src/OT/Var/VARC/VARC.cc#L195-L206>
165            let axis_indices_index = cursor.read_u32_var()?;
166            let num_axis_values = table
167                .axis_indices(axis_indices_index as usize)?
168                .count_or_compute();
169            // we need to consume num_axis_values entries in packed delta format
170            let deltas = if num_axis_values > 0 {
171                let Some(data) = cursor.remaining() else {
172                    return Err(ReadError::OutOfBounds);
173                };
174                let deltas = PackedDeltas::new(data, num_axis_values);
175                *cursor = deltas.iter().end(); // jump past the packed deltas
176                Some(deltas)
177            } else {
178                None
179            };
180            (Some(axis_indices_index), deltas)
181        } else {
182            (None, None)
183        };
184
185        let axis_values_var_index = if flags.contains(VarcFlags::AXIS_VALUES_HAVE_VARIATION) {
186            Some(cursor.read_u32_var()?)
187        } else {
188            None
189        };
190
191        let transform_var_index = if flags.contains(VarcFlags::TRANSFORM_HAS_VARIATION) {
192            Some(cursor.read_u32_var()?)
193        } else {
194            None
195        };
196
197        let mut transform = DecomposedTransform::default();
198        if flags.intersects(VarcFlags::HAVE_TRANSLATE_X | VarcFlags::HAVE_TRANSLATE_Y) {
199            if flags.contains(VarcFlags::HAVE_TRANSLATE_X) {
200                transform.translate_x = cursor.read::<FWord>()?.to_i16() as f32
201            }
202            if flags.contains(VarcFlags::HAVE_TRANSLATE_Y) {
203                transform.translate_y = cursor.read::<FWord>()?.to_i16() as f32
204            }
205        }
206        if flags.contains(VarcFlags::HAVE_ROTATION) {
207            transform.rotation = cursor.read::<F4Dot12>()?.to_f32()
208        }
209        if flags.intersects(VarcFlags::HAVE_SCALE_X | VarcFlags::HAVE_SCALE_Y) {
210            if flags.contains(VarcFlags::HAVE_SCALE_X) {
211                transform.scale_x = cursor.read::<F6Dot10>()?.to_f32()
212            }
213            transform.scale_y = if flags.contains(VarcFlags::HAVE_SCALE_Y) {
214                cursor.read::<F6Dot10>()?.to_f32()
215            } else {
216                transform.scale_x
217            };
218        }
219        // Per the spec, SkewX/SkewY are encoded before TCenterX/TCenterY.
220        // https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md#variable-component-record
221        if flags.intersects(VarcFlags::HAVE_SKEW_X | VarcFlags::HAVE_SKEW_Y) {
222            if flags.contains(VarcFlags::HAVE_SKEW_X) {
223                transform.skew_x = cursor.read::<F4Dot12>()?.to_f32()
224            }
225            if flags.contains(VarcFlags::HAVE_SKEW_Y) {
226                transform.skew_y = cursor.read::<F4Dot12>()?.to_f32()
227            }
228        }
229        if flags.intersects(VarcFlags::HAVE_TCENTER_X | VarcFlags::HAVE_TCENTER_Y) {
230            if flags.contains(VarcFlags::HAVE_TCENTER_X) {
231                transform.center_x = cursor.read::<FWord>()?.to_i16() as f32
232            }
233            if flags.contains(VarcFlags::HAVE_TCENTER_Y) {
234                transform.center_y = cursor.read::<FWord>()?.to_i16() as f32
235            }
236        }
237
238        // Optional, process and discard one uint32var per each set bit in RESERVED_MASK.
239        let reserved = raw_flags & VarcFlags::RESERVED_MASK.bits;
240        if reserved != 0 {
241            let num_reserved = reserved.count_ones();
242            for _ in 0..num_reserved {
243                cursor.read_u32_var()?;
244            }
245        }
246        Ok(VarcComponent {
247            flags,
248            gid,
249            condition_index,
250            axis_indices_index,
251            axis_values,
252            axis_values_var_index,
253            transform_var_index,
254            transform,
255        })
256    }
257
258    pub fn flags(&self) -> VarcFlags {
259        self.flags
260    }
261    pub fn gid(&self) -> GlyphId {
262        self.gid
263    }
264    pub fn condition_index(&self) -> Option<u32> {
265        self.condition_index
266    }
267    pub fn transform(&self) -> &DecomposedTransform {
268        &self.transform
269    }
270    pub fn axis_indices_index(&self) -> Option<u32> {
271        self.axis_indices_index
272    }
273    pub fn axis_values(&self) -> Option<&PackedDeltas<'a>> {
274        self.axis_values.as_ref()
275    }
276    pub fn axis_values_var_index(&self) -> Option<u32> {
277        self.axis_values_var_index
278    }
279    pub fn transform_var_index(&self) -> Option<u32> {
280        self.transform_var_index
281    }
282}
283
284/// <https://github.com/fonttools/fonttools/blob/5e6b12d12fa08abafbeb7570f47707fbedf69a45/Lib/fontTools/misc/transform.py#L410>
285#[derive(Clone, Copy)]
286pub struct DecomposedTransform {
287    translate_x: f32,
288    translate_y: f32,
289    rotation: f32, // multiples of Pi, counter-clockwise
290    scale_x: f32,
291    scale_y: f32,
292    skew_x: f32, // multiples of Pi, clockwise
293    skew_y: f32, // multiples of Pi, counter-clockwise
294    center_x: f32,
295    center_y: f32,
296}
297
298impl Default for DecomposedTransform {
299    fn default() -> Self {
300        Self {
301            translate_x: 0.0,
302            translate_y: 0.0,
303            rotation: 0.0,
304            scale_x: 1.0,
305            scale_y: 1.0,
306            skew_x: 0.0,
307            skew_y: 0.0,
308            center_x: 0.0,
309            center_y: 0.0,
310        }
311    }
312}
313
314impl DecomposedTransform {
315    pub fn translate_x(&self) -> f32 {
316        self.translate_x
317    }
318
319    pub fn translate_y(&self) -> f32 {
320        self.translate_y
321    }
322
323    pub fn rotation(&self) -> f32 {
324        self.rotation
325    }
326
327    pub fn scale_x(&self) -> f32 {
328        self.scale_x
329    }
330
331    pub fn scale_y(&self) -> f32 {
332        self.scale_y
333    }
334
335    pub fn skew_x(&self) -> f32 {
336        self.skew_x
337    }
338
339    pub fn skew_y(&self) -> f32 {
340        self.skew_y
341    }
342
343    pub fn center_x(&self) -> f32 {
344        self.center_x
345    }
346
347    pub fn center_y(&self) -> f32 {
348        self.center_y
349    }
350
351    pub fn set_translate_x(&mut self, value: f32) {
352        self.translate_x = value;
353    }
354
355    pub fn set_translate_y(&mut self, value: f32) {
356        self.translate_y = value;
357    }
358
359    pub fn set_rotation(&mut self, value: f32) {
360        self.rotation = value;
361    }
362
363    pub fn set_scale_x(&mut self, value: f32) {
364        self.scale_x = value;
365    }
366
367    pub fn set_scale_y(&mut self, value: f32) {
368        self.scale_y = value;
369    }
370
371    pub fn set_skew_x(&mut self, value: f32) {
372        self.skew_x = value;
373    }
374
375    pub fn set_skew_y(&mut self, value: f32) {
376        self.skew_y = value;
377    }
378
379    pub fn set_center_x(&mut self, value: f32) {
380        self.center_x = value;
381    }
382
383    pub fn set_center_y(&mut self, value: f32) {
384        self.center_y = value;
385    }
386
387    /// Convert decomposed form to 2x3 matrix form.
388    ///
389    /// The first two values are x,y x-basis vector,
390    /// the second 2 values are x,y y-basis vector, and the third 2 are translation.
391    ///
392    /// In augmented matrix
393    /// form, if this method returns `[a, b, c, d, e, f]` that is taken as:
394    ///
395    /// ```text
396    /// | a c e |
397    /// | b d f |
398    /// | 0 0 1 |
399    /// ```
400    ///
401    /// References:
402    ///   FontTools Python implementation <https://github.com/fonttools/fonttools/blob/5e6b12d12fa08abafbeb7570f47707fbedf69a45/Lib/fontTools/misc/transform.py#L484-L500>
403    /// * Wikipedia [affine transformation](https://en.wikipedia.org/wiki/Affine_transformation)
404    pub fn matrix(&self) -> Matrix<f32> {
405        // Python: t.translate(self.translateX + self.tCenterX, self.translateY + self.tCenterY)
406        let mut transform = Matrix::IDENTITY;
407        transform.dx = self.translate_x + self.center_x;
408        transform.dy = self.translate_y + self.center_y;
409
410        // TODO: this produces very small floats for rotations, e.g. 90 degree rotation a basic scale
411        // puts 1.2246467991473532e-16 into [0]. Should we special case? Round?
412
413        // Python: t = t.rotate(self.rotation * math.pi)
414        if self.rotation != 0.0 {
415            let (s, c) = (self.rotation * core::f32::consts::PI).sin_cos();
416            transform *= Matrix::from_elements([c, s, -s, c, 0.0, 0.0]);
417        }
418
419        // Python: t = t.scale(self.scaleX, self.scaleY)
420        if (self.scale_x, self.scale_y) != (1.0, 1.0) {
421            transform *= Matrix::from_elements([self.scale_x, 0.0, 0.0, self.scale_y, 0.0, 0.0]);
422        }
423
424        // Python: t = t.skew(-self.skewX * math.pi, self.skewY * math.pi)
425        if (self.skew_x, self.skew_y) != (0.0, 0.0) {
426            transform *= Matrix::from_elements([
427                1.0,
428                (self.skew_y * core::f32::consts::PI).tan(),
429                (-self.skew_x * core::f32::consts::PI).tan(),
430                1.0,
431                0.0,
432                0.0,
433            ])
434        }
435
436        // Python: t = t.translate(-self.tCenterX, -self.tCenterY)
437        if (self.center_x, self.center_y) != (0.0, 0.0) {
438            transform *=
439                Matrix::from_elements([1.0, 0.0, 0.0, 1.0, -self.center_x, -self.center_y]);
440        }
441
442        transform
443    }
444}
445
446impl<'a> MultiItemVariationData<'a> {
447    /// Read a specific delta set.
448    ///
449    /// Equivalent to calling [Self::delta_sets], fetching item i, and parsing as [PackedDeltas]
450    pub fn delta_set(&self, i: usize) -> Result<PackedDeltas<'a>, ReadError> {
451        let index = self.delta_sets()?;
452        let raw_deltas = index.get(i).ok_or(ReadError::OutOfBounds)?;
453        Ok(PackedDeltas::consume_all(raw_deltas.into()))
454    }
455}
456
457#[cfg(test)]
458mod tests {
459    use types::GlyphId16;
460
461    use crate::types::F2Dot14;
462    use crate::{FontData, FontRead};
463    use crate::{FontRef, ReadError, TableProvider};
464
465    use super::{
466        Condition, DecomposedTransform, MultiItemVariationData, SparseVariationRegion,
467        SparseVariationRegionList, Varc,
468    };
469
470    impl Varc<'_> {
471        fn conditions(&self) -> impl Iterator<Item = Condition<'_>> {
472            self.condition_list()
473                .expect("A condition list is present")
474                .expect("We could read the condition list")
475                .conditions()
476                .iter()
477                .enumerate()
478                .map(|(i, c)| c.unwrap_or_else(|e| panic!("condition {i} {e}")))
479        }
480
481        fn axis_indices_count(&self) -> Result<usize, ReadError> {
482            let Some(axis_indices_list) = self.axis_indices_list() else {
483                return Ok(0);
484            };
485            let axis_indices_list = axis_indices_list?;
486            Ok(axis_indices_list.count() as usize)
487        }
488    }
489
490    fn round6(v: f32) -> f32 {
491        (v * 1_000_000.0).round() / 1_000_000.0
492    }
493
494    fn coord(value: f32) -> F2Dot14 {
495        F2Dot14::from_f32(value)
496    }
497
498    fn assert_close(actual: f32, expected: f32) {
499        let diff = (actual - expected).abs();
500        assert!(
501            diff <= 1e-6,
502            "expected {expected}, got {actual}, diff {diff}"
503        );
504    }
505
506    fn sfnt_table_range(data: &[u8], tag: [u8; 4]) -> (usize, usize) {
507        let font = FontRef::new(data).unwrap();
508        if let Some(rec) = font
509            .table_directory()
510            .table_records()
511            .iter()
512            .find(|rec| rec.tag() == tag)
513        {
514            return (rec.offset() as usize, rec.length() as usize);
515        }
516        panic!(
517            "missing table {:?}",
518            core::str::from_utf8(&tag).unwrap_or("????")
519        );
520    }
521
522    fn write_be_u32(dst: &mut [u8], value: u32) {
523        dst.copy_from_slice(&value.to_be_bytes());
524    }
525
526    fn read_be_u32(src: &[u8]) -> u32 {
527        u32::from_be_bytes([src[0], src[1], src[2], src[3]])
528    }
529
530    fn encode_u32_var(value: u32) -> Vec<u8> {
531        if value < 0x80 {
532            vec![value as u8]
533        } else if value < 0x4000 {
534            vec![0x80 | ((value >> 8) as u8), value as u8]
535        } else if value < 0x20_0000 {
536            vec![
537                0xC0 | ((value >> 16) as u8),
538                (value >> 8) as u8,
539                value as u8,
540            ]
541        } else if value < 0x1000_0000 {
542            vec![
543                0xE0 | ((value >> 24) as u8),
544                (value >> 16) as u8,
545                (value >> 8) as u8,
546                value as u8,
547            ]
548        } else {
549            vec![
550                0xF0,
551                (value >> 24) as u8,
552                (value >> 16) as u8,
553                (value >> 8) as u8,
554                value as u8,
555            ]
556        }
557    }
558
559    #[test]
560    fn sparse_region_axis_offsets() {
561        let data = [
562            0, 0, 0, 2, 0, 0, 0, 12, 0, 0, 0, 18, 0, 1, 0, 0, 0, 16, 0, 2, 0, 0, 0, 10, 0, 0, 0,
563            18, 0, 0, 0, 0, 0x40, 0, 0x40, 0, 0, 1, 0xC0, 0, 0xC0, 0, 0, 0,
564        ];
565        let list = SparseVariationRegionList::read(data.as_slice().into()).unwrap();
566        let regions = list.regions();
567        let first = regions.get(0).unwrap();
568        let second = regions.get(1).unwrap();
569        assert_eq!(first.compute_scalar_f32(&[coord(0.5)]), 0.5);
570        assert_eq!(second.compute_scalar_f32(&[coord(0.5), coord(-1.0)]), 0.5);
571        assert_eq!(second.axis_coordinates().get(1).unwrap().axis_index(), 1);
572    }
573
574    #[test]
575    fn sparse_region_count_uint32() {
576        let count = 0x10000u32;
577        let offset = 4 + count * 4;
578        let mut bytes = count.to_be_bytes().to_vec();
579        for _ in 0..count {
580            bytes.extend(offset.to_be_bytes());
581        }
582        bytes.extend([0, 0]);
583        let list = SparseVariationRegionList::read(bytes.as_slice().into()).unwrap();
584        assert_eq!(list.region_count(), count);
585        assert_eq!(list.regions().get(0xFFFF).unwrap().region_axis_count(), 0);
586    }
587
588    #[test]
589    fn invalid_sparse_axis_offset() {
590        let data = [0, 1, 0xFF, 0xFF, 0xFF, 0xFF];
591        let region = SparseVariationRegion::read(data.as_slice().into()).unwrap();
592        assert_eq!(region.compute_scalar_f32(&[coord(1.0)]), 0.0);
593    }
594
595    #[test]
596    fn delta_set_index_offset() {
597        let data = [
598            1, 0, 2, 0, 0, 0, 1, 0, 0, 0, 19, 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF, 0, 0,
599            0, 2, 1, 1, 5, 5, 1, 1, 0xFE, 0x80,
600        ];
601        let table = MultiItemVariationData::read(data.as_slice().into()).unwrap();
602        assert_eq!(table.delta_sets_offset().to_u32(), 19);
603        assert_eq!(
604            table.delta_set(0).unwrap().iter().collect::<Vec<_>>(),
605            [1, -2, 0]
606        );
607        assert_eq!(table.delta_set(1).unwrap().iter().count(), 0);
608    }
609
610    #[test]
611    fn truncated_delta_set_index_offset() {
612        let data = [1, 0, 1, 0, 0, 0, 0];
613        let table = MultiItemVariationData::read(data.as_slice().into()).unwrap();
614        assert!(table.delta_sets_offset().is_null());
615        assert!(matches!(table.delta_sets(), Err(ReadError::NullOffset)));
616    }
617
618    #[test]
619    fn read_cjk_0x6868() {
620        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
621        let table = font.varc().unwrap();
622        table.coverage().unwrap(); // should have coverage
623    }
624
625    #[test]
626    fn identify_all_conditional_types() {
627        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
628        let table = font.varc().unwrap();
629
630        // We should have all 5 condition types in order
631        assert_eq!(
632            (1..=5).collect::<Vec<_>>(),
633            table.conditions().map(|c| c.format()).collect::<Vec<_>>()
634        );
635    }
636
637    #[test]
638    fn read_condition_format1_axis_range() {
639        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
640        let table = font.varc().unwrap();
641        let Some(Condition::Format1AxisRange(condition)) =
642            table.conditions().find(|c| c.format() == 1)
643        else {
644            panic!("No such item");
645        };
646
647        assert_eq!(
648            (0, 0.5, 1.0),
649            (
650                condition.axis_index(),
651                condition.filter_range_min_value().to_f32(),
652                condition.filter_range_max_value().to_f32(),
653            )
654        );
655    }
656
657    #[test]
658    fn read_condition_format2_variable_value() {
659        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
660        let table = font.varc().unwrap();
661        let Some(Condition::Format2VariableValue(condition)) =
662            table.conditions().find(|c| c.format() == 2)
663        else {
664            panic!("No such item");
665        };
666
667        assert_eq!((1, 2), (condition.default_value(), condition.var_index(),));
668    }
669
670    #[test]
671    fn read_condition_format3_and() {
672        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
673        let table = font.varc().unwrap();
674        let Some(Condition::Format3And(condition)) = table.conditions().find(|c| c.format() == 3)
675        else {
676            panic!("No such item");
677        };
678
679        // Should reference a format 1 and a format 2
680        assert_eq!(
681            vec![1, 2],
682            condition
683                .conditions()
684                .iter()
685                .map(|c| c.unwrap().format())
686                .collect::<Vec<_>>()
687        );
688    }
689
690    #[test]
691    fn read_condition_format4_or() {
692        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
693        let table = font.varc().unwrap();
694        let Some(Condition::Format4Or(condition)) = table.conditions().find(|c| c.format() == 4)
695        else {
696            panic!("No such item");
697        };
698
699        // Should reference a format 1 and a format 2
700        assert_eq!(
701            vec![1, 2],
702            condition
703                .conditions()
704                .iter()
705                .map(|c| c.unwrap().format())
706                .collect::<Vec<_>>()
707        );
708    }
709
710    #[test]
711    fn read_condition_format5_negate() {
712        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
713        let table = font.varc().unwrap();
714        let Some(Condition::Format5Negate(condition)) =
715            table.conditions().find(|c| c.format() == 5)
716        else {
717            panic!("No such item");
718        };
719
720        // Should reference a format 1
721        assert_eq!(1, condition.condition().unwrap().format(),);
722    }
723
724    #[test]
725    fn read_axis_indices_list() {
726        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
727        let table = font.varc().unwrap();
728        assert_eq!(table.axis_indices_count().unwrap(), 2);
729        assert_eq!(
730            vec![2, 3, 4, 5, 6],
731            table.axis_indices(1).unwrap().iter().collect::<Vec<_>>()
732        );
733    }
734
735    #[test]
736    fn compute_sparse_region_scalar_handles_boundaries_and_products() {
737        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
738        let varc = font.varc().unwrap();
739        let store = varc.multi_var_store().unwrap().unwrap();
740        let regions = store.region_list().unwrap();
741        let region_list = regions.regions();
742
743        let axis0_region = region_list.get(0).unwrap();
744        assert_close(axis0_region.compute_scalar_f32(&[coord(1.0)]), 1.0);
745        assert_close(axis0_region.compute_scalar_f32(&[coord(0.5)]), 0.5);
746        assert_close(axis0_region.compute_scalar_f32(&[F2Dot14::ZERO]), 0.0);
747        assert_close(axis0_region.compute_scalar_f32(&[]), 0.0);
748        assert_close(axis0_region.compute_scalar_f32(&[coord(-0.25)]), 0.0);
749
750        let axis0_axis1_region = region_list.get(2).unwrap();
751        assert_close(
752            axis0_axis1_region.compute_scalar_f32(&[coord(0.5), coord(0.25)]),
753            0.125,
754        );
755    }
756
757    #[test]
758    fn axis_indices_offset_out_of_bounds_errors() {
759        let mut bytes = font_test_data::varc::CJK_6868.to_vec();
760        let (varc_offset, varc_len) = sfnt_table_range(&bytes, *b"VARC");
761        // axis_indices_list_offset is the 5th u32 in the VARC header.
762        let axis_indices_offset = varc_offset + 16;
763        write_be_u32(
764            &mut bytes[axis_indices_offset..axis_indices_offset + 4],
765            (varc_len as u32).saturating_add(8),
766        );
767
768        let font = FontRef::new(&bytes).unwrap();
769        let table = font.varc().unwrap();
770        assert!(matches!(table.axis_indices(0), Err(ReadError::OutOfBounds)));
771    }
772
773    #[test]
774    fn var_composite_glyphs_offset_out_of_bounds_errors() {
775        let mut bytes = font_test_data::varc::CJK_6868.to_vec();
776        let (varc_offset, varc_len) = sfnt_table_range(&bytes, *b"VARC");
777        // var_composite_glyphs_offset is the 6th u32 in the VARC header.
778        let glyphs_offset = varc_offset + 20;
779        write_be_u32(
780            &mut bytes[glyphs_offset..glyphs_offset + 4],
781            (varc_len as u32).saturating_add(8),
782        );
783
784        let font = FontRef::new(&bytes).unwrap();
785        let table = font.varc().unwrap();
786        assert!(matches!(table.glyph(0), Err(ReadError::OutOfBounds)));
787    }
788
789    #[test]
790    fn parse_component_with_missing_translate_data_errors() {
791        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
792        let table = font.varc().unwrap();
793        // flags=HAVE_TRANSLATE_X, gid=1, missing FWORD payload.
794        let data = FontData::new(&[0x10, 0x00, 0x01]);
795        let mut cursor = data.cursor();
796        assert!(matches!(
797            super::VarcComponent::parse(&table, &mut cursor),
798            Err(ReadError::OutOfBounds)
799        ));
800    }
801
802    #[test]
803    fn parse_component_with_invalid_axis_indices_index_errors() {
804        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
805        let table = font.varc().unwrap();
806        // flags=HAVE_AXES, gid=1, axis_indices_index=127 (out of range).
807        let data = FontData::new(&[0x02, 0x00, 0x01, 0x7F]);
808        let mut cursor = data.cursor();
809        assert!(matches!(
810            super::VarcComponent::parse(&table, &mut cursor),
811            Err(ReadError::OutOfBounds)
812        ));
813    }
814
815    #[test]
816    fn parse_component_reserved_fields_are_consumed() {
817        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
818        let table = font.varc().unwrap();
819        // flags = HAVE_TRANSLATE_X plus two reserved bits.
820        let flags = 0x0001_8010_u32;
821        let mut bytes = Vec::new();
822        bytes.extend_from_slice(&encode_u32_var(flags));
823        bytes.extend_from_slice(&[0x00, 0x01]); // gid
824        bytes.extend_from_slice(&[0x00, 0x07]); // translate_x = 7
825        bytes.extend_from_slice(&encode_u32_var(1)); // reserved payload 1
826        bytes.extend_from_slice(&encode_u32_var(2)); // reserved payload 2
827        bytes.push(0xAA); // sentinel
828        let data = FontData::new(&bytes);
829        let mut cursor = data.cursor();
830
831        let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
832        assert_eq!(component.transform().translate_x(), 7.0);
833        assert_eq!(cursor.read::<u8>().unwrap(), 0xAA);
834    }
835
836    #[test]
837    fn parse_component_reserved_fields_truncation_errors() {
838        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
839        let table = font.varc().unwrap();
840        // flags = HAVE_TRANSLATE_X plus two reserved bits, but only one reserved payload follows.
841        let flags = 0x0001_8010_u32;
842        let mut bytes = Vec::new();
843        bytes.extend_from_slice(&encode_u32_var(flags));
844        bytes.extend_from_slice(&[0x00, 0x01]); // gid
845        bytes.extend_from_slice(&[0x00, 0x07]); // translate_x
846        bytes.extend_from_slice(&encode_u32_var(1)); // only one reserved payload
847        let data = FontData::new(&bytes);
848        let mut cursor = data.cursor();
849
850        assert!(matches!(
851            super::VarcComponent::parse(&table, &mut cursor),
852            Err(ReadError::OutOfBounds)
853        ));
854    }
855
856    #[test]
857    fn parse_component_gid_is_24bit_path() {
858        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
859        let table = font.varc().unwrap();
860        let mut bytes = Vec::new();
861        bytes.extend_from_slice(&encode_u32_var(super::VarcFlags::GID_IS_24BIT.bits()));
862        bytes.extend_from_slice(&[0x12, 0x34, 0x56]);
863        bytes.push(0xAA); // sentinel
864        let data = FontData::new(&bytes);
865        let mut cursor = data.cursor();
866
867        let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
868        assert_eq!(component.gid().to_u32(), 0x12_34_56);
869        assert_eq!(cursor.read::<u8>().unwrap(), 0xAA);
870    }
871
872    #[test]
873    fn parse_component_gid_is_24bit_truncation_errors() {
874        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
875        let table = font.varc().unwrap();
876        let mut bytes = Vec::new();
877        bytes.extend_from_slice(&encode_u32_var(super::VarcFlags::GID_IS_24BIT.bits()));
878        bytes.extend_from_slice(&[0x12, 0x34]); // truncated uint24
879        let data = FontData::new(&bytes);
880        let mut cursor = data.cursor();
881
882        assert!(matches!(
883            super::VarcComponent::parse(&table, &mut cursor),
884            Err(ReadError::OutOfBounds)
885        ));
886    }
887
888    #[test]
889    fn parse_component_with_axes_zero_count_does_not_consume_axis_values() {
890        let mut bytes = font_test_data::varc::CJK_6868.to_vec();
891        let (varc_offset, _) = sfnt_table_range(&bytes, *b"VARC");
892        let axis_indices_rel = read_be_u32(&bytes[varc_offset + 16..varc_offset + 20]) as usize;
893        let axis_indices_abs = varc_offset + axis_indices_rel;
894        // Overwrite axis_indices_list with Index2 { count = 1, off_size = 1, offsets = [1, 1] }.
895        // That single item is empty, so count_or_compute() must be zero.
896        bytes[axis_indices_abs..axis_indices_abs + 7]
897            .copy_from_slice(&[0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01]);
898        let font = FontRef::new(&bytes).unwrap();
899        let table = font.varc().unwrap();
900        assert_eq!(table.axis_indices(0).unwrap().count_or_compute(), 0);
901
902        // flags = HAVE_AXES | HAVE_TRANSLATE_X
903        let mut bytes = Vec::new();
904        bytes.extend_from_slice(&encode_u32_var(0x12));
905        bytes.extend_from_slice(&[0x00, 0x01]); // gid
906        bytes.extend_from_slice(&encode_u32_var(0)); // axis_indices_index, count is zero
907        bytes.extend_from_slice(&[0x00, 0x05]); // translate_x
908        bytes.push(0xAA); // sentinel
909        let data = FontData::new(&bytes);
910        let mut cursor = data.cursor();
911
912        let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
913        assert_eq!(component.transform().translate_x(), 5.0);
914        assert_eq!(cursor.read::<u8>().unwrap(), 0xAA);
915    }
916
917    #[test]
918    fn parse_component_with_axes_nonzero_count_consumes_axis_values() {
919        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
920        let table = font.varc().unwrap();
921        assert_eq!(table.axis_indices(1).unwrap().count_or_compute(), 5);
922
923        // flags = HAVE_AXES | HAVE_TRANSLATE_X
924        let mut bytes = Vec::new();
925        bytes.extend_from_slice(&encode_u32_var(0x12));
926        bytes.extend_from_slice(&[0x00, 0x01]); // gid
927        bytes.extend_from_slice(&encode_u32_var(1)); // axis_indices_index, count is five
928        bytes.push(0x04); // one I8 run, count = 5
929        bytes.extend_from_slice(&[1, 2, 3, 4, 5]); // packed axis values
930        bytes.extend_from_slice(&[0x00, 0x09]); // translate_x
931        bytes.push(0xAA); // sentinel
932        let data = FontData::new(&bytes);
933        let mut cursor = data.cursor();
934
935        let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
936        assert_eq!(component.transform().translate_x(), 9.0);
937        assert_eq!(cursor.read::<u8>().unwrap(), 0xAA);
938    }
939
940    #[test]
941    fn parse_component_scale_x_only_applies_to_scale_y() {
942        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
943        let table = font.varc().unwrap();
944        let mut bytes = Vec::new();
945        bytes.extend_from_slice(&encode_u32_var(super::VarcFlags::HAVE_SCALE_X.bits()));
946        bytes.extend_from_slice(&[0x00, 0x01]); // gid
947        bytes.extend_from_slice(&[0x08, 0x00]); // scale_x = 2.0 in F6Dot10
948        bytes.push(0xAA); // sentinel
949        let data = FontData::new(&bytes);
950        let mut cursor = data.cursor();
951
952        let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
953        assert_eq!(component.transform().scale_x(), 2.0);
954        assert_eq!(component.transform().scale_y(), 2.0);
955        assert_eq!(cursor.read::<u8>().unwrap(), 0xAA);
956    }
957
958    #[test]
959    fn parse_component_scale_x_and_scale_y_are_independent() {
960        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
961        let table = font.varc().unwrap();
962        let flags = super::VarcFlags::HAVE_SCALE_X.bits() | super::VarcFlags::HAVE_SCALE_Y.bits();
963        let mut bytes = Vec::new();
964        bytes.extend_from_slice(&encode_u32_var(flags));
965        bytes.extend_from_slice(&[0x00, 0x01]); // gid
966        bytes.extend_from_slice(&[0x08, 0x00]); // scale_x = 2.0
967        bytes.extend_from_slice(&[0x0C, 0x00]); // scale_y = 3.0
968        bytes.push(0xAA); // sentinel
969        let data = FontData::new(&bytes);
970        let mut cursor = data.cursor();
971
972        let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
973        assert_eq!(component.transform().scale_x(), 2.0);
974        assert_eq!(component.transform().scale_y(), 3.0);
975        assert_eq!(cursor.read::<u8>().unwrap(), 0xAA);
976    }
977
978    #[test]
979    fn parse_component_multibyte_condition_and_var_indices() {
980        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
981        let table = font.varc().unwrap();
982        let flags = super::VarcFlags::HAVE_CONDITION.bits()
983            | super::VarcFlags::AXIS_VALUES_HAVE_VARIATION.bits()
984            | super::VarcFlags::TRANSFORM_HAS_VARIATION.bits()
985            | super::VarcFlags::HAVE_TRANSLATE_X.bits();
986        let mut bytes = Vec::new();
987        bytes.extend_from_slice(&encode_u32_var(flags));
988        bytes.extend_from_slice(&[0x00, 0x01]); // gid
989        bytes.extend_from_slice(&encode_u32_var(0x2345)); // condition_index
990        bytes.extend_from_slice(&encode_u32_var(0x0123)); // axis_values_var_index
991        bytes.extend_from_slice(&encode_u32_var(0x0222)); // transform_var_index
992        bytes.extend_from_slice(&[0x00, 0x07]); // translate_x = 7
993        bytes.push(0xAA); // sentinel
994        let data = FontData::new(&bytes);
995        let mut cursor = data.cursor();
996
997        let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
998        assert_eq!(component.condition_index(), Some(0x2345));
999        assert_eq!(component.axis_values_var_index(), Some(0x0123));
1000        assert_eq!(component.transform_var_index(), Some(0x0222));
1001        assert_eq!(component.transform().translate_x(), 7.0);
1002        assert_eq!(cursor.read::<u8>().unwrap(), 0xAA);
1003    }
1004
1005    #[test]
1006    fn parse_component_truncated_multibyte_condition_index_errors() {
1007        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
1008        let table = font.varc().unwrap();
1009        let mut bytes = Vec::new();
1010        bytes.extend_from_slice(&encode_u32_var(super::VarcFlags::HAVE_CONDITION.bits()));
1011        bytes.extend_from_slice(&[0x00, 0x01]); // gid
1012        bytes.push(0x81); // truncated uint32var (needs one more byte)
1013        let data = FontData::new(&bytes);
1014        let mut cursor = data.cursor();
1015
1016        assert!(matches!(
1017            super::VarcComponent::parse(&table, &mut cursor),
1018            Err(ReadError::OutOfBounds)
1019        ));
1020    }
1021
1022    #[test]
1023    fn parse_component_axes_with_var_index_and_zero_axis_count() {
1024        let mut bytes = font_test_data::varc::CJK_6868.to_vec();
1025        let (varc_offset, _) = sfnt_table_range(&bytes, *b"VARC");
1026        let axis_indices_rel = read_be_u32(&bytes[varc_offset + 16..varc_offset + 20]) as usize;
1027        let axis_indices_abs = varc_offset + axis_indices_rel;
1028        // One empty axis-indices entry at index 0.
1029        bytes[axis_indices_abs..axis_indices_abs + 7]
1030            .copy_from_slice(&[0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01]);
1031        let font = FontRef::new(&bytes).unwrap();
1032        let table = font.varc().unwrap();
1033
1034        let flags = super::VarcFlags::HAVE_AXES.bits()
1035            | super::VarcFlags::AXIS_VALUES_HAVE_VARIATION.bits()
1036            | super::VarcFlags::HAVE_TRANSLATE_X.bits();
1037        let mut bytes = Vec::new();
1038        bytes.extend_from_slice(&encode_u32_var(flags));
1039        bytes.extend_from_slice(&[0x00, 0x01]); // gid
1040        bytes.extend_from_slice(&encode_u32_var(0)); // axis_indices_index => zero-length axis list
1041        bytes.extend_from_slice(&encode_u32_var(0x0123)); // axis_values_var_index
1042        bytes.extend_from_slice(&[0x00, 0x06]); // translate_x = 6
1043        bytes.push(0xAA); // sentinel
1044        let data = FontData::new(&bytes);
1045        let mut cursor = data.cursor();
1046
1047        let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
1048        assert_eq!(component.axis_indices_index(), Some(0));
1049        assert!(component.axis_values().is_none());
1050        assert_eq!(component.axis_values_var_index(), Some(0x0123));
1051        assert_eq!(component.transform().translate_x(), 6.0);
1052        assert_eq!(cursor.read::<u8>().unwrap(), 0xAA);
1053    }
1054
1055    #[test]
1056    fn parse_component_axes_truncated_i16_payload_detected_on_fetch() {
1057        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
1058        let table = font.varc().unwrap();
1059        assert_eq!(table.axis_indices(1).unwrap().count_or_compute(), 5);
1060
1061        // flags = HAVE_AXES.
1062        let mut bytes = Vec::new();
1063        bytes.extend_from_slice(&encode_u32_var(super::VarcFlags::HAVE_AXES.bits()));
1064        bytes.extend_from_slice(&[0x00, 0x01]); // gid
1065        bytes.extend_from_slice(&encode_u32_var(1)); // axis_indices_index => expects 5 values
1066        bytes.push(0x44); // I16 run, count = 5
1067        bytes.extend_from_slice(&[0x00, 0x01, 0x00, 0x02, 0x00, 0x03]); // only 3 i16 values
1068        let data = FontData::new(&bytes);
1069        let mut cursor = data.cursor();
1070
1071        let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
1072        let mut out = [0.0; 5];
1073        assert!(matches!(
1074            component
1075                .axis_values()
1076                .unwrap()
1077                .fetcher()
1078                .add_to_f32_scaled(&mut out, 1.0),
1079            Err(ReadError::OutOfBounds)
1080        ));
1081    }
1082
1083    #[test]
1084    fn parse_component_axes_truncated_i32_payload_detected_on_fetch() {
1085        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
1086        let table = font.varc().unwrap();
1087        assert_eq!(table.axis_indices(1).unwrap().count_or_compute(), 5);
1088
1089        // flags = HAVE_AXES.
1090        let mut bytes = Vec::new();
1091        bytes.extend_from_slice(&encode_u32_var(super::VarcFlags::HAVE_AXES.bits()));
1092        bytes.extend_from_slice(&[0x00, 0x01]); // gid
1093        bytes.extend_from_slice(&encode_u32_var(1)); // axis_indices_index => expects 5 values
1094        bytes.push(0xC4); // I32 run, count = 5
1095        bytes.extend_from_slice(&[
1096            0x00, 0x00, 0x00, 0x01, // only 1 i32 value
1097            0x00, 0x00, 0x00, 0x02,
1098        ]);
1099        let data = FontData::new(&bytes);
1100        let mut cursor = data.cursor();
1101
1102        let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
1103        let mut out = [0.0; 5];
1104        assert!(matches!(
1105            component
1106                .axis_values()
1107                .unwrap()
1108                .fetcher()
1109                .add_to_f32_scaled(&mut out, 1.0),
1110            Err(ReadError::OutOfBounds)
1111        ));
1112    }
1113
1114    #[test]
1115    fn parse_component_axes_payload_overshoot_causes_following_field_error() {
1116        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
1117        let table = font.varc().unwrap();
1118        assert_eq!(table.axis_indices(1).unwrap().count_or_compute(), 5);
1119
1120        // flags = HAVE_AXES | HAVE_TRANSLATE_X.
1121        let mut bytes = Vec::new();
1122        bytes.extend_from_slice(&encode_u32_var(
1123            super::VarcFlags::HAVE_AXES.bits() | super::VarcFlags::HAVE_TRANSLATE_X.bits(),
1124        ));
1125        bytes.extend_from_slice(&[0x00, 0x01]); // gid
1126        bytes.extend_from_slice(&encode_u32_var(1)); // axis_indices_index => expects 5 values
1127        bytes.push(0x44); // I16 run, count = 5 (needs 10 bytes)
1128        bytes.extend_from_slice(&[0x00, 0x01, 0x00, 0x02]); // too short
1129        bytes.extend_from_slice(&[0x00, 0x09]); // intended translate_x (should be unreachable)
1130        let data = FontData::new(&bytes);
1131        let mut cursor = data.cursor();
1132
1133        assert!(matches!(
1134            super::VarcComponent::parse(&table, &mut cursor),
1135            Err(ReadError::OutOfBounds)
1136        ));
1137    }
1138
1139    #[test]
1140    fn generated_condition_varints_roundtrip() {
1141        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
1142        let table = font.varc().unwrap();
1143        let mut state = 0x1234_5678_u32;
1144        for _ in 0..256 {
1145            // xorshift32
1146            state ^= state << 13;
1147            state ^= state >> 17;
1148            state ^= state << 5;
1149            let value = state;
1150
1151            let mut bytes = Vec::new();
1152            bytes.extend_from_slice(&encode_u32_var(super::VarcFlags::HAVE_CONDITION.bits()));
1153            bytes.extend_from_slice(&[0x00, 0x01]); // gid
1154            bytes.extend_from_slice(&encode_u32_var(value));
1155            bytes.push(0xAA); // sentinel
1156            let data = FontData::new(&bytes);
1157            let mut cursor = data.cursor();
1158
1159            let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
1160            assert_eq!(component.condition_index(), Some(value));
1161            assert_eq!(cursor.read::<u8>().unwrap(), 0xAA);
1162        }
1163    }
1164
1165    #[test]
1166    fn generated_axis_values_single_run_roundtrip() {
1167        let font = FontRef::new(font_test_data::varc::CONDITIONALS).unwrap();
1168        let table = font.varc().unwrap();
1169        assert_eq!(table.axis_indices(1).unwrap().count_or_compute(), 5);
1170
1171        let mut state = 0xA5A5_5A5A_u32;
1172        for _ in 0..128 {
1173            // xorshift32
1174            state ^= state << 13;
1175            state ^= state >> 17;
1176            state ^= state << 5;
1177            let run_kind = state & 3;
1178
1179            let mut payload = Vec::new();
1180            let mut expected = [0f32; 5];
1181            match run_kind {
1182                0 => {
1183                    // I8, count = 5
1184                    payload.push(0x04);
1185                    for out in &mut expected {
1186                        state = state.wrapping_mul(1664525).wrapping_add(1013904223);
1187                        let v = ((state >> 24) as i8) % 64;
1188                        payload.push(v as u8);
1189                        *out = v as f32;
1190                    }
1191                }
1192                1 => {
1193                    // I16, count = 5
1194                    payload.push(0x44);
1195                    for out in &mut expected {
1196                        state = state.wrapping_mul(1664525).wrapping_add(1013904223);
1197                        let v = ((state >> 16) as i16) % 2048;
1198                        payload.extend_from_slice(&v.to_be_bytes());
1199                        *out = v as f32;
1200                    }
1201                }
1202                2 => {
1203                    // I32, count = 5
1204                    payload.push(0xC4);
1205                    for out in &mut expected {
1206                        state = state.wrapping_mul(1664525).wrapping_add(1013904223);
1207                        let v = (state as i32) % 1_000_000;
1208                        payload.extend_from_slice(&v.to_be_bytes());
1209                        *out = v as f32;
1210                    }
1211                }
1212                _ => {
1213                    // Zero, count = 5
1214                    payload.push(0x84);
1215                }
1216            }
1217
1218            let mut bytes = Vec::new();
1219            bytes.extend_from_slice(&encode_u32_var(
1220                super::VarcFlags::HAVE_AXES.bits() | super::VarcFlags::HAVE_TRANSLATE_X.bits(),
1221            ));
1222            bytes.extend_from_slice(&[0x00, 0x01]); // gid
1223            bytes.extend_from_slice(&encode_u32_var(1)); // axis_indices_index => 5 values
1224            bytes.extend_from_slice(&payload);
1225            bytes.extend_from_slice(&[0x00, 0x07]); // translate_x
1226            bytes.push(0xAA); // sentinel
1227
1228            let data = FontData::new(&bytes);
1229            let mut cursor = data.cursor();
1230            let component = super::VarcComponent::parse(&table, &mut cursor).unwrap();
1231            let mut out = [0.0f32; 5];
1232            component
1233                .axis_values()
1234                .unwrap()
1235                .fetcher()
1236                .add_to_f32_scaled(&mut out, 1.0)
1237                .unwrap();
1238            assert_eq!(out, expected);
1239            assert_eq!(component.transform().translate_x(), 7.0);
1240            assert_eq!(cursor.read::<u8>().unwrap(), 0xAA);
1241        }
1242    }
1243
1244    #[test]
1245    fn parse_component_truncated_condition_varint_boundaries_error() {
1246        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
1247        let table = font.varc().unwrap();
1248        let values = [0x80_u32, 0x4000_u32, 0x20_0000_u32, 0x1000_0000_u32];
1249
1250        for value in values {
1251            let encoded = encode_u32_var(value);
1252            assert!(encoded.len() > 1);
1253            let truncated = &encoded[..encoded.len() - 1];
1254
1255            let mut bytes = Vec::new();
1256            bytes.extend_from_slice(&encode_u32_var(super::VarcFlags::HAVE_CONDITION.bits()));
1257            bytes.extend_from_slice(&[0x00, 0x01]); // gid
1258            bytes.extend_from_slice(truncated);
1259            let data = FontData::new(&bytes);
1260            let mut cursor = data.cursor();
1261
1262            assert!(matches!(
1263                super::VarcComponent::parse(&table, &mut cursor),
1264                Err(ReadError::OutOfBounds)
1265            ));
1266        }
1267    }
1268
1269    #[test]
1270    fn read_glyph_6868() {
1271        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
1272        let gid = font.cmap().unwrap().map_codepoint(0x6868_u32).unwrap();
1273        let table = font.varc().unwrap();
1274        let idx = table.coverage().unwrap().get(gid).unwrap();
1275
1276        let glyph = table.glyph(idx as usize).unwrap();
1277        assert_eq!(
1278            vec![GlyphId16::new(2), GlyphId16::new(5), GlyphId16::new(7)],
1279            glyph
1280                .components()
1281                .map(|c| c.unwrap().gid)
1282                .collect::<Vec<_>>()
1283        );
1284    }
1285
1286    // Expected created using the Python DecomposedTransform
1287    #[test]
1288    fn decomposed_scale_to_matrix() {
1289        let scale_x = 2.0;
1290        let scale_y = 3.0;
1291        assert_eq!(
1292            [scale_x, 0.0, 0.0, scale_y, 0.0, 0.0],
1293            DecomposedTransform {
1294                scale_x,
1295                scale_y,
1296                ..Default::default()
1297            }
1298            .matrix()
1299            .map(round6)
1300            .elements()
1301        );
1302    }
1303
1304    // Expected created using the Python DecomposedTransform
1305    #[test]
1306    fn decomposed_rotate_to_matrix() {
1307        assert_eq!(
1308            [0.0, 1.0, -1.0, 0.0, 0.0, 0.0],
1309            DecomposedTransform {
1310                // Rotation is in multiples of Pi (90 degrees = 0.5 * Pi).
1311                rotation: 0.5,
1312                ..Default::default()
1313            }
1314            .matrix()
1315            .map(round6)
1316            .elements()
1317        );
1318    }
1319
1320    // Expected created using the Python DecomposedTransform
1321    #[test]
1322    fn decomposed_skew_to_matrix() {
1323        // Skew is in multiples of Pi.
1324        let skew_x: f32 = 1.0 / 6.0; // 30 degrees
1325        let skew_y: f32 = -1.0 / 3.0; // -60 degrees
1326        assert_eq!(
1327            [
1328                1.0,
1329                round6((skew_y * core::f32::consts::PI).tan()),
1330                round6((-skew_x * core::f32::consts::PI).tan()),
1331                1.0,
1332                0.0,
1333                0.0
1334            ],
1335            DecomposedTransform {
1336                skew_x,
1337                skew_y,
1338                ..Default::default()
1339            }
1340            .matrix()
1341            .map(round6)
1342            .elements()
1343        );
1344    }
1345
1346    // Expected created using the Python DecomposedTransform
1347    #[test]
1348    fn decomposed_scale_rotate_to_matrix() {
1349        let scale_x = 2.0;
1350        let scale_y = 3.0;
1351        assert_eq!(
1352            [0.0, scale_x, -scale_y, 0.0, 0.0, 0.0],
1353            DecomposedTransform {
1354                scale_x,
1355                scale_y,
1356                // 90 degrees = 0.5 * Pi.
1357                rotation: 0.5,
1358                ..Default::default()
1359            }
1360            .matrix()
1361            .map(round6)
1362            .elements()
1363        );
1364    }
1365
1366    // Expected created using the Python DecomposedTransform
1367    #[test]
1368    fn decomposed_scale_rotate_translate_to_matrix() {
1369        assert_eq!(
1370            [0.0, 2.0, -1.0, 0.0, 10.0, 20.0],
1371            DecomposedTransform {
1372                scale_x: 2.0,
1373                // 90 degrees = 0.5 * Pi.
1374                rotation: 0.5,
1375                translate_x: 10.0,
1376                translate_y: 20.0,
1377                ..Default::default()
1378            }
1379            .matrix()
1380            .map(round6)
1381            .elements()
1382        );
1383    }
1384
1385    // Expected created using the Python DecomposedTransform
1386    #[test]
1387    fn decomposed_scale_skew_translate_to_matrix() {
1388        assert_eq!(
1389            [-0.866026, 5.5, -2.5, 2.020726, 10.0, 20.0],
1390            DecomposedTransform {
1391                scale_x: 2.0,
1392                scale_y: 3.0,
1393                // Angles are in multiples of Pi.
1394                rotation: 1.0 / 6.0, // 30 degrees
1395                skew_x: 1.0 / 6.0,   // 30 degrees
1396                skew_y: 1.0 / 3.0,   // 60 degrees
1397                translate_x: 10.0,
1398                translate_y: 20.0,
1399                ..Default::default()
1400            }
1401            .matrix()
1402            .map(round6)
1403            .elements()
1404        );
1405    }
1406
1407    // Expected created using the Python DecomposedTransform
1408    #[test]
1409    fn decomposed_rotate_around_to_matrix() {
1410        assert_eq!(
1411            [1.732051, 1.0, -0.5, 0.866025, 10.267949, 19.267949],
1412            DecomposedTransform {
1413                scale_x: 2.0,
1414                // 30 degrees = 1/6 * Pi.
1415                rotation: 1.0 / 6.0,
1416                translate_x: 10.0,
1417                translate_y: 20.0,
1418                center_x: 1.0,
1419                center_y: 2.0,
1420                ..Default::default()
1421            }
1422            .matrix()
1423            .map(round6)
1424            .elements()
1425        );
1426    }
1427
1428    #[test]
1429    fn read_multivar_store_region_list() {
1430        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
1431        let table = font.varc().unwrap();
1432        let varstore = table.multi_var_store().unwrap().unwrap();
1433        let regions = varstore.region_list().unwrap().regions();
1434
1435        let sparse_regions = regions
1436            .iter()
1437            .map(|r| {
1438                r.unwrap()
1439                    .axis_coordinates()
1440                    .iter()
1441                    .map(|a| {
1442                        let a = a.unwrap();
1443                        (
1444                            a.axis_index(),
1445                            a.start().to_f32(),
1446                            a.peak().to_f32(),
1447                            a.end().to_f32(),
1448                        )
1449                    })
1450                    .collect::<Vec<_>>()
1451            })
1452            .collect::<Vec<_>>();
1453
1454        // Check a sampling of the regions
1455        assert_eq!(
1456            vec![
1457                vec![(0, 0.0, 1.0, 1.0),],
1458                vec![(0, 0.0, 1.0, 1.0), (1, 0.0, 1.0, 1.0),],
1459                vec![(6, -1.0, -1.0, 0.0),],
1460            ],
1461            [0, 2, 38]
1462                .into_iter()
1463                .map(|i| sparse_regions[i].clone())
1464                .collect::<Vec<_>>()
1465        );
1466    }
1467
1468    #[test]
1469    fn read_multivar_store_delta_sets() {
1470        let font = FontRef::new(font_test_data::varc::CJK_6868).unwrap();
1471        let table = font.varc().unwrap();
1472        let varstore = table.multi_var_store().unwrap().unwrap();
1473        assert_eq!(
1474            vec![(3, 6), (33, 6), (10, 5), (25, 8),],
1475            varstore
1476                .variation_data()
1477                .iter()
1478                .map(|d| d.unwrap())
1479                .map(|d| (d.region_index_count(), d.delta_sets().unwrap().count()))
1480                .collect::<Vec<_>>()
1481        );
1482        assert_eq!(
1483            vec![-1, 33, 0, 0, 0, 0],
1484            varstore
1485                .variation_data()
1486                .get(0)
1487                .unwrap()
1488                .delta_set(5)
1489                .unwrap()
1490                .iter()
1491                .collect::<Vec<_>>()
1492        )
1493    }
1494}