readsight 1.0.0

Multilingual readability library — 86 languages, 17 formulas, TeX-based syllable counting via the Frank M. Liang algorithm.
Documentation
//! Hyphenation patterns and pattern collection.

use std::collections::HashMap;

/// A single parsed hyphenation pattern: interleaved characters and weights.
///
/// `weights.len() == chars.len() + 1`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pattern {
    /// The characters of the pattern (Unicode scalar values as 1-char strings).
    pub chars: Vec<String>,
    /// The inter-character weights (odd = hyphenation point).
    pub weights: Vec<i32>,
    /// `chars.len()`.
    pub length: usize,
}

impl Pattern {
    /// Construct a pattern from characters and weights.
    pub fn new(chars: Vec<String>, weights: Vec<i32>) -> Self {
        let length = chars.len();
        Pattern {
            chars,
            weights,
            length,
        }
    }
}

/// A collection of patterns keyed by their concatenated character string.
#[derive(Debug, Default, Clone)]
pub struct PatternsCollection {
    patterns: HashMap<String, Vec<i32>>,
    max_pattern_length: usize,
}

impl PatternsCollection {
    /// Create an empty collection.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a pattern (later insertions with the same key overwrite earlier ones).
    pub fn add(&mut self, pattern: Pattern) {
        let key = pattern.chars.concat();
        if pattern.length > self.max_pattern_length {
            self.max_pattern_length = pattern.length;
        }
        self.patterns.insert(key, pattern.weights);
    }

    /// Weights for an exact sub-pattern string, if present.
    pub fn get_weights(&self, subword: &str) -> Option<&[i32]> {
        self.patterns.get(subword).map(|v| v.as_slice())
    }

    /// Number of stored patterns.
    pub fn count(&self) -> usize {
        self.patterns.len()
    }

    /// Length (in characters) of the longest stored pattern.
    pub fn max_length(&self) -> usize {
        self.max_pattern_length
    }

    /// Whether the collection is empty.
    pub fn is_empty(&self) -> bool {
        self.patterns.is_empty()
    }
}