Browse Source

feat(compressor): deflate compress (#321)

* feat(compressor): deflate compress

1. Optimize compressor type definition. (Don't start with package name).
2. Implement deflate compressor and ut.

close #312

* refactor(compressor): revert compressor type definition

* refactor(compressor): remove fmt.Println in ut

* refactor(compressor): adjust the order of deflate compressor constants.
tags/1.0.2-RC1
liushao GitHub 2 years ago
parent
commit
ab27591ecf
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 70 additions and 0 deletions
  1. +1
    -0
      pkg/compressor/compressor.go
  2. +36
    -0
      pkg/compressor/defalte_compress_test.go
  3. +33
    -0
      pkg/compressor/deflate_compress.go

+ 1
- 0
pkg/compressor/compressor.go View File

@@ -28,6 +28,7 @@ const (
CompressorLz4
CompressorDefault
CompressorZstd
CompressorDeflate
CompressorMax
)



+ 36
- 0
pkg/compressor/defalte_compress_test.go View File

@@ -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))
}
}

pkg/compressor/deflater_compress.go → pkg/compressor/deflate_compress.go View File

@@ -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
}

Loading…
Cancel
Save