Understanding Rust syntax

I came across this piece of code

fn gen_padding_32bit(len: usize) -> &'static [u8] {
    &[b' ', b' ', b' '][0..(4 - (len & 3)) & 3]
}

My understanding of the first pair of brackets is it represents an array of 3 byte literals, but what is the meaning/intention of the second pair [0..(4 - (len & 3)) & 3]?

Thanks

The second pair is indexing into the array, using a Range.

Here's a simpler example, using a range to print the first four elements of an array:

let array = [0, 1, 2, 3, 4, 5, 6];
dbg!(&array[0..4]);

In the code that you shared, the start of the range is 0, and the end of the range is ((4 - (len & 3)) & 3), which I think is an optimized way of writing something like this:

{
    let array = [b' ', b' ', b' '];

    let len = max(len, 3);
    let mut end = 4 - len;
    end = max(end, 3);

    &array[0..end]
}
1 Like

I'm not so sure this is accurate:

It's a bitmask on the last two bits, and is equivalent to (for positive integers) len % 4.

Using that, it's (4 - len % 4) % 4.

2 Likes

Ah, right. Thanks for the correction.