Fix the hand-rolled duration parser
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) ors(1). - Units must go from largest to smallest, each used at most once:
d, thenh, thenm, thens. 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) -> intExample 1
Input
parse_duration_seconds("1h30m")Output
5400Example 2
Input
parse_duration_seconds("45s")Output
45Example 3
Input
parse_duration_seconds("2d")Output
172800