### Convenience Function to Load VPK Source: https://context7.com/roman901/vpk-rs/llms.txt Provides a simplified API for loading VPK files using a module-level function. This function takes a file path and returns a VPK struct. It's a convenient alternative to direct `VPK::read`. The output iterates through and prints all filenames found in the archive. ```rust fn main() -> Result<(), vpk::Error> { // Alternative way to load a VPK file let vpk_file = vpk::from_path("pak01_dir.vpk")?; // Iterate through all files in the archive for filename in vpk_file.tree.keys() { println!("Found file: {}", filename); } Ok(()) } ``` -------------------------------- ### Load and Parse VPK Archive Source: https://context7.com/roman901/vpk-rs/llms.txt Loads a VPK directory file from the filesystem and parses its structure. It returns a VPK struct containing the header information and the file tree. Dependencies include the `vpk` crate. Outputs include VPK version, tree length, and total file count, with optional V2 header details. ```rust use vpk::VPK; fn main() -> Result<(), vpk::Error> { // Load a VPK directory file let vpk_file = VPK::read("pak01_dir.vpk")?; // Access header information println!("VPK Version: {}", vpk_file.header.version); println!("Tree Length: {}", vpk_file.header.tree_length); println!("Total Files: {}", vpk_file.tree.len()); // Check for V2 header extensions if let Some(header_v2) = &vpk_file.header_v2 { println!("Embed Chunk Length: {}", header_v2.embed_chunk_length); println!("Has Checksums: {}", vpk_file.header_v2_checksum.is_some()); } Ok(()) } ``` -------------------------------- ### Extract All Files from VPK Archive to Directory Source: https://context7.com/roman901/vpk-rs/llms.txt Provides a command-line utility to extract all files from a specified VPK archive to a target directory. It preserves the original directory structure and handles the creation of necessary parent directories. Dependencies include 'vpk', 'std::env', 'std::fs', and 'std::io'. It takes two command-line arguments: the path to the VPK directory file and the path to the export directory. ```rust use vpk; use std::env; use std::fs::{self, File}; use std::io::{Read, Write}; use std::path::Path; fn main() -> std::io::Result<()> { let args: Vec<_> = env::args().collect(); if args.len() != 3 { panic!("Usage: extract "); } // Verify destination directory exists let export_path = Path::new(&args[2]); if !export_path.is_dir() { panic!("Export path is not a directory or doesn't exist"); } let mut vpk_file = match vpk::from_path(&args[1]) { Ok(vpk) => vpk, Err(e) => panic!("Error opening file {}: {}", &args[1], e), }; // Extract each file for (filename, vpk_entry) in vpk_file.tree.iter_mut() { println!("Extracting {} (archive index: {})...", filename, vpk_entry.dir_entry.archive_index); let file_path = Path::new(filename); // Create parent directories if let Some(parent) = file_path.parent() { fs::create_dir_all(export_path.join(parent))?; } // Read file data let mut buf = Vec::new(); vpk_entry.reader()?.read_to_end(&mut buf)?; // Write to destination let mut out_file = File::create(export_path.join(file_path))?; out_file.write_all(&buf)?; } println!("Extraction complete!"); Ok(()) } ``` -------------------------------- ### List All Files in VPK Archive Source: https://context7.com/roman901/vpk-rs/llms.txt Enumerates all files within a VPK archive by iterating through its file tree. This function takes the path to the VPK directory file as a command-line argument. It prints each file path found in the archive. Error handling is included for file loading. ```rust use vpk; use std::env; fn main() { let args: Vec<_> = env::args().collect(); if args.len() < 2 { panic!("Usage: list "); } let vpk_file = match vpk::from_path(&args[1]) { Ok(vpk) => vpk, Err(e) => panic!("Error opening file {}: {}", &args[1], e), }; // Print all file paths in the archive for file in vpk_file.tree.keys() { println!("{}", file); } // Example output: // materials/models/weapons/texture.vtf // models/weapons/gun.mdl // scripts/weapon_data.txt } ``` -------------------------------- ### Stream VPK Entry Data Incrementally with VPKEntryReader Source: https://context7.com/roman901/vpk-rs/llms.txt Demonstrates how to use VPKEntryReader to stream file data from a VPK archive in chunks rather than loading the entire file into memory. This is useful for handling large files efficiently. It requires the 'vpk' crate and standard Rust I/O traits. ```rust use vpk::VPK; use std::io::Read; fn main() -> Result<(), Box> { let vpk_file = VPK::read("pak01_dir.vpk")?; let filename = "models/large_model.mdl"; if let Some(entry) = vpk_file.tree.get(filename) { // Create a streaming reader let mut reader = entry.reader()?; // Read in chunks let mut buffer = [0u8; 4096]; let mut total_read = 0; loop { let bytes_read = reader.read(&mut buffer)?; if bytes_read == 0 { break; } total_read += bytes_read; // Process chunk here println!("Read chunk: {} bytes", bytes_read); } println!("Total bytes read: {}", total_read); } Ok(()) } ``` -------------------------------- ### Read Complete File Data from VPK Source: https://context7.com/roman901/vpk-rs/llms.txt Extracts the complete data (including preload and archive data) for a specified file entry from a VPK archive. It returns the data as a `Cow<[u8]>`. The function handles potential conversion to UTF-8 for text files, otherwise indicating binary data. Dependencies include `vpk` and `std::borrow::Cow`. ```rust use vpk::VPK; use std::borrow::Cow; fn main() -> Result<(), Box> { let vpk_file = VPK::read("pak01_dir.vpk")?; let filename = "scripts/weapon_data.txt"; if let Some(entry) = vpk_file.tree.get(filename) { // Get complete file data (preload + archive data) let data: Cow<[u8]> = entry.get()?; println!("Read {} bytes from {}", data.len(), filename); // Convert to string if it's text data if let Ok(text) = std::str::from_utf8(&data) { println!("Content:\n{}", text); } else { println!("Binary data: {} bytes", data.len()); } } Ok(()) } ``` -------------------------------- ### Handle VPK File Loading Errors Gracefully Source: https://context7.com/roman901/vpk-rs/llms.txt Illustrates how to implement robust error handling when loading VPK files. This function catches specific VPK errors like invalid signatures, unsupported versions, read errors, and malformed indexes, providing informative messages to the user. It uses the 'vpk' crate's Error enum for detailed error management. ```rust use vpk::{VPK, Error}; fn load_vpk_safe(path: &str) -> Result { match VPK::read(path) { Ok(vpk) => { println!("Successfully loaded VPK"); Ok(vpk) }, Err(Error::InvalidSignature) => { eprintln!("File is not a valid VPK archive"); Err(Error::InvalidSignature) }, Err(Error::UnsupportedVersion(v)) => { eprintln!("VPK version {} is not supported", v); Err(Error::UnsupportedVersion(v)) }, Err(Error::ReadError(e)) => { eprintln!("I/O error reading VPK: {}", e); Err(Error::ReadError(e)) }, Err(Error::MalformedIndex) => { eprintln!("VPK index is corrupted"); Err(Error::MalformedIndex) }, Err(e) => { eprintln!("Unexpected error: {}", e); Err(e) } } } fn main() { if let Ok(vpk) = load_vpk_safe("pak01_dir.vpk") { println!("Loaded {} files", vpk.tree.len()); } } ``` -------------------------------- ### Access Preloaded Data in VPK Directory Files Source: https://context7.com/roman901/vpk-rs/llms.txt Shows how to access data that is preloaded directly within the VPK directory file itself. This is beneficial for improving access times for small, frequently used files. The code iterates through VPK entries, checks for the presence of preload data, and displays information about its size and whether it's fully preloaded or split with an archive. ```rust use vpk::VPK; fn main() -> Result<(), vpk::Error> { let vpk_file = VPK::read("pak01_dir.vpk")?; for (filename, entry) in &vpk_file.tree { // Some entries have preloaded data stored in the dir file if !entry.preload_data.is_empty() { println!("File: {}", filename); println!(" Preload size: {} bytes", entry.preload_data.len()); println!(" Archive size: {} bytes", entry.dir_entry.file_length); // Files may be preload-only (archive_path is None) if entry.archive_path.is_none() { println!(" (Fully preloaded in directory file)"); } else { println!(" (Split between preload and archive)"); } } } Ok(()) } ``` -------------------------------- ### Access Individual File Entry Metadata Source: https://context7.com/roman901/vpk-rs/llms.txt Retrieves metadata for a specific file entry within a VPK archive. It uses the `tree.get()` method to find the file by its name. The output includes the file's CRC32 checksum, archive index, offset, and lengths. This is useful for inspecting file properties before extraction. ```rust use vpk::VPK; fn main() -> Result<(), vpk::Error> { let vpk_file = VPK::read("pak01_dir.vpk")?; // Look up a specific file let filename = "materials/models/weapons/texture.vtf"; if let Some(entry) = vpk_file.tree.get(filename) { println!("File: {}", filename); println!("CRC32: 0x{:08x}", entry.dir_entry.crc32); println!("Archive Index: {}", entry.dir_entry.archive_index); println!("Archive Offset: {}", entry.dir_entry.archive_offset); println!("File Length: {}", entry.dir_entry.file_length); println!("Preload Length: {}", entry.dir_entry.preload_length); // Total size is preload + file length let total_size = entry.dir_entry.preload_length as u32 + entry.dir_entry.file_length; println!("Total Size: {} bytes", total_size); } Ok(()) } ``` -------------------------------- ### Verify VPK File Integrity using CRC32 in Rust Source: https://context7.com/roman901/vpk-rs/llms.txt Verifies the integrity of a file extracted from a VPK archive by comparing its CRC32 checksum. It reads the file content into memory, retrieves the stored CRC32 from the VPK entry, and includes a placeholder for the actual CRC32 calculation and comparison. This function handles cases where the file might not be found within the VPK. ```rust use vpk::VPK; use std::io::Read; fn verify_file_integrity(vpk: &VPK, filename: &str) -> Result> { if let Some(entry) = vpk.tree.get(filename) { // Read the complete file data let mut reader = entry.reader()?; let mut data = Vec::new(); reader.read_to_end(&mut data)?; // Calculate CRC32 (using a hypothetical crc32 function) // Note: You would need to add a CRC32 crate for actual implementation let stored_crc = entry.dir_entry.crc32; println!("File: {}", filename); println!("Stored CRC32: 0x{:08x}", stored_crc); println!("Data size: {} bytes", data.len()); // In real implementation, compare calculated vs stored CRC // let calculated_crc = calculate_crc32(&data); // Ok(calculated_crc == stored_crc) Ok(true) } else { Err(format!("File not found: {}", filename).into()) } } fn main() -> Result<(), Box> { let vpk_file = VPK::read("pak01_dir.vpk")?; verify_file_integrity(&vpk_file, "materials/texture.vtf")?; Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.