Skip to content

Commit f36b813

Browse files
authored
Define resize! (#436)
1 parent dfbc287 commit f36b813

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

src/array.jl

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,3 +478,45 @@ function Base.unsafe_wrap(::Type{Array}, arr::oneArray{T,N,oneL0.SharedBuffer})
478478
ptr = reinterpret(Ptr{T}, pointer(arr))
479479
unsafe_wrap(Array, ptr, size(arr))
480480
end
481+
482+
## resizing
483+
484+
"""
485+
resize!(a::oneVector, n::Integer)
486+
487+
Resize `a` to contain `n` elements. If `n` is smaller than the current collection length,
488+
the first `n` elements will be retained. If `n` is larger, the new elements are not
489+
guaranteed to be initialized.
490+
"""
491+
function Base.resize!(a::oneVector{T}, n::Integer) where {T}
492+
# TODO: add additional space to allow for quicker resizing
493+
maxsize = n * sizeof(T)
494+
bufsize = if isbitstype(T)
495+
maxsize
496+
else
497+
# type tag array past the data
498+
maxsize + n
499+
end
500+
501+
# replace the data with a new one. this 'unshares' the array.
502+
# as a result, we can safely support resizing unowned buffers.
503+
ctx = context(a)
504+
dev = device(a)
505+
buf = allocate(buftype(a), ctx, dev, bufsize, Base.datatype_alignment(T))
506+
ptr = convert(ZePtr{T}, buf)
507+
m = min(length(a), n)
508+
if m > 0
509+
unsafe_copyto!(ctx, dev, ptr, pointer(a), m)
510+
end
511+
new_data = DataRef(buf) do buf
512+
free(buf)
513+
end
514+
unsafe_free!(a)
515+
516+
a.data = new_data
517+
a.dims = (n,)
518+
a.maxsize = maxsize
519+
a.offset = 0
520+
521+
a
522+
end

test/array.jl

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,24 @@ end
7474
e = c .+ d
7575
@test oneAPI.buftype(e) == oneL0.SharedBuffer
7676
end
77+
78+
@testset "resizing" begin
79+
a = oneArray([1,2,3])
80+
81+
resize!(a, 3)
82+
@test length(a) == 3
83+
@test Array(a) == [1,2,3]
84+
85+
resize!(a, 5)
86+
@test length(a) == 5
87+
@test Array(a)[1:3] == [1,2,3]
88+
89+
resize!(a, 2)
90+
@test length(a) == 2
91+
@test Array(a)[1:2] == [1,2]
92+
93+
b = oneArray{Int}(undef, 0)
94+
@test length(b) == 0
95+
resize!(b, 1)
96+
@test length(b) == 1
97+
end

0 commit comments

Comments
 (0)