1use alloc::{string::String, vec::Vec};
5
6use super::{
7 DateTimeError, POSTGRES_EPOCH_JDATE, PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz,
8 USECS_PER_DAY, USECS_PER_HOUR, USECS_PER_MINUTE, USECS_PER_SEC, abbreviation_offset, date2j,
9 days_in_month, is_valid_julian, local_offset, tm2timestamp,
10};
11use crate::{
12 PgTimeZone, TimeZoneAbbreviations,
13 cast::{is_pg_space, trim_pg_space},
14 float::{round_ties_even, truncate_to_i64},
15 interval::date_word_era,
16 zone::{DEFAULT_ABBREVIATIONS, Meaning},
17};
18
19const MAX_TZDISP_HOUR: i32 = 15;
21const MAX_LITERAL_LEN: usize = 64;
24const EPOCH_MICROS: i64 = -946_684_800_000_000;
26const EPOCH_DAYS: i32 = -10_957;
28
29#[derive(Debug, Clone, Copy)]
50pub struct InputContext<'a> {
51 time_zone: Option<&'a PgTimeZone>,
52 abbreviations: &'a TimeZoneAbbreviations,
53}
54
55impl<'a> InputContext<'a> {
56 #[must_use]
59 pub const fn new() -> Self {
60 Self {
61 time_zone: None,
62 abbreviations: &DEFAULT_ABBREVIATIONS,
63 }
64 }
65
66 #[must_use]
70 pub const fn with_time_zone(self, zone: &'a PgTimeZone) -> Self {
71 Self {
72 time_zone: Some(zone),
73 ..self
74 }
75 }
76
77 #[must_use]
79 pub const fn with_time_zone_abbreviations(
80 self,
81 abbreviations: &'a TimeZoneAbbreviations,
82 ) -> Self {
83 Self {
84 abbreviations,
85 ..self
86 }
87 }
88}
89
90impl Default for InputContext<'_> {
91 fn default() -> Self {
92 Self::new()
93 }
94}
95
96enum Special {
98 Late,
100 Early,
102 Epoch,
104}
105
106struct Fields {
108 year: i32,
110 month: i32,
111 day: i32,
112 clock: i64,
114 offset: Option<i32>,
116 zone: Option<LiteralZone>,
118}
119
120enum Literal {
122 Special(Special),
123 Fields(Fields),
124}
125
126struct RawOffset<'a> {
129 negative: bool,
130 digits: &'a [u8],
131}
132
133enum Word {
136 Era(bool),
138 Zone(LiteralZone),
140}
141
142#[derive(Clone)]
144enum LiteralZone {
145 Fixed(i32),
147 Dynamic {
149 zone: PgTimeZone,
150 abbreviation: String,
151 },
152 Named(PgTimeZone),
154}
155
156struct RawClock<'a> {
158 hour: [u8; 2],
159 minute: [u8; 2],
160 second: Option<[u8; 2]>,
161 fraction: Option<&'a [u8]>,
163 offset: Option<RawOffset<'a>>,
164}
165
166struct Scanner<'a> {
168 bytes: &'a [u8],
169 at: usize,
170}
171
172impl<'a> Scanner<'a> {
173 const fn new(bytes: &'a [u8]) -> Self {
174 Self { bytes, at: 0 }
175 }
176
177 fn peek(&self) -> Option<u8> {
178 self.bytes.get(self.at).copied()
179 }
180
181 fn peek_at(&self, ahead: usize) -> Option<u8> {
182 self.bytes.get(self.at + ahead).copied()
183 }
184
185 fn eat(&mut self, byte: u8) -> bool {
186 let found = self.peek() == Some(byte);
187 self.at += usize::from(found);
188 found
189 }
190
191 fn digits(&mut self) -> &'a [u8] {
192 let start = self.at;
193 while self.peek().is_some_and(|b| b.is_ascii_digit()) {
194 self.at += 1;
195 }
196 &self.bytes[start..self.at]
197 }
198
199 fn two_digits(&mut self) -> Option<[u8; 2]> {
200 match (self.peek(), self.peek_at(1)) {
201 (Some(a), Some(b)) if a.is_ascii_digit() && b.is_ascii_digit() => {
202 self.at += 2;
203 Some([a, b])
204 }
205 _ => None,
206 }
207 }
208
209 fn spaces(&mut self) -> usize {
210 let start = self.at;
211 while self.peek().is_some_and(is_pg_space) {
212 self.at += 1;
213 }
214 self.at - start
215 }
216
217 fn is_done(&self) -> bool {
218 self.at == self.bytes.len()
219 }
220
221 fn clock(&mut self) -> Option<RawClock<'a>> {
223 let hour = self.two_digits()?;
224 if !self.eat(b':') {
225 return None;
226 }
227 let minute = self.two_digits()?;
228 let mut second = None;
229 let mut fraction = None;
230 if self.eat(b':') {
231 second = Some(self.two_digits()?);
232 if self.peek() == Some(b'.') {
233 let start = self.at;
234 self.at += 1;
235 self.digits();
236 fraction = Some(&self.bytes[start..self.at]);
237 }
238 }
239 if self.peek().is_some_and(|b| b.is_ascii_digit() || b == b'.') {
240 return None;
241 }
242 let before_offset = self.at;
243 self.spaces();
244 let offset = match self.peek() {
245 Some(sign @ (b'+' | b'-')) if self.peek_at(1).is_some_and(|b| b.is_ascii_digit()) => {
246 self.at += 1;
247 let start = self.at;
248 while self.peek().is_some_and(|b| b.is_ascii_digit() || b == b':') {
249 self.at += 1;
250 }
251 if matches!(self.peek(), Some(b'.' | b'-')) {
252 return None;
253 }
254 Some(RawOffset {
255 negative: sign == b'-',
256 digits: &self.bytes[start..self.at],
257 })
258 }
259 _ => {
260 self.at = before_offset;
261 None
262 }
263 };
264 Some(RawClock {
265 hour,
266 minute,
267 second,
268 fraction,
269 offset,
270 })
271 }
272
273 fn words(&mut self) -> Option<Vec<Vec<u8>>> {
276 let mut words = Vec::new();
277 loop {
278 self.spaces();
279 if self.is_done() {
280 return Some(words);
281 }
282 let start = self.at;
283 while self.peek().is_some_and(|b| b.is_ascii_alphabetic()) {
284 self.at += 1;
285 }
286 if self.at == start || !(self.is_done() || self.peek().is_some_and(is_pg_space)) {
287 return None;
288 }
289 words.push(self.bytes[start..self.at].to_ascii_lowercase());
290 }
291 }
292}
293
294fn strtoint(digits: &[u8]) -> Option<i32> {
296 digits.iter().try_fold(0i32, |value, &digit| {
297 value.checked_mul(10)?.checked_add(i32::from(digit - b'0'))
298 })
299}
300
301fn two(digits: [u8; 2]) -> i32 {
303 i32::from(digits[0] - b'0') * 10 + i32::from(digits[1] - b'0')
304}
305
306fn fractional_second(fraction: &[u8]) -> i64 {
309 if fraction.len() == 1 {
310 return 0;
311 }
312 let value: f64 = core::str::from_utf8(fraction)
313 .ok()
314 .and_then(|text| text.parse().ok())
315 .expect("a point and digits read as a double");
316 truncate_to_i64(round_ties_even(value * 1_000_000.0))
317}
318
319impl RawClock<'_> {
320 fn decode(&self) -> Result<i64, DateTimeError> {
322 let (hour, minute) = (two(self.hour), two(self.minute));
323 let second = self.second.map_or(0, two);
324 let fsec = self.fraction.map_or(0, fractional_second);
325 if minute > 59 || second > 60 {
327 return Err(DateTimeError::FieldValueOutOfRange);
328 }
329 Ok(i64::from(hour) * USECS_PER_HOUR
330 + i64::from(minute) * USECS_PER_MINUTE
331 + i64::from(second) * USECS_PER_SEC
332 + fsec)
333 }
334}
335
336fn check_time_overflow(clock: i64) -> Result<i64, DateTimeError> {
339 if clock > USECS_PER_DAY {
340 Err(DateTimeError::FieldValueOutOfRange)
341 } else {
342 Ok(clock)
343 }
344}
345
346fn decode_timezone(offset: &RawOffset<'_>) -> Result<i32, DateTimeError> {
348 let RawOffset { negative, digits } = *offset;
349 let mut parts = digits.split(|&b| b == b':');
351 let mut field = || match parts.next() {
352 None => Ok(0),
353 Some([]) => Err(DateTimeError::Unsupported),
354 Some(part) => strtoint(part).ok_or(DateTimeError::TimeZoneDisplacementOutOfRange),
355 };
356 let mut hour = field()?;
357 let mut minute = field()?;
358 let second = field()?;
359 if parts.next().is_some() {
360 return Err(DateTimeError::Unsupported);
361 }
362 let colon = digits.contains(&b':');
363 if !colon && digits.len() > 2 {
365 minute = hour % 100;
366 hour /= 100;
367 }
368 if hour > MAX_TZDISP_HOUR || minute >= 60 || second >= 60 {
369 return Err(DateTimeError::TimeZoneDisplacementOutOfRange);
370 }
371 let seconds = (hour * 60 + minute) * 60 + second;
372 Ok(if negative { -seconds } else { seconds })
373}
374
375fn classify(word: &[u8], context: InputContext<'_>) -> Result<Word, DateTimeError> {
379 let upper = String::from_utf8_lossy(word).to_ascii_uppercase();
380 if let Some(zone) = context.time_zone
381 && let Some((meaning, fixed)) = zone.abbreviation_is_known(&upper)
382 {
383 return Ok(Word::Zone(if fixed {
384 LiteralZone::Fixed(meaning.offset)
385 } else {
386 LiteralZone::Dynamic {
387 zone: zone.clone(),
388 abbreviation: upper,
389 }
390 }));
391 }
392 match context.abbreviations.lookup(word) {
393 Some(Meaning::Fixed { offset, .. }) => return Ok(Word::Zone(LiteralZone::Fixed(*offset))),
394 Some(Meaning::Zone(name)) => {
395 let zone = PgTimeZone::load(name).ok_or(DateTimeError::TimeZoneNotRecognized)?;
396 return Ok(Word::Zone(LiteralZone::Dynamic {
397 zone,
398 abbreviation: upper,
399 }));
400 }
401 None => {}
402 }
403 match date_word_era(word) {
404 Some(Some(bc)) => Ok(Word::Era(bc)),
405 Some(None) => Err(DateTimeError::Unsupported),
406 None => PgTimeZone::load(&upper)
407 .map(|zone| Word::Zone(LiteralZone::Named(zone)))
408 .ok_or(DateTimeError::Unsupported),
409 }
410}
411
412fn classify_words(
415 words: &[Vec<u8>],
416 numeric_offset: bool,
417 context: InputContext<'_>,
418) -> Result<(Option<bool>, Option<LiteralZone>), DateTimeError> {
419 let (mut era, mut zone) = (None, None);
420 for word in words {
421 match classify(word, context)? {
422 Word::Era(_) if era.is_some() => return Err(DateTimeError::Unsupported),
423 Word::Era(bc) => era = Some(bc),
424 Word::Zone(_) if zone.is_some() || numeric_offset => {
425 return Err(DateTimeError::Unsupported);
426 }
427 Word::Zone(written) => zone = Some(written),
428 }
429 }
430 Ok((era, zone))
431}
432
433fn read_date_time(text: &str, context: InputContext<'_>) -> Result<Literal, DateTimeError> {
437 let bytes = trim_pg_space(text.as_bytes());
438 if bytes.len() > MAX_LITERAL_LEN {
439 return Err(DateTimeError::Unsupported);
440 }
441 let special =
442 if bytes.eq_ignore_ascii_case(b"infinity") || bytes.eq_ignore_ascii_case(b"+infinity") {
443 Some(Special::Late)
444 } else if bytes.eq_ignore_ascii_case(b"-infinity") {
445 Some(Special::Early)
446 } else if bytes.eq_ignore_ascii_case(b"epoch") {
447 Some(Special::Epoch)
448 } else {
449 None
450 };
451 if let Some(special) = special {
452 return Ok(Literal::Special(special));
453 }
454
455 let unsupported = DateTimeError::Unsupported;
456 let mut scanner = Scanner::new(bytes);
457 let year = scanner.digits();
458 if year.len() < 4 || (year.len() > 4 && year[0] == b'0') || !scanner.eat(b'-') {
459 return Err(unsupported);
460 }
461 let month = scanner.two_digits().ok_or(unsupported)?;
462 if !scanner.eat(b'-') {
463 return Err(unsupported);
464 }
465 let day = scanner.two_digits().ok_or(unsupported)?;
466 if scanner.peek().is_some_and(|b| b.is_ascii_digit()) {
467 return Err(unsupported);
468 }
469 let after_date = scanner.at;
470 let separated = match scanner.peek() {
471 Some(b'T' | b't') => {
472 scanner.at += 1;
473 true
474 }
475 _ => scanner.spaces() > 0,
476 };
477 let clock = if separated && scanner.peek().is_some_and(|b| b.is_ascii_digit()) {
478 Some(scanner.clock().ok_or(unsupported)?)
479 } else {
480 scanner.at = after_date;
481 None
482 };
483 let words = scanner.words().ok_or(unsupported)?;
484
485 let year = strtoint(year).ok_or(DateTimeError::FieldValueOutOfRange)?;
488 let (clock, offset) = match clock {
489 None => (0, None),
490 Some(raw) => {
491 let clock = check_time_overflow(raw.decode()?)?;
492 let offset = raw.offset.as_ref().map(decode_timezone).transpose()?;
493 (clock, offset)
494 }
495 };
496 let (era, zone) = classify_words(&words, offset.is_some(), context)?;
497 let bc = era.unwrap_or(false);
498 if year <= 0 {
499 return Err(DateTimeError::FieldValueOutOfRange);
500 }
501 let year = if bc { 1 - year } else { year };
502 let (month, day) = (two(month), two(day));
503 if !(1..=12).contains(&month) || !(1..=days_in_month(year, month)).contains(&day) {
504 return Err(DateTimeError::FieldValueOutOfRange);
505 }
506 Ok(Literal::Fields(Fields {
507 year,
508 month,
509 day,
510 clock,
511 offset,
512 zone,
513 }))
514}
515
516enum TimeOffset {
518 Unwritten,
520 Known(i32),
522 NeedsDate,
524}
525
526fn read_time(
530 text: &str,
531 context: InputContext<'_>,
532) -> Result<Option<(i64, TimeOffset)>, DateTimeError> {
533 let bytes = trim_pg_space(text.as_bytes());
534 if bytes.len() > MAX_LITERAL_LEN {
535 return Err(DateTimeError::Unsupported);
536 }
537 if bytes.eq_ignore_ascii_case(b"allballs") {
538 return Ok(None);
539 }
540 let mut scanner = Scanner::new(bytes);
541 let raw = scanner.clock().ok_or(DateTimeError::Unsupported)?;
542 let words = scanner.words().ok_or(DateTimeError::Unsupported)?;
543 let clock = raw.decode()?;
544 let offset = raw.offset.as_ref().map(decode_timezone).transpose()?;
545 let (era, zone) = classify_words(&words, offset.is_some(), context)?;
546 if era.is_some() {
547 return Err(DateTimeError::Unsupported);
548 }
549 let offset = match (offset, zone) {
550 (Some(offset), _) | (None, Some(LiteralZone::Fixed(offset))) => TimeOffset::Known(offset),
551 (None, Some(LiteralZone::Named(zone))) => zone
552 .fixed_offset()
553 .map_or(TimeOffset::NeedsDate, TimeOffset::Known),
554 (None, Some(LiteralZone::Dynamic { .. })) => TimeOffset::NeedsDate,
555 (None, None) => TimeOffset::Unwritten,
556 };
557 Ok(Some((check_time_overflow(clock)?, offset)))
558}
559
560impl PgDate {
561 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
579 let fields = match read_date_time(text, context)? {
580 Literal::Special(Special::Late) => return Ok(Self::INFINITY),
581 Literal::Special(Special::Early) => return Ok(Self::NEG_INFINITY),
582 Literal::Special(Special::Epoch) => return Ok(Self(EPOCH_DAYS)),
583 Literal::Fields(fields) => fields,
584 };
585 if !is_valid_julian(fields.year, fields.month) {
586 return Err(DateTimeError::DateOutOfRange);
587 }
588 Self::from_pg_days(date2j(fields.year, fields.month, fields.day) - POSTGRES_EPOCH_JDATE)
589 .filter(|date| date.is_finite())
590 .ok_or(DateTimeError::DateOutOfRange)
591 }
592}
593
594impl PgTimestamp {
595 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
612 match read_date_time(text, context)? {
613 Literal::Special(Special::Late) => Ok(Self::INFINITY),
614 Literal::Special(Special::Early) => Ok(Self::NEG_INFINITY),
615 Literal::Special(Special::Epoch) => Ok(Self(EPOCH_MICROS)),
616 Literal::Fields(fields) => {
617 tm2timestamp(fields.year, fields.month, fields.day, fields.clock, 0)
618 .map(Self)
619 .ok_or(DateTimeError::TimestampOutOfRange)
620 }
621 }
622 }
623}
624
625impl PgTimestampTz {
626 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
650 let fields = match read_date_time(text, context)? {
651 Literal::Special(Special::Late) => return Ok(Self::INFINITY),
652 Literal::Special(Special::Early) => return Ok(Self::NEG_INFINITY),
653 Literal::Special(Special::Epoch) => return Ok(Self(EPOCH_MICROS)),
654 Literal::Fields(fields) => fields,
655 };
656 let out_of_range = DateTimeError::TimestampOutOfRange;
657 let local = || {
659 if !is_valid_julian(fields.year, fields.month) {
660 return Err(out_of_range);
661 }
662 let days = i64::from(date2j(fields.year, fields.month, fields.day))
663 - i64::from(POSTGRES_EPOCH_JDATE);
664 days.checked_mul(USECS_PER_DAY)
665 .and_then(|micros| micros.checked_add(fields.clock))
666 .ok_or(out_of_range)
667 };
668 let offset = match (fields.offset, &fields.zone, context.time_zone) {
669 (Some(offset), _, _) => offset,
670 (None, Some(LiteralZone::Fixed(offset)), _) => *offset,
671 (None, Some(LiteralZone::Dynamic { zone, abbreviation }), _) => {
672 abbreviation_offset(zone, abbreviation, local()?)?
673 }
674 (None, Some(LiteralZone::Named(zone)), _) | (None, None, Some(zone)) => {
675 local_offset(zone, local()?)?
676 }
677 (None, None, None) => return Err(DateTimeError::NeedsTimeZone),
678 };
679 tm2timestamp(fields.year, fields.month, fields.day, fields.clock, offset)
680 .map(Self)
681 .ok_or(out_of_range)
682 }
683}
684
685impl PgTime {
686 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
703 Ok(Self(
704 read_time(text, context)?.map_or(0, |(clock, _)| clock),
705 ))
706 }
707}
708
709impl PgTimeTz {
710 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
727 match read_time(text, context)? {
728 None => Ok(Self { time: 0, offset: 0 }),
729 Some((clock, TimeOffset::Known(offset))) => Ok(Self {
730 time: clock,
731 offset,
732 }),
733 Some((_, TimeOffset::Unwritten | TimeOffset::NeedsDate)) => {
734 Err(DateTimeError::Unsupported)
735 }
736 }
737 }
738}
739
740#[must_use]
749pub fn parse_timestamp(text: &str) -> Option<PgTimestamp> {
750 match text {
751 "infinity" => return Some(PgTimestamp::INFINITY),
752 "-infinity" => return Some(PgTimestamp::NEG_INFINITY),
753 _ => {}
754 }
755 let (body, bc) = split_era(text.as_bytes());
756 match parse_datetime_prefix(body, bc)? {
757 (date, clock, []) => date.at(clock, 0).map(PgTimestamp),
758 _ => None,
759 }
760}
761
762#[must_use]
770pub fn parse_timestamp_tz(text: &str) -> Option<PgTimestampTz> {
771 match text {
772 "infinity" => return Some(PgTimestampTz::INFINITY),
773 "-infinity" => return Some(PgTimestampTz::NEG_INFINITY),
774 _ => {}
775 }
776 let (body, bc) = split_era(text.as_bytes());
777 let (date, clock, offset) = parse_datetime_prefix(body, bc)?;
778 date.at(clock, parse_offset(offset)?).map(PgTimestampTz)
779}
780
781#[must_use]
789pub fn parse_date(text: &str) -> Option<PgDate> {
790 match text {
791 "infinity" => return Some(PgDate::INFINITY),
792 "-infinity" => return Some(PgDate::NEG_INFINITY),
793 _ => {}
794 }
795 let (body, bc) = split_era(text.as_bytes());
796 match parse_date_prefix(body, bc)? {
797 (date, []) => PgDate::from_ymd(date.year, date.month, date.day),
798 _ => None,
799 }
800}
801
802#[must_use]
810pub fn parse_time(text: &str) -> Option<PgTime> {
811 match parse_time_prefix(text.as_bytes())? {
812 (micros, []) => Some(PgTime(micros)),
813 _ => None,
814 }
815}
816
817fn split_era(bytes: &[u8]) -> (&[u8], bool) {
819 match bytes.strip_suffix(b" BC") {
820 Some(body) => (body, true),
821 None => (bytes, false),
822 }
823}
824
825#[derive(Clone, Copy)]
827struct Ymd {
828 year: i32,
829 month: u8,
830 day: u8,
831}
832
833impl Ymd {
834 fn at(self, clock: i64, offset: i32) -> Option<i64> {
837 let (month, day) = (i32::from(self.month), i32::from(self.day));
838 if !(1..=12).contains(&month) || !(1..=days_in_month(self.year, month)).contains(&day) {
839 return None;
840 }
841 tm2timestamp(self.year, month, day, clock, offset)
842 }
843}
844
845fn parse_date_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, &[u8])> {
847 let year_len = bytes.iter().take_while(|b| b.is_ascii_digit()).count();
848 if year_len < 4 || (year_len > 4 && bytes[0] == b'0') {
849 return None;
850 }
851 let (year_digits, rest) = bytes.split_at(year_len);
852 let year = strtoint(year_digits)?;
853 let year = match (year, bc) {
854 (0, true) => return None,
855 (_, true) => 1 - year,
856 (_, false) => year,
857 };
858 let Some((&[b'-', m1, m2, b'-', d1, d2], rest)) = rest.split_first_chunk() else {
859 return None;
860 };
861 let month = parse_two_digits([m1, m2])?;
862 let day = parse_two_digits([d1, d2])?;
863 Some((Ymd { year, month, day }, rest))
864}
865
866fn parse_time_prefix(bytes: &[u8]) -> Option<(i64, &[u8])> {
869 let Some((&[h1, h2, b':', m1, m2, b':', s1, s2], rest)) = bytes.split_first_chunk() else {
870 return None;
871 };
872 let (fsec, rest) = match rest.split_first() {
873 Some((b'.', fraction)) => {
874 let len = fraction.iter().take_while(|b| b.is_ascii_digit()).count();
875 if !(1..=9).contains(&len) {
876 return None;
877 }
878 (fractional_second(&rest[..=len]), &fraction[len..])
879 }
880 _ => (0, rest),
881 };
882 let (hour, minute, second) = (
883 parse_two_digits([h1, h2])?,
884 parse_two_digits([m1, m2])?,
885 parse_two_digits([s1, s2])?,
886 );
887 if minute > 59 || second > 59 {
888 return None;
889 }
890 let micros = i64::from(hour) * USECS_PER_HOUR
891 + i64::from(minute) * USECS_PER_MINUTE
892 + i64::from(second) * USECS_PER_SEC
893 + fsec;
894 (micros <= USECS_PER_DAY).then_some((micros, rest))
895}
896
897fn parse_datetime_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, i64, &[u8])> {
899 let (date, rest) = parse_date_prefix(bytes, bc)?;
900 let (&(b' ' | b'T'), rest) = rest.split_first()? else {
901 return None;
902 };
903 let (clock, rest) = parse_time_prefix(rest)?;
904 Some((date, clock, rest))
905}
906
907fn parse_two_digits(digits: [u8; 2]) -> Option<u8> {
909 if digits.iter().all(u8::is_ascii_digit) {
910 Some((digits[0] - b'0') * 10 + (digits[1] - b'0'))
911 } else {
912 None
913 }
914}
915
916fn parse_offset(bytes: &[u8]) -> Option<i32> {
919 if bytes == b"Z" {
920 return Some(0);
921 }
922 let (&sign, digits) = bytes.split_first()?;
923 let negative = match sign {
924 b'+' => false,
925 b'-' => true,
926 _ => return None,
927 };
928 let pair = |at: usize| parse_two_digits(digits.get(at..at + 2)?.try_into().ok()?);
929 let hour = pair(0)?;
930 let (minute, second) = match digits.len() {
931 2 => (0, 0),
932 4 => (pair(2)?, 0),
933 5 if digits[2] == b':' => (pair(3)?, 0),
934 8 if digits[2] == b':' && digits[5] == b':' => (pair(3)?, pair(6)?),
935 _ => return None,
936 };
937 if hour > 23 || minute > 59 || second > 59 {
938 return None;
939 }
940 let seconds = (i32::from(hour) * 60 + i32::from(minute)) * 60 + i32::from(second);
941 Some(if negative { -seconds } else { seconds })
942}