Skip to content

Commit 91d61fb

Browse files
AtticusYangAtticusYang
AtticusYang
authored andcommitted
src: add encodeInto to TextEncoder
Add function encodeInto to TextEncoder, fix bug MessageChannel is not defined in encodeInto.any.js. Fixes: nodejs#28851 Refs: nodejs#26904
1 parent 43e5478 commit 91d61fb

File tree

11 files changed

+167
-34
lines changed

11 files changed

+167
-34
lines changed

doc/api/util.md

+19
Original file line numberDiff line numberDiff line change
@@ -1073,6 +1073,25 @@ The `TextEncoder` class is also available on the global object.
10731073
UTF-8 encodes the `input` string and returns a `Uint8Array` containing the
10741074
encoded bytes.
10751075

1076+
```js
1077+
const encoder = new TextEncoder();
1078+
const src = 'this is some data';
1079+
const dest = new Uint8Array(10);
1080+
const ret = encoder.encodeInto(src, dest);
1081+
```
1082+
1083+
### textEncoder.encodeInto(src, dest)
1084+
1085+
1086+
* `src` {string} The text to encode.
1087+
* `dest` {Uint8Array} the array to hold the encode result.
1088+
* Returns: {Object}
1089+
* `read` {number} The read Unicode code units of src.
1090+
* `written` {number} The written UTF-8 bytes of dest.
1091+
1092+
UTF-8 encodes the `src` string to `dest` Unit8Array and returns an object
1093+
containing the read Unicode code units and written UTF-8 bytes.
1094+
10761095
### textEncoder.encoding
10771096

10781097
* {string}

lib/internal/encoding.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,14 @@ const {
2525

2626
const {
2727
isArrayBuffer,
28-
isArrayBufferView
28+
isArrayBufferView,
29+
isUint8Array
2930
} = require('internal/util/types');
3031

32+
const { validateString } = require('internal/validators');
33+
3134
const {
35+
encodeInto,
3236
encodeUtf8String
3337
} = internalBinding('buffer');
3438

@@ -319,6 +323,14 @@ class TextEncoder {
319323
return encodeUtf8String(`${input}`);
320324
}
321325

326+
encodeInto(src, dest) {
327+
validateEncoder(this);
328+
validateString(src, 'src');
329+
if (!dest || !isUint8Array(dest))
330+
throw new ERR_INVALID_ARG_TYPE('dest', 'Uint8Array', dest);
331+
return encodeInto(src, dest);
332+
}
333+
322334
[inspect](depth, opts) {
323335
validateEncoder(this);
324336
if (typeof depth === 'number' && depth < 0)
@@ -336,6 +348,7 @@ class TextEncoder {
336348
Object.defineProperties(
337349
TextEncoder.prototype, {
338350
'encode': { enumerable: true },
351+
'encodeInto': { enumerable: true },
339352
'encoding': { enumerable: true },
340353
[Symbol.toStringTag]: {
341354
configurable: true,

src/env.h

+2
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,9 @@ constexpr size_t kFsStatsBufferLength =
214214
V(dns_txt_string, "TXT") \
215215
V(duration_string, "duration") \
216216
V(emit_warning_string, "emitWarning") \
217+
V(encoding_read_string, "read") \
217218
V(encoding_string, "encoding") \
219+
V(encoding_written_string, "written") \
218220
V(entries_string, "entries") \
219221
V(entry_type_string, "entryType") \
220222
V(env_pairs_string, "envPairs") \

src/node_buffer.cc

+115
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
#include "v8-profiler.h"
3232
#include "v8.h"
3333

34+
#include <unicode/unistr.h>
35+
3436
#include <cstring>
3537
#include <climits>
3638

@@ -56,6 +58,7 @@
5658
namespace node {
5759
namespace Buffer {
5860

61+
using v8::Array;
5962
using v8::ArrayBuffer;
6063
using v8::ArrayBufferCreationMode;
6164
using v8::ArrayBufferView;
@@ -1051,6 +1054,117 @@ static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
10511054
}
10521055

10531056

1057+
static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1058+
Environment* env = Environment::GetCurrent(args);
1059+
Isolate* isolate = env->isolate();
1060+
Local<Context> context = env->context();
1061+
CHECK_GE(args.Length(), 2);
1062+
CHECK(args[0]->IsString());
1063+
CHECK(args[1]->IsUint8Array());
1064+
1065+
size_t read = 0;
1066+
size_t written = 0;
1067+
1068+
Utf8Value src(isolate, args[0]);
1069+
const char* p = *src;
1070+
1071+
Local<Uint8Array> dest = args[1].As<Uint8Array>();
1072+
Local<ArrayBuffer> buf = dest->Buffer();
1073+
char* write_result =
1074+
static_cast<char*>(buf->GetContents().Data()) + dest->ByteOffset();
1075+
size_t dest_length = dest->ByteLength();
1076+
1077+
for (size_t i = 0; i < src.length(); ) {
1078+
uint32_t code = 0;
1079+
1080+
if ((p[i] & 0x80) == 0) {
1081+
code = p[i];
1082+
i += 1;
1083+
} else if ((p[i] & 0xE0) == 0xC0 && (i + 1 < src.length())) {
1084+
code = (p[i] & 0x1F) << 6;
1085+
code |= (p[i+1] & 0x3F);
1086+
i += 2;
1087+
} else if ((p[i] & 0xF0) == 0xE0 && (i + 2 < src.length())) {
1088+
code = (p[i] & 0xF) << 12;
1089+
code |= (p[i+1] & 0x3F) << 6;
1090+
code |= (p[i+2] & 0x3F);
1091+
i += 3;
1092+
} else if ((p[i] & 0xF8) == 0xF0 && (i + 3 < src.length())) {
1093+
code = (p[i] & 0x7) << 18;
1094+
code |= (p[i+1] & 0x3F) << 12;
1095+
code |= (p[i+2] & 0x3F) << 6;
1096+
code |= (p[i+3] & 0x3F);
1097+
i += 4;
1098+
} else if ((p[i] & 0xFC) == 0xF8 && (i + 4 < src.length())) {
1099+
code = (p[i] & 0x3) << 24;
1100+
code |= (p[i+1] & 0x3F) << 18;
1101+
code |= (p[i+2] & 0x3F) << 12;
1102+
code |= (p[i+3] & 0x3F) << 6;
1103+
code |= (p[i+4] & 0x3F);
1104+
i += 5;
1105+
} else if ((p[i] & 0xFE) == 0xFC && (i + 5 < src.length())) {
1106+
code = (p[i] & 0x1) << 30;
1107+
code |= (p[i+1] & 0x3F) << 24;
1108+
code |= (p[i+2] & 0x3F) << 18;
1109+
code |= (p[i+3] & 0x3F) << 12;
1110+
code |= (p[i+4] & 0x3F) << 6;
1111+
code |= (p[i+5] & 0x3F);
1112+
i += 6;
1113+
}
1114+
1115+
if (code <= 0x7F) {
1116+
if (dest_length < 1) break;
1117+
1118+
*write_result++ = static_cast<char>(code);
1119+
read += 1;
1120+
written += 1;
1121+
dest_length -= 1;
1122+
} else if (code <= 0x7FF) {
1123+
if (dest_length < 2) break;
1124+
1125+
*write_result++ = (0xC0 | (code >> 6));
1126+
*write_result++ = (0x80 | (code & 0x3F));
1127+
read += 1;
1128+
written += 2;
1129+
dest_length -= 2;
1130+
} else if (code <= 0xFFFF) {
1131+
if (dest_length < 3) break;
1132+
1133+
*write_result++ = (0xE0 | (code >> 12));
1134+
*write_result++ = (0x80 | ((code >> 6) & 0x3F));
1135+
*write_result++ = (0x80 | (code & 0x3F));
1136+
read += 1;
1137+
written += 3;
1138+
dest_length -= 3;
1139+
} else if (code <= 0x1FFFFF) {
1140+
if (dest_length < 4) break;
1141+
1142+
*write_result++ = (0xF0 | (code >> 18));
1143+
*write_result++ = (0x80 | ((code >> 12) & 0x3F));
1144+
*write_result++ = (0x80 | ((code >> 6) & 0x3F));
1145+
*write_result++ = (0x80 | (code & 0x3F));
1146+
read += 2;
1147+
written += 4;
1148+
dest_length -= 4;
1149+
} else {
1150+
// invalid unicode
1151+
}
1152+
}
1153+
1154+
Local<Object> result = Object::New(isolate);
1155+
if (result->Set(context,
1156+
env->encoding_read_string(),
1157+
Integer::New(isolate, read)).IsNothing() ||
1158+
result->Set(context,
1159+
env->encoding_written_string(),
1160+
Integer::New(isolate, written)).IsNothing()) {
1161+
return;
1162+
}
1163+
1164+
args.GetReturnValue().Set(result);
1165+
}
1166+
1167+
10541168
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
10551169
Environment* env = Environment::GetCurrent(args);
10561170

@@ -1082,6 +1196,7 @@ void Initialize(Local<Object> target,
10821196
env->SetMethod(target, "swap32", Swap32);
10831197
env->SetMethod(target, "swap64", Swap64);
10841198

1199+
env->SetMethod(target, "encodeInto", EncodeInto);
10851200
env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
10861201

10871202
target->Set(env->context(),

test/fixtures/wpt/LICENSE.md

+6-28
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,11 @@
1-
# Dual-License for W3C Test Suites
1+
# The 3-Clause BSD License
22

3-
All documents in this Repository are licensed by contributors to be distributed under both the [W3C Test Suite License](#w3c-test-suite-license) and the [W3C 3-clause BSD License](#w3c-3-clause-bsd-license), reproduced below. The choice of license is up to the licensee. For more information, see [Licenses for W3C Test Suites](https://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html)
4-
5-
# W3C Test Suite License
6-
7-
This document, Test Suites and other documents that link to this statement are provided by the copyright holders under the following license: By using and/or copying this document, or the W3C document from which this statement is linked, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions:
8-
9-
Permission to copy, and distribute the contents of this document, or the W3C document from which this statement is linked, in any medium for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the document, or portions thereof, that you use:
10-
11-
* A link or URL to the original W3C document.
12-
* The pre-existing copyright notice of the original author, or if it doesn't exist, a notice (hypertext is preferred, but a textual representation is permitted) of the form: "Copyright © [$date-of-document] World Wide Web Consortium, (MIT, ERCIM, Keio, Beihang) and others. All Rights Reserved. http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html"
13-
* If it exists, the STATUS of the W3C document.
14-
15-
When space permits, inclusion of the full text of this NOTICE should be provided. We request that authorship attribution be provided in any software, documents, or other items or products that you create pursuant to the implementation of the contents of this document, or any portion thereof.
16-
17-
No right to create modifications or derivatives of W3C documents is granted pursuant to this license. However, if additional requirements (documented in the Copyright FAQ) are satisfied, the right to create modifications or derivatives is sometimes granted by the W3C to individuals complying with those requirements.
18-
19-
If a Test Suite distinguishes the test harness (or, framework for navigation) and the actual tests, permission is given to remove or alter the harness or navigation if the Test Suite in question allows to do so. The tests themselves shall NOT be changed in any way.
20-
21-
The name and trademarks of W3C and other copyright holders may NOT be used in advertising or publicity pertaining to this document or other documents that link to this statement without specific, written prior permission. Title to copyright in this document will at all times remain with copyright holders. Permission is given to use the trademarked string "W3C" within claims of performance concerning W3C Specifications or features described therein, and there only, if the test suite so authorizes.
22-
23-
THIS WORK IS PROVIDED BY W3C, MIT, ERCIM, KEIO, BEIHANG, THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL W3C, MIT, ERCIM, KEIO, BEIHANG, THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24-
25-
# W3C 3-clause BSD License
3+
Copyright 2019 web-platform-tests contributors
264

275
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
286

29-
* Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer.
30-
* Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
31-
* Neither the name of the W3C nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission.
7+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
8+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9+
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
3210

33-
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

test/fixtures/wpt/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ See [test/wpt](../../wpt/README.md) for information on how these tests are run.
1111
Last update:
1212

1313
- console: https://github.com/web-platform-tests/wpt/tree/9786a4b131/console
14-
- encoding: https://github.com/web-platform-tests/wpt/tree/7287608f90/encoding
14+
- encoding: https://github.com/web-platform-tests/wpt/tree/5059d2c777/encoding
1515
- url: https://github.com/web-platform-tests/wpt/tree/418f7fabeb/url
1616
- resources: https://github.com/web-platform-tests/wpt/tree/e1fddfbf80/resources
1717
- interfaces: https://github.com/web-platform-tests/wpt/tree/712c9f275e/interfaces

test/fixtures/wpt/encoding/encodeInto.any.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@
126126
Float64Array].forEach(view => {
127127
test(() => {
128128
assert_throws(new TypeError(), () => new TextEncoder().encodeInto("", new view(new ArrayBuffer(0))));
129-
}, "Invalid encodeInto() destination: " + view);
129+
}, "Invalid encodeInto() destination: " + view.name);
130130
});
131131

132132
test(() => {

test/fixtures/wpt/versions.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"path": "console"
55
},
66
"encoding": {
7-
"commit": "7287608f90f6b9530635d10086fd2ab386faab38",
7+
"commit": "5059d2c77703d67d2f76931b44e6d2437526b6e9",
88
"path": "encoding"
99
},
1010
"url": {

test/wpt/status/encoding.json

-1
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,5 @@
5252
"fail": "No implementation of TextDecoderStream and TextEncoderStream"
5353
},
5454
"encodeInto.any.js": {
55-
"fail": "TextEncoder.prototype.encodeInto not implemented"
5655
}
5756
}

test/wpt/status/url.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@
1212
"idlharness.any.js": {
1313
"fail": "getter/setter names are wrong, etc."
1414
}
15-
}
15+
}

test/wpt/test-encoding.js

+7
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,17 @@
33
// Flags: --expose-internals
44

55
require('../common');
6+
const { MessageChannel } = require('worker_threads');
67
const { WPTRunner } = require('../common/wpt');
78
const runner = new WPTRunner('encoding');
89

910
// Copy global descriptors from the global object
1011
runner.copyGlobalsFromObject(global, ['TextDecoder', 'TextEncoder']);
1112

13+
runner.defineGlobal('MessageChannel', {
14+
get() {
15+
return MessageChannel;
16+
}
17+
});
18+
1219
runner.runJsTests();

0 commit comments

Comments
 (0)