From d7333d8798a929312ceb897007e7bb6a8b2999ee Mon Sep 17 00:00:00 2001 From: daurnimator Date: Thu, 9 Jan 2020 16:37:29 +1100 Subject: [PATCH] std: fix LoggingAllocator, add simple test --- lib/std/heap.zig | 4 ++++ lib/std/heap/logging_allocator.zig | 29 +++++++++++++++++++++++------ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/lib/std/heap.zig b/lib/std/heap.zig index 015f64e471..f25d2f0172 100644 --- a/lib/std/heap.zig +++ b/lib/std/heap.zig @@ -1063,3 +1063,7 @@ fn testAllocatorAlignedShrink(allocator: *mem.Allocator) mem.Allocator.Error!voi testing.expect(slice[0] == 0x12); testing.expect(slice[60] == 0x34); } + +test "heap" { + _ = @import("heap/logging_allocator.zig"); +} diff --git a/lib/std/heap/logging_allocator.zig b/lib/std/heap/logging_allocator.zig index c1f09a1aad..d1b7f4776d 100644 --- a/lib/std/heap/logging_allocator.zig +++ b/lib/std/heap/logging_allocator.zig @@ -27,15 +27,15 @@ pub const LoggingAllocator = struct { fn realloc(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 { const self = @fieldParentPtr(Self, "allocator", allocator); if (old_mem.len == 0) { - self.out_stream.print("allocation of {} ", new_size) catch {}; + self.out_stream.print("allocation of {} ", .{new_size}) catch {}; } else { - self.out_stream.print("resize from {} to {} ", old_mem.len, new_size) catch {}; + self.out_stream.print("resize from {} to {} ", .{ old_mem.len, new_size }) catch {}; } const result = self.parent_allocator.reallocFn(self.parent_allocator, old_mem, old_align, new_size, new_align); if (result) |buff| { - self.out_stream.print("success!\n") catch {}; + self.out_stream.print("success!\n", .{}) catch {}; } else |err| { - self.out_stream.print("failure!\n") catch {}; + self.out_stream.print("failure!\n", .{}) catch {}; } return result; } @@ -44,10 +44,27 @@ pub const LoggingAllocator = struct { const self = @fieldParentPtr(Self, "allocator", allocator); const result = self.parent_allocator.shrinkFn(self.parent_allocator, old_mem, old_align, new_size, new_align); if (new_size == 0) { - self.out_stream.print("free of {} bytes success!\n", old_mem.len) catch {}; + self.out_stream.print("free of {} bytes success!\n", .{old_mem.len}) catch {}; } else { - self.out_stream.print("shrink from {} bytes to {} bytes success!\n", old_mem.len, new_size) catch {}; + self.out_stream.print("shrink from {} bytes to {} bytes success!\n", .{ old_mem.len, new_size }) catch {}; } return result; } }; + +test "LoggingAllocator" { + var buf: [255]u8 = undefined; + var slice_stream = std.io.SliceOutStream.init(buf[0..]); + const stream = &slice_stream.stream; + + const allocator = &LoggingAllocator.init(std.heap.page_allocator, @ptrCast(*AnyErrorOutStream, stream)).allocator; + + const ptr = try allocator.alloc(u8, 10); + allocator.free(ptr); + + std.testing.expectEqualSlices(u8, + \\allocation of 10 success! + \\free of 10 bytes success! + \\ + , slice_stream.getWritten()); +}