bin_encode_decode/common/impl.rs
1use crate::*;
2
3impl<'a> Default for Charset<'a> {
4 fn default() -> Self {
5 Charset("")
6 }
7}
8
9impl<'a> Charset<'a> {
10 /// Creates a new instance of `Charset` with a default charset.
11 pub fn new() -> Self {
12 Charset::default()
13 }
14
15 /// Checks if the `charset` contains `CHARSET_LEN` unique characters.
16 ///
17 /// # Returns
18 /// Returns `true` if `charset` contains `CHARSET_LEN` unique characters, otherwise returns `false`.
19 pub(crate) fn judge_charset_safe(charset: &str) -> bool {
20 let mut hash_set: HashSet<char> = HashSet::new();
21 for tmp_char in charset.chars() {
22 hash_set.insert(tmp_char);
23 }
24 if hash_set.len() != CHARSET_LEN {
25 return false;
26 }
27 true
28 }
29
30 /// Sets the `charset` for the current `Charset` instance, if it is not already set.
31 ///
32 /// # Parameters
33 /// - `charset`: A string slice representing the charset to be used.
34 ///
35 /// # Returns
36 /// Returns a mutable reference to `Self` for method chaining.
37 pub fn charset<'b>(&mut self, charset: &'b str) -> &mut Self
38 where
39 'b: 'a,
40 {
41 if self.0 != Charset::default().0 {
42 return self;
43 }
44 self.0 = charset;
45 self
46 }
47
48 /// encodes a string based on the current `charset`.
49 ///
50 /// # Parameters
51 /// - `encode_str`: The string slice to be encoded.
52 ///
53 /// # Returns
54 /// Returns a `Result` containing the encoded `String` if successful, or a `EncodeError` if the charset is invalid.
55 pub fn encode(&self, encode_str: &str) -> Result<String, EncodeError> {
56 Encode::execute(self.0, encode_str)
57 }
58
59 /// decodes a string based on the current `charset`.
60 ///
61 /// # Parameters
62 /// - `decode_str`: The string slice to be decoded.
63 ///
64 /// # Returns
65 /// Returns a `Result` containing the decoded `String` if successful, or a `DecodeError` if the charset is invalid.
66 pub fn decode(&self, decode_str: &str) -> Result<String, DecodeError> {
67 Decode::execute(self.0, decode_str)
68 }
69}