Skip to main content

euv_core/runtime/vfs/format/
impl.rs

1use super::*;
2
3/// Chunk-resumable LZ4 block decoding routines for `Lz4StreamDecoder`.
4impl Lz4StreamDecoder {
5    /// Creates a new incremental LZ4 block decoder pre-allocated for `expected_len` uncompressed bytes.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - Exact expected uncompressed payload byte length.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Initialized resumable LZ4 decoder.
14    #[must_use]
15    pub fn new(expected_len: usize) -> Self {
16        Self {
17            input_pos: 0,
18            output_pos: 0,
19            expected_len,
20            output: vec![0u8; expected_len],
21        }
22    }
23
24    /// Returns the number of uncompressed bytes decoded so far.
25    ///
26    /// # Returns
27    ///
28    /// - `usize` - Decoded output byte cursor.
29    #[must_use]
30    pub fn decoded_bytes(&self) -> usize {
31        let Self { output_pos, .. } = self;
32        *output_pos
33    }
34
35    /// Returns the already-decoded uncompressed prefix slice up to `decoded_bytes()`.
36    ///
37    /// # Returns
38    ///
39    /// - `&[u8]` - Decoded output prefix slice.
40    #[must_use]
41    pub fn decoded_slice(&self) -> &[u8] {
42        let Self {
43            output_pos, output, ..
44        } = self;
45        &output[..*output_pos]
46    }
47
48    /// Decodes LZ4 sequences from `input` until at least `max_output_bytes` are produced in this slice or the block completes.
49    ///
50    /// # Arguments
51    ///
52    /// - `&[u8]` - Complete LZ4 compressed block slice.
53    /// - `usize` - Soft maximum uncompressed output bytes to decode during this cooperative slice.
54    ///
55    /// # Returns
56    ///
57    /// - `Result<bool, String>` - `Ok(true)` when the entire LZ4 block has finished decoding, `Ok(false)` when paused for the next frame slice.
58    pub fn decode_up_to_bytes(
59        &mut self,
60        input: &[u8],
61        max_output_bytes: usize,
62    ) -> Result<bool, String> {
63        let Self {
64            input_pos,
65            output_pos,
66            expected_len,
67            output,
68        } = self;
69        let input_len: usize = input.len();
70        let slice_start_out: usize = *output_pos;
71        let slice_limit: usize = slice_start_out.saturating_add(max_output_bytes.max(1));
72        while *input_pos < input_len {
73            let token: u8 = input[*input_pos];
74            *input_pos += 1;
75            let mut lit_len: usize = usize::from(token >> 4);
76            if lit_len == 15 {
77                loop {
78                    if *input_pos >= input_len {
79                        return Err(ERR_EUVPAK_LZ4_CORRUPT.to_string());
80                    }
81                    let extra: u8 = input[*input_pos];
82                    *input_pos += 1;
83                    lit_len = lit_len
84                        .checked_add(usize::from(extra))
85                        .ok_or_else(|| ERR_EUVPAK_LZ4_CORRUPT.to_string())?;
86                    if extra < 255 {
87                        break;
88                    }
89                }
90            }
91            let lit_in_end: usize = input_pos
92                .checked_add(lit_len)
93                .ok_or_else(|| ERR_EUVPAK_LZ4_CORRUPT.to_string())?;
94            let lit_out_end: usize = output_pos
95                .checked_add(lit_len)
96                .ok_or_else(|| ERR_EUVPAK_LZ4_SIZE_MISMATCH.to_string())?;
97            if lit_in_end > input_len || lit_out_end > *expected_len {
98                return Err(ERR_EUVPAK_LZ4_CORRUPT.to_string());
99            }
100            output[*output_pos..lit_out_end].copy_from_slice(&input[*input_pos..lit_in_end]);
101            *input_pos = lit_in_end;
102            *output_pos = lit_out_end;
103            if *input_pos >= input_len {
104                break;
105            }
106            if *input_pos + 2 > input_len {
107                return Err(ERR_EUVPAK_LZ4_CORRUPT.to_string());
108            }
109            let offset: usize = usize::from(u16::from_le_bytes([
110                input[*input_pos],
111                input[*input_pos + 1],
112            ]));
113            *input_pos += 2;
114            if offset == 0 || offset > *output_pos {
115                return Err(ERR_EUVPAK_LZ4_CORRUPT.to_string());
116            }
117            let mut match_len: usize = usize::from(token & 0x0F) + LZ4_MIN_MATCH;
118            if (token & 0x0F) == 15 {
119                loop {
120                    if *input_pos >= input_len {
121                        return Err(ERR_EUVPAK_LZ4_CORRUPT.to_string());
122                    }
123                    let extra: u8 = input[*input_pos];
124                    *input_pos += 1;
125                    match_len = match_len
126                        .checked_add(usize::from(extra))
127                        .ok_or_else(|| ERR_EUVPAK_LZ4_CORRUPT.to_string())?;
128                    if extra < 255 {
129                        break;
130                    }
131                }
132            }
133            let match_out_end: usize = output_pos
134                .checked_add(match_len)
135                .ok_or_else(|| ERR_EUVPAK_LZ4_SIZE_MISMATCH.to_string())?;
136            if match_out_end > *expected_len {
137                return Err(ERR_EUVPAK_LZ4_SIZE_MISMATCH.to_string());
138            }
139            lz4_copy_match_fast(output.as_mut_slice(), *output_pos, offset, match_len);
140            *output_pos = match_out_end;
141            if *output_pos >= slice_limit && *input_pos < input_len {
142                return Ok(false);
143            }
144        }
145        Ok(*input_pos >= input_len)
146    }
147
148    /// Consumes the completed decoder and validates that exact `expected_len` bytes were emitted.
149    ///
150    /// # Returns
151    ///
152    /// - `Result<Vec<u8>, String>` - Validated decompressed payload buffer.
153    pub fn into_output(self) -> Result<Vec<u8>, String> {
154        let Self {
155            output_pos,
156            expected_len,
157            output,
158            ..
159        } = self;
160        if output_pos != expected_len {
161            return Err(ERR_EUVPAK_LZ4_SIZE_MISMATCH.to_string());
162        }
163        Ok(output)
164    }
165}
166
167/// Serialization routines for `EuvPakWriter`.
168impl EuvPakWriter {
169    /// Creates an empty `.euvpak` archive builder.
170    ///
171    /// # Returns
172    ///
173    /// - `Self` - Empty `EuvPakWriter` ready to collect entries and mip-tails.
174    #[must_use]
175    pub fn new() -> Self {
176        Self::default()
177    }
178
179    /// Appends a virtual asset entry to the archive and returns its 64-bit FNV-1a path hash.
180    ///
181    /// # Arguments
182    ///
183    /// - `&str` - Virtual asset path inside the archive.
184    /// - `&[u8]` - Uncompressed asset payload bytes.
185    /// - `EuvPakEntryKind` - Typed asset category.
186    /// - `bool` - Whether LZ4 block compression is requested for this payload.
187    ///
188    /// # Returns
189    ///
190    /// - `u64` - Normalized 64-bit FNV-1a path hash for O(1) lookup.
191    pub fn add_entry(
192        &mut self,
193        path: &str,
194        bytes: &[u8],
195        kind: EuvPakEntryKind,
196        compress: bool,
197    ) -> u64 {
198        let path_hash: u64 = hash_euvpak_path(path);
199        self.add_entry_hashed(path_hash, bytes, kind, compress)
200    }
201
202    /// Appends a virtual asset entry by precomputed 64-bit path hash.
203    ///
204    /// # Arguments
205    ///
206    /// - `u64` - Precomputed 64-bit FNV-1a virtual path hash.
207    /// - `&[u8]` - Uncompressed asset payload bytes.
208    /// - `EuvPakEntryKind` - Typed asset category.
209    /// - `bool` - Whether LZ4 block compression is requested for this payload.
210    ///
211    /// # Returns
212    ///
213    /// - `u64` - Stored 64-bit path hash.
214    pub fn add_entry_hashed(
215        &mut self,
216        path_hash: u64,
217        bytes: &[u8],
218        kind: EuvPakEntryKind,
219        compress: bool,
220    ) -> u64 {
221        let Self { entries, .. } = self;
222        entries.push(EuvPakPendingEntry {
223            path_hash,
224            kind,
225            raw_bytes: bytes.to_vec(),
226            compress,
227        });
228        path_hash
229    }
230
231    /// Appends a low-resolution texture mip-tail payload into the contiguous Mip-Tail Superblock.
232    ///
233    /// # Arguments
234    ///
235    /// - `&str` - Virtual asset path identifying the texture mip-tail.
236    /// - `&[u8]` - Packed `16x16`/`32x32` mip-tail bytes.
237    ///
238    /// # Returns
239    ///
240    /// - `u64` - Normalized 64-bit FNV-1a path hash for O(1) lookup.
241    pub fn add_mip_tail(&mut self, path: &str, bytes: &[u8]) -> u64 {
242        let path_hash: u64 = hash_euvpak_path(path);
243        self.add_mip_tail_hashed(path_hash, bytes)
244    }
245
246    /// Appends a low-resolution texture mip-tail payload by precomputed 64-bit path hash.
247    ///
248    /// # Arguments
249    ///
250    /// - `u64` - Precomputed 64-bit FNV-1a virtual path hash.
251    /// - `&[u8]` - Packed `16x16`/`32x32` mip-tail bytes.
252    ///
253    /// # Returns
254    ///
255    /// - `u64` - Stored 64-bit path hash.
256    pub fn add_mip_tail_hashed(&mut self, path_hash: u64, bytes: &[u8]) -> u64 {
257        let Self { mip_tails, .. } = self;
258        mip_tails.push((path_hash, bytes.to_vec()));
259        path_hash
260    }
261
262    /// Returns the total number of queued entries including mip-tails.
263    ///
264    /// # Returns
265    ///
266    /// - `usize` - Total queued archive entry count.
267    #[must_use]
268    pub fn entry_count(&self) -> usize {
269        let Self {
270            entries, mip_tails, ..
271        } = self;
272        entries.len().saturating_add(mip_tails.len())
273    }
274
275    /// Finalizes and serializes all queued entries into a 64-byte-aligned `.euvpak` binary buffer with an open-addressed FNV-1a TOC and CRC32 integrity checksums.
276    ///
277    /// # Returns
278    ///
279    /// - `Result<Vec<u8>, String>` - Complete `.euvpak` binary archive bytes.
280    pub fn finish_bytes(&self) -> Result<Vec<u8>, String> {
281        let Self {
282            entries, mip_tails, ..
283        } = self;
284        let mut seen_hashes: HashSet<u64> =
285            HashSet::with_capacity(entries.len().saturating_add(mip_tails.len()));
286        let mut unique_mip_tails: Vec<(u64, &[u8])> = Vec::with_capacity(mip_tails.len());
287        for (path_hash, payload) in mip_tails.iter().rev() {
288            if seen_hashes.insert(*path_hash) {
289                unique_mip_tails.push((*path_hash, payload.as_slice()));
290            }
291        }
292        unique_mip_tails.reverse();
293        let mut unique_entries: Vec<&EuvPakPendingEntry> = Vec::with_capacity(entries.len());
294        for pending in entries.iter().rev() {
295            if seen_hashes.insert(pending.path_hash) {
296                unique_entries.push(pending);
297            }
298        }
299        unique_entries.reverse();
300        let total_entries: usize = unique_mip_tails.len().saturating_add(unique_entries.len());
301        let toc_bucket_count: usize = total_entries
302            .saturating_mul(2)
303            .max(EUVPAK_MIN_TOC_BUCKETS)
304            .next_power_of_two();
305        let toc_bytes: usize = toc_bucket_count
306            .checked_mul(EUVPAK_TOC_BUCKET_BYTES)
307            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
308        let toc_end: usize = EUVPAK_HEADER_BYTES
309            .checked_add(toc_bytes)
310            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
311        let mut cursor: usize = align_euvpak_offset(toc_end);
312        let mip_tail_start: usize = cursor;
313        let mut encoded_records: Vec<EuvPakEncodedRecord> = Vec::with_capacity(total_entries);
314        for (path_hash, payload) in unique_mip_tails.iter() {
315            let uncompressed_crc32: u32 = euvpak_crc32(payload);
316            let len_u64: u64 = payload.len() as u64;
317            encoded_records.push(EuvPakEncodedRecord {
318                meta: EuvPakEntryMeta::new(
319                    *path_hash,
320                    cursor as u64,
321                    len_u64,
322                    len_u64,
323                    EuvPakEntryKind::TextureMipTail,
324                    false,
325                ),
326                payload_crc32: uncompressed_crc32,
327                uncompressed_crc32,
328                stored_bytes: payload.to_vec(),
329            });
330            cursor = align_euvpak_offset(cursor.saturating_add(payload.len()));
331        }
332        let mip_tail_len: usize = cursor.saturating_sub(mip_tail_start);
333        for pending in unique_entries.iter() {
334            let uncompressed_crc32: u32 = euvpak_crc32(pending.raw_bytes.as_slice());
335            let (stored_bytes, is_compressed): (Vec<u8>, bool) = if pending.compress {
336                let candidate: Vec<u8> = lz4_compress_block(pending.raw_bytes.as_slice());
337                if !candidate.is_empty() && candidate.len() < pending.raw_bytes.len() {
338                    (candidate, true)
339                } else {
340                    (pending.raw_bytes.clone(), false)
341                }
342            } else {
343                (pending.raw_bytes.clone(), false)
344            };
345            let payload_crc32: u32 = if is_compressed {
346                euvpak_crc32(stored_bytes.as_slice())
347            } else {
348                uncompressed_crc32
349            };
350            let compressed_len: usize = stored_bytes.len();
351            encoded_records.push(EuvPakEncodedRecord {
352                meta: EuvPakEntryMeta::new(
353                    pending.path_hash,
354                    cursor as u64,
355                    compressed_len as u64,
356                    pending.raw_bytes.len() as u64,
357                    pending.kind,
358                    is_compressed,
359                ),
360                payload_crc32,
361                uncompressed_crc32,
362                stored_bytes,
363            });
364            cursor = align_euvpak_offset(cursor.saturating_add(compressed_len));
365        }
366        let mut out: Vec<u8> = vec![0u8; cursor];
367        let bucket_mask: usize = toc_bucket_count - 1;
368        for record in encoded_records.iter() {
369            let meta: EuvPakEntryMeta = record.meta;
370            let mut slot: usize = (meta.get_path_hash() as usize) & bucket_mask;
371            loop {
372                let base: usize = EUVPAK_HEADER_BYTES
373                    .saturating_add(slot.saturating_mul(EUVPAK_TOC_BUCKET_BYTES));
374                if out[base + 40] == EUVPAK_BUCKET_EMPTY {
375                    out[base..base + 8].copy_from_slice(&meta.get_path_hash().to_le_bytes());
376                    out[base + 8..base + 16].copy_from_slice(&meta.get_offset().to_le_bytes());
377                    out[base + 16..base + 24]
378                        .copy_from_slice(&meta.get_compressed_size().to_le_bytes());
379                    out[base + 24..base + 32]
380                        .copy_from_slice(&meta.get_uncompressed_size().to_le_bytes());
381                    out[base + 32..base + 36].copy_from_slice(&record.payload_crc32.to_le_bytes());
382                    out[base + 36..base + 40]
383                        .copy_from_slice(&record.uncompressed_crc32.to_le_bytes());
384                    out[base + 40] = EUVPAK_BUCKET_OCCUPIED;
385                    out[base + 41] = meta.get_kind() as u8;
386                    out[base + 42] = if meta.get_is_compressed() {
387                        EUVPAK_COMPRESSION_LZ4
388                    } else {
389                        EUVPAK_COMPRESSION_NONE
390                    };
391                    break;
392                }
393                slot = (slot + 1) & bucket_mask;
394            }
395            let start: usize = meta.get_offset() as usize;
396            let end: usize = start.saturating_add(record.stored_bytes.len());
397            out[start..end].copy_from_slice(record.stored_bytes.as_slice());
398        }
399        let toc_crc32: u32 = euvpak_crc32(&out[EUVPAK_HEADER_BYTES..toc_end]);
400        out[0..8].copy_from_slice(&EUVPAK_MAGIC);
401        out[8..12].copy_from_slice(&EUVPAK_FORMAT_VERSION.to_le_bytes());
402        out[12..16].copy_from_slice(&(total_entries as u32).to_le_bytes());
403        out[16..20].copy_from_slice(&(toc_bucket_count as u32).to_le_bytes());
404        out[20..24].copy_from_slice(&EUVPAK_FLAG_CRC32_ENABLED.to_le_bytes());
405        out[24..32].copy_from_slice(&(EUVPAK_HEADER_BYTES as u64).to_le_bytes());
406        out[32..40].copy_from_slice(&(mip_tail_start as u64).to_le_bytes());
407        out[40..48].copy_from_slice(&(mip_tail_len as u64).to_le_bytes());
408        let header_crc32: u32 = euvpak_crc32(&out[0..48]);
409        out[48..52].copy_from_slice(&header_crc32.to_le_bytes());
410        out[52..56].copy_from_slice(&toc_crc32.to_le_bytes());
411        out[56..64].copy_from_slice(&(cursor as u64).to_le_bytes());
412        Ok(out)
413    }
414}
415
416/// Mounting, integrity verification, LZ4 decoding, and zero-allocation O(1) lookup routines for `EuvPakArchive`.
417impl EuvPakArchive {
418    /// Mounts an `.euvpak` archive from disk using OS memory mapping on native targets.
419    ///
420    /// # Arguments
421    ///
422    /// - `&Path` - Filesystem path to an `.euvpak` archive file.
423    ///
424    /// # Returns
425    ///
426    /// - `Result<Self, String>` - Mounted zero-copy archive or diagnostic error.
427    pub fn open_mmap(path: &Path) -> Result<Self, String> {
428        let mapping: EuvPakMapping = EuvPakMapping::open_mmap(path)?;
429        Self::from_mapping(mapping)
430    }
431
432    /// Mounts an `.euvpak` archive from a shared in-memory `Arc<Vec<u8>>` buffer with zero copies.
433    ///
434    /// # Arguments
435    ///
436    /// - `Arc<Vec<u8>>` - Shared immutable `.euvpak` archive bytes.
437    ///
438    /// # Returns
439    ///
440    /// - `Result<Self, String>` - Mounted zero-copy archive or diagnostic error.
441    pub fn from_bytes(bytes: Arc<Vec<u8>>) -> Result<Self, String> {
442        let mapping: EuvPakMapping = EuvPakMapping::from_bytes(bytes);
443        Self::from_mapping(mapping)
444    }
445
446    /// Validates header, CRC32 checksums, and open-addressed TOC bounds over `mapping` with zero heap allocations.
447    ///
448    /// # Arguments
449    ///
450    /// - `EuvPakMapping` - Backing read-only archive byte mapping.
451    ///
452    /// # Returns
453    ///
454    /// - `Result<Self, String>` - Mounted zero-copy archive handle or structural validation error.
455    pub(crate) fn from_mapping(mapping: EuvPakMapping) -> Result<Self, String> {
456        let data: &[u8] = mapping.as_bytes();
457        if data.len() < EUVPAK_HEADER_BYTES || data[0..8] != EUVPAK_MAGIC {
458            return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
459        }
460        let version: u32 = read_le_u32(data, 8);
461        if version != EUVPAK_FORMAT_VERSION {
462            return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
463        }
464        let entry_count: usize = read_le_u32(data, 12) as usize;
465        let toc_bucket_count: usize = read_le_u32(data, 16) as usize;
466        let flags: u32 = read_le_u32(data, 20);
467        let toc_offset: usize = read_le_u64(data, 24) as usize;
468        let mip_start: usize = read_le_u64(data, 32) as usize;
469        let mip_len: usize = read_le_u64(data, 40) as usize;
470        let stored_header_crc: u32 = read_le_u32(data, 48);
471        let stored_toc_crc: u32 = read_le_u32(data, 52);
472        let archive_total_bytes: usize = read_le_u64(data, 56) as usize;
473        if archive_total_bytes != data.len()
474            || toc_offset < EUVPAK_HEADER_BYTES
475            || !toc_bucket_count.is_power_of_two()
476            || toc_bucket_count < EUVPAK_MIN_TOC_BUCKETS
477            || entry_count >= toc_bucket_count
478        {
479            return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
480        }
481        if (flags & EUVPAK_FLAG_CRC32_ENABLED) != 0
482            && euvpak_crc32(&data[0..48]) != stored_header_crc
483        {
484            return Err(ERR_EUVPAK_CRC_MISMATCH.to_string());
485        }
486        let toc_bytes: usize = toc_bucket_count
487            .checked_mul(EUVPAK_TOC_BUCKET_BYTES)
488            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
489        let toc_end: usize = toc_offset
490            .checked_add(toc_bytes)
491            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
492        let mip_end: usize = mip_start
493            .checked_add(mip_len)
494            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
495        if toc_end > data.len() || mip_end > data.len() {
496            return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
497        }
498        if (flags & EUVPAK_FLAG_CRC32_ENABLED) != 0
499            && euvpak_crc32(&data[toc_offset..toc_end]) != stored_toc_crc
500        {
501            return Err(ERR_EUVPAK_CRC_MISMATCH.to_string());
502        }
503        let mut occupied_seen: usize = 0;
504        for bucket_idx in 0..toc_bucket_count {
505            let base: usize =
506                toc_offset.saturating_add(bucket_idx.saturating_mul(EUVPAK_TOC_BUCKET_BYTES));
507            if data[base + 40] == EUVPAK_BUCKET_OCCUPIED {
508                let offset: usize = read_le_u64(data, base + 8) as usize;
509                let compressed_size: usize = read_le_u64(data, base + 16) as usize;
510                let end: usize = offset
511                    .checked_add(compressed_size)
512                    .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
513                if end > data.len() || !offset.is_multiple_of(EUVPAK_ALIGNMENT_BYTES) {
514                    return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
515                }
516                occupied_seen = occupied_seen.saturating_add(1);
517            }
518        }
519        if occupied_seen != entry_count {
520            return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
521        }
522        let data_start: usize = mip_end;
523        let data_len: usize = data.len().saturating_sub(data_start);
524        Ok(Self {
525            mapping,
526            entry_count,
527            toc_offset,
528            toc_bucket_count,
529            mip_tail_range: (mip_start, mip_len),
530            data_range: (data_start, data_len),
531        })
532    }
533
534    /// Probes the open-addressed TOC in O(1) with zero heap allocations and returns `(meta, payload_crc32, uncompressed_crc32)`.
535    ///
536    /// # Arguments
537    ///
538    /// - `u64` - Normalized 64-bit FNV-1a path hash.
539    ///
540    /// # Returns
541    ///
542    /// - `Option<(EuvPakEntryMeta, u32, u32)>` - Matching entry metadata and CRC32 checksums when present.
543    #[must_use]
544    pub(crate) fn probe_toc(&self, path_hash: u64) -> Option<(EuvPakEntryMeta, u32, u32)> {
545        let Self {
546            mapping,
547            toc_offset,
548            toc_bucket_count,
549            ..
550        } = self;
551        let data: &[u8] = mapping.as_bytes();
552        let mask: usize = toc_bucket_count.saturating_sub(1);
553        let mut slot: usize = (path_hash as usize) & mask;
554        for _ in 0..*toc_bucket_count {
555            let base: usize =
556                toc_offset.saturating_add(slot.saturating_mul(EUVPAK_TOC_BUCKET_BYTES));
557            if data[base + 40] == EUVPAK_BUCKET_EMPTY {
558                return None;
559            }
560            if read_le_u64(data, base) == path_hash {
561                return Some(parse_toc_bucket(data, base));
562            }
563            slot = (slot + 1) & mask;
564        }
565        None
566    }
567
568    /// Resolves an entry by its 64-bit FNV-1a path hash in O(1) with zero allocations and zero payload copies.
569    ///
570    /// # Arguments
571    ///
572    /// - `u64` - Normalized 64-bit FNV-1a virtual path hash.
573    ///
574    /// # Returns
575    ///
576    /// - `Option<EuvPakSlice<'_>>` - Borrowed zero-copy payload view when present.
577    #[must_use]
578    pub fn lookup_hash(&self, path_hash: u64) -> Option<EuvPakSlice<'_>> {
579        let (meta, _, _): (EuvPakEntryMeta, u32, u32) = self.probe_toc(path_hash)?;
580        let Self { mapping, .. } = self;
581        let start: usize = meta.get_offset() as usize;
582        let end: usize = start.saturating_add(meta.get_compressed_size() as usize);
583        let bytes: &[u8] = mapping.as_bytes().get(start..end)?;
584        Some(EuvPakSlice {
585            path_hash,
586            kind: meta.get_kind(),
587            uncompressed_size: meta.get_uncompressed_size(),
588            is_compressed: meta.get_is_compressed(),
589            bytes,
590        })
591    }
592
593    /// Resolves an entry by virtual asset path string in O(1) with zero allocations and zero payload copies.
594    ///
595    /// # Arguments
596    ///
597    /// - `&str` - Virtual asset path inside the archive.
598    ///
599    /// # Returns
600    ///
601    /// - `Option<EuvPakSlice<'_>>` - Borrowed zero-copy payload view when present.
602    #[must_use]
603    pub fn lookup_path(&self, path: &str) -> Option<EuvPakSlice<'_>> {
604        self.lookup_hash(hash_euvpak_path(path))
605    }
606
607    /// Verifies the stored payload CRC32 integrity checksum for `path_hash`.
608    ///
609    /// # Arguments
610    ///
611    /// - `u64` - Normalized 64-bit FNV-1a virtual path hash.
612    ///
613    /// # Returns
614    ///
615    /// - `Result<bool, String>` - `Ok(true)` if the checksum matches, `Err` if entry is missing.
616    pub fn verify_entry_crc(&self, path_hash: u64) -> Result<bool, String> {
617        let (meta, payload_crc32, _): (EuvPakEntryMeta, u32, u32) = self
618            .probe_toc(path_hash)
619            .ok_or_else(|| ERR_EUVPAK_ENTRY_NOT_FOUND.to_string())?;
620        let Self { mapping, .. } = self;
621        let start: usize = meta.get_offset() as usize;
622        let end: usize = start.saturating_add(meta.get_compressed_size() as usize);
623        let bytes: &[u8] = mapping
624            .as_bytes()
625            .get(start..end)
626            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
627        Ok(euvpak_crc32(bytes) == payload_crc32)
628    }
629
630    /// Reads, CRC32-verifies, and LZ4-decompresses (when compressed) the entry identified by `path_hash`.
631    ///
632    /// # Arguments
633    ///
634    /// - `u64` - Normalized 64-bit FNV-1a virtual path hash.
635    ///
636    /// # Returns
637    ///
638    /// - `Result<Vec<u8>, String>` - Verified uncompressed payload bytes or diagnostic error.
639    pub fn read_entry_decoded(&self, path_hash: u64) -> Result<Vec<u8>, String> {
640        let (meta, payload_crc32, uncompressed_crc32): (EuvPakEntryMeta, u32, u32) = self
641            .probe_toc(path_hash)
642            .ok_or_else(|| ERR_EUVPAK_ENTRY_NOT_FOUND.to_string())?;
643        let Self { mapping, .. } = self;
644        let start: usize = meta.get_offset() as usize;
645        let end: usize = start.saturating_add(meta.get_compressed_size() as usize);
646        let stored: &[u8] = mapping
647            .as_bytes()
648            .get(start..end)
649            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
650        if euvpak_crc32(stored) != payload_crc32 {
651            return Err(ERR_EUVPAK_CRC_MISMATCH.to_string());
652        }
653        if !meta.get_is_compressed() {
654            return Ok(stored.to_vec());
655        }
656        let decoded: Vec<u8> = lz4_decompress_block(stored, meta.get_uncompressed_size() as usize)?;
657        if euvpak_crc32(decoded.as_slice()) != uncompressed_crc32 {
658            return Err(ERR_EUVPAK_CRC_MISMATCH.to_string());
659        }
660        Ok(decoded)
661    }
662
663    /// Reads, CRC32-verifies, and LZ4-decompresses the entry identified by virtual `path`.
664    ///
665    /// # Arguments
666    ///
667    /// - `&str` - Virtual asset path inside the archive.
668    ///
669    /// # Returns
670    ///
671    /// - `Result<Vec<u8>, String>` - Verified uncompressed payload bytes or diagnostic error.
672    pub fn read_path_decoded(&self, path: &str) -> Result<Vec<u8>, String> {
673        self.read_entry_decoded(hash_euvpak_path(path))
674    }
675
676    /// Enumerates all `TextureMipTail` metadata records ordered by archive offset for sequential superblock warm-loading.
677    ///
678    /// # Returns
679    ///
680    /// - `Vec<EuvPakEntryMeta>` - Ordered list of mip-tail metadata entries.
681    #[must_use]
682    pub fn mip_tail_entries(&self) -> Vec<EuvPakEntryMeta> {
683        let Self {
684            mapping,
685            toc_offset,
686            toc_bucket_count,
687            ..
688        } = self;
689        let data: &[u8] = mapping.as_bytes();
690        let mut out: Vec<EuvPakEntryMeta> = Vec::new();
691        for bucket_idx in 0..*toc_bucket_count {
692            let base: usize =
693                toc_offset.saturating_add(bucket_idx.saturating_mul(EUVPAK_TOC_BUCKET_BYTES));
694            if data[base + 40] == EUVPAK_BUCKET_OCCUPIED
695                && decode_euvpak_entry_kind(data[base + 41]) == EuvPakEntryKind::TextureMipTail
696            {
697                let (meta, _, _): (EuvPakEntryMeta, u32, u32) = parse_toc_bucket(data, base);
698                out.push(meta);
699            }
700        }
701        out.sort_by_key(|meta: &EuvPakEntryMeta| meta.get_offset());
702        out
703    }
704
705    /// Enumerates every occupied TOC metadata record stored in this archive.
706    ///
707    /// # Returns
708    ///
709    /// - `Vec<EuvPakEntryMeta>` - List of all indexed archive entries.
710    #[must_use]
711    pub fn all_entries(&self) -> Vec<EuvPakEntryMeta> {
712        let Self {
713            mapping,
714            entry_count,
715            toc_offset,
716            toc_bucket_count,
717            ..
718        } = self;
719        let data: &[u8] = mapping.as_bytes();
720        let mut out: Vec<EuvPakEntryMeta> = Vec::with_capacity(*entry_count);
721        for bucket_idx in 0..*toc_bucket_count {
722            let base: usize =
723                toc_offset.saturating_add(bucket_idx.saturating_mul(EUVPAK_TOC_BUCKET_BYTES));
724            if data[base + 40] == EUVPAK_BUCKET_OCCUPIED {
725                let (meta, _, _): (EuvPakEntryMeta, u32, u32) = parse_toc_bucket(data, base);
726                out.push(meta);
727            }
728        }
729        out
730    }
731
732    /// Returns the total number of indexed entries inside this archive.
733    ///
734    /// # Returns
735    ///
736    /// - `usize` - Archive entry count.
737    #[must_use]
738    pub fn entry_count(&self) -> usize {
739        let Self { entry_count, .. } = self;
740        *entry_count
741    }
742
743    /// Returns the power-of-two bucket capacity of the open-addressed hash table TOC.
744    ///
745    /// # Returns
746    ///
747    /// - `usize` - Open-addressed TOC bucket capacity.
748    #[must_use]
749    pub fn toc_bucket_count(&self) -> usize {
750        let Self {
751            toc_bucket_count, ..
752        } = self;
753        *toc_bucket_count
754    }
755
756    /// Returns the contiguous Mip-Tail Superblock byte slice for instant Frame-1 mip-tail residency.
757    ///
758    /// # Returns
759    ///
760    /// - `&[u8]` - Contiguous superblock byte slice (empty when no mip-tails were packed).
761    #[must_use]
762    pub fn mip_tail_superblock(&self) -> &[u8] {
763        let Self {
764            mapping,
765            mip_tail_range,
766            ..
767        } = self;
768        let (start, len): (usize, usize) = *mip_tail_range;
769        mapping
770            .as_bytes()
771            .get(start..start.saturating_add(len))
772            .unwrap_or(&[])
773    }
774
775    /// Issues an OS `MADV_WILLNEED` hint for the contiguous Mip-Tail Superblock.
776    pub fn advise_mip_tails_willneed(&self) {
777        let Self {
778            mapping,
779            mip_tail_range,
780            ..
781        } = self;
782        let (start, len): (usize, usize) = *mip_tail_range;
783        if len > 0 {
784            mapping.advise_willneed(start, len);
785        }
786    }
787
788    /// Issues an OS `MADV_RANDOM` hint for the general asset payload region following the Mip-Tail Superblock.
789    pub fn advise_random_access(&self) {
790        let Self {
791            mapping,
792            data_range,
793            ..
794        } = self;
795        let (start, len): (usize, usize) = *data_range;
796        if len > 0 {
797            mapping.advise_random(start, len);
798        }
799    }
800
801    /// Returns `true` when the underlying archive storage uses an OS virtual memory mapping.
802    ///
803    /// # Returns
804    ///
805    /// - `bool` - Whether OS `mmap` / `MapViewOfFile` is active.
806    #[must_use]
807    pub fn is_os_mapped(&self) -> bool {
808        let Self { mapping, .. } = self;
809        mapping.is_os_mapped()
810    }
811}