Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions packages/pg-protocol/src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,26 @@ export class Parser {
this.bufferLength = 0
this.bufferOffset = 0
} else {
// Adjust the cursors of remainingBuffer
this.bufferLength = bufferFullLength - offset
this.bufferOffset = offset
// A partial message remains.
// Use a gradual shrinking strategy: only shrink if buffer is at least half empty,
// and when shrinking, reduce to half size (not exact size) to provide wiggle room.
const remainingLength = bufferFullLength - offset
const bufferUtilization = remainingLength / this.buffer.byteLength

if (bufferUtilization < 0.5) {
// Buffer is more than half empty - shrink it to half its current size
const newBufferSize = Math.max(this.buffer.byteLength / 2, remainingLength * 2)
const newBuffer = Buffer.allocUnsafe(newBufferSize)
this.buffer.copy(newBuffer, 0, offset, offset + remainingLength)

this.buffer = newBuffer
this.bufferOffset = 0
this.bufferLength = remainingLength
} else {
// Buffer utilization is reasonable - use existing cursor strategy
this.bufferLength = remainingLength
this.bufferOffset = offset
}
}
}

Expand Down