@@ -96,11 +96,20 @@ export class Parser {
96
96
const newLength = this . remainingBufferLength + combinedBufferLength
97
97
const newFullLength = newLength + this . remainingBufferOffset
98
98
if ( newFullLength > this . remainingBuffer . byteLength ) {
99
- let newBufferLength = this . remainingBuffer . byteLength * 2
100
- while ( newLength >= newBufferLength ) {
101
- newBufferLength *= 2
99
+ // We can't concat the new buffer with the remaining one
100
+ let newBuffer : Buffer
101
+ if ( newLength <= this . remainingBuffer . byteLength && this . remainingBufferOffset >= this . remainingBufferLength ) {
102
+ // We can move the relevant part to the beginning of the buffer instead of allocating a new buffer
103
+ newBuffer = this . remainingBuffer
104
+ } else {
105
+ // Allocate a new larger buffer
106
+ let newBufferLength = this . remainingBuffer . byteLength * 2
107
+ while ( newLength >= newBufferLength ) {
108
+ newBufferLength *= 2
109
+ }
110
+ newBuffer = Buffer . allocUnsafe ( newBufferLength )
102
111
}
103
- const newBuffer = Buffer . allocUnsafe ( newBufferLength )
112
+ // Move the remaining buffer to the new one
104
113
this . remainingBuffer . copy (
105
114
newBuffer ,
106
115
0 ,
@@ -110,6 +119,7 @@ export class Parser {
110
119
this . remainingBuffer = newBuffer
111
120
this . remainingBufferOffset = 0
112
121
}
122
+ // Concat the new buffer with the remaining one
113
123
buffer . copy ( this . remainingBuffer , this . remainingBufferOffset + this . remainingBufferLength )
114
124
combinedBuffer = this . remainingBuffer
115
125
combinedBufferLength = this . remainingBufferLength = newLength
@@ -134,16 +144,18 @@ export class Parser {
134
144
break
135
145
}
136
146
}
137
-
138
147
if ( offset === fullLength ) {
148
+ // No more use for the buffer
139
149
this . remainingBuffer = emptyBuffer
140
150
this . remainingBufferLength = 0
141
151
this . remainingBufferOffset = 0
142
152
} else {
143
153
if ( reuseRemainingBuffer ) {
154
+ // Adjust the cursors of remainingBuffer
144
155
this . remainingBufferLength = combinedBufferLength - offset
145
156
this . remainingBufferOffset += offset
146
157
} else {
158
+ // To avoid side effects, copy the remaining part of the new buffer to remainingBuffer
147
159
this . remainingBuffer = combinedBuffer . slice ( offset )
148
160
this . remainingBufferLength = this . remainingBuffer . byteLength
149
161
this . remainingBufferOffset = 0
0 commit comments