Commit d7333d8798

daurnimator <quae@daurnimator.com>
2020-01-09 06:37:29
std: fix LoggingAllocator, add simple test
1 parent 27b290f
Changed files (2)
lib/std/heap/logging_allocator.zig
@@ -27,15 +27,15 @@ pub const LoggingAllocator = struct {
     fn realloc(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
         const self = @fieldParentPtr(Self, "allocator", allocator);
         if (old_mem.len == 0) {
-            self.out_stream.print("allocation of {} ", new_size) catch {};
+            self.out_stream.print("allocation of {} ", .{new_size}) catch {};
         } else {
-            self.out_stream.print("resize from {} to {} ", old_mem.len, new_size) catch {};
+            self.out_stream.print("resize from {} to {} ", .{ old_mem.len, new_size }) catch {};
         }
         const result = self.parent_allocator.reallocFn(self.parent_allocator, old_mem, old_align, new_size, new_align);
         if (result) |buff| {
-            self.out_stream.print("success!\n") catch {};
+            self.out_stream.print("success!\n", .{}) catch {};
         } else |err| {
-            self.out_stream.print("failure!\n") catch {};
+            self.out_stream.print("failure!\n", .{}) catch {};
         }
         return result;
     }
@@ -44,10 +44,27 @@ pub const LoggingAllocator = struct {
         const self = @fieldParentPtr(Self, "allocator", allocator);
         const result = self.parent_allocator.shrinkFn(self.parent_allocator, old_mem, old_align, new_size, new_align);
         if (new_size == 0) {
-            self.out_stream.print("free of {} bytes success!\n", old_mem.len) catch {};
+            self.out_stream.print("free of {} bytes success!\n", .{old_mem.len}) catch {};
         } else {
-            self.out_stream.print("shrink from {} bytes to {} bytes success!\n", old_mem.len, new_size) catch {};
+            self.out_stream.print("shrink from {} bytes to {} bytes success!\n", .{ old_mem.len, new_size }) catch {};
         }
         return result;
     }
 };
+
+test "LoggingAllocator" {
+    var buf: [255]u8 = undefined;
+    var slice_stream = std.io.SliceOutStream.init(buf[0..]);
+    const stream = &slice_stream.stream;
+
+    const allocator = &LoggingAllocator.init(std.heap.page_allocator, @ptrCast(*AnyErrorOutStream, stream)).allocator;
+
+    const ptr = try allocator.alloc(u8, 10);
+    allocator.free(ptr);
+
+    std.testing.expectEqualSlices(u8,
+        \\allocation of 10 success!
+        \\free of 10 bytes success!
+        \\
+    , slice_stream.getWritten());
+}
lib/std/heap.zig
@@ -1063,3 +1063,7 @@ fn testAllocatorAlignedShrink(allocator: *mem.Allocator) mem.Allocator.Error!voi
     testing.expect(slice[0] == 0x12);
     testing.expect(slice[60] == 0x34);
 }
+
+test "heap" {
+    _ = @import("heap/logging_allocator.zig");
+}