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

Topic: MaybeUninit arrays


DutchGhost (Jul 19 2019 at 19:49, on Zulip):

Im unsure what the difference between a MaybeUninit<[T; N]> and a [MaybeUninit<T>; N] is.
What I understand is that the latter is preferred when dealing with partial arrays, however the ArrayVec crate uses the former, but also deals with partial arrays. (https://github.com/bluss/arrayvec/blob/master/src/lib.rs#L95)

And, is this okey to do?:

let mut array: MaybeUninit<[T; 10]> = MaybeUninit::uninit();
let ptr: *mut T = array.as_mut_ptr() as *mut T // <--- cast to *mut T, since the ptr() method gives *mut [T; 10]
ptr.write(some_value)

Notice the array within the MaybeUninit is never really initialized, but is still written to.

RalfJ (Jul 20 2019 at 11:05, on Zulip):

Im unsure what the difference between a MaybeUninit<[T; N]> and a [MaybeUninit<T>; N] is.

Good question! There isn't really any.

RalfJ (Jul 20 2019 at 11:05, on Zulip):

If we had const generics, we might want to add methods to freely convert between the two.

RalfJ (Jul 20 2019 at 11:05, on Zulip):

transmuting between the two is okay for any T and N

RalfJ (Jul 20 2019 at 11:06, on Zulip):

And, is this okey to do?

yes. ptr.write on uninitialized memory is okay. having to do a raw ptr cast is not nice (IMO those should be frowned upon as much as transmute), but cannot always be avoided with our current APIs.

Last update: Nov 19 2019 at 18:05UTC