Skip to content

Commit a7c45ec

Browse files
committed
improve documentation of pointer::align_offset
1 parent 127b6c4 commit a7c45ec

File tree

2 files changed

+19
-16
lines changed

2 files changed

+19
-16
lines changed

library/core/src/ptr/const_ptr.rs

+9-8
Original file line numberDiff line numberDiff line change
@@ -1267,20 +1267,21 @@ impl<T: ?Sized> *const T {
12671267
/// Accessing adjacent `u8` as `u16`
12681268
///
12691269
/// ```
1270-
/// # fn foo(n: usize) {
1271-
/// # use std::mem::align_of;
1270+
/// use std::mem::align_of;
1271+
///
12721272
/// # unsafe {
1273-
/// let x = [5u8, 6, 7, 8, 9];
1274-
/// let ptr = x.as_ptr().add(n);
1273+
/// let x = [5_u8, 6, 7, 8, 9];
1274+
/// let ptr = x.as_ptr();
12751275
/// let offset = ptr.align_offset(align_of::<u16>());
1276-
/// if offset < x.len() - n - 1 {
1277-
/// let u16_ptr = ptr.add(offset) as *const u16;
1278-
/// assert_ne!(*u16_ptr, 500);
1276+
///
1277+
/// if offset < x.len() - 1 {
1278+
/// let u16_ptr = ptr.add(offset).cast::<u16>();
1279+
/// assert!(*u16_ptr == u16::from_ne_bytes([5, 6]) || *u16_ptr == u16::from_ne_bytes([6, 7]));
12791280
/// } else {
12801281
/// // while the pointer can be aligned via `offset`, it would point
12811282
/// // outside the allocation
12821283
/// }
1283-
/// # } }
1284+
/// # }
12841285
/// ```
12851286
#[stable(feature = "align_offset", since = "1.36.0")]
12861287
#[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]

library/core/src/ptr/mut_ptr.rs

+10-8
Original file line numberDiff line numberDiff line change
@@ -1545,21 +1545,23 @@ impl<T: ?Sized> *mut T {
15451545
/// Accessing adjacent `u8` as `u16`
15461546
///
15471547
/// ```
1548-
/// # fn foo(n: usize) {
1549-
/// # use std::mem::align_of;
1548+
/// use std::mem::align_of;
1549+
///
15501550
/// # unsafe {
1551-
/// let mut x = [5u8, 6, 7, 8, 9];
1552-
/// let ptr = x.as_mut_ptr().add(n);
1551+
/// let mut x = [5_u8, 6, 7, 8, 9];
1552+
/// let ptr = x.as_mut_ptr();
15531553
/// let offset = ptr.align_offset(align_of::<u16>());
1554-
/// if offset < x.len() - n - 1 {
1555-
/// let u16_ptr = ptr.add(offset) as *mut u16;
1556-
/// assert_ne!(*u16_ptr, 500);
1554+
///
1555+
/// if offset < x.len() - 1 {
1556+
/// let u16_ptr = ptr.add(offset).cast::<u16>();
15571557
/// *u16_ptr = 0;
15581558
/// } else {
15591559
/// // while the pointer can be aligned via `offset`, it would point
15601560
/// // outside the allocation
15611561
/// }
1562-
/// # } }
1562+
///
1563+
/// assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
1564+
/// # }
15631565
/// ```
15641566
#[stable(feature = "align_offset", since = "1.36.0")]
15651567
#[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]

0 commit comments

Comments
 (0)