bin-encode-decode 11.0.0

A high-performance binary encode and decode library that supports customizable character sets beyond Base64.
Documentation
use super::*;

/// Provides display formatting for EncodeError.
///
/// Implements human-readable error messages for encoding failures.
impl fmt::Display for EncodeError {
    /// Formats the EncodeError for display purposes.
    ///
    /// # Arguments
    ///
    /// - `&mut fmt::Formatter<'_>` - The formatter to use.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Result of the formatting operation.
    #[inline(always)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EncodeError::CharsetError => write!(
                f,
                "EncodeError: Charset is invalid. Please ensure the charset contains exactly {CHARSET_LEN} unique characters."
            ),
        }
    }
}

/// Provides display formatting for DecodeError.
///
/// Implements human-readable error messages for decoding failures.
impl fmt::Display for DecodeError {
    /// Formats the DecodeError for display purposes.
    ///
    /// # Arguments
    ///
    /// - `&mut fmt::Formatter<'_>` - The formatter to use.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Result of the formatting operation.
    #[inline(always)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DecodeError::CharsetError => write!(
                f,
                "DecodeError: Charset is invalid. Please ensure the charset contains exactly {CHARSET_LEN} unique characters."
            ),
        }
    }
}

/// Provides default implementation for Charset.
///
/// Creates a new Charset instance with empty string as default charset.
///
/// # Returns
///
/// - `Charset<'a>` - New instance with empty charset.
impl<'a> Default for Charset<'a> {
    /// Creates an empty charset instance.
    #[inline(always)]
    fn default() -> Self {
        Charset(EMPTY_STR)
    }
}

impl<'a> Charset<'a> {
    /// Creates a new Charset instance with default charset.
    ///
    /// # Returns
    ///
    /// - `Charset<'a>` - New instance with empty charset.
    #[inline(always)]
    pub fn new() -> Self {
        Charset::default()
    }

    /// Validates that an ASCII charset byte slice contains exactly 64 unique bytes.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Candidate ASCII character set bytes.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the charset contains exactly 64 unique bytes.
    #[inline(always)]
    pub(crate) fn validate_ascii_charset(bytes: &[u8]) -> bool {
        if bytes.len() < CHARSET_LEN {
            return false;
        }
        let mut seen: [u64; 2] = [0u64; 2];
        if bytes.len() == CHARSET_LEN {
            for &byte in bytes {
                let word: usize = (byte >> 6) as usize;
                let bit: u64 = 1u64 << (byte & SIX_BIT_MASK);
                if (seen[word] & bit) != 0 {
                    return false;
                }
                seen[word] |= bit;
            }
            return true;
        }
        for &byte in bytes {
            let word: usize = (byte >> 6) as usize;
            seen[word] |= 1u64 << (byte & SIX_BIT_MASK);
        }
        (seen[0].count_ones() + seen[1].count_ones()) as usize == CHARSET_LEN
    }

    /// Validates an exact-length 64-byte ASCII charset and builds a compact 256-entry decode LUT.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Candidate 64-byte ASCII character set.
    ///
    /// # Returns
    ///
    /// - `Option<[u8; DECODE_LUT_LEN]>` - Byte-to-index table if all 64 bytes are unique.
    #[inline(always)]
    pub(crate) fn build_ascii_decode_lut_exact(bytes: &[u8]) -> Option<[u8; DECODE_LUT_LEN]> {
        let mut lut: [u8; DECODE_LUT_LEN] = [INVALID_DECODE_VAL; DECODE_LUT_LEN];
        for (idx, &byte) in bytes.iter().enumerate() {
            let slot: &mut u8 = &mut lut[byte as usize];
            if *slot != INVALID_DECODE_VAL {
                return None;
            }
            *slot = idx as u8;
        }
        Some(lut)
    }

    /// Validates an arbitrary-length ASCII charset and builds a collision-free `usize` decode LUT.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Candidate ASCII character set bytes.
    ///
    /// # Returns
    ///
    /// - `Option<[usize; DECODE_LUT_LEN]>` - Byte-to-first-index table if exactly 64 unique bytes exist.
    pub(crate) fn build_ascii_decode_lut_general(bytes: &[u8]) -> Option<[usize; DECODE_LUT_LEN]> {
        if bytes.len() < CHARSET_LEN {
            return None;
        }
        let mut lut: [usize; DECODE_LUT_LEN] = [INVALID_DECODE_INDEX; DECODE_LUT_LEN];
        let mut unique_count: usize = 0;
        for (idx, &byte) in bytes.iter().enumerate() {
            let slot: &mut usize = &mut lut[byte as usize];
            if *slot == INVALID_DECODE_INDEX {
                *slot = idx;
                unique_count += 1;
            }
        }
        if unique_count == CHARSET_LEN {
            Some(lut)
        } else {
            None
        }
    }

    /// Validates a non-ASCII charset and extracts its first 64 characters for encoding.
    ///
    /// # Arguments
    ///
    /// - `&str` - Candidate Unicode character set.
    ///
    /// # Returns
    ///
    /// - `Option<[char; CHARSET_LEN]>` - First 64 characters if the charset has exactly 64 unique characters.
    pub(crate) fn build_unicode_encode_table(charset: &str) -> Option<[char; CHARSET_LEN]> {
        let mut occupied: [bool; UNICODE_HASH_SLOTS] = [false; UNICODE_HASH_SLOTS];
        let mut keys: [char; UNICODE_HASH_SLOTS] = [NULL_CHAR; UNICODE_HASH_SLOTS];
        let mut table: [char; CHARSET_LEN] = [NULL_CHAR; CHARSET_LEN];
        let mut unique_count: usize = 0;
        for (total_count, ch) in charset.chars().enumerate() {
            if total_count < CHARSET_LEN {
                table[total_count] = ch;
            }
            let mut slot: usize =
                (((ch as u32).wrapping_mul(UNICODE_HASH_MULT)) >> 25) as usize & UNICODE_HASH_MASK;
            loop {
                if !occupied[slot] {
                    if unique_count == CHARSET_LEN {
                        return None;
                    }
                    occupied[slot] = true;
                    keys[slot] = ch;
                    unique_count += 1;
                    break;
                }
                if keys[slot] == ch {
                    break;
                }
                slot = (slot + 1) & UNICODE_HASH_MASK;
            }
        }
        if unique_count == CHARSET_LEN {
            Some(table)
        } else {
            None
        }
    }

    /// Validates a non-ASCII charset and builds a stack open-addressed lookup table for decoding.
    ///
    /// # Arguments
    ///
    /// - `&str` - Candidate Unicode character set.
    ///
    /// # Returns
    ///
    /// - `Option<[(char, usize); UNICODE_HASH_SLOTS]>` - Hash table mapping unique chars to first positions.
    pub(crate) fn build_unicode_decode_table(
        charset: &str,
    ) -> Option<[(char, usize); UNICODE_HASH_SLOTS]> {
        let mut table: [(char, usize); UNICODE_HASH_SLOTS] =
            [(NULL_CHAR, UNICODE_EMPTY_SLOT); UNICODE_HASH_SLOTS];
        let mut unique_count: usize = 0;
        for (pos, ch) in charset.chars().enumerate() {
            let mut slot: usize =
                (((ch as u32).wrapping_mul(UNICODE_HASH_MULT)) >> 25) as usize & UNICODE_HASH_MASK;
            loop {
                let entry: &mut (char, usize) = &mut table[slot];
                if entry.1 == UNICODE_EMPTY_SLOT {
                    if unique_count == CHARSET_LEN {
                        return None;
                    }
                    *entry = (ch, pos);
                    unique_count += 1;
                    break;
                }
                if entry.0 == ch {
                    break;
                }
                slot = (slot + 1) & UNICODE_HASH_MASK;
            }
        }
        if unique_count == CHARSET_LEN {
            Some(table)
        } else {
            None
        }
    }

    /// Sets the character set for encoding/decoding operations.
    ///
    /// # Arguments
    ///
    /// - `&'b str` - The character set to use.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Self reference for method chaining.
    #[inline(always)]
    pub fn charset<'b>(&mut self, charset: &'b str) -> &mut Self
    where
        'b: 'a,
    {
        if !self.0.is_empty() {
            return self;
        }
        self.0 = charset;
        self
    }

    /// Encodes input string using current charset.
    ///
    /// # Arguments
    ///
    /// - `&str` - The string to encode.
    ///
    /// # Returns
    ///
    /// - `Result<String, EncodeError>` - Encoding result.
    #[inline(always)]
    pub fn encode(&self, encode_str: &str) -> Result<String, EncodeError> {
        Encode::execute(self.0, encode_str)
    }

    /// Decodes input string using current charset.
    ///
    /// # Arguments
    ///
    /// - `&str` - The string to decode.
    ///
    /// # Returns
    ///
    /// - `Result<String, DecodeError>` - Decoding result.
    #[inline(always)]
    pub fn decode(&self, decode_str: &str) -> Result<String, DecodeError> {
        Decode::execute(self.0, decode_str)
    }
}