rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

struct with accessor to a Peekable field can cause unused_peekable to trigger

Open trinity-1686a opened this issue 2 years ago • 0 comments

Summary

I'm not sure whether this count as FP, so I'm reporting just in case. If it doesn't, feel free to close the issue

A struct containing a Peekable, and giving an accessor to it causes unused_peekable to be raised if the consumer of the accessor only use it as an iterator, without peeking. I think this lint should only trigger following a call to .peekable()

Lint Name

unused_peekable

Reproducer

I tried this code:

use std::iter::Peekable;

struct Wrapper<I: Iterator<Item = T>, T> {
    iter: std::iter::Peekable<I>,
}

impl<I: Iterator<Item = T>, T> Wrapper<I, T> {
    fn new(iter: I) -> Self {
        Wrapper {
            iter: iter.peekable(),
        }
    }

    fn iter(
        &mut self,
    ) -> &mut Peekable<impl Iterator<Item = T>> {
        &mut self.iter
    }
}

fn next() -> usize {
    let mut reader = Wrapper::new([1usize,2,3].iter());
    // ko
    let it = reader.iter();
    let tok = it.next().unwrap();
    *tok
}

fn peek() -> usize {
    let mut reader = Wrapper::new([1usize,2,3].iter());
    // ok
    let it = reader.iter();
    let tok = it.peek().unwrap();
    **tok
}

fn main() {
    next();
    peek();
}

I saw this happen:

--> /tmp/testing/src/main.rs:24:9
   |
24 |     let it = reader.iter();
   |         ^^
   |
   = note: `#[warn(clippy::unused_peekable)]` on by default
   = help: consider removing the call to `peekable`
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unused_peekable

warning: 1 warning emitted

I expected to see this happen: no warn

Version

clippy-driver compiled from 2ddbc86bef837b1072159c020c35940ce52ae696 (after #9465)

Additional Labels

No response

trinity-1686a avatar Sep 14 '22 17:09 trinity-1686a