const Allocation in nightly rust

51 points Sp00ph

I recently stumbled upon three very interesting intrinsics while browsing docs.rs : const\_eval\_select, const\_allocate and const\_deallocate. Seeing those got me thinking, is it possible to get heap allocation and deallocation at compile time, like it is in C++20? As it turns out, it actually is:

Playground link

Though it is nightly only, and requires quite an impressive amount of nightly features enabled, using this code it is able to allocate and deallocate heap memory at compile time or runtime. It does this using const_eval_select which is similar to if (std::is_constant_evaluated()) in C++ (or if consteval in C++20). Essentially it wraps any allocator, and implements const Allocator just forwarding any calls at compile time to const_allocate or const_deallocate and forwarding calls at runtime to the wrapped allocator.

Now while I do think it is pretty cool, it's not all that useful right now, as there is still no way to use something like a Vec or another collection at compile time :(

Edit: Messed up the playground link lol, now it should actually work