Skip to main content

glacier/
text.rs

1//! Text and number helpers, for views and code alike:
2//! `post.body.truncated(140)`, `"Annual Report 2026".parameterize()`,
3//! `"author_id".humanize()`, `"book".pluralize(n)`, `1234567.delimited()`,
4//! `price.to_currency("GBP")`, `size.human_size()`, `3.ordinal()`.
5//!
6//! In the prelude, as `Text` and `Number`.
7
8/// Helpers on text: `str` and `String`.
9pub trait Text {
10    /// Leading and trailing whitespace gone, and each run inside one
11    /// space: `"  a \n  b ".squish()` is `"a b"`.
12    fn squish(&self) -> String;
13
14    /// At most `max` characters; text cut short ends in `…`, at a word
15    /// break when there is one in the last third:
16    /// `"The quick brown fox".truncated(12)` is `"The quick…"`.
17    fn truncated(&self, max: usize) -> String;
18
19    /// The words around the first `phrase` (ignoring case), `radius`
20    /// characters each side, with `…` where text was cut; `None` when the
21    /// phrase isn't there.
22    fn excerpt(&self, phrase: &str, radius: usize) -> Option<String>;
23
24    /// A URL slug: lowercase letters, digits and single hyphens, accents
25    /// dropped: `"Crème Brûlée & Co.".parameterize()` is
26    /// `"creme-brulee-co"`.
27    fn parameterize(&self) -> String;
28
29    /// A column name as a label: `"author_id".humanize()` is `"Author"`,
30    /// `"first_name"` is `"First name"`.
31    fn humanize(&self) -> String;
32
33    /// Each word capitalised: `"first_name".titleize()` is `"First Name"`.
34    fn titleize(&self) -> String;
35
36    /// All but the last `visible` characters as `*`:
37    /// `"4242424242424242".mask(4)` is `"************4242"`.
38    fn mask(&self, visible: usize) -> String;
39
40    /// The count and the word, plural unless the count is 1:
41    /// `"book".pluralize(3)` is `"3 books"`, `"person".pluralize(1)` is
42    /// `"1 person"`.
43    fn pluralize(&self, count: i64) -> String;
44}
45
46impl Text for str {
47    fn squish(&self) -> String {
48        self.split_whitespace().collect::<Vec<_>>().join(" ")
49    }
50
51    fn truncated(&self, max: usize) -> String {
52        if self.chars().count() <= max {
53            return self.to_owned();
54        }
55        if max == 0 {
56            return String::new();
57        }
58        let kept: String = self.chars().take(max - 1).collect();
59        // Cut at the last space when it keeps most of the text.
60        let cut = match kept.rfind(char::is_whitespace) {
61            Some(at) if kept[..at].chars().count() * 3 >= (max - 1) * 2 => &kept[..at],
62            _ => kept.as_str(),
63        };
64        format!("{}…", cut.trim_end())
65    }
66
67    fn excerpt(&self, phrase: &str, radius: usize) -> Option<String> {
68        let lower = self.to_lowercase();
69        // Lowercasing can change byte lengths; find the phrase by
70        // characters so the cut lines up with `self`.
71        let chars: Vec<char> = self.chars().collect();
72        let lower_chars: Vec<char> = lower.chars().collect();
73        let needle: Vec<char> = phrase.to_lowercase().chars().collect();
74        if needle.is_empty() || lower_chars.len() != chars.len() {
75            return lower
76                .find(&phrase.to_lowercase())
77                .map(|_| self.to_owned())
78                .filter(|_| !needle.is_empty());
79        }
80        let at = lower_chars
81            .windows(needle.len())
82            .position(|w| w == needle.as_slice())?;
83        let start = at.saturating_sub(radius);
84        let end = (at + needle.len() + radius).min(chars.len());
85        let middle: String = chars[start..end].iter().collect();
86        let mut out = String::new();
87        if start > 0 {
88            out.push('…');
89        }
90        out.push_str(middle.trim());
91        if end < chars.len() {
92            out.push('…');
93        }
94        Some(out)
95    }
96
97    fn parameterize(&self) -> String {
98        let mut out = String::new();
99        let mut hyphen = false;
100        for c in self.chars() {
101            let plain = unaccent(c);
102            for c in plain.chars() {
103                if c.is_ascii_alphanumeric() {
104                    if hyphen && !out.is_empty() {
105                        out.push('-');
106                    }
107                    hyphen = false;
108                    out.push(c.to_ascii_lowercase());
109                } else {
110                    hyphen = true;
111                }
112            }
113        }
114        out
115    }
116
117    fn humanize(&self) -> String {
118        let text = self.strip_suffix("_id").unwrap_or(self);
119        let words = text.replace('_', " ").squish().to_lowercase();
120        let mut chars = words.chars();
121        match chars.next() {
122            Some(first) => first.to_uppercase().chain(chars).collect(),
123            None => String::new(),
124        }
125    }
126
127    fn titleize(&self) -> String {
128        self.humanize()
129            .split(' ')
130            .map(|word| {
131                let mut chars = word.chars();
132                match chars.next() {
133                    Some(first) => first.to_uppercase().chain(chars).collect(),
134                    None => String::new(),
135                }
136            })
137            .collect::<Vec<String>>()
138            .join(" ")
139    }
140
141    fn mask(&self, visible: usize) -> String {
142        let count = self.chars().count();
143        let hidden = count.saturating_sub(visible);
144        "*".repeat(hidden) + &self.chars().skip(hidden).collect::<String>()
145    }
146
147    fn pluralize(&self, count: i64) -> String {
148        if count == 1 {
149            format!("1 {self}")
150        } else {
151            format!("{count} {}", glacier_inflect::pluralize(self))
152        }
153    }
154}
155
156impl Text for String {
157    fn squish(&self) -> String {
158        self.as_str().squish()
159    }
160    fn truncated(&self, max: usize) -> String {
161        self.as_str().truncated(max)
162    }
163    fn excerpt(&self, phrase: &str, radius: usize) -> Option<String> {
164        self.as_str().excerpt(phrase, radius)
165    }
166    fn parameterize(&self) -> String {
167        self.as_str().parameterize()
168    }
169    fn humanize(&self) -> String {
170        self.as_str().humanize()
171    }
172    fn titleize(&self) -> String {
173        self.as_str().titleize()
174    }
175    fn mask(&self, visible: usize) -> String {
176        self.as_str().mask(visible)
177    }
178    fn pluralize(&self, count: i64) -> String {
179        self.as_str().pluralize(count)
180    }
181}
182
183/// A Latin letter without its accent (`é` → `e`, `ß` → `ss`); other
184/// characters as they are.
185fn unaccent(c: char) -> String {
186    let plain = match c {
187        'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' => "a",
188        'À' | 'Á' | 'Â' | 'Ã' | 'Ä' | 'Å' | 'Ā' => "A",
189        'æ' => "ae",
190        'Æ' => "AE",
191        'ç' | 'ć' | 'č' => "c",
192        'Ç' | 'Ć' | 'Č' => "C",
193        'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ę' | 'ě' => "e",
194        'È' | 'É' | 'Ê' | 'Ë' | 'Ē' | 'Ę' | 'Ě' => "E",
195        'ì' | 'í' | 'î' | 'ï' | 'ī' => "i",
196        'Ì' | 'Í' | 'Î' | 'Ï' | 'Ī' => "I",
197        'ł' => "l",
198        'Ł' => "L",
199        'ñ' | 'ń' | 'ň' => "n",
200        'Ñ' | 'Ń' | 'Ň' => "N",
201        'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' => "o",
202        'Ò' | 'Ó' | 'Ô' | 'Õ' | 'Ö' | 'Ø' | 'Ō' => "O",
203        'œ' => "oe",
204        'Œ' => "OE",
205        'ř' => "r",
206        'Ř' => "R",
207        'ś' | 'š' | 'ş' => "s",
208        'Ś' | 'Š' | 'Ş' => "S",
209        'ß' => "ss",
210        'ť' | 'ţ' => "t",
211        'Ť' | 'Ţ' => "T",
212        'ù' | 'ú' | 'û' | 'ü' | 'ū' | 'ů' => "u",
213        'Ù' | 'Ú' | 'Û' | 'Ü' | 'Ū' | 'Ů' => "U",
214        'ý' | 'ÿ' => "y",
215        'Ý' | 'Ÿ' => "Y",
216        'ź' | 'ż' | 'ž' => "z",
217        'Ź' | 'Ż' | 'Ž' => "Z",
218        'đ' | 'ð' => "d",
219        'Đ' | 'Ð' => "D",
220        'þ' => "th",
221        'Þ' => "TH",
222        _ => return c.to_string(),
223    };
224    plain.to_owned()
225}
226
227/// Helpers on numbers: integers, floats and `Decimal`.
228pub trait Number {
229    /// Thousands separated with commas: `1234567.delimited()` is
230    /// `"1,234,567"`, `1234.5.delimited()` is `"1,234.5"`.
231    fn delimited(&self) -> String;
232
233    /// An amount of money, to the currency's minor unit, with its symbol:
234    /// `1234.5.to_currency("GBP")` is `"£1,234.50"`; `"JPY"` has no
235    /// decimals; a currency without a known symbol is written before the
236    /// amount (`"CHF 12.00"`).
237    fn to_currency(&self, code: &str) -> String;
238}
239
240/// Helpers on whole numbers.
241pub trait Whole {
242    /// `1.ordinal()` is `"1st"`, `22` is `"22nd"`, `13` is `"13th"`.
243    fn ordinal(&self) -> String;
244
245    /// A byte count for people: `1536.human_size()` is `"1.5 KB"`,
246    /// `0` is `"0 bytes"` (units of 1024, as file browsers show them).
247    fn human_size(&self) -> String;
248}
249
250/// Helpers on times: a timestamp in words, as Rails'
251/// `time_ago_in_words`.
252pub trait Moment {
253    /// How long ago, or how long until, in words: `"3 minutes ago"`,
254    /// `"about 2 hours ago"`, `"in 4 days"`; `"just now"` within half a
255    /// minute.
256    fn time_ago(&self) -> String;
257
258    /// The time between this and `other`, in words, without a direction:
259    /// `"3 minutes"`, `"about 1 year"`.
260    fn time_between(&self, other: &chrono::DateTime<chrono::Utc>) -> String;
261
262    /// Formatted on the app's clock (`time_zone` in the config):
263    /// `inserted_at.local("%-d %B %Y %H:%M")`.
264    fn local(&self, format: &str) -> String;
265}
266
267impl Moment for chrono::DateTime<chrono::Utc> {
268    fn time_ago(&self) -> String {
269        let now = crate::time::now();
270        if (now - *self).num_seconds().abs() < 30 {
271            return "just now".to_owned();
272        }
273        let words = self.time_between(&now);
274        if *self <= now {
275            format!("{words} ago")
276        } else {
277            format!("in {words}")
278        }
279    }
280
281    fn time_between(&self, other: &chrono::DateTime<chrono::Utc>) -> String {
282        distance_in_words((*other - *self).num_seconds().unsigned_abs())
283    }
284
285    fn local(&self, format: &str) -> String {
286        crate::time::format_local(*self, format)
287    }
288}
289
290/// Rails' `distance_of_time_in_words`, without seconds.
291fn distance_in_words(seconds: u64) -> String {
292    let minutes = (seconds + 30) / 60;
293    let plural = |n: u64, unit: &str| {
294        if n == 1 {
295            format!("1 {unit}")
296        } else {
297            format!("{n} {unit}s")
298        }
299    };
300    const DAY: u64 = 1440;
301    match minutes {
302        0 => "less than a minute".to_owned(),
303        1..45 => plural(minutes, "minute"),
304        45..90 => "about 1 hour".to_owned(),
305        90..DAY => format!("about {}", plural((minutes + 30) / 60, "hour")),
306        DAY..2520 => "1 day".to_owned(),
307        2520..43200 => plural((minutes + DAY / 2) / DAY, "day"),
308        43200..86400 => format!("about {}", plural((minutes + 21600) / 43200, "month")),
309        86400..525600 => plural((minutes + 21600) / 43200, "month"),
310        _ => {
311            let years = minutes / 525600;
312            let rest = minutes % 525600;
313            if rest < 131400 {
314                format!("about {}", plural(years, "year"))
315            } else if rest < 394200 {
316                format!("over {}", plural(years, "year"))
317            } else {
318                format!("almost {}", plural(years + 1, "year"))
319            }
320        }
321    }
322}
323
324/// `"-1234.50"` (plain digits) with commas in its whole part.
325fn delimit(plain: &str) -> String {
326    let style = Style::current();
327    let (sign, digits) = match plain.strip_prefix('-') {
328        Some(rest) => ("-", rest),
329        None => ("", plain),
330    };
331    let (whole, fraction) = match digits.split_once('.') {
332        Some((whole, fraction)) => (whole, Some(fraction)),
333        None => (digits, None),
334    };
335    let mut out = String::new();
336    for (i, c) in whole.chars().enumerate() {
337        if i > 0 && (whole.len() - i).is_multiple_of(3) {
338            out.push_str(style.group);
339        }
340        out.push(c);
341    }
342    match fraction {
343        Some(fraction) => format!("{sign}{out}{}{fraction}", style.decimal),
344        None => format!("{sign}{out}"),
345    }
346}
347
348/// How a locale writes numbers: its thousands and decimal separators, and
349/// where a currency's symbol goes.
350struct Style {
351    group: &'static str,
352    decimal: &'static str,
353    /// `1.234,50 €` rather than `€1,234.50`.
354    symbol_after: bool,
355    /// A space between symbol and amount: `R$ 1.234,50`.
356    spaced: bool,
357}
358
359impl Style {
360    /// The request's locale's (`glacier::i18n::locale()`): English's for a
361    /// language without its own here.
362    fn current() -> Self {
363        Self::of(&crate::i18n::locale())
364    }
365
366    fn of(locale: &str) -> Self {
367        // A narrow no-break space, as CLDR writes French and Polish groups.
368        const THIN: &str = "\u{202f}";
369        const NBSP: &str = "\u{a0}";
370        let locale = locale.to_ascii_lowercase().replace('_', "-");
371        let language = locale.split('-').next().unwrap_or("");
372        let (group, decimal, symbol_after, spaced) = match (language, locale.as_str()) {
373            (_, "de-ch") => ("’", ".", false, true),
374            (_, "pt-br") => (".", ",", false, true),
375            ("de" | "es" | "it" | "pt" | "da" | "id" | "tr" | "ro" | "hr" | "sl" | "el", _) => {
376                (".", ",", true, true)
377            }
378            ("nl", _) => (".", ",", false, true),
379            ("fr", _) => (THIN, ",", true, true),
380            ("pl" | "cs" | "sk" | "ru" | "uk" | "sv" | "nb" | "no" | "fi" | "hu" | "bg", _) => {
381                (NBSP, ",", true, true)
382            }
383            _ => (",", ".", false, false),
384        };
385        Self {
386            group,
387            decimal,
388            symbol_after,
389            spaced,
390        }
391    }
392}
393
394/// A currency's symbol and minor-unit digits.
395fn currency(code: &str) -> (Option<&'static str>, usize) {
396    match code.to_ascii_uppercase().as_str() {
397        "GBP" => (Some("£"), 2),
398        "USD" | "CAD" | "AUD" | "NZD" => (Some("$"), 2),
399        "EUR" => (Some("€"), 2),
400        "JPY" => (Some("¥"), 0),
401        "INR" => (Some("₹"), 2),
402        "BRL" => (Some("R$"), 2),
403        "KRW" => (Some("₩"), 0),
404        _ => (None, 2),
405    }
406}
407
408/// `plain` (`"-1234.50"`), already rounded to the currency's decimals,
409/// as money.
410fn money(plain: &str, code: &str) -> String {
411    let (symbol, _) = currency(code);
412    let (sign, amount) = match plain.strip_prefix('-') {
413        Some(rest) => ("-", rest),
414        None => ("", plain),
415    };
416    let amount = delimit(amount);
417    // A negative zero after rounding is zero.
418    let sign = if amount.chars().all(|c| !c.is_ascii_digit() || c == '0') {
419        ""
420    } else {
421        sign
422    };
423    let style = Style::current();
424    let space = if style.spaced { "\u{a0}" } else { "" };
425    match (symbol, style.symbol_after) {
426        (Some(symbol), false) => format!("{sign}{symbol}{space}{amount}"),
427        (Some(symbol), true) => format!("{sign}{amount}{space}{symbol}"),
428        (None, false) => format!("{sign}{} {amount}", code.to_ascii_uppercase()),
429        (None, true) => format!("{sign}{amount} {}", code.to_ascii_uppercase()),
430    }
431}
432
433macro_rules! whole_numbers {
434    ($($ty:ty),*) => {$(
435        impl Number for $ty {
436            fn delimited(&self) -> String {
437                delimit(&self.to_string())
438            }
439            fn to_currency(&self, code: &str) -> String {
440                let (_, digits) = currency(code);
441                money(&format!("{:.digits$}", *self as f64), code)
442            }
443        }
444
445        impl Whole for $ty {
446            #[allow(unused_comparisons)]
447            fn ordinal(&self) -> String {
448                let n = (*self as i128).unsigned_abs();
449                let suffix = match (n % 10, n % 100) {
450                    (_, 11..=13) => "th",
451                    (1, _) => "st",
452                    (2, _) => "nd",
453                    (3, _) => "rd",
454                    _ => "th",
455                };
456                format!("{self}{suffix}")
457            }
458
459            fn human_size(&self) -> String {
460                human_size(*self as f64)
461            }
462        }
463    )*};
464}
465
466whole_numbers!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
467
468fn human_size(bytes: f64) -> String {
469    if bytes.abs() < 1024.0 {
470        return if bytes == 1.0 {
471            "1 byte".to_owned()
472        } else {
473            format!("{bytes} bytes")
474        };
475    }
476    let mut size = bytes;
477    let mut unit = "bytes";
478    for next in ["KB", "MB", "GB", "TB", "PB"] {
479        if size.abs() < 1024.0 {
480            break;
481        }
482        size /= 1024.0;
483        unit = next;
484    }
485    let shown = format!("{size:.1}");
486    let shown = shown.strip_suffix(".0").unwrap_or(&shown);
487    format!("{shown} {unit}")
488}
489
490impl Number for f64 {
491    fn delimited(&self) -> String {
492        delimit(&self.to_string())
493    }
494    fn to_currency(&self, code: &str) -> String {
495        let (_, digits) = currency(code);
496        money(&format!("{self:.digits$}"), code)
497    }
498}
499
500impl Number for f32 {
501    fn delimited(&self) -> String {
502        delimit(&self.to_string())
503    }
504    fn to_currency(&self, code: &str) -> String {
505        f64::from(*self).to_currency(code)
506    }
507}
508
509impl Number for crate::db::Decimal {
510    fn delimited(&self) -> String {
511        delimit(&self.0.normalized().to_plain_string())
512    }
513    fn to_currency(&self, code: &str) -> String {
514        let (_, digits) = currency(code);
515        let rounded = self
516            .0
517            .with_scale_round(digits as i64, bigdecimal::RoundingMode::HalfUp);
518        money(&rounded.to_plain_string(), code)
519    }
520}
521
522impl<T: Number + ?Sized> Number for &T {
523    fn delimited(&self) -> String {
524        (**self).delimited()
525    }
526    fn to_currency(&self, code: &str) -> String {
527        (**self).to_currency(code)
528    }
529}
530
531#[cfg(test)]
532mod tests {
533    use super::*;
534
535    #[test]
536    fn times_in_words_as_rails_writes_them() {
537        let words = |minutes: u64| distance_in_words(minutes * 60);
538        assert_eq!(distance_in_words(20), "less than a minute");
539        assert_eq!(words(1), "1 minute");
540        assert_eq!(words(3), "3 minutes");
541        assert_eq!(words(50), "about 1 hour");
542        assert_eq!(words(150), "about 3 hours");
543        assert_eq!(words(1500), "1 day");
544        assert_eq!(words(4 * 1440), "4 days");
545        assert_eq!(words(35 * 1440), "about 1 month");
546        assert_eq!(words(100 * 1440), "3 months");
547        assert_eq!(words(370 * 1440), "about 1 year");
548        assert_eq!(words(600 * 1440), "over 1 year");
549        assert_eq!(words(700 * 1440), "almost 2 years");
550    }
551
552    #[test]
553    fn time_ago_says_which_way() {
554        let now = crate::time::now();
555        assert_eq!(
556            (now - chrono::TimeDelta::minutes(3)).time_ago(),
557            "3 minutes ago"
558        );
559        assert_eq!((now + chrono::TimeDelta::days(4)).time_ago(), "in 4 days");
560        assert_eq!(now.time_ago(), "just now");
561    }
562
563    #[test]
564    fn text_helpers() {
565        assert_eq!("  a \n  b ".squish(), "a b");
566        assert_eq!("The quick brown fox".truncated(12), "The quick…");
567        assert_eq!("Supercalifragilistic".truncated(6), "Super…");
568        assert_eq!("short".truncated(10), "short");
569        assert_eq!(
570            "The rain in Spain falls mainly".excerpt("spain", 5),
571            Some("…n in Spain fall…".to_owned())
572        );
573        assert_eq!("hello".excerpt("bye", 3), None);
574        assert_eq!("Crème Brûlée & Co.".parameterize(), "creme-brulee-co");
575        assert_eq!("  Hello,  World! ".parameterize(), "hello-world");
576        assert_eq!("author_id".humanize(), "Author");
577        assert_eq!("first_name".humanize(), "First name");
578        assert_eq!("first_name".titleize(), "First Name");
579        assert_eq!("4242424242424242".mask(4), "************4242");
580        assert_eq!("ab".mask(4), "ab");
581        assert_eq!("book".pluralize(3), "3 books");
582        assert_eq!("person".pluralize(1), "1 person");
583        assert_eq!("person".pluralize(0), "0 people");
584    }
585
586    #[test]
587    fn number_helpers() {
588        assert_eq!(1234567.delimited(), "1,234,567");
589        assert_eq!(1234.5.to_currency("GBP"), "£1,234.50");
590        assert_eq!((-1234).delimited(), "-1,234");
591        assert_eq!(999.delimited(), "999");
592        assert_eq!(1234.5.delimited(), "1,234.5");
593        assert_eq!(1234.5.to_currency("GBP"), "£1,234.50");
594        assert_eq!((-5).to_currency("usd"), "-$5.00");
595        assert_eq!(1234.6.to_currency("JPY"), "¥1,235");
596        assert_eq!(12.to_currency("CHF"), "CHF 12.00");
597        assert_eq!((-0.001).to_currency("GBP"), "£0.00");
598        let price: crate::db::Decimal = "1999.995".parse().unwrap();
599        assert_eq!(price.to_currency("EUR"), "€2,000.00");
600        assert_eq!(price.delimited(), "1,999.995");
601        assert_eq!(1.ordinal(), "1st");
602        assert_eq!(22.ordinal(), "22nd");
603        assert_eq!(13.ordinal(), "13th");
604        assert_eq!(111.ordinal(), "111th");
605        assert_eq!(103.ordinal(), "103rd");
606        assert_eq!(0.human_size(), "0 bytes");
607        assert_eq!(1.human_size(), "1 byte");
608        assert_eq!(1536.human_size(), "1.5 KB");
609        assert_eq!((5 * 1024 * 1024).human_size(), "5 MB");
610    }
611
612    #[tokio::test]
613    async fn numbers_follow_the_locale() {
614        let de = crate::i18n::with_locale("de", async {
615            (
616                1234567.5.delimited(),
617                1234.5.to_currency("EUR"),
618                (-0.001).to_currency("EUR"),
619            )
620        })
621        .await;
622        assert_eq!(
623            de,
624            (
625                "1.234.567,5".to_owned(),
626                "1.234,50\u{a0}€".to_owned(),
627                "0,00\u{a0}€".to_owned()
628            )
629        );
630        let fr = crate::i18n::with_locale("fr-FR", async { 1234.5.to_currency("EUR") }).await;
631        assert_eq!(fr, "1\u{202f}234,50\u{a0}€");
632        let br = crate::i18n::with_locale("pt-BR", async { 1234.5.to_currency("BRL") }).await;
633        assert_eq!(br, "R$\u{a0}1.234,50");
634        let ja = crate::i18n::with_locale("ja", async { 1234.to_currency("JPY") }).await;
635        assert_eq!(ja, "¥1,234");
636    }
637}