|
75 | 75 | """
|
76 | 76 | b = LazyBufferCache(f=identity)
|
77 | 77 |
|
78 |
| -A lazily allocated buffer object. Given a vector `u`, `b[u]` returns a `Vector` of the |
79 |
| -same element type and length `f(length(u))` (defaulting to the same length), which is |
80 |
| -allocated as needed and then cached within `b` for subsequent usage. |
| 78 | +A lazily allocated buffer object. Given an array `u`, `b[u]` returns an array of the |
| 79 | +same type and size `f(size(u))` (defaulting to the same size), which is allocated as |
| 80 | +needed and then cached within `b` for subsequent usage. |
81 | 81 |
|
82 | 82 | """
|
83 | 83 | struct LazyBufferCache{F<:Function}
|
84 | 84 | bufs::Dict # a dictionary mapping types to buffers
|
85 |
| - lengthmap::F |
86 |
| - LazyBufferCache(f::F=identity) where {F<:Function} = new{F}(Dict()) # start with empty dict |
| 85 | + sizemap::F |
| 86 | + LazyBufferCache(f::F=identity) where {F<:Function} = new{F}(Dict(), f) # start with empty dict |
87 | 87 | end
|
88 | 88 |
|
89 | 89 | # override the [] method
|
90 |
| -function Base.getindex(b::LazyBufferCache, u::AbstractArray{T}) where {T} |
91 |
| - n = b.lengthmap(size(u)) # required buffer length |
92 |
| - buf = get!(b.bufs, T) do |
93 |
| - similar(u, T, n) # buffer to allocate if it was not found in b.bufs |
94 |
| - end::typeof(u) # declare type since b.bufs dictionary is untyped |
95 |
| - # Doesn't work well with matrices, needs more thought! |
96 |
| - #return resize!(buf, n) # resize the buffer if needed, e.g. if problem was resized |
| 90 | +function Base.getindex(b::LazyBufferCache, u::T) where {T<:AbstractArray} |
| 91 | + s = b.sizemap(size(u)) # required buffer size |
| 92 | + buf = get!(b.bufs, (T, s)) do |
| 93 | + similar(u, s) # buffer to allocate if it was not found in b.bufs |
| 94 | + end::T # declare type since b.bufs dictionary is untyped |
| 95 | + return buf |
97 | 96 | end
|
98 | 97 |
|
99 | 98 | export dualcache, get_tmp, LazyBufferCache
|
|
0 commit comments