aboutsummaryrefslogtreecommitdiff
path: root/lib/std/heap/logging_allocator.zig
diff options
context:
space:
mode:
authorAndrew Kelley <andrew@ziglang.org>2019-09-26 01:54:45 -0400
committerGitHub <noreply@github.com>2019-09-26 01:54:45 -0400
commit68bb3945708c43109c48bda3664176307d45b62c (patch)
treeafb9731e10cef9d192560b52cd9ae2cf179775c4 /lib/std/heap/logging_allocator.zig
parent6128bc728d1e1024a178c16c2149f5b1a167a013 (diff)
parent4637e8f9699af9c3c6cf4df50ef5bb67c7a318a4 (diff)
downloadzig-68bb3945708c43109c48bda3664176307d45b62c.tar.gz
zig-68bb3945708c43109c48bda3664176307d45b62c.zip
Merge pull request #3315 from ziglang/mv-std-lib
Move std/ to lib/std/
Diffstat (limited to 'lib/std/heap/logging_allocator.zig')
-rw-r--r--lib/std/heap/logging_allocator.zig53
1 files changed, 53 insertions, 0 deletions
diff --git a/lib/std/heap/logging_allocator.zig b/lib/std/heap/logging_allocator.zig
new file mode 100644
index 0000000000..c1f09a1aad
--- /dev/null
+++ b/lib/std/heap/logging_allocator.zig
@@ -0,0 +1,53 @@
+const std = @import("../std.zig");
+const Allocator = std.mem.Allocator;
+
+const AnyErrorOutStream = std.io.OutStream(anyerror);
+
+/// This allocator is used in front of another allocator and logs to the provided stream
+/// on every call to the allocator. Stream errors are ignored.
+/// If https://github.com/ziglang/zig/issues/2586 is implemented, this API can be improved.
+pub const LoggingAllocator = struct {
+ allocator: Allocator,
+ parent_allocator: *Allocator,
+ out_stream: *AnyErrorOutStream,
+
+ const Self = @This();
+
+ pub fn init(parent_allocator: *Allocator, out_stream: *AnyErrorOutStream) Self {
+ return Self{
+ .allocator = Allocator{
+ .reallocFn = realloc,
+ .shrinkFn = shrink,
+ },
+ .parent_allocator = parent_allocator,
+ .out_stream = out_stream,
+ };
+ }
+
+ 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 {};
+ } else {
+ 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 {};
+ } else |err| {
+ self.out_stream.print("failure!\n") catch {};
+ }
+ return result;
+ }
+
+ fn shrink(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
+ 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 {};
+ } else {
+ self.out_stream.print("shrink from {} bytes to {} bytes success!\n", old_mem.len, new_size) catch {};
+ }
+ return result;
+ }
+};