itertools icon indicating copy to clipboard operation
itertools copied to clipboard

Ownership issues for `Itertools` methods

Open Philippe-Cholet opened this issue 2 years ago • 0 comments

Following the logic of https://github.com/rust-itertools/itertools/issues/709#issuecomment-1616526337:

I looked at the methods in trait Iterator to find the way the "std" considers "iterator ownership". There are 4 cases:

  • no change (size_hint): immutable borrow ;
  • transfer ownership to another iterator type (such as take_while...): take by value ;
  • consume the iterator completely (such as count/last/max...): take by value ;
  • consume only part of the iterator (such as find/all/try_collect...): mutably borrow.

I was worried about ownership for other methods than take_while_inclusive (subject of the comment), here's what I found:

It consumes the iterator completely, it should take by value, right? Once called, the iterator still exists but is always empty, then it's dropped later.

fn join(&mut self, sep: &str) -> String;

Transfer ownership to another iterator: it should take by value (then people can call .by_ref() if they want).

fn take_while_inclusive... // subject of #709
fn peeking_take_while<F>(&mut self, accept: F) -> PeekingTakeWhile<Self, F>;
fn take_while_ref<F>(&mut self, accept: F) -> TakeWhileRef<Self, F>;

Methods that consume only part (in some case) of the iterator (should mutably borrow, people might want to consider remaining elements). But it's not a real issue as people can call .by_ref().

fn collect_tuple<T>(mut self) -> Option<T>;
fn try_collect<T, U, E>(self) -> Result<U, E>; // will be deprecated anyway once it's stabilized in Iterator
fn process_results<F, T, E, R>(self, processor: F) -> Result<R, E>;

The rest of the methods follow the "std Iterator logic" described in the quoted comment above.

Philippe-Cholet avatar Jul 02 '23 10:07 Philippe-Cholet