Skip to content

Commit ed73c99

Browse files
authored
Merge pull request #19 from putianyi889/version-0.0.4.7
support CartesianIndices
2 parents 4de713c + 96f3460 commit ed73c99

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

src/EltypeExtensions.jl

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ end
2020
"""
2121
elconvert(T, A)
2222
23-
Similar to `convert(T, A)`, but `T` refers to the eltype.
23+
Similar to `convert(T, A)`, but `T` refers to the eltype. See also [`_to_eltype`](@ref).
2424
2525
# Examples
2626
```jldoctest; setup = :(using EltypeExtensions: elconvert)
@@ -40,17 +40,26 @@ elconvert(::Type{T}, A::Tuple) where T = convert.(T, A)
4040
"""
4141
_to_eltype(T, S)
4242
43-
Convert type `S` to have the `eltype` of `T`.
43+
Convert type `S` to have the `eltype` of `T`. See also [`elconvert`](@ref).
4444
"""
45-
_to_eltype(::Type{T}, ::Type{S}) where {T,S} = eltype(S) == S ? T : MethodError(_to_eltype, T, S)
45+
_to_eltype(::Type{T}, ::Type{S}) where {T,S} = eltype(S) == S ? T : eltype(S) == T ? S : MethodError(_to_eltype, T, S)
4646
_to_eltype(::Type{T}, ::Type{Array{S,N}}) where {T,S,N} = Array{T,N}
4747
_to_eltype(::Type{T}, ::Type{<:Set}) where T = Set{T}
4848
for TYP in (Adjoint, Diagonal, Hermitian, Symmetric, SymTridiagonal, Transpose)
49+
@eval _to_eltype(::Type{T}, ::Type{$TYP}) where T = $TYP{T}
50+
@eval _to_eltype(::Type{T}, ::Type{$TYP{S}}) where {T,S} = $TYP{T}
4951
@eval _to_eltype(::Type{T}, ::Type{$TYP{S,M}}) where {T,S,M} = $TYP{T,_to_eltype(T,M)}
5052
@eval elconvert(::Type{T}, A::S) where {T,S<:$TYP} = convert(_to_eltype(T, S), A)
5153
end
5254
_to_eltype(::Type{T}, ::Type{<:UnitRange}) where T<:Integer = UnitRange{T}
5355

56+
@static if VERSION >= v"1.6"
57+
_to_eltype(::Type{CartesianIndex{N}}, ::Type{CartesianIndices{N,R}}) where {N, R<:Tuple{Vararg{OrdinalRange{Int64, Int64}, N}}} = CartesianIndices{N,R}
58+
else
59+
_to_eltype(::Type{CartesianIndex{N}}, ::Type{CartesianIndices{N,R}}) where {N, R<:Tuple{Vararg{AbstractUnitRange{Int64},N}}} = CartesianIndices{N,R}
60+
end
61+
_to_eltype(::Type{T}, ::Type{<:CartesianIndices}) where T = Array{T}
62+
5463
@static if VERSION >= v"1.7"
5564
_to_eltype(::Type{T}, ::Type{<:UnitRange}) where T<:Real = StepRangeLen{T,Base.TwicePrecision{T},Base.TwicePrecision{T},Int}
5665
else

test/runtests.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ end
2424
r = 1:5
2525
testelconvert(Int8, r)
2626
testelconvert(Float64, r)
27+
28+
inds = CartesianIndex(1,1):CartesianIndex(3,3)
29+
testelconvert(CartesianIndex{2}, inds)
30+
testelconvert(Tuple, inds)
2731
end
2832

2933
@testset "bugs" begin

0 commit comments

Comments
 (0)