Implement the From<Metadata> trait for Size

This commit is contained in:
Peltoche 2018-12-01 11:27:46 +01:00
parent b948e99970
commit af5809c4e7
No known key found for this signature in database
GPG key ID: CED68D0487156952
2 changed files with 18 additions and 13 deletions

View file

@ -116,15 +116,14 @@ impl Meta {
.expect("failed to convert group name to str") .expect("failed to convert group name to str")
.to_string(); .to_string();
let size = meta.len();
Ok(Meta { Ok(Meta {
size: Size::from(&meta),
path: path.to_path_buf(), path: path.to_path_buf(),
metadata: meta, metadata: meta,
name: String::from(name), name: String::from(name),
user, user,
group, group,
node_type: node_type, node_type: node_type,
size: Size::from_bytes(size as usize),
}) })
} }
} }

View file

@ -1,3 +1,5 @@
use std::fs::Metadata;
#[derive(Debug)] #[derive(Debug)]
pub enum Unit { pub enum Unit {
Byte, Byte,
@ -13,36 +15,40 @@ pub struct Size {
unit: Unit, unit: Unit,
} }
impl Size { impl<'a> From<&'a Metadata> for Size {
pub fn from_bytes(bytes: usize) -> Self { fn from(meta: &Metadata) -> Self {
if bytes < 1024 { let len = meta.len() as usize;
if len < 1024 {
Size { Size {
value: bytes * 1024, value: len * 1024,
unit: Unit::Byte, unit: Unit::Byte,
} }
} else if bytes < 1024 * 1024 { } else if len < 1024 * 1024 {
Size { Size {
value: bytes, value: len,
unit: Unit::Kilo, unit: Unit::Kilo,
} }
} else if bytes < 1024 * 1024 * 1024 { } else if len < 1024 * 1024 * 1024 {
Size { Size {
value: bytes / 1024, value: len / 1024,
unit: Unit::Mega, unit: Unit::Mega,
} }
} else if bytes < 1024 * 1024 * 1024 * 1024 { } else if len < 1024 * 1024 * 1024 * 1024 {
Size { Size {
value: bytes / (1024 * 1024), value: len / (1024 * 1024),
unit: Unit::Giga, unit: Unit::Giga,
} }
} else { } else {
Size { Size {
value: bytes / (1024 * 1024 * 1024), value: len / (1024 * 1024 * 1024),
unit: Unit::Tera, unit: Unit::Tera,
} }
} }
} }
}
impl Size {
pub fn render_value(&self) -> String { pub fn render_value(&self) -> String {
let size_str = (self.value as f32 / 1024.0).to_string(); let size_str = (self.value as f32 / 1024.0).to_string();