Skip to content

Commit 0c1d992

Browse files
author
Devdutt Shenoi
committed
fix: read as "X Bytes" from hottier manifest file
1 parent 90b020d commit 0c1d992

File tree

1 file changed

+41
-9
lines changed

1 file changed

+41
-9
lines changed

src/utils/human_size.rs

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,25 @@
11
use std::str::FromStr;
22

3-
use human_size::{multiples, SpecificSize};
3+
use human_size::{Any, SpecificSize};
44
use serde::{de, Deserialize, Deserializer, Serializer};
55

66
// Function to convert human-readable size to bytes (already provided)
77
// NOTE: consider number values as byte count, e.g. "1234" is 1234 bytes.
88
pub fn human_size_to_bytes(s: &str) -> Result<u64, String> {
9-
if let Ok(size) = s.parse() {
9+
let s = s.trim();
10+
if let Some(s) = s.strip_suffix("Bytes") {
11+
let size = s.trim().parse().expect("Suffix bytes implies byte count");
12+
return Ok(size);
13+
} else if let Ok(size) = s.parse() {
1014
return Ok(size);
1115
}
1216

1317
fn parse_and_map<T: human_size::Multiple>(s: &str) -> Result<u64, human_size::ParsingError> {
1418
SpecificSize::<T>::from_str(s).map(|x| x.to_bytes())
1519
}
1620

17-
let size = parse_and_map::<multiples::Mebibyte>(s)
18-
.or(parse_and_map::<multiples::Megabyte>(s))
19-
.or(parse_and_map::<multiples::Gigibyte>(s))
20-
.or(parse_and_map::<multiples::Gigabyte>(s))
21-
.or(parse_and_map::<multiples::Tebibyte>(s))
22-
.or(parse_and_map::<multiples::Terabyte>(s))
23-
.map_err(|_| "Could not parse given size".to_string())?;
21+
let size = parse_and_map::<Any>(s).map_err(|_| "Could not parse given size".to_string())?;
22+
2423
Ok(size)
2524
}
2625

@@ -64,3 +63,36 @@ where
6463
let s = String::deserialize(deserializer)?;
6564
human_size_to_bytes(&s).map_err(de::Error::custom)
6665
}
66+
67+
#[cfg(test)]
68+
mod tests {
69+
use crate::utils::human_size::human_size_to_bytes;
70+
71+
#[test]
72+
fn parse_numeric_input_without_unit() {
73+
assert_eq!(human_size_to_bytes("1234"), Ok(1234));
74+
}
75+
76+
#[test]
77+
fn parse_bytes_string_to_bytes() {
78+
assert_eq!(human_size_to_bytes("1234 Bytes"), Ok(1234));
79+
}
80+
81+
#[test]
82+
fn handle_empty_string_input() {
83+
assert_eq!(
84+
human_size_to_bytes(""),
85+
Err("Could not parse given size".to_string())
86+
);
87+
}
88+
89+
#[test]
90+
fn convert_mebibyte_string_to_bytes() {
91+
assert_eq!(human_size_to_bytes("1 MiB"), Ok(1048576));
92+
}
93+
94+
#[test]
95+
fn parse_gigabyte_string_input() {
96+
assert_eq!(human_size_to_bytes("1 GB"), Ok(1_000_000_000));
97+
}
98+
}

0 commit comments

Comments
 (0)