bin_encode_decode/common/
impl.rs

1use crate::*;
2
3/// Provides default implementation for Charset.
4///
5/// Creates a new Charset instance with empty string as default charset.
6///
7/// # Returns
8///
9/// - `Charset<'a>` - New instance with empty charset.
10impl<'a> Default for Charset<'a> {
11    fn default() -> Self {
12        Charset("")
13    }
14}
15
16impl<'a> Charset<'a> {
17    /// Creates a new Charset instance with default charset.
18    ///
19    /// # Returns
20    ///
21    /// - `Charset<'a>` - New instance with empty charset.
22    #[inline]
23    pub fn new() -> Self {
24        Charset::default()
25    }
26
27    /// Validates if charset meets safety requirements.
28    ///
29    /// # Arguments
30    ///
31    /// - `&str` - Checks if the charset contains exactly CHARSET_LEN unique characters.
32    ///
33    /// # Returns
34    ///
35    /// - `bool` - Validation result.
36    pub(crate) fn judge_charset_safe(charset: &str) -> bool {
37        let mut hash_set: HashSet<char> = HashSet::new();
38        for tmp_char in charset.chars() {
39            hash_set.insert(tmp_char);
40        }
41        if hash_set.len() != CHARSET_LEN {
42            return false;
43        }
44        true
45    }
46
47    /// Sets the character set for encoding/decoding operations.
48    ///
49    /// # Arguments
50    ///
51    /// - `&'b str` - The character set to use.
52    ///
53    /// # Returns
54    ///
55    /// - `&mut Charset<'a>` - Self reference for method chaining.
56    pub fn charset<'b>(&mut self, charset: &'b str) -> &mut Self
57    where
58        'b: 'a,
59    {
60        if self.0 != Charset::default().0 {
61            return self;
62        }
63        self.0 = charset;
64        self
65    }
66
67    /// Encodes input string using current charset.
68    ///
69    /// # Arguments
70    ///
71    /// - `&str` - The string to encode.
72    ///
73    /// # Returns
74    ///
75    /// - `Result<String, EncodeError>` - Encoding result.
76    pub fn encode(&self, encode_str: &str) -> Result<String, EncodeError> {
77        Encode::execute(self.0, encode_str)
78    }
79
80    /// Decodes input string using current charset.
81    ///
82    /// # Arguments
83    ///
84    /// - `&str` - The string to decode.
85    ///
86    /// # Returns
87    ///
88    /// - `Result<String, DecodeError>` - Decoding result.
89    pub fn decode(&self, decode_str: &str) -> Result<String, DecodeError> {
90        Decode::execute(self.0, decode_str)
91    }
92}