Skip to content

Commit 34a36a2

Browse files
committed
add VolatilePtr::as_slice_mut
1 parent 3e574ab commit 34a36a2

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/lib.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -866,6 +866,38 @@ impl<'a, T, R, W, const N: usize> VolatilePtr<'a, [T; N], Access<R, W>> {
866866
})
867867
}
868868
}
869+
870+
/// Converts an array reference to a shared slice.
871+
///
872+
/// This makes it possible to use the methods defined on slices.
873+
///
874+
/// ## Example
875+
///
876+
/// Copying two elements into a volatile array reference using `copy_from_slice`:
877+
///
878+
/// ```
879+
/// # extern crate core;
880+
/// use volatile::VolatilePtr;
881+
/// use core::ptr::NonNull;
882+
///
883+
/// let src = [1, 2];
884+
/// let mut dst = [0, 0];
885+
/// let volatile = unsafe { VolatilePtr::new_write_only(NonNull::from(&dst)) };
886+
///
887+
/// // convert the `Volatile<[i32; 2]>` array reference to a `Volatile<[i32]>` slice
888+
/// let volatile_slice = volatile.as_slice_mut();
889+
/// // we can now use the slice methods
890+
/// volatile_slice.copy_from_slice(&src);
891+
///
892+
/// assert_eq!(dst, [1, 2]);
893+
/// ```
894+
pub fn as_slice_mut(self) -> VolatilePtr<'a, [T], Access<R, W>> {
895+
unsafe {
896+
self.map_mut(|array| {
897+
NonNull::new(ptr::slice_from_raw_parts_mut(array.as_ptr() as *mut T, N)).unwrap()
898+
})
899+
}
900+
}
869901
}
870902

871903
/// Methods for restricting access.

0 commit comments

Comments
 (0)