Skip to main content

read_fonts/tables/layout/
feature_variations.rs

1//! Lookup variations (ISO/IEC 14496-22:2026, 6.2.11).
2
3use super::condition::Evaluator;
4use super::{
5    FeatureLookups, FeatureLookupsFlags, FeatureVariations, LookupConditionRecord,
6    LookupVariationRecord,
7};
8use crate::{
9    types::{Compatible, F2Dot14, FixedSize},
10    FontData,
11};
12use alloc::{collections::BTreeSet, vec::Vec};
13
14impl<'a> FeatureVariations<'a> {
15    /// Lookup variations, sorted by feature index; absent in version 1.0.
16    pub fn lookup_variation_records(&self) -> Option<&'a [LookupVariationRecord]> {
17        if !self.version().compatible((1, 1)) {
18            return None;
19        }
20        let data = self.offset_data();
21        if u64::from(self.feature_variation_record_count()) * 8
22            > data.len().saturating_sub(8) as u64
23        {
24            return None;
25        }
26        // A present, empty version-1.1 array is distinct from an absent field.
27        let count = usize::try_from(self.lookup_variation_record_count()?).ok()?;
28        let start = self.lookup_variation_record_count_byte_range().end;
29        let end = start.checked_add(count.checked_mul(LookupVariationRecord::RAW_BYTE_LEN)?)?;
30        data.read_array(start..end).ok()
31    }
32
33    /// Returns the table's lookup variations, or `None` if it has none.
34    ///
35    /// Only version 1.1 and later tables carry lookup variations, so for
36    /// other tables this is a version check. Records that are not strictly
37    /// sorted by feature index are ignored as a whole.
38    pub fn lookup_variations(&self) -> Option<LookupVariations<'a>> {
39        let records = self.lookup_variation_records()?;
40        let sorted = records
41            .windows(2)
42            .all(|pair| pair[0].feature_index() < pair[1].feature_index());
43        (!records.is_empty() && sorted).then(|| LookupVariations {
44            data: self.offset_data(),
45            records,
46        })
47    }
48}
49
50/// The lookup variations of a [`FeatureVariations`] table, which change the
51/// lookups of a feature depending on the location in design space.
52#[derive(Clone)]
53pub struct LookupVariations<'a> {
54    data: FontData<'a>,
55    records: &'a [LookupVariationRecord],
56}
57
58impl<'a> LookupVariations<'a> {
59    /// Applies the lookup variations of a feature at a location.
60    ///
61    /// `lookups` holds the feature's lookup indices. They are replaced,
62    /// unless the variations only add to them, by the lookups of each
63    /// condition record whose condition holds at `coords`. Format 2
64    /// conditions resolve their deltas through `delta`; see
65    /// [`Condition::evaluate`](super::Condition::evaluate).
66    ///
67    /// The added lookups may be unsorted and repeat ones already present.
68    /// All conditions of the feature share one evaluation budget.
69    ///
70    /// Returns `false`, leaving `lookups` unchanged, if the feature has no
71    /// lookup variations.
72    pub fn apply<E>(
73        &self,
74        feature_index: u16,
75        coords: &[F2Dot14],
76        delta: impl FnMut(u32) -> Result<f64, E>,
77        lookups: &mut Vec<u16>,
78    ) -> bool {
79        let Some(table) = self.feature_lookups(feature_index) else {
80            return false;
81        };
82        if !table
83            .flags()
84            .contains(FeatureLookupsFlags::ADD_DEFAULT_LOOKUPS)
85        {
86            lookups.clear();
87        }
88        // Only whether a condition holds is used, so a failed delta is simply
89        // a condition that does not.
90        let mut delta = delta;
91        let mut evaluator = Evaluator::new(coords, |index| {
92            delta(index).map_err(|_| crate::model::Error::Malformed)
93        });
94        let mut lists = LookupLists::new(&table);
95        for record in table.lookup_condition_records() {
96            if evaluator.evaluate_record(table.offset_data(), record).ok() == Some(true) {
97                lists.extend(record, lookups);
98            }
99        }
100        true
101    }
102
103    /// Adds the lookups of every condition record of a feature, as if each
104    /// condition held: the lookups the feature can use anywhere in design
105    /// space.
106    ///
107    /// Returns `false` if the feature has no lookup variations.
108    pub fn add_all(&self, feature_index: u16, lookups: &mut Vec<u16>) -> bool {
109        let Some(table) = self.feature_lookups(feature_index) else {
110            return false;
111        };
112        let mut lists = LookupLists::new(&table);
113        for record in table.lookup_condition_records() {
114            lists.extend(record, lookups);
115        }
116        true
117    }
118
119    /// The conditional lookups of a feature, if it has readable ones.
120    fn feature_lookups(&self, feature_index: u16) -> Option<FeatureLookups<'a>> {
121        let index = self
122            .records
123            .binary_search_by_key(&feature_index, LookupVariationRecord::feature_index)
124            .ok()?;
125        let record = &self.records[index];
126        if record.feature_lookups_offset().to_u32() == 0 {
127            return None;
128        }
129        let table = record.feature_lookups(self.data).ok()?;
130        // Checked before the records are read, whose range the generated
131        // code computes without checking for overflow.
132        let records_end = usize::try_from(table.lookup_condition_count())
133            .ok()?
134            .checked_mul(LookupConditionRecord::RAW_BYTE_LEN)?
135            .checked_add(table.lookup_condition_count_byte_range().end)?;
136        (table.version().major == 1 && records_end <= table.offset_data().len()).then_some(table)
137    }
138}
139
140/// The lookup index lists of a FeatureLookups table, each added at most once.
141///
142/// Condition records can share a list, so adding each one per record would
143/// let a small table produce an arbitrarily long result.
144struct LookupLists<'a> {
145    data: FontData<'a>,
146    added: BTreeSet<u32>,
147}
148
149impl<'a> LookupLists<'a> {
150    fn new(table: &FeatureLookups<'a>) -> Self {
151        Self {
152            data: table.offset_data(),
153            added: BTreeSet::new(),
154        }
155    }
156
157    /// Appends the lookups of a condition record, skipping a missing,
158    /// truncated or already added list.
159    fn extend(&mut self, record: &LookupConditionRecord, lookups: &mut Vec<u16>) {
160        let offset = record.lookup_index_list_offset().to_u32();
161        if offset == 0 || !self.added.insert(offset) {
162            return;
163        }
164        if let Ok(list) = record.lookup_index_list(self.data) {
165            let indices = list.lookup_indices();
166            if indices.len() == usize::from(list.lookup_index_count()) {
167                lookups.extend(indices.iter().map(|index| index.get()));
168            }
169        }
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use crate::{types::MajorMinor, FontRead, ReadError};
177
178    /// The conditional lookups of a feature, found through the raw records.
179    fn feature_lookups<'a>(
180        table: &FeatureVariations<'a>,
181        feature_index: u16,
182    ) -> Option<Result<FeatureLookups<'a>, ReadError>> {
183        let records = table.lookup_variation_records()?;
184        let record = records
185            .iter()
186            .find(|record| record.feature_index() == feature_index)?;
187        Some(record.feature_lookups(table.offset_data()))
188    }
189
190    /// A version 1.1 FeatureVariations table whose feature 2 has two
191    /// condition records: lookups 7 and 8 when axis 0 is at least 0.5, and
192    /// lookup 9 always (a null condition).
193    fn lookup_variation_table(flags: u16) -> alloc::vec::Vec<u8> {
194        let mut bytes = alloc::vec::Vec::new();
195        // FeatureVariations 1.1: no feature variation records, one lookup
196        // variation record.
197        bytes.extend([0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1]);
198        // LookupVariationRecord: feature 2, FeatureLookups at offset 18.
199        bytes.extend([0, 2, 0, 0, 0, 18]);
200        assert_eq!(bytes.len(), 18);
201        // FeatureLookups 1.0: flags, two condition records.
202        bytes.extend([0, 1, 0, 0]);
203        bytes.extend(flags.to_be_bytes());
204        bytes.extend([0, 0, 0, 2]);
205        // Record 1: condition at 26, lookup list at 34 (relative to
206        // FeatureLookups). Record 2: null condition, lookup list at 40.
207        bytes.extend([0, 0, 0, 26, 0, 0, 0, 34]);
208        bytes.extend([0, 0, 0, 0, 0, 0, 0, 40]);
209        assert_eq!(bytes.len() - 18, 26);
210        // ConditionFormat1: axis 0, min 0.5, max 1.0.
211        bytes.extend([0, 1, 0, 0, 0x20, 0, 0x40, 0]);
212        assert_eq!(bytes.len() - 18, 34);
213        // LookupIndexList [7, 8], then [9].
214        bytes.extend([0, 2, 0, 7, 0, 8]);
215        bytes.extend([0, 1, 0, 9]);
216        bytes
217    }
218
219    fn no_delta(_: u32) -> Result<f64, core::convert::Infallible> {
220        Ok(0.0)
221    }
222
223    #[test]
224    fn lookup_variations_replace_feature_lookups_by_location() {
225        let bytes = lookup_variation_table(0);
226        let table = FeatureVariations::read(bytes.as_slice().into()).unwrap();
227        let variations = table.lookup_variations().unwrap();
228        let mut lookups = alloc::vec![1, 2];
229        assert!(variations.apply(2, &[F2Dot14::from_f32(0.75)], no_delta, &mut lookups));
230        assert_eq!(lookups, [7, 8, 9]);
231        let mut lookups = alloc::vec![1, 2];
232        assert!(variations.apply(2, &[F2Dot14::from_f32(0.25)], no_delta, &mut lookups));
233        assert_eq!(lookups, [9]);
234        let mut lookups = alloc::vec![1, 2];
235        assert!(!variations.apply(3, &[F2Dot14::from_f32(0.75)], no_delta, &mut lookups));
236        assert_eq!(lookups, [1, 2]);
237        let mut lookups = alloc::vec![1];
238        assert!(variations.add_all(2, &mut lookups));
239        assert_eq!(lookups, [1, 7, 8, 9]);
240    }
241
242    #[test]
243    fn lookup_variations_can_add_to_default_lookups() {
244        let bytes = lookup_variation_table(FeatureLookupsFlags::ADD_DEFAULT_LOOKUPS.bits());
245        let table = FeatureVariations::read(bytes.as_slice().into()).unwrap();
246        let mut lookups = alloc::vec![1, 2];
247        assert!(table.lookup_variations().unwrap().apply(
248            2,
249            &[F2Dot14::from_f32(0.75)],
250            no_delta,
251            &mut lookups
252        ));
253        assert_eq!(lookups, [1, 2, 7, 8, 9]);
254    }
255
256    #[test]
257    fn lookup_variations_add_a_shared_list_once() {
258        let mut bytes = alloc::vec::Vec::new();
259        // FeatureVariations 1.1 with one lookup variation record for
260        // feature 2, whose FeatureLookups table is at 18.
261        bytes.extend([0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 18]);
262        // FeatureLookups 1.0: three unconditional records sharing the list
263        // at 34.
264        bytes.extend([0, 1, 0, 0, 0, 0, 0, 0, 0, 3]);
265        for _ in 0..3 {
266            bytes.extend([0, 0, 0, 0, 0, 0, 0, 34]);
267        }
268        bytes.extend([0, 2, 0, 7, 0, 8]);
269        let table = FeatureVariations::read(bytes.as_slice().into()).unwrap();
270        let variations = table.lookup_variations().unwrap();
271        let mut lookups = alloc::vec![];
272        assert!(variations.add_all(2, &mut lookups));
273        assert_eq!(lookups, [7, 8]);
274        let mut lookups = alloc::vec![];
275        assert!(variations.apply(2, &[], no_delta, &mut lookups));
276        assert_eq!(lookups, [7, 8]);
277    }
278
279    #[test]
280    fn lookup_variations_absent_or_unsorted() {
281        // Version 1.0 has none.
282        let v1_0 = [0, 1, 0, 0, 0, 0, 0, 0];
283        let table = FeatureVariations::read(v1_0.as_slice().into()).unwrap();
284        assert!(table.lookup_variations().is_none());
285        // Version 1.1 without records has none.
286        let v1_1 = [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0];
287        let table = FeatureVariations::read(v1_1.as_slice().into()).unwrap();
288        assert!(table.lookup_variations().is_none());
289        // Records out of order are ignored.
290        let unsorted = [
291            0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0,
292        ];
293        let table = FeatureVariations::read(unsorted.as_slice().into()).unwrap();
294        assert!(table.lookup_variations().is_none());
295    }
296
297    #[test]
298    fn lookup_variations_versioned_empty_arrays() {
299        let v1_0 = [0, 1, 0, 0, 0, 0, 0, 0];
300        let table = FeatureVariations::read(v1_0.as_slice().into()).unwrap();
301        assert_eq!(table.version(), MajorMinor::VERSION_1_0);
302        assert_eq!(table.lookup_variation_record_count(), None);
303        assert!(table.lookup_variation_records().is_none());
304        assert!(feature_lookups(&table, 0).is_none());
305
306        let v1_1 = [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0];
307        let table = FeatureVariations::read(v1_1.as_slice().into()).unwrap();
308        assert_eq!(table.version(), MajorMinor::VERSION_1_1);
309        assert_eq!(table.lookup_variation_record_count(), Some(0));
310        assert_eq!(table.lookup_variation_records().unwrap().len(), 0);
311        assert!(feature_lookups(&table, 0).is_none());
312    }
313
314    #[test]
315    fn lookup_variations_truncated_arrays_and_invalid_offsets() {
316        let bytes = [
317            0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 3, 0xff, 0xff, 0xff, 0xff,
318        ];
319        for len in 8..bytes.len() {
320            let table = FeatureVariations::read(bytes[..len].into()).unwrap();
321            assert!(table.lookup_variation_records().is_none());
322            assert!(feature_lookups(&table, 3).is_none());
323        }
324        let table = FeatureVariations::read(bytes.as_slice().into()).unwrap();
325        assert_eq!(table.lookup_variation_records().unwrap().len(), 1);
326        assert_eq!(
327            feature_lookups(&table, 3).unwrap().err(),
328            Some(ReadError::OutOfBounds)
329        );
330        assert!(feature_lookups(&table, 2).is_none());
331        assert!(feature_lookups(&table, 4).is_none());
332    }
333}