Trait scratchpad::SliceLike
[−]
[src]
pub trait SliceLike { type Element: Sized; fn as_element_slice(&self) -> &[Self::Element]; unsafe fn as_element_slice_mut(&mut self) -> &mut [Self::Element]; unsafe fn from_element_slice(slice: &[Self::Element]) -> &Self; unsafe fn from_element_slice_mut(slice: &mut [Self::Element]) -> &mut Self; }
Trait for dynamically sized types that wrap some slice type.
Some DSTs, such as str
, are mostly a wrapper for a basic slice type,
often providing some abstraction to ensure the data isn't used in an
unsafe manner. Implementing this trait for such DSTs exposes conversions
to and from the slice type, allowing us to use these types with allocation
operations.
Associated Types
Required Methods
fn as_element_slice(&self) -> &[Self::Element]
Returns a slice of Self::Element
elements containing this slice's
data.
Examples
use scratchpad::SliceLike; let message = "foo"; let bytes = message.as_element_slice(); assert_eq!(bytes, &[b'f', b'o', b'o']);
unsafe fn as_element_slice_mut(&mut self) -> &mut [Self::Element]
Returns a mutable slice of Self::Element
elements containing this
slice's data.
Safety
Slices of this type may perform validity checks against the internal
data (e.g. str
slices must contain valid UTF-8 data). This function
allows for modification of the slice contents outside such checks.
Improper use of this function can result in undefined behavior.
Examples
use scratchpad::SliceLike; let mut message = String::from("foo"); unsafe { let bytes = message.as_mut_str().as_element_slice_mut(); bytes[0] = b'b'; bytes[1] = b'a'; bytes[2] = b'r'; } assert_eq!(message, "bar");
unsafe fn from_element_slice(slice: &[Self::Element]) -> &Self
Reinterprets a slice of Self::Inner
elements as a slice of this
type.
Safety
Slices of this type may perform validity checks against the internal
data (e.g. str
slices must contain valid UTF-8 data). This function
bypasses any such checks, potentially returning data that is invalid.
Improper use of this function can result in undefined behavior.
Examples
use scratchpad::SliceLike; let bytes = [b'f', b'o', b'o']; let message = unsafe { <str as SliceLike>::from_element_slice(&bytes[..]) }; assert_eq!(message, "foo");
unsafe fn from_element_slice_mut(slice: &mut [Self::Element]) -> &mut Self
Reinterprets a mutable slice of Self::Inner
elements as a mutable
slice of this type.
Safety
Slices of this type may perform validity checks against the internal
data (e.g. str
slices must contain valid UTF-8 data). This function
bypasses any such checks, potentially returning data that is invalid.
Improper use of this function can result in undefined behavior.
Examples
use scratchpad::SliceLike; let mut bytes = [b'f', b'o', b'o']; unsafe { let message = <str as SliceLike>::from_element_slice_mut( &mut bytes[..], ); message.as_bytes_mut()[0] = b'b'; message.as_bytes_mut()[1] = b'a'; message.as_bytes_mut()[2] = b'r'; } assert_eq!(bytes, [b'b', b'a', b'r']);