diff options
| author | Mazdak Farrokhzad <twingoow@gmail.com> | 2019-07-10 16:08:24 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2019-07-10 16:08:24 +0200 |
| commit | d0cec040de22555519e991f08a48ec0b1b62fbc6 (patch) | |
| tree | 2b71cb20d8bfb4521d83dd3f8f1998349384a28b | |
| parent | ad21558b8539a8a9bcb21800ad1b7918304d7ef7 (diff) | |
| parent | bc322af444006973addb3e65bcd74f033080402b (diff) | |
| download | rust-d0cec040de22555519e991f08a48ec0b1b62fbc6.tar.gz rust-d0cec040de22555519e991f08a48ec0b1b62fbc6.zip | |
Rollup merge of #62493 - Freyskeyd:valid_example_read-write_unaligned, r=rkruppe
#62357: doc(ptr): add example for {read,write}_unaligned
related to #62357
> With #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>
| -rw-r--r-- | src/libcore/ptr/mod.rs | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/src/libcore/ptr/mod.rs b/src/libcore/ptr/mod.rs index 2a6c2b1331e..df66a2978de 100644 --- a/src/libcore/ptr/mod.rs +++ b/src/libcore/ptr/mod.rs @@ -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 { @@ -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) { |
