Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading