euv-core 0.57.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
use super::*;

/// Chunk-resumable LZ4 block decoding routines for `Lz4StreamDecoder`.
impl Lz4StreamDecoder {
    /// Creates a new incremental LZ4 block decoder pre-allocated for `expected_len` uncompressed bytes.
    ///
    /// # Arguments
    ///
    /// - `usize` - Exact expected uncompressed payload byte length.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized resumable LZ4 decoder.
    #[must_use]
    pub fn new(expected_len: usize) -> Self {
        Self {
            input_pos: 0,
            output_pos: 0,
            expected_len,
            output: vec![0u8; expected_len],
        }
    }

    /// Returns the number of uncompressed bytes decoded so far.
    ///
    /// # Returns
    ///
    /// - `usize` - Decoded output byte cursor.
    #[must_use]
    pub fn decoded_bytes(&self) -> usize {
        let Self { output_pos, .. } = self;
        *output_pos
    }

    /// Returns the already-decoded uncompressed prefix slice up to `decoded_bytes()`.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Decoded output prefix slice.
    #[must_use]
    pub fn decoded_slice(&self) -> &[u8] {
        let Self {
            output_pos, output, ..
        } = self;
        &output[..*output_pos]
    }

    /// Decodes LZ4 sequences from `input` until at least `max_output_bytes` are produced in this slice or the block completes.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Complete LZ4 compressed block slice.
    /// - `usize` - Soft maximum uncompressed output bytes to decode during this cooperative slice.
    ///
    /// # Returns
    ///
    /// - `Result<bool, String>` - `Ok(true)` when the entire LZ4 block has finished decoding, `Ok(false)` when paused for the next frame slice.
    pub fn decode_up_to_bytes(
        &mut self,
        input: &[u8],
        max_output_bytes: usize,
    ) -> Result<bool, String> {
        let Self {
            input_pos,
            output_pos,
            expected_len,
            output,
        } = self;
        let input_len: usize = input.len();
        let slice_start_out: usize = *output_pos;
        let slice_limit: usize = slice_start_out.saturating_add(max_output_bytes.max(1));
        while *input_pos < input_len {
            let token: u8 = input[*input_pos];
            *input_pos += 1;
            let mut lit_len: usize = usize::from(token >> 4);
            if lit_len == 15 {
                loop {
                    if *input_pos >= input_len {
                        return Err(ERR_EUVPAK_LZ4_CORRUPT.to_string());
                    }
                    let extra: u8 = input[*input_pos];
                    *input_pos += 1;
                    lit_len = lit_len
                        .checked_add(usize::from(extra))
                        .ok_or_else(|| ERR_EUVPAK_LZ4_CORRUPT.to_string())?;
                    if extra < 255 {
                        break;
                    }
                }
            }
            let lit_in_end: usize = input_pos
                .checked_add(lit_len)
                .ok_or_else(|| ERR_EUVPAK_LZ4_CORRUPT.to_string())?;
            let lit_out_end: usize = output_pos
                .checked_add(lit_len)
                .ok_or_else(|| ERR_EUVPAK_LZ4_SIZE_MISMATCH.to_string())?;
            if lit_in_end > input_len || lit_out_end > *expected_len {
                return Err(ERR_EUVPAK_LZ4_CORRUPT.to_string());
            }
            output[*output_pos..lit_out_end].copy_from_slice(&input[*input_pos..lit_in_end]);
            *input_pos = lit_in_end;
            *output_pos = lit_out_end;
            if *input_pos >= input_len {
                break;
            }
            if *input_pos + 2 > input_len {
                return Err(ERR_EUVPAK_LZ4_CORRUPT.to_string());
            }
            let offset: usize = usize::from(u16::from_le_bytes([
                input[*input_pos],
                input[*input_pos + 1],
            ]));
            *input_pos += 2;
            if offset == 0 || offset > *output_pos {
                return Err(ERR_EUVPAK_LZ4_CORRUPT.to_string());
            }
            let mut match_len: usize = usize::from(token & 0x0F) + LZ4_MIN_MATCH;
            if (token & 0x0F) == 15 {
                loop {
                    if *input_pos >= input_len {
                        return Err(ERR_EUVPAK_LZ4_CORRUPT.to_string());
                    }
                    let extra: u8 = input[*input_pos];
                    *input_pos += 1;
                    match_len = match_len
                        .checked_add(usize::from(extra))
                        .ok_or_else(|| ERR_EUVPAK_LZ4_CORRUPT.to_string())?;
                    if extra < 255 {
                        break;
                    }
                }
            }
            let match_out_end: usize = output_pos
                .checked_add(match_len)
                .ok_or_else(|| ERR_EUVPAK_LZ4_SIZE_MISMATCH.to_string())?;
            if match_out_end > *expected_len {
                return Err(ERR_EUVPAK_LZ4_SIZE_MISMATCH.to_string());
            }
            lz4_copy_match_fast(output.as_mut_slice(), *output_pos, offset, match_len);
            *output_pos = match_out_end;
            if *output_pos >= slice_limit && *input_pos < input_len {
                return Ok(false);
            }
        }
        Ok(*input_pos >= input_len)
    }

    /// Consumes the completed decoder and validates that exact `expected_len` bytes were emitted.
    ///
    /// # Returns
    ///
    /// - `Result<Vec<u8>, String>` - Validated decompressed payload buffer.
    pub fn into_output(self) -> Result<Vec<u8>, String> {
        let Self {
            output_pos,
            expected_len,
            output,
            ..
        } = self;
        if output_pos != expected_len {
            return Err(ERR_EUVPAK_LZ4_SIZE_MISMATCH.to_string());
        }
        Ok(output)
    }
}

/// Serialization routines for `EuvPakWriter`.
impl EuvPakWriter {
    /// Creates an empty `.euvpak` archive builder.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty `EuvPakWriter` ready to collect entries and mip-tails.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends a virtual asset entry to the archive and returns its 64-bit FNV-1a path hash.
    ///
    /// # Arguments
    ///
    /// - `&str` - Virtual asset path inside the archive.
    /// - `&[u8]` - Uncompressed asset payload bytes.
    /// - `EuvPakEntryKind` - Typed asset category.
    /// - `bool` - Whether LZ4 block compression is requested for this payload.
    ///
    /// # Returns
    ///
    /// - `u64` - Normalized 64-bit FNV-1a path hash for O(1) lookup.
    pub fn add_entry(
        &mut self,
        path: &str,
        bytes: &[u8],
        kind: EuvPakEntryKind,
        compress: bool,
    ) -> u64 {
        let path_hash: u64 = hash_euvpak_path(path);
        self.add_entry_hashed(path_hash, bytes, kind, compress)
    }

    /// Appends a virtual asset entry by precomputed 64-bit path hash.
    ///
    /// # Arguments
    ///
    /// - `u64` - Precomputed 64-bit FNV-1a virtual path hash.
    /// - `&[u8]` - Uncompressed asset payload bytes.
    /// - `EuvPakEntryKind` - Typed asset category.
    /// - `bool` - Whether LZ4 block compression is requested for this payload.
    ///
    /// # Returns
    ///
    /// - `u64` - Stored 64-bit path hash.
    pub fn add_entry_hashed(
        &mut self,
        path_hash: u64,
        bytes: &[u8],
        kind: EuvPakEntryKind,
        compress: bool,
    ) -> u64 {
        let Self { entries, .. } = self;
        entries.push(EuvPakPendingEntry {
            path_hash,
            kind,
            raw_bytes: bytes.to_vec(),
            compress,
        });
        path_hash
    }

    /// Appends a low-resolution texture mip-tail payload into the contiguous Mip-Tail Superblock.
    ///
    /// # Arguments
    ///
    /// - `&str` - Virtual asset path identifying the texture mip-tail.
    /// - `&[u8]` - Packed `16x16`/`32x32` mip-tail bytes.
    ///
    /// # Returns
    ///
    /// - `u64` - Normalized 64-bit FNV-1a path hash for O(1) lookup.
    pub fn add_mip_tail(&mut self, path: &str, bytes: &[u8]) -> u64 {
        let path_hash: u64 = hash_euvpak_path(path);
        self.add_mip_tail_hashed(path_hash, bytes)
    }

    /// Appends a low-resolution texture mip-tail payload by precomputed 64-bit path hash.
    ///
    /// # Arguments
    ///
    /// - `u64` - Precomputed 64-bit FNV-1a virtual path hash.
    /// - `&[u8]` - Packed `16x16`/`32x32` mip-tail bytes.
    ///
    /// # Returns
    ///
    /// - `u64` - Stored 64-bit path hash.
    pub fn add_mip_tail_hashed(&mut self, path_hash: u64, bytes: &[u8]) -> u64 {
        let Self { mip_tails, .. } = self;
        mip_tails.push((path_hash, bytes.to_vec()));
        path_hash
    }

    /// Returns the total number of queued entries including mip-tails.
    ///
    /// # Returns
    ///
    /// - `usize` - Total queued archive entry count.
    #[must_use]
    pub fn entry_count(&self) -> usize {
        let Self {
            entries, mip_tails, ..
        } = self;
        entries.len().saturating_add(mip_tails.len())
    }

    /// 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.
    ///
    /// # Returns
    ///
    /// - `Result<Vec<u8>, String>` - Complete `.euvpak` binary archive bytes.
    pub fn finish_bytes(&self) -> Result<Vec<u8>, String> {
        let Self {
            entries, mip_tails, ..
        } = self;
        let mut seen_hashes: HashSet<u64> =
            HashSet::with_capacity(entries.len().saturating_add(mip_tails.len()));
        let mut unique_mip_tails: Vec<(u64, &[u8])> = Vec::with_capacity(mip_tails.len());
        for (path_hash, payload) in mip_tails.iter().rev() {
            if seen_hashes.insert(*path_hash) {
                unique_mip_tails.push((*path_hash, payload.as_slice()));
            }
        }
        unique_mip_tails.reverse();
        let mut unique_entries: Vec<&EuvPakPendingEntry> = Vec::with_capacity(entries.len());
        for pending in entries.iter().rev() {
            if seen_hashes.insert(pending.path_hash) {
                unique_entries.push(pending);
            }
        }
        unique_entries.reverse();
        let total_entries: usize = unique_mip_tails.len().saturating_add(unique_entries.len());
        let toc_bucket_count: usize = total_entries
            .saturating_mul(2)
            .max(EUVPAK_MIN_TOC_BUCKETS)
            .next_power_of_two();
        let toc_bytes: usize = toc_bucket_count
            .checked_mul(EUVPAK_TOC_BUCKET_BYTES)
            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
        let toc_end: usize = EUVPAK_HEADER_BYTES
            .checked_add(toc_bytes)
            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
        let mut cursor: usize = align_euvpak_offset(toc_end);
        let mip_tail_start: usize = cursor;
        let mut encoded_records: Vec<EuvPakEncodedRecord> = Vec::with_capacity(total_entries);
        for (path_hash, payload) in unique_mip_tails.iter() {
            let uncompressed_crc32: u32 = euvpak_crc32(payload);
            let len_u64: u64 = payload.len() as u64;
            encoded_records.push(EuvPakEncodedRecord {
                meta: EuvPakEntryMeta::new(
                    *path_hash,
                    cursor as u64,
                    len_u64,
                    len_u64,
                    EuvPakEntryKind::TextureMipTail,
                    false,
                ),
                payload_crc32: uncompressed_crc32,
                uncompressed_crc32,
                stored_bytes: payload.to_vec(),
            });
            cursor = align_euvpak_offset(cursor.saturating_add(payload.len()));
        }
        let mip_tail_len: usize = cursor.saturating_sub(mip_tail_start);
        for pending in unique_entries.iter() {
            let uncompressed_crc32: u32 = euvpak_crc32(pending.raw_bytes.as_slice());
            let (stored_bytes, is_compressed): (Vec<u8>, bool) = if pending.compress {
                let candidate: Vec<u8> = lz4_compress_block(pending.raw_bytes.as_slice());
                if !candidate.is_empty() && candidate.len() < pending.raw_bytes.len() {
                    (candidate, true)
                } else {
                    (pending.raw_bytes.clone(), false)
                }
            } else {
                (pending.raw_bytes.clone(), false)
            };
            let payload_crc32: u32 = if is_compressed {
                euvpak_crc32(stored_bytes.as_slice())
            } else {
                uncompressed_crc32
            };
            let compressed_len: usize = stored_bytes.len();
            encoded_records.push(EuvPakEncodedRecord {
                meta: EuvPakEntryMeta::new(
                    pending.path_hash,
                    cursor as u64,
                    compressed_len as u64,
                    pending.raw_bytes.len() as u64,
                    pending.kind,
                    is_compressed,
                ),
                payload_crc32,
                uncompressed_crc32,
                stored_bytes,
            });
            cursor = align_euvpak_offset(cursor.saturating_add(compressed_len));
        }
        let mut out: Vec<u8> = vec![0u8; cursor];
        let bucket_mask: usize = toc_bucket_count - 1;
        for record in encoded_records.iter() {
            let meta: EuvPakEntryMeta = record.meta;
            let mut slot: usize = (meta.get_path_hash() as usize) & bucket_mask;
            loop {
                let base: usize = EUVPAK_HEADER_BYTES
                    .saturating_add(slot.saturating_mul(EUVPAK_TOC_BUCKET_BYTES));
                if out[base + 40] == EUVPAK_BUCKET_EMPTY {
                    out[base..base + 8].copy_from_slice(&meta.get_path_hash().to_le_bytes());
                    out[base + 8..base + 16].copy_from_slice(&meta.get_offset().to_le_bytes());
                    out[base + 16..base + 24]
                        .copy_from_slice(&meta.get_compressed_size().to_le_bytes());
                    out[base + 24..base + 32]
                        .copy_from_slice(&meta.get_uncompressed_size().to_le_bytes());
                    out[base + 32..base + 36].copy_from_slice(&record.payload_crc32.to_le_bytes());
                    out[base + 36..base + 40]
                        .copy_from_slice(&record.uncompressed_crc32.to_le_bytes());
                    out[base + 40] = EUVPAK_BUCKET_OCCUPIED;
                    out[base + 41] = meta.get_kind() as u8;
                    out[base + 42] = if meta.get_is_compressed() {
                        EUVPAK_COMPRESSION_LZ4
                    } else {
                        EUVPAK_COMPRESSION_NONE
                    };
                    break;
                }
                slot = (slot + 1) & bucket_mask;
            }
            let start: usize = meta.get_offset() as usize;
            let end: usize = start.saturating_add(record.stored_bytes.len());
            out[start..end].copy_from_slice(record.stored_bytes.as_slice());
        }
        let toc_crc32: u32 = euvpak_crc32(&out[EUVPAK_HEADER_BYTES..toc_end]);
        out[0..8].copy_from_slice(&EUVPAK_MAGIC);
        out[8..12].copy_from_slice(&EUVPAK_FORMAT_VERSION.to_le_bytes());
        out[12..16].copy_from_slice(&(total_entries as u32).to_le_bytes());
        out[16..20].copy_from_slice(&(toc_bucket_count as u32).to_le_bytes());
        out[20..24].copy_from_slice(&EUVPAK_FLAG_CRC32_ENABLED.to_le_bytes());
        out[24..32].copy_from_slice(&(EUVPAK_HEADER_BYTES as u64).to_le_bytes());
        out[32..40].copy_from_slice(&(mip_tail_start as u64).to_le_bytes());
        out[40..48].copy_from_slice(&(mip_tail_len as u64).to_le_bytes());
        let header_crc32: u32 = euvpak_crc32(&out[0..48]);
        out[48..52].copy_from_slice(&header_crc32.to_le_bytes());
        out[52..56].copy_from_slice(&toc_crc32.to_le_bytes());
        out[56..64].copy_from_slice(&(cursor as u64).to_le_bytes());
        Ok(out)
    }
}

/// Mounting, integrity verification, LZ4 decoding, and zero-allocation O(1) lookup routines for `EuvPakArchive`.
impl EuvPakArchive {
    /// Mounts an `.euvpak` archive from disk using OS memory mapping on native targets.
    ///
    /// # Arguments
    ///
    /// - `&Path` - Filesystem path to an `.euvpak` archive file.
    ///
    /// # Returns
    ///
    /// - `Result<Self, String>` - Mounted zero-copy archive or diagnostic error.
    pub fn open_mmap(path: &Path) -> Result<Self, String> {
        let mapping: EuvPakMapping = EuvPakMapping::open_mmap(path)?;
        Self::from_mapping(mapping)
    }

    /// Mounts an `.euvpak` archive from a shared in-memory `Arc<Vec<u8>>` buffer with zero copies.
    ///
    /// # Arguments
    ///
    /// - `Arc<Vec<u8>>` - Shared immutable `.euvpak` archive bytes.
    ///
    /// # Returns
    ///
    /// - `Result<Self, String>` - Mounted zero-copy archive or diagnostic error.
    pub fn from_bytes(bytes: Arc<Vec<u8>>) -> Result<Self, String> {
        let mapping: EuvPakMapping = EuvPakMapping::from_bytes(bytes);
        Self::from_mapping(mapping)
    }

    /// Validates header, CRC32 checksums, and open-addressed TOC bounds over `mapping` with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `EuvPakMapping` - Backing read-only archive byte mapping.
    ///
    /// # Returns
    ///
    /// - `Result<Self, String>` - Mounted zero-copy archive handle or structural validation error.
    pub(crate) fn from_mapping(mapping: EuvPakMapping) -> Result<Self, String> {
        let data: &[u8] = mapping.as_bytes();
        if data.len() < EUVPAK_HEADER_BYTES || data[0..8] != EUVPAK_MAGIC {
            return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
        }
        let version: u32 = read_le_u32(data, 8);
        if version != EUVPAK_FORMAT_VERSION {
            return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
        }
        let entry_count: usize = read_le_u32(data, 12) as usize;
        let toc_bucket_count: usize = read_le_u32(data, 16) as usize;
        let flags: u32 = read_le_u32(data, 20);
        let toc_offset: usize = read_le_u64(data, 24) as usize;
        let mip_start: usize = read_le_u64(data, 32) as usize;
        let mip_len: usize = read_le_u64(data, 40) as usize;
        let stored_header_crc: u32 = read_le_u32(data, 48);
        let stored_toc_crc: u32 = read_le_u32(data, 52);
        let archive_total_bytes: usize = read_le_u64(data, 56) as usize;
        if archive_total_bytes != data.len()
            || toc_offset < EUVPAK_HEADER_BYTES
            || !toc_bucket_count.is_power_of_two()
            || toc_bucket_count < EUVPAK_MIN_TOC_BUCKETS
            || entry_count >= toc_bucket_count
        {
            return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
        }
        if (flags & EUVPAK_FLAG_CRC32_ENABLED) != 0
            && euvpak_crc32(&data[0..48]) != stored_header_crc
        {
            return Err(ERR_EUVPAK_CRC_MISMATCH.to_string());
        }
        let toc_bytes: usize = toc_bucket_count
            .checked_mul(EUVPAK_TOC_BUCKET_BYTES)
            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
        let toc_end: usize = toc_offset
            .checked_add(toc_bytes)
            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
        let mip_end: usize = mip_start
            .checked_add(mip_len)
            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
        if toc_end > data.len() || mip_end > data.len() {
            return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
        }
        if (flags & EUVPAK_FLAG_CRC32_ENABLED) != 0
            && euvpak_crc32(&data[toc_offset..toc_end]) != stored_toc_crc
        {
            return Err(ERR_EUVPAK_CRC_MISMATCH.to_string());
        }
        let mut occupied_seen: usize = 0;
        for bucket_idx in 0..toc_bucket_count {
            let base: usize =
                toc_offset.saturating_add(bucket_idx.saturating_mul(EUVPAK_TOC_BUCKET_BYTES));
            if data[base + 40] == EUVPAK_BUCKET_OCCUPIED {
                let offset: usize = read_le_u64(data, base + 8) as usize;
                let compressed_size: usize = read_le_u64(data, base + 16) as usize;
                let end: usize = offset
                    .checked_add(compressed_size)
                    .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
                if end > data.len() || !offset.is_multiple_of(EUVPAK_ALIGNMENT_BYTES) {
                    return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
                }
                occupied_seen = occupied_seen.saturating_add(1);
            }
        }
        if occupied_seen != entry_count {
            return Err(ERR_EUVPAK_INVALID_ARCHIVE.to_string());
        }
        let data_start: usize = mip_end;
        let data_len: usize = data.len().saturating_sub(data_start);
        Ok(Self {
            mapping,
            entry_count,
            toc_offset,
            toc_bucket_count,
            mip_tail_range: (mip_start, mip_len),
            data_range: (data_start, data_len),
        })
    }

    /// Probes the open-addressed TOC in O(1) with zero heap allocations and returns `(meta, payload_crc32, uncompressed_crc32)`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Normalized 64-bit FNV-1a path hash.
    ///
    /// # Returns
    ///
    /// - `Option<(EuvPakEntryMeta, u32, u32)>` - Matching entry metadata and CRC32 checksums when present.
    #[must_use]
    pub(crate) fn probe_toc(&self, path_hash: u64) -> Option<(EuvPakEntryMeta, u32, u32)> {
        let Self {
            mapping,
            toc_offset,
            toc_bucket_count,
            ..
        } = self;
        let data: &[u8] = mapping.as_bytes();
        let mask: usize = toc_bucket_count.saturating_sub(1);
        let mut slot: usize = (path_hash as usize) & mask;
        for _ in 0..*toc_bucket_count {
            let base: usize =
                toc_offset.saturating_add(slot.saturating_mul(EUVPAK_TOC_BUCKET_BYTES));
            if data[base + 40] == EUVPAK_BUCKET_EMPTY {
                return None;
            }
            if read_le_u64(data, base) == path_hash {
                return Some(parse_toc_bucket(data, base));
            }
            slot = (slot + 1) & mask;
        }
        None
    }

    /// Resolves an entry by its 64-bit FNV-1a path hash in O(1) with zero allocations and zero payload copies.
    ///
    /// # Arguments
    ///
    /// - `u64` - Normalized 64-bit FNV-1a virtual path hash.
    ///
    /// # Returns
    ///
    /// - `Option<EuvPakSlice<'_>>` - Borrowed zero-copy payload view when present.
    #[must_use]
    pub fn lookup_hash(&self, path_hash: u64) -> Option<EuvPakSlice<'_>> {
        let (meta, _, _): (EuvPakEntryMeta, u32, u32) = self.probe_toc(path_hash)?;
        let Self { mapping, .. } = self;
        let start: usize = meta.get_offset() as usize;
        let end: usize = start.saturating_add(meta.get_compressed_size() as usize);
        let bytes: &[u8] = mapping.as_bytes().get(start..end)?;
        Some(EuvPakSlice {
            path_hash,
            kind: meta.get_kind(),
            uncompressed_size: meta.get_uncompressed_size(),
            is_compressed: meta.get_is_compressed(),
            bytes,
        })
    }

    /// Resolves an entry by virtual asset path string in O(1) with zero allocations and zero payload copies.
    ///
    /// # Arguments
    ///
    /// - `&str` - Virtual asset path inside the archive.
    ///
    /// # Returns
    ///
    /// - `Option<EuvPakSlice<'_>>` - Borrowed zero-copy payload view when present.
    #[must_use]
    pub fn lookup_path(&self, path: &str) -> Option<EuvPakSlice<'_>> {
        self.lookup_hash(hash_euvpak_path(path))
    }

    /// Verifies the stored payload CRC32 integrity checksum for `path_hash`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Normalized 64-bit FNV-1a virtual path hash.
    ///
    /// # Returns
    ///
    /// - `Result<bool, String>` - `Ok(true)` if the checksum matches, `Err` if entry is missing.
    pub fn verify_entry_crc(&self, path_hash: u64) -> Result<bool, String> {
        let (meta, payload_crc32, _): (EuvPakEntryMeta, u32, u32) = self
            .probe_toc(path_hash)
            .ok_or_else(|| ERR_EUVPAK_ENTRY_NOT_FOUND.to_string())?;
        let Self { mapping, .. } = self;
        let start: usize = meta.get_offset() as usize;
        let end: usize = start.saturating_add(meta.get_compressed_size() as usize);
        let bytes: &[u8] = mapping
            .as_bytes()
            .get(start..end)
            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
        Ok(euvpak_crc32(bytes) == payload_crc32)
    }

    /// Reads, CRC32-verifies, and LZ4-decompresses (when compressed) the entry identified by `path_hash`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Normalized 64-bit FNV-1a virtual path hash.
    ///
    /// # Returns
    ///
    /// - `Result<Vec<u8>, String>` - Verified uncompressed payload bytes or diagnostic error.
    pub fn read_entry_decoded(&self, path_hash: u64) -> Result<Vec<u8>, String> {
        let (meta, payload_crc32, uncompressed_crc32): (EuvPakEntryMeta, u32, u32) = self
            .probe_toc(path_hash)
            .ok_or_else(|| ERR_EUVPAK_ENTRY_NOT_FOUND.to_string())?;
        let Self { mapping, .. } = self;
        let start: usize = meta.get_offset() as usize;
        let end: usize = start.saturating_add(meta.get_compressed_size() as usize);
        let stored: &[u8] = mapping
            .as_bytes()
            .get(start..end)
            .ok_or_else(|| ERR_EUVPAK_INVALID_ARCHIVE.to_string())?;
        if euvpak_crc32(stored) != payload_crc32 {
            return Err(ERR_EUVPAK_CRC_MISMATCH.to_string());
        }
        if !meta.get_is_compressed() {
            return Ok(stored.to_vec());
        }
        let decoded: Vec<u8> = lz4_decompress_block(stored, meta.get_uncompressed_size() as usize)?;
        if euvpak_crc32(decoded.as_slice()) != uncompressed_crc32 {
            return Err(ERR_EUVPAK_CRC_MISMATCH.to_string());
        }
        Ok(decoded)
    }

    /// Reads, CRC32-verifies, and LZ4-decompresses the entry identified by virtual `path`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Virtual asset path inside the archive.
    ///
    /// # Returns
    ///
    /// - `Result<Vec<u8>, String>` - Verified uncompressed payload bytes or diagnostic error.
    pub fn read_path_decoded(&self, path: &str) -> Result<Vec<u8>, String> {
        self.read_entry_decoded(hash_euvpak_path(path))
    }

    /// Enumerates all `TextureMipTail` metadata records ordered by archive offset for sequential superblock warm-loading.
    ///
    /// # Returns
    ///
    /// - `Vec<EuvPakEntryMeta>` - Ordered list of mip-tail metadata entries.
    #[must_use]
    pub fn mip_tail_entries(&self) -> Vec<EuvPakEntryMeta> {
        let Self {
            mapping,
            toc_offset,
            toc_bucket_count,
            ..
        } = self;
        let data: &[u8] = mapping.as_bytes();
        let mut out: Vec<EuvPakEntryMeta> = Vec::new();
        for bucket_idx in 0..*toc_bucket_count {
            let base: usize =
                toc_offset.saturating_add(bucket_idx.saturating_mul(EUVPAK_TOC_BUCKET_BYTES));
            if data[base + 40] == EUVPAK_BUCKET_OCCUPIED
                && decode_euvpak_entry_kind(data[base + 41]) == EuvPakEntryKind::TextureMipTail
            {
                let (meta, _, _): (EuvPakEntryMeta, u32, u32) = parse_toc_bucket(data, base);
                out.push(meta);
            }
        }
        out.sort_by_key(|meta: &EuvPakEntryMeta| meta.get_offset());
        out
    }

    /// Enumerates every occupied TOC metadata record stored in this archive.
    ///
    /// # Returns
    ///
    /// - `Vec<EuvPakEntryMeta>` - List of all indexed archive entries.
    #[must_use]
    pub fn all_entries(&self) -> Vec<EuvPakEntryMeta> {
        let Self {
            mapping,
            entry_count,
            toc_offset,
            toc_bucket_count,
            ..
        } = self;
        let data: &[u8] = mapping.as_bytes();
        let mut out: Vec<EuvPakEntryMeta> = Vec::with_capacity(*entry_count);
        for bucket_idx in 0..*toc_bucket_count {
            let base: usize =
                toc_offset.saturating_add(bucket_idx.saturating_mul(EUVPAK_TOC_BUCKET_BYTES));
            if data[base + 40] == EUVPAK_BUCKET_OCCUPIED {
                let (meta, _, _): (EuvPakEntryMeta, u32, u32) = parse_toc_bucket(data, base);
                out.push(meta);
            }
        }
        out
    }

    /// Returns the total number of indexed entries inside this archive.
    ///
    /// # Returns
    ///
    /// - `usize` - Archive entry count.
    #[must_use]
    pub fn entry_count(&self) -> usize {
        let Self { entry_count, .. } = self;
        *entry_count
    }

    /// Returns the power-of-two bucket capacity of the open-addressed hash table TOC.
    ///
    /// # Returns
    ///
    /// - `usize` - Open-addressed TOC bucket capacity.
    #[must_use]
    pub fn toc_bucket_count(&self) -> usize {
        let Self {
            toc_bucket_count, ..
        } = self;
        *toc_bucket_count
    }

    /// Returns the contiguous Mip-Tail Superblock byte slice for instant Frame-1 mip-tail residency.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Contiguous superblock byte slice (empty when no mip-tails were packed).
    #[must_use]
    pub fn mip_tail_superblock(&self) -> &[u8] {
        let Self {
            mapping,
            mip_tail_range,
            ..
        } = self;
        let (start, len): (usize, usize) = *mip_tail_range;
        mapping
            .as_bytes()
            .get(start..start.saturating_add(len))
            .unwrap_or(&[])
    }

    /// Issues an OS `MADV_WILLNEED` hint for the contiguous Mip-Tail Superblock.
    pub fn advise_mip_tails_willneed(&self) {
        let Self {
            mapping,
            mip_tail_range,
            ..
        } = self;
        let (start, len): (usize, usize) = *mip_tail_range;
        if len > 0 {
            mapping.advise_willneed(start, len);
        }
    }

    /// Issues an OS `MADV_RANDOM` hint for the general asset payload region following the Mip-Tail Superblock.
    pub fn advise_random_access(&self) {
        let Self {
            mapping,
            data_range,
            ..
        } = self;
        let (start, len): (usize, usize) = *data_range;
        if len > 0 {
            mapping.advise_random(start, len);
        }
    }

    /// Returns `true` when the underlying archive storage uses an OS virtual memory mapping.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether OS `mmap` / `MapViewOfFile` is active.
    #[must_use]
    pub fn is_os_mapped(&self) -> bool {
        let Self { mapping, .. } = self;
        mapping.is_os_mapped()
    }
}