diff --git a/wrappers/packet/mtproto_frame.go b/wrappers/packet/mtproto_frame.go index 6a1cd1a..6190d39 100644 --- a/wrappers/packet/mtproto_frame.go +++ b/wrappers/packet/mtproto_frame.go @@ -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 diff --git a/wrappers/packet/pools.go b/wrappers/packet/pools.go new file mode 100644 index 0000000..c27e30e --- /dev/null +++ b/wrappers/packet/pools.go @@ -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) +}