1use ::hex::{decode as hex_decode, encode as hex_encode};
2
3use crate::encoding::EncodingTrait;
4use crate::*;
5
6pub enum HexEncodingCase {
7 UpperCase,
8 LowerCase,
9}
10
11pub struct HexEncoding(HexEncodingCase);
12
13impl HexEncoding {
14 pub const fn new(case: HexEncodingCase) -> HexEncoding {
15 HexEncoding(case)
16 }
17}
18
19impl Default for HexEncoding {
20 fn default() -> Self {
21 Self::new(HexEncodingCase::UpperCase)
22 }
23}
24
25impl EncodingTrait for HexEncoding {
26 fn encode(&self, data: &[u8]) -> String {
27 let res = hex_encode(data);
28 if let HexEncodingCase::LowerCase = self.0 {
29 return res.as_str().to_lowercase();
30 }
31 res.as_str().to_uppercase()
32 }
33 fn decode(&self, data: &str) -> Result<ByteVector> {
34 let res = hex_decode(data);
35 if let Ok(v) = res {
36 return Ok(v);
37 }
38 let error_message = format!("{}", res.unwrap_err());
39 Err(HEX_BAD_DECODING_SOURCE.add_opt_mess(&error_message))
40 }
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 #[test]
48 fn test_hex() {
49 let hexe = HexEncoding::default();
50 let res = hexe.encode("\\]^_`abcde".as_bytes());
51 assert_eq!("5C5D5E5F606162636465".to_string(), res);
52 let res = hexe.decode(&res).unwrap();
53 assert_eq!("\\]^_`abcde".as_bytes(), &res[..]);
54 let res = hexe.decode("5C5D5E5F6061626364651");
55 assert!(res.is_err());
56 println!("错误:{}", res.unwrap_err());
57 let res = hexe.decode("5C5D5E5F60616263646%");
58 assert!(res.is_err());
59 println!("错误:{}", res.unwrap_err());
60 }
61}