Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 345
Simon Avatar asked Jan 23 '26 12:01

Simon


1 Answers

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);
}
like image 124
Chayim Friedman Avatar answered Jan 26 '26 08:01

Chayim Friedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!