omni_dev/utils/
general.rs1use std::fmt;
4
5#[derive(Debug)]
7pub enum UtilError {
8 InvalidInput(String),
10 Io(std::io::Error),
12}
13
14impl fmt::Display for UtilError {
15 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16 match self {
17 UtilError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
18 UtilError::Io(err) => write!(f, "I/O error: {}", err),
19 }
20 }
21}
22
23impl std::error::Error for UtilError {
24 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
25 match self {
26 UtilError::InvalidInput(_) => None,
27 UtilError::Io(err) => Some(err),
28 }
29 }
30}
31
32impl From<std::io::Error> for UtilError {
33 fn from(err: std::io::Error) -> Self {
34 UtilError::Io(err)
35 }
36}
37
38pub fn validate_input(input: &str) -> Result<(), UtilError> {
40 if input.is_empty() {
41 return Err(UtilError::InvalidInput("Input cannot be empty".to_string()));
42 }
43
44 if input.len() > 1000 {
45 return Err(UtilError::InvalidInput("Input too long".to_string()));
46 }
47
48 Ok(())
49}
50
51pub fn format_bytes(bytes: u64) -> String {
53 const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
54 let mut size = bytes as f64;
55 let mut unit_index = 0;
56
57 while size >= 1024.0 && unit_index < UNITS.len() - 1 {
58 size /= 1024.0;
59 unit_index += 1;
60 }
61
62 if unit_index == 0 {
63 format!("{} {}", bytes, UNITS[unit_index])
64 } else {
65 format!("{:.1} {}", size, UNITS[unit_index])
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 #[test]
74 fn validate_input_valid() {
75 assert!(validate_input("valid input").is_ok());
76 }
77
78 #[test]
79 fn validate_input_empty() {
80 assert!(validate_input("").is_err());
81 }
82
83 #[test]
84 fn validate_input_too_long() {
85 let long_input = "a".repeat(1001);
86 assert!(validate_input(&long_input).is_err());
87 }
88
89 #[test]
90 fn format_bytes() {
91 assert_eq!(super::format_bytes(0), "0 B");
92 assert_eq!(super::format_bytes(512), "512 B");
93 assert_eq!(super::format_bytes(1024), "1.0 KB");
94 assert_eq!(super::format_bytes(1536), "1.5 KB");
95 assert_eq!(super::format_bytes(1048576), "1.0 MB");
96 assert_eq!(super::format_bytes(1073741824), "1.0 GB");
97 }
98}