Skip to content

Commit 29d5aa9

Browse files
committed
Fix and test LaztBufferCache on types that are not fixed points of similar
1 parent 5501e45 commit 29d5aa9

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

src/PreallocationTools.jl

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,12 +209,18 @@ struct LazyBufferCache{F <: Function}
209209
LazyBufferCache(f::F = identity) where {F <: Function} = new{F}(Dict(), f) # start with empty dict
210210
end
211211

212+
function similar_type(x::AbstractArray{T}, s::NTuple{N, Integer}) where {T, N}
213+
# The compiler is smart enough to not allocate
214+
# here for simple types like Array and SubArray
215+
typeof(similar(x, ntuple(Returns(1), N)))
216+
end
217+
212218
# override the [] method
213219
function Base.getindex(b::LazyBufferCache, u::T) where {T <: AbstractArray}
214220
s = b.sizemap(size(u)) # required buffer size
215221
get!(b.bufs, (T, s)) do
216222
similar(u, s) # buffer to allocate if it was not found in b.bufs
217-
end::T # declare type since b.bufs dictionary is untyped
223+
end::similar_type(u, s) # declare type since b.bufs dictionary is untyped
218224
end
219225

220226
# GeneralLazyBufferCache

test/general_lbc.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ cache = LazyBufferCache()
3737
x = rand(1000)
3838
@inferred cache[x]
3939
@test 0 == @allocated cache[x]
40+
y = view(x, 1:900)
41+
@inferred cache[y]
42+
@test 0 == @allocated cache[y]
4043

4144
cache = GeneralLazyBufferCache(T -> Vector{T}(undef, 1000))
4245
# GeneralLazyBufferCache is documented not to infer.

0 commit comments

Comments
 (0)