scolapasta_int_parse

Function parse

Source
pub fn parse<T>(subject: &T, radix: Option<i64>) -> Result<i64, Error<'_>>
where T: AsRef<[u8]> + ?Sized,
Expand description

Parse a given byte string and optional Radix into an i64.

This function wraps i64::from_str_radix by normalizing the input byte string:

  • Assert the byte string is ASCII and does not contain NUL bytes.
  • Parse the radix to ensure it is in range and valid for the given input byte string.
  • Trim leading and trailing whitespace.
  • Accept a single, optional + or - sign byte.
  • Parse a literal radix out of the string from one of 0b, 0B, 0o, 0O, 0d, 0D, 0x, or 0X. If the given radix is Some(_), the radix must match the embedded radix literal. A 0 prefix of arbitrary length is interpreted as an octal literal.
  • Remove (“squeeze”) leading zeros.
  • Collect ASCII alphanumeric bytes and filter out underscores.
  • Pass the collected ASCII alphanumeric bytes to i64::from_str_radix.

If the given radix argument is None the input byte string is either parsed with the radix embedded within it (e.g. 0x... is base 16) or defaults to base 10.

§Errors

This function can return an error in the following circumstances:

  • The input byte string has non-ASCII bytes.
  • The input byte string contains a NUL byte.
  • The input byte string is the empty byte slice.
  • The input byte string only contains +/- signs.
  • The given radix does not match a 0x-style prefix.
  • Invalid or duplicate +/- signs are in the input.
  • Consecutive underscores are present in the input.
  • Leading or trailing underscores are present in the input.
  • The input contains ASCII alphanumeric bytes that are invalid for the computed radix.
  • The input radix is out of range of i32.
  • The input radix is negative (if the input byte string does not have an 0x-style prefix) and out of range -36..=-2.
  • The input radix is out of range of 2..=36.

See ArgumentError and InvalidRadixError for more details.

§Examples

let int_max = parse("9_223_372_036_854_775_807", None)?;
assert_eq!(int_max, i64::MAX);

let deadbeef = parse("                       0x000000000deadbeef", None)?;
assert_eq!(deadbeef, 3_735_928_559);

let octal = parse("000123", None)?;
assert_eq!(octal, 83);

let negative = parse("-199", None)?;
assert_eq!(negative, -199);

let positive = parse("+199", None)?;
assert_eq!(positive, 199);

If a Some(_) radix is given, that radix is used:

let num = parse("32xyz", Some(36))?;
assert_eq!(num, 5_176_187);

let binary = parse("1100_0011", Some(2))?;
assert_eq!(binary, 195);

If a Some(_) radix is given and it does not match the embedded radix, an error is returned:

let result = parse("0b1100_0011", Some(12));
assert!(result.is_err());