Stream: t-lang/wg-unsafe-code-guidelines

Topic: Better support of Box> pattern.


Charles Lew (Aug 08 2019 at 15:58, on Zulip):

I think actually we're very close to providing a useful "placement new" mechanism, with Box<MaybeUnit<T>> pattern... Most of the things can be implemented at the library level, only with a few "primitives" needed.

Charles Lew (Aug 08 2019 at 15:59, on Zulip):

It's especially useful when T is a very big type. Instead of moving from stack to heap when constructing Box<T>, people can just build a Box<MaybeUnit<T>> somehow, initialize it somehow, and assume_init and call it done~

centril (Aug 08 2019 at 16:05, on Zulip):

@Charles Lew https://github.com/rust-lang/rust/pull/62451

Charles Lew (Aug 08 2019 at 16:05, on Zulip):

@centril Yay~~

Charles Lew (Aug 08 2019 at 16:06, on Zulip):

good to know, thx~

centril (Aug 08 2019 at 16:06, on Zulip):

np

gnzlbg (Aug 08 2019 at 17:23, on Zulip):

@Charles Lew do you have a library implementation ?

gnzlbg (Aug 08 2019 at 17:23, on Zulip):

I can imagine particular implementations for different use cases, but I wouldn't know how to write one that works even for the simple case of constructing a single value

gnzlbg (Aug 08 2019 at 17:26, on Zulip):

E.g. if I wanted to initialize a Box<[u32; N]> where N is big, I'd probably have some API like:

fn array_box<T, F: Fn(usize) -> T, const N: usize>(f: F) -> Box<[T; N]> {
    let mut b: Box<MaybeUninit<[T; N]>> = Box::new(MaybeUninit::uninit());
    let mut ptr = &mut *b as *mut _ as *mut T;
    for i in 0..N {  *(ptr.add(i)) = f(i); }
    b.assume_init()
}
gnzlbg (Aug 08 2019 at 17:27, on Zulip):

But that breaks if T is too big, like, another big array , so that you end up with Box<[[T; M]; N> where both M and N are big

gnzlbg (Aug 08 2019 at 17:28, on Zulip):

And if instead of a Box I want a Vec<[T; N]> I probably need something completely different

Charles Lew (Aug 08 2019 at 18:55, on Zulip):

@gnzlbg i dont have a library implementation. But i guess at least the non-generics cases are satisfied.

Charles Lew (Aug 08 2019 at 18:57, on Zulip):

i guess being generic over the "shape" of data is tricky.

Last update: Nov 20 2019 at 13:45UTC