4 ms·
In the past (also Advent of Code 2021), I found the bitvec crate’s BitSlice pretty convenient for parsing bitstreams.
by loeg 5y ago
In the past (also Advent of Code 2021), I found the bitvec crate’s BitSlice pretty convenient for parsing bitstreams.
- the_angry_angel 5y agoJust to echo this, I’m currently using a crate called deku (for a toy project to learn rust). Deku is a wrapper on top of bitvec which lets you annotate structs and enums for decoding and encoding. The speed I was able to implement a binary TCPStream encoder/decoder was great. Both have been rock solid for me. Highly recommend both libraries!
- arch_rust 5y agoIf you like bitvec, check out [deku](https://github.com/sharksforarms/deku https://github.com/sharksforarms/deku)
- loeg 5y agoThanks! Does deku work with records that are not byte-aligned? I checked out the examples and docs and all looked byte-aligned.
- adamch 5y agoOh, interesting. I've used Bitvec for serializing binary data, and I can see how you can use it for parsing single bits or u8s... do you have an example of how to parse, say, a 3-bit binary number with Bitvec?
- loeg 5y agoSomething like this: use bitvec::prelude::*; // BitView trait, Msb0, etc let my_input = vec![0b11100000u8]; let bitslice = my_input.view_bits::<Msb0>(); let my_num = bitslice[..3].load_be::<u8>(); // continue parsing after my_num let nextslice = &bitslice[3..]; You would use Lsb0 instead of Msb0 if you wanted to parse bytes starting at the low bit. It would be more convenient with a peek/take style wrapper over the slice, but I don't think one is included in the crate.
- adamch 5y agoThat's really neat, thanks for showing me. This looks very straightforward for parsing a straightforward format. I think Nom might be more useful as the format gets more complicated... the combinators can really save you quite a bit of time. Having things like many0, or delimited_pair, or length_count already tested and documented saves time compared to implementing + testing it yourself. It's cool seeing how many different approaches you can use to solve the same problem :)
- loeg 5y agoNo problem! > I think Nom might be more useful as the format gets more complicated... the combinators can really save you quite a bit of time. Having things like many0, or delimited_pair, or length_count already tested and documented saves time compared to implementing + testing it yourself. Totally agree -- bitvec works for things that are easy to hand write a parser for. Nom is a lot more powerful.