Created
March 1, 2024 05:39
-
-
Save Lavmint/7e244257094bcab31d783c47f43ccd0f to your computer and use it in GitHub Desktop.
LZMA unarchiving
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol LempelZivMarkovUnarchiver { | |
func unarchive(url: URL) throws -> URL | |
} | |
class StandartLZMUnarchiver: LempelZivMarkovUnarchiver { | |
func unarchive(url: URL) throws -> URL { | |
let algorithm: Algorithm = .lzma | |
let fileManager = FileManager.default | |
// Declare destinationURL outside of the autoreleasepool | |
let destinationFileName = url.deletingPathExtension().lastPathComponent | |
let destinationURL = fileManager.temporaryDirectory.appendingPathComponent(destinationFileName) | |
try autoreleasepool { | |
let sourceFile = try FileHandle(forReadingFrom: url) | |
defer { sourceFile.closeFile() } | |
// Use FileManager's createFile method to create the destination file | |
fileManager.createFile(atPath: destinationURL.path, contents: nil) | |
let destinationFile = try FileHandle(forWritingTo: destinationURL) | |
defer { destinationFile.closeFile() } | |
let bufferSize = 32_768 | |
let coder = try OutputFilter(.decompress, using: algorithm, bufferCapacity: bufferSize) { data in | |
guard let chunk = data else { return } | |
try destinationFile.write(contentsOf: chunk) | |
} | |
while true { | |
let chunk = sourceFile.readData(ofLength: bufferSize) | |
try coder.write(chunk) | |
if chunk.count < bufferSize { | |
break | |
} | |
} | |
} | |
return destinationURL | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment