From 5ea36a76b5ba03f096f3d0e456025faf298c0f48 Mon Sep 17 00:00:00 2001 From: zirkelc Date: Thu, 24 Sep 2026 15:57:52 +0200 Subject: [PATCH] perf(webidl): check ByteString code units with a native scan --- lib/web/webidl/index.js | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/web/webidl/index.js b/lib/web/webidl/index.js index 6f4bd5036c0..ffda4fb584c 100644 --- a/lib/web/webidl/index.js +++ b/lib/web/webidl/index.js @@ -607,6 +607,9 @@ webidl.converters.DOMString = function (V, prefix, argument, flags) { return String(V) } +// Matches any UTF-16 code unit above 255. +const nonByteStringCodeUnit = /[\u0100-\uffff]/ + // https://webidl.spec.whatwg.org/#es-ByteString webidl.converters.ByteString = function (V, prefix, argument) { // 1. Let x be ? ToString(V). @@ -621,13 +624,14 @@ webidl.converters.ByteString = function (V, prefix, argument) { // 2. If the value of any element of x is greater than // 255, then throw a TypeError. - for (let index = 0; index < x.length; index++) { - if (x.charCodeAt(index) > 255) { - throw new TypeError( - 'Cannot convert argument to a ByteString because the character at ' + - `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` - ) - } + // Note: A native regular expression scan instead of a loop over x. The + // index is only needed for the error message. + if (nonByteStringCodeUnit.test(x)) { + const index = x.search(nonByteStringCodeUnit) + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` + ) } // 3. Return an IDL ByteString value whose length is the