v8/test/mjsunit/wasm/gc-experimental-string-conversions.js
Tobias Tebbi b16d2a4e2f [wasm] add experimental string/Wasm GC array conversion fast-path
This CL adds two experimental JS builtins to convert between
i16 Wasm GC and JS strings. This is a non-standard experimental
feature only available with the flag --wasm-gc-js-interop.

WebAssembly.experimentalConvertArrayToString(array, start, count)
Convert the `count`-many WTF-16 code units starting at index `start`
into a JS string. Throws a TypeError if `array` is not an i16 array,
or if `start` and `count` are not numbers or not in range.

WebAssembly.experimentalConvertStringToArray(string, sampleArray)
Convert `string` to an i16 array. The `sampleArray` parameter needs
to be an arbitrary i16 array, which is only used to extract the rtt.
Throws a TypeError if `string` is not a string or `sampleArray` is not
an i16 array.

Change-Id: I7ac2f6bd89b8f638427f61da1bb01ccba90d735b
Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/3642301
Commit-Queue: Tobias Tebbi <tebbi@chromium.org>
Reviewed-by: Jakob Kummerow <jkummerow@chromium.org>
Cr-Commit-Position: refs/heads/main@{#80505}
2022-05-12 20:12:53 +00:00

48 lines
1.5 KiB
JavaScript

// Copyright 2022 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --experimental-wasm-gc --wasm-gc-js-interop
d8.file.execute('test/mjsunit/wasm/wasm-module-builder.js');
var builder = new WasmModuleBuilder();
let i16Array = builder.addArray(kWasmI16, true);
builder.addFunction('getHelloArray', makeSig([], [kWasmAnyRef]))
.addBody([
...wasmI32Const(72), ...wasmI32Const(69), ...wasmI32Const(76),
...wasmI32Const(76), ...wasmI32Const(79), kGCPrefix, kExprArrayInitStatic,
i16Array, 5
])
.exportFunc();
builder.addFunction('getChar', makeSig([kWasmAnyRef, kWasmI32], [kWasmI32]))
.addBody([
kExprLocalGet, 0, kGCPrefix, kExprRefAsData, kGCPrefix,
kExprRefCastStatic, i16Array, kExprLocalGet, 1, kGCPrefix, kExprArrayGetS,
i16Array
])
.exportFunc();
const instance = builder.instantiate();
const getHelloArray = instance.exports.getHelloArray;
const getChar = instance.exports.getChar;
assertEquals(
WebAssembly.experimentalConvertArrayToString(getHelloArray(), 0, 5),
'HELLO');
assertEquals(
WebAssembly.experimentalConvertArrayToString(getHelloArray(), 1, 4),
'ELLO');
assertEquals(
WebAssembly.experimentalConvertArrayToString(getHelloArray(), 0, 3), 'HEL');
const string = 'foobar'
const array =
WebAssembly.experimentalConvertStringToArray('foobar', getHelloArray());
for (let i = 0; i < string.length; ++i) {
assertEquals(getChar(array, i), string.charCodeAt(i));
}