Skip to main content

i18n_next/format/
relative.rs

1//! `Intl.RelativeTimeFormat` as `FormatService.formatRelativeTime` drives it (DESIGN 5.3):
2//! the largest unit that fits at least once, rounded down, `-0` (under a second in the past)
3//! as `0 … ago`. The patterns per plural form and the words of `numeric: "auto"` were read
4//! back from Node's ICU by `scripts/cldr.mjs`; the number is the locale's default format.
5
6use super::NumberOptions;
7use super::data::{self, DATE_REL, DATE_REL_PARTS, Loc};
8use crate::plural::{self, Operands};
9use std::fmt;
10
11/// Options of [`I18n::tdr_with`](crate::I18n::tdr_with), `Intl.RelativeTimeFormat`'s:
12/// `numeric` (`always` by default, [`auto`](Self::auto) says `yesterday` / `now`) and
13/// `style` (`long` by default, [`short`](Self::short), [`narrow`](Self::narrow)).
14///
15/// ```
16/// use i18n_next::RelativeOptions;
17///
18/// let o = RelativeOptions::default().auto().short();
19/// assert_ne!(o, RelativeOptions::default());
20/// ```
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
22pub struct RelativeOptions {
23    auto: bool,
24    /// 0 long, 1 short, 2 narrow
25    style: u8,
26}
27
28impl RelativeOptions {
29    /// `numeric: "auto"`: `yesterday`, `now`, `next year` where the locale has a word.
30    #[must_use]
31    pub const fn auto(mut self) -> Self {
32        self.auto = true;
33        self
34    }
35
36    /// `style: "short"`.
37    #[must_use]
38    pub const fn short(mut self) -> Self {
39        self.style = 1;
40        self
41    }
42
43    /// `style: "narrow"`.
44    #[must_use]
45    pub const fn narrow(mut self) -> Self {
46        self.style = 2;
47        self
48    }
49}
50
51/// Seconds per unit, largest first (`FormatService` `UNITS`).
52const SPANS: [f64; 6] = [31_536_000.0, 2_592_000.0, 86_400.0, 3600.0, 60.0, 1.0];
53
54/// Writes `at` relative to `now` (both milliseconds of valid dates).
55#[allow(
56    clippy::cast_precision_loss,
57    reason = "JS subtracts the two as doubles"
58)]
59#[allow(
60    clippy::cast_possible_truncation,
61    clippy::cast_sign_loss,
62    reason = "a whole count"
63)]
64pub(crate) fn write(
65    at: i64,
66    now: i64,
67    o: RelativeOptions,
68    loc: &Loc,
69    out: &mut dyn fmt::Write,
70) -> fmt::Result {
71    let seconds = (at as f64 - now as f64) / 1000.0;
72    let size = seconds.abs();
73    let unit = SPANS
74        .iter()
75        .position(|&s| size >= s)
76        .unwrap_or(SPANS.len() - 1);
77    let n = (size / SPANS.get(unit).copied().unwrap_or(1.0)).floor();
78    let past = seconds < 0.0;
79    // the locale's row names one part per unit and style: 5 words, then future and past
80    // patterns by plural category
81    let part = DATE_REL
82        .get(usize::from(loc.drel))
83        .and_then(|r| r.get(unit * 3 + usize::from(o.style)))
84        .and_then(|&p| DATE_REL_PARTS.get(usize::from(p)));
85    let s = |i: usize| data::dname(part.and_then(|r| r.get(i)).copied().unwrap_or(0));
86    if o.auto && n <= 2.0 {
87        // ICU: -2 … 2 by their own words (0 whatever its sign), where the locale has one
88        let word = s(if past { 2 - n as usize } else { 2 + n as usize });
89        if !word.is_empty() {
90            return out.write_str(word);
91        }
92    }
93    let cat = plural::select_rule(loc.plural, &Operands::int(n as u64)) as usize;
94    let list = if past { 11 } else { 5 };
95    let pattern = match s(list + cat) {
96        "" => s(list + 5),
97        p => p,
98    };
99    // a form may spell its number out (`ar`: `قبل سنتين`, two years ago)
100    let Some((before, after)) = pattern.split_once("{0}") else {
101        return out.write_str(pattern);
102    };
103    out.write_str(before)?;
104    super::number::write(n, &NumberOptions::DEFAULT, loc, out)?;
105    out.write_str(after)
106}