Skip to content

Commit 643a447

Browse files
authored
similar does not accept colons as indices (#126)
This attempts to get around #122 by explicitly preventing colons being passed to similar. This means that the StackOverflowError now becomes a MethodError
1 parent eae28f9 commit 643a447

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

src/OffsetArrays.jl

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,14 +95,17 @@ Base.eachindex(::IndexLinear, A::OffsetVector) = axes(A, 1)
9595
@inline Base.axes(A::OffsetArray, d) = d <= ndims(A) ? IdOffsetRange(axes(parent(A), d), A.offsets[d]) : IdOffsetRange(axes(parent(A), d))
9696
@inline Base.axes1(A::OffsetArray{T,0}) where {T} = IdOffsetRange(axes(parent(A), 1)) # we only need to specialize this one
9797

98-
const OffsetAxis = Union{Integer, UnitRange, Base.OneTo, IdentityUnitRange, IdOffsetRange, Colon}
98+
const OffsetAxisKnownLength = Union{Integer, UnitRange, Base.OneTo, IdentityUnitRange, IdOffsetRange}
99+
99100
Base.similar(A::OffsetArray, ::Type{T}, dims::Dims) where T =
100101
similar(parent(A), T, dims)
101-
function Base.similar(A::AbstractArray, ::Type{T}, inds::Tuple{OffsetAxis,Vararg{OffsetAxis}}) where T
102+
function Base.similar(A::AbstractArray, ::Type{T}, inds::Tuple{OffsetAxisKnownLength,Vararg{OffsetAxisKnownLength}}) where T
102103
B = similar(A, T, map(indexlength, inds))
103104
return OffsetArray(B, map(offset, axes(B), inds))
104105
end
105106

107+
# reshape accepts a single colon
108+
const OffsetAxis = Union{OffsetAxisKnownLength, Colon}
106109
Base.reshape(A::AbstractArray, inds::OffsetAxis...) = reshape(A, inds)
107110
function Base.reshape(A::AbstractArray, inds::Tuple{OffsetAxis,Vararg{OffsetAxis}})
108111
AR = reshape(A, map(indexlength, inds))

test/runtests.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,12 @@ end
424424
B = similar(Array{Int}, (0:0, 3))
425425
@test isa(B, OffsetArray{Int, 2})
426426
@test axes(B) == (0:0, 1:3)
427+
428+
@test_throws MethodError similar(A, (:,))
429+
@test_throws MethodError similar(A, (: ,:))
430+
@test_throws MethodError similar(A, (: ,2))
431+
@test_throws MethodError similar(A, Float64, (: ,:))
432+
@test_throws MethodError similar(A, Float64, (: ,2))
427433
end
428434

429435
@testset "reshape" begin

0 commit comments

Comments
 (0)