Alika97
Alika97

Reputation: 59

Rust example in Rust Book: for loop over a range

In the Rust Book there is an interesting example about an audio encoder: Comparing Performance: Loops vs. Iterators

let buffer: &mut [i32];
let coefficients: [i64; 12];
let qlp_shift: i16;

for i in 12..buffer.len() {
    let prediction = coefficients.iter()
        .zip(&buffer[i - 12..i])
        .map(|(&c, &s)| c * s as i64)
        .sum::<i64>() >> qlp_shift;
    let delta = buffer[i];
    buffer[i] = prediction as i32 + delta;
}
  1. I cant get what is iterating this for loop. In my mind, 12..buffer.len() would iterate from the 13th byte of the buffer to the end of the buffer. Which doesn't makes much sense.

  2. Also, when zipping, it is pairing the current item in coefficients —coefficients.iter()— and pairing with buffer[i - 12..i], which again makes no sense, as I don't know how can you take the index i and substranct a range like 12..i.

Any help will be welcome!

Upvotes: 3

Views: 664

Answers (1)

Peter Hall
Peter Hall

Reputation: 58745

The loop starts at 12, thereby skipping the first 12 elements in the buffer:

for i in 12..buffer.len() {

As pointed out in the comments, buffer[i - 12..i] is actually interpreted by the Rust parser as buffer[(i - 12)..i]. So, later in the algorithm it refers to the preceding 12 elements:

.zip(&buffer[i - 12..i])

This is creating a sliding window of 12 elements, starting 12 elements before the current index, and then zipping them with the fixed array of 12 coefficients.

Upvotes: 3

Related Questions