Crate deserialize_file_size
source · [−]Expand description
A serde helper function for deserializing file size input flexibly and robustly.
Accepts either:
- a “human” size string, e.g. “1k”, “5mb”, “12GiB”, etc.
- an integer number of bytes
Examples
use serde::Deserialize;
use deserialize_file_size::deserialize_file_size;
#[derive(Deserialize, Debug, PartialEq)]
struct FileSize {
#[serde(deserialize_with = "deserialize_file_size")]
sz: usize,
}
let size_str = r#"{"sz": "42mb"}"#;
assert_eq!(
serde_json::from_str::<FileSize>(size_str).unwrap(),
FileSize { sz: 1024 * 1024 * 42 },
);
let int_bytes = r#"{"sz": 4096}"#;
assert_eq!(
serde_json::from_str::<FileSize>(int_bytes).unwrap(),
FileSize { sz: 4096 },
);
Functions
A serde “deserialize_with” helper function for parsing a
usize
field
flexibly and robustly.returns size in bytes if parsing is successful. note: units “k”/“kb”, “m”/“mb”,
and “g”/“gb” are converted to KiB, MiB, and GiB respectively. there are no 1000-based
file sizes as far as this implementation is concerned, 1024 is file size god.