Skip to content

Commit

Permalink
optimize collect
Browse files Browse the repository at this point in the history
  • Loading branch information
mbauman committed Dec 3, 2024
1 parent 32e0ba4 commit 01fa568
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/InvertedIndices.jl
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,17 @@ end
(pickitr[1], (nothing, pickitr[2])) :
(pickitr[1], (skipitr, pickitr[2]))
end
Base.collect(III::InvertedIndexIterator) = [i for i in III]
function Base.collect(III::InvertedIndexIterator{T}) where {T}
!isconcretetype(T) && return [i for i in III] # use widening if T is not concrete
v = Vector{T}(undef, length(III))
i = 0
for elt in III
i += 1
@inbounds v[i] = elt
end
i != length(v) && throw(AssertionError("length of inverted index does not match iterated count"))
return v
end

should_skip(::Nothing, ::Any) = false
should_skip(s::Tuple, p::Tuple) = _should_skip(s[1], p[1])
Expand Down
1 change: 1 addition & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -198,5 +198,6 @@ returns(val) = _->val
@test all(isodd, I)
@allocated(foreach(returns(nothing), I))
@test @allocated(foreach(returns(nothing), I)) == 0
@test @inferred(collect(I)) == vec(filter(!iseven, arr))
end
end

0 comments on commit 01fa568

Please sign in to comment.