Type `Slot<T>` of storage space for type `T`


#1

I wish to define a type Slot<T> of storage space for type T so Slot<T>: Copy and (mem::size_of::<Slot<T>>(), mem::align_of::<Slot<T>>()) == (mem::size_of::<T>(), mem::align_of::<T>()).

I tried this:

#![feature(intrinsics)]

extern "rust-intrinsic" {
    fn size_of<T>() -> usize;
}

struct Slot<T>([T; 0], [u8; size_of::<T>()]);

but the compiler says this:

error: array length constant evaluation error: non-constant path in constant expression [E0250]

Can i somehow define such a type? My use cases are these:

  • Define some collection types, e.g. B-nodes, more easily, with [Slot<T>] rather than *T
  • Let caller of a collection type pass in the uninitialized storage space safely rather than have the callee allocate it dynamically or pass it a &mut [u8] whose length may not be a multiple of size_of::<T>()

and such a type would enable them all.


#2

I think that is type level numbers. Which is a priority feature waiting on MIR. In the meantime https://crates.io/crates/typenum may work.


#3

The difficulty is, i have no way to find the size of a type as an Unsigned.

What i did would actually work if the size_of intrinsic were a const fn, but alas, it’s not.

I merely hoped someone might have some trick to define this before then.