wasm: use shared, imported memory

This switches our wasm build to use "shared" memory. Shared memory can
be shared across multiple web workers, which is something we'll want to
support for our multi-threaded behaviors later.

Shared memory has a number of different restrictions so this updates
zig-js to support it as well as updates some of our functions that need
to be aware of it.
This commit is contained in:
Mitchell Hashimoto
2022-12-24 16:20:59 -08:00
parent 61450fce25
commit 241bfee7d4
5 changed files with 52 additions and 9 deletions

View File

@@ -423,9 +423,17 @@ pub const Wasm = struct {
defer mem_buf.deinit();
// Create an array that points to our buffer
const Uint8ClampedArray = try js.global.get(js.Object, "Uint8ClampedArray");
defer Uint8ClampedArray.deinit();
const arr = try Uint8ClampedArray.new(.{ mem_buf, buf.ptr, buf.len });
const arr = arr: {
const Uint8ClampedArray = try js.global.get(js.Object, "Uint8ClampedArray");
defer Uint8ClampedArray.deinit();
const arr = try Uint8ClampedArray.new(.{ mem_buf, buf.ptr, buf.len });
if (!wasm.shared_mem) break :arr arr;
// If we're sharing memory then we have to copy the data since
// we can't set ImageData directly using a SharedArrayBuffer.
defer arr.deinit();
break :arr try arr.call(js.Object, "slice", .{});
};
defer arr.deinit();
// Create the image data from our array

View File

@@ -1,6 +1,7 @@
//! This file contains helpers for wasm compilation.
const std = @import("std");
const builtin = @import("builtin");
const options = @import("build_options");
comptime {
if (!builtin.target.isWasm()) {
@@ -8,6 +9,10 @@ comptime {
}
}
/// True if we're in shared memory mode. If true, then the memory buffer
/// in JS will be backed by a SharedArrayBuffer and some behaviors change.
pub const shared_mem = options.wasm_shared;
/// The allocator to use in wasm environments.
///
/// The return values of this should NOT be sent to the host environment