From b74cfa838e221d226b905d58542d6ddabac843c5 Mon Sep 17 00:00:00 2001 From: iddev5 Date: Fri, 8 Jul 2022 23:26:09 +0530 Subject: [PATCH] js-runtime: Implement ``fn format()`` for js.Value for easier debugging and logging --- js-runtime/src/main.zig | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/js-runtime/src/main.zig b/js-runtime/src/main.zig index 35846300..23eb323a 100644 --- a/js-runtime/src/main.zig +++ b/js-runtime/src/main.zig @@ -80,6 +80,21 @@ pub const Value = extern struct { pub fn instanceOf(val: *const Value, other: Value) bool { return js.zigValueInstanceOf(val, &other); } + + pub fn format(val: *const Value, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { + switch (val.tag) { + .object => try writer.print("Object@{}({})", .{ val.val.ref, val.view(.object).attributeCount() }), + .num => if (val.val.num > 10000) + try writer.print("{e}", .{val.val.num}) + else + try writer.print("{d}", .{val.val.num}), + .bool => try writer.writeAll(if (val.view(.bool)) "true" else "false"), + .str => try writer.print("String@{}({})", .{ val.val.ref, val.view(.str).getLength() }), + .func => try writer.print("Function@{}({})", .{ val.val.ref, val.view(.func).paramCount() }), + .nulled => try writer.writeAll("null"), + .undef => try writer.writeAll("undefined"), + } + } }; pub const Object = struct {