Merge pull request #8821 from cakebaker/uucore_parse_time_very_small_number

uucore/parse_time: return 1ns for small numbers
This commit is contained in:
Sylvestre Ledru 2025-10-05 17:03:48 +02:00 committed by GitHub
commit 5e076fe5cf
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -13,9 +13,9 @@ use crate::{
extendedbigdecimal::ExtendedBigDecimal,
parser::num_parser::{self, ExtendedParserError, ParseTarget},
};
use num_traits::Signed;
use num_traits::ToPrimitive;
use num_traits::Zero;
use num_traits::{FromPrimitive, Signed};
use std::time::Duration;
/// Parse a duration from a string.
@ -86,6 +86,10 @@ pub fn from_str(string: &str, allow_suffixes: bool) -> Result<Duration, String>
// potentially expensive to-nanoseconds conversion
return Ok(Duration::MAX);
}
// early return if number is too small (< 1 ns)
if !bd.is_zero() && bd < bigdecimal::BigDecimal::from_f64(0.0000000001).unwrap() {
return Ok(NANOSECOND_DURATION);
}
bd
}
ExtendedBigDecimal::MinusZero => 0.into(),
@ -165,6 +169,10 @@ mod tests {
from_str("1e-92233720368547758080", false),
Ok(NANOSECOND_DURATION)
);
assert_eq!(
from_str("0x6p-4376646810043701", false),
Ok(NANOSECOND_DURATION)
);
// nanoseconds underflow (in Duration, false)
assert_eq!(from_str("0.0000000001", false), Ok(NANOSECOND_DURATION));
assert_eq!(from_str("1e-10", false), Ok(NANOSECOND_DURATION));