authorgravatar for hi@whatisaph.onewhatisaphone <hi@whatisaph.one> 2025-08-31 10:30:51-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-09-03 21:46:01-07:00
logae518dcb41ac6a403f04939e0d119a8c4b3c9737
tree1afbd6a84e0df3a971a4f77782b263fb6886db71
parent76c62e509b31fa31a537da94966cbd2971dfa79b

Add allocator that always fails


1 files changed, 72 insertions(+), 0 deletions(-)

lib/std/mem/Allocator.zig+72
......@@ -81,6 +81,19 @@ pub const VTable = struct {
8181 free: *const fn (*anyopaque, memory: []u8, alignment: Alignment, ret_addr: usize) void,
8282};
8383
84pub fn noAlloc(
85 self: *anyopaque,
86 len: usize,
87 alignment: Alignment,
88 ret_addr: usize,
89) ?[*]u8 {
90 _ = self;
91 _ = len;
92 _ = alignment;
93 _ = ret_addr;
94 return null;
95}
96
8497pub fn noResize(
8598 self: *anyopaque,
8699 memory: []u8,
......@@ -445,3 +458,62 @@ pub fn dupeZ(allocator: Allocator, comptime T: type, m: []const T) Error![:0]T {
445458 new_buf[m.len] = 0;
446459 return new_buf[0..m.len :0];
447460}
461
462/// An allocator that always fails to allocate.
463pub const failing: Allocator = .{
464 .ptr = undefined,
465 .vtable = &.{
466 .alloc = noAlloc,
467 .resize = unreachableResize,
468 .remap = unreachableRemap,
469 .free = unreachableFree,
470 },
471};
472
473fn unreachableResize(
474 self: *anyopaque,
475 memory: []u8,
476 alignment: Alignment,
477 new_len: usize,
478 ret_addr: usize,
479) bool {
480 _ = self;
481 _ = memory;
482 _ = alignment;
483 _ = new_len;
484 _ = ret_addr;
485 unreachable;
486}
487
488fn unreachableRemap(
489 self: *anyopaque,
490 memory: []u8,
491 alignment: Alignment,
492 new_len: usize,
493 ret_addr: usize,
494) ?[*]u8 {
495 _ = self;
496 _ = memory;
497 _ = alignment;
498 _ = new_len;
499 _ = ret_addr;
500 unreachable;
501}
502
503fn unreachableFree(
504 self: *anyopaque,
505 memory: []u8,
506 alignment: Alignment,
507 ret_addr: usize,
508) void {
509 _ = self;
510 _ = memory;
511 _ = alignment;
512 _ = ret_addr;
513 unreachable;
514}
515
516test failing {
517 const f: Allocator = .failing;
518 try std.testing.expectError(error.OutOfMemory, f.alloc(u8, 123));
519}