Box::take for taking the value out of a box without deallocating it (original) (raw)

Proposal

Problem statement

There's no provided way of taking the value out of a box without also deallocating the heap memory it owns. This could be useful to either defer deallocation to some other point in time, or to deallocate on a different thread, or to reuse that allocation for another boxed value (using Box::write).

Motivating examples or use cases

In message-oriented applications it's a fairly common practice to minimize the message enum type's size by boxing very large variants (see clippy::large_enum_variant). However, this currently isn't easily usable in realtime-constrained situations. A usecase could look like this:

enum RealtimeMessage { VeryLarge(Box), ... }

enum NonRealtimeMessage { Deallocate(Box<MaybeUninit>), ... }

match consumer.pop() { RealtimeMessage::VeryLarge(very_large) => { let (very_large, uninit) = Box::take(very_large); producer.push(NonRealtimeMessage::Deallocate(uninit)); ... } ... }

Solution sketch

impl Box { pub fn take(boxed: Box) -> (T, Box<MaybeUninit>); }

Alternatives