Created
March 21, 2021 07:32
-
-
Save JanGorman/afe8a203e91af1e7c747a1ca142143ae to your computer and use it in GitHub Desktop.
This file contains 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
// https://developer.apple.com/documentation/accelerate/compressing_and_decompressing_data_with_input_and_output_filters | |
import Compression | |
let sourceString = """ | |
Lorem ipsum dolor sit amet consectetur adipiscing elit mi | |
nibh ornare proin blandit diam ridiculus, faucibus mus | |
dui eu vehicula nam donec dictumst sed vivamus bibendum | |
aliquet efficitur. Felis imperdiet sodales dictum morbi | |
vivamus augue dis duis aliquet velit ullamcorper porttitor, | |
lobortis dapibus hac purus aliquam natoque iaculis blandit | |
montes nunc pretium. | |
""" | |
let sourceData = Data(sourceString.utf8) | |
let pageSize = 128 | |
var compressedData = Data() | |
do { | |
let outputFilter = try OutputFilter(.compress, using: .lzfse, writingTo: { data in | |
if let data = data { | |
compressedData.append(data) | |
} | |
}) | |
var index = 0 | |
let bufferSize = sourceData.count | |
while true { | |
let rangeLength = min(pageSize, bufferSize - index) | |
let subdata = sourceData.subdata(in: index..<index + rangeLength) | |
index += rangeLength | |
try outputFilter.write(subdata) | |
if rangeLength == 0 { | |
break | |
} | |
} | |
} catch { | |
fatalError("ENCODING \(error.localizedDescription)") | |
} | |
var decompressedData = Data() | |
do { | |
var index = 0 | |
let bufferSize = compressedData.count | |
let inputFilter = try InputFilter(.decompress, using: .lzfse) { length -> Data in | |
let rangeLength = min(length, bufferSize - index) | |
let subdata = compressedData.subdata(in: index..<index + rangeLength) | |
index += rangeLength | |
return subdata | |
} | |
while let page = try inputFilter.readData(ofLength: pageSize) { | |
decompressedData.append(page) | |
} | |
} catch { | |
fatalError("DECODING \(error.localizedDescription)") | |
} | |
let decompressedString = String(data: decompressedData, encoding: .utf8) | |
decompressedString == sourceString |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment