@@ -127,6 +127,11 @@ _maybe_reshape_parent(A::AbstractArray, ::NTuple{1, Bool}) = reshape(A, Val(1))
127127_maybe_reshape_parent (A:: AbstractArray{<:Any,1} , :: NTuple{1, Bool} ) = reshape (A, Val (1 ))
128128_maybe_reshape_parent (A:: AbstractArray{<:Any,N} , :: NTuple{N, Bool} ) where {N} = A
129129_maybe_reshape_parent (A:: AbstractArray , :: NTuple{N, Bool} ) where {N} = reshape (A, Val (N))
130+ # The trailing singleton indices could be eliminated after bounds checking.
131+ rm_singleton_indices (ndims:: Tuple , J1, Js... ) = (J1, rm_singleton_indices (IteratorsMD. _splitrest (ndims, index_ndims (J1)), Js... )... )
132+ rm_singleton_indices (:: Tuple{} , :: ScalarIndex , Js... ) = rm_singleton_indices ((), Js... )
133+ rm_singleton_indices (:: Tuple ) = ()
134+
130135"""
131136 view(A, inds...)
132137
@@ -173,15 +178,12 @@ julia> view(2:5, 2:3) # returns a range as type is immutable
1731783:4
174179```
175180"""
176- function view (A:: AbstractArray{<:Any,N} , I:: Vararg{Any,M} ) where {N, M}
181+ function view (A:: AbstractArray , I:: Vararg{Any,M} ) where {M}
177182 @inline
178183 J = map (i-> unalias (A,i), to_indices (A, I))
179184 @boundscheck checkbounds (A, J... )
180- if length (J) > ndims (A) && J[N+ 1 : end ] isa Tuple{Vararg{Int}}
181- # view([1,2,3], :, 1) does not need to reshape
182- return unsafe_view (A, J[1 : N]. .. )
183- end
184- unsafe_view (_maybe_reshape_parent (A, index_ndims (J... )), J... )
185+ J′ = rm_singleton_indices (ntuple (Returns (true ), Val (ndims (A))), J... )
186+ unsafe_view (_maybe_reshape_parent (A, index_ndims (J′... )), J′... )
185187end
186188
187189# Ranges implement getindex to return recomputed ranges; use that for views, too (when possible)
0 commit comments