How to handle reading from bytes into different numeric types unknown at compile time?

⚓ Rust    📅 2026-03-08    👤 surdeus    👁️ 2      

surdeus

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!

fn main() {
    enum Len {
        small,
        long,
    }

    struct Item<T> {
        len: Len,
        array: Vec<T>,
    }

    struct Store<T> {
        items: Vec<Item<T>>,
    }

    trait FromBytes<T> {
        fn from_bytes(&self, bytes: &[u8]) -> Vec<T> {
            vec![]
        }
    }

    impl<T> FromBytes for Item<T> {
        fn from_bytes(&mut self, bytes: &[u8]) {
            self.array = match self.len {
                Len::small => bytes
                    .chunks(4)
                    .map(|c| i32::from_le_bytes(c.try_into().unwrap()))
                    .collect(),
                Len::long => bytes
                    .chunks(8)
                    .map(|c| i64::from_le_bytes(c.try_into().unwrap()))
                    .collect(),
            }
        }
    }

    let mut store: Store = Store { items: vec![] };
    store.items.push(Item::<i32> {
        len: Len::small,
        array: vec![],
    });
    store.items.push(Item::<i64> {
        len: Len::long,
        array: vec![],
    });

    store.items[0].from_bytes(&[1, 2, 3, 4, 5, 6, 7, 8]);
    store.items[1].from_bytes(&[1, 2, 3, 4, 5, 6, 7, 8]);
}

2 posts - 2 participants

Read full topic

🏷️ Rust_feed