Closed TimDiekmann closed 4 years ago
I don't think this is the right abstraction for the AllocRef
trait. Your proposed API seems primarily aimed at array-like allocations, but most of the capacity-based allocation logic should be handled by RawVec
instead of messing with the generic allocation API.
As a person who has made some simple custom data structures myself, I would not use any of this myself.
That doesn't make is definitely bad, just that I would retain maximum control on my side of things and compute a Layout value myself.
Actually, even Layout is an awkward and poor type to use, but it's what we've got, so oh well.
I'm pretty happy with the current Layout
type, it describes exactly what information needs to be passed to an allocator: the size of a block of memory and its alignment.
Like @Amanieu, I feel that this focuses too much on a particular use case, while adding a lot of complexity. The Layout
is a simple yet versatile solution to the same(?) problem.
Allocating currently is based on a size in bytes and an alignment. For a given type
T
align
is simply the alignment ofT
in most cases andsize
is a multiple of the size ofT
. More exotic layouts can be constructed with a[repr(align(...))]
struct containing[u8; N]
. CurrentlyLayout
looks like this:size
is a multiple ofmem::size_of::<T>()
and align is almost alwaysmem::align_of::<T>()
. If we would addT
to this struct, we could simply removealign
, soLayout
would look like this (Renamed toMemoryLayout
asLayout
is stable. AlsoMemoryLayout
is more describtive.):We want
mem::size_of::<Option<MemoryLayout<T>>>() == mem::size_of::<MemoryLayout<T>>()
. Do we really need a layout with zero capacity? We have allowed ZSTs inAllocRef
, which is fine, but I really don't think we need to support zeroed-capacity allocations.AllocRef
has to support unsized types to deallocateBox<T: !Sized>
, this must be changed toMemoryLayout<T: ?Sized>
, butsize_of
andalign_of
requiresT: Sized
so we need to store the alignment forT: !Sized
. Also we can't usecapacity
, as we don't know the size ofT
but we can still usesize
instead.Okay, thats the same as
Layout
. However we can abuse the layout of pointers:T: Sized
pointers are 8 bytes wide,T: !Sized
are 16 bytes wide, a fat pointer. Putting everything in one struct:Now we have to interpret the data. For
T: Sized
T: Sized
:T: !Sized
:Then we just change
MemoryLayout
toand wrap the different functions. Our layout is now capacity-based for sized types.
I think this is a pretty big deal, as we halfed the size of
Layout
which is regularly used in the allocator API (for sized types, which is almost always the case. For unsized types nothing changes).