use std::borrow::Cow;
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
#[derive(Clone, Debug)]
pub struct FamilyName(Cow<'static, str>);
impl FamilyName {
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self(Cow::Owned(name.into()))
}
#[must_use]
pub const fn from_static(name: &'static str) -> Self {
Self(Cow::Borrowed(name))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn is(&self, name: &str) -> bool {
self.0.eq_ignore_ascii_case(name)
}
#[must_use]
pub fn cmp_name(&self, name: &str) -> Ordering {
folded(&self.0).cmp(folded(name))
}
}
fn folded(name: &str) -> impl Iterator<Item = u8> + '_ {
name.bytes().map(|byte| byte.to_ascii_lowercase())
}
impl PartialEq for FamilyName {
fn eq(&self, other: &Self) -> bool {
self.is(&other.0)
}
}
impl Eq for FamilyName {}
impl Hash for FamilyName {
fn hash<H: Hasher>(&self, state: &mut H) {
for byte in folded(&self.0) {
state.write_u8(byte);
}
state.write_u8(0xff);
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::FamilyName;
#[test]
fn names_one_family_in_any_case_of_ascii_letters() {
let courier = FamilyName::from_static("Courier New");
for other in ["courier new", "COURIER NEW", "cOURIER nEW"] {
assert_eq!(courier, FamilyName::new(other), "{other}");
assert!(courier.is(other), "{other}");
}
}
#[test]
fn names_no_family_whose_name_differs_in_more_than_case() {
let courier = FamilyName::from_static("Courier New");
assert_ne!(courier, FamilyName::new("Courier"));
assert_ne!(courier, FamilyName::new("Courier New "));
assert!(FamilyName::new("Times New Roman").is("times new roman"));
assert!(!FamilyName::new("Arial").is("Arial Narrow"));
assert!(!FamilyName::new("Arial").is("Arail"));
}
#[test]
fn folds_no_letter_outside_ascii() {
let gothic = FamilyName::from_static("MS ゴシック");
assert!(!gothic.is("ms ゴシック"));
assert_ne!(gothic, FamilyName::new("ms ゴシック"));
assert!(!FamilyName::new("ÉCOLE").is("école"));
assert!(FamilyName::new("ÉCOLE").is("École"));
}
#[test]
fn hashes_and_orders_as_it_compares() {
let names: HashSet<FamilyName> = ["Arial", "arial", "ARIAL", "Arial Narrow"]
.into_iter()
.map(FamilyName::new)
.collect();
assert_eq!(names.len(), 2);
let mut sorted: Vec<FamilyName> = ["b", "A", "a", "C"]
.into_iter()
.map(FamilyName::new)
.collect();
sorted.sort_by(|a, b| a.cmp_name(b.as_str()));
sorted.dedup();
let written: Vec<&str> = sorted.iter().map(FamilyName::as_str).collect();
assert_eq!(written, ["A", "b", "C"]);
assert!(sorted.binary_search_by(|probe| probe.cmp_name("B")).is_ok());
assert!(
sorted
.binary_search_by(|probe| probe.cmp_name("d"))
.is_err()
);
}
#[test]
fn keeps_the_name_as_written() {
let name = FamilyName::new("arial");
assert_eq!(name.as_str(), "arial");
assert_eq!(name, FamilyName::from_static("Arial"));
}
}