I’m looking for a function with a signature similar to:
split_header_and_tail(buf: &[u8]) -> Option<(&[u8; HEADER_LENGTH], &[u8])>
If the supplied slice is too short, the result is None, but if it’s long enough a reference to the first HEADER_LENGTH bytes and the tail slice are returned.
The first part must be a reference to a fixed-length array, as I need to subdivide it into various fixed-length fields.
>Solution :
On nightly, there is split_array_ref():
#![feature(split_array)]
fn split_header_and_tail(buf: &[u8]) -> Option<(&[u8; HEADER_LENGTH], &[u8])> {
if buf.len() < HEADER_LENGTH {
None
} else {
Some(buf.split_array_ref())
}
}
On stable, you can use TryInto:
fn split_header_and_tail(buf: &[u8]) -> Option<(&[u8; HEADER_LENGTH], &[u8])> {
if buf.len() < HEADER_LENGTH {
None
} else {
let (head, tail) = buf.split_at(HEADER_LENGTH);
Some((head.try_into().unwrap(), tail))
}
}