GeezerVison is showing github.com — buffer: add isByteString · nodejs/node@98b8ffc
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboard +57Lines changed: 57 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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 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 number | Diff line number | Diff line change |
|---|
@@ -5414,6 +5414,46 @@ including the case in which `input` is empty. | 5414 | 5414 |
| 5415 | 5415 | A detached `ArrayBuffer`, or a `TypedArray` backed by one, is treated as empty. | 5416 | 5416 |
| | 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 | + | 5417 | 5457 | ### `buffer.isUtf8(input)` | 5418 | 5458 |
| 5419 | 5459 | <!-- YAML | @@ -5775,6 +5815,7 @@ or after startup, if the alignment has to hold at run time. | 5775 | 5815 | [UTF-16]: https://en.wikipedia.org/wiki/UTF-16 | 5776 | 5816 | [UTF-8]: https://en.wikipedia.org/wiki/UTF-8 | 5777 | 5817 | [WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/ | | 5818 | +[WebIDL `ByteString`]: https://webidl.spec.whatwg.org/#idl-ByteString | 5778 | 5819 | [`--build-snapshot`]: cli.md#--build-snapshot | 5779 | 5820 | [`Buffer.alloc()`]: #static-method-bufferallocsize-fill-encoding | 5780 | 5821 | [`Buffer.allocUnsafe()`]: #static-method-bufferallocunsafesize-alignment | @@ -5814,6 +5855,8 @@ or after startup, if the alignment has to hold at run time. | 5814 | 5855 | [`buf.values()`]: #bufvalues | 5815 | 5856 | [`buffer.constants.MAX_LENGTH`]: #bufferconstantsmax_length | 5816 | 5857 | [`buffer.constants.MAX_STRING_LENGTH`]: #bufferconstantsmax_string_length | | 5858 | +[`buffer.isAscii()`]: #bufferisasciiinput | | 5859 | +[`buffer.isUtf8()`]: #bufferisutf8input | 5817 | 5860 | [`buffer.kMaxLength`]: #bufferkmaxlength | 5818 | 5861 | [`util.inspect()`]: util.md#utilinspectobject-options | 5819 | 5862 | [`v8.startupSnapshot.setDeserializeMainFunction()`]: v8.md#v8startupsnapshotsetdeserializemainfunctioncallback-data | |
Collapse file Copy file name to clipboardExpand all lines: lib/buffer.js +7Lines changed: 7 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -62,6 +62,7 @@ const { | 62 | 62 | copy: _copy, | 63 | 63 | fill: bindingFill, | 64 | 64 | isAscii: bindingIsAscii, | | 65 | + isByteString: bindingIsByteString, | 65 | 66 | isUtf8: bindingIsUtf8, | 66 | 67 | stringLengthUtf8: bindingStringLengthUtf8, | 67 | 68 | indexOfBuffer, | @@ -1498,6 +1499,11 @@ function isAscii(input) { | 1498 | 1499 | throw new ERR_INVALID_ARG_TYPE('input', ['ArrayBuffer', 'Buffer', 'TypedArray'], input); | 1499 | 1500 | } | 1500 | 1501 |
| | 1502 | +function isByteString(input) { | | 1503 | + validateString(input, 'input'); | | 1504 | + return bindingIsByteString(input); | | 1505 | +} | | 1506 | + | 1501 | 1507 | function stringLength(input, encoding = 'utf8') { | 1502 | 1508 | if (!isTypedArray(input) && !isAnyArrayBuffer(input)) { | 1503 | 1509 | throw new ERR_INVALID_ARG_TYPE('input', ['ArrayBuffer', 'Buffer', 'TypedArray'], input); | @@ -1529,6 +1535,7 @@ module.exports = { | 1529 | 1535 | transcode, | 1530 | 1536 | isUtf8, | 1531 | 1537 | isAscii, | | 1538 | + isByteString, | 1532 | 1539 |
| 1533 | 1540 | // Legacy | 1534 | 1541 | kMaxLength, | |
Collapse file Copy file name to clipboardExpand all lines: src/node_buffer.cc +27Lines changed: 27 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -1414,6 +1414,29 @@ static bool FastIsAscii(Local<Value> receiver, | 1414 | 1414 |
| 1415 | 1415 | static CFunction fast_is_ascii(CFunction::Make(FastIsAscii)); | 1416 | 1416 |
| | 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 | + | 1417 | 1440 | // Number of UTF-16 code units produced by decoding [p, end) as UTF-8 with | 1418 | 1441 | // WHATWG "maximal subpart" U+FFFD replacement, matching the fallback that | 1419 | 1442 | // StringBytes::Encode takes for invalid input (v8::String::NewFromUtf8). | @@ -1928,6 +1951,8 @@ void Initialize(Local<Object> target, | 1928 | 1951 | SetFastMethodNoSideEffect(context, target, "isUtf8", IsUtf8, &fast_is_utf8); | 1929 | 1952 | SetFastMethodNoSideEffect( | 1930 | 1953 | context, target, "isAscii", IsAscii, &fast_is_ascii); | | 1954 | + SetFastMethodNoSideEffect( | | 1955 | + context, target, "isByteString", IsByteString, &fast_is_byte_string); | 1931 | 1956 | SetFastMethodNoSideEffect(context, | 1932 | 1957 | target, | 1933 | 1958 | "stringLengthUtf8", | @@ -2008,6 +2033,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) { | 2008 | 2033 | registry->Register(fast_is_utf8); | 2009 | 2034 | registry->Register(IsAscii); | 2010 | 2035 | registry->Register(fast_is_ascii); | | 2036 | + registry->Register(IsByteString); | | 2037 | + registry->Register(fast_is_byte_string); | 2011 | 2038 | registry->Register(StringLengthUtf8); | 2012 | 2039 | registry->Register(fast_string_length_utf8); | 2013 | 2040 |
| |
Collapse file Copy file name to clipboard +85Lines changed: 85 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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 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 number | Diff line number | Diff line change |
|---|
| 3 | 3 |
| 4 | 4 | const common = require('../common'); | 5 | 5 | const assert = require('assert'); | 6 | | -const { Buffer, isAscii, isUtf8 } = require('buffer'); | | 6 | +const { Buffer, isAscii, isByteString, isUtf8 } = require('buffer'); | 7 | 7 |
| 8 | 8 | const ascii = Buffer.from('hello'); | 9 | 9 | const utf8 = Buffer.from('hello \xc4\x9f'); | | 10 | +const byteString = 'hello \u00e9'; | 10 | 11 |
| 11 | 12 | function testFastIsAscii() { | 12 | 13 | assert.strictEqual(isAscii(ascii), true); | @@ -16,6 +17,10 @@ function testFastIsUtf8() { | 16 | 17 | assert.strictEqual(isUtf8(utf8), true); | 17 | 18 | } | 18 | 19 |
| | 20 | +function testFastIsByteString() { | | 21 | + assert.strictEqual(isByteString(byteString), true); | | 22 | +} | | 23 | + | 19 | 24 | eval('%PrepareFunctionForOptimization(isAscii)'); | 20 | 25 | testFastIsAscii(); | 21 | 26 | eval('%OptimizeFunctionOnNextCall(isAscii)'); | @@ -26,9 +31,15 @@ testFastIsUtf8(); | 26 | 31 | eval('%OptimizeFunctionOnNextCall(isUtf8)'); | 27 | 32 | testFastIsUtf8(); | 28 | 33 |
| | 34 | +eval('%PrepareFunctionForOptimization(isByteString)'); | | 35 | +testFastIsByteString(); | | 36 | +eval('%OptimizeFunctionOnNextCall(isByteString)'); | | 37 | +testFastIsByteString(); | | 38 | + | 29 | 39 | if (common.isDebug) { | 30 | 40 | const { internalBinding } = require('internal/test/binding'); | 31 | 41 | const { getV8FastApiCallCount } = internalBinding('debug'); | 32 | 42 | assert.strictEqual(getV8FastApiCallCount('buffer.isAscii'), 1); | 33 | 43 | assert.strictEqual(getV8FastApiCallCount('buffer.isUtf8'), 1); | | 44 | + assert.strictEqual(getV8FastApiCallCount('buffer.isByteString'), 1); | 34 | 45 | } |
|