initial commit
All checks were successful
Run Tests / test (push) Successful in 9m42s
Run Tests / lint (push) Successful in 9m43s

This commit is contained in:
2024-08-27 17:17:02 +02:00
parent 296fa6fa38
commit ffb28f8e5b
6 changed files with 276 additions and 0 deletions

88
src/zlog.zig Normal file
View File

@@ -0,0 +1,88 @@
const std = @import("std");
const max_depth = 5;
// pub fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void
// TODO: provide comptime helper function to add format function for user types:
// - pretty printing
// - compact printing
// - show types of struct members
// Maybe the corresponding configurations for the `format` function could also
// be effected by build time configurations
pub const std_options: std.Options = .{
.logFn = logFn,
};
// zlog defaultLog function replacement, which adjusts the surrounding contents of every std.log message.
fn logFn(
comptime message_level: std.log.Level,
comptime scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
// TODO: provide build time configuration to allow tweaking corresponding output
// - add timestamp to all log messages
// - change output file for writing messages to (default `stderr`)
// TODO: improve formatting output, such that the resulting log has a good feel
// - should there be indenting?
// - should there be spacing?
// - should the messages be aligned (left, center, right)?
const level_txt = comptime message_level.asText();
const prefix2 = if (scope == .default) ":\t" else "(" ++ @tagName(scope) ++ "):\t";
const stderr = std.io.getStdErr().writer();
var bw = std.io.bufferedWriter(stderr);
const writer = bw.writer();
std.debug.lockStdErr();
defer std.debug.unlockStdErr();
nosuspend {
writer.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;
bw.flush() catch return;
}
}
pub fn generic_format(object: anytype, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
const Object = @TypeOf(object);
const object_info = @typeInfo(Object);
switch (object_info) {
.Struct => |s| {
try writer.writeAll(@typeName(Object));
try writer.writeAll(" = {\n");
inline for (s.fields) |field| {
try writer.writeAll("\t .");
try writer.writeAll(field.name);
try writer.writeAll(" = ");
// TODO check corresponding type and try to adapt fmt accordingly!
try std.fmt.format(writer, "{any}", .{@field(object, field.name)});
try writer.writeAll(",\n");
}
try writer.writeAll("}");
},
else => {},
}
}
pub fn enhance_format(comptime object: type) type {
// TODO: append a function to the type if it is a user defined type
// NOTE: this has the clear disadvantage that the type is not the same anymore! (but maybe this is still fine)
const object_info = @typeInfo(object);
switch (object_info) {
.Struct => |s| {
return @Type(.{
.Struct = .{
.layout = .auto,
.fields = s.fields,
.decls = s.decls,
.is_tuple = false,
},
});
},
else => {},
}
return object;
}