Skip to content

Commit

Permalink
Allow missing seconds in NaiveTime::from_str
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Jul 17, 2023
1 parent 3993c02 commit fd4ed0e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
14 changes: 12 additions & 2 deletions src/naive/time/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1324,26 +1324,36 @@ impl fmt::Display for NaiveTime {
/// let t = NaiveTime::from_hms_nano_opt(23, 59, 59, 1_234_567_890).unwrap(); // leap second
/// assert_eq!("23:59:60.23456789".parse::<NaiveTime>(), Ok(t));
///
/// // Seconds are optional
/// let t = NaiveTime::from_hms_opt(23, 56, 0).unwrap();
/// assert_eq!("23:56".parse::<NaiveTime>(), Ok(t));
///
/// assert!("foo".parse::<NaiveTime>().is_err());
/// ```
impl str::FromStr for NaiveTime {
type Err = ParseError;

fn from_str(s: &str) -> ParseResult<NaiveTime> {
const ITEMS: &[Item<'static>] = &[
const HOUR_AND_MINUTE: &[Item<'static>] = &[
Item::Numeric(Numeric::Hour, Pad::Zero),
Item::Space(""),
Item::Literal(":"),
Item::Numeric(Numeric::Minute, Pad::Zero),
];
const SECOND_AND_NANOS: &[Item<'static>] = &[
Item::Space(""),
Item::Literal(":"),
Item::Numeric(Numeric::Second, Pad::Zero),
Item::Fixed(Fixed::Nanosecond),
Item::Space(""),
];
const TRAILING_WHITESPACE: [Item<'static>; 1] = [Item::Space("")];

let mut parsed = Parsed::new();
parse(&mut parsed, s, ITEMS.iter())?;
let s = parse_and_remainder(&mut parsed, s, HOUR_AND_MINUTE.iter())?;
// Seconds are optional, don't fail if parsing them doesn't succeed.
let s = parse_and_remainder(&mut parsed, s, SECOND_AND_NANOS.iter()).unwrap_or(s);
parse(&mut parsed, s, TRAILING_WHITESPACE.iter())?;
parsed.to_naive_time()
}
}
Expand Down
9 changes: 5 additions & 4 deletions src/naive/time/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,14 +226,15 @@ fn test_time_fmt() {
}

#[test]
fn test_date_from_str() {
fn test_time_from_str() {
// valid cases
let valid = [
"0:0:0",
"0:0:0.0000000",
"0:0:0.0000003",
" 4 : 3 : 2.1 ",
" 09:08:07 ",
" 09:08 ",
" 9:8:07 ",
"01:02:03",
"4:3:2.1",
Expand Down Expand Up @@ -294,9 +295,9 @@ fn test_date_from_str() {
"", // empty
"x", // invalid
"15", // missing data
"15:8", // missing data
"15:8:x", // missing data, invalid data
"15:8:9x", // missing data, invalid data
"15:", // trailing colon
"15:8:x", // invalid data
"15:8:9x", // invalid data
"23:59:61", // invalid second (out of bounds)
"23:54:35 GMT", // invalid (timezone non-sensical for NaiveTime)
"23:54:35 +0000", // invalid (timezone non-sensical for NaiveTime)
Expand Down

0 comments on commit fd4ed0e

Please sign in to comment.