use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
#[derive(Clone, Debug)]
pub struct Warnings<W> {
counted: Vec<(W, u32)>,
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> {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, warning: W) {
self.add(warning, 1);
}
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));
}
#[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)
}
pub fn extend<V>(&mut self, other: Warnings<V>, into: impl Fn(V) -> W) {
for (warning, count) in other {
self.add(into(warning), count);
}
}
#[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> {
pub fn iter(&self) -> impl Iterator<Item = (&W, u32)> {
self.counted
.iter()
.map(|(warning, count)| (warning, *count))
}
#[must_use]
pub fn len(&self) -> usize {
self.counted.len()
}
#[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()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Warned<T, W> {
pub value: T,
pub warnings: Warnings<W>,
}
impl<T, W> Warned<T, W> {
#[must_use]
pub fn new(value: T, warnings: Warnings<W>) -> Self {
Self { value, warnings }
}
#[must_use]
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Warned<U, W> {
Warned {
value: f(self.value),
warnings: self.warnings,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Name(String);
impl Name {
pub const MAX_CHARS: usize = 64;
#[must_use]
pub fn new(name: &str) -> Self {
Self(
name.chars()
.filter(|&ch| printable(ch))
.take(Self::MAX_CHARS)
.collect(),
)
}
#[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)
}
}
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");
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()));
}
}