Skip to main content

gwr_components/
cli.rs

1// Copyright (c) 2026 Graphcore Ltd. All rights reserved.
2
3use byte_unit::Byte;
4
5/// Parse a CLI byte value, accepting either a bare byte count or a
6/// `byte-unit` string such as `32KiB`, `1484B`, or `2MiB`.
7pub fn parse_bytes_string(value: &str) -> Result<usize, String> {
8    // Don't ignore case so that bit (b) and Byte (B) can be distinguished.
9    let ignore_case = false;
10    let bytes = Byte::parse_str(value, ignore_case)
11        .map_err(|e| format!("Unable to parse {value} as Byte string: {e}"))?
12        .as_u64();
13    usize::try_from(bytes).map_err(|e| format!("{value} is too large for this platform: {e}"))
14}
15
16#[cfg(test)]
17mod tests {
18    use super::*;
19
20    #[test]
21    fn parse_buffer_bytes_accepts_binary_units() {
22        assert_eq!(parse_bytes_string("32KiB").unwrap(), 32 * 1024);
23    }
24
25    #[test]
26    fn parse_buffer_bytes_accepts_byte_units() {
27        assert_eq!(parse_bytes_string("32768B").unwrap(), 32 * 1024);
28    }
29
30    #[test]
31    fn parse_buffer_bytes_accepts_bare_byte_counts() {
32        assert_eq!(parse_bytes_string("32768").unwrap(), 32 * 1024);
33    }
34
35    #[test]
36    fn parse_buffer_bytes_rejects_invalid_values() {
37        assert!(parse_bytes_string("thirty-two").is_err());
38    }
39}