diff --git a/src/ptr_array.jl b/src/ptr_array.jl index eca6308..ecb24c1 100644 --- a/src/ptr_array.jl +++ b/src/ptr_array.jl @@ -994,16 +994,18 @@ end pstore!(pointer(A) + (i - oneunit(i)) * static_sizeof(T), v) v end -@inline function unsafe_getindex(A::PtrVector{T}, i::Integer) where {T} +@inline function unsafe_getindex(A::PtrVector{T}, i::Vararg{Integer}) where {T} + i_ = first(i) pload( pointer(A) + - (i - ArrayInterface.offset1(A)) * only(LayoutPointers.bytestrides(A)) + (i_ - ArrayInterface.offset1(A)) * only(LayoutPointers.bytestrides(A)) ) end -@inline function unsafe_setindex!(A::PtrVector{T}, v, i::Integer) where {T} +@inline function unsafe_setindex!(A::PtrVector{T}, v, i::Vararg{Integer}) where {T} + i_ = first(i) pstore!( pointer(A) + - (i - ArrayInterface.offset1(A)) * only(LayoutPointers.bytestrides(A)), + (i_ - ArrayInterface.offset1(A)) * only(LayoutPointers.bytestrides(A)), v ) v diff --git a/src/views.jl b/src/views.jl index c0667b2..dd4e6a1 100644 --- a/src/views.jl +++ b/src/views.jl @@ -2,18 +2,23 @@ A::AbstractPtrArray{T,N}, i::Vararg{Union{Integer,AbstractRange,Colon},N} ) where {T,N} - PtrArray(SubArray(A, Base.to_indices(A, i))) + j = Base.to_indices(A, i) + @boundscheck checkbounds(A, j...) + PtrArray(SubArray(A, j)) end @inline function Base.view( A::AbstractPtrArray{T,N}, i::AbstractUnitRange ) where {T,N} - view(vec(A), i) + V = vec(A) + @boundscheck checkbounds(V, i) + view(V, i) end @inline function Base.view( A::AbstractPtrArray{T,1}, i::AbstractUnitRange ) where {T} + @boundscheck checkbounds(A, i) sx = only(static_strides(A)) if sx === static(1) p = pointer(A) + (first(i) - first(offsets(A))) * sizeof(T) diff --git a/test/runtests.jl b/test/runtests.jl index 4a46e71..ea4aabe 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -449,4 +449,42 @@ end @test A == B end end + + @testset "PtrArray slicing" begin + # Testing for the bug in https://github.com/JuliaSIMD/StrideArrays.jl/issues/88 + x = [1 3; 2 4] + GC.@preserve x begin + ptrarrays = ( + StrideArraysCore.PtrArray(pointer(x), (2, 2)), + StrideArraysCore.PtrArray(pointer(x), (StaticInt(2), StaticInt(2))), + ) + for y in ptrarrays + # This triggered the bug, a 2D index into a Vector, which is used by display/show + y1 = y[1, :] + @test y1[2, 1] == x[1, 2] + + # Some general tests with slicing and bounds checking + @test y[1, 1] == x[1, 1] + @test y[2, 1] == x[2, 1] + @test y[1, 2] == x[1, 2] + @test y[2, 2] == x[2, 2] + @test y1[1] == x[1, 1] + @test y1[2] == x[1, 2] + y2 = y[2, :] + @test y2[1] == x[2, 1] + @test y2[2] == x[2, 2] + y3 = y[:, 1] + @test y3[1] == x[1, 1] + @test y3[2] == x[2, 1] + @test_throws BoundsError y[1:5] + @test_throws BoundsError y[3, :] + @test_throws BoundsError y[:, 3] + @test_throws BoundsError y[2:3, :] + @test_throws BoundsError y1[3] + @test_throws BoundsError y1[1:3] + @test_throws BoundsError y2[3] + @test_throws BoundsError y2[1:3] + end + end + end end