Skip to content

Commit ed3ad9f

Browse files
authored
websocket: avoid using Buffer.byteLength (#3394)
* websocket: avoid using Buffer.byteLength * rename sendHints.string to sendHints.text
1 parent db8e642 commit ed3ad9f

File tree

3 files changed

+11
-15
lines changed

3 files changed

+11
-15
lines changed

lib/web/websocket/constants.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ const parserStates = {
4747
const emptyBuffer = Buffer.allocUnsafe(0)
4848

4949
const sendHints = {
50-
string: 1,
50+
text: 1,
5151
typedArray: 2,
5252
arrayBuffer: 3,
5353
blob: 4

lib/web/websocket/sender.js

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,6 @@ const { WebsocketFrameSend } = require('./frame')
44
const { opcodes, sendHints } = require('./constants')
55
const FixedQueue = require('../../dispatcher/fixed-queue')
66

7-
/** @type {typeof Uint8Array} */
8-
const FastBuffer = Buffer[Symbol.species]
9-
107
/**
118
* @typedef {object} SendQueueNode
129
* @property {Promise<void> | null} promise
@@ -86,18 +83,17 @@ class SendQueue {
8683
}
8784

8885
function createFrame (data, hint) {
89-
return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.string ? opcodes.TEXT : opcodes.BINARY)
86+
return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.text ? opcodes.TEXT : opcodes.BINARY)
9087
}
9188

9289
function toBuffer (data, hint) {
9390
switch (hint) {
94-
case sendHints.string:
95-
return Buffer.from(data)
91+
case sendHints.text:
92+
case sendHints.typedArray:
93+
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
9694
case sendHints.arrayBuffer:
9795
case sendHints.blob:
98-
return new FastBuffer(data)
99-
case sendHints.typedArray:
100-
return new FastBuffer(data.buffer, data.byteOffset, data.byteLength)
96+
return new Uint8Array(data)
10197
}
10298
}
10399

lib/web/websocket/websocket.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -234,12 +234,12 @@ class WebSocket extends EventTarget {
234234
// the bufferedAmount attribute by the number of bytes needed to
235235
// express the argument as UTF-8.
236236

237-
const length = Buffer.byteLength(data)
237+
const buffer = Buffer.from(data)
238238

239-
this.#bufferedAmount += length
240-
this.#sendQueue.add(data, () => {
241-
this.#bufferedAmount -= length
242-
}, sendHints.string)
239+
this.#bufferedAmount += buffer.byteLength
240+
this.#sendQueue.add(buffer, () => {
241+
this.#bufferedAmount -= buffer.byteLength
242+
}, sendHints.text)
243243
} else if (types.isArrayBuffer(data)) {
244244
// If the WebSocket connection is established, and the WebSocket
245245
// closing handshake has not yet started, then the user agent must

0 commit comments

Comments
 (0)