From adcf38948e67d505754e7bdbdc54becc3603af22 Mon Sep 17 00:00:00 2001 From: Thomas Lamprecht Date: Fri, 19 Nov 2021 13:48:38 +0100 Subject: [PATCH] move HumanByte to pbs-abi-types crate Originally-by: Dietmar Maurer Signed-off-by: Thomas Lamprecht --- pbs-api-types/src/human_byte.rs | 50 +++++++++++++++++++++++++++++++++ pbs-api-types/src/lib.rs | 3 ++ 2 files changed, 53 insertions(+) create mode 100644 pbs-api-types/src/human_byte.rs diff --git a/pbs-api-types/src/human_byte.rs b/pbs-api-types/src/human_byte.rs new file mode 100644 index 00000000..a82d8fe8 --- /dev/null +++ b/pbs-api-types/src/human_byte.rs @@ -0,0 +1,50 @@ +pub struct HumanByte { + b: usize, +} +impl std::fmt::Display for HumanByte { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.b < 1024 { + return write!(f, "{} B", self.b); + } + let kb: f64 = self.b as f64 / 1024.0; + if kb < 1024.0 { + return write!(f, "{:.2} KiB", kb); + } + let mb: f64 = kb / 1024.0; + if mb < 1024.0 { + return write!(f, "{:.2} MiB", mb); + } + let gb: f64 = mb / 1024.0; + if gb < 1024.0 { + return write!(f, "{:.2} GiB", gb); + } + let tb: f64 = gb / 1024.0; + if tb < 1024.0 { + return write!(f, "{:.2} TiB", tb); + } + let pb: f64 = tb / 1024.0; + return write!(f, "{:.2} PiB", pb); + } +} +impl From for HumanByte { + fn from(v: usize) -> Self { + HumanByte { b: v } + } +} +impl From for HumanByte { + fn from(v: u64) -> Self { + HumanByte { b: v as usize } + } +} + +#[test] +fn correct_byte_convert() { + fn convert(b: usize) -> String { + HumanByte::from(b).to_string() + } + assert_eq!(convert(1023), "1023 B"); + assert_eq!(convert(1 << 10), "1.00 KiB"); + assert_eq!(convert(1 << 20), "1.00 MiB"); + assert_eq!(convert((1 << 30) + 103 * (1 << 20)), "1.10 GiB"); + assert_eq!(convert((2 << 50) + 500 * (1 << 40)), "2.49 PiB"); +} diff --git a/pbs-api-types/src/lib.rs b/pbs-api-types/src/lib.rs index 4247bba3..a28ddafd 100644 --- a/pbs-api-types/src/lib.rs +++ b/pbs-api-types/src/lib.rs @@ -39,6 +39,9 @@ pub use acl::*; mod datastore; pub use datastore::*; +mod human_byte; +pub use human_byte::HumanByte; + mod jobs; pub use jobs::*;