swift-gzip解压缩(一)-Data

解压缩使用swift需要引用libz库

  • 声明Data类的扩展
/**解压缩流大小**/
private let GZIP_STREAM_SIZE: Int32 = Int32(MemoryLayout<z_stream>.size)
/**解压缩缓冲区大小**/
private let GZIP_BUF_LENGTH:Int = 512
/**默认空数据**/
private let GZIP_NULL_DATA = Data()

  • 判断是否zip压缩后的数据。
   public var isGZipCompressed :Bool {
        return self.starts(with: [0x1f,0x8b])
    }
  • gzip压缩。
public func gzipCompress() -> Data {
        
        guard self.count > 0 else {
            return self
        }
        
        var stream = z_stream()
        stream.avail_in = uInt(self.count)
        stream.total_out = 0
        
        self.withUnsafeBytes { (bytes:UnsafePointer<Bytef>) in
            stream.next_in = UnsafeMutablePointer<Bytef>(mutating:bytes)
        }

        var status = deflateInit2_(&stream,Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS + 16, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY, ZLIB_VERSION, GZIP_STREAM_SIZE)
        
        if  status != Z_OK {
            return  GZIP_NULL_DATA
        }

        var compressedData = Data()
        
        while stream.avail_out == 0 {
            
            if Int(stream.total_out) >= compressedData.count {
                compressedData.count += GZIP_BUF_LENGTH
            }
            
            stream.avail_out = uInt(GZIP_BUF_LENGTH)
            
            compressedData.withUnsafeMutableBytes { (bytes:UnsafeMutablePointer<Bytef>) -> Void in
                stream.next_out = bytes.advanced(by: Int(stream.total_out))
            }
            
            status = deflate(&stream, Z_FINISH)
            
            if status != Z_OK && status != Z_STREAM_END {
                return GZIP_NULL_DATA
            }
        }
        
        guard deflateEnd(&stream) == Z_OK else {
            return GZIP_NULL_DATA
        }
        
        compressedData.count = Int(stream.total_out)
        return compressedData
    }
  • gzip解压。
    public func gzipUncompress() ->Data {
        guard self.count > 0  else {
            return GZIP_NULL_DATA
        }
        
        guard self.isGZipCompressed else {
            return self
        }
        
        var  stream = z_stream()
      
        self.withUnsafeBytes { (bytes:UnsafePointer<Bytef>) in
            stream.next_in =  UnsafeMutablePointer<Bytef>(mutating: bytes)
        }
        
        stream.avail_in = uInt(self.count)
        stream.total_out = 0
      
        
        var status: Int32 = inflateInit2_(&stream, MAX_WBITS + 16, ZLIB_VERSION,GZIP_STREAM_SIZE)
        
        guard status == Z_OK else {
            return GZIP_NULL_DATA
        }
        
        var decompressed = Data(capacity: self.count * 2)
        while stream.avail_out == 0 {

            stream.avail_out = uInt(GZIP_BUF_LENGTH)
            decompressed.count += GZIP_BUF_LENGTH

            decompressed.withUnsafeMutableBytes { (bytes:UnsafeMutablePointer<Bytef>)in
                 stream.next_out = bytes.advanced(by: Int(stream.total_out))
            }

            status = inflate(&stream, Z_SYNC_FLUSH)

            if status != Z_OK && status != Z_STREAM_END {
                break
            }
        }
        
        if inflateEnd(&stream) != Z_OK {
            return GZIP_NULL_DATA
        }
        
        decompressed.count = Int(stream.total_out)
        return decompressed
    }

  • 测试
        let string = "Hello world!"
        let helloData =  string.data(using: .utf8)
        let compressData =   helloData?.gzipCompress()
        let uncompressData =  compressData?.gzipUncompress()
        let resString =  String(data: uncompressData!, encoding: String.Encoding.utf8)
        print(resString)
        
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • WinRAR - 最新版本的更新 版本 5.50 1. WinRAR 和命令行 RAR 默认使用 RAR ...
    王舒璇阅读 7,063评论 0 2
  • 文 | 壹默了然 这是新沪族系列第6个故事 导读:一对校园恋人,毕业后各奔前程,爱情被残酷的生活打败。7年后,女方...
    壹默了然阅读 4,410评论 3 1
  • 经过我的实践 现实真的比想象要麻烦的多
    贾馆长阅读 1,283评论 0 0
  • 我妈妈老王是一个做事雷厉风行,心思敏感又粗犷的女王,家里一切她说了算。当然,她只能算上我爸,我和哥哥都只听不算。 ...
    悬崖上的小树阅读 3,926评论 21 23
  • 在刚进大学的时候,听到班主任说的最多的就是考研,考研这个想法就像在心里发了芽。 但是,进入大学的...
    绿萝囧了阅读 1,054评论 0 1

友情链接更多精彩内容