Skip to content

Commit 604ac4f

Browse files
anonrigaddaleax
andcommitted
util: add fast path for utf8 encoding
Co-authored-by: Anna Henningsen <[email protected]>
1 parent d55a7c3 commit 604ac4f

File tree

3 files changed

+81
-6
lines changed

3 files changed

+81
-6
lines changed

lib/internal/encoding.js

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
// https://encoding.spec.whatwg.org
55

66
const {
7+
Boolean,
78
ObjectCreate,
89
ObjectDefineProperties,
910
ObjectGetOwnPropertyDescriptors,
@@ -29,6 +30,8 @@ const kFlags = Symbol('flags');
2930
const kEncoding = Symbol('encoding');
3031
const kDecoder = Symbol('decoder');
3132
const kEncoder = Symbol('encoder');
33+
const kUTF8FastPath = Symbol('kUTF8FastPath');
34+
const kIgnoreBOM = Symbol('kIgnoreBOM');
3235

3336
const {
3437
getConstructorOf,
@@ -50,7 +53,8 @@ const {
5053

5154
const {
5255
encodeInto,
53-
encodeUtf8String
56+
encodeUtf8String,
57+
decodeUTF8,
5458
} = internalBinding('buffer');
5559

5660
let Buffer;
@@ -398,19 +402,40 @@ function makeTextDecoderICU() {
398402
flags |= options.ignoreBOM ? CONVERTER_FLAGS_IGNORE_BOM : 0;
399403
}
400404

401-
const handle = getConverter(enc, flags);
402-
if (handle === undefined)
403-
throw new ERR_ENCODING_NOT_SUPPORTED(encoding);
405+
// Only support fast path for UTF-8 without FATAL flag
406+
const fastPathAvailable = enc === 'utf-8' && !(options?.fatal);
404407

405408
this[kDecoder] = true;
406-
this[kHandle] = handle;
407409
this[kFlags] = flags;
408410
this[kEncoding] = enc;
411+
this[kIgnoreBOM] = Boolean(options?.ignoreBOM);
412+
this[kUTF8FastPath] = fastPathAvailable;
413+
this[kHandle] = undefined;
414+
415+
if (!fastPathAvailable) {
416+
this.#prepareConverter();
417+
}
409418
}
410419

420+
#prepareConverter() {
421+
if (this[kHandle] !== undefined) return;
422+
const handle = getConverter(this[kEncoding], this[kFlags]);
423+
if (handle === undefined)
424+
throw new ERR_ENCODING_NOT_SUPPORTED(this[kEncoding]);
425+
this[kHandle] = handle;
426+
}
411427

412428
decode(input = empty, options = kEmptyObject) {
413429
validateDecoder(this);
430+
431+
this[kUTF8FastPath] &&= !(options?.stream);
432+
433+
if (this[kUTF8FastPath]) {
434+
return decodeUTF8(input, this[kIgnoreBOM]);
435+
}
436+
437+
this.#prepareConverter();
438+
414439
if (!isAnyArrayBuffer(input) && !isArrayBufferView(input)) {
415440
throw new ERR_INVALID_ARG_TYPE('input',
416441
['ArrayBuffer', 'ArrayBufferView'],

src/node_buffer.cc

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
#include "node_blob.h"
2525
#include "node_errors.h"
2626
#include "node_external_reference.h"
27+
#include "node_i18n.h"
2728
#include "node_internals.h"
2829

2930
#include "env-inl.h"
@@ -565,6 +566,53 @@ void StringSlice(const FunctionCallbackInfo<Value>& args) {
565566
args.GetReturnValue().Set(ret);
566567
}
567568

569+
// Convert the input into an encoded string
570+
void DecodeUTF8(const FunctionCallbackInfo<Value>& args) {
571+
Environment* env = Environment::GetCurrent(args); // list, flags
572+
573+
if (!(args[0]->IsArrayBuffer() || args[0]->IsSharedArrayBuffer() ||
574+
args[0]->IsArrayBufferView())) {
575+
return node::THROW_ERR_INVALID_ARG_TYPE(
576+
env->isolate(),
577+
"The \"list\" argument must be an instance of SharedArrayBuffer, "
578+
"ArrayBuffer or ArrayBufferView.");
579+
}
580+
581+
ArrayBufferViewContents<char> buffer(args[0]);
582+
583+
CHECK(args[1]->IsBoolean());
584+
bool ignore_bom = args[1]->BooleanValue(env->isolate());
585+
586+
const char* data = buffer.data();
587+
size_t beginning = 0;
588+
size_t length = buffer.length();
589+
590+
if (length == 0) return args.GetReturnValue().SetEmptyString();
591+
592+
if (!ignore_bom) {
593+
char bom[] = "\xEF\xBB\xBF";
594+
595+
if (strncmp(data, bom, 3) == 0) {
596+
beginning += 3;
597+
length -= 3;
598+
}
599+
}
600+
601+
auto output = data + beginning;
602+
603+
Local<Value> error;
604+
MaybeLocal<Value> maybe_ret =
605+
StringBytes::Encode(env->isolate(), output, length, UTF8, &error);
606+
Local<Value> ret;
607+
608+
if (!maybe_ret.ToLocal(&ret)) {
609+
CHECK(!error.IsEmpty());
610+
env->isolate()->ThrowException(error);
611+
return;
612+
}
613+
614+
args.GetReturnValue().Set(ret);
615+
}
568616

569617
// bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
570618
void Copy(const FunctionCallbackInfo<Value> &args) {
@@ -1282,6 +1330,7 @@ void Initialize(Local<Object> target,
12821330

12831331
SetMethod(context, target, "setBufferPrototype", SetBufferPrototype);
12841332
SetMethodNoSideEffect(context, target, "createFromString", CreateFromString);
1333+
SetMethodNoSideEffect(context, target, "decodeUTF8", DecodeUTF8);
12851334

12861335
SetMethodNoSideEffect(context, target, "byteLengthUtf8", ByteLengthUtf8);
12871336
SetMethod(context, target, "copy", Copy);
@@ -1339,6 +1388,7 @@ void Initialize(Local<Object> target,
13391388
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
13401389
registry->Register(SetBufferPrototype);
13411390
registry->Register(CreateFromString);
1391+
registry->Register(DecodeUTF8);
13421392

13431393
registry->Register(ByteLengthUtf8);
13441394
registry->Register(Copy);

test/parallel/test-whatwg-encoding-custom-textdecoder.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ if (common.hasIntl) {
113113
' fatal: false,\n' +
114114
' ignoreBOM: true,\n' +
115115
' [Symbol(flags)]: 4,\n' +
116-
' [Symbol(handle)]: Converter {}\n' +
116+
' [Symbol(handle)]: undefined\n' +
117117
'}'
118118
);
119119
} else {

0 commit comments

Comments
 (0)