Skip to content

Add with_exact_size and with_size_hint to Iterator #68995

Open
@LukasKalbertodt

Description

@LukasKalbertodt

Usually iterator adaptors do a fine job at keeping information about the length of an iterator. But once you throw something like filter in your iterator chain, the lower bound is 0, meaning that collecting into a collection can't properly pre-allocate. Also, some iterator adaptors (like chain) cannot implemented ExactSizeIterator although in many real world cases, the size is perfectly known.

Currently, working around those limitations is often tedious and requires quite a bit of additional code. I think it would be a lot nicer to just add a .with_exact_size(27) somewhere into your chain. So I'd like to propose adding the following to Iterator:

  • fn with_size_hint(self, lower: usize, upper: Option<usize>) -> SizeHint
    • SizeHint would implement Iterator::size_hint with the given values, forwarding all other methods to the inner iterator (and implementing the same traits)
  • fn with_exact_size(self, size: usize) -> ExactSize
    • ExactSize would implement ExactSizeIterator with the given value and override Iterator::size_hint. All other methods are forwarded to the inner iterator (and implementing the same traits, plus ExactSizeIterator)

I would have created this as a PR, but I'm short on time and wanted to hear some opinions first.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-iteratorsArea: IteratorsC-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions