1use std::collections::HashMap;
16use std::fmt;
17use std::hash::Hash;
18
19#[derive(Clone, Debug)]
22pub struct Warnings<W> {
23 counted: Vec<(W, u32)>,
25 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 #[must_use]
49 pub fn new() -> Self {
50 Self::default()
51 }
52
53 pub fn push(&mut self, warning: W) {
55 self.add(warning, 1);
56 }
57
58 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 #[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 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 #[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 pub fn iter(&self) -> impl Iterator<Item = (&W, u32)> {
104 self.counted
105 .iter()
106 .map(|(warning, count)| (warning, *count))
107 }
108
109 #[must_use]
111 pub fn len(&self) -> usize {
112 self.counted.len()
113 }
114
115 #[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#[derive(Clone, Debug, PartialEq, Eq)]
133pub struct Warned<T, W> {
134 pub value: T,
136 pub warnings: Warnings<W>,
138}
139
140impl<T, W> Warned<T, W> {
141 #[must_use]
143 pub fn new(value: T, warnings: Warnings<W>) -> Self {
144 Self { value, warnings }
145 }
146
147 #[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#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
162pub struct Name(String);
163
164impl Name {
165 pub const MAX_CHARS: usize = 64;
167
168 #[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 #[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
198fn 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 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}