Skip to content

Commit bf88550

Browse files
committed
Reduce unsafe scope with Iter/IterMut
1 parent a2ce876 commit bf88550

File tree

1 file changed

+8
-16
lines changed

1 file changed

+8
-16
lines changed

library/core/src/slice/iter/macros.rs

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -471,23 +471,15 @@ macro_rules! iterator {
471471
#[unstable(feature = "peekable_iterator", issue = "132973")]
472472
impl<'a, T> PeekableIterator for $name<'a, T> {
473473
fn peek_with<U>(&mut self, func: impl for<'b> FnOnce(Option<&'b Self::Item>) -> U) -> U {
474-
let end_or_len = self.end_or_len;
475474

476-
// SAFETY: See inner comments.
477-
unsafe {
478-
if T::IS_ZST {
479-
let len = end_or_len.addr();
480-
if len == 0 {
481-
return func(None);
482-
}
483-
} else {
484-
if self.ptr == crate::intrinsics::transmute::<$ptr, NonNull<T>>(end_or_len) {
485-
return func(None);
486-
}
487-
}
488-
// SAFETY: Now that we know it wasn't empty
489-
// we can give out a reference to it.
490-
func(Some(self.ptr.$into_ref()).as_ref())
475+
if len!(self) == 0 {
476+
func(None)
477+
} else {
478+
// SAFETY: element within bounds as len > 0
479+
// Reference is dropped after the closure completes
480+
// and can not outlive the mutable borrow of self
481+
let tmp = unsafe { & $( $mut_ )? *self.ptr.as_ptr() };
482+
func(Some(tmp).as_ref())
491483
}
492484
}
493485
}

0 commit comments

Comments
 (0)