Taking a block of items off iterator

I want to process a &[u32] in chunks of 128 words at a time, and for each chunk process a word at a time. Something along the line of:

fn procbuf(buf: &[u32]) {
  for block in buf.take_up_to_X_elements_and_put_in_new_iterator(128) {
    for word in block {
      // do stuff with word
    }
  }
}

I know it can be done with regular indexing, but I'm trying to learn to think in terms of iterators.

Use the chunks() method:

fn procbuf(buf: &[u32]) {
  for block in buf.chunks(128) {
    for word in block {
      // do stuff with word
    }
  }
}
2 Likes

What does

mean?

For the outer loop to get chunks of 128, since you’re starting with a slice, you can just call .chunks(128)

Edit: Ah, you’re calling a u32 a word. Yeah, you can do that like @chrefr showed.

1 Like