JavaScript 字符串内置函数
【JavaScript String Builtins】
在导入 WebAssembly 模块时,WebAssembly JS 字符串内置函数提案 会通过 ESM 集成自动启用。这允许 WebAssembly 模块直接使用来自 wasm:js-string 命名空间的高效编译时字符串内置功能。
【When importing WebAssembly modules, the
WebAssembly JS String Builtins Proposal is automatically enabled through the
ESM Integration. This allows WebAssembly modules to directly use efficient
compile-time string builtins from the wasm:js-string namespace.】
例如,下面的 Wasm 模块使用 wasm:js-string 的 length 内置函数导出一个字符串 getLength 函数:
【For example, the following Wasm module exports a string getLength function using
the wasm:js-string length builtin:】
(module
;; Compile-time import of the string length builtin.
(import "wasm:js-string" "length" (func $string_length (param externref) (result i32)))
;; Define getLength, taking a JS value parameter assumed to be a string,
;; calling string length on it and returning the result.
(func $getLength (param $str externref) (result i32)
local.get $str
call $string_length
)
;; Export the getLength function.
(export "getLength" (func $get_length))
) import { getLength } from './string-len.wasm';
getLength('foo'); // Returns 3. Wasm 内建函数是在编译模块时进行链接的编译时导入,而不是在实例化期间。它们的行为不同于普通的模块图导入,也无法通过 WebAssembly.Module.imports(mod) 进行检查,除非使用禁用字符串内建函数的直接 WebAssembly.compile API 重新编译模块,否则无法对其进行虚拟化。
【Wasm builtins are compile-time imports that are linked during module compilation
rather than during instantiation. They do not behave like normal module graph
imports and they cannot be inspected via WebAssembly.Module.imports(mod)
or virtualized unless recompiling the module using the direct
WebAssembly.compile API with string builtins disabled.】
在模块被实例化之前在源阶段导入模块,也会自动使用编译时内置功能:
【Importing a module in the source phase before it has been instantiated will also use the compile-time builtins automatically:】
import source mod from './string-len.wasm';
const { exports: { getLength } } = await WebAssembly.instantiate(mod, {});
getLength('foo'); // Also returns 3.