• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / #37666

04 Nov 2023 02:27AM UTC coverage: 87.924% (+0.09%) from 87.831%
#37666

push

local

web-flow
Simplify, 16bit PDP-11 isn't going to be supported (#45763)

PDP_ENDIAN isn't used.

Co-authored-by: Viral B. Shah <ViralBShah@users.noreply.github.com>

74550 of 84789 relevant lines covered (87.92%)

15319904.67 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.9
/base/reshapedarray.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
using  Base.MultiplicativeInverses: SignedMultiplicativeInverse
4

5
struct ReshapedArray{T,N,P<:AbstractArray,MI<:Tuple{Vararg{SignedMultiplicativeInverse{Int}}}} <: AbstractArray{T,N}
6
    parent::P
129,643✔
7
    dims::NTuple{N,Int}
8
    mi::MI
9
end
10
ReshapedArray(parent::AbstractArray{T}, dims::NTuple{N,Int}, mi) where {T,N} = ReshapedArray{T,N,typeof(parent),typeof(mi)}(parent, dims, mi)
129,637✔
11

12
# IndexLinear ReshapedArray
13
const ReshapedArrayLF{T,N,P<:AbstractArray} = ReshapedArray{T,N,P,Tuple{}}
14

15
# Fast iteration on ReshapedArrays: use the parent iterator
16
struct ReshapedArrayIterator{I,M}
17
    iter::I
18
    mi::NTuple{M,SignedMultiplicativeInverse{Int}}
19
end
20
ReshapedArrayIterator(A::ReshapedArray) = _rs_iterator(parent(A), A.mi)
×
21
function _rs_iterator(P, mi::NTuple{M}) where M
×
22
    iter = eachindex(P)
×
23
    ReshapedArrayIterator{typeof(iter),M}(iter, mi)
×
24
end
25

26
struct ReshapedIndex{T}
27
    parentindex::T
4✔
28
end
29

30
# eachindex(A::ReshapedArray) = ReshapedArrayIterator(A)  # TODO: uncomment this line
31
@inline function iterate(R::ReshapedArrayIterator, i...)
×
32
    item, inext = iterate(R.iter, i...)
×
33
    ReshapedIndex(item), inext
×
34
end
35
length(R::ReshapedArrayIterator) = length(R.iter)
×
36
eltype(::Type{<:ReshapedArrayIterator{I}}) where {I} = @isdefined(I) ? ReshapedIndex{eltype(I)} : Any
×
37

38
## reshape(::Array, ::Dims) returns an Array, except for isbitsunion eltypes (issue #28611)
39
# reshaping to same # of dimensions
40
@eval function reshape(a::Array{T,M}, dims::NTuple{N,Int}) where {T,N,M}
19,299✔
41
    throw_dmrsa(dims, len) =
19,299✔
42
        throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $len"))
43
    len = Core.checked_dims(dims...) # make sure prod(dims) doesn't overflow (and because of the comparison to length(a))
19,299✔
44
    if len != length(a)
19,299✔
45
        throw_dmrsa(dims, length(a))
4✔
46
    end
47
    isbitsunion(T) && return ReshapedArray(a, dims, ())
19,292✔
48
    if N == M && dims == size(a)
23,607✔
49
        return a
4,413✔
50
    end
51
    ref = a.ref
14,839✔
52
    if M == 1 && N !== 1
14,836✔
53
        mem = ref.mem::Memory{T}
8,670✔
54
        if !(ref === GenericMemoryRef(mem) && len === mem.length)
8,670✔
55
            mem = ccall(:jl_genericmemory_slice, Memory{T}, (Any, Ptr{Cvoid}, Int), mem, ref.ptr_or_offset, len)
12✔
56
            ref = GenericMemoryRef(mem)::typeof(ref)
12✔
57
        end
58
    end
59
    # or we could use `a = Array{T,N}(undef, ntuple(0, Val(N))); a.ref = ref; a.size = dims; return a` here
60
    return $(Expr(:new, :(Array{T,N}), :ref, :dims))
14,839✔
61
end
62

63

64
"""
65
    reshape(A, dims...) -> AbstractArray
66
    reshape(A, dims) -> AbstractArray
67

68
Return an array with the same data as `A`, but with different
69
dimension sizes or number of dimensions. The two arrays share the same
70
underlying data, so that the result is mutable if and only if `A` is
71
mutable, and setting elements of one alters the values of the other.
72

73
The new dimensions may be specified either as a list of arguments or
74
as a shape tuple. At most one dimension may be specified with a `:`,
75
in which case its length is computed such that its product with all
76
the specified dimensions is equal to the length of the original array
77
`A`. The total number of elements must not change.
78

79
# Examples
80
```jldoctest
81
julia> A = Vector(1:16)
82
16-element Vector{Int64}:
83
  1
84
  2
85
  3
86
  4
87
  5
88
  6
89
  7
90
  8
91
  9
92
 10
93
 11
94
 12
95
 13
96
 14
97
 15
98
 16
99

100
julia> reshape(A, (4, 4))
101
4×4 Matrix{Int64}:
102
 1  5   9  13
103
 2  6  10  14
104
 3  7  11  15
105
 4  8  12  16
106

107
julia> reshape(A, 2, :)
108
2×8 Matrix{Int64}:
109
 1  3  5  7   9  11  13  15
110
 2  4  6  8  10  12  14  16
111

112
julia> reshape(1:6, 2, 3)
113
2×3 reshape(::UnitRange{Int64}, 2, 3) with eltype Int64:
114
 1  3  5
115
 2  4  6
116
```
117
"""
118
reshape
119

120
reshape(parent::AbstractArray, dims::IntOrInd...) = reshape(parent, dims)
1✔
121
reshape(parent::AbstractArray, shp::Tuple{Union{Integer,OneTo}, Vararg{Union{Integer,OneTo}}}) = reshape(parent, to_shape(shp))
6,456✔
122
reshape(parent::AbstractArray, dims::Dims)        = _reshape(parent, dims)
11,496✔
123

124
# Allow missing dimensions with Colon():
125
reshape(parent::AbstractVector, ::Colon) = parent
3✔
126
reshape(parent::AbstractVector, ::Tuple{Colon}) = parent
2✔
127
reshape(parent::AbstractArray, dims::Int...) = reshape(parent, dims)
14,724✔
128
reshape(parent::AbstractArray, dims::Union{Int,Colon}...) = reshape(parent, dims)
72✔
129
reshape(parent::AbstractArray, dims::Tuple{Vararg{Union{Int,Colon}}}) = reshape(parent, _reshape_uncolon(parent, dims))
80✔
130
@inline function _reshape_uncolon(A, dims)
78✔
131
    @noinline throw1(dims) = throw(DimensionMismatch(string("new dimensions $(dims) ",
80✔
132
        "may have at most one omitted dimension specified by `Colon()`")))
133
    @noinline throw2(A, dims) = throw(DimensionMismatch(string("array size $(length(A)) ",
81✔
134
        "must be divisible by the product of the new dimensions $dims")))
135
    pre = _before_colon(dims...)
78✔
136
    post = _after_colon(dims...)
78✔
137
    _any_colon(post...) && throw1(dims)
78✔
138
    sz, remainder = divrem(length(A), prod(pre)*prod(post))
76✔
139
    remainder == 0 || throw2(A, dims)
79✔
140
    (pre..., Int(sz), post...)
73✔
141
end
142
@inline _any_colon() = false
76✔
143
@inline _any_colon(dim::Colon, tail...) = true
2✔
144
@inline _any_colon(dim::Any, tail...) = _any_colon(tail...)
35✔
145
@inline _before_colon(dim::Any, tail...) = (dim, _before_colon(tail...)...)
24✔
146
@inline _before_colon(dim::Colon, tail...) = ()
78✔
147
@inline _after_colon(dim::Any, tail...) =  _after_colon(tail...)
24✔
148
@inline _after_colon(dim::Colon, tail...) = tail
78✔
149

150
reshape(parent::AbstractArray{T,N}, ndims::Val{N}) where {T,N} = parent
480,417✔
151
function reshape(parent::AbstractArray, ndims::Val{N}) where N
6,387✔
152
    reshape(parent, rdims(Val(N), axes(parent)))
6,387✔
153
end
154

155
# Move elements from inds to out until out reaches the desired
156
# dimensionality N, either filling with OneTo(1) or collapsing the
157
# product of trailing dims into the last element
158
rdims_trailing(l, inds...) = length(l) * rdims_trailing(inds...)
6,288✔
159
rdims_trailing(l) = length(l)
5,879✔
160
rdims(out::Val{N}, inds::Tuple) where {N} = rdims(ntuple(Returns(OneTo(1)), Val(N)), inds)
6,387✔
161
rdims(out::Tuple{}, inds::Tuple{}) = () # N == 0, M == 0
×
162
rdims(out::Tuple{}, inds::Tuple{Any}) = ()
6✔
163
rdims(out::Tuple{}, inds::NTuple{M,Any}) where {M} = ()
×
164
rdims(out::Tuple{Any}, inds::Tuple{}) = out # N == 1, M == 0
494✔
165
rdims(out::NTuple{N,Any}, inds::Tuple{}) where {N} = out # N > 1, M == 0
8✔
166
rdims(out::Tuple{Any}, inds::Tuple{Any}) = inds # N == 1, M == 1
×
167
rdims(out::Tuple{Any}, inds::NTuple{M,Any}) where {M} = (oneto(rdims_trailing(inds...)),) # N == 1, M > 1
5,879✔
168
rdims(out::NTuple{N,Any}, inds::NTuple{N,Any}) where {N} = inds # N > 1, M == N
×
169
rdims(out::NTuple{N,Any}, inds::NTuple{M,Any}) where {N,M} = (first(inds), rdims(tail(out), tail(inds))...) # N > 1, M > 1, M != N
546✔
170

171

172
# _reshape on Array returns an Array
173
_reshape(parent::Vector, dims::Dims{1}) = parent
2✔
174
_reshape(parent::Array, dims::Dims{1}) = reshape(parent, dims)
×
175
_reshape(parent::Array, dims::Dims) = reshape(parent, dims)
×
176

177
# When reshaping Vector->Vector, don't wrap with a ReshapedArray
178
function _reshape(v::AbstractVector, dims::Dims{1})
37✔
179
    require_one_based_indexing(v)
37✔
180
    len = dims[1]
37✔
181
    len == length(v) || _throw_dmrs(length(v), "length", len)
38✔
182
    v
36✔
183
end
184
# General reshape
185
function _reshape(parent::AbstractArray, dims::Dims)
11,449✔
186
    n = length(parent)
11,449✔
187
    prod(dims) == n || _throw_dmrs(n, "size", dims)
11,462✔
188
    __reshape((parent, IndexStyle(parent)), dims)
11,436✔
189
end
190

191
@noinline function _throw_dmrs(n, str, dims)
14✔
192
    throw(DimensionMismatch("parent has $n elements, which is incompatible with $str $dims"))
14✔
193
end
194

195
# Reshaping a ReshapedArray
196
_reshape(v::ReshapedArray{<:Any,1}, dims::Dims{1}) = _reshape(v.parent, dims)
2✔
197
_reshape(R::ReshapedArray, dims::Dims) = _reshape(R.parent, dims)
28✔
198

199
function __reshape(p::Tuple{AbstractArray,IndexStyle}, dims::Dims)
6,865✔
200
    parent = p[1]
6,865✔
201
    strds = front(size_to_strides(map(length, axes(parent))..., 1))
6,865✔
202
    strds1 = map(s->max(1,Int(s)), strds)  # for resizing empty arrays
13,734✔
203
    mi = map(SignedMultiplicativeInverse, strds1)
6,865✔
204
    ReshapedArray(parent, dims, reverse(mi))
6,865✔
205
end
206

207
function __reshape(p::Tuple{AbstractArray{<:Any,0},IndexCartesian}, dims::Dims)
4✔
208
    parent = p[1]
4✔
209
    ReshapedArray(parent, dims, ())
4✔
210
end
211

212
function __reshape(p::Tuple{AbstractArray,IndexLinear}, dims::Dims)
4,567✔
213
    parent = p[1]
4,567✔
214
    ReshapedArray(parent, dims, ())
4,567✔
215
end
216

217
size(A::ReshapedArray) = A.dims
4,154,347✔
218
length(A::ReshapedArray) = length(parent(A))
8,057,303✔
219
similar(A::ReshapedArray, eltype::Type, dims::Dims) = similar(parent(A), eltype, dims)
5,276✔
220
IndexStyle(::Type{<:ReshapedArrayLF}) = IndexLinear()
21,024✔
221
parent(A::ReshapedArray) = A.parent
17,244,770✔
222
parentindices(A::ReshapedArray) = map(oneto, size(parent(A)))
2✔
223
reinterpret(::Type{T}, A::ReshapedArray, dims::Dims) where {T} = reinterpret(T, parent(A), dims)
×
224
elsize(::Type{<:ReshapedArray{<:Any,<:Any,P}}) where {P} = elsize(P)
6,834✔
225

226
unaliascopy(A::ReshapedArray) = typeof(A)(unaliascopy(A.parent), A.dims, A.mi)
6✔
227
dataids(A::ReshapedArray) = dataids(A.parent)
5,143✔
228

229
@inline ind2sub_rs(ax, ::Tuple{}, i::Int) = (i,)
90,269✔
230
@inline ind2sub_rs(ax, strds, i) = _ind2sub_rs(ax, strds, i - 1)
1,773,781✔
231
@inline _ind2sub_rs(ax, ::Tuple{}, ind) = (ind + first(ax[end]),)
1,773,781✔
232
@inline function _ind2sub_rs(ax, strds, ind)
3,364,299✔
233
    d, r = divrem(ind, strds[1])
3,364,299✔
234
    (_ind2sub_rs(front(ax), tail(strds), r)..., d + first(ax[end]))
3,364,299✔
235
end
236
offset_if_vec(i::Integer, axs::Tuple{<:AbstractUnitRange}) = i + first(axs[1]) - 1
73,175✔
237
offset_if_vec(i::Integer, axs::Tuple) = i
1,660,369✔
238

239
@inline function isassigned(A::ReshapedArrayLF, index::Int)
4,008,803✔
240
    @boundscheck checkbounds(Bool, A, index) || return false
4,008,803✔
241
    @inbounds ret = isassigned(parent(A), index)
4,008,803✔
242
    ret
4,008,803✔
243
end
244
@inline function isassigned(A::ReshapedArray{T,N}, indices::Vararg{Int, N}) where {T,N}
595,839✔
245
    @boundscheck checkbounds(Bool, A, indices...) || return false
595,839✔
246
    axp = axes(A.parent)
595,839✔
247
    i = offset_if_vec(_sub2ind(size(A), indices...), axp)
595,839✔
248
    I = ind2sub_rs(axp, A.mi, i)
595,839✔
249
    @inbounds isassigned(A.parent, I...)
595,839✔
250
end
251

252
@inline function getindex(A::ReshapedArrayLF, index::Int)
4,026,726✔
253
    @boundscheck checkbounds(A, index)
4,026,726✔
254
    @inbounds ret = parent(A)[index]
4,027,025✔
255
    ret
4,026,726✔
256
end
257
@inline function getindex(A::ReshapedArray{T,N}, indices::Vararg{Int,N}) where {T,N}
1,136,214✔
258
    @boundscheck checkbounds(A, indices...)
1,136,216✔
259
    _unsafe_getindex(A, indices...)
1,137,160✔
260
end
261
@inline function getindex(A::ReshapedArray, index::ReshapedIndex)
2✔
262
    @boundscheck checkbounds(parent(A), index.parentindex)
2✔
263
    @inbounds ret = parent(A)[index.parentindex]
2✔
264
    ret
2✔
265
end
266

267
@inline function _unsafe_getindex(A::ReshapedArray{T,N}, indices::Vararg{Int,N}) where {T,N}
1,136,212✔
268
    axp = axes(A.parent)
1,136,212✔
269
    i = offset_if_vec(_sub2ind(size(A), indices...), axp)
1,136,212✔
270
    I = ind2sub_rs(axp, A.mi, i)
1,136,212✔
271
    _unsafe_getindex_rs(parent(A), I)
1,137,160✔
272
end
273
@inline _unsafe_getindex_rs(A, i::Integer) = (@inbounds ret = A[i]; ret)
×
274
@inline _unsafe_getindex_rs(A, I) = (@inbounds ret = A[I...]; ret)
2,273,372✔
275

276
@inline function setindex!(A::ReshapedArrayLF, val, index::Int)
258✔
277
    @boundscheck checkbounds(A, index)
258✔
278
    @inbounds parent(A)[index] = val
258✔
279
    val
258✔
280
end
281
@inline function setindex!(A::ReshapedArray{T,N}, val, indices::Vararg{Int,N}) where {T,N}
1,493✔
282
    @boundscheck checkbounds(A, indices...)
1,493✔
283
    _unsafe_setindex!(A, val, indices...)
1,493✔
284
end
285
@inline function setindex!(A::ReshapedArray, val, index::ReshapedIndex)
1✔
286
    @boundscheck checkbounds(parent(A), index.parentindex)
1✔
287
    @inbounds parent(A)[index.parentindex] = val
1✔
288
    val
1✔
289
end
290

291
@inline function _unsafe_setindex!(A::ReshapedArray{T,N}, val, indices::Vararg{Int,N}) where {T,N}
1,493✔
292
    axp = axes(A.parent)
1,493✔
293
    i = offset_if_vec(_sub2ind(size(A), indices...), axp)
1,493✔
294
    @inbounds parent(A)[ind2sub_rs(axes(A.parent), A.mi, i)...] = val
1,493✔
295
    val
1,493✔
296
end
297

298
# helpful error message for a common failure case
299
const ReshapedRange{T,N,A<:AbstractRange} = ReshapedArray{T,N,A,Tuple{}}
300
setindex!(A::ReshapedRange, val, index::Int) = _rs_setindex!_err()
1✔
301
setindex!(A::ReshapedRange{T,N}, val, indices::Vararg{Int,N}) where {T,N} = _rs_setindex!_err()
1✔
302
setindex!(A::ReshapedRange, val, index::ReshapedIndex) = _rs_setindex!_err()
1✔
303

304
@noinline _rs_setindex!_err() = error("indexed assignment fails for a reshaped range; consider calling collect")
3✔
305

306
cconvert(::Type{Ptr{T}}, a::ReshapedArray{T}) where {T} = cconvert(Ptr{T}, parent(a))
6,774✔
307

308
# Add a few handy specializations to further speed up views of reshaped ranges
309
const ReshapedUnitRange{T,N,A<:AbstractUnitRange} = ReshapedArray{T,N,A,Tuple{}}
310
viewindexing(I::Tuple{Slice, ReshapedUnitRange, Vararg{ScalarIndex}}) = IndexLinear()
2✔
311
viewindexing(I::Tuple{ReshapedRange, Vararg{ScalarIndex}}) = IndexLinear()
5✔
312
compute_stride1(s, inds, I::Tuple{ReshapedRange, Vararg{Any}}) = s*step(I[1].parent)
5✔
313
compute_offset1(parent::AbstractVector, stride1::Integer, I::Tuple{ReshapedRange}) =
1✔
314
    (@inline; first(I[1]) - first(axes1(I[1]))*stride1)
1✔
315
substrides(strds::NTuple{N,Int}, I::Tuple{ReshapedUnitRange, Vararg{Any}}) where N =
198✔
316
    (size_to_strides(strds[1], size(I[1])...)..., substrides(tail(strds), tail(I))...)
317

318
# cconvert(::Type{<:Ptr}, V::SubArray{T,N,P,<:Tuple{Vararg{Union{RangeIndex,ReshapedUnitRange}}}}) where {T,N,P} = V
319
function unsafe_convert(::Type{Ptr{S}}, V::SubArray{T,N,P,<:Tuple{Vararg{Union{RangeIndex,ReshapedUnitRange}}}}) where {S,T,N,P}
725,790✔
320
    parent = V.parent
725,851✔
321
    p = cconvert(Ptr{T}, parent) # XXX: this should occur in cconvert, the result is not GC-rooted
1,624,315✔
322
    Δmem = if _checkcontiguous(Bool, parent)
724,762✔
323
        (first_index(V) - firstindex(parent)) * elsize(parent)
1,159,895✔
324
    else
325
        _memory_offset(parent, map(first, V.indices)...)
22,840✔
326
    end
327
    return Ptr{S}(unsafe_convert(Ptr{T}, p) + Δmem)
1,624,315✔
328
end
329

330
_checkcontiguous(::Type{Bool}, A::AbstractArray) = false
30,179✔
331
# `strides(A::DenseArray)` calls `size_to_strides` by default.
332
# Thus it's OK to assume all `DenseArray`s are contiguously stored.
333
_checkcontiguous(::Type{Bool}, A::DenseArray) = true
135,295✔
334
_checkcontiguous(::Type{Bool}, A::ReshapedArray) = _checkcontiguous(Bool, parent(A))
1,903✔
335
_checkcontiguous(::Type{Bool}, A::FastContiguousSubArray) = _checkcontiguous(Bool, parent(A))
847,545✔
336

337
function strides(a::ReshapedArray)
1,696✔
338
    _checkcontiguous(Bool, a) && return size_to_strides(1, size(a)...)
1,696✔
339
    apsz::Dims = size(a.parent)
1,674✔
340
    apst::Dims = strides(a.parent)
1,674✔
341
    msz, mst, n = merge_adjacent_dim(apsz, apst) # Try to perform "lazy" reshape
1,674✔
342
    n == ndims(a.parent) && return size_to_strides(mst, size(a)...) # Parent is stridevector like
1,674✔
343
    return _reshaped_strides(size(a), 1, msz, mst, n, apsz, apst)
581✔
344
end
345

346
function _reshaped_strides(::Dims{0}, reshaped::Int, msz::Int, ::Int, ::Int, ::Dims, ::Dims)
581✔
347
    reshaped == msz && return ()
581✔
348
    throw(ArgumentError("Input is not strided."))
5✔
349
end
350
function _reshaped_strides(sz::Dims, reshaped::Int, msz::Int, mst::Int, n::Int, apsz::Dims, apst::Dims)
2,924✔
351
    st = reshaped * mst
2,924✔
352
    reshaped = reshaped * sz[1]
2,924✔
353
    if length(sz) > 1 && reshaped == msz && sz[2] != 1
2,924✔
354
        msz, mst, n = merge_adjacent_dim(apsz, apst, n + 1)
576✔
355
        reshaped = 1
576✔
356
    end
357
    sts = _reshaped_strides(tail(sz), reshaped, msz, mst, n, apsz, apst)
2,937✔
358
    return (st, sts...)
2,908✔
359
end
360

361
merge_adjacent_dim(::Dims{0}, ::Dims{0}) = 1, 1, 0
1✔
362
merge_adjacent_dim(apsz::Dims{1}, apst::Dims{1}) = apsz[1], apst[1], 1
3,313✔
363
function merge_adjacent_dim(apsz::Dims{N}, apst::Dims{N}, n::Int = 1) where {N}
2,429✔
364
    sz, st = apsz[n], apst[n]
2,412✔
365
    while n < N
1,848✔
366
        szₙ, stₙ = apsz[n+1], apst[n+1]
942✔
367
        if sz == 1
942✔
368
            sz, st = szₙ, stₙ
3✔
369
        elseif stₙ == st * sz || szₙ == 1
1,544✔
370
            sz *= szₙ
351✔
371
        else
372
            break
588✔
373
        end
374
        n += 1
354✔
375
    end
354✔
376
    return sz, st, n
1,494✔
377
end
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc