Skip to content

Commit

Permalink
Support Base.Slice axes (fixes #548)
Browse files Browse the repository at this point in the history
  • Loading branch information
timholy committed Nov 19, 2018
1 parent 4f089af commit bb4aca8
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ similar(::Type{A}, shape::Tuple{SOneTo, Vararg{SOneTo}}) where {A<:AbstractArray
similar(::A,::Type{T}, shape::Tuple{SOneTo, Vararg{SOneTo}}) where {A<:AbstractArray,T} = similar(A, T, Size(last.(shape)))
similar(::Type{A},::Type{T}, shape::Tuple{SOneTo, Vararg{SOneTo}}) where {A<:AbstractArray,T} = similar(A, T, Size(last.(shape)))

const SOneToLike{n} = Union{SOneTo{n}, Base.Slice{SOneTo{n}}}
deslice(ax::SOneTo) = ax
deslice(ax::Base.Slice) = ax.indices
similar(::A,::Type{T}, shape::Tuple{SOneToLike, Vararg{SOneToLike}}) where {A<:AbstractArray,T} = similar(A, T, Size(last.(deslice.(shape))))
similar(::Type{A},::Type{T}, shape::Tuple{SOneToLike, Vararg{SOneToLike}}) where {A<:AbstractArray,T} = similar(A, T, Size(last.(deslice.(shape))))

# Handle mixtures of SOneTo and other ranges (probably should make Base more robust here)
similar(::Type{A}, shape::Tuple{AbstractUnitRange, Vararg{AbstractUnitRange}}) where {A<:AbstractArray} = similar(A, length.(shape)) # Jumps back to 2-argument form in Base
similar(::Type{A},::Type{T}, shape::Tuple{AbstractUnitRange, Vararg{AbstractUnitRange}}) where {A<:AbstractArray,T} = similar(A, length.(shape))
Expand Down
6 changes: 6 additions & 0 deletions test/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ using StaticArrays, Test, LinearAlgebra
@test isa(@inferred(similar(Matrix{Int}, Int, Size(2,2))), SizedArray{Tuple{2, 2}, Int, 2, 2})
end

@testset "similar and Base.Slice (issue #548)" begin
v = @SVector [1]
b = similar(v, Int, Base.Slice(SOneTo(3)))
@test b isa MVector{3,Int}
end

@testset "reshape" begin
@test @inferred(reshape(SVector(1,2,3,4), Size(2,2))) === SMatrix{2,2}(1,2,3,4)
@test @inferred(reshape([1,2,3,4], Size(2,2)))::SizedArray{Tuple{2,2},Int,2,1} == [1 3; 2 4]
Expand Down

0 comments on commit bb4aca8

Please sign in to comment.