openzeppelin_monitor/utils/
parsing.rs

1//! Parsing utilities
2//!
3//! This module provides utilities for parsing various types of data.
4
5use byte_unit::Byte;
6use std::str::FromStr;
7
8/// Parses a string argument into a `u64` value representing a file size.
9///
10/// Accepts human-readable formats like "1GB", "500MB", "1024KB", etc.
11/// Returns an error if the format is invalid.
12pub fn parse_string_to_bytes_size(s: &str) -> Result<u64, String> {
13	match Byte::from_str(s) {
14		Ok(byte) => Ok(byte.as_u64()),
15		Err(e) => Err(format!("Invalid size format: '{}'. Error: {}", s, e)),
16	}
17}
18
19/// Normalizes a string by trimming whitespace and converting to lowercase.
20///
21/// This is useful for case-insensitive comparisons and removing leading/trailing whitespace.
22///
23/// # Arguments
24/// * `input` - The string to normalize
25///
26/// # Returns
27/// * `String` - The normalized string (trimmed and lowercase)
28pub fn normalize_string(input: &str) -> String {
29	input.trim().to_lowercase()
30}
31
32#[cfg(test)]
33mod tests {
34	use super::*;
35
36	#[test]
37	fn test_valid_size_formats() {
38		let test_cases = vec![
39			("1B", 1),
40			("1KB", 1000),
41			("1KiB", 1024),
42			("1MB", 1000 * 1000),
43			("1MiB", 1024 * 1024),
44			("1GB", 1000 * 1000 * 1000),
45			("1GiB", 1024 * 1024 * 1024),
46			("1.5GB", (1.5 * 1000.0 * 1000.0 * 1000.0) as u64),
47			("500MB", 500 * 1000 * 1000),
48			("0B", 0),
49		];
50
51		for (input, expected) in test_cases {
52			let result = parse_string_to_bytes_size(input);
53			assert!(result.is_ok(), "Failed to parse valid input: {}", input);
54			assert_eq!(
55				result.unwrap(),
56				expected,
57				"Incorrect parsing for input: {}",
58				input
59			);
60		}
61	}
62
63	#[test]
64	fn test_invalid_size_formats() {
65		let invalid_inputs = vec!["", "invalid", "GB", "-1GB", "1.5.5GB", "1GB2"];
66
67		for input in invalid_inputs {
68			let result = parse_string_to_bytes_size(input);
69			assert!(
70				result.is_err(),
71				"Expected error for invalid input: {}",
72				input
73			);
74		}
75	}
76
77	#[test]
78	fn test_normalize_string() {
79		let test_cases = vec![
80			("Hello World", "hello world"),
81			("  UPPERCASE  ", "uppercase"),
82			("MixedCase", "mixedcase"),
83			("  trim me  ", "trim me"),
84			("", ""),
85			("   ", ""),
86			("already lowercase", "already lowercase"),
87		];
88
89		for (input, expected) in test_cases {
90			let result = normalize_string(input);
91			println!("result: {}", result);
92			println!("expected: {}", expected);
93			assert_eq!(result, expected, "Failed to normalize: '{}'", input);
94		}
95	}
96}