|
| 1 | +// Author: cyrixninja |
| 2 | +// Octal to Decimal Converter: Converts Octal to Decimal |
| 3 | +// Wikipedia References: |
| 4 | +// 1. https://en.wikipedia.org/wiki/Octal |
| 5 | +// 2. https://en.wikipedia.org/wiki/Decimal |
| 6 | + |
| 7 | +pub fn octal_to_decimal(octal_str: &str) -> Result<u64, &'static str> { |
| 8 | + let octal_str = octal_str.trim(); |
| 9 | + |
| 10 | + if octal_str.is_empty() { |
| 11 | + return Err("Empty"); |
| 12 | + } |
| 13 | + |
| 14 | + if !octal_str.chars().all(|c| ('0'..='7').contains(&c)) { |
| 15 | + return Err("Non-octal Value"); |
| 16 | + } |
| 17 | + |
| 18 | + // Convert octal to decimal and directly return the Result |
| 19 | + u64::from_str_radix(octal_str, 8).map_err(|_| "Conversion error") |
| 20 | +} |
| 21 | + |
| 22 | +#[cfg(test)] |
| 23 | +mod tests { |
| 24 | + use super::*; |
| 25 | + |
| 26 | + #[test] |
| 27 | + fn test_empty_string() { |
| 28 | + let input = ""; |
| 29 | + let expected = Err("Empty"); |
| 30 | + assert_eq!(octal_to_decimal(input), expected); |
| 31 | + } |
| 32 | + |
| 33 | + #[test] |
| 34 | + fn test_invalid_octal() { |
| 35 | + let input = "89"; |
| 36 | + let expected = Err("Non-octal Value"); |
| 37 | + assert_eq!(octal_to_decimal(input), expected); |
| 38 | + } |
| 39 | + |
| 40 | + #[test] |
| 41 | + fn test_valid_octal() { |
| 42 | + let input = "123"; |
| 43 | + let expected = Ok(83); |
| 44 | + assert_eq!(octal_to_decimal(input), expected); |
| 45 | + } |
| 46 | + |
| 47 | + #[test] |
| 48 | + fn test_valid_octal2() { |
| 49 | + let input = "1234"; |
| 50 | + let expected = Ok(668); |
| 51 | + assert_eq!(octal_to_decimal(input), expected); |
| 52 | + } |
| 53 | + |
| 54 | + #[test] |
| 55 | + fn test_valid_octal3() { |
| 56 | + let input = "12345"; |
| 57 | + let expected = Ok(5349); |
| 58 | + assert_eq!(octal_to_decimal(input), expected); |
| 59 | + } |
| 60 | +} |
0 commit comments