From 03af2f2ed93d341381fee1143b3b554bc3715e23 Mon Sep 17 00:00:00 2001 From: Avril Date: Wed, 30 Dec 2020 00:19:28 +0000 Subject: [PATCH] bytes: works --- Cargo.lock | 34 ++++++++++++++++++++++++++++++++++ Cargo.toml | 1 + src/conv/bytes.rs | 25 ++++++++++++++++++++++++- 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index a671b8e..9b31b98 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6,9 +6,43 @@ version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +dependencies = [ + "semver", +] + +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +dependencies = [ + "semver-parser", +] + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" + +[[package]] +name = "smallmap" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d61d73d5986b7f728a76234ca60f7826faa44dd9043d2954ca6583bfc7b875d" +dependencies = [ + "rustc_version", +] + [[package]] name = "units" version = "0.1.0" dependencies = [ "lazy_static", + "smallmap", ] diff --git a/Cargo.toml b/Cargo.toml index 571d149..5fade99 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,3 +8,4 @@ edition = "2018" [dependencies] lazy_static = "1.4.0" +smallmap = "1.3.0" diff --git a/src/conv/bytes.rs b/src/conv/bytes.rs index 03c7f8e..d2ce42c 100644 --- a/src/conv/bytes.rs +++ b/src/conv/bytes.rs @@ -1,8 +1,20 @@ use super::*; +use smallmap::Map; #[derive(Debug)] pub struct Bytes; +const KB: u64 = 1024; + +lazy_static! { + static ref SUFFIX: Map = smallmap::smallmap! { + {'k' => KB}, + {'m' => KB * KB}, + {'g' => KB * KB * KB}, + {'p' => KB * KB * KB * KB}, + }; +} + impl Conversion for Bytes { const UNIT: &'static str = "bytes"; @@ -11,6 +23,17 @@ impl Conversion for Bytes fn convert(&self, input: &str) -> Result { - todo!() + #[macro_export] macro_rules! parse { + ($non:expr) => (($non).parse::().map_err(|e| ConversionError(format!("Failed to parse u64: {}", e)))?) + } + + match input.char_indices().last().map(|(idx, chr)| (chr.to_lowercase().next().unwrap(), &input[..idx])) { + Some((chr, _)) if chr.is_numeric() => Ok(parse!(input)), + + Some((ref chr, non)) if SUFFIX.contains_key(chr) => Ok(*SUFFIX.get(chr).unwrap() * parse!(non)), + + Some((chr, _)) => Err(ConversionError(format!("Unknown suffix {}", chr))), + None => Ok(0), + } } }