@@ -24,54 +24,56 @@ import (
24
24
25
25
// Read packet to buffer 'data'
26
26
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
+ }
34
36
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 )
37
39
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
+ }
43
45
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
+ }
50
53
}
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 )
53
65
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 {
57
68
return data , nil
58
69
}
59
70
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 ... )
63
72
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
68
75
}
69
76
}
70
-
71
- // err case
72
- mc .Close ()
73
- errLog .Print (err .Error ())
74
- return nil , driver .ErrBadConn
75
77
}
76
78
77
79
// Write packet buffer 'data'
0 commit comments