Skip to content

Commit 1f1f075

Browse files
authored
Implement collect_similar like collect for DiskGenerators (#198)
* Implement `collect_similar` like `collect` for DiskGenerators * Add a test
1 parent c41b193 commit 1f1f075

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/generator.jl

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,31 @@ function Base.collect(itr::DiskGenerator{<:AbstractArray{<:Any,N}}) where {N}
4747
return dest
4848
end
4949

50+
# Warning: this is not public API!
51+
function Base.collect_similar(A::AbstractArray, itr::DiskGenerator{<:AbstractArray{<:Any,N}}) where {N}
52+
y = iterate(itr)
53+
shp = axes(itr.iter)
54+
if y === nothing
55+
et = Base.@default_eltype(itr)
56+
return similar(A, et, shp)
57+
end
58+
v1, st = y
59+
dest = similar(A, typeof(v1), shp)
60+
i = y
61+
for I in eachindex(itr.iter)
62+
if i isa Nothing # Mainly to keep JET clean
63+
error(
64+
"Should not be reached: iterator is shorter than its `eachindex` iterator"
65+
)
66+
else
67+
dest[I] = first(i)
68+
i = iterate(itr, last(i))
69+
end
70+
end
71+
return dest
72+
73+
end
74+
5075
macro implement_generator(t)
5176
t = esc(t)
5277
quote

test/runtests.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -953,3 +953,17 @@ end
953953
@test getindex_count(A) == 0
954954
end
955955

956+
@testset "Map over indices correctly" begin
957+
# This is a regression test for issue #144
958+
# `map` should always work over the correct indices,
959+
# especially since we overload generators to `DiskArrayGenerator`.
960+
961+
data = [i+j for i in 1:200, j in 1:100]
962+
da = AccessCountDiskArray(data, chunksize=(10,10))
963+
@test map(identity, da) == data
964+
@test all(map(identity, da) .== data)
965+
966+
# Make sure that type inference works
967+
@inferred Matrix{Int} map(identity, da)
968+
@inferred Matrix{Float64} map(x -> x * 5.0, da)
969+
end

0 commit comments

Comments
 (0)