Skip to content

Commit 778fdf2

Browse files
committed
Add note that Vec::as_mut_ptr() does not materialize a reference to the internal buffer
1 parent 77e24f9 commit 778fdf2

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

library/alloc/src/vec/mod.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1218,6 +1218,12 @@ impl<T, A: Allocator> Vec<T, A> {
12181218
/// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
12191219
/// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
12201220
///
1221+
/// This method guarantees that when it is called multiple times without
1222+
/// the buffer being reallocated in the mean time, the returned pointer will
1223+
/// always be exactly the same, even for the purpose of the aliasing model, where
1224+
/// pointers may be invalidated even when the actual memory does not move.
1225+
/// See the second example below for how this can be used.
1226+
///
12211227
/// # Examples
12221228
///
12231229
/// ```
@@ -1231,6 +1237,16 @@ impl<T, A: Allocator> Vec<T, A> {
12311237
/// }
12321238
/// ```
12331239
///
1240+
/// The validity guarantee works out this way:
1241+
///
1242+
/// ```rust
1243+
/// let mut v = vec![0];
1244+
/// let ptr = v.as_ptr();
1245+
/// let x = ptr.read();
1246+
/// v[0] = 5;
1247+
/// // Notably, the write above did *not* invalidate `ptr1`:
1248+
/// let x = ptr.read();
1249+
/// ```
12341250
/// [`as_mut_ptr`]: Vec::as_mut_ptr
12351251
#[stable(feature = "vec_as_ptr", since = "1.37.0")]
12361252
#[inline]
@@ -1248,6 +1264,13 @@ impl<T, A: Allocator> Vec<T, A> {
12481264
/// Modifying the vector may cause its buffer to be reallocated,
12491265
/// which would also make any pointers to it invalid.
12501266
///
1267+
/// This method guarantees that when it is called multiple times without
1268+
/// the buffer being reallocated in the mean time, the returned pointer will
1269+
/// always be exactly the same, even for the purpose of the aliasing model, where
1270+
/// pointers may be invalidated even when the actual memory does not move.
1271+
/// See the second example below for how this can be used.
1272+
///
1273+
///
12511274
/// # Examples
12521275
///
12531276
/// ```
@@ -1265,6 +1288,18 @@ impl<T, A: Allocator> Vec<T, A> {
12651288
/// }
12661289
/// assert_eq!(&*x, &[0, 1, 2, 3]);
12671290
/// ```
1291+
///
1292+
/// The validity guarantee works out this way:
1293+
///
1294+
/// ```rust
1295+
/// let mut v = vec![0];
1296+
/// let ptr1 = v.as_mut_ptr();
1297+
/// ptr1.write(1);
1298+
/// let ptr2 = v.as_mut_ptr();
1299+
/// ptr2.write(2);
1300+
/// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1301+
/// ptr1.write(3);
1302+
/// ```
12681303
#[stable(feature = "vec_as_ptr", since = "1.37.0")]
12691304
#[inline]
12701305
pub fn as_mut_ptr(&mut self) -> *mut T {

0 commit comments

Comments
 (0)