github.com/wangyougui/gf/v2@v2.6.5/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/wangyougui/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  	"github.com/wangyougui/gf/v2/errors/gerror"
    16  )
    17  
    18  // Zlib compresses `data` with zlib algorithm.
    19  func Zlib(data []byte) ([]byte, error) {
    20  	if data == nil || len(data) < 13 {
    21  		return data, nil
    22  	}
    23  	var (
    24  		err    error
    25  		in     bytes.Buffer
    26  		writer = zlib.NewWriter(&in)
    27  	)
    28  
    29  	if _, err = writer.Write(data); err != nil {
    30  		err = gerror.Wrapf(err, `zlib.Writer.Write failed`)
    31  		return nil, err
    32  	}
    33  	if err = writer.Close(); err != nil {
    34  		err = gerror.Wrapf(err, `zlib.Writer.Close failed`)
    35  		return in.Bytes(), err
    36  	}
    37  	return in.Bytes(), nil
    38  }
    39  
    40  // UnZlib decompresses `data` with zlib algorithm.
    41  func UnZlib(data []byte) ([]byte, error) {
    42  	if data == nil || len(data) < 13 {
    43  		return data, nil
    44  	}
    45  	var (
    46  		out             bytes.Buffer
    47  		bytesReader     = bytes.NewReader(data)
    48  		zlibReader, err = zlib.NewReader(bytesReader)
    49  	)
    50  	if err != nil {
    51  		err = gerror.Wrapf(err, `zlib.NewReader failed`)
    52  		return nil, err
    53  	}
    54  	if _, err = io.Copy(&out, zlibReader); err != nil {
    55  		err = gerror.Wrapf(err, `io.Copy failed`)
    56  		return nil, err
    57  	}
    58  	return out.Bytes(), nil
    59  }