f-office-warnings 0.2.2

The warnings that F-Office's readers and writers return beside their results.
Documentation
//! Warnings.
//!
//! A warning says that a reader or a writer of F-Office left something of a file out, or drew it
//! in another way than the file asks, and went on: a part that does not read, a picture without
//! its image, a font that another font stands in for. Each crate that can warn has its own
//! `Warning` enum, and its calls return the warnings beside their result in a [`Warned`], so a
//! caller can tell a clean page from a page with something missing.
//!
//! [`Warnings`] keeps each distinct warning once with the number of times it came, so a document
//! that asks for a missing font in every run gives one warning and not thousands. A warning holds
//! no content of the document. It may hold the names that the file uses to point at a resource,
//! such as a part's name or a font family, as a [`Name`]: cut to a fixed length, with printable
//! characters only, because the file chooses it.

use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;

/// The warnings of one call, each distinct warning once with the number of times it came, in
/// the order in which each came first.
#[derive(Clone, Debug)]
pub struct Warnings<W> {
    /// Each distinct warning with its count, in the order of their first coming.
    counted: Vec<(W, u32)>,
    /// The place of each warning in `counted`.
    places: HashMap<W, usize>,
}

impl<W> Default for Warnings<W> {
    fn default() -> Self {
        Self {
            counted: Vec::new(),
            places: HashMap::new(),
        }
    }
}

impl<W: PartialEq> PartialEq for Warnings<W> {
    fn eq(&self, other: &Self) -> bool {
        self.counted == other.counted
    }
}

impl<W: Eq> Eq for Warnings<W> {}

impl<W: Clone + Eq + Hash> Warnings<W> {
    /// No warnings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a warning once.
    pub fn push(&mut self, warning: W) {
        self.add(warning, 1);
    }

    /// Adds a warning `count` times. A count of zero adds nothing.
    pub fn add(&mut self, warning: W, count: u32) {
        if count == 0 {
            return;
        }
        if let Some(&place) = self.places.get(&warning)
            && let Some((_, seen)) = self.counted.get_mut(place)
        {
            *seen = seen.saturating_add(count);
            return;
        }
        self.places.insert(warning.clone(), self.counted.len());
        self.counted.push((warning, count));
    }

    /// The number of times `warning` came: 0 when it did not come.
    #[must_use]
    pub fn count(&self, warning: &W) -> u32 {
        self.places
            .get(warning)
            .and_then(|&place| self.counted.get(place))
            .map_or(0, |(_, count)| *count)
    }

    /// Adds every warning of `other`, with its count, as `into` turns it into a warning of this
    /// kind, such as a crate's warning into the variant of the public crate that wraps it.
    pub fn extend<V>(&mut self, other: Warnings<V>, into: impl Fn(V) -> W) {
        for (warning, count) in other {
            self.add(into(warning), count);
        }
    }

    /// The warnings, each turned by `into` into a warning of another kind. Two warnings that
    /// turn into one add their counts.
    #[must_use]
    pub fn map<V: Clone + Eq + Hash>(self, into: impl Fn(W) -> V) -> Warnings<V> {
        let mut mapped = Warnings::new();
        mapped.extend(self, into);
        mapped
    }
}

impl<W> Warnings<W> {
    /// Each distinct warning with the number of times it came, in the order in which each came
    /// first.
    pub fn iter(&self) -> impl Iterator<Item = (&W, u32)> {
        self.counted
            .iter()
            .map(|(warning, count)| (warning, *count))
    }

    /// The number of distinct warnings.
    #[must_use]
    pub fn len(&self) -> usize {
        self.counted.len()
    }

    /// Whether no warning came.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.counted.is_empty()
    }
}

impl<W> IntoIterator for Warnings<W> {
    type Item = (W, u32);
    type IntoIter = std::vec::IntoIter<(W, u32)>;

    fn into_iter(self) -> Self::IntoIter {
        self.counted.into_iter()
    }
}

/// A value with the warnings of the call that made it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Warned<T, W> {
    /// The value.
    pub value: T,
    /// The warnings.
    pub warnings: Warnings<W>,
}

impl<T, W> Warned<T, W> {
    /// The value with its warnings.
    #[must_use]
    pub fn new(value: T, warnings: Warnings<W>) -> Self {
        Self { value, warnings }
    }

    /// The value as `f` turns it, with the same warnings.
    #[must_use]
    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Warned<U, W> {
        Warned {
            value: f(self.value),
            warnings: self.warnings,
        }
    }
}

/// A name that a file chooses and a warning keeps, such as a part's name in its package or a
/// font family that a document asks for: at most [`Name::MAX_CHARS`] characters of it, without
/// the characters that a terminal or a log does not show as themselves (control characters and
/// the marks that change the direction or the joining of text).
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Name(String);

impl Name {
    /// The most characters that a name keeps.
    pub const MAX_CHARS: usize = 64;

    /// The name that a warning keeps of `name`.
    #[must_use]
    pub fn new(name: &str) -> Self {
        Self(
            name.chars()
                .filter(|&ch| printable(ch))
                .take(Self::MAX_CHARS)
                .collect(),
        )
    }

    /// The kept name.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<&str> for Name {
    fn from(name: &str) -> Self {
        Self::new(name)
    }
}

impl fmt::Display for Name {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// Whether a name keeps a character: not a control character, and none of the marks of
/// direction, joining and width that change how the text around them shows.
fn printable(ch: char) -> bool {
    !ch.is_control()
        && !matches!(
            ch,
            '\u{061c}'
                | '\u{200b}'..='\u{200f}'
                | '\u{202a}'..='\u{202e}'
                | '\u{2060}'..='\u{2069}'
                | '\u{feff}'
                | '\u{fff9}'..='\u{fffb}'
        )
}

#[cfg(test)]
mod tests {
    use super::{Name, Warned, Warnings};

    #[test]
    fn keeps_each_warning_once_with_its_count_in_the_order_of_coming() {
        let mut warnings = Warnings::new();
        for warning in ["b", "a", "b", "b", "c"] {
            warnings.push(warning);
        }
        warnings.add("a", 2);
        warnings.add("d", 0);
        let counted: Vec<(&str, u32)> = warnings.iter().map(|(w, n)| (*w, n)).collect();
        assert_eq!(counted, [("b", 3), ("a", 3), ("c", 1)]);
        assert_eq!((warnings.count(&"b"), warnings.count(&"d")), (3, 0));
        assert_eq!(warnings.len(), 3);
        assert!(!warnings.is_empty());
        assert!(Warnings::<&str>::new().is_empty());
    }

    #[test]
    fn turns_warnings_into_another_kind_and_adds_the_counts_of_those_that_meet() {
        let mut inner = Warnings::new();
        inner.add(1_u8, 2);
        inner.push(2);
        inner.push(3);
        let mut outer: Warnings<String> = Warnings::new();
        outer.push("odd".to_owned());
        outer.extend(inner.clone(), |n| {
            if n % 2 == 1 { "odd" } else { "even" }.to_owned()
        });
        let counted: Vec<(String, u32)> = outer.into_iter().collect();
        assert_eq!(counted, [("odd".to_owned(), 4), ("even".to_owned(), 1)]);
        let doubled = inner.map(|n| n * 2);
        let counted: Vec<(u8, u32)> = doubled.into_iter().collect();
        assert_eq!(counted, [(2, 2), (4, 1), (6, 1)]);
    }

    #[test]
    fn carries_the_warnings_beside_a_value() {
        let mut warnings = Warnings::new();
        warnings.push('w');
        let warned = Warned::new(20, warnings.clone()).map(|n| n + 1);
        assert_eq!(
            warned,
            Warned {
                value: 21,
                warnings
            }
        );
    }

    #[test]
    fn cuts_a_name_and_keeps_its_printable_characters_only() {
        let long = "x".repeat(100);
        assert_eq!(Name::new(&long).as_str().chars().count(), Name::MAX_CHARS);
        let marked = "word/\u{202e}media\u{0}/image\u{200d}1.png\n";
        assert_eq!(Name::new(marked).to_string(), "word/media/image1.png");
        // A name of other scripts keeps its characters; each counts once.
        let family = "微軟正黑體".repeat(20);
        let kept = Name::from(family.as_str());
        assert_eq!(kept.as_str().chars().count(), Name::MAX_CHARS);
        assert!(family.starts_with(kept.as_str()));
    }
}