-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompressor.go
67 lines (60 loc) · 1.21 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"compress/gzip"
zstdcgo "github.com/DataDog/zstd"
"github.com/klauspost/compress/zstd"
"io"
"sync"
)
type Compressor int
const (
Identity = iota
ZstdDefault
ZstdSpeed
ZstdCgoDefault
ZstdCgoSpeed
Gzip
)
func (c Compressor) String() string {
return [...]string{"IDENTITY", "ZSTD DEFAULT", "ZSTD BEST_SPEED", "ZSTD CGO DEFAULT", "ZSTD CGO SPEED", "GZIP"}[c]
}
var zstdDefaultPool = sync.Pool{
New: func() interface{} {
w, err := zstd.NewWriter(nil)
if err != nil {
panic(err)
}
return w
},
}
var zstdSpeedFastestPool = sync.Pool{
New: func() interface{} {
w, err := zstd.NewWriter(nil, zstd.WithEncoderLevel(zstd.SpeedFastest))
if err != nil {
panic(err)
}
return w
},
}
func (c Compressor) NewWriter(w io.WriteCloser) io.WriteCloser {
switch c {
case Identity:
return w
case ZstdDefault:
z := zstdDefaultPool.Get().(*zstd.Encoder)
z.Reset(w)
return z
case ZstdSpeed:
z := zstdSpeedFastestPool.Get().(*zstd.Encoder)
z.Reset(w)
return z
case ZstdCgoSpeed:
return zstdcgo.NewWriterLevel(w, zstdcgo.BestSpeed)
case ZstdCgoDefault:
return zstdcgo.NewWriterLevel(w, zstdcgo.DefaultCompression)
case Gzip:
return gzip.NewWriter(w)
default:
panic(c)
}
}