Skip to main content

bin_encode_decode/common/
impl.rs

1use super::*;
2
3/// Provides display formatting for EncodeError.
4///
5/// Implements human-readable error messages for encoding failures.
6impl fmt::Display for EncodeError {
7    /// Formats the EncodeError for display purposes.
8    ///
9    /// # Arguments
10    ///
11    /// - `&mut fmt::Formatter<'_>` - The formatter to use.
12    ///
13    /// # Returns
14    ///
15    /// - `fmt::Result` - Result of the formatting operation.
16    #[inline(always)]
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        match self {
19            EncodeError::CharsetError => write!(
20                f,
21                "EncodeError: Charset is invalid. Please ensure the charset contains exactly {CHARSET_LEN} unique characters."
22            ),
23        }
24    }
25}
26
27/// Provides display formatting for DecodeError.
28///
29/// Implements human-readable error messages for decoding failures.
30impl fmt::Display for DecodeError {
31    /// Formats the DecodeError for display purposes.
32    ///
33    /// # Arguments
34    ///
35    /// - `&mut fmt::Formatter<'_>` - The formatter to use.
36    ///
37    /// # Returns
38    ///
39    /// - `fmt::Result` - Result of the formatting operation.
40    #[inline(always)]
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        match self {
43            DecodeError::CharsetError => write!(
44                f,
45                "DecodeError: Charset is invalid. Please ensure the charset contains exactly {CHARSET_LEN} unique characters."
46            ),
47        }
48    }
49}
50
51/// Provides default implementation for Charset.
52///
53/// Creates a new Charset instance with empty string as default charset.
54///
55/// # Returns
56///
57/// - `Charset<'a>` - New instance with empty charset.
58impl<'a> Default for Charset<'a> {
59    /// Creates an empty charset instance.
60    #[inline(always)]
61    fn default() -> Self {
62        Charset(EMPTY_STR)
63    }
64}
65
66impl<'a> Charset<'a> {
67    /// Creates a new Charset instance with default charset.
68    ///
69    /// # Returns
70    ///
71    /// - `Charset<'a>` - New instance with empty charset.
72    #[inline(always)]
73    pub fn new() -> Self {
74        Charset::default()
75    }
76
77    /// Validates that an ASCII charset byte slice contains exactly 64 unique bytes.
78    ///
79    /// # Arguments
80    ///
81    /// - `&[u8]` - Candidate ASCII character set bytes.
82    ///
83    /// # Returns
84    ///
85    /// - `bool` - `true` if the charset contains exactly 64 unique bytes.
86    #[inline(always)]
87    pub(crate) fn validate_ascii_charset(bytes: &[u8]) -> bool {
88        if bytes.len() < CHARSET_LEN {
89            return false;
90        }
91        let mut seen: [u64; 2] = [0u64; 2];
92        if bytes.len() == CHARSET_LEN {
93            for &byte in bytes {
94                let word: usize = (byte >> 6) as usize;
95                let bit: u64 = 1u64 << (byte & SIX_BIT_MASK);
96                if (seen[word] & bit) != 0 {
97                    return false;
98                }
99                seen[word] |= bit;
100            }
101            return true;
102        }
103        for &byte in bytes {
104            let word: usize = (byte >> 6) as usize;
105            seen[word] |= 1u64 << (byte & SIX_BIT_MASK);
106        }
107        (seen[0].count_ones() + seen[1].count_ones()) as usize == CHARSET_LEN
108    }
109
110    /// Validates an exact-length 64-byte ASCII charset and builds a compact 256-entry decode LUT.
111    ///
112    /// # Arguments
113    ///
114    /// - `&[u8]` - Candidate 64-byte ASCII character set.
115    ///
116    /// # Returns
117    ///
118    /// - `Option<[u8; DECODE_LUT_LEN]>` - Byte-to-index table if all 64 bytes are unique.
119    #[inline(always)]
120    pub(crate) fn build_ascii_decode_lut_exact(bytes: &[u8]) -> Option<[u8; DECODE_LUT_LEN]> {
121        let mut lut: [u8; DECODE_LUT_LEN] = [INVALID_DECODE_VAL; DECODE_LUT_LEN];
122        for (idx, &byte) in bytes.iter().enumerate() {
123            let slot: &mut u8 = &mut lut[byte as usize];
124            if *slot != INVALID_DECODE_VAL {
125                return None;
126            }
127            *slot = idx as u8;
128        }
129        Some(lut)
130    }
131
132    /// Validates an arbitrary-length ASCII charset and builds a collision-free `usize` decode LUT.
133    ///
134    /// # Arguments
135    ///
136    /// - `&[u8]` - Candidate ASCII character set bytes.
137    ///
138    /// # Returns
139    ///
140    /// - `Option<[usize; DECODE_LUT_LEN]>` - Byte-to-first-index table if exactly 64 unique bytes exist.
141    pub(crate) fn build_ascii_decode_lut_general(bytes: &[u8]) -> Option<[usize; DECODE_LUT_LEN]> {
142        if bytes.len() < CHARSET_LEN {
143            return None;
144        }
145        let mut lut: [usize; DECODE_LUT_LEN] = [INVALID_DECODE_INDEX; DECODE_LUT_LEN];
146        let mut unique_count: usize = 0;
147        for (idx, &byte) in bytes.iter().enumerate() {
148            let slot: &mut usize = &mut lut[byte as usize];
149            if *slot == INVALID_DECODE_INDEX {
150                *slot = idx;
151                unique_count += 1;
152            }
153        }
154        if unique_count == CHARSET_LEN {
155            Some(lut)
156        } else {
157            None
158        }
159    }
160
161    /// Validates a non-ASCII charset and extracts its first 64 characters for encoding.
162    ///
163    /// # Arguments
164    ///
165    /// - `&str` - Candidate Unicode character set.
166    ///
167    /// # Returns
168    ///
169    /// - `Option<[char; CHARSET_LEN]>` - First 64 characters if the charset has exactly 64 unique characters.
170    pub(crate) fn build_unicode_encode_table(charset: &str) -> Option<[char; CHARSET_LEN]> {
171        let mut occupied: [bool; UNICODE_HASH_SLOTS] = [false; UNICODE_HASH_SLOTS];
172        let mut keys: [char; UNICODE_HASH_SLOTS] = [NULL_CHAR; UNICODE_HASH_SLOTS];
173        let mut table: [char; CHARSET_LEN] = [NULL_CHAR; CHARSET_LEN];
174        let mut unique_count: usize = 0;
175        for (total_count, ch) in charset.chars().enumerate() {
176            if total_count < CHARSET_LEN {
177                table[total_count] = ch;
178            }
179            let mut slot: usize =
180                (((ch as u32).wrapping_mul(UNICODE_HASH_MULT)) >> 25) as usize & UNICODE_HASH_MASK;
181            loop {
182                if !occupied[slot] {
183                    if unique_count == CHARSET_LEN {
184                        return None;
185                    }
186                    occupied[slot] = true;
187                    keys[slot] = ch;
188                    unique_count += 1;
189                    break;
190                }
191                if keys[slot] == ch {
192                    break;
193                }
194                slot = (slot + 1) & UNICODE_HASH_MASK;
195            }
196        }
197        if unique_count == CHARSET_LEN {
198            Some(table)
199        } else {
200            None
201        }
202    }
203
204    /// Validates a non-ASCII charset and builds a stack open-addressed lookup table for decoding.
205    ///
206    /// # Arguments
207    ///
208    /// - `&str` - Candidate Unicode character set.
209    ///
210    /// # Returns
211    ///
212    /// - `Option<[(char, usize); UNICODE_HASH_SLOTS]>` - Hash table mapping unique chars to first positions.
213    pub(crate) fn build_unicode_decode_table(
214        charset: &str,
215    ) -> Option<[(char, usize); UNICODE_HASH_SLOTS]> {
216        let mut table: [(char, usize); UNICODE_HASH_SLOTS] =
217            [(NULL_CHAR, UNICODE_EMPTY_SLOT); UNICODE_HASH_SLOTS];
218        let mut unique_count: usize = 0;
219        for (pos, ch) in charset.chars().enumerate() {
220            let mut slot: usize =
221                (((ch as u32).wrapping_mul(UNICODE_HASH_MULT)) >> 25) as usize & UNICODE_HASH_MASK;
222            loop {
223                let entry: &mut (char, usize) = &mut table[slot];
224                if entry.1 == UNICODE_EMPTY_SLOT {
225                    if unique_count == CHARSET_LEN {
226                        return None;
227                    }
228                    *entry = (ch, pos);
229                    unique_count += 1;
230                    break;
231                }
232                if entry.0 == ch {
233                    break;
234                }
235                slot = (slot + 1) & UNICODE_HASH_MASK;
236            }
237        }
238        if unique_count == CHARSET_LEN {
239            Some(table)
240        } else {
241            None
242        }
243    }
244
245    /// Sets the character set for encoding/decoding operations.
246    ///
247    /// # Arguments
248    ///
249    /// - `&'b str` - The character set to use.
250    ///
251    /// # Returns
252    ///
253    /// - `&mut Self` - Self reference for method chaining.
254    #[inline(always)]
255    pub fn charset<'b>(&mut self, charset: &'b str) -> &mut Self
256    where
257        'b: 'a,
258    {
259        if !self.0.is_empty() {
260            return self;
261        }
262        self.0 = charset;
263        self
264    }
265
266    /// Encodes input string using current charset.
267    ///
268    /// # Arguments
269    ///
270    /// - `&str` - The string to encode.
271    ///
272    /// # Returns
273    ///
274    /// - `Result<String, EncodeError>` - Encoding result.
275    #[inline(always)]
276    pub fn encode(&self, encode_str: &str) -> Result<String, EncodeError> {
277        Encode::execute(self.0, encode_str)
278    }
279
280    /// Decodes input string using current charset.
281    ///
282    /// # Arguments
283    ///
284    /// - `&str` - The string to decode.
285    ///
286    /// # Returns
287    ///
288    /// - `Result<String, DecodeError>` - Decoding result.
289    #[inline(always)]
290    pub fn decode(&self, decode_str: &str) -> Result<String, DecodeError> {
291        Decode::execute(self.0, decode_str)
292    }
293}