Skip to content

Commit 80b8226

Browse files
jipolancomaleadt
andauthored
Fix resize! for JLVector (#546)
Co-authored-by: Tim Besard <[email protected]>
1 parent cb7d20f commit 80b8226

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

lib/JLArrays/src/JLArrays.jl

+15-6
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,9 @@ mutable struct JLArray{T, N} <: AbstractGPUArray{T, N}
169169
check_eltype(T)
170170
maxsize = prod(dims) * sizeof(T)
171171
data = Vector{UInt8}(undef, maxsize)
172-
ref = DataRef(data)
172+
ref = DataRef(data) do data
173+
resize!(data, 0)
174+
end
173175
obj = new{T,N}(ref, 0, dims)
174176
finalizer(unsafe_free!, obj)
175177
end
@@ -373,11 +375,18 @@ Base.copyto!(dest::DenseJLArray{T}, source::DenseJLArray{T}) where {T} =
373375
copyto!(dest, 1, source, 1, length(source))
374376

375377
function Base.resize!(a::DenseJLVector{T}, nl::Integer) where {T}
376-
a_resized = JLVector{T}(undef, nl)
377-
copyto!(a_resized, 1, a, 1, min(length(a), nl))
378-
a.data = a_resized.data
379-
a.offset = 0
380-
a.dims = size(a_resized)
378+
# JLArrays aren't performance critical, so simply allocate a new one
379+
# instead of duplicating the underlying data allocation from the ctor.
380+
b = JLVector{T}(undef, nl)
381+
copyto!(b, 1, a, 1, min(length(a), nl))
382+
383+
# replace the data, freeing the old one and increasing the refcount of the new one
384+
# to avoid it from being freed when we leave this function.
385+
unsafe_free!(a)
386+
a.data = copy(b.data)
387+
388+
a.offset = b.offset
389+
a.dims = b.dims
381390
return a
382391
end
383392

0 commit comments

Comments
 (0)