Skip to main content

relate_core/temporal/
format.rs

1//! CIP-223 temporal pattern formatting.
2
3use chrono::{Datelike, NaiveDate, NaiveTime, Timelike};
4
5use crate::{Error, Result};
6
7use super::pattern::FieldKind;
8use super::zone::{add_offset, zone_display};
9use super::{time_to_nanos, Temporal};
10
11mod duration;
12mod iso;
13
14use iso::format_offset;
15pub(in crate::temporal) use iso::{format_zone_offset, render};
16
17use duration::format_duration_pattern;
18
19/// English month names, January first: the one table the formatter renders
20/// from and the pattern parser reads (case-insensitively, with the
21/// three-letter abbreviation).
22pub(super) const MONTH_NAMES: [&str; 12] = [
23    "January",
24    "February",
25    "March",
26    "April",
27    "May",
28    "June",
29    "July",
30    "August",
31    "September",
32    "October",
33    "November",
34    "December",
35];
36
37/// English weekday names, Monday first (`num_days_from_monday` indexes it).
38pub(super) const WEEKDAY_NAMES: [&str; 7] = [
39    "Monday",
40    "Tuesday",
41    "Wednesday",
42    "Thursday",
43    "Friday",
44    "Saturday",
45    "Sunday",
46];
47
48/// The one fraction-of-second width policy: a pattern run of 1..=9 digits.
49/// Shared by the duration fraction spellings (`n`/`S`) and the date/time `S`
50/// arm, which used to truncate silently past nine.
51pub(super) fn fraction_width(width: usize) -> Result<usize> {
52    if (1..=9).contains(&width) {
53        Ok(width)
54    } else {
55        Err(invalid_pattern_character())
56    }
57}
58
59/// The one CIP-223 unsupported-pattern-character error: a letter outside
60/// the alphabet, or one the target temporal kind has no field for, is the
61/// same SyntaxError — never a per-field type error.
62fn invalid_pattern_character() -> Error {
63    Error::syntax("InvalidPatternCharacter")
64}
65
66/// The same rejection naming the letter — the one detail-carrying sibling
67/// of [`invalid_pattern_character`], so the token has two spellings for
68/// exactly this distinction and no other.
69fn invalid_pattern_symbol(c: char) -> Error {
70    Error::syntax(format!(
71        "InvalidPatternCharacter: unsupported temporal format symbol '{c}'"
72    ))
73}
74
75/// A pattern letter's field on the target temporal kind, or the one
76/// unsupported-character error when the kind has no such field.
77fn supported_field<T>(field: Option<T>) -> Result<T> {
78    field.ok_or_else(invalid_pattern_character)
79}
80
81/// The fields a temporal value offers a date/time pattern; a field the
82/// value's kind lacks is `None`, which a letter reading it rejects.
83#[derive(Clone, Copy, Default)]
84struct PatternParts<'a> {
85    date: Option<NaiveDate>,
86    time: Option<NaiveTime>,
87    offset: Option<i32>,
88    zone: Option<&'a str>,
89}
90
91/// One pattern letter run (`len` repetitions of `c`) rendered from `parts`:
92/// the symbol table, apart from the walk over quoting and padding. The
93/// letter is classified by the instant parser's one alphabet
94/// ([`FieldKind::from_letter`]) and the match over the resulting kind is
95/// exhaustive, so a field added to the alphabet cannot be left unrendered;
96/// `c` is kept only for the spellings a kind shares (`y`/`u`, `h`/`K`, …).
97fn render_symbol(c: char, len: usize, parts: PatternParts<'_>) -> Result<String> {
98    let PatternParts {
99        date,
100        time,
101        offset,
102        zone,
103    } = parts;
104    let kind = FieldKind::from_letter(c).ok_or_else(|| invalid_pattern_symbol(c))?;
105    Ok(match kind {
106        FieldKind::Year | FieldKind::WeekYear => {
107            let d = supported_field(date)?;
108            let y = if c == 'Y' {
109                d.iso_week().year()
110            } else if c == 'y' && d.year() <= 0 {
111                1 - d.year()
112            } else {
113                d.year()
114            };
115            if len == 2 {
116                format!("{:02}", y.rem_euclid(100))
117            } else if y < 0 {
118                format!("-{:0len$}", y.unsigned_abs())
119            } else {
120                format!("{y:0len$}")
121            }
122        }
123        FieldKind::Month => {
124            let month = supported_field(date)?.month();
125            if len >= 3 {
126                let full = MONTH_NAMES[month as usize - 1];
127                // The match's `_` arm is the single width rejection.
128                match len {
129                    3 => full.chars().take(3).collect(),
130                    4 => full.to_string(),
131                    5 => full
132                        .chars()
133                        .next()
134                        .expect("month names are non-empty")
135                        .to_string(),
136                    _ => return Err(invalid_pattern_character()),
137                }
138            } else {
139                format!("{month:0len$}")
140            }
141        }
142        FieldKind::Quarter => {
143            let q = (supported_field(date)?.month0() / 3) + 1;
144            match len {
145                1 => q.to_string(),
146                2 => format!("{q:02}"),
147                3 => format!("Q{q}"),
148                4 => match q {
149                    1 => "1st quarter".into(),
150                    2 => "2nd quarter".into(),
151                    3 => "3rd quarter".into(),
152                    _ => "4th quarter".into(),
153                },
154                5 => q.to_string(),
155                _ => return Err(invalid_pattern_character()),
156            }
157        }
158        FieldKind::Day => {
159            if len > 2 {
160                return Err(invalid_pattern_character());
161            }
162            format!("{:0len$}", supported_field(date)?.day())
163        }
164        FieldKind::DayOfYear => format!("{:0len$}", supported_field(date)?.ordinal()),
165        FieldKind::DayOfWeekName => {
166            let weekday = supported_field(date)?.weekday();
167            let name = WEEKDAY_NAMES[weekday.num_days_from_monday() as usize];
168            if len >= 4 {
169                name.into()
170            } else {
171                name.chars().take(3).collect()
172            }
173        }
174        FieldKind::DayOfWeekNum => {
175            (supported_field(date)?.weekday().num_days_from_sunday() + 1).to_string()
176        }
177        FieldKind::Week => supported_field(date)?.iso_week().week().to_string(),
178        FieldKind::WeekOfMonth => {
179            let date = supported_field(date)?;
180            let first = date
181                .with_day(1)
182                .expect("every month has a first day")
183                .weekday()
184                .num_days_from_sunday();
185            ((date.day() + first - 1) / 7 + 1).to_string()
186        }
187        FieldKind::AlignedDayOfWeek => (supported_field(date)?.day0() / 7 + 1).to_string(),
188        FieldKind::ModifiedJulianDay => {
189            (supported_field(date)?.num_days_from_ce() - 678_576).to_string()
190        }
191        FieldKind::Era => {
192            if supported_field(date)?.year() <= 0 {
193                "BC".into()
194            } else {
195                "AD".into()
196            }
197        }
198        FieldKind::HourOfDay => format!("{:0len$}", supported_field(time)?.hour()),
199        FieldKind::ClockHour => {
200            let h = supported_field(time)?.hour();
201            format!("{:0len$}", if h == 0 { 24 } else { h })
202        }
203        FieldKind::HourOfAmPm if c == 'h' => {
204            let h = supported_field(time)?.hour() % 12;
205            format!("{:0len$}", if h == 0 { 12 } else { h })
206        }
207        FieldKind::HourOfAmPm => format!("{:0len$}", supported_field(time)?.hour() % 12),
208        FieldKind::AmPm => {
209            if supported_field(time)?.hour() < 12 {
210                "AM".into()
211            } else {
212                "PM".into()
213            }
214        }
215        FieldKind::PeriodOfDay => {
216            let hour = supported_field(time)?.hour();
217            match hour {
218                0..=5 => "at night",
219                6..=11 => "in the morning",
220                12..=17 => "in the afternoon",
221                _ => "in the evening",
222            }
223            .into()
224        }
225        FieldKind::Minute => format!("{:0len$}", supported_field(time)?.minute()),
226        FieldKind::Second => format!("{:0len$}", supported_field(time)?.second()),
227        FieldKind::Fraction => {
228            let nanos = supported_field(time)?.nanosecond();
229            let width = fraction_width(len)?;
230            format!("{nanos:09}").chars().take(width).collect()
231        }
232        FieldKind::NanoOfSecond => supported_field(time)?.nanosecond().to_string(),
233        FieldKind::NanoOfDay => time_to_nanos(supported_field(time)?).to_string(),
234        FieldKind::MilliOfDay => (time_to_nanos(supported_field(time)?) / 1_000_000).to_string(),
235        FieldKind::OffsetZ => {
236            let offset = supported_field(offset)?;
237            match len {
238                1..=3 => format_offset(offset).replace(':', ""),
239                4 if offset == 0 => "GMT".into(),
240                4 => format!("GMT{}", format_offset(offset)),
241                5 => format_zone_offset(offset),
242                _ => return Err(invalid_pattern_character()),
243            }
244        }
245        FieldKind::OffsetFractional => {
246            let offset = supported_field(offset)?;
247            if offset == 0 && c == 'X' {
248                "Z".into()
249            } else {
250                let raw = format_offset(offset);
251                let compact = raw.replace(':', "");
252                match len {
253                    1 => {
254                        if offset % 3600 == 0 {
255                            compact[..3].into()
256                        } else {
257                            compact
258                        }
259                    }
260                    2 | 4 => compact,
261                    3 | 5 => raw,
262                    _ => return Err(invalid_pattern_character()),
263                }
264            }
265        }
266        FieldKind::OffsetLocalized => {
267            let offset = supported_field(offset)?;
268            match (len, offset) {
269                (1 | 4, 0) => "GMT".into(),
270                (1, _) if offset % 3600 == 0 => {
271                    format!("GMT{:+}", offset / 3600)
272                }
273                (1, _) => format!("GMT{}", format_offset(offset)),
274                (4, _) => format!("GMT{}", format_offset(offset)),
275                _ => return Err(invalid_pattern_character()),
276            }
277        }
278        // `V` (zone id) needs an actual zone: a zoned time or local
279        // datetime has no zone, so per the matrix it is an unsupported
280        // pattern character there — not an offset fallback.
281        FieldKind::ZoneId if c == 'V' && len == 2 => supported_field(zone)?.to_string(),
282        FieldKind::ZoneId if c == 'V' => return Err(invalid_pattern_symbol(c)),
283        // `z` (zone name) and `v` (generic zone name) share the display
284        // table.
285        FieldKind::ZoneName | FieldKind::ZoneId => {
286            let zone = supported_field(zone)?;
287            if (c == 'z' && len > 4) || (c == 'v' && !matches!(len, 1 | 4)) {
288                return Err(invalid_pattern_character());
289            }
290            match (zone_display(zone), c, len) {
291                (Some(d), 'z', 4) => d.long_summer.into(),
292                (Some(d), 'v', 4) => d.long_generic.into(),
293                (Some(d), 'z', _) => d.short_summer.into(),
294                (Some(d), _, _) => d.short_generic.into(),
295                (None, ..) => zone.into(),
296            }
297        }
298    })
299}
300
301/// Storage-independent subset of the CIP-223/Java temporal pattern surface.
302/// Unsupported alphabetic pattern symbols are rejected with the one
303/// SyntaxError the CIP-223 character matrix documents
304/// (`InvalidPatternCharacter`) instead of being emitted literally.
305pub fn format_pattern(value: &Temporal, pattern: &str) -> Result<String> {
306    if pattern.chars().any(|c| matches!(c, '#' | '{' | '}')) {
307        return Err(invalid_pattern_character());
308    }
309    let parts = match value {
310        Temporal::Date(d) => PatternParts {
311            date: Some(*d),
312            ..Default::default()
313        },
314        Temporal::LocalTime(t) => PatternParts {
315            time: Some(*t),
316            ..Default::default()
317        },
318        Temporal::Time { time, offset } => PatternParts {
319            time: Some(*time),
320            offset: Some(*offset),
321            ..Default::default()
322        },
323        Temporal::LocalDateTime(dt) => PatternParts {
324            date: Some(dt.date()),
325            time: Some(dt.time()),
326            ..Default::default()
327        },
328        Temporal::DateTime { utc, offset, zone } => {
329            let local = add_offset(*utc, *offset)?;
330            PatternParts {
331                date: Some(local.date()),
332                time: Some(local.time()),
333                offset: Some(*offset),
334                zone: zone.as_deref(),
335            }
336        }
337        Temporal::Duration {
338            months,
339            days,
340            nanos,
341        } => return format_duration_pattern(*months, *days, *nanos, pattern),
342        Temporal::CivilDate { .. } | Temporal::CivilDateTime { .. } => {
343            return if pattern.is_empty() {
344                Ok(String::new())
345            } else {
346                Err(Error::ty(
347                    "format pattern is unsupported for out-of-range dates",
348                ))
349            }
350        }
351    };
352    let chars: Vec<char> = pattern.chars().collect();
353    let mut out = String::new();
354    let mut i = 0;
355    let mut quoted = false;
356    while i < chars.len() {
357        if chars[i] == '\'' {
358            if chars.get(i + 1) == Some(&'\'') {
359                out.push('\'');
360                i += 2;
361                continue;
362            }
363            quoted = !quoted;
364            i += 1;
365            continue;
366        }
367        if !quoted && matches!(chars[i], '[' | ']') {
368            i += 1;
369            continue;
370        }
371        if quoted || !chars[i].is_ascii_alphabetic() {
372            out.push(chars[i]);
373            i += 1;
374            continue;
375        }
376        let c = chars[i];
377        let mut len = 1;
378        while chars.get(i + len) == Some(&c) {
379            len += 1;
380        }
381        if c == 'p' {
382            let Some(&next) = chars.get(i + len) else {
383                return Err(invalid_pattern_character());
384            };
385            let mut next_len = 1;
386            while chars.get(i + len + next_len) == Some(&next) {
387                next_len += 1;
388            }
389            let rendered = format_pattern(value, &next.to_string().repeat(next_len))?;
390            out.push_str(&format!("{rendered:>len$}"));
391            i += len + next_len;
392            continue;
393        }
394        let piece = render_symbol(c, len, parts)?;
395        out.push_str(&piece);
396        i += len;
397    }
398    if quoted {
399        // The duration pattern engine spells this the same way with the
400        // syntax class; one class for one escape failure in both engines.
401        return Err(Error::syntax("unterminated quote in temporal format"));
402    }
403    Ok(out)
404}