Skip to content

Commit

Permalink
Add invariant to Vec::pop that len < cap if pop successful
Browse files Browse the repository at this point in the history
Fixes: #114334
  • Loading branch information
krtab committed Aug 4, 2023
1 parent f475098 commit 3ff159b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1903,6 +1903,7 @@ impl<T, A: Allocator> Vec<T, A> {
} else {
unsafe {
self.len -= 1;
core::intrinsics::assume(self.len < self.capacity());
Some(ptr::read(self.as_ptr().add(self.len())))
}
}
Expand Down
25 changes: 25 additions & 0 deletions tests/codegen/vec_pop_push_noop.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// compile-flags: -O

#![crate_type = "lib"]

#[no_mangle]
pub fn noop(v: &mut Vec<u8>) {
// CHECK: start:
// CHECK-NEXT: getelementptr
// CHECK-NEXT: load
// CHECK-NEXT: icmp eq
// CHECK-NEXT: br

// CHECK: add
// CHECK-NEXT: getelementptr
// CHECK-NEXT: load
// CHECK-NEXT: icmp
// CHECK-NEXT: tail call
// CHECK-NEXT: br label %bb3

// CHECK: bb3:
// CHECK-NEXT: ret void
if let Some(x) = v.pop() {
v.push(x)
}
}

0 comments on commit 3ff159b

Please sign in to comment.