Skip to content

Commit

Permalink
dispatch on types, and add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jishnub committed Jul 4, 2023
1 parent c38d76e commit 71565b6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
22 changes: 15 additions & 7 deletions src/OffsetArrays.jl
Original file line number Diff line number Diff line change
Expand Up @@ -319,15 +319,23 @@ Base.similar(A::OffsetArray, ::Type{T}, dims::Dims) where T =
similar(parent(A), T, dims)

"""
isonebased(ax::AbstractUnitRange{<:Integer})
isonebased(::Type{T}) where {T<:AbstractUnitRange{<:Integer}}
Return whether `firstindex(ax)` is statically known to be `1`. Custom axis types may extend this method
to ensure that the axis offset is ignored, for example in `similar`.
Return whether `first(ax::T)` is statically known to be `1` for any `ax` of type `T`
(`false` by default).
Custom axis types may extend this method to ensure that the axis offset is ignored,
for example in `similar`. This may strip `OffsetArray` wrappers on occasion, or dispatch
to `Base` methods for 1-based axes.
For axes that are essentially wrappers around another `AbstractUnitRange`,
and share their indexing with their parents, one may forward the type of the
parent range to `isonebased`.
"""
isonebased(_) = false
isonebased(::Integer) = true
isonebased(::Base.OneTo) = true
isonebased(r::IIUR) = isonebased(r.indices)
isonebased(x) = isonebased(typeof(x))
isonebased(::Type) = false
isonebased(::Type{<:Integer}) = true
isonebased(::Type{<:Base.OneTo}) = true
isonebased(::Type{IdentityUnitRange{T}}) where {T} = isonebased(T)

# Since the following is committing type-piracy, we provide an opt-out mechanism to the users
function Base.similar(A::AbstractArray, ::Type{T}, shape::Tuple{OffsetAxisKnownLength,Vararg{OffsetAxisKnownLength}}) where T
Expand Down
10 changes: 9 additions & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ using EllipsisNotation
using FillArrays
using LinearAlgebra
using OffsetArrays
using OffsetArrays: IdentityUnitRange, no_offset_view, IIUR, Origin, IdOffsetRange
using OffsetArrays: IdentityUnitRange, no_offset_view, IIUR, Origin, IdOffsetRange, isonebased
using StaticArrays
using Test

Expand Down Expand Up @@ -2262,6 +2262,14 @@ Base.size(x::PointlessWrapper) = size(parent(x))
Base.axes(x::PointlessWrapper) = axes(parent(x))
Base.getindex(x::PointlessWrapper, i...) = x.parent[i...]

@testset "isonebased" begin
@test isonebased(Base.OneTo(2))
@test !isonebased(1:2)
@test isonebased(IdentityUnitRange(Base.OneTo(2)))
@test !isonebased(IdentityUnitRange(1:2))
@test similar(zeros(1), Int, IdentityUnitRange(Base.OneTo(2))) isa Vector{Int}
end

@testset "no offset view" begin
# OffsetArray fallback
A = randn(3, 3)
Expand Down

0 comments on commit 71565b6

Please sign in to comment.