Function abomonation::decode
source · pub unsafe fn decode<T: Abomonation>(
bytes: &mut [u8],
) -> Option<(&T, &mut [u8])>
Expand description
Decodes a mutable binary slice into an immutable typed reference.
decode
treats the first mem::size_of::<T>()
bytes as a T
, and will then exhume
the
element, offering it the ability to consume prefixes of bytes
to back any owned data.
The return value is either a pair of the typed reference &T
and the remaining &mut [u8]
binary data, or None
if decoding failed due to lack of data.
§Safety
The decode
method is unsafe due to a number of unchecked invariants.
Decoding arbitrary &[u8]
data can
result in invalid utf8 strings, enums with invalid discriminants, etc. decode
does
perform bounds checks, as part of determining if enough data are present to completely decode,
and while it should only write within the bounds of its &mut [u8]
argument, the use of invalid
utf8 and enums are undefined behavior.
Please do not decode data that was not encoded by the corresponding implementation.
In addition, decode
does not ensure that the bytes representing types will be correctly aligned.
On several platforms unaligned reads are undefined behavior, but on several other platforms they
are only a performance penalty.
§Examples
use abomonation::{encode, decode};
// create some test data out of abomonation-approved types
let vector = (0..256u64).map(|i| (i, format!("{}", i)))
.collect::<Vec<_>>();
// encode a Vec<(u64, String)> into a Vec<u8>
let mut bytes = Vec::new();
unsafe { encode(&vector, &mut bytes); }
// decode a &Vec<(u64, String)> from &mut [u8] binary data
if let Some((result, remaining)) = unsafe { decode::<Vec<(u64, String)>>(&mut bytes) } {
assert!(result == &vector);
assert!(remaining.len() == 0);
}