1pub const UNIX_EPOCH_JDN: i64 = 2_440_588;
16
17const LEAP_SECONDS: &[(i64, u32, u32, i64)] = &[
22 (1972, 1, 1, 10),
23 (1972, 7, 1, 11),
24 (1973, 1, 1, 12),
25 (1974, 1, 1, 13),
26 (1975, 1, 1, 14),
27 (1976, 1, 1, 15),
28 (1977, 1, 1, 16),
29 (1978, 1, 1, 17),
30 (1979, 1, 1, 18),
31 (1980, 1, 1, 19),
32 (1981, 7, 1, 20),
33 (1982, 7, 1, 21),
34 (1983, 7, 1, 22),
35 (1985, 7, 1, 23),
36 (1988, 1, 1, 24),
37 (1990, 1, 1, 25),
38 (1991, 1, 1, 26),
39 (1992, 7, 1, 27),
40 (1993, 7, 1, 28),
41 (1994, 7, 1, 29),
42 (1996, 1, 1, 30),
43 (1997, 7, 1, 31),
44 (1999, 1, 1, 32),
45 (2006, 1, 1, 33),
46 (2009, 1, 1, 34),
47 (2012, 7, 1, 35),
48 (2015, 7, 1, 36),
49 (2017, 1, 1, 37),
50];
51
52pub const TT_MINUS_TAI_NANOS: i64 = 32_184_000_000;
54
55pub fn tai_minus_utc(unix_seconds: i64) -> i64 {
58 let mut offset = LEAP_SECONDS[0].3; for &(y, m, d, value) in LEAP_SECONDS {
60 let effective = days_from_civil(y, m, d) * SECONDS_PER_DAY;
61 if effective <= unix_seconds {
62 offset = value;
63 } else {
64 break;
65 }
66 }
67 offset
68}
69
70pub fn tai_nanos_from_unix_nanos(unix_ns: i64) -> i64 {
72 let secs = unix_ns.div_euclid(NANOS_PER_SECOND);
73 unix_ns + tai_minus_utc(secs) * NANOS_PER_SECOND
74}
75
76pub fn tt_nanos_from_unix_nanos(unix_ns: i64) -> i64 {
79 tai_nanos_from_unix_nanos(unix_ns) + TT_MINUS_TAI_NANOS
80}
81
82pub fn unix_nanos_from_tt_nanos(tt_ns: i64) -> i64 {
84 let tai_ns = tt_ns - TT_MINUS_TAI_NANOS;
85 let unix_secs = tai_to_unix_seconds(tai_ns.div_euclid(NANOS_PER_SECOND));
87 tai_ns - tai_minus_utc(unix_secs) * NANOS_PER_SECOND
88}
89
90pub fn unix_to_tai_seconds(unix_seconds: i64) -> i64 {
92 unix_seconds + tai_minus_utc(unix_seconds)
93}
94
95pub fn tai_to_unix_seconds(tai_seconds: i64) -> i64 {
98 let mut unix = tai_seconds - tai_minus_utc(tai_seconds);
99 for _ in 0..2 {
100 unix = tai_seconds - tai_minus_utc(unix);
101 }
102 unix
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
112pub struct Hlc {
113 pub physical_nanos: i64,
114 pub logical: u32,
115}
116
117impl Hlc {
118 pub const ZERO: Hlc = Hlc {
120 physical_nanos: 0,
121 logical: 0,
122 };
123
124 pub fn tick(self, now_nanos: i64) -> Hlc {
128 let physical = self.physical_nanos.max(now_nanos);
129 let logical = if physical == self.physical_nanos {
130 self.logical + 1
131 } else {
132 0
133 };
134 Hlc {
135 physical_nanos: physical,
136 logical,
137 }
138 }
139
140 pub fn recv(self, remote: Hlc, now_nanos: i64) -> Hlc {
144 let physical = self
145 .physical_nanos
146 .max(remote.physical_nanos)
147 .max(now_nanos);
148 let logical = if physical == self.physical_nanos && physical == remote.physical_nanos {
149 self.logical.max(remote.logical) + 1
150 } else if physical == self.physical_nanos {
151 self.logical + 1
152 } else if physical == remote.physical_nanos {
153 remote.logical + 1
154 } else {
155 0
156 };
157 Hlc {
158 physical_nanos: physical,
159 logical,
160 }
161 }
162}
163
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
169pub struct EstimateInterval {
170 pub lower_nanos: i64,
171 pub upper_nanos: i64,
172}
173
174impl EstimateInterval {
175 pub fn new(lower_nanos: i64, upper_nanos: i64) -> Self {
176 EstimateInterval {
177 lower_nanos,
178 upper_nanos,
179 }
180 }
181 pub fn width(&self) -> i64 {
183 self.upper_nanos - self.lower_nanos
184 }
185 pub fn contains(&self, t: i64) -> bool {
186 self.lower_nanos <= t && t <= self.upper_nanos
187 }
188 pub fn intersect(&self, other: &EstimateInterval) -> EstimateInterval {
190 EstimateInterval {
191 lower_nanos: self.lower_nanos.max(other.lower_nanos),
192 upper_nanos: self.upper_nanos.min(other.upper_nanos),
193 }
194 }
195}
196
197pub fn knowable_horizon(now_nanos: i64, light_delay_nanos: i64) -> i64 {
201 now_nanos - light_delay_nanos
202}
203
204#[derive(Clone, Debug, PartialEq, Eq)]
211pub struct SyncClock {
212 pub hlc: Hlc,
213 pub knowledge: std::collections::BTreeMap<u64, EstimateInterval>,
214}
215
216impl SyncClock {
217 pub fn new() -> Self {
218 SyncClock {
219 hlc: Hlc::ZERO,
220 knowledge: std::collections::BTreeMap::new(),
221 }
222 }
223
224 pub fn tick(&self, now_nanos: i64) -> SyncClock {
226 SyncClock {
227 hlc: self.hlc.tick(now_nanos),
228 knowledge: self.knowledge.clone(),
229 }
230 }
231
232 pub fn observe(&self, node: u64, interval: EstimateInterval) -> SyncClock {
235 let mut knowledge = self.knowledge.clone();
236 knowledge
237 .entry(node)
238 .and_modify(|iv| *iv = iv.intersect(&interval))
239 .or_insert(interval);
240 SyncClock {
241 hlc: self.hlc,
242 knowledge,
243 }
244 }
245
246 pub fn merge(&self, other: &SyncClock) -> SyncClock {
250 let mut knowledge = self.knowledge.clone();
251 for (&node, &interval) in &other.knowledge {
252 knowledge
253 .entry(node)
254 .and_modify(|iv| *iv = iv.intersect(&interval))
255 .or_insert(interval);
256 }
257 SyncClock {
258 hlc: self.hlc.max(other.hlc),
259 knowledge,
260 }
261 }
262}
263
264impl Default for SyncClock {
265 fn default() -> Self {
266 SyncClock::new()
267 }
268}
269
270pub const NANOS_PER_SECOND: i64 = 1_000_000_000;
272pub const SECONDS_PER_DAY: i64 = 86_400;
274pub const NANOS_PER_DAY: i64 = SECONDS_PER_DAY * NANOS_PER_SECOND;
276
277#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
280pub struct CivilDateTime {
281 pub year: i64,
282 pub month: u32,
283 pub day: u32,
284 pub hour: u32,
285 pub minute: u32,
286 pub second: u32,
287 pub nanosecond: u32,
288}
289
290pub fn civil_from_unix_nanos(ns: i64) -> CivilDateTime {
293 let day = ns.div_euclid(NANOS_PER_DAY);
294 let rem = ns.rem_euclid(NANOS_PER_DAY); let (year, month, d) = civil_from_days(day);
296 let secs = rem / NANOS_PER_SECOND;
297 CivilDateTime {
298 year,
299 month,
300 day: d,
301 hour: (secs / 3600) as u32,
302 minute: ((secs % 3600) / 60) as u32,
303 second: (secs % 60) as u32,
304 nanosecond: (rem % NANOS_PER_SECOND) as u32,
305 }
306}
307
308pub fn unix_nanos_from_civil(dt: CivilDateTime) -> i64 {
310 let days = days_from_civil(dt.year, dt.month, dt.day);
311 let secs = dt.hour as i64 * 3600 + dt.minute as i64 * 60 + dt.second as i64;
312 days * NANOS_PER_DAY + secs * NANOS_PER_SECOND + dt.nanosecond as i64
313}
314
315#[derive(Clone, Copy, Debug, PartialEq, Eq)]
319pub struct ZoneTransition {
320 pub at_unix_seconds: i64,
321 pub offset_seconds: i32,
322}
323
324#[derive(Clone, Copy, Debug, PartialEq, Eq)]
329pub enum Fold {
330 Earlier,
331 Later,
332}
333
334pub fn offset_at(transitions: &[ZoneTransition], base_offset: i32, instant_ns: i64) -> i32 {
337 let secs = instant_ns.div_euclid(NANOS_PER_SECOND);
338 let mut off = base_offset;
339 for t in transitions {
340 if t.at_unix_seconds <= secs {
341 off = t.offset_seconds;
342 } else {
343 break;
344 }
345 }
346 off
347}
348
349pub fn to_local(
351 transitions: &[ZoneTransition],
352 base_offset: i32,
353 instant_ns: i64,
354) -> CivilDateTime {
355 let off = offset_at(transitions, base_offset, instant_ns);
356 civil_from_unix_nanos(instant_ns + off as i64 * NANOS_PER_SECOND)
357}
358
359pub fn from_local(
364 transitions: &[ZoneTransition],
365 base_offset: i32,
366 civil: CivilDateTime,
367 fold: Fold,
368) -> i64 {
369 let local_ns = unix_nanos_from_civil(civil);
370 let mut offsets: Vec<i32> = vec![base_offset];
372 for t in transitions {
373 if !offsets.contains(&t.offset_seconds) {
374 offsets.push(t.offset_seconds);
375 }
376 }
377 let mut valid: Vec<i64> = Vec::new();
380 for o in &offsets {
381 let utc = local_ns - *o as i64 * NANOS_PER_SECOND;
382 if offset_at(transitions, base_offset, utc) == *o {
383 valid.push(utc);
384 }
385 }
386 valid.sort_unstable();
387 valid.dedup();
388 if valid.len() >= 2 {
389 return match fold {
391 Fold::Earlier => valid[0],
392 Fold::Later => *valid.last().unwrap(),
393 };
394 }
395 if valid.len() == 1 {
396 return valid[0];
397 }
398 let mut cands: Vec<i64> = offsets
400 .iter()
401 .map(|o| local_ns - *o as i64 * NANOS_PER_SECOND)
402 .collect();
403 cands.sort_unstable();
404 match fold {
405 Fold::Earlier => cands[0],
406 Fold::Later => *cands.last().unwrap(),
407 }
408}
409
410#[derive(Clone, Copy, Debug, PartialEq, Eq)]
415pub struct DstRule {
416 pub month: u32,
417 pub week: u32,
418 pub weekday: u32,
419 pub time_seconds: i64,
420}
421
422pub fn nth_weekday_of_month(year: i64, month: u32, week: u32, weekday: u32) -> u32 {
425 let first = days_from_civil(year, month, 1);
426 let first_weekday = weekday_from_days(first);
427 let to_first = (weekday + 7 - first_weekday) % 7; let mut day = 1 + to_first + (week - 1) * 7;
429 let last = last_day_of_month(year, month);
430 while day > last {
431 day -= 7; }
433 day
434}
435
436pub fn dst_transitions_for_year(
440 std_offset: i32,
441 dst_offset: i32,
442 start: DstRule,
443 end: DstRule,
444 year: i64,
445) -> [ZoneTransition; 2] {
446 let transition = |rule: DstRule, pre_offset: i32, new_offset: i32| {
449 let day = nth_weekday_of_month(year, rule.month, rule.week, rule.weekday);
450 let local = days_from_civil(year, rule.month, day) * SECONDS_PER_DAY + rule.time_seconds;
451 ZoneTransition {
452 at_unix_seconds: local - pre_offset as i64,
453 offset_seconds: new_offset,
454 }
455 };
456 [
457 transition(start, std_offset, dst_offset), transition(end, dst_offset, std_offset), ]
460}
461
462#[derive(Clone, Copy, Debug, PartialEq, Eq)]
466pub struct ZoneSpec {
467 pub name: &'static str,
468 pub std_offset: i32,
469 pub dst: Option<(i32, DstRule, DstRule)>,
470}
471
472impl ZoneSpec {
473 pub fn transitions(&self, start_year: i64, end_year: i64) -> Vec<ZoneTransition> {
476 let mut v = Vec::new();
477 if let Some((dst_offset, start, end)) = self.dst {
478 for y in start_year..=end_year {
479 let pair = dst_transitions_for_year(self.std_offset, dst_offset, start, end, y);
480 v.extend_from_slice(&pair);
481 }
482 v.sort_by_key(|t| t.at_unix_seconds);
483 }
484 v
485 }
486
487 pub fn to_local(&self, instant_ns: i64) -> CivilDateTime {
489 if self.dst.is_none() {
490 return civil_from_unix_nanos(instant_ns + self.std_offset as i64 * NANOS_PER_SECOND);
491 }
492 let (year, _, _) = civil_from_days(instant_ns.div_euclid(NANOS_PER_DAY));
495 let tz = self.transitions(year - 1, year + 1);
496 to_local(&tz, self.std_offset, instant_ns)
497 }
498}
499
500pub fn local_instant_nanos(instant_ns: i64, zone_name: &str) -> Option<i64> {
506 let zone = zone_by_name(zone_name)?;
507 Some(unix_nanos_from_civil(zone.to_local(instant_ns)))
508}
509
510pub fn format_zoned(instant_ns: i64, zone_name: &str) -> Option<String> {
514 let zone = zone_by_name(zone_name)?;
515 let local = zone.to_local(instant_ns);
516 let offset_secs = (unix_nanos_from_civil(local) - instant_ns) / NANOS_PER_SECOND;
518 let sign = if offset_secs < 0 { '-' } else { '+' };
519 let abs = offset_secs.abs();
520 Some(format!(
521 "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}{}{:02}:{:02}",
522 local.year,
523 local.month,
524 local.day,
525 local.hour,
526 local.minute,
527 local.second,
528 sign,
529 abs / 3600,
530 (abs % 3600) / 60,
531 ))
532}
533
534pub fn zone_by_name(name: &str) -> Option<ZoneSpec> {
538 let us = (
540 DstRule {
541 month: 3,
542 week: 2,
543 weekday: 0,
544 time_seconds: 2 * 3600,
545 },
546 DstRule {
547 month: 11,
548 week: 1,
549 weekday: 0,
550 time_seconds: 2 * 3600,
551 },
552 );
553 let eu = |std_h: i64| {
555 (
556 DstRule {
557 month: 3,
558 week: 5,
559 weekday: 0,
560 time_seconds: (std_h + 1) * 3600,
561 },
562 DstRule {
563 month: 10,
564 week: 5,
565 weekday: 0,
566 time_seconds: (std_h + 2) * 3600,
567 },
568 )
569 };
570 let spec = match name {
571 "UTC" | "Etc/UTC" | "Zulu" => ZoneSpec {
572 name: "UTC",
573 std_offset: 0,
574 dst: None,
575 },
576 "America/New_York" => ZoneSpec {
577 name: "America/New_York",
578 std_offset: -5 * 3600,
579 dst: Some((-4 * 3600, us.0, us.1)),
580 },
581 "America/Chicago" => ZoneSpec {
582 name: "America/Chicago",
583 std_offset: -6 * 3600,
584 dst: Some((-5 * 3600, us.0, us.1)),
585 },
586 "America/Denver" => ZoneSpec {
587 name: "America/Denver",
588 std_offset: -7 * 3600,
589 dst: Some((-6 * 3600, us.0, us.1)),
590 },
591 "America/Los_Angeles" => ZoneSpec {
592 name: "America/Los_Angeles",
593 std_offset: -8 * 3600,
594 dst: Some((-7 * 3600, us.0, us.1)),
595 },
596 "America/Phoenix" => ZoneSpec {
597 name: "America/Phoenix",
598 std_offset: -7 * 3600,
599 dst: None,
600 },
601 "Europe/London" | "Europe/Dublin" | "Europe/Lisbon" => {
602 let (s, e) = eu(0);
603 ZoneSpec {
604 name: "Europe/London",
605 std_offset: 0,
606 dst: Some((3600, s, e)),
607 }
608 }
609 "Europe/Paris" | "Europe/Berlin" | "Europe/Madrid" | "Europe/Rome" | "Europe/Amsterdam" => {
610 let (s, e) = eu(1);
611 ZoneSpec {
612 name: "Europe/Paris",
613 std_offset: 3600,
614 dst: Some((2 * 3600, s, e)),
615 }
616 }
617 "Asia/Kolkata" | "Asia/Calcutta" => ZoneSpec {
618 name: "Asia/Kolkata",
619 std_offset: 5 * 3600 + 1800,
620 dst: None,
621 },
622 "Asia/Tokyo" => ZoneSpec {
623 name: "Asia/Tokyo",
624 std_offset: 9 * 3600,
625 dst: None,
626 },
627 "Asia/Shanghai" => ZoneSpec {
628 name: "Asia/Shanghai",
629 std_offset: 8 * 3600,
630 dst: None,
631 },
632 "Australia/Sydney" => ZoneSpec {
633 name: "Australia/Sydney",
634 std_offset: 10 * 3600,
635 dst: Some((
637 11 * 3600,
638 DstRule {
639 month: 10,
640 week: 1,
641 weekday: 0,
642 time_seconds: 2 * 3600,
643 },
644 DstRule {
645 month: 4,
646 week: 1,
647 weekday: 0,
648 time_seconds: 3 * 3600,
649 },
650 )),
651 },
652 _ => return None,
653 };
654 Some(spec)
655}
656
657pub fn add_span(dt: CivilDateTime, months: i64, days: i64) -> CivilDateTime {
663 let total = (dt.year * 12 + (dt.month as i64 - 1)) + months;
664 let new_year = total.div_euclid(12);
665 let new_month = (total.rem_euclid(12) + 1) as u32;
666 let clamped_day = dt.day.min(last_day_of_month(new_year, new_month));
667 let z = days_from_civil(new_year, new_month, clamped_day) + days;
668 let (year, month, day) = civil_from_days(z);
669 CivilDateTime {
670 year,
671 month,
672 day,
673 ..dt
674 }
675}
676
677pub fn date_add_span(days_since_epoch: i32, months: i32, days: i32) -> i32 {
682 let z = days_since_epoch + 719468;
683 let era = if z >= 0 {
684 z / 146097
685 } else {
686 (z - 146096) / 146097
687 };
688 let doe = (z - era * 146097) as u32;
689 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
690 let y = yoe as i32 + era * 400;
691 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
692 let mp = (5 * doy + 2) / 153;
693 let d = doy - (153 * mp + 2) / 5 + 1;
694 let m = if mp < 10 { mp + 3 } else { mp - 9 };
695 let mut year = y + if m <= 2 { 1 } else { 0 };
696 let mut month = m as i32;
697 let mut day = d as i32;
698
699 let total_months = year
700 .wrapping_mul(12)
701 .wrapping_add(month - 1)
702 .wrapping_add(months);
703 year = total_months / 12;
704 month = total_months % 12 + 1;
705 if month <= 0 {
706 month += 12;
707 year -= 1;
708 }
709
710 let last = last_day_of_month(year as i64, month as u32) as i32;
711 if day > last {
712 day = last;
713 }
714
715 let yp = year - if month <= 2 { 1 } else { 0 };
716 let era2 = if yp >= 0 { yp / 400 } else { (yp - 399) / 400 };
717 let yoe2 = (yp - era2 * 400) as u32;
718 let mp2 = if month > 2 {
719 month as u32 - 3
720 } else {
721 month as u32 + 9
722 };
723 let doy2 = (153 * mp2 + 2) / 5 + day as u32 - 1;
724 let doe2 = yoe2 * 365 + yoe2 / 4 - yoe2 / 100 + doy2;
725 let result = era2 * 146097 + doe2 as i32 - 719468;
726
727 result.wrapping_add(days)
728}
729
730pub fn months_between(a_nanos: i64, b_nanos: i64) -> i64 {
735 if b_nanos < a_nanos {
736 return -months_between(b_nanos, a_nanos);
737 }
738 let a = civil_from_unix_nanos(a_nanos);
739 let b = civil_from_unix_nanos(b_nanos);
740 let mut months = (b.year - a.year) * 12 + (b.month as i64 - a.month as i64);
741 if unix_nanos_from_civil(add_span(a, months, 0)) > b_nanos {
744 months -= 1;
745 }
746 months
747}
748
749pub fn years_between(a_nanos: i64, b_nanos: i64) -> i64 {
752 months_between(a_nanos, b_nanos) / 12
753}
754
755pub fn is_weekend(z: i64) -> bool {
757 matches!(iso_weekday_from_days(z), 6 | 7) }
759
760pub fn business_days_between(a: i64, b: i64) -> i64 {
763 if a == b {
764 return 0;
765 }
766 let (lo, hi, sign) = if a < b { (a, b, 1) } else { (b, a, -1) };
767 let span = hi - lo;
768 let full_weeks = span / 7;
769 let mut count = full_weeks * 5;
770 let mut d = lo + full_weeks * 7;
771 while d < hi {
772 if !is_weekend(d) {
773 count += 1;
774 }
775 d += 1;
776 }
777 sign * count
778}
779
780pub fn add_business_days(z: i64, n: i64) -> i64 {
785 let step = if n >= 0 { 1 } else { -1 };
786 let mut remaining = n.abs();
787 let mut d = z;
788 while remaining > 0 {
789 d += step;
790 if !is_weekend(d) {
791 remaining -= 1;
792 }
793 }
794 d
795}
796
797pub fn format_duration(nanos: i64) -> String {
802 if nanos == 0 {
803 return "0s".to_string();
804 }
805 const D: u128 = 86_400_000_000_000;
806 const H: u128 = 3_600_000_000_000;
807 const M: u128 = 60_000_000_000;
808 const S: u128 = 1_000_000_000;
809 const MS: u128 = 1_000_000;
810 const US: u128 = 1_000;
811 let mut out = String::new();
812 if nanos < 0 {
813 out.push('-');
814 }
815 let mut abs = (nanos as i128).unsigned_abs();
816 let frac_str = |frac: u128, width: usize| -> String {
818 let mut f = format!("{:0width$}", frac, width = width);
819 while f.ends_with('0') {
820 f.pop();
821 }
822 f
823 };
824 if abs >= S {
825 let d = abs / D;
826 abs %= D;
827 let h = abs / H;
828 abs %= H;
829 let m = abs / M;
830 abs %= M;
831 if d > 0 {
832 out += &format!("{d}d");
833 }
834 if h > 0 {
835 out += &format!("{h}h");
836 }
837 if m > 0 {
838 out += &format!("{m}m");
839 }
840 let (secs, frac) = (abs / S, abs % S);
841 if frac == 0 {
842 if secs > 0 {
843 out += &format!("{secs}s");
844 }
845 } else {
846 out += &format!("{secs}.{}s", frac_str(frac, 9));
847 }
848 } else if abs >= MS {
849 let (w, frac) = (abs / MS, abs % MS);
850 out += &(if frac == 0 {
851 format!("{w}ms")
852 } else {
853 format!("{w}.{}ms", frac_str(frac, 6))
854 });
855 } else if abs >= US {
856 let (w, frac) = (abs / US, abs % US);
857 out += &(if frac == 0 {
858 format!("{w}us")
859 } else {
860 format!("{w}.{}us", frac_str(frac, 3))
861 });
862 } else {
863 out += &format!("{abs}ns");
864 }
865 out
866}
867
868pub fn parse_duration(s: &str) -> Option<i64> {
871 let b = s.as_bytes();
872 let mut i = 0;
873 let neg = match b.first() {
874 Some(&b'-') => {
875 i += 1;
876 true
877 }
878 Some(&b'+') => {
879 i += 1;
880 false
881 }
882 _ => false,
883 };
884 if i >= b.len() {
885 return None;
886 }
887 let mut total: i128 = 0;
888 let mut saw_any = false;
889 while i < b.len() {
890 let int_start = i;
891 while i < b.len() && b[i].is_ascii_digit() {
892 i += 1;
893 }
894 let int_str = &s[int_start..i];
895 let mut frac_str = "";
896 if i < b.len() && b[i] == b'.' {
897 i += 1;
898 let frac_start = i;
899 while i < b.len() && b[i].is_ascii_digit() {
900 i += 1;
901 }
902 frac_str = &s[frac_start..i];
903 }
904 if int_str.is_empty() && frac_str.is_empty() {
905 return None; }
907 let rest = &s[i..];
908 let (unit_nanos, ulen): (i128, usize) = if rest.starts_with("ms") {
909 (1_000_000, 2)
910 } else if rest.starts_with("ns") {
911 (1, 2)
912 } else if rest.starts_with("us") {
913 (1_000, 2)
914 } else if rest.starts_with("µs") {
915 (1_000, "µs".len())
916 } else if rest.starts_with('s') {
917 (1_000_000_000, 1)
918 } else if rest.starts_with('m') {
919 (60_000_000_000, 1)
920 } else if rest.starts_with('h') {
921 (3_600_000_000_000, 1)
922 } else if rest.starts_with('d') {
923 (86_400_000_000_000, 1)
924 } else {
925 return None; };
927 i += ulen;
928 let int_val: i128 = if int_str.is_empty() {
929 0
930 } else {
931 int_str.parse().ok()?
932 };
933 total = total.checked_add(int_val.checked_mul(unit_nanos)?)?;
934 if !frac_str.is_empty() {
935 let frac_val: i128 = frac_str.parse().ok()?;
936 let mut denom: i128 = 1;
937 for _ in 0..frac_str.len() {
938 denom *= 10;
939 }
940 total = total.checked_add(frac_val * unit_nanos / denom)?;
941 }
942 saw_any = true;
943 }
944 if !saw_any {
945 return None;
946 }
947 i64::try_from(if neg { -total } else { total }).ok()
948}
949
950pub fn format_rfc3339(instant_ns: i64) -> String {
954 let c = civil_from_unix_nanos(instant_ns);
955 let mut s = format!(
956 "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
957 c.year, c.month, c.day, c.hour, c.minute, c.second
958 );
959 if c.nanosecond != 0 {
960 let mut frac = format!("{:09}", c.nanosecond);
961 while frac.ends_with('0') {
962 frac.pop();
963 }
964 s.push('.');
965 s.push_str(&frac);
966 }
967 s.push('Z');
968 s
969}
970
971pub fn format_time_of_day(nanos_from_midnight: i64) -> String {
976 let rem = nanos_from_midnight.rem_euclid(NANOS_PER_DAY);
977 let secs = rem / NANOS_PER_SECOND;
978 let mut s = format!(
979 "{:02}:{:02}:{:02}",
980 secs / 3600,
981 (secs % 3600) / 60,
982 secs % 60
983 );
984 let nanos = (rem % NANOS_PER_SECOND) as u32;
985 if nanos != 0 {
986 let mut frac = format!("{:09}", nanos);
987 while frac.ends_with('0') {
988 frac.pop();
989 }
990 s.push('.');
991 s.push_str(&frac);
992 }
993 s
994}
995
996pub fn parse_rfc3339(s: &str) -> Option<i64> {
999 let b = s.as_bytes();
1000 if b.len() < 20 {
1002 return None;
1003 }
1004 let digits = |start: usize, len: usize| -> Option<i64> {
1005 let mut v: i64 = 0;
1006 for i in start..start + len {
1007 let c = *b.get(i)?;
1008 if !c.is_ascii_digit() {
1009 return None;
1010 }
1011 v = v * 10 + (c - b'0') as i64;
1012 }
1013 Some(v)
1014 };
1015 if b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' {
1016 return None;
1017 }
1018 let year = digits(0, 4)?;
1019 let month = digits(5, 2)? as u32;
1020 let day = digits(8, 2)? as u32;
1021 let hour = digits(11, 2)? as u32;
1022 let minute = digits(14, 2)? as u32;
1023 let second = digits(17, 2)? as u32;
1024 if !(1..=12).contains(&month) || !(1..=last_day_of_month(year, month)).contains(&day) {
1025 return None;
1026 }
1027 if hour > 23 || minute > 59 || second > 59 {
1028 return None;
1029 }
1030 let mut pos = 19;
1031 let mut nanosecond: u32 = 0;
1033 if b.get(pos) == Some(&b'.') {
1034 pos += 1;
1035 let (mut frac, mut count) = (0u64, 0u32);
1036 while let Some(&c) = b.get(pos) {
1037 if !c.is_ascii_digit() {
1038 break;
1039 }
1040 if count < 9 {
1041 frac = frac * 10 + (c - b'0') as u64;
1042 count += 1;
1043 }
1044 pos += 1;
1045 }
1046 if count == 0 {
1047 return None; }
1049 for _ in count..9 {
1050 frac *= 10;
1051 }
1052 nanosecond = frac as u32;
1053 }
1054 let offset_seconds: i64 = match b.get(pos) {
1056 Some(&b'Z') => {
1057 pos += 1;
1058 0
1059 }
1060 Some(&c) if c == b'+' || c == b'-' => {
1061 let sign = if c == b'+' { 1 } else { -1 };
1062 let oh = digits(pos + 1, 2)?;
1063 if b.get(pos + 3) != Some(&b':') {
1064 return None;
1065 }
1066 let om = digits(pos + 4, 2)?;
1067 if oh > 23 || om > 59 {
1068 return None;
1069 }
1070 pos += 6;
1071 sign * (oh * 3600 + om * 60)
1072 }
1073 _ => return None,
1074 };
1075 if pos != b.len() {
1076 return None; }
1078 let civil = CivilDateTime {
1079 year,
1080 month,
1081 day,
1082 hour,
1083 minute,
1084 second,
1085 nanosecond,
1086 };
1087 Some(unix_nanos_from_civil(civil) - offset_seconds * NANOS_PER_SECOND)
1088}
1089
1090pub fn is_gregorian_leap(year: i64) -> bool {
1093 (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
1094}
1095
1096pub fn is_julian_leap(year: i64) -> bool {
1099 year.rem_euclid(4) == 0
1100}
1101
1102pub fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
1105 let y = if month <= 2 { year - 1 } else { year };
1106 let era = (if y >= 0 { y } else { y - 399 }) / 400;
1107 let yoe = (y - era * 400) as i64; let m = month as i64;
1109 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day as i64 - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; era * 146097 + doe - 719468
1112}
1113
1114pub fn civil_from_days(z: i64) -> (i64, u32, u32) {
1116 let z = z + 719468;
1117 let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
1118 let doe = z - era * 146097; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; let y = yoe + era * 400;
1121 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let day = (doy - (153 * mp + 2) / 5 + 1) as u32; let month = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32; let year = if month <= 2 { y + 1 } else { y };
1126 (year, month, day)
1127}
1128
1129pub fn last_day_of_month(year: i64, month: u32) -> u32 {
1131 match month {
1132 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1133 4 | 6 | 9 | 11 => 30,
1134 2 => {
1135 if is_gregorian_leap(year) {
1136 29
1137 } else {
1138 28
1139 }
1140 }
1141 _ => 0,
1142 }
1143}
1144
1145pub fn weekday_from_days(z: i64) -> u32 {
1147 (z + 4).rem_euclid(7) as u32
1148}
1149
1150pub fn iso_weekday_from_days(z: i64) -> u32 {
1152 (z + 3).rem_euclid(7) as u32 + 1
1153}
1154
1155pub fn day_of_year(year: i64, month: u32, day: u32) -> u32 {
1157 (days_from_civil(year, month, day) - days_from_civil(year, 1, 1) + 1) as u32
1158}
1159
1160pub fn iso_week_from_days(z: i64) -> (i64, u32, u32) {
1164 let iso_dow = iso_weekday_from_days(z);
1165 let thursday = z + (4 - iso_dow as i64);
1167 let (iso_year, _, _) = civil_from_days(thursday);
1168 let jan4 = days_from_civil(iso_year, 1, 4);
1172 let week1_monday = jan4 - (iso_weekday_from_days(jan4) as i64 - 1);
1173 let week = ((z - week1_monday) / 7 + 1) as u32;
1174 (iso_year, week, iso_dow)
1175}
1176
1177pub fn days_from_iso_week(iso_year: i64, week: u32, iso_weekday: u32) -> i64 {
1180 let jan4 = days_from_civil(iso_year, 1, 4);
1181 let week1_monday = jan4 - (iso_weekday_from_days(jan4) as i64 - 1);
1182 week1_monday + (week as i64 - 1) * 7 + (iso_weekday as i64 - 1)
1183}
1184
1185pub fn jdn_from_julian(year: i64, month: u32, day: u32) -> i64 {
1187 let a = (14 - month as i64) / 12;
1188 let y = year + 4800 - a;
1189 let m = month as i64 + 12 * a - 3;
1190 day as i64 + (153 * m + 2) / 5 + 365 * y + y / 4 - 32083
1191}
1192
1193pub fn julian_from_jdn(jdn: i64) -> (i64, u32, u32) {
1195 let c = jdn + 32082;
1196 let d = (4 * c + 3) / 1461;
1197 let e = c - (1461 * d) / 4;
1198 let m = (5 * e + 2) / 153;
1199 let day = (e - (153 * m + 2) / 5 + 1) as u32;
1200 let month = (m + 3 - 12 * (m / 10)) as u32;
1201 let year = d - 4800 + m / 10;
1202 (year, month, day)
1203}
1204
1205pub fn days_from_julian(year: i64, month: u32, day: u32) -> i64 {
1207 jdn_from_julian(year, month, day) - UNIX_EPOCH_JDN
1208}
1209
1210pub fn julian_from_days(z: i64) -> (i64, u32, u32) {
1212 julian_from_jdn(z + UNIX_EPOCH_JDN)
1213}
1214
1215#[cfg(test)]
1216#[path = "../../logicaffeine_tests/unit/logicaffeine_base/temporal/tests.rs"]
1217mod tests;