authorgravatar for quae@daurnimator.comdaurnimator <quae@daurnimator.com> 2020-01-09 16:37:29+11:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-01-09 13:34:46-05:00
logd7333d8798a929312ceb897007e7bb6a8b2999ee
tree5f607d8c6d3fbaeb89ad223ed653293ae8a6673e
parent27b290f3125b2526200bad4a818f9f43ba58ee2e

std: fix LoggingAllocator, add simple test


2 files changed, 27 insertions(+), 6 deletions(-)

lib/std/heap.zig+4
......@@ -1063,3 +1063,7 @@ fn testAllocatorAlignedShrink(allocator: *mem.Allocator) mem.Allocator.Error!voi
10631063 testing.expect(slice[0] == 0x12);
10641064 testing.expect(slice[60] == 0x34);
10651065}
1066
1067test "heap" {
1068 _ = @import("heap/logging_allocator.zig");
1069}
lib/std/heap/logging_allocator.zig+23-6
......@@ -27,15 +27,15 @@ pub const LoggingAllocator = struct {
2727 fn realloc(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
2828 const self = @fieldParentPtr(Self, "allocator", allocator);
2929 if (old_mem.len == 0) {
30 self.out_stream.print("allocation of {} ", new_size) catch {};
30 self.out_stream.print("allocation of {} ", .{new_size}) catch {};
3131 } else {
32 self.out_stream.print("resize from {} to {} ", old_mem.len, new_size) catch {};
32 self.out_stream.print("resize from {} to {} ", .{ old_mem.len, new_size }) catch {};
3333 }
3434 const result = self.parent_allocator.reallocFn(self.parent_allocator, old_mem, old_align, new_size, new_align);
3535 if (result) |buff| {
36 self.out_stream.print("success!\n") catch {};
36 self.out_stream.print("success!\n", .{}) catch {};
3737 } else |err| {
38 self.out_stream.print("failure!\n") catch {};
38 self.out_stream.print("failure!\n", .{}) catch {};
3939 }
4040 return result;
4141 }
......@@ -44,10 +44,27 @@ pub const LoggingAllocator = struct {
4444 const self = @fieldParentPtr(Self, "allocator", allocator);
4545 const result = self.parent_allocator.shrinkFn(self.parent_allocator, old_mem, old_align, new_size, new_align);
4646 if (new_size == 0) {
47 self.out_stream.print("free of {} bytes success!\n", old_mem.len) catch {};
47 self.out_stream.print("free of {} bytes success!\n", .{old_mem.len}) catch {};
4848 } else {
49 self.out_stream.print("shrink from {} bytes to {} bytes success!\n", old_mem.len, new_size) catch {};
49 self.out_stream.print("shrink from {} bytes to {} bytes success!\n", .{ old_mem.len, new_size }) catch {};
5050 }
5151 return result;
5252 }
5353};
54
55test "LoggingAllocator" {
56 var buf: [255]u8 = undefined;
57 var slice_stream = std.io.SliceOutStream.init(buf[0..]);
58 const stream = &slice_stream.stream;
59
60 const allocator = &LoggingAllocator.init(std.heap.page_allocator, @ptrCast(*AnyErrorOutStream, stream)).allocator;
61
62 const ptr = try allocator.alloc(u8, 10);
63 allocator.free(ptr);
64
65 std.testing.expectEqualSlices(u8,
66 \\allocation of 10 success!
67 \\free of 10 bytes success!
68 \\
69 , slice_stream.getWritten());
70}