Skip to content

Commit 772a5e0

Browse files
addaleaxBridgeAR
authored andcommitted
util: add encodeInto to TextEncoder
Add function encodeInto to TextEncoder, and add MessageChannel to the encodeInto.any.js test. Fixes: #28851 Fixes: #26904 Refs: #28862 Co-authored-by: AtticusYang <[email protected]> PR-URL: #29524 Reviewed-By: David Carlier <[email protected]> Reviewed-By: Joyee Cheung <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent dd5d944 commit 772a5e0

File tree

10 files changed

+87
-36
lines changed

10 files changed

+87
-36
lines changed

doc/api/util.md

+18
Original file line numberDiff line numberDiff line change
@@ -1057,6 +1057,24 @@ The `TextEncoder` class is also available on the global object.
10571057
UTF-8 encodes the `input` string and returns a `Uint8Array` containing the
10581058
encoded bytes.
10591059

1060+
### textEncoder.encodeInto(src, dest)
1061+
1062+
* `src` {string} The text to encode.
1063+
* `dest` {Uint8Array} The array to hold the encode result.
1064+
* Returns: {Object}
1065+
* `read` {number} The read Unicode code units of src.
1066+
* `written` {number} The written UTF-8 bytes of dest.
1067+
1068+
UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object
1069+
containing the read Unicode code units and written UTF-8 bytes.
1070+
1071+
```js
1072+
const encoder = new TextEncoder();
1073+
const src = 'this is some data';
1074+
const dest = new Uint8Array(10);
1075+
const { read, written } = encoder.encodeInto(src, dest);
1076+
```
1077+
10601078
### textEncoder.encoding
10611079

10621080
* {string}

lib/internal/encoding.js

+17-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

@@ -304,6 +308,8 @@ function getEncodingFromLabel(label) {
304308
return encodings.get(trimAsciiWhitespace(label.toLowerCase()));
305309
}
306310

311+
const encodeIntoResults = new Uint32Array(2);
312+
307313
class TextEncoder {
308314
constructor() {
309315
this[kEncoder] = true;
@@ -319,6 +325,15 @@ class TextEncoder {
319325
return encodeUtf8String(`${input}`);
320326
}
321327

328+
encodeInto(src, dest) {
329+
validateEncoder(this);
330+
validateString(src, 'src');
331+
if (!dest || !isUint8Array(dest))
332+
throw new ERR_INVALID_ARG_TYPE('dest', 'Uint8Array', dest);
333+
encodeInto(src, dest, encodeIntoResults);
334+
return { read: encodeIntoResults[0], written: encodeIntoResults[1] };
335+
}
336+
322337
[inspect](depth, opts) {
323338
validateEncoder(this);
324339
if (typeof depth === 'number' && depth < 0)
@@ -336,6 +351,7 @@ class TextEncoder {
336351
Object.defineProperties(
337352
TextEncoder.prototype, {
338353
'encode': { enumerable: true },
354+
'encodeInto': { enumerable: true },
339355
'encoding': { enumerable: true },
340356
[Symbol.toStringTag]: {
341357
configurable: true,

src/node_buffer.cc

+35
Original file line numberDiff line numberDiff line change
@@ -1047,6 +1047,40 @@ static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
10471047
}
10481048

10491049

1050+
static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1051+
Environment* env = Environment::GetCurrent(args);
1052+
Isolate* isolate = env->isolate();
1053+
CHECK_GE(args.Length(), 3);
1054+
CHECK(args[0]->IsString());
1055+
CHECK(args[1]->IsUint8Array());
1056+
CHECK(args[2]->IsUint32Array());
1057+
1058+
Local<String> source = args[0].As<String>();
1059+
1060+
Local<Uint8Array> dest = args[1].As<Uint8Array>();
1061+
Local<ArrayBuffer> buf = dest->Buffer();
1062+
char* write_result =
1063+
static_cast<char*>(buf->GetContents().Data()) + dest->ByteOffset();
1064+
size_t dest_length = dest->ByteLength();
1065+
1066+
// results = [ read, written ]
1067+
Local<Uint32Array> result_arr = args[2].As<Uint32Array>();
1068+
uint32_t* results = reinterpret_cast<uint32_t*>(
1069+
static_cast<char*>(result_arr->Buffer()->GetContents().Data()) +
1070+
result_arr->ByteOffset());
1071+
1072+
int nchars;
1073+
int written = source->WriteUtf8(
1074+
isolate,
1075+
write_result,
1076+
dest_length,
1077+
&nchars,
1078+
String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1079+
results[0] = nchars;
1080+
results[1] = written;
1081+
}
1082+
1083+
10501084
void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
10511085
Environment* env = Environment::GetCurrent(args);
10521086

@@ -1078,6 +1112,7 @@ void Initialize(Local<Object> target,
10781112
env->SetMethod(target, "swap32", Swap32);
10791113
env->SetMethod(target, "swap64", Swap64);
10801114

1115+
env->SetMethod(target, "encodeInto", EncodeInto);
10811116
env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
10821117

10831118
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

-3
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,5 @@
5050
},
5151
"streams/*.js": {
5252
"fail": "No implementation of TextDecoderStream and TextEncoderStream"
53-
},
54-
"encodeInto.any.js": {
55-
"fail": "TextEncoder.prototype.encodeInto not implemented"
5653
}
5754
}

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)