Skip to content

Commit 1fb77f5

Browse files
authored
Index trait for resulting array's shape (#314)
1 parent 7c7daec commit 1fb77f5

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

lib/ArrayInterfaceCore/Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name = "ArrayInterfaceCore"
22
uuid = "30b0a656-2188-435a-8636-2ec0e6a096e2"
3-
version = "0.1.10"
3+
version = "0.1.11"
44

55
[deps]
66
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"

lib/ArrayInterfaceCore/src/ArrayInterfaceCore.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,20 @@ ndims_index(@nospecialize T::Type{<:Base.LogicalIndex}) = ndims(fieldtype(T, :ma
548548
ndims_index(T::Type) = 1
549549
ndims_index(@nospecialize(i)) = ndims_index(typeof(i))
550550

551+
"""
552+
ndims_shape(::Type{I}) -> Union{Int,Tuple{Vararg{Int}}}
553+
554+
Returns the number of dimension that are represented in shape of the returned array when
555+
indexing with an instance of `I`.
556+
"""
557+
ndims_shape(T::DataType) = ndims_index(T)
558+
ndims_shape(::Type{Colon}) = 1
559+
ndims_shape(T::Type{<:Base.AbstractCartesianIndex{N}}) where {N} = ntuple(zero, Val{N}())
560+
ndims_shape(@nospecialize T::Type{<:CartesianIndices}) = ntuple(one, Val{ndims(T)}())
561+
ndims_shape(@nospecialize T::Type{<:Number}) = 0
562+
ndims_shape(@nospecialize T::Type{<:AbstractArray}) = ndims(T)
563+
ndims_shape(x) = ndims_shape(typeof(x))
564+
551565
"""
552566
instances_do_not_alias(::Type{T}) -> Bool
553567

lib/ArrayInterfaceCore/test/runtests.jl

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,14 @@ end
268268
@test @inferred(ArrayInterfaceCore.ndims_index(1)) == 1
269269
end
270270

271+
@testset "ndims_shape" begin
272+
@test @inferred(ArrayInterfaceCore.ndims_shape(1)) === 0
273+
@test @inferred(ArrayInterfaceCore.ndims_shape(:)) === 1
274+
@test @inferred(ArrayInterfaceCore.ndims_shape(CartesianIndex(1, 2))) === (0, 0)
275+
@test @inferred(ArrayInterfaceCore.ndims_shape(CartesianIndices((2,2)))) === (1, 1)
276+
@test @inferred(ArrayInterfaceCore.ndims_shape([1 1])) === 2
277+
end
278+
271279
@testset "indices_do_not_alias" begin
272280
@test ArrayInterfaceCore.instances_do_not_alias(Float64)
273281
@test !ArrayInterfaceCore.instances_do_not_alias(Matrix{Float64})
@@ -285,4 +293,3 @@ end
285293
@test !ArrayInterfaceCore.indices_do_not_alias(typeof(view(fill(rand(4,4),4,4)', 2:3, 1:2)))
286294
@test !ArrayInterfaceCore.indices_do_not_alias(typeof(view(rand(4,4)', StepRangeLen(1,0,5), 1:2)))
287295
end
288-

0 commit comments

Comments
 (0)