[bun.js] formatter

This commit is contained in:
Jarred Sumner
2022-02-14 04:28:25 -08:00
parent 8325db48ab
commit 7653a2338e
3 changed files with 90 additions and 11 deletions

View File

@@ -152,6 +152,15 @@ pub const ZigString = extern struct {
return ZigString{ .ptr = slice_.ptr, .len = slice_.len };
}
pub fn toBase64DataURL(this: ZigString, allocator: std.mem.Allocator) ![]const u8 {
const slice_ = this.slice();
const size = std.base64.standard.Encoder.calcSize(slice_.len);
var buf = try allocator.alloc(u8, size + "data:;base64,".len);
var encoded = std.base64.url_safe.Encoder.encode(buf["data:;base64,".len..], slice_);
buf[0.."data:;base64,".len].* = "data:;base64,".*;
return buf[0 .. "data:;base64,".len + encoded.len];
}
pub fn detectEncoding(this: *ZigString) void {
for (this.slice()) |char| {
if (char > 127) {
@@ -1928,6 +1937,24 @@ pub const JSValue = enum(i64) {
});
}
pub fn toFmt(
this: JSValue,
global: *JSGlobalObject,
formatter: *Exports.ZigConsoleClient.Formatter,
) Exports.ZigConsoleClient.Formatter.ZigFormatter {
formatter.remaining_values = &[_]JSValue{};
if (formatter.map_node) |node| {
node.release();
formatter.map_node = null;
}
return Exports.ZigConsoleClient.Formatter.ZigFormatter{
.formatter = formatter,
.value = this,
.global = global,
};
}
pub fn asObject(this: JSValue) JSObject {
return cppFn("asObject", .{
this,

View File

@@ -943,11 +943,34 @@ pub const ZigConsoleClient = struct {
}
pub const Formatter = struct {
remaining_values: []JSValue,
remaining_values: []JSValue = &[_]JSValue{},
map: Visited.Map = undefined,
map_node: ?*Visited.Pool.Node = null,
hide_native: bool = false,
pub const ZigFormatter = struct {
formatter: *Formatter,
global: *JSGlobalObject,
value: JSValue,
pub const WriteError = error{UhOh};
pub fn format(self: ZigFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
self.formatter.remaining_values = &[_]JSValue{self.value};
defer {
self.formatter.remaining_values = &[_]JSValue{};
}
self.formatter.format(
Tag.get(self.value, self.global),
@TypeOf(writer),
writer,
self.value,
self.global,
false,
);
}
};
// For detecting circular references
pub const Visited = struct {
const ObjectPool = @import("../../../pool.zig").ObjectPool;