forked from go-pdf/fpdf
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxcompr.go
79 lines (65 loc) · 1.44 KB
/
xcompr.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
// Copyright ©2021 The go-pdf Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package fpdf
import (
"bytes"
"compress/zlib"
"fmt"
"sync"
)
var xmem = xmempool{
Pool: sync.Pool{
New: func() interface{} {
var m membuffer
return &m
},
},
}
type xmempool struct{ sync.Pool }
func (pool *xmempool) compress(data []byte) *membuffer {
mem := pool.Get().(*membuffer)
buf := &mem.buf
buf.Grow(len(data))
zw, err := zlib.NewWriterLevel(buf, zlib.BestSpeed)
if err != nil {
panic(fmt.Errorf("could not create zlib writer: %w", err))
}
_, err = zw.Write(data)
if err != nil {
panic(fmt.Errorf("could not zlib-compress slice: %w", err))
}
err = zw.Close()
if err != nil {
panic(fmt.Errorf("could not close zlib writer: %w", err))
}
return mem
}
func (pool *xmempool) uncompress(data []byte) (*membuffer, error) {
zr, err := zlib.NewReader(bytes.NewReader(data))
if err != nil {
return nil, err
}
mem := pool.Get().(*membuffer)
mem.buf.Reset()
_, err = mem.buf.ReadFrom(zr)
if err != nil {
mem.release()
return nil, err
}
return mem, nil
}
type membuffer struct {
buf bytes.Buffer
}
func (mem *membuffer) bytes() []byte { return mem.buf.Bytes() }
func (mem *membuffer) release() {
mem.buf.Reset()
xmem.Put(mem)
}
func (mem *membuffer) copy() []byte {
src := mem.bytes()
dst := make([]byte, len(src))
copy(dst, src)
return dst
}