Crate btoi

source ·
Expand description

Parse integers from ASCII byte slices.

Provides functions similar to from_str_radix, but is faster when parsing directly from byte slices instead of strings.

Supports #![no_std].

Examples

use btoi::btoi;

assert_eq!(Ok(42), btoi(b"42"));
assert_eq!(Ok(-1000), btoi(b"-1000"));

All functions are generic over integer types. Use the turbofish syntax if a type cannot be inferred from the context.

// overflows the selected target type
assert!(btoi::<u32>(b"9876543210").is_err());

// underflows the selected target type (an unsigned integer)
assert!(btoi::<u32>(b"-1").is_err());

It is possible to use saturating arithmetic for overflow handling.

use btoi::btoi_saturating;

assert_eq!(Ok(0xffff_ffff), btoi_saturating::<u32>(b"9876543210"));
assert_eq!(Ok(0), btoi_saturating::<u32>(b"-1"));

Errors

All functions return ParseIntegerError for these error conditions:

  • The byte slice does not contain any digits.
  • Not all characters are 0-9, a-z, A-Z. Leading or trailing whitespace is not allowed. The btoi* functions accept an optional leading + or - sign. The btou* functions respectively do not allow signs.
  • Not all digits are valid in the given radix.
  • The number overflows or underflows the target type, but saturating arithmetic is not used.

Panics

Just like from_str_radix functions will panic if the given radix is not in the range 2..=36 (or in the pathological case that there is no representation of the radix in the target integer type).

Structs

An error that can occur when parsing an integer.

Functions

Converts a byte slice to an integer.
Converts a byte slice in a given base to an integer.
Converts a byte slice to the closest possible integer.
Converts a byte slice in a given base to the closest possible integer.
Converts a byte slice to an integer. Signs are not allowed.
Converts a byte slice in a given base to an integer. Signs are not allowed.
Converts a byte slice to the closest possible integer. Signs are not allowed.
Converts a byte slice in a given base to the closest possible integer. Signs are not allowed.