buup/transformers/
bin_to_dec.rs

1use crate::{Transform, TransformError, TransformerCategory};
2use std::fmt;
3
4#[derive(Debug)]
5pub enum BinToDecError {
6    ParseError(std::num::ParseIntError),
7}
8
9impl fmt::Display for BinToDecError {
10    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11        match self {
12            BinToDecError::ParseError(e) => write!(f, "Failed to parse binary: {}", e),
13        }
14    }
15}
16
17impl std::error::Error for BinToDecError {}
18
19impl From<BinToDecError> for TransformError {
20    fn from(err: BinToDecError) -> Self {
21        TransformError::HexDecodeError(err.to_string()) // Reusing HexDecodeError temporarily
22    }
23}
24
25#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, Debug)]
26pub struct BinToDecTransformer;
27
28impl Transform for BinToDecTransformer {
29    fn id(&self) -> &'static str {
30        "bin_to_dec"
31    }
32
33    fn name(&self) -> &'static str {
34        "Binary to Decimal"
35    }
36
37    fn description(&self) -> &'static str {
38        "Convert binary numbers to decimal."
39    }
40
41    fn category(&self) -> TransformerCategory {
42        TransformerCategory::Decoder
43    }
44
45    fn transform(&self, input: &str) -> Result<String, TransformError> {
46        if input.is_empty() {
47            return Ok("".to_string());
48        }
49        let binary_value = input.trim();
50        let decimal_value =
51            u64::from_str_radix(binary_value, 2).map_err(BinToDecError::ParseError)?;
52        Ok(decimal_value.to_string())
53    }
54
55    fn default_test_input(&self) -> &'static str {
56        "101010" // Represents 42
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn test_bin_to_dec() {
66        let transformer = BinToDecTransformer;
67        assert_eq!(
68            transformer
69                .transform(transformer.default_test_input())
70                .unwrap(),
71            "42".to_string()
72        );
73        assert_eq!(transformer.transform("1010").unwrap(), "10".to_string());
74        assert_eq!(transformer.transform("0").unwrap(), "0".to_string());
75        assert_eq!(transformer.transform("111").unwrap(), "7".to_string());
76        assert_eq!(
77            transformer.transform("11111111").unwrap(),
78            "255".to_string()
79        );
80    }
81
82    #[test]
83    fn test_bin_to_dec_invalid_input() {
84        let transformer = BinToDecTransformer;
85        assert!(transformer.transform("102").is_err());
86        assert!(transformer.transform("abc").is_err());
87    }
88
89    #[test]
90    fn test_empty_input() {
91        let transformer = BinToDecTransformer;
92        assert_eq!(transformer.transform("").unwrap(), "");
93    }
94}