Skip to content

Commit 4accd51

Browse files
committed
add VolatilePtr::as_slice_mut
1 parent b525f38 commit 4accd51

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/lib.rs

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

868900
/// Methods for restricting access.

0 commit comments

Comments
 (0)