Skip to main content

harfrust/aat/
common.rs

1use super::layout::DELETED_GLYPH;
2use super::map::RangeFlags;
3use crate::buffer::{Buffer, HB_BUFFER_SCRATCH_FLAG_SHAPER0};
4use crate::ot::apply::MappingCache;
5use crate::plan::ShapePlan;
6use crate::set_digest::SetDigest;
7use crate::LayoutData;
8use crate::Mask;
9use crate::Scale;
10use crate::U32Set;
11use alloc::vec::Vec;
12use read_fonts::tables::aat::*;
13use read_fonts::types::{FixedSize, GlyphId};
14use read_fonts::FontData;
15
16pub const HB_BUFFER_SCRATCH_FLAG_AAT_HAS_DELETED: u32 = HB_BUFFER_SCRATCH_FLAG_SHAPER0;
17
18pub(crate) const START_OF_TEXT: u16 = 0;
19
20pub(crate) type ClassCache = MappingCache;
21
22pub(crate) fn get_class<T: bytemuck::AnyBitPattern + FixedSize>(
23    machine: &ExtendedStateTable<'_, T>,
24    glyph_id: GlyphId,
25    cache: &ClassCache,
26) -> u16 {
27    if let Some(klass) = cache.get(glyph_id.to_u32()) {
28        return klass as u16;
29    }
30    let klass = machine
31        .class(glyph_id)
32        .unwrap_or(class::OUT_OF_BOUNDS as u16);
33    cache.set(glyph_id.to_u32(), klass as u32);
34    klass
35}
36
37/// HB: hb_aat_apply_context_t
38///
39/// See <https://github.com/harfbuzz/harfbuzz/blob/2c22a65f0cb99544c36580b9703a43b5dc97a9e1/src/hb-aat-layout-common.hh#L108>
40#[doc(alias = "hb_aat_apply_context_t")]
41pub struct AatApplyContext<'a, 'f, 'c> {
42    pub plan: &'a ShapePlan,
43    pub layout: LayoutData<'a>,
44    pub scale: Scale,
45    #[cfg(feature = "tracing")]
46    pub font: &'a crate::ShaperFont<'f, 'c>,
47    #[cfg(not(feature = "tracing"))]
48    font_lifetimes: core::marker::PhantomData<(&'f (), &'c ())>,
49    pub buffer: &'a mut Buffer,
50    pub has_glyph_classes: bool,
51    pub range_flags: Option<&'a [RangeFlags]>,
52    pub subtable_flags: Mask,
53    pub(crate) buffer_is_reversed: bool,
54    // Caches
55    using_buffer_glyph_set: bool,
56    /// Whether the buffer's digest is current, to rule out subtables cheaply.
57    using_buffer_digest: bool,
58    pub(crate) first_set: Option<&'a U32Set>,
59    /// A digest of `first_set`.
60    pub(crate) first_digest: SetDigest,
61    pub(crate) second_set: Option<&'a U32Set>,
62    pub(crate) machine_class_cache: Option<&'a ClassCache>,
63    pub(crate) start_end_safe_to_break: u64,
64    pub(crate) safe_to_break: SafeToBreak<'a>,
65}
66
67// The font's lifetimes are named for the font that tracing takes.
68#[cfg_attr(not(feature = "tracing"), allow(clippy::elidable_lifetime_names))]
69impl<'a, 'f, 'c> AatApplyContext<'a, 'f, 'c> {
70    pub fn new(
71        plan: &'a ShapePlan,
72        layout: LayoutData<'a>,
73        scale: Scale,
74        buffer: &'a mut Buffer,
75        #[cfg(feature = "tracing")] font: &'a crate::ShaperFont<'f, 'c>,
76    ) -> Self {
77        Self {
78            plan,
79            layout,
80            scale,
81            #[cfg(not(feature = "tracing"))]
82            font_lifetimes: core::marker::PhantomData,
83            buffer,
84            #[cfg(feature = "tracing")]
85            font,
86            has_glyph_classes: layout.ot.has_glyph_classes(),
87            range_flags: None,
88            subtable_flags: 0,
89            buffer_is_reversed: false,
90            using_buffer_glyph_set: false,
91            using_buffer_digest: false,
92            first_set: None,
93            first_digest: SetDigest::full(),
94            second_set: None,
95            machine_class_cache: None,
96            start_end_safe_to_break: 0,
97            safe_to_break: SafeToBreak::default(),
98        }
99    }
100
101    #[inline(always)]
102    pub(crate) fn scale_x(&self, value: i32) -> i32 {
103        self.scale.scale_x(value)
104    }
105
106    #[inline(always)]
107    pub(crate) fn scale_y(&self, value: i32) -> i32 {
108        self.scale.scale_y(value)
109    }
110
111    pub(crate) fn reverse_buffer(&mut self) {
112        self.buffer.reverse();
113        self.buffer_is_reversed = !self.buffer_is_reversed;
114    }
115
116    pub(crate) fn setup_buffer_glyph_set(&mut self) {
117        self.using_buffer_glyph_set = self.buffer.len >= 4;
118
119        if self.using_buffer_glyph_set {
120            self.buffer.update_glyph_set();
121        }
122    }
123
124    /// Prepares the digest that rules out subtables cheaply, if a table has
125    /// enough subtables to repay building it.
126    pub(crate) fn setup_buffer_digest(&mut self, subtable_count: usize) {
127        self.using_buffer_digest = subtable_count >= MIN_DIGESTED_SUBTABLES;
128        if self.using_buffer_digest {
129            self.buffer.update_digest();
130        }
131    }
132
133    pub(crate) fn buffer_intersects_machine(&self) -> bool {
134        if let Some(first_set) = &self.first_set {
135            if self.using_buffer_digest && !self.buffer.digest.may_intersect(&self.first_digest) {
136                return false;
137            }
138            if self.using_buffer_glyph_set {
139                return self.buffer.glyph_set.intersects_set(first_set);
140            }
141            for info in &self.buffer.info {
142                if first_set.contains(info.glyph_id) {
143                    return true;
144                }
145            }
146            false
147        } else {
148            true
149        }
150    }
151
152    pub fn output_glyph(&mut self, glyph: u32) -> Option<()> {
153        self.buffer.digest.add(glyph);
154        if self.using_buffer_glyph_set {
155            self.buffer.glyph_set.insert(glyph);
156        }
157
158        // Insertion state machines can emit glyphs during the end-of-text
159        // transition, when there is no current input glyph. output_glyph()
160        // supports that by copying the previous output glyph's metadata.
161        // Apply the AAT metadata to that new output glyph instead of indexing
162        // past the end of the input buffer.
163        let at_end = self.buffer.idx == self.buffer.len;
164        if at_end {
165            let out_len = self.buffer.out_len;
166            self.buffer.output_glyph(glyph);
167            if self.buffer.out_len == out_len {
168                return Some(());
169            }
170        }
171
172        if glyph == DELETED_GLYPH {
173            self.buffer.scratch_flags |= HB_BUFFER_SCRATCH_FLAG_AAT_HAS_DELETED;
174            let info = if at_end {
175                self.buffer.prev_mut()?
176            } else {
177                self.buffer.cur_mut(0)?
178            };
179            info.set_aat_deleted();
180        } else {
181            if self.has_glyph_classes {
182                let glyph_props = self.layout.ot.glyph_props(glyph.into());
183                let info = if at_end {
184                    self.buffer.prev_mut()?
185                } else {
186                    self.buffer.cur_mut(0)?
187                };
188                info.set_glyph_props(glyph_props);
189            }
190        }
191        if !at_end {
192            self.buffer.output_glyph(glyph);
193        }
194        Some(())
195    }
196
197    pub fn replace_glyph(&mut self, glyph: u32) -> Option<()> {
198        if glyph == DELETED_GLYPH {
199            self.buffer.scratch_flags |= HB_BUFFER_SCRATCH_FLAG_AAT_HAS_DELETED;
200            self.buffer.cur_mut(0)?.set_aat_deleted();
201        }
202
203        self.buffer.digest.add(glyph);
204        if self.using_buffer_glyph_set {
205            self.buffer.glyph_set.insert(glyph);
206        }
207        if self.has_glyph_classes {
208            self.buffer
209                .cur_mut(0)?
210                .set_glyph_props(self.layout.ot.glyph_props(glyph.into()));
211        }
212        self.buffer.replace_glyph(glyph);
213        Some(())
214    }
215
216    pub fn delete_glyph(&mut self) -> Option<()> {
217        self.buffer.scratch_flags |= HB_BUFFER_SCRATCH_FLAG_AAT_HAS_DELETED;
218        self.buffer.cur_mut(0)?.set_aat_deleted();
219        self.buffer.digest.add(DELETED_GLYPH);
220        if self.using_buffer_glyph_set {
221            self.buffer.glyph_set.insert(DELETED_GLYPH);
222        }
223        self.buffer.replace_glyph(DELETED_GLYPH);
224        Some(())
225    }
226
227    #[inline(always)]
228    pub fn replace_glyph_inplace(&mut self, i: usize, glyph: u32) -> Option<()> {
229        let info = self.buffer.info.get_mut(i)?;
230        info.glyph_id = glyph;
231        if glyph == DELETED_GLYPH {
232            self.buffer.scratch_flags |= HB_BUFFER_SCRATCH_FLAG_AAT_HAS_DELETED;
233            info.set_aat_deleted();
234        }
235        self.buffer.digest.add(glyph);
236        if self.using_buffer_glyph_set {
237            self.buffer.glyph_set.insert(glyph);
238        }
239        if self.has_glyph_classes {
240            info.set_glyph_props(self.layout.ot.glyph_props(glyph.into()));
241        }
242        Some(())
243    }
244}
245
246/// Tables with fewer subtables than this skip the buffer digest.
247const MIN_DIGESTED_SUBTABLES: usize = 4;
248
249/// A digest of the glyphs in `set`.
250pub(crate) fn set_digest(set: &U32Set) -> SetDigest {
251    let mut digest = SetDigest::new();
252    for range in set.iter_ranges() {
253        digest.add_range(*range.start(), *range.end());
254    }
255    digest
256}
257
258/// Per-table acceleration for the drive loops' safe-to-break computation.
259///
260/// The data for every state-machine subtable in one AAT table is stored in
261/// two packed vectors. Each top-level subtable cache carries a compact
262/// descriptor for its ranges. This avoids two `Vec` allocations in every
263/// subtable cache while retaining O(classes) + O(states) storage.
264#[derive(Default)]
265pub(crate) struct SafeToBreakAccel {
266    wouldbe: Vec<u16>,
267    eot_tail: Vec<u64>,
268}
269
270#[derive(Clone, Copy, Default)]
271pub(crate) struct SafeToBreakSubtable {
272    wouldbe_start: u32,
273    wouldbe_end: u32,
274    eot_tail_start: u32,
275    eot_tail_end: u32,
276}
277
278/// The slice of [`SafeToBreakAccel`] belonging to the active subtable.
279#[derive(Clone, Copy, Default)]
280pub(crate) struct SafeToBreak<'a> {
281    n_classes: u32,
282    /// Per class: `entry(START_OF_TEXT, class)` packed as 15 bits of
283    /// new state with the advance bit on top when present and
284    /// non-actionable, `!0` otherwise — so condition 2c is a single
285    /// compare. Real machines' state counts fit 15 bits.
286    wouldbe: &'a [u16],
287    /// Condition-3 bits for states 64 and up; states below 64 keep
288    /// using the `start_end_safe_to_break` word. Empty for machines
289    /// with at most 64 states.
290    eot_tail: &'a [u64],
291}
292
293pub(crate) const WOULDBE_NONE: u16 = !0;
294
295#[inline(always)]
296pub(crate) fn pack_wouldbe(new_state: u16, advance: bool) -> u16 {
297    // States fit 15 bits in any real font. A pathological new state
298    // that doesn't can alias the sentinel and misreport condition 2c,
299    // which only perturbs unsafe-to-break flags -- not worth runtime
300    // checks on this path.
301    new_state | ((advance as u16) << 15)
302}
303
304impl SafeToBreak<'_> {
305    /// Condition 2c: would starting from the start state on this class
306    /// take a non-actionable transition to the same state, advancing
307    /// the same way?
308    #[inline(always)]
309    pub(crate) fn wouldbe_matches(&self, class: u16, next_state: u16, advance: bool) -> bool {
310        let mut class = class as usize;
311        if class >= self.n_classes as usize {
312            class = class::OUT_OF_BOUNDS as usize;
313        }
314        self.wouldbe.get(class).copied() == Some(pack_wouldbe(next_state, advance))
315    }
316
317    /// Condition 3 for states 64 and up: no end-of-text action can fire
318    /// out of this state.
319    #[inline(always)]
320    pub(crate) fn eot_safe_high(&self, state: u16) -> bool {
321        let ix = (state - 64) as usize;
322        self.eot_tail
323            .get(ix / 64)
324            .is_some_and(|word| word & (1 << (ix % 64)) != 0)
325    }
326}
327
328impl SafeToBreakAccel {
329    /// Returns a view of the acceleration data described by a top-level
330    /// subtable cache.
331    pub(crate) fn subtable(&self, subtable: SafeToBreakSubtable) -> Option<SafeToBreak<'_>> {
332        let wouldbe_start = subtable.wouldbe_start as usize;
333        let wouldbe_end = subtable.wouldbe_end as usize;
334        let eot_tail_start = subtable.eot_tail_start as usize;
335        let eot_tail_end = subtable.eot_tail_end as usize;
336
337        Some(SafeToBreak {
338            n_classes: subtable.wouldbe_end - subtable.wouldbe_start,
339            wouldbe: self.wouldbe.get(wouldbe_start..wouldbe_end)?,
340            eot_tail: self.eot_tail.get(eot_tail_start..eot_tail_end)?,
341        })
342    }
343
344    /// Describes a subtable that does not contain a state machine.
345    pub(crate) fn empty_subtable(&self) -> SafeToBreakSubtable {
346        SafeToBreakSubtable {
347            wouldbe_start: self.wouldbe.len() as u32,
348            wouldbe_end: self.wouldbe.len() as u32,
349            eot_tail_start: self.eot_tail.len() as u32,
350            eot_tail_end: self.eot_tail.len() as u32,
351        }
352    }
353
354    /// Appends the data for an extended state table whose machine
355    /// starts at the beginning of `data`. The predicates mirror the
356    /// subtable kind's notion of actionable/advancing entries.
357    #[inline(never)]
358    pub(crate) fn build_extended<T: bytemuck::AnyBitPattern + FixedSize>(
359        &mut self,
360        machine: &ExtendedStateTable<T>,
361        data: &[u8],
362        is_actionable: &dyn Fn(&StateEntry<T>) -> bool,
363        can_advance: &dyn Fn(&StateEntry<T>) -> bool,
364    ) -> SafeToBreakSubtable {
365        let n_classes = machine.n_classes;
366        let wouldbe_start = self.wouldbe.len();
367        let eot_tail_start = self.eot_tail.len();
368
369        // Cover the OUT_OF_BOUNDS column the runtime clamp can select
370        // even on degenerate machines; entry() applies the same clamp
371        // internally, so the aliasing matches.
372        // Classes are u16 values, so columns past 0x10000 are
373        // unreachable and need no slots.
374        let wouldbe_len = n_classes
375            .max(class::OUT_OF_BOUNDS as usize + 1)
376            .min(1 << 16);
377        self.wouldbe.reserve(wouldbe_len);
378        for class in 0..wouldbe_len {
379            self.wouldbe
380                .push(match machine.entry(START_OF_TEXT, class as u16) {
381                    Ok(entry) if !is_actionable(&entry) => {
382                        pack_wouldbe(entry.new_state, can_advance(&entry))
383                    }
384                    _ => WOULDBE_NONE,
385                });
386        }
387
388        // The state array runs from its offset to the end of the
389        // subtable, matching how the table reader slices it; states
390        // beyond it fail entry() and stay unsafe, like the probes they
391        // replace.
392        if n_classes > 0 {
393            if let Ok(parts) = StateTableParts::read(FontData::new(data)) {
394                let n_cells = data.len().saturating_sub(parts.state_array_offset as usize)
395                    / u16::RAW_BYTE_LEN;
396                let n_rows = n_cells.div_ceil(n_classes).min(u16::MAX as usize + 1);
397                if n_rows > 64 {
398                    let eot_tail_start = self.eot_tail.len();
399                    self.eot_tail
400                        .resize(eot_tail_start + (n_rows - 64).div_ceil(64), 0);
401                    for state in 64..n_rows {
402                        if let Ok(entry) =
403                            machine.entry(state as u16, u16::from(class::END_OF_TEXT))
404                        {
405                            if !is_actionable(&entry) {
406                                let ix = state - 64;
407                                self.eot_tail[eot_tail_start + ix / 64] |= 1 << (ix % 64);
408                            }
409                        }
410                    }
411                }
412            }
413        }
414
415        SafeToBreakSubtable::new(
416            wouldbe_len,
417            wouldbe_start,
418            self.wouldbe.len(),
419            eot_tail_start,
420            self.eot_tail.len(),
421        )
422    }
423
424    /// The legacy (`kern` Format1) counterpart of [`Self::build_extended`]:
425    /// one-byte state cells and u8 classes.
426    #[inline(never)]
427    pub(crate) fn build_legacy<T: bytemuck::AnyBitPattern + FixedSize>(
428        &mut self,
429        machine: &StateTable<T>,
430        is_actionable: &dyn Fn(&StateEntry<T>) -> bool,
431        can_advance: &dyn Fn(&StateEntry<T>) -> bool,
432    ) -> SafeToBreakSubtable {
433        let n_classes = machine.header.state_size() as usize;
434        let wouldbe_start = self.wouldbe.len();
435        let eot_tail_start = self.eot_tail.len();
436
437        let wouldbe_len = n_classes.max(class::OUT_OF_BOUNDS as usize + 1).min(1 << 8);
438        self.wouldbe.reserve(wouldbe_len);
439        for class in 0..wouldbe_len {
440            self.wouldbe
441                .push(match machine.entry(START_OF_TEXT, class as u8) {
442                    Ok(entry) if !is_actionable(&entry) => {
443                        pack_wouldbe(entry.new_state, can_advance(&entry))
444                    }
445                    _ => WOULDBE_NONE,
446                });
447        }
448
449        if n_classes > 0 {
450            if let Ok(state_array) = machine.header.state_array() {
451                let n_cells = state_array.data().len();
452                let n_rows = n_cells.div_ceil(n_classes).min(u16::MAX as usize + 1);
453                if n_rows > 64 {
454                    let eot_tail_start = self.eot_tail.len();
455                    self.eot_tail
456                        .resize(eot_tail_start + (n_rows - 64).div_ceil(64), 0);
457                    for state in 64..n_rows {
458                        if let Ok(entry) = machine.entry(state as u16, class::END_OF_TEXT) {
459                            if !is_actionable(&entry) {
460                                let ix = state - 64;
461                                self.eot_tail[eot_tail_start + ix / 64] |= 1 << (ix % 64);
462                            }
463                        }
464                    }
465                }
466            }
467        }
468
469        SafeToBreakSubtable::new(
470            wouldbe_len,
471            wouldbe_start,
472            self.wouldbe.len(),
473            eot_tail_start,
474            self.eot_tail.len(),
475        )
476    }
477}
478
479impl SafeToBreakSubtable {
480    fn new(
481        wouldbe_len: usize,
482        wouldbe_start: usize,
483        wouldbe_end: usize,
484        eot_tail_start: usize,
485        eot_tail_end: usize,
486    ) -> Self {
487        debug_assert_eq!(wouldbe_end - wouldbe_start, wouldbe_len);
488        Self {
489            wouldbe_start: wouldbe_start as u32,
490            wouldbe_end: wouldbe_end as u32,
491            eot_tail_start: eot_tail_start as u32,
492            eot_tail_end: eot_tail_end as u32,
493        }
494    }
495}
496
497// Keep one closure type for the morx and kerx class-set filters so that
498// their lookup collectors share a monomorphization.
499pub(crate) fn class_set_filter(classes: &U32Set) -> impl Fn(u16) -> bool + '_ {
500    |class| classes.contains(u32::from(class))
501}
502
503pub trait TypedCollectGlyphs<T: LookupValue> {
504    /// Add all indices into `set`.
505    fn collect_glyphs(&self, set: &mut U32Set, num_glyphs: u32) {
506        self.collect_glyphs_filtered::<_>(set, num_glyphs, |_| true);
507    }
508
509    /// For each valid index, read the value of type `T`.
510    /// If `filter(&value)` returns true, insert the index into `set`.
511    fn collect_glyphs_filtered<F>(&self, _set: &mut U32Set, _num_glyphs: u32, _filter: F)
512    where
513        F: Fn(T) -> bool;
514}
515
516impl<T> TypedCollectGlyphs<T> for TypedLookup<'_, T>
517where
518    T: LookupValue,
519{
520    fn collect_glyphs(&self, set: &mut U32Set, num_glyphs: u32) {
521        self.lookup.collect_glyphs::<T>(set, num_glyphs);
522    }
523    fn collect_glyphs_filtered<F>(&self, set: &mut U32Set, num_glyphs: u32, filter: F)
524    where
525        F: Fn(T) -> bool,
526    {
527        self.lookup
528            .collect_glyphs_filtered::<T, F>(set, num_glyphs, filter);
529    }
530}
531
532pub trait CollectGlyphs {
533    /// Add all indices into `set`.
534    fn collect_glyphs<T>(&self, set: &mut U32Set, num_glyphs: u32)
535    where
536        T: LookupValue,
537    {
538        self.collect_glyphs_filtered::<T, _>(set, num_glyphs, |_| true);
539    }
540
541    /// For each valid index, read the value of type `T`.
542    /// If `filter(&value)` returns true, insert the index into `set`.
543    fn collect_glyphs_filtered<T, F>(&self, _set: &mut U32Set, _num_glyphs: u32, _filter: F)
544    where
545        T: LookupValue,
546        F: Fn(T) -> bool;
547}
548
549impl CollectGlyphs for Lookup<'_> {
550    fn collect_glyphs<T>(&self, set: &mut U32Set, num_glyphs: u32)
551    where
552        T: LookupValue,
553    {
554        match self {
555            Lookup::Format0(lookup) => lookup.collect_glyphs::<T>(set, num_glyphs),
556            Lookup::Format2(lookup) => lookup.collect_glyphs::<T>(set, num_glyphs),
557            Lookup::Format4(lookup) => lookup.collect_glyphs::<T>(set, num_glyphs),
558            Lookup::Format6(lookup) => lookup.collect_glyphs::<T>(set, num_glyphs),
559            Lookup::Format8(lookup) => lookup.collect_glyphs::<T>(set, num_glyphs),
560            Lookup::Format10(lookup) => lookup.collect_glyphs::<T>(set, num_glyphs),
561        }
562    }
563    // Keep the shared collector out of the state-machine cache constructors.
564    #[inline(never)]
565    fn collect_glyphs_filtered<T, F>(&self, set: &mut U32Set, num_glyphs: u32, filter: F)
566    where
567        T: LookupValue,
568        F: Fn(T) -> bool,
569    {
570        match self {
571            Lookup::Format0(lookup) => {
572                lookup.collect_glyphs_filtered::<T, F>(set, num_glyphs, filter);
573            }
574            Lookup::Format2(lookup) => {
575                lookup.collect_glyphs_filtered::<T, F>(set, num_glyphs, filter);
576            }
577            Lookup::Format4(lookup) => {
578                lookup.collect_glyphs_filtered::<T, F>(set, num_glyphs, filter);
579            }
580            Lookup::Format6(lookup) => {
581                lookup.collect_glyphs_filtered::<T, F>(set, num_glyphs, filter);
582            }
583            Lookup::Format8(lookup) => {
584                lookup.collect_glyphs_filtered::<T, F>(set, num_glyphs, filter);
585            }
586            Lookup::Format10(lookup) => {
587                lookup.collect_glyphs_filtered::<T, F>(set, num_glyphs, filter);
588            }
589        }
590    }
591}
592
593impl CollectGlyphs for Lookup0<'_> {
594    fn collect_glyphs<T>(&self, set: &mut U32Set, num_glyphs: u32)
595    where
596        T: LookupValue,
597    {
598        set.insert_range(0..=num_glyphs.saturating_sub(1));
599    }
600    fn collect_glyphs_filtered<T, F>(&self, set: &mut U32Set, num_glyphs: u32, filter: F)
601    where
602        T: LookupValue,
603        F: Fn(T) -> bool,
604    {
605        if let Ok(values) = self.values::<T>() {
606            for (i, value) in values.iter().take(num_glyphs as usize).enumerate() {
607                if filter(value.get()) {
608                    set.insert(i as u32);
609                }
610            }
611        }
612    }
613}
614impl CollectGlyphs for Lookup2<'_> {
615    fn collect_glyphs_filtered<T, F>(&self, set: &mut U32Set, _num_glyphs: u32, filter: F)
616    where
617        T: LookupValue,
618        F: Fn(T) -> bool,
619    {
620        if let Ok(segments) = self.segments::<T>() {
621            for segment in segments {
622                let value = segment.value;
623                if filter(value.get()) {
624                    if segment.first_glyph.get() as u32 == DELETED_GLYPH {
625                        continue;
626                    }
627                    set.insert_range(
628                        segment.first_glyph.get() as u32..=segment.last_glyph.get() as u32,
629                    );
630                }
631            }
632        }
633    }
634}
635impl CollectGlyphs for Lookup4<'_> {
636    fn collect_glyphs<T>(&self, set: &mut U32Set, _num_glyphs: u32)
637    where
638        T: LookupValue,
639    {
640        for segment in self.segments() {
641            if segment.first_glyph.get() as u32 == DELETED_GLYPH {
642                continue;
643            }
644            set.insert_range(segment.first_glyph.get() as u32..=segment.last_glyph.get() as u32);
645        }
646    }
647    fn collect_glyphs_filtered<T, F>(&self, set: &mut U32Set, _num_glyphs: u32, filter: F)
648    where
649        T: LookupValue,
650        F: Fn(T) -> bool,
651    {
652        for (segment_idx, segment) in self.segments().iter().enumerate() {
653            if segment.first_glyph.get() as u32 == DELETED_GLYPH {
654                continue;
655            }
656            let segment_values = self.segment_values(segment_idx);
657            if let Ok(segment_values) = segment_values {
658                for (i, value) in segment_values.iter().enumerate() {
659                    if filter(value.get()) {
660                        set.insert(segment.first_glyph.get() as u32 + i as u32);
661                    }
662                }
663            }
664        }
665    }
666}
667impl CollectGlyphs for Lookup6<'_> {
668    fn collect_glyphs_filtered<T, F>(&self, set: &mut U32Set, _num_glyphs: u32, filter: F)
669    where
670        T: LookupValue,
671        F: Fn(T) -> bool,
672    {
673        let entries = self.entries();
674        if let Ok(entries) = entries {
675            for entry in entries {
676                let value = entry.value;
677                if filter(value.get()) {
678                    if entry.glyph.get() as u32 == DELETED_GLYPH {
679                        continue;
680                    }
681                    set.insert(entry.glyph.get() as u32);
682                }
683            }
684        }
685    }
686}
687impl CollectGlyphs for Lookup8<'_> {
688    fn collect_glyphs<T>(&self, set: &mut U32Set, _num_glyphs: u32)
689    where
690        T: LookupValue,
691    {
692        let n_values = self.value_array().len();
693        let first_glyph = self.first_glyph();
694        if first_glyph as u32 == DELETED_GLYPH {
695            return;
696        }
697        set.insert_range(
698            first_glyph as u32..=first_glyph as u32 + n_values.saturating_sub(1) as u32,
699        );
700    }
701    fn collect_glyphs_filtered<T, F>(&self, set: &mut U32Set, _num_glyphs: u32, filter: F)
702    where
703        T: LookupValue,
704        F: Fn(T) -> bool,
705    {
706        let values = self.value_array();
707        let first_glyph = self.first_glyph();
708        if first_glyph as u32 == DELETED_GLYPH {
709            return;
710        }
711        for (i, value) in values.iter().enumerate() {
712            if filter(T::from_u16(value.get())) {
713                set.insert(first_glyph as u32 + i as u32);
714            }
715        }
716    }
717}
718impl CollectGlyphs for Lookup10<'_> {
719    fn collect_glyphs<T>(&self, set: &mut U32Set, _num_glyphs: u32)
720    where
721        T: LookupValue,
722    {
723        let n_values = self.glyph_count();
724        let first_glyph = self.first_glyph();
725        if first_glyph as u32 == DELETED_GLYPH {
726            return;
727        }
728        set.insert_range(
729            first_glyph as u32..=first_glyph as u32 + n_values.saturating_sub(1) as u32,
730        );
731    }
732    fn collect_glyphs_filtered<T, F>(&self, set: &mut U32Set, _num_glyphs: u32, filter: F)
733    where
734        T: LookupValue,
735        F: Fn(T) -> bool,
736    {
737        let first_glyph = self.first_glyph();
738        if first_glyph as u32 == DELETED_GLYPH {
739            return;
740        }
741        for i in 0..self.glyph_count() {
742            let idx = first_glyph as u32 + i as u32;
743            // TODO: Speed up by accessing the value array directly
744            let value = self.value::<T>(idx as u16);
745            if let Ok(value) = value {
746                if filter(value) {
747                    set.insert(idx);
748                }
749            }
750        }
751    }
752}
753
754#[cfg(test)]
755mod tests {
756    use super::*;
757    use crate::{Buffer, Direction, ShapePlan, ShaperFont};
758    use core::mem::size_of;
759
760    #[test]
761    fn safe_to_break_subtable_views_are_packed_and_bounded() {
762        assert_eq!(size_of::<SafeToBreakSubtable>(), 16);
763
764        let mut wouldbe = alloc::vec![WOULDBE_NONE; 8];
765        wouldbe[class::OUT_OF_BOUNDS as usize] = pack_wouldbe(7, true);
766        wouldbe[4 + class::OUT_OF_BOUNDS as usize] = pack_wouldbe(9, false);
767        let first_subtable = SafeToBreakSubtable::new(4, 0, 4, 0, 1);
768        let empty_subtable = SafeToBreakSubtable {
769            wouldbe_start: 4,
770            wouldbe_end: 4,
771            eot_tail_start: 1,
772            eot_tail_end: 1,
773        };
774        let last_subtable = SafeToBreakSubtable::new(4, 4, 8, 1, 2);
775        let accel = SafeToBreakAccel {
776            wouldbe,
777            eot_tail: alloc::vec![1, 2],
778        };
779
780        let first = accel.subtable(first_subtable).unwrap();
781        assert!(first.wouldbe_matches(99, 7, true));
782        assert!(first.eot_safe_high(64));
783        assert!(!first.eot_safe_high(65));
784        assert!(!first.eot_safe_high(128));
785
786        let empty = accel.subtable(empty_subtable).unwrap();
787        assert_eq!(empty.wouldbe, []);
788        assert_eq!(empty.eot_tail, []);
789
790        let last = accel.subtable(last_subtable).unwrap();
791        assert!(last.wouldbe_matches(99, 9, false));
792        assert!(!last.eot_safe_high(64));
793        assert!(last.eot_safe_high(65));
794    }
795
796    #[test]
797    fn output_deleted_glyph_at_end_of_text_marks_output() {
798        let font_data = include_bytes!("../../tests/fonts/text-rendering-tests/TestMORXOne.ttf");
799        let source = crate::font::Font::new(font_data.to_vec(), 0).unwrap();
800        let font = source.instance_builder().build();
801        let shaper_font = ShaperFont::new(&font);
802        let plan = ShapePlan::new(&font, Direction::LeftToRight, None, None, &[]);
803
804        let mut buffer = Buffer::new();
805        buffer.push('A' as u32, 0);
806        buffer.clear_output();
807        buffer.next_glyph();
808
809        let mut context = AatApplyContext::new(
810            &plan,
811            shaper_font.layout(),
812            Scale::default(),
813            &mut buffer,
814            #[cfg(feature = "tracing")]
815            &shaper_font,
816        );
817        context.output_glyph(DELETED_GLYPH);
818
819        assert_eq!(context.buffer.out_len, 2);
820        assert_eq!(context.buffer.prev().unwrap().glyph_id, DELETED_GLYPH);
821        assert!(context.buffer.prev().unwrap().is_aat_deleted());
822    }
823
824    #[test]
825    fn ligature_deletion_enables_later_subtables_in_short_and_cached_buffers() {
826        let data = include_bytes!(
827            "../../tests/fonts/in-house/007e2c13e6baf28a7f1e8f981c2db0cb850b1f1f.ttf"
828        );
829        let font = crate::Font::new(data.to_vec(), 0).unwrap();
830        let shaper_font = ShaperFont::new(&font);
831        // The font ligates 1,2 into 3, then a deleted-glyph transition
832        // enables substitution 4 -> 5. Four glyphs enable the glyph set.
833        for (text, expected) in [("abc", &[3, 5][..]), ("abcc", &[3, 5, 4][..])] {
834            let mut buffer = Buffer::new();
835            buffer.push_str(text);
836            buffer.set_direction(Direction::LeftToRight);
837            crate::shape(&shaper_font, &mut buffer, crate::ShapeOptions::new()).unwrap();
838            let glyphs: Vec<_> = buffer
839                .glyph_infos()
840                .iter()
841                .map(|info| info.glyph_id)
842                .collect();
843            assert_eq!(glyphs, expected, "{text}");
844        }
845    }
846}