use super::parse_error::fail; use crate::fault::Fault; fn digits_end(bytes: &[u8], from: usize) -> usize { from + bytes[from..].iter().take_while(|b| b.is_ascii_digit()).count() } /// Requires at least one digit at `from`; returns the end of the digit run. fn some_digits(bytes: &[u8], from: usize) -> Result { let end = digits_end(bytes, from); if end == from { Err(fail(from, "expected a digit")) } else { Ok(end) } } fn integer_part(bytes: &[u8], from: usize) -> Result { match bytes.get(from) { Some(b'0') => Ok(from + 1), Some(b'1'..=b'9') => Ok(digits_end(bytes, from)), _ => Err(fail(from, "expected a digit")), } } fn fraction_part(bytes: &[u8], from: usize) -> Result { match bytes.get(from) { Some(b'.') => some_digits(bytes, from + 1), _ => Ok(from), } } fn exponent_part(bytes: &[u8], from: usize) -> Result { match bytes.get(from) { Some(b'e' | b'E') => { let sign = matches!(bytes.get(from + 1), Some(b'+' | b'-')) as usize; some_digits(bytes, from + 1 + sign) } _ => Ok(from), } } /// RFC 8259 number starting at `start`; returns the value and the end offset. pub fn number(bytes: &[u8], start: usize) -> Result<(f64, usize), Fault> { let sign = (bytes.get(start) == Some(&b'-')) as usize; let end = integer_part(bytes, start + sign) .and_then(|p| fraction_part(bytes, p)) .and_then(|p| exponent_part(bytes, p))?; let parsed = std::str::from_utf8(&bytes[start..end]) .ok() .and_then(|s| s.parse::().ok()) .filter(|n| n.is_finite()); parsed.map(|n| (n, end)).ok_or_else(|| fail(start, "number out of range")) }