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