Skip to main content

f_office_warnings/
lib.rs

1//! Warnings.
2//!
3//! A warning says that a reader or a writer of F-Office left something of a file out, or drew it
4//! in another way than the file asks, and went on: a part that does not read, a picture without
5//! its image, a font that another font stands in for. Each crate that can warn has its own
6//! `Warning` enum, and its calls return the warnings beside their result in a [`Warned`], so a
7//! caller can tell a clean page from a page with something missing.
8//!
9//! [`Warnings`] keeps each distinct warning once with the number of times it came, so a document
10//! that asks for a missing font in every run gives one warning and not thousands. A warning holds
11//! no content of the document. It may hold the names that the file uses to point at a resource,
12//! such as a part's name or a font family, as a [`Name`]: cut to a fixed length, with printable
13//! characters only, because the file chooses it.
14
15use std::collections::HashMap;
16use std::fmt;
17use std::hash::Hash;
18
19/// The warnings of one call, each distinct warning once with the number of times it came, in
20/// the order in which each came first.
21#[derive(Clone, Debug)]
22pub struct Warnings<W> {
23    /// Each distinct warning with its count, in the order of their first coming.
24    counted: Vec<(W, u32)>,
25    /// The place of each warning in `counted`.
26    places: HashMap<W, usize>,
27}
28
29impl<W> Default for Warnings<W> {
30    fn default() -> Self {
31        Self {
32            counted: Vec::new(),
33            places: HashMap::new(),
34        }
35    }
36}
37
38impl<W: PartialEq> PartialEq for Warnings<W> {
39    fn eq(&self, other: &Self) -> bool {
40        self.counted == other.counted
41    }
42}
43
44impl<W: Eq> Eq for Warnings<W> {}
45
46impl<W: Clone + Eq + Hash> Warnings<W> {
47    /// No warnings.
48    #[must_use]
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    /// Adds a warning once.
54    pub fn push(&mut self, warning: W) {
55        self.add(warning, 1);
56    }
57
58    /// Adds a warning `count` times. A count of zero adds nothing.
59    pub fn add(&mut self, warning: W, count: u32) {
60        if count == 0 {
61            return;
62        }
63        if let Some(&place) = self.places.get(&warning)
64            && let Some((_, seen)) = self.counted.get_mut(place)
65        {
66            *seen = seen.saturating_add(count);
67            return;
68        }
69        self.places.insert(warning.clone(), self.counted.len());
70        self.counted.push((warning, count));
71    }
72
73    /// The number of times `warning` came: 0 when it did not come.
74    #[must_use]
75    pub fn count(&self, warning: &W) -> u32 {
76        self.places
77            .get(warning)
78            .and_then(|&place| self.counted.get(place))
79            .map_or(0, |(_, count)| *count)
80    }
81
82    /// Adds every warning of `other`, with its count, as `into` turns it into a warning of this
83    /// kind, such as a crate's warning into the variant of the public crate that wraps it.
84    pub fn extend<V>(&mut self, other: Warnings<V>, into: impl Fn(V) -> W) {
85        for (warning, count) in other {
86            self.add(into(warning), count);
87        }
88    }
89
90    /// The warnings, each turned by `into` into a warning of another kind. Two warnings that
91    /// turn into one add their counts.
92    #[must_use]
93    pub fn map<V: Clone + Eq + Hash>(self, into: impl Fn(W) -> V) -> Warnings<V> {
94        let mut mapped = Warnings::new();
95        mapped.extend(self, into);
96        mapped
97    }
98}
99
100impl<W> Warnings<W> {
101    /// Each distinct warning with the number of times it came, in the order in which each came
102    /// first.
103    pub fn iter(&self) -> impl Iterator<Item = (&W, u32)> {
104        self.counted
105            .iter()
106            .map(|(warning, count)| (warning, *count))
107    }
108
109    /// The number of distinct warnings.
110    #[must_use]
111    pub fn len(&self) -> usize {
112        self.counted.len()
113    }
114
115    /// Whether no warning came.
116    #[must_use]
117    pub fn is_empty(&self) -> bool {
118        self.counted.is_empty()
119    }
120}
121
122impl<W> IntoIterator for Warnings<W> {
123    type Item = (W, u32);
124    type IntoIter = std::vec::IntoIter<(W, u32)>;
125
126    fn into_iter(self) -> Self::IntoIter {
127        self.counted.into_iter()
128    }
129}
130
131/// A value with the warnings of the call that made it.
132#[derive(Clone, Debug, PartialEq, Eq)]
133pub struct Warned<T, W> {
134    /// The value.
135    pub value: T,
136    /// The warnings.
137    pub warnings: Warnings<W>,
138}
139
140impl<T, W> Warned<T, W> {
141    /// The value with its warnings.
142    #[must_use]
143    pub fn new(value: T, warnings: Warnings<W>) -> Self {
144        Self { value, warnings }
145    }
146
147    /// The value as `f` turns it, with the same warnings.
148    #[must_use]
149    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Warned<U, W> {
150        Warned {
151            value: f(self.value),
152            warnings: self.warnings,
153        }
154    }
155}
156
157/// A name that a file chooses and a warning keeps, such as a part's name in its package or a
158/// font family that a document asks for: at most [`Name::MAX_CHARS`] characters of it, without
159/// the characters that a terminal or a log does not show as themselves (control characters and
160/// the marks that change the direction or the joining of text).
161#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
162pub struct Name(String);
163
164impl Name {
165    /// The most characters that a name keeps.
166    pub const MAX_CHARS: usize = 64;
167
168    /// The name that a warning keeps of `name`.
169    #[must_use]
170    pub fn new(name: &str) -> Self {
171        Self(
172            name.chars()
173                .filter(|&ch| printable(ch))
174                .take(Self::MAX_CHARS)
175                .collect(),
176        )
177    }
178
179    /// The kept name.
180    #[must_use]
181    pub fn as_str(&self) -> &str {
182        &self.0
183    }
184}
185
186impl From<&str> for Name {
187    fn from(name: &str) -> Self {
188        Self::new(name)
189    }
190}
191
192impl fmt::Display for Name {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        f.write_str(&self.0)
195    }
196}
197
198/// Whether a name keeps a character: not a control character, and none of the marks of
199/// direction, joining and width that change how the text around them shows.
200fn printable(ch: char) -> bool {
201    !ch.is_control()
202        && !matches!(
203            ch,
204            '\u{061c}'
205                | '\u{200b}'..='\u{200f}'
206                | '\u{202a}'..='\u{202e}'
207                | '\u{2060}'..='\u{2069}'
208                | '\u{feff}'
209                | '\u{fff9}'..='\u{fffb}'
210        )
211}
212
213#[cfg(test)]
214mod tests {
215    use super::{Name, Warned, Warnings};
216
217    #[test]
218    fn keeps_each_warning_once_with_its_count_in_the_order_of_coming() {
219        let mut warnings = Warnings::new();
220        for warning in ["b", "a", "b", "b", "c"] {
221            warnings.push(warning);
222        }
223        warnings.add("a", 2);
224        warnings.add("d", 0);
225        let counted: Vec<(&str, u32)> = warnings.iter().map(|(w, n)| (*w, n)).collect();
226        assert_eq!(counted, [("b", 3), ("a", 3), ("c", 1)]);
227        assert_eq!((warnings.count(&"b"), warnings.count(&"d")), (3, 0));
228        assert_eq!(warnings.len(), 3);
229        assert!(!warnings.is_empty());
230        assert!(Warnings::<&str>::new().is_empty());
231    }
232
233    #[test]
234    fn turns_warnings_into_another_kind_and_adds_the_counts_of_those_that_meet() {
235        let mut inner = Warnings::new();
236        inner.add(1_u8, 2);
237        inner.push(2);
238        inner.push(3);
239        let mut outer: Warnings<String> = Warnings::new();
240        outer.push("odd".to_owned());
241        outer.extend(inner.clone(), |n| {
242            if n % 2 == 1 { "odd" } else { "even" }.to_owned()
243        });
244        let counted: Vec<(String, u32)> = outer.into_iter().collect();
245        assert_eq!(counted, [("odd".to_owned(), 4), ("even".to_owned(), 1)]);
246        let doubled = inner.map(|n| n * 2);
247        let counted: Vec<(u8, u32)> = doubled.into_iter().collect();
248        assert_eq!(counted, [(2, 2), (4, 1), (6, 1)]);
249    }
250
251    #[test]
252    fn carries_the_warnings_beside_a_value() {
253        let mut warnings = Warnings::new();
254        warnings.push('w');
255        let warned = Warned::new(20, warnings.clone()).map(|n| n + 1);
256        assert_eq!(
257            warned,
258            Warned {
259                value: 21,
260                warnings
261            }
262        );
263    }
264
265    #[test]
266    fn cuts_a_name_and_keeps_its_printable_characters_only() {
267        let long = "x".repeat(100);
268        assert_eq!(Name::new(&long).as_str().chars().count(), Name::MAX_CHARS);
269        let marked = "word/\u{202e}media\u{0}/image\u{200d}1.png\n";
270        assert_eq!(Name::new(marked).to_string(), "word/media/image1.png");
271        // A name of other scripts keeps its characters; each counts once.
272        let family = "微軟正黑體".repeat(20);
273        let kept = Name::from(family.as_str());
274        assert_eq!(kept.as_str().chars().count(), Name::MAX_CHARS);
275        assert!(family.starts_with(kept.as_str()));
276    }
277}