#How to catch OutOfMemory errors when allocating?

1 messages · Page 1 of 1 (latest)

trim sparrow
#

Working through allocators and trying to figure out an error I'm getting:

const std = @import("std");
const expect = std.testing.expect;
const expectError = std.testing.expectError;

// allocates memory into a fixed buffer and does not make heap allocations
// throws OutOfMemory when runs out of bytes
test "fixed buffer allocator" {
  var buffer: [1000]u8 = undefined;
  var fba = std.heap.FixedBufferAllocator.init(&buffer);
  const allocator = fba.allocator();

  var i: usize = 0;
  while (i < 11) {
    const memory: error{OutOfMemory}![]u8 = allocator.alloc(u8, 100);
    if (memory) |m| {
      try expect(@TypeOf(m) == []u8);
    } else |err| {
      expectError(error.OutOfMemory, err);
      break;
    }
    i += 1;
  }
}

Getting this error:

error: expected error union type, found 'error{OutOfMemory}'
    if (actual_error_union) |actual_payload| {

Must be something trivial, but I'm just so new...

shell quartz
#
const memory: []u8 = allocator.alloc(u8, 100) catch |err| {
  expectError(error.OutOfMemory, err);
  break;
}
pine root
#

expectError takes an error union as the first argument

#

So solution is probably:

try expectError(@as(error{OutOfMemory}!void, error.OutOfMemory), err);
trim sparrow
#

hmm, neither of these worked

#

ty for the responses

shell quartz
#

Both together should work, I think

pine root
quasi pewter
#
test "fixed buffer allocator" {
    var buffer: [1000]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(buffer[0..]);
    const allocator = fba.allocator();

    var i: usize = 0;
    while (i < 11) : (i += 1) {
        const memory: []u8 = allocator.alloc(u8, 100) catch |err| {
            try expect(err == error.OutOfMemory);
            break;
        };
        _ = memory;
    }
}```