Search code examples
compressionswift3ios10lzma

Data Compression in Swift 3


I was using LZMA data compression in an extension based on NSData+Compression.swift which worked totally fine till iOS 10 and auto-conversion to Swift 3. After auto-conversion the class looks like this:

import Compression

extension Data {
static func compress(_ data: Data) -> Data {

    let sourceBuffer = (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count)
    let sourceBufferSize = data.count

    let destinationBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: sourceBufferSize)
    let destinationBufferSize = sourceBufferSize

    let status = compression_encode_buffer(destinationBuffer, destinationBufferSize, sourceBuffer, sourceBufferSize, nil, COMPRESSION_LZMA)

    if status == 0 {
        print("Error with status: \(status)")
    }
    print("Original size: \(sourceBufferSize) | Compressed size: \(status)")
    return Data(bytesNoCopy: UnsafeMutablePointer<UInt8>(destinationBuffer), count: status, deallocator: .free)
}
}

Now the output of the method is always empty with a compressed size of 0. Can you help me finding out whats wrong with this code?


Solution

  • As Martin R suggested the problem was that the destination buffer was too small.

    Instead of using data.count I now use (data as NSData).length which results in the same sizes as before with Swift 2's NSData. Additionally I increased the destination buffer size by a factor of 2 - just to be sure that it will always work.

    Thank you for your quick answer!