Skip to main content

vector_core/
text_time.rs

1//! Times that read the same everywhere, Discord's `<t:UNIX:STYLE>`.
2//!
3//! On send each `<t:…>` outside code becomes a fixed UTC rendering, `2026-10-09 14:00 UTC`,
4//! and a `["time", from, to, unix, style]` tag. Other clients read a real time; a Vector
5//! shows it in the reader's own zone and locale. A tag only counts when the text it covers
6//! is exactly that rendering of its own instant, so it can never stand in for other words.
7
8use serde::{Deserialize, Serialize};
9
10pub const TAG: &str = "time";
11/// Discord's styles: t T (time), d D (date), f F (date and time, `f` the default),
12/// s S (short date with time), R (relative).
13pub const STYLES: &str = "tTdDfFsSR";
14const MAX_SPANS: usize = 64;
15/// Years 0000-9999, so the fallback always has its fixed shape.
16const MIN_UNIX: i64 = -62_167_219_200;
17const MAX_UNIX: i64 = 253_402_300_799;
18
19#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
20pub struct TimeSpan {
21    pub from: u32,
22    pub to: u32,
23    pub unix: i64,
24    pub style: char,
25}
26
27impl TimeSpan {
28    /// The span as stored and sent: the tag name, then its fields.
29    pub fn to_tag_parts(&self) -> Vec<String> {
30        vec![TAG.to_string(), self.from.to_string(), self.to.to_string(), self.unix.to_string(), self.style.to_string()]
31    }
32
33    /// A tag that covers exactly its own fallback in `content`, or None.
34    pub(crate) fn from_parts(parts: &[&str], content: &[char]) -> Option<Self> {
35        if parts.len() != 5 || parts[0] != TAG {
36            return None;
37        }
38        let from: u32 = parts[1].parse().ok()?;
39        let to: u32 = parts[2].parse().ok()?;
40        let unix: i64 = parts[3].parse().ok()?;
41        let mut style = parts[4].chars();
42        let style = style.next().filter(|c| STYLES.contains(*c) && style.next().is_none())?;
43        let expect = fallback(unix)?;
44        // The fallback is ASCII: its length in chars is its length in bytes.
45        if to.checked_sub(from)? as usize != expect.len() {
46            return None;
47        }
48        let covered = content.get(from as usize..to as usize)?;
49        covered.iter().copied().eq(expect.chars()).then_some(TimeSpan { from, to, unix, style })
50    }
51}
52
53/// Days since 1970-01-01 → (year, month, day), proleptic Gregorian.
54fn civil(days: i64) -> (i64, u32, u32) {
55    let z = days + 719_468;
56    let era = z.div_euclid(146_097);
57    let doe = z.rem_euclid(146_097);
58    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
59    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
60    let mp = (5 * doy + 2) / 153;
61    let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
62    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
63    (yoe + era * 400 + i64::from(month <= 2), month, day)
64}
65
66/// The fixed UTC text a time travels as: `YYYY-MM-DD HH:MM UTC`, with `:SS` when not on the minute.
67pub fn fallback(unix: i64) -> Option<String> {
68    if !(MIN_UNIX..=MAX_UNIX).contains(&unix) {
69        return None;
70    }
71    let (y, mo, d) = civil(unix.div_euclid(86_400));
72    let secs = unix.rem_euclid(86_400);
73    let (h, mi, s) = (secs / 3600, secs % 3600 / 60, secs % 60);
74    Some(if s == 0 {
75        format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02} UTC")
76    } else {
77        format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02}:{s:02} UTC")
78    })
79}
80
81/// Every `<t:UNIX>` / `<t:UNIX:STYLE>` outside code: (byte start, byte end, unix, style).
82pub(crate) fn tokens(content: &str) -> Vec<(usize, usize, i64, char)> {
83    if !content.contains("<t:") {
84        return Vec::new();
85    }
86    let code = crate::text_color::code_ranges(content);
87    let in_code = |i: usize| code.iter().any(|&(s, e)| i >= s && i < e);
88    let mut out = Vec::new();
89    let mut i = 0;
90    while let Some(off) = content[i..].find("<t:") {
91        let at = i + off;
92        i = at + 3;
93        if in_code(at) {
94            continue;
95        }
96        let rest = &content[at + 3..];
97        let digits = rest.char_indices().take_while(|&(k, c)| c.is_ascii_digit() || (k == 0 && c == '-')).count();
98        let num = &rest[..digits];
99        let after = &rest[digits..];
100        let (style, len) = if after.starts_with('>') {
101            ('f', 1)
102        } else if after.len() >= 3 && after.as_bytes()[0] == b':' && after.as_bytes()[2] == b'>' {
103            (after.as_bytes()[1] as char, 3)
104        } else {
105            continue;
106        };
107        let Ok(unix) = num.parse::<i64>() else { continue };
108        if !STYLES.contains(style) || num.trim_start_matches('-').len() > 12 || fallback(unix).is_none() {
109            continue;
110        }
111        let end = at + 3 + digits + len;
112        out.push((at, end, unix, style));
113        if out.len() == MAX_SPANS {
114            break;
115        }
116        i = end;
117    }
118    out
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn fallback_is_fixed_utc() {
127        assert_eq!(fallback(0).unwrap(), "1970-01-01 00:00 UTC");
128        assert_eq!(fallback(1_618_953_630).unwrap(), "2021-04-20 21:20:30 UTC");
129        assert_eq!(fallback(1_709_208_000).unwrap(), "2024-02-29 12:00 UTC", "a leap day");
130        assert_eq!(fallback(-1).unwrap(), "1969-12-31 23:59:59 UTC");
131        assert_eq!(fallback(MAX_UNIX).unwrap(), "9999-12-31 23:59:59 UTC");
132        assert_eq!(fallback(MIN_UNIX).unwrap(), "0000-01-01 00:00 UTC");
133        assert!(fallback(MAX_UNIX + 1).is_none());
134    }
135
136    #[test]
137    fn tokens_take_discords_forms_outside_code() {
138        let t = tokens("at <t:1618953630:R> and <t:0> but `<t:5:R>` and <t:9:x> <t:12:Rx> <t:abc:R>");
139        assert_eq!(t.iter().map(|x| (x.2, x.3)).collect::<Vec<_>>(), vec![(1_618_953_630, 'R'), (0, 'f')]);
140    }
141
142    #[test]
143    fn a_tag_only_covers_its_own_fallback() {
144        let content: Vec<char> = "meet 2021-04-20 21:20:30 UTC ok".chars().collect();
145        let good = ["time", "5", "28", "1618953630", "R"];
146        assert!(TimeSpan::from_parts(&good, &content).is_some());
147        assert!(TimeSpan::from_parts(&["time", "5", "28", "1618953631", "R"], &content).is_none(), "another instant");
148        assert!(TimeSpan::from_parts(&["time", "0", "4", "1618953630", "R"], &content).is_none(), "other words");
149        assert!(TimeSpan::from_parts(&["time", "5", "28", "1618953630", "Q"], &content).is_none());
150        assert!(TimeSpan::from_parts(&["time", "5", "28", "1618953630", "RR"], &content).is_none());
151        assert!(TimeSpan::from_parts(&["time", "5", "28", "1618953630", "R", "x"], &content).is_none(), "unknown args void it");
152    }
153}