Skip to content

Commit d0cec04

Browse files
authored
Rollup merge of rust-lang#62493 - Freyskeyd:valid_example_read-write_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>
2 parents ad21558 + bc322af commit d0cec04

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Diff for: src/libcore/ptr/mod.rs

+32
Original file line numberDiff line numberDiff line change
@@ -669,6 +669,22 @@ pub unsafe fn read<T>(src: *const T) -> T {
669669
///
670670
/// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
671671
// FIXME: Update docs based on outcome of RFC #2582 and friends.
672+
///
673+
/// # Examples
674+
///
675+
/// Read an usize value from a byte buffer:
676+
///
677+
/// ```
678+
/// use std::mem;
679+
///
680+
/// fn read_usize(x: &[u8]) -> usize {
681+
/// assert!(x.len() >= mem::size_of::<usize>());
682+
///
683+
/// let ptr = x.as_ptr() as *const usize;
684+
///
685+
/// unsafe { ptr.read_unaligned() }
686+
/// }
687+
/// ```
672688
#[inline]
673689
#[stable(feature = "ptr_unaligned", since = "1.17.0")]
674690
pub unsafe fn read_unaligned<T>(src: *const T) -> T {
@@ -839,6 +855,22 @@ pub unsafe fn write<T>(dst: *mut T, src: T) {
839855
///
840856
/// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
841857
// FIXME: Update docs based on outcome of RFC #2582 and friends.
858+
///
859+
/// # Examples
860+
///
861+
/// Write an usize value to a byte buffer:
862+
///
863+
/// ```
864+
/// use std::mem;
865+
///
866+
/// fn write_usize(x: &mut [u8], val: usize) {
867+
/// assert!(x.len() >= mem::size_of::<usize>());
868+
///
869+
/// let ptr = x.as_mut_ptr() as *mut usize;
870+
///
871+
/// unsafe { ptr.write_unaligned(val) }
872+
/// }
873+
/// ```
842874
#[inline]
843875
#[stable(feature = "ptr_unaligned", since = "1.17.0")]
844876
pub unsafe fn write_unaligned<T>(dst: *mut T, src: T) {

0 commit comments

Comments
 (0)