arraysrustslice

How to split a slice into a header array reference and a tail slice?


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

  • Since 1.77.0, there is split_first_chunk():

    fn split_header_and_tail(buf: &[u8]) -> Option<(&[u8; HEADER_LENGTH], &[u8])> {
        buf.split_first_chunk()
    }
    

    Before that, 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))
        }
    }