Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

buffer: add isAscii method #46046

Merged
merged 1 commit into from
Jan 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions doc/api/buffer.md
Original file line number Diff line number Diff line change
Expand Up @@ -5130,6 +5130,20 @@ For code running using Node.js APIs, converting between base64-encoded strings
and binary data should be performed using `Buffer.from(str, 'base64')` and
`buf.toString('base64')`.**

### `buffer.isAscii(input)`

<!-- YAML
added: REPLACEME
-->

* input {Buffer | ArrayBuffer | TypedArray} The input to validate.
* Returns: {boolean}

This function returns `true` if `input` contains only valid ASCII-encoded data,
including the case in which `input` is empty.

Throws if the `input` is a detached array buffer.

### `buffer.isUtf8(input)`

<!-- YAML
Expand Down
10 changes: 10 additions & 0 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ const {
compareOffset,
createFromString,
fill: bindingFill,
isAscii: bindingIsAscii,
isUtf8: bindingIsUtf8,
indexOfBuffer,
indexOfNumber,
Expand Down Expand Up @@ -1324,11 +1325,20 @@ function isUtf8(input) {
throw new ERR_INVALID_ARG_TYPE('input', ['TypedArray', 'Buffer'], input);
}

function isAscii(input) {
if (isTypedArray(input) || isAnyArrayBuffer(input)) {
return bindingIsAscii(input);
}

throw new ERR_INVALID_ARG_TYPE('input', ['ArrayBuffer', 'Buffer', 'TypedArray'], input);
}

module.exports = {
Buffer,
SlowBuffer,
transcode,
isUtf8,
isAscii,

// Legacy
kMaxLength,
Expand Down
17 changes: 17 additions & 0 deletions src/node_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1238,6 +1238,21 @@ static void IsUtf8(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(simdutf::validate_utf8(abv.data(), abv.length()));
}

static void IsAscii(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
CHECK_EQ(args.Length(), 1);
CHECK(args[0]->IsTypedArray() || args[0]->IsArrayBuffer() ||
args[0]->IsSharedArrayBuffer());
ArrayBufferViewContents<char> abv(args[0]);

if (abv.WasDetached()) {
return node::THROW_ERR_INVALID_STATE(
env, "Cannot validate on a detached buffer");
}

args.GetReturnValue().Set(simdutf::validate_ascii(abv.data(), abv.length()));
}

void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);

Expand Down Expand Up @@ -1373,6 +1388,7 @@ void Initialize(Local<Object> target,
SetMethodNoSideEffect(context, target, "encodeUtf8String", EncodeUtf8String);

SetMethodNoSideEffect(context, target, "isUtf8", IsUtf8);
SetMethodNoSideEffect(context, target, "isAscii", IsAscii);
anonrig marked this conversation as resolved.
Show resolved Hide resolved

target
->Set(context,
Expand Down Expand Up @@ -1430,6 +1446,7 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(EncodeUtf8String);

registry->Register(IsUtf8);
registry->Register(IsAscii);

registry->Register(StringSlice<ASCII>);
registry->Register(StringSlice<BASE64>);
Expand Down
42 changes: 42 additions & 0 deletions test/parallel/test-buffer-isascii.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'use strict';

require('../common');
const assert = require('assert');
const { isAscii, Buffer } = require('buffer');
const { TextEncoder } = require('util');

const encoder = new TextEncoder();

assert.strictEqual(isAscii(encoder.encode('hello')), true);
assert.strictEqual(isAscii(encoder.encode('ğ')), false);
assert.strictEqual(isAscii(Buffer.from([])), true);

[
undefined,
'', 'hello',
false, true,
0, 1,
0n, 1n,
Symbol(),
() => {},
{}, [], null,
].forEach((input) => {
assert.throws(
() => { isAscii(input); },
{
code: 'ERR_INVALID_ARG_TYPE',
},
);
});

{
// Test with detached array buffers
const arrayBuffer = new ArrayBuffer(1024);
structuredClone(arrayBuffer, { transfer: [arrayBuffer] });
assert.throws(
() => { isAscii(arrayBuffer); },
{
code: 'ERR_INVALID_STATE'
}
);
}