You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.0 KiB

4 years ago
use super::*;
4 years ago
use smallmap::Map;
4 years ago
#[derive(Debug)]
pub struct Bytes;
4 years ago
const KB: u64 = 1024;
lazy_static! {
static ref SUFFIX: Map<char, u64> = smallmap::smallmap! {
{'k' => KB},
{'m' => KB * KB},
{'g' => KB * KB * KB},
{'p' => KB * KB * KB * KB},
};
}
4 years ago
impl Conversion for Bytes
{
const UNIT: &'static str = "bytes";
type Output = u64;
4 years ago
fn convert(&self, input: &str) -> Result<(Self::Output, Option<Self::Unit>), Self::Error>
4 years ago
{
4 years ago
#[macro_export] macro_rules! parse {
($non:expr) => (($non).parse::<u64>().map_err(|e| ConversionError(format!("Failed to parse u64: {}", e)))?)
}
4 years ago
let (o, u) = match input.char_indices().last().map(|(idx, chr)| (chr.to_lowercase().next().unwrap(), &input[..idx])) {
Some((chr, _)) if chr.is_numeric() => (parse!(input), 1),
4 years ago
4 years ago
Some((ref chr, non)) if SUFFIX.contains_key(chr) => (parse!(non), *SUFFIX.get(chr).unwrap()),
4 years ago
4 years ago
Some((chr, _)) => return Err(ConversionError(format!("Unknown suffix {}", chr))),
None => (0, 1),
};
Ok((o * u, Some(u)))
4 years ago
}
}