Add a logging allocator that uses std.log (#8511)

This commit is contained in:
Lee Cannon
2021-06-09 19:42:07 +01:00
committed by GitHub
parent 96c60bcca5
commit 629e2e7844
4 changed files with 232 additions and 51 deletions

View File

@@ -599,4 +599,50 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
\\emergency(c):
\\
);
// It is required to override the log function in order to print to stdout instead of stderr
cases.add("std.heap.LoggingAllocator logs to std.log",
\\const std = @import("std");
\\
\\pub const log_level: std.log.Level = .debug;
\\
\\pub fn main() !void {
\\ var allocator_buf: [10]u8 = undefined;
\\ var fixedBufferAllocator = std.mem.validationWrap(std.heap.FixedBufferAllocator.init(&allocator_buf));
\\ const allocator = &std.heap.loggingAllocator(&fixedBufferAllocator.allocator).allocator;
\\
\\ var a = try allocator.alloc(u8, 10);
\\ a = allocator.shrink(a, 5);
\\ try std.testing.expect(a.len == 5);
\\ try std.testing.expectError(error.OutOfMemory, allocator.resize(a, 20));
\\ allocator.free(a);
\\}
\\
\\pub fn log(
\\ comptime level: std.log.Level,
\\ comptime scope: @TypeOf(.EnumLiteral),
\\ comptime format: []const u8,
\\ args: anytype,
\\) void {
\\ const level_txt = switch (level) {
\\ .emerg => "emergency",
\\ .alert => "alert",
\\ .crit => "critical",
\\ .err => "error",
\\ .warn => "warning",
\\ .notice => "notice",
\\ .info => "info",
\\ .debug => "debug",
\\ };
\\ const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
\\ const stdout = std.io.getStdOut().writer();
\\ nosuspend stdout.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;
\\}
,
\\debug: alloc - success - len: 10, ptr_align: 1, len_align: 0
\\debug: shrink - success - 10 to 5, len_align: 0, buf_align: 1
\\critical: expand - failure: OutOfMemory - 5 to 20, len_align: 0, buf_align: 1
\\debug: free - success - len: 5
\\
);
}