# Generic function for from\_be\_bytes

**URL:** <https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629>\
**Category:** help\
**Created:** [May 10, 2021, 9:55am UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629 "2021-05-10T09:55:18Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![kekronbekron](https://avatars.discourse-cdn.com/v4/letter/k/a87d85/32.png) [@kekronbekron](https://users.rust-lang.org/u/kekronbekron)\
**Post date:** [May 10, 2021, 9:55am UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/1 "2021-05-10T09:55:19Z")

</div>

Hello,

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.

```rust
fn read_be_u32(input: &mut &[u8]) -> u32 {
    let (int_bytes, rest) = input.split_at(std::mem::size_of::<u32>());
    *input = rest;
    u32::from_be_bytes(int_bytes.try_into().unwrap())
}

fn read_be_u16(input: &mut &[u8]) -> u16 {
    let (int_bytes, rest) = input.split_at(std::mem::size_of::<u16>());
    *input = rest;
    u16::from_be_bytes(int_bytes.try_into().unwrap())
}

```

Source: [u32 - Rust](https://doc.rust-lang.org/std/primitive.u32.html#method.from_be_bytes)

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [May 10, 2021, 10:16am UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/2 "2021-05-10T10:16:20Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![kekronbekron](https://avatars.discourse-cdn.com/v4/letter/k/a87d85/32.png) [@kekronbekron](https://users.rust-lang.org/u/kekronbekron)\
**Post date:** [May 10, 2021, 10:29am UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/3 "2021-05-10T10:29:15Z")

</div>

Return should be the same as what `read_be_u16` returns, i.e., same bytes read/interpreted as Big-Endian

```rust
u16::from_be_bytes(int_bytes.try_into().unwrap())

```

In most cases, it'll be either `u16` or `u32` or `u64` that I'll be passing to the function.  
But also want to cater for the conversion of `[0u8; 64]`.

... so I can do something like:

```rust
let fld_32 = read_be(rdr, 32);
let fld_512 = read_be(rdr, 512);
let fld_288 = read_be(rdr, 288);

```

---

<div class="post-metadata">

**Author:** ![kornel](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/kornel/32/4823_2.png) [@kornel](https://users.rust-lang.org/u/kornel)\
**Post date:** [May 10, 2021, 11:06am UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/4 "2021-05-10T11:06:48Z")

</div>

You might be able to implement that with const generics now:

```rust
let fld_32 = read_be::<32>(rdr);

```

or at least using an older array hack:

```rust
let fld_32 = read_be::<[_; 32]>(rdr);

```

or use a macro that translates it back to the `byteorder` calls.

```rust
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?

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [May 10, 2021, 11:09am UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/5 "2021-05-10T11:09:12Z")

</div>

You could try something like this:

```rust
trait FromBytes {
    fn from_be_bytes(a: &mut &[u8]) -> Self;
}

impl<const N: usize> FromBytes for [u8; N] {
    fn from_be_bytes(a: &mut &[u8]) -> [u8; N] {
        let (int_bytes, rest) = a.split_at(N);
        
        let mut me = [0u8; N];
        me.copy_from_slice(int_bytes);
        
        *a = rest;
        me
    }
}

impl FromBytes for u64 {
    fn from_be_bytes(a: &mut &[u8]) -> u64 {
        u64::from_be_bytes(FromBytes::from_be_bytes(a))
    }
}
impl FromBytes for u32 {
    fn from_be_bytes(a: &mut &[u8]) -> u32 {
        u32::from_be_bytes(FromBytes::from_be_bytes(a))
    }
}

fn read_be<T: FromBytes>(input: &mut &[u8]) -> T {
    T::from_be_bytes(input)
}

```

Here it will figure out how many bytes it should consume depending on what type it returns.

---

<div class="post-metadata">

**Author:** ![kekronbekron](https://avatars.discourse-cdn.com/v4/letter/k/a87d85/32.png) [@kekronbekron](https://users.rust-lang.org/u/kekronbekron)\
**Post date:** [May 10, 2021, 11:20am UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/6 "2021-05-10T11:20:05Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![kekronbekron](https://avatars.discourse-cdn.com/v4/letter/k/a87d85/32.png) [@kekronbekron](https://users.rust-lang.org/u/kekronbekron)\
**Post date:** [May 10, 2021, 11:30am UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/7 "2021-05-10T11:30:15Z")

</div>

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?

```rust
me.copy_from_slice(int_bytes);
me

```

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [May 10, 2021, 11:53am UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/8 "2021-05-10T11:53:00Z")

</div>

> [@kekronbekron](#):
>
> I'm afraid this is about the same size as having separate functions like in the first post.

There is nothing you can do that would beat defining several functions in code length.

> [@kekronbekron](#):
>
> Why `copy_from_slice`?

It is just a way to go from `&[u8]` to `[u8; N]`.

---

<div class="post-metadata">

**Author:** ![kekronbekron](https://avatars.discourse-cdn.com/v4/letter/k/a87d85/32.png) [@kekronbekron](https://users.rust-lang.org/u/kekronbekron)\
**Post date:** [May 10, 2021, 12:13pm UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/9 "2021-05-10T12:13:57Z")

</div>

Your examples are always beautifully clean.  
Incredible articulation of speech & code.

Thank you once again!

---

<div class="post-metadata">

**Author:** ![rossmacarthur](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rossmacarthur/32/15275_2.png) [@rossmacarthur](https://users.rust-lang.org/u/rossmacarthur)\
**Post date:** [May 10, 2021, 1:16pm UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/10 "2021-05-10T13:16:30Z")

</div>

I recently built a crate for a similar purpose that implements this using const generics that you might like.

See [crates.io: Rust Package Registry](https://crates.io/crates/eio).

It does this using a `FromBytes` trait which is defined like the the following. Which is implemented for all the std library number types.

```rust
pub trait FromBytes<const N: usize> {
    fn from_be_bytes(bytes: [u8; N]) -> Self;
    fn from_le_bytes(bytes: [u8; N]) -> Self;
}

```

Using this trait you could implement your functions like this:

```rust
use std::io;
use eio::FromBytes;

fn read_be<T: FromBytes<N>, const N: usize>(mut rdr: &mut &[u8]) -> io::Result<T> {
    let mut buf = [0u8; N];
    io::Read::read_exact(rdr, &mut buf)?;
    Ok(T::from_be_bytes(buf))
}

```

But `eio` actually provides a `ReadExt` trait which does exactly this, it also works with anything that implements `Read`, for example with a cursor:

```rust
use eio::ReadExt;

let mut data = io::Cursor::new([0x37, 0x13, 0x12, 0x34, 0x56, 0x78]);

let a: u16 = data.read_be()?;
let b: i32 = data.read_be()?;

```

### Comparison to `byteorder`

`eio` provides a lot of the same capabilities as the popular [`byteorder`](https://crates.io/crates/byteorder) crate but with a very different API. The advantages of `eio` are the following:

- It is extendible, anyone can implement `FromBytes` or `ToBytes` for their own integer types.
- Uses the core/std `{from,to}_{le,be}_bytes` functions to do the conversion for floats and integers. [`byteorder`](https://crates.io/crates/byteorder) reimplements these.
- Doesn't require turbofish type annotations all the time.

```rust
// byteorder
let i = rdr.read_u16::<BigEndian>()?;
// eio
let i: u16 = rdr.read_be()?;

```

---

<div class="post-metadata">

**Author:** ![rossmacarthur](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rossmacarthur/32/15275_2.png) [@rossmacarthur](https://users.rust-lang.org/u/rossmacarthur)\
**Post date:** [May 10, 2021, 3:18pm UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/12 "2021-05-10T15:18:38Z")

</div>

> Why not push this out as 1.0?

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?

```rust
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:

```rust
let buf = [u8; 64];
data.read_exact(&mut buf)?;

```

So it wouldn't be too hard to write your own function.

```rust
fn read_array<const N: usize>(mut rdr: &mut &[u8]) -> io::Result<[u8; N]> {
    let buf = [0; N];
    data.read_exact(&mut buf)?;
    Ok(buf)
}

```

Also I'm not sure that endianness is something that makes sense for an array 🤔 ? What would you expect the following to return?

```rust
let data = io::Cursor::new([1, 2, 3, 4])?
let a: [u8; 2] = data.read_be()?; // [1, 2] or [2, 1] ?
let b: [u8; 2] = data.read_le()?; // [3, 4] or [4, 3] ?

```

Maybe the following is better, because it is unambiguous? This could be something that I could add to `eio`.

```rust
let c: [u8; 2] data.read_array()?;

```

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [August 9, 2021, 2:43am UTC](https://users.rust-lang.org/t/generic-function-for-from-be-bytes/59629/14 "2021-08-09T02:43:34Z")

</div>

Closed on August 9, 2021, 2:43am UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
