GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — buffer: add isByteString · nodejs/node@98b8ffc

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • benchmark/buffers
    • buffer-isbytestring.js
  • doc/api
    • buffer.md
  • lib
    • buffer.js
  • src
    • node_buffer.cc
  • test/parallel
    • test-buffer-isbytestring.js
    • test-buffer-isutf8-isascii-fast.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎benchmark/buffers/buffer-isbytestring.js‎

Copy file name to clipboard
+57Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
const buffer = require('node:buffer');
5+
const assert = require('node:assert');
6+
7+
const bench = common.createBenchmark(main, {
8+
n: [1e7],
9+
length: ['short', 'long'],
10+
// onebyte: one-byte representation (O(1) check)
11+
// twobyte: two-byte representation containing only code units <= 0xFF
12+
// invalid: ends with a code unit > 0xFF
13+
input: ['onebyte', 'twobyte', 'invalid'],
14+
method: ['isByteString', 'loop', 'regex'],
15+
});
16+
17+
function loop(str) {
18+
for (let i = 0; i < str.length; i++) {
19+
if (str.charCodeAt(i) > 255) return false;
20+
}
21+
return true;
22+
}
23+
24+
const notByteStringRe = /[\u0100-\uffff]/;
25+
function regex(str) {
26+
return !notByteStringRe.test(str);
27+
}
28+
29+
const methods = { isByteString: buffer.isByteString, loop, regex };
30+
31+
function main({ n, length, input, method }) {
32+
const base = length === 'short' ? 'hello w\u00f6rld' : 'hello w\u00f6rld'.repeat(200);
33+
let str;
34+
switch (input) {
35+
case 'onebyte':
36+
str = base;
37+
break;
38+
case 'twobyte':
39+
// Slicing a two-byte string keeps the two-byte representation.
40+
str = ('\u0100' + base).slice(1);
41+
break;
42+
case 'invalid':
43+
str = base + '\u0100';
44+
break;
45+
}
46+
const expected = input !== 'invalid';
47+
const fn = methods[method];
48+
assert.strictEqual(fn(str), expected);
49+
50+
bench.start();
51+
let result;
52+
for (let i = 0; i < n; ++i) {
53+
result = fn(str);
54+
}
55+
bench.end(n);
56+
assert.strictEqual(result, expected);
57+
}
Collapse file

‎doc/api/buffer.md‎

Copy file name to clipboardExpand all lines: doc/api/buffer.md
+43Lines changed: 43 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -5414,6 +5414,46 @@ including the case in which `input` is empty.
54145414

54155415
A detached `ArrayBuffer`, or a `TypedArray` backed by one, is treated as empty.
54165416

5417+
### `buffer.isByteString(input)`
5418+
5419+
<!-- YAML
5420+
added: REPLACEME
5421+
-->
5422+
5423+
* `input` {string} The string to validate.
5424+
* Returns: {boolean}
5425+
5426+
This function returns `true` if `input` is a valid [WebIDL `ByteString`][],
5427+
that is, if every UTF-16 code unit of `input` is less than or equal to `0xFF`,
5428+
including the case in which `input` is empty. Such a string can be losslessly
5429+
encoded using the `'latin1'` encoding.
5430+
5431+
Despite its name, a `ByteString` is a JavaScript string, not binary data.
5432+
Unlike [`buffer.isAscii()`][] and [`buffer.isUtf8()`][], this function
5433+
therefore validates a string rather than a `Buffer`, `TypedArray`, or
5434+
`ArrayBuffer`. Every byte sequence would trivially be valid, since every byte
5435+
maps to a code unit less than or equal to `0xFF`.
5436+
5437+
```mjs
5438+
import { isByteString } from 'node:buffer';
5439+
5440+
isByteString('hello'); // true
5441+
isByteString('café'); // true
5442+
isByteString('\u00ff'); // true
5443+
isByteString('\u0100'); // false
5444+
isByteString('€'); // false
5445+
```
5446+
5447+
```cjs
5448+
const { isByteString } = require('node:buffer');
5449+
5450+
isByteString('hello'); // true
5451+
isByteString('café'); // true
5452+
isByteString('\u00ff'); // true
5453+
isByteString('\u0100'); // false
5454+
isByteString('€'); // false
5455+
```
5456+
54175457
### `buffer.isUtf8(input)`
54185458

54195459
<!-- YAML
@@ -5775,6 +5815,7 @@ or after startup, if the alignment has to hold at run time.
57755815
[UTF-16]: https://en.wikipedia.org/wiki/UTF-16
57765816
[UTF-8]: https://en.wikipedia.org/wiki/UTF-8
57775817
[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/
5818+
[WebIDL `ByteString`]: https://webidl.spec.whatwg.org/#idl-ByteString
57785819
[`--build-snapshot`]: cli.md#--build-snapshot
57795820
[`Buffer.alloc()`]: #static-method-bufferallocsize-fill-encoding
57805821
[`Buffer.allocUnsafe()`]: #static-method-bufferallocunsafesize-alignment
@@ -5814,6 +5855,8 @@ or after startup, if the alignment has to hold at run time.
58145855
[`buf.values()`]: #bufvalues
58155856
[`buffer.constants.MAX_LENGTH`]: #bufferconstantsmax_length
58165857
[`buffer.constants.MAX_STRING_LENGTH`]: #bufferconstantsmax_string_length
5858+
[`buffer.isAscii()`]: #bufferisasciiinput
5859+
[`buffer.isUtf8()`]: #bufferisutf8input
58175860
[`buffer.kMaxLength`]: #bufferkmaxlength
58185861
[`util.inspect()`]: util.md#utilinspectobject-options
58195862
[`v8.startupSnapshot.setDeserializeMainFunction()`]: v8.md#v8startupsnapshotsetdeserializemainfunctioncallback-data
Collapse file

‎lib/buffer.js‎

Copy file name to clipboardExpand all lines: lib/buffer.js
+7Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ const {
6262
copy: _copy,
6363
fill: bindingFill,
6464
isAscii: bindingIsAscii,
65+
isByteString: bindingIsByteString,
6566
isUtf8: bindingIsUtf8,
6667
stringLengthUtf8: bindingStringLengthUtf8,
6768
indexOfBuffer,
@@ -1498,6 +1499,11 @@ function isAscii(input) {
14981499
throw new ERR_INVALID_ARG_TYPE('input', ['ArrayBuffer', 'Buffer', 'TypedArray'], input);
14991500
}
15001501

1502+
function isByteString(input) {
1503+
validateString(input, 'input');
1504+
return bindingIsByteString(input);
1505+
}
1506+
15011507
function stringLength(input, encoding = 'utf8') {
15021508
if (!isTypedArray(input) && !isAnyArrayBuffer(input)) {
15031509
throw new ERR_INVALID_ARG_TYPE('input', ['ArrayBuffer', 'Buffer', 'TypedArray'], input);
@@ -1529,6 +1535,7 @@ module.exports = {
15291535
transcode,
15301536
isUtf8,
15311537
isAscii,
1538+
isByteString,
15321539

15331540
// Legacy
15341541
kMaxLength,
Collapse file

‎src/node_buffer.cc‎

Copy file name to clipboardExpand all lines: src/node_buffer.cc
+27Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1414,6 +1414,29 @@ static bool FastIsAscii(Local<Value> receiver,
14141414

14151415
static CFunction fast_is_ascii(CFunction::Make(FastIsAscii));
14161416

1417+
// Returns true if every UTF-16 code unit of the string is <= 0xFF, i.e. the
1418+
// string is a valid WebIDL ByteString. ContainsOnlyOneByte() is O(1) for
1419+
// strings with a one-byte representation, uses SIMD for flat two-byte
1420+
// strings, and traverses cons strings without flattening (no allocation),
1421+
// which makes it safe to call from a fast API call.
1422+
static void IsByteString(const FunctionCallbackInfo<Value>& args) {
1423+
CHECK_EQ(args.Length(), 1);
1424+
CHECK(args[0]->IsString());
1425+
args.GetReturnValue().Set(args[0].As<String>()->ContainsOnlyOneByte());
1426+
}
1427+
1428+
static bool FastIsByteString(Local<Value> receiver,
1429+
Local<Value> value,
1430+
// NOLINTNEXTLINE(runtime/references)
1431+
FastApiCallbackOptions& options) {
1432+
TRACK_V8_FAST_API_CALL("buffer.isByteString");
1433+
HandleScope scope(options.isolate);
1434+
CHECK(value->IsString());
1435+
return value.As<String>()->ContainsOnlyOneByte();
1436+
}
1437+
1438+
static CFunction fast_is_byte_string(CFunction::Make(FastIsByteString));
1439+
14171440
// Number of UTF-16 code units produced by decoding [p, end) as UTF-8 with
14181441
// WHATWG "maximal subpart" U+FFFD replacement, matching the fallback that
14191442
// StringBytes::Encode takes for invalid input (v8::String::NewFromUtf8).
@@ -1928,6 +1951,8 @@ void Initialize(Local<Object> target,
19281951
SetFastMethodNoSideEffect(context, target, "isUtf8", IsUtf8, &fast_is_utf8);
19291952
SetFastMethodNoSideEffect(
19301953
context, target, "isAscii", IsAscii, &fast_is_ascii);
1954+
SetFastMethodNoSideEffect(
1955+
context, target, "isByteString", IsByteString, &fast_is_byte_string);
19311956
SetFastMethodNoSideEffect(context,
19321957
target,
19331958
"stringLengthUtf8",
@@ -2008,6 +2033,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
20082033
registry->Register(fast_is_utf8);
20092034
registry->Register(IsAscii);
20102035
registry->Register(fast_is_ascii);
2036+
registry->Register(IsByteString);
2037+
registry->Register(fast_is_byte_string);
20112038
registry->Register(StringLengthUtf8);
20122039
registry->Register(fast_string_length_utf8);
20132040

Collapse file

‎test/parallel/test-buffer-isbytestring.js‎

Copy file name to clipboard
+85Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
'use strict';
2+
3+
require('../common');
4+
const assert = require('assert');
5+
const { isByteString } = require('buffer');
6+
7+
function reference(str) {
8+
for (let i = 0; i < str.length; i++) {
9+
if (str.charCodeAt(i) > 0xFF) return false;
10+
}
11+
return true;
12+
}
13+
14+
// Basic cases.
15+
assert.strictEqual(isByteString(''), true);
16+
assert.strictEqual(isByteString('hello'), true);
17+
assert.strictEqual(isByteString('\x00'), true);
18+
assert.strictEqual(isByteString('\x7f\x80'), true);
19+
assert.strictEqual(isByteString('caf\u00e9'), true);
20+
assert.strictEqual(isByteString('\u00ff'), true);
21+
assert.strictEqual(isByteString('\u0100'), false);
22+
assert.strictEqual(isByteString('\u20ac'), false);
23+
assert.strictEqual(isByteString('\uffff'), false);
24+
// Surrogate pairs and lone surrogates are > 0xFF.
25+
assert.strictEqual(isByteString('\ud83d\ude00'), false);
26+
assert.strictEqual(isByteString('\ud800'), false);
27+
assert.strictEqual(isByteString('\udfff'), false);
28+
29+
// Position of the offending code unit must not matter, and long strings must
30+
// exercise the vectorized paths.
31+
for (const len of [1, 7, 8, 15, 16, 31, 32, 33, 63, 64, 65, 1000, 4099]) {
32+
const base = 'a\u00ff'.repeat(len).slice(0, len);
33+
assert.strictEqual(isByteString(base), true);
34+
for (const pos of [0, len >> 1, len - 1]) {
35+
for (const ch of ['\u0100', '\u1234', '\ud800', '\uffff']) {
36+
const str = base.slice(0, pos) + ch + base.slice(pos + 1);
37+
assert.strictEqual(isByteString(str), false, `len=${len} pos=${pos}`);
38+
}
39+
}
40+
}
41+
42+
// Strings stored with a two-byte representation that only contain code units
43+
// <= 0xFF must still be reported as ByteStrings.
44+
{
45+
const twoByte = '\u0100' + 'abc\u00e9\u00ff'.repeat(100);
46+
const sliced = twoByte.slice(1);
47+
assert.strictEqual(isByteString(twoByte), false);
48+
assert.strictEqual(isByteString(sliced), true);
49+
assert.strictEqual(isByteString(twoByte.substring(1, 20)), true);
50+
}
51+
52+
// Cons strings (results of concatenation) with mixed representations.
53+
{
54+
let cons = '';
55+
for (let i = 0; i < 100; i++) cons += `x${i}\u00e9`;
56+
assert.strictEqual(isByteString(cons), true);
57+
assert.strictEqual(isByteString(cons + '\u0100'), false);
58+
assert.strictEqual(isByteString('\u0100' + cons), false);
59+
assert.strictEqual(isByteString(cons + '\u0100'.slice(1) + cons), true);
60+
}
61+
62+
// Randomized comparison with the reference implementation.
63+
for (let i = 0; i < 1000; i++) {
64+
const len = Math.floor(Math.random() * 100);
65+
const max = Math.random() < 0.5 ? 0x100 : 0x10000;
66+
let str = '';
67+
for (let j = 0; j < len; j++) {
68+
// Keep the probability of producing a code unit > 0xFF low so that
69+
// both outcomes are exercised.
70+
const code = Math.random() < 0.98 ?
71+
Math.floor(Math.random() * 0x100) :
72+
Math.floor(Math.random() * max);
73+
str += String.fromCharCode(code);
74+
}
75+
assert.strictEqual(isByteString(str), reference(str), JSON.stringify(str));
76+
}
77+
78+
// Invalid argument types.
79+
[
80+
undefined, null, 1, 1n, true, {}, [], Symbol('a'),
81+
Buffer.from('a'), new Uint8Array(1), new ArrayBuffer(1),
82+
new String('a'),
83+
].forEach((input) => {
84+
assert.throws(() => isByteString(input), { code: 'ERR_INVALID_ARG_TYPE' });
85+
});
Collapse file

‎test/parallel/test-buffer-isutf8-isascii-fast.js‎

Copy file name to clipboardExpand all lines: test/parallel/test-buffer-isutf8-isascii-fast.js
+12-1Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33

44
const common = require('../common');
55
const assert = require('assert');
6-
const { Buffer, isAscii, isUtf8 } = require('buffer');
6+
const { Buffer, isAscii, isByteString, isUtf8 } = require('buffer');
77

88
const ascii = Buffer.from('hello');
99
const utf8 = Buffer.from('hello \xc4\x9f');
10+
const byteString = 'hello \u00e9';
1011

1112
function testFastIsAscii() {
1213
assert.strictEqual(isAscii(ascii), true);
@@ -16,6 +17,10 @@ function testFastIsUtf8() {
1617
assert.strictEqual(isUtf8(utf8), true);
1718
}
1819

20+
function testFastIsByteString() {
21+
assert.strictEqual(isByteString(byteString), true);
22+
}
23+
1924
eval('%PrepareFunctionForOptimization(isAscii)');
2025
testFastIsAscii();
2126
eval('%OptimizeFunctionOnNextCall(isAscii)');
@@ -26,9 +31,15 @@ testFastIsUtf8();
2631
eval('%OptimizeFunctionOnNextCall(isUtf8)');
2732
testFastIsUtf8();
2833

34+
eval('%PrepareFunctionForOptimization(isByteString)');
35+
testFastIsByteString();
36+
eval('%OptimizeFunctionOnNextCall(isByteString)');
37+
testFastIsByteString();
38+
2939
if (common.isDebug) {
3040
const { internalBinding } = require('internal/test/binding');
3141
const { getV8FastApiCallCount } = internalBinding('debug');
3242
assert.strictEqual(getV8FastApiCallCount('buffer.isAscii'), 1);
3343
assert.strictEqual(getV8FastApiCallCount('buffer.isUtf8'), 1);
44+
assert.strictEqual(getV8FastApiCallCount('buffer.isByteString'), 1);
3445
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.