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

JuliaLang / julia / #37442

pending completion
#37442

push

local

web-flow
Inference: more thorough `UnionAll` renaming in `apply_type_tfunc` (#48662)

17 of 17 new or added lines in 1 file covered. (100.0%)

70703 of 82352 relevant lines covered (85.85%)

32294788.99 hits per line

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

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

3
## array.jl: Dense arrays
4

5
"""
6
    DimensionMismatch([msg])
7

8
The objects called do not have matching dimensionality. Optional argument `msg` is a
9
descriptive error string.
10
"""
11
struct DimensionMismatch <: Exception
12
    msg::String
13,129✔
13
end
14
DimensionMismatch() = DimensionMismatch("")
8✔
15

16
## Type aliases for convenience ##
17
"""
18
    AbstractVector{T}
19

20
Supertype for one-dimensional arrays (or array-like types) with
21
elements of type `T`. Alias for [`AbstractArray{T,1}`](@ref).
22
"""
23
const AbstractVector{T} = AbstractArray{T,1}
24

25
"""
26
    AbstractMatrix{T}
27

28
Supertype for two-dimensional arrays (or array-like types) with
29
elements of type `T`. Alias for [`AbstractArray{T,2}`](@ref).
30
"""
31
const AbstractMatrix{T} = AbstractArray{T,2}
32

33
"""
34
    AbstractVecOrMat{T}
35

36
Union type of [`AbstractVector{T}`](@ref) and [`AbstractMatrix{T}`](@ref).
37
"""
38
const AbstractVecOrMat{T} = Union{AbstractVector{T}, AbstractMatrix{T}}
39
const RangeIndex = Union{<:BitInteger, AbstractRange{<:BitInteger}}
40
const DimOrInd = Union{Integer, AbstractUnitRange}
41
const IntOrInd = Union{Int, AbstractUnitRange}
42
const DimsOrInds{N} = NTuple{N,DimOrInd}
43
const NeedsShaping = Union{Tuple{Integer,Vararg{Integer}}, Tuple{OneTo,Vararg{OneTo}}}
44

45
"""
46
    Array{T,N} <: AbstractArray{T,N}
47

48
`N`-dimensional dense array with elements of type `T`.
49
"""
50
Array
51

52
"""
53
    Vector{T} <: AbstractVector{T}
54

55
One-dimensional dense array with elements of type `T`, often used to represent
56
a mathematical vector. Alias for [`Array{T,1}`](@ref).
57

58
See also [`empty`](@ref), [`similar`](@ref) and [`zero`](@ref) for creating vectors.
59
"""
60
const Vector{T} = Array{T,1}
61

62
"""
63
    Matrix{T} <: AbstractMatrix{T}
64

65
Two-dimensional dense array with elements of type `T`, often used to represent
66
a mathematical matrix. Alias for [`Array{T,2}`](@ref).
67

68
See also [`fill`](@ref), [`zeros`](@ref), [`undef`](@ref) and [`similar`](@ref)
69
for creating matrices.
70
"""
71
const Matrix{T} = Array{T,2}
72

73
"""
74
    VecOrMat{T}
75

76
Union type of [`Vector{T}`](@ref) and [`Matrix{T}`](@ref) which allows functions to accept either a Matrix or a Vector.
77

78
# Examples
79
```jldoctest
80
julia> Vector{Float64} <: VecOrMat{Float64}
81
true
82

83
julia> Matrix{Float64} <: VecOrMat{Float64}
84
true
85

86
julia> Array{Float64, 3} <: VecOrMat{Float64}
87
false
88
```
89
"""
90
const VecOrMat{T} = Union{Vector{T}, Matrix{T}}
91

92
"""
93
    DenseArray{T, N} <: AbstractArray{T,N}
94

95
`N`-dimensional dense array with elements of type `T`.
96
The elements of a dense array are stored contiguously in memory.
97
"""
98
DenseArray
99

100
"""
101
    DenseVector{T}
102

103
One-dimensional [`DenseArray`](@ref) with elements of type `T`. Alias for `DenseArray{T,1}`.
104
"""
105
const DenseVector{T} = DenseArray{T,1}
106

107
"""
108
    DenseMatrix{T}
109

110
Two-dimensional [`DenseArray`](@ref) with elements of type `T`. Alias for `DenseArray{T,2}`.
111
"""
112
const DenseMatrix{T} = DenseArray{T,2}
113

114
"""
115
    DenseVecOrMat{T}
116

117
Union type of [`DenseVector{T}`](@ref) and [`DenseMatrix{T}`](@ref).
118
"""
119
const DenseVecOrMat{T} = Union{DenseVector{T}, DenseMatrix{T}}
120

121
## Basic functions ##
122

123
using Core: arraysize, arrayset, const_arrayref
124

125
vect() = Vector{Any}()
21,550,783✔
126
vect(X::T...) where {T} = T[ X[i] for i = 1:length(X) ]
1,232,979✔
127

128
"""
129
    vect(X...)
130

131
Create a [`Vector`](@ref) with element type computed from the `promote_typeof` of the argument,
132
containing the argument list.
133

134
# Examples
135
```jldoctest
136
julia> a = Base.vect(UInt8(1), 2.5, 1//2)
137
3-element Vector{Float64}:
138
 1.0
139
 2.5
140
 0.5
141
```
142
"""
143
function vect(X...)
1,972✔
144
    T = promote_typeof(X...)
1,972✔
145
    return T[X...]
2,201✔
146
end
147

148
size(a::Array, d::Integer) = arraysize(a, convert(Int, d))
3,995,764✔
149
size(a::Vector) = (arraysize(a,1),)
5,186,540,097✔
150
size(a::Matrix) = (arraysize(a,1), arraysize(a,2))
7,986,793✔
151
size(a::Array{<:Any,N}) where {N} = (@inline; ntuple(M -> size(a, M), Val(N))::Dims)
2,738,923✔
152

153
asize_from(a::Array, n) = n > ndims(a) ? () : (arraysize(a,n), asize_from(a, n+1)...)
×
154

155
allocatedinline(@nospecialize T::Type) = (@_total_meta; ccall(:jl_stored_inline, Cint, (Any,), T) != Cint(0))
2,474,875✔
156

157
"""
158
    Base.isbitsunion(::Type{T})
159

160
Return whether a type is an "is-bits" Union type, meaning each type included in a Union is [`isbitstype`](@ref).
161

162
# Examples
163
```jldoctest
164
julia> Base.isbitsunion(Union{Float64, UInt8})
165
true
166

167
julia> Base.isbitsunion(Union{Float64, String})
168
false
169
```
170
"""
171
isbitsunion(u::Union) = allocatedinline(u)
3,462✔
172
isbitsunion(x) = false
12,388✔
173

174
function _unsetindex!(A::Array{T}, i::Int) where {T}
49,096✔
175
    @inline
1,533✔
176
    @boundscheck checkbounds(A, i)
3,097,430✔
177
    t = @_gc_preserve_begin A
3,097,479✔
178
    p = Ptr{Ptr{Cvoid}}(pointer(A, i))
3,096,815✔
179
    if !allocatedinline(T)
1,533✔
180
        unsafe_store!(p, C_NULL)
2,851,381✔
181
    elseif T isa DataType
247,050✔
182
        if !datatype_pointerfree(T)
1,181✔
183
            for j = 1:(Core.sizeof(T) ÷ Core.sizeof(Ptr{Cvoid}))
1,119✔
184
                unsafe_store!(p, C_NULL, j)
2,832✔
185
            end
4,545✔
186
        end
187
    end
188
    @_gc_preserve_end t
3,098,266✔
189
    return A
3,097,720✔
190
end
191

192

193
"""
194
    Base.bitsunionsize(U::Union) -> Int
195

196
For a `Union` of [`isbitstype`](@ref) types, return the size of the largest type; assumes `Base.isbitsunion(U) == true`.
197

198
# Examples
199
```jldoctest
200
julia> Base.bitsunionsize(Union{Float64, UInt8})
201
8
202

203
julia> Base.bitsunionsize(Union{Float64, UInt8, Int128})
204
16
205
```
206
"""
207
function bitsunionsize(u::Union)
4✔
208
    isinline, sz, _ = uniontype_layout(u)
4✔
209
    @assert isinline
4✔
210
    return sz
4✔
211
end
212

213
elsize(@nospecialize _::Type{A}) where {T,A<:Array{T}} = aligned_sizeof(T)
1,719,664✔
214
sizeof(a::Array) = Core.sizeof(a)
3,495,779✔
215

216
function isassigned(a::Array, i::Int...)
3,283,531✔
217
    @inline
2,472,116✔
218
    @boundscheck checkbounds(Bool, a, i...) || return false
1,949,587,569✔
219
    ii = (_sub2ind(size(a), i...) % UInt) - 1
1,895,181,078✔
220
    ccall(:jl_array_isassigned, Cint, (Any, UInt), a, ii) == 1
1,949,194,811✔
221
end
222

223
## copy ##
224

225
"""
226
    unsafe_copyto!(dest::Ptr{T}, src::Ptr{T}, N)
227

228
Copy `N` elements from a source pointer to a destination, with no checking. The size of an
229
element is determined by the type of the pointers.
230

231
The `unsafe` prefix on this function indicates that no validation is performed on the
232
pointers `dest` and `src` to ensure that they are valid. Incorrect usage may corrupt or
233
segfault your program, in the same manner as C.
234
"""
235
function unsafe_copyto!(dest::Ptr{T}, src::Ptr{T}, n) where T
2,180,052✔
236
    # Do not use this to copy data between pointer arrays.
237
    # It can't be made safe no matter how carefully you checked.
238
    ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
15,702,703✔
239
          dest, src, n * aligned_sizeof(T))
240
    return dest
15,040,757✔
241
end
242

243

244
function _unsafe_copyto!(dest, doffs, src, soffs, n)
23,162,169✔
245
    destp = pointer(dest, doffs)
23,162,169✔
246
    srcp = pointer(src, soffs)
23,162,169✔
247
    @inbounds if destp < srcp || destp > srcp + n
37,717,787✔
248
        for i = 1:n
46,324,336✔
249
            if isassigned(src, soffs + i - 1)
122,701,862✔
250
                dest[doffs + i - 1] = src[soffs + i - 1]
122,701,306✔
251
            else
252
                _unsetindex!(dest, doffs + i - 1)
720✔
253
            end
254
        end
222,241,316✔
255
    else
256
        for i = n:-1:1
×
257
            if isassigned(src, soffs + i - 1)
×
258
                dest[doffs + i - 1] = src[soffs + i - 1]
×
259
            else
260
                _unsetindex!(dest, doffs + i - 1)
×
261
            end
262
        end
×
263
    end
264
    return dest
23,161,928✔
265
end
266

267
"""
268
    unsafe_copyto!(dest::Array, do, src::Array, so, N)
269

270
Copy `N` elements from a source array to a destination, starting at offset `so` in the
271
source and `do` in the destination (1-indexed).
272

273
The `unsafe` prefix on this function indicates that no validation is performed to ensure
274
that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in
275
the same manner as C.
276
"""
277
function unsafe_copyto!(dest::Array{T}, doffs, src::Array{T}, soffs, n) where T
3,939,504✔
278
    t1 = @_gc_preserve_begin dest
116,858,897✔
279
    t2 = @_gc_preserve_begin src
116,858,897✔
280
    destp = pointer(dest, doffs)
116,858,897✔
281
    srcp = pointer(src, soffs)
116,858,908✔
282
    if !allocatedinline(T)
3,939,422✔
283
        ccall(:jl_array_ptr_copy, Cvoid, (Any, Ptr{Cvoid}, Any, Ptr{Cvoid}, Int),
60,082,366✔
284
              dest, destp, src, srcp, n)
285
    elseif isbitstype(T)
1,919,275✔
286
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
38,589,874✔
287
              destp, srcp, n * aligned_sizeof(T))
288
    elseif isbitsunion(T)
6,662✔
289
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
923✔
290
              destp, srcp, n * aligned_sizeof(T))
291
        # copy selector bytes
292
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
923✔
293
              ccall(:jl_array_typetagdata, Ptr{UInt8}, (Any,), dest) + doffs - 1,
294
              ccall(:jl_array_typetagdata, Ptr{UInt8}, (Any,), src) + soffs - 1,
295
              n)
296
    else
297
        _unsafe_copyto!(dest, doffs, src, soffs, n)
18,185,745✔
298
    end
299
    @_gc_preserve_end t2
116,858,897✔
300
    @_gc_preserve_end t1
116,858,897✔
301
    return dest
40,616,507✔
302
end
303

304
unsafe_copyto!(dest::Array, doffs, src::Array, soffs, n) =
4,976,424✔
305
    _unsafe_copyto!(dest, doffs, src, soffs, n)
306

307
"""
308
    copyto!(dest, do, src, so, N)
309

310
Copy `N` elements from collection `src` starting at offset `so`, to array `dest` starting at
311
offset `do`. Return `dest`.
312
"""
313
function copyto!(dest::Array, doffs::Integer, src::Array, soffs::Integer, n::Integer)
34,133✔
314
    return _copyto_impl!(dest, doffs, src, soffs, n)
9,953,845✔
315
end
316

317
# this is only needed to avoid possible ambiguities with methods added in some packages
318
function copyto!(dest::Array{T}, doffs::Integer, src::Array{T}, soffs::Integer, n::Integer) where T
1,014,802✔
319
    return _copyto_impl!(dest, doffs, src, soffs, n)
158,899,461✔
320
end
321

322
function _copyto_impl!(dest::Array, doffs::Integer, src::Array, soffs::Integer, n::Integer)
121,892,890✔
323
    n == 0 && return dest
145,689,923✔
324
    n > 0 || _throw_argerror()
117,137,014✔
325
    @boundscheck checkbounds(dest, doffs:doffs+n-1)
117,137,033✔
326
    @boundscheck checkbounds(src, soffs:soffs+n-1)
117,136,994✔
327
    unsafe_copyto!(dest, doffs, src, soffs, n)
117,136,988✔
328
    return dest
117,136,747✔
329
end
330

331
# Outlining this because otherwise a catastrophic inference slowdown
332
# occurs, see discussion in #27874.
333
# It is also mitigated by using a constant string.
334
function _throw_argerror()
3,007✔
335
    @noinline
×
336
    throw(ArgumentError("Number of elements to copy must be nonnegative."))
3,007✔
337
end
338

339
copyto!(dest::Array, src::Array) = copyto!(dest, 1, src, 1, length(src))
9,946,580✔
340

341
# also to avoid ambiguities in packages
342
copyto!(dest::Array{T}, src::Array{T}) where {T} = copyto!(dest, 1, src, 1, length(src))
45,280,047✔
343

344
# N.B: The generic definition in multidimensional.jl covers, this, this is just here
345
# for bootstrapping purposes.
346
function fill!(dest::Array{T}, x) where T
418,958✔
347
    xT = convert(T, x)
415,200✔
348
    for i in eachindex(dest)
806,309,018✔
349
        @inbounds dest[i] = xT
4,764,469,045✔
350
    end
9,354,905,359✔
351
    return dest
632,276,287✔
352
end
353

354
"""
355
    copy(x)
356

357
Create a shallow copy of `x`: the outer structure is copied, but not all internal values.
358
For example, copying an array produces a new array with identically-same elements as the
359
original.
360

361
See also [`copy!`](@ref Base.copy!), [`copyto!`](@ref), [`deepcopy`](@ref).
362
"""
363
copy
364

365
copy(a::T) where {T<:Array} = ccall(:jl_array_copy, Ref{T}, (Any,), a)
96,468,934✔
366

367
## Constructors ##
368

369
similar(a::Array{T,1}) where {T}                    = Vector{T}(undef, size(a,1))
7,273✔
370
similar(a::Array{T,2}) where {T}                    = Matrix{T}(undef, size(a,1), size(a,2))
3,979✔
371
similar(a::Array{T,1}, S::Type) where {T}           = Vector{S}(undef, size(a,1))
7,803✔
372
similar(a::Array{T,2}, S::Type) where {T}           = Matrix{S}(undef, size(a,1), size(a,2))
18,602✔
373
similar(a::Array{T}, m::Int) where {T}              = Vector{T}(undef, m)
1,620,236✔
374
similar(a::Array, T::Type, dims::Dims{N}) where {N} = Array{T,N}(undef, dims)
51,622,125✔
375
similar(a::Array{T}, dims::Dims{N}) where {T,N}     = Array{T,N}(undef, dims)
430✔
376

377
# T[x...] constructs Array{T,1}
378
"""
379
    getindex(type[, elements...])
380

381
Construct a 1-d array of the specified type. This is usually called with the syntax
382
`Type[]`. Element values can be specified using `Type[a,b,c,...]`.
383

384
# Examples
385
```jldoctest
386
julia> Int8[1, 2, 3]
387
3-element Vector{Int8}:
388
 1
389
 2
390
 3
391

392
julia> getindex(Int8, 1, 2, 3)
393
3-element Vector{Int8}:
394
 1
395
 2
396
 3
397
```
398
"""
399
function getindex(::Type{T}, vals...) where T
191,658✔
400
    a = Vector{T}(undef, length(vals))
581,166,451✔
401
    if vals isa NTuple
49,719✔
402
        @inbounds for i in 1:length(vals)
21,196,231✔
403
            a[i] = vals[i]
21,245,566✔
404
        end
175,183✔
405
    else
406
        # use afoldl to avoid type instability inside loop
407
        afoldl(1, vals...) do i, v
3,117✔
408
            @inbounds a[i] = v
9,704✔
409
            return i + 1
8,294✔
410
        end
411
    end
412
    return a
21,195,476✔
413
end
414

415
function getindex(::Type{Any}, @nospecialize vals...)
20,009,086✔
416
    a = Vector{Any}(undef, length(vals))
45,648,611✔
417
    @inbounds for i = 1:length(vals)
60,535,154✔
418
        a[i] = vals[i]
86,075,879✔
419
    end
100,722,180✔
420
    return a
45,648,611✔
421
end
422
getindex(::Type{Any}) = Vector{Any}()
26,518,051✔
423

424
function fill!(a::Union{Array{UInt8}, Array{Int8}}, x::Integer)
11,072✔
425
    ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), a, convert(eltype(a), x), length(a))
140,172,209✔
426
    return a
140,172,203✔
427
end
428

429
to_dim(d::Integer) = d
×
430
to_dim(d::OneTo) = last(d)
376✔
431

432
"""
433
    fill(value, dims::Tuple)
434
    fill(value, dims...)
435

436
Create an array of size `dims` with every location set to `value`.
437

438
For example, `fill(1.0, (5,5))` returns a 5×5 array of floats,
439
with `1.0` in every location of the array.
440

441
The dimension lengths `dims` may be specified as either a tuple or a sequence of arguments.
442
An `N`-length tuple or `N` arguments following the `value` specify an `N`-dimensional
443
array. Thus, a common idiom for creating a zero-dimensional array with its only location
444
set to `x` is `fill(x)`.
445

446
Every location of the returned array is set to (and is thus [`===`](@ref) to)
447
the `value` that was passed; this means that if the `value` is itself modified,
448
all elements of the `fill`ed array will reflect that modification because they're
449
_still_ that very `value`. This is of no concern with `fill(1.0, (5,5))` as the
450
`value` `1.0` is immutable and cannot itself be modified, but can be unexpected
451
with mutable values like — most commonly — arrays.  For example, `fill([], 3)`
452
places _the very same_ empty array in all three locations of the returned vector:
453

454
```jldoctest
455
julia> v = fill([], 3)
456
3-element Vector{Vector{Any}}:
457
 []
458
 []
459
 []
460

461
julia> v[1] === v[2] === v[3]
462
true
463

464
julia> value = v[1]
465
Any[]
466

467
julia> push!(value, 867_5309)
468
1-element Vector{Any}:
469
 8675309
470

471
julia> v
472
3-element Vector{Vector{Any}}:
473
 [8675309]
474
 [8675309]
475
 [8675309]
476
```
477

478
To create an array of many independent inner arrays, use a [comprehension](@ref man-comprehensions) instead.
479
This creates a new and distinct array on each iteration of the loop:
480

481
```jldoctest
482
julia> v2 = [[] for _ in 1:3]
483
3-element Vector{Vector{Any}}:
484
 []
485
 []
486
 []
487

488
julia> v2[1] === v2[2] === v2[3]
489
false
490

491
julia> push!(v2[1], 8675309)
492
1-element Vector{Any}:
493
 8675309
494

495
julia> v2
496
3-element Vector{Vector{Any}}:
497
 [8675309]
498
 []
499
 []
500
```
501

502
See also: [`fill!`](@ref), [`zeros`](@ref), [`ones`](@ref), [`similar`](@ref).
503

504
# Examples
505
```jldoctest
506
julia> fill(1.0, (2,3))
507
2×3 Matrix{Float64}:
508
 1.0  1.0  1.0
509
 1.0  1.0  1.0
510

511
julia> fill(42)
512
0-dimensional Array{Int64, 0}:
513
42
514

515
julia> A = fill(zeros(2), 2) # sets both elements to the same [0.0, 0.0] vector
516
2-element Vector{Vector{Float64}}:
517
 [0.0, 0.0]
518
 [0.0, 0.0]
519

520
julia> A[1][1] = 42; # modifies the filled value to be [42.0, 0.0]
521

522
julia> A # both A[1] and A[2] are the very same vector
523
2-element Vector{Vector{Float64}}:
524
 [42.0, 0.0]
525
 [42.0, 0.0]
526
```
527
"""
528
function fill end
529

530
fill(v, dims::DimOrInd...) = fill(v, dims)
3,240,996,666✔
531
fill(v, dims::NTuple{N, Union{Integer, OneTo}}) where {N} = fill(v, map(to_dim, dims))
×
532
fill(v, dims::NTuple{N, Integer}) where {N} = (a=Array{typeof(v),N}(undef, dims); fill!(a, v); a)
4,073,578,619✔
533
fill(v, dims::Tuple{}) = (a=Array{typeof(v),0}(undef, dims); fill!(a, v); a)
387✔
534

535
"""
536
    zeros([T=Float64,] dims::Tuple)
537
    zeros([T=Float64,] dims...)
538

539
Create an `Array`, with element type `T`, of all zeros with size specified by `dims`.
540
See also [`fill`](@ref), [`ones`](@ref), [`zero`](@ref).
541

542
# Examples
543
```jldoctest
544
julia> zeros(1)
545
1-element Vector{Float64}:
546
 0.0
547

548
julia> zeros(Int8, 2, 3)
549
2×3 Matrix{Int8}:
550
 0  0  0
551
 0  0  0
552
```
553
"""
554
function zeros end
555

556
"""
557
    ones([T=Float64,] dims::Tuple)
558
    ones([T=Float64,] dims...)
559

560
Create an `Array`, with element type `T`, of all ones with size specified by `dims`.
561
See also [`fill`](@ref), [`zeros`](@ref).
562

563
# Examples
564
```jldoctest
565
julia> ones(1,2)
566
1×2 Matrix{Float64}:
567
 1.0  1.0
568

569
julia> ones(ComplexF64, 2, 3)
570
2×3 Matrix{ComplexF64}:
571
 1.0+0.0im  1.0+0.0im  1.0+0.0im
572
 1.0+0.0im  1.0+0.0im  1.0+0.0im
573
```
574
"""
575
function ones end
576

577
for (fname, felt) in ((:zeros, :zero), (:ones, :one))
578
    @eval begin
579
        $fname(dims::DimOrInd...) = $fname(dims)
20,447,029✔
580
        $fname(::Type{T}, dims::DimOrInd...) where {T} = $fname(T, dims)
325,585,999✔
581
        $fname(dims::Tuple{Vararg{DimOrInd}}) = $fname(Float64, dims)
20,482,608✔
582
        $fname(::Type{T}, dims::NTuple{N, Union{Integer, OneTo}}) where {T,N} = $fname(T, map(to_dim, dims))
1,625✔
583
        function $fname(::Type{T}, dims::NTuple{N, Integer}) where {T,N}
365,012✔
584
            a = Array{T,N}(undef, dims)
214,411,067✔
585
            fill!(a, $felt(T))
754,451,244✔
586
            return a
214,411,067✔
587
        end
588
        function $fname(::Type{T}, dims::Tuple{}) where {T}
16✔
589
            a = Array{T}(undef)
16✔
590
            fill!(a, $felt(T))
16✔
591
            return a
16✔
592
        end
593
    end
594
end
595

596
function _one(unit::T, x::AbstractMatrix) where T
140✔
597
    require_one_based_indexing(x)
140✔
598
    m,n = size(x)
140✔
599
    m==n || throw(DimensionMismatch("multiplicative identity defined only for square matrices"))
140✔
600
    # Matrix{T}(I, m, m)
601
    I = zeros(T, m, m)
3,693✔
602
    for i in 1:m
280✔
603
        I[i,i] = unit
613✔
604
    end
1,086✔
605
    I
140✔
606
end
607

608
one(x::AbstractMatrix{T}) where {T} = _one(one(T), x)
127✔
609
oneunit(x::AbstractMatrix{T}) where {T} = _one(oneunit(T), x)
19✔
610

611
## Conversions ##
612

613
convert(::Type{T}, a::AbstractArray) where {T<:Array} = a isa T ? a : T(a)::T
191,608,836✔
614

615
promote_rule(a::Type{Array{T,n}}, b::Type{Array{S,n}}) where {T,n,S} = el_same(promote_type(T,S), a, b)
6✔
616

617
## Constructors ##
618

619
if nameof(@__MODULE__) === :Base  # avoid method overwrite
620
# constructors should make copies
621
Array{T,N}(x::AbstractArray{S,N})         where {T,N,S} = copyto_axcheck!(Array{T,N}(undef, size(x)), x)
29,751✔
622
AbstractArray{T,N}(A::AbstractArray{S,N}) where {T,N,S} = copyto_axcheck!(similar(A,T), A)
25,841✔
623
end
624

625
## copying iterators to containers
626

627
"""
628
    collect(element_type, collection)
629

630
Return an `Array` with the given element type of all items in a collection or iterable.
631
The result has the same shape and number of dimensions as `collection`.
632

633
# Examples
634
```jldoctest
635
julia> collect(Float64, 1:2:5)
636
3-element Vector{Float64}:
637
 1.0
638
 3.0
639
 5.0
640
```
641
"""
642
collect(::Type{T}, itr) where {T} = _collect(T, itr, IteratorSize(itr))
19,875,991✔
643

644
_collect(::Type{T}, itr, isz::Union{HasLength,HasShape}) where {T} =
9,881,854✔
645
    copyto!(_array_for(T, isz, _similar_shape(itr, isz)), itr)
646
function _collect(::Type{T}, itr, isz::SizeUnknown) where T
9,994,139✔
647
    a = Vector{T}()
9,994,139✔
648
    for x in itr
15,047,994✔
649
        push!(a, x)
6,403,176✔
650
    end
7,752,494✔
651
    return a
9,994,139✔
652
end
653

654
# make a collection similar to `c` and appropriate for collecting `itr`
655
_similar_for(c, ::Type{T}, itr, isz, shp) where {T} = similar(c, T)
×
656

657
_similar_shape(itr, ::SizeUnknown) = nothing
1✔
658
_similar_shape(itr, ::HasLength) = length(itr)::Integer
32,884,783✔
659
_similar_shape(itr, ::HasShape) = axes(itr)
380,441,014✔
660

661
_similar_for(c::AbstractArray, ::Type{T}, itr, ::SizeUnknown, ::Nothing) where {T} =
911,105✔
662
    similar(c, T, 0)
663
_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasLength, len::Integer) where {T} =
3,787,703✔
664
    similar(c, T, len)
665
_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasShape, axs) where {T} =
124,655✔
666
    similar(c, T, axs)
667

668
# make a collection appropriate for collecting `itr::Generator`
669
_array_for(::Type{T}, ::SizeUnknown, ::Nothing) where {T} = Vector{T}(undef, 0)
426✔
670
_array_for(::Type{T}, ::HasLength, len::Integer) where {T} = Vector{T}(undef, Int(len))
26,619,874✔
671
_array_for(::Type{T}, ::HasShape{N}, axs) where {T,N} = similar(Array{T,N}, axs)
381,610,120✔
672

673
# used by syntax lowering for simple typed comprehensions
674
_array_for(::Type{T}, itr, isz) where {T} = _array_for(T, isz, _similar_shape(itr, isz))
405,084,932✔
675

676

677
"""
678
    collect(collection)
679

680
Return an `Array` of all items in a collection or iterator. For dictionaries, returns
681
`Pair{KeyType, ValType}`. If the argument is array-like or is an iterator with the
682
[`HasShape`](@ref IteratorSize) trait, the result will have the same shape
683
and number of dimensions as the argument.
684

685
Used by comprehensions to turn a generator into an `Array`.
686

687
# Examples
688
```jldoctest
689
julia> collect(1:2:13)
690
7-element Vector{Int64}:
691
  1
692
  3
693
  5
694
  7
695
  9
696
 11
697
 13
698

699
julia> [x^2 for x in 1:8 if isodd(x)]
700
4-element Vector{Int64}:
701
  1
702
  9
703
 25
704
 49
705
```
706
"""
707
collect(itr) = _collect(1:1 #= Array =#, itr, IteratorEltype(itr), IteratorSize(itr))
4,896,086✔
708

709
collect(A::AbstractArray) = _collect_indices(axes(A), A)
134,459✔
710

711
collect_similar(cont, itr) = _collect(cont, itr, IteratorEltype(itr), IteratorSize(itr))
124,041✔
712

713
_collect(cont, itr, ::HasEltype, isz::Union{HasLength,HasShape}) =
3,985,042✔
714
    copyto!(_similar_for(cont, eltype(itr), itr, isz, _similar_shape(itr, isz)), itr)
715

716
function _collect(cont, itr, ::HasEltype, isz::SizeUnknown)
911,072✔
717
    a = _similar_for(cont, eltype(itr), itr, isz, nothing)
911,072✔
718
    for x in itr
1,821,142✔
719
        push!(a,x)
8,504,072✔
720
    end
14,490,144✔
721
    return a
911,071✔
722
end
723

724
_collect_indices(::Tuple{}, A) = copyto!(Array{eltype(A),0}(undef), A)
26✔
725
_collect_indices(indsA::Tuple{Vararg{OneTo}}, A) =
177,266✔
726
    copyto!(Array{eltype(A)}(undef, length.(indsA)), A)
727
function _collect_indices(indsA, A)
119✔
728
    B = Array{eltype(A)}(undef, length.(indsA))
119✔
729
    copyto!(B, CartesianIndices(axes(B)), A, CartesianIndices(indsA))
119✔
730
end
731

732
# NOTE: this function is not meant to be called, only inferred, for the
733
# purpose of bounding the types of values generated by an iterator.
734
function _iterator_upper_bound(itr)
2✔
735
    x = iterate(itr)
×
736
    while x !== nothing
×
737
        val = getfield(x, 1)
×
738
        if inferencebarrier(nothing)
×
739
            return val
×
740
        end
741
        x = iterate(itr, getfield(x, 2))
×
742
    end
×
743
    throw(nothing)
2✔
744
end
745

746
# define this as a macro so that the call to Core.Compiler
747
# gets inlined into the caller before recursion detection
748
# gets a chance to see it, so that recursive calls to the caller
749
# don't trigger the inference limiter
750
if isdefined(Core, :Compiler)
751
    macro default_eltype(itr)
752
        I = esc(itr)
753
        return quote
754
            if $I isa Generator && ($I).f isa Type
697,612✔
755
                T = ($I).f
686✔
756
            else
757
                T = Core.Compiler.return_type(_iterator_upper_bound, Tuple{typeof($I)})
246,773✔
758
            end
759
            promote_typejoin_union(T)
248,037✔
760
        end
761
    end
762
else
763
    macro default_eltype(itr)
764
        I = esc(itr)
765
        return quote
766
            if $I isa Generator && ($I).f isa Type
767
                promote_typejoin_union($I.f)
768
            else
769
                Any
770
            end
771
        end
772
    end
773
end
774

775
function collect(itr::Generator)
572,036✔
776
    isz = IteratorSize(itr.iter)
572,031✔
777
    et = @default_eltype(itr)
×
778
    if isa(isz, SizeUnknown)
153,979✔
779
        return grow_to!(Vector{et}(), itr)
85,092✔
780
    else
781
        shp = _similar_shape(itr, isz)
487,516✔
782
        y = iterate(itr)
963,476✔
783
        if y === nothing
487,318✔
784
            return _array_for(et, isz, shp)
929✔
785
        end
786
        v1, st = y
68,469✔
787
        dest = _array_for(typeof(v1), isz, shp)
486,536✔
788
        # The typeassert gives inference a helping hand on the element type and dimensionality
789
        # (work-around for #28382)
790
        et′ = et <: Type ? Type : et
68,469✔
791
        RT = dest isa AbstractArray ? AbstractArray{<:et′, ndims(dest)} : Any
68,559✔
792
        collect_to_with_first!(dest, v1, itr, st)::RT
10,480,440✔
793
    end
794
end
795

796
_collect(c, itr, ::EltypeUnknown, isz::SizeUnknown) =
33✔
797
    grow_to!(_similar_for(c, @default_eltype(itr), itr, isz, nothing), itr)
798

799
function _collect(c, itr, ::EltypeUnknown, isz::Union{HasLength,HasShape})
123,507✔
800
    et = @default_eltype(itr)
91,934✔
801
    shp = _similar_shape(itr, isz)
123,508✔
802
    y = iterate(itr)
245,841✔
803
    if y === nothing
123,505✔
804
        return _similar_for(c, et, itr, isz, shp)
217✔
805
    end
806
    v1, st = y
91,923✔
807
    dest = _similar_for(c, typeof(v1), itr, isz, shp)
123,304✔
808
    # The typeassert gives inference a helping hand on the element type and dimensionality
809
    # (work-around for #28382)
810
    et′ = et <: Type ? Type : et
91,881✔
811
    RT = dest isa AbstractArray ? AbstractArray{<:et′, ndims(dest)} : Any
91,900✔
812
    collect_to_with_first!(dest, v1, itr, st)::RT
123,850✔
813
end
814

815
function collect_to_with_first!(dest::AbstractArray, v1, itr, st)
160,442✔
816
    i1 = first(LinearIndices(dest))
160,355✔
817
    dest[i1] = v1
609,723✔
818
    return collect_to!(dest, itr, i1+1, st)
82,761,412✔
819
end
820

821
function collect_to_with_first!(dest, v1, itr, st)
×
822
    push!(dest, v1)
×
823
    return grow_to!(dest, itr, st)
×
824
end
825

826
function setindex_widen_up_to(dest::AbstractArray{T}, el, i) where T
966✔
827
    @inline
963✔
828
    new = similar(dest, promote_typejoin(T, typeof(el)))
970✔
829
    f = first(LinearIndices(dest))
963✔
830
    copyto!(new, first(LinearIndices(new)), dest, f, i-f)
1,923✔
831
    @inbounds new[i] = el
966✔
832
    return new
966✔
833
end
834

835
function collect_to!(dest::AbstractArray{T}, itr, offs, st) where T
197,992✔
836
    # collect to dest array, checking the type of each result. if a result does not
837
    # match, widen the result type and re-dispatch.
838
    i = offs
161,321✔
839
    while true
84,542,519✔
840
        y = iterate(itr, st)
168,474,054✔
841
        y === nothing && break
84,542,511✔
842
        el, st = y
83,454,845✔
843
        if el isa T
83,453,587✔
844
            @inbounds dest[i] = el
83,939,770✔
845
            i += 1
83,931,830✔
846
        else
847
            new = setindex_widen_up_to(dest, el, i)
1,090✔
848
            return collect_to!(new, itr, i+1, st)
966✔
849
        end
850
    end
83,931,830✔
851
    return dest
609,715✔
852
end
853

854
function grow_to!(dest, itr)
85,141✔
855
    y = iterate(itr)
85,425✔
856
    y === nothing && return dest
85,140✔
857
    dest2 = empty(dest, typeof(y[1]))
305✔
858
    push!(dest2, y[1])
328✔
859
    grow_to!(dest2, itr, y[2])
289✔
860
end
861

862
function push_widen(dest, el)
53✔
863
    @inline
53✔
864
    new = sizehint!(empty(dest, promote_typejoin(eltype(dest), typeof(el))), length(dest))
53✔
865
    if new isa AbstractSet
53✔
866
        # TODO: merge back these two branches when copy! is re-enabled for sets/vectors
867
        union!(new, dest)
1✔
868
    else
869
        append!(new, dest)
104✔
870
    end
871
    push!(new, el)
53✔
872
    return new
53✔
873
end
874

875
function grow_to!(dest, itr, st)
342✔
876
    T = eltype(dest)
239✔
877
    y = iterate(itr, st)
623✔
878
    while y !== nothing
3,608✔
879
        el, st = y
2,008✔
880
        if el isa T
2,008✔
881
            push!(dest, el)
3,269✔
882
        else
883
            new = push_widen(dest, el)
55✔
884
            return grow_to!(new, itr, st)
53✔
885
        end
886
        y = iterate(itr, st)
5,152✔
887
    end
3,266✔
888
    return dest
289✔
889
end
890

891
## Iteration ##
892

893
iterate(A::Array, i=1) = (@inline; (i % UInt) - 1 < length(A) ? (@inbounds A[i], i + 1) : nothing)
8,406,682,798✔
894

895
## Indexing: getindex ##
896

897
"""
898
    getindex(collection, key...)
899

900
Retrieve the value(s) stored at the given key or index within a collection. The syntax
901
`a[i,j,...]` is converted by the compiler to `getindex(a, i, j, ...)`.
902

903
See also [`get`](@ref), [`keys`](@ref), [`eachindex`](@ref).
904

905
# Examples
906
```jldoctest
907
julia> A = Dict("a" => 1, "b" => 2)
908
Dict{String, Int64} with 2 entries:
909
  "b" => 2
910
  "a" => 1
911

912
julia> getindex(A, "a")
913
1
914
```
915
"""
916
function getindex end
917

918
# Faster contiguous indexing using copyto! for AbstractUnitRange and Colon
919
function getindex(A::Array, I::AbstractUnitRange{<:Integer})
822,088✔
920
    @inline
794,304✔
921
    @boundscheck checkbounds(A, I)
51,296,934✔
922
    lI = length(I)
51,296,932✔
923
    X = similar(A, axes(I))
51,296,944✔
924
    if lI > 0
51,296,932✔
925
        copyto!(X, firstindex(X), A, first(I), lI)
53,058,848✔
926
    end
927
    return X
51,296,932✔
928
end
929

930
# getindex for carrying out logical indexing for AbstractUnitRange{Bool} as Bool <: Integer
931
getindex(a::Array, r::AbstractUnitRange{Bool}) = getindex(a, to_index(r))
21✔
932

933
function getindex(A::Array, c::Colon)
4,790✔
934
    lI = length(A)
1,616,147✔
935
    X = similar(A, lI)
1,616,147✔
936
    if lI > 0
1,616,147✔
937
        unsafe_copyto!(X, 1, A, 1, lI)
1,616,145✔
938
    end
939
    return X
1,616,147✔
940
end
941

942
# This is redundant with the abstract fallbacks, but needed for bootstrap
943
function getindex(A::Array{S}, I::AbstractRange{Int}) where S
3,166,959✔
944
    return S[ A[i] for i in I ]
13,043,905✔
945
end
946

947
## Indexing: setindex! ##
948

949
"""
950
    setindex!(collection, value, key...)
951

952
Store the given value at the given key or index within a collection. The syntax `a[i,j,...] =
953
x` is converted by the compiler to `(setindex!(a, x, i, j, ...); x)`.
954

955
# Examples
956
```jldoctest
957
julia> a = Dict("a"=>1)
958
Dict{String, Int64} with 1 entry:
959
  "a" => 1
960

961
julia> setindex!(a, 2, "b")
962
Dict{String, Int64} with 2 entries:
963
  "b" => 2
964
  "a" => 1
965
```
966
"""
967
function setindex! end
968

969
@eval setindex!(A::Array{T}, x, i1::Int) where {T} = arrayset($(Expr(:boundscheck)), A, convert(T,x)::T, i1)
17,183,884,335✔
970
@eval setindex!(A::Array{T}, x, i1::Int, i2::Int, I::Int...) where {T} =
93,660,351✔
971
    (@inline; arrayset($(Expr(:boundscheck)), A, convert(T,x)::T, i1, i2, I...))
95,982,873✔
972

973
# This is redundant with the abstract fallbacks but needed and helpful for bootstrap
974
function setindex!(A::Array, X::AbstractArray, I::AbstractVector{Int})
800,481✔
975
    @_propagate_inbounds_meta
800,481✔
976
    @boundscheck setindex_shape_check(X, length(I))
5,784,595✔
977
    require_one_based_indexing(X)
800,481✔
978
    X′ = unalias(A, X)
805,800✔
979
    I′ = unalias(A, I)
800,910✔
980
    count = 1
800,481✔
981
    for i in I′
10,807,546✔
982
        @inbounds x = X′[count]
13,920,695✔
983
        A[i] = x
13,922,778✔
984
        count += 1
13,920,695✔
985
    end
22,771,642✔
986
    return A
5,784,595✔
987
end
988

989
# Faster contiguous setindex! with copyto!
990
function setindex!(A::Array{T}, X::Array{T}, I::AbstractUnitRange{Int}) where T
1,007,904✔
991
    @inline
1,007,490✔
992
    @boundscheck checkbounds(A, I)
1,008,253✔
993
    lI = length(I)
1,008,253✔
994
    @boundscheck setindex_shape_check(X, lI)
1,008,253✔
995
    if lI > 0
1,008,253✔
996
        unsafe_copyto!(A, first(I), X, 1, lI)
1,008,151✔
997
    end
998
    return A
1,008,253✔
999
end
1000
function setindex!(A::Array{T}, X::Array{T}, c::Colon) where T
47✔
1001
    @inline
47✔
1002
    lI = length(A)
47✔
1003
    @boundscheck setindex_shape_check(X, lI)
47✔
1004
    if lI > 0
47✔
1005
        unsafe_copyto!(A, 1, X, 1, lI)
47✔
1006
    end
1007
    return A
47✔
1008
end
1009

1010
# efficiently grow an array
1011

1012
_growbeg!(a::Vector, delta::Integer) =
1,015,428✔
1013
    ccall(:jl_array_grow_beg, Cvoid, (Any, UInt), a, delta)
1014
_growend!(a::Vector, delta::Integer) =
1,416,044,522✔
1015
    ccall(:jl_array_grow_end, Cvoid, (Any, UInt), a, delta)
1016
_growat!(a::Vector, i::Integer, delta::Integer) =
62,433,057✔
1017
    ccall(:jl_array_grow_at, Cvoid, (Any, Int, UInt), a, i - 1, delta)
1018

1019
# efficiently delete part of an array
1020

1021
_deletebeg!(a::Vector, delta::Integer) =
18,244,589✔
1022
    ccall(:jl_array_del_beg, Cvoid, (Any, UInt), a, delta)
1023
_deleteend!(a::Vector, delta::Integer) =
380,265,832✔
1024
    ccall(:jl_array_del_end, Cvoid, (Any, UInt), a, delta)
1025
_deleteat!(a::Vector, i::Integer, delta::Integer) =
221,217✔
1026
    ccall(:jl_array_del_at, Cvoid, (Any, Int, UInt), a, i - 1, delta)
1027

1028
## Dequeue functionality ##
1029

1030
"""
1031
    push!(collection, items...) -> collection
1032

1033
Insert one or more `items` in `collection`. If `collection` is an ordered container,
1034
the items are inserted at the end (in the given order).
1035

1036
# Examples
1037
```jldoctest
1038
julia> push!([1, 2, 3], 4, 5, 6)
1039
6-element Vector{Int64}:
1040
 1
1041
 2
1042
 3
1043
 4
1044
 5
1045
 6
1046
```
1047

1048
If `collection` is ordered, use [`append!`](@ref) to add all the elements of another
1049
collection to it. The result of the preceding example is equivalent to `append!([1, 2, 3], [4,
1050
5, 6])`. For `AbstractSet` objects, [`union!`](@ref) can be used instead.
1051

1052
See [`sizehint!`](@ref) for notes about the performance model.
1053

1054
See also [`pushfirst!`](@ref).
1055
"""
1056
function push! end
1057

1058
function push!(a::Array{T,1}, item) where T
43,112,328✔
1059
    # convert first so we don't grow the array if the assignment won't work
1060
    itemT = convert(T, item)
22,684,203✔
1061
    _growend!(a, 1)
933,289,796✔
1062
    @inbounds a[end] = itemT
933,289,796✔
1063
    return a
29,233,528✔
1064
end
1065

1066
# specialize and optimize the single argument case
1067
function push!(a::Vector{Any}, @nospecialize x)
3,157,989✔
1068
    _growend!(a, 1)
82,234,855✔
1069
    arrayset(true, a, x, length(a))
82,234,855✔
1070
    return a
2,792,916✔
1071
end
1072
function push!(a::Vector{Any}, @nospecialize x...)
97,317✔
1073
    na = length(a)
97,317✔
1074
    nx = length(x)
2✔
1075
    _growend!(a, nx)
97,317✔
1076
    for i = 1:nx
97,317✔
1077
        arrayset(true, a, x[i], na+i)
194,636✔
1078
    end
291,955✔
1079
    return a
97,317✔
1080
end
1081

1082
"""
1083
    append!(collection, collections...) -> collection.
1084

1085
For an ordered container `collection`, add the elements of each `collections`
1086
to the end of it.
1087

1088
!!! compat "Julia 1.6"
1089
    Specifying multiple collections to be appended requires at least Julia 1.6.
1090

1091
# Examples
1092
```jldoctest
1093
julia> append!([1], [2, 3])
1094
3-element Vector{Int64}:
1095
 1
1096
 2
1097
 3
1098

1099
julia> append!([1, 2, 3], [4, 5], [6])
1100
6-element Vector{Int64}:
1101
 1
1102
 2
1103
 3
1104
 4
1105
 5
1106
 6
1107
```
1108

1109
Use [`push!`](@ref) to add individual items to `collection` which are not already
1110
themselves in another collection. The result of the preceding example is equivalent to
1111
`push!([1, 2, 3], 4, 5, 6)`.
1112

1113
See [`sizehint!`](@ref) for notes about the performance model.
1114

1115
See also [`vcat`](@ref) for vectors, [`union!`](@ref) for sets,
1116
and [`prepend!`](@ref) and [`pushfirst!`](@ref) for the opposite order.
1117
"""
1118
function append!(a::Vector, items::AbstractVector)
5,613,126✔
1119
    itemindices = eachindex(items)
55,240,248✔
1120
    n = length(itemindices)
27,249✔
1121
    _growend!(a, n)
55,240,248✔
1122
    copyto!(a, length(a)-n+1, items, first(itemindices), n)
60,138,357✔
1123
    return a
55,240,248✔
1124
end
1125

1126
append!(a::AbstractVector, iter) = _append!(a, IteratorSize(iter), iter)
38,677,764✔
1127
push!(a::AbstractVector, iter...) = append!(a, iter)
4,004✔
1128

1129
append!(a::AbstractVector, iter...) = foldl(append!, iter, init=a)
1✔
1130

1131
function _append!(a, ::Union{HasLength,HasShape}, iter)
15,404,221✔
1132
    n = length(a)
15,404,221✔
1133
    i = lastindex(a)
15,404,221✔
1134
    resize!(a, n+Int(length(iter))::Int)
26,358,679✔
1135
    @inbounds for (i, item) in zip(i+1:lastindex(a), iter)
19,853,984✔
1136
        a[i] = item
19,898,570✔
1137
    end
35,343,729✔
1138
    a
15,404,221✔
1139
end
1140

1141
function _append!(a, ::IteratorSize, iter)
23,273,543✔
1142
    for item in iter
23,273,545✔
1143
        push!(a, item)
23,970,438✔
1144
    end
23,970,443✔
1145
    a
23,273,543✔
1146
end
1147

1148
"""
1149
    prepend!(a::Vector, collections...) -> collection
1150

1151
Insert the elements of each `collections` to the beginning of `a`.
1152

1153
When `collections` specifies multiple collections, order is maintained:
1154
elements of `collections[1]` will appear leftmost in `a`, and so on.
1155

1156
!!! compat "Julia 1.6"
1157
    Specifying multiple collections to be prepended requires at least Julia 1.6.
1158

1159
# Examples
1160
```jldoctest
1161
julia> prepend!([3], [1, 2])
1162
3-element Vector{Int64}:
1163
 1
1164
 2
1165
 3
1166

1167
julia> prepend!([6], [1, 2], [3, 4, 5])
1168
6-element Vector{Int64}:
1169
 1
1170
 2
1171
 3
1172
 4
1173
 5
1174
 6
1175
```
1176
"""
1177
function prepend! end
1178

1179
function prepend!(a::Vector, items::AbstractVector)
832✔
1180
    itemindices = eachindex(items)
832✔
1181
    n = length(itemindices)
792✔
1182
    _growbeg!(a, n)
832✔
1183
    if a === items
832✔
1184
        copyto!(a, 1, items, n+1, n)
1✔
1185
    else
1186
        copyto!(a, 1, items, first(itemindices), n)
1,351✔
1187
    end
1188
    return a
832✔
1189
end
1190

1191
prepend!(a::Vector, iter) = _prepend!(a, IteratorSize(iter), iter)
13✔
1192
pushfirst!(a::Vector, iter...) = prepend!(a, iter)
7✔
1193

1194
prepend!(a::AbstractVector, iter...) = foldr((v, a) -> prepend!(a, v), iter, init=a)
7✔
1195

1196
function _prepend!(a, ::Union{HasLength,HasShape}, iter)
7✔
1197
    require_one_based_indexing(a)
7✔
1198
    n = length(iter)
7✔
1199
    _growbeg!(a, n)
7✔
1200
    i = 0
7✔
1201
    for item in iter
7✔
1202
        @inbounds a[i += 1] = item
13✔
1203
    end
18✔
1204
    a
7✔
1205
end
1206
function _prepend!(a, ::IteratorSize, iter)
2✔
1207
    n = 0
2✔
1208
    for item in iter
3✔
1209
        n += 1
5✔
1210
        pushfirst!(a, item)
5✔
1211
    end
9✔
1212
    reverse!(a, 1, n)
2✔
1213
    a
2✔
1214
end
1215

1216
"""
1217
    resize!(a::Vector, n::Integer) -> Vector
1218

1219
Resize `a` to contain `n` elements. If `n` is smaller than the current collection
1220
length, the first `n` elements will be retained. If `n` is larger, the new elements are not
1221
guaranteed to be initialized.
1222

1223
# Examples
1224
```jldoctest
1225
julia> resize!([6, 5, 4, 3, 2, 1], 3)
1226
3-element Vector{Int64}:
1227
 6
1228
 5
1229
 4
1230

1231
julia> a = resize!([6, 5, 4, 3, 2, 1], 8);
1232

1233
julia> length(a)
1234
8
1235

1236
julia> a[1:6]
1237
6-element Vector{Int64}:
1238
 6
1239
 5
1240
 4
1241
 3
1242
 2
1243
 1
1244
```
1245
"""
1246
function resize!(a::Vector, nl::Integer)
1,374,574✔
1247
    l = length(a)
511,561,202✔
1248
    if nl > l
511,561,202✔
1249
        _growend!(a, nl-l)
236,061,253✔
1250
    elseif nl != l
275,499,951✔
1251
        if nl < 0
59,798,005✔
1252
            throw(ArgumentError("new length must be ≥ 0"))
2✔
1253
        end
1254
        _deleteend!(a, l-nl)
59,799,092✔
1255
    end
1256
    return a
511,561,200✔
1257
end
1258

1259
"""
1260
    sizehint!(s, n) -> s
1261

1262
Suggest that collection `s` reserve capacity for at least `n` elements. That is, if
1263
you expect that you're going to have to push a lot of values onto `s`, you can avoid
1264
the cost of incremental reallocation by doing it once up front; this can improve
1265
performance.
1266

1267
See also [`resize!`](@ref).
1268

1269
# Notes on the performance model
1270

1271
For types that support `sizehint!`,
1272

1273
1. `push!` and `append!` methods generally may (but are not required to) preallocate extra
1274
   storage. For types implemented in `Base`, they typically do, using a heuristic optimized for
1275
   a general use case.
1276

1277
2. `sizehint!` may control this preallocation. Again, it typically does this for types in
1278
   `Base`.
1279

1280
3. `empty!` is nearly costless (and O(1)) for types that support this kind of preallocation.
1281
"""
1282
function sizehint! end
1283

1284
function sizehint!(a::Vector, sz::Integer)
456,977✔
1285
    ccall(:jl_array_sizehint, Cvoid, (Any, UInt), a, sz)
163,867,714✔
1286
    a
622,659✔
1287
end
1288

1289
"""
1290
    pop!(collection) -> item
1291

1292
Remove an item in `collection` and return it. If `collection` is an
1293
ordered container, the last item is returned; for unordered containers,
1294
an arbitrary element is returned.
1295

1296
See also: [`popfirst!`](@ref), [`popat!`](@ref), [`delete!`](@ref), [`deleteat!`](@ref), [`splice!`](@ref), and [`push!`](@ref).
1297

1298
# Examples
1299
```jldoctest
1300
julia> A=[1, 2, 3]
1301
3-element Vector{Int64}:
1302
 1
1303
 2
1304
 3
1305

1306
julia> pop!(A)
1307
3
1308

1309
julia> A
1310
2-element Vector{Int64}:
1311
 1
1312
 2
1313

1314
julia> S = Set([1, 2])
1315
Set{Int64} with 2 elements:
1316
  2
1317
  1
1318

1319
julia> pop!(S)
1320
2
1321

1322
julia> S
1323
Set{Int64} with 1 element:
1324
  1
1325

1326
julia> pop!(Dict(1=>2))
1327
1 => 2
1328
```
1329
"""
1330
function pop!(a::Vector)
57,615✔
1331
    if isempty(a)
259,761,264✔
1332
        throw(ArgumentError("array must be non-empty"))
1✔
1333
    end
1334
    item = a[end]
259,761,263✔
1335
    _deleteend!(a, 1)
259,761,263✔
1336
    return item
259,761,263✔
1337
end
1338

1339
"""
1340
    popat!(a::Vector, i::Integer, [default])
1341

1342
Remove the item at the given `i` and return it. Subsequent items
1343
are shifted to fill the resulting gap.
1344
When `i` is not a valid index for `a`, return `default`, or throw an error if
1345
`default` is not specified.
1346

1347
See also: [`pop!`](@ref), [`popfirst!`](@ref), [`deleteat!`](@ref), [`splice!`](@ref).
1348

1349
!!! compat "Julia 1.5"
1350
    This function is available as of Julia 1.5.
1351

1352
# Examples
1353
```jldoctest
1354
julia> a = [4, 3, 2, 1]; popat!(a, 2)
1355
3
1356

1357
julia> a
1358
3-element Vector{Int64}:
1359
 4
1360
 2
1361
 1
1362

1363
julia> popat!(a, 4, missing)
1364
missing
1365

1366
julia> popat!(a, 4)
1367
ERROR: BoundsError: attempt to access 3-element Vector{Int64} at index [4]
1368
[...]
1369
```
1370
"""
1371
function popat!(a::Vector, i::Integer)
5✔
1372
    x = a[i]
5✔
1373
    _deleteat!(a, i, 1)
2✔
1374
    x
2✔
1375
end
1376

1377
function popat!(a::Vector, i::Integer, default)
2✔
1378
    if 1 <= i <= length(a)
2✔
1379
        x = @inbounds a[i]
1✔
1380
        _deleteat!(a, i, 1)
1✔
1381
        x
1✔
1382
    else
1383
        default
1✔
1384
    end
1385
end
1386

1387
"""
1388
    pushfirst!(collection, items...) -> collection
1389

1390
Insert one or more `items` at the beginning of `collection`.
1391

1392
This function is called `unshift` in many other programming languages.
1393

1394
# Examples
1395
```jldoctest
1396
julia> pushfirst!([1, 2, 3, 4], 5, 6)
1397
6-element Vector{Int64}:
1398
 5
1399
 6
1400
 1
1401
 2
1402
 3
1403
 4
1404
```
1405
"""
1406
function pushfirst!(a::Array{T,1}, item) where T
85,786✔
1407
    item = convert(T, item)
55,762✔
1408
    _growbeg!(a, 1)
86,123✔
1409
    a[1] = item
86,123✔
1410
    return a
55,779✔
1411
end
1412

1413
# specialize and optimize the single argument case
1414
function pushfirst!(a::Vector{Any}, @nospecialize x)
111✔
1415
    _growbeg!(a, 1)
739,459✔
1416
    a[1] = x
739,459✔
1417
    return a
111✔
1418
end
1419
function pushfirst!(a::Vector{Any}, @nospecialize x...)
715✔
1420
    na = length(a)
2✔
1421
    nx = length(x)
2✔
1422
    _growbeg!(a, nx)
715✔
1423
    for i = 1:nx
715✔
1424
        a[i] = x[i]
1,432✔
1425
    end
2,149✔
1426
    return a
715✔
1427
end
1428

1429
"""
1430
    popfirst!(collection) -> item
1431

1432
Remove the first `item` from `collection`.
1433

1434
This function is called `shift` in many other programming languages.
1435

1436
See also: [`pop!`](@ref), [`popat!`](@ref), [`delete!`](@ref).
1437

1438
# Examples
1439
```jldoctest
1440
julia> A = [1, 2, 3, 4, 5, 6]
1441
6-element Vector{Int64}:
1442
 1
1443
 2
1444
 3
1445
 4
1446
 5
1447
 6
1448

1449
julia> popfirst!(A)
1450
1
1451

1452
julia> A
1453
5-element Vector{Int64}:
1454
 2
1455
 3
1456
 4
1457
 5
1458
 6
1459
```
1460
"""
1461
function popfirst!(a::Vector)
1,034,473✔
1462
    if isempty(a)
18,244,588✔
1463
        throw(ArgumentError("array must be non-empty"))
1✔
1464
    end
1465
    item = a[1]
18,244,587✔
1466
    _deletebeg!(a, 1)
18,244,587✔
1467
    return item
18,244,587✔
1468
end
1469

1470
"""
1471
    insert!(a::Vector, index::Integer, item)
1472

1473
Insert an `item` into `a` at the given `index`. `index` is the index of `item` in
1474
the resulting `a`.
1475

1476
See also: [`push!`](@ref), [`replace`](@ref), [`popat!`](@ref), [`splice!`](@ref).
1477

1478
# Examples
1479
```jldoctest
1480
julia> insert!(Any[1:6;], 3, "here")
1481
7-element Vector{Any}:
1482
 1
1483
 2
1484
  "here"
1485
 3
1486
 4
1487
 5
1488
 6
1489
```
1490
"""
1491
function insert!(a::Array{T,1}, i::Integer, item) where T
346,270✔
1492
    # Throw convert error before changing the shape of the array
1493
    _item = convert(T, item)
298,605✔
1494
    _growat!(a, i, 1)
62,432,948✔
1495
    # _growat! already did bound check
1496
    @inbounds a[i] = _item
62,432,942✔
1497
    return a
298,611✔
1498
end
1499

1500
"""
1501
    deleteat!(a::Vector, i::Integer)
1502

1503
Remove the item at the given `i` and return the modified `a`. Subsequent items
1504
are shifted to fill the resulting gap.
1505

1506
See also: [`keepat!`](@ref), [`delete!`](@ref), [`popat!`](@ref), [`splice!`](@ref).
1507

1508
# Examples
1509
```jldoctest
1510
julia> deleteat!([6, 5, 4, 3, 2, 1], 2)
1511
5-element Vector{Int64}:
1512
 6
1513
 4
1514
 3
1515
 2
1516
 1
1517
```
1518
"""
1519
function deleteat!(a::Vector, i::Integer)
30✔
1520
    i isa Bool && depwarn("passing Bool as an index is deprecated", :deleteat!)
30✔
1521
    _deleteat!(a, i, 1)
211,223✔
1522
    return a
24✔
1523
end
1524

1525
function deleteat!(a::Vector, r::AbstractUnitRange{<:Integer})
4,966✔
1526
    if eltype(r) === Bool
4,966✔
1527
        return invoke(deleteat!, Tuple{Vector, AbstractVector{Bool}}, a, r)
×
1528
    else
1529
        n = length(a)
4,966✔
1530
        f = first(r)
5,061✔
1531
        f isa Bool && depwarn("passing Bool as an index is deprecated", :deleteat!)
4,966✔
1532
        isempty(r) || _deleteat!(a, f, length(r))
23,779✔
1533
        return a
13,841✔
1534
    end
1535
end
1536

1537
"""
1538
    deleteat!(a::Vector, inds)
1539

1540
Remove the items at the indices given by `inds`, and return the modified `a`.
1541
Subsequent items are shifted to fill the resulting gap.
1542

1543
`inds` can be either an iterator or a collection of sorted and unique integer indices,
1544
or a boolean vector of the same length as `a` with `true` indicating entries to delete.
1545

1546
# Examples
1547
```jldoctest
1548
julia> deleteat!([6, 5, 4, 3, 2, 1], 1:2:5)
1549
3-element Vector{Int64}:
1550
 5
1551
 3
1552
 1
1553

1554
julia> deleteat!([6, 5, 4, 3, 2, 1], [true, false, true, false, true, false])
1555
3-element Vector{Int64}:
1556
 5
1557
 3
1558
 1
1559

1560
julia> deleteat!([6, 5, 4, 3, 2, 1], (2, 2))
1561
ERROR: ArgumentError: indices must be unique and sorted
1562
Stacktrace:
1563
[...]
1564
```
1565
"""
1566
deleteat!(a::Vector, inds) = _deleteat!(a, inds)
19✔
1567
deleteat!(a::Vector, inds::AbstractVector) = _deleteat!(a, to_indices(a, (inds,))[1])
51,404✔
1568

1569
struct Nowhere; end
1570
push!(::Nowhere, _) = nothing
48✔
1571
_growend!(::Nowhere, _) = nothing
×
1572

1573
@inline function _push_deleted!(dltd, a::Vector, ind)
50✔
1574
    if @inbounds isassigned(a, ind)
56,878✔
1575
        push!(dltd, @inbounds a[ind])
56,890✔
1576
    else
1577
        _growend!(dltd, 1)
1✔
1578
    end
1579
end
1580

1581
@inline function _copy_item!(a::Vector, p, q)
275✔
1582
    if @inbounds isassigned(a, q)
27,043✔
1583
        @inbounds a[p] = a[q]
27,066✔
1584
    else
1585
        _unsetindex!(a, p)
1✔
1586
    end
1587
end
1588

1589
function _deleteat!(a::Vector, inds, dltd=Nowhere())
51,455✔
1590
    n = length(a)
102,847✔
1591
    y = iterate(inds)
51,435✔
1592
    y === nothing && return a
51,424✔
1593
    (p, s) = y
27✔
1594
    checkbounds(a, p)
51,425✔
1595
    _push_deleted!(dltd, a, p)
51,418✔
1596
    q = p+1
51,413✔
1597
    while true
56,878✔
1598
        y = iterate(inds, s)
108,285✔
1599
        y === nothing && break
56,878✔
1600
        (i,s) = y
29✔
1601
        if !(q <= i <= n)
5,467✔
1602
            if i < q
2✔
1603
                throw(ArgumentError("indices must be unique and sorted"))
1✔
1604
            else
1605
                throw(BoundsError())
1✔
1606
            end
1607
        end
1608
        while q < i
7,306✔
1609
            _copy_item!(a, p, q)
1,852✔
1610
            p += 1; q += 1
3,682✔
1611
        end
1,841✔
1612
        _push_deleted!(dltd, a, i)
5,474✔
1613
        q = i+1
5,465✔
1614
    end
5,465✔
1615
    while q <= n
76,423✔
1616
        _copy_item!(a, p, q)
25,026✔
1617
        p += 1; q += 1
50,024✔
1618
    end
25,012✔
1619
    _deleteend!(a, n-p+1)
51,411✔
1620
    return a
51,411✔
1621
end
1622

1623
# Simpler and more efficient version for logical indexing
1624
function deleteat!(a::Vector, inds::AbstractVector{Bool})
23✔
1625
    n = length(a)
23✔
1626
    length(inds) == n || throw(BoundsError(a, inds))
26✔
1627
    p = 1
20✔
1628
    for (q, i) in enumerate(inds)
39✔
1629
        _copy_item!(a, p, q)
190✔
1630
        p += !i
190✔
1631
    end
361✔
1632
    _deleteend!(a, n-p+1)
20✔
1633
    return a
20✔
1634
end
1635

1636
const _default_splice = []
1637

1638
"""
1639
    splice!(a::Vector, index::Integer, [replacement]) -> item
1640

1641
Remove the item at the given index, and return the removed item.
1642
Subsequent items are shifted left to fill the resulting gap.
1643
If specified, replacement values from an ordered
1644
collection will be spliced in place of the removed item.
1645

1646
See also: [`replace`](@ref), [`delete!`](@ref), [`deleteat!`](@ref), [`pop!`](@ref), [`popat!`](@ref).
1647

1648
# Examples
1649
```jldoctest
1650
julia> A = [6, 5, 4, 3, 2, 1]; splice!(A, 5)
1651
2
1652

1653
julia> A
1654
5-element Vector{Int64}:
1655
 6
1656
 5
1657
 4
1658
 3
1659
 1
1660

1661
julia> splice!(A, 5, -1)
1662
1
1663

1664
julia> A
1665
5-element Vector{Int64}:
1666
  6
1667
  5
1668
  4
1669
  3
1670
 -1
1671

1672
julia> splice!(A, 1, [-1, -2, -3])
1673
6
1674

1675
julia> A
1676
7-element Vector{Int64}:
1677
 -1
1678
 -2
1679
 -3
1680
  5
1681
  4
1682
  3
1683
 -1
1684
```
1685

1686
To insert `replacement` before an index `n` without removing any items, use
1687
`splice!(collection, n:n-1, replacement)`.
1688
"""
1689
function splice!(a::Vector, i::Integer, ins=_default_splice)
44✔
1690
    v = a[i]
54✔
1691
    m = length(ins)
37✔
1692
    if m == 0
37✔
1693
        _deleteat!(a, i, 1)
22✔
1694
    elseif m == 1
15✔
1695
        a[i] = ins[1]
5✔
1696
    else
1697
        _growat!(a, i, m-1)
10✔
1698
        k = 1
10✔
1699
        for x in ins
10✔
1700
            a[i+k-1] = x
35✔
1701
            k += 1
35✔
1702
        end
35✔
1703
    end
1704
    return v
37✔
1705
end
1706

1707
"""
1708
    splice!(a::Vector, indices, [replacement]) -> items
1709

1710
Remove items at specified indices, and return a collection containing
1711
the removed items.
1712
Subsequent items are shifted left to fill the resulting gaps.
1713
If specified, replacement values from an ordered collection will be spliced in
1714
place of the removed items; in this case, `indices` must be a `AbstractUnitRange`.
1715

1716
To insert `replacement` before an index `n` without removing any items, use
1717
`splice!(collection, n:n-1, replacement)`.
1718

1719
!!! compat "Julia 1.5"
1720
    Prior to Julia 1.5, `indices` must always be a `UnitRange`.
1721

1722
!!! compat "Julia 1.8"
1723
    Prior to Julia 1.8, `indices` must be a `UnitRange` if splicing in replacement values.
1724

1725
# Examples
1726
```jldoctest
1727
julia> A = [-1, -2, -3, 5, 4, 3, -1]; splice!(A, 4:3, 2)
1728
Int64[]
1729

1730
julia> A
1731
8-element Vector{Int64}:
1732
 -1
1733
 -2
1734
 -3
1735
  2
1736
  5
1737
  4
1738
  3
1739
 -1
1740
```
1741
"""
1742
function splice!(a::Vector, r::AbstractUnitRange{<:Integer}, ins=_default_splice)
250✔
1743
    v = a[r]
258✔
1744
    m = length(ins)
242✔
1745
    if m == 0
242✔
1746
        deleteat!(a, r)
230✔
1747
        return v
117✔
1748
    end
1749

1750
    n = length(a)
125✔
1751
    f = first(r)
125✔
1752
    l = last(r)
125✔
1753
    d = length(r)
125✔
1754

1755
    if m < d
125✔
1756
        delta = d - m
23✔
1757
        _deleteat!(a, (f - 1 < n - l) ? f : (l - delta + 1), delta)
32✔
1758
    elseif m > d
102✔
1759
        _growat!(a, (f - 1 < n - l) ? f : (l + 1), m - d)
85✔
1760
    end
1761

1762
    k = 1
42✔
1763
    for x in ins
125✔
1764
        a[f+k-1] = x
376✔
1765
        k += 1
376✔
1766
    end
418✔
1767
    return v
125✔
1768
end
1769

1770
splice!(a::Vector, inds) = (dltds = eltype(a)[]; _deleteat!(a, inds, dltds); dltds)
3✔
1771

1772
function empty!(a::Vector)
80,106✔
1773
    _deleteend!(a, length(a))
60,653,983✔
1774
    return a
60,653,983✔
1775
end
1776

1777
_memcmp(a, b, len) = ccall(:memcmp, Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), a, b, len % Csize_t) % Int
76,777✔
1778

1779
# use memcmp for cmp on byte arrays
1780
function cmp(a::Array{UInt8,1}, b::Array{UInt8,1})
3✔
1781
    c = _memcmp(a, b, min(length(a),length(b)))
3✔
1782
    return c < 0 ? -1 : c > 0 ? +1 : cmp(length(a),length(b))
3✔
1783
end
1784

1785
const BitIntegerArray{N} = Union{map(T->Array{T,N}, BitInteger_types)...} where N
×
1786
# use memcmp for == on bit integer types
1787
==(a::Arr, b::Arr) where {Arr <: BitIntegerArray} =
1,490✔
1788
    size(a) == size(b) && 0 == _memcmp(a, b, sizeof(eltype(Arr)) * length(a))
1789

1790
# this is ~20% faster than the generic implementation above for very small arrays
1791
function ==(a::Arr, b::Arr) where Arr <: BitIntegerArray{1}
9,430✔
1792
    len = length(a)
43,062✔
1793
    len == length(b) && 0 == _memcmp(a, b, sizeof(eltype(Arr)) * len)
43,064✔
1794
end
1795

1796
"""
1797
    reverse(v [, start=firstindex(v) [, stop=lastindex(v) ]] )
1798

1799
Return a copy of `v` reversed from start to stop.  See also [`Iterators.reverse`](@ref)
1800
for reverse-order iteration without making a copy, and in-place [`reverse!`](@ref).
1801

1802
# Examples
1803
```jldoctest
1804
julia> A = Vector(1:5)
1805
5-element Vector{Int64}:
1806
 1
1807
 2
1808
 3
1809
 4
1810
 5
1811

1812
julia> reverse(A)
1813
5-element Vector{Int64}:
1814
 5
1815
 4
1816
 3
1817
 2
1818
 1
1819

1820
julia> reverse(A, 1, 4)
1821
5-element Vector{Int64}:
1822
 4
1823
 3
1824
 2
1825
 1
1826
 5
1827

1828
julia> reverse(A, 3, 5)
1829
5-element Vector{Int64}:
1830
 1
1831
 2
1832
 5
1833
 4
1834
 3
1835
```
1836
"""
1837
function reverse(A::AbstractVector, start::Integer, stop::Integer=lastindex(A))
4,910✔
1838
    s, n = Int(start), Int(stop)
65✔
1839
    B = similar(A)
4,911✔
1840
    for i = firstindex(A):s-1
4,914✔
1841
        B[i] = A[i]
14✔
1842
    end
24✔
1843
    for i = s:n
9,814✔
1844
        B[i] = A[n+s-i]
176,474✔
1845
    end
348,040✔
1846
    for i = n+1:lastindex(A)
4,914✔
1847
        B[i] = A[i]
20✔
1848
    end
36✔
1849
    return B
4,910✔
1850
end
1851

1852
# 1d special cases of reverse(A; dims) and reverse!(A; dims):
1853
for (f,_f) in ((:reverse,:_reverse), (:reverse!,:_reverse!))
1854
    @eval begin
1855
        $f(A::AbstractVector; dims=:) = $_f(A, dims)
80,365,967✔
1856
        $_f(A::AbstractVector, ::Colon) = $f(A, firstindex(A), lastindex(A))
5,852✔
1857
        $_f(A::AbstractVector, dim::Tuple{Integer}) = $_f(A, first(dim))
×
1858
        function $_f(A::AbstractVector, dim::Integer)
7✔
1859
            dim == 1 || throw(ArgumentError("invalid dimension $dim ≠ 1"))
11✔
1860
            return $_f(A, :)
3✔
1861
        end
1862
    end
1863
end
1864

1865
function reverseind(a::AbstractVector, i::Integer)
3✔
1866
    li = LinearIndices(a)
3✔
1867
    first(li) + last(li) - i
3✔
1868
end
1869

1870
# This implementation of `midpoint` is performance-optimized but safe
1871
# only if `lo <= hi`.
1872
midpoint(lo::T, hi::T) where T<:Integer = lo + ((hi - lo) >>> 0x01)
3,382,076✔
1873
midpoint(lo::Integer, hi::Integer) = midpoint(promote(lo, hi)...)
×
1874

1875
"""
1876
    reverse!(v [, start=firstindex(v) [, stop=lastindex(v) ]]) -> v
1877

1878
In-place version of [`reverse`](@ref).
1879

1880
# Examples
1881
```jldoctest
1882
julia> A = Vector(1:5)
1883
5-element Vector{Int64}:
1884
 1
1885
 2
1886
 3
1887
 4
1888
 5
1889

1890
julia> reverse!(A);
1891

1892
julia> A
1893
5-element Vector{Int64}:
1894
 5
1895
 4
1896
 3
1897
 2
1898
 1
1899
```
1900
"""
1901
function reverse!(v::AbstractVector, start::Integer, stop::Integer=lastindex(v))
63,928✔
1902
    s, n = Int(start), Int(stop)
8,001✔
1903
    if n > s # non-empty and non-trivial
63,925✔
1904
        liv = LinearIndices(v)
60,471✔
1905
        if !(first(liv) ≤ s ≤ last(liv))
60,471✔
1906
            throw(BoundsError(v, s))
3✔
1907
        elseif !(first(liv) ≤ n ≤ last(liv))
60,468✔
1908
            throw(BoundsError(v, n))
1✔
1909
        end
1910
        r = n
7,330✔
1911
        @inbounds for i in s:midpoint(s, n-1)
120,934✔
1912
            v[i], v[r] = v[r], v[i]
1,579,774✔
1913
            r -= 1
1,575,358✔
1914
        end
3,090,249✔
1915
    end
1916
    return v
63,921✔
1917
end
1918

1919
# concatenations of homogeneous combinations of vectors, horizontal and vertical
1920

1921
vcat() = Vector{Any}()
10,628✔
1922
hcat() = Vector{Any}()
1✔
1923

1924
function hcat(V::Vector{T}...) where T
558✔
1925
    height = length(V[1])
558✔
1926
    for j = 2:length(V)
559✔
1927
        if length(V[j]) != height
624✔
1928
            throw(DimensionMismatch("vectors must have same lengths"))
1✔
1929
        end
1930
    end
721✔
1931
    return [ V[j][i]::T for i=1:length(V[1]), j=1:length(V) ]
557✔
1932
end
1933

1934
function vcat(arrays::Vector{T}...) where T
35,597✔
1935
    n = 0
6,078✔
1936
    for a in arrays
35,597✔
1937
        n += length(a)
2,071,346✔
1938
    end
2,106,923✔
1939
    arr = Vector{T}(undef, n)
35,597✔
1940
    nd = 1
6,078✔
1941
    for a in arrays
35,597✔
1942
        na = length(a)
2,071,346✔
1943
        @assert nd + na <= 1 + length(arr) # Concurrent modification of arrays?
2,071,346✔
1944
        unsafe_copyto!(arr, nd, a, 1, na)
2,071,346✔
1945
        nd += na
2,071,346✔
1946
    end
2,106,923✔
1947
    return arr
35,597✔
1948
end
1949

1950
_cat(n::Integer, x::Integer...) = reshape([x...], (ntuple(Returns(1), n-1)..., length(x)))
1✔
1951

1952
## find ##
1953

1954
"""
1955
    findnext(A, i)
1956

1957
Find the next index after or including `i` of a `true` element of `A`,
1958
or `nothing` if not found.
1959

1960
Indices are of the same type as those returned by [`keys(A)`](@ref)
1961
and [`pairs(A)`](@ref).
1962

1963
# Examples
1964
```jldoctest
1965
julia> A = [false, false, true, false]
1966
4-element Vector{Bool}:
1967
 0
1968
 0
1969
 1
1970
 0
1971

1972
julia> findnext(A, 1)
1973
3
1974

1975
julia> findnext(A, 4) # returns nothing, but not printed in the REPL
1976

1977
julia> A = [false false; true false]
1978
2×2 Matrix{Bool}:
1979
 0  0
1980
 1  0
1981

1982
julia> findnext(A, CartesianIndex(1, 1))
1983
CartesianIndex(2, 1)
1984
```
1985
"""
1986
findnext(A, start) = findnext(identity, A, start)
133✔
1987

1988
"""
1989
    findfirst(A)
1990

1991
Return the index or key of the first `true` value in `A`.
1992
Return `nothing` if no such value is found.
1993
To search for other kinds of values, pass a predicate as the first argument.
1994

1995
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
1996
and [`pairs(A)`](@ref).
1997

1998
See also: [`findall`](@ref), [`findnext`](@ref), [`findlast`](@ref), [`searchsortedfirst`](@ref).
1999

2000
# Examples
2001
```jldoctest
2002
julia> A = [false, false, true, false]
2003
4-element Vector{Bool}:
2004
 0
2005
 0
2006
 1
2007
 0
2008

2009
julia> findfirst(A)
2010
3
2011

2012
julia> findfirst(falses(3)) # returns nothing, but not printed in the REPL
2013

2014
julia> A = [false false; true false]
2015
2×2 Matrix{Bool}:
2016
 0  0
2017
 1  0
2018

2019
julia> findfirst(A)
2020
CartesianIndex(2, 1)
2021
```
2022
"""
2023
findfirst(A) = findfirst(identity, A)
2✔
2024

2025
# Needed for bootstrap, and allows defining only an optimized findnext method
2026
findfirst(A::AbstractArray) = findnext(A, first(keys(A)))
102✔
2027

2028
"""
2029
    findnext(predicate::Function, A, i)
2030

2031
Find the next index after or including `i` of an element of `A`
2032
for which `predicate` returns `true`, or `nothing` if not found.
2033

2034
Indices are of the same type as those returned by [`keys(A)`](@ref)
2035
and [`pairs(A)`](@ref).
2036

2037
# Examples
2038
```jldoctest
2039
julia> A = [1, 4, 2, 2];
2040

2041
julia> findnext(isodd, A, 1)
2042
1
2043

2044
julia> findnext(isodd, A, 2) # returns nothing, but not printed in the REPL
2045

2046
julia> A = [1 4; 2 2];
2047

2048
julia> findnext(isodd, A, CartesianIndex(1, 1))
2049
CartesianIndex(1, 1)
2050
```
2051
"""
2052
function findnext(testf::Function, A, start)
17,587✔
2053
    i = oftype(first(keys(A)), start)
17,390✔
2054
    l = last(keys(A))
33,568,464✔
2055
    i > l && return nothing
33,568,567✔
2056
    while true
169,295,858✔
2057
        testf(A[i]) && return i
169,297,249✔
2058
        i == l && break
168,897,044✔
2059
        # nextind(A, l) can throw/overflow
2060
        i = nextind(A, i)
164,834,128✔
2061
    end
164,834,109✔
2062
    return nothing
4,062,911✔
2063
end
2064

2065
"""
2066
    findfirst(predicate::Function, A)
2067

2068
Return the index or key of the first element of `A` for which `predicate` returns `true`.
2069
Return `nothing` if there is no such element.
2070

2071
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2072
and [`pairs(A)`](@ref).
2073

2074
# Examples
2075
```jldoctest
2076
julia> A = [1, 4, 2, 2]
2077
4-element Vector{Int64}:
2078
 1
2079
 4
2080
 2
2081
 2
2082

2083
julia> findfirst(iseven, A)
2084
2
2085

2086
julia> findfirst(x -> x>10, A) # returns nothing, but not printed in the REPL
2087

2088
julia> findfirst(isequal(4), A)
2089
2
2090

2091
julia> A = [1 4; 2 2]
2092
2×2 Matrix{Int64}:
2093
 1  4
2094
 2  2
2095

2096
julia> findfirst(iseven, A)
2097
CartesianIndex(2, 1)
2098
```
2099
"""
2100
function findfirst(testf::Function, A)
13✔
2101
    for (i, a) in pairs(A)
21✔
2102
        testf(a) && return i
14✔
2103
    end
11✔
2104
    return nothing
6✔
2105
end
2106

2107
# Needed for bootstrap, and allows defining only an optimized findnext method
2108
findfirst(testf::Function, A::Union{AbstractArray, AbstractString}) =
203,601,340✔
2109
    findnext(testf, A, first(keys(A)))
2110

2111
findfirst(p::Union{Fix2{typeof(isequal),Int},Fix2{typeof(==),Int}}, r::OneTo{Int}) =
3✔
2112
    1 <= p.x <= r.stop ? p.x : nothing
2113

2114
findfirst(p::Union{Fix2{typeof(isequal),T},Fix2{typeof(==),T}}, r::AbstractUnitRange) where {T<:Integer} =
4✔
2115
    first(r) <= p.x <= last(r) ? firstindex(r) + Int(p.x - first(r)) : nothing
2116

2117
function findfirst(p::Union{Fix2{typeof(isequal),T},Fix2{typeof(==),T}}, r::StepRange{T,S}) where {T,S}
6✔
2118
    isempty(r) && return nothing
6✔
2119
    minimum(r) <= p.x <= maximum(r) || return nothing
7✔
2120
    d = convert(S, p.x - first(r))
3✔
2121
    iszero(d % step(r)) || return nothing
3✔
2122
    return d ÷ step(r) + 1
3✔
2123
end
2124

2125
"""
2126
    findprev(A, i)
2127

2128
Find the previous index before or including `i` of a `true` element of `A`,
2129
or `nothing` if not found.
2130

2131
Indices are of the same type as those returned by [`keys(A)`](@ref)
2132
and [`pairs(A)`](@ref).
2133

2134
See also: [`findnext`](@ref), [`findfirst`](@ref), [`findall`](@ref).
2135

2136
# Examples
2137
```jldoctest
2138
julia> A = [false, false, true, true]
2139
4-element Vector{Bool}:
2140
 0
2141
 0
2142
 1
2143
 1
2144

2145
julia> findprev(A, 3)
2146
3
2147

2148
julia> findprev(A, 1) # returns nothing, but not printed in the REPL
2149

2150
julia> A = [false false; true true]
2151
2×2 Matrix{Bool}:
2152
 0  0
2153
 1  1
2154

2155
julia> findprev(A, CartesianIndex(2, 1))
2156
CartesianIndex(2, 1)
2157
```
2158
"""
2159
findprev(A, start) = findprev(identity, A, start)
3,833✔
2160

2161
"""
2162
    findlast(A)
2163

2164
Return the index or key of the last `true` value in `A`.
2165
Return `nothing` if there is no `true` value in `A`.
2166

2167
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2168
and [`pairs(A)`](@ref).
2169

2170
See also: [`findfirst`](@ref), [`findprev`](@ref), [`findall`](@ref).
2171

2172
# Examples
2173
```jldoctest
2174
julia> A = [true, false, true, false]
2175
4-element Vector{Bool}:
2176
 1
2177
 0
2178
 1
2179
 0
2180

2181
julia> findlast(A)
2182
3
2183

2184
julia> A = falses(2,2);
2185

2186
julia> findlast(A) # returns nothing, but not printed in the REPL
2187

2188
julia> A = [true false; true false]
2189
2×2 Matrix{Bool}:
2190
 1  0
2191
 1  0
2192

2193
julia> findlast(A)
2194
CartesianIndex(2, 1)
2195
```
2196
"""
2197
findlast(A) = findlast(identity, A)
22✔
2198

2199
# Needed for bootstrap, and allows defining only an optimized findprev method
2200
findlast(A::AbstractArray) = findprev(A, last(keys(A)))
3,831✔
2201

2202
"""
2203
    findprev(predicate::Function, A, i)
2204

2205
Find the previous index before or including `i` of an element of `A`
2206
for which `predicate` returns `true`, or `nothing` if not found.
2207

2208
Indices are of the same type as those returned by [`keys(A)`](@ref)
2209
and [`pairs(A)`](@ref).
2210

2211
# Examples
2212
```jldoctest
2213
julia> A = [4, 6, 1, 2]
2214
4-element Vector{Int64}:
2215
 4
2216
 6
2217
 1
2218
 2
2219

2220
julia> findprev(isodd, A, 1) # returns nothing, but not printed in the REPL
2221

2222
julia> findprev(isodd, A, 3)
2223
3
2224

2225
julia> A = [4 6; 1 2]
2226
2×2 Matrix{Int64}:
2227
 4  6
2228
 1  2
2229

2230
julia> findprev(isodd, A, CartesianIndex(1, 2))
2231
CartesianIndex(2, 1)
2232
```
2233
"""
2234
function findprev(testf::Function, A, start)
28,389✔
2235
    f = first(keys(A))
28,389✔
2236
    i = oftype(f, start)
28,400✔
2237
    i < f && return nothing
58,210✔
2238
    while true
43,364✔
2239
        testf(A[i]) && return i
43,403✔
2240
        i == f && break
13,532✔
2241
        # prevind(A, f) can throw/underflow
2242
        i = prevind(A, i)
13,474✔
2243
    end
13,446✔
2244
    return nothing
55✔
2245
end
2246

2247
"""
2248
    findlast(predicate::Function, A)
2249

2250
Return the index or key of the last element of `A` for which `predicate` returns `true`.
2251
Return `nothing` if there is no such element.
2252

2253
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2254
and [`pairs(A)`](@ref).
2255

2256
# Examples
2257
```jldoctest
2258
julia> A = [1, 2, 3, 4]
2259
4-element Vector{Int64}:
2260
 1
2261
 2
2262
 3
2263
 4
2264

2265
julia> findlast(isodd, A)
2266
3
2267

2268
julia> findlast(x -> x > 5, A) # returns nothing, but not printed in the REPL
2269

2270
julia> A = [1 2; 3 4]
2271
2×2 Matrix{Int64}:
2272
 1  2
2273
 3  4
2274

2275
julia> findlast(isodd, A)
2276
CartesianIndex(2, 1)
2277
```
2278
"""
2279
function findlast(testf::Function, A)
4✔
2280
    for (i, a) in Iterators.reverse(pairs(A))
4✔
2281
        testf(a) && return i
6✔
2282
    end
6✔
2283
    return nothing
2✔
2284
end
2285

2286
# Needed for bootstrap, and allows defining only an optimized findprev method
2287
findlast(testf::Function, A::Union{AbstractArray, AbstractString}) =
12,844✔
2288
    findprev(testf, A, last(keys(A)))
2289

2290
"""
2291
    findall(f::Function, A)
2292

2293
Return a vector `I` of the indices or keys of `A` where `f(A[I])` returns `true`.
2294
If there are no such elements of `A`, return an empty array.
2295

2296
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2297
and [`pairs(A)`](@ref).
2298

2299
# Examples
2300
```jldoctest
2301
julia> x = [1, 3, 4]
2302
3-element Vector{Int64}:
2303
 1
2304
 3
2305
 4
2306

2307
julia> findall(isodd, x)
2308
2-element Vector{Int64}:
2309
 1
2310
 2
2311

2312
julia> A = [1 2 0; 3 4 0]
2313
2×3 Matrix{Int64}:
2314
 1  2  0
2315
 3  4  0
2316
julia> findall(isodd, A)
2317
2-element Vector{CartesianIndex{2}}:
2318
 CartesianIndex(1, 1)
2319
 CartesianIndex(2, 1)
2320

2321
julia> findall(!iszero, A)
2322
4-element Vector{CartesianIndex{2}}:
2323
 CartesianIndex(1, 1)
2324
 CartesianIndex(2, 1)
2325
 CartesianIndex(1, 2)
2326
 CartesianIndex(2, 2)
2327

2328
julia> d = Dict(:A => 10, :B => -1, :C => 0)
2329
Dict{Symbol, Int64} with 3 entries:
2330
  :A => 10
2331
  :B => -1
2332
  :C => 0
2333

2334
julia> findall(x -> x >= 0, d)
2335
2-element Vector{Symbol}:
2336
 :A
2337
 :C
2338

2339
```
2340
"""
2341
findall(testf::Function, A) = collect(first(p) for p in pairs(A) if testf(last(p)))
52✔
2342

2343
# Broadcasting is much faster for small testf, and computing
2344
# integer indices from logical index using findall has a negligible cost
2345
findall(testf::F, A::AbstractArray) where {F<:Function} = findall(testf.(A))
316✔
2346

2347
"""
2348
    findall(A)
2349

2350
Return a vector `I` of the `true` indices or keys of `A`.
2351
If there are no such elements of `A`, return an empty array.
2352
To search for other kinds of values, pass a predicate as the first argument.
2353

2354
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2355
and [`pairs(A)`](@ref).
2356

2357
See also: [`findfirst`](@ref), [`searchsorted`](@ref).
2358

2359
# Examples
2360
```jldoctest
2361
julia> A = [true, false, false, true]
2362
4-element Vector{Bool}:
2363
 1
2364
 0
2365
 0
2366
 1
2367

2368
julia> findall(A)
2369
2-element Vector{Int64}:
2370
 1
2371
 4
2372

2373
julia> A = [true false; false true]
2374
2×2 Matrix{Bool}:
2375
 1  0
2376
 0  1
2377

2378
julia> findall(A)
2379
2-element Vector{CartesianIndex{2}}:
2380
 CartesianIndex(1, 1)
2381
 CartesianIndex(2, 2)
2382

2383
julia> findall(falses(3))
2384
Int64[]
2385
```
2386
"""
2387
function findall(A)
3✔
2388
    collect(first(p) for p in pairs(A) if last(p))
3✔
2389
end
2390

2391
# Allocating result upfront is faster (possible only when collection can be iterated twice)
2392
function _findall(f::Function, A::AbstractArray{Bool})
18✔
2393
    n = count(f, A)
22✔
2394
    I = Vector{eltype(keys(A))}(undef, n)
18✔
2395
    isempty(I) && return I
18✔
2396
    _findall(f, I, A)
16✔
2397
end
2398

2399
function _findall(f::Function, I::Vector, A::AbstractArray{Bool})
5✔
2400
    cnt = 1
5✔
2401
    len = length(I)
5✔
2402
    for (k, v) in pairs(A)
10✔
2403
        @inbounds I[cnt] = k
57✔
2404
        cnt += f(v)
57✔
2405
        cnt > len && return I
57✔
2406
    end
104✔
2407
    # In case of impure f, this line could potentially be hit. In that case,
2408
    # we can't assume I is the correct length.
2409
    resize!(I, cnt - 1)
×
2410
end
2411

2412
function _findall(f::Function, I::Vector, A::AbstractVector{Bool})
11✔
2413
    i = firstindex(A)
11✔
2414
    cnt = 1
11✔
2415
    len = length(I)
11✔
2416
    while cnt ≤ len
310✔
2417
        @inbounds I[cnt] = i
299✔
2418
        cnt += f(@inbounds A[i])
299✔
2419
        i = nextind(A, i)
299✔
2420
    end
299✔
2421
    cnt - 1 == len ? I : resize!(I, cnt - 1)
11✔
2422
end
2423

2424
findall(f::Function, A::AbstractArray{Bool}) = _findall(f, A)
4✔
2425
findall(f::Fix2{typeof(in)}, A::AbstractArray{Bool}) = _findall(f, A)
×
2426
findall(A::AbstractArray{Bool}) = _findall(identity, A)
17✔
2427

2428
findall(x::Bool) = x ? [1] : Vector{Int}()
2✔
2429
findall(testf::Function, x::Number) = testf(x) ? [1] : Vector{Int}()
2✔
2430
findall(p::Fix2{typeof(in)}, x::Number) = x in p.x ? [1] : Vector{Int}()
2✔
2431

2432
# similar to Matlab's ismember
2433
"""
2434
    indexin(a, b)
2435

2436
Return an array containing the first index in `b` for
2437
each value in `a` that is a member of `b`. The output
2438
array contains `nothing` wherever `a` is not a member of `b`.
2439

2440
See also: [`sortperm`](@ref), [`findfirst`](@ref).
2441

2442
# Examples
2443
```jldoctest
2444
julia> a = ['a', 'b', 'c', 'b', 'd', 'a'];
2445

2446
julia> b = ['a', 'b', 'c'];
2447

2448
julia> indexin(a, b)
2449
6-element Vector{Union{Nothing, Int64}}:
2450
 1
2451
 2
2452
 3
2453
 2
2454
  nothing
2455
 1
2456

2457
julia> indexin(b, a)
2458
3-element Vector{Union{Nothing, Int64}}:
2459
 1
2460
 2
2461
 3
2462
```
2463
"""
2464
function indexin(a, b::AbstractArray)
7✔
2465
    inds = keys(b)
7✔
2466
    bdict = Dict{eltype(b),eltype(inds)}()
7✔
2467
    for (val, ind) in zip(b, inds)
14✔
2468
        get!(bdict, val, ind)
30✔
2469
    end
53✔
2470
    return Union{eltype(inds), Nothing}[
7✔
2471
        get(bdict, i, nothing) for i in a
2472
    ]
2473
end
2474

2475
function _findin(a::Union{AbstractArray, Tuple}, b)
375✔
2476
    ind  = Vector{eltype(keys(a))}()
561✔
2477
    bset = Set(b)
375✔
2478
    @inbounds for (i,ai) in pairs(a)
606✔
2479
        ai in bset && push!(ind, i)
90,524✔
2480
    end
180,565✔
2481
    ind
375✔
2482
end
2483

2484
# If two collections are already sorted, _findin can be computed with
2485
# a single traversal of the two collections. This is much faster than
2486
# using a hash table (although it has the same complexity).
2487
function _sortedfindin(v::Union{AbstractArray, Tuple}, w)
9✔
2488
    viter, witer = keys(v), eachindex(w)
9✔
2489
    out  = eltype(viter)[]
9✔
2490
    vy, wy = iterate(viter), iterate(witer)
17✔
2491
    if vy === nothing || wy === nothing
17✔
2492
        return out
2✔
2493
    end
2494
    viteri, i = vy
7✔
2495
    witerj, j = wy
7✔
2496
    @inbounds begin
7✔
2497
        vi, wj = v[viteri], w[witerj]
7✔
2498
        while true
54✔
2499
            if isless(vi, wj)
56✔
2500
                vy = iterate(viter, i)
25✔
2501
                if vy === nothing
14✔
2502
                    break
2✔
2503
                end
2504
                viteri, i = vy
12✔
2505
                vi        = v[viteri]
12✔
2506
            elseif isless(wj, vi)
40✔
2507
                wy = iterate(witer, j)
44✔
2508
                if wy === nothing
24✔
2509
                    break
4✔
2510
                end
2511
                witerj, j = wy
20✔
2512
                wj        = w[witerj]
20✔
2513
            else
2514
                push!(out, viteri)
16✔
2515
                vy = iterate(viter, i)
25✔
2516
                if vy === nothing
16✔
2517
                    break
1✔
2518
                end
2519
                # We only increment the v iterator because v can have
2520
                # repeated matches to a single value in w
2521
                viteri, i = vy
15✔
2522
                vi        = v[viteri]
15✔
2523
            end
2524
        end
47✔
2525
    end
2526
    return out
7✔
2527
end
2528

2529
function findall(pred::Fix2{typeof(in),<:Union{Array{<:Real},Real}}, x::Array{<:Real})
15✔
2530
    if issorted(x, Sort.Forward) && issorted(pred.x, Sort.Forward)
25✔
2531
        return _sortedfindin(x, pred.x)
9✔
2532
    else
2533
        return _findin(x, pred.x)
6✔
2534
    end
2535
end
2536
# issorted fails for some element types so the method above has to be restricted
2537
# to element with isless/< defined.
2538
findall(pred::Fix2{typeof(in)}, x::AbstractArray) = _findin(x, pred.x)
373✔
2539
findall(pred::Fix2{typeof(in)}, x::Tuple) = _findin(x, pred.x)
×
2540

2541
# Copying subregions
2542
function indcopy(sz::Dims, I::Vector)
1✔
2543
    n = length(I)
1✔
2544
    s = sz[n]
1✔
2545
    for i = n+1:length(sz)
1✔
2546
        s *= sz[i]
×
2547
    end
×
2548
    dst = eltype(I)[_findin(I[i], i < n ? (1:sz[i]) : (1:s)) for i = 1:n]
2✔
2549
    src = eltype(I)[I[i][_findin(I[i], i < n ? (1:sz[i]) : (1:s))] for i = 1:n]
2✔
2550
    dst, src
1✔
2551
end
2552

2553
function indcopy(sz::Dims, I::Tuple{Vararg{RangeIndex}})
1✔
2554
    n = length(I)
1✔
2555
    s = sz[n]
1✔
2556
    for i = n+1:length(sz)
1✔
2557
        s *= sz[i]
×
2558
    end
×
2559
    dst::typeof(I) = ntuple(i-> _findin(I[i], i < n ? (1:sz[i]) : (1:s)), n)::typeof(I)
3✔
2560
    src::typeof(I) = ntuple(i-> I[i][_findin(I[i], i < n ? (1:sz[i]) : (1:s))], n)::typeof(I)
3✔
2561
    dst, src
1✔
2562
end
2563

2564
## Filter ##
2565

2566
"""
2567
    filter(f, a)
2568

2569
Return a copy of collection `a`, removing elements for which `f` is `false`.
2570
The function `f` is passed one argument.
2571

2572
!!! compat "Julia 1.4"
2573
    Support for `a` as a tuple requires at least Julia 1.4.
2574

2575
See also: [`filter!`](@ref), [`Iterators.filter`](@ref).
2576

2577
# Examples
2578
```jldoctest
2579
julia> a = 1:10
2580
1:10
2581

2582
julia> filter(isodd, a)
2583
5-element Vector{Int64}:
2584
 1
2585
 3
2586
 5
2587
 7
2588
 9
2589
```
2590
"""
2591
function filter(f, a::Array{T, N}) where {T, N}
443,750✔
2592
    j = 1
443,038✔
2593
    b = Vector{T}(undef, length(a))
443,750✔
2594
    for ai in a
443,762✔
2595
        @inbounds b[j] = ai
1,389,427✔
2596
        j = ifelse(f(ai)::Bool, j+1, j)
1,390,367✔
2597
    end
1,833,079✔
2598
    resize!(b, j-1)
887,499✔
2599
    sizehint!(b, length(b))
443,750✔
2600
    b
443,750✔
2601
end
2602

2603
function filter(f, a::AbstractArray)
376✔
2604
    (IndexStyle(a) != IndexLinear()) && return a[map(f, a)::AbstractArray{Bool}]
376✔
2605

2606
    j = 1
376✔
2607
    idxs = Vector{Int}(undef, length(a))
379✔
2608
    for idx in eachindex(a)
623✔
2609
        @inbounds idxs[j] = idx
103,122✔
2610
        ai = @inbounds a[idx]
103,122✔
2611
        j = ifelse(f(ai)::Bool, j+1, j)
137,190✔
2612
    end
205,996✔
2613
    resize!(idxs, j-1)
750✔
2614
    res = a[idxs]
375✔
2615
    empty!(idxs)
375✔
2616
    sizehint!(idxs, 0)
375✔
2617
    return res
375✔
2618
end
2619

2620
"""
2621
    filter!(f, a)
2622

2623
Update collection `a`, removing elements for which `f` is `false`.
2624
The function `f` is passed one argument.
2625

2626
# Examples
2627
```jldoctest
2628
julia> filter!(isodd, Vector(1:10))
2629
5-element Vector{Int64}:
2630
 1
2631
 3
2632
 5
2633
 7
2634
 9
2635
```
2636
"""
2637
function filter!(f, a::AbstractVector)
976,999✔
2638
    j = firstindex(a)
757✔
2639
    for ai in a
998,201✔
2640
        @inbounds a[j] = ai
3,508,895✔
2641
        j = ifelse(f(ai)::Bool, nextind(a, j), j)
6,577,296✔
2642
    end
4,464,701✔
2643
    j > lastindex(a) && return a
976,999✔
2644
    if a isa Vector
424✔
2645
        resize!(a, j-1)
330,740✔
2646
        sizehint!(a, j-1)
165,370✔
2647
    else
2648
        deleteat!(a, j:lastindex(a))
1✔
2649
    end
2650
    return a
165,371✔
2651
end
2652

2653
"""
2654
    filter(f)
2655

2656
Create a function that filters its arguments with function `f` using [`filter`](@ref), i.e.
2657
a function equivalent to `x -> filter(f, x)`.
2658

2659
The returned function is of type `Base.Fix1{typeof(filter)}`, which can be
2660
used to implement specialized methods.
2661

2662
# Examples
2663
```jldoctest
2664
julia> (1, 2, Inf, 4, NaN, 6) |> filter(isfinite)
2665
(1, 2, 4, 6)
2666

2667
julia> map(filter(iseven), [1:3, 2:4, 3:5])
2668
3-element Vector{Vector{Int64}}:
2669
 [2]
2670
 [2, 4]
2671
 [4]
2672
```
2673
!!! compat "Julia 1.9"
2674
    This method requires at least Julia 1.9.
2675
"""
2676
function filter(f)
1✔
2677
    Fix1(filter, f)
1✔
2678
end
2679

2680
"""
2681
    keepat!(a::Vector, inds)
2682
    keepat!(a::BitVector, inds)
2683

2684
Remove the items at all the indices which are not given by `inds`,
2685
and return the modified `a`.
2686
Items which are kept are shifted to fill the resulting gaps.
2687

2688
`inds` must be an iterator of sorted and unique integer indices.
2689
See also [`deleteat!`](@ref).
2690

2691
!!! compat "Julia 1.7"
2692
    This function is available as of Julia 1.7.
2693

2694
# Examples
2695
```jldoctest
2696
julia> keepat!([6, 5, 4, 3, 2, 1], 1:2:5)
2697
3-element Vector{Int64}:
2698
 6
2699
 4
2700
 2
2701
```
2702
"""
2703
keepat!(a::Vector, inds) = _keepat!(a, inds)
9✔
2704

2705
"""
2706
    keepat!(a::Vector, m::AbstractVector{Bool})
2707
    keepat!(a::BitVector, m::AbstractVector{Bool})
2708

2709
The in-place version of logical indexing `a = a[m]`. That is, `keepat!(a, m)` on
2710
vectors of equal length `a` and `m` will remove all elements from `a` for which
2711
`m` at the corresponding index is `false`.
2712

2713
# Examples
2714
```jldoctest
2715
julia> a = [:a, :b, :c];
2716

2717
julia> keepat!(a, [true, false, true])
2718
2-element Vector{Symbol}:
2719
 :a
2720
 :c
2721

2722
julia> a
2723
2-element Vector{Symbol}:
2724
 :a
2725
 :c
2726
```
2727
"""
2728
keepat!(a::Vector, m::AbstractVector{Bool}) = _keepat!(a, m)
4✔
2729

2730
# set-like operators for vectors
2731
# These are moderately efficient, preserve order, and remove dupes.
2732

2733
_unique_filter!(pred::P, update!::U, state) where {P,U} = function (x)
3,627✔
2734
    # P, U force specialization
2735
    if pred(x, state)
9,120✔
2736
        update!(state, x)
3,533✔
2737
        true
3,533✔
2738
    else
2739
        false
5,505✔
2740
    end
2741
end
2742

2743
_grow_filter!(seen) = _unique_filter!(∉, push!, seen)
242✔
2744
_shrink_filter!(keep) = _unique_filter!(∈, pop!, keep)
942✔
2745

2746
function _grow!(pred!, v::AbstractVector, itrs)
269✔
2747
    filter!(pred!, v) # uniquify v
269✔
2748
    for itr in itrs
269✔
2749
        mapfilter(pred!, push!, itr, v)
517✔
2750
    end
766✔
2751
    return v
269✔
2752
end
2753

2754
union!(v::AbstractVector{T}, itrs...) where {T} =
236✔
2755
    _grow!(_grow_filter!(sizehint!(Set{T}(), length(v))), v, itrs)
2756

2757
symdiff!(v::AbstractVector{T}, itrs...) where {T} =
33✔
2758
    _grow!(_shrink_filter!(symdiff!(Set{T}(), v, itrs...)), v, itrs)
2759

2760
function _shrink!(shrinker!::F, v::AbstractVector, itrs) where F
6✔
2761
    seen = Set{eltype(v)}()
6✔
2762
    filter!(_grow_filter!(seen), v)
6✔
2763
    shrinker!(seen, itrs...)
7✔
2764
    filter!(in(seen), v)
6✔
2765
end
2766

2767
intersect!(v::AbstractVector, itrs...) = _shrink!(intersect!, v, itrs)
3✔
2768
setdiff!(  v::AbstractVector, itrs...) = _shrink!(setdiff!, v, itrs)
3✔
2769

2770
vectorfilter(T::Type, f, v) = T[x for x in v if f(x)]
911✔
2771

2772
function _shrink(shrinker!::F, itr, itrs) where F
847✔
2773
    T = promote_eltype(itr, itrs...)
847✔
2774
    keep = shrinker!(Set{T}(itr), itrs...)
856✔
2775
    vectorfilter(T, _shrink_filter!(keep), itr)
847✔
2776
end
2777

2778
intersect(itr, itrs...) = _shrink(intersect!, itr, itrs)
390✔
2779
setdiff(  itr, itrs...) = _shrink(setdiff!, itr, itrs)
457✔
2780

2781
function intersect(v::AbstractVector, r::AbstractRange)
59✔
2782
    T = promote_eltype(v, r)
6✔
2783
    common = Iterators.filter(in(r), v)
63✔
2784
    seen = Set{T}(common)
63✔
2785
    return vectorfilter(T, _shrink_filter!(seen), common)
63✔
2786
end
2787
intersect(r::AbstractRange, v::AbstractVector) = intersect(v, r)
4✔
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