Skip to content

Instantly share code, notes, and snippets.

@kirti-swiggy
Last active December 25, 2024 18:29
Show Gist options
  • Save kirti-swiggy/b74cd4f562943e8ecdd52acde36fbe90 to your computer and use it in GitHub Desktop.
Save kirti-swiggy/b74cd4f562943e8ecdd52acde36fbe90 to your computer and use it in GitHub Desktop.
Helper extension over Foundation Data to compress/decompress it using given Compression algorithm. Originally designed for brotli compression/decompression of network request/response.
import Compression
extension Data {
/// Compresses the data using the specified compression algorithm.
func compressed(using algo: Algorithm, pageSize: Int = 65536) throws -> Data {
var outputData = Data()
let filter = try OutputFilter(.compress, using: algo, bufferCapacity: pageSize, writingTo: { $0.flatMap({ outputData.append($0) }) })
var index = 0
let bufferSize = count
while true {
let rangeLength = Swift.min(pageSize, bufferSize - index)
let subdata = self.subdata(in: index ..< index + rangeLength)
index += rangeLength
try filter.write(subdata)
if (rangeLength == 0) { break }
}
return outputData
}
/// Decompresses the data using the specified compression algorithm.
func decompressed(from algo: Algorithm, pageSize: Int = 65536) throws -> Data {
var outputData = Data()
let bufferSize = count
var decompressionIndex = 0
let filter = try InputFilter(.decompress, using: algo) { (length: Int) -> Data? in
let rangeLength = Swift.min(length, bufferSize - decompressionIndex)
let subdata = self.subdata(in: decompressionIndex ..< decompressionIndex + rangeLength)
decompressionIndex += rangeLength
return subdata
}
while let page = try filter.readData(ofLength: pageSize) {
outputData.append(page)
}
return outputData
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment