buup/transformers/
hex_to_bin.rs

1use crate::{Transform, TransformError, TransformerCategory};
2use std::fmt;
3
4#[derive(Debug)]
5pub enum HexToBinError {
6    ParseError(std::num::ParseIntError),
7}
8
9impl fmt::Display for HexToBinError {
10    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11        match self {
12            HexToBinError::ParseError(e) => write!(f, "Failed to parse hexadecimal: {}", e),
13        }
14    }
15}
16
17impl std::error::Error for HexToBinError {}
18
19impl From<HexToBinError> for TransformError {
20    fn from(err: HexToBinError) -> Self {
21        TransformError::HexDecodeError(err.to_string())
22    }
23}
24
25#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, Debug)]
26pub struct HexToBinTransformer;
27
28impl Transform for HexToBinTransformer {
29    fn id(&self) -> &'static str {
30        "hex_to_bin"
31    }
32
33    fn name(&self) -> &'static str {
34        "Hex to Binary"
35    }
36
37    fn description(&self) -> &'static str {
38        "Converts hexadecimal input to its binary representation (Base64 encoded)."
39    }
40
41    fn category(&self) -> TransformerCategory {
42        // Categorizing as Encoder as it primarily changes representation
43        TransformerCategory::Encoder
44    }
45
46    fn default_test_input(&self) -> &'static str {
47        "FF"
48    }
49
50    fn transform(&self, input: &str) -> Result<String, TransformError> {
51        if input.is_empty() {
52            return Ok("".to_string());
53        }
54        let hex_value = input.trim().trim_start_matches("0x");
55        let decimal_value =
56            u64::from_str_radix(hex_value, 16).map_err(HexToBinError::ParseError)?;
57        let binary_string = format!("{:b}", decimal_value);
58        Ok(binary_string)
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn test_hex_to_bin() {
68        let transformer = HexToBinTransformer;
69        assert_eq!(
70            transformer
71                .transform(transformer.default_test_input())
72                .unwrap(),
73            "11111111"
74        );
75        assert_eq!(transformer.transform("0").unwrap(), "0");
76        assert_eq!(transformer.transform("A").unwrap(), "1010");
77        assert_eq!(transformer.transform("1a").unwrap(), "11010");
78        assert_eq!(transformer.transform("100").unwrap(), "100000000");
79    }
80
81    #[test]
82    fn test_hex_to_bin_invalid_input() {
83        let transformer = HexToBinTransformer;
84        assert!(transformer.transform("FG").is_err());
85    }
86
87    #[test]
88    fn test_empty_input() {
89        let transformer = HexToBinTransformer;
90        assert_eq!(transformer.transform("").unwrap(), "");
91    }
92}