parent
fff867d1c4
commit
9cab3e1b98
@ -0,0 +1,35 @@
|
||||
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()))
|
||||
}
|
||||
|
Loading…
Reference in new issue