Need help with unknown Code

Hey there,

I need your help with the code i have found on the internet. I’m not familiar with the Rust language an I do not understand the following code:

fn compute_keys(shared_secret: &[u8], packets: &[u8]) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
let mut data = Vec::with_capacity(0x64);
let mut mac = Hmac::new(Sha1::new(), &shared_secret);

for i in 1..6 {
    mac.input(packets);
    mac.input(&[i]);
    data.extend_from_slice(&mac.result().code());
    mac.reset();
}

Can anyone explain, whar the for loop does (except for executing 5 times if I am right) ? I understand parts of it. The pointer stuff confuses with mac.input(&[i]); confuses me, because i never had to do with them in Java.

[i] makes an array that contains one element: the number i. & passes it by reference to the function (as a slice), because the function expects arbitrary-length slice as an argument.

On top of what /u/kornel said, the Vec::with_capacity(0x64) will allocate a vector with length zero but with “room” for 100 bytes, which is exactly five times the output size of HMAC-SHA1. I assume they have done so to avoid extra allocation, since the exact expected size of the vector is known. Otherwise it would reallocate.

And as far as I understand, the type of i is inferred by the use in the loop. For example, if I were to insert let r = i * 3_u32 then i could not be passed as &[u8] in the .input() call later. See this playground example.