Function plain::slice_from_bytes
[−]
[src]
pub fn slice_from_bytes<T>(bytes: &[u8]) -> Result<&[T], Error> where
T: Plain,
Similar to from_bytes()
,
except that the output is a slice of T, instead
of a reference to a single T. All concerns about
alignment also apply here, but size is handled
differently.
The result slice's length is set to be
bytes.len() / size_of::<T>()
, and there
are no requirements for input size. I.e.
the result may be empty slice, and the input
slice doesn't necessarily have to end on T
's
boundary. The latter has pragmatic reasons: If the
length of the array is not known in advance,
e.g. if it's terminated by a special element,
it's perfectly legal to turn the whole rest
of data into &[T]
and set the proper length
after inspecting the array.
In most cases it's preferrable to allocate
a value/slice of the target type and use
as_mut_bytes()
to copy
data instead. That way, any issues with alignment
are implicitly avoided.
Example
use plain::Plain; let bytes = &[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]; let nums: &[u32] = u32::slice_from_bytes(bytes).unwrap(); // Oops! This `unwrap()` will actually panic, in some cases! // The byte slice is NOT aligned! Don't write code like this! // If the above doesn't panic, this holds: assert_eq!(nums.len(), 3);