runmat-snapshot 0.5.6

High-performance snapshot creator for preloading RunMat standard library
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! High-performance snapshot loader with memory mapping and caching
//!
//! Optimized for fast startup times with parallel loading, compression,
//! and integration with the RunMat runtime.

#[cfg(target_arch = "wasm32")]
use futures::executor;
use runmat_time::Instant;
#[cfg(not(target_arch = "wasm32"))]
use std::fs::File;
#[cfg(not(target_arch = "wasm32"))]
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

use anyhow::Context;
#[cfg(not(target_arch = "wasm32"))]
use memmap2::Mmap;
#[cfg(target_arch = "wasm32")]
type Mmap = ();
use parking_lot::RwLock;
#[cfg(target_arch = "wasm32")]
use runmat_filesystem;

use crate::compression::CompressionEngine;
use crate::format::*;
use crate::validation::{SnapshotValidator, ValidationConfig};
use crate::{LoadingStats, Snapshot, SnapshotConfig, SnapshotError, SnapshotResult};

fn u64_to_usize(value: u64, context: &str) -> SnapshotResult<usize> {
    usize::try_from(value).map_err(|_| SnapshotError::Configuration {
        message: format!("{context} ({value}) exceeds platform limits"),
    })
}

fn snapshot_header_size(bytes: &[u8]) -> SnapshotResult<usize> {
    if bytes.len() < 4 {
        return Err(SnapshotError::Io(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "Snapshot bytes too small to contain header size",
        )));
    }
    Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize)
}

fn snapshot_header_end(header_size: usize, overflow_message: &str) -> SnapshotResult<usize> {
    4usize
        .checked_add(header_size)
        .ok_or_else(|| SnapshotError::Configuration {
            message: overflow_message.to_string(),
        })
}

fn snapshot_data_bounds(
    header: &SnapshotHeader,
    header_size: usize,
    container_len: usize,
    overflow_message: &str,
    out_of_bounds_message: &str,
) -> SnapshotResult<(usize, usize)> {
    let data_start = if header.data_info.data_offset != 0 {
        u64_to_usize(header.data_info.data_offset, "snapshot data offset")?
    } else {
        snapshot_header_end(
            header_size,
            "Snapshot header section overflowed container bounds",
        )?
    };
    let compressed_size =
        u64_to_usize(header.data_info.compressed_size, "snapshot compressed size")?;
    let data_end =
        data_start
            .checked_add(compressed_size)
            .ok_or_else(|| SnapshotError::Configuration {
                message: overflow_message.to_string(),
            })?;

    if data_end > container_len {
        return Err(SnapshotError::Io(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            out_of_bounds_message,
        )));
    }

    Ok((data_start, data_end))
}

/// High-performance snapshot loader
pub struct SnapshotLoader {
    /// Configuration
    config: SnapshotConfig,

    /// Compression engine for decompression
    compression: CompressionEngine,

    /// Validator for integrity checks
    #[cfg(feature = "validation")]
    validator: SnapshotValidator,

    /// Memory-mapped file cache
    mmap_cache: Arc<RwLock<Vec<Mmap>>>,

    /// Loading statistics
    stats: LoadingStats,
}

/// Loader for specific snapshot format
#[cfg(not(target_arch = "wasm32"))]
struct FormatLoader {
    /// File handle
    file: File,

    /// Memory mapping (if enabled)
    mmap: Option<Mmap>,

    /// Header information
    header: SnapshotHeader,

    /// Configuration
    config: SnapshotConfig,
}

impl SnapshotLoader {
    /// Create a new snapshot loader
    pub fn new(config: SnapshotConfig) -> Self {
        let compression = CompressionEngine::new(crate::compression::CompressionConfig {
            adaptive_selection: false, // Decompression doesn't need adaptation
            prefer_speed: true,
            ..Default::default()
        });

        #[cfg(feature = "validation")]
        let validator = SnapshotValidator::with_config(ValidationConfig {
            strict_mode: false, // Don't fail on warnings during loading
            ..ValidationConfig::default()
        });

        Self {
            config,
            compression,
            #[cfg(feature = "validation")]
            validator,
            mmap_cache: Arc::new(RwLock::new(Vec::new())),
            stats: LoadingStats {
                load_time: Duration::ZERO,
                decompression_time: Duration::ZERO,
                validation_time: Duration::ZERO,
                initialization_time: Duration::ZERO,
                total_size: 0,
                compressed_size: 0,
                compression_ratio: 1.0,
                builtin_count: 0,
                cache_hit_rate: 0.0,
            },
        }
    }

    /// Load snapshot from file
    #[cfg(not(target_arch = "wasm32"))]
    pub fn load<P: AsRef<Path>>(&mut self, path: P) -> SnapshotResult<(Snapshot, LoadingStats)> {
        let start_time = Instant::now();
        log::info!("Loading snapshot from {}", path.as_ref().display());

        // Open and validate file
        let format_loader = self.open_snapshot_file(path.as_ref())?;

        // Load and decompress data
        let data = self.load_snapshot_data(&format_loader)?;

        // Deserialize snapshot
        let snapshot = self.deserialize_snapshot(&data)?;

        // Validate snapshot if enabled
        #[cfg(feature = "validation")]
        if self.config.validation_enabled {
            self.validate_snapshot(&snapshot)?;
        }

        // Initialize runtime integration
        self.initialize_runtime_integration(&snapshot)?;

        self.stats.load_time = start_time.elapsed();
        log::info!("Snapshot loaded successfully in {:?}", self.stats.load_time);

        Ok((snapshot, self.stats.clone()))
    }

    /// Load snapshot from file (not supported on wasm targets).
    #[cfg(target_arch = "wasm32")]
    pub fn load<P: AsRef<Path>>(&mut self, path: P) -> SnapshotResult<(Snapshot, LoadingStats)> {
        let start_time = Instant::now();
        let path_ref = path.as_ref();
        log::info!(
            "Loading snapshot via filesystem provider from {}",
            path_ref.display()
        );
        let bytes = executor::block_on(runmat_filesystem::read_async(path_ref))?;
        let read_duration = start_time.elapsed();

        let (snapshot, _) = self.load_from_bytes(&bytes)?;
        self.stats.load_time += read_duration;
        log::info!("Snapshot loaded successfully in {:?}", self.stats.load_time);
        Ok((snapshot, self.stats.clone()))
    }

    /// Load snapshot from an in-memory byte slice (supports wasm streaming scenarios)
    pub fn load_from_bytes(&mut self, bytes: &[u8]) -> SnapshotResult<(Snapshot, LoadingStats)> {
        let start_time = Instant::now();
        self.stats.total_size = bytes.len() as u64;

        if bytes.len() < 4 {
            return Err(SnapshotError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Byte buffer too small to contain snapshot header size",
            )));
        }

        let header_size = snapshot_header_size(bytes)?;
        let header_end = snapshot_header_end(
            header_size,
            "Snapshot header section overflowed buffer length",
        )?;
        if bytes.len() < header_end {
            return Err(SnapshotError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Byte buffer too small to contain snapshot header",
            )));
        }

        let header_data = &bytes[4..header_end];
        let header: SnapshotHeader = bincode::deserialize(header_data)
            .context("Failed to deserialize snapshot header")
            .map_err(|e| SnapshotError::Configuration {
                message: e.to_string(),
            })?;

        header.validate()?;

        let (data_start, data_end) = snapshot_data_bounds(
            &header,
            header_size,
            bytes.len(),
            "Snapshot data section overflowed buffer length",
            "Snapshot data section extends beyond provided buffer",
        )?;

        let compressed_data = &bytes[data_start..data_end];
        self.stats.compressed_size = compressed_data.len() as u64;

        let decompression_start = Instant::now();
        let decompressed = if matches!(
            header.data_info.compression.algorithm,
            CompressionAlgorithm::None
        ) {
            compressed_data.to_vec()
        } else {
            self.compression
                .decompress(compressed_data, &header.data_info.compression)?
        };
        self.stats.decompression_time = decompression_start.elapsed();

        let snapshot = self.deserialize_snapshot(&decompressed)?;

        #[cfg(feature = "validation")]
        if self.config.validation_enabled {
            self.validate_snapshot(&snapshot)?;
        }

        self.initialize_runtime_integration(&snapshot)?;

        self.stats.load_time = start_time.elapsed();
        Ok((snapshot, self.stats.clone()))
    }

    /// Load snapshot asynchronously with true async I/O for non-blocking startup
    #[cfg(not(target_arch = "wasm32"))]
    pub async fn load_async<P: AsRef<Path>>(
        &mut self,
        path: P,
    ) -> SnapshotResult<(Snapshot, LoadingStats)> {
        let start_time = Instant::now();
        let path = path.as_ref();

        // Async file opening and validation
        let file = tokio::fs::File::open(path)
            .await
            .with_context(|| format!("Failed to open snapshot file: {}", path.display()))
            .map_err(|e| SnapshotError::Configuration {
                message: e.to_string(),
            })?;

        // Get file metadata asynchronously
        let metadata = file.metadata().await.map_err(SnapshotError::Io)?;
        let file_size = metadata.len() as usize;
        self.stats.total_size = file_size as u64;

        // Read entire file asynchronously
        let mut file_contents = Vec::with_capacity(file_size);
        let mut reader = tokio::io::BufReader::new(file);
        use tokio::io::AsyncReadExt;
        reader
            .read_to_end(&mut file_contents)
            .await
            .map_err(SnapshotError::Io)?;

        // Parse header
        let header_size = snapshot_header_size(&file_contents)?;
        let header = parse_snapshot_header(&file_contents)?;

        // Validate header
        header.validate()?;

        // Extract and decompress data
        let (data_start, data_end) = snapshot_data_bounds(
            &header,
            header_size,
            file_contents.len(),
            "Snapshot data section overflowed file bounds",
            "Data section extends beyond file size",
        )?;

        let compressed_data = &file_contents[data_start..data_end];
        self.stats.compressed_size = compressed_data.len() as u64;

        // Decompress data if needed
        let decompression_start = Instant::now();
        let decompressed_data = if matches!(
            header.data_info.compression.algorithm,
            CompressionAlgorithm::None
        ) {
            compressed_data.to_vec()
        } else {
            self.compression
                .decompress(compressed_data, &header.data_info.compression)?
        };
        self.stats.decompression_time = decompression_start.elapsed();

        // Deserialize snapshot
        let snapshot = self.deserialize_snapshot(&decompressed_data)?;

        // Validate snapshot if enabled
        #[cfg(feature = "validation")]
        if self.config.validation_enabled {
            self.validate_snapshot(&snapshot)?;
        }

        // Update stats
        let load_time = start_time.elapsed();
        self.stats.load_time = load_time;
        self.stats.builtin_count = snapshot.builtins.functions.len() as u64;

        Ok((snapshot, self.stats.clone()))
    }

    #[cfg(target_arch = "wasm32")]
    pub async fn load_async<P: AsRef<Path>>(
        &mut self,
        _path: P,
    ) -> SnapshotResult<(Snapshot, LoadingStats)> {
        Err(SnapshotError::Configuration {
            message: "Asynchronous snapshot loading from files is unavailable on wasm targets"
                .to_string(),
        })
    }

    /// Open and validate snapshot file
    #[cfg(not(target_arch = "wasm32"))]
    fn open_snapshot_file(&mut self, path: &Path) -> SnapshotResult<FormatLoader> {
        let start = Instant::now();

        // Open file
        let file = File::open(path)
            .with_context(|| format!("Failed to open snapshot file: {}", path.display()))
            .map_err(|e| crate::SnapshotError::Configuration {
                message: e.to_string(),
            })?;

        // Get file metadata
        let metadata = file.metadata()?;
        let file_size = metadata.len() as usize;
        self.stats.total_size = file_size as u64;

        // Create memory mapping if enabled and file is large enough
        let mmap = if self.config.memory_mapping_enabled && file_size > 4096 {
            match unsafe { Mmap::map(&file) } {
                Ok(mmap) => {
                    log::debug!("Created memory mapping for snapshot file ({file_size} bytes)");
                    Some(mmap)
                }
                Err(e) => {
                    log::warn!("Failed to create memory mapping, falling back to regular I/O: {e}");
                    None
                }
            }
        } else {
            None
        };

        // Read and validate header
        let mut format_loader = FormatLoader {
            file,
            mmap,
            header: SnapshotHeader::new(SnapshotMetadata::current()), // Temporary
            config: self.config.clone(),
        };

        format_loader.header = format_loader.read_header()?;
        format_loader.header.validate()?;

        // Update stats
        self.stats.compressed_size = format_loader.header.data_info.compressed_size;
        self.stats.compression_ratio = format_loader.header.data_info.compressed_size as f64
            / format_loader.header.data_info.uncompressed_size as f64;

        let load_time = start.elapsed();
        log::debug!("File opened and header validated in {load_time:?}");

        Ok(format_loader)
    }

    /// Load and decompress snapshot data
    #[cfg(not(target_arch = "wasm32"))]
    fn load_snapshot_data(&mut self, format_loader: &FormatLoader) -> SnapshotResult<Vec<u8>> {
        let start = Instant::now();

        // Read compressed data
        let compressed_data = format_loader.read_data_section()?;

        // Decompress if needed
        let decompression_start = Instant::now();
        let data = if matches!(
            format_loader.header.data_info.compression.algorithm,
            CompressionAlgorithm::None
        ) {
            compressed_data
        } else {
            self.compression.decompress(
                &compressed_data,
                &format_loader.header.data_info.compression,
            )?
        };
        self.stats.decompression_time = decompression_start.elapsed();

        let load_time = start.elapsed();
        log::debug!(
            "Data loaded and decompressed in {:?} (decompression: {:?})",
            load_time,
            self.stats.decompression_time
        );

        Ok(data)
    }

    /// Deserialize snapshot from data
    fn deserialize_snapshot(&mut self, data: &[u8]) -> SnapshotResult<Snapshot> {
        let start = Instant::now();

        let snapshot: Snapshot =
            bincode::deserialize(data).map_err(|err| crate::SnapshotError::Configuration {
                message: format!("Failed to deserialize snapshot data: {err}"),
            })?;

        // Update stats
        self.stats.builtin_count = snapshot.builtins.functions.len() as u64;
        self.stats.builtin_count = snapshot.builtins.functions.len() as u64;

        let deserialize_time = start.elapsed();
        log::debug!("Snapshot deserialized in {deserialize_time:?}");
        log::debug!(
            "Builtin registry counts: names={}, functions={}",
            snapshot.builtins.name_index.len(),
            snapshot.builtins.functions.len()
        );

        Ok(snapshot)
    }

    /// Validate loaded snapshot
    #[cfg(feature = "validation")]
    fn validate_snapshot(&mut self, snapshot: &Snapshot) -> SnapshotResult<()> {
        let start = Instant::now();

        // Validate content
        let content_result = self.validator.validate_content(snapshot)?;
        if !content_result.is_ok() {
            for error in &content_result.errors {
                log::error!(
                    "Snapshot content validation error ({:?}): {}",
                    error.severity,
                    error.message
                );
            }
            for warning in &content_result.warnings {
                log::warn!("Snapshot content validation warning: {}", warning.message);
            }
            if self.config.validation_enabled {
                return Err(SnapshotError::Validation {
                    message: "Snapshot content validation failed".to_string(),
                });
            } else {
                log::warn!("Snapshot content validation failed, but continuing");
            }
        }

        // Validate compatibility
        let compat_result = self.validator.validate_compatibility(snapshot)?;
        if !compat_result.is_ok() {
            log::warn!("Snapshot compatibility issues detected");
            for warning in compat_result.warnings {
                log::warn!("Compatibility: {}", warning.message);
            }
        }

        self.stats.validation_time = start.elapsed();
        log::debug!("Snapshot validated in {:?}", self.stats.validation_time);

        Ok(())
    }

    /// Initialize runtime integration
    fn initialize_runtime_integration(&mut self, snapshot: &Snapshot) -> SnapshotResult<()> {
        let start = Instant::now();

        // Initialize builtin dispatch table
        self.initialize_builtin_dispatch(&snapshot.builtins)?;

        // Apply optimization hints
        self.apply_optimization_hints(&snapshot.optimization_hints)?;

        // Configure GC with presets
        self.configure_gc(&snapshot.gc_presets)?;

        self.stats.initialization_time = start.elapsed();
        log::debug!(
            "Runtime integration initialized in {:?}",
            self.stats.initialization_time
        );

        Ok(())
    }

    /// Initialize builtin function dispatch table
    fn initialize_builtin_dispatch(&self, registry: &crate::BuiltinRegistry) -> SnapshotResult<()> {
        // Get current builtins from runtime
        let current_builtins = runmat_builtins::builtin_functions();
        let mut dispatch_table = Vec::with_capacity(registry.functions.len());

        // Build dispatch table by matching names
        for function_meta in &registry.functions {
            if let Some(builtin) = current_builtins
                .iter()
                .find(|b| b.name == function_meta.name)
            {
                dispatch_table.push(builtin.implementation);
            } else {
                log::warn!(
                    "Builtin function '{}' not found in current runtime",
                    function_meta.name
                );
                // Use a placeholder function that returns an error
                dispatch_table.push(|_args| {
                    Box::pin(async {
                        Err(runmat_async::runtime_error(
                            "Function not available in current runtime",
                        )
                        .build())
                    })
                });
            }
        }

        // Update the registry's dispatch table
        {
            let mut table = registry.dispatch_table.write();
            *table = dispatch_table;
        }

        log::debug!(
            "Initialized dispatch table with {} functions",
            registry.functions.len()
        );
        Ok(())
    }

    /// Apply optimization hints to runtime
    fn apply_optimization_hints(&self, hints: &crate::OptimizationHints) -> SnapshotResult<()> {
        // Apply JIT hints
        for hint in &hints.jit_hints {
            log::debug!(
                "JIT hint: {} ({:?}) - expected gain: {:.1}x",
                hint.pattern,
                hint.hint_type,
                hint.expected_performance_gain
            );
            // In a full implementation, these would be passed to the JIT compiler
        }

        // Apply memory hints
        for hint in &hints.memory_hints {
            log::debug!(
                "Memory hint: {} ({:?}) - alignment: {}",
                hint.data_structure,
                hint.hint_type,
                hint.alignment
            );
            // In a full implementation, these would configure memory layout
        }

        // Apply execution hints
        for hint in &hints.execution_hints {
            log::debug!(
                "Execution hint: {} ({:?}) - frequency: {}",
                hint.pattern,
                hint.hint_type,
                hint.frequency
            );
            // In a full implementation, these would configure execution strategies
        }

        Ok(())
    }

    /// Configure GC with snapshot presets
    fn configure_gc(&self, presets: &crate::GcPresetCache) -> SnapshotResult<()> {
        if let Some(default_config) = presets.presets.get(&presets.default_preset) {
            match runmat_gc::gc_configure(default_config.clone()) {
                Ok(_) => {
                    log::debug!("GC configured with preset '{}'", presets.default_preset);
                }
                Err(e) => {
                    log::warn!("Failed to configure GC with snapshot preset: {e}");
                }
            }
        }

        Ok(())
    }

    /// Get loading statistics
    pub fn stats(&self) -> &LoadingStats {
        &self.stats
    }

    /// Clear memory-mapped file cache
    pub fn clear_cache(&mut self) {
        let mut cache = self.mmap_cache.write();
        cache.clear();
        log::debug!("Memory mapping cache cleared");
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl FormatLoader {
    /// Read snapshot header from file
    fn read_header(&mut self) -> SnapshotResult<SnapshotHeader> {
        // Check configuration for memory mapping preference and validation
        let use_mmap = self.config.memory_mapping_enabled;
        let validate_data = self.config.validation_enabled;

        if use_mmap && self.mmap.is_some() {
            // Use memory mapping
            let mmap_data = self.mmap.as_ref().unwrap();

            // Read header size (4 bytes, little-endian)
            if mmap_data.len() < 4 {
                return Err(crate::SnapshotError::Io(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    "File too small to contain header size",
                )));
            }

            let header_size =
                u32::from_le_bytes([mmap_data[0], mmap_data[1], mmap_data[2], mmap_data[3]])
                    as usize;

            // Read header data
            let header_end = snapshot_header_end(
                header_size,
                "Snapshot header section overflowed file bounds",
            )?;
            if mmap_data.len() < header_end {
                return Err(crate::SnapshotError::Io(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    "File too small to contain header",
                )));
            }

            let header_data = &mmap_data[4..header_end];
            let header: SnapshotHeader = bincode::deserialize(header_data)
                .context("Failed to deserialize header from memory map")
                .map_err(|e| crate::SnapshotError::Configuration {
                    message: e.to_string(),
                })?;

            // Validate header if configuration requires it
            if validate_data {
                header.validate()?;
            }
            Ok(header)
        } else {
            // Use regular file I/O
            let mut reader = BufReader::new(&self.file);
            reader.seek(SeekFrom::Start(0))?;

            // Read header size (4 bytes, little-endian)
            let mut size_buffer = [0u8; 4];
            reader.read_exact(&mut size_buffer)?;
            let header_size = u32::from_le_bytes(size_buffer) as usize;

            // Read header data
            let mut header_buffer = vec![0u8; header_size];
            reader.read_exact(&mut header_buffer)?;

            let header: SnapshotHeader = bincode::deserialize(&header_buffer)
                .context("Failed to deserialize header")
                .map_err(|e| crate::SnapshotError::Configuration {
                    message: e.to_string(),
                })?;

            // Validate header if configuration requires it
            if validate_data {
                header.validate()?;
            }
            Ok(header)
        }
    }

    /// Read data section from file
    fn read_data_section(&self) -> SnapshotResult<Vec<u8>> {
        let data_start = if self.header.data_info.data_offset != 0 {
            u64_to_usize(self.header.data_info.data_offset, "snapshot data offset")?
        } else {
            let header_size = bincode::serialized_size(&self.header)? as usize;
            snapshot_header_end(
                header_size,
                "Snapshot header section overflowed file bounds",
            )?
        };
        let compressed_size = u64_to_usize(
            self.header.data_info.compressed_size,
            "snapshot compressed size",
        )?;
        let data_end = data_start.checked_add(compressed_size).ok_or_else(|| {
            SnapshotError::Configuration {
                message: "Snapshot data section overflowed file bounds".to_string(),
            }
        })?;

        if let Some(ref mmap) = self.mmap {
            // Use memory mapping
            if data_end > mmap.len() {
                return Err(SnapshotError::Corrupted {
                    reason: "Data section extends beyond file".to_string(),
                });
            }

            Ok(mmap[data_start..data_end].to_vec())
        } else {
            // Use regular file I/O
            let file = &self.file;
            let mut reader = BufReader::new(file);

            reader.seek(SeekFrom::Start(data_start as u64))?;

            let mut data = vec![0u8; compressed_size];
            reader.read_exact(&mut data)?;

            Ok(data)
        }
    }
}

/// Utility functions for snapshot loading
#[cfg(not(target_arch = "wasm32"))]
impl SnapshotLoader {
    /// Preload snapshot header for quick validation
    pub fn peek_header<P: AsRef<Path>>(path: P) -> SnapshotResult<SnapshotHeader> {
        let file = File::open(path.as_ref())
            .with_context(|| format!("Failed to open snapshot file: {}", path.as_ref().display()))
            .map_err(|e| crate::SnapshotError::Configuration {
                message: e.to_string(),
            })?;

        let mut format_loader = FormatLoader {
            file,
            mmap: None,
            header: SnapshotHeader::new(SnapshotMetadata::current()),
            config: SnapshotConfig::default(),
        };

        format_loader.read_header()
    }

    /// Check if snapshot file is valid without full loading
    pub fn quick_validate<P: AsRef<Path>>(path: P) -> SnapshotResult<bool> {
        match Self::peek_header(path) {
            Ok(header) => Ok(header.validate().is_ok()),
            Err(_) => Ok(false),
        }
    }

    /// Get snapshot metadata without loading content
    pub fn get_metadata<P: AsRef<Path>>(path: P) -> SnapshotResult<SnapshotMetadata> {
        let header = Self::peek_header(path)?;
        Ok(header.metadata)
    }

    /// Estimate loading time based on snapshot header
    pub fn estimate_load_time<P: AsRef<Path>>(path: P) -> SnapshotResult<Duration> {
        let header = Self::peek_header(path)?;
        Ok(header.estimated_load_time())
    }
}

#[cfg(target_arch = "wasm32")]
impl SnapshotLoader {
    pub fn peek_header<P: AsRef<Path>>(path: P) -> SnapshotResult<SnapshotHeader> {
        let bytes = executor::block_on(runmat_filesystem::read_async(path.as_ref()))
            .map_err(SnapshotError::Io)?;
        let header = parse_snapshot_header(&bytes)?;
        header.validate()?;
        Ok(header)
    }

    pub fn quick_validate<P: AsRef<Path>>(path: P) -> SnapshotResult<bool> {
        match Self::peek_header(path) {
            Ok(header) => Ok(header.validate().is_ok()),
            Err(_) => Ok(false),
        }
    }

    pub fn get_metadata<P: AsRef<Path>>(path: P) -> SnapshotResult<SnapshotMetadata> {
        let header = Self::peek_header(path)?;
        Ok(header.metadata)
    }

    pub fn estimate_load_time<P: AsRef<Path>>(path: P) -> SnapshotResult<Duration> {
        let header = Self::peek_header(path)?;
        Ok(header.estimated_load_time())
    }
}

fn parse_snapshot_header(bytes: &[u8]) -> SnapshotResult<SnapshotHeader> {
    let header_size = snapshot_header_size(bytes)?;
    let header_end = snapshot_header_end(
        header_size,
        "Snapshot header section overflowed buffer length",
    )?;
    if bytes.len() < header_end {
        return Err(SnapshotError::Io(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "Snapshot bytes too small to contain full header",
        )));
    }
    bincode::deserialize(&bytes[4..header_end]).map_err(|e| SnapshotError::Configuration {
        message: format!("Failed to deserialize snapshot header: {e}"),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_loader_creation() {
        let config = SnapshotConfig::default();
        let loader = SnapshotLoader::new(config);
        assert_eq!(loader.stats.load_time, Duration::ZERO);
    }

    #[test]
    fn snapshot_header_end_rejects_overflow() {
        let err = snapshot_header_end(usize::MAX, "header overflow").expect_err("overflow");
        assert!(matches!(
            err,
            SnapshotError::Configuration { ref message } if message == "header overflow"
        ));
    }

    #[test]
    fn test_quick_validate_nonexistent() {
        assert!(!SnapshotLoader::quick_validate("nonexistent.snapshot").unwrap_or(true));
    }

    #[test]
    fn test_header_peek() {
        // This would require a real snapshot file
        // For now, just test that the function exists
        let result = SnapshotLoader::peek_header("nonexistent.snapshot");
        assert!(result.is_err());
    }

    #[test]
    fn test_metadata_extraction() {
        // This would require a real snapshot file
        let result = SnapshotLoader::get_metadata("nonexistent.snapshot");
        assert!(result.is_err());
    }
}