garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /ttf/src/layout.rs

raw

//! OpenType layout: what a font says about which glyphs a run of
//! characters becomes (`GSUB`) and where each goes (`GPOS`), with the
//! glyph classes both lean on (`GDEF`).
//!
//! A shaper (`pinnacle-text`) fills a [`Buffer`] with one glyph a
//! character, each with a mask saying which features apply to it (Arabic's
//! initial, medial and final forms are set per letter), asks for the
//! lookups of the features it wants ([`Layout::lookups`]), and runs them in
//! the font's order. Read: substitution lookups 1–7 (single, multiple,
//! alternate as its first, ligature, context and chained context in all
//! three formats, extension), positioning lookups 1, 2, 4, 5, 6, 7, 8 and 9
//! (single and pair adjustment, marks to bases, ligatures and marks,
//! context, extension), lookup flags and mark filtering sets. Not read:
//! reverse chained substitution (8), cursive attachment (3), device tables,
//! variations.

use alloc::vec::Vec;

use super::{be16, be32, bei16};

/// A glyph as layout moves it, in font units.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Info {
    pub glyph: u16,
    /// The character it came from: its index in the text, kept through
    /// substitutions (a ligature takes its first character's).
    pub cluster: u32,
    /// Which features apply to it (bits the shaper chose).
    pub mask: u32,
    /// From `hmtx`, then adjusted.
    pub advance: i32,
    pub dx: i32,
    pub dy: i32,
    /// A mark attached to the glyph at this index: `dx` and `dy` are then
    /// from that glyph's origin rather than this one's pen.
    pub attached: Option<u32>,
}

/// The glyphs being laid out, in the text's logical order.
pub type Buffer = Vec<Info>;

/// A glyph's class in `GDEF`.
const BASE: u16 = 1;
const LIGATURE: u16 = 2;
const MARK: u16 = 3;

/// Lookup flags.
const IGNORE_BASE: u16 = 2;
const IGNORE_LIGATURES: u16 = 4;
const IGNORE_MARKS: u16 = 8;
const MARK_FILTERING_SET: u16 = 0x10;

/// How deep context lookups may call each other.
const DEPTH: u8 = 8;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Table {
    Gsub,
    Gpos,
}

/// A font's layout tables, as far as it has them.
#[derive(Clone, Copy)]
pub struct Layout<'a> {
    d: &'a [u8],
    gsub: Option<usize>,
    gpos: Option<usize>,
    gdef: Option<usize>,
}

/// One lookup of a table, with where its flags and subtables are.
#[derive(Clone, Copy)]
struct Lookup {
    kind: u16,
    flags: u16,
    filter: Option<usize>,
    at: usize,
    subtables: u16,
}

fn get16(d: &[u8], at: usize) -> u16 {
    be16(d, at).unwrap_or(0)
}

impl<'a> Layout<'a> {
    pub fn new(font: &super::Font<'a>) -> Layout<'a> {
        Layout {
            d: font.data(),
            gsub: font.table(b"GSUB"),
            gpos: font.table(b"GPOS"),
            gdef: font.table(b"GDEF"),
        }
    }

    pub fn has(&self, table: Table) -> bool {
        self.base(table).is_some()
    }

    fn base(&self, table: Table) -> Option<usize> {
        match table {
            Table::Gsub => self.gsub,
            Table::Gpos => self.gpos,
        }
    }

    /// The lookups that make up `features` (tag and the mask a glyph needs
    /// to have them) for `script`, in the order the font applies them: by
    /// their index in the lookup list. A lookup in two features takes both
    /// masks. The script's default language; `DFLT` when the font has no
    /// such script, then the first script it has.
    pub fn lookups(&self, table: Table, script: &[u8; 4], features: &[([u8; 4], u32)]) -> Vec<(u16, u32)> {
        let mut out: Vec<(u16, u32)> = Vec::new();
        let Some(base) = self.base(table) else {
            return out;
        };
        let d = self.d;
        let scripts = base + usize::from(get16(d, base + 4));
        let feature_list = base + usize::from(get16(d, base + 6));
        let count = usize::from(get16(d, scripts));
        let find = |tag: &[u8; 4]| {
            (0..count)
                .map(|i| scripts + 2 + i * 6)
                .find(|&at| d.get(at..at + 4) == Some(tag))
                .map(|at| scripts + usize::from(get16(d, at + 4)))
        };
        let script_at = find(script)
            .or_else(|| find(b"DFLT"))
            .or_else(|| (count > 0).then(|| scripts + usize::from(get16(d, scripts + 6))));
        let Some(script_at) = script_at else {
            return out;
        };
        let lang = get16(d, script_at);
        if lang == 0 {
            return out;
        }
        let lang = script_at + usize::from(lang);
        let indices = usize::from(get16(d, lang + 4));
        for k in 0..indices {
            let f = usize::from(get16(d, lang + 6 + k * 2));
            let record = feature_list + 2 + f * 6;
            let Some(tag) = d.get(record..record + 4) else {
                continue;
            };
            let Some(&(_, mask)) = features.iter().find(|(t, _)| t == tag) else {
                continue;
            };
            let feature = feature_list + usize::from(get16(d, record + 4));
            for l in 0..usize::from(get16(d, feature + 2)) {
                let index = get16(d, feature + 4 + l * 2);
                match out.binary_search_by_key(&index, |&(i, _)| i) {
                    Ok(i) => out[i].1 |= mask,
                    Err(i) => out.insert(i, (index, mask)),
                }
            }
        }
        out
    }

    fn lookup(&self, table: Table, index: u16) -> Option<Lookup> {
        let base = self.base(table)?;
        let d = self.d;
        let list = base + usize::from(be16(d, base + 8)?);
        if index >= be16(d, list)? {
            return None;
        }
        let at = list + usize::from(be16(d, list + 2 + usize::from(index) * 2)?);
        let flags = be16(d, at + 2)?;
        let subtables = be16(d, at + 4)?;
        let filter = (flags & MARK_FILTERING_SET != 0)
            .then(|| be16(d, at + 6 + usize::from(subtables) * 2))
            .flatten()
            .and_then(|set| self.mark_set(set));
        Some(Lookup {
            kind: be16(d, at)?,
            flags,
            filter,
            at,
            subtables,
        })
    }

    /// Where mark filtering set `set` of `GDEF` is.
    fn mark_set(&self, set: u16) -> Option<usize> {
        let gdef = self.gdef?;
        let d = self.d;
        if be32(d, gdef)? < 0x0001_0002 {
            return None;
        }
        let sets = usize::from(be16(d, gdef + 12)?);
        if sets == 0 {
            return None;
        }
        let sets = gdef + sets;
        if set >= be16(d, sets + 2)? {
            return None;
        }
        Some(sets + be32(d, sets + 4 + usize::from(set) * 4)? as usize)
    }

    /// A glyph's class in `GDEF` (base, ligature, mark, component), 0 when
    /// it has none.
    pub fn class(&self, glyph: u16) -> u16 {
        self.gdef
            .and_then(|g| {
                let at = be16(self.d, g + 4)?;
                (at != 0).then(|| class_of(self.d, g + usize::from(at), glyph))
            })
            .unwrap_or(0)
    }

    fn attach_class(&self, glyph: u16) -> u16 {
        self.gdef
            .and_then(|g| {
                let at = be16(self.d, g + 10)?;
                (at != 0).then(|| class_of(self.d, g + usize::from(at), glyph))
            })
            .unwrap_or(0)
    }

    /// Whether lookup `l` passes over `glyph`, as its flags say.
    fn skips(&self, l: &Lookup, glyph: u16) -> bool {
        let class = self.class(glyph);
        match class {
            BASE => l.flags & IGNORE_BASE != 0,
            LIGATURE => l.flags & IGNORE_LIGATURES != 0,
            MARK => {
                if l.flags & IGNORE_MARKS != 0 {
                    return true;
                }
                if let Some(set) = l.filter {
                    return coverage(self.d, set, glyph).is_none();
                }
                let wanted = l.flags >> 8;
                wanted != 0 && self.attach_class(glyph) != wanted
            }
            _ => false,
        }
    }

    fn next(&self, l: &Lookup, buf: &[Info], mut i: usize) -> Option<usize> {
        loop {
            i += 1;
            let info = buf.get(i)?;
            if !self.skips(l, info.glyph) {
                return Some(i);
            }
        }
    }

    fn prev(&self, l: &Lookup, buf: &[Info], mut i: usize) -> Option<usize> {
        loop {
            i = i.checked_sub(1)?;
            if !self.skips(l, buf[i].glyph) {
                return Some(i);
            }
        }
    }

    /// Runs `lookups` (from [`Layout::lookups`]) over `buf`, each over the
    /// whole buffer before the next, on the glyphs whose mask it has.
    pub fn apply(&self, table: Table, lookups: &[(u16, u32)], buf: &mut Buffer) {
        for &(index, mask) in lookups {
            let Some(l) = self.lookup(table, index) else {
                continue;
            };
            let mut i = 0;
            while i < buf.len() {
                if buf[i].mask & mask == 0 || self.skips(&l, buf[i].glyph) {
                    i += 1;
                    continue;
                }
                i = match self.apply_at(table, &l, buf, i, 0) {
                    Some(next) => next.max(i + 1).min(buf.len().max(i + 1)),
                    None => i + 1,
                };
            }
        }
    }

    /// Lookup `l` at glyph `i`, its first subtable that applies: where
    /// the next glyph to look at is, or `None` when none applied.
    fn apply_at(&self, table: Table, l: &Lookup, buf: &mut Buffer, i: usize, depth: u8) -> Option<usize> {
        for s in 0..usize::from(l.subtables) {
            let Some(offset) = be16(self.d, l.at + 6 + s * 2) else {
                continue;
            };
            let mut at = l.at + usize::from(offset);
            let mut kind = l.kind;
            let extension = match table {
                Table::Gsub => 7,
                Table::Gpos => 9,
            };
            if kind == extension {
                kind = get16(self.d, at + 2);
                at += be32(self.d, at + 4).unwrap_or(0) as usize;
            }
            let applied = match table {
                Table::Gsub => self.substitute(l, kind, at, buf, i, depth),
                Table::Gpos => self.position(l, kind, at, buf, i, depth),
            };
            if applied.is_some() {
                return applied;
            }
        }
        None
    }

    fn substitute(
        &self,
        l: &Lookup,
        kind: u16,
        at: usize,
        buf: &mut Buffer,
        i: usize,
        depth: u8,
    ) -> Option<usize> {
        let d = self.d;
        let glyph = buf[i].glyph;
        match kind {
            1 => {
                let k = coverage(d, at + usize::from(be16(d, at + 2)?), glyph)?;
                let new = match be16(d, at)? {
                    1 => glyph.wrapping_add(be16(d, at + 4)?),
                    2 => be16(d, at + 6 + k * 2)?,
                    _ => return None,
                };
                buf[i].glyph = new;
                Some(i + 1)
            }
            2 | 3 => {
                let k = coverage(d, at + usize::from(be16(d, at + 2)?), glyph)?;
                if k >= usize::from(be16(d, at + 4)?) {
                    return None;
                }
                let seq = at + usize::from(be16(d, at + 6 + k * 2)?);
                let n = usize::from(be16(d, seq)?);
                if kind == 3 {
                    // An alternate: the first.
                    buf[i].glyph = be16(d, seq + 2).filter(|_| n > 0)?;
                    return Some(i + 1);
                }
                let template = buf[i];
                buf.remove(i);
                for g in 0..n {
                    let glyph = be16(d, seq + 2 + g * 2)?;
                    buf.insert(i + g, Info { glyph, ..template });
                }
                Some(i + n)
            }
            4 => {
                let k = coverage(d, at + usize::from(be16(d, at + 2)?), glyph)?;
                if k >= usize::from(be16(d, at + 4)?) {
                    return None;
                }
                let set = at + usize::from(be16(d, at + 6 + k * 2)?);
                'ligatures: for n in 0..usize::from(be16(d, set)?) {
                    let lig = set + usize::from(be16(d, set + 2 + n * 2)?);
                    let components = usize::from(be16(d, lig + 2)?);
                    let mut found = Vec::new();
                    let mut j = i;
                    for c in 1..components {
                        let Some(next) = self.next(l, buf, j) else {
                            continue 'ligatures;
                        };
                        if buf[next].glyph != be16(d, lig + 4 + (c - 1) * 2)? {
                            continue 'ligatures;
                        }
                        found.push(next);
                        j = next;
                    }
                    buf[i].glyph = be16(d, lig)?;
                    for &f in found.iter().rev() {
                        buf.remove(f);
                    }
                    return Some(i + 1);
                }
                None
            }
            5 | 6 => self.context(Table::Gsub, l, kind == 6, at, buf, i, depth),
            _ => None,
        }
    }

    fn position(
        &self,
        l: &Lookup,
        kind: u16,
        at: usize,
        buf: &mut Buffer,
        i: usize,
        depth: u8,
    ) -> Option<usize> {
        let d = self.d;
        let glyph = buf[i].glyph;
        match kind {
            1 => {
                let k = coverage(d, at + usize::from(be16(d, at + 2)?), glyph)?;
                let format = be16(d, at + 4)?;
                let value = match be16(d, at)? {
                    1 => at + 6,
                    2 => at + 8 + k * value_size(format),
                    _ => return None,
                };
                adjust(d, format, value, &mut buf[i]);
                Some(i + 1)
            }
            2 => {
                let k = coverage(d, at + usize::from(be16(d, at + 2)?), glyph)?;
                let j = self.next(l, buf, i)?;
                let second = buf[j].glyph;
                let (f1, f2) = (be16(d, at + 4)?, be16(d, at + 6)?);
                let (s1, s2) = (value_size(f1), value_size(f2));
                let values = match be16(d, at)? {
                    1 => {
                        if k >= usize::from(be16(d, at + 8)?) {
                            return None;
                        }
                        let set = at + usize::from(be16(d, at + 10 + k * 2)?);
                        let record = 2 + s1 + s2;
                        (0..usize::from(be16(d, set)?))
                            .map(|r| set + 2 + r * record)
                            .find(|&r| be16(d, r) == Some(second))
                            .map(|r| r + 2)?
                    }
                    2 => {
                        let c1 = class_of(d, at + usize::from(be16(d, at + 8)?), glyph);
                        let c2 = class_of(d, at + usize::from(be16(d, at + 10)?), second);
                        let (n1, n2) = (be16(d, at + 12)?, be16(d, at + 14)?);
                        if c1 >= n1 || c2 >= n2 {
                            return None;
                        }
                        at + 16 + (usize::from(c1) * usize::from(n2) + usize::from(c2)) * (s1 + s2)
                    }
                    _ => return None,
                };
                adjust(d, f1, values, &mut buf[i]);
                if f2 != 0 {
                    adjust(d, f2, values + s1, &mut buf[j]);
                    return Some(j + 1);
                }
                Some(j)
            }
            4..=6 => {
                let marks = at + usize::from(be16(d, at + 2)?);
                let m = coverage(d, marks, glyph)?;
                // The glyph it goes on: for 4 and 5 the last before it that
                // is not a mark, for 6 the mark just before it.
                let target = if kind == 6 {
                    let p = self.prev(l, buf, i)?;
                    (self.class(buf[p].glyph) == MARK).then_some(p)?
                } else {
                    (0..i).rev().find(|&p| self.class(buf[p].glyph) != MARK)?
                };
                let b = coverage(d, at + usize::from(be16(d, at + 4)?), buf[target].glyph)?;
                let classes = usize::from(be16(d, at + 6)?);
                let mark_array = at + usize::from(be16(d, at + 8)?);
                let base_array = at + usize::from(be16(d, at + 10)?);
                let record = mark_array + 2 + m * 4;
                let class = usize::from(be16(d, record)?);
                if class >= classes {
                    return None;
                }
                let mark_anchor = mark_array + usize::from(be16(d, record + 2)?);
                let base_anchor = if kind == 5 {
                    // A ligature: its last component's anchor.
                    let lig = base_array + usize::from(be16(d, base_array + 2 + b * 2)?);
                    let components = usize::from(be16(d, lig)?);
                    let last = components.checked_sub(1)?;
                    let a = be16(d, lig + 2 + (last * classes + class) * 2)?;
                    (a != 0).then(|| lig + usize::from(a))?
                } else {
                    let a = be16(d, base_array + 2 + (b * classes + class) * 2)?;
                    (a != 0).then(|| base_array + usize::from(a))?
                };
                let (bx, by) = anchor(d, base_anchor)?;
                let (mx, my) = anchor(d, mark_anchor)?;
                let mark = &mut buf[i];
                mark.attached = Some(target as u32);
                mark.dx = bx - mx;
                mark.dy = by - my;
                Some(i + 1)
            }
            7 | 8 => self.context(Table::Gpos, l, kind == 8, at, buf, i, depth),
            _ => None,
        }
    }

    /// Context and chained context lookups, all three formats: whether the
    /// glyphs at and around `i` match a rule, and if one does, its lookups
    /// run at the places in the input it names.
    #[allow(clippy::too_many_arguments)]
    fn context(
        &self,
        table: Table,
        l: &Lookup,
        chained: bool,
        at: usize,
        buf: &mut Buffer,
        i: usize,
        depth: u8,
    ) -> Option<usize> {
        let d = self.d;
        let glyph = buf[i].glyph;
        let format = be16(d, at)?;
        // Each rule as three sequences of tests and the lookup records.
        let mut rules: Vec<Rule> = Vec::new();
        match format {
            1 | 2 => {
                let k = coverage(d, at + usize::from(be16(d, at + 2)?), glyph)?;
                let (sets_at, set_index, classes) = if format == 1 {
                    (at + 4, k, [None; 3])
                } else if chained {
                    let cd = |o: usize| {
                        let v = get16(d, at + o);
                        (v != 0).then(|| at + usize::from(v))
                    };
                    let (back, input, ahead) = (cd(4), cd(6), cd(8));
                    let c = input.map_or(0, |cd| class_of(d, cd, glyph));
                    (at + 10, usize::from(c), [back, input, ahead])
                } else {
                    let input = at + usize::from(be16(d, at + 4)?);
                    (
                        at + 6,
                        usize::from(class_of(d, input, glyph)),
                        [None, Some(input), None],
                    )
                };
                if set_index >= usize::from(be16(d, sets_at)?) {
                    return None;
                }
                let set = be16(d, sets_at + 2 + set_index * 2)?;
                if set == 0 {
                    return None;
                }
                let set = at + usize::from(set);
                let by = |n: usize| {
                    if format == 1 {
                        Test::Glyph
                    } else {
                        Test::Class(classes[n])
                    }
                };
                for r in 0..usize::from(be16(d, set)?) {
                    let rule = set + usize::from(be16(d, set + 2 + r * 2)?);
                    rules.push(if chained {
                        let back = usize::from(be16(d, rule)?);
                        let input_at = rule + 2 + back * 2;
                        let input = usize::from(be16(d, input_at)?);
                        let ahead_at = input_at + 2 + input.saturating_sub(1) * 2;
                        let ahead = usize::from(be16(d, ahead_at)?);
                        let records_at = ahead_at + 2 + ahead * 2;
                        Rule {
                            back: (rule + 2, back, by(0)),
                            input: (input_at + 2, input.saturating_sub(1), by(1)),
                            ahead: (ahead_at + 2, ahead, by(2)),
                            records: (records_at + 2, usize::from(be16(d, records_at)?)),
                        }
                    } else {
                        let input = usize::from(be16(d, rule)?);
                        let count = usize::from(be16(d, rule + 2)?);
                        Rule {
                            back: (0, 0, Test::Glyph),
                            input: (rule + 4, input.saturating_sub(1), by(1)),
                            ahead: (0, 0, Test::Glyph),
                            records: (rule + 4 + input.saturating_sub(1) * 2, count),
                        }
                    });
                }
            }
            3 => {
                // Coverage per place, the first input's included.
                if chained {
                    let back = usize::from(be16(d, at + 2)?);
                    let input_at = at + 4 + back * 2;
                    let input = usize::from(be16(d, input_at)?);
                    let ahead_at = input_at + 2 + input * 2;
                    let ahead = usize::from(be16(d, ahead_at)?);
                    let records_at = ahead_at + 2 + ahead * 2;
                    if input == 0 || coverage(d, at + usize::from(be16(d, input_at + 2)?), glyph).is_none() {
                        return None;
                    }
                    rules.push(Rule {
                        back: (at + 4, back, Test::Coverage(at)),
                        input: (input_at + 4, input - 1, Test::Coverage(at)),
                        ahead: (ahead_at + 2, ahead, Test::Coverage(at)),
                        records: (records_at + 2, usize::from(be16(d, records_at)?)),
                    });
                } else {
                    let input = usize::from(be16(d, at + 2)?);
                    let count = usize::from(be16(d, at + 4)?);
                    if input == 0 || coverage(d, at + usize::from(be16(d, at + 6)?), glyph).is_none() {
                        return None;
                    }
                    rules.push(Rule {
                        back: (0, 0, Test::Glyph),
                        input: (at + 8, input - 1, Test::Coverage(at)),
                        ahead: (0, 0, Test::Glyph),
                        records: (at + 6 + input * 2, count),
                    });
                }
            }
            _ => return None,
        }
        for rule in rules {
            let Some(places) = self.matches(l, &rule, buf, i) else {
                continue;
            };
            let end = *places.last().unwrap_or(&i);
            if depth >= DEPTH {
                return Some(end + 1);
            }
            let before = buf.len();
            let mut places = places;
            let (records, count) = rule.records;
            for r in 0..count {
                let (Some(seq), Some(index)) = (be16(d, records + r * 4), be16(d, records + r * 4 + 2))
                else {
                    continue;
                };
                let Some(&place) = places.get(usize::from(seq)) else {
                    continue;
                };
                let Some(nested) = self.lookup(table, index) else {
                    continue;
                };
                if place >= buf.len() {
                    continue;
                }
                let len = buf.len();
                self.apply_at(table, &nested, buf, place, depth + 1);
                // A nested lookup may have added or removed glyphs: the
                // places after it move by as many.
                let grown = buf.len() as isize - len as isize;
                if grown != 0 {
                    for p in places.iter_mut().filter(|p| **p > place) {
                        *p = (*p as isize + grown).max(place as isize) as usize;
                    }
                }
            }
            let grown = buf.len() as isize - before as isize;
            return Some((end as isize + 1 + grown).max(i as isize + 1) as usize);
        }
        None
    }

    /// Where a rule's input glyphs are, the first at `i`, when its
    /// backtrack, input and lookahead all match.
    fn matches(&self, l: &Lookup, rule: &Rule, buf: &[Info], i: usize) -> Option<Vec<usize>> {
        let d = self.d;
        let test = |t: Test, at: usize, k: usize, glyph: u16| -> bool {
            let v = get16(d, at + k * 2);
            match t {
                Test::Glyph => glyph == v,
                Test::Class(cd) => cd.map_or(0, |cd| class_of(d, cd, glyph)) == v,
                Test::Coverage(base) => coverage(d, base + usize::from(v), glyph).is_some(),
            }
        };
        let mut places = alloc::vec![i];
        let (at, n, t) = rule.input;
        let mut j = i;
        for k in 0..n {
            j = self.next(l, buf, j)?;
            if !test(t, at, k, buf[j].glyph) {
                return None;
            }
            places.push(j);
        }
        let (at, n, t) = rule.ahead;
        for k in 0..n {
            j = self.next(l, buf, j)?;
            if !test(t, at, k, buf[j].glyph) {
                return None;
            }
        }
        let (at, n, t) = rule.back;
        let mut j = i;
        for k in 0..n {
            j = self.prev(l, buf, j)?;
            if !test(t, at, k, buf[j].glyph) {
                return None;
            }
        }
        Some(places)
    }
}

/// How a rule's sequence is compared: values are glyphs, classes in a
/// class definition, or offsets to coverage tables from the subtable.
#[derive(Clone, Copy)]
enum Test {
    Glyph,
    Class(Option<usize>),
    Coverage(usize),
}

/// A context rule: each sequence's values (where, how many, compared how)
/// and its lookup records (where, how many).
struct Rule {
    back: (usize, usize, Test),
    input: (usize, usize, Test),
    ahead: (usize, usize, Test),
    records: (usize, usize),
}

/// A glyph's index in a coverage table, if it is covered.
fn coverage(d: &[u8], at: usize, glyph: u16) -> Option<usize> {
    let count = usize::from(be16(d, at + 2)?);
    match be16(d, at)? {
        1 => {
            let (mut lo, mut hi) = (0, count);
            while lo < hi {
                let mid = (lo + hi) / 2;
                let g = be16(d, at + 4 + mid * 2)?;
                if glyph < g {
                    hi = mid;
                } else if glyph > g {
                    lo = mid + 1;
                } else {
                    return Some(mid);
                }
            }
            None
        }
        2 => {
            let (mut lo, mut hi) = (0, count);
            while lo < hi {
                let mid = (lo + hi) / 2;
                let r = at + 4 + mid * 6;
                let (start, end) = (be16(d, r)?, be16(d, r + 2)?);
                if glyph < start {
                    hi = mid;
                } else if glyph > end {
                    lo = mid + 1;
                } else {
                    return Some(usize::from(be16(d, r + 4)? + glyph - start));
                }
            }
            None
        }
        _ => None,
    }
}

/// A glyph's class in a class definition, 0 when it is not listed.
fn class_of(d: &[u8], at: usize, glyph: u16) -> u16 {
    let found = || -> Option<u16> {
        match be16(d, at)? {
            1 => {
                let start = be16(d, at + 2)?;
                let count = be16(d, at + 4)?;
                let k = glyph.checked_sub(start).filter(|&k| k < count)?;
                be16(d, at + 6 + usize::from(k) * 2)
            }
            2 => {
                let count = usize::from(be16(d, at + 2)?);
                let (mut lo, mut hi) = (0, count);
                while lo < hi {
                    let mid = (lo + hi) / 2;
                    let r = at + 4 + mid * 6;
                    let (start, end) = (be16(d, r)?, be16(d, r + 2)?);
                    if glyph < start {
                        hi = mid;
                    } else if glyph > end {
                        lo = mid + 1;
                    } else {
                        return be16(d, r + 4);
                    }
                }
                None
            }
            _ => None,
        }
    };
    found().unwrap_or(0)
}

/// A value record's size in bytes, by its format's bits.
fn value_size(format: u16) -> usize {
    (format & 0xff).count_ones() as usize * 2
}

/// Adds a value record's placement and advance to a glyph; device tables
/// are skipped.
fn adjust(d: &[u8], format: u16, at: usize, info: &mut Info) {
    let mut at = at;
    let mut take = || {
        let v = bei16(d, at).unwrap_or(0);
        at += 2;
        i32::from(v)
    };
    if format & 1 != 0 {
        info.dx += take();
    }
    if format & 2 != 0 {
        info.dy += take();
    }
    if format & 4 != 0 {
        info.advance += take();
    }
}

fn anchor(d: &[u8], at: usize) -> Option<(i32, i32)> {
    Some((i32::from(bei16(d, at + 2)?), i32::from(bei16(d, at + 4)?)))
}