/
algorithm.go
94 lines (78 loc) · 1.71 KB
/
algorithm.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package logwriter
import (
"bytes"
"compress/gzip"
"github.com/klauspost/compress/zstd"
"io"
"sync"
)
type Algorithm interface {
Compress(in []byte, out *bytes.Buffer) error
Decompress(in []byte, out *bytes.Buffer) error
}
var _ Algorithm = &NopAlgorithm{}
type NopAlgorithm struct{}
func (n *NopAlgorithm) Compress(in []byte, out *bytes.Buffer) error {
_, err := out.Write(in)
return err
}
func (n *NopAlgorithm) Decompress(in []byte, out *bytes.Buffer) error {
_, err := out.Write(in)
return err
}
var _ Algorithm = &GzipAlgorithm{}
type GzipAlgorithm struct {
once sync.Once
gw *gzip.Writer
}
func (g *GzipAlgorithm) Compress(in []byte, out *bytes.Buffer) error {
g.once.Do(g.init)
g.gw.Reset(out)
_, err := g.gw.Write(in)
if err != nil {
return err
}
return g.gw.Close()
}
func (g *GzipAlgorithm) Decompress(in []byte, out *bytes.Buffer) error {
r, err := gzip.NewReader(bytes.NewReader(in))
if err != nil {
return err
}
defer r.Close()
_, err = io.Copy(out, r)
return err
}
func (g *GzipAlgorithm) init() {
g.gw = gzip.NewWriter(Discard)
}
var _ Algorithm = &ZstdAlgorithm{}
type ZstdAlgorithm struct {
once sync.Once
zw *zstd.Encoder
err error
}
func (z *ZstdAlgorithm) Compress(in []byte, out *bytes.Buffer) error {
z.once.Do(z.init)
if z.err != nil {
return z.err
}
z.zw.Reset(out)
_, err := z.zw.Write(in)
if err != nil {
return err
}
return z.zw.Close()
}
func (z *ZstdAlgorithm) Decompress(in []byte, out *bytes.Buffer) error {
r, err := zstd.NewReader(bytes.NewReader(in))
if err != nil {
return err
}
defer r.Close()
_, err = io.Copy(out, r)
return err
}
func (z *ZstdAlgorithm) init() {
z.zw, z.err = zstd.NewWriter(Discard, zstd.WithEncoderConcurrency(1))
}