While killing some time online, I can into a blog post that explained the origins of some weird numbers by looking at the hex data and converting that to strings.
This gave me something to try in rust. Specifically, taking the bit of python code that converted strings into unsigned 32-bit and 16-bit integers and porting that to rust.
I started by converting a string to bytes.
|
|
Rust strings are UTF-8. I had a set of well-defined strings so there would be no encoding issues.
The next step was to convert the byte array into a u32
or u16
. Rust
already has functions for this.
The part that took some getting used to was the slices and the arrays.
as_bytes() returns a
byte slice &[u8]
.
from_be_bytes
expects a 4-byte array as an input [u8;4]
.
This was my first approach, pre-allocate the correct type of array and copy the slice into it.
|
|
A slightly more dangerous (more C-like) way was to disable the soundness checks and just point to the slice.
|
|
I settled on the following approach I got from the Rust discord channel.
|
|
I guess I should have paid more attention to the documentation since this code snippet is there for the documentation for from_le_bytes().
From there it was pretty straight forward. It’s just a matter of iterating over the different sizes of integers and the different http verbs.
|
|
I could probably clean this up further by switching out the if
with a match
.
The only other problem I had was a weird compiler error about borrowing that
was actually about me missing an else
case. The unimplemented handled that case.
I still have a lot to learn but I’m really enjoying everything about the language so far.