6

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]),
        }
    }
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Henry
  • 6,502
  • 2
  • 24
  • 30

1 Answers1

6

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,
        }
    }
    )
);
antoyo
  • 11,097
  • 7
  • 51
  • 82
  • Awesome, can't believe I missed that one. I found byteorder as you can see but nom looks much more suitable for what I'm doing. Thank you! – Henry Oct 20 '16 at 05:31
  • 3
    @Henry: ByteOrder is a low-level crate to deal with byte ordering (whether for parsing or formatting), while nom is a full-fledged parser generator crate :) – Matthieu M. Oct 20 '16 at 06:46
  • What is record? A name of the parsing function? – Evgeni Nabokov Feb 29 '20 at 06:18