From 37bde2e066f2ddbaa4b32ea4d2635062614fe53d Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Mon, 22 Jul 2019 01:22:09 +0800 Subject: [PATCH] add parse_size() --- src/lib.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 0a11f18..19fa60e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -152,6 +152,26 @@ pub fn print_lastline(line: &str) { flush_stdout(); } +pub fn parse_size(size: &str) -> XResult { + let lower_size = size.to_lowercase(); + if lower_size.ends_with("b") { + let no_last_b_size = &lower_size[0..lower_size.len()-1]; + if no_last_b_size.ends_with("k") { + return Ok((SIZE_KB as f64 * no_last_b_size[0..no_last_b_size.len()-1].parse::()?) as i64); + } else if no_last_b_size.ends_with("m") { + return Ok((SIZE_MB as f64 * no_last_b_size[0..no_last_b_size.len()-1].parse::()?) as i64); + } else if no_last_b_size.ends_with("g") { + return Ok((SIZE_GB as f64 * no_last_b_size[0..no_last_b_size.len()-1].parse::()?) as i64); + } else if no_last_b_size.ends_with("t") { + return Ok((SIZE_TB as f64 * no_last_b_size[0..no_last_b_size.len()-1].parse::()?) as i64); + } else if no_last_b_size.ends_with("p") { + return Ok((SIZE_PB as f64 * no_last_b_size[0..no_last_b_size.len()-1].parse::()?) as i64); + } + } + + Err(new_box_error(&format!("Cannot parse size: {}", size))) +} + pub fn get_display_size(size: i64) -> String { if size < SIZE_KB { return size.to_string(); @@ -159,12 +179,12 @@ pub fn get_display_size(size: i64) -> String { return format!("{:.*}KB", 2, (size as f64) / 1024.); } else if size < SIZE_GB { return format!("{:.*}MB", 2, (size as f64) / 1024. / 1024.); - } else if size < SIZE_PB { - return format!("{:.*}GB", 2, (size as f64) / 1024. / 1024. / 1024.); } else if size < SIZE_TB { - return format!("{:.*}PB", 2, (size as f64) / 1024. / 1024. / 1024. / 1024.); + return format!("{:.*}GB", 2, (size as f64) / 1024. / 1024. / 1024.); + } else if size < SIZE_PB { + return format!("{:.*}TB", 2, (size as f64) / 1024. / 1024. / 1024. / 1024.); } else { - return format!("{:.*}TB", 2, (size as f64) / 1024. / 1024. / 1024. / 1024. / 1024.); + return format!("{:.*}PB", 2, (size as f64) / 1024. / 1024. / 1024. / 1024. / 1024.); } }