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

JuliaLang / julia / #38205

28 Aug 2025 06:55AM UTC coverage: 77.955% (-0.003%) from 77.958%
#38205

push

local

web-flow
PCRE2: New version 10.46 (#59416)

48572 of 62308 relevant lines covered (77.95%)

10154018.81 hits per line

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

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

3
abstract type AbstractCartesianIndex{N} end # This is a hacky forward declaration for CartesianIndex
4
const ViewIndex = Union{Real, AbstractArray}
5
const ScalarIndex = Real
6

7
"""
8
    SubArray{T,N,P,I,L} <: AbstractArray{T,N}
9

10
`N`-dimensional view into a parent array (of type `P`) with an element type `T`, restricted by a tuple of indices (of type `I`). `L` is true for types that support fast linear indexing, and `false` otherwise.
11

12
Construct `SubArray`s using the [`view`](@ref) function.
13
"""
14
struct SubArray{T,N,P,I,L} <: AbstractArray{T,N}
15
    parent::P
16
    indices::I
17
    offset1::Int       # for linear indexing and pointer, only valid when L==true
18
    stride1::Int       # used only for linear indexing
19
    function SubArray{T,N,P,I,L}(parent, indices, offset1, stride1) where {T,N,P,I,L}
6✔
20
        @inline
85,418,034✔
21
        check_parent_index_match(parent, indices)
85,418,034✔
22
        new(parent, indices, offset1, stride1)
90,604,086✔
23
    end
24
end
25
# Compute the linear indexability of the indices, and combine it with the linear indexing of the parent
26
function SubArray(parent::AbstractArray, indices::Tuple)
8✔
27
    @inline
85,426,185✔
28
    SubArray(IndexStyle(viewindexing(indices), IndexStyle(parent)), parent, ensure_indexable(indices), index_dimsum(indices...))
90,606,420✔
29
end
30
function SubArray(::IndexCartesian, parent::P, indices::I, ::NTuple{N,Any}) where {P,I,N}
31
    @inline
448,215✔
32
    SubArray{eltype(P), N, P, I, false}(parent, indices, 0, 0)
454,833✔
33
end
34
function SubArray(::IndexLinear, parent::P, indices::I, ::NTuple{N,Any}) where {P,I,N}
42✔
35
    @inline
84,977,962✔
36
    # Compute the stride and offset
37
    stride1 = compute_stride1(parent, indices)
84,978,604✔
38
    SubArray{eltype(P), N, P, I, true}(parent, indices, compute_offset1(parent, stride1, indices), stride1)
90,151,121✔
39
end
40

41
check_parent_index_match(parent, indices) = check_parent_index_match(parent, index_ndims(indices...))
85,418,032✔
42
check_parent_index_match(parent::AbstractArray{T,N}, ::NTuple{N, Bool}) where {T,N} = nothing
56,302,674✔
43
check_parent_index_match(parent, ::NTuple{N, Bool}) where {N} =
×
44
    throw(ArgumentError("number of indices ($N) must match the parent dimensionality ($(ndims(parent)))"))
45

46
# This computes the linear indexing compatibility for a given tuple of indices
47
viewindexing(I::Tuple{}) = IndexLinear()
×
48
# Leading scalar indices simply increase the stride
49
viewindexing(I::Tuple{ScalarIndex, Vararg{Any}}) = (@inline; viewindexing(tail(I)))
265,240✔
50
# Slices may begin a section which may be followed by any number of Slices
51
viewindexing(I::Tuple{Slice, Slice, Vararg{Any}}) = (@inline; viewindexing(tail(I)))
2,136✔
52
# A UnitRange can follow Slices, but only if all other indices are scalar
53
viewindexing(I::Tuple{Slice, AbstractUnitRange, Vararg{ScalarIndex}}) = IndexLinear()
28,754✔
54
viewindexing(I::Tuple{Slice, Slice, Vararg{ScalarIndex}}) = IndexLinear() # disambiguate
1,447✔
55
# In general, scalar ranges are only fast if all other indices are scalar
56
# Other ranges, such as those of `CartesianIndex`es, are not fast even if these
57
# are followed by `ScalarIndex`es
58
viewindexing(I::Tuple{AbstractRange{<:ScalarIndex}, Vararg{ScalarIndex}}) = IndexLinear()
55,006,914✔
59
# All other index combinations are slow
60
viewindexing(I::Tuple{Vararg{Any}}) = IndexCartesian()
×
61
# Of course, all other array types are slow
62
viewindexing(I::Tuple{AbstractArray, Vararg{Any}}) = IndexCartesian()
10,818✔
63

64
# Simple utilities
65
size(V::SubArray) = (@inline; map(length, axes(V)))
74,209,990✔
66

67
similar(V::SubArray, T::Type, dims::Dims) = similar(V.parent, T, dims)
13,284✔
68
similar(::Type{TA}, dims::Dims) where {T,N,P,TA<:SubArray{T,N,P}} = similar(P, dims)
×
69

70
sizeof(V::SubArray) = length(V) * sizeof(eltype(V))
5✔
71
sizeof(V::SubArray{<:Any,<:Any,<:Array}) = length(V) * elsize(V.parent)
4✔
72

73
function Base.copy(V::SubArray)
539✔
74
    v = V.parent[V.indices...]
2,094✔
75
    ndims(V) == 0 || return v
1,141✔
76
    x = similar(V) # ensure proper type of x
1✔
77
    x[] = v
1✔
78
    return x
1✔
79
end
80

81
parent(V::SubArray) = V.parent
57,381,208✔
82
parentindices(V::SubArray) = V.indices
194,253✔
83

84
"""
85
    parentindices(A)
86

87
Return the indices in the [`parent`](@ref) which correspond to the view `A`.
88

89
# Examples
90
```jldoctest
91
julia> A = [1 2; 3 4];
92

93
julia> V = view(A, 1, :)
94
2-element view(::Matrix{Int64}, 1, :) with eltype Int64:
95
 1
96
 2
97

98
julia> parentindices(V)
99
(1, Base.Slice(Base.OneTo(2)))
100
```
101
"""
102
function parentindices end
103

104
parentindices(a::AbstractArray) = map(oneto, size(a))
1✔
105

106
## Aliasing detection
107
dataids(A::SubArray) = (dataids(A.parent)..., _splatmap(dataids, A.indices)...)
3,584,528✔
108
_splatmap(f, ::Tuple{}) = ()
10✔
109
_splatmap(f, t::Tuple) = (f(t[1])..., _splatmap(f, tail(t))...)
459,173✔
110
unaliascopy(A::SubArray) = typeof(A)(unaliascopy(A.parent), map(unaliascopy, A.indices), A.offset1, A.stride1)
4✔
111

112
# When the parent is an Array we can trim the size down a bit. In the future this
113
# could possibly be extended to any mutable array.
114
function unaliascopy(V::SubArray{T,N,A,I,LD}) where {T,N,A<:Array,I<:Tuple{Vararg{Union{ScalarIndex,AbstractRange{<:ScalarIndex},Array{<:Union{ScalarIndex,AbstractCartesianIndex}}}}},LD}
8✔
115
    dest = Array{T}(undef, _trimmedshape(V.indices...))
1,136✔
116
    trimmedpind = _trimmedpind(V.indices...)
1,128✔
117
    vdest = trimmedpind isa Tuple{Vararg{Union{Slice,Colon}}} ? dest : view(dest, trimmedpind...)
1,129✔
118
    copyto!(vdest, view(V, _trimmedvind(V.indices...)...))
1,133✔
119
    indices = map(_trimmedindex, V.indices)
1,130✔
120
    stride1 = LD ? compute_stride1(dest, indices) : 0
1,128✔
121
    offset1 = LD ? compute_offset1(dest, stride1, indices) : 0
1,129✔
122
    SubArray{T,N,A,I,LD}(dest, indices, offset1, stride1)
1,128✔
123
end
124
# Get the proper trimmed shape
125
_trimmedshape(::ScalarIndex, rest...) = (1, _trimmedshape(rest...)...)
1,080✔
126
_trimmedshape(i::AbstractRange, rest...) = (isempty(i) ? zero(eltype(i)) : maximum(i), _trimmedshape(rest...)...)
20✔
127
_trimmedshape(i::Union{UnitRange,StepRange,OneTo}, rest...) = (length(i), _trimmedshape(rest...)...)
1,150✔
128
_trimmedshape(i::AbstractArray{<:ScalarIndex}, rest...) = (length(i), _trimmedshape(rest...)...)
×
129
_trimmedshape(i::AbstractArray{<:AbstractCartesianIndex{0}}, rest...) = _trimmedshape(rest...)
2✔
130
_trimmedshape(i::AbstractArray{<:AbstractCartesianIndex{N}}, rest...) where {N} = (length(i), ntuple(Returns(1), Val(N - 1))..., _trimmedshape(rest...)...)
4✔
131
_trimmedshape() = ()
10✔
132
# We can avoid the repetition from `AbstractArray{CartesianIndex{0}}`
133
_trimmedpind(i, rest...) = (map(Returns(:), axes(i))..., _trimmedpind(rest...)...)
1,084✔
134
_trimmedpind(i::AbstractRange, rest...) = (i, _trimmedpind(rest...)...)
7✔
135
_trimmedpind(i::Union{UnitRange,StepRange,OneTo}, rest...) = ((:), _trimmedpind(rest...)...)
1,146✔
136
_trimmedpind(i::AbstractArray{<:AbstractCartesianIndex{0}}, rest...) = _trimmedpind(rest...)
2✔
137
_trimmedpind() = ()
10✔
138
_trimmedvind(i, rest...) = (map(Returns(:), axes(i))..., _trimmedvind(rest...)...)
2,246✔
139
_trimmedvind(i::AbstractArray{<:AbstractCartesianIndex{0}}, rest...) = (map(first, axes(i))..., _trimmedvind(rest...)...)
2✔
140
_trimmedvind() = ()
10✔
141
# Transform indices to be "dense"
142
_trimmedindex(i::ScalarIndex) = oftype(i, 1)
1,080✔
143
_trimmedindex(i::AbstractRange) = i
4✔
144
_trimmedindex(i::Union{UnitRange,StepRange,OneTo}) = oftype(i, oneto(length(i)))
1,170✔
145
_trimmedindex(i::AbstractArray{<:ScalarIndex}) = oftype(i, reshape(eachindex(IndexLinear(), i), axes(i)))
×
146
_trimmedindex(i::AbstractArray{<:AbstractCartesianIndex{0}}) = oftype(i, copy(i))
4✔
147
function _trimmedindex(i::AbstractArray{<:AbstractCartesianIndex{N}}) where {N}
2✔
148
    padding = ntuple(Returns(1), Val(N - 1))
4✔
149
    ax1 = eachindex(IndexLinear(), i)
4✔
150
    return oftype(i, reshape(CartesianIndices((ax1, padding...)), axes(i)))
4✔
151
end
152
## SubArray creation
153
# We always assume that the dimensionality of the parent matches the number of
154
# indices that end up getting passed to it, so we store the parent as a
155
# ReshapedArray view if necessary. The trouble is that arrays of `CartesianIndex`
156
# can make the number of effective indices not equal to length(I).
157
_maybe_reshape_parent(A::AbstractArray, ::NTuple{1, Bool}) = reshape(A, Val(1))
3,883✔
158
_maybe_reshape_parent(A::AbstractArray{<:Any,1}, ::NTuple{1, Bool}) = reshape(A, Val(1))
55,625,943✔
159
_maybe_reshape_parent(A::AbstractArray{<:Any,N}, ::NTuple{N, Bool}) where {N} = A
926,984✔
160
_maybe_reshape_parent(A::AbstractArray, ::NTuple{N, Bool}) where {N} = reshape(A, Val(N))
327✔
161
# The trailing singleton indices could be eliminated after bounds checking.
162
rm_singleton_indices(ndims::Tuple, J1, Js...) = (J1, rm_singleton_indices(IteratorsMD._splitrest(ndims, index_ndims(J1)), Js...)...)
55,344,466✔
163
rm_singleton_indices(::Tuple{}, ::ScalarIndex, Js...) = rm_singleton_indices((), Js...)
19,109✔
164
rm_singleton_indices(::Tuple) = ()
55,008,914✔
165

166
"""
167
    view(A, inds...)
168

169
Like [`getindex`](@ref), but returns a lightweight array that lazily references
170
(or is effectively a _view_ into) the parent array `A` at the given index or indices
171
`inds` instead of eagerly extracting elements or constructing a copied subset.
172
Calling [`getindex`](@ref) or [`setindex!`](@ref) on the returned value
173
(often a [`SubArray`](@ref)) computes the indices to access or modify the
174
parent array on the fly.  The behavior is undefined if the shape of the parent array is
175
changed after `view` is called because there is no bound check for the parent array; e.g.,
176
it may cause a segmentation fault.
177

178
Some immutable parent arrays (like ranges) may choose to simply
179
recompute a new array in some circumstances instead of returning
180
a `SubArray` if doing so is efficient and provides compatible semantics.
181

182
!!! compat "Julia 1.6"
183
    In Julia 1.6 or later, `view` can be called on an `AbstractString`, returning a
184
    `SubString`.
185

186
# Examples
187
```jldoctest
188
julia> A = [1 2; 3 4]
189
2×2 Matrix{Int64}:
190
 1  2
191
 3  4
192

193
julia> b = view(A, :, 1)
194
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
195
 1
196
 3
197

198
julia> fill!(b, 0)
199
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
200
 0
201
 0
202

203
julia> A # Note A has changed even though we modified b
204
2×2 Matrix{Int64}:
205
 0  2
206
 0  4
207

208
julia> view(2:5, 2:3) # returns a range as type is immutable
209
3:4
210
```
211
"""
212
function view(A::AbstractArray, I::Vararg{Any,M}) where {M}
9,810✔
213
    @inline
87,378,564✔
214
    J = map(i->unalias(A,i), to_indices(A, I))
173,950,699✔
215
    @boundscheck checkbounds(A, J...)
90,603,903✔
216
    J′ = rm_singleton_indices(ntuple(Returns(true), Val(ndims(A))), J...)
87,378,537✔
217
    unsafe_view(_maybe_reshape_parent(A, index_ndims(J′...)), J′...)
90,606,587✔
218
end
219

220
# Ranges implement getindex to return recomputed ranges; use that for views, too (when possible)
221
function view(r1::AbstractUnitRange, r2::AbstractUnitRange{<:Integer})
10✔
222
    @_propagate_inbounds_meta
414✔
223
    getindex(r1, r2)
414✔
224
end
225
function view(r1::AbstractUnitRange, r2::StepRange{<:Integer})
3✔
226
    @_propagate_inbounds_meta
3✔
227
    getindex(r1, r2)
3✔
228
end
229
function view(r1::StepRange, r2::AbstractRange{<:Integer})
1✔
230
    @_propagate_inbounds_meta
4✔
231
    getindex(r1, r2)
4✔
232
end
233
function view(r1::StepRangeLen, r2::OrdinalRange{<:Integer})
×
234
    @_propagate_inbounds_meta
×
235
    getindex(r1, r2)
×
236
end
237
function view(r1::LinRange, r2::OrdinalRange{<:Integer})
×
238
    @_propagate_inbounds_meta
×
239
    getindex(r1, r2)
×
240
end
241

242
# getindex(r::AbstractRange, ::Colon) returns a copy of the range, and we may do the same for a view
243
function view(r1::AbstractRange, c::Colon)
3✔
244
    @_propagate_inbounds_meta
3✔
245
    getindex(r1, c)
3✔
246
end
247

248
function unsafe_view(A::AbstractArray, I::Vararg{ViewIndex,N}) where {N}
6✔
249
    @inline
85,409,642✔
250
    SubArray(A, I)
90,336,706✔
251
end
252
# When we take the view of a view, it's often possible to "reindex" the parent
253
# view's indices such that we can "pop" the parent view and keep just one layer
254
# of indirection. But we can't always do this because arrays of `CartesianIndex`
255
# might span multiple parent indices, making the reindex calculation very hard.
256
# So we use _maybe_reindex to figure out if there are any arrays of
257
# `CartesianIndex`, and if so, we punt and keep two layers of indirection.
258
unsafe_view(V::SubArray, I::Vararg{ViewIndex,N}) where {N} =
259
    (@inline; _maybe_reindex(V, I))
269,794✔
260
_maybe_reindex(V, I) = (@inline; _maybe_reindex(V, I, I))
269,794✔
261
_maybe_reindex(V, I, ::Tuple{AbstractArray{<:AbstractCartesianIndex}, Vararg{Any}}) =
262
    (@inline; SubArray(V, I))
18✔
263
# But allow arrays of CartesianIndex{1}; they behave just like arrays of Ints
264
_maybe_reindex(V, I, A::Tuple{AbstractArray{<:AbstractCartesianIndex{1}}, Vararg{Any}}) =
×
265
    (@inline; _maybe_reindex(V, I, tail(A)))
×
266
_maybe_reindex(V, I, A::Tuple{Any, Vararg{Any}}) = (@inline; _maybe_reindex(V, I, tail(A)))
284,318✔
267
function _maybe_reindex(V, I, ::Tuple{})
268
    @inline
269,534✔
269
    @inbounds idxs = to_indices(V.parent, reindex(V.indices, I))
270,213✔
270
    SubArray(V.parent, idxs)
269,693✔
271
end
272

273
## Re-indexing is the heart of a view, transforming A[i, j][x, y] to A[i[x], j[y]]
274
#
275
# Recursively look through the heads of the parent- and sub-indices, considering
276
# the following cases:
277
# * Parent index is array  -> re-index that with one or more sub-indices (one per dimension)
278
# * Parent index is Colon  -> just use the sub-index as provided
279
# * Parent index is scalar -> that dimension was dropped, so skip the sub-index and use the index as is
280

281
AbstractZeroDimArray{T} = AbstractArray{T, 0}
282

283
reindex(::Tuple{}, ::Tuple{}) = ()
113✔
284

285
# Skip dropped scalars, so simply peel them off the parent indices and continue
286
reindex(idxs::Tuple{ScalarIndex, Vararg{Any}}, subidxs::Tuple{Vararg{Any}}) =
287
    (@_propagate_inbounds_meta; (idxs[1], reindex(tail(idxs), subidxs)...))
2,588,770✔
288

289
# Slices simply pass their subindices straight through
290
reindex(idxs::Tuple{Slice, Vararg{Any}}, subidxs::Tuple{Any, Vararg{Any}}) =
21✔
291
    (@_propagate_inbounds_meta; (subidxs[1], reindex(tail(idxs), tail(subidxs))...))
6,664,367✔
292

293
# Re-index into parent vectors with one subindex
294
reindex(idxs::Tuple{AbstractVector, Vararg{Any}}, subidxs::Tuple{Any, Vararg{Any}}) =
295
    (@_propagate_inbounds_meta; (idxs[1][subidxs[1]], reindex(tail(idxs), tail(subidxs))...))
33,066,614✔
296

297
# Parent matrices are re-indexed with two sub-indices
298
reindex(idxs::Tuple{AbstractMatrix, Vararg{Any}}, subidxs::Tuple{Any, Any, Vararg{Any}}) =
299
    (@_propagate_inbounds_meta; (idxs[1][subidxs[1], subidxs[2]], reindex(tail(idxs), tail(tail(subidxs)))...))
519,683✔
300

301
# In general, we index N-dimensional parent arrays with N indices
302
@generated function reindex(idxs::Tuple{AbstractArray{T,N}, Vararg{Any}}, subidxs::Tuple{Vararg{Any}}) where {T,N}
104,288✔
303
    if length(subidxs.parameters) >= N
217✔
304
        subs = [:(subidxs[$d]) for d in 1:N]
214✔
305
        tail = [:(subidxs[$d]) for d in N+1:length(subidxs.parameters)]
214✔
306
        :(@_propagate_inbounds_meta; (idxs[1][$(subs...)], reindex(tail(idxs), ($(tail...),))...))
52,358✔
307
    else
308
        :(throw(ArgumentError("cannot re-index SubArray with fewer indices than dimensions\nThis should not occur; please submit a bug report.")))
220✔
309
    end
310
end
311

312
# In general, we simply re-index the parent indices by the provided ones
313
SlowSubArray{T,N,P,I} = SubArray{T,N,P,I,false}
314
function getindex(V::SubArray{T,N}, I::Vararg{Int,N}) where {T,N}
14,565✔
315
    @inline
15,426,422✔
316
    @boundscheck checkbounds(V, I...)
15,426,802✔
317
    @inbounds r = V.parent[reindex(V.indices, I)...]
16,380,268✔
318
    r
15,426,327✔
319
end
320

321
# But SubArrays with fast linear indexing pre-compute a stride and offset
322
FastSubArray{T,N,P,I} = SubArray{T,N,P,I,true}
323
# We define a convenience functions to compute the shifted parent index
324
# This differs from reindex as this accepts the view directly, instead of its indices
325
@inline _reindexlinear(V::FastSubArray, i::Int) = V.offset1 + V.stride1*i
22,177,030✔
326
@inline _reindexlinear(V::FastSubArray, i::AbstractUnitRange{Int}) = V.offset1 .+ V.stride1 .* i
54✔
327

328
function getindex(V::FastSubArray, i::Int)
8,746✔
329
    @inline
667,533✔
330
    @boundscheck checkbounds(V, i)
667,539✔
331
    @inbounds r = V.parent[_reindexlinear(V, i)]
667,527✔
332
    r
667,527✔
333
end
334

335
# For vector views with linear indexing, we disambiguate to favor the stride/offset
336
# computation as that'll generally be faster than (or just as fast as) re-indexing into a range.
337
function getindex(V::FastSubArray{<:Any, 1}, i::Int)
4,135✔
338
    @inline
281,923,645✔
339
    @boundscheck checkbounds(V, i)
417,834,361✔
340
    @inbounds r = V.parent[_reindexlinear(V, i)]
417,834,349✔
341
    r
281,923,639✔
342
end
343

344
# We can avoid a multiplication if the first parent index is a Colon or AbstractUnitRange,
345
# or if all the indices are scalars, i.e. the view is for a single value only
346
FastContiguousSubArray{T,N,P,I<:Union{Tuple{AbstractUnitRange, Vararg{Any}},
347
                                      Tuple{Vararg{ScalarIndex}}}} = SubArray{T,N,P,I,true}
348

349
@inline _reindexlinear(V::FastContiguousSubArray, i::Int) = V.offset1 + i
861,686,865✔
350
@inline _reindexlinear(V::FastContiguousSubArray, i::AbstractUnitRange{Int}) = V.offset1 .+ i
699✔
351

352
"""
353
An internal type representing arrays stored contiguously in memory.
354
"""
355
const DenseArrayType{T,N} = Union{
356
    DenseArray{T,N},
357
    <:FastContiguousSubArray{T,N,<:DenseArray},
358
}
359

360
"""
361
An internal type representing mutable arrays stored contiguously in memory.
362
"""
363
const MutableDenseArrayType{T,N} = Union{
364
    Array{T, N},
365
    Memory{T},
366
    FastContiguousSubArray{T,N,<:Array},
367
    FastContiguousSubArray{T,N,<:Memory}
368
}
369

370
# parents of FastContiguousSubArrays may support fast indexing with AbstractUnitRanges,
371
# so we may just forward the indexing to the parent
372
# This may only be done for non-offset ranges, as the result would otherwise have offset axes
373
const _OneBasedRanges = Union{OneTo{Int}, UnitRange{Int}, Slice{OneTo{Int}}, IdentityUnitRange{OneTo{Int}}}
374
function getindex(V::FastContiguousSubArray, i::_OneBasedRanges)
674✔
375
    @inline
690✔
376
    @boundscheck checkbounds(V, i)
690✔
377
    @inbounds r = V.parent[_reindexlinear(V, i)]
1,418✔
378
    r
690✔
379
end
380

381
@inline getindex(V::FastContiguousSubArray, i::Colon) = getindex(V, to_indices(V, (:,))...)
14✔
382

383
# Indexed assignment follows the same pattern as `getindex` above
384
function setindex!(V::SubArray{T,N}, x, I::Vararg{Int,N}) where {T,N}
188,117✔
385
    @inline
9,613,368✔
386
    @boundscheck checkbounds(V, I...)
9,618,751✔
387
    @inbounds V.parent[reindex(V.indices, I)...] = x
9,618,725✔
388
    V
9,613,355✔
389
end
390
function setindex!(V::FastSubArray, x, i::Int)
391
    @inline
1,002,144✔
392
    @boundscheck checkbounds(V, i)
1,002,144✔
393
    @inbounds V.parent[_reindexlinear(V, i)] = x
1,002,144✔
394
    V
1,002,144✔
395
end
396
function setindex!(V::FastSubArray{<:Any, 1}, x, i::Int)
1✔
397
    @inline
464,676,481✔
398
    @boundscheck checkbounds(V, i)
464,768,910✔
399
    @inbounds V.parent[_reindexlinear(V, i)] = x
464,768,910✔
400
    V
464,676,481✔
401
end
402

403
function setindex!(V::FastSubArray, x, i::AbstractUnitRange{Int})
10✔
404
    @inline
63✔
405
    @boundscheck checkbounds(V, i)
112✔
406
    @inbounds V.parent[_reindexlinear(V, i)] = x
245✔
407
    V
63✔
408
end
409

410
@inline setindex!(V::FastSubArray, x, i::Colon) = setindex!(V, x, to_indices(V, (i,))...)
53✔
411

412
function isassigned(V::SubArray{T,N}, I::Vararg{Int,N}) where {T,N}
5,684✔
413
    @inline
5,720✔
414
    @boundscheck checkbounds(Bool, V, I...) || return false
5,725✔
415
    @inbounds r = isassigned(V.parent, reindex(V.indices, I)...)
5,715✔
416
    r
5,715✔
417
end
418
function isassigned(V::FastSubArray, i::Int)
×
419
    @inline
×
420
    @boundscheck checkbounds(Bool, V, i) || return false
×
421
    @inbounds r = isassigned(V.parent, _reindexlinear(V, i))
×
422
    r
×
423
end
424
function isassigned(V::FastSubArray{<:Any, 1}, i::Int)
8✔
425
    @inline
48✔
426
    @boundscheck checkbounds(Bool, V, i) || return false
52✔
427
    @inbounds r = isassigned(V.parent, _reindexlinear(V, i))
44✔
428
    r
44✔
429
end
430

431
IndexStyle(::Type{<:FastSubArray}) = IndexLinear()
48,053,641✔
432

433
# Strides are the distance in memory between adjacent elements in a given dimension
434
# which we determine from the strides of the parent
435
strides(V::SubArray) = substrides(strides(V.parent), V.indices)
123,893✔
436

437
substrides(strds::Tuple{}, ::Tuple{}) = ()
×
438
substrides(strds::NTuple{N,Int}, I::Tuple{ScalarIndex, Vararg{Any}}) where N = (substrides(tail(strds), tail(I))...,)
19,029✔
439
substrides(strds::NTuple{N,Int}, I::Tuple{Slice, Vararg{Any}}) where N = (first(strds), substrides(tail(strds), tail(I))...)
56,036✔
440
substrides(strds::NTuple{N,Int}, I::Tuple{AbstractRange, Vararg{Any}}) where N = (first(strds)*step(I[1]), substrides(tail(strds), tail(I))...)
174,778✔
441
substrides(strds, I::Tuple{Any, Vararg{Any}}) = throw(ArgumentError(
×
442
    LazyString("strides is invalid for SubArrays with indices of type ", typeof(I[1]))))
443

444
stride(V::SubArray, d::Integer) = d <= ndims(V) ? strides(V)[d] : strides(V)[end] * size(V)[end]
27,271✔
445

446
compute_stride1(parent::AbstractArray, I::NTuple{N,Any}) where {N} =
6✔
447
    (@inline; compute_stride1(1, fill_to_length(axes(parent), OneTo(1), Val(N)), I))
84,970,431✔
448
compute_stride1(s, inds, I::Tuple{}) = s
2✔
449
compute_stride1(s, inds, I::Tuple{Vararg{ScalarIndex}}) = s
109✔
450
compute_stride1(s, inds, I::Tuple{ScalarIndex, Vararg{Any}}) =
451
    (@inline; compute_stride1(s*length(inds[1]), tail(inds), tail(I)))
262,813✔
452
compute_stride1(s, inds, I::Tuple{AbstractRange, Vararg{Any}}) = s*step(I[1])
55,019,317✔
453
compute_stride1(s, inds, I::Tuple{Slice, Vararg{Any}}) = s
31,090✔
454
compute_stride1(s, inds, I::Tuple{Any, Vararg{Any}}) = throw(ArgumentError(LazyString("invalid strided index type ", typeof(I[1]))))
×
455

456
elsize(::Type{<:SubArray{<:Any,<:Any,P}}) where {P} = elsize(P)
56,211,100✔
457

458
iscontiguous(A::SubArray) = iscontiguous(typeof(A))
61✔
459
iscontiguous(::Type{<:SubArray}) = false
×
460
iscontiguous(::Type{<:FastContiguousSubArray}) = true
×
461

462
first_index(V::FastSubArray) = V.offset1 + V.stride1 * firstindex(V) # cached for fast linear SubArrays
55,477,645✔
463
first_index(V::SubArray) = compute_linindex(parent(V), V.indices)
67,916✔
464

465
# Computing the first index simply steps through the indices, accumulating the
466
# sum of index each multiplied by the parent's stride.
467
# The running sum is `f`; the cumulative stride product is `s`.
468
# If the parent is a vector, then we offset the parent's own indices with parameters of I
469
compute_offset1(parent::AbstractVector, stride1::Integer, I::Tuple{AbstractRange}) =
6✔
470
    (@inline; first(I[1]) - stride1*first(axes1(I[1])))
87,717,123✔
471
# If the result is one-dimensional and it's a Colon, then linear
472
# indexing uses the indices along the given dimension.
473
# If the result is one-dimensional and it's a range, then linear
474
# indexing might be offset if the index itself is offset
475
# Otherwise linear indexing always matches the parent.
476
compute_offset1(parent, stride1::Integer, I::Tuple) =
477
    (@inline; compute_offset1(parent, stride1, find_extended_dims(1, I...), find_extended_inds(I...), I))
738,497✔
478
compute_offset1(parent, stride1::Integer, dims::Tuple{Int}, inds::Tuple{Slice}, I::Tuple) =
479
    (@inline; compute_linindex(parent, I) - stride1*first(axes(parent, dims[1])))  # index-preserving case
298,953✔
480
compute_offset1(parent, stride1::Integer, dims, inds::Tuple{AbstractRange}, I::Tuple) =
481
    (@inline; compute_linindex(parent, I) - stride1*first(axes1(inds[1]))) # potentially index-offsetting case
409,308✔
482
compute_offset1(parent, stride1::Integer, dims, inds, I::Tuple) =
483
    (@inline; compute_linindex(parent, I) - stride1)
30,236✔
484
function compute_linindex(parent, I::NTuple{N,Any}) where N
485
    @inline
788,871✔
486
    IP = fill_to_length(axes(parent), OneTo(1), Val(N))
806,394✔
487
    compute_linindex(first(LinearIndices(parent)), 1, IP, I)
806,394✔
488
end
489
function compute_linindex(f, s, IP::Tuple, I::Tuple{Any, Vararg{Any}})
1✔
490
    @inline
402,133✔
491
    Δi = first(I[1])-first(IP[1])
1,129,511✔
492
    compute_linindex(f + Δi*s, s*length(IP[1]), tail(IP), tail(I))
1,672,777✔
493
end
494
compute_linindex(f, s, IP::Tuple, I::Tuple{}) = f
8,042✔
495

496
find_extended_dims(dim, ::ScalarIndex, I...) = (@inline; find_extended_dims(dim + 1, I...))
264,526✔
497
find_extended_dims(dim, i1, I...) = (@inline; (dim, find_extended_dims(dim + 1, I...)...))
321,902✔
498
find_extended_dims(dim) = ()
13✔
499
find_extended_inds(::ScalarIndex, I...) = (@inline; find_extended_inds(I...))
264,526✔
500
find_extended_inds(i1, I...) = (@inline; (i1, find_extended_inds(I...)...))
321,902✔
501
find_extended_inds() = ()
13✔
502

503
pointer(V::FastSubArray, i::Int) = pointer(V.parent, V.offset1 + V.stride1*i)
2,610✔
504
pointer(V::FastContiguousSubArray, i::Int) = pointer(V.parent, V.offset1 + i)
9,635✔
505

506
function pointer(V::SubArray{<:Any,<:Any,<:Array,<:Tuple{Vararg{RangeIndex}}}, is::AbstractCartesianIndex{N}) where {N}
×
507
    index = first_index(V)
×
508
    strds = strides(V)
×
509
    for d = 1:N
×
510
        index += (is[d]-1)*strds[d]
×
511
    end
×
512
    return pointer(V.parent, index)
×
513
end
514

515
# indices are taken from the range/vector
516
# Since bounds-checking is performance-critical and uses
517
# indices, it's worth optimizing these implementations thoroughly
518
axes(S::SubArray) = (@inline; _indices_sub(S.indices...))
101,766,528✔
519
_indices_sub(::Real, I...) = (@inline; _indices_sub(I...))
3,956,493✔
520
_indices_sub() = ()
55,969,221✔
521
function _indices_sub(i1::AbstractArray, I...)
210✔
522
    @inline
76,559,747✔
523
    (axes(i1)..., _indices_sub(I...)...)
133,115,678✔
524
end
525

526
axes1(::SubArray{<:Any,0}) = OneTo(1)
×
527
axes1(S::SubArray) = (@inline; _axes1_sub(S.indices...))
984,280,084✔
528
_axes1_sub() = ()
×
529
_axes1_sub(::Real, I...) = (@inline; _axes1_sub(I...))
3,443,023✔
530
_axes1_sub(::AbstractArray{<:Any,0}, I...) = _axes1_sub(I...)
2,869✔
531
function _axes1_sub(i1::AbstractArray, I...)
109✔
532
    @inline
86,440,195✔
533
    axes1(i1)
954,275,666✔
534
end
535

536
has_offset_axes(S::SubArray) = has_offset_axes(S.indices...)
821,512✔
537

538
function replace_in_print_matrix(S::SubArray{<:Any,2,<:AbstractMatrix}, i::Integer, j::Integer, s::AbstractString)
7✔
539
    replace_in_print_matrix(S.parent, to_indices(S.parent, reindex(S.indices, (i,j)))..., s)
7✔
540
end
541
function replace_in_print_matrix(S::SubArray{<:Any,1,<:AbstractVector}, i::Integer, j::Integer, s::AbstractString)
16✔
542
    replace_in_print_matrix(S.parent, to_indices(S.parent, reindex(S.indices, (i,)))..., j, s)
16✔
543
end
544

545
# XXX: this is considerably more unsafe than the other similarly named methods
546
unsafe_wrap(::Type{Vector{UInt8}}, s::FastContiguousSubArray{UInt8,1,Vector{UInt8}}) = unsafe_wrap(Vector{UInt8}, pointer(s), size(s))
×
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