Reputation: 1825
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?
Upvotes: 0
Views: 729
Reputation: 6430
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);
Upvotes: 2