...
1
2
3 package gzstd
4
5 import (
6 "compress/gzip"
7 "io"
8 "sync"
9
10 "github.com/klauspost/compress/gzhttp/writer"
11 )
12
13
14
15
16 var gzipWriterPools [gzip.BestCompression - gzip.HuffmanOnly + 1]*sync.Pool
17
18 func init() {
19 for i := gzip.HuffmanOnly; i <= gzip.BestCompression; i++ {
20 addLevelPool(i)
21 }
22 }
23
24
25
26 func poolIndex(level int) int {
27 if level > gzip.BestCompression {
28 level = gzip.BestCompression
29 }
30 if level < gzip.HuffmanOnly {
31 level = gzip.BestSpeed
32 }
33 return level - gzip.HuffmanOnly
34 }
35
36 func addLevelPool(level int) {
37 gzipWriterPools[poolIndex(level)] = &sync.Pool{
38 New: func() interface{} {
39
40
41
42 w, _ := gzip.NewWriterLevel(nil, level)
43 return w
44 },
45 }
46 }
47
48 type pooledWriter struct {
49 *gzip.Writer
50 index int
51 }
52
53 func (pw *pooledWriter) Close() error {
54 err := pw.Writer.Close()
55 gzipWriterPools[pw.index].Put(pw.Writer)
56 pw.Writer = nil
57 return err
58 }
59
60 func NewWriter(w io.Writer, level int) writer.GzipWriter {
61 index := poolIndex(level)
62 gzw := gzipWriterPools[index].Get().(*gzip.Writer)
63 gzw.Reset(w)
64 return &pooledWriter{
65 Writer: gzw,
66 index: index,
67 }
68 }
69
70
71 func (pw *pooledWriter) SetHeader(h writer.Header) {
72 pw.Name = h.Name
73 pw.Extra = h.Extra
74 pw.Comment = h.Comment
75 pw.ModTime = h.ModTime
76 pw.OS = h.OS
77 }
78
79 func Levels() (min, max int) {
80 return gzip.HuffmanOnly, gzip.BestCompression
81 }
82
83 func ImplementationInfo() string {
84 return "compress/gzip"
85 }
86
View as plain text