pub const comptime_allocator: Allocator = .{ .ptr = undefined, .vtable = &.{ .alloc = &comptimeAlloc, .resize = &comptimeResize, .remap = &comptimeRemap, .free = &Allocator.noFree, }, }; fn comptimeAlloc(_: *anyopaque, len: usize, alignment: Alignment, ra: usize) ?[*]u8 { _ = ra; if (!@inComptime()) @panic("comptimeAlloc called at runtime"); var buf: [len]u8 align(alignment.toByteUnits()) = undefined; return &buf; } fn comptimeResize(_: *anyopaque, mem: []u8, alignment: Alignment, new_len: usize, ra: usize) bool { _ = alignment; _ = ra; if (!@inComptime()) @panic("comptimeResize called at runtime"); return new_len <= mem.len; // allow shrinking in-place } fn comptimeRemap(_: *anyopaque, mem: []u8, alignment: Alignment, new_len: usize, ra: usize) ?[*]u8 { _ = alignment; _ = ra; if (!@inComptime()) @panic("comptimeRemap called at runtime"); return if (new_len <= mem.len) mem.ptr else null; // allow shrinking in-place } comptime { var mal: std.MultiArrayList(struct { a: u32, b: u16 }) = .empty; defer mal.deinit(comptime_allocator); mal.append(comptime_allocator, .{ .a = 123, .b = 45 }) catch unreachable; mal.append(comptime_allocator, .{ .a = 456, .b = 99 }) catch unreachable; assert(mal.items(.a)[0] == 123); assert(mal.items(.a)[1] == 456); assert(mal.items(.b)[0] == 45); assert(mal.items(.b)[1] == 99); } comptime { // We can't use `AutoArrayHashMapUnmanaged` because `store_hash == false` breaks at comptime right now var map: std.ArrayHashMapUnmanaged(u32, u16, std.array_hash_map.AutoContext(u32), true) = .empty; defer map.deinit(comptime_allocator); map.put(comptime_allocator, 7, 123) catch unreachable; map.put(comptime_allocator, 99, 456) catch unreachable; assert(map.contains(7)); assert(map.contains(99)); assert(!map.contains(10)); assert(map.get(7).? == 123); assert(map.get(99).? == 456); } const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const Alignment = std.mem.Alignment;