This is primarily motivated by a toy RPN calculator I’m writing, but I think this has pretty general application.
At a certain point in my lexer, I need to parse a number out of the input stream. Ideally, I’d be able to use the FromStr::<f64> machinery, which already has all the logic (including overflow detection!) already built.
Unfortunately, the current semantics of FromStr prevent this use case:
- The entire input stream is considered to be consumed. Trailing characters are considered an error.
- Even if trailing characters were not an error, the caller has no idea how much of the input was consumed on a successful parse.
To remedy this, I propose a more composable main trait method, and the existing behaviour can be maintained as a shim. There’s probably a better name than from_str_with_unread but I’ll leave that bikeshed for another time:
trait FromStr {
fn from_str_with_unread<'a>(s: &'a str) -> Option<(Self, &'a str)>;
fn from_str(s: &str) -> Option<Self> {
FromStr::<Self>::from_str_with_unread(s).map(|(x, _)| x);
}
}
The basic idea behind from_str_with_unread() is to return the unconsumed subslice of the string passed in, so the caller can use it to do further parsing. FromStrRadix would also be similarly modified.