Sometimes Rust makes me so happy. I wrote this over the weekend:
let embedded_data = include_bytes!("../static/data.bin");
let my_set: HashSet<&[u8]> = embedded_data[7..].chunks(10).collect();
It does this:
- Read a binary file and embed it in the final executable as an array of bytes.
- Create a
HashSet
(Python folks: aset()
of items of a specific type) where each element is an array of bytes. - Skip the first 7 bytes of the binary file using Python-like slice notation.
- Create an iterator that emits 10-byte portions of the rest of the file, one at a time.
- Collect all the values from that iterator into… oh!, a
HashSet<&[u8]>
because Rust can tell what the type of the target variable is, so why make me repeat myself?
Rust isn’t magic. Other languages can do similar things if you poke at them enough. It’s more that 2 lines of builtin Rust can readably implement a reasonably sophisticated set of operations that get compiled into a static executable. That’s a very pleasant combination of features.