0

I want to build a struct from an array like so:

use std::convert::TryFrom;

impl TryFrom for Chunk {
    type Error = Error;
    
    fn try_from<&[u8]>(bytes: &[u8]) -> Result<Self> {
        // construct
    }
}

The array needs to be sliced up in some pieces, those pieces are then converted to their required datatypes and used for initializing the struct.

But I ran across this issue: The size of the varying member of the array is given as first four bytes of the struct bytes[0..4]. But when I try to access even those four bytes I get error that the size of array is not known at compile time, therefore Rust is not allowing me to index it.

What is the correct, Rustacean way of doing what I am trying to accomplish? How does one index an array size of which is unknown at compile time?

3
  • What is the definition of Chunk? Are the types being pulled from the byte array simple, numeric types, such asu8, f32, etc? If so, the bytes crate is very useful for doing exactly this. Commented Sep 12, 2020 at 16:59
  • @bnaecker its just a struct. bytes (argument passed to function) is just an array of u8 numbers, not all types pulled from the array are numeric. But thats not really what I am after. I just want to divide the array into fixed number of slices. Commented Sep 12, 2020 at 17:04
  • Yes it's "just a struct". I was asking about the types of its fields, to better understand what the bytes represent. In any case, sounds like the bytes crate won't do exactly what you need, so see my answer. Commented Sep 12, 2020 at 17:24

1 Answer 1

2

To be clear, bytes is not an array, it is a slice. These are different in Rust: arrays have their sizes fixed at compile time, while slices do not.

There are many methods for splitting slices. If the chunks are of the same size, then the chunks is the way to go. It returns an iterator over those fixed-size chunks, as sub-slices.

If they do not have fixed sizes, another option is to call split_at, which will construct two new slices from the source, divided at the provided index. You will need to make sure that the split index is valid, or the method panics.

So to split the first four bytes out of the slice, you'd do something like:

// Split into two chunks, of size 4 and (bytes.len() - 4)
let (head, remainder) = bytes.split_at(4);

// convert `head` to whatever type you need

// Continue, for example parsing out a 2-byte type.
let (head, remainder) = remainder.split_at(2); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.