`Cycle::size_hint` is wrong

Aperta
#166,145 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
1-2 giorni
Idoneità per principianti
54/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
rust
Ambito
backend

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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.

Lingua principale
Rust
Stelle
122k
Fork
16.7k
Merge medio
2g 16h
PR unite (30g)
515

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di rust-lang/rust

Tutte le issue di rust-lang/rust

Issue simili

Altre issue su Rust

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.