Function btoi::btoi_saturating

source ·
pub fn btoi_saturating<I>(bytes: &[u8]) -> Result<I, ParseIntegerError>where
    I: FromPrimitive + Zero + CheckedMul + Saturating + Bounded,
Expand description

Converts a byte slice to the closest possible integer.

Like btou_saturating, but numbers may optionally start with a sign (- or +).

Errors

Returns ParseIntegerError for any of the following conditions:

  • bytes has no digits
  • not all characters of bytes are 0-9, excluding an optional leading sign

Panics

Panics in the pathological case that there is no representation of 10 in I.

Examples

assert_eq!(Ok(127), btoi_saturating::<i8>(b"127"));
assert_eq!(Ok(127), btoi_saturating::<i8>(b"128")); // i8 saturated
assert_eq!(Ok(127), btoi_saturating::<i8>(b"+1024")); // i8 saturated
assert_eq!(Ok(-128), btoi_saturating::<i8>(b"-128"));
assert_eq!(Ok(-128), btoi_saturating::<i8>(b"-129")); // i8 saturated

assert_eq!(Ok(0), btoi_saturating::<u32>(b"-123")); // unsigned integer saturated