Skip to content

Commit

Permalink
improve documentation of pointer::align_offset
Browse files Browse the repository at this point in the history
  • Loading branch information
WaffleLapkin committed Aug 1, 2022
1 parent 4eee5aa commit 6d6979b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
17 changes: 9 additions & 8 deletions library/core/src/ptr/const_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1267,20 +1267,21 @@ impl<T: ?Sized> *const T {
/// Accessing adjacent `u8` as `u16`
///
/// ```
/// # fn foo(n: usize) {
/// # use std::mem::align_of;
/// use std::mem::align_of;
///
/// # unsafe {
/// let x = [5u8, 6, 7, 8, 9];
/// let ptr = x.as_ptr().add(n);
/// let x = [5_u8, 6, 7, 8, 9];
/// let ptr = x.as_ptr();
/// let offset = ptr.align_offset(align_of::<u16>());
/// if offset < x.len() - n - 1 {
/// let u16_ptr = ptr.add(offset) as *const u16;
/// assert_ne!(*u16_ptr, 500);
///
/// if offset < x.len() - 1 {
/// let u16_ptr = ptr.add(offset).cast::<u16>();
/// assert!(*u16_ptr == u16::from_ne_bytes([5, 6]) || *u16_ptr == u16::from_ne_bytes([6, 7]));
/// } else {
/// // while the pointer can be aligned via `offset`, it would point
/// // outside the allocation
/// }
/// # } }
/// # }
/// ```
#[stable(feature = "align_offset", since = "1.36.0")]
#[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
Expand Down
18 changes: 10 additions & 8 deletions library/core/src/ptr/mut_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1545,21 +1545,23 @@ impl<T: ?Sized> *mut T {
/// Accessing adjacent `u8` as `u16`
///
/// ```
/// # fn foo(n: usize) {
/// # use std::mem::align_of;
/// use std::mem::align_of;
///
/// # unsafe {
/// let mut x = [5u8, 6, 7, 8, 9];
/// let ptr = x.as_mut_ptr().add(n);
/// let mut x = [5_u8, 6, 7, 8, 9];
/// let ptr = x.as_mut_ptr();
/// let offset = ptr.align_offset(align_of::<u16>());
/// if offset < x.len() - n - 1 {
/// let u16_ptr = ptr.add(offset) as *mut u16;
/// assert_ne!(*u16_ptr, 500);
///
/// if offset < x.len() - 1 {
/// let u16_ptr = ptr.add(offset).cast::<u16>();
/// *u16_ptr = 0;
/// } else {
/// // while the pointer can be aligned via `offset`, it would point
/// // outside the allocation
/// }
/// # } }
///
/// assert!(x == [0, 0, 7, 8, 9] || x == [5, 0, 0, 8, 9]);
/// # }
/// ```
#[stable(feature = "align_offset", since = "1.36.0")]
#[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
Expand Down

0 comments on commit 6d6979b

Please sign in to comment.