### Complete Gzip Workflow Example Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/README.md Demonstrates a full workflow from creating sample data, compressing it, checking its format, and decompressing it with error handling. This example covers the essential steps for using the GzipSwift library. ```swift import Foundation import Gzip // 1. Get data (from network, file, etc.) let data = "Sample data".data(using: .utf8)! // 2. Compress with appropriate level let compressed = try data.gzipped(level: .bestCompression) // 3. Check format print(compressed.isGzipped) // true // 4. Decompress with error handling do { let decompressed = try compressed.gunzipped() print(String(data: decompressed, encoding: .utf8)!) } catch let error as GzipError { print("Error: (error.message)") } ``` -------------------------------- ### Initializer Example Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md Demonstrates creating a CompressionLevel instance using its raw value and then using it for compression. ```swift let level = CompressionLevel(rawValue: 5) let compressed = try data.gzipped(level: level) ``` -------------------------------- ### Docker Example for Swift Application with GzipSwift Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/INTEGRATION.md A Dockerfile to build and run a Swift application on Linux, ensuring zlib development files are installed. Sets up the environment for a release build and defines the entry point. ```dockerfile FROM swift:latest RUN apt-get update && apt-get install -y zlib1g-dev WORKDIR /app COPY . . RUN swift build -c release CMD ["./.build/release/MyApp"] ``` -------------------------------- ### Convenience Initializer Example Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md Shows how to create a CompressionLevel using the convenience initializer and apply it to data compression. ```swift let level = CompressionLevel(7) let compressed = try data.gzipped(level: level) ``` -------------------------------- ### Hashable Conformance Example Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md Illustrates using CompressionLevel instances as keys in a dictionary, leveraging their Hashable conformance. ```swift var compressionSettings: [CompressionLevel: String] = [ .bestSpeed: "Real-time streaming", .bestCompression: "Archival storage", .defaultCompression: "General purpose" ] ``` -------------------------------- ### Comparable Conformance Example Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md Demonstrates comparing CompressionLevel instances based on their raw values and sorting an array of compression levels. ```swift let level1 = CompressionLevel.bestSpeed // rawValue: 1 let level2 = CompressionLevel.bestCompression // rawValue: 9 if level1 < level2 { print("bestSpeed is lower than bestCompression") } let levels = [ CompressionLevel(5), CompressionLevel(2), CompressionLevel(8) ].sorted() // Result: [CompressionLevel(2), CompressionLevel(5), CompressionLevel(8)] ``` -------------------------------- ### Example Usage of maxWindowBits Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/types.md Demonstrates how to use the maxWindowBits constant with different wBits values to specify gzip, zlib, or auto-detection formats for compression and decompression. ```swift import Gzip // Standard gzip format (default) let data = try input.gzipped(wBits: maxWindowBits + 16) // Zlib format let zlibData = try input.gzipped(wBits: maxWindowBits) // Auto-detect format during decompression let decompressed = try data.gunzipped(wBits: maxWindowBits + 32) ``` -------------------------------- ### Install zlib for Linux Source: https://github.com/1024jp/gzipswift/blob/main/README.md Installs the zlib development library on Debian-based Linux systems, which is required for GzipSwift. ```bash $ apt-get install zlib1g-dev ``` -------------------------------- ### Build Swift Project on Linux Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/INTEGRATION.md Standard command to build a Swift project on Linux. Includes an option to specify linker paths if zlib is installed in a non-standard location. ```bash # Standard build swift build # If zlib is in non-standard location swift build -Xlinker -L/usr/local/lib ``` -------------------------------- ### Link zlib on Linux Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/INTEGRATION.md Provides commands to install the zlib development library on Linux systems and rebuild the project. This is necessary if the 'Symbol not found: _deflateInit2_' error occurs. ```bash # macOS (usually automatic) swift build # Linux apt-get install zlib1g-dev swift build ``` -------------------------------- ### Quick Start: Compress, Check, and Decompress Data Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/API.md Demonstrates the basic usage of GzipSwift for compressing data, checking if it's gzipped, and then decompressing it. Shows how to use default and custom compression levels. ```swift import Foundation import Gzip // Compress data let originalData = "Hello, World!".data(using: .utf8)! let compressedData = try originalData.gzipped() // Check if data is gzip-compressed if compressedData.isGzipped { // Decompress data let decompressed = try compressedData.gunzipped() print(String(data: decompressed, encoding: .utf8)!) } // Custom compression level let highlyCompressed = try originalData.gzipped(level: .bestCompression) let fastCompressed = try originalData.gzipped(level: .bestSpeed) ``` -------------------------------- ### Handling Unknown Gzip Errors Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/gzip-error.md Example demonstrating how to catch and identify an unknown GzipError by checking if the error kind is .unknown and extracting the associated numeric code. ```swift do { try data.gzipped() } catch let error as GzipError { if case .unknown(let code) = error.kind { print("Unknown error code: \(code)") } } ``` -------------------------------- ### Linux zlib Prerequisite Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/README.md On Linux systems, ensure the zlib development library is installed before using GzipSwift. This is typically done using the system's package manager. ```bash sudo apt-get install zlib1g-dev ``` -------------------------------- ### Switching on GzipError Kind Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/gzip-error.md This example demonstrates how to use a switch statement to handle different GzipError kinds, providing specific messages for stream, data, memory, buffer, version, and unknown errors. ```swift do { let result = try data.gunzipped() } catch let error as GzipError { switch error.kind { case .stream: print("Invalid compression stream") case .data: print("Corrupted data") case .memory: print("Out of memory") case .buffer: print("Incomplete data") case .version: print("Version mismatch") case .unknown(let code): print("Unknown error: \(code)") } } ``` -------------------------------- ### Handling Data Errors in Gzip Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/gzip-error.md Example showing how to catch and identify a GzipError of kind .data, which occurs when attempting to decompress non-gzip data or if the gzip data is corrupted. ```swift let plainData = "Hello, World!".data(using: .utf8)! do { try plainData.gunzipped() // Not gzip data } catch let error as GzipError { if error.kind == .data { print("Invalid gzip data: \(error.message)") } } ``` -------------------------------- ### GzipError Fallback Message Example Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md Demonstrates how to access the fallback error message for a GzipError when the underlying zlib provides no specific message. This is useful for providing user-friendly error feedback. ```swift // Example of fallback message let error = GzipError(code: -5, msg: nil) print(error.message) // Prints fallback message ``` -------------------------------- ### Handling Stream Errors in Gzip Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/gzip-error.md Example demonstrating how to catch and identify a GzipError of kind .stream, typically caused by invalid stream parameters like an incorrect wBits value. ```swift do { try data.gzipped(wBits: 1000) // Invalid wBits } catch let error as GzipError { if error.kind == .stream { print("Invalid stream parameters: \(error.message)") } } ``` -------------------------------- ### Comprehensive Gzip Error Handling Pattern Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md A detailed pattern for processing compressed data, checking if it's gzipped, and then decompressing it. This example maps specific GzipError kinds to custom NSError objects for more granular error reporting. ```swift import Foundation import Gzip func processCompressedData(_ data: Data) throws -> Data { do { if data.isGzipped { let decompressed = try data.gunzipped() return decompressed } else { return data } } catch let error as GzipError { switch error.kind { case .stream: throw NSError( domain: "GzipError", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid compression stream: \(error.message)"] ) case .data: throw NSError( domain: "GzipError", code: -2, userInfo: [NSLocalizedDescriptionKey: "Corrupted data: \(error.message)"] ) case .memory: throw NSError( domain: "GzipError", code: -3, userInfo: [NSLocalizedDescriptionKey: "Insufficient memory"] ) case .buffer: throw NSError( domain: "GzipError", code: -4, userInfo: [NSLocalizedDescriptionKey: "Incomplete data: \(error.message)"] ) case .version: throw NSError( domain: "GzipError", code: -5, userInfo: [NSLocalizedDescriptionKey: "Version incompatibility: \(error.message)"] ) case .unknown(let code): throw NSError( domain: "GzipError", code: Int(code), userInfo: [NSLocalizedDescriptionKey: "Unknown error: \(error.message)"] ) } } } ``` -------------------------------- ### Basic Usage with Default Compression Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md Shows how to compress data using the default compression level, and explicitly using the `.defaultCompression` constant. ```swift import Foundation import Gzip let data = "Sample text".data(using: .utf8)! // Use default compression level let compressed = try data.gzipped() // Explicit default let alsoCompressed = try data.gzipped(level: .defaultCompression) ``` -------------------------------- ### Compressing Data with Different Levels Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/API.md Demonstrates how to compress data using predefined and custom compression levels. Shows comparison of levels. ```swift let level = CompressionLevel.bestCompression let data = try input.gzipped(level: level) // Custom levels 0-9 for level in 0...9 { let compressed = try input.gzipped(level: CompressionLevel(Int32(level))) } // Comparison if CompressionLevel(3) < CompressionLevel(7) { print("Level 3 is lower than level 7") } ``` -------------------------------- ### Choose Gzip Compression Level Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/INTEGRATION.md Demonstrates selecting different compression levels for GzipSwift, balancing speed and compression ratio. ```swift import Gzip let data = /* large data */ // For real-time or streaming scenarios let fastCompressed = try data.gzipped(level: .bestSpeed) // For storage or archival let smallCompressed = try data.gzipped(level: .bestCompression) // For balanced performance (default) let standardCompressed = try data.gzipped() // For no compression (just gzip container) let noCompressionData = try data.gzipped(level: .noCompression) ``` -------------------------------- ### Convenience Initializer Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md A convenience initializer to create a CompressionLevel from a numeric raw value. ```swift public init(_ rawValue: Int32) { // Implementation details omitted for brevity } ``` -------------------------------- ### Downloading and Decompressing with Incomplete Download Handling Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md Illustrates a process for downloading data from a URL and then decompressing it. It includes error handling for the .buffer error during decompression, suggesting a retry mechanism if the download appears incomplete. ```swift import Gzip // For network downloads, ensure complete data reception func downloadAndDecompress(from url: URL) throws -> Data { let data = try Data(contentsOf: url) // Verify download completed (file size matches Content-Length) do { return try data.gunzipped() } catch let error as GzipError { if error.kind == .buffer { print("Download incomplete; re-downloading...") // Retry download throw error } } } ``` -------------------------------- ### Common Usage Patterns Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/API.md Illustrates common ways to use the GzipSwift library for decompression, compression with level selection, and error handling. ```APIDOC ## Common Usage Patterns ### Pattern 1: Safe Decompression Ensures data is decompressed only if it's gzipped, with robust error handling. ```swift import Foundation import Gzip let data = /* from network or file */ if data.isGzipped { do { let decompressed = try data.gunzipped() // Process decompressed data } catch let error as GzipError { print("Decompression failed: \(error.message)") } } else { // Use data as-is } ``` ### Pattern 2: Compression with Level Selection Demonstrates how to compress data using different compression levels based on requirements (size vs. speed). ```swift import Gzip let data = /* to compress */ // Choose level based on use case let compressedSmall = try data.gzipped(level: .bestCompression) // Smaller, slower let compressedFast = try data.gzipped(level: .bestSpeed) // Larger, faster let compressedDefault = try data.gzipped() // Balanced (default) ``` ### Pattern 3: Error Handling with Recovery Shows how to handle specific errors, like data corruption, by falling back to the original data. ```swift import Gzip func decompressWithFallback(_ data: Data) -> Data { do { if data.isGzipped { return try data.gunzipped() } return data } catch let error as GzipError { if error.kind == .data { print("Data is corrupted, using original") return data } // For other errors, can't recover fatalError("Unexpected error: \(error.message)") } } ``` ``` -------------------------------- ### Compression with Level Selection Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/API.md Shows how to compress data using different compression levels, including best compression, best speed, and default. ```swift import Gzip let data = /* to compress */ // Choose level based on use case let compressedSmall = try data.gzipped(level: .bestCompression) // Smaller, slower let compressedFast = try data.gzipped(level: .bestSpeed) // Larger, faster let compressedDefault = try data.gzipped() // Balanced (default) ``` -------------------------------- ### Selecting Compression Strategy Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md Choose the compression level based on your needs: .bestSpeed for real-time scenarios, .bestCompression for storage/transmission, and .noCompression for archive without compression overhead. ```swift import Foundation import Gzip let largeData = /* ... */ // For streaming or real-time scenarios let fastCompressed = try largeData.gzipped(level: .bestSpeed) // For storage or network transmission where bandwidth is expensive let smallCompressed = try largeData.gzipped(level: .bestCompression) // For archive without compression overhead let noCompressionData = try largeData.gzipped(level: .noCompression) ``` -------------------------------- ### Basic Gzip Error Handling Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/gzip-error.md Demonstrates basic try-catch block for handling potential GzipErrors during compression or decompression. ```swift import Foundation import Gzip let data = "Sample data".data(using: .utf8)! do { let compressed = try data.gzipped(level: .bestCompression) let decompressed = try compressed.gunzipped() } catch let error as GzipError { print("Gzip operation failed: \(error.message)") } ``` -------------------------------- ### Handling Empty Data with Gzip Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/gzip-error.md Demonstrates that empty Data can be compressed but will result in a .data GzipError when attempting to decompress. ```swift import Foundation import Gzip let emptyData = Data() // Empty data can be compressed let compressedEmpty = try emptyData.gzipped() print(compressedEmpty.isGzipped) // true // But empty data cannot be decompressed do { try emptyData.gunzipped() } catch let error as GzipError { print(error.kind) // .data print(error.message) // "Input data is empty." } ``` -------------------------------- ### Basic Error Handling Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/gzip-error.md Demonstrates the fundamental way to handle potential GzipErrors using a `do-catch` block. ```APIDOC ## Basic Error Handling ```swift import Foundation import Gzip let data = "Sample data".data(using: .utf8)! do { let compressed = try data.gzipped(level: .bestCompression) let decompressed = try compressed.gunzipped() } catch let error as GzipError { print("Gzip operation failed: \(error.message)") } ``` ``` -------------------------------- ### Select Compression Level for GzipSwift Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/INTEGRATION.md Provides guidance on choosing the appropriate compression level based on the target platform and use case. Different levels offer trade-offs between compression ratio, speed, and resource usage. ```swift // iOS/Watch (battery-sensitive): use balanced or fast let level: CompressionLevel = .defaultCompression // Backend processing: use maximum compression let level: CompressionLevel = .bestCompression // Real-time streaming: use fast compression let level: CompressionLevel = .bestSpeed ``` -------------------------------- ### Load and Decompress Data from Disk Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/INTEGRATION.md Loads data from a file path, checks if it's Gzip-compressed, and decompresses it if necessary. ```swift import Foundation import Gzip func loadAndDecompress(from filePath: String) throws -> Data { let compressed = try Data(contentsOf: URL(fileURLWithPath: filePath)) if compressed.isGzipped { return try compressed.gunzipped() } else { return compressed } } // Usage let data = try loadAndDecompress(from: "/tmp/data.gz") let text = String(data: data, encoding: .utf8) ``` -------------------------------- ### Core API for GzipSwift Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/README.md Demonstrates the basic usage of GzipSwift for compressing and decompressing data, and checking if data is gzipped. Ensure data is available before calling these methods. ```swift let compressed = try data.gzipped(level: .defaultCompression) let original = try compressed.gunzipped() if data.isGzipped { // ... } ``` -------------------------------- ### GzipError Initializer Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/gzip-error.md Details the `init(code:msg:)` initializer for creating GzipError instances. ```APIDOC ## Initializers ### init(code:msg:) Creates a GzipError from a zlib error code and C string message. ```swift init(code: Int32, msg: UnsafePointer?) ``` **Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `code` | `Int32` | Yes | The numeric error code returned by zlib. Mapped to Kind enum values (Z_STREAM_ERROR, Z_DATA_ERROR, etc.). | | `msg` | `UnsafePointer?` | Yes | The C string error message from zlib, or nil if no message available. | **Description** This initializer is primarily for internal use by GzipSwift during error conversion from zlib return codes. It automatically maps zlib error codes to appropriate `Kind` values and converts C strings to Swift String. ``` -------------------------------- ### CompressionLevel Initializers Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md This snippet covers the initializers for the CompressionLevel struct, allowing creation from raw numeric values. ```APIDOC ## CompressionLevel Initializers ### init(rawValue:) Creates a compression level from a numeric raw value. ```swift public init(rawValue: Int32) ``` **Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `rawValue` | `Int32` | Yes | Compression level value from 0 (no compression) to 9 (maximum compression), or -1 for default compression. Values outside this range are passed to zlib unchanged. | **Returns** A new `CompressionLevel` instance with the specified raw value. **Example** ```swift let level = CompressionLevel(rawValue: 5) let compressed = try data.gzipped(level: level) ``` ### init(_:) Creates a compression level from a numeric raw value (convenience initializer). ```swift public init(_ rawValue: Int32) ``` **Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `rawValue` | `Int32` | Yes | Compression level value from 0 to 9, or -1 for default. | **Returns** A new `CompressionLevel` instance with the specified raw value. **Example** ```swift let level = CompressionLevel(7) let compressed = try data.gzipped(level: level) ``` ``` -------------------------------- ### Using Custom Compression Levels Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md Iterate through custom compression levels from 0 to 9 to find the optimal balance between compression and speed for your data. ```swift import Gzip let data = /* ... */ // Medium compression (levels 0-9 are supported) for level in 0...9 { let compressed = try data.gzipped(level: CompressionLevel(Int32(level))) print("Level \(level): \(compressed.count) bytes") } ``` -------------------------------- ### Handling zlib Version Incompatibility Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md Shows how to catch and handle the .version error, which indicates an incompatibility between the zlib library version used at compile time and the one present at runtime. It suggests rebuilding the application or reinstalling zlib. ```swift do { try data.gzipped() } catch let error as GzipError { if error.kind == .version { print("zlib version incompatibility: \(error.message)") print("Rebuild application or reinstall zlib") } } ``` -------------------------------- ### Import Gzip Library Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/API.md The basic import statement required to use the Gzip library in your Swift project. ```swift import Gzip ``` -------------------------------- ### Comparing Compression Levels Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md Compare different compression levels using standard comparison operators and find the minimum level among predefined options. ```swift import Gzip let level1 = CompressionLevel(3) let level2 = CompressionLevel(7) if level1 < level2 { print("Level 3 is lower than level 7") } let minLevel = min(.bestSpeed, .bestCompression, .defaultCompression) print("Minimum level: \(minLevel.rawValue)") ``` -------------------------------- ### Handling Empty Data Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/gzip-error.md Explains the behavior of GzipError when dealing with empty data, both for compression and decompression. ```APIDOC ## Handling Empty Data ```swift import Foundation import Gzip let emptyData = Data() // Empty data can be compressed let compressedEmpty = try emptyData.gzipped() print(compressedEmpty.isGzipped) // true // But empty data cannot be decompressed do { try emptyData.gunzipped() } catch let error as GzipError { print(error.kind) // .data print(error.message) // "Input data is empty." } ``` ``` -------------------------------- ### Initializer with Raw Value Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md Creates a CompressionLevel instance from a numeric raw value. The raw value can range from 0 to 9, or -1 for default. ```swift public init(rawValue: Int32) { // Implementation details omitted for brevity } ``` -------------------------------- ### Handling Corrupted Gzip Data Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md Demonstrates catching a .data error when attempting to gunzip corrupted or incomplete gzip data. ```swift let corruptedData = /* incomplete gzip download */ do { try corruptedData.gunzipped() // Triggers .data error } catch let error as GzipError { if error.kind == .data { print("Corrupted gzip data: \(error.message)") } } ``` -------------------------------- ### Check Gzip Format Before Decompression Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md This strategy demonstrates the best practice of verifying if data is gzipped using `isGzipped` before attempting decompression. This prevents potential errors and allows direct use of data if it's not compressed. ```swift // Best practice: verify gzip format before decompressing let data = /* from network, file, or other source */ if data.isGzipped { do { let decompressed = try data.gunzipped() // Use decompressed data } catch { // Handle decompression error } } else { // Use data directly } ``` -------------------------------- ### Auto-Detection for Unknown Format Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md Shows how to use a specific wBits value to enable auto-detection of zlib or gzip format during decompression, catching potential .data errors. ```swift // Use auto-detection for unknown format do { let decompressed = try data.gunzipped(wBits: maxWindowBits + 32) print("Successfully decompressed") } catch let error as GzipError { if error.kind == .data { print("Invalid compression format or corrupted data") } } ``` -------------------------------- ### Default Compression and Decompression Parameters Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/API.md Shows the default parameters for gzip compression and decompression functions. Compression defaults to gzip format, while decompression defaults to auto-detecting the format. ```swift // Compression defaults to gzip format func gzipped(level: CompressionLevel = .defaultCompression, wBits: Int32 = maxWindowBits + 16) ``` ```swift // Decompression defaults to auto-detect format func gunzipped(wBits: Int32 = maxWindowBits + 32) ``` -------------------------------- ### gzipswift Type Structure Overview Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/types.md This snippet illustrates the hierarchical structure of key types in the gzipswift library, including extensions, properties, methods, and enums, showing their relationships and members. ```Swift Data (Foundation) ├── Extension: Data+Gzip │ ├── var isGzipped: Bool │ ├── func gzipped(level: CompressionLevel = .defaultCompression, wBits: Int32 = maxWindowBits + 16) throws(GzipError) -> Data │ └── func gunzipped(wBits: Int32 = maxWindowBits + 32) throws(GzipError) -> Data │ GzipError (Error thrown by Data methods) ├── var kind: GzipError.Kind ├── var message: String └── enum Kind ├── case stream ├── case data ├── case memory ├── case buffer ├── case version └── case unknown(code: Int) CompressionLevel (Parameter for gzipped()) ├── var rawValue: Int32 ├── static let noCompression ├── static let bestSpeed ├── static let bestCompression └── static let defaultCompression ``` -------------------------------- ### CompressionLevel Conformances Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md This snippet details the conformances of the CompressionLevel struct to protocols like Comparable, Hashable, and Sendable. ```APIDOC ## CompressionLevel Conformances ### Comparable `CompressionLevel` conforms to `Comparable` to allow ordering and comparison operations. ```swift public static func < (lhs: Self, rhs: Self) -> Bool ``` Comparison is based on `rawValue`. Note that `.defaultCompression` (value -1) compares less than other levels despite representing automatic selection. **Example** ```swift let level1 = CompressionLevel.bestSpeed // rawValue: 1 let level2 = CompressionLevel.bestCompression // rawValue: 9 if level1 < level2 { print("bestSpeed is lower than bestCompression") } let levels = [ CompressionLevel(5), CompressionLevel(2), CompressionLevel(8) ].sorted() // Result: [CompressionLevel(2), CompressionLevel(5), CompressionLevel(8)] ``` ### Hashable `CompressionLevel` can be used as a dictionary key or in sets due to `Hashable` conformance. ```swift var compressionSettings: [CompressionLevel: String] = [ .bestSpeed: "Real-time streaming", .bestCompression: "Archival storage", .defaultCompression: "General purpose" ] ``` ### Sendable `CompressionLevel` is safe to pass across Swift concurrency boundaries. ``` -------------------------------- ### gzipped(level:wBits:) Method Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/data-gzip.md Compresses the receiver using zlib in gzip format. ```APIDOC ## gzipped(level:wBits:) Method ### Description Compresses the receiver using zlib in gzip format. ### Signature ```swift public func gzipped( level: CompressionLevel = .defaultCompression, wBits: Int32 = maxWindowBits + 16 ) throws(GzipError) -> Data ``` ### Parameters #### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `level` | `CompressionLevel` | No | `.defaultCompression` | The compression level controlling the tradeoff between compression ratio and speed. Valid levels range from 0 (no compression) to 9 (maximum compression). | | `wBits` | `Int32` | No | `maxWindowBits + 16` | The size of the history buffer (window size) in powers of 2. Default adds 16 to `maxWindowBits` to enable gzip format with header and trailer. Range: +25 to +31 for gzip, +9 to +15 for zlib, -9 to -15 for raw deflate. | ### Returns `Data` — A new Data instance containing the gzip-compressed content. Even if the input is empty, returns a valid gzip stream representing empty data. ### Throws `GzipError` — Thrown if compression fails. Possible error kinds: - `.stream` — The compression stream structure was invalid (Z_STREAM_ERROR) - `.memory` — Insufficient memory for compression (Z_MEM_ERROR) - `.version` — Zlib version incompatibility (Z_VERSION_ERROR) Throws if the input data exceeds `UInt.max` bytes with `.stream` kind and message "Input data is too large to compress." ### Description The method uses zlib's DEFLATE algorithm to compress the data. The `wBits` parameter controls the compression format through the following values: - **+25 to +31**: Gzip format (includes gzip header and trailing checksum) - **+9 to +15**: Zlib format (includes zlib header and trailer) - **-9 to -15**: Raw deflate (no header or trailer) The default `wBits = maxWindowBits + 16` produces standard gzip format compatible with Unix `gzip` command and web compression. ### Example ```swift import Foundation import Gzip let data = "This is sample text to compress".data(using: .utf8)! // Default compression level let compressed = try data.gzipped() // Maximum compression (slower, smaller output) let maxCompressed = try data.gzipped(level: .bestCompression) // No compression (faster, larger output) let fastCompressed = try data.gzipped(level: .noCompression) // Custom compression level (0-9) let customCompressed = try data.gzipped(level: CompressionLevel(5)) // Custom wBits for raw deflate format let rawDeflate = try data.gzipped(wBits: -15) ``` ### Source Location `Sources/Gzip/Data+Gzip.swift:69` ``` -------------------------------- ### Decompressing Truncated Data with Buffer Error Handling Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md Demonstrates how to handle the .buffer error, which can occur if the compressed data is incomplete or truncated. This snippet shows a basic check for the .buffer error kind during decompression. ```swift let truncatedGzip = /* incomplete gzip download */ do { try truncatedGzip.gunzipped() // May trigger .buffer } catch let error as GzipError { if error.kind == .buffer { print("Incomplete data: \(error.message)") } } ``` -------------------------------- ### Usage of LocalizedError with GzipError Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/gzip-error.md Shows how to directly use error.localizedDescription to print gzip errors when Foundation is available. ```swift import Foundation import Gzip do { try data.gunzipped() } catch { // Can use Error.localizedDescription directly print(error.localizedDescription) } ``` -------------------------------- ### Compress Data with Metrics Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/INTEGRATION.md Compresses data and logs performance metrics such as size reduction ratio and compression time. Useful for performance analysis. ```swift import Foundation import Gzip class CompressionMetrics { func compressWithMetrics(_ data: Data) throws -> Data { let startTime = Date() let startSize = data.count let compressed = try data.gzipped() let duration = Date().timeIntervalSince(startTime) let ratio = Double(startSize) / Double(compressed.count) print("Compression: \(startSize) -> \(compressed.count) bytes") print("Ratio: \(String(format: \"%.2f\", ratio))x") print("Time: \(String(format: \"%.3f\", duration))s") return compressed } } ``` -------------------------------- ### Handling Gzip Errors During Decompression Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/API.md Illustrates how to catch and handle `GzipError` during decompression, with specific cases for different error kinds. ```swift do { let decompressed = try data.gunzipped() } catch let error as GzipError { switch error.kind { case .stream: print("Invalid parameters") case .data: print("Corrupted data: \(error.message)") case .memory: print("Out of memory") case .buffer: print("Incomplete data") case .version: print("Version mismatch") case .unknown(let code): print("Unknown error: \(code)") } } ``` -------------------------------- ### Compress and Decompress Data with Async/Await Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/INTEGRATION.md Provides asynchronous functions for Gzip compression and decompression using Swift's async/await pattern for modern concurrency. ```swift import Foundation import Gzip func compressAsync(_ data: Data, level: CompressionLevel = .defaultCompression) async throws -> Data { return try await Task(priority: .userInitiated) { return try data.gzipped(level: level) }.value } func decompressAsync(_ data: Data) async throws -> Data { return try await Task(priority: .userInitiated) { return try data.gunzipped() }.value } // Usage let largeData = /* ... */ let compressed = try await compressAsync(largeData, level: .bestCompression) let decompressed = try await decompressAsync(compressed) ``` -------------------------------- ### CompressionLevel Predefined Constants Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/compression-level.md This snippet details the predefined constants available for CompressionLevel, each representing a different compression strategy with its use case. ```APIDOC ## CompressionLevel Predefined Constants ### noCompression No compression; data passes through the compressor unchanged. ```swift public static let noCompression = Self(Z_NO_COMPRESSION) // rawValue: 0 ``` **Use case:** Speed is prioritized when compression is unnecessary or when you want compression metadata without actual compression. ### bestSpeed Fastest compression with minimal compression ratio. ```swift public static let bestSpeed = Self(Z_BEST_SPEED) // rawValue: 1 ``` **Use case:** Real-time compression scenarios where latency is critical and compression ratio is secondary. ### bestCompression Maximum compression ratio with slowest speed. ```swift public static let bestCompression = Self(Z_BEST_COMPRESSION) // rawValue: 9 ``` **Use case:** One-time compression of large data or scenarios where bandwidth cost outweighs computational cost. ### defaultCompression Automatic compression level selected by zlib (typically level 6). ```swift public static let defaultCompression = Self(Z_DEFAULT_COMPRESSION) // rawValue: -1 ``` **Use case:** General-purpose compression when you have no specific performance requirements. Provides balanced tradeoff between speed and compression ratio. ``` -------------------------------- ### Add GzipSwift Package to SwiftPM Source: https://github.com/1024jp/gzipswift/blob/main/README.md Integrates the GzipSwift library into your project using Swift Package Manager by adding it to your Package.swift dependencies. ```swift dependencies: [ .package(name: "Gzip", url: "https://github.com/1024jp/GzipSwift", from: Version(7, 0, 0)) ] ``` -------------------------------- ### Reinstall zlib Development Files on Linux Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md On Linux, if you encounter version errors with zlib, you may need to reinstall its development files. This ensures that the zlib library is available in the standard location for your application to link against. ```bash # Reinstall zlib development files apt-get install zlib1g-dev # Verify zlib is in standard location ls /usr/local/lib/libz.so* # Rebuild the application swift build ``` -------------------------------- ### Compressing Large Data with Memory Error Handling Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md Demonstrates how to catch and handle the .memory error when compressing very large data that might exceed available heap memory. This snippet shows a basic check for the specific error kind. ```swift // Compressing gigabytes of data may trigger .memory let hugeData = /* 10 GB of data */ do { try hugeData.gzipped() // May trigger .memory } catch let error as GzipError { if error.kind == .memory { print("Not enough memory to compress") } } ``` -------------------------------- ### Automatic Gzip/Zlib Format Detection Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md Utilizes the `wBits` parameter with `maxWindowBits + 32` to automatically detect and handle both gzip and zlib compressed data formats. It includes a specific catch for `.data` errors to indicate if the data is not in a recognized format. ```swift // Use auto-detection wBits to handle both zlib and gzip do { let decompressed = try data.gunzipped(wBits: maxWindowBits + 32) } catch let error as GzipError { if error.kind == .data { print("Data is not in gzip or zlib format") } } ``` -------------------------------- ### Compress Data and Save to Disk Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/INTEGRATION.md Compresses a Data object using the best compression level and writes the compressed data to a specified file path. ```swift import Foundation import Gzip func compressAndSave(_ data: Data, to filePath: String) throws { let compressed = try data.gzipped(level: .bestCompression) try compressed.write(to: URL(fileURLWithPath: filePath)) } // Usage let data = "Important data".data(using: .utf8)! try compressAndSave(data, to: "/tmp/data.gz") ``` -------------------------------- ### Checking Gzip Format Before Decompressing Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/gzip-error.md Shows how to check if data is gzipped before attempting decompression using the `isGzipped` property. ```APIDOC ## Checking Gzip Format Before Decompressing ```swift import Foundation import Gzip let data = /* ... from network or file ... */ if data.isGzipped { do { let decompressed = try data.gunzipped() // Process decompressed data } catch let error as GzipError { if error.kind == .data { print("Corrupted gzip data") } else { print("Decompression error: \(error.message)") } } } else { // Use data as-is } ``` ``` -------------------------------- ### Compress Data to Gzip Format Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/data-gzip.md Compress Data using zlib in gzip format. You can specify the compression level and window bits. The default settings produce standard gzip format. ```swift import Foundation import Gzip let data = "This is sample text to compress".data(using: .utf8)! // Default compression level let compressed = try data.gzipped() // Maximum compression (slower, smaller output) let maxCompressed = try data.gzipped(level: .bestCompression) // No compression (faster, larger output) let fastCompressed = try data.gzipped(level: .noCompression) // Custom compression level (0-9) let customCompressed = try data.gzipped(level: CompressionLevel(5)) // Custom wBits for raw deflate format let rawDeflate = try data.gzipped(wBits: -15) ``` -------------------------------- ### Compressing Large Data in Chunks Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/errors.md Illustrates a strategy for compressing very large data by processing it in smaller, manageable chunks. This approach helps prevent memory exhaustion by avoiding loading the entire dataset into memory at once. ```swift // For large data, compress in chunks func compressInChunks(_ data: Data, chunkSize: Int = 1 << 20) throws -> Data { // Process data in manageable chunks for chunk in stride(from: 0, to: data.count, by: chunkSize) { let end = min(chunk + chunkSize, data.count) let subdata = data.subdata(in: chunk.. Data { do { if data.isGzipped { return try data.gunzipped() } return data } catch { // If decompression fails, return original data return data } } ``` -------------------------------- ### Handle Decompression Errors Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/data-gzip.md Demonstrates how to handle potential errors during decompression, such as corrupted data, using a do-catch block with GzipError. ```swift // Error handling do { let decompressed = try compressedData.gunzipped() } catch let error as GzipError { if error.kind == .data { print("Data is corrupted: \(error.message)") } } ``` -------------------------------- ### gunzipped(wBits:) Method Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/api-reference/data-gzip.md Decompresses the receiver from gzip or zlib format using zlib. ```APIDOC ## gunzipped(wBits:) Method ### Description Decompresses the receiver from gzip or zlib format using zlib. ### Signature ```swift public func gunzipped(wBits: Int32 = maxWindowBits + 32) throws(GzipError) -> Data ``` ### Parameters #### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `wBits` | `Int32` | No | `maxWindowBits + 32` | The size of the history buffer (window size) in powers of 2. Default adds 32 to `maxWindowBits` to auto-detect both gzip and zlib formats. Range: +8 to +15 for zlib, -8 to -15 for raw deflate, +24 to +31 for gzip, +40 to +47 for auto-detection. | ### Returns `Data` — A new Data instance containing the decompressed content. The returned data has no compression format markers. ### Throws `GzipError` — Thrown if decompression fails. Possible error kinds: - `.data` — The input data is corrupted or not in a recognized compression format (Z_DATA_ERROR) - `.memory` — Insufficient memory for decompression (Z_MEM_ERROR) - `.buffer` — No progress possible due to incomplete input or insufficient output space (Z_BUF_ERROR) - `.stream` — The decompression stream structure was inconsistent (Z_STREAM_ERROR) - `.version` — Zlib version incompatibility (Z_VERSION_ERROR) Throws with `.data` kind if the receiver is empty with message "Input data is empty." ``` -------------------------------- ### Data Extension Source: https://github.com/1024jp/gzipswift/blob/main/_autodocs/API.md Provides methods for gzip compression and decompression on Swift's Data type. ```APIDOC ## isGzipped Property ### Description Returns `true` if the data begins with the gzip magic number bytes (0x1f 0x8b). ### Example ```swift let data = try originalData.gzipped() print(data.isGzipped) // true ``` ``` ```APIDOC ## gzipped(level:wBits:) Method ### Description Compresses the receiver using zlib in gzip format. ### Method `func gzipped(level: CompressionLevel = .defaultCompression, wBits: Int32 = maxWindowBits + 16) throws(GzipError) -> Data` ### Parameters #### Parameters - `level` (CompressionLevel) - Compression level (0-9 or -1 for default). Default: `.defaultCompression` - `wBits` (Int32) - Window bits for format control. Default: `maxWindowBits + 16` (gzip format) ### Returns Compressed Data ### Throws `GzipError` with kind `.stream`, `.memory`, or `.version` ### Example ```swift let data = "Sample text".data(using: .utf8)! // Default compression let compressed = try data.gzipped() // Maximum compression let small = try data.gzipped(level: .bestCompression) // Fast compression let fast = try data.gzipped(level: .bestSpeed) // Custom level let medium = try data.gzipped(level: CompressionLevel(5)) ``` ``` ```APIDOC ## gunzipped(wBits:) Method ### Description Decompresses the receiver from gzip or zlib format. ### Method `func gunzipped(wBits: Int32 = maxWindowBits + 32) throws(GzipError) -> Data` ### Parameters #### Parameters - `wBits` (Int32) - Window bits for format detection. Default: `maxWindowBits + 32` (auto-detect gzip and zlib) ### Returns Decompressed Data ### Throws `GzipError` with kind `.data`, `.memory`, `.buffer`, `.stream`, or `.version` ### Example ```swift if compressedData.isGzipped { let original = try compressedData.gunzipped() } // Auto-detect format let decompressed = try data.gunzipped(wBits: maxWindowBits + 32) // Gzip format only let gzipOnly = try data.gunzipped(wBits: 31) // Zlib format only let zlibOnly = try data.gunzipped(wBits: 15) ``` ```