MCPcopy Index your code
hub / github.com/bytesize-rs/bytesize / from_str

Method from_str

src/parse.rs:9–34  ·  view source on GitHub ↗
(value: &str)

Source from the content-addressed store, hash-verified

7 type Err = String;
8
9 fn from_str(value: &str) -> Result<Self, Self::Err> {
10 if let Ok(v) = value.parse::<u64>() {
11 return Ok(Self(v));
12 }
13 let number = take_while(value, |c| c.is_ascii_digit() || c == '.');
14 match number.parse::<f64>() {
15 Ok(v) => {
16 let suffix = skip_while(&value[number.len()..], char::is_whitespace);
17 match suffix.parse::<Unit>() {
18 // Use exact integer arithmetic when the number has no
19 // fractional part. `f64` only has a 53-bit mantissa, so byte
20 // counts at or above 2^53 would otherwise be rounded (e.g.
21 // "9007199254740993B" parsed to 9007199254740992).
22 Ok(u) if !number.contains('.') => match number.parse::<u64>() {
23 Ok(n) => Ok(Self(n.saturating_mul(u.factor()))),
24 Err(_) => Ok(Self((v * u) as u64)),
25 },
26 Ok(u) => Ok(Self((v * u) as u64)),
27 Err(error) => Err(format!(
28 "couldn't parse {suffix:?} into a known SI unit, {error}"
29 )),
30 }
31 }
32 Err(error) => Err(format!("couldn't parse {value:?} into a ByteSize, {error}")),
33 }
34 }
35}
36
37fn take_while<P>(s: &str, mut predicate: P) -> &str

Callers

nothing calls this directly

Calls 5

take_whileFunction · 0.85
skip_whileFunction · 0.85
UnitParseErrorClass · 0.85
to_string_truncateFunction · 0.85
factorMethod · 0.80

Tested by

no test coverage detected