simd_r_drive/utils/parse_buffer_size.rs
1/// Parses a buffer size string with optional unit suffixes into a `usize` value.
2///
3/// This function accepts numeric values with optional unit suffixes (e.g., `"K"`, `"MB"`, `"GB"`)
4/// and converts them into their corresponding byte values. The parsing is case-insensitive,
5/// and spaces around the input string are trimmed.
6///
7/// # Supported Units
8///
9/// - No unit: Assumes bytes (e.g., `"1024"` → `1024` bytes)
10/// - `K` or `KB`: Kilobytes (e.g., `"2K"` or `"2KB"` → `2048` bytes)
11/// - `M` or `MB`: Megabytes (e.g., `"1M"` or `"1MB"` → `1048576` bytes)
12/// - `G` or `GB`: Gigabytes (e.g., `"1G"` or `"1GB"` → `1073741824` bytes)
13///
14/// # Arguments
15///
16/// * `size_str` - A string slice representing the buffer size with an optional unit.
17///
18/// # Returns
19///
20/// Returns `Ok(usize)` if parsing succeeds, or an `Err(String)` if the format is invalid.
21///
22/// # Examples
23///
24/// ```
25/// use simd_r_drive::utils::parse_buffer_size;
26///
27/// assert_eq!(parse_buffer_size("1024").unwrap(), 1024);
28/// assert_eq!(parse_buffer_size("2K").unwrap(), 2048);
29/// assert_eq!(parse_buffer_size("1MB").unwrap(), 1_048_576);
30/// assert_eq!(parse_buffer_size("1G").unwrap(), 1_073_741_824);
31///
32/// assert!(parse_buffer_size("abc").is_err()); // Invalid input
33/// assert!(parse_buffer_size("10XZ").is_err()); // Invalid unit
34/// ```
35pub fn parse_buffer_size(size_str: &str) -> Result<usize, String> {
36 let size_str = size_str.trim().to_lowercase();
37
38 // Find the position where the numeric part ends
39 let num_end = size_str
40 .find(|c: char| !c.is_ascii_digit())
41 .unwrap_or(size_str.len());
42
43 let (num_part, unit_part) = size_str.split_at(num_end);
44
45 let multiplier = match unit_part {
46 "" => 1, // No unit -> assume bytes
47 "k" | "kb" => 1024,
48 "m" | "mb" => 1024 * 1024,
49 "g" | "gb" => 1024 * 1024 * 1024,
50 _ => return Err(format!("Invalid buffer size unit: {unit_part}")),
51 };
52
53 num_part
54 .parse::<usize>()
55 .map(|n| n * multiplier)
56 .map_err(|_| format!("Failed to parse buffer size: {size_str}"))
57}