authorgravatar for quae@daurnimator.comdaurnimator <quae@daurnimator.com> 2019-04-23 00:43:23+10:00
committergravatar for quae@daurnimator.comdaurnimator <quae@daurnimator.com> 2019-04-27 15:36:53+10:00
logad7927a7486123b61221746b43cb0936fa5c71c0
tree6d95837014b9ebf3e543d4862fc74d4bff37f5a1
parentd02489fd9a56588bad800afcc18fc58b07f19b56
signaturelock-open Commit is signed but in an unrecognized format.

std: add LoggingAllocator prototype


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

std/heap.zig+47
...@@ -565,6 +565,53 @@ pub fn StackFallbackAllocator(comptime size: usize) type {...@@ -565,6 +565,53 @@ pub fn StackFallbackAllocator(comptime size: usize) type {
565 };565 };
566}566}
567567
568pub const NoErrorOutStream = std.io.OutStream(error{});
569pub const LoggingAllocator = struct {
570 allocator: Allocator,
571 parentAllocator: *Allocator,
572 outStream: *NoErrorOutStream,
573
574 const Self = @This();
575
576 pub fn init(parentAllocator: *Allocator, outStream: *NoErrorOutStream) Self {
577 return Self{
578 .allocator = Allocator{
579 .reallocFn = realloc,
580 .shrinkFn = shrink,
581 },
582 .parentAllocator = parentAllocator,
583 .outStream = outStream,
584 };
585 }
586
587 fn realloc(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
588 const self = @fieldParentPtr(Self, "allocator", allocator);
589 if (old_mem.len == 0) {
590 self.outStream.print("allocation of {} ", new_size) catch unreachable;
591 } else {
592 self.outStream.print("resize from {} to {} ", old_mem.len, new_size) catch unreachable;
593 }
594 const result = self.parentAllocator.reallocFn(self.parentAllocator, old_mem, old_align, new_size, new_align);
595 if (result) |buff| {
596 self.outStream.print("success!\n") catch unreachable;
597 } else |err| {
598 self.outStream.print("failure!\n") catch unreachable;
599 }
600 return result;
601 }
602
603 fn shrink(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
604 const self = @fieldParentPtr(Self, "allocator", allocator);
605 const result = self.parentAllocator.shrinkFn(self.parentAllocator, old_mem, old_align, new_size, new_align);
606 if (new_size == 0) {
607 self.outStream.print("free of {} bytes success!\n", old_mem.len) catch unreachable;
608 } else {
609 self.outStream.print("shrink from {} bytes to {} bytes success!\n", old_mem.len, new_size) catch unreachable;
610 }
611 return result;
612 }
613};
614
568test "c_allocator" {615test "c_allocator" {
569 if (builtin.link_libc) {616 if (builtin.link_libc) {
570 var slice = try c_allocator.alloc(u8, 50);617 var slice = try c_allocator.alloc(u8, 50);