How would I make a generic function out of the below variants.
Also, is it possible to make a generic function to cover/convert 512 bits ([0u8; 64]), for example.
Want to replace loads of ByteOrder TurboFish statements
(rdr.read_u16::<BigEndian>()?)
with something like read_be(rdr, num_bytes)
where, reader's cursor is adjusted to move forward like in the below functions.
You want one where you can pass the number of bytes as an argument? What should the return value be? It can't depend on a number determined at runtime.
You might be able to implement that with const generics now:
let fld_32 = read_be::<32>(rdr);
or at least using an older array hack:
let fld_32 = read_be::<[_; 32]>(rdr);
or use a macro that translates it back to the byteorder calls.
let fld_32 = read_be!(rdr, 32);
but I wonder what is the endian of a 64-byte type in your case. These aren't typical libstd types. Is that a bignum? Is that an array of smaller integers?
Oooh.. I like the simplicity of the first one.
How would I go about implementing it though?
but I wonder what is the endian of a 64-byte type in your case. These aren't typical libstd types. Is that a bignum? Is that an array of smaller integers?
I'm passing a &[u8] into a function, using read_be within that function to 'consume' & keep moving the cursor forward.
The 64-byte ones are actually char SOME_VAR[64]; in the reference C/C++ code.
They're actually strings but I need to take those bytes as a slice or an array, so that I can pass them to a codepage conversion function.
Thank you, as always, for your detailed examples.
Congrats on becoming a paid contributor to tokio recently!
I'm afraid this is about the same size as having separate functions like in the first post.
Except that your soln. also caters for variable-sized arrays.
Just for that factor, I might need to use this.
In the first impl block, why are we copying int_bytes into me and returning it.
That is, why these 2 lines?
Well it's quite new and there are still some unanswered questions with regards to the API. I was hoping to get feedback from people using it first.
Does data have to be a cursor, or can it just be a &[u8]
You need something that implements Read. &[u8] doesn't implement read because in order to read from it you would need to store the current position as a state. You can use an &mut &[u8] however.
Will this work, then?
let c: [u8; 64] = data.read_be()?;
Not yet, but it wouldn't be too hard to implement. By the way you can already do this with anything implementing Read like this:
let buf = [u8; 64];
data.read_exact(&mut buf)?;
So it wouldn't be too hard to write your own function.