From 346bac811d32ddeb4fa129f548f617aa40a3dd61 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 8 Jun 2023 02:10:57 -0400 Subject: lleeaakk --- src/parse.rs | 76 ++++++++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 53 insertions(+), 23 deletions(-) (limited to 'src/parse.rs') diff --git a/src/parse.rs b/src/parse.rs index c5521d6..d6e5dfa 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -1,16 +1,45 @@ use std::str::FromStr; -use crate::{PissError, PissAmount}; +use crate::{LeakError, LeakAmount}; -impl From for PissAmount -where T: Into { - fn from(num: T) -> Self { - Self { - to_piss: num.into() - } - } +macro_rules! from_num { + ($t:ty) => { + impl From<$t> for LeakAmount { + fn from(num: $t) -> Self { + Self { + to_leak: num as u128 + } + } + } + + impl From> for LeakAmount { + fn from(vec: Vec<$t>) -> Self { + let mut amount = 0; + for i in vec { + amount += i as u128; + } + Self { + to_leak: amount + } + } + } + }; } -fn parse_suffix(s: &str) -> Result { +from_num!(u128); +from_num!(u64); +from_num!(u32); +from_num!(u16); +from_num!(u8); +from_num!(i128); +from_num!(i64); +from_num!(i32); +from_num!(i16); +from_num!(i8); +from_num!(f32); +from_num!(f64); +from_num!(bool); + +fn parse_suffix(s: &str) -> Result { Ok(match s { // nepal "k" | "kb" => 1_000, "m" | "mb" => 1_000_000, @@ -33,39 +62,40 @@ fn parse_suffix(s: &str) -> Result { "ri" | "rib" => 0x0400_0000_0000_0000_0000_0000, "qi" | "qib" => 0x0010_0000_0000_0000_0000_0000_0000, "" | "b" => 1, // uwu - _ => return Err(PissError::InvalidSuffix(s.into())) // such nepal + _ => return Err(LeakError::InvalidSuffix(s.into())) // such nepal }) } -fn parse_file_size(s: &str) -> Result { +fn parse_file_size(s: &str) -> Result { let mut end = 0; for (i, c) in s.char_indices() { - if c.is_ascii_digit() || c == '.' { continue; } end = i; - break; + if !c.is_ascii_digit() && c != '.' { break; } + } + + if end == 0 { + if let Some(c) = s.chars().nth(0) { + return Err(LeakError::Unexpected(c)) + } } let num_text = &s[..end]; let suffix_text = &s[end..]; let Ok(num) = num_text.parse::() else { - return Err(PissError::InvalidNumber(num_text.into())) + return Err(LeakError::InvalidNumber(num_text.into())) }; - if num <= 0f64 { - return Err(PissError::NumberNotPositive) - } - let multiplier = parse_suffix(suffix_text)?; - Ok(PissAmount { - to_piss: (num * multiplier as f64) as u128 + Ok(LeakAmount { + to_leak: (num * multiplier as f64) as u128 }) } -impl FromStr for PissAmount { - type Err = PissError; +impl FromStr for LeakAmount { + type Err = LeakError; fn from_str(s: &str) -> Result { - parse_file_size(s) + parse_file_size(s.to_lowercase().as_str()) } } -- cgit v1.2.3-freya