Skip to content

Commit

Permalink
Auto merge of #97521 - SkiFire13:clarify-vec-as-ptr, r=Dylan-DPC
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bors committed May 31, 2022
2 parents dcbd5f5 + 8ef2dd7 commit 16a0d03
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1107,7 +1107,8 @@ impl<T, A: Allocator> Vec<T, A> {
self
}

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

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

0 comments on commit 16a0d03

Please sign in to comment.