Skip to content

Specialize iterate for AbstractOneTo #58677

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -921,14 +921,22 @@ function iterate(r::Union{StepRangeLen,LinRange}, i::Integer=zero(length(r)))
unsafe_getindex(r, i), i
end

iterate(r::OrdinalRange) = isempty(r) ? nothing : (first(r), first(r))

function iterate(r::OrdinalRange{T}, i) where {T}
_iterate(r::OrdinalRange{T}, i::Nothing) where {T} = isempty(r) ? nothing : (first(r), first(r))
function _iterate(r::OrdinalRange{T}, i) where {T}
@inline
i == last(r) && return nothing
next = convert(T, i + step(r))
(next, next)
end
iterate(r::OrdinalRange, i = nothing) = _iterate(r, i)

# optimized implementation that returns `nothing` for large offsets
function iterate(r::AbstractOneTo, st = (first(r), zero(step(r))))
val, offset = st
offset < length(r) || return nothing
v = unsafe_getindex(r, val) # convert to eltype(r)
v, (val + step(r), oftype(step(r), v))
end

## indexing

Expand Down Expand Up @@ -970,7 +978,7 @@ end
# unsafe_getindex is separate to make it useful even when running with --check-bounds=yes
# it assumes the index is inbounds but does not segfault even if the index is out of bounds.
# it does not check if the index isa bool.
unsafe_getindex(v::OneTo{T}, i::Integer) where T = convert(T, i)
unsafe_getindex(v::AbstractOneTo{T}, i::Integer) where T = convert(T, i)
unsafe_getindex(v::AbstractRange{T}, i::Integer) where T = convert(T, first(v) + (i - oneunit(i))*step_hp(v))
function unsafe_getindex(r::StepRangeLen{T}, i::Integer) where T
u = oftype(r.offset, i) - r.offset
Expand Down
1 change: 1 addition & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1890,6 +1890,7 @@ struct Position <: Integer
val::Int
end
Position(x::Position) = x # to resolve ambiguity with boot.jl:770
Base.Int(p::Position) = p.val

struct Displacement <: Integer
val::Int
Expand Down