Last active
December 4, 2016 02:42
-
-
Save zaczh/d1e37a2ff7f071191f1c30866d5db0f5 to your computer and use it in GitHub Desktop.
NSData lzfse compress & decompress
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
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