Fix the hand-rolled duration parser

Review the AI's codeEasy12 minAnthropic style

Your task

Your Rust service needs to parse durations like 1h30m, 45s and 2d. An agent first reached for chrono::Duration::from_str, which does not exist, then for the humantime crate, which your crate may not depend on. Told to write it by hand with only the standard library, it produced a parser over the characters.

An assistant wrote parse_duration_seconds(text), which models that parser. It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • text: the duration as written in config.
  • Return the total in seconds, or -1 when the text is not a valid duration.

Rules the tests check:

  • A valid duration is one or more pairs with nothing between them. Each pair is a number, one or more digits from 0 to 9, followed by a unit: d (86400 seconds), h (3600), m (60) or s (1).
  • Units must go from largest to smallest, each used at most once: d, then h, then m, then s. Any unit may be left out.
  • Return -1 for anything else: empty text, a number without a unit, a unit without a number, a repeated unit, units out of order, any other unit, and any other character, spaces included.

Examples

parse_duration_seconds(text: str) -> int
Example 1
Inputparse_duration_seconds("1h30m")
Output5400
Example 2
Inputparse_duration_seconds("45s")
Output45
Example 3
Inputparse_duration_seconds("2d")
Output172800