pub trait Text {
fn squish(&self) -> String;
fn truncated(&self, max: usize) -> String;
fn excerpt(&self, phrase: &str, radius: usize) -> Option<String>;
fn parameterize(&self) -> String;
fn humanize(&self) -> String;
fn titleize(&self) -> String;
fn mask(&self, visible: usize) -> String;
fn pluralize(&self, count: i64) -> String;
}
impl Text for str {
fn squish(&self) -> String {
self.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn truncated(&self, max: usize) -> String {
if self.chars().count() <= max {
return self.to_owned();
}
if max == 0 {
return String::new();
}
let kept: String = self.chars().take(max - 1).collect();
let cut = match kept.rfind(char::is_whitespace) {
Some(at) if kept[..at].chars().count() * 3 >= (max - 1) * 2 => &kept[..at],
_ => kept.as_str(),
};
format!("{}…", cut.trim_end())
}
fn excerpt(&self, phrase: &str, radius: usize) -> Option<String> {
let lower = self.to_lowercase();
let chars: Vec<char> = self.chars().collect();
let lower_chars: Vec<char> = lower.chars().collect();
let needle: Vec<char> = phrase.to_lowercase().chars().collect();
if needle.is_empty() || lower_chars.len() != chars.len() {
return lower
.find(&phrase.to_lowercase())
.map(|_| self.to_owned())
.filter(|_| !needle.is_empty());
}
let at = lower_chars
.windows(needle.len())
.position(|w| w == needle.as_slice())?;
let start = at.saturating_sub(radius);
let end = (at + needle.len() + radius).min(chars.len());
let middle: String = chars[start..end].iter().collect();
let mut out = String::new();
if start > 0 {
out.push('…');
}
out.push_str(middle.trim());
if end < chars.len() {
out.push('…');
}
Some(out)
}
fn parameterize(&self) -> String {
let mut out = String::new();
let mut hyphen = false;
for c in self.chars() {
let plain = unaccent(c);
for c in plain.chars() {
if c.is_ascii_alphanumeric() {
if hyphen && !out.is_empty() {
out.push('-');
}
hyphen = false;
out.push(c.to_ascii_lowercase());
} else {
hyphen = true;
}
}
}
out
}
fn humanize(&self) -> String {
let text = self.strip_suffix("_id").unwrap_or(self);
let words = text.replace('_', " ").squish().to_lowercase();
let mut chars = words.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => String::new(),
}
}
fn titleize(&self) -> String {
self.humanize()
.split(' ')
.map(|word| {
let mut chars = word.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => String::new(),
}
})
.collect::<Vec<String>>()
.join(" ")
}
fn mask(&self, visible: usize) -> String {
let count = self.chars().count();
let hidden = count.saturating_sub(visible);
"*".repeat(hidden) + &self.chars().skip(hidden).collect::<String>()
}
fn pluralize(&self, count: i64) -> String {
if count == 1 {
format!("1 {self}")
} else {
format!("{count} {}", glacier_inflect::pluralize(self))
}
}
}
impl Text for String {
fn squish(&self) -> String {
self.as_str().squish()
}
fn truncated(&self, max: usize) -> String {
self.as_str().truncated(max)
}
fn excerpt(&self, phrase: &str, radius: usize) -> Option<String> {
self.as_str().excerpt(phrase, radius)
}
fn parameterize(&self) -> String {
self.as_str().parameterize()
}
fn humanize(&self) -> String {
self.as_str().humanize()
}
fn titleize(&self) -> String {
self.as_str().titleize()
}
fn mask(&self, visible: usize) -> String {
self.as_str().mask(visible)
}
fn pluralize(&self, count: i64) -> String {
self.as_str().pluralize(count)
}
}
fn unaccent(c: char) -> String {
let plain = match c {
'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' => "a",
'À' | 'Á' | 'Â' | 'Ã' | 'Ä' | 'Å' | 'Ā' => "A",
'æ' => "ae",
'Æ' => "AE",
'ç' | 'ć' | 'č' => "c",
'Ç' | 'Ć' | 'Č' => "C",
'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ę' | 'ě' => "e",
'È' | 'É' | 'Ê' | 'Ë' | 'Ē' | 'Ę' | 'Ě' => "E",
'ì' | 'í' | 'î' | 'ï' | 'ī' => "i",
'Ì' | 'Í' | 'Î' | 'Ï' | 'Ī' => "I",
'ł' => "l",
'Ł' => "L",
'ñ' | 'ń' | 'ň' => "n",
'Ñ' | 'Ń' | 'Ň' => "N",
'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' => "o",
'Ò' | 'Ó' | 'Ô' | 'Õ' | 'Ö' | 'Ø' | 'Ō' => "O",
'œ' => "oe",
'Œ' => "OE",
'ř' => "r",
'Ř' => "R",
'ś' | 'š' | 'ş' => "s",
'Ś' | 'Š' | 'Ş' => "S",
'ß' => "ss",
'ť' | 'ţ' => "t",
'Ť' | 'Ţ' => "T",
'ù' | 'ú' | 'û' | 'ü' | 'ū' | 'ů' => "u",
'Ù' | 'Ú' | 'Û' | 'Ü' | 'Ū' | 'Ů' => "U",
'ý' | 'ÿ' => "y",
'Ý' | 'Ÿ' => "Y",
'ź' | 'ż' | 'ž' => "z",
'Ź' | 'Ż' | 'Ž' => "Z",
'đ' | 'ð' => "d",
'Đ' | 'Ð' => "D",
'þ' => "th",
'Þ' => "TH",
_ => return c.to_string(),
};
plain.to_owned()
}
pub trait Number {
fn delimited(&self) -> String;
fn to_currency(&self, code: &str) -> String;
}
pub trait Whole {
fn ordinal(&self) -> String;
fn human_size(&self) -> String;
}
pub trait Moment {
fn time_ago(&self) -> String;
fn time_between(&self, other: &chrono::DateTime<chrono::Utc>) -> String;
fn local(&self, format: &str) -> String;
}
impl Moment for chrono::DateTime<chrono::Utc> {
fn time_ago(&self) -> String {
let now = crate::time::now();
if (now - *self).num_seconds().abs() < 30 {
return "just now".to_owned();
}
let words = self.time_between(&now);
if *self <= now {
format!("{words} ago")
} else {
format!("in {words}")
}
}
fn time_between(&self, other: &chrono::DateTime<chrono::Utc>) -> String {
distance_in_words((*other - *self).num_seconds().unsigned_abs())
}
fn local(&self, format: &str) -> String {
crate::time::format_local(*self, format)
}
}
fn distance_in_words(seconds: u64) -> String {
let minutes = (seconds + 30) / 60;
let plural = |n: u64, unit: &str| {
if n == 1 {
format!("1 {unit}")
} else {
format!("{n} {unit}s")
}
};
const DAY: u64 = 1440;
match minutes {
0 => "less than a minute".to_owned(),
1..45 => plural(minutes, "minute"),
45..90 => "about 1 hour".to_owned(),
90..DAY => format!("about {}", plural((minutes + 30) / 60, "hour")),
DAY..2520 => "1 day".to_owned(),
2520..43200 => plural((minutes + DAY / 2) / DAY, "day"),
43200..86400 => format!("about {}", plural((minutes + 21600) / 43200, "month")),
86400..525600 => plural((minutes + 21600) / 43200, "month"),
_ => {
let years = minutes / 525600;
let rest = minutes % 525600;
if rest < 131400 {
format!("about {}", plural(years, "year"))
} else if rest < 394200 {
format!("over {}", plural(years, "year"))
} else {
format!("almost {}", plural(years + 1, "year"))
}
}
}
}
fn delimit(plain: &str) -> String {
let style = Style::current();
let (sign, digits) = match plain.strip_prefix('-') {
Some(rest) => ("-", rest),
None => ("", plain),
};
let (whole, fraction) = match digits.split_once('.') {
Some((whole, fraction)) => (whole, Some(fraction)),
None => (digits, None),
};
let mut out = String::new();
for (i, c) in whole.chars().enumerate() {
if i > 0 && (whole.len() - i).is_multiple_of(3) {
out.push_str(style.group);
}
out.push(c);
}
match fraction {
Some(fraction) => format!("{sign}{out}{}{fraction}", style.decimal),
None => format!("{sign}{out}"),
}
}
struct Style {
group: &'static str,
decimal: &'static str,
symbol_after: bool,
spaced: bool,
}
impl Style {
fn current() -> Self {
Self::of(&crate::i18n::locale())
}
fn of(locale: &str) -> Self {
const THIN: &str = "\u{202f}";
const NBSP: &str = "\u{a0}";
let locale = locale.to_ascii_lowercase().replace('_', "-");
let language = locale.split('-').next().unwrap_or("");
let (group, decimal, symbol_after, spaced) = match (language, locale.as_str()) {
(_, "de-ch") => ("’", ".", false, true),
(_, "pt-br") => (".", ",", false, true),
("de" | "es" | "it" | "pt" | "da" | "id" | "tr" | "ro" | "hr" | "sl" | "el", _) => {
(".", ",", true, true)
}
("nl", _) => (".", ",", false, true),
("fr", _) => (THIN, ",", true, true),
("pl" | "cs" | "sk" | "ru" | "uk" | "sv" | "nb" | "no" | "fi" | "hu" | "bg", _) => {
(NBSP, ",", true, true)
}
_ => (",", ".", false, false),
};
Self {
group,
decimal,
symbol_after,
spaced,
}
}
}
fn currency(code: &str) -> (Option<&'static str>, usize) {
match code.to_ascii_uppercase().as_str() {
"GBP" => (Some("£"), 2),
"USD" | "CAD" | "AUD" | "NZD" => (Some("$"), 2),
"EUR" => (Some("€"), 2),
"JPY" => (Some("¥"), 0),
"INR" => (Some("₹"), 2),
"BRL" => (Some("R$"), 2),
"KRW" => (Some("₩"), 0),
_ => (None, 2),
}
}
fn money(plain: &str, code: &str) -> String {
let (symbol, _) = currency(code);
let (sign, amount) = match plain.strip_prefix('-') {
Some(rest) => ("-", rest),
None => ("", plain),
};
let amount = delimit(amount);
let sign = if amount.chars().all(|c| !c.is_ascii_digit() || c == '0') {
""
} else {
sign
};
let style = Style::current();
let space = if style.spaced { "\u{a0}" } else { "" };
match (symbol, style.symbol_after) {
(Some(symbol), false) => format!("{sign}{symbol}{space}{amount}"),
(Some(symbol), true) => format!("{sign}{amount}{space}{symbol}"),
(None, false) => format!("{sign}{} {amount}", code.to_ascii_uppercase()),
(None, true) => format!("{sign}{amount} {}", code.to_ascii_uppercase()),
}
}
macro_rules! whole_numbers {
($($ty:ty),*) => {$(
impl Number for $ty {
fn delimited(&self) -> String {
delimit(&self.to_string())
}
fn to_currency(&self, code: &str) -> String {
let (_, digits) = currency(code);
money(&format!("{:.digits$}", *self as f64), code)
}
}
impl Whole for $ty {
#[allow(unused_comparisons)]
fn ordinal(&self) -> String {
let n = (*self as i128).unsigned_abs();
let suffix = match (n % 10, n % 100) {
(_, 11..=13) => "th",
(1, _) => "st",
(2, _) => "nd",
(3, _) => "rd",
_ => "th",
};
format!("{self}{suffix}")
}
fn human_size(&self) -> String {
human_size(*self as f64)
}
}
)*};
}
whole_numbers!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
fn human_size(bytes: f64) -> String {
if bytes.abs() < 1024.0 {
return if bytes == 1.0 {
"1 byte".to_owned()
} else {
format!("{bytes} bytes")
};
}
let mut size = bytes;
let mut unit = "bytes";
for next in ["KB", "MB", "GB", "TB", "PB"] {
if size.abs() < 1024.0 {
break;
}
size /= 1024.0;
unit = next;
}
let shown = format!("{size:.1}");
let shown = shown.strip_suffix(".0").unwrap_or(&shown);
format!("{shown} {unit}")
}
impl Number for f64 {
fn delimited(&self) -> String {
delimit(&self.to_string())
}
fn to_currency(&self, code: &str) -> String {
let (_, digits) = currency(code);
money(&format!("{self:.digits$}"), code)
}
}
impl Number for f32 {
fn delimited(&self) -> String {
delimit(&self.to_string())
}
fn to_currency(&self, code: &str) -> String {
f64::from(*self).to_currency(code)
}
}
impl Number for crate::db::Decimal {
fn delimited(&self) -> String {
delimit(&self.0.normalized().to_plain_string())
}
fn to_currency(&self, code: &str) -> String {
let (_, digits) = currency(code);
let rounded = self
.0
.with_scale_round(digits as i64, bigdecimal::RoundingMode::HalfUp);
money(&rounded.to_plain_string(), code)
}
}
impl<T: Number + ?Sized> Number for &T {
fn delimited(&self) -> String {
(**self).delimited()
}
fn to_currency(&self, code: &str) -> String {
(**self).to_currency(code)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn times_in_words_as_rails_writes_them() {
let words = |minutes: u64| distance_in_words(minutes * 60);
assert_eq!(distance_in_words(20), "less than a minute");
assert_eq!(words(1), "1 minute");
assert_eq!(words(3), "3 minutes");
assert_eq!(words(50), "about 1 hour");
assert_eq!(words(150), "about 3 hours");
assert_eq!(words(1500), "1 day");
assert_eq!(words(4 * 1440), "4 days");
assert_eq!(words(35 * 1440), "about 1 month");
assert_eq!(words(100 * 1440), "3 months");
assert_eq!(words(370 * 1440), "about 1 year");
assert_eq!(words(600 * 1440), "over 1 year");
assert_eq!(words(700 * 1440), "almost 2 years");
}
#[test]
fn time_ago_says_which_way() {
let now = crate::time::now();
assert_eq!(
(now - chrono::TimeDelta::minutes(3)).time_ago(),
"3 minutes ago"
);
assert_eq!((now + chrono::TimeDelta::days(4)).time_ago(), "in 4 days");
assert_eq!(now.time_ago(), "just now");
}
#[test]
fn text_helpers() {
assert_eq!(" a \n b ".squish(), "a b");
assert_eq!("The quick brown fox".truncated(12), "The quick…");
assert_eq!("Supercalifragilistic".truncated(6), "Super…");
assert_eq!("short".truncated(10), "short");
assert_eq!(
"The rain in Spain falls mainly".excerpt("spain", 5),
Some("…n in Spain fall…".to_owned())
);
assert_eq!("hello".excerpt("bye", 3), None);
assert_eq!("Crème Brûlée & Co.".parameterize(), "creme-brulee-co");
assert_eq!(" Hello, World! ".parameterize(), "hello-world");
assert_eq!("author_id".humanize(), "Author");
assert_eq!("first_name".humanize(), "First name");
assert_eq!("first_name".titleize(), "First Name");
assert_eq!("4242424242424242".mask(4), "************4242");
assert_eq!("ab".mask(4), "ab");
assert_eq!("book".pluralize(3), "3 books");
assert_eq!("person".pluralize(1), "1 person");
assert_eq!("person".pluralize(0), "0 people");
}
#[test]
fn number_helpers() {
assert_eq!(1234567.delimited(), "1,234,567");
assert_eq!(1234.5.to_currency("GBP"), "£1,234.50");
assert_eq!((-1234).delimited(), "-1,234");
assert_eq!(999.delimited(), "999");
assert_eq!(1234.5.delimited(), "1,234.5");
assert_eq!(1234.5.to_currency("GBP"), "£1,234.50");
assert_eq!((-5).to_currency("usd"), "-$5.00");
assert_eq!(1234.6.to_currency("JPY"), "¥1,235");
assert_eq!(12.to_currency("CHF"), "CHF 12.00");
assert_eq!((-0.001).to_currency("GBP"), "£0.00");
let price: crate::db::Decimal = "1999.995".parse().unwrap();
assert_eq!(price.to_currency("EUR"), "€2,000.00");
assert_eq!(price.delimited(), "1,999.995");
assert_eq!(1.ordinal(), "1st");
assert_eq!(22.ordinal(), "22nd");
assert_eq!(13.ordinal(), "13th");
assert_eq!(111.ordinal(), "111th");
assert_eq!(103.ordinal(), "103rd");
assert_eq!(0.human_size(), "0 bytes");
assert_eq!(1.human_size(), "1 byte");
assert_eq!(1536.human_size(), "1.5 KB");
assert_eq!((5 * 1024 * 1024).human_size(), "5 MB");
}
#[tokio::test]
async fn numbers_follow_the_locale() {
let de = crate::i18n::with_locale("de", async {
(
1234567.5.delimited(),
1234.5.to_currency("EUR"),
(-0.001).to_currency("EUR"),
)
})
.await;
assert_eq!(
de,
(
"1.234.567,5".to_owned(),
"1.234,50\u{a0}€".to_owned(),
"0,00\u{a0}€".to_owned()
)
);
let fr = crate::i18n::with_locale("fr-FR", async { 1234.5.to_currency("EUR") }).await;
assert_eq!(fr, "1\u{202f}234,50\u{a0}€");
let br = crate::i18n::with_locale("pt-BR", async { 1234.5.to_currency("BRL") }).await;
assert_eq!(br, "R$\u{a0}1.234,50");
let ja = crate::i18n::with_locale("ja", async { 1234.to_currency("JPY") }).await;
assert_eq!(ja, "¥1,234");
}
}