Skip to content

Commit 48aa59e

Browse files
committed
examples for as[_mut]_ptr
1 parent 10f511d commit 48aa59e

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

src/libcore/mem.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1165,6 +1165,32 @@ impl<T> MaybeUninit<T> {
11651165

11661166
/// Gets a pointer to the contained value. Reading from this pointer or turning it
11671167
/// into a reference is undefined behavior unless the `MaybeUninit` is initialized.
1168+
///
1169+
/// # Examples
1170+
///
1171+
/// Correct usage of this method:
1172+
///
1173+
/// ```rust
1174+
/// #![feature(maybe_uninit)]
1175+
/// use std::mem::MaybeUninit;
1176+
///
1177+
/// let mut x = MaybeUninit::<Vec<u32>>::uninitialized();
1178+
/// x.set(vec![0,1,2]);
1179+
/// // Create a reference into the `MaybeUninit`. This is okay because we initialized it.
1180+
/// let x_vec = unsafe { &*x.as_ptr() };
1181+
/// assert_eq!(x_vec.len(), 3);
1182+
/// ```
1183+
///
1184+
/// *Incorrect* usage of this method:
1185+
///
1186+
/// ```rust,no_run
1187+
/// #![feature(maybe_uninit)]
1188+
/// use std::mem::MaybeUninit;
1189+
///
1190+
/// let x = MaybeUninit::<Vec<u32>>::uninitialized();
1191+
/// let x_vec = unsafe { &*x.as_ptr() };
1192+
/// // We have created a reference to an uninitialized vector! This is undefined behavior.
1193+
/// ```
11681194
#[unstable(feature = "maybe_uninit", issue = "53491")]
11691195
#[inline(always)]
11701196
pub fn as_ptr(&self) -> *const T {
@@ -1173,6 +1199,33 @@ impl<T> MaybeUninit<T> {
11731199

11741200
/// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
11751201
/// into a reference is undefined behavior unless the `MaybeUninit` is initialized.
1202+
///
1203+
/// # Examples
1204+
///
1205+
/// Correct usage of this method:
1206+
///
1207+
/// ```rust
1208+
/// #![feature(maybe_uninit)]
1209+
/// use std::mem::MaybeUninit;
1210+
///
1211+
/// let mut x = MaybeUninit::<Vec<u32>>::uninitialized();
1212+
/// x.set(vec![0,1,2]);
1213+
/// // Create a reference into the `MaybeUninit`. This is okay because we initialized it.
1214+
/// let x_vec = unsafe { &mut *x.as_mut_ptr() };
1215+
/// x_vec.push(3);
1216+
/// assert_eq!(x_vec.len(), 4);
1217+
/// ```
1218+
///
1219+
/// *Incorrect* usage of this method:
1220+
///
1221+
/// ```rust,no_run
1222+
/// #![feature(maybe_uninit)]
1223+
/// use std::mem::MaybeUninit;
1224+
///
1225+
/// let mut x = MaybeUninit::<Vec<u32>>::uninitialized();
1226+
/// let x_vec = unsafe { &mut *x.as_mut_ptr() };
1227+
/// // We have created a reference to an uninitialized vector! This is undefined behavior.
1228+
/// ```
11761229
#[unstable(feature = "maybe_uninit", issue = "53491")]
11771230
#[inline(always)]
11781231
pub fn as_mut_ptr(&mut self) -> *mut T {

0 commit comments

Comments
 (0)