pub fn parse(input: &str) -> Result<u64, Error<'_>>Expand description
Parse a SI prefixed string into a number.
Only “positive” and multiple of 1_000^n prefixes are supported (kilo,
mega, …, upto exa). Whitespaces will be trimmed multiple times at
different places, allowing flexible parsing. Because SI prefixes are
uniques, the parser in case-insensitive.
At most one unit must be specified:
5kkis not supported for example- if no units is specified, a factor of
1will be used
§Examples
use bity::{Error, si::parse};
// Basics.
assert_eq!(parse("12.3k").unwrap(), 12_300);
assert_eq!(parse("0.12k").unwrap(), 120);
assert_eq!(parse("12").unwrap(), 12);
// "Strange" fractions.
assert_eq!(parse("0.2").unwrap(), 0); // Less than a bit.
assert_eq!(parse("012.340k").unwrap(), 12_340); // Unused zeroes.
assert_eq!(parse("12.3456k").unwrap(), 12_345); // Overflowing fraction.
assert_eq!(parse(".5k").unwrap(), 500); // Missing integer.
assert_eq!(parse("5.k").unwrap(), 5_000); // Missing fraction.
// Additional spaces.
assert_eq!(parse(" 12k").unwrap(), 12_000);
assert_eq!(parse("12k ").unwrap(), 12_000);
assert_eq!(parse("12 k").unwrap(), 12_000);
// Invalids.
assert!(matches!(parse("k"), Err(Error::ParseIntError("", None))));
assert!(matches!(parse(".k"), Err(Error::ParseIntError(".", None))));
assert!(matches!(parse("1.1."), Err(Error::ParseIntError("1.", Some(_)))));
assert!(matches!(parse("1.1.k"), Err(Error::ParseIntError("1.", Some(_)))));
assert!(matches!(parse("1.1.1k"), Err(Error::ParseIntError("1.1", Some(_)))));
assert!(matches!(parse(".1.1k"), Err(Error::ParseIntError("1.1", Some(_)))));
assert!(matches!(parse("12kk"), Err(Error::InvalidUnit("kk"))));
assert!(matches!(parse("12kM"), Err(Error::InvalidUnit("kM"))));
assert!(matches!(parse("12k M"), Err(Error::InvalidUnit("k M"))));