Hi, I am new here and trying to learn some Rust concepts by trying to code a small library that would be able to read a standardized file format (a simple key-array format).
This format has a header and descriptors that define a list of arrays and their types to be read from the bytes of the file.
I've handled reading the header and descriptors, but now I'm confronted with some issues I don't know how to handle reading the arrays to their correct type, which is only know at execution time.
I've tried sketching some minimal example with just two types, which should give you an idea of the problem.
I feel like this should be handled with generics and traits but I didn't to manage to get there on my own, and trying to follow the compiler indications didn't get me anywhere.
Any pointers or solutions appreciated, Thanks!
Rust is statically typed, and all enum variants have the type of the enum, so there's no way to have the variant of Len dictate the type of T in something like
struct Item<T> {
len: Len,
array: Vec<T>,
}
You can either propagate the enum pattern up however many levels makes the most sense...
pub enum Value {
Small(i32),
Long(i64),
}
pub struct Store<T> {
items: Vec<T>,
}
// Use `Store<i32>`, `Store<i64>`, or `Store<Value>`
// ...or...
pub enum Store {
Small(Vec<i32>),
Long(Vec<i64>),
}
...which may involve a lot of explicit matching/branching and use of macros to cut down on repetition. (Sketch.)
And/or at some level, you can try to hide that behind type erasure instead...
also i recommend you use chunks_exact over chunks as it allows you to set an explicit behavior for the reminder rather than having a crash on the unwrap (and i think optimizes a bit better)
For now I went with @giocri's solution as this is the easiest to understand for me.
(I understand the use of chunks_exact but I don't think I would need it in my use case).
I think the length of bytes of each type is implicit now in the Item struct and do not need extra information. Although I'm not sure how I could avoid the byte conversion code repetition in the fill_array function (I will consider 10 types in the end).