Skip to content

Commit

Permalink
Add fastrange method
Browse files Browse the repository at this point in the history
  • Loading branch information
emmt committed Oct 9, 2018
1 parent 4ca72ed commit f4d1cab
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/methods.jl
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,48 @@ densevector(::Type{T}, V::AbstractVector) where {T} = densearray(T, V)
densematrix(M::AbstractMatrix{T}) where {T} = densearray(T, M)
densematrix(::Type{T}, M::AbstractMatrix) where {T} = densearray(T, M)
@doc @doc(densearray) densematrix

"""
Any of the following calls:
```julia
fastrange(A)
fastrange((n1, n2, ...))
fastrange((i1:j1, i2:j2, ...))
fastrange(CartesianIndex(i1, i2, ...), CartesianIndex(j1, j2, ...))
fastrange(R)
```
yields an instance of `CartesianIndices` or `CartesianRange` (whichever is the
most efficient depending on the version of Julia) for multi-dimensional
indexing of all the elements of array `A`, a multi-dimensional array of
dimensions `(n1,n2,...)`, a multi-dimensional region whose first and last
indices are `(i1,i2,...)` and `(j1,j2,...)` or a Cartesian region defined by
`R`, an instance of `CartesianIndices` or of `CartesianRange`.
"""
fastrange(A::AbstractArray) = fastrange(axes(A))
@static if isdefined(Base, :CartesianIndices)
import Base: axes
fastrange(R::CartesianIndices) = R
fastrange(start::CartesianIndex{N}, stop::CartesianIndex{N}) where {N} =
CartesianIndices(map((i,j) -> i:j, start, stop))
fastrange(dims::NTuple{N,Integer}) where {N} =
CartesianIndices(map((d) -> Base.OneTo(Int(d)), dims))
fastrange(dims::NTuple{N,Int}) where {N} =
CartesianIndices(map(Base.OneTo, dims))
fastrange(dims::NTuple{N,AbstractUnitRange{<:Integer}}) where {N} =
CartesianIndices(inds)
else
import Base: indices
const axes = indices
fastrange(R::CartesianIndices) = fastrange(R.indices)
fastrange(R::CartesianRange) = R
fastrange(start::CartesianIndex{N}, stop::CartesianIndex{N}) where {N} =
CartesianRange(start, stop)
fastrange(dims::NTuple{N,Integer}) where {N} =
CartesianRange(one(CartesianIndex{N}), CartesianIndex(dims))
fastrange(dims::NTuple{N,AbstractUnitRange{<:Integer}}) where {N} =
CartesianRange(CartesianIndex(map(first, inds)),
CartesianIndex(map(last, inds)))
end

0 comments on commit f4d1cab

Please sign in to comment.