diff --git a/lib/std/mem/Allocator.zig b/lib/std/mem/Allocator.zig index 1b63cc6a0f7ea2305c8ce1f394eccb6136ffd877..43db84febd6f222ef617d48bb136fd46abee2f9d 100644 --- a/lib/std/mem/Allocator.zig +++ b/lib/std/mem/Allocator.zig @@ -168,14 +168,35 @@ pub inline fn rawFree(a: Allocator, memory: []u8, alignment: Alignment, ret_addr /// Returns a pointer to undefined memory. /// Call `destroy` with the result to free the memory. pub fn create(a: Allocator, comptime T: type) Error!*T { + return a.createAdvancedWithRetAddr(T, null, @returnAddress()); +} + +pub fn alignedCreate( + self: Allocator, + comptime T: type, + /// null means naturally aligned + comptime alignment: ?Alignment, +) Error!*align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T { + return self.createAdvancedWithRetAddr(T, alignment, @returnAddress()); +} + +pub inline fn createAdvancedWithRetAddr( + self: Allocator, + comptime T: type, + /// null means naturally aligned + comptime alignment: ?Alignment, + return_address: usize, +) Error!*align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T { if (@sizeOf(T) == 0) { const ptr = comptime std.mem.alignBackward(usize, math.maxInt(usize), @alignOf(T)); return @ptrFromInt(ptr); } - const ptr: *T = @ptrCast(try a.allocBytesAligned(.of(T), @sizeOf(T), @returnAddress())); + const a: Alignment = alignment orelse comptime .of(T); + const ptr: *align(a.toByteUnits()) T = @ptrCast(try self.allocBytesAligned(a, @sizeOf(T), return_address)); return ptr; } + /// `ptr` should be the return value of `create`, or otherwise /// have the same address and alignment property. pub fn destroy(self: Allocator, ptr: anytype) void { diff --git a/lib/std/zon/parse.zig b/lib/std/zon/parse.zig index bd9281267a160c5636225aa06988036f76823325..4585d111a842c7bc118c30d8e2b3da25324c33fc 100644 --- a/lib/std/zon/parse.zig +++ b/lib/std/zon/parse.zig @@ -473,11 +473,10 @@ const Parser = struct { // If the existing value is initialized and non const, use it if (initialized and !pointer.attrs.@"const") break :b out.*; // Otherwise, allocate new memory - const new = &(try self.arena.alignedAlloc( + const new = try self.arena.alignedCreate( pointer.child, if (pointer.attrs.@"align") |a| .fromByteUnits(a) else null, - 1, - ))[0]; + ); // If the original value was initialized, dupe it into the new memory if (initialized) new.* = out.*.*; break :b new;