init static method

Future<WasmParserWorld> init(
  1. WasmInstanceBuilder builder, {
  2. required WasmParserWorldImports imports,
})

Implementation

static Future<WasmParserWorld> init(
  WasmInstanceBuilder builder, {
  required WasmParserWorldImports imports,
}) async {
  late final WasmLibrary library;
  WasmLibrary getLib() => library;

  var memType = MemoryTy(minimum: 1, maximum: 2, shared: true);
  try {
    // Find the shared memory import. May not work in web.
    final mem = builder.module.getImports().firstWhere(
          (e) =>
              e.kind == WasmExternalKind.memory &&
              (e.type!.field0 as MemoryTy).shared,
        );
    memType = mem.type!.field0 as MemoryTy;
  } catch (_) {}

  var attempts = 0;
  late WasmSharedMemory wasmMemory;
  WasmInstance? instance;
  while (instance == null) {
    try {
      wasmMemory = builder.module.createSharedMemory(
        minPages: memType.minimum,
        maxPages: memType.maximum! > memType.minimum
            ? memType.maximum!
            : memType.minimum + 1,
      );
      builder.addImport('env', 'memory', wasmMemory);
      instance = await builder.build();
    } catch (e) {
      // TODO: This is not great, remove it.
      if (identical(0, 0.0) && attempts < 2) {
        final str = e.toString();
        final init = RegExp('initial ([0-9]+)').firstMatch(str);
        final maxi = RegExp('maximum ([0-9]+)').firstMatch(str);
        if (init != null || maxi != null) {
          final initVal =
              init == null ? memType.minimum : int.parse(init.group(1)!);
          final maxVal =
              maxi == null ? memType.maximum : int.parse(maxi.group(1)!);
          memType = MemoryTy(minimum: initVal, maximum: maxVal, shared: true);
          attempts++;
          continue;
        }
      }
      rethrow;
    }
  }

  library = WasmLibrary(
    instance,
    int64Type: Int64TypeConfig.bigInt,
    wasmMemory: wasmMemory,
  );
  return WasmParserWorld(imports: imports, library: library);
}