silk.wasm.bridge.
Runtime primitives for core WebAssembly (wasm32-unknown-unknown) TypeScript and Effect
bindings generated by silk.wasm.bindgen.
When to use#
Implement WasmResource on stateful structs that should cross the WebAssembly boundary as
opaque generational handles rather than serialized value objects. Plain pub struct,
pub enum, pub union, and fixed-size array types with public fields cross by value using
generated positional binary codecs backed by WireReader and WireWriter. The generated
glue module uses TableRuntime, BridgeRuntime, WireReader, WireWriter, and
NonWaitingClock directly; application code rarely calls them by hand.
Details#
Value types cross via generated positional little-endian binary codecs (
WireReaderandWireWriter) locked to TypeScript viasilk_wb_abi_hash.Resource types implementing
WasmResourcelive in per-type, non-moving generational tables backed byOption<Box<T>>so borrowed&T/&mut Taddresses never move across re-entrant table growth.Synchronous thunks enforce
Intrinsic.NonParkingand installNativeDiagnostics.observeso traps populate the standalone runtime'ssilk_reportbuffer.
Import as BridgeRuntime with import silk.wasm.bridge { BridgeRuntime }.
Public declarations: 23.
WasmResource#
pub interface WasmResourceExplicit opt-in marker for stateful structs exported as opaque generational handles across the WebAssembly ABI.
When to use#
Implement WasmResource on structs that hold private fields, mutable state, resources, or
Drop hooks and should expose methods rather than copying their fields across the ABI by value.
HandleRef#
pub struct HandleRefA generational resource handle transferred across the WebAssembly ABI as (slot, gen).
Field slot#
pub slot: u32The zero-based table slot index.
Field gen#
pub gen: u32The non-zero slot generation; 0 is reserved as an invalid/disposed sentinel on the host.
Implementation Copy for HandleRef#
impl Copy for HandleRefResultHeader#
pub extern "C" struct ResultHeaderThe 16-byte result header written by generated glue thunks into a caller-provided out-slot.
Details#
tag == TAG_OK (0): success. Payload bytes live at(ptr, len, cap)orptr = 0, len = 0, cap = 0for unit returns and inline handles.tag == TAG_GUEST_DEFECT (1): unrecoverable guest encoding/OOM fault (optional UTF-8 message).tag >= TAG_ERROR_BASE (2): declared failure union variant index (tag - TAG_ERROR_BASE).
Field tag#
pub tag: u32Outcome tag (TAG_OK, TAG_GUEST_DEFECT, or TAG_ERROR_BASE + variantIndex).
Field ptr#
pub ptr: u32Linear-memory pointer to the heap-owned payload buffer, or 0 when empty.
Field len#
pub len: u32Byte length of the payload at ptr.
Field cap#
pub cap: u32Allocation capacity to pass to __silk_result_free(ptr, cap), or 0 when no buffer was allocated.
Implementation Copy for ResultHeader#
impl Copy for ResultHeaderTAG_OK#
pub const TAG_OK: u32Success tag in ResultHeader.tag.
TAG_GUEST_DEFECT#
pub const TAG_GUEST_DEFECT: u32Guest defect tag (serialization failure or undeclared OOM) in ResultHeader.tag.
TAG_ERROR_BASE#
pub const TAG_ERROR_BASE: u32Base tag for declared error union variants in ResultHeader.tag.
TAG_PENDING#
pub const TAG_PENDING: u32Pending async operation tag in ResultHeader.tag (ptr = opSlot, len = opGen, cap = 0).
STREAM_STATUS_ITEM#
pub const STREAM_STATUS_ITEM: u32Stream delivery status: one encoded data item.
STREAM_STATUS_END#
pub const STREAM_STATUS_END: u32Stream delivery status: stream ended cleanly with no error.
STREAM_STATUS_ERROR#
pub const STREAM_STATUS_ERROR: u32Stream delivery status: terminal typed error (or guest defect) after all buffered items.
STREAM_STATUS_BATCH_END#
pub const STREAM_STATUS_BATCH_END: u32Stream delivery status: pull batch finished draining ready items; stream stays open.
DeferredRunner#
pub interface DeferredRunner<A: 'static, E: 'static>Erased runner interface for WasmDeferred.
Operation runTask#
effect fn runTask(self: &mut Self) -> A ! E ? &mut Scheduler | &mut MonotonicClockExecutes the deferred computation once.
AsyncTaskRunner#
pub interface AsyncTaskRunnerErased runner interface for WasmStream producers and async glue tasks.
Operation runTask#
effect fn runTask(self: &mut Self) -> () ? &mut Scheduler | &mut MonotonicClockExecutes the task once.
WasmDeferred#
pub struct WasmDeferred<A: 'static, E: 'static>One-shot asynchronous computation exported across the WebAssembly boundary as a Promise
(Plain TS) or Effect (Effect 4.x) with cooperative cancellation.
Implementation WasmDeferred<A, E>#
impl<A: 'static, E: 'static> WasmDeferred<A, E>Associated function fromRunner#
pub effect fn fromRunner<T: DeferredRunner<A, E> + 'static>(
task: T,
) -> WasmDeferred<A, E>
! OutOfMemoryError
? &mut AllocatorWraps a concrete DeferredRunner task as a WasmDeferred return value.
Method execute#
pub effect fn execute(self: Self) -> A ! E ? &mut Scheduler | &mut MonotonicClockRuns the underlying 'static task (used by generated glue).
StreamItem#
pub union StreamItem<A, E>One element or terminal typed error carried by a WasmStream.
Item#
ItemA data item yielded by the stream.
Field value#
pub value: AError#
ErrorA terminal typed error delivered after all preceding buffered items.
Field error#
pub error: EWasmStreamParts#
pub struct WasmStreamParts<A: 'static, E: 'static>The owned parts extracted from a WasmStream by generated glue.
Field receiver#
pub receiver: Receiver<StreamItem<A, E>>Bounded channel receiver drained under host pull credit.
Field producer#
pub producer: Option<AnyBox<any AsyncTaskRunner>>Optional producer fiber spawned onto the instance's LocalDriver and cancelled on stream drop.
WasmStream#
pub struct WasmStream<A: 'static, E: 'static>Backpressured asynchronous stream exported across the WebAssembly boundary as an
AsyncIterable (Plain TS) or Stream.Stream<A, E> (Effect 4.x).
Implementation WasmStream<A, E>#
impl<A: 'static, E: 'static> WasmStream<A, E>Associated function fromReceiver#
pub fn fromReceiver(receiver: Receiver<StreamItem<A, E>>) -> WasmStream<A, E>Wraps an existing channel receiver as a WasmStream.
Associated function fromTask#
pub effect fn fromTask<T: AsyncTaskRunner + 'static>(
receiver: Receiver<StreamItem<A, E>>,
producer: T,
) -> WasmStream<A, E>
! OutOfMemoryError
? &mut AllocatorWraps a channel receiver together with a concrete AsyncTaskRunner producer that the
bindings runtime spawns on the instance's LocalDriver and cancels on stream drop.
Method intoParts#
pub fn intoParts(self: Self) -> WasmStreamParts<A, E>Extracts the receiver and optional producer task (used by generated glue).
HandleTable#
pub struct HandleTable<T>An instance-local, non-moving generational handle table for one WasmResource type T.
Details#
Values are stored as Option<Box<T>> so growing the backing List never relocates a live
T while an outer guest call holds &T or &mut T.
TableRuntime#
pub struct TableRuntimeStatic operations over per-type instance-local generational handle tables.
Implementation TableRuntime#
impl TableRuntimeAssociated function insert#
pub effect fn insert<T>(value: T) -> HandleRef
! OutOfMemoryError
? &mut AllocatorStores value in a heap-pinned Box<T> inside T's handle table and returns its handle.
Associated function acquireShared#
pub fn acquireShared<T>(slot: u32, gen: u32) -> *const TAcquires a shared borrow on (slot, gen) and returns the pinned address of the T inside
its Box<T>. The table borrow ends before this returns so re-entrant calls can grow the
table safely. Must be paired with releaseShared.
Associated function releaseShared#
pub fn releaseShared<T>(slot: u32, gen: u32) -> ()Releases a shared borrow previously acquired with acquireShared.
Associated function acquireMut#
pub fn acquireMut<T>(slot: u32, gen: u32) -> *mut TAcquires an exclusive borrow on (slot, gen) and returns the pinned mutable address of T
inside its Box<T>. Traps if any shared or mutable borrow is active. Must be paired with
releaseMut.
Associated function releaseMut#
pub fn releaseMut<T>(slot: u32, gen: u32) -> ()Releases an exclusive borrow previously acquired with acquireMut.
Associated function takeOwned#
pub effect fn takeOwned<T>(slot: u32, gen: u32) -> T
! OutOfMemoryError
? &mut AllocatorRemoves (slot, gen) from T's table and returns the owned T via Box.into, advancing
the slot generation. Traps if the handle is stale or currently borrowed.
Associated function dropHandle#
pub effect fn dropHandle<T>(slot: u32, gen: u32) -> ()
! OutOfMemoryError
? &mut AllocatorDrops the resource at (slot, gen), advancing its generation and recycling the slot.
Traps if the handle is stale or currently borrowed.
Associated function dropAll#
pub fn dropAll<T>() -> ()Drops every live resource in T's table and releases the table storage.
Must only be called by __silk_shutdown() at call depth 0.
WireReader#
pub struct WireReaderSequential bounds-checked little-endian binary reader over linear-memory input bytes.
Details#
Used by generated glue thunks to decode positional binary value payloads without Schema
reflection or MessagePack framing. Traps on truncated buffers, null non-empty pointers,
invalid booleans or option tags, invalid UTF-8 strings, or trailing payload bytes.
Implementation WireReader#
impl WireReaderAssociated function make#
pub fn make(ptr: ?[*]const u8, len: usize) -> WireReaderCreates a WireReader over len bytes starting at ptr.
Method finish#
pub fn finish(self: &Self) -> ()Verifies that all payload bytes have been consumed, trapping on trailing data.
Method readU8#
pub fn readU8(self: &mut Self) -> u8Reads an unsigned 8-bit integer (u8).
Method readI8#
pub fn readI8(self: &mut Self) -> i8Reads a signed 8-bit integer (i8).
Method readBool#
pub fn readBool(self: &mut Self) -> boolReads a boolean (0 -> false, 1 -> true), trapping on any other byte value.
Method readOptionTag#
pub fn readOptionTag(self: &mut Self) -> boolReads an Option tag (0 -> None, 1 -> Some), trapping on any other byte value.
Method readU16#
pub fn readU16(self: &mut Self) -> u16Reads a little-endian unsigned 16-bit integer (u16).
Method readI16#
pub fn readI16(self: &mut Self) -> i16Reads a little-endian signed 16-bit integer (i16).
Method readU32#
pub fn readU32(self: &mut Self) -> u32Reads a little-endian unsigned 32-bit integer (u32).
Method readI32#
pub fn readI32(self: &mut Self) -> i32Reads a little-endian signed 32-bit integer (i32).
Method readUsize#
pub fn readUsize(self: &mut Self) -> usizeReads a little-endian usize encoded as a 32-bit unsigned integer.
Method readIsize#
pub fn readIsize(self: &mut Self) -> isizeReads a little-endian isize encoded as a 32-bit signed integer.
Method readU64#
pub fn readU64(self: &mut Self) -> u64Reads a little-endian unsigned 64-bit integer (u64).
Method readI64#
pub fn readI64(self: &mut Self) -> i64Reads a little-endian signed 64-bit integer (i64).
Method readF32#
pub fn readF32(self: &mut Self) -> f32Reads a little-endian IEEE 754 f32.
Method readF64#
pub fn readF64(self: &mut Self) -> f64Reads a little-endian IEEE 754 f64.
Method readString#
pub effect fn readString(self: &mut Self) -> String
! OutOfMemoryError
? &mut AllocatorReads a u32 byte-length prefix followed by UTF-8 bytes into an owned String.
Method readBytes#
pub effect fn readBytes(self: &mut Self) -> Bytes
! OutOfMemoryError
? &mut AllocatorReads a u32 byte-length prefix followed by raw bytes into an owned Bytes.
WireWriter#
pub struct WireWriterGrowable little-endian binary writer that transfers its heap buffer directly into a
ResultHeader with zero secondary copy.
Details#
Allocations grow lazily from WasmHeap starting at 64 bytes on the first write. If an
allocation fails, oom is flagged while keeping any prior buffer intact so intoHeader
releases it cleanly and returns TAG_GUEST_DEFECT.
Implementation WireWriter#
impl WireWriterAssociated function make#
pub fn make() -> WireWriterCreates an empty WireWriter without allocating.
Method writeU8#
pub fn writeU8(self: &mut Self, value: u8) -> ()Appends an unsigned 8-bit integer (u8).
Method writeI8#
pub fn writeI8(self: &mut Self, value: i8) -> ()Appends a signed 8-bit integer (i8).
Method writeBool#
pub fn writeBool(self: &mut Self, value: bool) -> ()Appends a boolean byte (1 for true, 0 for false).
Method writeU16#
pub fn writeU16(self: &mut Self, value: u16) -> ()Appends a little-endian unsigned 16-bit integer (u16).
Method writeI16#
pub fn writeI16(self: &mut Self, value: i16) -> ()Appends a little-endian signed 16-bit integer (i16).
Method writeU32#
pub fn writeU32(self: &mut Self, value: u32) -> ()Appends a little-endian unsigned 32-bit integer (u32).
Method writeI32#
pub fn writeI32(self: &mut Self, value: i32) -> ()Appends a little-endian signed 32-bit integer (i32).
Method writeUsize#
pub fn writeUsize(self: &mut Self, value: usize) -> ()Appends a usize encoded as a little-endian u32.
Method writeIsize#
pub fn writeIsize(self: &mut Self, value: isize) -> ()Appends an isize encoded as a little-endian i32.
Method writeU64#
pub fn writeU64(self: &mut Self, value: u64) -> ()Appends a little-endian unsigned 64-bit integer (u64).
Method writeI64#
pub fn writeI64(self: &mut Self, value: i64) -> ()Appends a little-endian signed 64-bit integer (i64).
Method writeF32#
pub fn writeF32(self: &mut Self, value: f32) -> ()Appends a little-endian IEEE 754 f32.
Method writeF64#
pub fn writeF64(self: &mut Self, value: f64) -> ()Appends a little-endian IEEE 754 f64.
Method writeBytes#
pub fn writeBytes(self: &mut Self, bytes: &[u8]) -> ()Appends a u32 byte-length prefix followed by bytes.
Method writeString#
pub fn writeString(self: &mut Self, value: string) -> ()Appends a u32 byte-length prefix followed by the UTF-8 bytes of value.
Method intoHeader#
pub fn intoHeader(self: Self, tag: u32) -> ResultHeaderConsumes this writer and transfers ownership of its heap buffer into a ResultHeader,
returning TAG_GUEST_DEFECT if allocation failed.
Method writeInto#
pub fn writeInto(self: Self, outPtr: *mut ResultHeader, tag: u32) -> ()Consumes this writer and writes the resulting ResultHeader into outPtr.
NonWaitingClock#
pub struct NonWaitingClockRead-only MonotonicClock provider for synchronous WebAssembly exports.
Details#
Delegates now and getResolution to JsHost, and traps on waitUntil, waitFor, and
waitReady so synchronous exports can never busy-spin the JavaScript event loop.
Implementation NonWaitingClock#
impl NonWaitingClockAssociated function make#
pub fn make() -> NonWaitingClockCreates a NonWaitingClock provider.
Implementation MonotonicClock for NonWaitingClock#
impl MonotonicClock for NonWaitingClockOperation now#
effect fn now(self: &mut Self) -> MarkOperation getResolution#
effect fn getResolution(self: &mut Self) -> u64Operation waitUntil#
effect fn waitUntil(self: &mut Self, when: Mark) -> ()Operation waitFor#
effect fn waitFor(self: &mut Self, howLong: u64) -> ()Operation waitReady#
effect fn waitReady(self: &mut Self, watch: &mut [ReadyWatch], until: Option<Mark>) -> usizeBridgeRuntime#
pub struct BridgeRuntimeMemory, serialization, result-header, and entry-observation helpers called by generated glue.
Implementation BridgeRuntime#
impl BridgeRuntimeAssociated function alloc#
pub fn alloc(size: usize, _align: usize) -> ?[*]mut u8Allocates size bytes from linear memory (WasmHeap), aligned to at least 16 bytes.
Associated function free#
pub fn free(ptr: ?[*]mut u8, size: usize, _align: usize) -> ()Releases an input buffer previously allocated with alloc.
Associated function resultFree#
pub fn resultFree(ptr: ?[*]mut u8, cap: usize) -> ()Releases an output buffer whose pointer and capacity were returned in a ResultHeader.
Associated function slabReserve#
pub fn slabReserve(minBytes: usize) -> ?[*]mut u8Reserves a reusable top-level input slab of at least minBytes bytes and returns its pointer.
Associated function writeHeader#
pub fn writeHeader(outPtr: *mut ResultHeader, tag: u32, ptr: u32, len: u32, cap: u32) -> ()Writes a ResultHeader into outPtr.
Associated function writeUnit#
pub fn writeUnit(outPtr: *mut ResultHeader, tag: u32) -> ()Writes a payload-free ResultHeader (zero heap allocation; safe for () and OOM errors).
Associated function writeHandle#
pub fn writeHandle(outPtr: *mut ResultHeader, tag: u32, handle: HandleRef) -> ()Writes a HandleRef directly into a ResultHeader (ptr = slot, len = gen, cap = 0).
Associated function makeScalar32Header#
pub fn makeScalar32Header(tag: u32, bits: u32) -> ResultHeaderReturns an inline 32-bit scalar ResultHeader (ptr = bits, len = 0, cap = 0) with zero heap allocation.
Associated function makeScalar64Header#
pub fn makeScalar64Header(tag: u32, bits: u64) -> ResultHeaderReturns an inline 64-bit scalar ResultHeader (ptr = low 32 bits, len = high 32 bits, cap = 0) with zero heap allocation.
Associated function writeScalar32#
pub fn writeScalar32(outPtr: *mut ResultHeader, tag: u32, bits: u32) -> ()Writes a 32-bit scalar value inline into outPtr (ptr = bits, len = 0, cap = 0) with zero heap allocation.
Associated function writeScalar64#
pub fn writeScalar64(outPtr: *mut ResultHeader, tag: u32, bits: u64) -> ()Writes a 64-bit scalar value inline into outPtr (ptr = low 32 bits, len = high 32 bits, cap = 0) with zero heap allocation.
Associated function makePayloadHeader#
pub fn makePayloadHeader(tag: u32, bytes: &[u8]) -> ResultHeaderCopies bytes into a heap-owned output buffer and returns its ResultHeader.
Associated function writePayload#
pub fn writePayload(outPtr: *mut ResultHeader, tag: u32, bytes: &[u8]) -> ()Copies bytes into a heap-owned output buffer and records it in outPtr.
On OOM, writes TAG_GUEST_DEFECT with zero payload.
Associated function writeDefect#
pub fn writeDefect(outPtr: *mut ResultHeader, message: string) -> ()Writes a TAG_GUEST_DEFECT header with a UTF-8 diagnostic message (or empty on OOM).
Associated function writeString#
pub fn writeString(outPtr: *mut ResultHeader, tag: u32, value: string) -> ()Writes a UTF-8 string payload directly into outPtr.
Associated function borrowBytes#
pub unsafe fn borrowBytes<'a, A>(anchor: &'a A, ptr: ?[*]const u8, len: usize) -> &'a [u8]Borrows a byte slice from linear memory (ptr, len) anchored to anchor.
Associated function readOwnedString#
pub effect fn readOwnedString(ptr: ?[*]const u8, len: usize) -> String
! OutOfMemoryError
? &mut AllocatorCopies a UTF-8 string from linear memory (ptr, len) into an owned String.
Associated function borrowString#
pub unsafe fn borrowString<'a, A>(anchor: &'a A, ptr: ?[*]const u8, len: usize) -> string<'a>Borrows a UTF-8 string view from linear memory (ptr, len) anchored to anchor.
Associated function readOwnedBytes#
pub effect fn readOwnedBytes(ptr: ?[*]const u8, len: usize) -> Bytes
! OutOfMemoryError
? &mut AllocatorCopies raw bytes from linear memory (ptr, len) into an owned Bytes.
Associated function observeSync#
pub fn observeSync<'env, R, F: once Effect<'env; R ! never> + Intrinsic.NonParking>(body: F) -> RRuns a synchronous glue thunk under NativeDiagnostics.observe and statically enforces
Intrinsic.NonParking.
Category: WebAssembly.
Profiles: wasm32-unknown-unknown, wasm64-unknown-unknown.