Add Bytes and impl Display for Bytes

This commit is contained in:
Vinícius R. Miguel 2021-04-06 02:34:27 -03:00
parent d3de94dfca
commit 368a776b70
3 changed files with 32 additions and 1 deletions

30
src/bytes.rs Normal file
View File

@ -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])
}
}

View File

@ -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).

View File

@ -1,3 +1,4 @@
mod bytes;
mod cli;
mod compressors;
mod decompressors;