Skip to content

Instantly share code, notes, and snippets.

@miquels
Last active March 6, 2026 13:13
Show Gist options
  • Select an option

  • Save miquels/b703cbcc8246463e916f2268e7534101 to your computer and use it in GitHub Desktop.

Select an option

Save miquels/b703cbcc8246463e916f2268e7534101 to your computer and use it in GitHub Desktop.
In-place box construction

The Rust Box::new(X) method first creates X on the stack, then allocates memory and copies X from the stack to the heap. That is very wasteful if X is large.

Now, it turns out that there is a compiler intrinsic that you can use to allocate a Box and initialize it right on the heap. It's not directly exposed via the standard library, but it is used by the vec! macro here.

So you can use vec! to initialize structures right on the stack. But what if you wanted a Box and not a Vec? Use this macro:

macro_rules! boxed {
    ($e:expr) => {{
        // SAFETY: 
        // 1. into_boxed_slice() ensures the allocation is exactly for 1 element.
        // 2. T and [T; 1] have identical alignment.
        // 3. We strip the slice metadata (length) to create a thin Box<T>.
        let boxed_slice = vec![$e].into_boxed_slice();
        fn __transmute<T>(from: Box<[T]>) -> Box<T> {
            assert_eq!(from.len(), 1, "Must have exactly one element");
            unsafe { Box::from_raw(Box::into_raw(from) as *mut T) }
        }
        __transmute(boxed_slice)
    }}
}

NOTE: this only works in release mode, in debug mode it still copies from the stack.

Link to playground, allocating 100MB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment