]> git.lizzy.rs Git - rust.git/commitdiff
doc(ptr): add example for {read,write}_unaligned
authorFreyskeyd <simon.paitrault@gmail.com>
Mon, 8 Jul 2019 14:03:29 +0000 (16:03 +0200)
committerFreyskeyd <simon.paitrault@gmail.com>
Tue, 9 Jul 2019 14:55:00 +0000 (16:55 +0200)
Signed-off-by: Freyskeyd <simon.paitrault@gmail.com>
src/libcore/ptr/mod.rs

index 2a6c2b1331e5c5754e8b7c5e63025a9f9e0d29ef..df66a2978de41f8de35c31f2352d0d42b5d680c5 100644 (file)
@@ -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) {