0

I have a long iterator chain generating data that is inserted into a fixed array with for_each. An MWE version (playground):

fn f(xs: impl Iterator<Item = u8>) { let mut buf = [0u8; 32]; xs.zip(buf.iter_mut()).for_each(|(v, b)| *b = v); // ... process buf } 

I'd like to count how many values were inserted. A mut variable that is updated in for_each is one possibility, but I wanted to see if mut can be avoided. Tried the following:

fn g(xs: impl Iterator<Item = u8>) { let mut buf = [0u8; 32]; let c = xs.zip(buf.iter_mut()).inspect(|(v, b)| *b = v).count(); // ... process buf } 

but this does not work because I cannot modify b inside of inspect.

Is there a way for the iterator chain to do the array assignment and return the count?

2 Answers 2

1

In this case, you can simply replace inspect with map:

fn g(xs: impl Iterator<Item = u8>) { let mut buf = [0u8; 32]; let c = xs.zip(buf.iter_mut()).map(|(v, b)| *b = v).count(); // ... process buf } 

This map() will yield an iterator of ()s (since that's what assignment returns), but you're only counting so it doesn't matter what the actual values are.

Sign up to request clarification or add additional context in comments.

Comments

0

A mut variable that is updated in for_each is one possibility, but I wanted to see if mut can be avoided.

That would have been my first suggestion, but if you'd like to see an alternative approach you could tighten the bound on xs to be an ExactSizeIterator instead of just an Iterator which gives you the ability to query its len and then you can calculate the count using simple math:

use std::cmp; fn f(xs: impl ExactSizeIterator<Item = u8>) { let mut buf = [0u8; 32]; let count = cmp::min(32, xs.len()); xs.zip(buf.iter_mut()).for_each(|(v, b)| *b = v); // Process buf } 

playground

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.