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

JuliaLang / julia / #38120

03 Jul 2025 03:51AM UTC coverage: 25.688% (-0.003%) from 25.691%
#38120

push

local

web-flow
Add missing module qualifier (#58877)

A very simple fix addressing the following bug:
```julia
Validation: Error During Test at REPL[61]:1
  Got exception outside of a @test
  #=ERROR showing exception stack=# UndefVarError: `get_ci_mi` not defined in `Base.StackTraces`
  Suggestion: check for spelling errors or missing imports.
  Hint: a global variable of this name also exists in Base.
      - Also declared public in Compiler (loaded but not imported in Main).
  Stacktrace:
    [1] show_custom_spec_sig(io::IOContext{IOBuffer}, owner::Any, linfo::Core.CodeInstance, frame::Base.StackTraces.StackFrame)
      @ Base.StackTraces ./stacktraces.jl:293
    [2] show_spec_linfo(io::IOContext{IOBuffer}, frame::Base.StackTraces.StackFrame)
      @ Base.StackTraces ./stacktraces.jl:278
    [3] print_stackframe(io::IOContext{IOBuffer}, i::Int64, frame::Base.StackTraces.StackFrame, n::Int64, ndigits_max::Int64, modulecolor::Symbol; prefix::Nothing)
      @ Base ./errorshow.jl:786
```

AFAIK this occurs when printing a stacktrace from a `CodeInstance` that
has a non-default owner.

0 of 1 new or added line in 1 file covered. (0.0%)

1187 existing lines in 8 files now uncovered.

12872 of 50109 relevant lines covered (25.69%)

736460.96 hits per line

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

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

3
## Basic functions ##
4

5
"""
6
    AbstractArray{T,N}
7

8
Supertype for `N`-dimensional arrays (or array-like types) with elements of type `T`.
9
[`Array`](@ref) and other types are subtypes of this. See the manual section on the
10
[`AbstractArray` interface](@ref man-interface-array).
11

12
See also: [`AbstractVector`](@ref), [`AbstractMatrix`](@ref), [`eltype`](@ref), [`ndims`](@ref).
13
"""
14
AbstractArray
15

16
convert(::Type{T}, a::T) where {T<:AbstractArray} = a
×
17
convert(::Type{AbstractArray{T}}, a::AbstractArray) where {T} = AbstractArray{T}(a)::AbstractArray{T}
×
18
convert(::Type{AbstractArray{T,N}}, a::AbstractArray{<:Any,N}) where {T,N} = AbstractArray{T,N}(a)::AbstractArray{T,N}
×
19

20
"""
21
    size(A::AbstractArray, [dim])
22

23
Return a tuple containing the dimensions of `A`. Optionally you can specify a
24
dimension to just get the length of that dimension.
25

26
Note that `size` may not be defined for arrays with non-standard indices, in which case [`axes`](@ref)
27
may be useful. See the manual chapter on [arrays with custom indices](@ref man-custom-indices).
28

29
See also: [`length`](@ref), [`ndims`](@ref), [`eachindex`](@ref), [`sizeof`](@ref).
30

31
# Examples
32
```jldoctest
33
julia> A = fill(1, (2,3,4));
34

35
julia> size(A)
36
(2, 3, 4)
37

38
julia> size(A, 2)
39
3
40
```
41
"""
42
size(t::AbstractArray{T,N}, d) where {T,N} = d::Integer <= N ? size(t)[d] : 1
22,218✔
43

44
"""
45
    axes(A, d)
46

47
Return the valid range of indices for array `A` along dimension `d`.
48

49
See also [`size`](@ref), and the manual chapter on [arrays with custom indices](@ref man-custom-indices).
50

51
# Examples
52

53
```jldoctest
54
julia> A = fill(1, (5,6,7));
55

56
julia> axes(A, 2)
57
Base.OneTo(6)
58

59
julia> axes(A, 4) == 1:1  # all dimensions d > ndims(A) have size 1
60
true
61
```
62

63
# Usage note
64

65
Each of the indices has to be an `AbstractUnitRange{<:Integer}`, but at the same time can be
66
a type that uses custom indices. So, for example, if you need a subset, use generalized
67
indexing constructs like `begin`/`end` or [`firstindex`](@ref)/[`lastindex`](@ref):
68

69
```julia
70
ix = axes(v, 1)
71
ix[2:end]          # will work for eg Vector, but may fail in general
72
ix[(begin+1):end]  # works for generalized indexes
73
```
74
"""
75
function axes(A::AbstractArray{T,N}, d) where {T,N}
76
    @inline
52,390✔
77
    d::Integer <= N ? axes(A)[d] : OneTo(1)
62,538✔
78
end
79

80
"""
81
    axes(A)
82

83
Return the tuple of valid indices for array `A`.
84

85
See also: [`size`](@ref), [`keys`](@ref), [`eachindex`](@ref).
86

87
# Examples
88

89
```jldoctest
90
julia> A = fill(1, (5,6,7));
91

92
julia> axes(A)
93
(Base.OneTo(5), Base.OneTo(6), Base.OneTo(7))
94
```
95
"""
96
function axes(A)
3,579,879✔
97
    @inline
3,601,992✔
98
    map(unchecked_oneto, size(A))
25,619,605✔
99
end
100

101
"""
102
    has_offset_axes(A)
103
    has_offset_axes(A, B, ...)
104

105
Return `true` if the indices of `A` start with something other than 1 along any axis.
106
If multiple arguments are passed, equivalent to `has_offset_axes(A) || has_offset_axes(B) || ...`.
107

108
See also [`require_one_based_indexing`](@ref).
109
"""
110
has_offset_axes() = false
×
111
has_offset_axes(A) = _any_tuple(x->Int(first(x))::Int != 1, false, axes(A)...)
×
112
has_offset_axes(A::AbstractVector) = Int(firstindex(A))::Int != 1 # improve performance of a common case (ranges)
×
113
has_offset_axes(::Colon) = false
×
114
has_offset_axes(::Array) = false
×
115
# note: this could call `any` directly if the compiler can infer it. We don't use _any_tuple
116
# here because it stops full elision in some cases (#49332) and we don't need handling of
117
# `missing` (has_offset_axes(A) always returns a Bool)
118
has_offset_axes(A, As...) = has_offset_axes(A) || has_offset_axes(As...)
×
119

120

121
"""
122
    require_one_based_indexing(A::AbstractArray)
123
    require_one_based_indexing(A,B...)
124

125
Throw an `ArgumentError` if the indices of any argument start with something other than `1` along any axis.
126
See also [`has_offset_axes`](@ref).
127

128
!!! compat "Julia 1.2"
129
     This function requires at least Julia 1.2.
130
"""
131
require_one_based_indexing(A...) = !has_offset_axes(A...) || throw(ArgumentError("offset arrays are not supported but got an array with index other than 1"))
1✔
132

133
# Performance optimization: get rid of a branch on `d` in `axes(A, d)`
134
# for d=1. 1d arrays are heavily used, and the first dimension comes up
135
# in other applications.
136
axes1(A::AbstractArray{<:Any,0}) = OneTo(1)
×
137
axes1(A::AbstractArray) = (@inline; axes(A)[1])
16,054,088✔
138
axes1(iter) = oneto(length(iter))
×
139

140
"""
141
    keys(a::AbstractArray)
142

143
Return an efficient array describing all valid indices for `a` arranged in the shape of `a` itself.
144

145
The keys of 1-dimensional arrays (vectors) are integers, whereas all other N-dimensional
146
arrays use [`CartesianIndex`](@ref) to describe their locations.  Often the special array
147
types [`LinearIndices`](@ref) and [`CartesianIndices`](@ref) are used to efficiently
148
represent these arrays of integers and `CartesianIndex`es, respectively.
149

150
Note that the `keys` of an array might not be the most efficient index type; for maximum
151
performance use  [`eachindex`](@ref) instead.
152

153
# Examples
154
```jldoctest
155
julia> keys([4, 5, 6])
156
3-element LinearIndices{1, Tuple{Base.OneTo{Int64}}}:
157
 1
158
 2
159
 3
160

161
julia> keys([4 5; 6 7])
162
CartesianIndices((2, 2))
163
```
164
"""
165
keys(a::AbstractArray) = CartesianIndices(axes(a))
×
166
keys(a::AbstractVector) = LinearIndices(a)
1,906,152✔
167

168
"""
169
    keytype(T::Type{<:AbstractArray})
170
    keytype(A::AbstractArray)
171

172
Return the key type of an array. This is equal to the
173
[`eltype`](@ref) of the result of `keys(...)`, and is provided
174
mainly for compatibility with the dictionary interface.
175

176
# Examples
177
```jldoctest
178
julia> keytype([1, 2, 3]) == Int
179
true
180

181
julia> keytype([1 2; 3 4])
182
CartesianIndex{2}
183
```
184

185
!!! compat "Julia 1.2"
186
     For arrays, this function requires at least Julia 1.2.
187
"""
188
keytype(a::AbstractArray) = keytype(typeof(a))
×
189
keytype(::Type{Union{}}, slurp...) = eltype(Union{})
×
190

191
keytype(A::Type{<:AbstractArray}) = CartesianIndex{ndims(A)}
×
192
keytype(A::Type{<:AbstractVector}) = Int
×
193

194
valtype(a::AbstractArray) = valtype(typeof(a))
×
195
valtype(::Type{Union{}}, slurp...) = eltype(Union{})
×
196

197
"""
198
    valtype(T::Type{<:AbstractArray})
199
    valtype(A::AbstractArray)
200

201
Return the value type of an array. This is identical to [`eltype`](@ref) and is
202
provided mainly for compatibility with the dictionary interface.
203

204
# Examples
205
```jldoctest
206
julia> valtype(["one", "two", "three"])
207
String
208
```
209

210
!!! compat "Julia 1.2"
211
     For arrays, this function requires at least Julia 1.2.
212
"""
213
valtype(A::Type{<:AbstractArray}) = eltype(A)
×
214

215
prevind(::AbstractArray, i::Integer) = Int(i)-1
422✔
216
nextind(::AbstractArray, i::Integer) = Int(i)+1
3,389,513✔
217

218

219
"""
220
    eltype(type)
221

222
Determine the type of the elements generated by iterating a collection of the given `type`.
223
For dictionary types, this will be a `Pair{KeyType,ValType}`. The definition
224
`eltype(x) = eltype(typeof(x))` is provided for convenience so that instances can be passed
225
instead of types. However the form that accepts a type argument should be defined for new
226
types.
227

228
See also: [`keytype`](@ref), [`typeof`](@ref).
229

230
# Examples
231
```jldoctest
232
julia> eltype(fill(1f0, (2,2)))
233
Float32
234

235
julia> eltype(fill(0x1, (2,2)))
236
UInt8
237
```
238
"""
239
eltype(::Type) = Any
304✔
240
eltype(::Type{Bottom}, slurp...) = throw(ArgumentError("Union{} does not have elements"))
×
241
eltype(x) = eltype(typeof(x))
247,551✔
242
eltype(::Type{<:AbstractArray{E}}) where {E} = @isdefined(E) ? E : Any
231✔
243

244
"""
245
    elsize(type)
246

247
Compute the memory stride in bytes between consecutive elements of [`eltype`](@ref)
248
stored inside the given `type`, if the array elements are stored densely with a
249
uniform linear stride.
250

251
# Examples
252
```jldoctest
253
julia> Base.elsize(rand(Float32, 10))
254
4
255
```
256
"""
257
elsize(A::AbstractArray) = elsize(typeof(A))
371,679✔
258

259
"""
260
    ndims(A::AbstractArray)::Integer
261

262
Return the number of dimensions of `A`.
263

264
See also: [`size`](@ref), [`axes`](@ref).
265

266
# Examples
267
```jldoctest
268
julia> A = fill(1, (3,4,5));
269

270
julia> ndims(A)
271
3
272
```
273
"""
274
ndims(::AbstractArray{T,N}) where {T,N} = N::Int
10,702✔
275
ndims(::Type{<:AbstractArray{<:Any,N}}) where {N} = N::Int
×
276
ndims(::Type{Union{}}, slurp...) = throw(ArgumentError("Union{} does not have elements"))
×
277

278
"""
279
    length(collection)::Integer
280

281
Return the number of elements in the collection.
282

283
Use [`lastindex`](@ref) to get the last valid index of an indexable collection.
284

285
See also: [`size`](@ref), [`ndims`](@ref), [`eachindex`](@ref).
286

287
# Examples
288
```jldoctest
289
julia> length(1:5)
290
5
291

292
julia> length([1, 2, 3, 4])
293
4
294

295
julia> length([1 2; 3 4])
296
4
297
```
298
"""
299
length
300

301
"""
302
    length(A::AbstractArray)
303

304
Return the number of elements in the array, defaults to `prod(size(A))`.
305

306
# Examples
307
```jldoctest
308
julia> length([1, 2, 3, 4])
309
4
310

311
julia> length([1 2; 3 4])
312
4
313
```
314
"""
315
length(t::AbstractArray) = (@inline; prod(size(t)))
911,642✔
316

317
# `eachindex` is mostly an optimization of `keys`
318
eachindex(itrs...) = keys(itrs...)
3✔
319

320
# eachindex iterates over all indices. IndexCartesian definitions are later.
321
eachindex(A::AbstractVector) = (@inline(); axes1(A))
12,459,359✔
322

323

324
# we unroll the join for easier inference
325
_join_comma_and(indsA, indsB) = LazyString(indsA, " and ", indsB)
×
326
_join_comma_and(indsA, indsB, indsC...) = LazyString(indsA, ", ", _join_comma_and(indsB, indsC...))
×
327
@noinline function throw_eachindex_mismatch_indices(indices_str, indsA, indsBs...)
×
328
    throw(DimensionMismatch(
×
329
            LazyString("all inputs to eachindex must have the same ", indices_str, ", got ",
330
                _join_comma_and(indsA, indsBs...))))
331
end
332

333
"""
334
    eachindex(A...)
335
    eachindex(::IndexStyle, A::AbstractArray...)
336

337
Create an iterable object for visiting each index of an `AbstractArray` `A` in an efficient
338
manner. For array types that have opted into fast linear indexing (like `Array`), this is
339
simply the range `1:length(A)` if they use 1-based indexing.
340
For array types that have not opted into fast linear indexing, a specialized Cartesian
341
range is typically returned to efficiently index into the array with indices specified
342
for every dimension.
343

344
In general `eachindex` accepts arbitrary iterables, including strings and dictionaries, and returns
345
an iterator object supporting arbitrary index types (e.g. unevenly spaced or non-integer indices).
346

347
If `A` is `AbstractArray` it is possible to explicitly specify the style of the indices that
348
should be returned by `eachindex` by passing a value having `IndexStyle` type as its first argument
349
(typically `IndexLinear()` if linear indices are required or `IndexCartesian()` if Cartesian
350
range is wanted).
351

352
If you supply more than one `AbstractArray` argument, `eachindex` will create an
353
iterable object that is fast for all arguments (typically a [`UnitRange`](@ref)
354
if all inputs have fast linear indexing, a [`CartesianIndices`](@ref) otherwise).
355
If the arrays have different sizes and/or dimensionalities, a `DimensionMismatch` exception
356
will be thrown.
357

358
See also [`pairs`](@ref)`(A)` to iterate over indices and values together,
359
and [`axes`](@ref)`(A, 2)` for valid indices along one dimension.
360

361
# Examples
362
```jldoctest
363
julia> A = [10 20; 30 40];
364

365
julia> for i in eachindex(A) # linear indexing
366
           println("A[", i, "] == ", A[i])
367
       end
368
A[1] == 10
369
A[2] == 30
370
A[3] == 20
371
A[4] == 40
372

373
julia> for i in eachindex(view(A, 1:2, 1:1)) # Cartesian indexing
374
           println(i)
375
       end
376
CartesianIndex(1, 1)
377
CartesianIndex(2, 1)
378
```
379
"""
380
eachindex(A::AbstractArray) = (@inline(); eachindex(IndexStyle(A), A))
×
381

382
function eachindex(A::AbstractArray, B::AbstractArray)
×
383
    @inline
×
384
    eachindex(IndexStyle(A,B), A, B)
×
385
end
386
function eachindex(A::AbstractArray, B::AbstractArray...)
×
387
    @inline
×
388
    eachindex(IndexStyle(A,B...), A, B...)
×
389
end
390
eachindex(::IndexLinear, A::Union{Array, Memory}) = unchecked_oneto(length(A))
39,348,919✔
UNCOV
391
eachindex(::IndexLinear, A::AbstractArray) = (@inline; oneto(length(A)))
×
392
eachindex(::IndexLinear, A::AbstractVector) = (@inline; axes1(A))
3,212,626✔
393
function eachindex(::IndexLinear, A::AbstractArray, B::AbstractArray...)
×
394
    @inline
×
395
    indsA = eachindex(IndexLinear(), A)
×
396
    indsBs = map(X -> eachindex(IndexLinear(), X), B)
×
UNCOV
397
    all(==(indsA), indsBs) ||
×
398
        throw_eachindex_mismatch_indices("indices", indsA, indsBs...)
UNCOV
399
    indsA
×
400
end
401

402
# keys with an IndexStyle
UNCOV
403
keys(s::IndexStyle, A::AbstractArray, B::AbstractArray...) = eachindex(s, A, B...)
×
404

405
"""
406
    lastindex(collection)::Integer
407
    lastindex(collection, d)::Integer
408

409
Return the last index of `collection`. If `d` is given, return the last index of `collection` along dimension `d`.
410

411
The syntaxes `A[end]` and `A[end, end]` lower to `A[lastindex(A)]` and
412
`A[lastindex(A, 1), lastindex(A, 2)]`, respectively.
413

414
See also: [`axes`](@ref), [`firstindex`](@ref), [`eachindex`](@ref), [`prevind`](@ref).
415

416
# Examples
417
```jldoctest
418
julia> lastindex([1,2,4])
419
3
420

421
julia> lastindex(rand(3,4,5), 2)
422
4
423
```
424
"""
425
lastindex(a::AbstractArray) = (@inline; last(eachindex(IndexLinear(), a)))
36,892,617✔
426
lastindex(a, d) = (@inline; last(axes(a, d)))
1,151✔
427

428
"""
429
    firstindex(collection)::Integer
430
    firstindex(collection, d)::Integer
431

432
Return the first index of `collection`. If `d` is given, return the first index of `collection` along dimension `d`.
433

434
The syntaxes `A[begin]` and `A[1, begin]` lower to `A[firstindex(A)]` and
435
`A[1, firstindex(A, 2)]`, respectively.
436

437
See also: [`first`](@ref), [`axes`](@ref), [`lastindex`](@ref), [`nextind`](@ref).
438

439
# Examples
440
```jldoctest
441
julia> firstindex([1,2,4])
442
1
443

444
julia> firstindex(rand(3,4,5), 2)
445
1
446
```
447
"""
448
firstindex(a::AbstractArray) = (@inline; first(eachindex(IndexLinear(), a)))
145,345✔
UNCOV
449
firstindex(a, d) = (@inline; first(axes(a, d)))
×
450

451
@propagate_inbounds first(a::AbstractArray) = a[first(eachindex(a))]
325✔
452

453
"""
454
    first(coll)
455

456
Get the first element of an iterable collection. Return the start point of an
457
[`AbstractRange`](@ref) even if it is empty.
458

459
See also: [`only`](@ref), [`firstindex`](@ref), [`last`](@ref).
460

461
# Examples
462
```jldoctest
463
julia> first(2:2:10)
464
2
465

466
julia> first([1; 2; 3; 4])
467
1
468
```
469
"""
470
function first(itr)
471
    x = iterate(itr)
×
472
    x === nothing && throw(ArgumentError("collection must be non-empty"))
×
UNCOV
473
    x[1]
×
474
end
475

476
"""
477
    first(itr, n::Integer)
478

479
Get the first `n` elements of the iterable collection `itr`, or fewer elements if `itr` is not
480
long enough.
481

482
See also: [`startswith`](@ref), [`Iterators.take`](@ref).
483

484
!!! compat "Julia 1.6"
485
    This method requires at least Julia 1.6.
486

487
# Examples
488
```jldoctest
489
julia> first(["foo", "bar", "qux"], 2)
490
2-element Vector{String}:
491
 "foo"
492
 "bar"
493

494
julia> first(1:6, 10)
495
1:6
496

497
julia> first(Bool[], 1)
498
Bool[]
499
```
500
"""
UNCOV
501
first(itr, n::Integer) = collect(Iterators.take(itr, n))
×
502
# Faster method for vectors
503
function first(v::AbstractVector, n::Integer)
×
504
    n < 0 && throw(ArgumentError("Number of elements must be non-negative"))
×
UNCOV
505
    v[range(begin, length=min(n, checked_length(v)))]
×
506
end
507

508
"""
509
    last(coll)
510

511
Get the last element of an ordered collection, if it can be computed in O(1) time. This is
512
accomplished by calling [`lastindex`](@ref) to get the last index. Return the end
513
point of an [`AbstractRange`](@ref) even if it is empty.
514

515
See also [`first`](@ref), [`endswith`](@ref).
516

517
# Examples
518
```jldoctest
519
julia> last(1:2:10)
520
9
521

522
julia> last([1; 2; 3; 4])
523
4
524
```
525
"""
526
last(a) = a[end]
2,518,730✔
527

528
"""
529
    last(itr, n::Integer)
530

531
Get the last `n` elements of the iterable collection `itr`, or fewer elements if `itr` is not
532
long enough.
533

534
!!! compat "Julia 1.6"
535
    This method requires at least Julia 1.6.
536

537
# Examples
538
```jldoctest
539
julia> last(["foo", "bar", "qux"], 2)
540
2-element Vector{String}:
541
 "bar"
542
 "qux"
543

544
julia> last(1:6, 10)
545
1:6
546

547
julia> last(Float64[], 1)
548
Float64[]
549
```
550
"""
UNCOV
551
last(itr, n::Integer) = reverse!(collect(Iterators.take(Iterators.reverse(itr), n)))
×
552
# Faster method for arrays
553
function last(v::AbstractVector, n::Integer)
×
554
    n < 0 && throw(ArgumentError("Number of elements must be non-negative"))
×
UNCOV
555
    v[range(stop=lastindex(v), length=min(n, checked_length(v)))]
×
556
end
557

558
"""
559
    strides(A)
560

561
Return a tuple of the memory strides in each dimension.
562

563
See also: [`stride`](@ref).
564

565
# Examples
566
```jldoctest
567
julia> A = fill(1, (3,4,5));
568

569
julia> strides(A)
570
(1, 3, 12)
571
```
572
"""
573
function strides end
574

575
"""
576
    stride(A, k::Integer)
577

578
Return the distance in memory (in number of elements) between adjacent elements in dimension `k`.
579

580
See also: [`strides`](@ref).
581

582
# Examples
583
```jldoctest
584
julia> A = fill(1, (3,4,5));
585

586
julia> stride(A,2)
587
3
588

589
julia> stride(A,3)
590
12
591
```
592
"""
593
function stride(A::AbstractArray, k::Integer)
×
594
    st = strides(A)
×
595
    k ≤ ndims(A) && return st[k]
×
596
    ndims(A) == 0 && return 1
×
597
    sz = size(A)
×
598
    s = st[1] * sz[1]
×
599
    for i in 2:ndims(A)
×
600
        s += st[i] * sz[i]
×
601
    end
×
UNCOV
602
    return s
×
603
end
604

605
@inline size_to_strides(s, d, sz...) = (s, size_to_strides(s * d, sz...)...)
×
606
size_to_strides(s, d) = (s,)
×
UNCOV
607
size_to_strides(s) = ()
×
608

609
function isstored(A::AbstractArray{<:Any,N}, I::Vararg{Integer,N}) where {N}
×
610
    @boundscheck checkbounds(A, I...)
×
UNCOV
611
    return true
×
612
end
613

614
# used to compute "end" for last index
615
function trailingsize(A, n)
×
616
    s = 1
×
617
    for i=n:ndims(A)
×
618
        s *= size(A,i)
×
619
    end
×
UNCOV
620
    return s
×
621
end
622
function trailingsize(inds::Indices, n)
×
623
    s = 1
×
624
    for i=n:length(inds)
×
625
        s *= length(inds[i])
×
626
    end
×
UNCOV
627
    return s
×
628
end
629
# This version is type-stable even if inds is heterogeneous
630
function trailingsize(inds::Indices)
×
631
    @inline
×
UNCOV
632
    prod(map(length, inds))
×
633
end
634

635
## Bounds checking ##
636

637
# The overall hierarchy is
638
#     `checkbounds(A, I...)` ->
639
#         `checkbounds(Bool, A, I...)` ->
640
#             `checkbounds_indices(Bool, IA, I)`, which recursively calls
641
#                 `checkindex` for each dimension
642
#
643
# See the "boundscheck" devdocs for more information.
644
#
645
# Note this hierarchy has been designed to reduce the likelihood of
646
# method ambiguities.  We try to make `checkbounds` the place to
647
# specialize on array type, and try to avoid specializations on index
648
# types; conversely, `checkindex` is intended to be specialized only
649
# on index type (especially, its last argument).
650

651
"""
652
    checkbounds(Bool, A, I...)
653

654
Return `true` if the specified indices `I` are in bounds for the given
655
array `A`. Subtypes of `AbstractArray` should specialize this method
656
if they need to provide custom bounds checking behaviors; however, in
657
many cases one can rely on `A`'s indices and [`checkindex`](@ref).
658

659
See also [`checkindex`](@ref).
660

661
# Examples
662
```jldoctest
663
julia> A = rand(3, 3);
664

665
julia> checkbounds(Bool, A, 2)
666
true
667

668
julia> checkbounds(Bool, A, 3, 4)
669
false
670

671
julia> checkbounds(Bool, A, 1:3)
672
true
673

674
julia> checkbounds(Bool, A, 1:3, 2:4)
675
false
676
```
677
"""
678
function checkbounds(::Type{Bool}, A::AbstractArray, I...)
679
    @inline
10,723✔
680
    checkbounds_indices(Bool, axes(A), I)
126,963✔
681
end
682

683
# Linear indexing is explicitly allowed when there is only one (non-cartesian) index;
684
# indices that do not allow linear indexing (e.g., logical arrays, cartesian indices, etc)
685
# must add specialized methods to implement their restrictions
686
function checkbounds(::Type{Bool}, A::AbstractArray, i)
258,232✔
687
    @inline
951,315✔
688
    return checkindex(Bool, eachindex(IndexLinear(), A), i)
7,069,827✔
689
end
690

691
"""
692
    checkbounds(A, I...)
693

694
Throw an error if the specified indices `I` are not in bounds for the given array `A`.
695
"""
696
function checkbounds(A::AbstractArray, I...)
258,232✔
697
    @inline
828,304✔
698
    checkbounds(Bool, A, I...) || throw_boundserror(A, I)
5,444,095✔
699
    nothing
828,304✔
700
end
701

702
"""
703
    checkbounds_indices(Bool, IA, I)
704

705
Return `true` if the "requested" indices in the tuple `I` fall within
706
the bounds of the "permitted" indices specified by the tuple
707
`IA`. This function recursively consumes elements of these tuples,
708
usually in a 1-for-1 fashion,
709

710
    checkbounds_indices(Bool, (IA1, IA...), (I1, I...)) = checkindex(Bool, IA1, I1) &
711
                                                          checkbounds_indices(Bool, IA, I)
712

713
Note that [`checkindex`](@ref) is being used to perform the actual
714
bounds-check for a single dimension of the array.
715

716
There are two important exceptions to the 1-1 rule: linear indexing and
717
CartesianIndex{N}, both of which may "consume" more than one element
718
of `IA`.
719

720
See also [`checkbounds`](@ref).
721
"""
722
function checkbounds_indices(::Type{Bool}, inds::Tuple, I::Tuple{Any, Vararg})
723
    @inline
13,845✔
724
    return checkindex(Bool, get(inds, 1, OneTo(1)), I[1])::Bool &
253,346✔
725
        checkbounds_indices(Bool, safe_tail(inds), tail(I))
726
end
727

UNCOV
728
checkbounds_indices(::Type{Bool}, inds::Tuple, ::Tuple{}) = (@inline; all(x->length(x)==1, inds))
×
729

730
# check along a single dimension
731
"""
732
    checkindex(Bool, inds::AbstractUnitRange, index)
733

734
Return `true` if the given `index` is within the bounds of
735
`inds`. Custom types that would like to behave as indices for all
736
arrays can extend this method in order to provide a specialized bounds
737
checking implementation.
738

739
See also [`checkbounds`](@ref).
740

741
# Examples
742
```jldoctest
743
julia> checkindex(Bool, 1:20, 8)
744
true
745

746
julia> checkindex(Bool, 1:20, 21)
747
false
748
```
749
"""
UNCOV
750
checkindex(::Type{Bool}, inds, i) = throw(ArgumentError(LazyString("unable to check bounds for indices of type ", typeof(i))))
×
751
checkindex(::Type{Bool}, inds::AbstractUnitRange, i::Real) = (first(inds) <= i) & (i <= last(inds))
1,559,196✔
UNCOV
752
checkindex(::Type{Bool}, inds::IdentityUnitRange, i::Real) = checkindex(Bool, inds.indices, i)
×
753
checkindex(::Type{Bool}, inds::OneTo{T}, i::T) where {T<:BitInteger} = unsigned(i - one(i)) < unsigned(last(inds))
7,649,327✔
754
checkindex(::Type{Bool}, inds::AbstractUnitRange, ::Colon) = true
×
UNCOV
755
checkindex(::Type{Bool}, inds::AbstractUnitRange, ::Slice) = true
×
756
checkindex(::Type{Bool}, inds::AbstractUnitRange, i::AbstractRange) =
3,188,461✔
757
    isempty(i) | (checkindex(Bool, inds, first(i)) & checkindex(Bool, inds, last(i)))
758
# range like indices with cheap `extrema`
UNCOV
759
checkindex(::Type{Bool}, inds::AbstractUnitRange, i::LinearIndices) =
×
760
    isempty(i) | (checkindex(Bool, inds, first(i)) & checkindex(Bool, inds, last(i)))
761

762
function checkindex(::Type{Bool}, inds, I::AbstractArray)
763
    @inline
×
UNCOV
764
    b = true
×
765
    for i in I
2,551✔
766
        b &= checkindex(Bool, inds, i)
28,557✔
767
    end
28,557✔
768
    b
2,551✔
769
end
770

771
# See also specializations in multidimensional
772

773
## Constructors ##
774

775
# default arguments to similar()
776
"""
777
    similar(array, [element_type=eltype(array)], [dims=size(array)])
778

779
Create an uninitialized mutable array with the given element type and size, based upon the
780
given source array. The second and third arguments are both optional, defaulting to the
781
given array's `eltype` and `size`. The dimensions may be specified either as a single tuple
782
argument or as a series of integer arguments.
783

784
Custom AbstractArray subtypes may choose which specific array type is best-suited to return
785
for the given element type and dimensionality. If they do not specialize this method, the
786
default is an `Array{element_type}(undef, dims...)`.
787

788
For example, `similar(1:10, 1, 4)` returns an uninitialized `Array{Int,2}` since ranges are
789
neither mutable nor support 2 dimensions:
790

791
```julia-repl
792
julia> similar(1:10, 1, 4)
793
1×4 Matrix{Int64}:
794
 4419743872  4374413872  4419743888  0
795
```
796

797
Conversely, `similar(trues(10,10), 2)` returns an uninitialized `BitVector` with two
798
elements since `BitArray`s are both mutable and can support 1-dimensional arrays:
799

800
```jldoctest; filter = r"[01]"
801
julia> similar(trues(10,10), 2)
802
2-element BitVector:
803
 0
804
 0
805
```
806

807
Since `BitArray`s can only store elements of type [`Bool`](@ref), however, if you request a
808
different element type it will create a regular `Array` instead:
809

810
```julia-repl
811
julia> similar(falses(10), Float64, 2, 4)
812
2×4 Matrix{Float64}:
813
 2.18425e-314  2.18425e-314  2.18425e-314  2.18425e-314
814
 2.18425e-314  2.18425e-314  2.18425e-314  2.18425e-314
815
```
816

817
See also: [`undef`](@ref), [`isassigned`](@ref).
818
"""
819
similar(a::AbstractArray{T}) where {T}                             = similar(a, T)
18✔
820
similar(a::AbstractArray, ::Type{T}) where {T}                     = similar(a, T, axes(a))
18✔
821
similar(a::AbstractArray{T}, dims::Tuple) where {T}                = similar(a, T, dims)
965,331✔
UNCOV
822
similar(a::AbstractArray{T}, dims::DimOrInd...) where {T}          = similar(a, T, dims)
×
823
similar(a::AbstractArray, ::Type{T}, dims::DimOrInd...) where {T}  = similar(a, T, dims)
40,882✔
824
# Similar supports specifying dims as either Integers or AbstractUnitRanges or any mixed combination
825
# thereof. Ideally, we'd just convert Integers to OneTos and then call a canonical method with the axes,
826
# but we don't want to require all AbstractArray subtypes to dispatch on Base.OneTo. So instead we
827
# define this method to convert supported axes to Ints, with the expectation that an offset array
828
# package will define a method with dims::Tuple{Union{Integer, UnitRange}, Vararg{Union{Integer, UnitRange}}}
UNCOV
829
similar(a::AbstractArray, ::Type{T}, dims::Tuple{Union{Integer, AbstractOneTo}, Vararg{Union{Integer, AbstractOneTo}}}) where {T} = similar(a, T, to_shape(dims))
×
830
# legacy method for packages that specialize similar(A::AbstractArray, ::Type{T}, dims::Tuple{Union{Integer, OneTo, CustomAxis}, Vararg{Union{Integer, OneTo, CustomAxis}}}
831
# leaving this method in ensures that Base owns the more specific method
832
similar(a::AbstractArray, ::Type{T}, dims::Tuple{Union{Integer, OneTo}, Vararg{Union{Integer, OneTo}}}) where {T} = similar(a, T, to_shape(dims))
965,560✔
833
# similar creates an Array by default
834
similar(a::AbstractArray, ::Type{T}, dims::Dims{N}) where {T,N}    = Array{T,N}(undef, dims)
40,895✔
835

836
to_shape(::Tuple{}) = ()
×
UNCOV
837
to_shape(dims::Dims) = dims
×
838
to_shape(dims::DimsOrInds) = map(to_shape, dims)::DimsOrInds
550,598✔
839
# each dimension
840
to_shape(i::Int) = i
434,414✔
841
to_shape(i::Integer) = Int(i)
2,486✔
842
to_shape(r::AbstractOneTo) = _to_shape(last(r))
550,597✔
843
_to_shape(x::Integer) = to_shape(x)
436,900✔
844
_to_shape(x) = Int(x)
×
UNCOV
845
to_shape(r::AbstractUnitRange) = r
×
846

847
"""
848
    similar(storagetype, axes)
849

850
Create an uninitialized mutable array analogous to that specified by
851
`storagetype`, but with `axes` specified by the last
852
argument.
853

854
**Examples**:
855

856
    similar(Array{Int}, axes(A))
857

858
creates an array that "acts like" an `Array{Int}` (and might indeed be
859
backed by one), but which is indexed identically to `A`. If `A` has
860
conventional indexing, this will be identical to
861
`Array{Int}(undef, size(A))`, but if `A` has unconventional indexing then the
862
indices of the result will match `A`.
863

864
    similar(BitArray, (axes(A, 2),))
865

866
would create a 1-dimensional logical array whose indices match those
867
of the columns of `A`.
868
"""
869
similar(::Type{T}, dims::DimOrInd...) where {T<:AbstractArray} = similar(T, dims)
×
UNCOV
870
similar(::Type{T}, shape::Tuple{Union{Integer, AbstractOneTo}, Vararg{Union{Integer, AbstractOneTo}}}) where {T<:AbstractArray} = similar(T, to_shape(shape))
×
871
# legacy method for packages that specialize similar(::Type{T}, dims::Tuple{Union{Integer, OneTo, CustomAxis}, Vararg{Union{Integer, OneTo, CustomAxis}})
872
similar(::Type{T}, shape::Tuple{Union{Integer, OneTo}, Vararg{Union{Integer, OneTo}}}) where {T<:AbstractArray} = similar(T, to_shape(shape))
5,966,225✔
873
similar(::Type{T}, dims::Dims) where {T<:AbstractArray} = T(undef, dims)
5,966,225✔
874

875
"""
876
    empty(v::AbstractVector, [eltype])
877

878
Create an empty vector similar to `v`, optionally changing the `eltype`.
879

880
See also: [`empty!`](@ref), [`isempty`](@ref), [`isassigned`](@ref).
881

882
# Examples
883

884
```jldoctest
885
julia> empty([1.0, 2.0, 3.0])
886
Float64[]
887

888
julia> empty([1.0, 2.0, 3.0], String)
889
String[]
890
```
891
"""
892
empty(a::AbstractVector{T}, ::Type{U}=T) where {T,U} = similar(a, U, 0)
4✔
893

894
# like empty, but should return a mutable collection, a Vector by default
895
emptymutable(a::AbstractVector{T}, ::Type{U}=T) where {T,U} = Vector{U}()
2✔
UNCOV
896
emptymutable(itr, ::Type{U}) where {U} = Vector{U}()
×
897

898
"""
899
    copy!(dst, src) -> dst
900

901
In-place [`copy`](@ref) of `src` into `dst`, discarding any pre-existing
902
elements in `dst`.
903
If `dst` and `src` are of the same type, `dst == src` should hold after
904
the call. If `dst` and `src` are vector types, they must have equal
905
offset. If `dst` and `src` are multidimensional arrays, they must have
906
equal [`axes`](@ref).
907

908
$(_DOCS_ALIASING_WARNING)
909

910
See also [`copyto!`](@ref).
911

912
!!! note
913
    When operating on vector types, if `dst` and `src` are not of the
914
    same length, `dst` is resized to `length(src)` prior to the `copy`.
915

916
!!! compat "Julia 1.1"
917
    This method requires at least Julia 1.1. In Julia 1.0 this method
918
    is available from the `Future` standard library as `Future.copy!`.
919
"""
920
function copy!(dst::AbstractVector, src::AbstractVector)
126,331✔
921
    firstindex(dst) == firstindex(src) || throw(ArgumentError(
126,331✔
922
        "vectors must have the same offset for copy! (consider using `copyto!`)"))
923
    if length(dst) != length(src)
126,331✔
924
        resize!(dst, length(src))
123,721✔
925
    end
926
    copyto!(dst, src)
126,331✔
927
end
928

929
function copy!(dst::AbstractArray, src::AbstractArray)
×
UNCOV
930
    axes(dst) == axes(src) || throw(ArgumentError(
×
931
        "arrays must have the same axes for copy! (consider using `copyto!`)"))
UNCOV
932
    copyto!(dst, src)
×
933
end
934

935
## from general iterable to any array
936

937
# This is `Experimental.@max_methods 1 function copyto! end`, which is not
938
# defined at this point in bootstrap.
939
typeof(function copyto! end).name.max_methods = UInt8(1)
940

941
function copyto!(dest::AbstractArray, src)
38,496✔
942
    destiter = eachindex(dest)
38,496✔
943
    y = iterate(destiter)
38,496✔
944
    for x in src
65,729✔
945
        y === nothing &&
115,633✔
946
            throw(ArgumentError("destination has fewer elements than required"))
947
        dest[y[1]] = x
115,633✔
948
        y = iterate(destiter, y[2])
194,962✔
949
    end
178,363✔
950
    return dest
38,496✔
951
end
952

953
function copyto!(dest::AbstractArray, dstart::Integer, src)
×
954
    i = Int(dstart)
×
955
    if haslength(src) && length(dest) > 0
×
956
        @boundscheck checkbounds(dest, i:(i + length(src) - 1))
×
957
        for x in src
×
958
            @inbounds dest[i] = x
×
959
            i += 1
×
UNCOV
960
        end
×
961
    else
962
        for x in src
×
963
            dest[i] = x
×
964
            i += 1
×
UNCOV
965
        end
×
966
    end
UNCOV
967
    return dest
×
968
end
969

970
# copy from an some iterable object into an AbstractArray
971
function copyto!(dest::AbstractArray, dstart::Integer, src, sstart::Integer)
×
972
    if (sstart < 1)
×
UNCOV
973
        throw(ArgumentError(LazyString("source start offset (",sstart,") is < 1")))
×
974
    end
975
    y = iterate(src)
×
976
    for j = 1:(sstart-1)
×
977
        if y === nothing
×
UNCOV
978
            throw(ArgumentError(LazyString(
×
979
                "source has fewer elements than required, ",
980
                "expected at least ", sstart,", got ", j-1)))
981
        end
982
        y = iterate(src, y[2])
×
983
    end
×
984
    if y === nothing
×
UNCOV
985
        throw(ArgumentError(LazyString(
×
986
            "source has fewer elements than required, ",
987
            "expected at least ",sstart," got ", sstart-1)))
988
    end
989
    i = Int(dstart)
×
990
    while y !== nothing
×
991
        val, st = y
×
992
        dest[i] = val
×
993
        i += 1
×
994
        y = iterate(src, st)
×
995
    end
×
UNCOV
996
    return dest
×
997
end
998

999
# this method must be separate from the above since src might not have a length
1000
function copyto!(dest::AbstractArray, dstart::Integer, src, sstart::Integer, n::Integer)
1,911✔
1001
    n < 0 && throw(ArgumentError(LazyString("tried to copy n=",n,
1,911✔
1002
        ", elements, but n should be non-negative")))
1003
    n == 0 && return dest
1,911✔
1004
    dmax = dstart + n - 1
1,911✔
1005
    inds = LinearIndices(dest)
1,911✔
1006
    if (dstart ∉ inds || dmax ∉ inds) | (sstart < 1)
3,822✔
UNCOV
1007
        sstart < 1 && throw(ArgumentError(LazyString("source start offset (",
×
1008
            sstart,") is < 1")))
UNCOV
1009
        throw(BoundsError(dest, dstart:dmax))
×
1010
    end
1011
    y = iterate(src)
1,911✔
1012
    for j = 1:(sstart-1)
1,911✔
1013
        if y === nothing
×
UNCOV
1014
            throw(ArgumentError(LazyString(
×
1015
                "source has fewer elements than required, ",
1016
                "expected at least ",sstart,", got ",j-1)))
1017
        end
1018
        y = iterate(src, y[2])
×
UNCOV
1019
    end
×
1020
    if y === nothing
1,911✔
UNCOV
1021
        throw(ArgumentError(LazyString(
×
1022
            "source has fewer elements than required, ",
1023
            "expected at least ",sstart," got ", sstart-1)))
1024
    end
1025
    val, st = y
1,911✔
1026
    i = Int(dstart)
1,911✔
1027
    @inbounds dest[i] = val
1,911✔
1028
    for val in Iterators.take(Iterators.rest(src, st), n-1)
3,776✔
1029
        i += 1
3,822✔
1030
        @inbounds dest[i] = val
3,822✔
1031
    end
5,687✔
1032
    i < dmax && throw(BoundsError(dest, i))
1,911✔
1033
    return dest
1,911✔
1034
end
1035

1036
## copy between abstract arrays - generally more efficient
1037
## since a single index variable can be used.
1038

1039
"""
1040
    copyto!(dest::AbstractArray, src) -> dest
1041

1042
Copy all elements from collection `src` to array `dest`, whose length must be greater than
1043
or equal to the length `n` of `src`. The first `n` elements of `dest` are overwritten,
1044
the other elements are left untouched.
1045

1046
See also [`copy!`](@ref Base.copy!), [`copy`](@ref).
1047

1048
$(_DOCS_ALIASING_WARNING)
1049

1050
# Examples
1051
```jldoctest
1052
julia> x = [1., 0., 3., 0., 5.];
1053

1054
julia> y = zeros(7);
1055

1056
julia> copyto!(y, x);
1057

1058
julia> y
1059
7-element Vector{Float64}:
1060
 1.0
1061
 0.0
1062
 3.0
1063
 0.0
1064
 5.0
1065
 0.0
1066
 0.0
1067
```
1068
"""
UNCOV
1069
function copyto!(dest::AbstractArray, src::AbstractArray)
×
1070
    isempty(src) && return dest
8,440✔
UNCOV
1071
    if dest isa BitArray
×
1072
        # avoid ambiguities with other copyto!(::AbstractArray, ::SourceArray) methods
UNCOV
1073
        return _copyto_bitarray!(dest, src)
×
1074
    end
1075
    src′ = unalias(dest, src)
8,422✔
1076
    copyto_unaliased!(IndexStyle(dest), dest, IndexStyle(src′), src′)
8,440✔
1077
end
1078

1079
function copyto!(deststyle::IndexStyle, dest::AbstractArray, srcstyle::IndexStyle, src::AbstractArray)
×
1080
    isempty(src) && return dest
×
1081
    src′ = unalias(dest, src)
×
UNCOV
1082
    copyto_unaliased!(deststyle, dest, srcstyle, src′)
×
1083
end
1084

UNCOV
1085
function copyto_unaliased!(deststyle::IndexStyle, dest::AbstractArray, srcstyle::IndexStyle, src::AbstractArray)
×
1086
    isempty(src) && return dest
18✔
1087
    destinds, srcinds = LinearIndices(dest), LinearIndices(src)
18✔
1088
    idf, isf = first(destinds), first(srcinds)
×
UNCOV
1089
    Δi = idf - isf
×
1090
    (checkbounds(Bool, destinds, isf+Δi) & checkbounds(Bool, destinds, last(srcinds)+Δi)) ||
18✔
1091
        throw(BoundsError(dest, srcinds))
1092
    if deststyle isa IndexLinear
×
UNCOV
1093
        if srcstyle isa IndexLinear
×
1094
            # Single-index implementation
1095
            @inbounds for i in srcinds
18✔
1096
                dest[i + Δi] = src[i]
36✔
1097
            end
54✔
1098
        else
1099
            # Dual-index implementation
1100
            i = idf - 1
×
1101
            @inbounds for a in src
×
1102
                dest[i+=1] = a
×
UNCOV
1103
            end
×
1104
        end
1105
    else
1106
        iterdest, itersrc = eachindex(dest), eachindex(src)
×
UNCOV
1107
        if iterdest == itersrc
×
1108
            # Shared-iterator implementation
1109
            for I in iterdest
×
1110
                @inbounds dest[I] = src[I]
×
UNCOV
1111
            end
×
1112
        else
1113
            # Dual-iterator implementation
1114
            for (Idest, Isrc) in zip(iterdest, itersrc)
×
1115
                @inbounds dest[Idest] = src[Isrc]
×
UNCOV
1116
            end
×
1117
        end
1118
    end
1119
    return dest
18✔
1120
end
1121

1122
function copyto!(dest::AbstractArray, dstart::Integer, src::AbstractArray)
×
UNCOV
1123
    copyto!(dest, dstart, src, first(LinearIndices(src)), length(src))
×
1124
end
1125

1126
function copyto!(dest::AbstractArray, dstart::Integer, src::AbstractArray, sstart::Integer)
×
1127
    srcinds = LinearIndices(src)
×
1128
    checkbounds(Bool, srcinds, sstart) || throw(BoundsError(src, sstart))
×
UNCOV
1129
    copyto!(dest, dstart, src, sstart, last(srcinds)-sstart+1)
×
1130
end
1131

1132
function copyto!(dest::AbstractArray, dstart::Integer,
386,691✔
1133
                 src::AbstractArray, sstart::Integer,
1134
                 n::Integer)
1135
    n == 0 && return dest
386,691✔
1136
    n < 0 && throw(ArgumentError(LazyString("tried to copy n=",
386,691✔
1137
        n," elements, but n should be non-negative")))
1138
    destinds, srcinds = LinearIndices(dest), LinearIndices(src)
386,691✔
1139
    (checkbounds(Bool, destinds, dstart) && checkbounds(Bool, destinds, dstart+n-1)) || throw(BoundsError(dest, dstart:dstart+n-1))
386,691✔
1140
    (checkbounds(Bool, srcinds, sstart)  && checkbounds(Bool, srcinds, sstart+n-1))  || throw(BoundsError(src,  sstart:sstart+n-1))
386,691✔
1141
    src′ = unalias(dest, src)
386,691✔
1142
    @inbounds for i = 0:n-1
386,691✔
1143
        dest[dstart+i] = src′[sstart+i]
22,571,078✔
1144
    end
44,755,465✔
1145
    return dest
386,691✔
1146
end
1147

1148
function copy(a::AbstractArray)
×
UNCOV
1149
    @_propagate_inbounds_meta
×
1150
    copymutable(a)
5,885✔
1151
end
1152

UNCOV
1153
function copyto!(B::AbstractVecOrMat{R}, ir_dest::AbstractRange{Int}, jr_dest::AbstractRange{Int},
×
1154
               A::AbstractVecOrMat{S}, ir_src::AbstractRange{Int}, jr_src::AbstractRange{Int}) where {R,S}
1155
    if length(ir_dest) != length(ir_src)
×
UNCOV
1156
        throw(ArgumentError(LazyString("source and destination must have same size (got ",
×
1157
            length(ir_src)," and ",length(ir_dest),")")))
1158
    end
1159
    if length(jr_dest) != length(jr_src)
×
UNCOV
1160
        throw(ArgumentError(LazyString("source and destination must have same size (got ",
×
1161
            length(jr_src)," and ",length(jr_dest),")")))
1162
    end
1163
    @boundscheck checkbounds(B, ir_dest, jr_dest)
×
1164
    @boundscheck checkbounds(A, ir_src, jr_src)
×
1165
    A′ = unalias(B, A)
×
1166
    jdest = first(jr_dest)
×
1167
    for jsrc in jr_src
×
1168
        idest = first(ir_dest)
×
1169
        for isrc in ir_src
×
1170
            @inbounds B[idest,jdest] = A′[isrc,jsrc]
×
1171
            idest += step(ir_dest)
×
1172
        end
×
1173
        jdest += step(jr_dest)
×
1174
    end
×
UNCOV
1175
    return B
×
1176
end
1177

1178
@noinline _checkaxs(axd, axs) = axd == axs || throw(DimensionMismatch("axes must agree, got $axd and $axs"))
39✔
1179

1180
function copyto_axcheck!(dest, src)
37✔
1181
    _checkaxs(axes(dest), axes(src))
163✔
1182
    copyto!(dest, src)
164✔
1183
end
1184

1185
"""
1186
    copymutable(a)
1187

1188
Make a mutable copy of an array or iterable `a`.  For `a::Array`,
1189
this is equivalent to `copy(a)`, but for other array types it may
1190
differ depending on the type of `similar(a)`.  For generic iterables
1191
this is equivalent to `collect(a)`.
1192

1193
# Examples
1194
```jldoctest
1195
julia> tup = (1, 2, 3)
1196
(1, 2, 3)
1197

1198
julia> Base.copymutable(tup)
1199
3-element Vector{Int64}:
1200
 1
1201
 2
1202
 3
1203
```
1204
"""
UNCOV
1205
function copymutable(a::AbstractArray)
×
1206
    @_propagate_inbounds_meta
793✔
1207
    copyto!(similar(a), a)
7,507✔
1208
end
UNCOV
1209
copymutable(itr) = collect(itr)
×
1210

1211
zero(x::AbstractArray{T}) where {T<:Number} = fill!(similar(x, typeof(zero(T))), zero(T))
×
1212
zero(x::AbstractArray{S}) where {S<:Union{Missing, Number}} = fill!(similar(x, typeof(zero(S))), zero(S))
×
UNCOV
1213
zero(x::AbstractArray) = map(zero, x)
×
1214

1215
function _one(unit::T, mat::AbstractMatrix) where {T}
×
1216
    (rows, cols) = axes(mat)
×
UNCOV
1217
    (length(rows) == length(cols)) ||
×
1218
      throw(DimensionMismatch("multiplicative identity defined only for square matrices"))
1219
    zer = zero(unit)::T
×
1220
    require_one_based_indexing(mat)
×
1221
    I = similar(mat, T)
×
1222
    fill!(I, zer)
×
1223
    for i ∈ rows
×
1224
        I[i, i] = unit
×
1225
    end
×
UNCOV
1226
    I
×
1227
end
1228

1229
one(x::AbstractMatrix{T}) where {T} = _one(one(T), x)
×
UNCOV
1230
oneunit(x::AbstractMatrix{T}) where {T} = _one(oneunit(T), x)
×
1231

1232
## iteration support for arrays by iterating over `eachindex` in the array ##
1233
# Allows fast iteration by default for both IndexLinear and IndexCartesian arrays
1234

1235
# While the definitions for IndexLinear are all simple enough to inline on their
1236
# own, IndexCartesian's CartesianIndices is more complicated and requires explicit
1237
# inlining.
1238
iterate_starting_state(A) = iterate_starting_state(A, IndexStyle(A))
262,725✔
1239
iterate_starting_state(A, ::IndexLinear) = firstindex(A)
262,717✔
1240
iterate_starting_state(A, ::IndexStyle) = (eachindex(A),)
8✔
1241
@inline iterate(A::AbstractArray, state = iterate_starting_state(A)) = _iterate(A, state)
208,315,966✔
1242
@inline function _iterate(A::AbstractArray, state::Tuple)
1243
    y = iterate(state...)
12✔
1244
    y === nothing && return nothing
11✔
1245
    A[y[1]], (state[1], tail(y)...)
3✔
1246
end
1247
@inline function _iterate(A::AbstractArray, state::Integer)
15,273,616✔
1248
    checkbounds(Bool, A, state) || return nothing
206,270,705✔
1249
    A[state], state + one(state)
156,070,789✔
1250
end
1251

1252
isempty(a::AbstractArray) = (length(a) == 0)
63,461,243✔
1253

1254

1255
## range conversions ##
1256

1257
map(::Type{T}, r::StepRange) where {T<:Real} = T(r.start):T(r.step):T(last(r))
×
1258
map(::Type{T}, r::UnitRange) where {T<:Real} = T(r.start):T(last(r))
×
1259
map(::Type{T}, r::StepRangeLen) where {T<:AbstractFloat} = convert(StepRangeLen{T}, r)
×
1260
function map(::Type{T}, r::LinRange) where T<:AbstractFloat
×
UNCOV
1261
    LinRange(T(r.start), T(r.stop), length(r))
×
1262
end
1263

1264
## unsafe/pointer conversions ##
1265

1266
# note: the following type definitions don't mean any AbstractArray is convertible to
1267
# a data Ref. they just map the array element type to the pointer type for
1268
# convenience in cases that work.
1269
pointer(x::AbstractArray{T}) where {T} = unsafe_convert(Ptr{T}, cconvert(Ptr{T}, x))
999,996✔
1270
function pointer(x::AbstractArray{T}, i::Integer) where T
1271
    @inline
132✔
1272
    pointer(x) + Int(_memory_offset(x, i))::Int
284,217✔
1273
end
1274

1275
# The distance from pointer(x) to the element at x[I...] in bytes
1276
_memory_offset(x::DenseArray, I::Vararg{Any,N}) where {N} = (_to_linear_index(x, I...) - first(LinearIndices(x)))*elsize(x)
284,088✔
1277
function _memory_offset(x::AbstractArray, I::Vararg{Any,N}) where {N}
×
1278
    J = _to_subscript_indices(x, I...)
×
UNCOV
1279
    return sum(map((i, s, o)->s*(i-o), J, strides(x), Tuple(first(CartesianIndices(x)))))*elsize(x)
×
1280
end
1281

1282
## Special constprop heuristics for getindex/setindex
1283
typename(typeof(function getindex end)).constprop_heuristic = Core.ARRAY_INDEX_HEURISTIC
1284
typename(typeof(function setindex! end)).constprop_heuristic = Core.ARRAY_INDEX_HEURISTIC
1285

1286
## Approach:
1287
# We only define one fallback method on getindex for all argument types.
1288
# That dispatches to an (inlined) internal _getindex function, where the goal is
1289
# to transform the indices such that we can call the only getindex method that
1290
# we require the type A{T,N} <: AbstractArray{T,N} to define; either:
1291
#       getindex(::A, ::Int) # if IndexStyle(A) == IndexLinear() OR
1292
#       getindex(::A{T,N}, ::Vararg{Int, N}) where {T,N} # if IndexCartesian()
1293
# If the subtype hasn't defined the required method, it falls back to the
1294
# _getindex function again where an error is thrown to prevent stack overflows.
1295
"""
1296
    getindex(A, inds...)
1297

1298
Return a subset of array `A` as selected by the indices `inds`.
1299

1300
Each index may be any [supported index type](@ref man-supported-index-types), such
1301
as an [`Integer`](@ref), [`CartesianIndex`](@ref), [range](@ref Base.AbstractRange), or [array](@ref man-multi-dim-arrays) of supported indices.
1302
A [:](@ref Base.Colon) may be used to select all elements along a specific dimension, and a boolean array (e.g. an `Array{Bool}` or a [`BitArray`](@ref)) may be used to filter for elements where the corresponding index is `true`.
1303

1304
When `inds` selects multiple elements, this function returns a newly
1305
allocated array. To index multiple elements without making a copy,
1306
use [`view`](@ref) instead.
1307

1308
See the manual section on [array indexing](@ref man-array-indexing) for details.
1309

1310
# Examples
1311
```jldoctest
1312
julia> A = [1 2; 3 4]
1313
2×2 Matrix{Int64}:
1314
 1  2
1315
 3  4
1316

1317
julia> getindex(A, 1)
1318
1
1319

1320
julia> getindex(A, [2, 1])
1321
2-element Vector{Int64}:
1322
 3
1323
 1
1324

1325
julia> getindex(A, 2:4)
1326
3-element Vector{Int64}:
1327
 3
1328
 2
1329
 4
1330

1331
julia> getindex(A, 2, 1)
1332
3
1333

1334
julia> getindex(A, CartesianIndex(2, 1))
1335
3
1336

1337
julia> getindex(A, :, 2)
1338
2-element Vector{Int64}:
1339
 2
1340
 4
1341

1342
julia> getindex(A, 2, :)
1343
2-element Vector{Int64}:
1344
 3
1345
 4
1346

1347
julia> getindex(A, A .> 2)
1348
2-element Vector{Int64}:
1349
 3
1350
 4
1351
```
1352
"""
1353
function getindex(A::AbstractArray, I...)
14,514✔
1354
    @_propagate_inbounds_meta
23,649,467✔
1355
    error_if_canonical_getindex(IndexStyle(A), A, I...)
23,649,467✔
1356
    _getindex(IndexStyle(A), A, to_indices(A, I)...)
23,829,971✔
1357
end
1358
# To avoid invalidations from multidimensional.jl: getindex(A::Array, i1::Union{Integer, CartesianIndex}, I::Union{Integer, CartesianIndex}...)
1359
@propagate_inbounds getindex(A::Array, i1::Integer, I::Integer...) = A[to_indices(A, (i1, I...))...]
757,008✔
1360

UNCOV
1361
@inline unsafe_getindex(A::AbstractArray, I...) = @inbounds getindex(A, I...)
×
1362

1363
struct CanonicalIndexError <: Exception
1364
    func::String
1365
    type::Any
UNCOV
1366
    CanonicalIndexError(func::String, @nospecialize(type)) = new(func, type)
×
1367
end
1368

UNCOV
1369
error_if_canonical_getindex(::IndexLinear, A::AbstractArray, ::Int) =
×
1370
    throw(CanonicalIndexError("getindex", typeof(A)))
UNCOV
1371
error_if_canonical_getindex(::IndexCartesian, A::AbstractArray{T,N}, ::Vararg{Int,N}) where {T,N} =
×
1372
    throw(CanonicalIndexError("getindex", typeof(A)))
1373
error_if_canonical_getindex(::IndexStyle, ::AbstractArray, ::Any...) = nothing
23,634,957✔
1374

1375
## Internal definitions
UNCOV
1376
_getindex(::IndexStyle, A::AbstractArray, I...) =
×
1377
    error("getindex for $(typeof(A)) with types $(typeof(I)) is not supported")
1378

1379
## IndexLinear Scalar indexing: canonical method is one Int
1380
_getindex(::IndexLinear, A::AbstractVector, i::Int) = (@_propagate_inbounds_meta; getindex(A, i))  # ambiguity resolution in case packages specialize this (to be avoided if at all possible, but see Interpolations.jl)
23,097,475✔
UNCOV
1381
_getindex(::IndexLinear, A::AbstractArray, i::Int) = (@_propagate_inbounds_meta; getindex(A, i))
×
1382
function _getindex(::IndexLinear, A::AbstractArray, I::Vararg{Int,M}) where M
14,510✔
1383
    @inline
14,510✔
1384
    @boundscheck checkbounds(A, I...) # generally _to_linear_index requires bounds checking
720,949✔
1385
    @inbounds r = getindex(A, _to_linear_index(A, I...))
720,949✔
1386
    r
14,510✔
1387
end
1388
_to_linear_index(A::AbstractArray, i::Integer) = i
×
1389
_to_linear_index(A::AbstractVector, i::Integer, I::Integer...) = i
×
UNCOV
1390
_to_linear_index(A::AbstractArray) = first(LinearIndices(A))
×
1391
_to_linear_index(A::AbstractArray, I::Integer...) = (@inline; _sub2ind(A, I...))
642,637✔
1392

1393
## IndexCartesian Scalar indexing: Canonical method is full dimensionality of Ints
1394
function _getindex(::IndexCartesian, A::AbstractArray, I::Vararg{Int,M}) where M
×
1395
    @inline
×
1396
    @boundscheck checkbounds(A, I...) # generally _to_subscript_indices requires bounds checking
×
1397
    @inbounds r = getindex(A, _to_subscript_indices(A, I...)...)
×
UNCOV
1398
    r
×
1399
end
1400
function _getindex(::IndexCartesian, A::AbstractArray{T,N}, I::Vararg{Int, N}) where {T,N}
×
1401
    @_propagate_inbounds_meta
×
UNCOV
1402
    getindex(A, I...)
×
1403
end
1404
_to_subscript_indices(A::AbstractArray, i::Integer) = (@inline; _unsafe_ind2sub(A, i))
×
1405
_to_subscript_indices(A::AbstractArray{T,N}) where {T,N} = (@inline; fill_to_length((), 1, Val(N)))
×
1406
_to_subscript_indices(A::AbstractArray{T,0}) where {T} = ()
×
1407
_to_subscript_indices(A::AbstractArray{T,0}, i::Integer) where {T} = ()
×
1408
_to_subscript_indices(A::AbstractArray{T,0}, I::Integer...) where {T} = ()
×
1409
function _to_subscript_indices(A::AbstractArray{T,N}, I::Integer...) where {T,N}
×
1410
    @inline
×
1411
    J, Jrem = IteratorsMD.split(I, Val(N))
×
UNCOV
1412
    _to_subscript_indices(A, J, Jrem)
×
1413
end
UNCOV
1414
_to_subscript_indices(A::AbstractArray, J::Tuple, Jrem::Tuple{}) =
×
1415
    __to_subscript_indices(A, axes(A), J, Jrem)
UNCOV
1416
function __to_subscript_indices(A::AbstractArray,
×
1417
        ::Tuple{AbstractUnitRange,Vararg{AbstractUnitRange}}, J::Tuple, Jrem::Tuple{})
1418
    @inline
×
UNCOV
1419
    (J..., map(first, tail(_remaining_size(J, axes(A))))...)
×
1420
end
1421
_to_subscript_indices(A, J::Tuple, Jrem::Tuple) = J # already bounds-checked, safe to drop
×
1422
_to_subscript_indices(A::AbstractArray{T,N}, I::Vararg{Int,N}) where {T,N} = I
×
1423
_remaining_size(::Tuple{Any}, t::Tuple) = t
×
1424
_remaining_size(h::Tuple, t::Tuple) = (@inline; _remaining_size(tail(h), tail(t)))
×
1425
_unsafe_ind2sub(::Tuple{}, i) = () # _ind2sub may throw(BoundsError()) in this case
×
UNCOV
1426
_unsafe_ind2sub(sz, i) = (@inline; _ind2sub(sz, i))
×
1427

1428
## Setindex! is defined similarly. We first dispatch to an internal _setindex!
1429
# function that allows dispatch on array storage
1430

1431
"""
1432
    setindex!(A, X, inds...)
1433
    A[inds...] = X
1434

1435
Store values from array `X` within some subset of `A` as specified by `inds`.
1436
The syntax `A[inds...] = X` is equivalent to `(setindex!(A, X, inds...); X)`.
1437

1438
$(_DOCS_ALIASING_WARNING)
1439

1440
# Examples
1441
```jldoctest
1442
julia> A = zeros(2,2);
1443

1444
julia> setindex!(A, [10, 20], [1, 2]);
1445

1446
julia> A[[3, 4]] = [30, 40];
1447

1448
julia> A
1449
2×2 Matrix{Float64}:
1450
 10.0  30.0
1451
 20.0  40.0
1452
```
1453
"""
1454
function setindex!(A::AbstractArray, v, I...)
6,570✔
1455
    @_propagate_inbounds_meta
532,967✔
1456
    error_if_canonical_setindex(IndexStyle(A), A, I...)
532,967✔
1457
    _setindex!(IndexStyle(A), A, v, to_indices(A, I)...)
712,176✔
1458
end
1459
function unsafe_setindex!(A::AbstractArray, v, I...)
×
1460
    @inline
×
1461
    @inbounds r = setindex!(A, v, I...)
×
UNCOV
1462
    r
×
1463
end
1464

UNCOV
1465
error_if_canonical_setindex(::IndexLinear, A::AbstractArray, ::Int) =
×
1466
    throw(CanonicalIndexError("setindex!", typeof(A)))
UNCOV
1467
error_if_canonical_setindex(::IndexCartesian, A::AbstractArray{T,N}, ::Vararg{Int,N}) where {T,N} =
×
1468
    throw(CanonicalIndexError("setindex!", typeof(A)))
1469
error_if_canonical_setindex(::IndexStyle, ::AbstractArray, ::Any...) = nothing
526,397✔
1470

1471
## Internal definitions
UNCOV
1472
_setindex!(::IndexStyle, A::AbstractArray, v, I...) =
×
1473
    error("setindex! for $(typeof(A)) with types $(typeof(I)) is not supported")
1474

1475
## IndexLinear Scalar indexing
1476
_setindex!(::IndexLinear, A::AbstractArray, v, i::Int) = (@_propagate_inbounds_meta; setindex!(A, v, i))
596,378✔
1477
function _setindex!(::IndexLinear, A::AbstractArray, v, I::Vararg{Int,M}) where M
UNCOV
1478
    @inline
×
1479
    @boundscheck checkbounds(A, I...)
115,798✔
1480
    @inbounds r = setindex!(A, v, _to_linear_index(A, I...))
115,798✔
UNCOV
1481
    r
×
1482
end
1483

1484
# IndexCartesian Scalar indexing
1485
function _setindex!(::IndexCartesian, A::AbstractArray{T,N}, v, I::Vararg{Int, N}) where {T,N}
×
1486
    @_propagate_inbounds_meta
×
UNCOV
1487
    setindex!(A, v, I...)
×
1488
end
1489
function _setindex!(::IndexCartesian, A::AbstractArray, v, I::Vararg{Int,M}) where M
×
1490
    @inline
×
1491
    @boundscheck checkbounds(A, I...)
×
1492
    @inbounds r = setindex!(A, v, _to_subscript_indices(A, I...)...)
×
UNCOV
1493
    r
×
1494
end
1495

UNCOV
1496
_unsetindex!(A::AbstractArray, i::Integer) = _unsetindex!(A, to_index(i))
×
1497

1498
"""
1499
    parent(A)
1500

1501
Return the underlying parent object of the view. This parent of objects of types `SubArray`, `SubString`, `ReshapedArray`
1502
or `LinearAlgebra.Transpose` is what was passed as an argument to `view`, `reshape`, `transpose`, etc.
1503
during object creation. If the input is not a wrapped object, return the input itself. If the input is
1504
wrapped multiple times, only the outermost wrapper will be removed.
1505

1506
# Examples
1507
```jldoctest
1508
julia> A = [1 2; 3 4]
1509
2×2 Matrix{Int64}:
1510
 1  2
1511
 3  4
1512

1513
julia> V = view(A, 1:2, :)
1514
2×2 view(::Matrix{Int64}, 1:2, :) with eltype Int64:
1515
 1  2
1516
 3  4
1517

1518
julia> parent(V)
1519
2×2 Matrix{Int64}:
1520
 1  2
1521
 3  4
1522
```
1523
"""
1524
function parent end
1525

UNCOV
1526
parent(a::AbstractArray) = a
×
1527

1528
## rudimentary aliasing detection ##
1529
"""
1530
    Base.unalias(dest, A)
1531

1532
Return either `A` or a copy of `A` in a rough effort to prevent modifications to `dest` from
1533
affecting the returned object. No guarantees are provided.
1534

1535
Custom arrays that wrap or use fields containing arrays that might alias against other
1536
external objects should provide a [`Base.dataids`](@ref) implementation.
1537

1538
This function must return an object of exactly the same type as `A` for performance and type
1539
stability. Mutable custom arrays for which [`copy(A)`](@ref) is not `typeof(A)` should
1540
provide a [`Base.unaliascopy`](@ref) implementation.
1541

1542
See also [`Base.mightalias`](@ref).
1543
"""
1544
unalias(dest, A::AbstractArray) = mightalias(dest, A) ? unaliascopy(A) : A
387,084✔
1545
unalias(dest, A::AbstractRange) = A
24,593✔
1546
unalias(dest, A) = A
2✔
1547

1548
"""
1549
    Base.unaliascopy(A)
1550

1551
Make a preventative copy of `A` in an operation where `A` [`Base.mightalias`](@ref) against
1552
another array in order to preserve consistent semantics as that other array is mutated.
1553

1554
This must return an object of the same type as `A` to preserve optimal performance in the
1555
much more common case where aliasing does not occur. By default,
1556
`unaliascopy(A::AbstractArray)` will attempt to use [`copy(A)`](@ref), but in cases where
1557
`copy(A)` is not a `typeof(A)`, then the array should provide a custom implementation of
1558
`Base.unaliascopy(A)`.
1559
"""
1560
unaliascopy(A::Array) = copy(A)
×
1561
unaliascopy(A::AbstractArray)::typeof(A) = (@noinline; _unaliascopy(A, copy(A)))
×
1562
_unaliascopy(A::T, C::T) where {T} = C
×
1563
function _unaliascopy(A, C)
×
1564
    Aw = typename(typeof(A)).wrapper
×
UNCOV
1565
    throw(ArgumentError(LazyString("an array of type `", Aw, "` shares memory with another argument ",
×
1566
    "and must make a preventative copy of itself in order to maintain consistent semantics, ",
1567
    "but `copy(::", typeof(A), ")` returns a new array of type `", typeof(C), "`.\n",
1568
    """To fix, implement:
1569
        `Base.unaliascopy(A::""", Aw, ")::typeof(A)`")))
1570
end
UNCOV
1571
unaliascopy(A) = A
×
1572

1573
"""
1574
    Base.mightalias(A::AbstractArray, B::AbstractArray)
1575

1576
Perform a conservative test to check if arrays `A` and `B` might share the same memory.
1577

1578
By default, this simply checks if either of the arrays reference the same memory
1579
regions, as identified by their [`Base.dataids`](@ref).
1580
"""
1581
mightalias(A::AbstractArray, B::AbstractArray) = !isbits(A) && !isbits(B) && !isempty(A) && !isempty(B) && !_isdisjoint(dataids(A), dataids(B))
387,084✔
UNCOV
1582
mightalias(x, y) = false
×
1583

1584
_isdisjoint(as::Tuple{}, bs::Tuple{}) = true
×
1585
_isdisjoint(as::Tuple{}, bs::Tuple{UInt}) = true
×
1586
_isdisjoint(as::Tuple{}, bs::Tuple) = true
×
UNCOV
1587
_isdisjoint(as::Tuple{UInt}, bs::Tuple{}) = true
×
1588
_isdisjoint(as::Tuple{UInt}, bs::Tuple{UInt}) = as[1] != bs[1]
387,009✔
1589
_isdisjoint(as::Tuple{UInt}, bs::Tuple) = !(as[1] in bs)
×
1590
_isdisjoint(as::Tuple, bs::Tuple{}) = true
×
1591
_isdisjoint(as::Tuple, bs::Tuple{UInt}) = !(bs[1] in as)
×
UNCOV
1592
_isdisjoint(as::Tuple, bs::Tuple) = !(as[1] in bs) && _isdisjoint(tail(as), bs)
×
1593

1594
"""
1595
    Base.dataids(A::AbstractArray)
1596

1597
Return a tuple of `UInt`s that represent the mutable data segments of an array.
1598

1599
Custom arrays that would like to opt-in to aliasing detection of their component
1600
parts can specialize this method to return the concatenation of the `dataids` of
1601
their component parts.  A typical definition for an array that wraps a parent is
1602
`Base.dataids(C::CustomArray) = dataids(C.parent)`.
1603
"""
1604
dataids(A::AbstractArray) = (UInt(objectid(A)),)
44✔
1605
dataids(A::Memory) = (UInt(A.ptr),)
773,974✔
1606
dataids(A::Array) = dataids(A.ref.mem)
773,765✔
1607
dataids(::AbstractRange) = ()
×
UNCOV
1608
dataids(x) = ()
×
1609

1610
## get (getindex with a default value) ##
1611

1612
RangeVecIntList{A<:AbstractVector{Int}} = Union{Tuple{Vararg{Union{AbstractRange, AbstractVector{Int}}}},
1613
    AbstractVector{UnitRange{Int}}, AbstractVector{AbstractRange{Int}}, AbstractVector{A}}
1614

1615
get(A::AbstractArray, i::Integer, default) = checkbounds(Bool, A, i) ? A[i] : default
4✔
1616
get(A::AbstractArray, I::Tuple{}, default) = checkbounds(Bool, A) ? A[] : default
×
1617
get(A::AbstractArray, I::Dims, default) = checkbounds(Bool, A, I...) ? A[I...] : default
×
1618
get(f::Callable, A::AbstractArray, i::Integer) = checkbounds(Bool, A, i) ? A[i] : f()
×
1619
get(f::Callable, A::AbstractArray, I::Tuple{}) = checkbounds(Bool, A) ? A[] : f()
×
UNCOV
1620
get(f::Callable, A::AbstractArray, I::Dims) = checkbounds(Bool, A, I...) ? A[I...] : f()
×
1621

UNCOV
1622
function get!(X::AbstractVector{T}, A::AbstractVector, I::Union{AbstractRange,AbstractVector{Int}}, default::T) where T
×
1623
    # 1d is not linear indexing
1624
    ind = findall(in(axes1(A)), I)
×
1625
    X[ind] = A[I[ind]]
×
1626
    Xind = axes1(X)
×
1627
    X[first(Xind):first(ind)-1] = default
×
1628
    X[last(ind)+1:last(Xind)] = default
×
UNCOV
1629
    X
×
1630
end
UNCOV
1631
function get!(X::AbstractArray{T}, A::AbstractArray, I::Union{AbstractRange,AbstractVector{Int}}, default::T) where T
×
1632
    # Linear indexing
1633
    ind = findall(in(1:length(A)), I)
×
1634
    X[ind] = A[I[ind]]
×
1635
    fill!(view(X, 1:first(ind)-1), default)
×
1636
    fill!(view(X, last(ind)+1:length(X)), default)
×
UNCOV
1637
    X
×
1638
end
1639

UNCOV
1640
get(A::AbstractArray, I::AbstractRange, default) = get!(similar(A, typeof(default), index_shape(I)), A, I, default)
×
1641

1642
function get!(X::AbstractArray{T}, A::AbstractArray, I::RangeVecIntList, default::T) where T
×
1643
    fill!(X, default)
×
1644
    dst, src = indcopy(size(A), I)
×
1645
    X[dst...] = A[src...]
×
UNCOV
1646
    X
×
1647
end
1648

UNCOV
1649
get(A::AbstractArray, I::RangeVecIntList, default) =
×
1650
    get!(similar(A, typeof(default), index_shape(I...)), A, I, default)
1651

1652
## structured matrix methods ##
1653
replace_in_print_matrix(A::AbstractMatrix,i::Integer,j::Integer,s::AbstractString) = s
×
UNCOV
1654
replace_in_print_matrix(A::AbstractVector,i::Integer,j::Integer,s::AbstractString) = s
×
1655

1656
## Concatenation ##
1657
eltypeof(x) = typeof(x)
1✔
1658
eltypeof(x::AbstractArray) = eltype(x)
3✔
1659

1660
promote_eltypeof() = error()
×
UNCOV
1661
promote_eltypeof(v1) = eltypeof(v1)
×
1662
promote_eltypeof(v1, v2) = promote_type(eltypeof(v1), eltypeof(v2))
2✔
1663
promote_eltypeof(v1, v2, vs...) = (@inline; afoldl(((::Type{T}, y) where {T}) -> promote_type(T, eltypeof(y)), promote_eltypeof(v1, v2), vs...))
×
1664
promote_eltypeof(v1::T, vs::T...) where {T} = eltypeof(v1)
×
UNCOV
1665
promote_eltypeof(v1::AbstractArray{T}, vs::AbstractArray{T}...) where {T} = T
×
1666

1667
promote_eltype() = error()
×
1668
promote_eltype(v1) = eltype(v1)
×
1669
promote_eltype(v1, v2) = promote_type(eltype(v1), eltype(v2))
×
UNCOV
1670
promote_eltype(v1, v2, vs...) = (@inline; afoldl(((::Type{T}, y) where {T}) -> promote_type(T, eltype(y)), promote_eltype(v1, v2), vs...))
×
1671
promote_eltype(v1::T, vs::T...) where {T} = eltype(T)
83✔
1672
promote_eltype(v1::AbstractArray{T}, vs::AbstractArray{T}...) where {T} = T
6✔
1673

1674
#TODO: ERROR CHECK
UNCOV
1675
_cat(catdim::Int) = Vector{Any}()
×
1676

1677
typed_vcat(::Type{T}) where {T} = Vector{T}()
×
UNCOV
1678
typed_hcat(::Type{T}) where {T} = Vector{T}()
×
1679

1680
## cat: special cases
1681
vcat(X::T...) where {T}         = T[ X[i] for i=eachindex(X) ]
×
1682
vcat(X::T...) where {T<:Number} = T[ X[i] for i=eachindex(X) ]
×
1683
hcat(X::T...) where {T}         = T[ X[j] for i=1:1, j=eachindex(X) ]
×
UNCOV
1684
hcat(X::T...) where {T<:Number} = T[ X[j] for i=1:1, j=eachindex(X) ]
×
1685

1686
vcat(X::Number...) = hvcat_fill!(Vector{promote_typeof(X...)}(undef, length(X)), X)
×
1687
hcat(X::Number...) = hvcat_fill!(Matrix{promote_typeof(X...)}(undef, 1,length(X)), X)
×
1688
typed_vcat(::Type{T}, X::Number...) where {T} = hvcat_fill!(Vector{T}(undef, length(X)), X)
×
UNCOV
1689
typed_hcat(::Type{T}, X::Number...) where {T} = hvcat_fill!(Matrix{T}(undef, 1,length(X)), X)
×
1690

1691
vcat(V::AbstractVector...) = typed_vcat(promote_eltype(V...), V...)
×
UNCOV
1692
vcat(V::AbstractVector{T}...) where {T} = typed_vcat(T, V...)
×
1693

1694
# FIXME: this alias would better be Union{AbstractVector{T}, Tuple{Vararg{T}}}
1695
# and method signatures should do AbstractVecOrTuple{<:T} when they want covariance,
1696
# but that solution currently fails (see #27188 and #27224)
1697
AbstractVecOrTuple{T} = Union{AbstractVector{<:T}, Tuple{Vararg{T}}}
1698

1699
_typed_vcat_similar(V, ::Type{T}, n) where T = similar(V[1], T, n)
3✔
1700
_typed_vcat(::Type{T}, V::AbstractVecOrTuple{AbstractVector}) where T =
5✔
1701
    _typed_vcat!(_typed_vcat_similar(V, T, sum(map(length, V))), V)
1702

1703
function _typed_vcat!(a::AbstractVector{T}, V::AbstractVecOrTuple{AbstractVector}) where T
1704
    pos = 1
3✔
1705
    for k=1:Int(length(V))::Int
3✔
1706
        Vk = V[k]
83✔
1707
        p1 = pos + Int(length(Vk))::Int - 1
83✔
1708
        a[pos:p1] = Vk
103✔
1709
        pos = p1+1
83✔
1710
    end
163✔
1711
    a
3✔
1712
end
1713

UNCOV
1714
typed_hcat(::Type{T}, A::AbstractVecOrMat...) where {T} = _typed_hcat(T, A)
×
1715

1716
# Catch indexing errors like v[i +1] (instead of v[i+1] or v[i + 1]), where indexing is
1717
# interpreted as a typed concatenation. (issue #49676)
UNCOV
1718
typed_hcat(::AbstractArray, other...) = throw(ArgumentError("It is unclear whether you \
×
1719
    intend to perform an indexing operation or typed concatenation. If you intend to \
1720
    perform indexing (v[1 + 2]), adjust spacing or insert missing operator to clarify. \
1721
    If you intend to perform typed concatenation (T[1 2]), ensure that T is a type."))
1722

1723

1724
hcat(A::AbstractVecOrMat...) = typed_hcat(promote_eltype(A...), A...)
×
UNCOV
1725
hcat(A::AbstractVecOrMat{T}...) where {T} = typed_hcat(T, A...)
×
1726

1727
function _typed_hcat(::Type{T}, A::AbstractVecOrTuple{AbstractVecOrMat}) where T
×
1728
    nargs = length(A)
×
1729
    nrows = size(A[1], 1)
×
1730
    ncols = 0
×
1731
    dense = true
×
1732
    for j = 1:nargs
×
1733
        Aj = A[j]
×
1734
        if size(Aj, 1) != nrows
×
UNCOV
1735
            throw(DimensionMismatch("number of rows of each array must match (got $(map(x->size(x,1), A)))"))
×
1736
        end
1737
        dense &= isa(Aj,Array)
×
1738
        nd = ndims(Aj)
×
1739
        ncols += (nd==2 ? size(Aj,2) : 1)
×
1740
    end
×
1741
    B = similar(A[1], T, nrows, ncols)
×
1742
    pos = 1
×
1743
    if dense
×
1744
        for k=1:nargs
×
1745
            Ak = A[k]
×
1746
            n = length(Ak)
×
1747
            copyto!(B, pos, Ak, 1, n)
×
1748
            pos += n
×
UNCOV
1749
        end
×
1750
    else
1751
        for k=1:nargs
×
1752
            Ak = A[k]
×
1753
            p1 = pos+(isa(Ak,AbstractMatrix) ? size(Ak, 2) : 1)-1
×
1754
            B[:, pos:p1] = Ak
×
1755
            pos = p1+1
×
UNCOV
1756
        end
×
1757
    end
UNCOV
1758
    return B
×
1759
end
1760

1761
vcat(A::AbstractVecOrMat...) = typed_vcat(promote_eltype(A...), A...)
×
UNCOV
1762
vcat(A::AbstractVecOrMat{T}...) where {T} = typed_vcat(T, A...)
×
1763

1764
function _typed_vcat(::Type{T}, A::AbstractVecOrTuple{AbstractVecOrMat}) where T
×
1765
    nargs = length(A)
×
1766
    nrows = sum(a->size(a, 1), A)::Int
×
1767
    ncols = size(A[1], 2)
×
1768
    for j = 2:nargs
×
1769
        if size(A[j], 2) != ncols
×
UNCOV
1770
            throw(DimensionMismatch("number of columns of each array must match (got $(map(x->size(x,2), A)))"))
×
1771
        end
1772
    end
×
1773
    B = similar(A[1], T, nrows, ncols)
×
1774
    pos = 1
×
1775
    for k=1:nargs
×
1776
        Ak = A[k]
×
1777
        p1 = pos+size(Ak,1)::Int-1
×
1778
        B[pos:p1, :] = Ak
×
1779
        pos = p1+1
×
1780
    end
×
UNCOV
1781
    return B
×
1782
end
1783

1784
typed_vcat(::Type{T}, A::AbstractVecOrMat...) where {T} = _typed_vcat(T, A)
4✔
1785

1786
reduce(::typeof(vcat), A::AbstractVector{<:AbstractVecOrMat}) =
1✔
1787
    _typed_vcat(mapreduce(eltype, promote_type, A), A)
1788

UNCOV
1789
reduce(::typeof(hcat), A::AbstractVector{<:AbstractVecOrMat}) =
×
1790
    _typed_hcat(mapreduce(eltype, promote_type, A), A)
1791

1792
## cat: general case
1793

1794
# helper functions
1795
cat_size(A) = (1,)
1✔
1796
cat_size(A::AbstractArray) = size(A)
3✔
UNCOV
1797
cat_size(A, d) = 1
×
1798
cat_size(A::AbstractArray, d) = size(A, d)
3✔
1799

1800
cat_length(::Any) = 1
×
UNCOV
1801
cat_length(a::AbstractArray) = length(a)
×
1802

1803
cat_ndims(a) = 0
×
UNCOV
1804
cat_ndims(a::AbstractArray) = ndims(a)
×
1805

1806
cat_indices(A, d) = OneTo(1)
1✔
1807
cat_indices(A::AbstractArray, d) = axes(A, d)
3✔
1808

1809
cat_similar(A, ::Type{T}, shape::Tuple) where T = Array{T}(undef, shape)
1✔
UNCOV
1810
cat_similar(A, ::Type{T}, shape::Vector) where T = Array{T}(undef, shape...)
×
1811
cat_similar(A::Array, ::Type{T}, shape::Tuple) where T = Array{T}(undef, shape)
1✔
1812
cat_similar(A::Array, ::Type{T}, shape::Vector) where T = Array{T}(undef, shape...)
×
1813
cat_similar(A::AbstractArray, T::Type, shape::Tuple) = similar(A, T, shape)
×
UNCOV
1814
cat_similar(A::AbstractArray, T::Type, shape::Vector) = similar(A, T, shape...)
×
1815

1816
# These are for backwards compatibility (even though internal)
1817
cat_shape(dims, shape::Tuple{Vararg{Int}}) = shape
×
1818
function cat_shape(dims, shapes::Tuple)
×
1819
    out_shape = ()
×
1820
    for s in shapes
×
1821
        out_shape = _cshp(1, dims, out_shape, s)
×
1822
    end
×
UNCOV
1823
    return out_shape
×
1824
end
1825
# The new way to compute the shape (more inferable than combining cat_size & cat_shape, due to Varargs + issue#36454)
UNCOV
1826
cat_size_shape(dims) = ntuple(zero, Val(length(dims)))
×
1827
@inline cat_size_shape(dims, X, tail...) = _cat_size_shape(dims, _cshp(1, dims, (), cat_size(X)), tail...)
2✔
UNCOV
1828
_cat_size_shape(dims, shape) = shape
×
1829
@inline _cat_size_shape(dims, shape, X, tail...) = _cat_size_shape(dims, _cshp(1, dims, shape, cat_size(X)), tail...)
2✔
1830

1831
_cshp(ndim::Int, ::Tuple{}, ::Tuple{}, ::Tuple{}) = ()
×
1832
_cshp(ndim::Int, ::Tuple{}, ::Tuple{}, nshape) = nshape
×
1833
_cshp(ndim::Int, dims, ::Tuple{}, ::Tuple{}) = ntuple(Returns(1), Val(length(dims)))
×
UNCOV
1834
@inline _cshp(ndim::Int, dims, shape, ::Tuple{}) =
×
1835
    (shape[1] + dims[1], _cshp(ndim + 1, tail(dims), tail(shape), ())...)
1836
@inline _cshp(ndim::Int, dims, ::Tuple{}, nshape) =
2✔
1837
    (nshape[1], _cshp(ndim + 1, tail(dims), (), tail(nshape))...)
1838
@inline function _cshp(ndim::Int, ::Tuple{}, shape, ::Tuple{})
×
1839
    _cs(ndim, shape[1], 1)
×
UNCOV
1840
    (1, _cshp(ndim + 1, (), tail(shape), ())...)
×
1841
end
1842
@inline function _cshp(ndim::Int, ::Tuple{}, shape, nshape)
×
1843
    next = _cs(ndim, shape[1], nshape[1])
×
UNCOV
1844
    (next, _cshp(ndim + 1, (), tail(shape), tail(nshape))...)
×
1845
end
1846
@inline function _cshp(ndim::Int, dims, shape, nshape)
1847
    a = shape[1]
2✔
1848
    b = nshape[1]
2✔
1849
    next = dims[1] ? a + b : _cs(ndim, a, b)
2✔
1850
    (next, _cshp(ndim + 1, tail(dims), tail(shape), tail(nshape))...)
2✔
1851
end
1852

UNCOV
1853
_cs(d, a, b) = (a == b ? a : throw(DimensionMismatch(
×
1854
    "mismatch in dimension $d (expected $a got $b)")))
1855

1856
dims2cat(::Val{dims}) where dims = dims2cat(dims)
×
1857
function dims2cat(dims)
×
1858
    if any(≤(0), dims)
×
UNCOV
1859
        throw(ArgumentError("All cat dimensions must be positive integers, but got $dims"))
×
1860
    end
UNCOV
1861
    ntuple(in(dims), maximum(dims))
×
1862
end
1863

1864
_cat(dims, X...) = _cat_t(dims, promote_eltypeof(X...), X...)
3✔
1865

1866
@inline function _cat_t(dims, ::Type{T}, X...) where {T}
1867
    catdims = dims2cat(dims)
2✔
1868
    shape = cat_size_shape(catdims, X...)
2✔
1869
    A = cat_similar(X[1], T, shape)
2✔
1870
    if count(!iszero, catdims)::Int > 1
2✔
UNCOV
1871
        fill!(A, zero(T))
×
1872
    end
1873
    return __cat(A, shape, catdims, X...)
3✔
1874
end
1875
# this version of `cat_t` is not very kind for inference and so its usage should be avoided,
1876
# nevertheless it is here just for compat after https://github.com/JuliaLang/julia/pull/45028
UNCOV
1877
@inline cat_t(::Type{T}, X...; dims) where {T} = _cat_t(dims, T, X...)
×
1878

1879
# Why isn't this called `__cat!`?
1880
__cat(A, shape, catdims, X...) = __cat_offset!(A, shape, catdims, ntuple(zero, length(shape)), X...)
3✔
1881

1882
function __cat_offset!(A, shape, catdims, offsets, x, X...)
1✔
1883
    # splitting the "work" on x from X... may reduce latency (fewer costly specializations)
1884
    newoffsets = __cat_offset1!(A, shape, catdims, offsets, x)
5✔
1885
    return __cat_offset!(A, shape, catdims, newoffsets, X...)
5✔
1886
end
1887
__cat_offset!(A, shape, catdims, offsets) = A
2✔
1888

1889
function __cat_offset1!(A, shape, catdims, offsets, x)
1890
    inds = ntuple(length(offsets)) do i
5✔
1891
        (i <= length(catdims) && catdims[i]) ? offsets[i] .+ cat_indices(x, i) : 1:shape[i]
5✔
1892
    end
1893
    _copy_or_fill!(A, inds, x)
6✔
1894
    newoffsets = ntuple(length(offsets)) do i
4✔
1895
        (i <= length(catdims) && catdims[i]) ? offsets[i] + cat_size(x, i) : offsets[i]
4✔
1896
    end
1897
    return newoffsets
4✔
1898
end
1899

1900
_copy_or_fill!(A, inds, x) = fill!(view(A, inds...), x)
1✔
1901
_copy_or_fill!(A, inds, x::AbstractArray) = (A[inds...] = x)
5✔
1902

1903
"""
1904
    vcat(A...)
1905

1906
Concatenate arrays or numbers vertically. Equivalent to [`cat`](@ref)`(A...; dims=1)`,
1907
and to the syntax `[a; b; c]`.
1908

1909
To concatenate a large vector of arrays, `reduce(vcat, A)` calls an efficient method
1910
when `A isa AbstractVector{<:AbstractVecOrMat}`, rather than working pairwise.
1911

1912
See also [`hcat`](@ref), [`Iterators.flatten`](@ref), [`stack`](@ref).
1913

1914
# Examples
1915
```jldoctest
1916
julia> v = vcat([1,2], [3,4])
1917
4-element Vector{Int64}:
1918
 1
1919
 2
1920
 3
1921
 4
1922

1923
julia> v == vcat(1, 2, [3,4])  # accepts numbers
1924
true
1925

1926
julia> v == [1; 2; [3,4]]  # syntax for the same operation
1927
true
1928

1929
julia> summary(ComplexF64[1; 2; [3,4]])  # syntax for supplying the element type
1930
"4-element Vector{ComplexF64}"
1931

1932
julia> vcat(range(1, 2, length=3))  # collects lazy ranges
1933
3-element Vector{Float64}:
1934
 1.0
1935
 1.5
1936
 2.0
1937

1938
julia> two = ([10, 20, 30]', Float64[4 5 6; 7 8 9])  # row vector and a matrix
1939
(adjoint([10, 20, 30]), [4.0 5.0 6.0; 7.0 8.0 9.0])
1940

1941
julia> vcat(two...)
1942
3×3 Matrix{Float64}:
1943
 10.0  20.0  30.0
1944
  4.0   5.0   6.0
1945
  7.0   8.0   9.0
1946

1947
julia> vs = [[1, 2], [3, 4], [5, 6]];
1948

1949
julia> reduce(vcat, vs)  # more efficient than vcat(vs...)
1950
6-element Vector{Int64}:
1951
 1
1952
 2
1953
 3
1954
 4
1955
 5
1956
 6
1957

1958
julia> ans == collect(Iterators.flatten(vs))
1959
true
1960
```
1961
"""
UNCOV
1962
vcat(X...) = cat(X...; dims=Val(1))
×
1963
"""
1964
    hcat(A...)
1965

1966
Concatenate arrays or numbers horizontally. Equivalent to [`cat`](@ref)`(A...; dims=2)`,
1967
and to the syntax `[a b c]` or `[a;; b;; c]`.
1968

1969
For a large vector of arrays, `reduce(hcat, A)` calls an efficient method
1970
when `A isa AbstractVector{<:AbstractVecOrMat}`.
1971
For a vector of vectors, this can also be written [`stack`](@ref)`(A)`.
1972

1973
See also [`vcat`](@ref), [`hvcat`](@ref).
1974

1975
# Examples
1976
```jldoctest
1977
julia> hcat([1,2], [3,4], [5,6])
1978
2×3 Matrix{Int64}:
1979
 1  3  5
1980
 2  4  6
1981

1982
julia> hcat(1, 2, [30 40], [5, 6, 7]')  # accepts numbers
1983
1×7 Matrix{Int64}:
1984
 1  2  30  40  5  6  7
1985

1986
julia> ans == [1 2 [30 40] [5, 6, 7]']  # syntax for the same operation
1987
true
1988

1989
julia> Float32[1 2 [30 40] [5, 6, 7]']  # syntax for supplying the eltype
1990
1×7 Matrix{Float32}:
1991
 1.0  2.0  30.0  40.0  5.0  6.0  7.0
1992

1993
julia> ms = [zeros(2,2), [1 2; 3 4], [50 60; 70 80]];
1994

1995
julia> reduce(hcat, ms)  # more efficient than hcat(ms...)
1996
2×6 Matrix{Float64}:
1997
 0.0  0.0  1.0  2.0  50.0  60.0
1998
 0.0  0.0  3.0  4.0  70.0  80.0
1999

2000
julia> stack(ms) |> summary  # disagrees on a vector of matrices
2001
"2×2×3 Array{Float64, 3}"
2002

2003
julia> hcat(Int[], Int[], Int[])  # empty vectors, each of size (0,)
2004
0×3 Matrix{Int64}
2005

2006
julia> hcat([1.1, 9.9], Matrix(undef, 2, 0))  # hcat with empty 2×0 Matrix
2007
2×1 Matrix{Any}:
2008
 1.1
2009
 9.9
2010
```
2011
"""
UNCOV
2012
hcat(X...) = cat(X...; dims=Val(2))
×
2013

2014
typed_vcat(::Type{T}, X...) where T = _cat_t(Val(1), T, X...)
×
UNCOV
2015
typed_hcat(::Type{T}, X...) where T = _cat_t(Val(2), T, X...)
×
2016

2017
"""
2018
    cat(A...; dims)
2019

2020
Concatenate the input arrays along the dimensions specified in `dims`.
2021

2022
Along a dimension `d in dims`, the size of the output array is `sum(size(a,d) for
2023
a in A)`.
2024
Along other dimensions, all input arrays should have the same size,
2025
which will also be the size of the output array along those dimensions.
2026

2027
If `dims` is a single number, the different arrays are tightly packed along that dimension.
2028
If `dims` is an iterable containing several dimensions, the positions along these dimensions
2029
are increased simultaneously for each input array, filling with zero elsewhere.
2030
This allows one to construct block-diagonal matrices as `cat(matrices...; dims=(1,2))`,
2031
and their higher-dimensional analogues.
2032

2033
The special case `dims=1` is [`vcat`](@ref), and `dims=2` is [`hcat`](@ref).
2034
See also [`hvcat`](@ref), [`hvncat`](@ref), [`stack`](@ref), [`repeat`](@ref).
2035

2036
The keyword also accepts `Val(dims)`.
2037

2038
!!! compat "Julia 1.8"
2039
    For multiple dimensions `dims = Val(::Tuple)` was added in Julia 1.8.
2040

2041
# Examples
2042

2043
Concatenate two arrays in different dimensions:
2044
```jldoctest
2045
julia> a = [1 2 3]
2046
1×3 Matrix{Int64}:
2047
 1  2  3
2048

2049
julia> b = [4 5 6]
2050
1×3 Matrix{Int64}:
2051
 4  5  6
2052

2053
julia> cat(a, b; dims=1)
2054
2×3 Matrix{Int64}:
2055
 1  2  3
2056
 4  5  6
2057

2058
julia> cat(a, b; dims=2)
2059
1×6 Matrix{Int64}:
2060
 1  2  3  4  5  6
2061

2062
julia> cat(a, b; dims=(1, 2))
2063
2×6 Matrix{Int64}:
2064
 1  2  3  0  0  0
2065
 0  0  0  4  5  6
2066
```
2067

2068
# Extended Help
2069

2070
Concatenate 3D arrays:
2071
```jldoctest
2072
julia> a = ones(2, 2, 3);
2073

2074
julia> b = ones(2, 2, 4);
2075

2076
julia> c = cat(a, b; dims=3);
2077

2078
julia> size(c) == (2, 2, 7)
2079
true
2080
```
2081

2082
Concatenate arrays of different sizes:
2083
```jldoctest
2084
julia> cat([1 2; 3 4], [pi, pi], fill(10, 2,3,1); dims=2)  # same as hcat
2085
2×6×1 Array{Float64, 3}:
2086
[:, :, 1] =
2087
 1.0  2.0  3.14159  10.0  10.0  10.0
2088
 3.0  4.0  3.14159  10.0  10.0  10.0
2089
```
2090

2091
Construct a block diagonal matrix:
2092
```
2093
julia> cat(true, trues(2,2), trues(4)', dims=(1,2))  # block-diagonal
2094
4×7 Matrix{Bool}:
2095
 1  0  0  0  0  0  0
2096
 0  1  1  0  0  0  0
2097
 0  1  1  0  0  0  0
2098
 0  0  0  1  1  1  1
2099
```
2100

2101
```
2102
julia> cat(1, [2], [3;;]; dims=Val(2))
2103
1×3 Matrix{Int64}:
2104
 1  2  3
2105
```
2106

2107
!!! note
2108
    `cat` does not join two strings, you may want to use `*`.
2109

2110
```jldoctest
2111
julia> a = "aaa";
2112

2113
julia> b = "bbb";
2114

2115
julia> cat(a, b; dims=1)
2116
2-element Vector{String}:
2117
 "aaa"
2118
 "bbb"
2119

2120
julia> cat(a, b; dims=2)
2121
1×2 Matrix{String}:
2122
 "aaa"  "bbb"
2123

2124
julia> a * b
2125
"aaabbb"
2126
```
2127
"""
2128
@inline cat(A...; dims) = _cat(dims, A...)
5✔
2129
# `@constprop :aggressive` allows `catdims` to be propagated as constant improving return type inference
UNCOV
2130
@constprop :aggressive _cat(catdims, A::AbstractArray{T}...) where {T} = _cat_t(catdims, T, A...)
×
2131

2132
# The specializations for 1 and 2 inputs are important
2133
# especially when running with --inline=no, see #11158
2134
vcat(A::AbstractArray) = cat(A; dims=Val(1))
×
2135
vcat(A::AbstractArray, B::AbstractArray) = cat(A, B; dims=Val(1))
×
UNCOV
2136
vcat(A::AbstractArray...) = cat(A...; dims=Val(1))
×
2137
vcat(A::Union{AbstractArray,Number}...) = cat(A...; dims=Val(1))
1✔
2138
hcat(A::AbstractArray) = cat(A; dims=Val(2))
×
2139
hcat(A::AbstractArray, B::AbstractArray) = cat(A, B; dims=Val(2))
×
2140
hcat(A::AbstractArray...) = cat(A...; dims=Val(2))
×
UNCOV
2141
hcat(A::Union{AbstractArray,Number}...) = cat(A...; dims=Val(2))
×
2142

2143
typed_vcat(T::Type, A::AbstractArray) = _cat_t(Val(1), T, A)
×
2144
typed_vcat(T::Type, A::AbstractArray, B::AbstractArray) = _cat_t(Val(1), T, A, B)
×
2145
typed_vcat(T::Type, A::AbstractArray...) = _cat_t(Val(1), T, A...)
×
2146
typed_hcat(T::Type, A::AbstractArray) = _cat_t(Val(2), T, A)
×
2147
typed_hcat(T::Type, A::AbstractArray, B::AbstractArray) = _cat_t(Val(2), T, A, B)
×
UNCOV
2148
typed_hcat(T::Type, A::AbstractArray...) = _cat_t(Val(2), T, A...)
×
2149

2150
# 2d horizontal and vertical concatenation
2151

2152
# these are produced in lowering if splatting occurs inside hvcat
2153
hvcat_rows(rows::Tuple...) = hvcat(map(length, rows), (rows...)...)
×
UNCOV
2154
typed_hvcat_rows(T::Type, rows::Tuple...) = typed_hvcat(T, map(length, rows), (rows...)...)
×
2155

UNCOV
2156
function hvcat(nbc::Int, as...)
×
2157
    # nbc = # of block columns
2158
    n = length(as)
×
UNCOV
2159
    mod(n,nbc) != 0 &&
×
2160
        throw(ArgumentError("number of arrays $n is not a multiple of the requested number of block columns $nbc"))
2161
    nbr = div(n,nbc)
×
UNCOV
2162
    hvcat(ntuple(Returns(nbc), nbr), as...)
×
2163
end
2164

2165
"""
2166
    hvcat(blocks_per_row::Union{Tuple{Vararg{Int}}, Int}, values...)
2167

2168
Horizontal and vertical concatenation in one call. This function is called for block matrix
2169
syntax. The first argument specifies the number of arguments to concatenate in each block
2170
row. If the first argument is a single integer `n`, then all block rows are assumed to have `n`
2171
block columns.
2172

2173
# Examples
2174
```jldoctest
2175
julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
2176
(1, 2, 3, 4, 5, 6)
2177

2178
julia> [a b c; d e f]
2179
2×3 Matrix{Int64}:
2180
 1  2  3
2181
 4  5  6
2182

2183
julia> hvcat((3,3), a,b,c,d,e,f)
2184
2×3 Matrix{Int64}:
2185
 1  2  3
2186
 4  5  6
2187

2188
julia> [a b; c d; e f]
2189
3×2 Matrix{Int64}:
2190
 1  2
2191
 3  4
2192
 5  6
2193

2194
julia> hvcat((2,2,2), a,b,c,d,e,f)
2195
3×2 Matrix{Int64}:
2196
 1  2
2197
 3  4
2198
 5  6
2199
julia> hvcat((2,2,2), a,b,c,d,e,f) == hvcat(2, a,b,c,d,e,f)
2200
true
2201
```
2202
"""
2203
hvcat(rows::Tuple{Vararg{Int}}, xs::AbstractArray...) = typed_hvcat(promote_eltype(xs...), rows, xs...)
×
UNCOV
2204
hvcat(rows::Tuple{Vararg{Int}}, xs::AbstractArray{T}...) where {T} = typed_hvcat(T, rows, xs...)
×
2205

2206
rows_to_dimshape(rows::Tuple{Vararg{Int}}) = all(==(rows[1]), rows) ? (length(rows), rows[1]) : (rows, (sum(rows),))
×
UNCOV
2207
typed_hvcat(::Type{T}, rows::Tuple{Vararg{Int}}, as::AbstractVecOrMat...) where T = typed_hvncat(T, rows_to_dimshape(rows), true, as...)
×
2208

2209
hvcat(rows::Tuple{Vararg{Int}}) = []
×
UNCOV
2210
typed_hvcat(::Type{T}, rows::Tuple{Vararg{Int}}) where {T} = Vector{T}()
×
2211

2212
function hvcat(rows::Tuple{Vararg{Int}}, xs::T...) where T<:Number
×
2213
    nr = length(rows)
×
UNCOV
2214
    nc = rows[1]
×
2215

2216
    a = Matrix{T}(undef, nr, nc)
×
2217
    if length(a) != length(xs)
×
UNCOV
2218
        throw(ArgumentError("argument count does not match specified shape (expected $(length(a)), got $(length(xs)))"))
×
2219
    end
2220
    k = 1
×
2221
    @inbounds for i=1:nr
×
2222
        if nc != rows[i]
×
UNCOV
2223
            throw(DimensionMismatch("row $(i) has mismatched number of columns (expected $nc, got $(rows[i]))"))
×
2224
        end
2225
        for j=1:nc
×
2226
            a[i,j] = xs[k]
×
2227
            k += 1
×
2228
        end
×
2229
    end
×
UNCOV
2230
    a
×
2231
end
2232

2233
function hvcat_fill!(a::Array, xs::Tuple)
×
2234
    nr, nc = size(a,1), size(a,2)
×
2235
    len = length(xs)
×
2236
    if nr*nc != len
×
UNCOV
2237
        throw(ArgumentError("argument count $(len) does not match specified shape $((nr,nc))"))
×
2238
    end
2239
    k = 1
×
2240
    for i=1:nr
×
2241
        @inbounds for j=1:nc
×
2242
            a[i,j] = xs[k]
×
2243
            k += 1
×
2244
        end
×
2245
    end
×
UNCOV
2246
    a
×
2247
end
2248

2249
hvcat(rows::Tuple{Vararg{Int}}, xs::Number...) = typed_hvcat(promote_typeof(xs...), rows, xs...)
×
UNCOV
2250
hvcat(rows::Tuple{Vararg{Int}}, xs...) = typed_hvcat(promote_eltypeof(xs...), rows, xs...)
×
2251
# the following method is needed to provide a more specific one compared to LinearAlgebra/uniformscaling.jl
UNCOV
2252
hvcat(rows::Tuple{Vararg{Int}}, xs::Union{AbstractArray,Number}...) = typed_hvcat(promote_eltypeof(xs...), rows, xs...)
×
2253

2254
function typed_hvcat(::Type{T}, rows::Tuple{Vararg{Int}}, xs::Number...) where T
×
2255
    nr = length(rows)
×
2256
    nc = rows[1]
×
2257
    for i = 2:nr
×
2258
        if nc != rows[i]
×
UNCOV
2259
            throw(DimensionMismatch("row $(i) has mismatched number of columns (expected $nc, got $(rows[i]))"))
×
2260
        end
2261
    end
×
UNCOV
2262
    hvcat_fill!(Matrix{T}(undef, nr, nc), xs)
×
2263
end
2264

UNCOV
2265
typed_hvcat(::Type{T}, rows::Tuple{Vararg{Int}}, as...) where T = typed_hvncat(T, rows_to_dimshape(rows), true, as...)
×
2266

2267
## N-dimensional concatenation ##
2268

2269
"""
2270
    hvncat(dim::Int, row_first, values...)
2271
    hvncat(dims::Tuple{Vararg{Int}}, row_first, values...)
2272
    hvncat(shape::Tuple{Vararg{Tuple}}, row_first, values...)
2273

2274
Horizontal, vertical, and n-dimensional concatenation of many `values` in one call.
2275

2276
This function is called for block matrix syntax. The first argument either specifies the
2277
shape of the concatenation, similar to `hvcat`, as a tuple of tuples, or the dimensions that
2278
specify the key number of elements along each axis, and is used to determine the output
2279
dimensions. The `dims` form is more performant, and is used by default when the concatenation
2280
operation has the same number of elements along each axis (e.g., [a b; c d;;; e f ; g h]).
2281
The `shape` form is used when the number of elements along each axis is unbalanced
2282
(e.g., [a b ; c]). Unbalanced syntax needs additional validation overhead. The `dim` form
2283
is an optimization for concatenation along just one dimension. `row_first` indicates how
2284
`values` are ordered. The meaning of the first and second elements of `shape` are also
2285
swapped based on `row_first`.
2286

2287
# Examples
2288
```jldoctest
2289
julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
2290
(1, 2, 3, 4, 5, 6)
2291

2292
julia> [a b c;;; d e f]
2293
1×3×2 Array{Int64, 3}:
2294
[:, :, 1] =
2295
 1  2  3
2296

2297
[:, :, 2] =
2298
 4  5  6
2299

2300
julia> hvncat((2,1,3), false, a,b,c,d,e,f)
2301
2×1×3 Array{Int64, 3}:
2302
[:, :, 1] =
2303
 1
2304
 2
2305

2306
[:, :, 2] =
2307
 3
2308
 4
2309

2310
[:, :, 3] =
2311
 5
2312
 6
2313

2314
julia> [a b;;; c d;;; e f]
2315
1×2×3 Array{Int64, 3}:
2316
[:, :, 1] =
2317
 1  2
2318

2319
[:, :, 2] =
2320
 3  4
2321

2322
[:, :, 3] =
2323
 5  6
2324

2325
julia> hvncat(((3, 3), (3, 3), (6,)), true, a, b, c, d, e, f)
2326
1×3×2 Array{Int64, 3}:
2327
[:, :, 1] =
2328
 1  2  3
2329

2330
[:, :, 2] =
2331
 4  5  6
2332
```
2333

2334
# Examples for construction of the arguments
2335
```
2336
[a b c ; d e f ;;;
2337
 g h i ; j k l ;;;
2338
 m n o ; p q r ;;;
2339
 s t u ; v w x]
2340
⇒ dims = (2, 3, 4)
2341

2342
[a b ; c ;;; d ;;;;]
2343
 ___   _     _
2344
 2     1     1 = elements in each row (2, 1, 1)
2345
 _______     _
2346
 3           1 = elements in each column (3, 1)
2347
 _____________
2348
 4             = elements in each 3d slice (4,)
2349
 _____________
2350
 4             = elements in each 4d slice (4,)
2351
⇒ shape = ((2, 1, 1), (3, 1), (4,), (4,)) with `row_first` = true
2352
```
2353
"""
2354
hvncat(dimsshape::Tuple, row_first::Bool, xs...) = _hvncat(dimsshape, row_first, xs...)
×
UNCOV
2355
hvncat(dim::Int, xs...) = _hvncat(dim, true, xs...)
×
2356

2357
_hvncat(dimsshape::Union{Tuple, Int}, row_first::Bool) = _typed_hvncat(Any, dimsshape, row_first)
×
2358
_hvncat(dimsshape::Union{Tuple, Int}, row_first::Bool, xs...) = _typed_hvncat(promote_eltypeof(xs...), dimsshape, row_first, xs...)
×
2359
_hvncat(dimsshape::Union{Tuple, Int}, row_first::Bool, xs::T...) where T<:Number = _typed_hvncat(T, dimsshape, row_first, xs...)
×
2360
_hvncat(dimsshape::Union{Tuple, Int}, row_first::Bool, xs::Number...) = _typed_hvncat(promote_typeof(xs...), dimsshape, row_first, xs...)
×
2361
_hvncat(dimsshape::Union{Tuple, Int}, row_first::Bool, xs::AbstractArray...) = _typed_hvncat(promote_eltype(xs...), dimsshape, row_first, xs...)
×
UNCOV
2362
_hvncat(dimsshape::Union{Tuple, Int}, row_first::Bool, xs::AbstractArray{T}...) where T = _typed_hvncat(T, dimsshape, row_first, xs...)
×
2363

2364

2365
typed_hvncat(T::Type, dimsshape::Tuple, row_first::Bool, xs...) = _typed_hvncat(T, dimsshape, row_first, xs...)
×
UNCOV
2366
typed_hvncat(T::Type, dim::Int, xs...) = _typed_hvncat(T, Val(dim), xs...)
×
2367

2368
# 1-dimensional hvncat methods
2369

2370
_typed_hvncat(::Type, ::Val{0}) = _typed_hvncat_0d_only_one()
×
2371
_typed_hvncat(T::Type, ::Val{0}, x) = fill(convert(T, x))
×
2372
_typed_hvncat(T::Type, ::Val{0}, x::Number) = fill(convert(T, x))
×
2373
_typed_hvncat(T::Type, ::Val{0}, x::AbstractArray) = convert.(T, x)
×
2374
_typed_hvncat(::Type, ::Val{0}, ::Any...) = _typed_hvncat_0d_only_one()
×
2375
_typed_hvncat(::Type, ::Val{0}, ::Number...) = _typed_hvncat_0d_only_one()
×
UNCOV
2376
_typed_hvncat(::Type, ::Val{0}, ::AbstractArray...) = _typed_hvncat_0d_only_one()
×
2377

UNCOV
2378
_typed_hvncat_0d_only_one() =
×
2379
    throw(ArgumentError("a 0-dimensional array may only contain exactly one element"))
2380

2381
# `@constprop :aggressive` here to form constant `Val(dim)` type to get type stability
UNCOV
2382
@constprop :aggressive _typed_hvncat(T::Type, dim::Int, ::Bool, xs...) = _typed_hvncat(T, Val(dim), xs...) # catches from _hvncat type promoters
×
2383

2384
function _typed_hvncat(::Type{T}, ::Val{N}) where {T, N}
×
UNCOV
2385
    N < 0 &&
×
2386
        throw(ArgumentError("concatenation dimension must be non-negative"))
UNCOV
2387
    return Array{T, N}(undef, ntuple(x -> 0, Val(N)))
×
2388
end
2389

2390
function _typed_hvncat(T::Type, ::Val{N}, xs::Number...) where N
×
UNCOV
2391
    N < 0 &&
×
2392
        throw(ArgumentError("concatenation dimension must be non-negative"))
2393
    A = cat_similar(xs[1], T, (ntuple(x -> 1, Val(N - 1))..., length(xs)))
×
2394
    hvncat_fill!(A, false, xs)
×
UNCOV
2395
    return A
×
2396
end
2397

UNCOV
2398
function _typed_hvncat(::Type{T}, ::Val{N}, as::AbstractArray...) where {T, N}
×
2399
    # optimization for arrays that can be concatenated by copying them linearly into the destination
2400
    # conditions: the elements must all have 1-length dimensions above N
UNCOV
2401
    length(as) > 0 ||
×
2402
        throw(ArgumentError("must have at least one element"))
UNCOV
2403
    N < 0 &&
×
2404
        throw(ArgumentError("concatenation dimension must be non-negative"))
2405
    for a ∈ as
×
2406
        ndims(a) <= N || all(x -> size(a, x) == 1, (N + 1):ndims(a)) ||
×
UNCOV
2407
            return _typed_hvncat(T, (ntuple(x -> 1, Val(N - 1))..., length(as), 1), false, as...)
×
2408
            # the extra 1 is to avoid an infinite cycle
UNCOV
2409
    end
×
2410

UNCOV
2411
    nd = N
×
2412

2413
    Ndim = 0
×
2414
    for i ∈ eachindex(as)
×
2415
        Ndim += cat_size(as[i], N)
×
2416
        nd = max(nd, cat_ndims(as[i]))
×
2417
        for d ∈ 1:N - 1
×
2418
            cat_size(as[1], d) == cat_size(as[i], d) || throw(DimensionMismatch("mismatched size along axis $d in element $i"))
×
2419
        end
×
UNCOV
2420
    end
×
2421

2422
    A = cat_similar(as[1], T, (ntuple(d -> size(as[1], d), N - 1)..., Ndim, ntuple(x -> 1, nd - N)...))
×
2423
    k = 1
×
2424
    for a ∈ as
×
2425
        for i ∈ eachindex(a)
×
2426
            A[k] = a[i]
×
2427
            k += 1
×
2428
        end
×
2429
    end
×
UNCOV
2430
    return A
×
2431
end
2432

2433
function _typed_hvncat(::Type{T}, ::Val{N}, as...) where {T, N}
×
UNCOV
2434
    length(as) > 0 ||
×
2435
        throw(ArgumentError("must have at least one element"))
UNCOV
2436
    N < 0 &&
×
2437
        throw(ArgumentError("concatenation dimension must be non-negative"))
2438
    nd = N
×
2439
    Ndim = 0
×
2440
    for i ∈ eachindex(as)
×
2441
        Ndim += cat_size(as[i], N)
×
2442
        nd = max(nd, cat_ndims(as[i]))
×
2443
        for d ∈ 1:N-1
×
UNCOV
2444
            cat_size(as[i], d) == 1 ||
×
2445
                throw(DimensionMismatch("all dimensions of element $i other than $N must be of length 1"))
2446
        end
×
UNCOV
2447
    end
×
2448

UNCOV
2449
    A = Array{T, nd}(undef, ntuple(x -> 1, Val(N - 1))..., Ndim, ntuple(x -> 1, nd - N)...)
×
2450

2451
    k = 1
×
2452
    for a ∈ as
×
2453
        if a isa AbstractArray
×
2454
            lena = length(a)
×
2455
            copyto!(A, k, a, 1, lena)
×
UNCOV
2456
            k += lena
×
2457
        else
2458
            A[k] = a
×
UNCOV
2459
            k += 1
×
2460
        end
2461
    end
×
UNCOV
2462
    return A
×
2463
end
2464

2465
# 0-dimensional cases for balanced and unbalanced hvncat method
2466

2467
_typed_hvncat(T::Type, ::Tuple{}, ::Bool, x...) = _typed_hvncat(T, Val(0), x...)
×
UNCOV
2468
_typed_hvncat(T::Type, ::Tuple{}, ::Bool, x::Number...) = _typed_hvncat(T, Val(0), x...)
×
2469

2470

2471
# balanced dimensions hvncat methods
2472

2473
_typed_hvncat(T::Type, dims::Tuple{Int}, ::Bool, as...) = _typed_hvncat_1d(T, dims[1], Val(false), as...)
×
UNCOV
2474
_typed_hvncat(T::Type, dims::Tuple{Int}, ::Bool, as::Number...) = _typed_hvncat_1d(T, dims[1], Val(false), as...)
×
2475

2476
function _typed_hvncat_1d(::Type{T}, ds::Int, ::Val{row_first}, as...) where {T, row_first}
×
2477
    lengthas = length(as)
×
UNCOV
2478
    ds > 0 ||
×
2479
        throw(ArgumentError("`dimsshape` argument must consist of positive integers"))
UNCOV
2480
    lengthas == ds ||
×
2481
        throw(ArgumentError("number of elements does not match `dimshape` argument; expected $ds, got $lengthas"))
2482
    if row_first
×
UNCOV
2483
        return _typed_hvncat(T, Val(2), as...)
×
2484
    else
UNCOV
2485
        return _typed_hvncat(T, Val(1), as...)
×
2486
    end
2487
end
2488

2489
function _typed_hvncat(::Type{T}, dims::NTuple{N, Int}, row_first::Bool, xs::Number...) where {T, N}
×
UNCOV
2490
    all(>(0), dims) ||
×
2491
        throw(ArgumentError("`dims` argument must contain positive integers"))
2492
    A = Array{T, N}(undef, dims...)
×
2493
    lengtha = length(A)  # Necessary to store result because throw blocks are being deoptimized right now, which leads to excessive allocations
×
2494
    lengthx = length(xs) # Cuts from 3 allocations to 1.
×
2495
    if lengtha != lengthx
×
UNCOV
2496
       throw(ArgumentError("argument count does not match specified shape (expected $lengtha, got $lengthx)"))
×
2497
    end
2498
    hvncat_fill!(A, row_first, xs)
×
UNCOV
2499
    return A
×
2500
end
2501

2502
function hvncat_fill!(A::Array, row_first::Bool, xs::Tuple)
×
2503
    nr, nc = size(A, 1), size(A, 2)
×
2504
    na = prod(size(A)[3:end])
×
2505
    len = length(xs)
×
2506
    nrc = nr * nc
×
2507
    if nrc * na != len
×
UNCOV
2508
        throw(ArgumentError("argument count $(len) does not match specified shape $(size(A))"))
×
2509
    end
2510
    # putting these in separate functions leads to unnecessary allocations
2511
    if row_first
×
2512
        k = 1
×
2513
        for d ∈ 1:na
×
2514
            dd = nrc * (d - 1)
×
2515
            for i ∈ 1:nr
×
2516
                Ai = dd + i
×
2517
                for j ∈ 1:nc
×
2518
                    @inbounds A[Ai] = xs[k]
×
2519
                    k += 1
×
2520
                    Ai += nr
×
2521
                end
×
2522
            end
×
UNCOV
2523
        end
×
2524
    else
2525
        for k ∈ eachindex(xs)
×
2526
            @inbounds A[k] = xs[k]
×
UNCOV
2527
        end
×
2528
    end
2529
end
2530

UNCOV
2531
function _typed_hvncat(T::Type, dims::NTuple{N, Int}, row_first::Bool, as...) where {N}
×
2532
    # function barrier after calculating the max is necessary for high performance
2533
    nd = max(maximum(cat_ndims(a) for a ∈ as), N)
×
UNCOV
2534
    return _typed_hvncat_dims(T, (dims..., ntuple(x -> 1, nd - N)...), row_first, as)
×
2535
end
2536

2537
function _typed_hvncat_dims(::Type{T}, dims::NTuple{N, Int}, row_first::Bool, as::Tuple) where {T, N}
×
UNCOV
2538
    length(as) > 0 ||
×
2539
        throw(ArgumentError("must have at least one element"))
UNCOV
2540
    all(>(0), dims) ||
×
2541
        throw(ArgumentError("`dims` argument must contain positive integers"))
2542

2543
    d1 = row_first ? 2 : 1
×
UNCOV
2544
    d2 = row_first ? 1 : 2
×
2545

UNCOV
2546
    outdims = zeros(Int, N)
×
2547

2548
    # validate shapes for lowest level of concatenation
2549
    d = findfirst(>(1), dims)
×
2550
    if d !== nothing # all dims are 1
×
2551
        if row_first && d < 3
×
UNCOV
2552
            d = d == 1 ? 2 : 1
×
2553
        end
2554
        nblocks = length(as) ÷ dims[d]
×
2555
        for b ∈ 1:nblocks
×
2556
            offset = ((b - 1) * dims[d])
×
2557
            startelementi = offset + 1
×
2558
            for i ∈ offset .+ (2:dims[d])
×
2559
                for dd ∈ 1:N
×
2560
                    dd == d && continue
×
2561
                    if cat_size(as[startelementi], dd) != cat_size(as[i], dd)
×
UNCOV
2562
                        throw(DimensionMismatch("incompatible shape in element $i"))
×
2563
                    end
2564
                end
×
2565
            end
×
UNCOV
2566
        end
×
2567
    end
2568

2569
    # discover number of rows or columns
2570
    for i ∈ 1:dims[d1]
×
2571
        outdims[d1] += cat_size(as[i], d1)
×
UNCOV
2572
    end
×
2573

2574
    currentdims = zeros(Int, N)
×
2575
    blockcount = 0
×
2576
    elementcount = 0
×
2577
    for i ∈ eachindex(as)
×
2578
        elementcount += cat_length(as[i])
×
2579
        currentdims[d1] += cat_size(as[i], d1)
×
2580
        if currentdims[d1] == outdims[d1]
×
2581
            currentdims[d1] = 0
×
2582
            for d ∈ (d2, 3:N...)
×
2583
                currentdims[d] += cat_size(as[i], d)
×
2584
                if outdims[d] == 0 # unfixed dimension
×
2585
                    blockcount += 1
×
2586
                    if blockcount == dims[d]
×
2587
                        outdims[d] = currentdims[d]
×
2588
                        currentdims[d] = 0
×
UNCOV
2589
                        blockcount = 0
×
2590
                    else
UNCOV
2591
                        break
×
2592
                    end
2593
                else # fixed dimension
2594
                    if currentdims[d] == outdims[d] # end of dimension
×
2595
                        currentdims[d] = 0
×
2596
                    elseif currentdims[d] < outdims[d] # dimension in progress
×
UNCOV
2597
                        break
×
2598
                    else # exceeded dimension
UNCOV
2599
                        throw(DimensionMismatch("argument $i has too many elements along axis $d"))
×
2600
                    end
2601
                end
2602
            end
×
2603
        elseif currentdims[d1] > outdims[d1] # exceeded dimension
×
UNCOV
2604
            throw(DimensionMismatch("argument $i has too many elements along axis $d1"))
×
2605
        end
UNCOV
2606
    end
×
2607

2608
    outlen = prod(outdims)
×
UNCOV
2609
    elementcount == outlen ||
×
2610
        throw(DimensionMismatch("mismatched number of elements; expected $(outlen), got $(elementcount)"))
2611

2612
    # copy into final array
UNCOV
2613
    A = cat_similar(as[1], T, ntuple(i -> outdims[i], N))
×
2614
    # @assert all(==(0), currentdims)
2615
    outdims .= 0
×
2616
    hvncat_fill!(A, currentdims, outdims, d1, d2, as)
×
UNCOV
2617
    return A
×
2618
end
2619

2620

2621
# unbalanced dimensions hvncat methods
2622

2623
function _typed_hvncat(T::Type, shape::Tuple{Tuple}, row_first::Bool, xs...)
×
UNCOV
2624
    length(shape[1]) > 0 ||
×
2625
        throw(ArgumentError("each level of `shape` argument must have at least one value"))
UNCOV
2626
    return _typed_hvncat_1d(T, shape[1][1], Val(row_first), xs...)
×
2627
end
2628

UNCOV
2629
function _typed_hvncat(T::Type, shape::NTuple{N, Tuple}, row_first::Bool, as...) where {N}
×
2630
    # function barrier after calculating the max is necessary for high performance
2631
    nd = max(maximum(cat_ndims(a) for a ∈ as), N)
×
UNCOV
2632
    return _typed_hvncat_shape(T, (shape..., ntuple(x -> shape[end], nd - N)...), row_first, as)
×
2633
end
2634

2635
function _typed_hvncat_shape(::Type{T}, shape::NTuple{N, Tuple}, row_first, as::Tuple) where {T, N}
×
UNCOV
2636
    length(as) > 0 ||
×
2637
        throw(ArgumentError("must have at least one element"))
UNCOV
2638
    all(>(0), tuple((shape...)...)) ||
×
2639
        throw(ArgumentError("`shape` argument must consist of positive integers"))
2640

2641
    d1 = row_first ? 2 : 1
×
UNCOV
2642
    d2 = row_first ? 1 : 2
×
2643

2644
    shapev = collect(shape) # saves allocations later
×
UNCOV
2645
    all(!isempty, shapev) ||
×
2646
        throw(ArgumentError("each level of `shape` argument must have at least one value"))
UNCOV
2647
    length(shapev[end]) == 1 ||
×
2648
        throw(ArgumentError("last level of shape must contain only one integer"))
2649
    shapelength = shapev[end][1]
×
2650
    lengthas = length(as)
×
UNCOV
2651
    shapelength == lengthas || throw(ArgumentError("number of elements does not match shape; expected $(shapelength), got $lengthas)"))
×
2652
    # discover dimensions
2653
    nd = max(N, cat_ndims(as[1]))
×
2654
    outdims = fill(-1, nd)
×
2655
    currentdims = zeros(Int, nd)
×
2656
    blockcounts = zeros(Int, nd)
×
UNCOV
2657
    shapepos = ones(Int, nd)
×
2658

2659
    elementcount = 0
×
2660
    for i ∈ eachindex(as)
×
2661
        elementcount += cat_length(as[i])
×
2662
        wasstartblock = false
×
2663
        for d ∈ 1:N
×
2664
            ad = (d < 3 && row_first) ? (d == 1 ? 2 : 1) : d
×
2665
            dsize = cat_size(as[i], ad)
×
UNCOV
2666
            blockcounts[d] += 1
×
2667

2668
            if d == 1 || i == 1 || wasstartblock
×
2669
                currentdims[d] += dsize
×
2670
            elseif dsize != cat_size(as[i - 1], ad)
×
UNCOV
2671
                throw(DimensionMismatch("argument $i has a mismatched number of elements along axis $ad; \
×
2672
                                         expected $(cat_size(as[i - 1], ad)), got $dsize"))
2673
            end
2674

UNCOV
2675
            wasstartblock = blockcounts[d] == 1 # remember for next dimension
×
2676

2677
            isendblock = blockcounts[d] == shapev[d][shapepos[d]]
×
2678
            if isendblock
×
2679
                if outdims[d] == -1
×
2680
                    outdims[d] = currentdims[d]
×
2681
                elseif outdims[d] != currentdims[d]
×
UNCOV
2682
                    throw(DimensionMismatch("argument $i has a mismatched number of elements along axis $ad; \
×
2683
                                             expected $(abs(outdims[d] - (currentdims[d] - dsize))), got $dsize"))
2684
                end
2685
                currentdims[d] = 0
×
2686
                blockcounts[d] = 0
×
2687
                shapepos[d] += 1
×
UNCOV
2688
                d > 1 && (blockcounts[d - 1] == 0 ||
×
2689
                    throw(DimensionMismatch("shape in level $d is inconsistent; level counts must nest \
2690
                                             evenly into each other")))
2691
            end
2692
        end
×
UNCOV
2693
    end
×
2694

2695
    outlen = prod(outdims)
×
UNCOV
2696
    elementcount == outlen ||
×
2697
        throw(ArgumentError("mismatched number of elements; expected $(outlen), got $(elementcount)"))
2698

2699
    if row_first
×
UNCOV
2700
        outdims[1], outdims[2] = outdims[2], outdims[1]
×
2701
    end
2702

2703
    # @assert all(==(0), currentdims)
2704
    # @assert all(==(0), blockcounts)
2705

2706
    # copy into final array
2707
    A = cat_similar(as[1], T, ntuple(i -> outdims[i], nd))
×
2708
    hvncat_fill!(A, currentdims, blockcounts, d1, d2, as)
×
UNCOV
2709
    return A
×
2710
end
2711

UNCOV
2712
function hvncat_fill!(A::AbstractArray{T, N}, scratch1::Vector{Int}, scratch2::Vector{Int},
×
2713
                              d1::Int, d2::Int, as::Tuple) where {T, N}
2714
    N > 1 || throw(ArgumentError("dimensions of the destination array must be at least 2"))
×
UNCOV
2715
    length(scratch1) == length(scratch2) == N ||
×
2716
        throw(ArgumentError("scratch vectors must have as many elements as the destination array has dimensions"))
UNCOV
2717
    0 < d1 < 3 &&
×
2718
    0 < d2 < 3 &&
2719
    d1 != d2 ||
2720
        throw(ArgumentError("d1 and d2 must be either 1 or 2, exclusive."))
2721
    outdims = size(A)
×
2722
    offsets = scratch1
×
2723
    inneroffsets = scratch2
×
2724
    for a ∈ as
×
2725
        if isa(a, AbstractArray)
×
2726
            for ai ∈ a
×
2727
                @inbounds Ai = hvncat_calcindex(offsets, inneroffsets, outdims, N)
×
UNCOV
2728
                A[Ai] = ai
×
2729

2730
                @inbounds for j ∈ 1:N
×
2731
                    inneroffsets[j] += 1
×
2732
                    inneroffsets[j] < cat_size(a, j) && break
×
2733
                    inneroffsets[j] = 0
×
2734
                end
×
UNCOV
2735
            end
×
2736
        else
2737
            @inbounds Ai = hvncat_calcindex(offsets, inneroffsets, outdims, N)
×
UNCOV
2738
            A[Ai] = a
×
2739
        end
2740

2741
        @inbounds for j ∈ (d1, d2, 3:N...)
×
2742
            offsets[j] += cat_size(a, j)
×
2743
            offsets[j] < outdims[j] && break
×
2744
            offsets[j] = 0
×
2745
        end
×
UNCOV
2746
    end
×
2747
end
2748

UNCOV
2749
@propagate_inbounds function hvncat_calcindex(offsets::Vector{Int}, inneroffsets::Vector{Int},
×
2750
                                              outdims::Tuple{Vararg{Int}}, nd::Int)
2751
    Ai = inneroffsets[1] + offsets[1] + 1
×
2752
    for j ∈ 2:nd
×
2753
        increment = inneroffsets[j] + offsets[j]
×
2754
        for k ∈ 1:j-1
×
2755
            increment *= outdims[k]
×
2756
        end
×
2757
        Ai += increment
×
2758
    end
×
UNCOV
2759
    Ai
×
2760
end
2761

2762
"""
2763
    stack(iter; [dims])
2764

2765
Combine a collection of arrays (or other iterable objects) of equal size
2766
into one larger array, by arranging them along one or more new dimensions.
2767

2768
By default the axes of the elements are placed first,
2769
giving `size(result) = (size(first(iter))..., size(iter)...)`.
2770
This has the same order of elements as [`Iterators.flatten`](@ref)`(iter)`.
2771

2772
With keyword `dims::Integer`, instead the `i`th element of `iter` becomes the slice
2773
[`selectdim`](@ref)`(result, dims, i)`, so that `size(result, dims) == length(iter)`.
2774
In this case `stack` reverses the action of [`eachslice`](@ref) with the same `dims`.
2775

2776
The various [`cat`](@ref) functions also combine arrays. However, these all
2777
extend the arrays' existing (possibly trivial) dimensions, rather than placing
2778
the arrays along new dimensions.
2779
They also accept arrays as separate arguments, rather than a single collection.
2780

2781
!!! compat "Julia 1.9"
2782
    This function requires at least Julia 1.9.
2783

2784
# Examples
2785
```jldoctest
2786
julia> vecs = (1:2, [30, 40], Float32[500, 600]);
2787

2788
julia> mat = stack(vecs)
2789
2×3 Matrix{Float32}:
2790
 1.0  30.0  500.0
2791
 2.0  40.0  600.0
2792

2793
julia> mat == hcat(vecs...) == reduce(hcat, collect(vecs))
2794
true
2795

2796
julia> vec(mat) == vcat(vecs...) == reduce(vcat, collect(vecs))
2797
true
2798

2799
julia> stack(zip(1:4, 10:99))  # accepts any iterators of iterators
2800
2×4 Matrix{Int64}:
2801
  1   2   3   4
2802
 10  11  12  13
2803

2804
julia> vec(ans) == collect(Iterators.flatten(zip(1:4, 10:99)))
2805
true
2806

2807
julia> stack(vecs; dims=1)  # unlike any cat function, 1st axis of vecs[1] is 2nd axis of result
2808
3×2 Matrix{Float32}:
2809
   1.0    2.0
2810
  30.0   40.0
2811
 500.0  600.0
2812

2813
julia> x = rand(3,4);
2814

2815
julia> x == stack(eachcol(x)) == stack(eachrow(x), dims=1)  # inverse of eachslice
2816
true
2817
```
2818

2819
Higher-dimensional examples:
2820

2821
```jldoctest
2822
julia> A = rand(5, 7, 11);
2823

2824
julia> E = eachslice(A, dims=2);  # a vector of matrices
2825

2826
julia> (element = size(first(E)), container = size(E))
2827
(element = (5, 11), container = (7,))
2828

2829
julia> stack(E) |> size
2830
(5, 11, 7)
2831

2832
julia> stack(E) == stack(E; dims=3) == cat(E...; dims=3)
2833
true
2834

2835
julia> A == stack(E; dims=2)
2836
true
2837

2838
julia> M = (fill(10i+j, 2, 3) for i in 1:5, j in 1:7);
2839

2840
julia> (element = size(first(M)), container = size(M))
2841
(element = (2, 3), container = (5, 7))
2842

2843
julia> stack(M) |> size  # keeps all dimensions
2844
(2, 3, 5, 7)
2845

2846
julia> stack(M; dims=1) |> size  # vec(container) along dims=1
2847
(35, 2, 3)
2848

2849
julia> hvcat(5, M...) |> size  # hvcat puts matrices next to each other
2850
(14, 15)
2851
```
2852
"""
UNCOV
2853
stack(iter; dims=:) = _stack(dims, iter)
×
2854

2855
"""
2856
    stack(f, args...; [dims])
2857

2858
Apply a function to each element of a collection, and `stack` the result.
2859
Or to several collections, [`zip`](@ref)ped together.
2860

2861
The function should return arrays (or tuples, or other iterators) all of the same size.
2862
These become slices of the result, each separated along `dims` (if given) or by default
2863
along the last dimensions.
2864

2865
See also [`mapslices`](@ref), [`eachcol`](@ref).
2866

2867
# Examples
2868
```jldoctest
2869
julia> stack(c -> (c, c-32), "julia")
2870
2×5 Matrix{Char}:
2871
 'j'  'u'  'l'  'i'  'a'
2872
 'J'  'U'  'L'  'I'  'A'
2873

2874
julia> stack(eachrow([1 2 3; 4 5 6]), (10, 100); dims=1) do row, n
2875
         vcat(row, row .* n, row ./ n)
2876
       end
2877
2×9 Matrix{Float64}:
2878
 1.0  2.0  3.0   10.0   20.0   30.0  0.1   0.2   0.3
2879
 4.0  5.0  6.0  400.0  500.0  600.0  0.04  0.05  0.06
2880
```
2881
"""
2882
stack(f, iter; dims=:) = _stack(dims, f(x) for x in iter)
×
UNCOV
2883
stack(f, xs, yzs...; dims=:) = _stack(dims, f(xy...) for xy in zip(xs, yzs...))
×
2884

UNCOV
2885
_stack(dims::Union{Integer, Colon}, iter) = _stack(dims, IteratorSize(iter), iter)
×
2886

UNCOV
2887
_stack(dims, ::IteratorSize, iter) = _stack(dims, collect(iter))
×
2888

2889
function _stack(dims, ::Union{HasShape, HasLength}, iter)
×
2890
    S = @default_eltype iter
×
2891
    T = S != Union{} ? eltype(S) : Any  # Union{} occurs for e.g. stack(1,2), postpone the error
×
2892
    if isconcretetype(T)
×
UNCOV
2893
        _typed_stack(dims, T, S, iter)
×
2894
    else  # Need to look inside, but shouldn't run an expensive iterator twice:
2895
        array = iter isa Union{Tuple, AbstractArray} ? iter : collect(iter)
×
2896
        isempty(array) && return _empty_stack(dims, T, S, iter)
×
2897
        T2 = mapreduce(eltype, promote_type, array)
×
UNCOV
2898
        _typed_stack(dims, T2, eltype(array), array)
×
2899
    end
2900
end
2901

2902
function _typed_stack(::Colon, ::Type{T}, ::Type{S}, A, Aax=_iterator_axes(A)) where {T, S}
×
2903
    xit = iterate(A)
×
2904
    nothing === xit && return _empty_stack(:, T, S, A)
×
2905
    x1, _ = xit
×
2906
    ax1 = _iterator_axes(x1)
×
2907
    B = similar(_ensure_array(x1), T, ax1..., Aax...)
×
2908
    off = firstindex(B)
×
2909
    len = length(x1)
×
2910
    while xit !== nothing
×
2911
        x, state = xit
×
2912
        _stack_size_check(x, ax1)
×
2913
        copyto!(B, off, x)
×
2914
        off += len
×
2915
        xit = iterate(A, state)
×
2916
    end
×
UNCOV
2917
    B
×
2918
end
2919

2920
_iterator_axes(x) = _iterator_axes(x, IteratorSize(x))
×
2921
_iterator_axes(x, ::HasLength) = (OneTo(length(x)),)
×
UNCOV
2922
_iterator_axes(x, ::IteratorSize) = axes(x)
×
2923

2924
# For some dims values, stack(A; dims) == stack(vec(A)), and the : path will be faster
UNCOV
2925
_typed_stack(dims::Integer, ::Type{T}, ::Type{S}, A) where {T,S} =
×
2926
    _typed_stack(dims, T, S, IteratorSize(S), A)
UNCOV
2927
_typed_stack(dims::Integer, ::Type{T}, ::Type{S}, ::HasLength, A) where {T,S} =
×
2928
    _typed_stack(dims, T, S, HasShape{1}(), A)
2929
function _typed_stack(dims::Integer, ::Type{T}, ::Type{S}, ::HasShape{N}, A) where {T,S,N}
×
2930
    if dims == N+1
×
UNCOV
2931
        _typed_stack(:, T, S, A, (_vec_axis(A),))
×
2932
    else
UNCOV
2933
        _dim_stack(dims, T, S, A)
×
2934
    end
2935
end
UNCOV
2936
_typed_stack(dims::Integer, ::Type{T}, ::Type{S}, ::IteratorSize, A) where {T,S} =
×
2937
    _dim_stack(dims, T, S, A)
2938

UNCOV
2939
_vec_axis(A, ax=_iterator_axes(A)) = length(ax) == 1 ? only(ax) : OneTo(prod(length, ax; init=1))
×
2940

2941
@constprop :aggressive function _dim_stack(dims::Integer, ::Type{T}, ::Type{S}, A) where {T,S}
×
2942
    xit = Iterators.peel(A)
×
2943
    nothing === xit && return _empty_stack(dims, T, S, A)
×
2944
    x1, xrest = xit
×
2945
    ax1 = _iterator_axes(x1)
×
2946
    N1 = length(ax1)+1
×
UNCOV
2947
    dims in 1:N1 || throw(ArgumentError(LazyString("cannot stack slices ndims(x) = ", N1-1, " along dims = ", dims)))
×
2948

2949
    newaxis = _vec_axis(A)
×
2950
    outax = ntuple(d -> d==dims ? newaxis : ax1[d - (d>dims)], N1)
×
UNCOV
2951
    B = similar(_ensure_array(x1), T, outax...)
×
2952

2953
    if dims == 1
×
2954
        _dim_stack!(Val(1), B, x1, xrest)
×
2955
    elseif dims == 2
×
UNCOV
2956
        _dim_stack!(Val(2), B, x1, xrest)
×
2957
    else
UNCOV
2958
        _dim_stack!(Val(dims), B, x1, xrest)
×
2959
    end
UNCOV
2960
    B
×
2961
end
2962

2963
function _dim_stack!(::Val{dims}, B::AbstractArray, x1, xrest) where {dims}
×
2964
    before = ntuple(d -> Colon(), dims - 1)
×
UNCOV
2965
    after = ntuple(d -> Colon(), ndims(B) - dims)
×
2966

2967
    i = firstindex(B, dims)
×
UNCOV
2968
    copyto!(view(B, before..., i, after...), x1)
×
2969

2970
    for x in xrest
×
2971
        _stack_size_check(x, _iterator_axes(x1))
×
2972
        i += 1
×
2973
        @inbounds copyto!(view(B, before..., i, after...), x)
×
UNCOV
2974
    end
×
2975
end
2976

2977
@inline function _stack_size_check(x, ax1::Tuple)
×
2978
    if _iterator_axes(x) != ax1
×
2979
        uax1 = map(UnitRange, ax1)
×
2980
        uaxN = map(UnitRange, _iterator_axes(x))
×
UNCOV
2981
        throw(DimensionMismatch(
×
2982
            LazyString("stack expects uniform slices, got axes(x) == ", uaxN, " while first had ", uax1)))
2983
    end
2984
end
2985

2986
_ensure_array(x::AbstractArray) = x
×
UNCOV
2987
_ensure_array(x) = 1:0  # passed to similar, makes stack's output an Array
×
2988

UNCOV
2989
_empty_stack(_...) = throw(ArgumentError("`stack` on an empty collection is not allowed"))
×
2990

2991

2992
## Reductions and accumulates ##
2993

2994
function isequal(A::AbstractArray, B::AbstractArray)
2995
    if A === B return true end
1,434✔
2996
    if axes(A) != axes(B)
2,740✔
UNCOV
2997
        return false
×
2998
    end
2999
    for (a, b) in zip(A, B)
2,730✔
3000
        if !isequal(a, b)
162,524✔
3001
            return false
251✔
3002
        end
3003
    end
323,437✔
3004
    return true
1,119✔
3005
end
3006

3007
function cmp(A::AbstractVector, B::AbstractVector)
×
3008
    for (a, b) in zip(A, B)
×
3009
        if !isequal(a, b)
×
UNCOV
3010
            return isless(a, b) ? -1 : 1
×
3011
        end
3012
    end
×
UNCOV
3013
    return cmp(length(A), length(B))
×
3014
end
3015

3016
"""
3017
    isless(A::AbstractArray{<:Any,0}, B::AbstractArray{<:Any,0})
3018

3019
Return `true` when the only element of `A` is less than the only element of `B`.
3020
"""
3021
function isless(A::AbstractArray{<:Any,0}, B::AbstractArray{<:Any,0})
×
UNCOV
3022
    isless(only(A), only(B))
×
3023
end
3024

3025
"""
3026
    isless(A::AbstractVector, B::AbstractVector)
3027

3028
Return `true` when `A` is less than `B` in lexicographic order.
3029
"""
UNCOV
3030
isless(A::AbstractVector, B::AbstractVector) = cmp(A, B) < 0
×
3031

3032
function (==)(A::AbstractArray, B::AbstractArray)
233✔
3033
    if axes(A) != axes(B)
405,820✔
UNCOV
3034
        return false
×
3035
    end
3036
    anymissing = false
233✔
3037
    for (a, b) in zip(A, B)
405,817✔
3038
        eq = (a == b)
2,641,834✔
3039
        if ismissing(eq)
596✔
UNCOV
3040
            anymissing = true
×
3041
        elseif !eq
1,322,084✔
3042
            return false
59✔
3043
        end
3044
    end
2,440,744✔
3045
    return anymissing ? missing : true
202,963✔
3046
end
3047

3048
# _sub2ind and _ind2sub
3049
# fallbacks
3050
function _sub2ind(A::AbstractArray, I...)
UNCOV
3051
    @inline
×
3052
    _sub2ind(axes(A), I...)
642,637✔
3053
end
3054

3055
function _ind2sub(A::AbstractArray, ind)
×
3056
    @inline
×
UNCOV
3057
    _ind2sub(axes(A), ind)
×
3058
end
3059

3060
# 0-dimensional arrays and indexing with []
3061
_sub2ind(::Tuple{}) = 1
×
3062
_sub2ind(::DimsInteger) = 1
×
3063
_sub2ind(::Indices) = 1
×
UNCOV
3064
_sub2ind(::Tuple{}, I::Integer...) = (@inline; _sub2ind_recurse((), 1, 1, I...))
×
3065

3066
# Generic cases
UNCOV
3067
_sub2ind(dims::DimsInteger, I::Integer...) = (@inline; _sub2ind_recurse(dims, 1, 1, I...))
×
3068
_sub2ind(inds::Indices, I::Integer...) = (@inline; _sub2ind_recurse(inds, 1, 1, I...))
642,637✔
3069
# In 1d, there's a question of whether we're doing cartesian indexing
3070
# or linear indexing. Support only the former.
UNCOV
3071
_sub2ind(inds::Indices{1}, I::Integer...) =
×
3072
    throw(ArgumentError("Linear indexing is not defined for one-dimensional arrays"))
3073
_sub2ind(inds::Tuple{OneTo}, I::Integer...) = (@inline; _sub2ind_recurse(inds, 1, 1, I...)) # only OneTo is safe
×
UNCOV
3074
_sub2ind(inds::Tuple{OneTo}, i::Integer)    = i
×
3075

3076
_sub2ind_recurse(::Any, L, ind) = ind
×
3077
function _sub2ind_recurse(::Tuple{}, L, ind, i::Integer, I::Integer...)
×
3078
    @inline
×
UNCOV
3079
    _sub2ind_recurse((), L, ind+(i-1)*L, I...)
×
3080
end
3081
function _sub2ind_recurse(inds, L, ind, i::Integer, I::Integer...)
3082
    @inline
×
UNCOV
3083
    r1 = inds[1]
×
3084
    _sub2ind_recurse(tail(inds), nextL(L, r1), ind+offsetin(i, r1)*L, I...)
1,285,274✔
3085
end
3086

UNCOV
3087
nextL(L, l::Integer) = L*l
×
3088
nextL(L, r::AbstractUnitRange) = L*length(r)
642,637✔
3089
nextL(L, r::Slice) = L*length(r.indices)
×
UNCOV
3090
offsetin(i, l::Integer) = i-1
×
3091
offsetin(i, r::AbstractUnitRange) = i-first(r)
1,285,274✔
3092

3093
_ind2sub(::Tuple{}, ind::Integer) = (@inline; ind == 1 ? () : throw(BoundsError()))
×
3094
_ind2sub(dims::DimsInteger, ind::Integer) = (@inline; _ind2sub_recurse(dims, ind-1))
×
3095
_ind2sub(inds::Indices, ind::Integer)     = (@inline; _ind2sub_recurse(inds, ind-1))
×
UNCOV
3096
_ind2sub(inds::Indices{1}, ind::Integer) =
×
3097
    throw(ArgumentError("Linear indexing is not defined for one-dimensional arrays"))
UNCOV
3098
_ind2sub(inds::Tuple{OneTo}, ind::Integer) = (ind,)
×
3099

3100
_ind2sub_recurse(::Tuple{}, ind) = (ind+1,)
×
3101
function _ind2sub_recurse(indslast::NTuple{1}, ind)
×
3102
    @inline
×
UNCOV
3103
    (_lookup(ind, indslast[1]),)
×
3104
end
3105
function _ind2sub_recurse(inds, ind)
×
3106
    @inline
×
3107
    r1 = inds[1]
×
3108
    indnext, f, l = _div(ind, r1)
×
UNCOV
3109
    (ind-l*indnext+f, _ind2sub_recurse(tail(inds), indnext)...)
×
3110
end
3111

3112
_lookup(ind, d::Integer) = ind+1
×
3113
_lookup(ind, r::AbstractUnitRange) = ind+first(r)
×
3114
_div(ind, d::Integer) = div(ind, d), 1, d
×
UNCOV
3115
_div(ind, r::AbstractUnitRange) = (d = length(r); (div(ind, d), first(r), d))
×
3116

3117
# Vectorized forms
3118
function _sub2ind(inds::Indices{1}, I1::AbstractVector{T}, I::AbstractVector{T}...) where T<:Integer
×
UNCOV
3119
    throw(ArgumentError("Linear indexing is not defined for one-dimensional arrays"))
×
3120
end
UNCOV
3121
_sub2ind(inds::Tuple{OneTo}, I1::AbstractVector{T}, I::AbstractVector{T}...) where {T<:Integer} =
×
3122
    _sub2ind_vecs(inds, I1, I...)
UNCOV
3123
_sub2ind(inds::Union{DimsInteger,Indices}, I1::AbstractVector{T}, I::AbstractVector{T}...) where {T<:Integer} =
×
3124
    _sub2ind_vecs(inds, I1, I...)
3125
function _sub2ind_vecs(inds, I::AbstractVector...)
×
3126
    I1 = I[1]
×
3127
    Iinds = axes1(I1)
×
3128
    for j = 2:length(I)
×
3129
        axes1(I[j]) == Iinds || throw(DimensionMismatch("indices of I[1] ($(Iinds)) does not match indices of I[$j] ($(axes1(I[j])))"))
×
3130
    end
×
3131
    Iout = similar(I1)
×
3132
    _sub2ind!(Iout, inds, Iinds, I)
×
UNCOV
3133
    Iout
×
3134
end
3135

3136
function _sub2ind!(Iout, inds, Iinds, I)
×
3137
    @noinline
×
UNCOV
3138
    for i in Iinds
×
3139
        # Iout[i] = _sub2ind(inds, map(Ij -> Ij[i], I)...)
3140
        Iout[i] = sub2ind_vec(inds, i, I)
×
3141
    end
×
UNCOV
3142
    Iout
×
3143
end
3144

3145
sub2ind_vec(inds, i, I) = (@inline; _sub2ind(inds, _sub2ind_vec(i, I...)...))
×
3146
_sub2ind_vec(i, I1, I...) = (@inline; (I1[i], _sub2ind_vec(i, I...)...))
×
UNCOV
3147
_sub2ind_vec(i) = ()
×
3148

3149
function _ind2sub(inds::Union{DimsInteger{N},Indices{N}}, ind::AbstractVector{<:Integer}) where N
×
3150
    M = length(ind)
×
3151
    t = ntuple(n->similar(ind),Val(N))
×
3152
    for (i,idx) in pairs(IndexLinear(), ind)
×
3153
        sub = _ind2sub(inds, idx)
×
3154
        for j = 1:N
×
3155
            t[j][i] = sub[j]
×
3156
        end
×
3157
    end
×
UNCOV
3158
    t
×
3159
end
3160

3161
## iteration utilities ##
3162

3163
"""
3164
    foreach(f, c...) -> nothing
3165

3166
Call function `f` on each element of iterable `c`.
3167
For multiple iterable arguments, `f` is called elementwise, and iteration stops when
3168
any iterator is finished.
3169

3170
`foreach` should be used instead of [`map`](@ref) when the results of `f` are not
3171
needed, for example in `foreach(println, array)`.
3172

3173
# Examples
3174
```jldoctest
3175
julia> tri = 1:3:7; res = Int[];
3176

3177
julia> foreach(x -> push!(res, x^2), tri)
3178

3179
julia> res
3180
3-element Vector{$(Int)}:
3181
  1
3182
 16
3183
 49
3184

3185
julia> foreach((x, y) -> println(x, " with ", y), tri, 'a':'z')
3186
1 with a
3187
4 with b
3188
7 with c
3189
```
3190
"""
3191
foreach(f, itr) = (for x in itr; f(x); end; nothing)
3,294,150✔
UNCOV
3192
foreach(f, itr, itrs...) = (for z in zip(itr, itrs...); f(z...); end; nothing)
×
3193

3194
## map over arrays ##
3195

3196
## transform any set of dimensions
3197
## dims specifies which dimensions will be transformed. for example
3198
## dims==1:2 will call f on all slices A[:,:,...]
3199
"""
3200
    mapslices(f, A; dims)
3201

3202
Transform the given dimensions of array `A` by applying a function `f` on each slice
3203
of the form `A[..., :, ..., :, ...]`, with a colon at each `d` in `dims`. The results are
3204
concatenated along the remaining dimensions.
3205

3206
For example, if `dims = [1,2]` and `A` is 4-dimensional, then `f` is called on `x = A[:,:,i,j]`
3207
for all `i` and `j`, and `f(x)` becomes `R[:,:,i,j]` in the result `R`.
3208

3209
See also [`eachcol`](@ref) or [`eachslice`](@ref), used with [`map`](@ref) or [`stack`](@ref).
3210

3211
# Examples
3212
```jldoctest
3213
julia> A = reshape(1:30,(2,5,3))
3214
2×5×3 reshape(::UnitRange{$Int}, 2, 5, 3) with eltype $Int:
3215
[:, :, 1] =
3216
 1  3  5  7   9
3217
 2  4  6  8  10
3218

3219
[:, :, 2] =
3220
 11  13  15  17  19
3221
 12  14  16  18  20
3222

3223
[:, :, 3] =
3224
 21  23  25  27  29
3225
 22  24  26  28  30
3226

3227
julia> f(x::Matrix) = fill(x[1,1], 1,4);  # returns a 1×4 matrix
3228

3229
julia> B = mapslices(f, A, dims=(1,2))
3230
1×4×3 Array{$Int, 3}:
3231
[:, :, 1] =
3232
 1  1  1  1
3233

3234
[:, :, 2] =
3235
 11  11  11  11
3236

3237
[:, :, 3] =
3238
 21  21  21  21
3239

3240
julia> f2(x::AbstractMatrix) = fill(x[1,1], 1,4);
3241

3242
julia> B == stack(f2, eachslice(A, dims=3))
3243
true
3244

3245
julia> g(x) = x[begin] // x[end-1];  # returns a number
3246

3247
julia> mapslices(g, A, dims=[1,3])
3248
1×5×1 Array{Rational{$Int}, 3}:
3249
[:, :, 1] =
3250
 1//21  3//23  1//5  7//27  9//29
3251

3252
julia> map(g, eachslice(A, dims=2))
3253
5-element Vector{Rational{$Int}}:
3254
 1//21
3255
 3//23
3256
 1//5
3257
 7//27
3258
 9//29
3259

3260
julia> mapslices(sum, A; dims=(1,3)) == sum(A; dims=(1,3))
3261
true
3262
```
3263

3264
Notice that in `eachslice(A; dims=2)`, the specified dimension is the
3265
one *without* a colon in the slice. This is `view(A,:,i,:)`, whereas
3266
`mapslices(f, A; dims=(1,3))` uses `A[:,i,:]`. The function `f` may mutate
3267
values in the slice without affecting `A`.
3268
"""
3269
@constprop :aggressive function mapslices(f, A::AbstractArray; dims)
×
UNCOV
3270
    isempty(dims) && return map(f, A)
×
3271

3272
    for d in dims
×
3273
        d isa Integer || throw(ArgumentError("mapslices: dimension must be an integer, got $d"))
×
UNCOV
3274
        d >= 1 || throw(ArgumentError("mapslices: dimension must be ≥ 1, got $d"))
×
3275
        # Indexing a matrix M[:,1,:] produces a 1-column matrix, but dims=(1,3) here
3276
        # would otherwise ignore 3, and slice M[:,i]. Previously this gave error:
3277
        # BoundsError: attempt to access 2-element Vector{Any} at index [3]
3278
        d > ndims(A) && throw(ArgumentError("mapslices does not accept dimensions > ndims(A) = $(ndims(A)), got $d"))
×
3279
    end
×
UNCOV
3280
    dim_mask = ntuple(d -> d in dims, ndims(A))
×
3281

3282
    # Apply the function to the first slice in order to determine the next steps
3283
    idx1 = ntuple(d -> d in dims ? (:) : firstindex(A,d), ndims(A))
×
3284
    Aslice = A[idx1...]
×
UNCOV
3285
    r1 = f(Aslice)
×
3286

3287
    res1 = if r1 isa AbstractArray && ndims(r1) > 0
×
3288
        n = sum(dim_mask)
×
3289
        if ndims(r1) > n && any(ntuple(d -> size(r1,d+n)>1, ndims(r1)-n))
×
3290
            s = size(r1)[1:n]
×
UNCOV
3291
            throw(DimensionMismatch("mapslices cannot assign slice f(x) of size $(size(r1)) into output of size $s"))
×
3292
        end
UNCOV
3293
        r1
×
3294
    else
3295
        # If the result of f on a single slice is a scalar then we add singleton
3296
        # dimensions. When adding the dimensions, we have to respect the
3297
        # index type of the input array (e.g. in the case of OffsetArrays)
3298
        _res1 = similar(Aslice, typeof(r1), reduced_indices(Aslice, 1:ndims(Aslice)))
×
3299
        _res1[begin] = r1
×
UNCOV
3300
        _res1
×
3301
    end
3302

3303
    # Determine result size and allocate. We always pad ndims(res1) out to length(dims):
3304
    din = Ref(0)
×
3305
    Rsize = ntuple(ndims(A)) do d
×
3306
        if d in dims
×
UNCOV
3307
            axes(res1, din[] += 1)
×
3308
        else
UNCOV
3309
            axes(A,d)
×
3310
        end
3311
    end
UNCOV
3312
    R = similar(res1, Rsize)
×
3313

3314
    # Determine iteration space. It will be convenient in the loop to mask N-dimensional
3315
    # CartesianIndices, with some trivial dimensions:
3316
    itershape = ntuple(d -> d in dims ? Base.OneTo(1) : axes(A,d), ndims(A))
×
UNCOV
3317
    indices = Iterators.drop(CartesianIndices(itershape), 1)
×
3318

3319
    # That skips the first element, which we already have:
3320
    ridx = ntuple(d -> d in dims ? Slice(axes(R,d)) : firstindex(A,d), ndims(A))
×
UNCOV
3321
    concatenate_setindex!(R, res1, ridx...)
×
3322

3323
    # In some cases, we can re-use the first slice for a dramatic performance
3324
    # increase. The slice itself must be mutable and the result cannot contain
3325
    # any mutable containers. The following errs on the side of being overly
3326
    # strict (#18570 & #21123).
UNCOV
3327
    safe_for_reuse = isa(Aslice, StridedArray) &&
×
3328
                     (isa(r1, Number) || (isa(r1, AbstractArray) && eltype(r1) <: Number))
3329

3330
    _inner_mapslices!(R, indices, f, A, dim_mask, Aslice, safe_for_reuse)
×
UNCOV
3331
    return R
×
3332
end
3333

3334
@noinline function _inner_mapslices!(R, indices, f, A, dim_mask, Aslice, safe_for_reuse)
×
3335
    must_extend = any(dim_mask .& size(R) .> 1)
×
UNCOV
3336
    if safe_for_reuse
×
3337
        # when f returns an array, R[ridx...] = f(Aslice) line copies elements,
3338
        # so we can reuse Aslice
3339
        for I in indices
×
3340
            idx = ifelse.(dim_mask, Slice.(axes(A)), Tuple(I))
×
3341
            _unsafe_getindex!(Aslice, A, idx...)
×
3342
            r = f(Aslice)
×
3343
            if r isa AbstractArray || must_extend
×
3344
                ridx = ifelse.(dim_mask, Slice.(axes(R)), Tuple(I))
×
UNCOV
3345
                R[ridx...] = r
×
3346
            else
3347
                ridx = ifelse.(dim_mask, first.(axes(R)), Tuple(I))
×
UNCOV
3348
                R[ridx...] = r
×
3349
            end
UNCOV
3350
        end
×
3351
    else
3352
        # we can't guarantee safety (#18524), so allocate new storage for each slice
3353
        for I in indices
×
3354
            idx = ifelse.(dim_mask, Slice.(axes(A)), Tuple(I))
×
3355
            ridx = ifelse.(dim_mask, Slice.(axes(R)), Tuple(I))
×
3356
            concatenate_setindex!(R, f(A[idx...]), ridx...)
×
UNCOV
3357
        end
×
3358
    end
3359
end
3360

3361
concatenate_setindex!(R, v, I...) = (R[I...] .= (v,); R)
×
UNCOV
3362
concatenate_setindex!(R, X::AbstractArray, I...) = (R[I...] = X)
×
3363

3364
## 1 argument
3365

3366
function map!(f::F, dest::AbstractArray, A::AbstractArray) where F
542,476✔
3367
    for (i,j) in zip(eachindex(dest),eachindex(A))
4,743,337✔
3368
        val = f(@inbounds A[j])
4,544,495✔
3369
        @inbounds dest[i] = val
3,444,101✔
3370
    end
4,243,836✔
3371
    return dest
2,779,833✔
3372
end
3373

3374
# map on collections
3375
map(f, A::AbstractArray) = collect_similar(A, Generator(f,A))
219✔
3376

3377
mapany(f, A::AbstractArray) = map!(f, Vector{Any}(undef, length(A)), A)
4✔
UNCOV
3378
mapany(f, itr) = Any[f(x) for x in itr]
×
3379

3380
"""
3381
    map(f, c...) -> collection
3382

3383
Transform collection `c` by applying `f` to each element. For multiple collection arguments,
3384
apply `f` elementwise, and stop when any of them is exhausted.
3385

3386
The element type of the result is determined in the same manner as in [`collect`](@ref).
3387

3388
See also [`map!`](@ref), [`foreach`](@ref), [`mapreduce`](@ref), [`mapslices`](@ref), [`zip`](@ref), [`Iterators.map`](@ref).
3389

3390
# Examples
3391
```jldoctest
3392
julia> map(x -> x * 2, [1, 2, 3])
3393
3-element Vector{Int64}:
3394
 2
3395
 4
3396
 6
3397

3398
julia> map(+, [1, 2, 3], [10, 20, 30, 400, 5000])
3399
3-element Vector{Int64}:
3400
 11
3401
 22
3402
 33
3403
```
3404
"""
3405
map(f, A) = collect(Generator(f,A)) # default to returning an Array for `map` on general iterators
1✔
3406

3407
map(f, ::AbstractDict) = error("map is not defined on dictionaries")
×
UNCOV
3408
map(f, ::AbstractSet) = error("map is not defined on sets")
×
3409

3410
## 2 argument
3411
function map!(f::F, dest::AbstractArray, A::AbstractArray, B::AbstractArray) where F
×
3412
    for (i, j, k) in zip(eachindex(dest), eachindex(A), eachindex(B))
×
3413
        @inbounds a, b = A[j], B[k]
×
3414
        val = f(a, b)
×
3415
        @inbounds dest[i] = val
×
3416
    end
×
UNCOV
3417
    return dest
×
3418
end
3419

3420
## N argument
3421

3422
@inline ith_all(i, ::Tuple{}) = ()
×
3423
function ith_all(i, as)
×
3424
    @_propagate_inbounds_meta
×
UNCOV
3425
    return (as[1][i], ith_all(i, tail(as))...)
×
3426
end
3427

3428
function map_n!(f::F, dest::AbstractArray, As) where F
×
3429
    idxs = LinearIndices(dest)
×
3430
    if all(x -> LinearIndices(x) == idxs, As)
×
3431
        for i in idxs
×
3432
            @inbounds as = ith_all(i, As)
×
3433
            val = f(as...)
×
3434
            @inbounds dest[i] = val
×
UNCOV
3435
        end
×
3436
    else
3437
        for (i, Is...) in zip(eachindex(dest), map(eachindex, As)...)
×
3438
            as = ntuple(j->getindex(As[j], Is[j]), length(As))
×
3439
            val = f(as...)
×
3440
            dest[i] = val
×
UNCOV
3441
        end
×
3442
    end
UNCOV
3443
    return dest
×
3444
end
3445

3446
"""
3447
    map!(function, destination, collection...)
3448

3449
Like [`map`](@ref), but stores the result in `destination` rather than a new
3450
collection. `destination` must be at least as large as the smallest collection.
3451

3452
$(_DOCS_ALIASING_WARNING)
3453

3454
See also: [`map`](@ref), [`foreach`](@ref), [`zip`](@ref), [`copyto!`](@ref).
3455

3456
# Examples
3457
```jldoctest
3458
julia> a = zeros(3);
3459

3460
julia> map!(x -> x * 2, a, [1, 2, 3]);
3461

3462
julia> a
3463
3-element Vector{Float64}:
3464
 2.0
3465
 4.0
3466
 6.0
3467

3468
julia> map!(+, zeros(Int, 5), 100:999, 1:3)
3469
5-element Vector{$(Int)}:
3470
 101
3471
 103
3472
 105
3473
   0
3474
   0
3475
```
3476
"""
3477
function map!(f::F, dest::AbstractArray, As::AbstractArray...) where {F}
×
3478
    @assert !isempty(As) # should dispatch to map!(f, A)
×
UNCOV
3479
    map_n!(f, dest, As)
×
3480
end
3481

3482
"""
3483
    map!(function, array)
3484

3485
Like [`map`](@ref), but stores the result in the same array.
3486
!!! compat "Julia 1.12"
3487
    This method requires Julia 1.12 or later. To support previous versions too,
3488
    use the equivalent `map!(function, array, array)`.
3489

3490
# Examples
3491
```jldoctest
3492
julia> a = [1 2 3; 4 5 6];
3493

3494
julia> map!(x -> x^3, a);
3495

3496
julia> a
3497
2×3 Matrix{$Int}:
3498
  1    8   27
3499
 64  125  216
3500
```
3501
"""
UNCOV
3502
map!(f::F, inout::AbstractArray) where F = map!(f, inout, inout)
×
3503

3504
"""
3505
    map(f, A::AbstractArray...) -> N-array
3506

3507
When acting on multi-dimensional arrays of the same [`ndims`](@ref),
3508
they must all have the same [`axes`](@ref), and the answer will too.
3509

3510
See also [`broadcast`](@ref), which allows mismatched sizes.
3511

3512
# Examples
3513
```
3514
julia> map(//, [1 2; 3 4], [4 3; 2 1])
3515
2×2 Matrix{Rational{$Int}}:
3516
 1//4  2//3
3517
 3//2  4//1
3518

3519
julia> map(+, [1 2; 3 4], zeros(2,1))
3520
ERROR: DimensionMismatch
3521

3522
julia> map(+, [1 2; 3 4], [1,10,100,1000], zeros(3,1))  # iterates until 3rd is exhausted
3523
3-element Vector{Float64}:
3524
   2.0
3525
  13.0
3526
 102.0
3527
```
3528
"""
UNCOV
3529
map(f, it, iters...) = collect(Generator(f, it, iters...))
×
3530

3531
# Generic versions of push! for AbstractVector
3532
# These are specialized further for Vector for faster resizing and setindexing
UNCOV
3533
function push!(a::AbstractVector{T}, item) where T
×
3534
    # convert first so we don't grow the array if the assignment won't work
3535
    itemT = item isa T ? item : convert(T, item)::T
×
3536
    new_length = length(a) + 1
×
3537
    resize!(a, new_length)
×
3538
    a[end] = itemT
×
UNCOV
3539
    return a
×
3540
end
3541

3542
# specialize and optimize the single argument case
3543
function push!(a::AbstractVector{Any}, @nospecialize x)
×
3544
    new_length = length(a) + 1
×
3545
    resize!(a, new_length)
×
3546
    a[end] = x
×
UNCOV
3547
    return a
×
3548
end
3549
function push!(a::AbstractVector{Any}, @nospecialize x...)
×
3550
    @_terminates_locally_meta
×
3551
    na = length(a)
×
3552
    nx = length(x)
×
3553
    resize!(a, na + nx)
×
3554
    e = lastindex(a) - nx
×
3555
    for i = 1:nx
×
3556
        a[e+i] = x[i]
×
3557
    end
×
UNCOV
3558
    return a
×
3559
end
3560

3561
# multi-item push!, pushfirst! (built on top of type-specific 1-item version)
3562
# (note: must not cause a dispatch loop when 1-item case is not defined)
3563
push!(A, a, b) = push!(push!(A, a), b)
×
3564
push!(A, a, b, c...) = push!(push!(A, a, b), c...)
×
3565
pushfirst!(A, a, b) = pushfirst!(pushfirst!(A, b), a)
×
UNCOV
3566
pushfirst!(A, a, b, c...) = pushfirst!(pushfirst!(A, c...), a, b)
×
3567

3568
# sizehint! does not nothing by default
UNCOV
3569
sizehint!(a::AbstractVector, _) = a
×
3570

3571
# The semantics of `collect` are weird. Better to write our own
3572
function rest(a::AbstractArray{T}, state...) where {T}
×
UNCOV
3573
    v = Vector{T}(undef, 0)
×
3574
    # assume only very few items are taken from the front
3575
    sizehint!(v, length(a))
×
UNCOV
3576
    return foldl(push!, Iterators.rest(a, state...), init=v)
×
3577
end
3578

3579
## keepat! ##
3580

3581
# NOTE: since these use `@inbounds`, they are actually only intended for Vector and BitVector
3582

3583
function _keepat!(a::AbstractVector, inds)
×
3584
    local prev
×
3585
    i = firstindex(a)
×
3586
    for k in inds
×
3587
        if @isdefined(prev)
×
UNCOV
3588
            prev < k || throw(ArgumentError("indices must be unique and sorted"))
×
3589
        end
3590
        ak = a[k] # must happen even when i==k for bounds checking
×
3591
        if i != k
×
UNCOV
3592
            @inbounds a[i] = ak # k > i, so a[i] is inbounds
×
3593
        end
3594
        prev = k
×
3595
        i = nextind(a, i)
×
3596
    end
×
3597
    deleteat!(a, i:lastindex(a))
×
UNCOV
3598
    return a
×
3599
end
3600

3601
function _keepat!(a::AbstractVector, m::AbstractVector{Bool})
×
3602
    length(m) == length(a) || throw(BoundsError(a, m))
×
3603
    j = firstindex(a)
×
3604
    for i in eachindex(a, m)
×
3605
        @inbounds begin
×
3606
            if m[i]
×
3607
                i == j || (a[j] = a[i])
×
UNCOV
3608
                j = nextind(a, j)
×
3609
            end
3610
        end
3611
    end
×
UNCOV
3612
    deleteat!(a, j:lastindex(a))
×
3613
end
3614

3615
"""
3616
    circshift!(a::AbstractVector, shift::Integer)
3617

3618
Circularly shift, or rotate, the data in vector `a` by `shift` positions.
3619

3620
# Examples
3621

3622
```jldoctest
3623
julia> circshift!([1, 2, 3, 4, 5], 2)
3624
5-element Vector{Int64}:
3625
 4
3626
 5
3627
 1
3628
 2
3629
 3
3630

3631
julia> circshift!([1, 2, 3, 4, 5], -2)
3632
5-element Vector{Int64}:
3633
 3
3634
 4
3635
 5
3636
 1
3637
 2
3638
```
3639
"""
3640
function circshift!(a::AbstractVector, shift::Integer)
×
3641
    n = length(a)
×
3642
    n == 0 && return a
×
3643
    shift = mod(shift, n)
×
3644
    shift == 0 && return a
×
3645
    l = lastindex(a)
×
3646
    reverse!(a, firstindex(a), l-shift)
×
3647
    reverse!(a, l-shift+1, lastindex(a))
×
3648
    reverse!(a)
×
UNCOV
3649
    return a
×
3650
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