1use std::fmt::{self, Write};
26
27use jiff::civil;
28use jiff::tz::{Offset, TimeZone};
29
30use crate::{SecondsFormat, UtcDateTime};
31
32const MONTHS: [&str; 12] = [
33 "January",
34 "February",
35 "March",
36 "April",
37 "May",
38 "June",
39 "July",
40 "August",
41 "September",
42 "October",
43 "November",
44 "December",
45];
46const WEEKDAYS: [&str; 7] = [
47 "Monday",
48 "Tuesday",
49 "Wednesday",
50 "Thursday",
51 "Friday",
52 "Saturday",
53 "Sunday",
54];
55
56#[derive(Clone, Debug)]
58pub(crate) struct Parts {
59 civil: civil::DateTime,
60 nanos: u32,
61 offset_secs: i32,
62 unix_secs: i64,
63 zone_name: Option<&'static str>,
64}
65
66impl Parts {
67 pub(crate) fn utc(t: UtcDateTime) -> Self {
68 Self::with_offset(t, 0, Some("UTC"))
69 }
70
71 pub(crate) fn with_offset(
72 t: UtcDateTime,
73 offset_secs: i32,
74 zone_name: Option<&'static str>,
75 ) -> Self {
76 let offset = Offset::from_seconds(offset_secs).expect("offset within ±25:59:59");
77 let civil = TimeZone::fixed(offset).to_datetime(t.as_jiff());
78 Self {
79 civil,
80 nanos: t.timestamp_subsec_nanos(),
81 offset_secs,
82 unix_secs: t.timestamp(),
83 zone_name,
84 }
85 }
86
87 fn year(&self) -> i32 {
88 i32::from(self.civil.year())
89 }
90 fn month(&self) -> u32 {
91 self.civil.month().unsigned_abs().into()
92 }
93 fn day(&self) -> u32 {
94 self.civil.day().unsigned_abs().into()
95 }
96 fn hour(&self) -> u32 {
97 self.civil.hour().unsigned_abs().into()
98 }
99 fn minute(&self) -> u32 {
100 self.civil.minute().unsigned_abs().into()
101 }
102 fn second(&self) -> u32 {
103 self.civil.second().unsigned_abs().into()
104 }
105 fn weekday0(&self) -> usize {
107 usize::from(self.civil.weekday().to_monday_zero_offset().unsigned_abs())
108 }
109 fn ordinal(&self) -> u32 {
110 self.civil.day_of_year().unsigned_abs().into()
111 }
112}
113
114pub(crate) fn offset_colon(secs: i32) -> String {
116 let mut s = String::with_capacity(6);
117 write_offset(&mut s, secs, OffsetStyle::Colon);
118 s
119}
120
121#[derive(Clone, Copy)]
122enum OffsetStyle {
123 Plain,
125 Colon,
127 ColonSeconds,
129 HoursOnly,
131}
132
133fn write_offset(out: &mut String, secs: i32, style: OffsetStyle) {
134 let sign = if secs < 0 { '-' } else { '+' };
135 let abs = secs.unsigned_abs();
136 let (h, m, s) = (abs / 3600, abs / 60 % 60, abs % 60);
137 let _ = match style {
138 OffsetStyle::Plain => write!(out, "{sign}{h:02}{m:02}"),
139 OffsetStyle::Colon => write!(out, "{sign}{h:02}:{m:02}"),
140 OffsetStyle::ColonSeconds => write!(out, "{sign}{h:02}:{m:02}:{s:02}"),
141 OffsetStyle::HoursOnly => write!(out, "{sign}{h:02}"),
142 };
143}
144
145fn write_year(out: &mut String, year: i32) {
146 let _ = if (0..=9999).contains(&year) {
147 write!(out, "{year:04}")
148 } else {
149 write!(out, "{year:+05}")
150 };
151}
152
153fn write_auto_fraction(out: &mut String, nanos: u32) {
155 let _ = if nanos == 0 {
156 Ok(())
157 } else if nanos.is_multiple_of(1_000_000) {
158 write!(out, ".{:03}", nanos / 1_000_000)
159 } else if nanos.is_multiple_of(1_000) {
160 write!(out, ".{:06}", nanos / 1_000)
161 } else {
162 write!(out, ".{nanos:09}")
163 };
164}
165
166fn write_fixed_fraction(out: &mut String, nanos: u32, digits: u32, dot: bool) {
167 if dot {
168 out.push('.');
169 }
170 let _ = match digits {
171 3 => write!(out, "{:03}", nanos / 1_000_000),
172 6 => write!(out, "{:06}", nanos / 1_000),
173 _ => write!(out, "{nanos:09}"),
174 };
175}
176
177pub(crate) fn write_rfc3339(out: &mut String, p: &Parts, secform: SecondsFormat, offset: &str) {
178 write_year(out, p.year());
179 let _ = write!(
180 out,
181 "-{:02}-{:02}T{:02}:{:02}:{:02}",
182 p.month(),
183 p.day(),
184 p.hour(),
185 p.minute(),
186 p.second()
187 );
188 match secform {
189 SecondsFormat::Secs => {}
190 SecondsFormat::Millis => write_fixed_fraction(out, p.nanos, 3, true),
191 SecondsFormat::Micros => write_fixed_fraction(out, p.nanos, 6, true),
192 SecondsFormat::Nanos => write_fixed_fraction(out, p.nanos, 9, true),
193 SecondsFormat::AutoSi => write_auto_fraction(out, p.nanos),
194 }
195 out.push_str(offset);
196}
197
198pub(crate) fn write_display(out: &mut String, p: &Parts) {
200 write_year(out, p.year());
201 let _ = write!(
202 out,
203 "-{:02}-{:02} {:02}:{:02}:{:02}",
204 p.month(),
205 p.day(),
206 p.hour(),
207 p.minute(),
208 p.second()
209 );
210 write_auto_fraction(out, p.nanos);
211 out.push(' ');
212 match p.zone_name {
213 Some(name) => out.push_str(name),
214 None => write_offset(out, p.offset_secs, OffsetStyle::Colon),
215 }
216}
217
218#[derive(Clone, Debug)]
220pub struct Formatted<'a> {
221 parts: Parts,
222 fmt: &'a str,
223}
224
225impl<'a> Formatted<'a> {
226 pub(crate) fn new(parts: Parts, fmt: &'a str) -> Self {
227 Self { parts, fmt }
228 }
229}
230
231impl fmt::Display for Formatted<'_> {
232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233 let mut out = String::with_capacity(self.fmt.len() + 16);
234 strftime(&mut out, &self.parts, self.fmt);
235 f.pad(&out)
236 }
237}
238
239#[derive(Clone, Copy, PartialEq, Eq)]
240enum Pad {
241 Default,
242 None,
243 Space,
244 Zero,
245}
246
247fn num(out: &mut String, v: i64, width: usize, default: Pad, pad: Pad) {
248 let pad = if pad == Pad::Default { default } else { pad };
249 let _ = match pad {
250 Pad::None => write!(out, "{v}"),
251 Pad::Space => write!(out, "{v:>width$}"),
252 Pad::Zero | Pad::Default => {
253 if v < 0 {
254 write!(
255 out,
256 "-{:0w$}",
257 v.unsigned_abs(),
258 w = width.saturating_sub(1)
259 )
260 } else {
261 write!(out, "{v:0width$}")
262 }
263 }
264 };
265}
266
267fn week_number(p: &Parts, first_is_sunday: bool) -> i64 {
270 let ordinal0 = i64::from(p.ordinal()) - 1;
271 let wd_from_first = if first_is_sunday {
272 (p.weekday0() as i64 + 1) % 7
273 } else {
274 p.weekday0() as i64
275 };
276 (ordinal0 - wd_from_first + 7) / 7
277}
278
279fn strftime(out: &mut String, p: &Parts, fmt: &str) {
280 let mut chars = fmt.chars().peekable();
281 while let Some(c) = chars.next() {
282 if c != '%' {
283 out.push(c);
284 continue;
285 }
286 let mut pad = Pad::Default;
287 match chars.peek() {
288 Some('-') => pad = Pad::None,
289 Some('_') => pad = Pad::Space,
290 Some('0') => pad = Pad::Zero,
291 _ => {}
292 }
293 if pad != Pad::Default {
294 chars.next();
295 }
296 let Some(spec) = chars.next() else {
297 out.push('%');
298 break;
299 };
300 match spec {
301 'Y' => {
302 if pad == Pad::Default {
303 write_year(out, p.year());
304 } else {
305 num(out, i64::from(p.year()), 4, Pad::Zero, pad);
306 }
307 }
308 'C' => num(out, i64::from(p.year().div_euclid(100)), 2, Pad::Zero, pad),
309 'y' => num(out, i64::from(p.year().rem_euclid(100)), 2, Pad::Zero, pad),
310 'm' => num(out, i64::from(p.month()), 2, Pad::Zero, pad),
311 'b' | 'h' => out.push_str(&MONTHS[(p.month() - 1) as usize][..3]),
312 'B' => out.push_str(MONTHS[(p.month() - 1) as usize]),
313 'd' => num(out, i64::from(p.day()), 2, Pad::Zero, pad),
314 'e' => num(out, i64::from(p.day()), 2, Pad::Space, pad),
315 'j' => num(out, i64::from(p.ordinal()), 3, Pad::Zero, pad),
316 'a' => out.push_str(&WEEKDAYS[p.weekday0()][..3]),
317 'A' => out.push_str(WEEKDAYS[p.weekday0()]),
318 'u' => num(out, p.weekday0() as i64 + 1, 1, Pad::Zero, pad),
319 'w' => num(out, (p.weekday0() as i64 + 1) % 7, 1, Pad::Zero, pad),
320 'U' => num(out, week_number(p, true), 2, Pad::Zero, pad),
321 'W' => num(out, week_number(p, false), 2, Pad::Zero, pad),
322 'G' | 'g' | 'V' => {
323 let iso = p.civil.date().iso_week_date();
324 match spec {
325 'G' => num(out, i64::from(iso.year()), 4, Pad::Zero, pad),
326 'g' => num(
327 out,
328 i64::from(i32::from(iso.year()).rem_euclid(100)),
329 2,
330 Pad::Zero,
331 pad,
332 ),
333 _ => num(out, i64::from(iso.week()), 2, Pad::Zero, pad),
334 }
335 }
336 'H' => num(out, i64::from(p.hour()), 2, Pad::Zero, pad),
337 'k' => num(out, i64::from(p.hour()), 2, Pad::Space, pad),
338 'I' => num(out, i64::from((p.hour() + 11) % 12 + 1), 2, Pad::Zero, pad),
339 'l' => num(out, i64::from((p.hour() + 11) % 12 + 1), 2, Pad::Space, pad),
340 'p' => out.push_str(if p.hour() < 12 { "AM" } else { "PM" }),
341 'P' => out.push_str(if p.hour() < 12 { "am" } else { "pm" }),
342 'M' => num(out, i64::from(p.minute()), 2, Pad::Zero, pad),
343 'S' => num(out, i64::from(p.second()), 2, Pad::Zero, pad),
344 's' => {
345 let _ = write!(out, "{}", p.unix_secs);
346 }
347 'f' => write_fixed_fraction(out, p.nanos, 9, false),
348 '3' | '6' | '9' if chars.peek() == Some(&'f') => {
349 chars.next();
350 write_fixed_fraction(out, p.nanos, spec.to_digit(10).unwrap_or(9), false);
351 }
352 '.' => match (chars.peek().copied(), chars.clone().nth(1)) {
353 (Some('f'), _) => {
354 chars.next();
355 write_auto_fraction(out, p.nanos);
356 }
357 (Some(d @ ('3' | '6' | '9')), Some('f')) => {
358 chars.next();
359 chars.next();
360 write_fixed_fraction(out, p.nanos, d.to_digit(10).unwrap_or(9), true);
361 }
362 _ => out.push_str("%."),
363 },
364 'z' => write_offset(out, p.offset_secs, OffsetStyle::Plain),
365 ':' => {
366 let mut colons = 1;
367 while chars.peek() == Some(&':') {
368 chars.next();
369 colons += 1;
370 }
371 if chars.peek() == Some(&'z') && colons <= 3 {
372 chars.next();
373 let style = match colons {
374 1 => OffsetStyle::Colon,
375 2 => OffsetStyle::ColonSeconds,
376 _ => OffsetStyle::HoursOnly,
377 };
378 write_offset(out, p.offset_secs, style);
379 } else {
380 out.push('%');
381 out.extend(std::iter::repeat_n(':', colons));
382 }
383 }
384 'Z' => match p.zone_name {
385 Some(name) => out.push_str(name),
386 None => write_offset(out, p.offset_secs, OffsetStyle::Colon),
387 },
388 'F' => strftime(out, p, "%Y-%m-%d"),
389 'T' | 'X' => strftime(out, p, "%H:%M:%S"),
390 'R' => strftime(out, p, "%H:%M"),
391 'D' | 'x' => strftime(out, p, "%m/%d/%y"),
392 'r' => strftime(out, p, "%I:%M:%S %p"),
393 'c' => strftime(out, p, "%a %b %e %H:%M:%S %Y"),
394 'v' => strftime(out, p, "%e-%b-%Y"),
395 '+' => strftime(out, p, "%Y-%m-%dT%H:%M:%S%.f%:z"),
396 '%' => out.push('%'),
397 'n' => out.push('\n'),
398 't' => out.push('\t'),
399 other => {
400 out.push('%');
401 match pad {
402 Pad::None => out.push('-'),
403 Pad::Space => out.push('_'),
404 Pad::Zero => out.push('0'),
405 Pad::Default => {}
406 }
407 out.push(other);
408 }
409 }
410 }
411}