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.

36 lines
921 B

use std::{
fmt, error,
};
#[derive(Debug)]
pub struct ReadBytesError(String);
impl error::Error for ReadBytesError{}
impl fmt::Display for ReadBytesError
{
#[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
write!(f, "{:?} is not a valid integer of bytes", self.0)
}
}
/// Parse bytes from a string
pub fn bytes(string: impl AsRef<str>) -> Result<u64, ReadBytesError>
{
let string = string.as_ref();
let string = string.trim();
let last = string.chars().last().ok_or_else(move || ReadBytesError(string.to_owned()))?;
let (sl, mul) = match last {
'k' | 'K' => (1, 1024),
'm' | 'M' => (1, 1024 * 1024),
'g' | 'G' => (1, 1024 * 1024 * 1024),
_ if last.is_numeric() => (0, 1),
_ => return Err(ReadBytesError(string.to_owned())),
};
string[..(string.len()-sl)].parse()
.map(|x: u64| x * mul)
.map_err(move |_| ReadBytesError(string.to_owned()))
}