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

Throw an error when collecting from iterators with inconsistent length #29458

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
13 changes: 11 additions & 2 deletions base/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -640,7 +640,9 @@ emptymutable(itr, ::Type{U}) where {U} = Vector{U}()

## from general iterable to any array

function copyto!(dest::AbstractArray, src)
copyto!(dest::AbstractArray, src) = _copyto_impl!(dest, src, true)

function _copyto_impl!(dest::AbstractArray, src, allowshorter::Bool)
destiter = eachindex(dest)
y = iterate(destiter)
for x in src
Expand All @@ -649,6 +651,9 @@ function copyto!(dest::AbstractArray, src)
dest[y[1]] = x
y = iterate(destiter, y[2])
end
if !allowshorter && y !== nothing
throw(ArgumentError(string("source has fewer elements than destination")))
end
return dest
end

Expand Down Expand Up @@ -720,8 +725,12 @@ end
## copy between abstract arrays - generally more efficient
## since a single index variable can be used.

copyto!(dest::AbstractArray, src::AbstractArray) =
function _copyto_impl!(dest::AbstractArray, src::AbstractArray, allowshorter::Bool)
if !allowshorter && length(src) < length(dest)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check and the one below is actually not needed for this PR since we already allocate an array of the correct length, and the AbstractArray interface relies on the fact that the length is correctly declared. But I added these for consistency, so that the allowshorter argument (which needs to be accepted) isn't a no-op. I can drop it and add a comment explaining that if you want.

throw(ArgumentError("source has fewer elements than destination"))
end
copyto!(IndexStyle(dest), dest, IndexStyle(src), src)
end

function copyto!(::IndexStyle, dest::AbstractArray, ::IndexStyle, src::AbstractArray)
destinds, srcinds = LinearIndices(dest), LinearIndices(src)
Expand Down
23 changes: 19 additions & 4 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,12 @@ function copyto!(dest::Array{T}, doffs::Integer, src::Array{T}, soffs::Integer,
unsafe_copyto!(dest, doffs, src, soffs, n)
end

copyto!(dest::Array{T}, src::Array{T}) where {T} = copyto!(dest, 1, src, 1, length(src))
function _copyto_impl!(dest::Array{T}, src::Array{T}, allowshorter::Bool) where {T}
if !allowshorter && length(src) < length(dest)
throw(ArgumentError("source has fewer elements than destination"))
end
copyto!(dest, 1, src, 1, length(src))
end

# N.B: The generic definition in multidimensional.jl covers, this, this is just here
# for bootstrapping purposes.
Expand Down Expand Up @@ -517,8 +522,10 @@ julia> collect(Float64, 1:2:5)
"""
collect(::Type{T}, itr) where {T} = _collect(T, itr, IteratorSize(itr))

_collect(::Type{T}, itr, isz::HasLength) where {T} = copyto!(Vector{T}(undef, Int(length(itr)::Integer)), itr)
_collect(::Type{T}, itr, isz::HasShape) where {T} = copyto!(similar(Array{T}, axes(itr)), itr)
_collect(::Type{T}, itr, isz::HasLength) where {T} =
_copyto_impl!(Vector{T}(undef, Int(length(itr)::Integer)), itr, false)
_collect(::Type{T}, itr, isz::HasShape) where {T} =
_copyto_impl!(similar(Array{T}, axes(itr)), itr, false)
function _collect(::Type{T}, itr, isz::SizeUnknown) where T
a = Vector{T}()
for x in itr
Expand Down Expand Up @@ -561,7 +568,7 @@ collect(A::AbstractArray) = _collect_indices(axes(A), A)
collect_similar(cont, itr) = _collect(cont, itr, IteratorEltype(itr), IteratorSize(itr))

_collect(cont, itr, ::HasEltype, isz::Union{HasLength,HasShape}) =
copyto!(_similar_for(cont, eltype(itr), itr, isz), itr)
_copyto_impl!(_similar_for(cont, eltype(itr), itr, isz), itr, false)

function _collect(cont, itr, ::HasEltype, isz::SizeUnknown)
a = _similar_for(cont, eltype(itr), itr, isz)
Expand Down Expand Up @@ -618,6 +625,9 @@ function collect(itr::Generator)
else
y = iterate(itr)
if y === nothing
if isa(isz, Union{HasLength, HasShape}) && length(itr) != 0
throw(ArgumentError("iterator returned fewer elements than its declared length"))
end
return _array_for(et, itr.iter, isz)
end
v1, st = y
Expand Down Expand Up @@ -667,6 +677,11 @@ function collect_to!(dest::AbstractArray{T}, itr, offs, st) where T
return collect_to!(new, itr, i+1, st)
end
end
lastidx = lastindex(dest)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should actually be last(LinearIndices(dest)). Will fix in the next round of reviews.

i-1 < lastidx &&
throw(ArgumentError("iterator returned fewer elements than its declared length"))
i-1 > lastidx &&
throw(ArgumentError("iterator returned more elements than its declared length"))
return dest
end

Expand Down
6 changes: 5 additions & 1 deletion base/multidimensional.jl
Original file line number Diff line number Diff line change
Expand Up @@ -815,8 +815,12 @@ julia> y
"""
copyto!(dest, src)

function copyto!(dest::AbstractArray{T,N}, src::AbstractArray{T,N}) where {T,N}
function _copyto_impl!(dest::AbstractArray{T,N}, src::AbstractArray{T,N},
allowshorter::Bool) where {T,N}
checkbounds(dest, axes(src)...)
if !allowshorter && length(src) < length(dest)
throw(ArgumentError("source has fewer elements than destination"))
end
src′ = unalias(dest, src)
for I in eachindex(IndexStyle(src′,dest), src′)
@inbounds dest[I] = src′[I]
Expand Down
25 changes: 25 additions & 0 deletions test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2524,3 +2524,28 @@ Base.view(::T25958, args...) = args
@test t[end,end,1] == @view(t[end,end,1]) == @views t[end,end,1]
@test t[end,end,end] == @view(t[end,end,end]) == @views t[end,end,end]
end

# Iterator with declared length too large
struct InvalidIter1 end
Base.length(::InvalidIter1) = 2
Base.iterate(::InvalidIter1, i=1) = i > 1 ? nothing : (i, (i + 1))
# Iterator with declared length too small
struct InvalidIter2 end
Base.length(::InvalidIter2) = 2
Base.iterate(::InvalidIter2, i=1) = i > 3 ? nothing : (i, (i + 1))
@testset "collect on iterator with incorrect length" begin
@test_throws ArgumentError collect(InvalidIter1())
@test_throws ArgumentError collect(Any, InvalidIter1())
@test_throws ArgumentError collect(Int, InvalidIter1())
@test_throws ArgumentError [x for x in InvalidIter1()]
# Should also throw ArgumentError
@test_broken length(Int[x for x in InvalidIter1()]) != 2

@test_throws ArgumentError collect(InvalidIter2())
@test_throws ArgumentError collect(Any, InvalidIter2())
@test_throws ArgumentError collect(Int, InvalidIter2())
# These cases cannot be tested without writing to invalid memory
# unless the function checked bounds on each iteration (#29458)
# @test_throws ErrorException [x for x in InvalidIter2()]
# @test_broken length(Int[x for x in InvalidIter2()]) != 2
end