Skip to content

Commit 29ca03d

Browse files
committed
Avoid use of unsafe in pop_if
1 parent 1f83ed2 commit 29ca03d

File tree

2 files changed

+13
-13
lines changed

2 files changed

+13
-13
lines changed

Diff for: library/alloc/src/vec/mod.rs

+2-13
Original file line numberDiff line numberDiff line change
@@ -2079,19 +2079,8 @@ impl<T, A: Allocator> Vec<T, A> {
20792079
where
20802080
F: FnOnce(&mut T) -> bool,
20812081
{
2082-
if self.len == 0 {
2083-
return None;
2084-
}
2085-
2086-
// SAFETY: the vector is not empty
2087-
let mut last = unsafe { ptr::read(self.as_ptr().add(self.len() - 1)) };
2088-
2089-
if f(&mut last) {
2090-
self.len -= 1;
2091-
Some(last)
2092-
} else {
2093-
None
2094-
}
2082+
let last = self.last_mut()?;
2083+
if f(last) { self.pop() } else { None }
20952084
}
20962085

20972086
/// Moves all the elements of `other` into `self`, leaving `other` empty.

Diff for: library/alloc/tests/vec.rs

+11
Original file line numberDiff line numberDiff line change
@@ -2663,6 +2663,17 @@ fn test_pop_if_empty() {
26632663
assert!(v.is_empty());
26642664
}
26652665

2666+
#[test]
2667+
fn test_pop_if_mutates() {
2668+
let mut v = vec![1];
2669+
let pred = |x: &mut i32| {
2670+
*x += 1;
2671+
false
2672+
};
2673+
assert_eq!(v.pop_if(pred), None);
2674+
assert_eq!(v, [2]);
2675+
}
2676+
26662677
/// This assortment of tests, in combination with miri, verifies we handle UB on fishy arguments
26672678
/// in the stdlib. Draining and extending the allocation are fairly well-tested earlier, but
26682679
/// `vec.insert(usize::MAX, val)` once slipped by!

0 commit comments

Comments
 (0)