rustrust-macros

Rust macro split expression into bytes and into byte vector


I am having issues getting this functionality to work.

I basically need a macro that will accept a vector of bytes and an expression to be inserted into the vector.

Example

let mut bytes: Vec<u8> = vec![0x0; 6];
println!("{:?}", bytes);

let a: u32 = 0xf1f2f3f4;

convert!(bytes, &a);
println!("{:?}", bytes);

Output:

[0x0, 0x0, 0x0, 0x0, 0x0, 0x0]
[0xf1, 0xf2, 0xf3, 0xf4, 0x0, 0x0]

This definitely feels like something that should exist (like sending over wire). I can't however find anything in the documentation. And if there isn't; I could need some help getting there or linked relevant resources (already know about DanielKeep's The Little Book of Rust Macros) that could help me.


Solution

  • I don't know why you want a macro, this can be done very simply with a function:

    fn assign_u32(bytes: &mut [u8], v: u32) {
        bytes[..4].copy_from_slice(&v.to_be_bytes());
    }
    

    And using it like:

    fn main() {
        let mut bytes: Vec<u8> = vec![0x0; 6];
        println!("{:x?}", bytes);
    
        let a: u32 = 0xf1f2f3f4;
    
        assign_u32(&mut bytes, a);
        println!("{:x?}", bytes);
    }