Add pooler for mtproto_frame wrapper

This commit is contained in:
9seconds
2020-03-23 17:00:54 +03:00
parent 829669eefd
commit 6449109b2b
2 changed files with 28 additions and 4 deletions
+5 -4
View File
@@ -42,7 +42,9 @@ type wrapperMtprotoFrame struct {
}
func (w *wrapperMtprotoFrame) Read() (conntypes.Packet, error) { // nolint: funlen
buf := &bytes.Buffer{}
buf := acquireMtprotoFrameBytesBuffer()
defer releaseMtprotoFrameBytesBuffer(buf)
sum := crc32.NewIEEE()
writer := io.MultiWriter(buf, sum)
@@ -71,7 +73,6 @@ func (w *wrapperMtprotoFrame) Read() (conntypes.Packet, error) { // nolint: funl
}
buf.Reset()
buf.Grow(int(messageLength) - 4 - 4)
if _, err := io.CopyN(writer, w.parent, int64(messageLength)-4-4); err != nil {
return nil, fmt.Errorf("cannot read the message frame: %w", err)
@@ -113,8 +114,8 @@ func (w *wrapperMtprotoFrame) Write(p conntypes.Packet) error {
messageLength := 4 + 4 + len(p) + 4
paddingLength := (aes.BlockSize - messageLength%aes.BlockSize) % aes.BlockSize
buf := &bytes.Buffer{}
buf.Grow(messageLength + paddingLength)
buf := acquireMtprotoFrameBytesBuffer()
defer releaseMtprotoFrameBytesBuffer(buf)
binary.Write(buf, binary.LittleEndian, uint32(messageLength)) // nolint: errcheck
binary.Write(buf, binary.LittleEndian, w.writeSeqNo) // nolint: errcheck
+23
View File
@@ -0,0 +1,23 @@
package packet
import (
"bytes"
"sync"
)
var (
poolMtprotoFrameBytesBuffer = sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
)
func acquireMtprotoFrameBytesBuffer() *bytes.Buffer {
return poolMtprotoFrameBytesBuffer.Get().(*bytes.Buffer)
}
func releaseMtprotoFrameBytesBuffer(buf *bytes.Buffer) {
buf.Reset()
poolMtprotoFrameBytesBuffer.Put(buf)
}