1use std::fmt;
37use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset};
38
39const MIN_YEAR: i32 = -262_143;
41const MAX_YEAR: i32 = 262_142;
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum ParseError {
48 OutOfRange,
50 Impossible,
52 NotEnough,
54 Invalid,
56 TooShort,
58 TooLong,
60 LeapSecond,
62}
63
64impl fmt::Display for ParseError {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.write_str(match self {
67 Self::OutOfRange => "input is out of range",
68 Self::Impossible => "no possible date and time matching input",
69 Self::NotEnough => "input is not enough for unique date and time",
70 Self::Invalid => "input contains invalid characters",
71 Self::TooShort => "premature end of input",
72 Self::TooLong => "trailing input",
73 Self::LeapSecond => "leap seconds (:60) are not representable",
74 })
75 }
76}
77
78impl std::error::Error for ParseError {}
79
80type PResult<T> = Result<T, ParseError>;
81
82pub fn now() -> OffsetDateTime {
88 OffsetDateTime::now_utc()
89}
90
91pub fn now_rfc3339() -> String {
93 to_rfc3339(now())
94}
95
96pub fn now_micros_z() -> String {
98 to_rfc3339_micros_z(now())
99}
100
101pub fn from_unix_timestamp(secs: i64) -> Option<OffsetDateTime> {
103 let dt = OffsetDateTime::from_unix_timestamp(secs).ok()?;
104 year_in_range(dt.year()).then_some(dt)
105}
106
107fn year_in_range(year: i32) -> bool {
108 (MIN_YEAR..=MAX_YEAR).contains(&year)
109}
110
111#[derive(Clone, Copy)]
116enum Fraction {
117 Auto,
118 Millis,
119 Micros,
120 Secs,
121}
122
123pub fn to_rfc3339(dt: OffsetDateTime) -> String {
125 format_utc(dt, Fraction::Auto, false)
126}
127
128pub fn to_rfc3339_z(dt: OffsetDateTime) -> String {
130 format_utc(dt, Fraction::Auto, true)
131}
132
133pub fn to_rfc3339_micros_z(dt: OffsetDateTime) -> String {
135 format_utc(dt, Fraction::Micros, true)
136}
137
138pub fn to_rfc3339_millis_z(dt: OffsetDateTime) -> String {
140 format_utc(dt, Fraction::Millis, true)
141}
142
143pub fn to_rfc3339_secs_z(dt: OffsetDateTime) -> String {
145 format_utc(dt, Fraction::Secs, true)
146}
147
148fn format_utc(dt: OffsetDateTime, fraction: Fraction, zulu: bool) -> String {
149 let dt = dt.to_offset(UtcOffset::UTC);
150 let year = dt.year();
151 let nanos = dt.nanosecond();
152 let mut out = String::with_capacity(35);
153 if (0..=9999).contains(&year) {
154 out.push_str(&format!("{year:04}"));
155 } else {
156 out.push_str(&format!("{year:+05}"));
157 }
158 out.push_str(&format!(
159 "-{:02}-{:02}T{:02}:{:02}:{:02}",
160 u8::from(dt.month()),
161 dt.day(),
162 dt.hour(),
163 dt.minute(),
164 dt.second()
165 ));
166 match fraction {
167 Fraction::Auto => {
168 if nanos == 0 {
169 } else if nanos.is_multiple_of(1_000_000) {
170 out.push_str(&format!(".{:03}", nanos / 1_000_000));
171 } else if nanos.is_multiple_of(1_000) {
172 out.push_str(&format!(".{:06}", nanos / 1_000));
173 } else {
174 out.push_str(&format!(".{nanos:09}"));
175 }
176 }
177 Fraction::Millis => out.push_str(&format!(".{:03}", nanos / 1_000_000)),
178 Fraction::Micros => out.push_str(&format!(".{:06}", nanos / 1_000)),
179 Fraction::Secs => {}
180 }
181 out.push_str(if zulu { "Z" } else { "+00:00" });
182 out
183}
184
185fn number(s: &str, min: usize, max: usize) -> PResult<(&str, i64)> {
192 let bytes = s.as_bytes();
193 if bytes.len() < min {
194 return Err(ParseError::TooShort);
195 }
196 let mut n = 0i64;
197 for (i, &c) in bytes.iter().take(max).enumerate() {
198 if !c.is_ascii_digit() {
199 if i < min {
200 return Err(ParseError::Invalid);
201 }
202 return Ok((&s[i..], n));
203 }
204 n = n
205 .checked_mul(10)
206 .and_then(|n| n.checked_add(i64::from(c - b'0')))
207 .ok_or(ParseError::OutOfRange)?;
208 }
209 Ok((&s[max.min(bytes.len())..], n))
210}
211
212fn nanosecond(s: &str) -> PResult<(&str, u32)> {
215 let orig = s.len();
216 let (s, v) = number(s, 1, 9)?;
217 let consumed = orig - s.len();
218 let v = u32::try_from(v).map_err(|_| ParseError::OutOfRange)?;
219 let v = v * 10u32.pow(9 - consumed as u32);
220 Ok((s.trim_start_matches(|c: char| c.is_ascii_digit()), v))
221}
222
223fn char(s: &str, c1: u8) -> PResult<&str> {
224 match s.as_bytes().first() {
225 Some(&c) if c == c1 => Ok(&s[1..]),
226 Some(_) => Err(ParseError::Invalid),
227 None => Err(ParseError::TooShort),
228 }
229}
230
231fn colon(s: &str) -> PResult<&str> {
232 char(s, b':')
233}
234
235fn colon_or_space(s: &str) -> PResult<&str> {
236 Ok(s.trim_start_matches(|c: char| c == ':' || c.is_whitespace()))
237}
238
239fn timezone_offset(mut s: &str, consume_colon: fn(&str) -> PResult<&str>) -> PResult<(&str, i32)> {
241 if let Some(&b'Z' | &b'z') = s.as_bytes().first() {
242 return Ok((&s[1..], 0));
243 }
244 let digits = |s: &str| -> PResult<(u8, u8)> {
245 let b = s.as_bytes();
246 if b.len() < 2 {
247 Err(ParseError::TooShort)
248 } else {
249 Ok((b[0], b[1]))
250 }
251 };
252 let negative = match s.chars().next() {
253 Some('+') => {
254 s = &s[1..];
255 false
256 }
257 Some('-') => {
258 s = &s[1..];
259 true
260 }
261 Some('\u{2212}') => {
262 s = &s['\u{2212}'.len_utf8()..];
263 true
264 }
265 Some(_) => return Err(ParseError::Invalid),
266 None => return Err(ParseError::TooShort),
267 };
268 let hours = match digits(s)? {
269 (h1 @ b'0'..=b'9', h2 @ b'0'..=b'9') => i32::from((h1 - b'0') * 10 + (h2 - b'0')),
270 _ => return Err(ParseError::Invalid),
271 };
272 s = &s[2..];
273 s = consume_colon(s)?;
274 let minutes = if let Ok(ds) = digits(s) {
275 match ds {
276 (m1 @ b'0'..=b'5', m2 @ b'0'..=b'9') => i32::from((m1 - b'0') * 10 + (m2 - b'0')),
277 (b'6'..=b'9', b'0'..=b'9') => return Err(ParseError::OutOfRange),
278 _ => return Err(ParseError::Invalid),
279 }
280 } else {
281 return Err(ParseError::TooShort);
282 };
283 s = match s.len() {
284 len if len >= 2 => &s[2..],
285 0 => s,
286 _ => return Err(ParseError::TooShort),
287 };
288 let seconds = hours * 3600 + minutes * 60;
289 Ok((s, if negative { -seconds } else { seconds }))
290}
291
292struct Fields {
297 year: i32,
298 month: u32,
299 day: u32,
300 hour: u32,
301 minute: u32,
302 second: u32,
304 nano: u32,
305 offset_secs: i32,
306}
307
308fn build(f: &Fields) -> PResult<(OffsetDateTime, bool)> {
311 if !year_in_range(f.year) {
312 return Err(ParseError::OutOfRange);
313 }
314 let month = u8::try_from(f.month)
315 .ok()
316 .and_then(|m| Month::try_from(m).ok())
317 .ok_or(ParseError::OutOfRange)?;
318 let date =
319 Date::from_calendar_date(f.year, month, f.day as u8).map_err(|_| ParseError::OutOfRange)?;
320 let leap = f.second == 60;
321 let (second, nano) = if leap {
325 (59, 999_999_999)
326 } else {
327 (f.second, f.nano)
328 };
329 let time = Time::from_hms_nano(f.hour as u8, f.minute as u8, second as u8, nano)
330 .map_err(|_| ParseError::OutOfRange)?;
331 if f.offset_secs.abs() >= 86_400 {
333 return Err(ParseError::OutOfRange);
334 }
335 let offset =
336 UtcOffset::from_whole_seconds(f.offset_secs).map_err(|_| ParseError::OutOfRange)?;
337 let dt = PrimitiveDateTime::new(date, time).assume_offset(offset);
338 dt.checked_to_offset(UtcOffset::UTC)
340 .filter(|u| year_in_range(u.year()))
341 .ok_or(ParseError::Impossible)?;
342 Ok((dt, leap))
343}
344
345fn digit(bytes: &[u8], index: usize) -> PResult<u32> {
350 if bytes[index].is_ascii_digit() {
351 Ok(u32::from(bytes[index] - b'0'))
352 } else {
353 Err(ParseError::Invalid)
354 }
355}
356
357fn parse_strict_fields(mut s: &str) -> PResult<Fields> {
358 let bytes = s.as_bytes();
359 if bytes.len() < 19 {
360 return Err(ParseError::TooShort);
361 }
362 let year =
363 digit(bytes, 0)? * 1000 + digit(bytes, 1)? * 100 + digit(bytes, 2)? * 10 + digit(bytes, 3)?;
364 if bytes.get(4) != Some(&b'-') {
365 return Err(ParseError::Invalid);
366 }
367 let month = digit(bytes, 5)? * 10 + digit(bytes, 6)?;
368 if bytes.get(7) != Some(&b'-') {
369 return Err(ParseError::Invalid);
370 }
371 let day = digit(bytes, 8)? * 10 + digit(bytes, 9)?;
372 let month_enum = u8::try_from(month)
374 .ok()
375 .and_then(|m| Month::try_from(m).ok())
376 .ok_or(ParseError::OutOfRange)?;
377 Date::from_calendar_date(year as i32, month_enum, day as u8)
378 .map_err(|_| ParseError::OutOfRange)?;
379 if !matches!(bytes.get(10), Some(&b't' | &b'T' | &b' ')) {
380 return Err(ParseError::Invalid);
381 }
382 let hour = digit(bytes, 11)? * 10 + digit(bytes, 12)?;
383 if bytes.get(13) != Some(&b':') {
384 return Err(ParseError::Invalid);
385 }
386 let minute = digit(bytes, 14)? * 10 + digit(bytes, 15)?;
387 if bytes.get(16) != Some(&b':') {
388 return Err(ParseError::Invalid);
389 }
390 let second = digit(bytes, 17)? * 10 + digit(bytes, 18)?;
391 let nano = if bytes.get(19) == Some(&b'.') {
392 let (rest, nano) = nanosecond(&s[20..])?;
393 s = rest;
394 nano
395 } else {
396 s = &s[19..];
397 0
398 };
399 if hour >= 24 || minute >= 60 || second > 60 {
400 return Err(ParseError::OutOfRange);
401 }
402 let (rest, offset_secs) = timezone_offset(s, colon)?;
403 if !rest.is_empty() {
404 return Err(ParseError::TooLong);
405 }
406 Ok(Fields {
407 year: year as i32,
408 month,
409 day,
410 hour,
411 minute,
412 second,
413 nano,
414 offset_secs,
415 })
416}
417
418pub fn parse_rfc3339(s: &str) -> Result<OffsetDateTime, ParseError> {
425 build(&parse_strict_fields(s)?).map(|(dt, _)| dt)
426}
427
428pub fn parse_rfc3339_exact(s: &str) -> Result<OffsetDateTime, ParseError> {
430 match build(&parse_strict_fields(s)?)? {
431 (_, true) => Err(ParseError::LeapSecond),
432 (dt, false) => Ok(dt),
433 }
434}
435
436pub fn parse_relaxed(s: &str) -> Result<OffsetDateTime, ParseError> {
441 let fields = parse_relaxed_fields(s)?;
442 match build(&fields)? {
443 (_, true) => Err(ParseError::LeapSecond),
444 (dt, false) => Ok(dt.to_offset(UtcOffset::UTC)),
445 }
446}
447
448fn signed_or_width(s: &str, width: usize) -> PResult<(&str, i64)> {
449 if let Some(rest) = s.strip_prefix('-') {
450 let (rest, v) = number(rest, 1, usize::MAX)?;
451 Ok((rest, 0i64.checked_sub(v).ok_or(ParseError::OutOfRange)?))
452 } else if let Some(rest) = s.strip_prefix('+') {
453 number(rest, 1, usize::MAX)
454 } else {
455 number(s, 1, width)
456 }
457}
458
459fn parse_relaxed_fields(s: &str) -> PResult<Fields> {
460 let literal = |s: &str, lit: &str| -> PResult<()> {
461 if s.len() < lit.len() {
462 return Err(ParseError::TooShort);
463 }
464 if !s.starts_with(lit) {
465 return Err(ParseError::Invalid);
466 }
467 Ok(())
468 };
469 let s = s.trim_start();
471 let (s, year) = signed_or_width(s, 4)?;
472 let year = i32::try_from(year).map_err(|_| ParseError::OutOfRange)?;
473 let s = s.trim_start();
474 literal(s, "-")?;
475 let s = &s[1..];
476 let s = s.trim_start();
478 let (s, month) = number(s, 1, 2)?;
479 if !(1..=12).contains(&month) {
480 return Err(ParseError::OutOfRange);
481 }
482 let s = s.trim_start();
483 literal(s, "-")?;
484 let s = &s[1..];
485 let s = s.trim_start();
487 let (s, day) = number(s, 1, 2)?;
488 if !(1..=31).contains(&day) {
489 return Err(ParseError::OutOfRange);
490 }
491 let s = match s.as_bytes().first() {
493 Some(&b't' | &b'T' | &b' ') => &s[1..],
494 Some(_) => return Err(ParseError::Invalid),
495 None => return Err(ParseError::TooShort),
496 };
497 let s = s.trim_start();
499 let (s, hour) = number(s, 1, 2)?;
500 if !(0..=23).contains(&hour) {
501 return Err(ParseError::OutOfRange);
502 }
503 let s = s.trim_start();
504 literal(s, ":")?;
505 let s = &s[1..];
506 let s = s.trim_start();
508 let (s, minute) = number(s, 1, 2)?;
509 if !(0..=59).contains(&minute) {
510 return Err(ParseError::OutOfRange);
511 }
512 let s = s.trim_start();
513 literal(s, ":")?;
514 let s = &s[1..];
515 let s = s.trim_start();
517 let (s, second) = number(s, 1, 2)?;
518 if !(0..=60).contains(&second) {
519 return Err(ParseError::OutOfRange);
520 }
521 let (s, nano) = if let Some(rest) = s.strip_prefix('.') {
523 nanosecond(rest)?
524 } else {
525 (s, 0)
526 };
527 let s = s.trim_start();
529 let (s, offset_secs) = if s.len() >= 3 && s.as_bytes()[..3].eq_ignore_ascii_case(b"UTC") {
530 (&s[3..], 0)
531 } else {
532 timezone_offset(s, colon_or_space)?
533 };
534 if !s.trim_start().is_empty() {
535 return Err(ParseError::TooLong);
536 }
537 Ok(Fields {
538 year,
539 month: month as u32,
540 day: day as u32,
541 hour: hour as u32,
542 minute: minute as u32,
543 second: second as u32,
544 nano,
545 offset_secs,
546 })
547}
548
549pub mod serde_ts {
557 use super::*;
558 use serde::{de, Deserializer, Serializer};
559
560 pub fn serialize<S: Serializer>(dt: &OffsetDateTime, s: S) -> Result<S::Ok, S::Error> {
561 s.serialize_str(&to_rfc3339_z(*dt))
562 }
563
564 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<OffsetDateTime, D::Error> {
565 struct Visitor;
566 impl de::Visitor<'_> for Visitor {
567 type Value = OffsetDateTime;
568 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
569 f.write_str("a formatted date and time string")
570 }
571 fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
572 parse_relaxed(v).map_err(E::custom)
573 }
574 }
575 d.deserialize_str(Visitor)
576 }
577}
578
579pub mod serde_ts_option {
581 use super::*;
582 use serde::{Deserialize, Deserializer, Serialize, Serializer};
583
584 pub fn serialize<S: Serializer>(dt: &Option<OffsetDateTime>, s: S) -> Result<S::Ok, S::Error> {
585 dt.map(to_rfc3339_z).serialize(s)
586 }
587
588 pub fn deserialize<'de, D: Deserializer<'de>>(
589 d: D,
590 ) -> Result<Option<OffsetDateTime>, D::Error> {
591 use serde::de::Error;
592 Option::<String>::deserialize(d)?
593 .map(|v| parse_relaxed(&v).map_err(D::Error::custom))
594 .transpose()
595 }
596}
597
598pub mod serde_duration {
601 use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
602
603 const LIMIT_NANOS: i128 = (i64::MAX as i128) * 1_000_000;
605
606 pub(super) fn to_parts(d: time::Duration) -> (i64, i32) {
607 let mut secs = d.whole_seconds();
608 let mut nanos = d.subsec_nanoseconds();
609 if nanos < 0 {
610 secs -= 1;
611 nanos += 1_000_000_000;
612 }
613 (secs, nanos)
614 }
615
616 pub(super) fn from_parts(secs: i64, nanos: i32) -> Option<time::Duration> {
617 let nanos = u32::try_from(nanos).ok().filter(|n| *n < 1_000_000_000)?;
618 let total = i128::from(secs) * 1_000_000_000 + i128::from(nanos);
619 if !(-LIMIT_NANOS..=LIMIT_NANOS).contains(&total) {
620 return None;
621 }
622 Some(time::Duration::new(secs, nanos as i32))
623 }
624
625 pub fn serialize<S: Serializer>(d: &time::Duration, s: S) -> Result<S::Ok, S::Error> {
626 to_parts(*d).serialize(s)
627 }
628
629 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<time::Duration, D::Error> {
630 let (secs, nanos) = <(i64, i32)>::deserialize(d)?;
631 from_parts(secs, nanos).ok_or_else(|| D::Error::custom("TimeDelta out of bounds"))
632 }
633}
634
635pub mod serde_duration_option {
637 use super::*;
638 use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
639
640 pub fn serialize<S: Serializer>(d: &Option<time::Duration>, s: S) -> Result<S::Ok, S::Error> {
641 d.map(serde_duration::to_parts).serialize(s)
642 }
643
644 pub fn deserialize<'de, D: Deserializer<'de>>(
645 d: D,
646 ) -> Result<Option<time::Duration>, D::Error> {
647 Option::<(i64, i32)>::deserialize(d)?
648 .map(|(secs, nanos)| {
649 serde_duration::from_parts(secs, nanos)
650 .ok_or_else(|| D::Error::custom("TimeDelta out of bounds"))
651 })
652 .transpose()
653 }
654}