JavaScript 字符串内置函数


¥JavaScript String Builtins

稳定性: 1.2 - 发布候选

¥Stability: 1.2 - Release candidate

导入 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.