| ... | ... | @@ -565,6 +565,53 @@ pub fn StackFallbackAllocator(comptime size: usize) type { |
| 565 | 565 | }; |
| 566 | 566 | } |
| 567 | 567 | |
| 568 | pub const NoErrorOutStream = std.io.OutStream(error{}); |
| 569 | pub 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 | |
| 568 | 615 | test "c_allocator" { |
| 569 | 616 | if (builtin.link_libc) { |
| 570 | 617 | var slice = try c_allocator.alloc(u8, 50); |