`Cycle::size_hint` is wrong

オープン
#166,145 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
1〜2日
初心者へのやさしさ
54/100
issue の種類
バグ
明瞭さ
おおむね明確
活発さ
活発
技術スタック
rust
領域
backend

調査の方向性

Read library/core/src/iter/adapters/cycle.rs, especially the size_hint implementation linked in the issue, and compare its branches with the Custom iterator example. Check the relevant iterator adapter tests and add coverage for clones whose reported size hints differ. Done means Cycle::size_hint is correct for every iterator allowed by the Iterator contract.

索引モデルが issue の本文から書いたものです。

説明

A-iterators C-bug T-libs

Similar to #90085

Cycle::size_hint is implemented as
https://github.com/rust-lang/rust/blob/6c587fd5a7f62ceb4fda4e19f0af26d2f9521ae6/library/core/src/iter/adapters/cycle.rs#L47-L52
Note that orig is a clone of inner in inner.cycle(), i.e. not the original.

Every branch except the middle one is incorrect, i.e. the only possible correct size_hint is (0, None).

struct Custom(Option<i32>, fn() -> Self);
impl Iterator for Custom {
    type Item = i32;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.take()
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.iter().size_hint() // trivially correct
    }
}
impl Clone for Custom {
    fn clone(&self) -> Self {
        self.1()
    }
}

fn main() {
    const EMPTY: Custom = Custom(None, || EMPTY);

    let fake_empty = Custom(Some(1), || EMPTY).cycle();
    dbg!(fake_empty.size_hint(), fake_empty.count()); // (0, Some(0)), 1

    let fake_infinite = Custom(None, || Custom(Some(0), || EMPTY)).cycle();
    dbg!(fake_infinite.size_hint(), fake_infinite.count());  // (usize::MAX, None), 0
}

In reality, an iterator that behaves like Custom here could conceivably happen if there is some iterator that depends on external state not preserved by Clone, e.g. a channel, with some cached items that do not get cloned, but are reported in size_hint.

Either way, Custom does not violate any part of the Iterator contract, but Cycle<Custom> does.

主要言語
Rust
スター
122k
フォーク
16.7k
平均マージ
2日 16時間
マージ済み PR(30日)
515

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

rust-lang/rust のほかの issue

rust-lang/rust の issue をすべて見る

似ている issue

Rust の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。