0

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.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
Simon
  • 95
  • 1
  • 11
  • 3
    Why a macro specifically? Why not a function? – Chayim Friedman Jun 04 '23 at 12:50
  • I'd prefer it to be a macro to keep my code clean. This functionality is used by a second macro for initialising stuff with a variable number of arguments. Edit: this will be one macro if I get it to work. – Simon Jun 04 '23 at 12:58
  • 2
    Prefer functions wherever you can, use macros only when you must. Macros won't keep your code clean; they'll do the opposite. – Chayim Friedman Jun 04 '23 at 13:00
  • This is an optional helper macro. Got tired of specifying and hard-coding configurations manually so made this macro for just that. ```rust set_field!(&mut f; 0, 0, 2; 1, 0, 4; 2, 0, 7; ); ``` – Simon Jun 04 '23 at 13:07
  • 2
    Your macro can call functions, so I still don't get why it should be a macro. – Chayim Friedman Jun 04 '23 at 13:11

1 Answers1

2

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);
}
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77