Skip to content
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

Simplify iteration over ranges in general #27161

Merged
merged 5 commits into from
May 25, 2018
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Simplify iteration over ordinal range
  • Loading branch information
haampie committed May 20, 2018
commit 13c92aeed44178bd655bf6631b576439d785a612
30 changes: 9 additions & 21 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -456,34 +456,22 @@ function iterate(r::LinRange, i::Int=1)
unsafe_getindex(r, i), i+1
end

function iterate(r::StepRange{T}, i=oftype(r.start + r.step, r.start)) where {T}
if i isa Integer
(isempty(r) | (i == oftype(i, r.stop) + r.step)) && return nothing
else
(isempty(r) | (i < min(r.start, r.stop)) | (i > max(r.start, r.stop))) && return nothing
end
(convert(T,i), i+r.step)
end

iterate(r::StepRangeLen{T}, i=1) where {T} = i > length(r) ? nothing : (unsafe_getindex(r, i), i+1)

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

function iterate(r::AbstractUnitRange{T}, i) where {T}
function iterate(r::OrdinalRange{T}, i) where {T}
@_inline_meta
i == last(r) && return nothing
next = convert(T, i + oneunit(T))
next = convert(T, i + step(r))
(next, next)
end

# some special cases to favor default Int type to avoid overflow
let smallint = (Int === Int64 ?
Union{Int8,UInt8,Int16,UInt16,Int32,UInt32} :
Union{Int8,UInt8,Int16,UInt16})
global iterate
function iterate(r::StepRange{T}, i=convert(Int, r.start)) where {T<:smallint}
(isempty(r) | (i == oftype(i, r.stop) + r.step)) && return nothing
(i % T, i + r.step)
end
# In the case of floats we might not land exactly on the boundary due to rounding errors
function iterate(r::StepRange{T}, i) where {T<:AbstractFloat}
next = convert(T, i + step(r))
((next < min(r.start, r.stop)) | (next > max(r.start, r.stop))) && return nothing
(next, next)
end

## indexing
Expand Down