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

JuliaLang / julia / #37497

pending completion
#37497

push

local

web-flow
<a href="https://github.com/JuliaLang/julia/commit/<a class=hub.com/JuliaLang/julia/commit/def2ddacc9a9b064d06c24d12885427fb0502465">def2ddacc<a href="https://github.com/JuliaLang/julia/commit/def2ddacc9a9b064d06c24d12885427fb0502465">&quot;&gt;make default worker pool an AbstractWorkerPool (#49101)

Changes [Distributed._default_worker_pool](https://github.com/JuliaLang/julia/blob/</a><a class="double-link" href="https://github.com/JuliaLang/julia/commit/<a class="double-link" href="https://github.com/JuliaLang/julia/commit/5f5d2040511b42ba74bd7529a0eac9cf817ad496">5f5d20405</a>">5f5d20405</a><a href="https://github.com/JuliaLang/julia/commit/def2ddacc9a9b064d06c24d12885427fb0502465">/stdlib/Distributed/src/workerpool.jl#L242) to hold an `AbstractWorkerPool` instead of `WorkerPool`. With this, alternate implementations can be plugged in as the default pool. Helps in cases where a cluster is always meant to use a certain custom pool. Lower level calls can then work without having to pass a custom pool reference with every call.

4 of 4 new or added lines in 2 files covered. (100.0%)

71044 of 82770 relevant lines covered (85.83%)

33857692.69 hits per line

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

83.48
/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,193✔
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
"""
126
    @_safeindex
127

128
This internal macro converts:
129
- `getindex(xs::Tuple, )` -> `__inbounds_getindex(args...)`
130
- `setindex!(xs::Vector, args...)` -> `__inbounds_setindex!(xs, args...)`
131
to tell the compiler that indexing operations within the applied expression are always
132
inbounds and do not need to taint `:consistent` and `:nothrow`.
133
"""
134
macro _safeindex(ex)
135
    return esc(_safeindex(__module__, ex))
136
end
137
function _safeindex(__module__, ex)
×
138
    isa(ex, Expr) || return ex
×
139
    if ex.head === :(=)
×
140
        lhs = arrayref(true, ex.args, 1)
×
141
        if isa(lhs, Expr) && lhs.head === :ref # xs[i] = x
×
142
            rhs = arrayref(true, ex.args, 2)
×
143
            xs = arrayref(true, lhs.args, 1)
×
144
            args = Vector{Any}(undef, length(lhs.args)-1)
×
145
            for i = 2:length(lhs.args)
×
146
                arrayset(true, args, _safeindex(__module__, arrayref(true, lhs.args, i)), i-1)
×
147
            end
×
148
            return Expr(:call, GlobalRef(__module__, :__inbounds_setindex!), xs, _safeindex(__module__, rhs), args...)
×
149
        end
150
    elseif ex.head === :ref # xs[i]
×
151
        return Expr(:call, GlobalRef(__module__, :__inbounds_getindex), ex.args...)
×
152
    end
153
    args = Vector{Any}(undef, length(ex.args))
×
154
    for i = 1:length(ex.args)
×
155
        arrayset(true, args, _safeindex(__module__, arrayref(true, ex.args, i)), i)
×
156
    end
×
157
    return Expr(ex.head, args...)
×
158
end
159

160
vect() = Vector{Any}()
23,392,212✔
161
function vect(X::T...) where T
126,913✔
162
    @_terminates_locally_meta
37,086✔
163
    vec = Vector{T}(undef, length(X))
1,204,647✔
164
    @_safeindex for i = 1:length(X)
1,247,869✔
165
        vec[i] = X[i]
4,303,620✔
166
    end
6,317,113✔
167
    return vec
1,204,647✔
168
end
169

170
"""
171
    vect(X...)
172

173
Create a [`Vector`](@ref) with element type computed from the `promote_typeof` of the argument,
174
containing the argument list.
175

176
# Examples
177
```jldoctest
178
julia> a = Base.vect(UInt8(1), 2.5, 1//2)
179
3-element Vector{Float64}:
180
 1.0
181
 2.5
182
 0.5
183
```
184
"""
185
function vect(X...)
53,593✔
186
    T = promote_typeof(X...)
53,593✔
187
    return T[X...]
55,718✔
188
end
189

190
size(a::Array, d::Integer) = arraysize(a, convert(Int, d))
2,931,278✔
191
size(a::Vector) = (arraysize(a,1),)
4,741,577,143✔
192
size(a::Matrix) = (arraysize(a,1), arraysize(a,2))
7,253,868✔
193
size(a::Array{<:Any,N}) where {N} = (@inline; ntuple(M -> size(a, M), Val(N))::Dims)
2,661,010✔
194

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

197
allocatedinline(@nospecialize T::Type) = (@_total_meta; ccall(:jl_stored_inline, Cint, (Any,), T) != Cint(0))
2,978,666✔
198

199
"""
200
    Base.isbitsunion(::Type{T})
201

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

204
# Examples
205
```jldoctest
206
julia> Base.isbitsunion(Union{Float64, UInt8})
207
true
208

209
julia> Base.isbitsunion(Union{Float64, String})
210
false
211
```
212
"""
213
isbitsunion(u::Union) = allocatedinline(u)
1,463✔
214
isbitsunion(x) = false
12,181✔
215

216
function _unsetindex!(A::Array{T}, i::Int) where {T}
62,674✔
217
    @inline
1,529✔
218
    @boundscheck checkbounds(A, i)
3,101,188✔
219
    t = @_gc_preserve_begin A
3,102,411✔
220
    p = Ptr{Ptr{Cvoid}}(pointer(A, i))
3,101,783✔
221
    if !allocatedinline(T)
1,529✔
222
        Intrinsics.atomic_pointerset(p, C_NULL, :monotonic)
2,853,961✔
223
    elseif T isa DataType
248,385✔
224
        if !datatype_pointerfree(T)
1,767✔
225
            for j = 1:Core.sizeof(Ptr{Cvoid}):Core.sizeof(T)
1,715✔
226
                Intrinsics.atomic_pointerset(p + j - 1, C_NULL, :monotonic)
4,641✔
227
            end
7,485✔
228
        end
229
    end
230
    @_gc_preserve_end t
3,102,194✔
231
    return A
3,101,897✔
232
end
233

234

235
"""
236
    Base.bitsunionsize(U::Union) -> Int
237

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

240
# Examples
241
```jldoctest
242
julia> Base.bitsunionsize(Union{Float64, UInt8})
243
8
244

245
julia> Base.bitsunionsize(Union{Float64, UInt8, Int128})
246
16
247
```
248
"""
249
function bitsunionsize(u::Union)
4✔
250
    isinline, sz, _ = uniontype_layout(u)
4✔
251
    @assert isinline
4✔
252
    return sz
4✔
253
end
254

255
elsize(@nospecialize _::Type{A}) where {T,A<:Array{T}} = aligned_sizeof(T)
1,788,294✔
256
sizeof(a::Array) = Core.sizeof(a)
3,386,778✔
257

258
function isassigned(a::Array, i::Int...)
13,965,496✔
259
    @inline
8,429,452✔
260
    @boundscheck checkbounds(Bool, a, i...) || return false
2,202,506,060✔
261
    ii = (_sub2ind(size(a), i...) % UInt) - 1
2,142,917,496✔
262
    ccall(:jl_array_isassigned, Cint, (Any, UInt), a, ii) == 1
2,202,126,656✔
263
end
264

265
## copy ##
266

267
"""
268
    unsafe_copyto!(dest::Ptr{T}, src::Ptr{T}, N)
269

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

273
The `unsafe` prefix on this function indicates that no validation is performed on the
274
pointers `dest` and `src` to ensure that they are valid. Incorrect usage may corrupt or
275
segfault your program, in the same manner as C.
276
"""
277
function unsafe_copyto!(dest::Ptr{T}, src::Ptr{T}, n) where T
2,183,567✔
278
    # Do not use this to copy data between pointer arrays.
279
    # It can't be made safe no matter how carefully you checked.
280
    ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
17,811,319✔
281
          dest, src, n * aligned_sizeof(T))
282
    return dest
17,084,718✔
283
end
284

285

286
function _unsafe_copyto!(dest, doffs, src, soffs, n)
25,352,420✔
287
    destp = pointer(dest, doffs)
25,352,420✔
288
    srcp = pointer(src, soffs)
25,352,420✔
289
    @inbounds if destp < srcp || destp > srcp + n
41,468,921✔
290
        for i = 1:n
50,704,838✔
291
            if isassigned(src, soffs + i - 1)
142,498,049✔
292
                dest[doffs + i - 1] = src[soffs + i - 1]
146,069,748✔
293
            else
294
                _unsetindex!(dest, doffs + i - 1)
720✔
295
            end
296
        end
259,643,439✔
297
    else
298
        for i = n:-1:1
×
299
            if isassigned(src, soffs + i - 1)
×
300
                dest[doffs + i - 1] = src[soffs + i - 1]
×
301
            else
302
                _unsetindex!(dest, doffs + i - 1)
×
303
            end
304
        end
×
305
    end
306
    return dest
25,352,179✔
307
end
308

309
"""
310
    unsafe_copyto!(dest::Array, do, src::Array, so, N)
311

312
Copy `N` elements from a source array to a destination, starting at the linear index `so` in the
313
source and `do` in the destination (1-indexed).
314

315
The `unsafe` prefix on this function indicates that no validation is performed to ensure
316
that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in
317
the same manner as C.
318
"""
319
function unsafe_copyto!(dest::Array{T}, doffs, src::Array{T}, soffs, n) where T
4,073,697✔
320
    t1 = @_gc_preserve_begin dest
128,350,524✔
321
    t2 = @_gc_preserve_begin src
128,350,524✔
322
    destp = pointer(dest, doffs)
128,350,524✔
323
    srcp = pointer(src, soffs)
128,350,535✔
324
    if !allocatedinline(T)
4,071,045✔
325
        ccall(:jl_array_ptr_copy, Cvoid, (Any, Ptr{Cvoid}, Any, Ptr{Cvoid}, Int),
66,643,228✔
326
              dest, destp, src, srcp, n)
327
    elseif isbitstype(T)
2,049,177✔
328
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
41,701,004✔
329
              destp, srcp, n * aligned_sizeof(T))
330
    elseif isbitsunion(T)
5,847✔
331
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
81✔
332
              destp, srcp, n * aligned_sizeof(T))
333
        # copy selector bytes
334
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
81✔
335
              ccall(:jl_array_typetagdata, Ptr{UInt8}, (Any,), dest) + doffs - 1,
336
              ccall(:jl_array_typetagdata, Ptr{UInt8}, (Any,), src) + soffs - 1,
337
              n)
338
    else
339
        _unsafe_copyto!(dest, doffs, src, soffs, n)
20,006,222✔
340
    end
341
    @_gc_preserve_end t2
128,350,524✔
342
    @_gc_preserve_end t1
128,350,524✔
343
    return dest
43,728,547✔
344
end
345

346
unsafe_copyto!(dest::Array, doffs, src::Array, soffs, n) =
5,346,198✔
347
    _unsafe_copyto!(dest, doffs, src, soffs, n)
348

349
"""
350
    copyto!(dest, do, src, so, N)
351

352
Copy `N` elements from collection `src` starting at the linear index `so`, to array `dest` starting at
353
the index `do`. Return `dest`.
354
"""
355
function copyto!(dest::Array, doffs::Integer, src::Array, soffs::Integer, n::Integer)
58,327✔
356
    return _copyto_impl!(dest, doffs, src, soffs, n)
10,669,655✔
357
end
358

359
# this is only needed to avoid possible ambiguities with methods added in some packages
360
function copyto!(dest::Array{T}, doffs::Integer, src::Array{T}, soffs::Integer, n::Integer) where T
1,157,151✔
361
    return _copyto_impl!(dest, doffs, src, soffs, n)
153,991,321✔
362
end
363

364
function _copyto_impl!(dest::Array, doffs::Integer, src::Array, soffs::Integer, n::Integer)
154,048,996✔
365
    n == 0 && return dest
159,337,945✔
366
    n > 0 || _throw_argerror("Number of elements to copy must be nonnegative.")
128,837,111✔
367
    @boundscheck checkbounds(dest, doffs:doffs+n-1)
128,837,129✔
368
    @boundscheck checkbounds(src, soffs:soffs+n-1)
128,837,092✔
369
    unsafe_copyto!(dest, doffs, src, soffs, n)
128,837,086✔
370
    return dest
128,836,845✔
371
end
372

373
# Outlining this because otherwise a catastrophic inference slowdown
374
# occurs, see discussion in #27874.
375
# It is also mitigated by using a constant string.
376
_throw_argerror(s) = (@noinline; throw(ArgumentError(s)))
3,940✔
377

378
copyto!(dest::Array, src::Array) = copyto!(dest, 1, src, 1, length(src))
10,639,510✔
379

380
# also to avoid ambiguities in packages
381
copyto!(dest::Array{T}, src::Array{T}) where {T} = copyto!(dest, 1, src, 1, length(src))
42,369,302✔
382

383
# N.B: The generic definition in multidimensional.jl covers, this, this is just here
384
# for bootstrapping purposes.
385
function fill!(dest::Array{T}, x) where T
100,332✔
386
    xT = convert(T, x)
96,532✔
387
    for i in eachindex(dest)
868,743,902✔
388
        @inbounds dest[i] = xT
5,294,702,824✔
389
    end
10,402,709,002✔
390
    return dest
682,047,256✔
391
end
392

393
"""
394
    copy(x)
395

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

400
See also [`copy!`](@ref Base.copy!), [`copyto!`](@ref), [`deepcopy`](@ref).
401
"""
402
copy
403

404
copy(a::T) where {T<:Array} = ccall(:jl_array_copy, Ref{T}, (Any,), a)
135,399,107✔
405

406
## Constructors ##
407

408
similar(a::Array{T,1}) where {T}                    = Vector{T}(undef, size(a,1))
7,937✔
409
similar(a::Array{T,2}) where {T}                    = Matrix{T}(undef, size(a,1), size(a,2))
4,114✔
410
similar(a::Array{T,1}, S::Type) where {T}           = Vector{S}(undef, size(a,1))
8,424✔
411
similar(a::Array{T,2}, S::Type) where {T}           = Matrix{S}(undef, size(a,1), size(a,2))
16,988✔
412
similar(a::Array{T}, m::Int) where {T}              = Vector{T}(undef, m)
1,777,557✔
413
similar(a::Array, T::Type, dims::Dims{N}) where {N} = Array{T,N}(undef, dims)
57,584,647✔
414
similar(a::Array{T}, dims::Dims{N}) where {T,N}     = Array{T,N}(undef, dims)
232✔
415

416
# T[x...] constructs Array{T,1}
417
"""
418
    getindex(type[, elements...])
419

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

423
# Examples
424
```jldoctest
425
julia> Int8[1, 2, 3]
426
3-element Vector{Int8}:
427
 1
428
 2
429
 3
430

431
julia> getindex(Int8, 1, 2, 3)
432
3-element Vector{Int8}:
433
 1
434
 2
435
 3
436
```
437
"""
438
function getindex(::Type{T}, vals...) where T
3,512✔
439
    @inline
3,441✔
440
    @_effect_free_terminates_locally_meta
3,441✔
441
    a = Vector{T}(undef, length(vals))
3,514✔
442
    if vals isa NTuple
3,441✔
443
        @_safeindex for i in 1:length(vals)
3,486✔
444
            a[i] = vals[i]
21,783✔
445
        end
40,350✔
446
    else
447
        # use afoldl to avoid type instability inside loop
448
        afoldl(1, vals...) do i, v
325✔
449
            @inbounds a[i] = v
1,111✔
450
            return i + 1
1,104✔
451
        end
452
    end
453
    return a
3,513✔
454
end
455

456
# safe version
457
function getindex(::Type{T}, vals::T...) where T
261,809✔
458
    @inline
101,317✔
459
    @_effect_free_terminates_locally_meta
101,317✔
460
    a = Vector{T}(undef, length(vals))
641,884,823✔
461
    @_safeindex for i in 1:length(vals)
23,335,457✔
462
        a[i] = vals[i]
23,462,885✔
463
    end
275,299✔
464
    return a
23,335,114✔
465
end
466

467
function getindex(::Type{Any}, @nospecialize vals...)
22,028,117✔
468
    @_effect_free_terminates_locally_meta
16,709✔
469
    a = Vector{Any}(undef, length(vals))
50,716,086✔
470
    @_safeindex for i = 1:length(vals)
66,951,149✔
471
        a[i] = vals[i]
95,031,819✔
472
    end
110,515,725✔
473
    return a
50,716,086✔
474
end
475
getindex(::Type{Any}) = Vector{Any}()
31,838,818✔
476

477
function fill!(a::Union{Array{UInt8}, Array{Int8}}, x::Integer)
12,179✔
478
    ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), a, convert(eltype(a), x), length(a))
149,988,902✔
479
    return a
149,988,902✔
480
end
481

482
to_dim(d::Integer) = d
×
483
to_dim(d::OneTo) = last(d)
358✔
484

485
"""
486
    fill(value, dims::Tuple)
487
    fill(value, dims...)
488

489
Create an array of size `dims` with every location set to `value`.
490

491
For example, `fill(1.0, (5,5))` returns a 5×5 array of floats,
492
with `1.0` in every location of the array.
493

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

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

507
```jldoctest
508
julia> v = fill([], 3)
509
3-element Vector{Vector{Any}}:
510
 []
511
 []
512
 []
513

514
julia> v[1] === v[2] === v[3]
515
true
516

517
julia> value = v[1]
518
Any[]
519

520
julia> push!(value, 867_5309)
521
1-element Vector{Any}:
522
 8675309
523

524
julia> v
525
3-element Vector{Vector{Any}}:
526
 [8675309]
527
 [8675309]
528
 [8675309]
529
```
530

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

534
```jldoctest
535
julia> v2 = [[] for _ in 1:3]
536
3-element Vector{Vector{Any}}:
537
 []
538
 []
539
 []
540

541
julia> v2[1] === v2[2] === v2[3]
542
false
543

544
julia> push!(v2[1], 8675309)
545
1-element Vector{Any}:
546
 8675309
547

548
julia> v2
549
3-element Vector{Vector{Any}}:
550
 [8675309]
551
 []
552
 []
553
```
554

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

557
# Examples
558
```jldoctest
559
julia> fill(1.0, (2,3))
560
2×3 Matrix{Float64}:
561
 1.0  1.0  1.0
562
 1.0  1.0  1.0
563

564
julia> fill(42)
565
0-dimensional Array{Int64, 0}:
566
42
567

568
julia> A = fill(zeros(2), 2) # sets both elements to the same [0.0, 0.0] vector
569
2-element Vector{Vector{Float64}}:
570
 [0.0, 0.0]
571
 [0.0, 0.0]
572

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

575
julia> A # both A[1] and A[2] are the very same vector
576
2-element Vector{Vector{Float64}}:
577
 [42.0, 0.0]
578
 [42.0, 0.0]
579
```
580
"""
581
function fill end
582

583
fill(v, dims::DimOrInd...) = fill(v, dims)
3,635,974,755✔
584
fill(v, dims::NTuple{N, Union{Integer, OneTo}}) where {N} = fill(v, map(to_dim, dims))
×
585
fill(v, dims::NTuple{N, Integer}) where {N} = (a=Array{typeof(v),N}(undef, dims); fill!(a, v); a)
4,522,116,710✔
586
fill(v, dims::Tuple{}) = (a=Array{typeof(v),0}(undef, dims); fill!(a, v); a)
147✔
587

588
"""
589
    zeros([T=Float64,] dims::Tuple)
590
    zeros([T=Float64,] dims...)
591

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

595
# Examples
596
```jldoctest
597
julia> zeros(1)
598
1-element Vector{Float64}:
599
 0.0
600

601
julia> zeros(Int8, 2, 3)
602
2×3 Matrix{Int8}:
603
 0  0  0
604
 0  0  0
605
```
606
"""
607
function zeros end
608

609
"""
610
    ones([T=Float64,] dims::Tuple)
611
    ones([T=Float64,] dims...)
612

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

616
# Examples
617
```jldoctest
618
julia> ones(1,2)
619
1×2 Matrix{Float64}:
620
 1.0  1.0
621

622
julia> ones(ComplexF64, 2, 3)
623
2×3 Matrix{ComplexF64}:
624
 1.0+0.0im  1.0+0.0im  1.0+0.0im
625
 1.0+0.0im  1.0+0.0im  1.0+0.0im
626
```
627
"""
628
function ones end
629

630
for (fname, felt) in ((:zeros, :zero), (:ones, :one))
631
    @eval begin
632
        $fname(dims::DimOrInd...) = $fname(dims)
20,446,783✔
633
        $fname(::Type{T}, dims::DimOrInd...) where {T} = $fname(T, dims)
355,539,436✔
634
        $fname(dims::Tuple{Vararg{DimOrInd}}) = $fname(Float64, dims)
20,483,823✔
635
        $fname(::Type{T}, dims::NTuple{N, Union{Integer, OneTo}}) where {T,N} = $fname(T, map(to_dim, dims))
1,190✔
636
        function $fname(::Type{T}, dims::NTuple{N, Integer}) where {T,N}
46,097✔
637
            a = Array{T,N}(undef, dims)
230,245,915✔
638
            fill!(a, $felt(T))
780,273,207✔
639
            return a
230,245,915✔
640
        end
641
        function $fname(::Type{T}, dims::Tuple{}) where {T}
18✔
642
            a = Array{T}(undef)
18✔
643
            fill!(a, $felt(T))
18✔
644
            return a
18✔
645
        end
646
    end
647
end
648

649
function _one(unit::T, x::AbstractMatrix) where T
153✔
650
    require_one_based_indexing(x)
153✔
651
    m,n = size(x)
153✔
652
    m==n || throw(DimensionMismatch("multiplicative identity defined only for square matrices"))
153✔
653
    # Matrix{T}(I, m, m)
654
    I = zeros(T, m, m)
3,745✔
655
    for i in 1:m
306✔
656
        I[i,i] = unit
639✔
657
    end
1,125✔
658
    I
153✔
659
end
660

661
one(x::AbstractMatrix{T}) where {T} = _one(one(T), x)
129✔
662
oneunit(x::AbstractMatrix{T}) where {T} = _one(oneunit(T), x)
30✔
663

664
## Conversions ##
665

666
convert(::Type{T}, a::AbstractArray) where {T<:Array} = a isa T ? a : T(a)::T
114,098,609✔
667

668
promote_rule(a::Type{Array{T,n}}, b::Type{Array{S,n}}) where {T,n,S} = el_same(promote_type(T,S), a, b)
62✔
669

670
## Constructors ##
671

672
if nameof(@__MODULE__) === :Base  # avoid method overwrite
673
# constructors should make copies
674
Array{T,N}(x::AbstractArray{S,N})         where {T,N,S} = copyto_axcheck!(Array{T,N}(undef, size(x)), x)
30,016✔
675
AbstractArray{T,N}(A::AbstractArray{S,N}) where {T,N,S} = copyto_axcheck!(similar(A,T), A)
25,488✔
676
end
677

678
## copying iterators to containers
679

680
"""
681
    collect(element_type, collection)
682

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

686
# Examples
687
```jldoctest
688
julia> collect(Float64, 1:2:5)
689
3-element Vector{Float64}:
690
 1.0
691
 3.0
692
 5.0
693
```
694
"""
695
collect(::Type{T}, itr) where {T} = _collect(T, itr, IteratorSize(itr))
21,440,627✔
696

697
_collect(::Type{T}, itr, isz::Union{HasLength,HasShape}) where {T} =
10,574,814✔
698
    copyto!(_array_for(T, isz, _similar_shape(itr, isz)), itr)
699
function _collect(::Type{T}, itr, isz::SizeUnknown) where T
10,865,811✔
700
    a = Vector{T}()
10,865,811✔
701
    for x in itr
16,444,770✔
702
        push!(a, x)
7,134,164✔
703
    end
8,689,368✔
704
    return a
10,865,811✔
705
end
706

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

710
_similar_shape(itr, ::SizeUnknown) = nothing
1✔
711
_similar_shape(itr, ::HasLength) = length(itr)::Integer
36,013,945✔
712
_similar_shape(itr, ::HasShape) = axes(itr)
428,114,052✔
713

714
_similar_for(c::AbstractArray, ::Type{T}, itr, ::SizeUnknown, ::Nothing) where {T} =
985,770✔
715
    similar(c, T, 0)
716
_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasLength, len::Integer) where {T} =
4,009,812✔
717
    similar(c, T, len)
718
_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasShape, axs) where {T} =
142,453✔
719
    similar(c, T, axs)
720

721
# make a collection appropriate for collecting `itr::Generator`
722
_array_for(::Type{T}, ::SizeUnknown, ::Nothing) where {T} = Vector{T}(undef, 0)
487✔
723
_array_for(::Type{T}, ::HasLength, len::Integer) where {T} = Vector{T}(undef, Int(len))
29,133,534✔
724
_array_for(::Type{T}, ::HasShape{N}, axs) where {T,N} = similar(Array{T,N}, axs)
428,171,341✔
725

726
# used by syntax lowering for simple typed comprehensions
727
_array_for(::Type{T}, itr, isz) where {T} = _array_for(T, isz, _similar_shape(itr, isz))
454,162,418✔
728

729

730
"""
731
    collect(collection)
732

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

738
Used by comprehensions to turn a generator into an `Array`.
739

740
# Examples
741
```jldoctest
742
julia> collect(1:2:13)
743
7-element Vector{Int64}:
744
  1
745
  3
746
  5
747
  7
748
  9
749
 11
750
 13
751

752
julia> [x^2 for x in 1:8 if isodd(x)]
753
4-element Vector{Int64}:
754
  1
755
  9
756
 25
757
 49
758
```
759
"""
760
collect(itr) = _collect(1:1 #= Array =#, itr, IteratorEltype(itr), IteratorSize(itr))
5,234,585✔
761

762
collect(A::AbstractArray) = _collect_indices(axes(A), A)
133,942✔
763

764
collect_similar(cont, itr) = _collect(cont, itr, IteratorEltype(itr), IteratorSize(itr))
141,679✔
765

766
_collect(cont, itr, ::HasEltype, isz::Union{HasLength,HasShape}) =
4,248,889✔
767
    copyto!(_similar_for(cont, eltype(itr), itr, isz, _similar_shape(itr, isz)), itr)
768

769
function _collect(cont, itr, ::HasEltype, isz::SizeUnknown)
985,736✔
770
    a = _similar_for(cont, eltype(itr), itr, isz, nothing)
985,736✔
771
    for x in itr
1,970,527✔
772
        push!(a,x)
8,713,237✔
773
    end
14,833,881✔
774
    return a
985,735✔
775
end
776

777
_collect_indices(::Tuple{}, A) = copyto!(Array{eltype(A),0}(undef), A)
26✔
778
_collect_indices(indsA::Tuple{Vararg{OneTo}}, A) =
178,265✔
779
    copyto!(Array{eltype(A)}(undef, length.(indsA)), A)
780
function _collect_indices(indsA, A)
120✔
781
    B = Array{eltype(A)}(undef, length.(indsA))
120✔
782
    copyto!(B, CartesianIndices(axes(B)), A, CartesianIndices(indsA))
120✔
783
end
784

785
# NOTE: this function is not meant to be called, only inferred, for the
786
# purpose of bounding the types of values generated by an iterator.
787
function _iterator_upper_bound(itr)
6✔
788
    x = iterate(itr)
×
789
    while x !== nothing
×
790
        val = getfield(x, 1)
×
791
        if inferencebarrier(nothing)
×
792
            return val
×
793
        end
794
        x = iterate(itr, getfield(x, 2))
×
795
    end
×
796
    throw(nothing)
6✔
797
end
798

799
# define this as a macro so that the call to Core.Compiler
800
# gets inlined into the caller before recursion detection
801
# gets a chance to see it, so that recursive calls to the caller
802
# don't trigger the inference limiter
803
if isdefined(Core, :Compiler)
804
    macro default_eltype(itr)
1✔
805
        I = esc(itr)
1✔
806
        return quote
1✔
807
            if $I isa Generator && ($I).f isa Type
730,675✔
808
                T = ($I).f
13,237✔
809
            else
810
                T = Core.Compiler.return_type(_iterator_upper_bound, Tuple{typeof($I)})
200,472✔
811
            end
812
            promote_typejoin_union(T)
214,081✔
813
        end
814
    end
815
else
816
    macro default_eltype(itr)
817
        I = esc(itr)
818
        return quote
819
            if $I isa Generator && ($I).f isa Type
820
                promote_typejoin_union($I.f)
821
            else
822
                Any
823
            end
824
        end
825
    end
826
end
827

828
function collect(itr::Generator)
574,988✔
829
    isz = IteratorSize(itr.iter)
70,749✔
830
    et = @default_eltype(itr)
×
831
    if isa(isz, SizeUnknown)
70,749✔
832
        return grow_to!(Vector{et}(), itr)
85,229✔
833
    else
834
        shp = _similar_shape(itr, isz)
490,033✔
835
        y = iterate(itr)
968,420✔
836
        if y === nothing
489,835✔
837
            return _array_for(et, isz, shp)
1,021✔
838
        end
839
        v1, st = y
69,179✔
840
        dest = _array_for(typeof(v1), isz, shp)
488,930✔
841
        # The typeassert gives inference a helping hand on the element type and dimensionality
842
        # (work-around for #28382)
843
        et′ = et <: Type ? Type : et
69,179✔
844
        RT = dest isa AbstractArray ? AbstractArray{<:et′, ndims(dest)} : Any
69,238✔
845
        collect_to_with_first!(dest, v1, itr, st)::RT
10,482,865✔
846
    end
847
end
848

849
_collect(c, itr, ::EltypeUnknown, isz::SizeUnknown) =
34✔
850
    grow_to!(_similar_for(c, @default_eltype(itr), itr, isz, nothing), itr)
851

852
function _collect(c, itr, ::EltypeUnknown, isz::Union{HasLength,HasShape})
141,316✔
853
    et = @default_eltype(itr)
128,881✔
854
    shp = _similar_shape(itr, isz)
141,317✔
855
    y = iterate(itr)
280,647✔
856
    if y === nothing
141,314✔
857
        return _similar_for(c, et, itr, isz, shp)
1,296✔
858
    end
859
    v1, st = y
127,803✔
860
    dest = _similar_for(c, typeof(v1), itr, isz, shp)
140,034✔
861
    # The typeassert gives inference a helping hand on the element type and dimensionality
862
    # (work-around for #28382)
863
    et′ = et <: Type ? Type : et
127,761✔
864
    RT = dest isa AbstractArray ? AbstractArray{<:et′, ndims(dest)} : Any
127,780✔
865
    collect_to_with_first!(dest, v1, itr, st)::RT
140,409✔
866
end
867

868
function collect_to_with_first!(dest::AbstractArray, v1, itr, st)
197,022✔
869
    i1 = first(LinearIndices(dest))
196,940✔
870
    dest[i1] = v1
628,878✔
871
    return collect_to!(dest, itr, i1+1, st)
84,516,878✔
872
end
873

874
function collect_to_with_first!(dest, v1, itr, st)
×
875
    push!(dest, v1)
×
876
    return grow_to!(dest, itr, st)
×
877
end
878

879
function setindex_widen_up_to(dest::AbstractArray{T}, el, i) where T
766✔
880
    @inline
764✔
881
    new = similar(dest, promote_typejoin(T, typeof(el)))
770✔
882
    f = first(LinearIndices(dest))
764✔
883
    copyto!(new, first(LinearIndices(new)), dest, f, i-f)
1,524✔
884
    @inbounds new[i] = el
766✔
885
    return new
766✔
886
end
887

888
function collect_to!(dest::AbstractArray{T}, itr, offs, st) where T
234,994✔
889
    # collect to dest array, checking the type of each result. if a result does not
890
    # match, widen the result type and re-dispatch.
891
    i = offs
197,706✔
892
    while true
86,267,169✔
893
        y = iterate(itr, st)
171,904,133✔
894
        y === nothing && break
86,267,162✔
895
        el, st = y
85,187,005✔
896
        if el isa T
85,185,682✔
897
            @inbounds dest[i] = el
85,644,316✔
898
            i += 1
85,637,525✔
899
        else
900
            new = setindex_widen_up_to(dest, el, i)
888✔
901
            return collect_to!(new, itr, i+1, st)
766✔
902
        end
903
    end
85,637,525✔
904
    return dest
628,871✔
905
end
906

907
function grow_to!(dest, itr)
1,166✔
908
    y = iterate(itr)
1,408✔
909
    y === nothing && return dest
1,167✔
910
    dest2 = empty(dest, typeof(y[1]))
264✔
911
    push!(dest2, y[1])
288✔
912
    grow_to!(dest2, itr, y[2])
248✔
913
end
914

915
function push_widen(dest, el)
53✔
916
    @inline
53✔
917
    new = sizehint!(empty(dest, promote_typejoin(eltype(dest), typeof(el))), length(dest))
53✔
918
    if new isa AbstractSet
53✔
919
        # TODO: merge back these two branches when copy! is re-enabled for sets/vectors
920
        union!(new, dest)
1✔
921
    else
922
        append!(new, dest)
104✔
923
    end
924
    push!(new, el)
53✔
925
    return new
53✔
926
end
927

928
function grow_to!(dest, itr, st)
301✔
929
    T = eltype(dest)
196✔
930
    y = iterate(itr, st)
549✔
931
    while y !== nothing
3,908✔
932
        el, st = y
2,349✔
933
        if el isa T
2,349✔
934
            push!(dest, el)
3,610✔
935
        else
936
            new = push_widen(dest, el)
55✔
937
            return grow_to!(new, itr, st)
53✔
938
        end
939
        y = iterate(itr, st)
5,528✔
940
    end
3,607✔
941
    return dest
248✔
942
end
943

944
## Iteration ##
945

946
iterate(A::Array, i=1) = (@inline; (i % UInt) - 1 < length(A) ? (@inbounds A[i], i + 1) : nothing)
9,359,020,775✔
947

948
## Indexing: getindex ##
949

950
"""
951
    getindex(collection, key...)
952

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

956
See also [`get`](@ref), [`keys`](@ref), [`eachindex`](@ref).
957

958
# Examples
959
```jldoctest
960
julia> A = Dict("a" => 1, "b" => 2)
961
Dict{String, Int64} with 2 entries:
962
  "b" => 2
963
  "a" => 1
964

965
julia> getindex(A, "a")
966
1
967
```
968
"""
969
function getindex end
970

971
# Faster contiguous indexing using copyto! for AbstractUnitRange and Colon
972
function getindex(A::Array, I::AbstractUnitRange{<:Integer})
907,383✔
973
    @inline
866,024✔
974
    @boundscheck checkbounds(A, I)
57,227,134✔
975
    lI = length(I)
57,227,132✔
976
    X = similar(A, axes(I))
57,227,144✔
977
    if lI > 0
57,227,132✔
978
        copyto!(X, firstindex(X), A, first(I), lI)
50,969,578✔
979
    end
980
    return X
57,227,132✔
981
end
982

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

986
function getindex(A::Array, c::Colon)
4,891✔
987
    lI = length(A)
1,773,424✔
988
    X = similar(A, lI)
1,773,424✔
989
    if lI > 0
1,773,424✔
990
        unsafe_copyto!(X, 1, A, 1, lI)
1,773,422✔
991
    end
992
    return X
1,773,424✔
993
end
994

995
# This is redundant with the abstract fallbacks, but needed for bootstrap
996
function getindex(A::Array{S}, I::AbstractRange{Int}) where S
3,165,592✔
997
    return S[ A[i] for i in I ]
13,041,490✔
998
end
999

1000
## Indexing: setindex! ##
1001

1002
"""
1003
    setindex!(collection, value, key...)
1004

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

1008
# Examples
1009
```jldoctest
1010
julia> a = Dict("a"=>1)
1011
Dict{String, Int64} with 1 entry:
1012
  "a" => 1
1013

1014
julia> setindex!(a, 2, "b")
1015
Dict{String, Int64} with 2 entries:
1016
  "b" => 2
1017
  "a" => 1
1018
```
1019
"""
1020
function setindex! end
1021

1022
@eval setindex!(A::Array{T}, x, i1::Int) where {T} =
18,192,628,067✔
1023
    arrayset($(Expr(:boundscheck)), A, convert(T,x)::T, i1)
1024
@eval setindex!(A::Array{T}, x, i1::Int, i2::Int, I::Int...) where {T} =
56,724,558✔
1025
    (@inline; arrayset($(Expr(:boundscheck)), A, convert(T,x)::T, i1, i2, I...))
59,455,250✔
1026

1027
__inbounds_setindex!(A::Array{T}, x, i1::Int) where {T} =
1,287,660,963✔
1028
    arrayset(false, A, convert(T,x)::T, i1)
1029
__inbounds_setindex!(A::Array{T}, x, i1::Int, i2::Int, I::Int...) where {T} =
×
1030
    (@inline; arrayset(false, A, convert(T,x)::T, i1, i2, I...))
×
1031

1032
# This is redundant with the abstract fallbacks but needed and helpful for bootstrap
1033
function setindex!(A::Array, X::AbstractArray, I::AbstractVector{Int})
810,497✔
1034
    @_propagate_inbounds_meta
810,497✔
1035
    @boundscheck setindex_shape_check(X, length(I))
6,168,709✔
1036
    require_one_based_indexing(X)
810,497✔
1037
    X′ = unalias(A, X)
814,856✔
1038
    I′ = unalias(A, I)
810,640✔
1039
    count = 1
810,497✔
1040
    for i in I′
11,533,563✔
1041
        @inbounds x = X′[count]
14,580,153✔
1042
        A[i] = x
14,582,236✔
1043
        count += 1
14,580,153✔
1044
    end
23,793,490✔
1045
    return A
6,168,709✔
1046
end
1047

1048
# Faster contiguous setindex! with copyto!
1049
function setindex!(A::Array{T}, X::Array{T}, I::AbstractUnitRange{Int}) where T
1,008,510✔
1050
    @inline
1,008,049✔
1051
    @boundscheck checkbounds(A, I)
1,008,863✔
1052
    lI = length(I)
1,008,863✔
1053
    @boundscheck setindex_shape_check(X, lI)
1,008,863✔
1054
    if lI > 0
1,008,863✔
1055
        unsafe_copyto!(A, first(I), X, 1, lI)
1,008,779✔
1056
    end
1057
    return A
1,008,863✔
1058
end
1059
function setindex!(A::Array{T}, X::Array{T}, c::Colon) where T
47✔
1060
    @inline
47✔
1061
    lI = length(A)
47✔
1062
    @boundscheck setindex_shape_check(X, lI)
47✔
1063
    if lI > 0
47✔
1064
        unsafe_copyto!(A, 1, X, 1, lI)
47✔
1065
    end
1066
    return A
47✔
1067
end
1068

1069
# efficiently grow an array
1070

1071
_growbeg!(a::Vector, delta::Integer) =
1,099,995✔
1072
    ccall(:jl_array_grow_beg, Cvoid, (Any, UInt), a, delta)
1073
_growend!(a::Vector, delta::Integer) =
1,579,838,331✔
1074
    ccall(:jl_array_grow_end, Cvoid, (Any, UInt), a, delta)
1075
_growat!(a::Vector, i::Integer, delta::Integer) =
68,219,376✔
1076
    ccall(:jl_array_grow_at, Cvoid, (Any, Int, UInt), a, i - 1, delta)
1077

1078
# efficiently delete part of an array
1079

1080
_deletebeg!(a::Vector, delta::Integer) =
20,269,034✔
1081
    ccall(:jl_array_del_beg, Cvoid, (Any, UInt), a, delta)
1082
_deleteend!(a::Vector, delta::Integer) =
425,072,188✔
1083
    ccall(:jl_array_del_end, Cvoid, (Any, UInt), a, delta)
1084
_deleteat!(a::Vector, i::Integer, delta::Integer) =
315,828✔
1085
    ccall(:jl_array_del_at, Cvoid, (Any, Int, UInt), a, i - 1, delta)
1086

1087
## Dequeue functionality ##
1088

1089
"""
1090
    push!(collection, items...) -> collection
1091

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

1095
# Examples
1096
```jldoctest
1097
julia> push!([1, 2, 3], 4, 5, 6)
1098
6-element Vector{Int64}:
1099
 1
1100
 2
1101
 3
1102
 4
1103
 5
1104
 6
1105
```
1106

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

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

1113
See also [`pushfirst!`](@ref).
1114
"""
1115
function push! end
1116

1117
function push!(a::Vector{T}, item) where T
23,624,410✔
1118
    # convert first so we don't grow the array if the assignment won't work
1119
    itemT = convert(T, item)
25,641,993✔
1120
    _growend!(a, 1)
1,050,132,081✔
1121
    @_safeindex a[length(a)] = itemT
1,050,132,081✔
1122
    return a
10,436,245✔
1123
end
1124

1125
# specialize and optimize the single argument case
1126
function push!(a::Vector{Any}, @nospecialize x)
3,172,317✔
1127
    _growend!(a, 1)
90,985,989✔
1128
    @_safeindex a[length(a)] = x
90,985,987✔
1129
    return a
2,919,611✔
1130
end
1131
function push!(a::Vector{Any}, @nospecialize x...)
99,525✔
1132
    @_terminates_locally_meta
1✔
1133
    na = length(a)
99,525✔
1134
    nx = length(x)
1✔
1135
    _growend!(a, nx)
99,525✔
1136
    @_safeindex for i = 1:nx
99,525✔
1137
        a[na+i] = x[i]
203,492✔
1138
    end
298,577✔
1139
    return a
99,525✔
1140
end
1141

1142
"""
1143
    append!(collection, collections...) -> collection.
1144

1145
For an ordered container `collection`, add the elements of each `collections`
1146
to the end of it.
1147

1148
!!! compat "Julia 1.6"
1149
    Specifying multiple collections to be appended requires at least Julia 1.6.
1150

1151
# Examples
1152
```jldoctest
1153
julia> append!([1], [2, 3])
1154
3-element Vector{Int64}:
1155
 1
1156
 2
1157
 3
1158

1159
julia> append!([1, 2, 3], [4, 5], [6])
1160
6-element Vector{Int64}:
1161
 1
1162
 2
1163
 3
1164
 4
1165
 5
1166
 6
1167
```
1168

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

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

1175
See also [`vcat`](@ref) for vectors, [`union!`](@ref) for sets,
1176
and [`prepend!`](@ref) and [`pushfirst!`](@ref) for the opposite order.
1177
"""
1178
function append!(a::Vector, items::AbstractVector)
77,170✔
1179
    itemindices = eachindex(items)
60,170,549✔
1180
    n = length(itemindices)
48,796✔
1181
    _growend!(a, n)
60,170,549✔
1182
    copyto!(a, length(a)-n+1, items, first(itemindices), n)
60,171,902✔
1183
    return a
60,170,549✔
1184
end
1185

1186
append!(a::AbstractVector, iter) = _append!(a, IteratorSize(iter), iter)
43,033,990✔
1187
push!(a::AbstractVector, iter...) = append!(a, iter)
3,865✔
1188

1189
append!(a::AbstractVector, iter...) = foldl(append!, iter, init=a)
76✔
1190

1191
function _append!(a, ::Union{HasLength,HasShape}, iter)
16,589,060✔
1192
    @_terminates_locally_meta
1,807✔
1193
    n = length(a)
16,589,060✔
1194
    i = lastindex(a)
16,589,060✔
1195
    resize!(a, n+Int(length(iter))::Int)
28,282,632✔
1196
    @_safeindex for (i, item) in zip(i+1:lastindex(a), iter)
21,484,548✔
1197
        a[i] = item
22,729,846✔
1198
    end
40,561,020✔
1199
    a
16,589,060✔
1200
end
1201

1202
function _append!(a, ::IteratorSize, iter)
26,444,929✔
1203
    for item in iter
26,444,930✔
1204
        push!(a, item)
27,851,881✔
1205
    end
27,851,882✔
1206
    a
26,444,929✔
1207
end
1208

1209
"""
1210
    prepend!(a::Vector, collections...) -> collection
1211

1212
Insert the elements of each `collections` to the beginning of `a`.
1213

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

1217
!!! compat "Julia 1.6"
1218
    Specifying multiple collections to be prepended requires at least Julia 1.6.
1219

1220
# Examples
1221
```jldoctest
1222
julia> prepend!([3], [1, 2])
1223
3-element Vector{Int64}:
1224
 1
1225
 2
1226
 3
1227

1228
julia> prepend!([6], [1, 2], [3, 4, 5])
1229
6-element Vector{Int64}:
1230
 1
1231
 2
1232
 3
1233
 4
1234
 5
1235
 6
1236
```
1237
"""
1238
function prepend! end
1239

1240
function prepend!(a::Vector, items::AbstractVector)
4,670✔
1241
    itemindices = eachindex(items)
4,670✔
1242
    n = length(itemindices)
4,630✔
1243
    _growbeg!(a, n)
4,670✔
1244
    if a === items
4,670✔
1245
        copyto!(a, 1, items, n+1, n)
×
1246
    else
1247
        copyto!(a, 1, items, first(itemindices), n)
4,968✔
1248
    end
1249
    return a
4,670✔
1250
end
1251

1252
prepend!(a::Vector, iter) = _prepend!(a, IteratorSize(iter), iter)
4✔
1253
pushfirst!(a::Vector, iter...) = prepend!(a, iter)
4✔
1254

1255
prepend!(a::AbstractVector, iter...) = foldr((v, a) -> prepend!(a, v), iter, init=a)
×
1256

1257
function _prepend!(a, ::Union{HasLength,HasShape}, iter)
2✔
1258
    @_terminates_locally_meta
2✔
1259
    require_one_based_indexing(a)
2✔
1260
    n = length(iter)
2✔
1261
    _growbeg!(a, n)
2✔
1262
    i = 0
2✔
1263
    for item in iter
2✔
1264
        @_safeindex a[i += 1] = item
4✔
1265
    end
6✔
1266
    a
2✔
1267
end
1268
function _prepend!(a, ::IteratorSize, iter)
×
1269
    n = 0
×
1270
    for item in iter
×
1271
        n += 1
×
1272
        pushfirst!(a, item)
×
1273
    end
×
1274
    reverse!(a, 1, n)
×
1275
    a
×
1276
end
1277

1278
"""
1279
    resize!(a::Vector, n::Integer) -> Vector
1280

1281
Resize `a` to contain `n` elements. If `n` is smaller than the current collection
1282
length, the first `n` elements will be retained. If `n` is larger, the new elements are not
1283
guaranteed to be initialized.
1284

1285
# Examples
1286
```jldoctest
1287
julia> resize!([6, 5, 4, 3, 2, 1], 3)
1288
3-element Vector{Int64}:
1289
 6
1290
 5
1291
 4
1292

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

1295
julia> length(a)
1296
8
1297

1298
julia> a[1:6]
1299
6-element Vector{Int64}:
1300
 6
1301
 5
1302
 4
1303
 3
1304
 2
1305
 1
1306
```
1307
"""
1308
function resize!(a::Vector, nl::Integer)
5,907,213✔
1309
    l = length(a)
569,802,209✔
1310
    if nl > l
569,802,209✔
1311
        _growend!(a, nl-l)
259,591,618✔
1312
    elseif nl != l
310,210,593✔
1313
        if nl < 0
64,137,306✔
1314
            _throw_argerror("new length must be ≥ 0")
1✔
1315
        end
1316
        _deleteend!(a, l-nl)
64,138,511✔
1317
    end
1318
    return a
569,802,208✔
1319
end
1320

1321
"""
1322
    sizehint!(s, n) -> s
1323

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

1329
See also [`resize!`](@ref).
1330

1331
# Notes on the performance model
1332

1333
For types that support `sizehint!`,
1334

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

1339
2. `sizehint!` may control this preallocation. Again, it typically does this for types in
1340
   `Base`.
1341

1342
3. `empty!` is nearly costless (and O(1)) for types that support this kind of preallocation.
1343
"""
1344
function sizehint! end
1345

1346
function sizehint!(a::Vector, sz::Integer)
458,925✔
1347
    ccall(:jl_array_sizehint, Cvoid, (Any, UInt), a, sz)
177,053,524✔
1348
    a
624,163✔
1349
end
1350

1351
"""
1352
    pop!(collection) -> item
1353

1354
Remove an item in `collection` and return it. If `collection` is an
1355
ordered container, the last item is returned; for unordered containers,
1356
an arbitrary element is returned.
1357

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

1360
# Examples
1361
```jldoctest
1362
julia> A=[1, 2, 3]
1363
3-element Vector{Int64}:
1364
 1
1365
 2
1366
 3
1367

1368
julia> pop!(A)
1369
3
1370

1371
julia> A
1372
2-element Vector{Int64}:
1373
 1
1374
 2
1375

1376
julia> S = Set([1, 2])
1377
Set{Int64} with 2 elements:
1378
  2
1379
  1
1380

1381
julia> pop!(S)
1382
2
1383

1384
julia> S
1385
Set{Int64} with 1 element:
1386
  1
1387

1388
julia> pop!(Dict(1=>2))
1389
1 => 2
1390
```
1391
"""
1392
function pop!(a::Vector)
62,433✔
1393
    if isempty(a)
294,771,554✔
1394
        _throw_argerror("array must be non-empty")
×
1395
    end
1396
    item = a[end]
294,771,554✔
1397
    _deleteend!(a, 1)
294,771,554✔
1398
    return item
294,771,554✔
1399
end
1400

1401
"""
1402
    popat!(a::Vector, i::Integer, [default])
1403

1404
Remove the item at the given `i` and return it. Subsequent items
1405
are shifted to fill the resulting gap.
1406
When `i` is not a valid index for `a`, return `default`, or throw an error if
1407
`default` is not specified.
1408

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

1411
!!! compat "Julia 1.5"
1412
    This function is available as of Julia 1.5.
1413

1414
# Examples
1415
```jldoctest
1416
julia> a = [4, 3, 2, 1]; popat!(a, 2)
1417
3
1418

1419
julia> a
1420
3-element Vector{Int64}:
1421
 4
1422
 2
1423
 1
1424

1425
julia> popat!(a, 4, missing)
1426
missing
1427

1428
julia> popat!(a, 4)
1429
ERROR: BoundsError: attempt to access 3-element Vector{Int64} at index [4]
1430
[...]
1431
```
1432
"""
1433
function popat!(a::Vector, i::Integer)
2✔
1434
    x = a[i]
2✔
1435
    _deleteat!(a, i, 1)
2✔
1436
    x
2✔
1437
end
1438

1439
function popat!(a::Vector, i::Integer, default)
×
1440
    if 1 <= i <= length(a)
×
1441
        x = @inbounds a[i]
×
1442
        _deleteat!(a, i, 1)
×
1443
        x
×
1444
    else
1445
        default
×
1446
    end
1447
end
1448

1449
"""
1450
    pushfirst!(collection, items...) -> collection
1451

1452
Insert one or more `items` at the beginning of `collection`.
1453

1454
This function is called `unshift` in many other programming languages.
1455

1456
# Examples
1457
```jldoctest
1458
julia> pushfirst!([1, 2, 3, 4], 5, 6)
1459
6-element Vector{Int64}:
1460
 5
1461
 6
1462
 1
1463
 2
1464
 3
1465
 4
1466
```
1467
"""
1468
function pushfirst!(a::Vector{T}, item) where T
88,486✔
1469
    item = convert(T, item)
58,618✔
1470
    _growbeg!(a, 1)
88,847✔
1471
    @_safeindex a[1] = item
88,847✔
1472
    return a
58,635✔
1473
end
1474

1475
# specialize and optimize the single argument case
1476
function pushfirst!(a::Vector{Any}, @nospecialize x)
113✔
1477
    _growbeg!(a, 1)
775,822✔
1478
    @_safeindex a[1] = x
775,822✔
1479
    return a
111✔
1480
end
1481
function pushfirst!(a::Vector{Any}, @nospecialize x...)
731✔
1482
    @_terminates_locally_meta
1✔
1483
    na = length(a)
1✔
1484
    nx = length(x)
1✔
1485
    _growbeg!(a, nx)
731✔
1486
    @_safeindex for i = 1:nx
731✔
1487
        a[i] = x[i]
1,463✔
1488
    end
2,195✔
1489
    return a
731✔
1490
end
1491

1492
"""
1493
    popfirst!(collection) -> item
1494

1495
Remove the first `item` from `collection`.
1496

1497
This function is called `shift` in many other programming languages.
1498

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

1501
# Examples
1502
```jldoctest
1503
julia> A = [1, 2, 3, 4, 5, 6]
1504
6-element Vector{Int64}:
1505
 1
1506
 2
1507
 3
1508
 4
1509
 5
1510
 6
1511

1512
julia> popfirst!(A)
1513
1
1514

1515
julia> A
1516
5-element Vector{Int64}:
1517
 2
1518
 3
1519
 4
1520
 5
1521
 6
1522
```
1523
"""
1524
function popfirst!(a::Vector)
1,038,663✔
1525
    if isempty(a)
20,236,376✔
1526
        _throw_argerror("array must be non-empty")
×
1527
    end
1528
    item = a[1]
20,236,377✔
1529
    _deletebeg!(a, 1)
20,236,377✔
1530
    return item
20,236,376✔
1531
end
1532

1533
"""
1534
    insert!(a::Vector, index::Integer, item)
1535

1536
Insert an `item` into `a` at the given `index`. `index` is the index of `item` in
1537
the resulting `a`.
1538

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

1541
# Examples
1542
```jldoctest
1543
julia> insert!(Any[1:6;], 3, "here")
1544
7-element Vector{Any}:
1545
 1
1546
 2
1547
  "here"
1548
 3
1549
 4
1550
 5
1551
 6
1552
```
1553
"""
1554
function insert!(a::Array{T,1}, i::Integer, item) where T
351,682✔
1555
    # Throw convert error before changing the shape of the array
1556
    _item = convert(T, item)
298,175✔
1557
    _growat!(a, i, 1)
68,194,975✔
1558
    # _growat! already did bound check
1559
    @inbounds a[i] = _item
68,194,971✔
1560
    return a
298,177✔
1561
end
1562

1563
"""
1564
    deleteat!(a::Vector, i::Integer)
1565

1566
Remove the item at the given `i` and return the modified `a`. Subsequent items
1567
are shifted to fill the resulting gap.
1568

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

1571
# Examples
1572
```jldoctest
1573
julia> deleteat!([6, 5, 4, 3, 2, 1], 2)
1574
5-element Vector{Int64}:
1575
 6
1576
 4
1577
 3
1578
 2
1579
 1
1580
```
1581
"""
1582
function deleteat!(a::Vector, i::Integer)
322✔
1583
    i isa Bool && depwarn("passing Bool as an index is deprecated", :deleteat!)
322✔
1584
    _deleteat!(a, i, 1)
221,851✔
1585
    return a
318✔
1586
end
1587

1588
function deleteat!(a::Vector, r::AbstractUnitRange{<:Integer})
75,539✔
1589
    if eltype(r) === Bool
75,539✔
1590
        return invoke(deleteat!, Tuple{Vector, AbstractVector{Bool}}, a, r)
6✔
1591
    else
1592
        n = length(a)
75,533✔
1593
        f = first(r)
75,628✔
1594
        f isa Bool && depwarn("passing Bool as an index is deprecated", :deleteat!)
75,533✔
1595
        isempty(r) || _deleteat!(a, f, length(r))
165,051✔
1596
        return a
84,334✔
1597
    end
1598
end
1599

1600
"""
1601
    deleteat!(a::Vector, inds)
1602

1603
Remove the items at the indices given by `inds`, and return the modified `a`.
1604
Subsequent items are shifted to fill the resulting gap.
1605

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

1609
# Examples
1610
```jldoctest
1611
julia> deleteat!([6, 5, 4, 3, 2, 1], 1:2:5)
1612
3-element Vector{Int64}:
1613
 5
1614
 3
1615
 1
1616

1617
julia> deleteat!([6, 5, 4, 3, 2, 1], [true, false, true, false, true, false])
1618
3-element Vector{Int64}:
1619
 5
1620
 3
1621
 1
1622

1623
julia> deleteat!([6, 5, 4, 3, 2, 1], (2, 2))
1624
ERROR: ArgumentError: indices must be unique and sorted
1625
Stacktrace:
1626
[...]
1627
```
1628
"""
1629
deleteat!(a::Vector, inds) = _deleteat!(a, inds)
×
1630
deleteat!(a::Vector, inds::AbstractVector) = _deleteat!(a, to_indices(a, (inds,))[1])
86,894✔
1631

1632
struct Nowhere; end
1633
push!(::Nowhere, _) = nothing
1,491,174✔
1634
_growend!(::Nowhere, _) = nothing
×
1635

1636
@inline function _push_deleted!(dltd, a::Vector, ind)
1,491,174✔
1637
    if @inbounds isassigned(a, ind)
1,548,095✔
1638
        push!(dltd, @inbounds a[ind])
1,548,108✔
1639
    else
1640
        _growend!(dltd, 1)
×
1641
    end
1642
end
1643

1644
@inline function _copy_item!(a::Vector, p, q)
4,376,785✔
1645
    if @inbounds isassigned(a, q)
4,403,379✔
1646
        @inbounds a[p] = a[q]
4,403,398✔
1647
    else
1648
        _unsetindex!(a, p)
×
1649
    end
1650
end
1651

1652
function _deleteat!(a::Vector, inds, dltd=Nowhere())
122,568✔
1653
    n = length(a)
173,788✔
1654
    y = iterate(inds)
87,136✔
1655
    y === nothing && return a
86,894✔
1656
    (p, s) = y
35,432✔
1657
    checkbounds(a, p)
86,652✔
1658
    _push_deleted!(dltd, a, p)
86,656✔
1659
    q = p+1
86,652✔
1660
    while true
1,548,095✔
1661
        y = iterate(inds, s)
1,634,747✔
1662
        y === nothing && break
1,548,095✔
1663
        (i,s) = y
1,455,742✔
1664
        if !(q <= i <= n)
1,461,443✔
1665
            if i < q
×
1666
                _throw_argerror("indices must be unique and sorted")
×
1667
            else
1668
                throw(BoundsError())
×
1669
            end
1670
        end
1671
        while q < i
2,885,704✔
1672
            _copy_item!(a, p, q)
1,424,276✔
1673
            p += 1; q += 1
2,848,522✔
1674
        end
1,424,261✔
1675
        _push_deleted!(dltd, a, i)
1,461,452✔
1676
        q = i+1
1,461,443✔
1677
    end
1,461,443✔
1678
    while q <= n
3,023,766✔
1679
        _copy_item!(a, p, q)
2,937,118✔
1680
        p += 1; q += 1
5,874,228✔
1681
    end
2,937,114✔
1682
    _deleteend!(a, n-p+1)
86,652✔
1683
    return a
86,652✔
1684
end
1685

1686
# Simpler and more efficient version for logical indexing
1687
function deleteat!(a::Vector, inds::AbstractVector{Bool})
4,006✔
1688
    n = length(a)
4,006✔
1689
    length(inds) == n || throw(BoundsError(a, inds))
4,008✔
1690
    p = 1
4,004✔
1691
    for (q, i) in enumerate(inds)
8,008✔
1692
        _copy_item!(a, p, q)
42,004✔
1693
        p += !i
42,004✔
1694
    end
80,004✔
1695
    _deleteend!(a, n-p+1)
4,004✔
1696
    return a
4,004✔
1697
end
1698

1699
const _default_splice = []
1700

1701
"""
1702
    splice!(a::Vector, index::Integer, [replacement]) -> item
1703

1704
Remove the item at the given index, and return the removed item.
1705
Subsequent items are shifted left to fill the resulting gap.
1706
If specified, replacement values from an ordered
1707
collection will be spliced in place of the removed item.
1708

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

1711
# Examples
1712
```jldoctest
1713
julia> A = [6, 5, 4, 3, 2, 1]; splice!(A, 5)
1714
2
1715

1716
julia> A
1717
5-element Vector{Int64}:
1718
 6
1719
 5
1720
 4
1721
 3
1722
 1
1723

1724
julia> splice!(A, 5, -1)
1725
1
1726

1727
julia> A
1728
5-element Vector{Int64}:
1729
  6
1730
  5
1731
  4
1732
  3
1733
 -1
1734

1735
julia> splice!(A, 1, [-1, -2, -3])
1736
6
1737

1738
julia> A
1739
7-element Vector{Int64}:
1740
 -1
1741
 -2
1742
 -3
1743
  5
1744
  4
1745
  3
1746
 -1
1747
```
1748

1749
To insert `replacement` before an index `n` without removing any items, use
1750
`splice!(collection, n:n-1, replacement)`.
1751
"""
1752
function splice!(a::Vector, i::Integer, ins=_default_splice)
3,682✔
1753
    v = a[i]
3,692✔
1754
    m = length(ins)
3,406✔
1755
    if m == 0
3,406✔
1756
        _deleteat!(a, i, 1)
546✔
1757
    elseif m == 1
2,860✔
1758
        a[i] = ins[1]
261✔
1759
    else
1760
        _growat!(a, i, m-1)
2,599✔
1761
        k = 1
2,599✔
1762
        for x in ins
2,599✔
1763
            a[i+k-1] = x
334,853✔
1764
            k += 1
334,853✔
1765
        end
334,853✔
1766
    end
1767
    return v
3,406✔
1768
end
1769

1770
"""
1771
    splice!(a::Vector, indices, [replacement]) -> items
1772

1773
Remove items at specified indices, and return a collection containing
1774
the removed items.
1775
Subsequent items are shifted left to fill the resulting gaps.
1776
If specified, replacement values from an ordered collection will be spliced in
1777
place of the removed items; in this case, `indices` must be a `AbstractUnitRange`.
1778

1779
To insert `replacement` before an index `n` without removing any items, use
1780
`splice!(collection, n:n-1, replacement)`.
1781

1782
!!! compat "Julia 1.5"
1783
    Prior to Julia 1.5, `indices` must always be a `UnitRange`.
1784

1785
!!! compat "Julia 1.8"
1786
    Prior to Julia 1.8, `indices` must be a `UnitRange` if splicing in replacement values.
1787

1788
# Examples
1789
```jldoctest
1790
julia> A = [-1, -2, -3, 5, 4, 3, -1]; splice!(A, 4:3, 2)
1791
Int64[]
1792

1793
julia> A
1794
8-element Vector{Int64}:
1795
 -1
1796
 -2
1797
 -3
1798
  2
1799
  5
1800
  4
1801
  3
1802
 -1
1803
```
1804
"""
1805
function splice!(a::Vector, r::AbstractUnitRange{<:Integer}, ins=_default_splice)
105,710✔
1806
    v = a[r]
105,718✔
1807
    m = length(ins)
71,772✔
1808
    if m == 0
71,772✔
1809
        deleteat!(a, r)
74,225✔
1810
        return v
37,171✔
1811
    end
1812

1813
    n = length(a)
34,601✔
1814
    f = first(r)
34,601✔
1815
    l = last(r)
34,601✔
1816
    d = length(r)
34,601✔
1817

1818
    if m < d
34,601✔
1819
        delta = d - m
12,704✔
1820
        _deleteat!(a, (f - 1 < n - l) ? f : (l - delta + 1), delta)
19,180✔
1821
    elseif m > d
21,897✔
1822
        _growat!(a, (f - 1 < n - l) ? f : (l + 1), m - d)
21,788✔
1823
    end
1824

1825
    k = 1
34,518✔
1826
    for x in ins
46,107✔
1827
        a[f+k-1] = x
5,375,864✔
1828
        k += 1
4,031,979✔
1829
    end
5,398,896✔
1830
    return v
34,601✔
1831
end
1832

1833
splice!(a::Vector, inds) = (dltds = eltype(a)[]; _deleteat!(a, inds, dltds); dltds)
×
1834

1835
function empty!(a::Vector)
80,811✔
1836
    _deleteend!(a, length(a))
65,953,283✔
1837
    return a
65,953,283✔
1838
end
1839

1840
_memcmp(a, b, len) = ccall(:memcmp, Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), a, b, len % Csize_t) % Int
79,046✔
1841

1842
# use memcmp for cmp on byte arrays
1843
function cmp(a::Array{UInt8,1}, b::Array{UInt8,1})
×
1844
    c = _memcmp(a, b, min(length(a),length(b)))
×
1845
    return c < 0 ? -1 : c > 0 ? +1 : cmp(length(a),length(b))
×
1846
end
1847

1848
const BitIntegerArray{N} = Union{map(T->Array{T,N}, BitInteger_types)...} where N
×
1849
# use memcmp for == on bit integer types
1850
==(a::Arr, b::Arr) where {Arr <: BitIntegerArray} =
1,461✔
1851
    size(a) == size(b) && 0 == _memcmp(a, b, sizeof(eltype(Arr)) * length(a))
1852

1853
# this is ~20% faster than the generic implementation above for very small arrays
1854
function ==(a::Arr, b::Arr) where Arr <: BitIntegerArray{1}
7,584✔
1855
    len = length(a)
46,032✔
1856
    len == length(b) && 0 == _memcmp(a, b, sizeof(eltype(Arr)) * len)
46,034✔
1857
end
1858

1859
"""
1860
    reverse(v [, start=firstindex(v) [, stop=lastindex(v) ]] )
1861

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

1865
# Examples
1866
```jldoctest
1867
julia> A = Vector(1:5)
1868
5-element Vector{Int64}:
1869
 1
1870
 2
1871
 3
1872
 4
1873
 5
1874

1875
julia> reverse(A)
1876
5-element Vector{Int64}:
1877
 5
1878
 4
1879
 3
1880
 2
1881
 1
1882

1883
julia> reverse(A, 1, 4)
1884
5-element Vector{Int64}:
1885
 4
1886
 3
1887
 2
1888
 1
1889
 5
1890

1891
julia> reverse(A, 3, 5)
1892
5-element Vector{Int64}:
1893
 1
1894
 2
1895
 5
1896
 4
1897
 3
1898
```
1899
"""
1900
function reverse(A::AbstractVector, start::Integer, stop::Integer=lastindex(A))
5,145✔
1901
    s, n = Int(start), Int(stop)
563✔
1902
    B = similar(A)
5,146✔
1903
    for i = firstindex(A):s-1
5,145✔
1904
        B[i] = A[i]
×
1905
    end
×
1906
    for i = s:n
10,282✔
1907
        B[i] = A[n+s-i]
244,703✔
1908
    end
484,265✔
1909
    for i = n+1:lastindex(A)
5,145✔
1910
        B[i] = A[i]
×
1911
    end
×
1912
    return B
5,145✔
1913
end
1914

1915
# 1d special cases of reverse(A; dims) and reverse!(A; dims):
1916
for (f,_f) in ((:reverse,:_reverse), (:reverse!,:_reverse!))
1917
    @eval begin
1918
        $f(A::AbstractVector; dims=:) = $_f(A, dims)
87,105,242✔
1919
        $_f(A::AbstractVector, ::Colon) = $f(A, firstindex(A), lastindex(A))
7,139✔
1920
        $_f(A::AbstractVector, dim::Tuple{Integer}) = $_f(A, first(dim))
×
1921
        function $_f(A::AbstractVector, dim::Integer)
1✔
1922
            dim == 1 || _throw_argerror(LazyString("invalid dimension ", dim, " ≠ 1"))
1✔
1923
            return $_f(A, :)
1✔
1924
        end
1925
    end
1926
end
1927

1928
function reverseind(a::AbstractVector, i::Integer)
×
1929
    li = LinearIndices(a)
×
1930
    first(li) + last(li) - i
×
1931
end
1932

1933
# This implementation of `midpoint` is performance-optimized but safe
1934
# only if `lo <= hi`.
1935
midpoint(lo::T, hi::T) where T<:Integer = lo + ((hi - lo) >>> 0x01)
3,350,194✔
1936
midpoint(lo::Integer, hi::Integer) = midpoint(promote(lo, hi)...)
×
1937

1938
"""
1939
    reverse!(v [, start=firstindex(v) [, stop=lastindex(v) ]]) -> v
1940

1941
In-place version of [`reverse`](@ref).
1942

1943
# Examples
1944
```jldoctest
1945
julia> A = Vector(1:5)
1946
5-element Vector{Int64}:
1947
 1
1948
 2
1949
 3
1950
 4
1951
 5
1952

1953
julia> reverse!(A);
1954

1955
julia> A
1956
5-element Vector{Int64}:
1957
 5
1958
 4
1959
 3
1960
 2
1961
 1
1962
```
1963
"""
1964
function reverse!(v::AbstractVector, start::Integer, stop::Integer=lastindex(v))
63,474✔
1965
    s, n = Int(start), Int(stop)
2,587✔
1966
    if n > s # non-empty and non-trivial
63,472✔
1967
        liv = LinearIndices(v)
60,350✔
1968
        if !(first(liv) ≤ s ≤ last(liv))
60,350✔
1969
            throw(BoundsError(v, s))
2✔
1970
        elseif !(first(liv) ≤ n ≤ last(liv))
60,348✔
1971
            throw(BoundsError(v, n))
×
1972
        end
1973
        r = n
2,137✔
1974
        @inbounds for i in s:midpoint(s, n-1)
120,696✔
1975
            v[i], v[r] = v[r], v[i]
1,562,271✔
1976
            r -= 1
1,562,271✔
1977
        end
3,064,194✔
1978
    end
1979
    return v
63,470✔
1980
end
1981

1982
# concatenations of (in)homogeneous combinations of vectors, horizontal and vertical
1983

1984
vcat() = Vector{Any}()
10,497✔
1985
hcat() = Vector{Any}()
1✔
1986

1987
function hcat(V::Vector{T}...) where T
557✔
1988
    height = length(V[1])
557✔
1989
    for j = 2:length(V)
558✔
1990
        if length(V[j]) != height
625✔
1991
            throw(DimensionMismatch("vectors must have same lengths"))
×
1992
        end
1993
    end
723✔
1994
    return [ V[j][i]::T for i=1:length(V[1]), j=1:length(V) ]
557✔
1995
end
1996
hcat(A::Vector...) = cat(A...; dims=Val(2)) # more special than SparseArrays's hcat
6✔
1997

1998
function vcat(arrays::Vector{T}...) where T
36,103✔
1999
    n = 0
6,966✔
2000
    for a in arrays
36,103✔
2001
        n += length(a)
2,072,302✔
2002
    end
2,108,386✔
2003
    arr = Vector{T}(undef, n)
36,103✔
2004
    nd = 1
6,966✔
2005
    for a in arrays
36,103✔
2006
        na = length(a)
2,072,302✔
2007
        @assert nd + na <= 1 + length(arr) # Concurrent modification of arrays?
2,072,302✔
2008
        unsafe_copyto!(arr, nd, a, 1, na)
2,072,302✔
2009
        nd += na
2,072,302✔
2010
    end
2,108,386✔
2011
    return arr
36,103✔
2012
end
2013
vcat(A::Vector...) = cat(A...; dims=Val(1)) # more special than SparseArrays's vcat
44✔
2014

2015
# disambiguation with LinAlg/special.jl
2016
# Union{Number,Vector,Matrix} is for LinearAlgebra._DenseConcatGroup
2017
# VecOrMat{T} is for LinearAlgebra._TypedDenseConcatGroup
2018
hcat(A::Union{Number,Vector,Matrix}...) = cat(A...; dims=Val(2))
104✔
2019
hcat(A::VecOrMat{T}...) where {T} = typed_hcat(T, A...)
172✔
2020
vcat(A::Union{Number,Vector,Matrix}...) = cat(A...; dims=Val(1))
110✔
2021
vcat(A::VecOrMat{T}...) where {T} = typed_vcat(T, A...)
540✔
2022
hvcat(rows::Tuple{Vararg{Int}}, xs::Union{Number,Vector,Matrix}...) =
91✔
2023
    typed_hvcat(promote_eltypeof(xs...), rows, xs...)
2024
hvcat(rows::Tuple{Vararg{Int}}, xs::VecOrMat{T}...) where {T} =
61✔
2025
    typed_hvcat(T, rows, xs...)
2026

2027
_cat(n::Integer, x::Integer...) = reshape([x...], (ntuple(Returns(1), n-1)..., length(x)))
×
2028

2029
## find ##
2030

2031
"""
2032
    findnext(A, i)
2033

2034
Find the next index after or including `i` of a `true` element of `A`,
2035
or `nothing` if not found.
2036

2037
Indices are of the same type as those returned by [`keys(A)`](@ref)
2038
and [`pairs(A)`](@ref).
2039

2040
# Examples
2041
```jldoctest
2042
julia> A = [false, false, true, false]
2043
4-element Vector{Bool}:
2044
 0
2045
 0
2046
 1
2047
 0
2048

2049
julia> findnext(A, 1)
2050
3
2051

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

2054
julia> A = [false false; true false]
2055
2×2 Matrix{Bool}:
2056
 0  0
2057
 1  0
2058

2059
julia> findnext(A, CartesianIndex(1, 1))
2060
CartesianIndex(2, 1)
2061
```
2062
"""
2063
findnext(A, start) = findnext(identity, A, start)
77,508✔
2064

2065
"""
2066
    findfirst(A)
2067

2068
Return the index or key of the first `true` value in `A`.
2069
Return `nothing` if no such value is found.
2070
To search for other kinds of values, pass a predicate as the first argument.
2071

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

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

2077
# Examples
2078
```jldoctest
2079
julia> A = [false, false, true, false]
2080
4-element Vector{Bool}:
2081
 0
2082
 0
2083
 1
2084
 0
2085

2086
julia> findfirst(A)
2087
3
2088

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

2091
julia> A = [false false; true false]
2092
2×2 Matrix{Bool}:
2093
 0  0
2094
 1  0
2095

2096
julia> findfirst(A)
2097
CartesianIndex(2, 1)
2098
```
2099
"""
2100
findfirst(A) = findfirst(identity, A)
×
2101

2102
# Needed for bootstrap, and allows defining only an optimized findnext method
2103
findfirst(A::AbstractArray) = findnext(A, first(keys(A)))
11,688✔
2104

2105
"""
2106
    findnext(predicate::Function, A, i)
2107

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

2111
Indices are of the same type as those returned by [`keys(A)`](@ref)
2112
and [`pairs(A)`](@ref).
2113

2114
# Examples
2115
```jldoctest
2116
julia> A = [1, 4, 2, 2];
2117

2118
julia> findnext(isodd, A, 1)
2119
1
2120

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

2123
julia> A = [1 4; 2 2];
2124

2125
julia> findnext(isodd, A, CartesianIndex(1, 1))
2126
CartesianIndex(1, 1)
2127
```
2128
"""
2129
function findnext(testf::Function, A, start)
47,608✔
2130
    i = oftype(first(keys(A)), start)
45,556✔
2131
    l = last(keys(A))
37,656,576✔
2132
    i > l && return nothing
37,656,576✔
2133
    while true
152,532,492✔
2134
        testf(A[i]) && return i
152,536,563✔
2135
        i == l && break
152,103,303✔
2136
        # nextind(A, l) can throw/overflow
2137
        i = nextind(A, i)
148,029,344✔
2138
    end
148,029,326✔
2139
    return nothing
4,073,955✔
2140
end
2141

2142
"""
2143
    findfirst(predicate::Function, A)
2144

2145
Return the index or key of the first element of `A` for which `predicate` returns `true`.
2146
Return `nothing` if there is no such element.
2147

2148
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2149
and [`pairs(A)`](@ref).
2150

2151
# Examples
2152
```jldoctest
2153
julia> A = [1, 4, 2, 2]
2154
4-element Vector{Int64}:
2155
 1
2156
 4
2157
 2
2158
 2
2159

2160
julia> findfirst(iseven, A)
2161
2
2162

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

2165
julia> findfirst(isequal(4), A)
2166
2
2167

2168
julia> A = [1 4; 2 2]
2169
2×2 Matrix{Int64}:
2170
 1  4
2171
 2  2
2172

2173
julia> findfirst(iseven, A)
2174
CartesianIndex(2, 1)
2175
```
2176
"""
2177
function findfirst(testf::Function, A)
12✔
2178
    for (i, a) in pairs(A)
18✔
2179
        testf(a) && return i
12✔
2180
    end
10✔
2181
    return nothing
6✔
2182
end
2183

2184
# Needed for bootstrap, and allows defining only an optimized findnext method
2185
findfirst(testf::Function, A::Union{AbstractArray, AbstractString}) =
190,377,624✔
2186
    findnext(testf, A, first(keys(A)))
2187

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

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

2194
function findfirst(p::Union{Fix2{typeof(isequal),T},Fix2{typeof(==),T}}, r::StepRange{T,S}) where {T,S}
6✔
2195
    isempty(r) && return nothing
6✔
2196
    minimum(r) <= p.x <= maximum(r) || return nothing
7✔
2197
    d = convert(S, p.x - first(r))
3✔
2198
    iszero(d % step(r)) || return nothing
3✔
2199
    return d ÷ step(r) + 1
3✔
2200
end
2201

2202
"""
2203
    findprev(A, i)
2204

2205
Find the previous index before or including `i` of a `true` element of `A`,
2206
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
See also: [`findnext`](@ref), [`findfirst`](@ref), [`findall`](@ref).
2212

2213
# Examples
2214
```jldoctest
2215
julia> A = [false, false, true, true]
2216
4-element Vector{Bool}:
2217
 0
2218
 0
2219
 1
2220
 1
2221

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

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

2227
julia> A = [false false; true true]
2228
2×2 Matrix{Bool}:
2229
 0  0
2230
 1  1
2231

2232
julia> findprev(A, CartesianIndex(2, 1))
2233
CartesianIndex(2, 1)
2234
```
2235
"""
2236
findprev(A, start) = findprev(identity, A, start)
12,119✔
2237

2238
"""
2239
    findlast(A)
2240

2241
Return the index or key of the last `true` value in `A`.
2242
Return `nothing` if there is no `true` value in `A`.
2243

2244
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2245
and [`pairs(A)`](@ref).
2246

2247
See also: [`findfirst`](@ref), [`findprev`](@ref), [`findall`](@ref).
2248

2249
# Examples
2250
```jldoctest
2251
julia> A = [true, false, true, false]
2252
4-element Vector{Bool}:
2253
 1
2254
 0
2255
 1
2256
 0
2257

2258
julia> findlast(A)
2259
3
2260

2261
julia> A = falses(2,2);
2262

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

2265
julia> A = [true false; true false]
2266
2×2 Matrix{Bool}:
2267
 1  0
2268
 1  0
2269

2270
julia> findlast(A)
2271
CartesianIndex(2, 1)
2272
```
2273
"""
2274
findlast(A) = findlast(identity, A)
22✔
2275

2276
# Needed for bootstrap, and allows defining only an optimized findprev method
2277
findlast(A::AbstractArray) = findprev(A, last(keys(A)))
3,921✔
2278

2279
"""
2280
    findprev(predicate::Function, A, i)
2281

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

2285
Indices are of the same type as those returned by [`keys(A)`](@ref)
2286
and [`pairs(A)`](@ref).
2287

2288
# Examples
2289
```jldoctest
2290
julia> A = [4, 6, 1, 2]
2291
4-element Vector{Int64}:
2292
 4
2293
 6
2294
 1
2295
 2
2296

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

2299
julia> findprev(isodd, A, 3)
2300
3
2301

2302
julia> A = [4 6; 1 2]
2303
2×2 Matrix{Int64}:
2304
 4  6
2305
 1  2
2306

2307
julia> findprev(isodd, A, CartesianIndex(1, 2))
2308
CartesianIndex(2, 1)
2309
```
2310
"""
2311
function findprev(testf::Function, A, start)
36,692✔
2312
    f = first(keys(A))
36,692✔
2313
    i = oftype(f, start)
36,699✔
2314
    i < f && return nothing
38,241✔
2315
    while true
185,164✔
2316
        testf(A[i]) && return i
185,247✔
2317
        i == f && break
147,005✔
2318
        # prevind(A, f) can throw/underflow
2319
        i = prevind(A, i)
146,950✔
2320
    end
146,924✔
2321
    return nothing
53✔
2322
end
2323

2324
"""
2325
    findlast(predicate::Function, A)
2326

2327
Return the index or key of the last element of `A` for which `predicate` returns `true`.
2328
Return `nothing` if there is no such element.
2329

2330
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2331
and [`pairs(A)`](@ref).
2332

2333
# Examples
2334
```jldoctest
2335
julia> A = [1, 2, 3, 4]
2336
4-element Vector{Int64}:
2337
 1
2338
 2
2339
 3
2340
 4
2341

2342
julia> findlast(isodd, A)
2343
3
2344

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

2347
julia> A = [1 2; 3 4]
2348
2×2 Matrix{Int64}:
2349
 1  2
2350
 3  4
2351

2352
julia> findlast(isodd, A)
2353
CartesianIndex(2, 1)
2354
```
2355
"""
2356
function findlast(testf::Function, A)
3✔
2357
    for (i, a) in Iterators.reverse(pairs(A))
3✔
2358
        testf(a) && return i
5✔
2359
    end
5✔
2360
    return nothing
1✔
2361
end
2362

2363
# Needed for bootstrap, and allows defining only an optimized findprev method
2364
findlast(testf::Function, A::Union{AbstractArray, AbstractString}) =
13,190✔
2365
    findprev(testf, A, last(keys(A)))
2366

2367
"""
2368
    findall(f::Function, A)
2369

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

2373
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2374
and [`pairs(A)`](@ref).
2375

2376
# Examples
2377
```jldoctest
2378
julia> x = [1, 3, 4]
2379
3-element Vector{Int64}:
2380
 1
2381
 3
2382
 4
2383

2384
julia> findall(isodd, x)
2385
2-element Vector{Int64}:
2386
 1
2387
 2
2388

2389
julia> A = [1 2 0; 3 4 0]
2390
2×3 Matrix{Int64}:
2391
 1  2  0
2392
 3  4  0
2393
julia> findall(isodd, A)
2394
2-element Vector{CartesianIndex{2}}:
2395
 CartesianIndex(1, 1)
2396
 CartesianIndex(2, 1)
2397

2398
julia> findall(!iszero, A)
2399
4-element Vector{CartesianIndex{2}}:
2400
 CartesianIndex(1, 1)
2401
 CartesianIndex(2, 1)
2402
 CartesianIndex(1, 2)
2403
 CartesianIndex(2, 2)
2404

2405
julia> d = Dict(:A => 10, :B => -1, :C => 0)
2406
Dict{Symbol, Int64} with 3 entries:
2407
  :A => 10
2408
  :B => -1
2409
  :C => 0
2410

2411
julia> findall(x -> x >= 0, d)
2412
2-element Vector{Symbol}:
2413
 :A
2414
 :C
2415

2416
```
2417
"""
2418
function findall(testf::Function, A)
55✔
2419
    T = eltype(keys(A))
55✔
2420
    gen = (first(p) for p in pairs(A) if testf(last(p)))
55✔
2421
    isconcretetype(T) ? collect(T, gen) : collect(gen)
55✔
2422
end
2423

2424
# Broadcasting is much faster for small testf, and computing
2425
# integer indices from logical index using findall has a negligible cost
2426
findall(testf::F, A::AbstractArray) where {F<:Function} = findall(testf.(A))
314✔
2427

2428
"""
2429
    findall(A)
2430

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

2435
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2436
and [`pairs(A)`](@ref).
2437

2438
See also: [`findfirst`](@ref), [`searchsorted`](@ref).
2439

2440
# Examples
2441
```jldoctest
2442
julia> A = [true, false, false, true]
2443
4-element Vector{Bool}:
2444
 1
2445
 0
2446
 0
2447
 1
2448

2449
julia> findall(A)
2450
2-element Vector{Int64}:
2451
 1
2452
 4
2453

2454
julia> A = [true false; false true]
2455
2×2 Matrix{Bool}:
2456
 1  0
2457
 0  1
2458

2459
julia> findall(A)
2460
2-element Vector{CartesianIndex{2}}:
2461
 CartesianIndex(1, 1)
2462
 CartesianIndex(2, 2)
2463

2464
julia> findall(falses(3))
2465
Int64[]
2466
```
2467
"""
2468
function findall(A)
1✔
2469
    collect(first(p) for p in pairs(A) if last(p))
1✔
2470
end
2471

2472
# Allocating result upfront is faster (possible only when collection can be iterated twice)
2473
function _findall(f::Function, A::AbstractArray{Bool})
2,827✔
2474
    n = count(f, A)
2,829✔
2475
    I = Vector{eltype(keys(A))}(undef, n)
2,827✔
2476
    isempty(I) && return I
2,827✔
2477
    _findall(f, I, A)
2,456✔
2478
end
2479

2480
function _findall(f::Function, I::Vector, A::AbstractArray{Bool})
22✔
2481
    cnt = 1
22✔
2482
    len = length(I)
22✔
2483
    for (k, v) in pairs(A)
43✔
2484
        @inbounds I[cnt] = k
2,352✔
2485
        cnt += f(v)
2,352✔
2486
        cnt > len && return I
2,352✔
2487
    end
4,660✔
2488
    # In case of impure f, this line could potentially be hit. In that case,
2489
    # we can't assume I is the correct length.
2490
    resize!(I, cnt - 1)
×
2491
end
2492

2493
function _findall(f::Function, I::Vector, A::AbstractVector{Bool})
2,434✔
2494
    i = firstindex(A)
2,434✔
2495
    cnt = 1
2,434✔
2496
    len = length(I)
2,434✔
2497
    while cnt ≤ len
89,390✔
2498
        @inbounds I[cnt] = i
86,956✔
2499
        cnt += f(@inbounds A[i])
86,956✔
2500
        i = nextind(A, i)
86,956✔
2501
    end
86,956✔
2502
    cnt - 1 == len ? I : resize!(I, cnt - 1)
2,434✔
2503
end
2504

2505
findall(f::Function, A::AbstractArray{Bool}) = _findall(f, A)
2✔
2506
findall(f::Fix2{typeof(in)}, A::AbstractArray{Bool}) = _findall(f, A)
×
2507
findall(A::AbstractArray{Bool}) = _findall(identity, A)
4,732✔
2508

2509
findall(x::Bool) = x ? [1] : Vector{Int}()
×
2510
findall(testf::Function, x::Number) = testf(x) ? [1] : Vector{Int}()
×
2511
findall(p::Fix2{typeof(in)}, x::Number) = x in p.x ? [1] : Vector{Int}()
×
2512

2513
# similar to Matlab's ismember
2514
"""
2515
    indexin(a, b)
2516

2517
Return an array containing the first index in `b` for
2518
each value in `a` that is a member of `b`. The output
2519
array contains `nothing` wherever `a` is not a member of `b`.
2520

2521
See also: [`sortperm`](@ref), [`findfirst`](@ref).
2522

2523
# Examples
2524
```jldoctest
2525
julia> a = ['a', 'b', 'c', 'b', 'd', 'a'];
2526

2527
julia> b = ['a', 'b', 'c'];
2528

2529
julia> indexin(a, b)
2530
6-element Vector{Union{Nothing, Int64}}:
2531
 1
2532
 2
2533
 3
2534
 2
2535
  nothing
2536
 1
2537

2538
julia> indexin(b, a)
2539
3-element Vector{Union{Nothing, Int64}}:
2540
 1
2541
 2
2542
 3
2543
```
2544
"""
2545
function indexin(a, b::AbstractArray)
×
2546
    inds = keys(b)
×
2547
    bdict = Dict{eltype(b),eltype(inds)}()
×
2548
    for (val, ind) in zip(b, inds)
×
2549
        get!(bdict, val, ind)
×
2550
    end
×
2551
    return Union{eltype(inds), Nothing}[
×
2552
        get(bdict, i, nothing) for i in a
2553
    ]
2554
end
2555

2556
function _findin(a::Union{AbstractArray, Tuple}, b)
364✔
2557
    ind  = Vector{eltype(keys(a))}()
550✔
2558
    bset = Set(b)
364✔
2559
    @inbounds for (i,ai) in pairs(a)
585✔
2560
        ai in bset && push!(ind, i)
90,472✔
2561
    end
180,477✔
2562
    ind
364✔
2563
end
2564

2565
# If two collections are already sorted, _findin can be computed with
2566
# a single traversal of the two collections. This is much faster than
2567
# using a hash table (although it has the same complexity).
2568
function _sortedfindin(v::Union{AbstractArray, Tuple}, w)
×
2569
    viter, witer = keys(v), eachindex(w)
×
2570
    out  = eltype(viter)[]
×
2571
    vy, wy = iterate(viter), iterate(witer)
×
2572
    if vy === nothing || wy === nothing
×
2573
        return out
×
2574
    end
2575
    viteri, i = vy
×
2576
    witerj, j = wy
×
2577
    @inbounds begin
×
2578
        vi, wj = v[viteri], w[witerj]
×
2579
        while true
×
2580
            if isless(vi, wj)
×
2581
                vy = iterate(viter, i)
×
2582
                if vy === nothing
×
2583
                    break
×
2584
                end
2585
                viteri, i = vy
×
2586
                vi        = v[viteri]
×
2587
            elseif isless(wj, vi)
×
2588
                wy = iterate(witer, j)
×
2589
                if wy === nothing
×
2590
                    break
×
2591
                end
2592
                witerj, j = wy
×
2593
                wj        = w[witerj]
×
2594
            else
2595
                push!(out, viteri)
×
2596
                vy = iterate(viter, i)
×
2597
                if vy === nothing
×
2598
                    break
×
2599
                end
2600
                # We only increment the v iterator because v can have
2601
                # repeated matches to a single value in w
2602
                viteri, i = vy
×
2603
                vi        = v[viteri]
×
2604
            end
2605
        end
×
2606
    end
2607
    return out
×
2608
end
2609

2610
function findall(pred::Fix2{typeof(in),<:Union{Array{<:Real},Real}}, x::Array{<:Real})
1✔
2611
    if issorted(x, Sort.Forward) && issorted(pred.x, Sort.Forward)
1✔
2612
        return _sortedfindin(x, pred.x)
×
2613
    else
2614
        return _findin(x, pred.x)
1✔
2615
    end
2616
end
2617
# issorted fails for some element types so the method above has to be restricted
2618
# to element with isless/< defined.
2619
findall(pred::Fix2{typeof(in)}, x::AbstractArray) = _findin(x, pred.x)
370✔
2620
findall(pred::Fix2{typeof(in)}, x::Tuple) = _findin(x, pred.x)
×
2621

2622
# Copying subregions
2623
function indcopy(sz::Dims, I::Vector)
×
2624
    n = length(I)
×
2625
    s = sz[n]
×
2626
    for i = n+1:length(sz)
×
2627
        s *= sz[i]
×
2628
    end
×
2629
    dst = eltype(I)[_findin(I[i], i < n ? (1:sz[i]) : (1:s)) for i = 1:n]
×
2630
    src = eltype(I)[I[i][_findin(I[i], i < n ? (1:sz[i]) : (1:s))] for i = 1:n]
×
2631
    dst, src
×
2632
end
2633

2634
function indcopy(sz::Dims, I::Tuple{Vararg{RangeIndex}})
×
2635
    n = length(I)
×
2636
    s = sz[n]
×
2637
    for i = n+1:length(sz)
×
2638
        s *= sz[i]
×
2639
    end
×
2640
    dst::typeof(I) = ntuple(i-> _findin(I[i], i < n ? (1:sz[i]) : (1:s)), n)::typeof(I)
×
2641
    src::typeof(I) = ntuple(i-> I[i][_findin(I[i], i < n ? (1:sz[i]) : (1:s))], n)::typeof(I)
×
2642
    dst, src
×
2643
end
2644

2645
## Filter ##
2646

2647
"""
2648
    filter(f, a)
2649

2650
Return a copy of collection `a`, removing elements for which `f` is `false`.
2651
The function `f` is passed one argument.
2652

2653
!!! compat "Julia 1.4"
2654
    Support for `a` as a tuple requires at least Julia 1.4.
2655

2656
See also: [`filter!`](@ref), [`Iterators.filter`](@ref).
2657

2658
# Examples
2659
```jldoctest
2660
julia> a = 1:10
2661
1:10
2662

2663
julia> filter(isodd, a)
2664
5-element Vector{Int64}:
2665
 1
2666
 3
2667
 5
2668
 7
2669
 9
2670
```
2671
"""
2672
function filter(f, a::Array{T, N}) where {T, N}
443,963✔
2673
    j = 1
443,114✔
2674
    b = Vector{T}(undef, length(a))
443,963✔
2675
    for ai in a
443,980✔
2676
        @inbounds b[j] = ai
1,399,366✔
2677
        j = ifelse(f(ai)::Bool, j+1, j)
1,404,430✔
2678
    end
1,843,228✔
2679
    resize!(b, j-1)
887,926✔
2680
    sizehint!(b, length(b))
443,963✔
2681
    b
443,963✔
2682
end
2683

2684
function filter(f, a::AbstractArray)
369✔
2685
    (IndexStyle(a) != IndexLinear()) && return a[map(f, a)::AbstractArray{Bool}]
369✔
2686

2687
    j = 1
369✔
2688
    idxs = Vector{Int}(undef, length(a))
372✔
2689
    for idx in eachindex(a)
609✔
2690
        @inbounds idxs[j] = idx
103,231✔
2691
        ai = @inbounds a[idx]
103,231✔
2692
        j = ifelse(f(ai)::Bool, j+1, j)
137,287✔
2693
    end
206,221✔
2694
    resize!(idxs, j-1)
736✔
2695
    res = a[idxs]
368✔
2696
    empty!(idxs)
368✔
2697
    sizehint!(idxs, 0)
368✔
2698
    return res
368✔
2699
end
2700

2701
"""
2702
    filter!(f, a)
2703

2704
Update collection `a`, removing elements for which `f` is `false`.
2705
The function `f` is passed one argument.
2706

2707
# Examples
2708
```jldoctest
2709
julia> filter!(isodd, Vector(1:10))
2710
5-element Vector{Int64}:
2711
 1
2712
 3
2713
 5
2714
 7
2715
 9
2716
```
2717
"""
2718
function filter!(f, a::AbstractVector)
962,831✔
2719
    j = firstindex(a)
1,033✔
2720
    for ai in a
986,363✔
2721
        @inbounds a[j] = ai
3,451,577✔
2722
        j = ifelse(f(ai)::Bool, nextind(a, j), j)
6,469,912✔
2723
    end
4,390,876✔
2724
    j > lastindex(a) && return a
962,831✔
2725
    if a isa Vector
479✔
2726
        resize!(a, j-1)
329,690✔
2727
        sizehint!(a, j-1)
164,845✔
2728
    else
2729
        deleteat!(a, j:lastindex(a))
×
2730
    end
2731
    return a
164,845✔
2732
end
2733

2734
"""
2735
    filter(f)
2736

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

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

2743
# Examples
2744
```jldoctest
2745
julia> (1, 2, Inf, 4, NaN, 6) |> filter(isfinite)
2746
(1, 2, 4, 6)
2747

2748
julia> map(filter(iseven), [1:3, 2:4, 3:5])
2749
3-element Vector{Vector{Int64}}:
2750
 [2]
2751
 [2, 4]
2752
 [4]
2753
```
2754
!!! compat "Julia 1.9"
2755
    This method requires at least Julia 1.9.
2756
"""
2757
function filter(f)
×
2758
    Fix1(filter, f)
×
2759
end
2760

2761
"""
2762
    keepat!(a::Vector, inds)
2763
    keepat!(a::BitVector, inds)
2764

2765
Remove the items at all the indices which are not given by `inds`,
2766
and return the modified `a`.
2767
Items which are kept are shifted to fill the resulting gaps.
2768

2769
`inds` must be an iterator of sorted and unique integer indices.
2770
See also [`deleteat!`](@ref).
2771

2772
!!! compat "Julia 1.7"
2773
    This function is available as of Julia 1.7.
2774

2775
# Examples
2776
```jldoctest
2777
julia> keepat!([6, 5, 4, 3, 2, 1], 1:2:5)
2778
3-element Vector{Int64}:
2779
 6
2780
 4
2781
 2
2782
```
2783
"""
2784
keepat!(a::Vector, inds) = _keepat!(a, inds)
9✔
2785

2786
"""
2787
    keepat!(a::Vector, m::AbstractVector{Bool})
2788
    keepat!(a::BitVector, m::AbstractVector{Bool})
2789

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

2794
# Examples
2795
```jldoctest
2796
julia> a = [:a, :b, :c];
2797

2798
julia> keepat!(a, [true, false, true])
2799
2-element Vector{Symbol}:
2800
 :a
2801
 :c
2802

2803
julia> a
2804
2-element Vector{Symbol}:
2805
 :a
2806
 :c
2807
```
2808
"""
2809
keepat!(a::Vector, m::AbstractVector{Bool}) = _keepat!(a, m)
×
2810

2811
# set-like operators for vectors
2812
# These are moderately efficient, preserve order, and remove dupes.
2813

2814
_unique_filter!(pred::P, update!::U, state) where {P,U} = function (x)
10,538✔
2815
    # P, U force specialization
2816
    if pred(x, state)
9,469✔
2817
        update!(state, x)
3,591✔
2818
        true
3,591✔
2819
    else
2820
        false
5,773✔
2821
    end
2822
end
2823

2824
_grow_filter!(seen) = _unique_filter!(∉, push!, seen)
242✔
2825
_shrink_filter!(keep) = _unique_filter!(∈, pop!, keep)
986✔
2826

2827
function _grow!(pred!, v::AbstractVector, itrs)
257✔
2828
    filter!(pred!, v) # uniquify v
259✔
2829
    for itr in itrs
259✔
2830
        mapfilter(pred!, push!, itr, v)
502✔
2831
    end
747✔
2832
    return v
259✔
2833
end
2834

2835
union!(v::AbstractVector{T}, itrs...) where {T} =
236✔
2836
    _grow!(_grow_filter!(sizehint!(Set{T}(), length(v))), v, itrs)
2837

2838
symdiff!(v::AbstractVector{T}, itrs...) where {T} =
23✔
2839
    _grow!(_shrink_filter!(symdiff!(Set{T}(), v, itrs...)), v, itrs)
2840

2841
function _shrink!(shrinker!::F, v::AbstractVector, itrs) where F
6✔
2842
    seen = Set{eltype(v)}()
6✔
2843
    filter!(_grow_filter!(seen), v)
6✔
2844
    shrinker!(seen, itrs...)
7✔
2845
    filter!(in(seen), v)
6✔
2846
end
2847

2848
intersect!(v::AbstractVector, itrs...) = _shrink!(intersect!, v, itrs)
3✔
2849
setdiff!(  v::AbstractVector, itrs...) = _shrink!(setdiff!, v, itrs)
3✔
2850

2851
vectorfilter(T::Type, f, v) = T[x for x in v if f(x)]
964✔
2852

2853
function _shrink(shrinker!::F, itr, itrs) where F
904✔
2854
    T = promote_eltype(itr, itrs...)
826✔
2855
    keep = shrinker!(Set{T}(itr), itrs...)
913✔
2856
    vectorfilter(T, _shrink_filter!(keep), itr)
904✔
2857
end
2858

2859
intersect(itr, itrs...) = _shrink(intersect!, itr, itrs)
461✔
2860
setdiff(  itr, itrs...) = _shrink(setdiff!, itr, itrs)
443✔
2861

2862
function intersect(v::AbstractVector, r::AbstractRange)
55✔
2863
    T = promote_eltype(v, r)
7✔
2864
    common = Iterators.filter(in(r), v)
59✔
2865
    seen = Set{T}(common)
59✔
2866
    return vectorfilter(T, _shrink_filter!(seen), common)
59✔
2867
end
2868
intersect(r::AbstractRange, v::AbstractVector) = intersect(v, r)
3✔
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