swift zlib 解压缩

swift使用zlib框架compress/uncompress进行解压缩,示例代码如下,

    func testDataCompression()  {
        let helloworld = "Hello"
        let data = helloworld.data(using: .utf8)

        // 压缩数据
        var uncompressedSize = uLong(data?.count ?? 0)
        var compressedSize = compressBound(uLong(data!.count))
        var compressedData = Data(count: Int(compressedSize))
        compressedData.withUnsafeMutableBytes { compressedBytes in
            data!.withUnsafeBytes { uncompressedBytes in
                compress(compressedBytes.baseAddress!.assumingMemoryBound(to: Bytef.self), &compressedSize, uncompressedBytes.baseAddress!.assumingMemoryBound(to: Bytef.self), uncompressedSize)
            }
        }
        compressedData.count = Int(compressedSize)
        print("压缩后的数据:\(compressedData)")
        
        var uncompressedData = Data(count: Int(uncompressedSize))
        let actualSize = uncompressedData.withUnsafeMutableBytes { uncompressedBytes in
            compressedData.withUnsafeBytes { compressedBytes in
                return uncompress(uncompressedBytes.baseAddress!.assumingMemoryBound(to: Bytef.self), &uncompressedSize, compressedBytes.baseAddress!.assumingMemoryBound(to: Bytef.self), uLong(compressedData.count))
            }
        }
        if actualSize != Z_OK {
            print("解压缩数据失败")
        } else {
            let uncompressedString = String(data: uncompressedData, encoding: .utf8)!
            print("解压缩后的数据:\(uncompressedString)")
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容