Skip to content

Commit c404bb7

Browse files
haampiembauman
authored andcommitted
Guarantee inbounds iteration over Array{T} (#27386)
* 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
1 parent 554b13e commit c404bb7

File tree

3 files changed

+7
-9
lines changed

3 files changed

+7
-9
lines changed

base/array.jl

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -677,10 +677,8 @@ function grow_to!(dest, itr, st)
677677
end
678678

679679
## Iteration ##
680-
function iterate(A::Array, i=1)
681-
@_propagate_inbounds_meta
682-
i >= length(A) + 1 ? nothing : (A[i], i+1)
683-
end
680+
681+
iterate(A::Array, i=1) = (@_inline_meta; (i % UInt) - 1 < length(A) ? (@inbounds A[i], i + 1) : nothing)
684682

685683
## Indexing: getindex ##
686684

base/iterators.jl

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -946,10 +946,9 @@ function length(itr::PartitionIterator)
946946
end
947947

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

955954
struct IterationCutShort; end

test/strings/basic.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -555,7 +555,8 @@ mutable struct CharStr <: AbstractString
555555
chars::Vector{Char}
556556
CharStr(x) = new(collect(x))
557557
end
558-
Base.iterate(x::CharStr, i::Integer=1) = iterate(x.chars, i)
558+
Base.iterate(x::CharStr) = iterate(x.chars)
559+
Base.iterate(x::CharStr, i::Int) = iterate(x.chars, i)
559560
Base.lastindex(x::CharStr) = lastindex(x.chars)
560561
@testset "cmp without UTF-8 indexing" begin
561562
# Simple case, with just ANSI Latin 1 characters

0 commit comments

Comments
 (0)