#deserialize #byte #human #serde #filesize #formatting #derive-deserialize

deserialize-file-size

A serde helper function for deserializing file size input flexibly and robustly

1 stable release

1.0.0 Oct 8, 2022

#2397 in Encoding

MIT license

9KB
104 lines

deserialize-file-size

A serde helper function for deserializing file size input flexibly and robustly.

Accepts either:

  1. a "human" size string, e.g. "1k", "5mb", "12GiB", etc.
  2. an integer number of bytes

Example

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 },
);

lib.rs:

A serde helper function for deserializing file size input flexibly and robustly.

Accepts either:

  1. a "human" size string, e.g. "1k", "5mb", "12GiB", etc.
  2. 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 },
);

Dependencies

~0.5–1MB
~25K SLoC