Skip to content

Commit

Permalink
Guarantee inbounds iteration over Array{T} (JuliaLang#27386)
Browse files Browse the repository at this point in the history
* Guarantee inbounds iteration over Array{T}

* Replace indexing with an iterator with actual indexing

* Make the CharStr iterator unaware of the initial state of a Vector{Char} iterator

* Fix tests

* Force inlining of ::Array iterate function
  • Loading branch information
haampie authored and mbauman committed Jun 27, 2018
1 parent 554b13e commit c404bb7
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 9 deletions.
6 changes: 2 additions & 4 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -677,10 +677,8 @@ function grow_to!(dest, itr, st)
end

## Iteration ##
function iterate(A::Array, i=1)
@_propagate_inbounds_meta
i >= length(A) + 1 ? nothing : (A[i], i+1)
end

iterate(A::Array, i=1) = (@_inline_meta; (i % UInt) - 1 < length(A) ? (@inbounds A[i], i + 1) : nothing)

## Indexing: getindex ##

Expand Down
7 changes: 3 additions & 4 deletions base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -946,10 +946,9 @@ function length(itr::PartitionIterator)
end

function iterate(itr::PartitionIterator{<:Vector}, state=1)
iterate(itr.c, state) === nothing && return nothing
l = state
r = min(state + itr.n-1, length(itr.c))
return view(itr.c, l:r), r + 1
state > length(itr.c) && return nothing
r = min(state + itr.n - 1, length(itr.c))
return view(itr.c, state:r), r + 1
end

struct IterationCutShort; end
Expand Down
3 changes: 2 additions & 1 deletion test/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,8 @@ mutable struct CharStr <: AbstractString
chars::Vector{Char}
CharStr(x) = new(collect(x))
end
Base.iterate(x::CharStr, i::Integer=1) = iterate(x.chars, i)
Base.iterate(x::CharStr) = iterate(x.chars)
Base.iterate(x::CharStr, i::Int) = iterate(x.chars, i)
Base.lastindex(x::CharStr) = lastindex(x.chars)
@testset "cmp without UTF-8 indexing" begin
# Simple case, with just ANSI Latin 1 characters
Expand Down

0 comments on commit c404bb7

Please sign in to comment.