| ... | @@ -713,6 +713,53 @@ pub fn StackFallbackAllocator(comptime size: usize) type { | ... | @@ -713,6 +713,53 @@ pub fn StackFallbackAllocator(comptime size: usize) type { |
| 713 | }; | 713 | }; |
| 714 | } | 714 | } |
| 715 | | 715 | |
| | 716 | pub const NoErrorOutStream = std.io.OutStream(error{}); |
| | 717 | pub 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 | |
| 716 | test "c_allocator" { | 763 | test "c_allocator" { |
| 717 | if (builtin.link_libc) { | 764 | if (builtin.link_libc) { |
| 718 | var slice = try c_allocator.alloc(u8, 50); | 765 | var slice = try c_allocator.alloc(u8, 50); |