Skip to content

Instantly share code, notes, and snippets.

@zaczh
Last active December 4, 2016 02:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaczh/d1e37a2ff7f071191f1c30866d5db0f5 to your computer and use it in GitHub Desktop.
Save zaczh/d1e37a2ff7f071191f1c30866d5db0f5 to your computer and use it in GitHub Desktop.
NSData lzfse compress & decompress
extension NSData {
func lzfseCompressed() -> NSData {
let sourceBuffer: UnsafePointer<UInt8> = UnsafePointer<UInt8>(self.bytes.assumingMemoryBound(to: UInt8.self))
let sourceBufferSize: Int = self.length
let destinationBuffer: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>.allocate(capacity: sourceBufferSize)
let destinationBufferSize: Int = sourceBufferSize
let status = compression_encode_buffer(destinationBuffer, destinationBufferSize, sourceBuffer, sourceBufferSize, nil, COMPRESSION_LZFSE)
if status == 0 {
print("Error with status: \(status)")
fatalError()
}
print("Original size: \(sourceBufferSize) | Compressed size: \(status)")
return NSData(bytesNoCopy: destinationBuffer, length: status)
}
func lzfseDecompressed() -> NSData {
let sourceBuffer: UnsafePointer<UInt8> = UnsafePointer<UInt8>(self.bytes.assumingMemoryBound(to: UInt8.self))
let sourceBufferSize: Int = self.length
//assuming 20x is OK?
let destinationBufferSize: Int = 20 * sourceBufferSize
let destinationBuffer: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>.allocate(capacity: destinationBufferSize)
let status = compression_decode_buffer(destinationBuffer, destinationBufferSize, sourceBuffer, sourceBufferSize, nil, COMPRESSION_LZFSE)
if status == 0 {
print("Error with status: \(status)")
fatalError()
}
print("Original size: \(sourceBufferSize) | Decompressed size: \(status)")
return NSData(bytesNoCopy: destinationBuffer, length: status)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment