aboutsummaryrefslogtreecommitdiff
path: root/lib/std/debug/failing_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/debug/failing_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/debug/failing_allocator.zig')
-rw-r--r--lib/std/debug/failing_allocator.zig65
1 files changed, 65 insertions, 0 deletions
diff --git a/lib/std/debug/failing_allocator.zig b/lib/std/debug/failing_allocator.zig
new file mode 100644
index 0000000000..5776d23194
--- /dev/null
+++ b/lib/std/debug/failing_allocator.zig
@@ -0,0 +1,65 @@
+const std = @import("../std.zig");
+const mem = std.mem;
+
+/// Allocator that fails after N allocations, useful for making sure out of
+/// memory conditions are handled correctly.
+pub const FailingAllocator = struct {
+ allocator: mem.Allocator,
+ index: usize,
+ fail_index: usize,
+ internal_allocator: *mem.Allocator,
+ allocated_bytes: usize,
+ freed_bytes: usize,
+ allocations: usize,
+ deallocations: usize,
+
+ pub fn init(allocator: *mem.Allocator, fail_index: usize) FailingAllocator {
+ return FailingAllocator{
+ .internal_allocator = allocator,
+ .fail_index = fail_index,
+ .index = 0,
+ .allocated_bytes = 0,
+ .freed_bytes = 0,
+ .allocations = 0,
+ .deallocations = 0,
+ .allocator = mem.Allocator{
+ .reallocFn = realloc,
+ .shrinkFn = shrink,
+ },
+ };
+ }
+
+ fn realloc(allocator: *mem.Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
+ const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);
+ if (self.index == self.fail_index) {
+ return error.OutOfMemory;
+ }
+ const result = try self.internal_allocator.reallocFn(
+ self.internal_allocator,
+ old_mem,
+ old_align,
+ new_size,
+ new_align,
+ );
+ if (new_size < old_mem.len) {
+ self.freed_bytes += old_mem.len - new_size;
+ if (new_size == 0)
+ self.deallocations += 1;
+ } else if (new_size > old_mem.len) {
+ self.allocated_bytes += new_size - old_mem.len;
+ if (old_mem.len == 0)
+ self.allocations += 1;
+ }
+ self.index += 1;
+ return result;
+ }
+
+ fn shrink(allocator: *mem.Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
+ const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);
+ const r = self.internal_allocator.shrinkFn(self.internal_allocator, old_mem, old_align, new_size, new_align);
+ self.freed_bytes += old_mem.len - r.len;
+ if (new_size == 0)
+ self.deallocations += 1;
+ return r;
+ }
+};