|
1 | 1 | use std::str::FromStr;
|
2 | 2 |
|
3 |
| -use human_size::{multiples, SpecificSize}; |
| 3 | +use human_size::{Any, SpecificSize}; |
4 | 4 | use serde::{de, Deserialize, Deserializer, Serializer};
|
5 | 5 |
|
6 | 6 | // Function to convert human-readable size to bytes (already provided)
|
7 | 7 | // NOTE: consider number values as byte count, e.g. "1234" is 1234 bytes.
|
8 | 8 | 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() { |
10 | 14 | return Ok(size);
|
11 | 15 | }
|
12 | 16 |
|
13 | 17 | fn parse_and_map<T: human_size::Multiple>(s: &str) -> Result<u64, human_size::ParsingError> {
|
14 | 18 | SpecificSize::<T>::from_str(s).map(|x| x.to_bytes())
|
15 | 19 | }
|
16 | 20 |
|
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 | + |
24 | 23 | Ok(size)
|
25 | 24 | }
|
26 | 25 |
|
|
64 | 63 | let s = String::deserialize(deserializer)?;
|
65 | 64 | human_size_to_bytes(&s).map_err(de::Error::custom)
|
66 | 65 | }
|
| 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