i18n_next/format/
relative.rs1use super::NumberOptions;
7use super::data::{self, DATE_REL, DATE_REL_PARTS, Loc};
8use crate::plural::{self, Operands};
9use std::fmt;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
22pub struct RelativeOptions {
23 auto: bool,
24 style: u8,
26}
27
28impl RelativeOptions {
29 #[must_use]
31 pub const fn auto(mut self) -> Self {
32 self.auto = true;
33 self
34 }
35
36 #[must_use]
38 pub const fn short(mut self) -> Self {
39 self.style = 1;
40 self
41 }
42
43 #[must_use]
45 pub const fn narrow(mut self) -> Self {
46 self.style = 2;
47 self
48 }
49}
50
51const SPANS: [f64; 6] = [31_536_000.0, 2_592_000.0, 86_400.0, 3600.0, 60.0, 1.0];
53
54#[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 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 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 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}