Skip to content

Commit 4c8905e

Browse files
committed
Merge pull request #170 from cxmcc/minor
Replace recursive approach with iterative approach for readPacket()
2 parents 587def8 + 7847296 commit 4c8905e

File tree

1 file changed

+39
-37
lines changed

1 file changed

+39
-37
lines changed

packets.go

Lines changed: 39 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -24,54 +24,56 @@ import (
2424

2525
// Read packet to buffer 'data'
2626
func (mc *mysqlConn) readPacket() ([]byte, error) {
27-
// Read packet header
28-
data, err := mc.buf.readNext(4)
29-
if err != nil {
30-
errLog.Print(err.Error())
31-
mc.Close()
32-
return nil, driver.ErrBadConn
33-
}
27+
var payload []byte
28+
for {
29+
// Read packet header
30+
data, err := mc.buf.readNext(4)
31+
if err != nil {
32+
errLog.Print(err.Error())
33+
mc.Close()
34+
return nil, driver.ErrBadConn
35+
}
3436

35-
// Packet Length [24 bit]
36-
pktLen := int(uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16)
37+
// Packet Length [24 bit]
38+
pktLen := int(uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16)
3739

38-
if pktLen < 1 {
39-
errLog.Print(errMalformPkt.Error())
40-
mc.Close()
41-
return nil, driver.ErrBadConn
42-
}
40+
if pktLen < 1 {
41+
errLog.Print(errMalformPkt.Error())
42+
mc.Close()
43+
return nil, driver.ErrBadConn
44+
}
4345

44-
// Check Packet Sync [8 bit]
45-
if data[3] != mc.sequence {
46-
if data[3] > mc.sequence {
47-
return nil, errPktSyncMul
48-
} else {
49-
return nil, errPktSync
46+
// Check Packet Sync [8 bit]
47+
if data[3] != mc.sequence {
48+
if data[3] > mc.sequence {
49+
return nil, errPktSyncMul
50+
} else {
51+
return nil, errPktSync
52+
}
5053
}
51-
}
52-
mc.sequence++
54+
mc.sequence++
55+
56+
// Read packet body [pktLen bytes]
57+
data, err = mc.buf.readNext(pktLen)
58+
if err != nil {
59+
errLog.Print(err.Error())
60+
mc.Close()
61+
return nil, driver.ErrBadConn
62+
}
63+
64+
isLastPacket := (pktLen < maxPacketSize)
5365

54-
// Read packet body [pktLen bytes]
55-
if data, err = mc.buf.readNext(pktLen); err == nil {
56-
if pktLen < maxPacketSize {
66+
// Zero allocations for non-splitting packets
67+
if isLastPacket && payload == nil {
5768
return data, nil
5869
}
5970

60-
// Make a copy since data becomes invalid with the next read
61-
buf := make([]byte, len(data))
62-
copy(buf, data)
71+
payload = append(payload, data...)
6372

64-
// More data
65-
data, err = mc.readPacket()
66-
if err == nil {
67-
return append(buf, data...), nil
73+
if isLastPacket {
74+
return payload, nil
6875
}
6976
}
70-
71-
// err case
72-
mc.Close()
73-
errLog.Print(err.Error())
74-
return nil, driver.ErrBadConn
7577
}
7678

7779
// Write packet buffer 'data'

0 commit comments

Comments
 (0)