euv-core 0.55.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Builds the 4x256 slice-by-4 IEEE 802.3 CRC32 lookup tables at compile time.
///
/// # Returns
///
/// - `[[u32; 256]; 4]` - Precomputed slice-by-4 CRC32 tables.
#[must_use]
pub(crate) const fn build_euvpak_crc32_tables() -> [[u32; 256]; 4] {
    let mut tables: [[u32; 256]; 4] = [[0u32; 256]; 4];
    let mut idx: usize = 0;
    while idx < 256 {
        let mut crc: u32 = idx as u32;
        let mut bit: usize = 0;
        while bit < 8 {
            if (crc & 1) != 0 {
                crc = (crc >> 1) ^ EUVPAK_CRC32_POLY;
            } else {
                crc >>= 1;
            }
            bit += 1;
        }
        tables[0][idx] = crc;
        idx += 1;
    }
    let mut slice_idx: usize = 1;
    while slice_idx < 4 {
        let mut entry: usize = 0;
        while entry < 256 {
            let prev: u32 = tables[slice_idx - 1][entry];
            tables[slice_idx][entry] = (prev >> 8) ^ tables[0][(prev & 0xFF) as usize];
            entry += 1;
        }
        slice_idx += 1;
    }
    tables
}

/// Incrementally updates a running IEEE 802.3 CRC32 state over `bytes` using slice-by-4 table acceleration.
///
/// # Arguments
///
/// - `u32` - Previous raw CRC32 accumulator (start with `0xFFFF_FFFF`).
/// - `&[u8]` - Next input byte chunk.
///
/// # Returns
///
/// - `u32` - Updated raw CRC32 accumulator (bitwise-invert `!crc` to finalize).
#[must_use]
pub(crate) fn euvpak_crc32_update(mut crc: u32, bytes: &[u8]) -> u32 {
    let (chunks, remainder): (&[[u8; 4]], &[u8]) = bytes.as_chunks::<4>();
    for chunk in chunks {
        crc ^= u32::from_le_bytes(*chunk);
        crc = EUVPAK_CRC32_TABLES[3][(crc & 0xFF) as usize]
            ^ EUVPAK_CRC32_TABLES[2][((crc >> 8) & 0xFF) as usize]
            ^ EUVPAK_CRC32_TABLES[1][((crc >> 16) & 0xFF) as usize]
            ^ EUVPAK_CRC32_TABLES[0][(crc >> 24) as usize];
    }
    for &byte_val in remainder {
        let table_idx: usize = ((crc ^ u32::from(byte_val)) & 0xFF) as usize;
        crc = (crc >> 8) ^ EUVPAK_CRC32_TABLES[0][table_idx];
    }
    crc
}

/// Computes an IEEE 802.3 CRC32 checksum using slice-by-4 lookup table acceleration.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice to checksum.
///
/// # Returns
///
/// - `u32` - Computed CRC32 digest.
#[must_use]
pub fn euvpak_crc32(bytes: &[u8]) -> u32 {
    !euvpak_crc32_update(0xFFFF_FFFF, bytes)
}

/// Computes the canonical 64-bit FNV-1a hash of a normalized virtual asset path (`\` converted to `/`, leading `/` stripped).
///
/// # Arguments
///
/// - `&str` - Virtual asset path inside an `.euvpak` archive.
///
/// # Returns
///
/// - `u64` - Deterministic 64-bit FNV-1a path hash.
#[must_use]
pub fn hash_euvpak_path(path: &str) -> u64 {
    let trimmed: &str = path.trim_start_matches(['/', '\\']);
    let mut hash: u64 = EUVPAK_FNV1A_OFFSET;
    for byte in trimmed.as_bytes().iter().copied() {
        let normalized: u8 = if byte == b'\\' { b'/' } else { byte };
        hash ^= u64::from(normalized);
        hash = hash.wrapping_mul(EUVPAK_FNV1A_PRIME);
    }
    hash
}

/// Aligns `offset` upward to the next multiple of `EUVPAK_ALIGNMENT_BYTES`.
///
/// # Arguments
///
/// - `usize` - Raw byte offset.
///
/// # Returns
///
/// - `usize` - 64-byte-aligned offset greater than or equal to `offset`.
#[must_use]
pub(crate) fn align_euvpak_offset(offset: usize) -> usize {
    let mask: usize = EUVPAK_ALIGNMENT_BYTES - 1;
    (offset.saturating_add(mask)) & !mask
}

/// Decodes a raw `u8` discriminant into a typed `EuvPakEntryKind`.
///
/// # Arguments
///
/// - `u8` - Serialized entry kind discriminant byte.
///
/// # Returns
///
/// - `EuvPakEntryKind` - Matching entry kind (falls back to `RawBytes` for unknown tags).
#[must_use]
pub(crate) fn decode_euvpak_entry_kind(tag: u8) -> EuvPakEntryKind {
    match tag {
        1 => EuvPakEntryKind::MeshEuv3d,
        2 => EuvPakEntryKind::TextureMip,
        3 => EuvPakEntryKind::TextureMipTail,
        4 => EuvPakEntryKind::Audio,
        5 => EuvPakEntryKind::Font,
        6 => EuvPakEntryKind::ShaderCache,
        _ => EuvPakEntryKind::RawBytes,
    }
}

/// Reads a little-endian `u32` from `data` at `offset`.
///
/// # Arguments
///
/// - `&[u8]` - Source byte slice.
/// - `usize` - Byte offset within `data`.
///
/// # Returns
///
/// - `u32` - Decoded little-endian `u32`.
#[must_use]
pub(crate) fn read_le_u32(data: &[u8], offset: usize) -> u32 {
    u32::from_le_bytes([
        data[offset],
        data[offset + 1],
        data[offset + 2],
        data[offset + 3],
    ])
}

/// Reads a little-endian `u64` from `data` at `offset`.
///
/// # Arguments
///
/// - `&[u8]` - Source byte slice.
/// - `usize` - Byte offset within `data`.
///
/// # Returns
///
/// - `u64` - Decoded little-endian `u64`.
#[must_use]
pub(crate) fn read_le_u64(data: &[u8], offset: usize) -> u64 {
    u64::from_le_bytes([
        data[offset],
        data[offset + 1],
        data[offset + 2],
        data[offset + 3],
        data[offset + 4],
        data[offset + 5],
        data[offset + 6],
        data[offset + 7],
    ])
}

/// Computes a 12-bit LZ4 hash bucket index for 4 bytes starting at `input[pos]`.
///
/// # Arguments
///
/// - `&[u8]` - Source uncompressed byte slice.
/// - `usize` - Starting byte offset (`pos + 4 <= input.len()`).
///
/// # Returns
///
/// - `usize` - Hash table index in `0..LZ4_HASH_SIZE`.
#[must_use]
pub(crate) fn lz4_hash4(input: &[u8], pos: usize) -> usize {
    let val: u32 = read_le_u32(input, pos);
    (val.wrapping_mul(LZ4_HASH_MULTIPLIER) >> (32 - LZ4_HASH_LOG)) as usize
}

/// Appends extended LZ4 length bytes (`255` chunks plus final remainder) to `out`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Compressed output buffer.
/// - `usize` - Extra length above `15` to encode.
pub(crate) fn lz4_write_extra_len(out: &mut Vec<u8>, mut extra: usize) {
    while extra >= 255 {
        out.push(255);
        extra -= 255;
    }
    out.push(extra as u8);
}

/// Compresses `input` using a fast pure-Rust standard LZ4 block encoder.
///
/// # Arguments
///
/// - `&[u8]` - Raw uncompressed payload bytes.
///
/// # Returns
///
/// - `Vec<u8>` - Standard LZ4 block-compressed bytes.
#[must_use]
pub fn lz4_compress_block(input: &[u8]) -> Vec<u8> {
    let input_len: usize = input.len();
    if input_len == 0 {
        return Vec::new();
    }
    let mut out: Vec<u8> = Vec::with_capacity(input_len + (input_len / 255) + 16);
    if input_len < LZ4_MF_LIMIT {
        let token_lit: u8 = input_len.min(15) as u8;
        out.push(token_lit << 4);
        if input_len >= 15 {
            lz4_write_extra_len(&mut out, input_len - 15);
        }
        out.extend_from_slice(input);
        return out;
    }
    let mut hash_table: [u32; LZ4_HASH_SIZE] = [0u32; LZ4_HASH_SIZE];
    let match_limit: usize = input_len - LZ4_LAST_LITERALS;
    let mf_limit: usize = input_len - LZ4_MF_LIMIT;
    let mut anchor: usize = 0;
    let mut pos: usize = 1;
    hash_table[lz4_hash4(input, 0)] = 0;
    while pos <= mf_limit {
        let mut find_pos: usize = pos;
        let mut step: usize = 1;
        let mut search_match_nb: usize = 1 << 6;
        let mut matched_ref: Option<usize> = None;
        while find_pos <= mf_limit {
            let hash_idx: usize = lz4_hash4(input, find_pos);
            let candidate: usize = hash_table[hash_idx] as usize;
            hash_table[hash_idx] = find_pos as u32;
            if find_pos > candidate
                && find_pos - candidate <= LZ4_MAX_DISTANCE
                && read_le_u32(input, candidate) == read_le_u32(input, find_pos)
            {
                matched_ref = Some(candidate);
                break;
            }
            find_pos = find_pos.saturating_add(step);
            search_match_nb = search_match_nb.saturating_add(1);
            step = search_match_nb >> 6;
        }
        let Some(mut cand) = matched_ref else {
            break;
        };
        pos = find_pos;
        while pos > anchor && cand > 0 && input[pos - 1] == input[cand - 1] {
            pos -= 1;
            cand -= 1;
        }
        let lit_len: usize = pos - anchor;
        let offset: u16 = (pos - cand) as u16;
        let mut match_end: usize = pos + LZ4_MIN_MATCH;
        let mut cand_end: usize = cand + LZ4_MIN_MATCH;
        while match_end + 8 <= match_limit
            && read_le_u64(input, match_end) == read_le_u64(input, cand_end)
        {
            match_end += 8;
            cand_end += 8;
        }
        while match_end < match_limit && input[match_end] == input[cand_end] {
            match_end += 1;
            cand_end += 1;
        }
        let match_len_minus_min: usize = (match_end - pos) - LZ4_MIN_MATCH;
        let token_lit: u8 = lit_len.min(15) as u8;
        let token_match: u8 = match_len_minus_min.min(15) as u8;
        out.push((token_lit << 4) | token_match);
        if lit_len >= 15 {
            lz4_write_extra_len(&mut out, lit_len - 15);
        }
        out.extend_from_slice(&input[anchor..pos]);
        out.extend_from_slice(&offset.to_le_bytes());
        if match_len_minus_min >= 15 {
            lz4_write_extra_len(&mut out, match_len_minus_min - 15);
        }
        pos = match_end;
        anchor = pos;
        if pos > 2 && pos <= mf_limit {
            hash_table[lz4_hash4(input, pos - 2)] = (pos - 2) as u32;
        }
    }
    let last_lit: usize = input_len - anchor;
    let token_lit: u8 = last_lit.min(15) as u8;
    out.push(token_lit << 4);
    if last_lit >= 15 {
        lz4_write_extra_len(&mut out, last_lit - 15);
    }
    out.extend_from_slice(&input[anchor..input_len]);
    out
}

/// Copies a validated LZ4 back-reference match inside `output` using fast non-overlapping, RLE, and doubling spans.
///
/// # Arguments
///
/// - `&mut [u8]` - Destination decompressed output buffer.
/// - `usize` - Current write cursor inside `output`.
/// - `usize` - Positive backward match offset (`1..=op`).
/// - `usize` - Number of match bytes to copy (`op + match_len <= output.len()`).
pub(crate) fn lz4_copy_match_fast(output: &mut [u8], op: usize, offset: usize, match_len: usize) {
    let src: usize = op - offset;
    if offset >= match_len {
        output.copy_within(src..src + match_len, op);
        return;
    }
    if offset == 1 {
        let fill_byte: u8 = output[src];
        output[op..op + match_len].fill(fill_byte);
        return;
    }
    let mut copied: usize = 0;
    let mut span: usize = offset;
    while copied < match_len {
        let chunk: usize = span.min(match_len - copied);
        output.copy_within(src..src + chunk, op + copied);
        copied += chunk;
        span = span.saturating_mul(2);
    }
}

/// Decompresses a standard LZ4 block into an exact `expected_len` byte buffer with zero unsafe code.
///
/// # Arguments
///
/// - `&[u8]` - LZ4 block-compressed bytes.
/// - `usize` - Exact expected uncompressed output length in bytes.
///
/// # Returns
///
/// - `Result<Vec<u8>, String>` - Decompressed payload or structural validation error.
pub fn lz4_decompress_block(input: &[u8], expected_len: usize) -> Result<Vec<u8>, String> {
    if expected_len == 0 {
        if input.is_empty() {
            return Ok(Vec::new());
        }
        return Err(ERR_EUVPAK_LZ4_SIZE_MISMATCH.to_string());
    }
    let mut decoder: Lz4StreamDecoder = Lz4StreamDecoder::new(expected_len);
    let finished: bool = decoder.decode_up_to_bytes(input, usize::MAX)?;
    if !finished {
        return Err(ERR_EUVPAK_LZ4_CORRUPT.to_string());
    }
    decoder.into_output()
}

/// Parses one occupied 48-byte open-addressed TOC bucket at `base` into `(EuvPakEntryMeta, payload_crc32, uncompressed_crc32)`.
///
/// # Arguments
///
/// - `&[u8]` - Complete backing archive bytes.
/// - `usize` - Byte offset of the 48-byte TOC bucket.
///
/// # Returns
///
/// - `(EuvPakEntryMeta, u32, u32)` - Entry metadata paired with stored and uncompressed CRC32 checksums.
#[must_use]
pub(crate) fn parse_toc_bucket(data: &[u8], base: usize) -> (EuvPakEntryMeta, u32, u32) {
    let path_hash: u64 = read_le_u64(data, base);
    let offset: u64 = read_le_u64(data, base + 8);
    let compressed_size: u64 = read_le_u64(data, base + 16);
    let uncompressed_size: u64 = read_le_u64(data, base + 24);
    let payload_crc32: u32 = read_le_u32(data, base + 32);
    let uncompressed_crc32: u32 = read_le_u32(data, base + 36);
    let kind: EuvPakEntryKind = decode_euvpak_entry_kind(data[base + 41]);
    let is_compressed: bool = data[base + 42] == EUVPAK_COMPRESSION_LZ4;
    (
        EuvPakEntryMeta::new(
            path_hash,
            offset,
            compressed_size,
            uncompressed_size,
            kind,
            is_compressed,
        ),
        payload_crc32,
        uncompressed_crc32,
    )
}