Files
gf/g/encoding/gcompress/gcompress.go

84 lines
1.8 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
2017-12-29 16:03:30 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2017-12-29 16:03:30 +08:00
2019-01-15 23:27:47 +08:00
// Package gcompress provides kinds of compression algorithms for binary/bytes data.
2017-11-23 10:21:28 +08:00
package gcompress
import (
2019-06-19 09:06:52 +08:00
"bytes"
"compress/gzip"
"compress/zlib"
"io"
2017-11-23 10:21:28 +08:00
)
// Zlib compresses <data> with zlib algorithm.
2019-06-21 22:23:07 +08:00
func Zlib(data []byte) ([]byte, error) {
2019-06-19 09:06:52 +08:00
if data == nil || len(data) < 13 {
2019-06-21 22:23:07 +08:00
return data, nil
2019-06-19 09:06:52 +08:00
}
var in bytes.Buffer
2019-06-21 22:23:07 +08:00
var err error
2019-06-19 09:06:52 +08:00
w := zlib.NewWriter(&in)
2019-06-21 22:23:07 +08:00
if _, err = w.Write(data); err != nil {
return nil, err
}
if err = w.Close(); err != nil {
return in.Bytes(), err
}
return in.Bytes(), nil
2017-11-23 10:21:28 +08:00
}
// UnZlib decompresses <data> with zlib algorithm.
2019-06-21 22:23:07 +08:00
func UnZlib(data []byte) ([]byte, error) {
2019-06-19 09:06:52 +08:00
if data == nil || len(data) < 13 {
2019-06-21 22:23:07 +08:00
return data, nil
2019-06-19 09:06:52 +08:00
}
2019-06-21 22:23:07 +08:00
2019-06-19 09:06:52 +08:00
b := bytes.NewReader(data)
var out bytes.Buffer
2019-06-21 22:23:07 +08:00
var err error
2019-06-19 09:06:52 +08:00
r, err := zlib.NewReader(b)
if err != nil {
2019-06-21 22:23:07 +08:00
return nil, err
}
if _, err = io.Copy(&out, r); err != nil {
return nil, err
2019-06-19 09:06:52 +08:00
}
2019-06-21 22:23:07 +08:00
return out.Bytes(), nil
}
// Gzip compresses <data> with gzip algorithm.
2019-06-21 22:23:07 +08:00
func Gzip(data []byte) ([]byte, error) {
var buf bytes.Buffer
2019-06-21 22:23:07 +08:00
var err error
2019-06-19 09:06:52 +08:00
zip := gzip.NewWriter(&buf)
2019-06-21 22:23:07 +08:00
_, err = zip.Write(data)
if err != nil {
2019-06-21 22:23:07 +08:00
return nil, err
}
2019-06-21 22:23:07 +08:00
if err = zip.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// UnGzip decompresses <data> with gzip algorithm.
2019-06-21 22:23:07 +08:00
func UnGzip(data []byte) ([]byte, error) {
2019-06-19 09:06:52 +08:00
var buf bytes.Buffer
content := bytes.NewReader(data)
zipData, err := gzip.NewReader(content)
if err != nil {
2019-06-21 22:23:07 +08:00
return nil, err
}
if _, err = io.Copy(&buf, zipData); err != nil {
return nil, err
}
if err = zipData.Close(); err != nil {
return buf.Bytes(), err
}
2019-06-21 22:23:07 +08:00
return buf.Bytes(), nil
}