Skip to content

Commit

Permalink
Add Base.mightalias
Browse files Browse the repository at this point in the history
  • Loading branch information
jakobnissen committed Nov 15, 2024
1 parent 3ffadc6 commit 50c764f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,24 @@ function Base.empty(mem::MemoryView{T1, M}, ::Type{T2}) where {T1, T2, M}
end

Base.empty(T::Type{<:MemoryView{E}}) where {E} = T(unsafe, memoryref(Memory{E}()), 0)

Base.pointer(x::MemoryView{T}) where {T} = Ptr{T}(pointer(x.ref))
Base.unsafe_convert(::Type{Ptr{T}}, v::MemoryView{T}) where {T} = pointer(v)
Base.elsize(::Type{<:MemoryView{T}}) where {T} = Base.elsize(Memory{T})
Base.sizeof(x::MemoryView) = Base.elsize(typeof(x)) * length(x)
Base.strides(::MemoryView) = (1,)

function Base.mightalias(a::MemoryView, b::MemoryView)
(isempty(a) | isempty(b)) && return false
parent(a) === parent(b) || return false
(p1, p2) = (pointer(a), pointer(b))
elz = Base.elsize(a)
return if p1 < p2
p1 + length(a) * elz > p2
else
p2 + length(b) * elz > p1
end
end

function Base.getindex(v::MemoryView, idx::AbstractUnitRange)
# This branch is necessary, because the memoryref can't point out of bounds.
# So if the user gives an empty slice that is out of bounds, the boundscheck
Expand Down
18 changes: 18 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,24 @@ end
@test_throws Exception unsafe_copyto!(mem, 1, mutmem, 1, 2)
end

@testset "Mightalias" begin
v = [1,2,3,4,5]
m1 = MemoryView(v)[2:3]
@test Base.mightalias(m1, MemoryView(v)[1:2])
@test Base.mightalias(m1, MemoryView(v)[3:4])
@test Base.mightalias(m1, MemoryView(v)[1:4])
@test !Base.mightalias(m1, MemoryView(v)[1:1])
@test !Base.mightalias(m1, MemoryView(v)[4:5])

v = string.(collect("abcdefgh"))
v1 = view(v, 2:6)
v2 = view(v, 6:7)
@test Base.mightalias(MemoryView(v), MemoryView(v1))
@test Base.mightalias(MemoryView(v), MemoryView(v2))
@test Base.mightalias(MemoryView(v), MemoryView(view(v, 7:8)))
@test !Base.mightalias(MemoryView(v1), MemoryView(view(v, 7:8)))
end

# Span of views
@testset "Span of views" begin
mem = MemoryView("abc")
Expand Down

0 comments on commit 50c764f

Please sign in to comment.