Fastest way to find out if a string with leading zeroes is not a number

Hi fellow Rustaceans!
I have this snippet in a hot loop inferring the data type of a string.

            // leading zeroes indicate a string
            // unless its followed by a period 
            // (e.g. 07094 is a string, 0.70 is a float )
            let mut chars = string.chars();
            if chars.next() == Some('0')
                && chars.next().unwrap_or_default() != '.'
                && !chars.next().unwrap_or_default().is_ascii_digit()
            {
                return TString;
            }

            if string.parse::<i64>().is_ok() {
                return TInteger;
            }

            if string.parse::<f64>().is_ok() {
                return TFloat;
            }

Is the check for leading zeroes at the beginning the most efficient way to do this?

I was thinking the compiler will short-circuit on the first condition so it shouldn't be very expensive and doing the chars.next is more efficient than a regex.

Thanks in advance!

I'd simply match it against the compiled version of the regex "^0+.". If it matches that, it's a float according to your definition. If not, it's a string.
The reasons I'd do it that way are 1. that the worst case is O(n) anyway, 2. It's concise and 3. This is lazy in the sense that it won't scan the input string more than necessary.

1 Like

It turns out the solution I ended up using was simpler and faster:

            if let Ok(int_val) = string.parse::<i64>() {
                // leading zero, its a string
                if string.starts_with('0') && int_val != 0 {
                    return TString;
                }
                return TInteger;
            }

            if string.parse::<f64>().is_ok() {
                return TFloat;
            }
1 Like