Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define resize! #436

Merged
merged 4 commits into from
May 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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