Skip to content

Commit 28ca678

Browse files
ronagRafaelGSS
authored andcommitted
buffer: optimize byteLength for common encodings
PR-URL: #54342 Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: Yagiz Nizipli <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
1 parent c6544ff commit 28ca678

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

lib/buffer.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -782,13 +782,22 @@ function byteLength(string, encoding) {
782782
if (len === 0)
783783
return 0;
784784

785-
if (encoding) {
786-
const ops = getEncodingOps(encoding);
787-
if (ops) {
788-
return ops.byteLength(string);
789-
}
785+
if (!encoding || encoding === 'utf8') {
786+
return byteLengthUtf8(string);
787+
}
788+
789+
if (encoding === 'ascii') {
790+
return len;
790791
}
791-
return byteLengthUtf8(string);
792+
793+
const ops = getEncodingOps(encoding);
794+
if (ops === undefined) {
795+
// TODO (ronag): Makes more sense to throw here.
796+
// throw new ERR_UNKNOWN_ENCODING(encoding);
797+
return byteLengthUtf8(string);
798+
}
799+
800+
return ops.byteLength(string);
792801
}
793802

794803
Buffer.byteLength = byteLength;

0 commit comments

Comments
 (0)