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

JuliaLang / julia / #37545

pending completion
#37545

push

local

web-flow
Fix jl_timing_show_method_instance for top-level thunks (#49862)

This was causing invalid pointer dereferences when the method instance
had no backing method.

72631 of 83733 relevant lines covered (86.74%)

33727021.22 hits per line

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

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

3
module PermutedDimsArrays
4

5
import Base: permutedims, permutedims!
6
export PermutedDimsArray
7

8
# Some day we will want storage-order-aware iteration, so put perm in the parameters
9
struct PermutedDimsArray{T,N,perm,iperm,AA<:AbstractArray} <: AbstractArray{T,N}
10
    parent::AA
11

12
    function PermutedDimsArray{T,N,perm,iperm,AA}(data::AA) where {T,N,perm,iperm,AA<:AbstractArray}
336✔
13
        (isa(perm, NTuple{N,Int}) && isa(iperm, NTuple{N,Int})) || error("perm and iperm must both be NTuple{$N,Int}")
336✔
14
        isperm(perm) || throw(ArgumentError(string(perm, " is not a valid permutation of dimensions 1:", N)))
336✔
15
        all(map(d->iperm[perm[d]]==d, 1:N)) || throw(ArgumentError(string(perm, " and ", iperm, " must be inverses")))
1,238✔
16
        new(data)
336✔
17
    end
18
end
19

20
"""
21
    PermutedDimsArray(A, perm) -> B
22

23
Given an AbstractArray `A`, create a view `B` such that the
24
dimensions appear to be permuted. Similar to `permutedims`, except
25
that no copying occurs (`B` shares storage with `A`).
26

27
See also [`permutedims`](@ref), [`invperm`](@ref).
28

29
# Examples
30
```jldoctest
31
julia> A = rand(3,5,4);
32

33
julia> B = PermutedDimsArray(A, (3,1,2));
34

35
julia> size(B)
36
(4, 3, 5)
37

38
julia> B[3,1,2] == A[1,2,3]
39
true
40
```
41
"""
42
function PermutedDimsArray(data::AbstractArray{T,N}, perm) where {T,N}
320✔
43
    length(perm) == N || throw(ArgumentError(string(perm, " is not a valid permutation of dimensions 1:", N)))
320✔
44
    iperm = invperm(perm)
320✔
45
    PermutedDimsArray{T,N,(perm...,),(iperm...,),typeof(data)}(data)
318✔
46
end
47

48
Base.parent(A::PermutedDimsArray) = A.parent
249,285✔
49
Base.size(A::PermutedDimsArray{T,N,perm}) where {T,N,perm} = genperm(size(parent(A)), perm)
49,701✔
50
Base.axes(A::PermutedDimsArray{T,N,perm}) where {T,N,perm} = genperm(axes(parent(A)), perm)
145,915✔
51
Base.has_offset_axes(A::PermutedDimsArray) = Base.has_offset_axes(A.parent)
×
52

53
Base.similar(A::PermutedDimsArray, T::Type, dims::Base.Dims) = similar(parent(A), T, dims)
23✔
54

55
Base.unsafe_convert(::Type{Ptr{T}}, A::PermutedDimsArray{T}) where {T} = Base.unsafe_convert(Ptr{T}, parent(A))
17,981✔
56

57
# It's OK to return a pointer to the first element, and indeed quite
58
# useful for wrapping C routines that require a different storage
59
# order than used by Julia. But for an array with unconventional
60
# storage order, a linear offset is ambiguous---is it a memory offset
61
# or a linear index?
62
Base.pointer(A::PermutedDimsArray, i::Integer) = throw(ArgumentError("pointer(A, i) is deliberately unsupported for PermutedDimsArray"))
81✔
63

64
function Base.strides(A::PermutedDimsArray{T,N,perm}) where {T,N,perm}
35,602✔
65
    s = strides(parent(A))
35,602✔
66
    ntuple(d->s[perm[d]], Val(N))
141,278✔
67
end
68
Base.elsize(::Type{<:PermutedDimsArray{<:Any, <:Any, <:Any, <:Any, P}}) where {P} = Base.elsize(P)
35,560✔
69

70
@inline function Base.getindex(A::PermutedDimsArray{T,N,perm,iperm}, I::Vararg{Int,N}) where {T,N,perm,iperm}
72,908✔
71
    @boundscheck checkbounds(A, I...)
72,908✔
72
    @inbounds val = getindex(A.parent, genperm(I, iperm)...)
72,908✔
73
    val
72,908✔
74
end
75
@inline function Base.setindex!(A::PermutedDimsArray{T,N,perm,iperm}, val, I::Vararg{Int,N}) where {T,N,perm,iperm}
4,748✔
76
    @boundscheck checkbounds(A, I...)
4,748✔
77
    @inbounds setindex!(A.parent, val, genperm(I, iperm)...)
4,748✔
78
    val
4,748✔
79
end
80

81
function Base.isassigned(A::PermutedDimsArray{T,N,perm,iperm}, I::Vararg{Int,N}) where {T,N,perm,iperm}
×
82
    @boundscheck checkbounds(Bool, A, I...) || return false
×
83
    @inbounds x = isassigned(A.parent, genperm(I, iperm)...)
×
84
    x
×
85
end
86

87
@inline genperm(I::NTuple{N,Any}, perm::Dims{N}) where {N} = ntuple(d -> I[perm[d]], Val(N))
1,096,378✔
88
@inline genperm(I, perm::AbstractVector{Int}) = genperm(I, (perm...,))
7✔
89

90
"""
91
    permutedims(A::AbstractArray, perm)
92

93
Permute the dimensions of array `A`. `perm` is a vector or a tuple of length `ndims(A)`
94
specifying the permutation.
95

96
See also [`permutedims!`](@ref), [`PermutedDimsArray`](@ref), [`transpose`](@ref), [`invperm`](@ref).
97

98
# Examples
99
```jldoctest
100
julia> A = reshape(Vector(1:8), (2,2,2))
101
2×2×2 Array{Int64, 3}:
102
[:, :, 1] =
103
 1  3
104
 2  4
105

106
[:, :, 2] =
107
 5  7
108
 6  8
109

110
julia> perm = (3, 1, 2); # put the last dimension first
111

112
julia> B = permutedims(A, perm)
113
2×2×2 Array{Int64, 3}:
114
[:, :, 1] =
115
 1  2
116
 5  6
117

118
[:, :, 2] =
119
 3  4
120
 7  8
121

122
julia> A == permutedims(B, invperm(perm)) # the inverse permutation
123
true
124
```
125

126
For each dimension `i` of `B = permutedims(A, perm)`, its corresponding dimension of `A`
127
will be `perm[i]`. This means the equality `size(B, i) == size(A, perm[i])` holds.
128

129
```jldoctest
130
julia> A = randn(5, 7, 11, 13);
131

132
julia> perm = [4, 1, 3, 2];
133

134
julia> B = permutedims(A, perm);
135

136
julia> size(B)
137
(13, 5, 11, 7)
138

139
julia> size(A)[perm] == ans
140
true
141
```
142
"""
143
function permutedims(A::AbstractArray, perm)
14✔
144
    dest = similar(A, genperm(axes(A), perm))
18✔
145
    permutedims!(dest, A, perm)
14✔
146
end
147

148
"""
149
    permutedims(m::AbstractMatrix)
150

151
Permute the dimensions of the matrix `m`, by flipping the elements across the diagonal of
152
the matrix. Differs from `LinearAlgebra`'s [`transpose`](@ref) in that the
153
operation is not recursive.
154

155
# Examples
156
```jldoctest; setup = :(using LinearAlgebra)
157
julia> a = [1 2; 3 4];
158

159
julia> b = [5 6; 7 8];
160

161
julia> c = [9 10; 11 12];
162

163
julia> d = [13 14; 15 16];
164

165
julia> X = [[a] [b]; [c] [d]]
166
2×2 Matrix{Matrix{Int64}}:
167
 [1 2; 3 4]     [5 6; 7 8]
168
 [9 10; 11 12]  [13 14; 15 16]
169

170
julia> permutedims(X)
171
2×2 Matrix{Matrix{Int64}}:
172
 [1 2; 3 4]  [9 10; 11 12]
173
 [5 6; 7 8]  [13 14; 15 16]
174

175
julia> transpose(X)
176
2×2 transpose(::Matrix{Matrix{Int64}}) with eltype Transpose{Int64, Matrix{Int64}}:
177
 [1 3; 2 4]  [9 11; 10 12]
178
 [5 7; 6 8]  [13 15; 14 16]
179
```
180
"""
181
permutedims(A::AbstractMatrix) = permutedims(A, (2,1))
4✔
182

183
"""
184
    permutedims(v::AbstractVector)
185

186
Reshape vector `v` into a `1 × length(v)` row matrix.
187
Differs from `LinearAlgebra`'s [`transpose`](@ref) in that
188
the operation is not recursive.
189

190
# Examples
191
```jldoctest; setup = :(using LinearAlgebra)
192
julia> permutedims([1, 2, 3, 4])
193
1×4 Matrix{Int64}:
194
 1  2  3  4
195

196
julia> V = [[[1 2; 3 4]]; [[5 6; 7 8]]]
197
2-element Vector{Matrix{Int64}}:
198
 [1 2; 3 4]
199
 [5 6; 7 8]
200

201
julia> permutedims(V)
202
1×2 Matrix{Matrix{Int64}}:
203
 [1 2; 3 4]  [5 6; 7 8]
204

205
julia> transpose(V)
206
1×2 transpose(::Vector{Matrix{Int64}}) with eltype Transpose{Int64, Matrix{Int64}}:
207
 [1 3; 2 4]  [5 7; 6 8]
208
```
209
"""
210
permutedims(v::AbstractVector) = reshape(v, (1, length(v)))
123✔
211

212
"""
213
    permutedims!(dest, src, perm)
214

215
Permute the dimensions of array `src` and store the result in the array `dest`. `perm` is a
216
vector specifying a permutation of length `ndims(src)`. The preallocated array `dest` should
217
have `size(dest) == size(src)[perm]` and is completely overwritten. No in-place permutation
218
is supported and unexpected results will happen if `src` and `dest` have overlapping memory
219
regions.
220

221
See also [`permutedims`](@ref).
222
"""
223
function permutedims!(dest, src::AbstractArray, perm)
12✔
224
    Base.checkdims_perm(dest, src, perm)
12✔
225
    P = PermutedDimsArray(dest, invperm(perm))
10✔
226
    _copy!(P, src)
10✔
227
    return dest
10✔
228
end
229

230
function Base.copyto!(dest::PermutedDimsArray{T,N}, src::AbstractArray{T,N}) where {T,N}
×
231
    checkbounds(dest, axes(src)...)
×
232
    _copy!(dest, src)
×
233
end
234
Base.copyto!(dest::PermutedDimsArray, src::AbstractArray) = _copy!(dest, src)
×
235

236
function _copy!(P::PermutedDimsArray{T,N,perm}, src) where {T,N,perm}
10✔
237
    # If dest/src are "close to dense," then it pays to be cache-friendly.
238
    # Determine the first permuted dimension
239
    d = 0  # d+1 will hold the first permuted dimension of src
10✔
240
    while d < ndims(src) && perm[d+1] == d+1
16✔
241
        d += 1
6✔
242
    end
6✔
243
    if d == ndims(src)
10✔
244
        copyto!(parent(P), src) # it's not permuted
3✔
245
    else
246
        R1 = CartesianIndices(axes(src)[1:d])
9✔
247
        d1 = findfirst(isequal(d+1), perm)::Int  # first permuted dim of dest
9✔
248
        R2 = CartesianIndices(axes(src)[d+2:d1-1])
8✔
249
        R3 = CartesianIndices(axes(src)[d1+1:end])
8✔
250
        _permutedims!(P, src, R1, R2, R3, d+1, d1)
8✔
251
    end
252
    return P
10✔
253
end
254

255
@noinline function _permutedims!(P::PermutedDimsArray, src, R1::CartesianIndices{0}, R2, R3, ds, dp)
7✔
256
    ip, is = axes(src, dp), axes(src, ds)
7✔
257
    for jo in first(ip):8:last(ip), io in first(is):8:last(is)
14✔
258
        for I3 in R3, I2 in R2
11✔
259
            for j in jo:min(jo+7, last(ip))
26✔
260
                for i in io:min(io+7, last(is))
72✔
261
                    @inbounds P[i, I2, j, I3] = src[i, I2, j, I3]
108✔
262
                end
180✔
263
            end
59✔
264
        end
17✔
265
    end
7✔
266
    P
7✔
267
end
268

269
@noinline function _permutedims!(P::PermutedDimsArray, src, R1, R2, R3, ds, dp)
1✔
270
    ip, is = axes(src, dp), axes(src, ds)
1✔
271
    for jo in first(ip):8:last(ip), io in first(is):8:last(is)
2✔
272
        for I3 in R3, I2 in R2
1✔
273
            for j in jo:min(jo+7, last(ip))
2✔
274
                for i in io:min(io+7, last(is))
4✔
275
                    for I1 in R1
12✔
276
                        @inbounds P[I1, i, I2, j, I3] = src[I1, i, I2, j, I3]
18✔
277
                    end
24✔
278
                end
10✔
279
            end
3✔
280
        end
1✔
281
    end
1✔
282
    P
1✔
283
end
284

285
const CommutativeOps = Union{typeof(+),typeof(Base.add_sum),typeof(min),typeof(max),typeof(Base._extrema_rf),typeof(|),typeof(&)}
286

287
function Base._mapreduce_dim(f, op::CommutativeOps, init::Base._InitialValue, A::PermutedDimsArray, dims::Colon)
19✔
288
    Base._mapreduce_dim(f, op, init, parent(A), dims)
19✔
289
end
290
function Base._mapreduce_dim(f::typeof(identity), op::Union{typeof(Base.mul_prod),typeof(*)}, init::Base._InitialValue, A::PermutedDimsArray{<:Union{Real,Complex}}, dims::Colon)
4✔
291
    Base._mapreduce_dim(f, op, init, parent(A), dims)
4✔
292
end
293

294
function Base.mapreducedim!(f, op::CommutativeOps, B::AbstractArray{T,N}, A::PermutedDimsArray{S,N,perm,iperm}) where {T,S,N,perm,iperm}
10✔
295
    C = PermutedDimsArray{T,N,iperm,perm,typeof(B)}(B) # make the inverse permutation for the output
10✔
296
    Base.mapreducedim!(f, op, C, parent(A))
10✔
297
    B
10✔
298
end
299
function Base.mapreducedim!(f::typeof(identity), op::Union{typeof(Base.mul_prod),typeof(*)}, B::AbstractArray{T,N}, A::PermutedDimsArray{<:Union{Real,Complex},N,perm,iperm}) where {T,N,perm,iperm}
8✔
300
    C = PermutedDimsArray{T,N,iperm,perm,typeof(B)}(B) # make the inverse permutation for the output
8✔
301
    Base.mapreducedim!(f, op, C, parent(A))
8✔
302
    B
8✔
303
end
304

305
function Base.showarg(io::IO, A::PermutedDimsArray{T,N,perm}, toplevel) where {T,N,perm}
2✔
306
    print(io, "PermutedDimsArray(")
2✔
307
    Base.showarg(io, parent(A), false)
2✔
308
    print(io, ", ", perm, ')')
2✔
309
    toplevel && print(io, " with eltype ", eltype(A))
2✔
310
    return nothing
2✔
311
end
312

313
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