Skip to content

Commit d0790ef

Browse files
committed
Add as_slice/as_mut_slice methods for volatile array references
1 parent 1515a95 commit d0790ef

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

src/lib.rs

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
1010
#![no_std]
1111
#![cfg_attr(feature = "nightly", feature(core_intrinsics))]
12+
#![cfg_attr(feature = "nightly", feature(const_generics))]
13+
#![cfg_attr(feature = "nightly", allow(incomplete_features))]
1214

1315
use access::{ReadOnly, ReadWrite, Readable, Writable, WriteOnly};
1416
#[cfg(feature = "nightly")]
@@ -293,6 +295,77 @@ where
293295
}
294296
}
295297

298+
/// Methods for converting arrays to slices
299+
///
300+
/// These methods are only available with the `nightly` feature enabled (requires a nightly
301+
/// Rust compiler).
302+
#[cfg(feature = "nightly")]
303+
impl<R, A, T, const N: usize> Volatile<R, A>
304+
where
305+
R: Deref<Target = [T; N]>,
306+
{
307+
/// Converts an array reference to a shared slice.
308+
///
309+
/// This makes it possible to use the methods defined on slices.
310+
///
311+
/// ## Example
312+
///
313+
/// Copying two elements from a volatile array reference using `copy_into_slice`:
314+
///
315+
/// ```
316+
/// use volatile::Volatile;
317+
///
318+
/// let src = [1, 2];
319+
/// let volatile = Volatile::new(&src);
320+
/// let mut dst = [0, 0];
321+
///
322+
/// // convert the `Volatile<&[i32; 2]>` array reference to a `Volatile<&[i32]>` slice
323+
/// let volatile_slice = volatile.as_slice();
324+
/// // we can now use the slice methods
325+
/// volatile_slice.copy_into_slice(&mut dst);
326+
///
327+
/// assert_eq!(dst, [1, 2]);
328+
/// ```
329+
pub fn as_slice(&self) -> Volatile<&[T], A> {
330+
Volatile {
331+
reference: &*self.reference,
332+
access: self.access,
333+
}
334+
}
335+
336+
/// Converts a mutable array reference to a mutable slice.
337+
///
338+
/// This makes it possible to use the methods defined on slices.
339+
///
340+
/// ## Example
341+
///
342+
/// Copying two elements from a slice into a mutable array reference:
343+
///
344+
/// ```
345+
/// use volatile::Volatile;
346+
///
347+
/// let src = [1, 2, 3, 4];
348+
/// let mut dst = [0, 0];
349+
/// let mut volatile = Volatile::new(&mut dst);
350+
///
351+
/// // convert the `Volatile<&mut [i32; 2]>` array reference to a `Volatile<&mut [i32]>` slice
352+
/// let mut volatile_slice = volatile.as_mut_slice();
353+
/// // we can now use the slice methods
354+
/// volatile_slice.copy_from_slice(&src[2..]);
355+
///
356+
/// assert_eq!(dst, [3, 4]);
357+
/// ```
358+
pub fn as_mut_slice(&mut self) -> Volatile<&mut [T], A>
359+
where
360+
R: DerefMut,
361+
{
362+
Volatile {
363+
reference: &mut *self.reference,
364+
access: self.access,
365+
}
366+
}
367+
}
368+
296369
#[cfg(test)]
297370
mod tests {
298371
use super::Volatile;

0 commit comments

Comments
 (0)