1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-01-08 10:45:04 +02:00
imgproxy/etag.go

91 lines
1.3 KiB
Go
Raw Normal View History

package main
import (
2018-10-05 18:20:29 +02:00
"context"
"crypto/sha256"
2018-10-05 21:45:14 +02:00
"encoding/hex"
"encoding/json"
"hash"
"sync"
)
2019-02-25 14:26:51 +02:00
type etagPool struct {
mutex sync.Mutex
top *etagPoolEntry
}
type etagPoolEntry struct {
2018-10-05 21:45:14 +02:00
hash hash.Hash
enc *json.Encoder
2019-02-25 14:26:51 +02:00
next *etagPoolEntry
2019-03-22 19:27:32 +02:00
b []byte
2019-02-25 14:26:51 +02:00
}
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,
2019-03-22 19:27:32 +02:00
b: make([]byte, 64),
2019-02-25 14:26:51 +02:00
next: p.top,
}
2018-10-05 21:45:14 +02:00
}
2019-02-25 14:26:51 +02:00
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
2018-10-05 21:45:14 +02:00
2019-02-25 14:26:51 +02:00
return entry
}
func (p *etagPool) Put(e *etagPoolEntry) {
p.mutex.Lock()
defer p.mutex.Unlock()
2018-10-05 21:45:14 +02:00
2019-02-25 14:26:51 +02:00
e.next = p.top
p.top = e
2018-10-05 21:45:14 +02:00
}
2019-02-25 14:26:51 +02:00
var eTagCalcPool *etagPool
func calcETag(ctx context.Context) ([]byte, context.CancelFunc) {
c := eTagCalcPool.Get()
cancel := func() { eTagCalcPool.Put(c) }
2018-10-05 21:45:14 +02:00
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))
2019-03-22 19:27:32 +02:00
hex.Encode(c.b, c.hash.Sum(nil))
2019-02-25 14:26:51 +02:00
2019-03-22 19:27:32 +02:00
return c.b, cancel
}