Skip to content

Commit c38d76e

Browse files
committed
use isonebased in similar(::Type{<:AbstractArray}, ax...)
1 parent 49c463b commit c38d76e

File tree

1 file changed

+11
-16
lines changed

1 file changed

+11
-16
lines changed

src/OffsetArrays.jl

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -327,30 +327,25 @@ to ensure that the axis offset is ignored, for example in `similar`.
327327
isonebased(_) = false
328328
isonebased(::Integer) = true
329329
isonebased(::Base.OneTo) = true
330-
isonebased(::IIUR{<:Base.OneTo}) = true
331-
332-
to_length(i::Integer) = i
333-
to_length(i::AbstractUnitRange) = length(i)
330+
isonebased(r::IIUR) = isonebased(r.indices)
334331

335332
# Since the following is committing type-piracy, we provide an opt-out mechanism to the users
336333
function Base.similar(A::AbstractArray, ::Type{T}, shape::Tuple{OffsetAxisKnownLength,Vararg{OffsetAxisKnownLength}}) where T
337-
if all(isonebased, shape)
338-
return similar(A, T, map(to_length, shape))
339-
else
340-
# strip IdOffsetRanges to extract the parent range and use it to generate the array
341-
new_shape = map(_strip_IdOffsetRange, shape)
342-
# route through _similar_axes_or_length to avoid a stack overflow if map(_strip_IdOffsetRange, shape) === shape
343-
# This tries to use new_shape directly in similar if similar(A, T, ::typeof(new_shape)) is defined
344-
# If this fails, it calls similar(A, T, map(_indexlength, new_shape)) to use the size along each axis
345-
# to generate the new array
346-
P = _similar_axes_or_length(A, T, new_shape, shape)
347-
return OffsetArray(P, map(_offset, axes(P), shape))
348-
end
334+
# strip IdOffsetRanges to extract the parent range and use it to generate the array
335+
new_shape = map(_strip_IdOffsetRange, shape)
336+
# route through _similar_axes_or_length to avoid a stack overflow if map(_strip_IdOffsetRange, shape) === shape
337+
# This tries to use new_shape directly in similar if similar(A, T, ::typeof(new_shape)) is defined
338+
# If this fails, it calls similar(A, T, map(_indexlength, new_shape)) to use the size along each axis
339+
# to generate the new array
340+
P = _similar_axes_or_length(A, T, new_shape, shape)
341+
all(isonebased, shape) && return P
342+
return OffsetArray(P, map(_offset, axes(P), shape))
349343
end
350344
Base.similar(::Type{A}, sz::Tuple{Vararg{Int}}) where {A<:OffsetArray} = similar(Array{eltype(A)}, sz)
351345
function Base.similar(::Type{T}, shape::Tuple{OffsetAxisKnownLength,Vararg{OffsetAxisKnownLength}}) where {T<:AbstractArray}
352346
new_shape = map(_strip_IdOffsetRange, shape)
353347
P = _similar_axes_or_length(T, new_shape, shape)
348+
all(isonebased, shape) && return P
354349
OffsetArray(P, map(_offset, axes(P), shape))
355350
end
356351
# Try to use the axes to generate the parent array type

0 commit comments

Comments
 (0)