forked from aws/amazon-kinesis-streams-for-fluent-bit
-
Notifications
You must be signed in to change notification settings - Fork 2
/
zstd.go
73 lines (62 loc) · 1.57 KB
/
zstd.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Package zstd is an implementation of Compression interface using zstd format.
package zstd
import (
"bytes"
"sync"
"github.com/klauspost/compress/zstd"
)
// ZSTD implements Compression interface using gzip format.
type ZSTD struct {
mutex sync.Mutex
buffer bytes.Buffer
writer *zstd.Encoder
writerOpts []zstd.EOption
}
// New creates a new ZSTD instance.
func New(level int) (*ZSTD, error) {
z := ZSTD{
writerOpts: []zstd.EOption{
zstd.WithEncoderConcurrency(1),
zstd.WithEncoderLevel(zstd.EncoderLevel(level)),
zstd.WithZeroFrames(true),
},
}
var err error
z.writer, err = zstd.NewWriter(&z.buffer, z.writerOpts...)
if err != nil {
return nil, err
}
return &z, nil
}
// Compress will compress data using zstd format.
// In case of any errors, it will return raw data without compression.
func (z *ZSTD) Compress(data []byte) ([]byte, error) {
var err error
tmpBuffer := &z.buffer
tmpWriter := z.writer
if z.mutex.TryLock() {
defer z.mutex.Unlock()
tmpBuffer.Reset()
tmpWriter.Reset(&z.buffer)
} else {
// This should not happen since we only run a single thread.
// Good to have this logic here if we want to support concurrent processing.
tmpBuffer = new(bytes.Buffer)
tmpWriter, err = zstd.NewWriter(tmpBuffer, z.writerOpts...)
if err != nil {
return data, err
}
}
_, err = tmpWriter.Write(data)
if err != nil {
return data, err
}
err = tmpWriter.Close()
if err != nil {
return data, err
}
bufferBytes := tmpBuffer.Bytes()
result := make([]byte, len(bufferBytes))
copy(result, bufferBytes)
return result, nil
}