| 1 |
//! `AsSlice` and `AsMutSlice` traits |
| 2 |
//! |
| 3 |
//! These traits are somewhat similar to the `AsRef` and `AsMut` except that they are **NOT** |
| 4 |
//! polymorphic (no input type parameter) and their methods always return slices (`[T]`). |
| 5 |
//! |
| 6 |
//! The main use case of these traits is writing generic code that accepts (fixed size) buffers. For |
| 7 |
//! example, a bound `T: StableDeref + AsMutSlice<Element = u8> + 'static` will accepts types like |
| 8 |
//! `&'static mut [u8]` and `&'static mut [u8; 128]` -- all |
| 9 |
//! of them are appropriate for DMA transfers. |
| 10 |
//! |
| 11 |
//! # Minimal Supported Rust Version (MSRV) |
| 12 |
//! |
| 13 |
//! This crate is guaranteed to compile on stable Rust 1.51 and up. It *might* compile on older |
| 14 |
//! versions but that may change in any new patch release. |
| 15 |
|
| 16 |
#![deny(missing_docs)] |
| 17 |
#![deny(warnings)] |
| 18 |
#![no_std] |
| 19 |
|
| 20 |
extern crate stable_deref_trait; |
| 21 |
|
| 22 |
/// Something that can be seen as an immutable slice |
| 23 |
pub trait AsSlice { |
| 24 |
/// The element type of the slice view |
| 25 |
type Element; |
| 26 |
|
| 27 |
/// Returns the immutable slice view of `Self` |
| 28 |
fn as_slice(&self) -> &[Self::Element]; |
| 29 |
} |
| 30 |
|
| 31 |
/// Something that can be seen as an mutable slice |
| 32 |
pub trait AsMutSlice: AsSlice { |
| 33 |
/// Returns the mutable slice view of `Self` |
| 34 |
fn as_mut_slice(&mut self) -> &mut [Self::Element]; |
| 35 |
} |
| 36 |
|
| 37 |
impl<'a, S> AsSlice for &'a S |
| 38 |
where |
| 39 |
S: ?Sized + AsSlice, |
| 40 |
{ |
| 41 |
type Element = S::Element; |
| 42 |
|
| 43 |
fn as_slice(&self) -> &[S::Element] { |
| 44 |
(**self).as_slice() |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
impl<'a, S> AsSlice for &'a mut S |
| 49 |
where |
| 50 |
S: ?Sized + AsSlice, |
| 51 |
{ |
| 52 |
type Element = S::Element; |
| 53 |
|
| 54 |
fn as_slice(&self) -> &[S::Element] { |
| 55 |
(**self).as_slice() |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
impl<'a, S> AsMutSlice for &'a mut S |
| 60 |
where |
| 61 |
S: ?Sized + AsMutSlice, |
| 62 |
{ |
| 63 |
fn as_mut_slice(&mut self) -> &mut [S::Element] { |
| 64 |
(**self).as_mut_slice() |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
impl<T> AsSlice for [T] { |
| 69 |
type Element = T; |
| 70 |
|
| 71 |
fn as_slice(&self) -> &[T] { |
| 72 |
self |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
impl<T> AsMutSlice for [T] { |
| 77 |
fn as_mut_slice(&mut self) -> &mut [T] { |
| 78 |
self |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
impl<T, const N: usize> AsSlice for [T; N] { |
| 83 |
type Element = T; |
| 84 |
|
| 85 |
fn as_slice(&self) -> &[T] { |
| 86 |
self |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
impl<T, const N: usize> AsMutSlice for [T; N] { |
| 91 |
fn as_mut_slice(&mut self) -> &mut [T] { |
| 92 |
self |
| 93 |
} |
| 94 |
} |