bin_encode_decode/encode/impl.rs
1use crate::*;
2
3impl Encode {
4 /// Encodes a given input string into an encoded format using a specified character set (`charset`).
5 /// This function groups bytes in chunks of 3 and maps them into 4-character segments based on `charset`.
6 ///
7 /// # Parameters
8 /// - `charset`: A string representing the character set to use for encoding. Each character
9 /// in `charset` should have a unique position to ensure accurate encoding.
10 /// - `encode_str`: The input string to encode. It will be converted to bytes and processed
11 /// in 3-byte chunks.
12 ///
13 /// # Returns
14 /// Returns a `Result` containing the encoded `String` if successful, or a `EncodeError` if the charset is invalid.
15 ///
16 /// # Example
17 /// ```
18 /// use bin_encode_decode::*;
19 ///
20 /// let charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_=";
21 /// let original_str = "test";
22 /// let encoded_str = Encode::execute(charset, original_str);
23 /// assert_eq!(encoded_str.unwrap(), "aab0aabLaabZaab0");
24 /// ```
25 pub fn execute(charset: &str, encode_str: &str) -> Result<String, EncodeError> {
26 if !Charset::judge_charset_safe(charset) {
27 return Err(EncodeError::CharsetError);
28 }
29 let mut result: String = String::new();
30 let mut buffer: Vec<u8> = Vec::new();
31 for &byte in encode_str.as_bytes() {
32 buffer.extend_from_slice(&[0, 0, byte]);
33 }
34 for chunk in buffer.chunks(3) {
35 let combined: usize =
36 ((chunk[0] as usize) << 16) | ((chunk[1] as usize) << 8) | (chunk[2] as usize);
37 for i in (0..4).rev() {
38 let idx: usize = (combined >> (i * 6)) & 0b111111;
39 result.push(charset.chars().nth(idx).unwrap_or_default());
40 }
41 }
42 Ok(result)
43 }
44}