diff --git a/base/abstractarray.jl b/base/abstractarray.jl index bf2a6ebabecba..d026f8082cfcd 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -1234,11 +1234,19 @@ oneunit(x::AbstractMatrix{T}) where {T} = _one(oneunit(T), x) # While the definitions for IndexLinear are all simple enough to inline on their # own, IndexCartesian's CartesianIndices is more complicated and requires explicit # inlining. -function iterate(A::AbstractArray, state=(eachindex(A),)) +iterate_starting_state(A) = iterate_starting_state(A, IndexStyle(A)) +iterate_starting_state(A, ::IndexLinear) = firstindex(A) +iterate_starting_state(A, ::IndexStyle) = (eachindex(A),) +iterate(A::AbstractArray, state = iterate_starting_state(A)) = _iterate(A, state) +function _iterate(A::AbstractArray, state::Tuple) y = iterate(state...) y === nothing && return nothing A[y[1]], (state[1], tail(y)...) end +function _iterate(A::AbstractArray, state::Integer) + checkbounds(Bool, A, state) || return nothing + @inbounds(A[state]), state + one(state) +end isempty(a::AbstractArray) = (length(a) == 0) diff --git a/test/abstractarray.jl b/test/abstractarray.jl index 01e13f17460b5..bbac7812174da 100644 --- a/test/abstractarray.jl +++ b/test/abstractarray.jl @@ -2286,3 +2286,13 @@ end @test_throws "no method matching $Int(::$Infinity)" similar(ones(2), OneToInf()) end end + +@testset "iterate for linear indexing" begin + A = [1 2; 3 4] + v = view(A, :) + @test sum(x for x in v) == sum(A) + v = view(A, 1:2:lastindex(A)) + @test sum(x for x in v) == sum(A[1:2:end]) + v2 = view(A, Base.IdentityUnitRange(1:length(A))) + @test sum(x for x in v2) == sum(A) +end diff --git a/test/stacktraces.jl b/test/stacktraces.jl index 3df0998fe88f6..f71cf9f616eaa 100644 --- a/test/stacktraces.jl +++ b/test/stacktraces.jl @@ -248,7 +248,7 @@ struct F49231{a,b,c,d,e,f,g} end stacktrace(catch_backtrace()) end str = sprint(Base.show_backtrace, st, context = (:limit=>true, :stacktrace_types_limited => Ref(false), :color=>true, :displaysize=>(50,105))) - @test contains(str, "[5] \e[0m\e[1mcollect_to!\e[22m\e[0m\e[1m(\e[22m\e[90mdest\e[39m::\e[0mVector\e[90m{…}\e[39m, \e[90mitr\e[39m::\e[0mBase.Generator\e[90m{…}\e[39m, \e[90moffs\e[39m::\e[0m$Int, \e[90mst\e[39m::\e[0mTuple\e[90m{…}\e[39m\e[0m\e[1m)\e[22m\n\e[90m") + @test contains(str, "[5] \e[0m\e[1mcollect_to!\e[22m\e[0m\e[1m(\e[22m\e[90mdest\e[39m::\e[0mVector\e[90m{…}\e[39m, \e[90mitr\e[39m::\e[0mBase.Generator\e[90m{…}\e[39m, \e[90moffs\e[39m::\e[0m$Int, \e[90mst\e[39m::\e[0m$Int\e[0m\e[1m)\e[22m\n\e[90m") st = try F49231{Vector,Val{'}'},Vector{Vector{Vector{Vector}}},Tuple{Int,Int,Int,Int,Int,Int,Int},Int,Int,Int}()(1,2,3)