diff --git a/binary/utils.go b/binary/utils.go index e74d3793..35f77642 100644 --- a/binary/utils.go +++ b/binary/utils.go @@ -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 {