`Cycle::size_hint` is wrong

Abierto
#166,145 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
1-2 días
Aptitud para principiantes
54/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
rust
Área
backend

Línea de trabajo

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.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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.

Lenguaje dominante
Rust
Estrellas
122k
Forks
16.7k
Merge medio
2 d 16 h
PR fusionados (30 d)
515

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de rust-lang/rust

Todos los issues de rust-lang/rust

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.