Skip to main content

read_fonts/tables/layout/
condition.rs

1//! Shared evaluation of layout and VARC conditions.
2
3use super::{Condition, ConditionSet, LookupConditionRecord};
4use crate::limits::MAX_RECURSION_DEPTH;
5use crate::tables::variations::{DeltaSetIndex, ItemVariationStore, NO_VARIATION_INDEX};
6use crate::types::F2Dot14;
7use crate::{model::Error, FontData, FontRead, ReadError};
8
9#[cfg(test)]
10#[path = "condition_tests.rs"]
11mod tests;
12
13/// Returns a delta function for [`Condition::evaluate`] that reads `store`,
14/// usually the GDEF variation store.
15///
16/// A missing store or delta set has a delta of zero.
17pub fn store_deltas<'a>(
18    store: Option<&'a ItemVariationStore<'a>>,
19    coords: &'a [F2Dot14],
20) -> impl Fn(u32) -> Result<f64, Error> + Copy + 'a {
21    move |index| {
22        Ok(store
23            .and_then(|store| {
24                store.compute_delta(
25                    DeltaSetIndex {
26                        outer: (index >> 16) as u16,
27                        inner: index as u16,
28                    },
29                    coords,
30                )
31            })
32            .unwrap_or_default()
33            .to_f64())
34    }
35}
36
37impl Condition<'_> {
38    /// Evaluates this condition at the given normalized coordinates.
39    ///
40    /// Missing coordinates are zero. `delta` resolves format-2 variation
41    /// indices using the caller's variation store; it is not called for
42    /// [`NO_VARIATION_INDEX`]. The value is tested before rounding.
43    ///
44    /// A condition of an unknown format is false. Malformed children and
45    /// evaluation limits return errors, including beneath a NOT condition.
46    /// AND and OR conditions short-circuit.
47    pub fn evaluate(
48        &self,
49        coords: &[F2Dot14],
50        delta: impl FnMut(u32) -> Result<f64, Error>,
51    ) -> Result<bool, Error> {
52        Evaluator::new(coords, delta).evaluate(self, MAX_RECURSION_DEPTH)
53    }
54}
55
56impl ConditionSet<'_> {
57    /// Evaluates all conditions in this set, sharing one total-work budget.
58    ///
59    /// A null condition offset is unconditional. See [`Condition::evaluate`]
60    /// for variation-delta resolution and error handling.
61    pub fn evaluate(
62        &self,
63        coords: &[F2Dot14],
64        delta: impl FnMut(u32) -> Result<f64, Error>,
65    ) -> Result<bool, Error> {
66        let offsets = self.condition_offsets();
67        if offsets.len() != usize::from(self.condition_count()) {
68            return Err(Error::Malformed);
69        }
70        let mut evaluator = Evaluator::new(coords, delta);
71        for offset in offsets {
72            if !evaluator.evaluate_offset(
73                self.offset_data(),
74                offset.get().to_u32(),
75                MAX_RECURSION_DEPTH,
76            )? {
77                return Ok(false);
78            }
79        }
80        Ok(true)
81    }
82}
83
84impl LookupConditionRecord {
85    /// Evaluates this record's condition, relative to its FeatureLookups table.
86    ///
87    /// A null offset is unconditional. See [`Condition::evaluate`] for
88    /// variation-delta resolution and error handling.
89    pub fn evaluate(
90        &self,
91        data: FontData<'_>,
92        coords: &[F2Dot14],
93        delta: impl FnMut(u32) -> Result<f64, Error>,
94    ) -> Result<bool, Error> {
95        Evaluator::new(coords, delta).evaluate_record(data, self)
96    }
97}
98
99/// Evaluates conditions under one total-work budget.
100pub(super) struct Evaluator<'a, F> {
101    coords: &'a [F2Dot14],
102    delta: F,
103    remaining_ops: usize,
104}
105
106impl<'a, F: FnMut(u32) -> Result<f64, Error>> Evaluator<'a, F> {
107    pub(super) fn new(coords: &'a [F2Dot14], delta: F) -> Self {
108        Self {
109            coords,
110            delta,
111            // Enough for a full flat ConditionSet, while bounding repeated
112            // visits when several offsets refer to the same child.
113            remaining_ops: usize::from(u16::MAX) + 1,
114        }
115    }
116
117    /// Evaluates a lookup condition record, relative to its FeatureLookups
118    /// table.
119    pub(super) fn evaluate_record(
120        &mut self,
121        data: FontData<'_>,
122        record: &LookupConditionRecord,
123    ) -> Result<bool, Error> {
124        self.evaluate_offset(
125            data,
126            record.condition_offset().offset().to_u32(),
127            MAX_RECURSION_DEPTH,
128        )
129    }
130
131    fn evaluate_offset(
132        &mut self,
133        data: FontData<'_>,
134        offset: u32,
135        depth: usize,
136    ) -> Result<bool, Error> {
137        if offset == 0 {
138            return Ok(true);
139        }
140        let data = data.split_off(offset as usize).ok_or(Error::Malformed)?;
141        let condition = match Condition::read(data) {
142            Ok(condition) => condition,
143            // The spec treats a condition of an unknown format as false.
144            Err(ReadError::InvalidFormat(_)) => return Ok(false),
145            Err(error) => return Err(error.into()),
146        };
147        self.evaluate(&condition, depth)
148    }
149
150    fn evaluate(&mut self, condition: &Condition<'_>, depth: usize) -> Result<bool, Error> {
151        if depth == 0 || self.remaining_ops == 0 {
152            return Err(Error::LimitExceeded);
153        }
154        self.remaining_ops -= 1;
155        Ok(match condition {
156            Condition::Format1AxisRange(condition) => {
157                let coord = self
158                    .coords
159                    .get(usize::from(condition.axis_index()))
160                    .copied()
161                    .unwrap_or_default();
162                coord >= condition.filter_range_min_value()
163                    && coord <= condition.filter_range_max_value()
164            }
165            Condition::Format2VariableValue(condition) => {
166                let index = condition.var_index();
167                let delta = if index == NO_VARIATION_INDEX {
168                    0.0
169                } else {
170                    (self.delta)(index)?
171                };
172                f64::from(condition.default_value()) + delta > 0.0
173            }
174            Condition::Format3And(condition) => {
175                let offsets = condition.condition_offsets();
176                if offsets.len() != usize::from(condition.condition_count()) {
177                    return Err(Error::Malformed);
178                }
179                for offset in offsets {
180                    if !self.evaluate_offset(
181                        condition.offset_data(),
182                        offset.get().to_u32(),
183                        depth - 1,
184                    )? {
185                        return Ok(false);
186                    }
187                }
188                true
189            }
190            Condition::Format4Or(condition) => {
191                let offsets = condition.condition_offsets();
192                if offsets.len() != usize::from(condition.condition_count()) {
193                    return Err(Error::Malformed);
194                }
195                for offset in offsets {
196                    if self.evaluate_offset(
197                        condition.offset_data(),
198                        offset.get().to_u32(),
199                        depth - 1,
200                    )? {
201                        return Ok(true);
202                    }
203                }
204                false
205            }
206            Condition::Format5Negate(condition) => !self.evaluate_offset(
207                condition.offset_data(),
208                condition.condition_offset().to_u32(),
209                depth - 1,
210            )?,
211        })
212    }
213}