@@ -197,19 +197,27 @@ end
197197# LazyBufferCache
198198
199199"""
200- b = LazyBufferCache(f= identity)
200+ b = LazyBufferCache(f = identity; initializer! = identity)
201201
202202A lazily allocated buffer object. Given an array `u`, `b[u]` returns an array of the
203203same type and size `f(size(u))` (defaulting to the same size), which is allocated as
204204needed and then cached within `b` for subsequent usage.
205205
206+ By default the created buffers are not initialized, but a function `initializer!`
207+ can be supplied which is applied to the buffer when it is created, for instance `buf -> fill!(buf, 0.0)`.
208+
206209Optionally, the size can be explicitly given at calltime using `b[u,s]`, which will
207210return a cache of size `s`.
208211"""
209- struct LazyBufferCache{F <: Function }
212+ struct LazyBufferCache{F <: Function , I <: Function }
210213 bufs:: Dict{Any, Any} # a dictionary mapping (type, size) pairs to buffers
211214 sizemap:: F
212- LazyBufferCache (f:: F = identity) where {F <: Function } = new {F} (Dict (), f) # start with empty dict
215+ initializer!:: I
216+ function LazyBufferCache (
217+ f:: F = identity; initializer!:: I = identity) where {
218+ F <: Function , I <: Function }
219+ new {F, I} (Dict (), f, initializer!)
220+ end # start with empty dict
213221end
214222
215223similar_type (x:: AbstractArray , s:: Integer ) = similar_type (x, (s,))
222230function get_tmp (
223231 b:: LazyBufferCache , u:: T , s = b. sizemap (size (u))) where {T <: AbstractArray }
224232 get! (b. bufs, (T, s)) do
225- similar (u, s) # buffer to allocate if it was not found in b.bufs
233+ buffer = similar (u, s) # buffer to allocate if it was not found in b.bufs
234+ b. initializer! (buffer)
235+ buffer
226236 end :: similar_type (u, s) # declare type since b.bufs dictionary is untyped
227237end
228238
0 commit comments