Skip to content

Commit

Permalink
Support parsing negative timestamps
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Mar 4, 2024
1 parent 5304354 commit 53ea528
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
6 changes: 3 additions & 3 deletions src/format/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ where
Minute => (2, false, Parsed::set_minute),
Second => (2, false, Parsed::set_second),
Nanosecond => (9, false, Parsed::set_nanosecond),
Timestamp => (usize::MAX, false, Parsed::set_timestamp),
Timestamp => (usize::MAX, true, Parsed::set_timestamp),

// for the future expansion
Internal(ref int) => match int._dummy {},
Expand All @@ -366,8 +366,7 @@ where
s = s.trim_start();
let v = if signed {
if s.starts_with('-') {
let v = try_consume!(scan::number(&s[1..], 1, usize::MAX));
0i64.checked_sub(v).ok_or(OUT_OF_RANGE)?
try_consume!(scan::negative_number(&s[1..], 1, usize::MAX))
} else if s.starts_with('+') {
try_consume!(scan::number(&s[1..], 1, usize::MAX))
} else {
Expand Down Expand Up @@ -765,6 +764,7 @@ mod tests {
check(" + 42", &[Space(" "), num(Year)], Err(INVALID));
check("-", &[num(Year)], Err(TOO_SHORT));
check("+", &[num(Year)], Err(TOO_SHORT));
check("-9223372036854775808", &[num(Timestamp)], parsed!(timestamp: i64::MIN));

// unsigned numeric
check("345", &[num(Ordinal)], parsed!(ordinal: 345));
Expand Down
12 changes: 11 additions & 1 deletion src/format/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ use crate::Weekday;
/// Any number that does not fit in `i64` is an error.
#[inline]
pub(super) fn number(s: &str, min: usize, max: usize) -> ParseResult<(&str, i64)> {
let (s, n) = negative_number(s, min, max)?;
Ok((s, n.checked_neg().ok_or(OUT_OF_RANGE)?))
}

/// Tries to parse a negative number from `min` to `max` digits.
///
/// This method parses a value as a negative integer, of wich the range is one larger than the range
/// of positive integers. This is to allows us to parse `i64::MIN`.
#[inline]
pub(super) fn negative_number(s: &str, min: usize, max: usize) -> ParseResult<(&str, i64)> {
assert!(min <= max);

// We are only interested in ascii numbers, so we can work with the `str` as bytes. We stop on
Expand All @@ -36,7 +46,7 @@ pub(super) fn number(s: &str, min: usize, max: usize) -> ParseResult<(&str, i64)
}
}

n = match n.checked_mul(10).and_then(|n| n.checked_add((c - b'0') as i64)) {
n = match n.checked_mul(10).and_then(|n| n.checked_sub((c - b'0') as i64)) {
Some(n) => n,
None => return Err(OUT_OF_RANGE),
};
Expand Down

0 comments on commit 53ea528

Please sign in to comment.