Skip to content

Commit 2183237

Browse files
committed
Swap order of forget
Add pub and rm guard impl Add explicit type to guard Add safety note Change guard type from T to S It should never have been T, as it guards over [MaybeUninit<S>; N] Also add feature to test
1 parent 1d768db commit 2183237

File tree

2 files changed

+6
-10
lines changed

2 files changed

+6
-10
lines changed

library/core/src/array/mod.rs

+5-10
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ impl<T, const N: usize> [T; N] {
377377
/// assert_eq!(y, [2,3,4]);
378378
/// ```
379379
#[unstable(feature = "array_map", issue = "77777")]
380-
fn map<F, S>(self, mut f: F) -> [S; N]
380+
pub fn map<F, S>(self, mut f: F) -> [S; N]
381381
where
382382
F: FnMut(T) -> S,
383383
{
@@ -387,12 +387,6 @@ impl<T, const N: usize> [T; N] {
387387
curr_init: usize,
388388
}
389389

390-
impl<T, const N: usize> Guard<T, N> {
391-
fn new(dst: &mut [MaybeUninit<T>; N]) -> Self {
392-
Guard { dst: dst as *mut _ as *mut T, curr_init: 0 }
393-
}
394-
}
395-
396390
impl<T, const N: usize> Drop for Guard<T, N> {
397391
fn drop(&mut self) {
398392
debug_assert!(self.curr_init <= N);
@@ -407,15 +401,16 @@ impl<T, const N: usize> [T; N] {
407401
}
408402
}
409403
let mut dst = MaybeUninit::uninit_array::<N>();
410-
let mut guard = Guard::new(&mut dst);
404+
let mut guard: Guard<S, N> = Guard { dst: &mut dst as *mut _ as *mut S, curr_init: 0 };
411405
for (i, e) in IntoIter::new(self).enumerate() {
412406
dst[i] = MaybeUninit::new(f(e));
413407
guard.curr_init += 1;
414408
}
415409
// FIXME convert to crate::mem::transmute when works with generics
416410
// unsafe { crate::mem::transmute::<[MaybeUninit<S>; N], [S; N]>(dst) }
417-
let mapped = unsafe { (&mut dst as *mut _ as *mut [S; N]).read() };
418411
crate::mem::forget(guard);
419-
mapped
412+
// SAFETY: At this point we've properly initialized the whole array
413+
// and we just need to cast it to the correct type
414+
unsafe { (&mut dst as *mut _ as *mut [S; N]).read() }
420415
}
421416
}

library/core/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#![feature(alloc_layout_extra)]
22
#![feature(array_chunks)]
3+
#![feature(array_map)]
34
#![feature(bool_to_option)]
45
#![feature(bound_cloned)]
56
#![feature(box_syntax)]

0 commit comments

Comments
 (0)