diff --git a/pkg/compressor/compressor.go b/pkg/compressor/compressor.go index dadd530b3..5b30e2a35 100644 --- a/pkg/compressor/compressor.go +++ b/pkg/compressor/compressor.go @@ -28,6 +28,7 @@ const ( CompressorLz4 CompressorDefault CompressorZstd + CompressorDeflate CompressorMax ) diff --git a/pkg/compressor/defalte_compress_test.go b/pkg/compressor/defalte_compress_test.go new file mode 100644 index 000000000..95757273d --- /dev/null +++ b/pkg/compressor/defalte_compress_test.go @@ -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)) + } +} diff --git a/pkg/compressor/deflater_compress.go b/pkg/compressor/deflate_compress.go similarity index 56% rename from pkg/compressor/deflater_compress.go rename to pkg/compressor/deflate_compress.go index d1eea9879..ed53b4f66 100644 --- a/pkg/compressor/deflater_compress.go +++ b/pkg/compressor/deflate_compress.go @@ -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 +}