Skip to content

Commit 49691b1

Browse files
committed
Auto merge of rust-lang#114370 - krtab:pop_assume_cap, r=scottmcm
Add invariant to Vec::pop that len < cap if pop successful Fixes: rust-lang#114334
2 parents a76ec18 + 0bcac8a commit 49691b1

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

library/alloc/src/vec/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1956,6 +1956,7 @@ impl<T, A: Allocator> Vec<T, A> {
19561956
} else {
19571957
unsafe {
19581958
self.len -= 1;
1959+
core::intrinsics::assume(self.len < self.capacity());
19591960
Some(ptr::read(self.as_ptr().add(self.len())))
19601961
}
19611962
}

tests/codegen/vec_pop_push_noop.rs

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// compile-flags: -O
2+
3+
#![crate_type = "lib"]
4+
5+
#[no_mangle]
6+
// CHECK-LABEL: @noop(
7+
pub fn noop(v: &mut Vec<u8>) {
8+
// CHECK-NOT: reserve_for_push
9+
// CHECK-NOT: call
10+
// CHECK: tail call void @llvm.assume
11+
// CHECK-NOT: reserve_for_push
12+
// CHECK-NOT: call
13+
// CHECK: ret
14+
if let Some(x) = v.pop() {
15+
v.push(x)
16+
}
17+
}
18+
19+
#[no_mangle]
20+
// CHECK-LABEL: @push_byte(
21+
pub fn push_byte(v: &mut Vec<u8>) {
22+
// CHECK: call {{.*}}reserve_for_push
23+
v.push(3);
24+
}

0 commit comments

Comments
 (0)