How to mock std.Io for WASM and non-WASM targets support

I need to use CSPRNG in my project but Zig doesnt provide Io in wasm target, so i will create js binding. but how to keep same api for wasm and non-wasm. can i mock std.Io ? link to file that uses std.Io. Zig 0.16.0

make an Io that calls the js bindings, then you can just switch the implementation depending on the platform.

You dont have to implement the whole of Io, just what you need, you can even not support concurrency, and just run async tasks synchronously.

1 Like

but i need to pass io to argon kdf

std.Io is just interface with VTable.

const std = @import("std");

pub fn Io() std.Io {
    return .{
        .userdata = null,
        .vtable = &wasmVtable,
    };
}

fn getVtable(sets: anytype) std.Io.VTable {
    var vt = std.Io.failing.vtable.*;
    inline for (std.meta.fields(@TypeOf(sets))) |f| {
        @field(vt, f.name) = @field(sets, f.name);
    }
    return vt;
}

const wasmVtable = getVtable(.{
    .random = wasmRandom,
    .randomSecure = wasmRandomSecure,
});

fn wasmRandom(userdata: ?*anyopaque, buffer: []u8) void {
    // Implementation
}

fn wasmRandomSecure(userdata: ?*anyopaque, buffer: []u8) std.Io.RandomSecureError!void {
    // Implementation
}
3 Likes

I knew the nature of the problem but I thought the implementation would look a little bit jankier. I was wrong, that’s a really nice way to declare all the missing functions!