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

Fix collect on stateful generator #41919

Merged
merged 2 commits into from
Aug 24, 2021
Merged
Show file tree
Hide file tree
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
18 changes: 15 additions & 3 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -766,13 +766,25 @@ function collect(itr::Generator)
et = @default_eltype(itr)
if isa(isz, SizeUnknown)
return grow_to!(Vector{et}(), itr)
else
elseif isa(isz, HasLength)
len = length(itr)
y = iterate(itr)
if y === nothing
return et[]
end
v1, st = y
return collect_to_with_first!(Vector{typeof(v1)}(undef, len), v1, itr, st)
elseif isa(isz, HasShape)
axs = axes(itr)
y = iterate(itr)
if y === nothing
return _array_for(et, itr.iter, isz)
jakobnissen marked this conversation as resolved.
Show resolved Hide resolved
return similar(Array{et,length(axs)}, axs)
end
v1, st = y
collect_to_with_first!(_array_for(typeof(v1), itr.iter, isz), v1, itr, st)
arr = similar(Array{typeof(v1),length(axs)}, axs)
return collect_to_with_first!(arr, v1, itr, st)
else
error("unreachable")
end
end

Expand Down
11 changes: 10 additions & 1 deletion test/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,15 @@ let (a, b) = (1:3, [4 6;
end
end

# collect stateful iterator
let
itr = (i+1 for i in Base.Stateful([1,2,3]))
@test collect(itr) == [2, 3, 4]
A = zeros(Int, 0, 0)
itr = (i-1 for i in Base.Stateful(A))
@test collect(itr) == Int[] # Stateful do not preserve shape
end

# with 1D inputs
let a = 1:2,
b = 1.0:10.0,
Expand Down Expand Up @@ -860,4 +869,4 @@ end
@test Iterators.peel(1:10)[2] |> collect == 2:10
@test Iterators.peel(x^2 for x in 2:4)[1] == 4
@test Iterators.peel(x^2 for x in 2:4)[2] |> collect == [9, 16]
end
end