Skip to content

iter::Flatten, FlatMap should return more precise size_hint and be TrustedLen when item type is an array #87094

Closed
@adrian17

Description

@adrian17

If I understand correctly, presence of TrustedLen trait allows .collect::<Vec<_>>() to avoid reallocations, right?

In that case, given the following:

    #[derive(Clone, Copy)]
    pub struct Pixel(u8, u8, u8, u8);

    let pixels: Vec<Pixel> = vec![Pixel(1, 2, 3, 4); 10];
    let iter = pixels
        .iter()
        .flat_map(|p| [p.0, p.1, p.2, p.3]); // or: .map(|p| [p.0, p.1, p.2, p.3]).flatten();
    println!("{:?}", iter.size_hint());

    let v: Vec<u8> = iter.collect();

Since the type I map to has known const size ([u8; 4]), size_hint should be able to precisely return (40, Some(40)), and the iterator specialization should implement TrustedLen.
Currently, it returns (0, None). This means that to implement this function efficiently, I'd need to manually do Vec::with_capacity(pixels.len() * 4).

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions