Skip to content

Commit c47e2ef

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

File tree

1 file changed

+20
-20
lines changed

1 file changed

+20
-20
lines changed

lib/internal/encoding.js

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,6 @@ const {
6161

6262
const { Buffer } = require('buffer');
6363

64-
function validateEncoder(obj) {
65-
if (obj == null || obj[kEncoder] !== true)
66-
throw new ERR_INVALID_THIS('TextEncoder');
67-
}
68-
6964
function validateDecoder(obj) {
7065
if (obj == null || obj[kDecoder] !== true)
7166
throw new ERR_INVALID_THIS('TextDecoder');
@@ -338,45 +333,50 @@ function getEncodingFromLabel(label) {
338333
return encodings.get(trimAsciiWhitespace(label.toLowerCase()));
339334
}
340335

336+
let lazyInspect;
337+
341338
class TextEncoder {
342-
constructor() {
343-
this[kEncoder] = true;
339+
#encoding = 'utf-8';
340+
341+
#encode(input) {
342+
return encodeUtf8String(`${input}`);
343+
}
344+
345+
#encodeInto(input, dest) {
346+
encodeInto(src, dest);
347+
// We need to read from the binding here since the buffer gets refreshed
348+
// from the snapshot.
349+
const { 0: read, 1: written } = encodeIntoResults;
350+
return { read, written };
344351
}
345352

346353
get encoding() {
347-
validateEncoder(this);
348-
return 'utf-8';
354+
return this.#encoding;
349355
}
350356

351357
encode(input = '') {
352-
validateEncoder(this);
353-
return encodeUtf8String(`${input}`);
358+
return this.#encode(input);
354359
}
355360

356361
encodeInto(src, dest) {
357-
validateEncoder(this);
358362
validateString(src, 'src');
359363
if (!dest || !isUint8Array(dest))
360364
throw new ERR_INVALID_ARG_TYPE('dest', 'Uint8Array', dest);
361365

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 };
366+
return this.#encodeInto(src, dest);
367367
}
368368

369369
[inspect](depth, opts) {
370-
validateEncoder(this);
371370
if (typeof depth === 'number' && depth < 0)
372371
return this;
373372
const ctor = getConstructorOf(this);
374373
const obj = { __proto__: {
375374
constructor: ctor === null ? TextEncoder : ctor,
376375
} };
377-
obj.encoding = this.encoding;
376+
obj.encoding = this.#encoding;
378377
// Lazy to avoid circular dependency
379-
return require('internal/util/inspect').inspect(obj, opts);
378+
lazyInspect ??= require('internal/util/inspect').inspect;
379+
return lazyInspect(obj, opts);
380380
}
381381
}
382382

0 commit comments

Comments
 (0)