### Rust Search Example Source: https://docs.rs/vpk/latest/src/vpk/entry.rs_search= Provides examples of search queries for Rust, demonstrating common search patterns like finding specific types or function signatures. ```rust Example searches: * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### Rust VPKEntry Data Access and Reader Creation Source: https://docs.rs/vpk/latest/src/vpk/entry.rs_search=u32+-%3E+bool Demonstrates how to get the data of a VPKEntry and create a VPKEntryReader. The get() method retrieves all entry data, while reader() sets up a reader that can access data from preloaded buffers or archive files. ```rust use binrw::BinRead; use std::borrow::Cow; use std::fs::File; use std::io::{Error, Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::Arc; /// An entry in the VPK. #[derive(Debug)] pub struct VPKEntry { /// [`VPKDirectoryEntry`]. pub dir_entry: VPKDirectoryEntry, /// [`PathBuf`] to archive (VPK) to read from. /// /// Is [`Some`] when data for the entry must be read from the file /// (in addition to [`Self::preload_data`]). /// /// Is [`None`] when the data must be read only from /// [`Self::preload_data`]. pub archive_path: Option>, /// Preloaded data of the entry. This is read first before reading /// from the archive. pub preload_data: Vec, } impl VPKEntry { /// Get the data of the [`VPKEntry`]. pub fn get(&self) -> Result, Error> { let mut reader = self.reader()?; let mut buf = Vec::new(); reader.read_to_end(&mut buf)?; Ok(Cow::from(buf)) } /// Create a [`VPKEntryReader`]. pub fn reader(&self) -> Result, Error> { let file = self .archive_path .as_ref() .map(|archive_path| { let mut file = File::open(archive_path.as_path())?; file.seek(SeekFrom::Start(self.dir_entry.archive_offset as u64))?; Ok::<_, Error>(file.take(self.dir_entry.file_length as u64)) }) .transpose()?; Ok(VPKEntryReader::new(&self.preload_data, file)) } } /// A reader over the [`VPKEntry`]. pub enum VPKEntryReader<'a> { /// Only preloaded data must be read. PreloadedOnly { preloaded_data: std::io::Cursor<&'a [u8]> }, /// Read from preloaded data first and then the file. PreloadAndFile { /// Length of the preloaded data. preloaded_data_len: usize, /// Number of bytes of the preloaded data read so far. preloaded_bytes_read: usize, /// Preloaded data. preloaded_data: std::io::Cursor<&'a [u8]>, /// The file that must be read. file: std::io::Take, }, /// Only the file must be read. FileOnly { file: std::io::Take }, } impl Read for VPKEntryReader<'_> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { match self { VPKEntryReader::PreloadedOnly { preloaded_data } => preloaded_data.read(buf), VPKEntryReader::PreloadAndFile { preloaded_data_len, preloaded_bytes_read, preloaded_data, file, } => { if preloaded_bytes_read >= preloaded_data_len { file.read(buf) } else { let bytes_read = preloaded_data.read(buf)?; let bytes_read = if bytes_read < buf.len() { let file_bytes_read = file.read(&mut buf[bytes_read..])?; bytes_read + file_bytes_read } else { bytes_read }; *preloaded_bytes_read += bytes_read; Ok(bytes_read) } } VPKEntryReader::FileOnly { file } => file.read(buf), } } } impl<'a> VPKEntryReader<'a> { /// Create a new [`VPKEntryReader`]. pub fn new(preloaded_data: &'a [u8], file: Option>) -> Self { match file { Some(file) => { if preloaded_data.is_empty() { Self::FileOnly { file } } else { Self::PreloadAndFile { preloaded_data_len: preloaded_data.len(), preloaded_bytes_read: 0, preloaded_data: std::io::Cursor::new(preloaded_data), file, } } } None => Self::PreloadedOnly { preloaded_data: std::io::Cursor::new(preloaded_data), }, } } } /// [`VPKEntry`] header. /// /// Information about the entry stored in the root VPK. #[derive(Debug, BinRead)] pub struct VPKDirectoryEntry { /// 32 bit CRC. pub crc32: u32, /// Number of bytes to preload from the root VPK. pub preload_length: u16, /// Index of archive to load entry from. pub archive_index: u16, /// Offset of the entry in the archive. pub archive_offset: u32, /// Length of the entry in the archive. /// /// # Note /// ``` -------------------------------- ### VPKEntry Methods: get and reader in Rust Source: https://docs.rs/vpk/latest/vpk/entry/struct.VPKEntry_search=u32+-%3E+bool Provides implementations for `get` and `reader` methods on the VPKEntry struct. The `get` method retrieves the entry's data, returning a `Cow<'_, [u8]>`. The `reader` method creates a `VPKEntryReader` for more granular access to the entry's content. Both methods return a `Result` to handle potential errors. ```rust pub fn get(&self) -> Result, Error> pub fn reader(&self) -> Result, Error> ``` -------------------------------- ### VPKEntry Methods Source: https://docs.rs/vpk/latest/vpk/entry/struct.VPKEntry Available methods for the VPKEntry struct, including getting entry data and creating readers. ```APIDOC ## impl VPKEntry ### pub fn get(&self) -> Result, Error> Get the data of the `VPKEntry`. * **Returns**: A `Result` containing a `Cow<'_, [u8]>` with the entry data on success, or an `Error` on failure. ``` ```APIDOC ### pub fn reader(&self) -> Result, Error> Create a `VPKEntryReader` to read the entry's data. * **Returns**: A `Result` containing a `VPKEntryReader` on success, or an `Error` on failure. ``` -------------------------------- ### Implement VPKEntry Get Method in Rust Source: https://docs.rs/vpk/latest/vpk/entry/struct.VPKEntry Provides a method to retrieve the data associated with a VPKEntry. It returns the data as a byte slice, potentially reading from preload data or the archive file. ```Rust pub fn get(&self) -> Result, Error> ``` -------------------------------- ### VPKEntryReader Constructor Source: https://docs.rs/vpk/latest/vpk/entry/enum.VPKEntryReader_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides a constructor function `new` for creating instances of VPKEntryReader. This function takes preloaded data and an optional file, allowing for flexible initialization based on available resources. ```rust pub fn new(preloaded_data: &'a [u8], file: Option>) -> Self ``` -------------------------------- ### VPKEntryReader Constructor Source: https://docs.rs/vpk/latest/vpk/entry/enum.VPKEntryReader_search= Creates a new VPKEntryReader instance, allowing specification of preloaded data and an optional file. ```APIDOC ## `new` Function ### Description Create a new `VPKEntryReader`. ### Method `pub fn new(preloaded_data: &'a [u8], file: Option>) -> Self` ### Parameters * `preloaded_data` (&'a [u8]) - The preloaded data slice. * `file` (Option>) - An optional `Take` object representing the file to read from. ``` -------------------------------- ### VPK Error Type Conversions (try_from) Source: https://docs.rs/vpk/latest/vpk/fn.from_path_search=u32+-%3E+bool Demonstrates various type conversion implementations for VPK related errors and structures, particularly focusing on `try_from`. ```APIDOC ## VPK Error Type Conversions (try_from) ### Description This section details the `try_from` implementations for various VPK components, illustrating how different types (`U` and `T`) are matched during conversion, often involving `u32` and `bool`. ### Method Several `try_from` methods are available: - `vpk::Error::try_from` - `vpk::entry::VPKEntryReader::try_from` - `vpk::entry::VPKEntry::try_from` - `vpk::entry::VPKDirectoryEntry::try_from` - `vpk::structs::VPKHeader::try_from` - `vpk::structs::VPKHeaderV2::try_from` - `vpk::structs::VPKHeaderV2Checksum::try_from` - `vpk::vpk::VPK::try_from` Each method follows the pattern: `U -> Result` where `u32` matches `U` and `bool` matches `T`. ### Endpoint N/A (These are library function implementations) ### Parameters N/A ### Request Example N/A ### Response #### Success Response (Result) - **T**: The target type resulting from a successful conversion. - **Error**: An error object if the conversion fails. #### Response Example N/A ``` -------------------------------- ### Rust Trait Implementation: std::error::Error for Error Source: https://docs.rs/vpk/latest/vpk/enum.Error Implements the standard `Error` trait for the vpk Error enum. This includes methods like `source` to get the underlying error cause, and deprecated methods like `description` and `cause`. ```rust impl Error for Error { fn source(&self) -> Option<&(dyn Error + 'static)> fn description(&self) -> &str fn cause(&self) -> Option<&dyn Error> fn provide<'a>(&'a self, request: &mut Request<'a>) } ``` -------------------------------- ### vpk::entry::VPKDirectoryEntry::try_from Source: https://docs.rs/vpk/latest/vpk/entry/struct.VPKDirectoryEntry_search=u32+-%3E+bool Used for creating a `VPKDirectoryEntry`, this `try_from` method adheres to the `u32` for `U` and `bool` for `T` generic mapping. ```APIDOC ## vpk::entry::VPKDirectoryEntry::try_from ### Description Converts an input into a `VPKDirectoryEntry`, specifying generic type expectations for the operation. ### Method `try_from` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ``` // Example usage (conceptual) let dir_entry_result: Result = vpk::entry::VPKDirectoryEntry::try_from(some_u32_value); ``` ### Response #### Success Response (Result) - **Ok(bool)**: Successfully created a VPK directory entry. - **Err(vpk::Error)**: Error during directory entry creation. #### Response Example ```json // Success example (conceptual) Ok(true) // Error example (conceptual) Err(vpk::Error::OutOfBounds) ``` ``` -------------------------------- ### Blanket Trait Implementations for Generic Types (Rust) Source: https://docs.rs/vpk/latest/vpk/entry/enum.VPKEntryReader_search=u32+-%3E+bool Shows blanket implementations for generic types, demonstrating how traits like `Any`, `Borrow`, `BorrowMut`, `From`, `Into`, `TryFrom`, and `TryInto` are applied. These are common utility implementations in Rust. ```rust impl Any for T impl Borrow for T impl BorrowMut for T impl From for T impl Into for T impl TryFrom for T impl TryInto for T ``` -------------------------------- ### Rust VPKEntry Structure and Methods Source: https://docs.rs/vpk/latest/src/vpk/entry.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Defines the VPKEntry struct to represent an entry in a VPK file, including its directory information, archive path, and preloaded data. It provides methods to retrieve the entry's data and create a reader for it. Dependencies include binrw, std::io, and std::path. ```rust use binrw::BinRead; use std::borrow::Cow; use std::fs::File; use std::io::{Error, Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::Arc; /// An entry in the VPK. #[derive(Debug)] pub struct VPKEntry { /// [`VPKDirectoryEntry`]. pub dir_entry: VPKDirectoryEntry, /// [`PathBuf`] to archive (VPK) to read from. /// /// Is [`Some`] when data for the entry must be read from the file /// (in addition to [`Self::preload_data`]). /// /// Is [`None`] when the data must be read only from /// [`Self::preload_data`]. pub archive_path: Option>, /// Preloaded data of the entry. This is read first before reading /// from the archive. pub preload_data: Vec, } impl VPKEntry { /// Get the data of the [`VPKEntry`]. pub fn get(&self) -> Result, Error> { let mut reader = self.reader()?; let mut buf = Vec::new(); reader.read_to_end(&mut buf)?; Ok(Cow::from(buf)) } /// Create a [`VPKEntryReader`]. pub fn reader(&self) -> Result, Error> { let file = self .archive_path .as_ref() .map(|archive_path| { let mut file = File::open(archive_path.as_path())?; file.seek(SeekFrom::Start(self.dir_entry.archive_offset as u64))?; Ok::<_, Error>(file.take(self.dir_entry.file_length as u64)) }) .transpose()?; Ok(VPKEntryReader::new(&self.preload_data, file)) } } ``` -------------------------------- ### VPK File Structure Definitions (Rust) Source: https://docs.rs/vpk/latest/src/vpk/entry.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Defines fields for a VPK file entry, including preload length, file length, and suffix. The total entry length is the sum of `preload_length` and `file_length`. The `suffix` is used for correct VPK reading. ```Rust pub struct VpkEntryHeader { /// Preload data length. pub preload_length: u32, /// This does not include the [`Self::preload_length`]. Thus the /// total entry length would be [`Self::preload_length`] + /// [`Self::file_length`]. pub file_length: u32, /// Suffix of the header. This seems to be used for ensuring the /// entry is read correctly from the root VPK. pub suffix: u16, } ``` -------------------------------- ### Read VPK File - Rust Source: https://docs.rs/vpk/latest/src/vpk/vpk.rs Opens and reads a VPK file from the specified directory path. It parses the VPK header, including version-specific details like V2 headers and checksums. This function initializes the VPK structure with header information and prepares for reading the file tree. Dependencies include standard Rust libraries for file I/O and collections, as well as the `binrw` crate for binary reading. ```rust use crate::entry::* use crate::structs::* use crate::Error use std::collections::HashMap use std::fs::File use std::io::{BufReader, Cursor, ErrorKind, Read, Seek, SeekFrom} use std::path::Path use std::path::PathBuf use std::sync::Arc use std::{io, mem} use ahash::RandomState use binrw::BinReaderExt const VPK_SIGNATURE: u32 = 0x55aa1234 const VPK_SELF_HASHES_LENGTH: u32 = 48 /// Valve pack (VPK). /// /// Package format used by post-GCF Source engine games to store game /// content. /// /// There is usually a directory VPK which can refers to other VPKs at /// the same directory level via indices as variations of the loaded /// VPKs file name. The directory VPK is usually named /// `pak01_dir.vpk`. #[derive(Debug)] pub struct VPK { /// Header length. pub header_length: u32, /// [`VPKHeader`]. pub header: VPKHeader, /// [`VPKHeaderV2`]. pub header_v2: Option, /// [`VPKHeaderV2Checksum`]. pub header_v2_checksum: Option, /// Tree of the VPK containing all the [`VPKEntry`]s. pub tree: HashMap, /// Path to root VPK. /// /// This is the path to the `.vpk` that [`VPK`] has read. pub root_path: Arc, } impl VPK { /// Read the [`VPK`] at the given [`Path`]. #[doc(alias = "open")] pub fn read(dir_path: impl AsRef) -> Result { let dir_path = dir_path.as_ref().to_path_buf(); let file = File::open(&dir_path)?; let mut reader = BufReader::new(file); // Read main VPK header let header: VPKHeader = reader.read_le()?; if header.signature != VPK_SIGNATURE { return Err(Error::InvalidSignature); } if header.version > 2 { return Err(Error::UnsupportedVersion(header.version)); } let mut vpk = VPK { header_length: 4 * 3, header, header_v2: None, header_v2_checksum: None, tree: HashMap::with_capacity_and_hasher( header.tree_length as usize / 50, RandomState::new(), ), root_path: Arc::new(dir_path), }; if vpk.header.version == 2 { let header_v2: VPKHeaderV2 = reader.read_le()?; if header_v2.self_hashes_length != VPK_SELF_HASHES_LENGTH { return Err(Error::HashSizeMismatch); } vpk.header_length += 4 * 4; let checksum_offset: u32 = vpk.header.tree_length + header_v2.embed_chunk_length + header_v2.chunk_hashes_length; reader.seek(SeekFrom::Current(checksum_offset as i64))?; let header_v2_checksum: VPKHeaderV2Checksum = reader.read_le()?; vpk.header_v2 = Some(header_v2); vpk.header_v2_checksum = Some(header_v2_checksum); // Return seek to initial position - after header let header_length = mem::size_of::() + mem::size_of::(); reader.seek(SeekFrom::Start(header_length as u64))?; } let vpk_root_parent = vpk.root_path.parent().expect("file always in a directory"); let vpk_root_file_name = vpk .root_path .file_name() .ok_or(Error::FilenameNotAvailable)? .to_str() .ok_or(Error::FilenameNotRepresentableAsStr)?; let mut vpk_paths = HashMap::new(); vpk_paths.insert(0x7fff, vpk.root_path.clone()); let mut vpk_path_for_archive_index = |archive_index: u16| { vpk_paths .entry(archive_index) .or_insert_with(|| { Arc::new(vpk_root_parent.join( vpk_root_file_name.replace("dir", &format!("{:03}", archive_index)), )) }) .clone() }; let mut tree_data = vec![0; header.tree_length as usize]; reader.read_exact(&mut tree_data)?; let mut reader = Cursor::new(tree_data.as_slice()); // Read index tree loop { let ext = read_cstring(&mut reader)?; if ext.is_empty() { break; } loop { let mut path = read_cstring(&mut reader)?; if path.is_empty() { break; } if path == " " { path = "" } loop { ``` -------------------------------- ### Read Trait Adapter Methods for VPKEntryReader (Rust) Source: https://docs.rs/vpk/latest/vpk/entry/enum.VPKEntryReader_search=u32+-%3E+bool Includes standard adapter methods from the `Read` trait for `VPKEntryReader`, such as `by_ref`, `bytes`, `chain`, and `take`. These allow for convenient manipulation and iteration over the reader's data. ```rust fn by_ref(&mut self) -> &mut Self fn bytes(self) -> Bytes fn chain(self, next: R) -> Chain fn take(self, limit: u64) -> Take ``` -------------------------------- ### Rust try_from Methods for Type Conversion (vpk crate) Source: https://docs.rs/vpk/latest/src/vpk/structs.rs_search=u32+-%3E+bool Demonstrates the implementation of `try_from` methods across various types within the vpk crate. These methods facilitate conversions, often from a `u32` type to a generic type `T`, returning a `Result`. This is useful for handling potential errors during type casting or data interpretation. ```Rust // Example for vpk::Error::try_from // U -> Result // where // u32 matches U // bool matches T // Example for vpk::entry::VPKEntryReader::try_from // U -> Result // where // u32 matches U // bool matches T // Example for vpk::entry::VPKEntry::try_from // U -> Result // where // u32 matches U // bool matches T // Example for vpk::entry::VPKDirectoryEntry::try_from // U -> Result // where // u32 matches U // bool matches T // Example for vpk::structs::VPKHeader::try_from // U -> Result // where // u32 matches U // bool matches T // Example for vpk::structs::VPKHeaderV2::try_from // U -> Result // where // u32 matches U // bool matches T // Example for vpk::structs::VPKHeaderV2Checksum::try_from // U -> Result // where // u32 matches U // bool matches T // Example for vpk::vpk::VPK::try_from // U -> Result // where // u32 matches U // bool matches T ``` -------------------------------- ### VPK File Reading API Source: https://docs.rs/vpk/latest/vpk/index_search=u32+-%3E+bool This section details the `from_path` function for reading VPK files and various `try_from` methods for converting different VPK components. These methods are crucial for parsing and interpreting VPK file structures. ```APIDOC ## Function `from_path` ### Description Reads the `VPK` from the given `Path`. ### Method GET (Conceptual - this is a function, not an HTTP endpoint) ### Endpoint `vpk::from_path(path: &Path)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None (Function call) ### Response #### Success Response (Result) - **VPK** (struct) - The VPK file object if successfully read. - **Error** (enum) - An error type if reading fails. #### Response Example ```rust // Example usage: // let vpk_result = vpk::from_path(Path::new("path/to/your/file.vpk")); // match vpk_result { // Ok(vpk) => { // // Process VPK data // } // Err(e) => { // eprintln!("Error reading VPK: {:?}", e); // } // } ``` ## Method `try_from` (Generic Usage) ### Description This method attempts to create a specific type (`T`) from a source type (`U`), commonly used for conversions within the VPK crate. The primary use case shown is converting from `u32` to other types like `bool` or specific VPK structures. ### Method POST/PUT (Conceptual - these are trait implementations, not HTTP endpoints) ### Endpoint `vpk::Error::try_from(source: U) -> Result` `vpk::entry::VPKEntryReader::try_from(source: U) -> Result` `vpk::entry::VPKEntry::try_from(source: U) -> Result` `vpk::entry::VPKDirectoryEntry::try_from(source: U) -> Result` `vpk::structs::VPKHeader::try_from(source: U) -> Result` `vpk::structs::VPKHeaderV2::try_from(source: U) -> Result` `vpk::structs::VPKHeaderV2Checksum::try_from(source: U) -> Result` `vpk::vpk::VPK::try_from(source: U) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **source** (Type `U`) - The input data to convert from. ### Request Example None (Method call) ### Response #### Success Response (Result) - **T** (Type) - The successfully converted type. - **Error** (enum) - An error type if conversion fails. #### Response Example ```rust // Example for VPKHeader::try_from: // let header_bytes: [u8; 4] = [0x01, 0x02, 0x03, 0x04]; // let header_result = vpk::structs::VPKHeader::try_from(header_bytes); // match header_result { // Ok(header) => { // // Use the header data // } // Err(e) => { // eprintln!("Error converting header: {:?}", e); // } // } ``` ``` -------------------------------- ### VPK Entry Point Conversions using try_from in Rust Source: https://docs.rs/vpk/latest/vpk/entry/struct.VPKEntry_search=u32+-%3E+bool Illustrates various `try_from` function signatures across different vpk modules (Error, entry, structs). These signatures suggest that the crate supports converting from `u32` to other types like `bool`, indicating flexible data handling and potential error management strategies within the vpk library. ```rust vpk::Error::try_from vpk::entry::VPKEntryReader::try_from vpk::entry::VPKEntry::try_from vpk::entry::VPKDirectoryEntry::try_from vpk::structs::VPKHeader::try_from vpk::structs::VPKHeaderV2::try_from vpk::structs::VPKHeaderV2Checksum::try_from vpk::vpk::VPK::try_from ``` -------------------------------- ### vpk::vpk::VPK::try_from Source: https://docs.rs/vpk/latest/vpk/entry/struct.VPKDirectoryEntry_search=u32+-%3E+bool This is the primary `try_from` method for creating a `VPK` object. It uses generic parameters `U` and `T`, expecting `u32` and `bool` respectively. ```APIDOC ## vpk::vpk::VPK::try_from ### Description Constructs a `VPK` archive object from a given input source, performing necessary validations. ### Method `try_from` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ``` // Example usage (conceptual) let vpk_result: Result = vpk::vpk::VPK::try_from(source_data); ``` ### Response #### Success Response (Result) - **Ok(bool)**: The VPK archive was successfully created and is ready for use. - **Err(vpk::Error)**: An error occurred during VPK creation or loading. #### Response Example ```json // Success example (conceptual) Ok(true) // Error example (conceptual) Err(vpk::Error::FileTooLarge) ``` ``` -------------------------------- ### VPK Read Implementation Source: https://docs.rs/vpk/latest/vpk/vpk/struct.VPK_search=std%3A%3Avec Documentation for the `read` function, which is used to read a VPK file from a given path. ```APIDOC ## impl VPK ### pub fn read(dir_path: impl AsRef) -> Result Read the `VPK` at the given `Path`. ``` -------------------------------- ### VPK TryFrom Implementations Source: https://docs.rs/vpk/latest/vpk/vpk/struct.VPK_search=u32+-%3E+bool Details the `try_from` implementations for various VPK-related types, indicating conversions from `u32` to other types. ```APIDOC ## Trait Implementations: TryFrom for VPK types ### Description These implementations define how to convert from a `u32` type into other VPK-related types. ### Implementations * `impl TryFrom for VPK::Error` * `impl TryFrom for VPKEntryReader` * `impl TryFrom for VPKEntry` * `impl TryFrom for VPKDirectoryEntry` * `impl TryFrom for VPKHeader` * `impl TryFrom for VPKHeaderV2` * `impl TryFrom for VPKHeaderV2Checksum` * `impl TryFrom for VPK` ### Method Signature (common pattern) `fn try_from(value: u32) -> Result` ### Returns A `Result` containing the converted type on success, or an appropriate `Error` on failure. ``` -------------------------------- ### VPKEntry Struct Documentation Source: https://docs.rs/vpk/latest/vpk/entry/struct.VPKEntry_search=u32+-%3E+bool Details the VPKEntry struct, which represents an entry within a VPK archive. It includes information about directory entry, archive path, and preload data. ```APIDOC ## Struct VPKEntry ### Description An entry in the VPK. ### Fields - **dir_entry** (VPKDirectoryEntry) - The directory entry associated with this VPK entry. - **archive_path** (Option>) - Path to the VPK archive file. `Some` if data needs to be read from the file, `None` if data is only in `preload_data`. - **preload_data** (Vec) - Preloaded data for the entry, read before data from the archive. ### Implementations #### impl VPKEntry - **pub fn get(&self) -> Result, Error>** Get the data of the `VPKEntry`. - **pub fn reader(&self) -> Result, Error>** Create a `VPKEntryReader`. ``` -------------------------------- ### Rust VPKDirectoryEntry Structure with BinRead Source: https://docs.rs/vpk/latest/src/vpk/entry.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Defines the VPKDirectoryEntry struct, which holds metadata for a VPK file entry, including CRC32, preload length, archive index, and offset. It derives BinRead for easy deserialization from binary data. Dependencies include binrw. ```rust use binrw::BinRead; /// [`VPKEntry`] header. /// /// Information about the entry stored in the root VPK. #[derive(Debug, BinRead)] pub struct VPKDirectoryEntry { /// 32 bit CRC. pub crc32: u32, /// Number of bytes to preload from the root VPK. pub preload_length: u16, /// Index of archive to load entry from. pub archive_index: u16, /// Offset of the entry in the archive. pub archive_offset: u32, /// Length of the entry in the archive. /// /// # Note /// ``` -------------------------------- ### Rust VPKEntryReader Implementation for Reading Source: https://docs.rs/vpk/latest/src/vpk/entry.rs_search= Implements the `Read` trait for VPKEntryReader, allowing it to read data sequentially from either preloaded buffers or archive files. It handles different reading strategies based on the availability of preloaded data and archive files. ```rust /// A reader over the [`VPKEntry`]. pub enum VPKEntryReader<'a> { /// Only preloaded data must be read. PreloadedOnly { preloaded_data: std::io::Cursor<&'a [u8]>, }, /// Read from preloaded data first and then the file. PreloadAndFile { /// Length of the preloaded data. preloaded_data_len: usize, /// Number of bytes of the preloaded data read so far. preloaded_bytes_read: usize, /// Preloaded data. preloaded_data: std::io::Cursor<&'a [u8]>, /// The file that must be read. file: std::io::Take, }, /// Only the file must be read. FileOnly { file: std::io::Take }, } impl Read for VPKEntryReader<'_> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { match self { VPKEntryReader::PreloadedOnly { preloaded_data } => preloaded_data.read(buf), VPKEntryReader::PreloadAndFile { preloaded_data_len, preloaded_bytes_read, preloaded_data, file, } => { if preloaded_bytes_read >= preloaded_data_len { file.read(buf) } else { let bytes_read = preloaded_data.read(buf)?; let bytes_read = if bytes_read < buf.len() { let file_bytes_read = file.read(&mut buf[bytes_read..])?; bytes_read + file_bytes_read } else { bytes_read }; *preloaded_bytes_read += bytes_read; Ok(bytes_read) } } VPKEntryReader::FileOnly { file } => file.read(buf), } } } impl<'a> VPKEntryReader<'a> { /// Create a new [`VPKEntryReader`]. pub fn new(preloaded_data: &'a [u8], file: Option>) -> Self { match file { Some(file) => { if preloaded_data.is_empty() { Self::FileOnly { file } } else { Self::PreloadAndFile { preloaded_data_len: preloaded_data.len(), preloaded_bytes_read: 0, preloaded_data: std::io::Cursor::new(preloaded_data), file, } } } None => Self::PreloadedOnly { preloaded_data: std::io::Cursor::new(preloaded_data), }, } } } ``` -------------------------------- ### VPKHeader Clone and Debug Implementations (Rust) Source: https://docs.rs/vpk/latest/vpk/structs/struct.VPKHeader_search= Shows the implementations of Clone and Debug traits for the VPKHeader struct. These allow VPKHeader instances to be duplicated and formatted for debugging purposes. ```rust impl Clone for VPKHeader { fn clone(&self) -> VPKHeader { // Implementation details for cloning VPKHeader unimplemented!(); } fn clone_from(&mut self, source: &Self) { // Implementation details for clone_from unimplemented!(); } } impl Debug for VPKHeader { fn fmt(&self, f: &mut Formatter<'_>) -> Result { // Implementation details for formatting VPKHeader unimplemented!(); } } ``` -------------------------------- ### Read Trait Implementation for VPKEntryReader Source: https://docs.rs/vpk/latest/vpk/entry/enum.VPKEntryReader_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the implementation of the `Read` trait for `VPKEntryReader`. This enables reading bytes into a buffer, supporting various reading methods like `read`, `read_vectored`, `read_to_end`, and `read_exact`. ```rust impl<'a> Read for VPKEntryReader<'a> { fn read(&mut self, buf: &mut [u8]) -> Result fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result fn read_to_end(&mut self, buf: &mut Vec) -> Result fn read_to_string(&mut self, buf: &mut String) -> Result fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error> fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error> fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error> fn by_ref(&mut self) -> &mut Self fn bytes(self) -> Bytes fn chain(self, next: R) -> Chain fn take(self, limit: u64) -> Take } ``` -------------------------------- ### Rust Blanket Implementations: Borrow for T Source: https://docs.rs/vpk/latest/vpk/enum.Error Demonstrates the blanket implementation of `Borrow` for any type `T`, providing immutable borrowing capabilities. ```rust impl Borrow for T where T: ?Sized { fn borrow(&self) -> &T } ``` -------------------------------- ### BinRead Implementation for VPKDirectoryEntry Source: https://docs.rs/vpk/latest/vpk/entry/struct.VPKDirectoryEntry_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods for reading VPKDirectoryEntry from binary data using the BinRead trait. Supports reading with different endianness (big-endian, little-endian, native-endian) and with optional arguments. ```Rust impl BinRead for VPKDirectoryEntry { type Args<'__binrw_generated_args_lifetime> = (); fn read_options( __binrw_generated_var_reader: &mut R, __binrw_generated_var_endian: Endian, __binrw_generated_var_arguments: Self::Args<'_>, ) -> BinResult; fn read_be(reader: &mut R) -> BinResult; fn read_le(reader: &mut R) -> BinResult; fn read_ne(reader: &mut R) -> BinResult; fn read_be_args( reader: &mut R, args: Self::Args<'_>, ) -> BinResult; fn read_le_args( reader: &mut R, args: Self::Args<'_>, ) -> BinResult; fn read_ne_args( reader: &mut R, args: Self::Args<'_>, ) -> BinResult; } ``` -------------------------------- ### VPKEntry Struct Source: https://docs.rs/vpk/latest/vpk/entry/struct.VPKEntry Details of the VPKEntry struct, including its fields and their descriptions. ```APIDOC ## Struct VPKEntry An entry in the VPK. ### Fields * **`dir_entry`** (VPKDirectoryEntry) - Represents the directory entry information for this VPK entry. * **`archive_path`** (Option>) - Path to the archive (VPK) file. `Some` if data needs to be read from the file, `None` if data is only in `preload_data`. * **`preload_data`** (Vec) - Preloaded data for the entry, read before data from the archive. ``` -------------------------------- ### VPKHeader Clone and Debug Implementations Source: https://docs.rs/vpk/latest/vpk/structs/struct.VPKHeader Provides implementations for the Clone and Debug traits for VPKHeader. Clone allows for creating copies of the header, while Debug enables formatted printing for debugging purposes. ```Rust impl Clone for VPKHeader { fn clone(&self) -> VPKHeader { // Implementation details for cloning VPKHeader todo!() } fn clone_from(&mut self, source: &Self) { // Implementation details for clone_from todo!() } } impl Debug for VPKHeader { fn fmt(&self, f: &mut Formatter<'_>) -> Result { // Implementation details for formatting VPKHeader todo!() } } ``` -------------------------------- ### VPK from_path Function Source: https://docs.rs/vpk/latest/vpk/fn.from_path_search=std%3A%3Avec This section details the `from_path` function, which is used to read a VPK file from a given file system path. ```APIDOC ## `from_path` Function ### Description Reads the VPK file from the given `Path`. ### Signature ```rust pub fn from_path(path: impl AsRef) -> Result ``` ### Parameters #### Path Parameter - **path** (impl AsRef) - Required - The file path from which to read the VPK. ### Return Value - **Result** - Returns `Ok(VPK)` on success, or `Err(Error)` if the VPK file cannot be read. ``` -------------------------------- ### VPKEntry Trait Implementations Source: https://docs.rs/vpk/latest/vpk/entry/struct.VPKEntry_search=u32+-%3E+bool Lists the implemented traits for the VPKEntry struct, including Debug, Send, Sync, and various blanket implementations. ```APIDOC ## Trait Implementations for VPKEntry ### impl Debug for VPKEntry - **fn fmt(&self, f: &mut Formatter<'_>) -> Result** Formats the value using the given formatter. ### Auto Trait Implementations - **impl Freeze for VPKEntry** - **impl RefUnwindSafe for VPKEntry** - **impl Send for VPKEntry** - **impl Sync for VPKEntry** - **impl Unpin for VPKEntry** - **impl UnwindSafe for VPKEntry** ### Blanket Implementations These are generic implementations that apply to many types, including VPKEntry. - **impl Any for T** - **impl Borrow for T** - **impl BorrowMut for T** - **impl From for T** - **impl Into for T** - **impl TryFrom for T** - **impl TryInto for T** ``` -------------------------------- ### VPK::from_path Source: https://docs.rs/vpk/latest/vpk/fn.from_path_search=u32+-%3E+bool Reads a VPK file from the given path. ```APIDOC ## VPK::from_path ### Description Reads the VPK the given Path. ### Method `pub fn from_path(path: impl AsRef) -> Result` ### Endpoint N/A (This is a library function, not an HTTP endpoint) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (Result) - **VPK**: The VPK object if successfully read. - **Error**: An error object if reading fails. #### Response Example N/A ``` -------------------------------- ### VPKHeader BinRead Implementation (Rust) Source: https://docs.rs/vpk/latest/vpk/structs/struct.VPKHeader_search= Provides implementations for reading VPKHeader from binary data using the BinRead trait. It includes methods for reading with different endianness and arguments, enabling flexible VPK file parsing. ```rust impl BinRead for VPKHeader { type Args<'__binrw_generated_args_lifetime> = (); fn read_options( __binrw_generated_var_reader: &mut R, __binrw_generated_var_endian: Endian, __binrw_generated_var_arguments: Self::Args<'_>, ) -> BinResult { // Implementation details for reading VPKHeader with options unimplemented!(); } // Other read_* methods are also implemented here... } ``` -------------------------------- ### Rust Blanket Implementations: BorrowMut for T Source: https://docs.rs/vpk/latest/vpk/enum.Error Illustrates the blanket implementation of `BorrowMut` for any type `T`, enabling mutable borrowing. ```rust impl BorrowMut for T where T: ?Sized { fn borrow_mut(&mut self) -> &mut T } ``` -------------------------------- ### vpk::entry::VPKEntry::try_from Source: https://docs.rs/vpk/latest/vpk/entry/struct.VPKDirectoryEntry_search=u32+-%3E+bool This method allows for the conversion into a `VPKEntry` type. Similar to others, it maps `u32` to `U` and `bool` to `T`. ```APIDOC ## vpk::entry::VPKEntry::try_from ### Description Attempts to create a `VPKEntry` instance from an input value using generic type constraints. ### Method `try_from` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ``` // Example usage (conceptual) let entry_result: Result = vpk::entry::VPKEntry::try_from(some_u32_value); ``` ### Response #### Success Response (Result) - **Ok(bool)**: Successfully created a VPK entry. - **Err(vpk::Error)**: Failed to create the VPK entry. #### Response Example ```json // Success example (conceptual) Ok(true) // Error example (conceptual) Err(vpk::Error::InvalidFormat) ``` ``` -------------------------------- ### Read VPK File from Path in Rust Source: https://docs.rs/vpk/latest/src/vpk/lib.rs Provides a public function `from_path` to read a VPK file given a path. This function acts as a convenient wrapper around the `VPK::read` method, abstracting the underlying reading mechanism and returning a `Result` containing either the parsed `VPK` object or an `Error`. ```rust /// Read the [`VPK`] the given [`Path`]. #[doc(alias = "read")] pub fn from_path(path: impl AsRef) -> Result { VPK::read(path) } ``` -------------------------------- ### Implement Debug for VPKHeaderV2 in Rust Source: https://docs.rs/vpk/latest/vpk/structs/struct.VPKHeaderV2_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This Rust code shows the implementation of the Debug trait for the VPKHeaderV2 struct. The `fmt` method allows for formatted output of the struct's contents, typically used for debugging purposes. ```rust impl Debug for VPKHeaderV2 { fn fmt(&self, f: &mut Formatter<'_>) -> Result { // Implementation details would be here unimplemented!() } } ```