Skip to content

Commit 99e9a13

Browse files
committed
faster buffer-writer
1 parent 76bbe37 commit 99e9a13

File tree

2 files changed

+40
-30
lines changed

2 files changed

+40
-30
lines changed

packages/pg-protocol/dist/buffer-writer.js

Lines changed: 20 additions & 15 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

packages/pg-protocol/src/buffer-writer.ts

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,17 @@ export class Writer {
2424

2525
public addInt32(num: number): Writer {
2626
this.ensure(4)
27-
this.buffer[this.offset++] = (num >>> 24) & 0xff
28-
this.buffer[this.offset++] = (num >>> 16) & 0xff
29-
this.buffer[this.offset++] = (num >>> 8) & 0xff
30-
this.buffer[this.offset++] = (num >>> 0) & 0xff
27+
// use Node Buffer native method for big-endian 32-bit integer
28+
this.buffer.writeInt32BE(num, this.offset)
29+
this.offset += 4
3130
return this
3231
}
3332

3433
public addInt16(num: number): Writer {
3534
this.ensure(2)
36-
this.buffer[this.offset++] = (num >>> 8) & 0xff
37-
this.buffer[this.offset++] = (num >>> 0) & 0xff
35+
// use Node Buffer native method for big-endian 16-bit integer
36+
this.buffer.writeInt16BE(num, this.offset)
37+
this.offset += 2
3838
return this
3939
}
4040

@@ -44,7 +44,8 @@ export class Writer {
4444
} else {
4545
let len = Buffer.byteLength(string)
4646
this.ensure(len + 1) // +1 for null terminator
47-
this.buffer.write(string, this.offset, 'utf-8')
47+
// write with explicit length and utf8 encoding
48+
this.buffer.write(string, this.offset, len, 'utf8')
4849
this.offset += len
4950
}
5051

@@ -55,20 +56,24 @@ export class Writer {
5556
public addString(string: string = ''): Writer {
5657
let len = Buffer.byteLength(string)
5758
this.ensure(len)
58-
this.buffer.write(string, this.offset)
59-
this.offset += len
59+
// pass explicit length and encoding to avoid incorrect arg ordering
60+
if (len > 0) {
61+
this.buffer.write(string, this.offset, len, 'utf8')
62+
this.offset += len
63+
}
6064
return this
6165
}
6266

6367
public addString32(string: string = ''): Writer {
6468
let len = Buffer.byteLength(string)
6569
this.ensure(len + 4)
66-
this.buffer[this.offset++] = (len >>> 24) & 0xff
67-
this.buffer[this.offset++] = (len >>> 16) & 0xff
68-
this.buffer[this.offset++] = (len >>> 8) & 0xff
69-
this.buffer[this.offset++] = (len >>> 0) & 0xff
70-
this.buffer.write(string, this.offset)
71-
this.offset += len
70+
// write 32-bit length prefix in big-endian order
71+
this.buffer.writeInt32BE(len, this.offset)
72+
this.offset += 4
73+
if (len > 0) {
74+
this.buffer.write(string, this.offset, len, 'utf8')
75+
this.offset += len
76+
}
7277
return this
7378
}
7479

0 commit comments

Comments
 (0)