f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! The exact comparison of two faces' layout values.

use std::collections::{BTreeMap, BTreeSet};

use super::{LayoutValues, Place, ValueKind, Values};

/// One place whose values differ between two faces.
#[derive(Clone, Debug, PartialEq)]
pub struct Difference {
    /// Where the values differ.
    pub place: Place,
    /// The largest gap between the values of the two faces at the same index, in the kind's
    /// unit. `None` when one face has no value at the place, or the two faces have another
    /// number of values there, such as a ligature in one face only.
    pub gap: Option<u64>,
    /// The values of the first face at the place, `None` when it has none.
    pub left: Option<Values>,
    /// The values of the second face at the place, `None` when it has none.
    pub right: Option<Values>,
}

/// The comparison of one kind of layout values.
#[derive(Clone, Debug, PartialEq)]
pub struct KindComparison {
    /// The kind.
    pub kind: ValueKind,
    /// The number of places compared: the places of either face, of characters that both
    /// faces map.
    pub compared: usize,
    /// The places whose values differ, in the order of the places.
    pub differences: Vec<Difference>,
}

impl KindComparison {
    /// The difference with the largest gap, the first of equal gaps; `None` when no
    /// difference has a gap.
    #[must_use]
    pub fn largest(&self) -> Option<&Difference> {
        self.differences
            .iter()
            .filter(|difference| difference.gap.is_some())
            .fold(None, |best: Option<&Difference>, difference| match best {
                Some(best) if best.gap >= difference.gap => Some(best),
                _ => Some(difference),
            })
    }

    /// The number of places that one face has and the other face lacks, or where the two faces
    /// have another number of values.
    #[must_use]
    pub fn without_gap(&self) -> usize {
        self.differences
            .iter()
            .filter(|difference| difference.gap.is_none())
            .count()
    }
}

/// The exact comparison of two faces' layout values, with no tolerance.
///
/// Two faces with other units per em differ in that one value, and their other values are not
/// compared: no value of one face is scaled to the other's units.
#[derive(Clone, Debug, PartialEq)]
pub struct Comparison {
    units_per_em: (u16, u16),
    kinds: Vec<KindComparison>,
}

impl Comparison {
    /// Compares the layout values of `kinds` of two faces. The values of a character, a pair
    /// or a sequence are compared only when both faces map each of its characters; the kind
    /// [`ValueKind::Characters`] counts the characters that one face maps and the other does
    /// not. A pair that a face does not list has the kerning 0.
    #[must_use]
    pub fn new(left: &LayoutValues, right: &LayoutValues, kinds: &[ValueKind]) -> Self {
        let units_per_em = (left.units_per_em(), right.units_per_em());
        if units_per_em.0 != units_per_em.1 {
            return Self {
                units_per_em,
                kinds: Vec::new(),
            };
        }
        let left_characters: BTreeSet<char> = left.characters().collect();
        let shared: BTreeSet<char> = right
            .characters()
            .filter(|c| left_characters.contains(c))
            .collect();
        let mut compared: Vec<KindComparison> = kinds
            .iter()
            .map(|&kind| compare_kind(kind, left.of(kind), right.of(kind), &shared))
            .collect();
        // The kinds with the most differences come first; a stable sort keeps the order of
        // `kinds` between equal counts.
        compared.sort_by_key(|kind| std::cmp::Reverse(kind.differences.len()));
        Self {
            units_per_em,
            kinds: compared,
        }
    }

    /// The two faces' units per em when they differ.
    #[must_use]
    pub const fn units_per_em_differ(&self) -> Option<(u16, u16)> {
        if self.units_per_em.0 == self.units_per_em.1 {
            None
        } else {
            Some(self.units_per_em)
        }
    }

    /// The comparison of each kind, the kinds with the most differences first. None when the
    /// units per em differ.
    #[must_use]
    pub fn kinds(&self) -> &[KindComparison] {
        &self.kinds
    }

    /// The number of differences: one for other units per em, else the differing places of
    /// every kind.
    #[must_use]
    pub fn difference_count(&self) -> usize {
        if self.units_per_em_differ().is_some() {
            return 1;
        }
        self.kinds.iter().map(|kind| kind.differences.len()).sum()
    }

    /// Whether the two faces have the same layout values in every kind compared.
    #[must_use]
    pub fn is_match(&self) -> bool {
        self.difference_count() == 0
    }
}

/// The values of one kind of one face, by place.
type Placed = BTreeMap<Place, Values>;

/// Compares the values of one kind of the faces `left` and `right`.
fn compare_kind(
    kind: ValueKind,
    left: Option<&Placed>,
    right: Option<&Placed>,
    shared: &BTreeSet<char>,
) -> KindComparison {
    let places: BTreeSet<&Place> = left
        .into_iter()
        .chain(right)
        .flat_map(BTreeMap::keys)
        .filter(|place| {
            kind == ValueKind::Characters || place.characters().iter().all(|c| shared.contains(c))
        })
        .collect();
    let mut differences = Vec::new();
    for &place in &places {
        let (a, b) = (value(kind, left, place), value(kind, right, place));
        if a != b {
            differences.push(Difference {
                place: place.clone(),
                gap: gap(a, b),
                left: a.map(<[i64]>::to_vec),
                right: b.map(<[i64]>::to_vec),
            });
        }
    }
    KindComparison {
        kind,
        compared: places.len(),
        differences,
    }
}

/// The values of one face at `place`, or those of a place that the face does not list.
fn value<'a>(kind: ValueKind, values: Option<&'a Placed>, place: &Place) -> Option<&'a [i64]> {
    values
        .and_then(|values| values.get(place))
        .map(Vec::as_slice)
        .or_else(|| kind.unlisted())
}

/// The largest gap between two lists of values of the same length.
fn gap(a: Option<&[i64]>, b: Option<&[i64]>) -> Option<u64> {
    let (a, b) = (a?, b?);
    (a.len() == b.len() && !a.is_empty())
        .then(|| a.iter().zip(b).map(|(x, y)| x.abs_diff(*y)).max())
        .flatten()
}