@@ -91,11 +91,12 @@ export class Parser {
91
91
let combinedBuffer = buffer
92
92
let combinedBufferOffset = 0
93
93
let combinedBufferLength = buffer . byteLength
94
- const newRealLength = this . remainingBufferLength + combinedBufferLength
95
- if ( this . remainingBufferLength ) {
94
+ let remainingBufferNotEmpty = this . remainingBufferLength > 0
95
+ if ( remainingBufferNotEmpty ) {
96
+ const newRealLength = this . remainingBufferLength + combinedBufferLength
96
97
const newLength = newRealLength + this . remainingBufferOffset
97
98
if ( newLength > this . remainingBuffer . byteLength ) {
98
- let newBufferLength = this . remainingBufferLength * 2
99
+ let newBufferLength = this . remainingBuffer . byteLength * 2
99
100
while ( newRealLength >= newBufferLength ) {
100
101
newBufferLength *= 2
101
102
}
@@ -111,11 +112,12 @@ export class Parser {
111
112
}
112
113
buffer . copy ( this . remainingBuffer , this . remainingBufferOffset + this . remainingBufferLength )
113
114
combinedBuffer = this . remainingBuffer
114
- combinedBufferLength = newRealLength
115
+ combinedBufferLength = this . remainingBufferLength = newRealLength
115
116
combinedBufferOffset = this . remainingBufferOffset
116
117
}
118
+ const realLength = combinedBufferOffset + combinedBufferLength
117
119
let offset = combinedBufferOffset
118
- while ( offset + HEADER_LENGTH <= combinedBufferLength ) {
120
+ while ( offset + HEADER_LENGTH <= realLength ) {
119
121
// code is 1 byte long - it identifies the message type
120
122
const code = combinedBuffer [ offset ]
121
123
@@ -124,7 +126,7 @@ export class Parser {
124
126
125
127
const fullMessageLength = CODE_LENGTH + length
126
128
127
- if ( fullMessageLength + offset <= combinedBufferLength ) {
129
+ if ( fullMessageLength + offset <= realLength ) {
128
130
const message = this . handlePacket ( offset + HEADER_LENGTH , code , length , combinedBuffer )
129
131
callback ( message )
130
132
offset += fullMessageLength
@@ -133,12 +135,12 @@ export class Parser {
133
135
}
134
136
}
135
137
136
- if ( offset === combinedBufferLength ) {
138
+ if ( offset === realLength ) {
137
139
this . remainingBuffer = emptyBuffer
138
140
this . remainingBufferLength = 0
139
141
this . remainingBufferOffset = 0
140
142
} else {
141
- this . remainingBuffer = combinedBuffer
143
+ this . remainingBuffer = remainingBufferNotEmpty ? combinedBuffer : combinedBuffer . slice ( )
142
144
this . remainingBufferLength = combinedBufferLength - offset
143
145
this . remainingBufferOffset += offset
144
146
}
0 commit comments