Post: byte ordered stream parsing

https://blog.yoshuawuyts.com/byte-ordered-stream-parsing/


I wrote a post about reading / writing numbers to streams with selected endianness. This was inspired by the conversations preceding Rust 1.32 in which the {le_*, be_*, ne_*} methods were added (tracking issue).

The gist of the implementation is a set of two traits that are implemented for all number types, and a Iterator::collect-like API that picks the right encoding through type inference (heh, not sure I'm explaining this alright.) The implementation can be found here.

use std::fs::File;
use omnom::prelude::*;

let mut file = File::open("foo.txt")?;

file.write_le(56_i32)?;        // Write an i32 as little-endian to a byte stream.
let n: u16 = file.read_be()?;  // Read a u16 as big-endian from a byte stream.

I'm sharing this on internals because reading and writing numbers with a declared endianness from streams is something that's desired, and could probably use a bit of work. It's come up before in discussions, and I hope this might make for an interesting read. Thanks!

3 Likes