Skip to content

Commit 3559b72

Browse files
authored
fix an edge constructor bug in LinearIndices (#37928)
1 parent 74d017c commit 3559b72

File tree

2 files changed

+56
-2
lines changed

2 files changed

+56
-2
lines changed

base/indices.jl

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -451,11 +451,13 @@ end
451451
LinearIndices(::Tuple{}) = LinearIndices{0,typeof(())}(())
452452
LinearIndices(inds::NTuple{N,AbstractUnitRange{<:Integer}}) where {N} =
453453
LinearIndices(map(r->convert(AbstractUnitRange{Int}, r), inds))
454-
LinearIndices(sz::NTuple{N,<:Integer}) where {N} = LinearIndices(map(Base.OneTo, sz))
455454
LinearIndices(inds::NTuple{N,Union{<:Integer,AbstractUnitRange{<:Integer}}}) where {N} =
456-
LinearIndices(map(i->first(i):last(i), inds))
455+
LinearIndices(map(_convert2ind, inds))
457456
LinearIndices(A::Union{AbstractArray,SimpleVector}) = LinearIndices(axes(A))
458457

458+
_convert2ind(i::Integer) = Base.OneTo(i)
459+
_convert2ind(ind::AbstractUnitRange) = first(ind):last(ind)
460+
459461
promote_rule(::Type{LinearIndices{N,R1}}, ::Type{LinearIndices{N,R2}}) where {N,R1,R2} =
460462
LinearIndices{N,indices_promote_type(R1,R2)}
461463

test/abstractarray.jl

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,58 @@ end
225225
end
226226
end
227227

228+
@testset "LinearIndices" begin
229+
@testset "constructors" begin
230+
for oinds in [
231+
(2, 3),
232+
(UInt8(2), 3),
233+
(2, UInt8(3)),
234+
(2, 1:3),
235+
(Base.OneTo(2), 1:3)
236+
]
237+
R = LinearIndices(oinds)
238+
@test size(R) == (2, 3)
239+
@test axes(R) == (Base.OneTo(2), Base.OneTo(3))
240+
@test R[begin] == 1
241+
@test R[end] == 6
242+
end
243+
244+
for oinds in [(2, ), (2, 3), (2, 3, 4)]
245+
R = CartesianIndices(oinds)
246+
@test size(R) == oinds
247+
end
248+
end
249+
250+
@testset "IdentityUnitRange" begin
251+
function _collect(A)
252+
rst = eltype(A)[]
253+
for i in A
254+
push!(rst, i)
255+
end
256+
rst
257+
end
258+
function _simd_collect(A)
259+
rst = eltype(A)[]
260+
@simd for i in A
261+
push!(rst, i)
262+
end
263+
rst
264+
end
265+
266+
for oinds in [
267+
(Base.IdentityUnitRange(0:1),),
268+
(Base.IdentityUnitRange(0:1), Base.IdentityUnitRange(0:2)),
269+
(Base.IdentityUnitRange(0:1), Base.OneTo(3)),
270+
]
271+
R = LinearIndices(oinds)
272+
@test axes(R) === oinds
273+
@test _collect(R) == _simd_collect(R) == vec(collect(R))
274+
end
275+
R = LinearIndices((Base.IdentityUnitRange(0:1), 0:1))
276+
@test axes(R) == (Base.IdentityUnitRange(0:1), Base.OneTo(2))
277+
end
278+
end
279+
228280
# token type on which to dispatch testing methods in order to avoid potential
229281
# name conflicts elsewhere in the base test suite
230282
mutable struct TestAbstractArray end

0 commit comments

Comments
 (0)