| 
 | 1 | +pub fn hexadecimal_to_decimal(hexadecimal_str: &str) -> Result<u64, &'static str> {  | 
 | 2 | + if hexadecimal_str.is_empty() {  | 
 | 3 | + return Err("Empty input");  | 
 | 4 | + }  | 
 | 5 | + | 
 | 6 | + for hexadecimal_str in hexadecimal_str.chars() {  | 
 | 7 | + if !hexadecimal_str.is_ascii_hexdigit() {  | 
 | 8 | + return Err("Input was not a hexadecimal number");  | 
 | 9 | + }  | 
 | 10 | + }  | 
 | 11 | + | 
 | 12 | + match u64::from_str_radix(hexadecimal_str, 16) {  | 
 | 13 | + Ok(decimal) => Ok(decimal),  | 
 | 14 | + Err(_e) => Err("Failed to convert octal to hexadecimal"),  | 
 | 15 | + }  | 
 | 16 | +}  | 
 | 17 | + | 
 | 18 | +#[cfg(test)]  | 
 | 19 | +mod tests {  | 
 | 20 | + use super::*;  | 
 | 21 | + | 
 | 22 | + #[test]  | 
 | 23 | + fn test_hexadecimal_to_decimal_empty() {  | 
 | 24 | + assert_eq!(hexadecimal_to_decimal(""), Err("Empty input"));  | 
 | 25 | + }  | 
 | 26 | + | 
 | 27 | + #[test]  | 
 | 28 | + fn test_hexadecimal_to_decimal_invalid() {  | 
 | 29 | + assert_eq!(  | 
 | 30 | + hexadecimal_to_decimal("xyz"),  | 
 | 31 | + Err("Input was not a hexadecimal number")  | 
 | 32 | + );  | 
 | 33 | + assert_eq!(  | 
 | 34 | + hexadecimal_to_decimal("0xabc"),  | 
 | 35 | + Err("Input was not a hexadecimal number")  | 
 | 36 | + );  | 
 | 37 | + }  | 
 | 38 | + | 
 | 39 | + #[test]  | 
 | 40 | + fn test_hexadecimal_to_decimal_valid1() {  | 
 | 41 | + assert_eq!(hexadecimal_to_decimal("45"), Ok(69));  | 
 | 42 | + assert_eq!(hexadecimal_to_decimal("2b3"), Ok(691));  | 
 | 43 | + assert_eq!(hexadecimal_to_decimal("4d2"), Ok(1234));  | 
 | 44 | + assert_eq!(hexadecimal_to_decimal("1267a"), Ok(75386));  | 
 | 45 | + }  | 
 | 46 | + | 
 | 47 | + #[test]  | 
 | 48 | + fn test_hexadecimal_to_decimal_valid2() {  | 
 | 49 | + assert_eq!(hexadecimal_to_decimal("1a"), Ok(26));  | 
 | 50 | + assert_eq!(hexadecimal_to_decimal("ff"), Ok(255));  | 
 | 51 | + assert_eq!(hexadecimal_to_decimal("a1b"), Ok(2587));  | 
 | 52 | + assert_eq!(hexadecimal_to_decimal("7fffffff"), Ok(2147483647));  | 
 | 53 | + }  | 
 | 54 | + | 
 | 55 | + #[test]  | 
 | 56 | + fn test_hexadecimal_to_decimal_valid3() {  | 
 | 57 | + assert_eq!(hexadecimal_to_decimal("0"), Ok(0));  | 
 | 58 | + assert_eq!(hexadecimal_to_decimal("7f"), Ok(127));  | 
 | 59 | + assert_eq!(hexadecimal_to_decimal("80000000"), Ok(2147483648));  | 
 | 60 | + }  | 
 | 61 | +}  | 
0 commit comments