### Initialize RAR Archive Object (Rust) Source: https://context7.com/muja/unrar.rs/llms.txt Demonstrates creating an `Archive` object for RAR archives, including handling encrypted archives with passwords and creating owned archive objects. It also shows basic checks for archive validity and multipart status. ```rust use unrar::Archive; fn main() -> Result<(), Box> { // Create archive object for plain (non-encrypted) archive let archive = Archive::new("archive.rar"); // Create archive object with password for encrypted archive let encrypted_archive = Archive::with_password("secure.rar", "my_password"); // Create owned archive (takes ownership of path, returns Archive<'static>) let owned = Archive::new_owned("archive.rar".to_string()); // Check if file is a RAR archive based on filename (no FS operations) if archive.is_archive() { println!("Valid RAR archive filename"); } // Check if archive is multipart if archive.is_multipart() { println!("This is a multi-part archive"); } Ok(()) } ``` -------------------------------- ### HANDLE PASCAL RAROpenArchiveEx Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RAROpenArchiveEx.md Opens a RAR archive and allocates necessary memory structures. This function is an updated version of RAROpenArchive, offering enhanced options and Unicode name support. ```APIDOC ## HANDLE PASCAL RAROpenArchiveEx ### Description Opens RAR archive and allocate memory structures. Replaces the obsolete RAROpenArchive providing more options and Unicode names support. ### Method [Not specified, presumed CALL for a DLL function] ### Endpoint [Not applicable for a DLL function] ### Parameters #### Path Parameters [None] #### Query Parameters [None] #### Request Body - **ArchiveData** (struct RAROpenArchiveDataEx *) - Required - Points to RAROpenArchiveDataEx structure. ### Request Example [Not applicable for a DLL function] ### Response #### Success Response - **Archive handle** (HANDLE) - Handle to the opened archive. #### Response Example [Handle value or NULL in case of error] ``` -------------------------------- ### RAROpenArchiveDataEx Structure Definition (C/C++) Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RAROpenArchiveDataEx.md Defines the RAROpenArchiveDataEx structure, used for opening RAR archives with UnRAR.dll. This structure contains information about the archive name, open mode, results, comments, and flags. ```c++ struct RAROpenArchiveDataEx { char *ArcName; wchar_t *ArcNameW; unsigned int OpenMode; unsigned int OpenResult; char *CmtBuf; unsigned int CmtBufSize; unsigned int CmtSize; unsigned int CmtState; unsigned int Flags; UNRARCALLBACK Callback; LPARAM UserData; unsigned int OpFlags; wchar_t *CmtBufW; unsigned int Reserved[25]; }; ``` -------------------------------- ### List Archive Entries with Unrar.rs (Rust) Source: https://github.com/muja/unrar.rs/blob/master/README.md This snippet demonstrates how to list all entries within a RAR archive using the `unrar` crate. It opens the archive for listing and iterates through each entry, printing its details. This functionality is useful for inspecting archive contents without extracting them. ```rust use unrar::Archive; fn main() { for entry in Archive::new("archive.rar").open_for_listing().unwrap() { println!("{}", entry.unwrap()); } } ``` -------------------------------- ### List RAR Archive Contents with Iterator (Rust) Source: https://context7.com/muja/unrar.rs/llms.txt Demonstrates how to open a RAR archive in listing mode and iterate through its entries using a standard Rust iterator. It prints details for each file entry, such as filename, size, CRC32 checksum, and flags for directory, encryption, and splitting. ```rust use unrar::Archive; fn main() -> Result<(), Box> { // Open archive in List mode (implements Iterator) let archive = Archive::new("archive.rar").open_for_listing()?; // Iterate through all entries for entry_result in archive { let entry = entry_result?; // Print file information println!("File: {}", entry.filename.display()); println!(" Size: {} bytes", entry.unpacked_size); println!(" CRC32: {:08x}", entry.file_crc); println!(" Is directory: {}", entry.is_directory()); println!(" Is encrypted: {}", entry.is_encrypted()); println!(" Is split: {}", entry.is_split()); } Ok(()) } ``` -------------------------------- ### Work with Multi-Part RAR Archives (Rust) Source: https://context7.com/muja/unrar.rs/llms.txt Provides methods for handling multi-part RAR archives, including finding the first part, generating glob patterns for all parts, retrieving specific parts by number, and adjusting the archive object to point to the first part. ```rust use unrar::Archive; use std::path::PathBuf; fn main() { let archive = Archive::new("archive.part42.rar"); // Get the first part of a multi-part archive let first_part = archive.first_part(); println!("First part: {}", first_part.display()); // Output: "archive.part01.rar" // Get a glob pattern for all parts let all_parts = archive.all_parts(); println!("All parts pattern: {}", all_parts.display()); // Output: "archive.part??.rar" // Get a specific part number if let Some(part10) = archive.nth_part(10) { println!("Part 10: {}", part10.display()); // Output: "archive.part10.rar" } // Navigate to first part before opening let first_archive = Archive::new("archive.part15.rar").as_first_part(); println!("Adjusted to: {}", first_archive.filename().display()); // Output: "archive.part01.rar" } ``` -------------------------------- ### RARSetCallback Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RARSetCallback.md Sets a user-defined callback function to process UnRAR events. This method is obsolete and RAROpenArchiveDataEx is recommended for newer implementations. ```APIDOC ## void PASCAL RARSetCallback(HANDLE hArcData, int PASCAL (*Callback)(UINT msg, LPARAM UserData, LPARAM P1, LPARAM P2), LPARAM UserData) ### Description Sets a user-defined callback function to process UnRAR events. This function is obsolete and less preferable than setting the Callback and UserData fields in RAROpenArchiveDataEx when calling RAROpenArchiveEx. Using RARSetCallback may prevent reading archive comments in archives with encrypted headers. ### Method (Not applicable, this is a C function signature) ### Endpoint (Not applicable, this is a C function signature) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters * **hArcData** (HANDLE) - The archive handle obtained from RAROpenArchive or RAROpenArchiveEx. * **Callback** (int PASCAL (*)(UINT msg, LPARAM UserData, LPARAM P1, LPARAM P2)) - Address of the user-defined callback function. Set to NULL to not define a callback. Required for multivolume and encrypted archives. * **UserData** (LPARAM) - User-defined value passed to the callback function. ### Request Example (Not applicable, this is a C function signature) ### Response #### Success Response (200) None. #### Response Example (None) ``` -------------------------------- ### Manually List RAR Archive Contents (Rust) Source: https://context7.com/muja/unrar.rs/llms.txt Shows how to manually control the iteration process when listing RAR archive contents. This approach uses `read_header()` to process entries one by one and `skip()` to move to the next, offering more granular control than the basic iterator. ```rust use unrar::Archive; fn main() -> Result<(), Box> { let mut archive = Archive::new("archive.rar").open_for_listing()?; // Manually control iteration while let Some(header) = archive.read_header()? { let entry = header.entry(); println!("{} - {} bytes", entry.filename.display(), entry.unpacked_size ); // Skip to next entry archive = header.skip()?; } Ok(()) } ``` -------------------------------- ### Unrar.rs Archive Flags Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RAROpenArchiveDataEx.md Defines bit flags used for specifying options and properties of RAR archives. ```APIDOC ## Unrar.rs Archive Flags ### Description These are bit flags that can be used to represent various properties and options related to RAR archives. They are often used in conjunction with archive operations or to describe archive characteristics. ### Flags - **ROADF_SIGNED** (0x0020): Authenticity information present (obsolete). - **ROADF_RECOVERY** (0x0040): Recovery record present. - **ROADF_ENCHEADERS** (0x0080): Block headers are encrypted. - **ROADF_FIRSTVOLUME** (0x0100): First volume (set only by RAR 3.0 and later). - **ROADOF_KEEPBROKEN** (0x0001): If set, extracted files with checksum errors are not deleted. ``` -------------------------------- ### RAROpenArchiveData Structure Definition (C/C++) Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RAROpenArchiveData.md Defines the RAROpenArchiveData structure used for opening and managing RAR archives with UnRAR.dll. It includes fields for archive name, open mode, results, and comment handling. This structure is essential for functions like RAROpenArchive. ```c struct RAROpenArchiveData { char *ArcName; UINT OpenMode; UINT OpenResult; char *CmtBuf; UINT CmtBufSize; UINT CmtSize; UINT CmtState; }; ``` -------------------------------- ### Unrar.rs Callback Function Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RAROpenArchiveDataEx.md Details the user-defined callback function used for processing UnRAR events during archive operations. ```APIDOC ## Unrar.rs Callback Function ### Description This section describes the user-defined callback function that can be provided to process events during UnRAR operations. This function is crucial for handling complex archive types like multivolume and encrypted archives. ### Callback Function Pointer - **Callback**: Address of a user-defined callback function (type `RARCallback.md`) to process UnRAR events. - Set to `NULL` if no callback function is desired. ### User Data - **UserData**: A user-defined value that will be passed to the callback function. ``` -------------------------------- ### Automate unrar DLL update with Bash script Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/README.md This Bash script automates the process of downloading and applying patches to update the unrar DLL. It requires the URL of the unrar source tarball as an argument. ```bash #!/bin/sh URL="$1" if [ -z "$URL" ]; then echo "Usage: $0 " exit 1 fi rm -rf unrar tar -xzf "$(basename $URL)" cd unrar cat ../patches.txt | xargs git cherry-pick -n cd .. exit 0 ``` -------------------------------- ### Read First File Content from RAR Archive in Rust Source: https://github.com/muja/unrar.rs/blob/master/README.md This Rust function reads the first content of a RAR archive. It takes a path to the archive, opens it, reads the header, and then extracts the data of the first entry. Dependencies include the `unrar` crate. It returns a `UnrarResult` containing the file content as a `Vec`. ```rust fn first_file_content>(path: P) -> UnrarResult> { let archive = Archive::new(&path).open_for_processing()?; let archive = archive.read_header()?.expect("empty archive"); dbg!(&archive.entry().filename); let (data, _rest) = archive.read()?; Ok(data) } # use std::path::Path; # use unrar::{Archive, UnrarResult}; # # let data = first_file_content("data/version.rar").unwrap(); # assert_eq!(std::str::from_utf8(&data), Ok("unrar-0.4.0")); ``` -------------------------------- ### Extract Password-Protected RAR Archive in Rust Source: https://context7.com/muja/unrar.rs/llms.txt Demonstrates how to open and extract files from a password-protected RAR archive using the unrar.rs library. It iterates through archive entries, checks for encryption, and extracts files or skips directories. Requires the 'unrar' crate. ```rust use unrar::Archive; fn main() -> Result<(), Box> { let password = "secret123"; // Open encrypted archive with password let mut archive = Archive::with_password("encrypted.rar", password) .open_for_processing()?; while let Some(header) = archive.read_header()? { let entry = header.entry(); println!("File: {} (encrypted: {})", entry.filename.display(), entry.is_encrypted() ); archive = if entry.is_file() { header.extract()? } else { header.skip()? }; } Ok(()) } ``` -------------------------------- ### Extract All Files to Current Directory (Rust) Source: https://context7.com/muja/unrar.rs/llms.txt Extracts all files from a RAR archive to the current directory. It iterates through archive entries, extracts files, and skips directories. Dependencies: `unrar` crate. ```rust use unrar::Archive; fn main() -> Result<(), Box> { let mut archive = Archive::new("archive.rar").open_for_processing()?; while let Some(header) = archive.read_header()? { let entry = header.entry(); println!("Extracting: {} ({} bytes)", entry.filename.display(), entry.unpacked_size ); archive = if entry.is_file() { // Extract file to current directory header.extract()? } else { // Skip directories header.skip()? }; } println!("Extraction complete!"); Ok(()) } ``` -------------------------------- ### Extract Files to Specific Directory (Rust) Source: https://context7.com/muja/unrar.rs/llms.txt Extracts all files from a RAR archive to a specified output directory. It creates the directory if it doesn't exist and extracts each file into it. Dependencies: `unrar` crate, `std::path::Path`. ```rust use unrar::Archive; use std::path::Path; fn main() -> Result<(), Box> { let output_dir = Path::new("/tmp/extracted"); std::fs::create_dir_all(output_dir)?; let mut archive = Archive::new("archive.rar").open_for_processing()?; while let Some(header) = archive.read_header()? { println!("Processing: {}", header.entry().filename.display()); archive = if header.entry().is_file() { // Extract with base directory header.extract_with_base(output_dir)? } else { header.skip()? }; } Ok(()) } ``` -------------------------------- ### Extract Rust Files from RAR Archive by Pattern Source: https://context7.com/muja/unrar.rs/llms.txt This snippet demonstrates how to extract only Rust source files (.rs) from a RAR archive using the unrar crate and the regex crate for pattern matching. It iterates through archive entries, checks filenames against a regex pattern, and extracts matching files while skipping others. Dependencies include `unrar` and `regex`. ```rust use unrar::Archive; use regex::Regex; fn main() -> Result<(), Box> { let pattern = Regex::new(r"\.rs$")?; // Extract only Rust source files let mut archive = Archive::new("source.rar").open_for_processing()?; let mut extracted_count = 0; while let Some(header) = archive.read_header()? { let filename = header.entry().filename.to_string_lossy(); archive = if pattern.is_match(&filename) { println!("Extracting: {}", filename); extracted_count += 1; header.extract()? } else { header.skip()? }; } println!("Extracted {} Rust files", extracted_count); Ok(()) } ``` -------------------------------- ### RARProcessFile Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RARProcessFile.md Performs a specified operation on the current file in an archive and advances to the next file. It can be used for testing, extracting, or skipping files. ```APIDOC ## int PASCAL RARProcessFile(HANDLE hArcData, int Operation, char *DestPath, char *DestName) ### Description Performs the user defined action and moves the current position in the archive to the next file. If archive is opened in RAR_OM_EXTRACT mode, this function extracts or tests the current file and sets the archive position to the next file. If open mode is RAR_OM_LIST, then a call to this function will skip the current file and set the archive position to the next file. It is recommended to use RARProcessFileW instead of this function, because RARProcessFileW supports Unicode. ### Parameters #### Path Parameters - **hArcData** (HANDLE) - Required - Archive handle obtained from RAROpenArchive or RAROpenArchiveEx. - **Operation** (int) - Required - File operation. Possible values: RAR_SKIP, RAR_TEST, RAR_EXTRACT. - **DestPath** (char *) - Optional - Zero-terminated string containing the destination directory for extracted files. If NULL, extracts to the current directory. Meaningful only if DestName is NULL. Must be in OEM encoding. - **DestName** (char *) - Optional - Zero-terminated string containing the full path and name for the extracted file. If NULL, uses the default name. Overrides original filename and DestPath. Must be in OEM encoding. ### Return values - **0** - Success - **ERAR_BAD_DATA** - File CRC error - **ERAR_UNKNOWN_FORMAT** - Unknown archive format - **ERAR_EOPEN** - Volume open error - **ERAR_ECREATE** - File create error - **ERAR_ECLOSE** - File close error - **ERAR_EREAD** - Read error - **ERAR_EWRITE** - Write error - **ERAR_NO_MEMORY** - Not enough memory - **ERAR_EREFERENCE** - Source file for reference record not found. - **ERAR_BAD_PASSWORD** - Entered password is invalid (RAR 5.0 format only). ### Notes If you wish to cancel extraction, return -1 when processing UCM_PROCESSDATA message in a user-defined callback function. ``` -------------------------------- ### Query RAR Archive Metadata in Rust Source: https://context7.com/muja/unrar.rs/llms.txt Illustrates how to inspect the properties of a RAR archive without extracting its contents using the unrar.rs library. It retrieves information such as whether the archive is solid, locked, has comments, a recovery record, encrypted headers, and its volume status (single-part or multi-part). Requires the 'unrar' crate. ```rust use unrar::{Archive, VolumeInfo}; fn main() -> Result<(), Box> { let archive = Archive::new("archive.rar").open_for_listing()?; // Check archive properties println!("Archive Properties:"); println!(" Solid: {}", archive.is_solid()); println!(" Locked: {}", archive.is_locked()); println!(" Has comments: {}", archive.has_comment()); println!(" Has recovery record: {}", archive.has_recovery_record()); println!(" Encrypted headers: {}", archive.has_encrypted_headers()); // Check volume information match archive.volume_info() { VolumeInfo::None => println!(" Single-part archive"), VolumeInfo::First => println!(" First volume of multi-part archive"), VolumeInfo::Subsequent => println!(" Subsequent volume of multi-part archive"), } Ok(()) } ``` -------------------------------- ### RARProcessFileW Function Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RARProcessFileW.md Processes a file within a RAR archive, performing specified operations like extraction or testing, and then advancing to the next file. ```APIDOC ## int RARProcessFileW(HANDLE hArcData, int Operation, wchar_t *DestPath, wchar_t *DestName) ### Description Performs the user-defined action on the current file in the archive and advances the archive position to the next file. - If the archive is opened in `RAR_OM_EXTRACT` mode, this function extracts or tests the current file. - If the archive is opened in `RAR_OM_LIST` mode, this function skips the current file. ### Method `int` (Function Call) ### Endpoint N/A (This is a function within a DLL, not a network endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **hArcData** (HANDLE) - Required - Archive handle obtained from `RAROpenArchive` or `RAROpenArchiveEx`. * **Operation** (int) - Required - Specifies the file operation: * `RAR_SKIP`: Move to the next file. For solid archives in `RAR_OM_EXTRACT` mode, the file is analyzed, which may be slower than a simple seek. * `RAR_TEST`: Test the current file's integrity and move to the next file. If the archive was opened in `RAR_OM_LIST` mode, this is equivalent to `RAR_SKIP`. * `RAR_EXTRACT`: Extract the current file and move to the next file. If the archive was opened in `RAR_OM_LIST` mode, this is equivalent to `RAR_SKIP`. * **DestPath** (wchar_t *) - Optional - A null-terminated Unicode string specifying the destination directory for extracted files. If `NULL`, files are extracted to the current directory. This parameter is only relevant if `DestName` is `NULL`. * **DestName** (wchar_t *) - Optional - A null-terminated Unicode string specifying the full path and filename for the extracted file. If `NULL`, the default filename stored in the archive is used. If provided, it overrides both the original filename and the `DestPath`. ### Request Example ```c // Example of calling RARProcessFileW to extract a file HANDLE hArchive = RAROpenArchive(...); if (hArchive) { wchar_t destPath[] = L"C:\ExtractedFiles\"; RARProcessFileW(hArchive, RAR_EXTRACT, destPath, NULL); RARCloseArchive(hArchive); } ``` ### Response #### Success Response (0) * **Return Value** (int) - `0` indicates success. #### Error Responses * **ERAR_BAD_DATA** (int) - File CRC error. * **ERAR_UNKNOWN_FORMAT** (int) - Unknown archive format. * **ERAR_EOPEN** (int) - Volume open error. * **ERAR_ECREATE** (int) - File create error. * **ERAR_ECLOSE** (int) - File close error. * **ERAR_EREAD** (int) - Read error. * **ERAR_EWRITE** (int) - Write error. * **ERAR_NO_MEMORY** (int) - Not enough memory. * **ERAR_EREFERENCE** (int) - Source file for a reference record not found. * **ERAR_BAD_PASSWORD** (int) - Invalid password (RAR 5.0 format only). ### Response Example ```c int result = RARProcessFileW(hArchive, RAR_TEST, NULL, NULL); if (result == 0) { // Operation successful } else { // Handle error based on the return code (e.g., ERAR_BAD_DATA) } ``` ### Notes To cancel extraction, return -1 from a user-defined callback function processing `UCM_PROCESSDATA`. ``` -------------------------------- ### Handle Broken Archives with Recovery in Rust Source: https://context7.com/muja/unrar.rs/llms.txt Shows how to attempt opening a potentially broken RAR archive and list its contents, even if errors occur during the process. It utilizes the `break_open` method and checks for recoverable errors, printing warnings and specific error details like CRC errors. Requires the 'unrar' crate. ```rust use unrar::{Archive, List, error::{When, Code}}; use std::io::Write; fn main() { let mut possible_error = None; let mut stderr = std::io::stderr(); // Try to open even if archive is partially broken match Archive::new("broken.rar").break_open::(Some(&mut possible_error)) { Ok(mut archive) => { // Check if recoverable error occurred during opening if let Some(error) = possible_error { writeln!(&mut stderr, "Warning: {}, continuing anyway", error).unwrap(); } // Try to list contents despite errors for entry in archive { match entry { Ok(e) => println!("✓ {}", e.filename.display()), Err(err) => { writeln!(&mut stderr, "✗ Error: {}", err).unwrap(); // Check error type if err.code == Code::BadData && err.when == When::Process { writeln!(&mut stderr, " (CRC error, file may be corrupted)").unwrap(); } } } } } Err(e) => { writeln!(&mut stderr, "Fatal error: Cannot open archive: {}", e).unwrap(); std::process::exit(1); } } } ``` -------------------------------- ### Collect Statistics from RAR Archive Source: https://context7.com/muja/unrar.rs/llms.txt This snippet shows how to collect statistics from a RAR archive, including the total number of files, directories, total size, and counts of encrypted and split files. It utilizes the unrar crate to iterate through archive entries and aggregates the information into an ArchiveStats struct. No external dependencies beyond `unrar` are required for this functionality. ```rust use unrar::Archive; #[derive(Default)] struct ArchiveStats { total_files: usize, total_dirs: usize, total_size: u64, encrypted_files: usize, split_files: usize, } fn main() -> Result<(), Box> { let mut stats = ArchiveStats::default(); let archive = Archive::new("archive.rar").open_for_listing()?; for entry_result in archive { let entry = entry_result?; if entry.is_file() { stats.total_files += 1; stats.total_size += entry.unpacked_size; if entry.is_encrypted() { stats.encrypted_files += 1; } if entry.is_split() { stats.split_files += 1; } } else { stats.total_dirs += 1; } } println!("Archive Statistics:"); println!(" Files: {}", stats.total_files); println!(" Directories: {}", stats.total_dirs); println!(" Total size: {} bytes ({:.2} MB)", stats.total_size, stats.total_size as f64 / 1_048_576.0 ); println!(" Encrypted files: {}", stats.encrypted_files); println!(" Split files: {}", stats.split_files); Ok(()) } ``` -------------------------------- ### Unrar.rs Reserved Field Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RAROpenArchiveDataEx.md Reserved field for future use. ```APIDOC ## Unrar.rs Reserved Field ### Description This field is reserved for future use and must be set to zero. ### Reserved - **Reserved[25]**: Array of 25 bytes reserved for future expansion. Must be zero. ``` -------------------------------- ### Unrar.rs Operation Flags Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RAROpenArchiveDataEx.md Defines bit flags for modifying operation modes when interacting with UnRAR functions. ```APIDOC ## Unrar.rs Operation Flags ### Description Input parameter that modifies the operation mode. It accepts a combination of bit flags to control how UnRAR operations are performed. ### OpFlags - **OpFlags** (combination of bit flags): Modifiers for the operation mode. - **ROADOF_KEEPBROKEN** (0x0001): If set, extracted files with checksum errors are not deleted. ``` -------------------------------- ### Comprehensive Error Handling for RAR Extraction in Rust Source: https://context7.com/muja/unrar.rs/llms.txt Provides robust error handling for RAR archive extraction. This Rust code snippet categorizes and reports specific errors encountered during archive opening and file extraction, such as invalid format, permissions issues, missing passwords, and data corruption (CRC errors). Requires the 'unrar' crate. ```rust use unrar::{Archive, error::{Code, When, UnrarError}}; fn extract_with_error_handling(path: &str) -> Result<(), UnrarError> { let mut archive = match Archive::new(path).open_for_processing() { Ok(a) => a, Err(e) => { match (e.code, e.when) { (Code::BadArchive, When::Open) => { eprintln!("Error: Not a valid RAR archive"); } (Code::EOpen, When::Open) => { eprintln!("Error: Cannot open file (check permissions)"); } (Code::MissingPassword, When::Open) => { eprintln!("Error: Archive is encrypted, password required"); } (Code::UnknownFormat, When::Open) => { eprintln!("Error: Unknown or unsupported RAR format"); } _ => { eprintln!("Error opening archive: {}", e); } } return Err(e); } }; while let Some(header) = archive.read_header()? { archive = match header.extract() { Ok(a) => a, Err(e) if e.code == Code::EWrite => { eprintln!("Write error, disk full?"); return Err(e); } Err(e) if e.code == Code::BadData => { eprintln!("CRC error in {}, skipping", header.entry().filename.display()); header.skip()? } Err(e) => return Err(e), }; } Ok(()) } fn main() { if let Err(e) = extract_with_error_handling("archive.rar") { eprintln!("Extraction failed: {}", e); std::process::exit(1); } } ``` -------------------------------- ### Read Single File Contents into Memory (Rust) Source: https://context7.com/muja/unrar.rs/llms.txt Reads the contents of a specific file (e.g., config.json) from a RAR archive directly into memory. It then attempts to parse the content as UTF-8. Dependencies: `unrar` crate. ```rust use unrar::{Archive, UnrarResult}; fn main() -> UnrarResult<()> { let mut archive = Archive::new("archive.rar").open_for_processing()?; while let Some(header) = archive.read_header()? { let entry = header.entry(); if entry.filename.to_string_lossy() == "config.json" { // Read entire file into memory let (data, rest) = header.read()?; // Process the data match std::str::from_utf8(&data) { Ok(text) => { println!("File contents:\n{}", text); // Early exit after finding the file return Ok(()) } Err(_) => eprintln!("File is not valid UTF-8") } // Continue with rest of archive if needed archive = rest; } else { archive = header.skip()?; } } Ok(()) } ``` -------------------------------- ### Read Multiple Files into Memory (Rust) Source: https://context7.com/muja/unrar.rs/llms.txt Reads the contents of multiple specified files (e.g., README.md, LICENSE) from a RAR archive into a HashMap. It iterates through the archive, checks if the filename is in the target list, and stores the content. Dependencies: `unrar` crate, `std::collections::HashMap`. ```rust use unrar::Archive; use std::collections::HashMap; fn main() -> Result<(), Box> { let target_files = vec!["README.md", "LICENSE", "config.toml"]; let mut file_contents: HashMap> = HashMap::new(); let mut archive = Archive::new("archive.rar").open_for_processing()?; while let Some(header) = archive.read_header()? { let filename = header.entry().filename.to_string_lossy().to_string(); if target_files.contains(&filename.as_str()) { let (data, rest) = header.read()?; file_contents.insert(filename.clone(), data); println!("Read {} bytes from {}", data.len(), filename); archive = rest; } else { archive = header.skip()?; } } println!("Read {} files from archive", file_contents.len()); Ok(()) } ``` -------------------------------- ### List Split RAR Archives Without Merging (Rust) Source: https://context7.com/muja/unrar.rs/llms.txt Demonstrates listing contents of split RAR archives without merging them into a single entity. This method, using `open_for_listing_split()`, allows checking if individual file entries span across multiple volumes using `is_split_after()` and `is_split_before()`. ```rust use unrar::{Archive, ListSplit}; fn main() -> Result<(), Box> { // Open in ListSplit mode to see entries split across volumes let archive = Archive::new("archive.part01.rar").open_for_listing_split()?; for entry_result in archive { let entry = entry_result?; println!("{}", entry.filename.display()); // Check if file continues in next volume if entry.is_split_after() { println!(" -> continues in next volume"); } // Check if file started in previous volume if entry.is_split_before() { println!(" <- started in previous volume"); } } Ok(()) } ``` -------------------------------- ### Set UnRAR Callback Function (C) Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RARSetCallback.md Sets a user-defined callback function to process UnRAR events. This method is less preferable than using RAROpenArchiveDataEx and is not recommended for archives with encrypted headers. The callback is essential for handling multivolume and encrypted archives. ```C void PASCAL RARSetCallback(HANDLE hArcData, int PASCAL (*Callback)(UINT msg,LPARAM UserData,LPARAM P1,LPARAM P2), LPARAM UserData) ``` -------------------------------- ### RARGetDllVersion API Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RARGetDllVersion.md Retrieves the version of the UnRAR.dll API. This function returns an integer representing the API version, which is defined in unrar.h as RAR_DLL_VERSION. ```APIDOC ## int PASCAL RARGetDllVersion() ### Description Returns API version. ### Method GET (Conceptual - this is a C-style function call, not a web API) ### Endpoint N/A ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body None. ### Request Example ```c int apiVersion = RARGetDllVersion(); ``` ### Response #### Success Response (200) - **Return Value** (integer) - An integer value denoting UnRAR.dll API version. #### Response Example ``` 15 ``` ### Notes - API version number is incremented only in case of noticeable changes in UnRAR.dll API. - This function may be missing in very old versions of UnRAR.dll. It is safer to use LoadLibrary and GetProcAddress to access it in such cases. ``` -------------------------------- ### RARReadHeader Function Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RARReadHeader.md Reads a file header from an archive. This function is obsolete and does not support Unicode names or 64-bit file sizes. RARReadHeaderEx is recommended instead. ```APIDOC ## int PASCAL RARReadHeader(HANDLE hArcData, struct RARHeaderData *HeaderData) ### Description Reads a file header from an archive. This function is obsolete and does not support Unicode names or 64-bit file sizes. It is recommended to use RARReadHeaderEx instead. ### Method *Not applicable (this is a C function signature)* ### Endpoint *Not applicable (this is a C function signature)* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None* ### Parameters * **hArcData** (HANDLE) - The archive handle obtained from RAROpenArchive or RAROpenArchiveEx. * **HeaderData** (struct RARHeaderData *) - Points to a RARHeaderData structure to be filled with header information. ### Return values * **0**: Success * **ERAR_END_ARCHIVE**: End of archive * **ERAR_BAD_DATA**: File header broken * **ERAR_MISSING_PASSWORD**: Password was not provided for an encrypted file header * **ERAR_EOPEN**: Volume open error ### See also * [RARHeaderData structure](RARHeaderData.md) ``` -------------------------------- ### Test Archive Integrity Without Extraction (Rust) Source: https://context7.com/muja/unrar.rs/llms.txt Tests the integrity of files within a RAR archive without actually extracting them. It iterates through entries, uses the `test()` method to verify each file's data, and reports any errors. Dependencies: `unrar` crate. ```rust use unrar::Archive; fn main() -> Result<(), Box> { let mut archive = Archive::new("archive.rar").open_for_processing()?; let mut file_count = 0; let mut error_count = 0; while let Some(header) = archive.read_header()? { let entry = header.entry(); if entry.is_file() { print!("Testing: {}... ", entry.filename.display()); match header.test() { Ok(rest) => { println!("OK"); file_count += 1; archive = rest; } Err(e) => { println!("FAILED: {}", e); error_count += 1; return Err(e.into()); } } } else { archive = header.skip()?; } } println!("\nTested {} files, {} errors", file_count, error_count); Ok(()) } ``` -------------------------------- ### RARHeaderDataEx Structure Definition (C/C++) Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RARHeaderDataEx.md Defines the RARHeaderDataEx structure, used to hold information about files within a RAR archive. This structure is populated by the RARReadHeaderEx function. Ensure the structure is zero-initialized before use. ```c struct RARHeaderDataEx { char ArcName[1024]; wchar_t ArcNameW[1024]; char FileName[1024]; wchar_t FileNameW[1024]; unsigned int Flags; unsigned int PackSize; unsigned int PackSizeHigh; unsigned int UnpSize; unsigned int UnpSizeHigh; unsigned int HostOS; unsigned int FileCRC; unsigned int FileTime; unsigned int UnpVer; unsigned int Method; unsigned int FileAttr; char *CmtBuf; unsigned int CmtBufSize; unsigned int CmtSize; unsigned int CmtState; unsigned int DictSize; unsigned int HashType; char Hash[32]; unsigned int RedirType; wchar_t *RedirName; unsigned int RedirNameSize; unsigned int DirTarget; unsigned int MtimeLow; unsigned int MtimeHigh; unsigned int CtimeLow; unsigned int CtimeHigh; unsigned int AtimeLow; unsigned int AtimeHigh; unsigned int Reserved[988]; }; ``` -------------------------------- ### Extract File with Custom Filename (Rust) Source: https://context7.com/muja/unrar.rs/llms.txt Extracts a specific file from a RAR archive and saves it with a custom filename and path. It checks the filename and uses `extract_to` for custom extraction. Dependencies: `unrar` crate, `std::path::PathBuf`. ```rust use unrar::Archive; use std::path::PathBuf; fn main() -> Result<(), Box> { let mut archive = Archive::new("archive.rar").open_for_processing()?; while let Some(header) = archive.read_header()? { let entry = header.entry(); archive = if entry.filename.to_string_lossy() == "important.txt" { // Extract to specific path with custom name let dest = PathBuf::from("/tmp/renamed_file.txt"); println!("Extracting {} to {}", entry.filename.display(), dest.display()); header.extract_to(dest)? } else { header.skip()? }; } Ok(()) } ``` -------------------------------- ### Unrar.rs Archive Comment Buffer Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RAROpenArchiveDataEx.md Specifies the buffer for reading the archive comment in Unicode encoding. ```APIDOC ## Unrar.rs Archive Comment Buffer ### Description This parameter is used to specify a buffer for retrieving the archive's comment in Unicode encoding. The comment will be zero-terminated, and if it exceeds the buffer size, it will be truncated. ### CmtBufW - **CmtBufW**: Pointer to a buffer for archive comment in Unicode encoding. - Comment text is zero-terminated. - If comment text is larger than buffer size, it is truncated. - Set to `NULL` if you do not need to read the Unicode comment. ### Comment Handling - If both `CmtBuf` and `CmtBufW` are not `NULL`, only the `CmtBufW` comment is read. - If both `CmtBuf` and `CmtBufW` are `NULL`, the archive comment is not read. ``` -------------------------------- ### RARSetPassword Function Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RARSetPassword.md Sets a password for decrypting files within a RAR archive. This function is suitable for archives with encrypted file data but unencrypted headers. ```APIDOC ## void PASCAL RARSetPassword(HANDLE hArcData, char *Password) ### Description Sets a password to decrypt files. This function is intended for archives with encrypted file data and unencrypted headers. For broader compatibility, especially with archives containing encrypted headers, it's recommended to use the `UCM_NEEDPASSWORDW` message within a user-defined callback function. ### Method N/A (This is a C function declaration, not an HTTP request) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A #### Function Parameters - **hArcData** (HANDLE) - Required - The archive handle obtained from `RAROpenArchive` or `RAROpenArchiveEx`. - **Password** (char *) - Required - A zero-terminated string containing the password. ``` -------------------------------- ### RARHeaderData Structure Definition (C) Source: https://github.com/muja/unrar.rs/blob/master/unrar_sys/vendor/Documentation/RARHeaderData.md Defines the RARHeaderData structure in C, used to hold information about archive headers. It includes fields for archive and file names, flags, packed and unpacked sizes, host OS, CRC, timestamps, compression method, and attributes. It also contains members related to file comments, though their support is limited. ```c struct RARHeaderData { char ArcName[260]; char FileName[260]; unsigned int Flags; unsigned int PackSize; unsigned int UnpSize; unsigned int HostOS; unsigned int FileCRC; unsigned int FileTime; unsigned int UnpVer; unsigned int Method; unsigned int FileAttr; char *CmtBuf; unsigned int CmtBufSize; unsigned int CmtSize; unsigned int CmtState; }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.