Skip to content

Commit

Permalink
Rollup merge of rust-lang#62493 - Freyskeyd:valid_example_read-write_…
Browse files Browse the repository at this point in the history
…unaligned, r=rkruppe

rust-lang#62357: doc(ptr): add example for {read,write}_unaligned

related to rust-lang#62357

> With rust-lang#62323 the only example (that had UB and was thus invalid) in std::ptr::read_unaligned and std::ptr::write_unaligned is removed.

> We should add a valid example of using the aforementioned functions.

Signed-off-by: Freyskeyd <simon.paitrault@gmail.com>
  • Loading branch information
Centril committed Jul 10, 2019
2 parents ad21558 + bc322af commit d0cec04
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/libcore/ptr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,22 @@ pub unsafe fn read<T>(src: *const T) -> T {
///
/// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
// FIXME: Update docs based on outcome of RFC #2582 and friends.
///
/// # Examples
///
/// Read an usize value from a byte buffer:
///
/// ```
/// use std::mem;
///
/// fn read_usize(x: &[u8]) -> usize {
/// assert!(x.len() >= mem::size_of::<usize>());
///
/// let ptr = x.as_ptr() as *const usize;
///
/// unsafe { ptr.read_unaligned() }
/// }
/// ```
#[inline]
#[stable(feature = "ptr_unaligned", since = "1.17.0")]
pub unsafe fn read_unaligned<T>(src: *const T) -> T {
Expand Down Expand Up @@ -839,6 +855,22 @@ pub unsafe fn write<T>(dst: *mut T, src: T) {
///
/// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
// FIXME: Update docs based on outcome of RFC #2582 and friends.
///
/// # Examples
///
/// Write an usize value to a byte buffer:
///
/// ```
/// use std::mem;
///
/// fn write_usize(x: &mut [u8], val: usize) {
/// assert!(x.len() >= mem::size_of::<usize>());
///
/// let ptr = x.as_mut_ptr() as *mut usize;
///
/// unsafe { ptr.write_unaligned(val) }
/// }
/// ```
#[inline]
#[stable(feature = "ptr_unaligned", since = "1.17.0")]
pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
Expand Down

0 comments on commit d0cec04

Please sign in to comment.