Henry
Henry

Reputation: 6620

Is this the most natural way to read structs from a binary file?

I just realized this is quite similar to What is the best way to parse binary protocols with Rust


Is this the most natural way to read structs from a binary file using Rust? It works but seems a bit odd (why can't I just fill the struct wholesale?).

extern crate byteorder;
use byteorder::{ByteOrder, LittleEndian};

struct Record {
    latch: u32,
    total_energy: f32,
    x_cm: f32,
    y_cm: f32,
    x_cos: f32,
    y_cos: f32,
    weight: f32
}

impl Record {
    fn make_from_bytes(buffer: &[u8]) -> Record {
        Record {
            latch: LittleEndian::read_u32(&buffer[0..4]),
            total_energy: LittleEndian::read_f32(&buffer[4..8]),
            x_cm: LittleEndian::read_f32(&buffer[8..12]),
            y_cm: LittleEndian::read_f32(&buffer[12..16]),
            x_cos: LittleEndian::read_f32(&buffer[16..20]),
            y_cos: LittleEndian::read_f32(&buffer[20..24]),
            weight: LittleEndian::read_f32(&buffer[24..28]),
        }
    }
}

Upvotes: 6

Views: 3155

Answers (1)

antoyo
antoyo

Reputation: 11933

Have a look a the nom crate: it is very useful to parse binary data.

With nom, you could write your parser with something like the following (not tested):

named!(record<Record>, chain!
    ( latch: le_u32
    ~ total_energy: le_f32
    ~ x_cm: le_f32
    ~ y_cm: le_f32
    ~ x_cos: le_f32
    ~ y_cos: le_f32
    ~ weight: le_f32
    , {
        Record {
            latch: latch,
            total_energy: total_energy,
            x_cm: x_cm,
            y_cm: y_cm,
            x_cos: x_cos,
            y_cos: y_cos,
            weight: weight,
        }
    }
    )
);

Upvotes: 6

Related Questions