Skip to main content

rsfn_file/header/fields/
hash_algo.rs

1use std::fmt;
2
3/// Algoritmo de "hash".
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum HashAlgo {
6    SHA1,
7    SHA256,
8    Unknown(u8),
9}
10
11impl From<[u8; 1]> for HashAlgo {
12    fn from(value: [u8; 1]) -> Self {
13        value[0].into()
14    }
15}
16
17impl From<u8> for HashAlgo {
18    fn from(value: u8) -> Self {
19        match value {
20            0x02 => Self::SHA1,
21            0x03 => Self::SHA256,
22            n => Self::Unknown(n),
23        }
24    }
25}
26
27impl HashAlgo {
28    pub fn value(&self) -> u8 {
29        match self {
30            Self::SHA1 => 0x02,
31            Self::SHA256 => 0x03,
32            Self::Unknown(n) => *n,
33        }
34    }
35
36    pub fn describe_value(&self) -> String {
37        match self {
38            Self::SHA1 => "SHA-1".to_string(),
39            Self::SHA256 => "SHA-256".to_string(),
40            Self::Unknown(_) => "DESCONHECIDO".to_string(),
41        }
42    }
43
44    pub fn is_valid(&self) -> bool {
45        !matches!(self, Self::Unknown(_))
46    }
47
48    pub fn to_bytes(&self) -> [u8; 1] {
49        [self.value()]
50    }
51}
52
53impl fmt::Display for HashAlgo {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        let value = self.value();
56        let desc = self.describe_value();
57        write!(f, "0x{value:02x} [{desc}]")
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn value_zero() {
67        let sut: HashAlgo = [0x00].into();
68
69        assert_eq!(sut, HashAlgo::Unknown(0x00));
70        assert_eq!(sut, 0x00.into());
71        assert_eq!(sut.value(), 0x00);
72        assert_eq!(sut.describe_value(), "DESCONHECIDO");
73        assert!(!sut.is_valid());
74        assert_eq!(sut.to_bytes(), [0x00]);
75        assert_eq!(sut.to_string(), "0x00 [DESCONHECIDO]");
76    }
77
78    #[test]
79    fn value_sha1() {
80        let sut: HashAlgo = [0x02].into();
81
82        assert_eq!(sut, HashAlgo::SHA1);
83        assert_eq!(sut, 0x02.into());
84        assert_eq!(sut.value(), 0x02);
85        assert_eq!(sut.describe_value(), "SHA-1");
86        assert!(sut.is_valid());
87        assert_eq!(sut.to_bytes(), [0x02]);
88        assert_eq!(sut.to_string(), "0x02 [SHA-1]");
89    }
90
91    #[test]
92    fn value_sha256() {
93        let sut: HashAlgo = [0x03].into();
94
95        assert_eq!(sut, HashAlgo::SHA256);
96        assert_eq!(sut, 0x03.into());
97        assert_eq!(sut.value(), 0x03);
98        assert_eq!(sut.describe_value(), "SHA-256");
99        assert!(sut.is_valid());
100        assert_eq!(sut.to_bytes(), [0x03]);
101        assert_eq!(sut.to_string(), "0x03 [SHA-256]");
102    }
103}