glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
//! Text and number helpers, for views and code alike:
//! `post.body.truncated(140)`, `"Annual Report 2026".parameterize()`,
//! `"author_id".humanize()`, `"book".pluralize(n)`, `1234567.delimited()`,
//! `price.to_currency("GBP")`, `size.human_size()`, `3.ordinal()`.
//!
//! In the prelude, as `Text` and `Number`.

/// Helpers on text: `str` and `String`.
pub trait Text {
    /// Leading and trailing whitespace gone, and each run inside one
    /// space: `"  a \n  b ".squish()` is `"a b"`.
    fn squish(&self) -> String;

    /// At most `max` characters; text cut short ends in `…`, at a word
    /// break when there is one in the last third:
    /// `"The quick brown fox".truncated(12)` is `"The quick…"`.
    fn truncated(&self, max: usize) -> String;

    /// The words around the first `phrase` (ignoring case), `radius`
    /// characters each side, with `…` where text was cut; `None` when the
    /// phrase isn't there.
    fn excerpt(&self, phrase: &str, radius: usize) -> Option<String>;

    /// A URL slug: lowercase letters, digits and single hyphens, accents
    /// dropped: `"Crème Brûlée & Co.".parameterize()` is
    /// `"creme-brulee-co"`.
    fn parameterize(&self) -> String;

    /// A column name as a label: `"author_id".humanize()` is `"Author"`,
    /// `"first_name"` is `"First name"`.
    fn humanize(&self) -> String;

    /// Each word capitalised: `"first_name".titleize()` is `"First Name"`.
    fn titleize(&self) -> String;

    /// All but the last `visible` characters as `*`:
    /// `"4242424242424242".mask(4)` is `"************4242"`.
    fn mask(&self, visible: usize) -> String;

    /// The count and the word, plural unless the count is 1:
    /// `"book".pluralize(3)` is `"3 books"`, `"person".pluralize(1)` is
    /// `"1 person"`.
    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();
        // Cut at the last space when it keeps most of the text.
        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();
        // Lowercasing can change byte lengths; find the phrase by
        // characters so the cut lines up with `self`.
        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)
    }
}

/// A Latin letter without its accent (`é` → `e`, `ß` → `ss`); other
/// characters as they are.
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()
}

/// Helpers on numbers: integers, floats and `Decimal`.
pub trait Number {
    /// Thousands separated with commas: `1234567.delimited()` is
    /// `"1,234,567"`, `1234.5.delimited()` is `"1,234.5"`.
    fn delimited(&self) -> String;

    /// An amount of money, to the currency's minor unit, with its symbol:
    /// `1234.5.to_currency("GBP")` is `"£1,234.50"`; `"JPY"` has no
    /// decimals; a currency without a known symbol is written before the
    /// amount (`"CHF 12.00"`).
    fn to_currency(&self, code: &str) -> String;
}

/// Helpers on whole numbers.
pub trait Whole {
    /// `1.ordinal()` is `"1st"`, `22` is `"22nd"`, `13` is `"13th"`.
    fn ordinal(&self) -> String;

    /// A byte count for people: `1536.human_size()` is `"1.5 KB"`,
    /// `0` is `"0 bytes"` (units of 1024, as file browsers show them).
    fn human_size(&self) -> String;
}

/// Helpers on times: a timestamp in words, as Rails'
/// `time_ago_in_words`.
pub trait Moment {
    /// How long ago, or how long until, in words: `"3 minutes ago"`,
    /// `"about 2 hours ago"`, `"in 4 days"`; `"just now"` within half a
    /// minute.
    fn time_ago(&self) -> String;

    /// The time between this and `other`, in words, without a direction:
    /// `"3 minutes"`, `"about 1 year"`.
    fn time_between(&self, other: &chrono::DateTime<chrono::Utc>) -> String;

    /// Formatted on the app's clock (`time_zone` in the config):
    /// `inserted_at.local("%-d %B %Y %H:%M")`.
    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)
    }
}

/// Rails' `distance_of_time_in_words`, without seconds.
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"))
            }
        }
    }
}

/// `"-1234.50"` (plain digits) with commas in its whole part.
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}"),
    }
}

/// How a locale writes numbers: its thousands and decimal separators, and
/// where a currency's symbol goes.
struct Style {
    group: &'static str,
    decimal: &'static str,
    /// `1.234,50 €` rather than `€1,234.50`.
    symbol_after: bool,
    /// A space between symbol and amount: `R$ 1.234,50`.
    spaced: bool,
}

impl Style {
    /// The request's locale's (`glacier::i18n::locale()`): English's for a
    /// language without its own here.
    fn current() -> Self {
        Self::of(&crate::i18n::locale())
    }

    fn of(locale: &str) -> Self {
        // A narrow no-break space, as CLDR writes French and Polish groups.
        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,
        }
    }
}

/// A currency's symbol and minor-unit digits.
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),
    }
}

/// `plain` (`"-1234.50"`), already rounded to the currency's decimals,
/// as money.
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);
    // A negative zero after rounding is zero.
    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");
    }
}