mirror of
https://github.com/Mrs4s/MiraiGo.git
synced 2025-05-04 19:17:38 +08:00
feat: gzip with sync pool
挺有用的
This commit is contained in:
parent
5a90a592d0
commit
192b8c562f
@ -8,10 +8,43 @@ import (
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/utils"
|
||||
)
|
||||
|
||||
type gzipWriter struct {
|
||||
w *gzip.Writer
|
||||
buf *bytes.Buffer
|
||||
}
|
||||
|
||||
var gzipPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
buf := new(bytes.Buffer)
|
||||
w := gzip.NewWriter(buf)
|
||||
return &gzipWriter{
|
||||
w: w,
|
||||
buf: buf,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func acquireGzipWriter() *gzipWriter {
|
||||
ret := gzipPool.Get().(*gzipWriter)
|
||||
ret.buf.Reset()
|
||||
ret.w.Reset(ret.buf)
|
||||
return ret
|
||||
}
|
||||
|
||||
func releaseGzipWriter(w *gzipWriter) {
|
||||
// See https://golang.org/issue/23199
|
||||
const maxSize = 1 << 15
|
||||
if w.buf.Cap() < maxSize {
|
||||
w.buf.Reset()
|
||||
gzipPool.Put(w)
|
||||
}
|
||||
}
|
||||
|
||||
func ZlibUncompress(src []byte) []byte {
|
||||
b := bytes.NewReader(src)
|
||||
var out bytes.Buffer
|
||||
@ -30,11 +63,12 @@ func ZlibCompress(data []byte) []byte {
|
||||
}
|
||||
|
||||
func GZipCompress(data []byte) []byte {
|
||||
buf := new(bytes.Buffer)
|
||||
w := gzip.NewWriter(buf)
|
||||
_, _ = w.Write(data)
|
||||
_ = w.Close()
|
||||
return buf.Bytes()
|
||||
gw := acquireGzipWriter()
|
||||
_, _ = gw.w.Write(data)
|
||||
_ = gw.w.Close()
|
||||
ret := append([]byte(nil), gw.buf.Bytes()...)
|
||||
releaseGzipWriter(gw)
|
||||
return ret
|
||||
}
|
||||
|
||||
func GZipUncompress(src []byte) []byte {
|
||||
|
Loading…
x
Reference in New Issue
Block a user