Skip to main content

harfrust/aat/
morx.rs

1use super::layout::*;
2use super::map::{AatMap, AatMapBuilder, RangeFlags};
3use super::AatData;
4use crate::aat::common::{
5    set_digest, AatApplyContext, ClassCache, SafeToBreakAccel, SafeToBreakSubtable,
6    TypedCollectGlyphs, START_OF_TEXT,
7};
8use crate::ot::layout::MAX_CONTEXT_LENGTH;
9use crate::set_digest::SetDigest;
10use crate::tag::lang_matches;
11use crate::Language;
12use crate::U32Set;
13use alloc::{vec, vec::Vec};
14use read_fonts::tables::aat::{self, ExtendedStateTable, NoPayload, StateEntry, StateTable};
15use read_fonts::tables::{mort, morx};
16use read_fonts::types::{BigEndian, FixedSize, GlyphId, GlyphId16};
17use read_fonts::ReadError;
18
19trait MorphChain {
20    fn default_flags(&self) -> u32;
21    fn for_each_feature(&self, f: impl FnMut(u16, u16, u32, u32));
22}
23
24impl MorphChain for morx::Chain<'_> {
25    fn default_flags(&self) -> u32 {
26        self.default_flags()
27    }
28
29    fn for_each_feature(&self, mut f: impl FnMut(u16, u16, u32, u32)) {
30        for feature in self.features() {
31            f(
32                feature.feature_type(),
33                feature.feature_settings(),
34                feature.enable_flags(),
35                feature.disable_flags(),
36            );
37        }
38    }
39}
40
41impl MorphChain for mort::Chain<'_> {
42    fn default_flags(&self) -> u32 {
43        self.default_flags()
44    }
45
46    fn for_each_feature(&self, mut f: impl FnMut(u16, u16, u32, u32)) {
47        for feature in self.features() {
48            f(
49                feature.feature_type(),
50                feature.feature_settings(),
51                feature.enable_flags(),
52                feature.disable_flags(),
53            );
54        }
55    }
56}
57
58// Chain::compile_flags in harfbuzz
59pub fn compile_flags(aat: &AatData, builder: &AatMapBuilder, map: &mut AatMap) -> Option<()> {
60    let has_feature = |kind: u16, setting: u16| {
61        builder
62            .current_features
63            .binary_search_by(|probe| {
64                if probe.kind != kind {
65                    probe.kind.cmp(&kind)
66                } else {
67                    probe.setting.cmp(&setting)
68                }
69            })
70            .is_ok()
71    };
72    let language_matches = |setting: u16| {
73        let Some(index) = setting.checked_sub(1) else {
74            return false;
75        };
76        let Some(requested) = builder.language.as_ref() else {
77            return false;
78        };
79        let Some(ltag) = aat.ltag.as_ref() else {
80            return false;
81        };
82        let Some(tag) = ltag
83            .tag_indices()
84            .find_map(|(tag_index, tag)| (tag_index == u32::from(index)).then_some(tag))
85        else {
86            return false;
87        };
88        let Some(language) = Language::new(tag) else {
89            return false;
90        };
91        lang_matches(requested.as_bytes(), language.as_bytes())
92    };
93
94    fn compile_chain(
95        chain: &impl MorphChain,
96        has_feature: &impl Fn(u16, u16) -> bool,
97        language_matches: &impl Fn(u16) -> bool,
98        chain_flags: &mut Vec<RangeFlags>,
99        builder: &AatMapBuilder,
100    ) {
101        let mut flags = chain.default_flags();
102        chain.for_each_feature(
103            |feature_type, feature_setting, enable_flags, disable_flags| {
104                // Check whether this type/setting pair was requested in the map,
105                // and if so, apply its flags.
106                if has_feature(feature_type, feature_setting) {
107                    flags &= disable_flags;
108                    flags |= enable_flags;
109                } else if feature_type == FEATURE_TYPE_LETTER_CASE as u16
110                    && feature_setting == u16::from(FEATURE_SELECTOR_SMALL_CAPS)
111                {
112                    // Deprecated. https://github.com/harfbuzz/harfbuzz/issues/1342
113                    let ok = has_feature(
114                        FEATURE_TYPE_LOWER_CASE as u16,
115                        u16::from(FEATURE_SELECTOR_LOWER_CASE_SMALL_CAPS),
116                    );
117                    if ok {
118                        flags &= disable_flags;
119                        flags |= enable_flags;
120                    }
121                } else if feature_type == FEATURE_TYPE_LANGUAGE_TAG_TYPE as u16
122                    && language_matches(feature_setting)
123                {
124                    flags &= disable_flags;
125                    flags |= enable_flags;
126                }
127            },
128        );
129
130        chain_flags.push(RangeFlags {
131            flags,
132            cluster_first: builder.range_first as u32,
133            cluster_last: builder.range_last as u32,
134        });
135    }
136
137    if let Some(morx) = aat.morx.as_ref() {
138        let chains = morx.chains();
139        map.chain_flags.resize(chains.iter().count(), vec![]);
140        for (chain, chain_flags) in chains.iter().zip(map.chain_flags.iter_mut()) {
141            if let Ok(chain) = chain {
142                compile_chain(
143                    &chain,
144                    &has_feature,
145                    &language_matches,
146                    chain_flags,
147                    builder,
148                );
149            }
150        }
151    } else {
152        let chains = aat.mort.as_ref()?.chains();
153        map.chain_flags.resize(chains.iter().count(), vec![]);
154        for (chain, chain_flags) in chains.iter().zip(map.chain_flags.iter_mut()) {
155            if let Ok(chain) = chain {
156                compile_chain(
157                    &chain,
158                    &has_feature,
159                    &language_matches,
160                    chain_flags,
161                    builder,
162                );
163            }
164        }
165    }
166
167    Some(())
168}
169
170// Chain::apply in harfbuzz
171pub fn apply<'a>(c: &mut AatApplyContext<'a, '_, '_>, map: &'a AatMap) -> Option<()> {
172    c.buffer.unsafe_to_concat(None, None);
173
174    c.setup_buffer_glyph_set();
175
176    let cache = if c.layout.aat.morx.is_some() {
177        c.layout.aat.morx_cache()?
178    } else {
179        c.layout.aat.mort_cache()?
180    };
181    c.setup_buffer_digest(cache.descriptors.len());
182    apply_table(
183        c,
184        map,
185        &cache.safe_to_break,
186        &cache.subtables,
187        &cache.descriptors,
188    )
189}
190
191fn apply_table<'a>(
192    c: &mut AatApplyContext<'a, '_, '_>,
193    map: &'a AatMap,
194    safe_to_break: &'a SafeToBreakAccel,
195    subtable_caches: &'a [MorphSubtableCache<'a>],
196    descriptors: &'a [MorphSubtableDescriptor],
197) -> Option<()> {
198    let mut last_chain_index = u32::MAX;
199    let mut chain_flags = None;
200
201    for (subtable_idx, desc) in descriptors.iter().enumerate() {
202        if desc.chain_index != last_chain_index {
203            // Chain boundary: restore buffer order, load this chain's flags.
204            if c.buffer_is_reversed {
205                c.reverse_buffer();
206            }
207            last_chain_index = desc.chain_index;
208            chain_flags = map.chain_flags.get(desc.chain_index as usize);
209        }
210        let Some(chain_flags) = chain_flags else {
211            continue;
212        };
213        c.range_flags = Some(chain_flags.as_slice());
214
215        if chain_flags.len() == 1 && (desc.sub_feature_flags & chain_flags[0].flags == 0) {
216            continue;
217        }
218
219        let coverage = desc.coverage;
220        let is_all_directions = coverage & 0x2000_0000 != 0;
221        let is_vertical = coverage & 0x8000_0000 != 0;
222        if !is_all_directions && c.buffer.direction.is_vertical() != is_vertical {
223            continue;
224        }
225
226        let subtable_cache = &subtable_caches[subtable_idx];
227        c.subtable_flags = desc.sub_feature_flags;
228        c.first_set = Some(&subtable_cache.glyph_set);
229        c.first_digest = subtable_cache.glyph_digest.clone();
230        c.machine_class_cache = Some(&subtable_cache.class_cache);
231        c.start_end_safe_to_break = subtable_cache.start_end_safe_to_break;
232        c.safe_to_break = safe_to_break.subtable(subtable_cache.safe_to_break)?;
233
234        if !c.buffer_intersects_machine() {
235            message!(
236                c,
237                "skipped chainsubtable {} because no glyph matches",
238                subtable_idx
239            );
240            continue;
241        }
242        message_continue!(c, "start chainsubtable {}", subtable_idx);
243
244        // Buffer contents is always in logical direction.  Determine if
245        // we need to reverse before applying this subtable.  We reverse
246        // back after if we did reverse indeed.
247        //
248        // See the coverage bits table in the `morx` spec for the meaning
249        // of is_logical/is_backwards here.
250        let is_logical = coverage & 0x1000_0000 != 0;
251        let is_backwards = coverage & 0x4000_0000 != 0;
252        let reverse = if is_logical {
253            is_backwards
254        } else {
255            is_backwards != c.buffer.direction.is_backward()
256        };
257
258        if reverse != c.buffer_is_reversed {
259            c.reverse_buffer();
260        }
261
262        match &subtable_cache.kind {
263            Some(MorphSubtableKind::Morx(kind)) => apply_morx_subtable(kind, c),
264            Some(MorphSubtableKind::Mort(kind)) => apply_mort_subtable(kind, c),
265            None => {}
266        }
267        message!(c, "end chainsubtable {}", subtable_idx);
268    }
269    if c.buffer_is_reversed {
270        c.reverse_buffer();
271    }
272
273    Some(())
274}
275
276trait MorphStateTable<T>
277where
278    T: FixedSize + bytemuck::AnyBitPattern,
279{
280    fn n_classes(&self) -> usize;
281    fn class(&self, glyph_id: GlyphId) -> Result<u16, ReadError>;
282    fn entry(&self, state: u16, class: u16) -> Result<StateEntry<T>, ReadError>;
283    fn collect_glyphs_filtered(
284        &self,
285        glyphs: &mut U32Set,
286        num_glyphs: u32,
287        filter: impl Fn(u16) -> bool,
288    );
289    fn build_safe_to_break(
290        &self,
291        accel: &mut SafeToBreakAccel,
292        data: &[u8],
293        is_actionable: &dyn Fn(&StateEntry<T>) -> bool,
294        can_advance: &dyn Fn(&StateEntry<T>) -> bool,
295    ) -> SafeToBreakSubtable;
296}
297
298impl<T> MorphStateTable<T> for ExtendedStateTable<'_, T>
299where
300    T: FixedSize + bytemuck::AnyBitPattern,
301{
302    fn n_classes(&self) -> usize {
303        self.n_classes
304    }
305
306    fn class(&self, glyph_id: GlyphId) -> Result<u16, ReadError> {
307        self.class(glyph_id)
308    }
309
310    fn entry(&self, state: u16, class: u16) -> Result<StateEntry<T>, ReadError> {
311        self.entry(state, class)
312    }
313
314    fn collect_glyphs_filtered(
315        &self,
316        glyphs: &mut U32Set,
317        num_glyphs: u32,
318        filter: impl Fn(u16) -> bool,
319    ) {
320        self.class_table
321            .collect_glyphs_filtered(glyphs, num_glyphs, filter);
322    }
323
324    fn build_safe_to_break(
325        &self,
326        accel: &mut SafeToBreakAccel,
327        data: &[u8],
328        is_actionable: &dyn Fn(&StateEntry<T>) -> bool,
329        can_advance: &dyn Fn(&StateEntry<T>) -> bool,
330    ) -> SafeToBreakSubtable {
331        accel.build_extended(self, data, is_actionable, can_advance)
332    }
333}
334
335impl<T> MorphStateTable<T> for StateTable<'_, T>
336where
337    T: FixedSize + bytemuck::AnyBitPattern,
338{
339    fn n_classes(&self) -> usize {
340        self.n_classes
341    }
342
343    fn class(&self, glyph_id: GlyphId) -> Result<u16, ReadError> {
344        let glyph_id = u16::try_from(glyph_id.to_u32()).map_err(|_| ReadError::OutOfBounds)?;
345        self.class(GlyphId16::new(glyph_id)).map(u16::from)
346    }
347
348    fn entry(&self, state: u16, class: u16) -> Result<StateEntry<T>, ReadError> {
349        let class = u8::try_from(class).unwrap_or(aat::class::OUT_OF_BOUNDS);
350        self.entry(state, class)
351    }
352
353    fn collect_glyphs_filtered(
354        &self,
355        glyphs: &mut U32Set,
356        num_glyphs: u32,
357        filter: impl Fn(u16) -> bool,
358    ) {
359        let (first_glyph, classes) = self.class_mappings();
360        for (i, class) in classes.iter().copied().enumerate() {
361            let glyph = u32::from(first_glyph).saturating_add(i as u32);
362            if glyph < num_glyphs && filter(u16::from(class)) {
363                glyphs.insert(glyph);
364            }
365        }
366    }
367
368    fn build_safe_to_break(
369        &self,
370        accel: &mut SafeToBreakAccel,
371        _data: &[u8],
372        is_actionable: &dyn Fn(&StateEntry<T>) -> bool,
373        can_advance: &dyn Fn(&StateEntry<T>) -> bool,
374    ) -> SafeToBreakSubtable {
375        accel.build_legacy(self, is_actionable, can_advance)
376    }
377}
378
379fn get_morph_class<T, M>(machine: &M, glyph_id: GlyphId, cache: &ClassCache) -> u16
380where
381    T: FixedSize + bytemuck::AnyBitPattern,
382    M: MorphStateTable<T>,
383{
384    if let Some(class) = cache.get(glyph_id.to_u32()) {
385        return class as u16;
386    }
387    let class = machine
388        .class(glyph_id)
389        .unwrap_or(u16::from(aat::class::OUT_OF_BOUNDS));
390    cache.set(glyph_id.to_u32(), u32::from(class));
391    class
392}
393
394fn collect_initial_glyphs<T, M, Ctx>(machine: &M, glyphs: &mut U32Set, num_glyphs: u32)
395where
396    T: FixedSize + bytemuck::AnyBitPattern,
397    M: MorphStateTable<T>,
398    Ctx: DriverContext<T>,
399{
400    let mut classes = U32Set::default();
401
402    for i in 0..machine.n_classes() {
403        if let Ok(entry) = machine.entry(START_OF_TEXT, i as u16) {
404            if entry.new_state == START_OF_TEXT
405                && !Ctx::is_action_initiable(&entry)
406                && !Ctx::is_actionable(&entry)
407            {
408                continue;
409            }
410            classes.insert(i as u32);
411        }
412    }
413
414    // And glyphs in those classes.
415
416    let filter = crate::aat::common::class_set_filter(&classes);
417
418    if filter(aat::class::DELETED_GLYPH as u16) {
419        glyphs.insert(DELETED_GLYPH);
420    }
421
422    machine.collect_glyphs_filtered(glyphs, num_glyphs, filter);
423}
424
425fn collect_start_end_safe_to_break<T, M, Ctx>(machine: &M) -> u64
426where
427    T: FixedSize + bytemuck::AnyBitPattern,
428    M: MorphStateTable<T>,
429    Ctx: DriverContext<T>,
430{
431    let mut result = 0u64;
432    for state in 0..64 {
433        let bit = if let Ok(entry) = machine.entry(state, aat::class::END_OF_TEXT as u16) {
434            !Ctx::is_actionable(&entry)
435        } else {
436            true
437        };
438        if bit {
439            result |= 1 << state;
440        }
441    }
442    result
443}
444
445pub(crate) trait DriverContext<T> {
446    fn in_place() -> bool;
447    fn can_advance(entry: &StateEntry<T>) -> bool;
448    fn is_action_initiable(entry: &StateEntry<T>) -> bool;
449    fn is_actionable(entry: &StateEntry<T>) -> bool;
450    fn transition(&mut self, entry: &StateEntry<T>, ac: &mut AatApplyContext) -> Option<()>;
451}
452
453fn drive<T, M, Ctx>(machine: &M, c: &mut Ctx, ac: &mut AatApplyContext) -> Option<()>
454where
455    T: bytemuck::AnyBitPattern + FixedSize + core::fmt::Debug,
456    M: MorphStateTable<T>,
457    Ctx: DriverContext<T>,
458{
459    if !Ctx::in_place() {
460        ac.buffer.clear_output();
461    }
462
463    let mut state = START_OF_TEXT;
464    let mut last_range = ac.range_flags.as_ref().and_then(|rf| {
465        if rf.len() > 1 {
466            rf.first().map(|_| 0usize)
467        } else {
468            // If there's only one range, we already checked the flag.
469            None
470        }
471    });
472    // Condition 3 below, precomputed for the start-of-text state: no
473    // end-of-text action can fire if we stop while in the start state.
474    let start_state_safe_to_break_eot = (ac.start_end_safe_to_break & (1 << START_OF_TEXT)) != 0;
475    ac.buffer.idx = 0;
476    'drive: loop {
477        // This block copied from NoncontextualSubtable::apply. Keep in sync.
478        if let Some(range_flags) = ac.range_flags.as_ref() {
479            if let Some(last_range) = last_range.as_mut() {
480                let mut range = *last_range;
481                if ac.buffer.idx < ac.buffer.len {
482                    let cluster = ac.buffer.cur(0)?.cluster;
483                    while cluster < range_flags[range].cluster_first {
484                        range -= 1;
485                    }
486
487                    while cluster > range_flags[range].cluster_last {
488                        range += 1;
489                    }
490
491                    *last_range = range;
492                }
493
494                if range_flags[range].flags & ac.subtable_flags == 0 {
495                    if ac.buffer.idx == ac.buffer.len || !ac.buffer.successful {
496                        break;
497                    }
498
499                    state = START_OF_TEXT;
500
501                    ac.buffer.next_glyph();
502                    continue;
503                }
504            }
505        }
506
507        let class = if ac.buffer.idx < ac.buffer.len {
508            get_morph_class::<T, _>(
509                machine,
510                ac.buffer.cur(0)?.as_glyph(),
511                ac.machine_class_cache.unwrap(),
512            )
513        } else {
514            u16::from(aat::class::END_OF_TEXT)
515        };
516
517        let Ok(entry) = machine.entry(state, class) else {
518            break;
519        };
520
521        let next_state = entry.new_state;
522
523        // Fast path for when transitioning from start-state to start-state with
524        // no action and advancing. Do so as long as the class remains the same.
525        // This is common with runs of non-actionable glyphs.
526        if last_range.is_none()
527            && state == START_OF_TEXT
528            && next_state == START_OF_TEXT
529            && start_state_safe_to_break_eot
530            && !Ctx::is_actionable(&entry)
531            && Ctx::can_advance(&entry)
532        {
533            let old_class = class;
534            loop {
535                c.transition(&entry, ac);
536                if ac.buffer.idx >= ac.buffer.len || !ac.buffer.successful {
537                    break 'drive;
538                }
539                ac.buffer.next_glyph();
540
541                let new_class = if ac.buffer.idx < ac.buffer.len {
542                    get_morph_class::<T, _>(
543                        machine,
544                        ac.buffer.cur(0)?.as_glyph(),
545                        ac.machine_class_cache.unwrap(),
546                    )
547                } else {
548                    u16::from(aat::class::END_OF_TEXT)
549                };
550                if new_class != old_class {
551                    break;
552                }
553            }
554            if ac.buffer.idx >= ac.buffer.len || !ac.buffer.successful {
555                break 'drive;
556            }
557            continue 'drive;
558        }
559
560        // Conditions under which it's guaranteed safe-to-break before current glyph:
561        //
562        // 1. There was no action in this transition; and
563        //
564        // 2. If we break before current glyph, the results will be the same. That
565        //    is guaranteed if:
566        //
567        //    2a. We were already in start-of-text state; or
568        //
569        //    2b. We are epsilon-transitioning to start-of-text state; or
570        //
571        //    2c. Starting from start-of-text state seeing current glyph:
572        //
573        //        2c'. There won't be any actions; and
574        //
575        //        2c". We would end up in the same state that we were going to end up
576        //             in now, including whether epsilon-transitioning.
577        //
578        //    and
579        //
580        // 3. If we break before current glyph, there won't be any end-of-text action
581        //    after previous glyph.
582        //
583        // This triples the transitions we need to look up, but is worth returning
584        // granular unsafe-to-break results. See eg.:
585        //
586        //   https://github.com/harfbuzz/harfbuzz/issues/2860
587
588        let is_safe_to_break =
589            // 1
590            !Ctx::is_actionable(&entry) &&
591
592            // 2
593            (
594                state == START_OF_TEXT
595                || (!Ctx::can_advance(&entry) && next_state == START_OF_TEXT)
596                // 2c, 2c', 2c"
597                || ac.safe_to_break.wouldbe_matches(class, next_state, Ctx::can_advance(&entry))
598            ) &&
599
600            // 3
601            (
602                if state < 64 {
603                    (ac.start_end_safe_to_break & (1 << state)) != 0
604                } else {
605                    ac.safe_to_break.eot_safe_high(state)
606                }
607            )
608        ;
609
610        if !is_safe_to_break && ac.buffer.backtrack_len() > 0 && ac.buffer.idx < ac.buffer.len {
611            ac.buffer.unsafe_to_break_from_outbuffer(
612                Some(ac.buffer.backtrack_len() - 1),
613                Some(ac.buffer.idx + 1),
614            );
615        }
616
617        c.transition(&entry, ac);
618
619        state = next_state;
620
621        if ac.buffer.idx >= ac.buffer.len || !ac.buffer.successful {
622            break;
623        }
624
625        if Ctx::can_advance(&entry) {
626            ac.buffer.next_glyph();
627        } else {
628            if ac.buffer.max_ops <= 0 {
629                ac.buffer.next_glyph();
630            }
631            ac.buffer.max_ops -= 1;
632        }
633    }
634
635    if !Ctx::in_place() {
636        ac.buffer.sync();
637    }
638    Some(())
639}
640
641fn apply_morx_subtable<'a>(kind: &'a morx::SubtableKind<'a>, ac: &mut AatApplyContext<'a, '_, '_>) {
642    match kind {
643        morx::SubtableKind::Rearrangement(table) => {
644            let mut c = RearrangementCtx { start: 0, end: 0 };
645            if drive(table, &mut c, ac).is_none() {
646                ac.buffer.index_failed();
647            }
648        }
649        morx::SubtableKind::Contextual(table) => {
650            let mut c = ContextualCtx {
651                mark_set: false,
652                mark: 0,
653                table: table.clone(),
654            };
655            if drive(&table.state_table, &mut c, ac).is_none() {
656                ac.buffer.index_failed();
657            }
658        }
659        morx::SubtableKind::Ligature(table) => {
660            let mut c = LigatureCtx {
661                table: table.clone(),
662                match_length: 0,
663                match_positions: [0; LIGATURE_MAX_MATCHES],
664            };
665            if drive(&table.state_table, &mut c, ac).is_none() {
666                ac.buffer.index_failed();
667            }
668        }
669        morx::SubtableKind::NonContextual(lookup) => {
670            if apply_noncontextual(lookup, ac).is_none() {
671                ac.buffer.index_failed();
672            }
673        }
674        morx::SubtableKind::Insertion(table) => {
675            let mut c = InsertionCtx {
676                mark: 0,
677                glyphs: table.glyphs,
678            };
679            if drive(&table.state_table, &mut c, ac).is_none() {
680                ac.buffer.index_failed();
681            }
682        }
683    }
684}
685
686fn apply_mort_subtable<'a>(kind: &'a mort::SubtableKind<'a>, ac: &mut AatApplyContext<'a, '_, '_>) {
687    match kind {
688        mort::SubtableKind::Rearrangement(table) => {
689            let mut c = RearrangementCtx { start: 0, end: 0 };
690            if drive(table, &mut c, ac).is_none() {
691                ac.buffer.index_failed();
692            }
693        }
694        mort::SubtableKind::Contextual(table) => {
695            let mut c = ContextualCtx {
696                mark_set: false,
697                mark: 0,
698                table: table.clone(),
699            };
700            if drive(&table.state_table, &mut c, ac).is_none() {
701                ac.buffer.index_failed();
702            }
703        }
704        mort::SubtableKind::Ligature(table) => {
705            let mut c = LigatureCtx {
706                table: table.clone(),
707                match_length: 0,
708                match_positions: [0; LIGATURE_MAX_MATCHES],
709            };
710            if drive(&table.state_table, &mut c, ac).is_none() {
711                ac.buffer.index_failed();
712            }
713        }
714        mort::SubtableKind::NonContextual(lookup) => {
715            if apply_noncontextual(lookup, ac).is_none() {
716                ac.buffer.index_failed();
717            }
718        }
719        mort::SubtableKind::Insertion(table) => {
720            let mut c = InsertionCtx {
721                mark: 0,
722                glyphs: table.glyphs,
723            };
724            if drive(&table.state_table, &mut c, ac).is_none() {
725                ac.buffer.index_failed();
726            }
727        }
728    }
729}
730
731fn apply_noncontextual(lookup: &aat::LookupU16, ac: &mut AatApplyContext) -> Option<()> {
732    let mut last_range = ac.range_flags.as_ref().and_then(|rf| {
733        if rf.len() > 1 {
734            rf.first().map(|_| 0usize)
735        } else {
736            // If there's only one range, we already checked the flag.
737            None
738        }
739    });
740
741    for i in 0..ac.buffer.len {
742        // This block copied from the state-table driver. Keep in sync.
743        if let Some(range_flags) = ac.range_flags.as_ref() {
744            if let Some(last_range) = last_range.as_mut() {
745                let mut range = *last_range;
746                if ac.buffer.idx < ac.buffer.len {
747                    let cluster = ac.buffer.cur(0)?.cluster;
748                    while cluster < range_flags[range].cluster_first {
749                        range -= 1;
750                    }
751
752                    while cluster > range_flags[range].cluster_last {
753                        range += 1;
754                    }
755
756                    *last_range = range;
757                }
758
759                if range_flags[range].flags & ac.subtable_flags == 0 {
760                    continue;
761                }
762            }
763        }
764
765        if let Some(glyph) = ac.buffer.info.get(i).and_then(|info| info.as_gid16()) {
766            if let Ok(replacement) = lookup.value(glyph.to_u16()) {
767                if ac.replace_glyph_inplace(i, replacement.into()).is_none() {
768                    ac.buffer.index_failed();
769                }
770            }
771        }
772    }
773    Some(())
774}
775
776struct RearrangementCtx {
777    start: usize,
778    end: usize,
779}
780
781impl RearrangementCtx {
782    const MARK_FIRST: u16 = 0x8000;
783    const DONT_ADVANCE: u16 = 0x4000;
784    const MARK_LAST: u16 = 0x2000;
785    const VERB: u16 = 0x000F;
786}
787
788impl DriverContext<NoPayload> for RearrangementCtx {
789    fn in_place() -> bool {
790        true
791    }
792
793    fn can_advance(entry: &StateEntry) -> bool {
794        entry.flags & Self::DONT_ADVANCE == 0
795    }
796
797    fn is_action_initiable(entry: &StateEntry) -> bool {
798        entry.flags & Self::MARK_FIRST != 0
799    }
800
801    fn is_actionable(entry: &StateEntry) -> bool {
802        entry.flags & Self::VERB != 0
803    }
804
805    #[inline(always)]
806    fn transition(&mut self, entry: &StateEntry, ac: &mut AatApplyContext) -> Option<()> {
807        let buffer = &mut *ac.buffer;
808        let flags = entry.flags;
809
810        if flags & Self::MARK_FIRST != 0 {
811            self.start = buffer.idx;
812        }
813
814        if flags & Self::MARK_LAST != 0 {
815            self.end = (buffer.idx + 1).min(buffer.len);
816        }
817
818        if flags & Self::VERB != 0 && self.start < self.end {
819            // The following map has two nibbles, for start-side
820            // and end-side. Values of 0,1,2 mean move that many
821            // to the other side. Value of 3 means move 2 and
822            // flip them.
823            static MAP: [u8; 16] = [
824                0x00, // 0  no change
825                0x10, // 1  Ax => xA
826                0x01, // 2  xD => Dx
827                0x11, // 3  AxD => DxA
828                0x20, // 4  ABx => xAB
829                0x30, // 5  ABx => xBA
830                0x02, // 6  xCD => CDx
831                0x03, // 7  xCD => DCx
832                0x12, // 8  AxCD => CDxA
833                0x13, // 9  AxCD => DCxA
834                0x21, // 10 ABxD => DxAB
835                0x31, // 11 ABxD => DxBA
836                0x22, // 12 ABxCD => CDxAB
837                0x32, // 13 ABxCD => CDxBA
838                0x23, // 14 ABxCD => DCxAB
839                0x33, // 15 ABxCD => DCxBA
840            ];
841
842            let m = MAP[usize::from(flags & Self::VERB)];
843            let l = 2.min(m >> 4) as usize;
844            let r = 2.min(m & 0x0F) as usize;
845            let reverse_l = 3 == (m >> 4);
846            let reverse_r = 3 == (m & 0x0F);
847
848            if (self.end - self.start >= l + r) && (self.end - self.start <= MAX_CONTEXT_LENGTH) {
849                buffer.merge_clusters(self.start, (buffer.idx + 1).min(buffer.len));
850                buffer.merge_clusters(self.start, self.end);
851
852                // Swap the first l glyphs with the last r: rotating the run
853                // left by l puts the l glyphs at the end, then rotating the
854                // rest right by r brings the r glyphs to the front.
855                let run = buffer.info.get_mut(self.start..self.end)?;
856                let len = run.len();
857                run.rotate_left(l);
858                run.get_mut(..len - l)?.rotate_right(r);
859
860                if reverse_l {
861                    run.get_mut(len - 2..)?.reverse();
862                }
863
864                if reverse_r {
865                    run.get_mut(..2)?.reverse();
866                }
867            }
868        }
869
870        Some(())
871    }
872}
873
874trait ContextualActions<P> {
875    fn mark_action(payload: &P) -> bool;
876    fn current_action(payload: &P) -> bool;
877    fn mark_replacement(&self, payload: &P, glyph: GlyphId16) -> Option<GlyphId16>;
878    fn current_replacement(&self, payload: &P, glyph: GlyphId16) -> Option<GlyphId16>;
879}
880
881impl ContextualActions<morx::ContextualEntryData> for morx::ContextualSubtable<'_> {
882    fn mark_action(payload: &morx::ContextualEntryData) -> bool {
883        payload.mark_index.get() != 0xFFFF
884    }
885
886    fn current_action(payload: &morx::ContextualEntryData) -> bool {
887        payload.current_index.get() != 0xFFFF
888    }
889
890    fn mark_replacement(
891        &self,
892        payload: &morx::ContextualEntryData,
893        glyph: GlyphId16,
894    ) -> Option<GlyphId16> {
895        self.lookup(usize::from(payload.mark_index.get()))?
896            .value(glyph.to_u16())
897            .ok()
898            .map(GlyphId16::new)
899    }
900
901    fn current_replacement(
902        &self,
903        payload: &morx::ContextualEntryData,
904        glyph: GlyphId16,
905    ) -> Option<GlyphId16> {
906        self.lookup(usize::from(payload.current_index.get()))?
907            .value(glyph.to_u16())
908            .ok()
909            .map(GlyphId16::new)
910    }
911}
912
913impl ContextualActions<mort::ContextualEntryData> for mort::ContextualSubtable<'_> {
914    fn mark_action(payload: &mort::ContextualEntryData) -> bool {
915        payload.mark_offset.get() != 0
916    }
917
918    fn current_action(payload: &mort::ContextualEntryData) -> bool {
919        payload.current_offset.get() != 0
920    }
921
922    fn mark_replacement(
923        &self,
924        payload: &mort::ContextualEntryData,
925        glyph: GlyphId16,
926    ) -> Option<GlyphId16> {
927        self.substitution(payload.mark_offset.get(), glyph)
928            .ok()
929            .filter(|glyph| *glyph != GlyphId16::NOTDEF)
930    }
931
932    fn current_replacement(
933        &self,
934        payload: &mort::ContextualEntryData,
935        glyph: GlyphId16,
936    ) -> Option<GlyphId16> {
937        self.substitution(payload.current_offset.get(), glyph)
938            .ok()
939            .filter(|glyph| *glyph != GlyphId16::NOTDEF)
940    }
941}
942
943struct ContextualCtx<T> {
944    mark_set: bool,
945    mark: usize,
946    table: T,
947}
948
949impl<T> ContextualCtx<T> {
950    const SET_MARK: u16 = 0x8000;
951    const DONT_ADVANCE: u16 = 0x4000;
952}
953
954impl<P, T> DriverContext<P> for ContextualCtx<T>
955where
956    T: ContextualActions<P>,
957{
958    fn in_place() -> bool {
959        true
960    }
961
962    fn can_advance(entry: &StateEntry<P>) -> bool {
963        entry.flags & Self::DONT_ADVANCE == 0
964    }
965
966    fn is_action_initiable(entry: &StateEntry<P>) -> bool {
967        entry.flags & Self::SET_MARK != 0
968    }
969
970    fn is_actionable(entry: &StateEntry<P>) -> bool {
971        T::mark_action(&entry.payload) || T::current_action(&entry.payload)
972    }
973
974    #[inline(always)]
975    fn transition(&mut self, entry: &StateEntry<P>, ac: &mut AatApplyContext) -> Option<()> {
976        // Looks like CoreText applies neither mark nor current substitution for
977        // end-of-text if mark was not explicitly set.
978        if ac.buffer.idx == ac.buffer.len && !self.mark_set {
979            return Some(());
980        }
981
982        let mut replacement = None;
983
984        if T::mark_action(&entry.payload) {
985            if let Some(gid) = ac
986                .buffer
987                .info
988                .get(self.mark)
989                .and_then(|info| info.as_gid16())
990            {
991                replacement = self.table.mark_replacement(&entry.payload, gid);
992            }
993        }
994
995        if let Some(replacement) = replacement {
996            ac.buffer.unsafe_to_break(
997                Some(self.mark),
998                Some((ac.buffer.idx + 1).min(ac.buffer.len)),
999            );
1000            if ac
1001                .replace_glyph_inplace(self.mark, replacement.into())
1002                .is_none()
1003            {
1004                ac.buffer.index_failed();
1005            }
1006        }
1007
1008        replacement = None;
1009        let idx = ac.buffer.idx.min(ac.buffer.len - 1);
1010        if T::current_action(&entry.payload) {
1011            if let Some(gid) = ac.buffer.info.get(idx).and_then(|info| info.as_gid16()) {
1012                replacement = self.table.current_replacement(&entry.payload, gid);
1013            }
1014        }
1015
1016        if let Some(replacement) = replacement {
1017            if ac.replace_glyph_inplace(idx, replacement.into()).is_none() {
1018                ac.buffer.index_failed();
1019            }
1020        }
1021
1022        if entry.flags & Self::SET_MARK != 0 {
1023            self.mark_set = true;
1024            self.mark = ac.buffer.idx;
1025        }
1026
1027        Some(())
1028    }
1029}
1030
1031struct InsertionCtx<'a> {
1032    mark: u32,
1033    glyphs: &'a [BigEndian<GlyphId16>],
1034}
1035
1036trait InsertionPayload {
1037    fn current_insert_index(&self) -> u16;
1038    fn marked_insert_index(&self) -> u16;
1039}
1040
1041impl InsertionPayload for morx::InsertionEntryData {
1042    fn current_insert_index(&self) -> u16 {
1043        self.current_insert_index.get()
1044    }
1045
1046    fn marked_insert_index(&self) -> u16 {
1047        self.marked_insert_index.get()
1048    }
1049}
1050
1051impl InsertionPayload for mort::InsertionEntryData {
1052    fn current_insert_index(&self) -> u16 {
1053        self.current_insert_index.get()
1054    }
1055
1056    fn marked_insert_index(&self) -> u16 {
1057        self.marked_insert_index.get()
1058    }
1059}
1060
1061impl InsertionCtx<'_> {
1062    const SET_MARK: u16 = 0x8000;
1063    const DONT_ADVANCE: u16 = 0x4000;
1064    const CURRENT_INSERT_BEFORE: u16 = 0x0800;
1065    const MARKED_INSERT_BEFORE: u16 = 0x0400;
1066    const CURRENT_INSERT_COUNT: u16 = 0x03E0;
1067    const MARKED_INSERT_COUNT: u16 = 0x001F;
1068}
1069
1070impl<P: InsertionPayload> DriverContext<P> for InsertionCtx<'_> {
1071    fn in_place() -> bool {
1072        false
1073    }
1074
1075    fn can_advance(entry: &StateEntry<P>) -> bool {
1076        entry.flags & Self::DONT_ADVANCE == 0
1077    }
1078
1079    fn is_action_initiable(entry: &StateEntry<P>) -> bool {
1080        entry.flags & Self::SET_MARK != 0
1081    }
1082
1083    fn is_actionable(entry: &StateEntry<P>) -> bool {
1084        (entry.flags & (Self::CURRENT_INSERT_COUNT | Self::MARKED_INSERT_COUNT) != 0)
1085            && (entry.payload.current_insert_index() != 0xFFFF
1086                || entry.payload.marked_insert_index() != 0xFFFF)
1087    }
1088
1089    #[inline(always)]
1090    fn transition(&mut self, entry: &StateEntry<P>, ac: &mut AatApplyContext) -> Option<()> {
1091        let flags = entry.flags;
1092        let mark_loc = ac.buffer.out_len;
1093
1094        if entry.payload.marked_insert_index() != 0xFFFF {
1095            let count = flags & Self::MARKED_INSERT_COUNT;
1096            ac.buffer.max_ops -= i32::from(count);
1097            if ac.buffer.max_ops <= 0 {
1098                return Some(());
1099            }
1100
1101            let start = entry.payload.marked_insert_index();
1102            let before = flags & Self::MARKED_INSERT_BEFORE != 0;
1103
1104            let end = ac.buffer.out_len;
1105            if !ac.buffer.move_to(self.mark as usize) {
1106                return Some(());
1107            }
1108
1109            if ac.buffer.idx < ac.buffer.len && !before {
1110                ac.buffer.copy_glyph();
1111            }
1112
1113            // TODO We ignore KashidaLike setting.
1114            for i in 0..count {
1115                let i = usize::from(start + i);
1116                if ac
1117                    .output_glyph(u32::from(self.glyphs.get(i)?.get().to_u16()))
1118                    .is_none()
1119                {
1120                    ac.buffer.index_failed();
1121                }
1122            }
1123
1124            if ac.buffer.idx < ac.buffer.len && !before {
1125                ac.buffer.skip_glyph();
1126            }
1127
1128            if !ac.buffer.move_to(end + usize::from(count)) {
1129                return Some(());
1130            }
1131
1132            ac.buffer.unsafe_to_break_from_outbuffer(
1133                Some(self.mark as usize),
1134                Some((ac.buffer.idx + 1).min(ac.buffer.len)),
1135            );
1136        }
1137
1138        if flags & Self::SET_MARK != 0 {
1139            self.mark = mark_loc as u32;
1140        }
1141
1142        if entry.payload.current_insert_index() != 0xFFFF {
1143            let count = (flags & Self::CURRENT_INSERT_COUNT) >> 5;
1144            ac.buffer.max_ops -= i32::from(count);
1145            if ac.buffer.max_ops < 0 {
1146                return Some(());
1147            }
1148
1149            let start = entry.payload.current_insert_index();
1150            let before = flags & Self::CURRENT_INSERT_BEFORE != 0;
1151            let end = ac.buffer.out_len;
1152
1153            if ac.buffer.idx < ac.buffer.len && !before {
1154                ac.buffer.copy_glyph();
1155            }
1156
1157            // TODO We ignore KashidaLike setting.
1158            for i in 0..count {
1159                let i = usize::from(start + i);
1160                if ac
1161                    .output_glyph(u32::from(self.glyphs.get(i)?.get().to_u16()))
1162                    .is_none()
1163                {
1164                    ac.buffer.index_failed();
1165                }
1166            }
1167
1168            if ac.buffer.idx < ac.buffer.len && !before {
1169                ac.buffer.skip_glyph();
1170            }
1171
1172            // Humm. Not sure where to move to. There's this wording under
1173            // DontAdvance flag:
1174            //
1175            // "If set, don't update the glyph index before going to the new state.
1176            // This does not mean that the glyph pointed to is the same one as
1177            // before. If you've made insertions immediately downstream of the
1178            // current glyph, the next glyph processed would in fact be the first
1179            // one inserted."
1180            //
1181            // This suggests that if DontAdvance is NOT set, we should move to
1182            // end+count. If it *was*, then move to end, such that newly inserted
1183            // glyphs are now visible.
1184            //
1185            // https://github.com/harfbuzz/harfbuzz/issues/1224#issuecomment-427691417
1186            if !ac.buffer.move_to(if flags & Self::DONT_ADVANCE != 0 {
1187                end
1188            } else {
1189                end + usize::from(count)
1190            }) {
1191                return Some(());
1192            }
1193        }
1194
1195        Some(())
1196    }
1197}
1198
1199const LIGATURE_MAX_MATCHES: usize = 64;
1200
1201trait LigatureActions<P> {
1202    fn action_start(entry: &StateEntry<P>) -> Option<usize>;
1203    fn action(&self, index: usize) -> Option<u32>;
1204    fn next_action(index: usize) -> usize;
1205    fn component(&self, glyph: u32, offset: i32) -> Option<u16>;
1206    fn ligature(&self, index: u32) -> Option<GlyphId16>;
1207}
1208
1209impl LigatureActions<BigEndian<u16>> for morx::LigatureSubtable<'_> {
1210    fn action_start(entry: &StateEntry<BigEndian<u16>>) -> Option<usize> {
1211        (entry.flags & 0x2000 != 0).then(|| usize::from(entry.payload.get()))
1212    }
1213
1214    fn action(&self, index: usize) -> Option<u32> {
1215        self.ligature_actions.get(index).map(|action| action.get())
1216    }
1217
1218    fn next_action(index: usize) -> usize {
1219        index + 1
1220    }
1221
1222    fn component(&self, glyph: u32, offset: i32) -> Option<u16> {
1223        let index = usize::try_from(i64::from(glyph) + i64::from(offset)).ok()?;
1224        self.components.get(index).map(|component| component.get())
1225    }
1226
1227    fn ligature(&self, index: u32) -> Option<GlyphId16> {
1228        self.ligatures.get(index as usize).map(|glyph| glyph.get())
1229    }
1230}
1231
1232impl LigatureActions<NoPayload> for mort::LigatureSubtable<'_> {
1233    fn action_start(entry: &StateEntry) -> Option<usize> {
1234        let offset = entry.flags & 0x3FFF;
1235        (offset != 0).then_some(usize::from(offset))
1236    }
1237
1238    fn action(&self, index: usize) -> Option<u32> {
1239        self.ligature_action(index).ok()
1240    }
1241
1242    fn next_action(index: usize) -> usize {
1243        index + u32::RAW_BYTE_LEN
1244    }
1245
1246    fn component(&self, glyph: u32, offset: i32) -> Option<u16> {
1247        let word_offset = i32::try_from(glyph).ok()?.checked_add(offset)?;
1248        self.component(word_offset).ok()
1249    }
1250
1251    fn ligature(&self, index: u32) -> Option<GlyphId16> {
1252        self.ligature(index as usize).ok()
1253    }
1254}
1255
1256struct LigatureCtx<T> {
1257    table: T,
1258    match_length: usize,
1259    match_positions: [usize; LIGATURE_MAX_MATCHES],
1260}
1261
1262impl<T> LigatureCtx<T> {
1263    const SET_COMPONENT: u16 = 0x8000;
1264    const DONT_ADVANCE: u16 = 0x4000;
1265
1266    const LIG_ACTION_LAST: u32 = 0x8000_0000;
1267    const LIG_ACTION_STORE: u32 = 0x4000_0000;
1268    const LIG_ACTION_OFFSET: u32 = 0x3FFF_FFFF;
1269}
1270
1271impl<P, T> DriverContext<P> for LigatureCtx<T>
1272where
1273    T: LigatureActions<P>,
1274{
1275    fn in_place() -> bool {
1276        false
1277    }
1278
1279    fn can_advance(entry: &StateEntry<P>) -> bool {
1280        entry.flags & Self::DONT_ADVANCE == 0
1281    }
1282
1283    fn is_action_initiable(entry: &StateEntry<P>) -> bool {
1284        entry.flags & Self::SET_COMPONENT != 0
1285    }
1286
1287    fn is_actionable(entry: &StateEntry<P>) -> bool {
1288        T::action_start(entry).is_some()
1289    }
1290
1291    #[inline(always)]
1292    fn transition(&mut self, entry: &StateEntry<P>, ac: &mut AatApplyContext) -> Option<()> {
1293        if entry.flags & Self::SET_COMPONENT != 0 {
1294            // Never mark same index twice, in case DONT_ADVANCE was used...
1295            if self.match_length != 0
1296                && self.match_positions[(self.match_length - 1) % LIGATURE_MAX_MATCHES]
1297                    == ac.buffer.out_len
1298            {
1299                self.match_length -= 1;
1300            }
1301
1302            self.match_positions[self.match_length % LIGATURE_MAX_MATCHES] = ac.buffer.out_len;
1303            self.match_length += 1;
1304        }
1305
1306        if let Some(mut ligature_actions_index) = T::action_start(entry) {
1307            let end = ac.buffer.out_len;
1308
1309            if self.match_length == 0 {
1310                return Some(());
1311            }
1312
1313            if ac.buffer.idx >= ac.buffer.len {
1314                return Some(()); // TODO: Work on previous instead?
1315            }
1316
1317            let mut cursor = self.match_length;
1318
1319            let mut ligature_idx = 0u32;
1320            loop {
1321                if cursor == 0 {
1322                    // Stack underflow. Clear the stack.
1323                    self.match_length = 0;
1324                    break;
1325                }
1326
1327                cursor -= 1;
1328                if !ac
1329                    .buffer
1330                    .move_to(self.match_positions[cursor % LIGATURE_MAX_MATCHES])
1331                {
1332                    return Some(());
1333                }
1334
1335                // We cannot use ? in this loop, because we must call
1336                // ac.buffer.move_to(end) in the end.
1337                let Some(action) = self.table.action(ligature_actions_index) else {
1338                    break;
1339                };
1340
1341                let mut uoffset = action & Self::LIG_ACTION_OFFSET;
1342                if uoffset & 0x2000_0000 != 0 {
1343                    uoffset |= 0xC000_0000; // Sign-extend.
1344                }
1345
1346                let offset = uoffset as i32;
1347                let component = match self.table.component(ac.buffer.cur(0)?.glyph_id, offset) {
1348                    Some(component) => u32::from(component),
1349                    None => break,
1350                };
1351                let Some(next_ligature_idx) = ligature_idx.checked_add(component) else {
1352                    break;
1353                };
1354                ligature_idx = next_ligature_idx;
1355
1356                if (action & (Self::LIG_ACTION_STORE | Self::LIG_ACTION_LAST)) != 0 {
1357                    let Some(lig) = self.table.ligature(ligature_idx) else {
1358                        break;
1359                    };
1360
1361                    if ac.replace_glyph(u32::from(lig.to_u16())).is_none() {
1362                        ac.buffer.index_failed();
1363                    }
1364
1365                    let lig_end =
1366                        self.match_positions[(self.match_length - 1) % LIGATURE_MAX_MATCHES] + 1;
1367                    // Now go and delete all subsequent components.
1368                    while self.match_length - 1 > cursor {
1369                        self.match_length -= 1;
1370                        if !ac
1371                            .buffer
1372                            .move_to(self.match_positions[self.match_length % LIGATURE_MAX_MATCHES])
1373                        {
1374                            return Some(());
1375                        }
1376                        if ac.delete_glyph().is_none() {
1377                            ac.buffer.index_failed();
1378                        }
1379                    }
1380
1381                    if !ac.buffer.move_to(lig_end) {
1382                        return Some(());
1383                    }
1384                    ac.buffer.merge_out_clusters(
1385                        self.match_positions[cursor % LIGATURE_MAX_MATCHES],
1386                        ac.buffer.out_len,
1387                    );
1388                }
1389
1390                ligature_actions_index = T::next_action(ligature_actions_index);
1391
1392                if action & Self::LIG_ACTION_LAST != 0 {
1393                    break;
1394                }
1395            }
1396
1397            if !ac.buffer.move_to(end) {
1398                return Some(());
1399            }
1400        }
1401
1402        Some(())
1403    }
1404}
1405
1406/// Flat, packed per-subtable filter state: everything the per-buffer walk
1407/// needs to decide whether a subtable applies, in one small contiguous
1408/// array that stays cache-resident. The heavy state (glyph set, class
1409/// cache, parts) lives in [MorphSubtableCache] and is only touched once a
1410/// subtable passes these filters.
1411pub(crate) struct MorphSubtableDescriptor {
1412    pub(crate) chain_index: u32,
1413    pub(crate) coverage: u32,
1414    pub(crate) sub_feature_flags: u32,
1415}
1416
1417enum MorphSubtableKind<'a> {
1418    Morx(morx::SubtableKind<'a>),
1419    Mort(mort::SubtableKind<'a>),
1420}
1421
1422pub(crate) struct MorphSubtableCache<'a> {
1423    start_end_safe_to_break: u64,
1424    safe_to_break: SafeToBreakSubtable,
1425    glyph_set: U32Set,
1426    glyph_digest: SetDigest,
1427    class_cache: ClassCache,
1428    /// The parsed subtable, or `None` if it is unreadable.
1429    kind: Option<MorphSubtableKind<'a>>,
1430}
1431
1432fn accelerate_state_machine<T, M, Ctx>(
1433    machine: &M,
1434    data: &[u8],
1435    num_glyphs: u32,
1436    safe_to_break: &mut SafeToBreakAccel,
1437    start_end_safe_to_break: &mut u64,
1438    safe_to_break_subtable: &mut SafeToBreakSubtable,
1439    glyph_set: &mut U32Set,
1440) where
1441    T: FixedSize + bytemuck::AnyBitPattern,
1442    M: MorphStateTable<T>,
1443    Ctx: DriverContext<T>,
1444{
1445    *start_end_safe_to_break = collect_start_end_safe_to_break::<T, M, Ctx>(machine);
1446    *safe_to_break_subtable =
1447        machine.build_safe_to_break(safe_to_break, data, &Ctx::is_actionable, &Ctx::can_advance);
1448    collect_initial_glyphs::<T, M, Ctx>(machine, glyph_set, num_glyphs);
1449}
1450
1451impl<'a> MorphSubtableCache<'a> {
1452    pub(crate) fn descriptor_morx(
1453        chain_index: usize,
1454        subtable: &morx::Subtable,
1455    ) -> MorphSubtableDescriptor {
1456        MorphSubtableDescriptor {
1457            chain_index: chain_index as u32,
1458            coverage: subtable.coverage(),
1459            sub_feature_flags: subtable.sub_feature_flags(),
1460        }
1461    }
1462
1463    pub(crate) fn descriptor_mort(
1464        chain_index: usize,
1465        subtable: &mort::Subtable,
1466    ) -> MorphSubtableDescriptor {
1467        MorphSubtableDescriptor {
1468            chain_index: chain_index as u32,
1469            // Normalize legacy coverage flags to the `morx` bit positions
1470            // consumed by the shared application loop.
1471            coverage: u32::from(subtable.coverage()) << 16,
1472            sub_feature_flags: subtable.sub_feature_flags(),
1473        }
1474    }
1475
1476    pub(crate) fn new_morx(
1477        subtable: &morx::Subtable<'a>,
1478        num_glyphs: u32,
1479        safe_to_break: &mut SafeToBreakAccel,
1480    ) -> Self {
1481        let mut start_end_safe_to_break = 0u64;
1482        let mut safe_to_break_subtable = safe_to_break.empty_subtable();
1483        let mut glyph_set = U32Set::default();
1484        let kind = subtable.kind().ok();
1485        if let Some(kind) = &kind {
1486            match kind {
1487                morx::SubtableKind::Rearrangement(table) => {
1488                    accelerate_state_machine::<_, _, RearrangementCtx>(
1489                        table,
1490                        subtable.data(),
1491                        num_glyphs,
1492                        safe_to_break,
1493                        &mut start_end_safe_to_break,
1494                        &mut safe_to_break_subtable,
1495                        &mut glyph_set,
1496                    );
1497                }
1498                morx::SubtableKind::Contextual(table) => {
1499                    accelerate_state_machine::<_, _, ContextualCtx<morx::ContextualSubtable<'_>>>(
1500                        &table.state_table,
1501                        subtable.data(),
1502                        num_glyphs,
1503                        safe_to_break,
1504                        &mut start_end_safe_to_break,
1505                        &mut safe_to_break_subtable,
1506                        &mut glyph_set,
1507                    );
1508                }
1509                morx::SubtableKind::Ligature(table) => {
1510                    accelerate_state_machine::<_, _, LigatureCtx<morx::LigatureSubtable<'_>>>(
1511                        &table.state_table,
1512                        subtable.data(),
1513                        num_glyphs,
1514                        safe_to_break,
1515                        &mut start_end_safe_to_break,
1516                        &mut safe_to_break_subtable,
1517                        &mut glyph_set,
1518                    );
1519                }
1520                morx::SubtableKind::NonContextual(ref lookup) => {
1521                    lookup.collect_glyphs(&mut glyph_set, num_glyphs);
1522                }
1523                morx::SubtableKind::Insertion(table) => {
1524                    accelerate_state_machine::<_, _, InsertionCtx<'_>>(
1525                        &table.state_table,
1526                        subtable.data(),
1527                        num_glyphs,
1528                        safe_to_break,
1529                        &mut start_end_safe_to_break,
1530                        &mut safe_to_break_subtable,
1531                        &mut glyph_set,
1532                    );
1533                }
1534            }
1535        }
1536        MorphSubtableCache {
1537            start_end_safe_to_break,
1538            safe_to_break: safe_to_break_subtable,
1539            glyph_digest: set_digest(&glyph_set),
1540            glyph_set,
1541            class_cache: ClassCache::new(),
1542            kind: kind.map(MorphSubtableKind::Morx),
1543        }
1544    }
1545
1546    pub(crate) fn new_mort(
1547        subtable: &mort::Subtable<'a>,
1548        num_glyphs: u32,
1549        safe_to_break: &mut SafeToBreakAccel,
1550    ) -> Self {
1551        let mut start_end_safe_to_break = 0u64;
1552        let mut safe_to_break_subtable = safe_to_break.empty_subtable();
1553        let mut glyph_set = U32Set::default();
1554        let kind = subtable.kind().ok();
1555        if let Some(kind) = &kind {
1556            match kind {
1557                mort::SubtableKind::Rearrangement(table) => {
1558                    accelerate_state_machine::<_, _, RearrangementCtx>(
1559                        table,
1560                        subtable.data(),
1561                        num_glyphs,
1562                        safe_to_break,
1563                        &mut start_end_safe_to_break,
1564                        &mut safe_to_break_subtable,
1565                        &mut glyph_set,
1566                    );
1567                }
1568                mort::SubtableKind::Contextual(table) => {
1569                    accelerate_state_machine::<_, _, ContextualCtx<mort::ContextualSubtable<'_>>>(
1570                        &table.state_table,
1571                        subtable.data(),
1572                        num_glyphs,
1573                        safe_to_break,
1574                        &mut start_end_safe_to_break,
1575                        &mut safe_to_break_subtable,
1576                        &mut glyph_set,
1577                    );
1578                }
1579                mort::SubtableKind::Ligature(table) => {
1580                    accelerate_state_machine::<_, _, LigatureCtx<mort::LigatureSubtable<'_>>>(
1581                        &table.state_table,
1582                        subtable.data(),
1583                        num_glyphs,
1584                        safe_to_break,
1585                        &mut start_end_safe_to_break,
1586                        &mut safe_to_break_subtable,
1587                        &mut glyph_set,
1588                    );
1589                }
1590                mort::SubtableKind::NonContextual(ref lookup) => {
1591                    lookup.collect_glyphs(&mut glyph_set, num_glyphs);
1592                }
1593                mort::SubtableKind::Insertion(table) => {
1594                    accelerate_state_machine::<_, _, InsertionCtx<'_>>(
1595                        &table.state_table,
1596                        subtable.data(),
1597                        num_glyphs,
1598                        safe_to_break,
1599                        &mut start_end_safe_to_break,
1600                        &mut safe_to_break_subtable,
1601                        &mut glyph_set,
1602                    );
1603                }
1604            }
1605        }
1606        MorphSubtableCache {
1607            start_end_safe_to_break,
1608            safe_to_break: safe_to_break_subtable,
1609            glyph_digest: set_digest(&glyph_set),
1610            glyph_set,
1611            class_cache: ClassCache::new(),
1612            kind: kind.map(MorphSubtableKind::Mort),
1613        }
1614    }
1615}