Преглед изворни кода

Add pooler for mtproto_frame wrapper

tags/v1.0.4^2
9seconds пре 6 година
родитељ
комит
6449109b2b
2 измењених фајлова са 28 додато и 4 уклоњено
  1. 5
    4
      wrappers/packet/mtproto_frame.go
  2. 23
    0
      wrappers/packet/pools.go

+ 5
- 4
wrappers/packet/mtproto_frame.go Прегледај датотеку

@@ -42,7 +42,9 @@ type wrapperMtprotoFrame struct {
42 42
 }
43 43
 
44 44
 func (w *wrapperMtprotoFrame) Read() (conntypes.Packet, error) { // nolint: funlen
45
-	buf := &bytes.Buffer{}
45
+	buf := acquireMtprotoFrameBytesBuffer()
46
+	defer releaseMtprotoFrameBytesBuffer(buf)
47
+
46 48
 	sum := crc32.NewIEEE()
47 49
 	writer := io.MultiWriter(buf, sum)
48 50
 
@@ -71,7 +73,6 @@ func (w *wrapperMtprotoFrame) Read() (conntypes.Packet, error) { // nolint: funl
71 73
 	}
72 74
 
73 75
 	buf.Reset()
74
-	buf.Grow(int(messageLength) - 4 - 4)
75 76
 
76 77
 	if _, err := io.CopyN(writer, w.parent, int64(messageLength)-4-4); err != nil {
77 78
 		return nil, fmt.Errorf("cannot read the message frame: %w", err)
@@ -113,8 +114,8 @@ func (w *wrapperMtprotoFrame) Write(p conntypes.Packet) error {
113 114
 	messageLength := 4 + 4 + len(p) + 4
114 115
 	paddingLength := (aes.BlockSize - messageLength%aes.BlockSize) % aes.BlockSize
115 116
 
116
-	buf := &bytes.Buffer{}
117
-	buf.Grow(messageLength + paddingLength)
117
+	buf := acquireMtprotoFrameBytesBuffer()
118
+	defer releaseMtprotoFrameBytesBuffer(buf)
118 119
 
119 120
 	binary.Write(buf, binary.LittleEndian, uint32(messageLength)) // nolint: errcheck
120 121
 	binary.Write(buf, binary.LittleEndian, w.writeSeqNo)          // nolint: errcheck

+ 23
- 0
wrappers/packet/pools.go Прегледај датотеку

@@ -0,0 +1,23 @@
1
+package packet
2
+
3
+import (
4
+	"bytes"
5
+	"sync"
6
+)
7
+
8
+var (
9
+	poolMtprotoFrameBytesBuffer = sync.Pool{
10
+		New: func() interface{} {
11
+			return &bytes.Buffer{}
12
+		},
13
+	}
14
+)
15
+
16
+func acquireMtprotoFrameBytesBuffer() *bytes.Buffer {
17
+	return poolMtprotoFrameBytesBuffer.Get().(*bytes.Buffer)
18
+}
19
+
20
+func releaseMtprotoFrameBytesBuffer(buf *bytes.Buffer) {
21
+	buf.Reset()
22
+	poolMtprotoFrameBytesBuffer.Put(buf)
23
+}

Loading…
Откажи
Сачувај