Skip to content

Commit

Permalink
Define resize! (#436)
Browse files Browse the repository at this point in the history
  • Loading branch information
mtfishman authored May 15, 2024
1 parent dfbc287 commit f36b813
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -478,3 +478,45 @@ function Base.unsafe_wrap(::Type{Array}, arr::oneArray{T,N,oneL0.SharedBuffer})
ptr = reinterpret(Ptr{T}, pointer(arr))
unsafe_wrap(Array, ptr, size(arr))
end

## resizing

"""
resize!(a::oneVector, n::Integer)
Resize `a` to contain `n` elements. If `n` is smaller than the current collection length,
the first `n` elements will be retained. If `n` is larger, the new elements are not
guaranteed to be initialized.
"""
function Base.resize!(a::oneVector{T}, n::Integer) where {T}
# TODO: add additional space to allow for quicker resizing
maxsize = n * sizeof(T)
bufsize = if isbitstype(T)
maxsize
else
# type tag array past the data
maxsize + n
end

# replace the data with a new one. this 'unshares' the array.
# as a result, we can safely support resizing unowned buffers.
ctx = context(a)
dev = device(a)
buf = allocate(buftype(a), ctx, dev, bufsize, Base.datatype_alignment(T))
ptr = convert(ZePtr{T}, buf)
m = min(length(a), n)
if m > 0
unsafe_copyto!(ctx, dev, ptr, pointer(a), m)
end
new_data = DataRef(buf) do buf
free(buf)
end
unsafe_free!(a)

a.data = new_data
a.dims = (n,)
a.maxsize = maxsize
a.offset = 0

a
end
21 changes: 21 additions & 0 deletions test/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,24 @@ end
e = c .+ d
@test oneAPI.buftype(e) == oneL0.SharedBuffer
end

@testset "resizing" begin
a = oneArray([1,2,3])

resize!(a, 3)
@test length(a) == 3
@test Array(a) == [1,2,3]

resize!(a, 5)
@test length(a) == 5
@test Array(a)[1:3] == [1,2,3]

resize!(a, 2)
@test length(a) == 2
@test Array(a)[1:2] == [1,2]

b = oneArray{Int}(undef, 0)
@test length(b) == 0
resize!(b, 1)
@test length(b) == 1
end

0 comments on commit f36b813

Please sign in to comment.