authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2019-06-27 11:20:00-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2019-06-27 11:20:00-04:00
logc346b257bba0b4f62c3a27970efa0a53894da6cf
treef058a0b5132a48a158596a6983205fe520f11d6b
parent516b5e649fa5f6c4043275b3dbe8e38273d79344
parentad7927a7486123b61221746b43cb0936fa5c71c0
signaturelock-open Commit is signed but in an unrecognized format.

Merge branch 'logging-allocator' of https://github.com/daurnimator/zig into daurnimator-logging-allocator


1 files changed, 47 insertions(+), 0 deletions(-)

std/heap.zig+47
......@@ -713,6 +713,53 @@ pub fn StackFallbackAllocator(comptime size: usize) type {
713713 };
714714}
715715
716pub const NoErrorOutStream = std.io.OutStream(error{});
717pub const LoggingAllocator = struct {
718 allocator: Allocator,
719 parentAllocator: *Allocator,
720 outStream: *NoErrorOutStream,
721
722 const Self = @This();
723
724 pub fn init(parentAllocator: *Allocator, outStream: *NoErrorOutStream) Self {
725 return Self{
726 .allocator = Allocator{
727 .reallocFn = realloc,
728 .shrinkFn = shrink,
729 },
730 .parentAllocator = parentAllocator,
731 .outStream = outStream,
732 };
733 }
734
735 fn realloc(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
736 const self = @fieldParentPtr(Self, "allocator", allocator);
737 if (old_mem.len == 0) {
738 self.outStream.print("allocation of {} ", new_size) catch unreachable;
739 } else {
740 self.outStream.print("resize from {} to {} ", old_mem.len, new_size) catch unreachable;
741 }
742 const result = self.parentAllocator.reallocFn(self.parentAllocator, old_mem, old_align, new_size, new_align);
743 if (result) |buff| {
744 self.outStream.print("success!\n") catch unreachable;
745 } else |err| {
746 self.outStream.print("failure!\n") catch unreachable;
747 }
748 return result;
749 }
750
751 fn shrink(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
752 const self = @fieldParentPtr(Self, "allocator", allocator);
753 const result = self.parentAllocator.shrinkFn(self.parentAllocator, old_mem, old_align, new_size, new_align);
754 if (new_size == 0) {
755 self.outStream.print("free of {} bytes success!\n", old_mem.len) catch unreachable;
756 } else {
757 self.outStream.print("shrink from {} bytes to {} bytes success!\n", old_mem.len, new_size) catch unreachable;
758 }
759 return result;
760 }
761};
762
716763test "c_allocator" {
717764 if (builtin.link_libc) {
718765 var slice = try c_allocator.alloc(u8, 50);