### Error Handling Example Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/MANIFEST.md Illustrates basic error handling patterns when working with the library. ```rust use sevenz_rust::Error; fn process_archive() -> Result<(), Error> { // ... archive operations ... Ok(()) } match process_archive() { Ok(_) => println!("Archive processed successfully."), Err(Error::PasswordRequired) => println!("Error: Password is required."), Err(e) => println!("An unexpected error occurred: {:?}", e), } ``` -------------------------------- ### Convenience API for Compression and Decompression Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/README.md Provides examples of using the convenience API for simple file decompression, password-protected decompression, and basic compression/encryption to a path. ```rust use sevenz_rust2::{decompress_file, compress_to_path, Password}; // Simple decompression decompress_file("archive.7z", "./output/")?; // Simple decompression with password let pwd = Password::from("secret"); decompress_file_with_password("encrypted.7z", "./output/", pwd)?; // Simple compression compress_to_path("./data/", "archive.7z")?; // Simple encryption compress_to_path_encrypted("./data/", "secure.7z", pwd)?; ``` -------------------------------- ### Get Compression Methods for a File Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Retrieves the compression methods used for a specific file within the archive. The methods are populated into the provided vector. Returns an error if the file is not found. ```rust let mut reader = ArchiveReader::open("archive.7z", Password::empty())?; let mut methods = Vec::new(); reader.file_compression_methods("file.bin", &mut methods)?; for method in methods { println!("Method: {}", method.name()); } ``` -------------------------------- ### Handle MaybeBadPassword Error Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/errors.md This example shows how to catch and handle the MaybeBadPassword error, which indicates either a wrong password or a corrupted archive. It unwraps the underlying IO error for more details. ```rust match archive { Err(Error::MaybeBadPassword(e)) => { eprintln!("Wrong password or corrupted archive: {}", e); } Err(e) => return Err(e), Ok(a) => { /* use archive */ } } ``` -------------------------------- ### Create Archive with Custom Compression Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/README.md Shows how to create a new archive, set custom compression methods like LZMA2 with specific levels, and add a directory using solid compression. ```rust use sevenz_rust2::{ArchiveWriter, EncoderMethod, encoder_options::Lzma2Options}; // Create writer with custom compression let mut writer = ArchiveWriter::create("output.7z")?; let options = Lzma2Options::from_level(9); writer.set_content_methods(vec![ EncoderMethod::LZMA2.into() .with_options(EncoderOptions::Lzma2(options)) ]); // Add directory (solid compression) writer.push_source_path("./data/", |_| true)?; writer.finish()?; ``` -------------------------------- ### Get Password as Byte Slice Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Returns the byte representation of the password. The underlying encoding is UTF-16 LE. ```rust pub fn as_slice(&self) -> &[u8] ``` -------------------------------- ### Get Entries from BlockDecoder Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Retrieves a slice containing all ArchiveEntry metadata for the current block. Use this to access information about files and directories within the block. ```rust let decoder = BlockDecoder::new(1, 0, &archive, &Password::empty(), &mut file); println!("Block contains {} entries", decoder.entry_count()); for entry in decoder.entries() { println!(" - {}", entry.name()); } ``` -------------------------------- ### Compress Files to a 7z Archive Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/README.md Create a new .7z archive from a source directory using `compress_to_path`. The destination path will be created if it does not exist. ```rust sevenz_rust2::compress_to_path("examples/data/sample", "examples/data/sample.7z").expect("compress ok"); ``` -------------------------------- ### BadSignature Error in sevenz-rust2 Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/errors.md Indicates that the input file does not start with the valid 7z signature bytes. This error occurs when attempting to open or read an archive. ```rust Error::BadSignature([u8; 6]) ``` -------------------------------- ### Create a Solid 7z Archive Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/README.md Construct a solid archive using `ArchiveWriter` for potentially better compression. Note that solid archives require sequential decompression. ```rust use sevenz_rust2::* let mut writer = ArchiveWriter::create("dest.7z").expect("create writer ok"); writer.push_source_path("path/to/compress", | _ | true).expect("pack ok"); writer.finish().expect("compress ok"); ``` -------------------------------- ### Get Entry Count from BlockDecoder Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Returns the total number of entries (files and directories) present in the current block. Useful for quick checks or pre-allocating buffers. ```rust let decoder = BlockDecoder::new(1, 0, &archive, &Password::empty(), &mut file); println!("This block has {} entries", decoder.entry_count()); ``` -------------------------------- ### Configure Compression Methods with Encryption and LZMA2 Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/README.md Customize archive creation by specifying encryption and compression algorithms like AES and LZMA2 with specific levels. ```rust use sevenz_rust2::* let mut writer = ArchiveWriter::create("dest.7z").expect("create writer ok"); writer.set_content_methods(vec![ encoder_options::AesEncoderOptions::new("sevenz-rust".into()).into(), encoder_options::Lzma2Options::from_level(9).into(), ]); writer.push_source_path("path/to/compress", | _ | true).expect("pack ok"); writer.finish().expect("compress ok"); ``` -------------------------------- ### Read Archive Files Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/README.md Demonstrates how to open an archive, list its files, read a specific file's data, and iterate through all entries with their streams. ```rust use sevenz_rust2::{Archive, ArchiveReader, Password}; // Parse archive let archive = Archive::open("example.7z")?; println!("Files: {}", archive.files.len()); // Read a specific file let mut reader = ArchiveReader::open("example.7z", Password::empty())?; let data = reader.read_file("document.txt")?; // Iterate all files reader.for_each_entries(|entry, stream| { if !entry.is_directory() { let mut buf = Vec::new(); stream.read_to_end(&mut buf)?; println!("{}: {} bytes", entry.name(), buf.len()); } Ok(true) })?; ``` -------------------------------- ### Create Encrypted Archive Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/README.md Illustrates how to set up AES256 encryption with a password during archive creation and how to provide the password for decryption. ```rust use sevenz_rust2::{Password, encoder_options::AesEncoderOptions}; let pwd = Password::from("secret"); // Encrypt during compression writer.set_content_methods(vec![ AesEncoderOptions::new(pwd.clone()).into(), EncoderMethod::LZMA2.into(), ]); // Decrypt during decompression let archive = Archive::open_with_password("secure.7z", &pwd)?; ``` -------------------------------- ### Configure Complex Compression Chain Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Sets up a compression chain with a Delta filter followed by LZMA2 compression. This is useful for binary data with gradual changes where Delta can reduce redundancy before LZMA2 provides high-quality compression. ```rust use sevenz_rust2::{ ArchiveWriter, EncoderMethod, EncoderConfiguration, encoder_options::{Lzma2Options, DeltaOptions}, }; use std::fs::File; fn create_optimal_archive() -> Result<(), Box> { let mut writer = ArchiveWriter::create("output.7z")?; // Configure compression chain: // 1. Delta filter (for binary data gradual changes) // 2. LZMA2 compression (multi-threaded, high quality) let lzma2 = Lzma2Options::from_level_mt(9, 4, 2 * 1024 * 1024); writer.set_content_methods(vec![ DeltaOptions::from_distance(1).into(), EncoderConfiguration::new(EncoderMethod::LZMA2) .with_options(EncoderOptions::Lzma2(lzma2)), ]); // Add files writer.push_source_path("./data/", |p| { // Exclude temporary files !p.to_string_lossy().contains(".tmp") })?; writer.finish()?; Ok(()) } ``` -------------------------------- ### Create Archive with Solid Compression Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Compresses a directory's contents as a single block, offering better compression ratios for homogeneous content. ```rust let mut writer = ArchiveWriter::create("archive.7z")?; writer.push_source_path("./data/", |_| true)?; writer.finish()?; ``` -------------------------------- ### Create EncoderConfiguration with Method Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Creates a new encoder configuration with a specified compression method and no additional options. ```rust pub fn new(method: EncoderMethod) -> Self ``` -------------------------------- ### Create New Default Archive Entry Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Initializes a new ArchiveEntry with default, uninitialized fields. ```rust pub fn new() -> Self ``` -------------------------------- ### Low-Level Archive Writer API (Rust) Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/overview.md Use this API for fine-grained control over archive creation. Configure content methods and encryption before adding entries. Requires the `compress` feature. ```rust ArchiveWriter::create(path) → Result, Error> ``` ```rust ArchiveWriter::new(writer) → Result, Error> ``` ```rust writer.set_content_methods(methods) → &mut Self ``` ```rust writer.set_encrypt_header(bool) → () ``` ```rust writer.push_archive_entry(entry, reader) → Result<&ArchiveEntry, Error> ``` ```rust writer.push_source_path(path, filter) → Result<(), Error> ``` ```rust writer.finish() → Result ``` -------------------------------- ### Open 7z Archive by Path Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Use this function to open and parse a 7z archive directly from a filesystem path. Ensure the file exists and has a valid 7z signature. ```rust use sevenz_rust2::Archive; let archive = Archive::open("example.7z")?; println!("Archive contains {} files", archive.files.len()); for file in &archive.files { println!(" - {}", file.name()); } ``` -------------------------------- ### Handle FileNotFound Error in SevenZip Archive Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/errors.md Demonstrates how to open an archive, list its files, and handle a FileNotFound error when accessing a specific file. Verifies file name case sensitivity and path separators. ```rust let mut reader = ArchiveReader::open("archive.7z", Password::empty())?; // List all available files for entry in &reader.archive().files { println!("{}", entry.name()); } // Then access with exact name match reader.read_file("path/to/file.txt") { Ok(data) => println!("Got {} bytes", data.len()), Err(Error::FileNotFound) => eprintln!("File not in archive"), Err(e) => return Err(e), } ``` -------------------------------- ### push_source_path (Solid) Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Compresses a directory and its contents as a single block, enabling better compression ratios for homogeneous data. ```APIDOC ## push_source_path (Solid Compression) ### Description Compresses a directory and its contents as a single block, enabling better compression ratios for homogeneous data. This is the solid compression method. ### Method Signature `pub fn push_source_path(&mut self, source_path: &str, filter: impl Fn(&Path) -> bool) -> Result<()>` ### Parameters * `source_path` (string) - The path to the directory or files to be compressed. * `filter` (closure) - A closure that determines which files to include in the archive. ### Example ```rust let mut writer = ArchiveWriter::create("archive.7z")?; writer.push_source_path("./data/", |_| true)?; writer.finish()?; ``` ``` -------------------------------- ### Configure WASM Build with Specific Features Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Shows how to build for WASM targets by disabling default features and enabling the `default_wasm` feature, along with setting RUSTFLAGS for random number generation. This configuration is necessary for WASM environments where file I/O might be limited. ```bash RUSTFLAGS='--cfg getrandom_backend="wasm_js"' \ cargo build --target wasm32-unknown-unknown \ --no-default-features --features=default_wasm ``` -------------------------------- ### Compress Files to an Encrypted 7z Archive Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/README.md Create a password-protected .7z archive using `compress_to_path_encrypted`. The provided password will be used for AES encryption. ```rust sevenz_rust2::compress_to_path_encrypted("examples/data/sample", "examples/data/sample.7z", "password".into()).expect("compress ok"); ``` -------------------------------- ### ArchiveEntry::new Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Creates a new default archive entry with all fields uninitialized. ```APIDOC ## ArchiveEntry::new ### Description Creates a new default archive entry. ### Method `ArchiveEntry::new()` ### Returns `ArchiveEntry` - Default entry with all fields uninitialized. ``` -------------------------------- ### Create Archive Entry from Filesystem Path Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Generates an ArchiveEntry by reading metadata from a given filesystem path. Handles path conversion on Windows. ```rust pub fn from_path( path: impl AsRef, entry_name: String, ) -> Self ``` ```rust let entry = ArchiveEntry::from_path("./README.md", "README.md".to_string()); assert_eq!(entry.name, "README.md"); assert!(entry.has_last_modified_date || entry.has_creation_date); ``` -------------------------------- ### push_archive_entry (Non-Solid) Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Adds an individual file to the archive, compressing it independently. This is the default non-solid compression method. ```APIDOC ## push_archive_entry (Non-Solid Compression) ### Description Adds an individual file to the archive, compressing it independently. This is the default non-solid compression method, offering advantages in extraction flexibility and parallelization. ### Method Signature `pub fn push_archive_entry(&mut self, entry: ArchiveEntry, data: Option) -> Result<()>` ### Parameters * `entry` (ArchiveEntry) - The metadata for the archive entry. * `data` (Option) - An optional reader for the file content to be compressed. ### Example ```rust let mut writer = ArchiveWriter::create("archive.7z")?; writer.push_archive_entry(entry1, Some(file1))?; writer.push_archive_entry(entry2, Some(file2))?; writer.finish()?; ``` ``` -------------------------------- ### Create Brotli Encoder from Quality and Window Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Instantiates a Brotli encoder with specified quality and window size. The quality ranges from 0-11 (default 11), and window size from 10-24 bits (default 22). ```rust pub const fn from_quality_window(quality: u32, window: u32) -> Self ``` -------------------------------- ### Solid Archive Source Path Push Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/MANIFEST.md Adds a file or directory to a solid archive using its path. ```rust use sevenz_rust::ArchiveWriter; let mut writer = ArchiveWriter::new(); writer.push_source_path("path/to/your/file_or_directory")?; ``` -------------------------------- ### Open Encrypted 7z Archive with Password Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Opens an encrypted 7z archive by providing the file path and the correct password. The password must be UTF-16 LE encoded. Incorrect passwords may result in a `MaybeBadPassword` error. ```rust use sevenz_rust2::{Archive, Password}; let password = Password::from("secret"); let archive = Archive::open_with_password("encrypted.7z", &password)?; for file in &archive.files { println!(" {}", file.name()); } ``` -------------------------------- ### Create Archive with Non-Solid Compression Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Compresses each file independently. Suitable for heterogeneous files and allows for parallel extraction. ```rust let mut writer = ArchiveWriter::create("archive.7z")?; writer.push_archive_entry(entry1, Some(file1))?; writer.push_archive_entry(entry2, Some(file2))?; writer.finish()?; ``` -------------------------------- ### Set Compression Methods Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Configures the compression methods for subsequent entries. The order of methods in the vector matters. Defaults to LZMA2 if not specified. ```rust pub fn set_content_methods( &mut self, content_methods: Vec, ) -> &mut Self ``` ```rust use sevenz_rust2::{ArchiveWriter, EncoderMethod, encoder_options::Lzma2Options}; let mut writer = ArchiveWriter::create("output.7z")?; writer.set_content_methods(vec![ EncoderMethod::LZMA2.into(), ]); ``` -------------------------------- ### Create AesEncoderOptions with Password Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Initializes AES256-SHA256 encryption options using a provided password. This requires the `aes256` feature and is used internally by encrypted compression methods. ```rust pub fn new(password: Password) -> Self ``` -------------------------------- ### Single Compression Method (LZMA2 Default) Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Applies LZMA2 compression with default settings. This is the default behavior if no methods are explicitly set. ```rust let mut writer = ArchiveWriter::create("archive.7z")?; writer.set_content_methods(vec![ EncoderMethod::LZMA2.into(), ]); ``` -------------------------------- ### Bzip2Options Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Options for BZIP2 compression. Requires the `bzip2` feature. ```APIDOC ## Bzip2Options Options for BZIP2 compression (requires `bzip2` feature). ### Struct Definition ```rust pub struct Bzip2Options(pub(crate) u32); ``` ### Methods #### `from_level(level: u32) -> Self` Creates BZIP2 options with compression level. ### Default Level 6. ``` -------------------------------- ### Open ArchiveReader from Path Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Creates an ArchiveReader from a filesystem path. This method is not available on WASM targets. Requires a password for encrypted archives. ```rust #[cfg(not(target_arch = "wasm32"))] pub fn ArchiveReader::open( path: impl AsRef, password: Password, ) -> Result ``` ```rust use sevenz_rust2::{ArchiveReader, Password}; let mut reader = ArchiveReader::open("archive.7z", Password::empty())?; let data = reader.read_file("document.txt")?; println!("File size: {} bytes", data.len()); ``` -------------------------------- ### BrotliOptions Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Options for Brotli compression. Requires the `brotli` feature. ```APIDOC ## BrotliOptions Options for Brotli compression (requires `brotli` feature). ### Struct Definition ```rust pub struct BrotliOptions { pub quality: u32, pub window: u32, pub skippable_frame_size: u32, } ``` ### Fields - `quality` (u32) - Compression quality (0-11) - `window` (u32) - Window size (10-24) - `skippable_frame_size` (u32) - Frame size for skippable frames (0 = none) ### Methods #### `from_quality_window(quality: u32, window: u32) -> Self` Creates Brotli options with quality and window. #### `with_skippable_frame_size(self, size: u32) -> Self` Sets skippable frame size (minimum 64 KiB if non-zero). ### Default Quality 11, window 22, frame size 128 KiB. ``` -------------------------------- ### Set Content Methods Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Use `set_content_methods` to specify compression/encryption methods. Methods are applied in order and chained. ```rust pub fn set_content_methods( &mut self, content_methods: Vec, ) -> &mut Self ``` -------------------------------- ### Configure Archive Compression Method Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/overview.md Specify the compression method chain when writing archives using `EncoderConfiguration`. Requires enabling the corresponding feature (e.g., `lzma2`). ```rust let options = Lzma2Options::from_level(9); let config = EncoderConfiguration::new(EncoderMethod::LZMA2) .with_options(EncoderOptions::Lzma2(options)); writer.set_content_methods(vec![config]); ``` -------------------------------- ### Create LZMA2 Encoder from Level Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Instantiates a multi-threaded LZMA2 encoder with a specified compression level, number of threads, and chunk size. This is the recommended LZMA method. ```rust pub fn from_level_mt(level: u32, threads: u32, chunk_size: u64) -> Self ``` -------------------------------- ### AES256 Encryption Configuration Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/MANIFEST.md Sets up AES256 encryption for the archive. ```rust use sevenz_rust::{ArchiveWriter, EncoderOptions, Method, AesEncoderOptions}; let mut writer = ArchiveWriter::new(); let password = "mysecretpassword"; let options = EncoderOptions::new(Method::Aes256, Some(AesEncoderOptions { password: password.to_string(), ..Default::default() })); writer.set_content_methods(&[options]); ``` -------------------------------- ### Build for WASM with Default Features Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/README.md Compile the crate for WebAssembly targets using specific RUSTFLAGS to enable WASM compatibility and disable default features. ```bash RUSTFLAGS='--cfg getrandom_backend="wasm_js"' cargo build --target wasm32-unknown-unknown --no-default-features --features=default_wasm ``` -------------------------------- ### ArchiveWriter Set Content Methods Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/MANIFEST.md Demonstrates the usage of `ArchiveWriter::set_content_methods` for configuring compression methods. ```rust use sevenz_rust::ArchiveWriter; let mut writer = ArchiveWriter::new(); writer.set_content_methods(&[sevenz_rust::Method::Lzma2]); ``` -------------------------------- ### Add sevenz-rust2 to Dependencies Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/README.md Include the sevenz-rust2 crate in your project's Cargo.toml file to manage dependencies. ```toml [dependencies] sevenz-rust2 = { version = "0.20" } ``` -------------------------------- ### Create LZMA Encoder from Level Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Instantiates an LZMA encoder with a specified compression level. LZMA2 is generally preferred over this legacy method. ```rust pub fn from_level(level: u32) -> Self ``` -------------------------------- ### Create Archive Writer for File Path Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Use this to create a new archive writer targeting a specific file path. Ensure the `compress` feature is enabled. ```rust #[cfg(not(target_arch = "wasm32"))] pub fn ArchiveWriter::create(path: impl AsRef) -> Result ``` ```rust use sevenz_rust2::ArchiveWriter; let mut writer = ArchiveWriter::create("output.7z")?; // ... add entries ... writer.finish()?; ``` -------------------------------- ### Configure Delta Filter with LZMA2 Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Apply a 4-byte delta filter before LZMA2 compression. This is beneficial for binary data with gradual changes, such as image files. ```rust writer.set_content_methods(vec![ DeltaOptions::from_distance(4).into(), // 4-byte delta EncoderMethod::LZMA2.into(), ]); ``` -------------------------------- ### Brotli Compression Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Uses Brotli compression. Requires the `brotli` feature. Allows configuration of quality and window size. ```rust use sevenz_rust2::encoder_options::BrotliOptions; let mut writer = ArchiveWriter::create("archive.7z")?; let options = BrotliOptions::from_quality_window(11, 22); writer.set_content_methods(vec![ EncoderConfiguration::new(EncoderMethod::BROTLI) .with_options(EncoderOptions::Brotli(options)), ]); ``` -------------------------------- ### Brotli Compression Configuration Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/MANIFEST.md Configures Brotli compression for the archive. ```rust use sevenz_rust::{ArchiveWriter, EncoderOptions, Method}; let mut writer = ArchiveWriter::new(); writer.set_content_methods(&[EncoderOptions::new(Method::Brotli, None)]); ``` -------------------------------- ### LzmaOptions Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Configuration options for LZMA compression. ```APIDOC ## LzmaOptions Options for LZMA compression. ### Methods #### `from_level(level: u32) -> Self` Creates LZMA options with compression level (0-9). **Default:** Level 6. ``` -------------------------------- ### Lzma2Options Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Configuration options for LZMA2 compression, allowing control over threads and dictionary size. ```APIDOC ## Lzma2Options Options for LZMA2 compression. ### Struct Fields - `options` (lzma_rust2::Lzma2Options) - Required - LZMA2 codec options - `threads` (u32) - Required - Number of compression threads ### Methods #### `from_level(level: u32) -> Self` Creates LZMA2 options with compression level (0-9, single-threaded). #### `from_level_mt(level: u32, threads: u32, chunk_size: u64) -> Self` Creates LZMA2 options with multi-threaded compression. #### `set_dictionary_size(&mut self, dict_size: u32)` Sets dictionary size (clamped to 4096..=4294967280). **Default:** Level 6, single-threaded. ``` -------------------------------- ### Create Password from Raw Bytes Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Creates a `Password` instance directly from a byte slice. This is useful if the password bytes are already in the correct UTF-16 LE format. ```rust pub fn from_raw(bytes: &[u8]) -> Self ``` -------------------------------- ### Create BZIP2 Encoder from Level Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Instantiates a BZIP2 encoder with a specified compression level. This method requires the 'bzip2' feature to be enabled. ```rust pub const fn from_level(level: u32) -> Self ``` -------------------------------- ### Configure AES256-SHA256 Encryption Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Set up AES256-SHA256 encryption for an archive. This must be the last method in the chain. The password is UTF-16 LE encoded internally. ```rust use sevenz_rust2::{ArchiveWriter, Password, encoder_options::AesEncoderOptions}; let mut writer = ArchiveWriter::create("secure.7z")?; let password = Password::from("secure_password"); writer.set_content_methods(vec![ AesEncoderOptions::new(password).into(), EncoderMethod::LZMA2.into(), ]); writer.push_source_path("./data/", |_| true)?; writer.finish()?; ``` -------------------------------- ### Match SevenZip Archive Errors Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/errors.md Demonstrates how to match against specific SevenZip archive errors using a `match` statement. This is useful for handling different error conditions distinctly. ```rust use sevenz_rust2::{Archive, Error, Password}; match Archive::open("archive.7z") { Ok(archive) => { println!("Archive has {} files", archive.files.len()); } Err(Error::BadSignature(sig)) => { eprintln!("Not a 7z file. Found signature: {:?}", sig); } Err(Error::UnsupportedVersion { major, minor }) => { eprintln!("7z version {}.{} not supported", major, minor); } Err(Error::PasswordRequired) => { eprintln!("Archive is encrypted, please provide password"); } Err(Error::MaybeBadPassword(e)) => { eprintln!("Wrong password or corrupted archive: {}", e); } Err(Error::FileOpen(e, path)) => { eprintln!("Cannot open {}: {}", path, e); } Err(e) => { eprintln!("Error: {:?}", e); } } ``` -------------------------------- ### LZMA2 Compression with Multi-threading Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/MANIFEST.md Enables multi-threading for LZMA2 compression. ```rust use sevenz_rust::{ArchiveWriter, EncoderOptions, Method}; let mut writer = ArchiveWriter::new(); let options = EncoderOptions::new(Method::Lzma2, Some(sevenz_rust::Lzma2Options { threads: 4, ..Default::default() })); writer.set_content_methods(&[options]); ``` -------------------------------- ### Enable Compression Features in Cargo.toml Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/README.md Add desired compression features like 'zstd' or 'brotli' to your Cargo.toml file to resolve 'UnsupportedCompressionMethod' errors. ```toml sevenz-rust2 = { version = "0.21", features = ["zstd", "brotli"] } ``` -------------------------------- ### ArchiveEntry::from_path Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Constructs an ArchiveEntry by extracting metadata from a given filesystem path. ```APIDOC ## ArchiveEntry::from_path ### Description Creates archive entry from filesystem path, extracting metadata. ### Method `ArchiveEntry::from_path(path: impl AsRef, entry_name: String)` ### Parameters #### Path Parameters - **path** (impl AsRef) - Required - Filesystem path to extract metadata from - **entry_name** (String) - Required - Name to use in archive (backslashes converted to forward slashes on Windows) ### Returns `ArchiveEntry` - Entry with metadata from filesystem ### Notes Extracts modification, creation, and access dates from filesystem. On Windows, converts backslashes to forward slashes in entry name. ### Example ```rust let entry = ArchiveEntry::from_path("./README.md", "README.md".to_string()); assert_eq!(entry.name, "README.md"); assert!(entry.has_last_modified_date || entry.has_creation_date); ``` ``` -------------------------------- ### Create Archive Entry for a Directory Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Constructs an ArchiveEntry for a directory, marking it as not having a data stream. ```rust pub fn new_directory(entry_name: &str) -> Self ``` -------------------------------- ### Create Password from String Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Creates a `Password` instance from a string slice. The input string is automatically converted to UTF-16 LE encoding. ```rust pub fn new(password: &str) -> Self ``` -------------------------------- ### Bzip2Options Struct Definition Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Defines the structure for Bzip2 compression options. Requires the `bzip2` feature. ```rust pub struct Bzip2Options(pub(crate) u32); ``` -------------------------------- ### Create Archive Writer for Existing Writer Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Use this to create a new archive writer for an existing `Write + Seek` destination, such as an in-memory buffer. ```rust pub fn ArchiveWriter::new(writer: W) -> Result where W: Write + Seek ``` ```rust use std::io::Cursor; use sevenz_rust2::ArchiveWriter; let cursor = Cursor::new(Vec::new()); let mut writer = ArchiveWriter::new(cursor)?; ``` -------------------------------- ### ArchiveReader::new Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Creates an ArchiveReader from a Read + Seek source. ```APIDOC ## ArchiveReader::new ### Description Creates an ArchiveReader from a Read + Seek source. ### Method Signature ```rust pub fn ArchiveReader::new< R: Read + Seek, >(source: R, password: Password) -> Result ``` ### Parameters #### Path Parameters - **source** (`R: Read + Seek`) - Required - Reader at archive start - **password** (`Password`) - Required - Archive password ### Returns `Result, Error>` — Reader for decompression ### Example ```rust use std::io::Cursor; use sevenz_rust2::{ArchiveReader, Password}; let data = std::fs::read("archive.7z")?; let cursor = Cursor::new(data); let mut reader = ArchiveReader::new(cursor, Password::empty())?; let file_data = reader.read_file("file.txt")?; ``` ``` -------------------------------- ### High-Level Convenience Functions Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/overview.md These functions provide a simple interface for common file compression and decompression tasks. Some functions require specific features to be enabled. ```APIDOC ## High-Level Convenience Functions (Require `util` feature; some require `compress` feature) ### Decompression - `decompress_file(src: &str, dest: &str) -> Result<(), Error>`: Decompresses a file from `src` to `dest`. - `decompress_file_with_password(src: &str, dest: &str, pwd: &str) -> Result<(), Error>`: Decompresses a password-protected file from `src` to `dest`. ### Compression - `compress_to_path(src: &str, dest: &str) -> Result<(), Error>`: Compresses a file from `src` to `dest`. - `compress_to_path_encrypted(src: &str, dest: &str, pwd: &str) -> Result<(), Error>`: Compresses a file from `src` to `dest` with password protection. ``` -------------------------------- ### ArchiveReader::open Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Creates an ArchiveReader from a filesystem path. This method is not available on WASM targets. ```APIDOC ## ArchiveReader::open ### Description Creates an ArchiveReader from a filesystem path (non-WASM only). ### Method Signature ```rust #[cfg(not(target_arch = "wasm32"))] pub fn ArchiveReader::open( path: impl AsRef, password: Password, ) -> Result ``` ### Parameters #### Path Parameters - **path** (`impl AsRef`) - Required - Path to 7z archive - **password** (`Password`) - Required - Archive password ### Returns `Result, Error>` — Reader for archive decompression ### Example ```rust use sevenz_rust2::{ArchiveReader, Password}; let mut reader = ArchiveReader::open("archive.7z", Password::empty())?; let data = reader.read_file("document.txt")?; println!("File size: {} bytes", data.len()); ``` ``` -------------------------------- ### Bzip2 Compression Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Uses Bzip2 compression. Requires the `bzip2` feature. Allows configuration of the compression level. ```rust use sevenz_rust2::encoder_options::Bzip2Options; let mut writer = ArchiveWriter::create("archive.7z")?; let options = Bzip2Options::from_level(9); writer.set_content_methods(vec![ EncoderConfiguration::new(EncoderMethod::BZIP2) .with_options(EncoderOptions::Bzip2(options)), ]); ``` -------------------------------- ### Iterate Archive Entries with Callback Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Use this method to process each entry within an archive. The closure receives entry metadata and a reader for its decompressed data. Returning `false` from the closure stops the iteration. Be aware of performance implications for solid archives. ```rust let mut reader = ArchiveReader::open("archive.7z", Password::empty())?; reader.for_each_entries(|entry, reader| { if entry.is_directory() { println!("DIR: {}", entry.name()); } else { println!("FILE: {} ({} bytes)", entry.name(), entry.size()); // Read file data if needed let mut buf = Vec::new(); reader.read_to_end(&mut buf)?; } Ok(true) // Continue iteration })?; ``` -------------------------------- ### ArchiveWriter::create Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Creates a new archive writer for a file path. This is the entry point for creating a new .7z file. ```APIDOC ## ArchiveWriter::create ### Description Creates a new archive writer for a file path. ### Method `pub fn create(path: impl AsRef) -> Result` ### Parameters #### Path Parameters - **path** (`impl AsRef`) - Yes - Output .7z file path ### Returns `Result>` ### Request Example ```rust use sevenz_rust2::ArchiveWriter; let mut writer = ArchiveWriter::create("output.7z")?; // ... add entries ... writer.finish()?; ``` ``` -------------------------------- ### Password Conversions (From<&str>) Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Provides conversion from string slices to Password objects using `into()` or `from()`. ```APIDOC ## Password Conversions ### Description Convert string to password via `into()` or `from()`. ### Method Signature ```rust impl From<&str> for Password ``` ### Parameters None ### Request Example ```rust let pwd: Password = "secret".into(); ``` ### Response #### Success Response - **Password** (`Self`) - The converted Password object. #### Response Example None provided. ``` -------------------------------- ### ZSTD Compression Configuration Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/MANIFEST.md Configures ZSTD compression for the archive. ```rust use sevenz_rust::{ArchiveWriter, EncoderOptions, Method}; let mut writer = ArchiveWriter::new(); writer.set_content_methods(&[EncoderOptions::new(Method::Zstd, None)]); ``` -------------------------------- ### Add Source Path Recursively (Solid) Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Adds a file or directory recursively to the archive using solid compression. A filter function can be provided to include or exclude specific paths. ```rust pub fn push_source_path bool>( &mut self, path: impl AsRef, filter: F, ) -> Result<()> ``` ```rust use sevenz_rust2::ArchiveWriter; let mut writer = ArchiveWriter::create("solid.7z")?; writer.push_source_path("./src/", |path| { !path.to_string_lossy().contains(".git") })?; writer.finish()?; ``` -------------------------------- ### High-Level Compression Functions (Rust) Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/overview.md These functions provide convenient ways to compress files. `compress_to_path_encrypted` allows for password-protected compression. ```rust compress_to_path(src, dest) → Result<(), Error> ``` ```rust compress_to_path_encrypted(src, dest, pwd) → Result<(), Error> ``` -------------------------------- ### Query Archive Entry Creation Date Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Retrieves the creation timestamp of the archive entry. ```rust pub fn creation_date(&self) -> NtTime ``` -------------------------------- ### Define LZMA Compression Options Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Defines the structure for LZMA compression options, wrapping the underlying lzma_rust2 options. Used for configuring archive compression. ```rust pub struct LzmaOptions(pub(crate) lzma_rust2::LzmaOptions); ``` -------------------------------- ### Block Methods Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Provides methods to retrieve information about a compression block, such as total uncompressed size and coder details. ```APIDOC ## Block Represents a compression block containing one or more coders (compression/filter methods). ### Methods ```rust pub fn get_unpack_size(&self) -> u64 ``` Returns total uncompressed size of block data. ```rust pub fn get_unpack_size_for_coder(&self, coder: &Coder) -> u64 ``` Returns uncompressed size for specific coder. ```rust pub fn get_unpack_size_at_index(&self, index: usize) -> u64 ``` Returns uncompressed size for coder at index. ```rust pub fn ordered_coder_iter(&self) -> OrderedCoderIter<'_> ``` Returns iterator over coders in processing order. ``` -------------------------------- ### LZMA2 Compression with Custom Level Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/MANIFEST.md Configures LZMA2 compression with a specific compression level. ```rust use sevenz_rust::{ArchiveWriter, EncoderOptions, Method}; let mut writer = ArchiveWriter::new(); let options = EncoderOptions::new(Method::Lzma2, Some(sevenz_rust::Lzma2Options { level: 9, ..Default::default() })); writer.set_content_methods(&[options]); ``` -------------------------------- ### Query Archive Entry Name Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Retrieves the name or path of the archive entry. ```rust pub fn name(&self) -> &str ``` -------------------------------- ### Compress File or Directory to Path Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Compresses a file or directory into a .7z archive at the specified destination path. This function is not available for WebAssembly targets. ```rust use sevenz_rust2::compress_to_path; compress_to_path("./data/", "archive.7z")?; ``` -------------------------------- ### Low-Level Archive Writer API Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/overview.md This API provides fine-grained control over creating and writing archive files, including configuring compression methods and encryption. Requires the `compress` feature. ```APIDOC ## Low-Level Archive Writer API (with `compress` feature) ### Creating Writers - `ArchiveWriter::create(path: &str) -> Result, Error>`: Creates a new archive writer to a file path. - `ArchiveWriter::new(writer: W) -> Result, Error>`: Creates a new archive writer for a generic `Write` trait object. ### Configuring Writer - `writer.set_content_methods(methods: Vec) -> &mut Self`: Sets the content compression methods for the archive entries. - `writer.set_encrypt_header(bool)`: Configures whether the archive header should be encrypted. ### Adding Entries - `writer.push_archive_entry(entry: ArchiveEntry, reader: impl Read) -> Result<&ArchiveEntry, Error>`: Adds a single archive entry with its content from a reader. - `writer.push_source_path(path: &str, filter: Option bool>) -> Result<(), Error>`: Adds all files from a source path to the archive, with an optional filter. ### Finalizing Archive - `writer.finish() -> Result`: Finalizes the archive writing process and returns the underlying writer. ``` -------------------------------- ### Password::new Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Creates a new Password object from a given string slice. The password string is internally converted to UTF-16 LE. ```APIDOC ## Password::new ### Description Creates password from string. ### Method Signature ```rust pub fn new(password: &str) -> Self ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **password** (`&str`) - Required - Password string (converted to UTF-16 LE internally) ### Request Example ```rust use sevenz_rust2::Password; let pwd = Password::new("my_password"); ``` ### Response #### Success Response - **Password** (`Self`) - The newly created Password object. #### Response Example None provided. ``` -------------------------------- ### Create Archive Entry for a File Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/api-reference.md Constructs an ArchiveEntry specifically for a file, ensuring it's marked as having a data stream. ```rust pub fn new_file(entry_name: &str) -> Self ``` ```rust let entry = ArchiveEntry::new_file("document.txt"); assert!(entry.has_stream); assert!(!entry.is_directory); ``` -------------------------------- ### Propagate SevenZip Errors with Context Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/errors.md Illustrates how to propagate SevenZip errors using the `?` operator within a function that returns a `Result`. This allows errors to be automatically returned up the call stack. ```rust fn extract_all(path: &str) -> Result<(), Error> { let archive = Archive::open(path)?; let mut reader = ArchiveReader::new(file, Password::empty())?; reader.for_each_entries(|entry, mut data| { // Read data or return error let mut buf = Vec::new(); data.read_to_end(&mut buf)?; Ok(true) })?; Ok(()) } ``` -------------------------------- ### EncoderMethod Constant Methods Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/types.md Provides access to the human-readable name and binary ID of compression methods. Used for identifying and configuring compression algorithms. ```rust pub const fn name(&self) -> &'static str ``` ```rust pub const fn id(&self) -> &'static [u8] ``` -------------------------------- ### Zstandard (ZSTD) Compression Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Uses Zstandard compression. Requires the `zstd` feature. ```rust let mut writer = ArchiveWriter::create("archive.7z")?; writer.set_content_methods(vec![ EncoderMethod::ZSTD.into(), ]); ``` -------------------------------- ### Non-solid Archive Entry Push Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/MANIFEST.md Adds a single file entry to a non-solid archive. ```rust use sevenz_rust::ArchiveWriter; use std::fs::File; let mut writer = ArchiveWriter::new(); let mut file = File::open("path/to/your/file.txt")?; writer.push_archive_entry("entry_name.txt", &mut file)?; ``` -------------------------------- ### Password Creation for Encryption Source: https://github.com/hasenbanck/sevenz-rust2/blob/main/_autodocs/configuration.md Create a Password object for encryption. It can be created directly from a string or from pre-encoded raw bytes. ```rust use sevenz_rust2::Password; let pwd: Password = "my_password".into(); // Or from raw bytes (pre-encoded UTF-16 LE): let pwd = Password::from_raw(utf16_bytes); ```