Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(compressor): deflate compress #321

Merged
merged 4 commits into from
Oct 23, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pkg/compressor/compressor.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const (
CompressorDefault
CompressorZstd
CompressorMax
CompressorDeflate
iSuperCoder marked this conversation as resolved.
Show resolved Hide resolved
)

type Compressor interface {
Expand Down
36 changes: 36 additions & 0 deletions pkg/compressor/defalte_compress_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package compressor

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestDeflateCompress(t *testing.T) {
ts := []struct {
text string
}{
{
text: "Don't communicate by sharing memory, share memory by communicating.",
},
{
text: "Concurrency is not parallelism.",
},
{
text: "The bigger the interface, the weaker the abstraction.",
},
{
text: "Documentation is for users.",
},
}

dc := &DeflateCompress{}
assert.EqualValues(t, CompressorDeflate, dc.GetCompressorType())

for _, s := range ts {
var data []byte = []byte(s.text)
dataCompressed, _ := dc.Compress(data)
ret, _ := dc.Decompress(dataCompressed)
assert.EqualValues(t, s.text, string(ret))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,36 @@
*/

package compressor

import (
"bytes"
"compress/flate"
"io"

"github.com/seata/seata-go/pkg/util/log"
)

type DeflateCompress struct{}

func (*DeflateCompress) Compress(data []byte) ([]byte, error) {
var buf bytes.Buffer
fw, err := flate.NewWriter(&buf, flate.BestCompression)
if err != nil {
log.Error(err)
return nil, err
}
defer fw.Close()
fw.Write(data)
fw.Flush()
return buf.Bytes(), nil
}

func (*DeflateCompress) Decompress(data []byte) ([]byte, error) {
fr := flate.NewReader(bytes.NewBuffer(data))
defer fr.Close()
return io.ReadAll(fr)
}

func (*DeflateCompress) GetCompressorType() CompressorType {
return CompressorDeflate
}