1use super::data::{
12 self, DATE_B, DATE_NAMES, DATE_OVER, DATE_OVER_KEYS, DATE_PATS, DATE_TIMES, Loc,
13};
14use std::fmt;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub struct Timestamp(Option<i64>);
35
36const MAX_MS: i64 = 8_640_000_000_000_000;
38
39impl Timestamp {
40 #[must_use]
42 pub fn millis(self) -> Option<i64> {
43 self.0
44 }
45
46 #[must_use]
48 pub fn is_valid(self) -> bool {
49 self.0.is_some()
50 }
51}
52
53impl From<i64> for Timestamp {
54 fn from(ms: i64) -> Self {
55 Timestamp((-MAX_MS..=MAX_MS).contains(&ms).then_some(ms))
56 }
57}
58
59impl From<f64> for Timestamp {
60 #[allow(
61 clippy::cast_possible_truncation,
62 reason = "the range is checked first"
63 )]
64 fn from(ms: f64) -> Self {
65 if ms.abs() <= MAX_MS as f64 {
67 Timestamp(Some(ms.trunc() as i64))
68 } else {
69 Timestamp(None)
70 }
71 }
72}
73
74#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
75impl From<std::time::SystemTime> for Timestamp {
76 fn from(t: std::time::SystemTime) -> Self {
77 let ms = match t.duration_since(std::time::UNIX_EPOCH) {
78 Ok(d) => i64::try_from(d.as_millis()).ok(),
79 Err(e) => i64::try_from(e.duration().as_millis()).ok().map(|m| -m),
81 };
82 ms.map_or(Timestamp(None), Timestamp::from)
83 }
84}
85
86#[cfg(feature = "time")]
88fn from_nanos(ns: i128) -> Timestamp {
89 i64::try_from(ns / 1_000_000).map_or(Timestamp(None), Timestamp::from)
90}
91
92#[cfg(feature = "time")]
94impl From<time::OffsetDateTime> for Timestamp {
95 fn from(t: time::OffsetDateTime) -> Self {
96 from_nanos(t.unix_timestamp_nanos())
97 }
98}
99
100#[cfg(feature = "time")]
102impl From<time::UtcDateTime> for Timestamp {
103 fn from(t: time::UtcDateTime) -> Self {
104 from_nanos(t.unix_timestamp_nanos())
105 }
106}
107
108#[cfg(feature = "time")]
110impl From<time::PrimitiveDateTime> for Timestamp {
111 fn from(t: time::PrimitiveDateTime) -> Self {
112 Timestamp::from(t.assume_utc())
113 }
114}
115
116#[cfg(feature = "tz")]
119pub(crate) use crate::tz::Zone;
120
121#[cfg(feature = "tz")]
122use crate::tz::{Civil, civil_from_days, civil_from_unix, days_from_civil};
123
124#[cfg(not(feature = "tz"))]
126#[derive(Debug, Clone)]
127pub(crate) struct Zone;
128
129#[cfg(not(feature = "tz"))]
130impl Zone {
131 pub(crate) fn utc() -> Zone {
132 Zone
133 }
134
135 pub(crate) fn system() -> Zone {
136 Zone
137 }
138
139 #[allow(clippy::unused_self, reason = "the `tz` zone's signature")]
140 pub(crate) fn offset_at(&self, _: i64) -> i32 {
141 0
142 }
143
144 pub(crate) fn named(_: &str) -> Option<Zone> {
145 None
146 }
147}
148
149#[cfg(not(feature = "tz"))]
151#[path = "../tz/civil.rs"]
152mod civil;
153#[cfg(not(feature = "tz"))]
154use civil::{Civil, civil_from_days, civil_from_unix, days_from_civil};
155
156pub(crate) fn zone_named(name: &str) -> Option<Zone> {
159 const UTC: [&str; 6] = ["UTC", "Etc/UTC", "GMT", "Etc/GMT", "Etc/UCT", "UCT"];
160 if UTC.iter().any(|u| u.eq_ignore_ascii_case(name)) {
161 return Some(Zone::utc());
162 }
163 Zone::named(name)
164}
165
166#[inline(never)]
169fn week_year(c: &Civil) -> i64 {
170 let days = days_from_civil(c.year, c.month, c.day);
171 let monday_based = (i64::from(c.weekday) + 6) % 7;
172 civil_from_days(days - monday_based + 3).0
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178pub(crate) enum Cycle {
179 Locale,
180 H11,
181 H12,
182 H23,
183 H24,
184 Hour12(bool),
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub(crate) enum Shape {
192 Components { date: u8, time: u8 },
193 Styles { date: u8, time: u8 },
194}
195
196pub(crate) const NO_STYLE: u8 = u8::MAX;
197
198#[derive(Debug, Clone)]
200pub(crate) struct DateOptions {
201 pub(crate) shape: Shape,
202 pub(crate) cycle: Cycle,
203 pub(crate) zone: Option<Zone>,
205}
206
207impl DateOptions {
208 pub(crate) const DEFAULT: DateOptions = DateOptions {
210 shape: Shape::Components {
211 date: DATE_NUMERIC,
212 time: 0,
213 },
214 cycle: Cycle::Locale,
215 zone: None,
216 };
217}
218
219const DATE_NUMERIC: u8 = 88;
221
222const DATE_STYLES: usize = 216;
224const GLUE: usize = 220;
225const STYLE_GLUE: usize = 224;
226const HOUR_TABLES: usize = 9;
227const TIME_STYLES: usize = 99;
228
229fn glue_width(date: u8) -> usize {
232 match date / 12 % 6 {
233 3 if !date.is_multiple_of(4) => 0,
234 3 => 1,
235 4 => 2,
236 _ => 3,
237 }
238}
239
240fn table(cycle: Cycle, loc: &Loc) -> usize {
242 let letter = match cycle {
243 Cycle::Locale => return 0,
244 Cycle::H11 => b'K',
245 Cycle::H12 => b'h',
246 Cycle::H23 => b'H',
247 Cycle::H24 => b'k',
248 Cycle::Hour12(true) => loc.hc12,
249 Cycle::Hour12(false) => loc.hc24,
250 };
251 match letter {
252 b'K' => 1,
253 b'h' => 2,
254 b'H' => 3,
255 _ => 4,
256 }
257}
258
259fn override_of(loc: &Loc, kind: u32, a: u8, b: u8, mode: usize) -> Option<&'static str> {
261 let key = (kind << 20) | (u32::from(a) << 12) | (u32::from(b) << 4) | mode as u32;
262 let start = loc.dover as usize;
263 let keys = DATE_OVER_KEYS.get(start..start + usize::from(loc.dover_len))?;
264 let i = keys.binary_search(&key).ok()?;
265 DATE_OVER.get(start + i).map(|&p| data::dpat(p))
266}
267
268struct Picked {
270 pattern: &'static str,
271 date: &'static str,
272 time: &'static str,
273}
274
275fn pick(o: &DateOptions, loc: &Loc) -> Picked {
276 let row = DATE_PATS.get(usize::from(loc.dpats));
277 let times = DATE_TIMES.get(usize::from(loc.dtimes));
278 let p = |slot: usize| data::dpat(row.and_then(|r| r.get(slot)).copied().unwrap_or(0));
279 let t = |slot: usize| data::dpat(times.and_then(|r| r.get(slot)).copied().unwrap_or(0));
280 let mode = table(o.cycle, loc);
281 let one = |pattern| Picked {
282 pattern,
283 date: "",
284 time: "",
285 };
286 match o.shape {
287 Shape::Components { date, time } => {
288 let time_pattern = || match time {
289 1..9 => t(usize::from(time)),
290 _ => t(HOUR_TABLES + mode * 18 + usize::from(time) - 9),
291 };
292 match (date, time) {
293 (_, 0) => one(p(usize::from(date))),
294 (0, _) => one(time_pattern()),
295 _ => {
296 let m = if time < 9 { 0 } else { mode };
297 match override_of(loc, 0, date, time, m) {
298 Some(full) => one(full),
299 None => Picked {
300 pattern: p(GLUE + glue_width(date)),
301 date: p(usize::from(date)),
302 time: time_pattern(),
303 },
304 }
305 }
306 }
307 }
308 Shape::Styles { date, time } => {
309 let time_pattern = || t(TIME_STYLES + mode * 2 + usize::from(time.saturating_sub(2)));
310 match (date, time) {
311 (_, NO_STYLE) => one(p(DATE_STYLES + usize::from(date))),
312 (NO_STYLE, _) => one(time_pattern()),
313 _ => match override_of(loc, 1, date, time, mode) {
314 Some(full) => one(full),
315 None => Picked {
316 pattern: p(STYLE_GLUE + usize::from(date)),
317 date: p(DATE_STYLES + usize::from(date)),
318 time: time_pattern(),
319 },
320 },
321 }
322 }
323 }
324}
325
326struct Cx {
328 names: &'static [u16],
329 digits: [&'static str; 10],
330 latin: bool,
332 loc: &'static Loc,
333}
334
335pub(crate) fn write(
338 t: Timestamp,
339 o: &DateOptions,
340 loc: &'static Loc,
341 zone: &Zone,
342 out: &mut dyn fmt::Write,
343) -> fmt::Result {
344 let Some(ms) = t.0 else {
345 return out.write_str("Invalid Date");
346 };
347 let zone = o.zone.as_ref().unwrap_or(zone);
348 let secs = ms.div_euclid(1000);
349 let c = civil_from_unix(secs + i64::from(zone.offset_at(secs)));
350 let cx = Cx {
351 names: DATE_NAMES
352 .get(usize::from(loc.dnames))
353 .map_or(&[][..], |r| &r[..]),
354 digits: super::number::digit_table(loc),
355 latin: data::s(loc.digits).is_empty(),
356 loc,
357 };
358 let picked = pick(o, loc);
359 render(picked.pattern, &c, &cx, (picked.date, picked.time), out)
360}
361
362fn render(
364 p: &str,
365 c: &Civil,
366 cx: &Cx,
367 parts: (&str, &str),
368 out: &mut dyn fmt::Write,
369) -> fmt::Result {
370 let b = p.as_bytes();
371 let mut from = 0;
372 let mut i = 0;
373 while i < b.len() {
374 if b.get(i) != Some(&1) {
375 i += 1;
376 continue;
377 }
378 if from < i {
379 out.write_str(p.get(from..i).unwrap_or(""))?;
380 }
381 let letter = b.get(i + 1).copied().unwrap_or(0);
382 let width = b.get(i + 2).map_or(1, |w| w.wrapping_sub(b'0'));
383 i += 3;
384 from = i;
385 match (letter, width) {
386 (b'{', 1) => render(parts.0, c, cx, ("", ""), out)?,
387 (b'{', _) => render(parts.1, c, cx, ("", ""), out)?,
388 _ => field(letter, width, p, c, cx, out)?,
389 }
390 }
391 match p.get(from..) {
392 Some(rest) if !rest.is_empty() => out.write_str(rest),
393 _ => Ok(()),
394 }
395}
396
397static PAIRS: &str = match std::str::from_utf8(&PAIR_BYTES) {
399 Ok(s) => s,
400 Err(_) => "",
401};
402const PAIR_BYTES: [u8; 200] = {
403 let mut a = [0u8; 200];
404 let mut i = 0;
405 while i < 100 {
406 a[2 * i] = b'0' + (i / 10) as u8;
407 a[2 * i + 1] = b'0' + (i % 10) as u8;
408 i += 1;
409 }
410 a
411};
412
413fn number(v: u64, width: u8, cx: &Cx, out: &mut dyn fmt::Write) -> fmt::Result {
415 if cx.latin && v < 10_000 && width <= 4 {
416 let v = v as usize;
418 let len = match v {
419 0..10 => 1,
420 10..100 => 2,
421 100..1000 => 3,
422 _ => 4,
423 }
424 .max(usize::from(width));
425 let pair = |n: usize| PAIRS.get(2 * n..2 * n + 2).unwrap_or("00");
426 let (hi, lo) = (pair(v / 100), pair(v % 100));
427 if len > 2 {
428 out.write_str(if len == 3 {
429 hi.get(1..).unwrap_or("")
430 } else {
431 hi
432 })?;
433 }
434 return out.write_str(if len == 1 {
435 lo.get(1..).unwrap_or("")
436 } else {
437 lo
438 });
439 }
440 let mut buf = [0u8; 20];
441 let mut n = v;
442 let mut len = 0;
443 while (n > 0 || len < usize::from(width.max(1))) && len < buf.len() {
444 if let Some(slot) = buf.get_mut(len) {
445 *slot = (n % 10) as u8;
446 }
447 n /= 10;
448 len += 1;
449 }
450 for d in buf.get(..len).unwrap_or(&[]).iter().rev() {
451 out.write_str(cx.digits.get(usize::from(*d)).copied().unwrap_or("0"))?;
452 }
453 Ok(())
454}
455
456fn name(cx: &Cx, set: usize, i: usize) -> &'static str {
458 let at = match set {
460 0..6 => set * 12 + i,
461 6..14 => 72 + (set - 6) * 7 + i,
462 _ => 128 + (set - 14) * 2 + i,
463 };
464 data::dname(cx.names.get(at).copied().unwrap_or(0))
465}
466
467fn width_index(width: u8) -> usize {
469 match width {
470 4 => 1,
471 5 => 2,
472 6 => 3,
473 _ => 0,
474 }
475}
476
477fn field(
478 letter: u8,
479 width: u8,
480 p: &str,
481 c: &Civil,
482 cx: &Cx,
483 out: &mut dyn fmt::Write,
484) -> fmt::Result {
485 match letter {
486 b'y' => {
487 let y = if c.year > 0 { c.year } else { 1 - c.year }.unsigned_abs();
489 if width == 2 {
490 number(y % 100, 2, cx, out)
491 } else {
492 number(y, width, cx, out)
493 }
494 }
495 b'Y' => {
496 let y = week_year(c);
497 if y < 0 {
498 out.write_str(data::s(
499 data::PATTERNS
500 .get(usize::from(cx.loc.decimal_pat))
501 .map_or(0, |pat| pat.np),
502 ))?;
503 }
504 let a = y.unsigned_abs();
505 number(if width == 2 { a % 100 } else { a }, width, cx, out)
506 }
507 b'M' | b'L' if width <= 2 => number(u64::from(c.month), width, cx, out),
508 b'M' | b'L' => {
509 let set = usize::from(letter == b'L') * 3 + width_index(width).min(2);
510 out.write_str(name(cx, set, usize::from(c.month).saturating_sub(1)))
511 }
512 b'r' => {
513 const ROMAN: [&str; 12] = [
515 "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix", "x", "xi", "xii",
516 ];
517 out.write_str(
518 ROMAN
519 .get(usize::from(c.month).saturating_sub(1))
520 .copied()
521 .unwrap_or(""),
522 )
523 }
524 b'd' => number(u64::from(c.day), width, cx, out),
525 b'E' | b'c' => {
526 let set = 6 + usize::from(letter == b'c') * 4 + width_index(width);
527 out.write_str(name(cx, set, usize::from(c.weekday)))
528 }
529 b'h' => number(
530 u64::from(match c.hour % 12 {
531 0 => 12,
532 h => h,
533 }),
534 width,
535 cx,
536 out,
537 ),
538 b'H' => number(u64::from(c.hour), width, cx, out),
539 b'K' => number(u64::from(c.hour % 12), width, cx, out),
540 b'k' => number(
541 u64::from(if c.hour == 0 { 24 } else { c.hour }),
542 width,
543 cx,
544 out,
545 ),
546 b'm' => number(u64::from(c.minute), width, cx, out),
547 b's' => number(u64::from(c.second), width, cx, out),
548 b'a' => out.write_str(name(
549 cx,
550 14 + width_index(width).min(2),
551 usize::from(c.hour >= 12),
552 )),
553 b'B' => out.write_str(flexible(p, c, cx, width)),
554 b'G' => out.write_str(name(
555 cx,
556 17 + width_index(width).min(2),
557 usize::from(c.year > 0),
558 )),
559 _ => Ok(()),
560 }
561}
562
563fn flexible(p: &str, c: &Civil, cx: &Cx, width: u8) -> &'static str {
566 let Some(row) = DATE_B.get(usize::from(cx.loc.db)) else {
567 return name(cx, 14, usize::from(c.hour >= 12));
568 };
569 let base = width_index(width).min(2) * 25;
570 let shows = |l: u8| p.as_bytes().windows(2).any(|w| w == [1, l]);
571 let noon = row.get(base + 24).copied().unwrap_or(0);
572 let exact = (!shows(b'm') || c.minute == 0) && (!shows(b's') || c.second == 0);
573 let i = if c.hour == 12 && noon != 0 && exact {
574 noon
575 } else {
576 row.get(base + usize::from(c.hour)).copied().unwrap_or(0)
577 };
578 data::dname(i)
579}