Skip to content

Commit 66108be

Browse files
committed
Reduce (unsafe) code with array::map and pointers
1 parent d3f1968 commit 66108be

File tree

1 file changed

+7
-20
lines changed

1 file changed

+7
-20
lines changed

src/map.rs

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -498,29 +498,16 @@ where
498498
}
499499
}
500500

501-
// Replace with MaybeUninit::uninit_array when that is stable
502-
// SAFETY: Creating MaybeUninit from uninit is always safe
503-
#[allow(unsafe_code)]
504-
let mut out: [std::mem::MaybeUninit<&'a mut V>; N] =
505-
unsafe { std::mem::MaybeUninit::uninit().assume_init() };
506-
507501
let entries = self.as_entries_mut();
508-
for (elem, idx) in out.iter_mut().zip(indices) {
509-
let v: &mut V = &mut entries[idx].value;
510-
// SAFETY: As we know that each index is unique, it is OK to discard the mutable
511-
// borrow lifetime of v, we will never mutably borrow an element twice.
512-
// The pointer is valid and aligned as we get it from MaybeUninit.
502+
let out = indices.map(|i| {
503+
// SAFETY: OK to discard mutable borrow lifetime as each index is unique
513504
#[allow(unsafe_code)]
514-
unsafe { std::ptr::write(elem.as_mut_ptr(), &mut *(v as *mut V)) };
515-
}
505+
unsafe {
506+
&mut *(&mut entries[i].value as *mut V)
507+
}
508+
});
516509

517-
// Can't transmute a const-sized array:
518-
// https://github.com/rust-lang/rust/issues/61956
519-
// This is the workaround.
520-
// SAFETY: This is fine as the references all are from unique entries that we own and all of
521-
// them have been properly initialized by the above loop.
522-
#[allow(unsafe_code)]
523-
Some(unsafe { std::mem::transmute_copy::<_, [&'a mut V; N]>(&out) })
510+
Some(out)
524511
}
525512

526513
/// Remove the key-value pair equivalent to `key` and return

0 commit comments

Comments
 (0)