#alloc.destroy()'ing an *anyopaque

1 messages · Page 1 of 1 (latest)

charred imp
#

I've been stuck on this for a minute.

I have an entity struct that's similar to

struct {
  inner: *anyopaque,
  alignment: u8, // power of 2

  pub fn init(data: anytype) @This() {
    const data_ptr = alloc.create(@TypeOf(data)) catch @panic("oom"); // create space for a copy
    @memcpy(std.mem.asBytes(data_ptr), std.mem.asBytes(&data)); // copies data into data_ptr

    return @This() {
      inner = @ptrcast(data_ptr), // typed* -> opaque*
      alignment: @alignOf(@TypeOf(data)), // power of 2
    }
  }

  pub fn deinit(this: *@This()) void {
    // ?
  }
}

I alloc.create, but how do I alloc.destroy from the *anyopaque? The documentation for alloc.destroy mentions it only needs a ptr and the alignment but I can't figure out how to make the needed aligned pointer. std.mem.alignPointer() didn't work out for me because it requires a many item pointer

Any help would be appreciated :)

chilly lark
#

If you look at Allocator.VTable.free, you'll see that differently from C's free, the former needs the size. So I'd consider storing the size in your struct and allocating/decallocating a number of bytes.

charred imp
#

I'm assuming you mean to allocate enough bytes to fit whatever data, save the size of those bytes, then just deallocate the number of bytes?

#

that worked flawlessly

#

thank you :)

chilly lark
#

Another option would be to store a pointer to the destruction function (generated per @TypeOf(data)) in your struct and call that function. Then you still can simply call create/destroy and don't need to explicitly bother with alignment.

charred imp
#

i've seen that used somewhere in the std lib