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/// - `Self` - 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    /// This is equivalent to calling Charset::default().
20    ///
21    /// # Returns
22    ///
23    /// - `Self` - New instance with empty charset.
24    pub fn new() -> Self {
25        Charset::default()
26    }
27
28    /// Validates if charset meets safety requirements.
29    ///
30    /// Checks if the charset contains exactly CHARSET_LEN unique characters.
31    ///
32    /// # Arguments
33    ///
34    /// - `&str` - Character set string to validate.
35    ///
36    /// # Returns
37    ///
38    /// - `bool` - True if charset has exactly CHARSET_LEN unique characters.
39    pub(crate) fn judge_charset_safe(charset: &str) -> bool {
40        let mut hash_set: HashSet<char> = HashSet::new();
41        for tmp_char in charset.chars() {
42            hash_set.insert(tmp_char);
43        }
44        if hash_set.len() != CHARSET_LEN {
45            return false;
46        }
47        true
48    }
49
50    /// Sets the character set for encoding/decoding operations.
51    ///
52    /// If charset is already set, this method does nothing.
53    ///
54    /// # Arguments
55    ///
56    /// - `&'b str` - Character set string to use.
57    ///
58    /// # Returns
59    ///
60    /// - `&mut Self` - Mutable self reference for method chaining.
61    pub fn charset<'b>(&mut self, charset: &'b str) -> &mut Self
62    where
63        'b: 'a,
64    {
65        if self.0 != Charset::default().0 {
66            return self;
67        }
68        self.0 = charset;
69        self
70    }
71
72    /// Encodes input string using current charset.
73    ///
74    /// Performs the encoding operation with the configured character set.
75    ///
76    /// # Arguments
77    ///
78    /// - `&str` - String to encode.
79    ///
80    /// # Returns
81    ///
82    /// - `Result<String, EncodeError>` - Encoded string or error.
83    pub fn encode(&self, encode_str: &str) -> Result<String, EncodeError> {
84        Encode::execute(self.0, encode_str)
85    }
86
87    /// Decodes input string using current charset.
88    ///
89    /// Performs the decoding operation with the configured character set.
90    ///
91    /// # Arguments
92    ///
93    /// - `&str` - String to decode.
94    ///
95    /// # Returns
96    ///
97    /// - `Result<String, DecodeError>` - Decoded string or error.
98    pub fn decode(&self, decode_str: &str) -> Result<String, DecodeError> {
99        Decode::execute(self.0, decode_str)
100    }
101}