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 (WireReader and WireWriter) locked to TypeScript via silk_wb_abi_hash.

  • Resource types implementing WasmResource live in per-type, non-moving generational tables backed by Option<Box<T>> so borrowed &T / &mut T addresses never move across re-entrant table growth.

  • Synchronous thunks enforce Intrinsic.NonParking and install NativeDiagnostics.observe so traps populate the standalone runtime's silk_report buffer.

Import as BridgeRuntime with import silk.wasm.bridge { BridgeRuntime }.

Public declarations: 23.

WasmResource#

silk
pub interface WasmResource

Explicit 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#

silk
pub struct HandleRef

A generational resource handle transferred across the WebAssembly ABI as (slot, gen).

Field slot#

silk
pub slot: u32

The zero-based table slot index.

Field gen#

silk
pub gen: u32

The non-zero slot generation; 0 is reserved as an invalid/disposed sentinel on the host.

Implementation Copy for HandleRef#

silk
impl Copy for HandleRef

ResultHeader#

silk
pub extern "C" struct ResultHeader

The 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) or ptr = 0, len = 0, cap = 0 for 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#

silk
pub tag: u32

Outcome tag (TAG_OK, TAG_GUEST_DEFECT, or TAG_ERROR_BASE + variantIndex).

Field ptr#

silk
pub ptr: u32

Linear-memory pointer to the heap-owned payload buffer, or 0 when empty.

Field len#

silk
pub len: u32

Byte length of the payload at ptr.

Field cap#

silk
pub cap: u32

Allocation capacity to pass to __silk_result_free(ptr, cap), or 0 when no buffer was allocated.

Implementation Copy for ResultHeader#

silk
impl Copy for ResultHeader

TAG_OK#

silk
pub const TAG_OK: u32

Success tag in ResultHeader.tag.

TAG_GUEST_DEFECT#

silk
pub const TAG_GUEST_DEFECT: u32

Guest defect tag (serialization failure or undeclared OOM) in ResultHeader.tag.

TAG_ERROR_BASE#

silk
pub const TAG_ERROR_BASE: u32

Base tag for declared error union variants in ResultHeader.tag.

TAG_PENDING#

silk
pub const TAG_PENDING: u32

Pending async operation tag in ResultHeader.tag (ptr = opSlot, len = opGen, cap = 0).

STREAM_STATUS_ITEM#

silk
pub const STREAM_STATUS_ITEM: u32

Stream delivery status: one encoded data item.

STREAM_STATUS_END#

silk
pub const STREAM_STATUS_END: u32

Stream delivery status: stream ended cleanly with no error.

STREAM_STATUS_ERROR#

silk
pub const STREAM_STATUS_ERROR: u32

Stream delivery status: terminal typed error (or guest defect) after all buffered items.

STREAM_STATUS_BATCH_END#

silk
pub const STREAM_STATUS_BATCH_END: u32

Stream delivery status: pull batch finished draining ready items; stream stays open.

DeferredRunner#

silk
pub interface DeferredRunner<A: 'static, E: 'static>

Erased runner interface for WasmDeferred.

Operation runTask#

silk
effect fn runTask(self: &mut Self) -> A ! E ? &mut Scheduler | &mut MonotonicClock

Executes the deferred computation once.

AsyncTaskRunner#

silk
pub interface AsyncTaskRunner

Erased runner interface for WasmStream producers and async glue tasks.

Operation runTask#

silk
effect fn runTask(self: &mut Self) -> () ? &mut Scheduler | &mut MonotonicClock

Executes the task once.

WasmDeferred#

silk
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>#

silk
impl<A: 'static, E: 'static> WasmDeferred<A, E>

Associated function fromRunner#

silk
pub effect fn fromRunner<T: DeferredRunner<A, E> + 'static>(
    task: T,
  ) -> WasmDeferred<A, E>
    ! OutOfMemoryError
    ? &mut Allocator

Wraps a concrete DeferredRunner task as a WasmDeferred return value.

Method execute#

silk
pub effect fn execute(self: Self) -> A ! E ? &mut Scheduler | &mut MonotonicClock

Runs the underlying 'static task (used by generated glue).

StreamItem#

silk
pub union StreamItem<A, E>

One element or terminal typed error carried by a WasmStream.

Item#

silk
Item

A data item yielded by the stream.

Field value#

silk
pub value: A

Error#

silk
Error

A terminal typed error delivered after all preceding buffered items.

Field error#

silk
pub error: E

WasmStreamParts#

silk
pub struct WasmStreamParts<A: 'static, E: 'static>

The owned parts extracted from a WasmStream by generated glue.

Field receiver#

silk
pub receiver: Receiver<StreamItem<A, E>>

Bounded channel receiver drained under host pull credit.

Field producer#

silk
pub producer: Option<AnyBox<any AsyncTaskRunner>>

Optional producer fiber spawned onto the instance's LocalDriver and cancelled on stream drop.

WasmStream#

silk
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>#

silk
impl<A: 'static, E: 'static> WasmStream<A, E>

Associated function fromReceiver#

silk
pub fn fromReceiver(receiver: Receiver<StreamItem<A, E>>) -> WasmStream<A, E>

Wraps an existing channel receiver as a WasmStream.

Associated function fromTask#

silk
pub effect fn fromTask<T: AsyncTaskRunner + 'static>(
    receiver: Receiver<StreamItem<A, E>>,
    producer: T,
  ) -> WasmStream<A, E>
    ! OutOfMemoryError
    ? &mut Allocator

Wraps 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#

silk
pub fn intoParts(self: Self) -> WasmStreamParts<A, E>

Extracts the receiver and optional producer task (used by generated glue).

HandleTable#

silk
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#

silk
pub struct TableRuntime

Static operations over per-type instance-local generational handle tables.

Implementation TableRuntime#

silk
impl TableRuntime

Associated function insert#

silk
pub effect fn insert<T>(value: T) -> HandleRef
      ! OutOfMemoryError
      ? &mut Allocator

Stores value in a heap-pinned Box<T> inside T's handle table and returns its handle.

Associated function acquireShared#

silk
pub fn acquireShared<T>(slot: u32, gen: u32) -> *const T

Acquires 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#

silk
pub fn releaseShared<T>(slot: u32, gen: u32) -> ()

Releases a shared borrow previously acquired with acquireShared.

Associated function acquireMut#

silk
pub fn acquireMut<T>(slot: u32, gen: u32) -> *mut T

Acquires 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#

silk
pub fn releaseMut<T>(slot: u32, gen: u32) -> ()

Releases an exclusive borrow previously acquired with acquireMut.

Associated function takeOwned#

silk
pub effect fn takeOwned<T>(slot: u32, gen: u32) -> T
      ! OutOfMemoryError
      ? &mut Allocator

Removes (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#

silk
pub effect fn dropHandle<T>(slot: u32, gen: u32) -> ()
      ! OutOfMemoryError
      ? &mut Allocator

Drops the resource at (slot, gen), advancing its generation and recycling the slot. Traps if the handle is stale or currently borrowed.

Associated function dropAll#

silk
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#

silk
pub struct WireReader

Sequential 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#

silk
impl WireReader

Associated function make#

silk
pub fn make(ptr: ?[*]const u8, len: usize) -> WireReader

Creates a WireReader over len bytes starting at ptr.

Method finish#

silk
pub fn finish(self: &Self) -> ()

Verifies that all payload bytes have been consumed, trapping on trailing data.

Method readU8#

silk
pub fn readU8(self: &mut Self) -> u8

Reads an unsigned 8-bit integer (u8).

Method readI8#

silk
pub fn readI8(self: &mut Self) -> i8

Reads a signed 8-bit integer (i8).

Method readBool#

silk
pub fn readBool(self: &mut Self) -> bool

Reads a boolean (0 -> false, 1 -> true), trapping on any other byte value.

Method readOptionTag#

silk
pub fn readOptionTag(self: &mut Self) -> bool

Reads an Option tag (0 -> None, 1 -> Some), trapping on any other byte value.

Method readU16#

silk
pub fn readU16(self: &mut Self) -> u16

Reads a little-endian unsigned 16-bit integer (u16).

Method readI16#

silk
pub fn readI16(self: &mut Self) -> i16

Reads a little-endian signed 16-bit integer (i16).

Method readU32#

silk
pub fn readU32(self: &mut Self) -> u32

Reads a little-endian unsigned 32-bit integer (u32).

Method readI32#

silk
pub fn readI32(self: &mut Self) -> i32

Reads a little-endian signed 32-bit integer (i32).

Method readUsize#

silk
pub fn readUsize(self: &mut Self) -> usize

Reads a little-endian usize encoded as a 32-bit unsigned integer.

Method readIsize#

silk
pub fn readIsize(self: &mut Self) -> isize

Reads a little-endian isize encoded as a 32-bit signed integer.

Method readU64#

silk
pub fn readU64(self: &mut Self) -> u64

Reads a little-endian unsigned 64-bit integer (u64).

Method readI64#

silk
pub fn readI64(self: &mut Self) -> i64

Reads a little-endian signed 64-bit integer (i64).

Method readF32#

silk
pub fn readF32(self: &mut Self) -> f32

Reads a little-endian IEEE 754 f32.

Method readF64#

silk
pub fn readF64(self: &mut Self) -> f64

Reads a little-endian IEEE 754 f64.

Method readString#

silk
pub effect fn readString(self: &mut Self) -> String
      ! OutOfMemoryError
      ? &mut Allocator

Reads a u32 byte-length prefix followed by UTF-8 bytes into an owned String.

Method readBytes#

silk
pub effect fn readBytes(self: &mut Self) -> Bytes
      ! OutOfMemoryError
      ? &mut Allocator

Reads a u32 byte-length prefix followed by raw bytes into an owned Bytes.

WireWriter#

silk
pub struct WireWriter

Growable 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#

silk
impl WireWriter

Associated function make#

silk
pub fn make() -> WireWriter

Creates an empty WireWriter without allocating.

Method writeU8#

silk
pub fn writeU8(self: &mut Self, value: u8) -> ()

Appends an unsigned 8-bit integer (u8).

Method writeI8#

silk
pub fn writeI8(self: &mut Self, value: i8) -> ()

Appends a signed 8-bit integer (i8).

Method writeBool#

silk
pub fn writeBool(self: &mut Self, value: bool) -> ()

Appends a boolean byte (1 for true, 0 for false).

Method writeU16#

silk
pub fn writeU16(self: &mut Self, value: u16) -> ()

Appends a little-endian unsigned 16-bit integer (u16).

Method writeI16#

silk
pub fn writeI16(self: &mut Self, value: i16) -> ()

Appends a little-endian signed 16-bit integer (i16).

Method writeU32#

silk
pub fn writeU32(self: &mut Self, value: u32) -> ()

Appends a little-endian unsigned 32-bit integer (u32).

Method writeI32#

silk
pub fn writeI32(self: &mut Self, value: i32) -> ()

Appends a little-endian signed 32-bit integer (i32).

Method writeUsize#

silk
pub fn writeUsize(self: &mut Self, value: usize) -> ()

Appends a usize encoded as a little-endian u32.

Method writeIsize#

silk
pub fn writeIsize(self: &mut Self, value: isize) -> ()

Appends an isize encoded as a little-endian i32.

Method writeU64#

silk
pub fn writeU64(self: &mut Self, value: u64) -> ()

Appends a little-endian unsigned 64-bit integer (u64).

Method writeI64#

silk
pub fn writeI64(self: &mut Self, value: i64) -> ()

Appends a little-endian signed 64-bit integer (i64).

Method writeF32#

silk
pub fn writeF32(self: &mut Self, value: f32) -> ()

Appends a little-endian IEEE 754 f32.

Method writeF64#

silk
pub fn writeF64(self: &mut Self, value: f64) -> ()

Appends a little-endian IEEE 754 f64.

Method writeBytes#

silk
pub fn writeBytes(self: &mut Self, bytes: &[u8]) -> ()

Appends a u32 byte-length prefix followed by bytes.

Method writeString#

silk
pub fn writeString(self: &mut Self, value: string) -> ()

Appends a u32 byte-length prefix followed by the UTF-8 bytes of value.

Method intoHeader#

silk
pub fn intoHeader(self: Self, tag: u32) -> ResultHeader

Consumes this writer and transfers ownership of its heap buffer into a ResultHeader, returning TAG_GUEST_DEFECT if allocation failed.

Method writeInto#

silk
pub fn writeInto(self: Self, outPtr: *mut ResultHeader, tag: u32) -> ()

Consumes this writer and writes the resulting ResultHeader into outPtr.

NonWaitingClock#

silk
pub struct NonWaitingClock

Read-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#

silk
impl NonWaitingClock

Associated function make#

silk
pub fn make() -> NonWaitingClock

Creates a NonWaitingClock provider.

Implementation MonotonicClock for NonWaitingClock#

silk
impl MonotonicClock for NonWaitingClock

Operation now#

silk
effect fn now(self: &mut Self) -> Mark

Operation getResolution#

silk
effect fn getResolution(self: &mut Self) -> u64

Operation waitUntil#

silk
effect fn waitUntil(self: &mut Self, when: Mark) -> ()

Operation waitFor#

silk
effect fn waitFor(self: &mut Self, howLong: u64) -> ()

Operation waitReady#

silk
effect fn waitReady(self: &mut Self, watch: &mut [ReadyWatch], until: Option<Mark>) -> usize

BridgeRuntime#

silk
pub struct BridgeRuntime

Memory, serialization, result-header, and entry-observation helpers called by generated glue.

Implementation BridgeRuntime#

silk
impl BridgeRuntime

Associated function alloc#

silk
pub fn alloc(size: usize, _align: usize) -> ?[*]mut u8

Allocates size bytes from linear memory (WasmHeap), aligned to at least 16 bytes.

Associated function free#

silk
pub fn free(ptr: ?[*]mut u8, size: usize, _align: usize) -> ()

Releases an input buffer previously allocated with alloc.

Associated function resultFree#

silk
pub fn resultFree(ptr: ?[*]mut u8, cap: usize) -> ()

Releases an output buffer whose pointer and capacity were returned in a ResultHeader.

Associated function slabReserve#

silk
pub fn slabReserve(minBytes: usize) -> ?[*]mut u8

Reserves a reusable top-level input slab of at least minBytes bytes and returns its pointer.

Associated function writeHeader#

silk
pub fn writeHeader(outPtr: *mut ResultHeader, tag: u32, ptr: u32, len: u32, cap: u32) -> ()

Writes a ResultHeader into outPtr.

Associated function writeUnit#

silk
pub fn writeUnit(outPtr: *mut ResultHeader, tag: u32) -> ()

Writes a payload-free ResultHeader (zero heap allocation; safe for () and OOM errors).

Associated function writeHandle#

silk
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#

silk
pub fn makeScalar32Header(tag: u32, bits: u32) -> ResultHeader

Returns an inline 32-bit scalar ResultHeader (ptr = bits, len = 0, cap = 0) with zero heap allocation.

Associated function makeScalar64Header#

silk
pub fn makeScalar64Header(tag: u32, bits: u64) -> ResultHeader

Returns an inline 64-bit scalar ResultHeader (ptr = low 32 bits, len = high 32 bits, cap = 0) with zero heap allocation.

Associated function writeScalar32#

silk
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#

silk
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#

silk
pub fn makePayloadHeader(tag: u32, bytes: &[u8]) -> ResultHeader

Copies bytes into a heap-owned output buffer and returns its ResultHeader.

Associated function writePayload#

silk
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#

silk
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#

silk
pub fn writeString(outPtr: *mut ResultHeader, tag: u32, value: string) -> ()

Writes a UTF-8 string payload directly into outPtr.

Associated function borrowBytes#

silk
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#

silk
pub effect fn readOwnedString(ptr: ?[*]const u8, len: usize) -> String
      ! OutOfMemoryError
      ? &mut Allocator

Copies a UTF-8 string from linear memory (ptr, len) into an owned String.

Associated function borrowString#

silk
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#

silk
pub effect fn readOwnedBytes(ptr: ?[*]const u8, len: usize) -> Bytes
      ! OutOfMemoryError
      ? &mut Allocator

Copies raw bytes from linear memory (ptr, len) into an owned Bytes.

Associated function observeSync#

silk
pub fn observeSync<'env, R, F: once Effect<'env; R ! never> + Intrinsic.NonParking>(body: F) -> R

Runs a synchronous glue thunk under NativeDiagnostics.observe and statically enforces Intrinsic.NonParking.

Category: WebAssembly.

Profiles: wasm32-unknown-unknown, wasm64-unknown-unknown.

View the source of this page