forked from imgproxy/imgproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gzippool.go
70 lines (53 loc) · 999 Bytes
/
gzippool.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
package main
import (
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"sync"
)
type gzipPool struct {
mutex sync.Mutex
top *gzipPoolEntry
}
type gzipPoolEntry struct {
gz *gzip.Writer
next *gzipPoolEntry
}
func newGzipPool(n int) (*gzipPool, error) {
pool := new(gzipPool)
for i := 0; i < n; i++ {
if err := pool.grow(); err != nil {
return nil, err
}
}
return pool, nil
}
func (p *gzipPool) grow() error {
gz, err := gzip.NewWriterLevel(ioutil.Discard, conf.GZipCompression)
if err != nil {
return fmt.Errorf("Can't init GZip compression: %s", err)
}
p.top = &gzipPoolEntry{
gz: gz,
next: p.top,
}
return nil
}
func (p *gzipPool) Get(w io.Writer) *gzip.Writer {
p.mutex.Lock()
defer p.mutex.Unlock()
if p.top == nil {
p.grow()
}
gz := p.top.gz
gz.Reset(w)
p.top = p.top.next
return gz
}
func (p *gzipPool) Put(gz *gzip.Writer) {
p.mutex.Lock()
defer p.mutex.Unlock()
gz.Reset(ioutil.Discard)
p.top = &gzipPoolEntry{gz: gz, next: p.top}
}