Skip to content

Commit e3e6bc6

Browse files
committed
assert_unsafe_precondition!(length <= capacity) in Vec::from_raw_parts
This hopefully helps to catch cases where these arguments are accidentally swapped.
1 parent d423c81 commit e3e6bc6

File tree

2 files changed

+9
-0
lines changed

2 files changed

+9
-0
lines changed

library/alloc/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@
156156
#![feature(try_trait_v2)]
157157
#![feature(try_with_capacity)]
158158
#![feature(tuple_trait)]
159+
#![feature(ub_checks)]
159160
#![feature(unicode_internals)]
160161
#![feature(unsize)]
161162
#![feature(unwrap_infallible)]

library/alloc/src/vec/mod.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -944,6 +944,14 @@ impl<T, A: Allocator> Vec<T, A> {
944944
#[inline]
945945
#[unstable(feature = "allocator_api", issue = "32838")]
946946
pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
947+
assert_unsafe_precondition!(
948+
check_library_ub,
949+
"Vec::from_raw_parts requires that length is less than or equal to capacity",
950+
(
951+
length: usize = length,
952+
capacity: usize = capacity,
953+
) => length <= capacity,
954+
);
947955
unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } }
948956
}
949957

0 commit comments

Comments
 (0)