Skip to content

Commit f233c2c

Browse files
committed
util: reduce TextEncoder.encodeInto function size
1 parent 94cbb77 commit f233c2c

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

lib/internal/encoding.js

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -338,45 +338,54 @@ function getEncodingFromLabel(label) {
338338
return encodings.get(trimAsciiWhitespace(label.toLowerCase()));
339339
}
340340

341+
let lazyInspect;
342+
341343
class TextEncoder {
344+
#encoding = 'utf-8';
345+
346+
#encode(input) {
347+
return encodeUtf8String(`${input}`);
348+
}
349+
350+
#encodeInto(input, dest) {
351+
encodeInto(src, dest);
352+
// We need to read from the binding here since the buffer gets refreshed
353+
// from the snapshot.
354+
const { 0: read, 1: written } = encodeIntoResults;
355+
return { read, written };
356+
}
357+
342358
constructor() {
343359
this[kEncoder] = true;
344360
}
345361

346362
get encoding() {
347-
validateEncoder(this);
348-
return 'utf-8';
363+
return this.#encoding;
349364
}
350365

351366
encode(input = '') {
352-
validateEncoder(this);
353-
return encodeUtf8String(`${input}`);
367+
return this.#encode(input);
354368
}
355369

356370
encodeInto(src, dest) {
357-
validateEncoder(this);
358371
validateString(src, 'src');
359372
if (!dest || !isUint8Array(dest))
360373
throw new ERR_INVALID_ARG_TYPE('dest', 'Uint8Array', dest);
361374

362-
encodeInto(src, dest);
363-
// We need to read from the binding here since the buffer gets refreshed
364-
// from the snapshot.
365-
const { 0: read, 1: written } = encodeIntoResults;
366-
return { read, written };
375+
return this.#encodeInto(src, dest);
367376
}
368377

369378
[inspect](depth, opts) {
370-
validateEncoder(this);
371379
if (typeof depth === 'number' && depth < 0)
372380
return this;
373381
const ctor = getConstructorOf(this);
374382
const obj = { __proto__: {
375383
constructor: ctor === null ? TextEncoder : ctor,
376384
} };
377-
obj.encoding = this.encoding;
385+
obj.encoding = this.#encoding;
378386
// Lazy to avoid circular dependency
379-
return require('internal/util/inspect').inspect(obj, opts);
387+
lazyInspect ??= require('internal/util/inspect').inspect;
388+
return lazyInspect(obj, opts);
380389
}
381390
}
382391

0 commit comments

Comments
 (0)