How to convert multiple integers into byte array

Viewed 160

Given three integers of different size in Rust

let tlv_type: u8 = 1;
let length: u16 = 8;
let value: u64 = 123;

how can I convert those into a byte array [u8; 11] or slice &[u8]?

Is there something along the lines of

let tlv_array = [tlv_type, length.to_be_bytes(), value.to_be_bytes()].flat_map()
1 Answers

Solution 1: chain iterators

There's no native syntax doing exactly this. A simple solution is to chain iterators.

let tlv_array: Vec<u8> = tlv_type.to_be_bytes().iter().copied()
    .chain(length.to_be_bytes())
    .chain(value.to_be_bytes())
    .collect();

Solution 2 : write a macro to do it for you

There's no native syntax, but you can add one!

macro_rules! u8_vec {
    [$first_val:expr, $($other_val:expr),*] => {{
        let arr = $first_val.to_be_bytes();
        let arr = arr.iter().copied();
        $(
            let arr = arr.chain($other_val.to_be_bytes());
        )*
        let arr:Vec<u8> = arr.collect();
        arr
    }}
}

Macro usage:

let tlv_array = u8_vec![tlv_type, length, value];
Related