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

Slice element type.

Required Methods

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']);

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");

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");

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']);

Implementations on Foreign Types

impl<T> SliceLike for [T]
[src]

[src]

[src]

[src]

[src]

impl SliceLike for str
[src]

[src]

[src]

[src]

[src]

Implementors