iceyee_convert/
lib.rs

1// **************************************************
2// *  Author: Iceyee                                *
3// *  Mail: iceyee.studio@qq.com                    *
4// *  Git: https://github.com/iceyee                *
5// **************************************************
6//
7// Use.
8
9//! 转换类型.
10
11// Enum.
12
13/// Error.
14#[derive(Debug, Clone)]
15pub enum ConversionError {
16    TooLong(usize),
17    UnexpectedCharacter(char),
18}
19
20impl std::error::Error for ConversionError {
21    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
22        return None;
23    }
24}
25
26impl std::fmt::Display for ConversionError {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
28        match self {
29            Self::TooLong(length) => {
30                f.write_str("长度过长, length=")?;
31                f.write_str(length.to_string().as_str())?;
32                f.write_str(".")?;
33            }
34            Self::UnexpectedCharacter(character) => {
35                f.write_str("出现未预期字符, character=")?;
36                f.write_str(character.to_string().as_str())?;
37                f.write_str(".")?;
38            }
39        }
40        return Ok(());
41    }
42}
43
44// Trait.
45
46// Struct.
47
48/// 转换类型.
49
50#[derive(Debug, Clone, Default)]
51pub struct Conversion;
52
53impl Conversion {
54    /// 字符串转数字, 十六进制.
55    ///
56    /// - @exception [ConversionError::TooLong] 长度超过16.
57    /// - @exception [ConversionError::UnexpectedCharacter] 出现未预期的字符.
58    #[deprecated = "被iceyee_encoder v1.3.0 的 HexEncoder::decode_to_number() 代替."]
59    pub fn string_to_hex(s: &str) -> Result<u64, ConversionError> {
60        let v1: &[u8] = s.as_bytes();
61        if 16 < v1.len() {
62            // 长度过长.
63            return Err(ConversionError::TooLong(v1.len()));
64        }
65        let mut hex: u64 = 0;
66        for x in 0..v1.len() {
67            match v1[x] {
68                b'0'..=b'9' => {
69                    hex <<= 4;
70                    hex |= (v1[x] - b'0') as u64;
71                }
72                b'A'..=b'F' => {
73                    hex <<= 4;
74                    hex |= (v1[x] - b'A' + 10) as u64;
75                }
76                b'a'..=b'f' => {
77                    hex <<= 4;
78                    hex |= (v1[x] - b'a' + 10) as u64;
79                }
80                any => {
81                    return Err(ConversionError::UnexpectedCharacter(any as char));
82                }
83            }
84        }
85        return Ok(hex);
86    }
87}
88
89// Function.