From 368a776b70ae9008fde5d26d09186469dd8c4768 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20R=2E=20Miguel?= Date: Tue, 6 Apr 2021 02:34:27 -0300 Subject: [PATCH] Add Bytes and impl Display for Bytes --- src/bytes.rs | 30 ++++++++++++++++++++++++++++++ src/extension.rs | 2 +- src/main.rs | 1 + 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 src/bytes.rs diff --git a/src/bytes.rs b/src/bytes.rs new file mode 100644 index 0000000..e79375b --- /dev/null +++ b/src/bytes.rs @@ -0,0 +1,30 @@ +use std::cmp; + +const UNITS: [&str; 4] = ["B", "kB", "MB", "GB"]; + +struct Bytes { + bytes: f64, +} + +impl Bytes { + pub fn new(bytes: u64) -> Self { + Self { + bytes: bytes as f64, + } + } +} + +impl std::fmt::Display for Bytes { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let num = self.bytes; + debug_assert!(num >= 0.0); + if num < 1_f64 { + return write!(f, "{} B", num); + } + let delimiter = 1000_f64; + let exponent = cmp::min((num.ln() / 6.90775).floor() as i32, 4); + + write!(f, "{:.2} ", num / delimiter.powi(exponent))?; + write!(f, "{}", UNITS[exponent as usize]) + } +} \ No newline at end of file diff --git a/src/extension.rs b/src/extension.rs index bb23dc8..f8a4029 100644 --- a/src/extension.rs +++ b/src/extension.rs @@ -7,7 +7,7 @@ use std::{ use CompressionFormat::*; -use crate::{debug, utils::to_utf}; +use crate::utils::to_utf; /// Represents the extension of a file, but only really caring about /// compression formats (and .tar). diff --git a/src/main.rs b/src/main.rs index e70b499..f19879d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,4 @@ +mod bytes; mod cli; mod compressors; mod decompressors;