In C++:
template<class T>
using buffer_t = std::aligned_buffer<sizeof(T), alignof(T)>;
After this sizeof(buffer_t) == sizeof(T)
and alignof(buffer_t) == alignof(T)
, but buffer_t
is just an array of char
's with the right alignment, suitable for doing a placement new of T
. I'm not sure how to accomplish the same in generic code in rust.
fn make_buffer<T>() -> [u8; std::mem::size_of::<T>()] {
[0; std::mem::size_of::<T>()]
}
Results in:
error: generic parameters may not be used in const operations
--> src/lib.rs:1:49
|
1 | fn make_buffer<T>() -> [u8; std::mem::size_of::<T>()] {
| ^ cannot perform const operation using `T`
|
I would also need the alignment to be correct, and I'm not sure how to do that at all because I really doubt #[repr(align(std::mem::align_of::<T>()))]
is gonna work.
My ultimate goal is I have a U: 'a
that I want to hold in a struct by value, but with the lifetime erased. If the struct directly stores U
it will get infected with the 'a
lifetime (this is for building new primitives with unsafe -- I use other mechanisms to enforce the data can't actually be used after drop). So I want to have an array of u8s with sufficient alignment as a struct field, and manually move the U: 'a
into that space by copying the bits. Then I can cast to hand out &U
with lifetime tied to my struct.