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"
|
"encoding/hex"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/Mrs4s/MiraiGo/utils"
|
"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 {
|
func ZlibUncompress(src []byte) []byte {
|
||||||
b := bytes.NewReader(src)
|
b := bytes.NewReader(src)
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
@ -30,11 +63,12 @@ func ZlibCompress(data []byte) []byte {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GZipCompress(data []byte) []byte {
|
func GZipCompress(data []byte) []byte {
|
||||||
buf := new(bytes.Buffer)
|
gw := acquireGzipWriter()
|
||||||
w := gzip.NewWriter(buf)
|
_, _ = gw.w.Write(data)
|
||||||
_, _ = w.Write(data)
|
_ = gw.w.Close()
|
||||||
_ = w.Close()
|
ret := append([]byte(nil), gw.buf.Bytes()...)
|
||||||
return buf.Bytes()
|
releaseGzipWriter(gw)
|
||||||
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
func GZipUncompress(src []byte) []byte {
|
func GZipUncompress(src []byte) []byte {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user