Skip to content

Commit 16a0d03

Browse files
committed
Auto merge of #97521 - SkiFire13:clarify-vec-as-ptr, r=Dylan-DPC
Clarify the guarantees of Vec::as_ptr and Vec::as_mut_ptr when there's no allocation Currently the documentation says they return a pointer to the vector's buffer, which has the implied precondition that the vector allocated some memory. However `Vec`'s documentation also specifies that it won't always allocate, so it's unclear whether the pointer returned is valid in that case. Of course you won't be able to read/write actual bytes to/from it since the capacity is 0, but there's an exception: zero sized read/writes. They are still valid as long as the pointer is not null and the memory it points to wasn't deallocated, but `Vec::as_ptr` and `Vec::as_mut_ptr` don't specify that's not the case. This PR thus specifies they are actually valid for zero sized reads since `Vec` is implemented to hold a dangling pointer in those cases, which is neither null nor was deallocated.
2 parents dcbd5f5 + 8ef2dd7 commit 16a0d03

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

library/alloc/src/vec/mod.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -1107,7 +1107,8 @@ impl<T, A: Allocator> Vec<T, A> {
11071107
self
11081108
}
11091109

1110-
/// Returns a raw pointer to the vector's buffer.
1110+
/// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
1111+
/// valid for zero sized reads if the vector didn't allocate.
11111112
///
11121113
/// The caller must ensure that the vector outlives the pointer this
11131114
/// function returns, or else it will end up pointing to garbage.
@@ -1144,7 +1145,8 @@ impl<T, A: Allocator> Vec<T, A> {
11441145
ptr
11451146
}
11461147

1147-
/// Returns an unsafe mutable pointer to the vector's buffer.
1148+
/// Returns an unsafe mutable pointer to the vector's buffer, or a dangling
1149+
/// raw pointer valid for zero sized reads if the vector didn't allocate.
11481150
///
11491151
/// The caller must ensure that the vector outlives the pointer this
11501152
/// function returns, or else it will end up pointing to garbage.

0 commit comments

Comments
 (0)