Home > Software design >  Convert a generic type (u16, u32, u64) into a vector of bytes Vec<u8> in Rust
Convert a generic type (u16, u32, u64) into a vector of bytes Vec<u8> in Rust

Time:06-27

How can I implement a generic function in Rust in a way that can convert a generic type T (u16, u32, or u64) into a Vec<u8> using either little-endian or big-endian formats.

E.g. (not valid Rust code):

fn convert<T>(a: T) -> vec<u8> {
   // a = 0x01234567
   // returns vec![0x01, 0x23, 0x45, 0x67]
}

CodePudding user response:

As @PitaJ suggested implementing a trait solves this problem, here is a working example:

trait IntoBytes: Sized {
    fn to_le_bytes(a: Self) -> Vec<u8>;
}

impl IntoBytes for u16 {
    fn to_le_bytes(a: Self) -> Vec<u8> {
        a.to_le_bytes().to_vec()
    }
}

impl IntoBytes for u32 {
    fn to_le_bytes(a: Self) -> Vec<u8> {
        a.to_le_bytes().to_vec()
    }
}

impl IntoBytes for u64 {
    fn to_le_bytes(a: Self) -> Vec<u8> {
        a.to_le_bytes().to_vec()
    }
}

fn foo<T: IntoBytes>(a: T) -> Vec<u8> {
    T::to_le_bytes(a)
}
    
fn main() {
    println!("{:?}", foo::<u32>(87u32));
    println!("{:?}", foo::<u64>(0x0123456789abcdfu64));
}
  • Related