Skip to content

Commit 0e8722c

Browse files
committed
fix linear indexing for ReshapedArray
1 parent d09a290 commit 0e8722c

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

base/reshapedarray.jl

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,6 @@ function _reshape(v::AbstractVector, dims::Dims{1})
172172
end
173173
# General reshape
174174
function _reshape(parent::AbstractArray, dims::Dims)
175-
require_one_based_indexing(parent)
176175
n = length(parent)
177176
prod(dims) == n || _throw_dmrs(n, "size", dims)
178177
__reshape((parent, IndexStyle(parent)), dims)
@@ -227,7 +226,8 @@ offset_if_vec(i::Integer, axs::Tuple) = i
227226

228227
@inline function getindex(A::ReshapedArrayLF, index::Int)
229228
@boundscheck checkbounds(A, index)
230-
@inbounds ret = parent(A)[index]
229+
indexparent = index - firstindex(A) + firstindex(parent(A))
230+
@inbounds ret = parent(A)[indexparent]
231231
ret
232232
end
233233
@inline function getindex(A::ReshapedArray{T,N}, indices::Vararg{Int,N}) where {T,N}
@@ -251,7 +251,8 @@ end
251251

252252
@inline function setindex!(A::ReshapedArrayLF, val, index::Int)
253253
@boundscheck checkbounds(A, index)
254-
@inbounds parent(A)[index] = val
254+
indexparent = index - firstindex(A) + firstindex(parent(A))
255+
@inbounds parent(A)[indexparent] = val
255256
val
256257
end
257258
@inline function setindex!(A::ReshapedArray{T,N}, val, indices::Vararg{Int,N}) where {T,N}

test/abstractarray.jl

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1414,5 +1414,29 @@ end
14141414
end
14151415

14161416
@testset "reshape for offset arrays" begin
1417-
@test_throws ArgumentError reshape(Base.IdentityUnitRange(0:1), (2,1))
1417+
r = reshape(Base.IdentityUnitRange(0:1), (2,1))
1418+
@test r[eachindex(r)] == [0:1;]
1419+
1420+
struct ZeroBasedArray{T,N,A<:AbstractArray{T,N}} <: AbstractArray{T,N}
1421+
a :: A
1422+
function ZeroBasedArray(a::AbstractArray)
1423+
Base.require_one_based_indexing(a)
1424+
new{eltype(a), ndims(a), typeof(a)}(a)
1425+
end
1426+
end
1427+
Base.parent(z::ZeroBasedArray) = z.a
1428+
Base.size(z::ZeroBasedArray) = size(parent(z))
1429+
Base.axes(z::ZeroBasedArray) = map(x -> Base.IdentityUnitRange(0:x - 1), size(parent(z)))
1430+
Base.getindex(z::ZeroBasedArray{<:Any, N}, i::Vararg{Int,N}) where {N} = parent(z)[map(x -> x + 1, i)...]
1431+
Base.setindex!(z::ZeroBasedArray{<:Any, N}, val, i::Vararg{Int,N}) where {N} = parent(z)[map(x -> x + 1, i)...] = val
1432+
1433+
z = ZeroBasedArray(collect(1:4))
1434+
r2 = reshape(z, (4, 1))
1435+
@test r2[CartesianIndices(r2)] == r2[LinearIndices(r2)]
1436+
r2[firstindex(r2)] = 34
1437+
@test z[0] == 34
1438+
r2[eachindex(r2)] = r2 .* 2
1439+
for (i, j) in zip(eachindex(r2), eachindex(z))
1440+
@test r2[i] == z[j]
1441+
end
14181442
end

0 commit comments

Comments
 (0)