/
etag.go
90 lines (69 loc) · 1.31 KB
/
etag.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
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"hash"
"sync"
)
type etagPool struct {
mutex sync.Mutex
top *etagPoolEntry
}
type etagPoolEntry struct {
hash hash.Hash
enc *json.Encoder
next *etagPoolEntry
b []byte
}
func newEtagPool(n int) *etagPool {
pool := new(etagPool)
for i := 0; i < n; i++ {
pool.grow()
}
return pool
}
func (p *etagPool) grow() {
h := sha256.New()
enc := json.NewEncoder(h)
enc.SetEscapeHTML(false)
enc.SetIndent("", "")
p.top = &etagPoolEntry{
hash: h,
enc: enc,
b: make([]byte, 64),
next: p.top,
}
}
func (p *etagPool) Get() *etagPoolEntry {
p.mutex.Lock()
defer p.mutex.Unlock()
if p.top == nil {
p.grow()
}
entry := p.top
p.top = p.top.next
return entry
}
func (p *etagPool) Put(e *etagPoolEntry) {
p.mutex.Lock()
defer p.mutex.Unlock()
e.next = p.top
p.top = e
}
var eTagCalcPool *etagPool
func calcETag(ctx context.Context) ([]byte, context.CancelFunc) {
c := eTagCalcPool.Get()
cancel := func() { eTagCalcPool.Put(c) }
c.hash.Reset()
c.hash.Write(getImageData(ctx).Bytes())
footprint := c.hash.Sum(nil)
c.hash.Reset()
c.hash.Write(footprint)
c.hash.Write([]byte(version))
c.enc.Encode(conf)
c.enc.Encode(getProcessingOptions(ctx))
hex.Encode(c.b, c.hash.Sum(nil))
return c.b, cancel
}