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")
.to_string();
let size = meta.len();
Ok(Meta {
size: Size::from(&meta),
path: path.to_path_buf(),
metadata: meta,
name: String::from(name),
user,
group,
node_type: node_type,
size: Size::from_bytes(size as usize),
})
}
}

View file

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