Skip to content

Instantly share code, notes, and snippets.

@miquels
Last active June 21, 2021 07:26
Show Gist options
  • Save miquels/b703cbcc8246463e916f2268e7534101 to your computer and use it in GitHub Desktop.
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.

Simple macro that abuses vec! to do more or less the same as the copyless crate:

macro_rules! boxed {
    ($e:expr) => {{
        #[inline(always)]
        fn __transmute<T>(from: Box<[T]>) -> Box<T> {
            unsafe { Box::from_raw(Box::into_raw(from) as *mut T) }
        }
        __transmute(vec![ $e ].into_boxed_slice())
    }}
}

Godbolt: https://godbolt.org/z/dsYxjWMac

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