What's the right way to destroy an array where you don't have the type specifically, but you have the alignment and size

Hmm interesting I’m trying to figure out how I can make that work for runtime. As the the alignment if I understand correctly can’t be changed, it’s part of the type.

Oh I suppose I can just allocate everything as if they were align 8. Like c style malloc behaviour. For release builds I just use malloc/free for this specific operation.

My current solution which satisfies the GPA is a comptime which properly casts it to the right type and frees it.

struct managed_allocation{
    data: []u8,
    destroyFn: *const fn (*anyopaque, std.mem.Allocator) void,

    pub fn create(T: type, allocator: std.mem.Allocator) @This() 
    { 
        const Wrap = struct {
            pub fn wrappedDestroy(ptr: *anyopaque, alloc: std.mem.Allocator) void {
                var p = @as(*T, @ptrCast(@alignCast(ptr)));
                alloc.destroy(p);
            }
        };
        return .{
              .data = <... allocator.create and a bunch of casting>, 
              .destroyFn = Wrap.wrappedDestroy,
        };
    }

    pub fn destroy(self: *@This(), allocator: std.mem.Allocator) void 
    {
         self.destroyFn(self.data.ptr, self.allocator);
    }
};
1 Like