Skip to content

[new RangeInclusive] Convert to half-open in into_iter if possible#159200

Open
scottmcm wants to merge 1 commit into
rust-lang:mainfrom
scottmcm:improved-rangeinclusive-iter
Open

[new RangeInclusive] Convert to half-open in into_iter if possible#159200
scottmcm wants to merge 1 commit into
rust-lang:mainfrom
scottmcm:improved-rangeinclusive-iter

Conversation

@scottmcm

Copy link
Copy Markdown
Member

The core goal here is to attempt to remove the penalty between

for x in i..=j {}

and

for x in i..(j+1) {}

by changing how range::RangeInclusiveIter works.

In legacy::RangeInclusive, there's no opportunity to run a fixup before the loop, and trying in every iteration of the loop wasn't worth it.

But now that we have the range::RangeInclusive vs range::RangeInclusiveIter split, we can!

The approach here is to, in into_iter, attempt to convert from start..=last to start..(last+1). Regardless whether that worked, we always delegate to a normal Range for iteration, just with a cold check for "actually we need to return one more element".

Basically you can think of this as having start..=last do either (start..(last+1)).chain(None) or (start..last).chain(Some(last)), though stored more efficiently than literally using Chain.

That way, for example, for a slice of non-ZST if you run a for i in 0..=slice.len() loop, it runs exactly the same as if you'd written for i in 0..(slice.len() + 1) (while also still working for slize-of-ZST where slice.len() + 1 might overflow).

r? libs

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Jul 13, 2026
@scottmcm scottmcm force-pushed the improved-rangeinclusive-iter branch from 78f5932 to a058e3b Compare July 13, 2026 03:49
@rust-log-analyzer

This comment has been minimized.

@scottmcm scottmcm force-pushed the improved-rangeinclusive-iter branch from a058e3b to 7e9ef25 Compare July 13, 2026 04:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants