Debian Codegraph @

gzhttp/writer/gzstd/stdlib.go

raw
1 // package gzstd provides gzip compression through the standard library.
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 // gzipWriterPools stores a sync.Pool for each compression level for reuse of
14 // gzip.Writers. Use poolIndex to covert a compression level to an index into
15 // gzipWriterPools.
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 // poolIndex maps a compression level to its index into gzipWriterPools. It
25 // assumes that level is a valid gzip compression level.
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() any {
39 // NewWriterLevel only returns error on a bad level, we are guaranteeing
40 // that this will be a valid level so it is okay to ignore the returned
41 // error.
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 // SetHeader will override the gzip header on pw.
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 }