logging works for wasm

This commit is contained in:
Mitchell Hashimoto
2022-12-04 12:29:11 -08:00
parent 940828ed97
commit 437f1772f1
6 changed files with 32 additions and 3 deletions

View File

@ -137,6 +137,7 @@ pub fn build(b: *std.build.Builder) !void {
const main_test = b.addTest("src/main_wasm.zig");
main_test.setTarget(.{ .cpu_arch = .wasm32, .os_tag = .wasi });
main_test.addOptions("build_options", exe_options);
main_test.addPackage(js.pkg);
test_step.dependOn(&main_test.step);
}

View File

@ -307,7 +307,7 @@ pub fn clear(self: *Atlas) void {
pub const Wasm = struct {
// If you're copying this file (Atlas.zig) out to a separate project,
// just replace this with the allocator you want to use.
const wasm = @import("../wasm.zig");
const wasm = @import("../os/wasm.zig");
const alloc = wasm.alloc;
export fn atlas_new(size: u32, format: u8) ?*Atlas {

View File

@ -73,7 +73,7 @@ pub const Face = struct {
/// The wasm-compatible API.
pub const Wasm = struct {
const wasm = @import("../../wasm.zig");
const wasm = @import("../../os/wasm.zig");
const alloc = wasm.alloc;
export fn face_new(ptr: [*]const u8, len: usize, pts: u16) ?*Face {

View File

@ -1,5 +1,6 @@
// This is the main file for the WASM module. The WASM module has to
// export a C ABI compatible API.
pub usingnamespace @import("wasm.zig");
pub usingnamespace @import("os/wasm.zig");
pub usingnamespace @import("os/wasm/log.zig");
pub usingnamespace @import("font/main.zig");

27
src/os/wasm/log.zig Normal file
View File

@ -0,0 +1,27 @@
const std = @import("std");
const builtin = @import("builtin");
const wasm = @import("../wasm.zig");
// The function std.log will call.
pub fn log(
comptime level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
// Build the string
const level_txt = comptime level.asText();
const prefix = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
const txt = level_txt ++ prefix ++ format;
const str = nosuspend std.fmt.allocPrint(wasm.alloc, txt, args) catch return;
defer wasm.alloc.free(str);
// Send it over to the JS side
JS.log(str.ptr, str.len);
}
// We wrap our externs in this namespace so we can reuse symbols, otherwise
// "log" would collide.
const JS = struct {
extern "env" fn log(ptr: [*]const u8, len: usize) void;
};