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