Parse capacity limit from string to number of bytes by allowing units: K, M and G. Supports formats like '1.5G' -> 1610612736, '100M' -> 104857600
(limit: &str)
| 152 | /// Parse capacity limit from string to number of bytes by allowing units: K, M and G. |
| 153 | /// Supports formats like '1.5G' -> 1610612736, '100M' -> 104857600 |
| 154 | fn parse_capacity_limit(limit: &str) -> Result<usize, String> { |
| 155 | if limit.trim().is_empty() { |
| 156 | return Err("Capacity limit cannot be empty".to_string()); |
| 157 | } |
| 158 | let (number, unit) = limit.split_at(limit.len() - 1); |
| 159 | let number: f64 = number |
| 160 | .parse() |
| 161 | .map_err(|_| format!("Failed to parse number from capacity limit '{limit}'"))?; |
| 162 | if number.is_sign_negative() || number.is_infinite() { |
| 163 | return Err("Limit value should be positive finite number".to_string()); |
| 164 | } |
| 165 | |
| 166 | match unit { |
| 167 | "K" => Ok((number * 1024.0) as usize), |
| 168 | "M" => Ok((number * 1024.0 * 1024.0) as usize), |
| 169 | "G" => Ok((number * 1024.0 * 1024.0 * 1024.0) as usize), |
| 170 | _ => Err(format!( |
| 171 | "Unsupported unit '{unit}' in capacity limit '{limit}'. Unit must be one of: 'K', 'M', 'G'" |
| 172 | )), |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | #[cfg(test)] |
| 177 | mod tests { |
searching dependent graphs…