forked from galaxydi/go-loghub
-
Notifications
You must be signed in to change notification settings - Fork 116
/
compressor.go
52 lines (44 loc) · 1.4 KB
/
compressor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package sls
import (
"github.com/klauspost/compress/zstd"
)
var slsZstdCompressor LogCompressor = NewZstdCompressor(zstd.SpeedFastest)
func SetZstdCompressor(compressor LogCompressor) error {
slsZstdCompressor = compressor
return nil
}
type LogCompressor interface {
// Compress src into dst. If you have a buffer to use, you can pass it to
// prevent allocation. If it is too small, or if nil is passed, a new buffer
// will be allocated and returned.
Compress(src, dst []byte) ([]byte, error)
// Decompress src into dst. If you have a buffer to use, you can pass it to
// prevent allocation. If it is too small, or if nil is passed, a new buffer
// will be allocated and returned.
Decompress(src, dst []byte) ([]byte, error)
}
type ZstdCompressor struct {
writer *zstd.Encoder
reader *zstd.Decoder
level zstd.EncoderLevel
}
func NewZstdCompressor(level zstd.EncoderLevel) *ZstdCompressor {
res := &ZstdCompressor{
level: level,
}
res.writer, _ = zstd.NewWriter(nil, zstd.WithEncoderLevel(res.level))
res.reader, _ = zstd.NewReader(nil)
return res
}
func (c *ZstdCompressor) Compress(src, dst []byte) ([]byte, error) {
if dst != nil {
return c.writer.EncodeAll(src, dst[:0]), nil
}
return c.writer.EncodeAll(src, nil), nil
}
func (c *ZstdCompressor) Decompress(src, dst []byte) ([]byte, error) {
if dst != nil {
return c.reader.DecodeAll(src, dst[:0])
}
return c.reader.DecodeAll(src, nil)
}