github.com/gogf/gf@v1.16.9/encoding/gcompress/gcompress_zlib.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  // Package gcompress provides kinds of compression algorithms for binary/bytes data.
     8  package gcompress
     9  
    10  import (
    11  	"bytes"
    12  	"compress/zlib"
    13  	"io"
    14  )
    15  
    16  // Zlib compresses <data> with zlib algorithm.
    17  func Zlib(data []byte) ([]byte, error) {
    18  	if data == nil || len(data) < 13 {
    19  		return data, nil
    20  	}
    21  	var in bytes.Buffer
    22  	var err error
    23  	w := zlib.NewWriter(&in)
    24  	if _, err = w.Write(data); err != nil {
    25  		return nil, err
    26  	}
    27  	if err = w.Close(); err != nil {
    28  		return in.Bytes(), err
    29  	}
    30  	return in.Bytes(), nil
    31  }
    32  
    33  // UnZlib decompresses <data> with zlib algorithm.
    34  func UnZlib(data []byte) ([]byte, error) {
    35  	if data == nil || len(data) < 13 {
    36  		return data, nil
    37  	}
    38  
    39  	b := bytes.NewReader(data)
    40  	var out bytes.Buffer
    41  	var err error
    42  	r, err := zlib.NewReader(b)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	if _, err = io.Copy(&out, r); err != nil {
    47  		return nil, err
    48  	}
    49  	return out.Bytes(), nil
    50  }