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