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

JuliaLang / julia / #37550

pending completion
#37550

push

local

web-flow
Extend comparison lifting to `Core.ifelse` (#49882)

This change extends our existing transformation for:
   φ(a,b) === Const(c)   =>   φ(a === c, b === c)

to perform the analogous transformation for `Core.ifelse`:
   Core.ifelse(cond, a, b) === Const(c)
  =>
   Core.ifelse(cond, a === c, b === c)

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

72705 of 83986 relevant lines covered (86.57%)

20561515.97 hits per line

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

93.07
/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,234✔
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,156,632✔
161
function vect(X::T...) where T
163,700✔
162
    @_terminates_locally_meta
80,293✔
163
    vec = Vector{T}(undef, length(X))
1,281,909✔
164
    @_safeindex for i = 1:length(X)
1,332,014✔
165
        vec[i] = X[i]
4,418,838✔
166
    end
6,437,043✔
167
    return vec
1,281,909✔
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...)
54,120✔
186
    T = promote_typeof(X...)
54,120✔
187
    return T[X...]
54,349✔
188
end
189

190
size(a::Array, d::Integer) = arraysize(a, d isa Int ? d : convert(Int, d))
2,105,726✔
191
size(a::Vector) = (arraysize(a,1),)
4,686,789,436✔
192
size(a::Matrix) = (arraysize(a,1), arraysize(a,2))
6,680,702✔
193
size(a::Array{<:Any,N}) where {N} = (@inline; ntuple(M -> size(a, M), Val(N))::Dims)
1,382,439✔
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,518,796✔
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,053✔
214
isbitsunion(x) = false
16,063✔
215

216
function _unsetindex!(A::Array{T}, i::Int) where {T}
72,636✔
217
    @inline
5,612✔
218
    @boundscheck checkbounds(A, i)
6,255,281✔
219
    t = @_gc_preserve_begin A
6,252,604✔
220
    p = Ptr{Ptr{Cvoid}}(pointer(A, i))
6,251,578✔
221
    if !allocatedinline(T)
5,612✔
222
        Intrinsics.atomic_pointerset(p, C_NULL, :monotonic)
5,994,232✔
223
    elseif T isa DataType
258,620✔
224
        if !datatype_pointerfree(T)
6,174✔
225
            for j = 1:Core.sizeof(Ptr{Cvoid}):Core.sizeof(T)
1,329✔
226
                Intrinsics.atomic_pointerset(p + j - 1, C_NULL, :monotonic)
4,383✔
227
            end
7,354✔
228
        end
229
    end
230
    @_gc_preserve_end t
6,252,406✔
231
    return A
6,251,857✔
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
# Deprecate this, as it seems to have no documented meaning and is unused here,
256
# but is frequently accessed in packages
257
elsize(@nospecialize _::Type{A}) where {T,A<:Array{T}} = aligned_sizeof(T)
358,003✔
258
elsize(::Type{Union{}}, slurp...) = 0
×
259
sizeof(a::Array) = Core.sizeof(a)
3,439,649✔
260

261
function isassigned(a::Array, i::Int...)
13,081,125✔
262
    @inline
7,940,222✔
263
    @boundscheck checkbounds(Bool, a, i...) || return false
2,250,881,932✔
264
    ii = (_sub2ind(size(a), i...) % UInt) - 1
2,190,106,162✔
265
    ccall(:jl_array_isassigned, Cint, (Any, UInt), a, ii) == 1
2,250,356,798✔
266
end
267

268
## copy ##
269

270
"""
271
    unsafe_copyto!(dest::Ptr{T}, src::Ptr{T}, N)
272

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

276
The `unsafe` prefix on this function indicates that no validation is performed on the
277
pointers `dest` and `src` to ensure that they are valid. Incorrect usage may corrupt or
278
segfault your program, in the same manner as C.
279
"""
280
function unsafe_copyto!(dest::Ptr{T}, src::Ptr{T}, n) where T
8,190,202✔
281
    # Do not use this to copy data between pointer arrays.
282
    # It can't be made safe no matter how carefully you checked.
283
    ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
24,538,637✔
284
          dest, src, n * aligned_sizeof(T))
285
    return dest
23,723,546✔
286
end
287

288

289
function _unsafe_copyto!(dest, doffs, src, soffs, n)
25,895,694✔
290
    destp = pointer(dest, doffs)
25,895,694✔
291
    srcp = pointer(src, soffs)
25,895,694✔
292
    @inbounds if destp < srcp || destp > srcp + n
43,619,533✔
293
        for i = 1:n
51,791,386✔
294
            if isassigned(src, soffs + i - 1)
147,269,230✔
295
                dest[doffs + i - 1] = src[soffs + i - 1]
150,815,282✔
296
            else
297
                _unsetindex!(dest, doffs + i - 1)
×
298
            end
299
        end
268,642,527✔
300
    else
301
        for i = n:-1:1
×
302
            if isassigned(src, soffs + i - 1)
×
303
                dest[doffs + i - 1] = src[soffs + i - 1]
×
304
            else
305
                _unsetindex!(dest, doffs + i - 1)
×
306
            end
307
        end
×
308
    end
309
    return dest
25,895,453✔
310
end
311

312
"""
313
    unsafe_copyto!(dest::Array, do, src::Array, so, N)
314

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

318
The `unsafe` prefix on this function indicates that no validation is performed to ensure
319
that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in
320
the same manner as C.
321
"""
322
function unsafe_copyto!(dest::Array{T}, doffs, src::Array{T}, soffs, n) where T
2,254,933✔
323
    t1 = @_gc_preserve_begin dest
127,421,431✔
324
    t2 = @_gc_preserve_begin src
127,421,431✔
325
    destp = pointer(dest, doffs)
127,421,431✔
326
    srcp = pointer(src, soffs)
127,421,442✔
327
    if !allocatedinline(T)
2,252,325✔
328
        ccall(:jl_array_ptr_copy, Cvoid, (Any, Ptr{Cvoid}, Any, Ptr{Cvoid}, Int),
66,890,036✔
329
              dest, destp, src, srcp, n)
330
    elseif isbitstype(T)
229,925✔
331
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
40,003,331✔
332
              destp, srcp, n * aligned_sizeof(T))
333
    elseif isbitsunion(T)
6,511✔
334
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
973✔
335
              destp, srcp, n * aligned_sizeof(T))
336
        # copy selector bytes
337
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
973✔
338
              ccall(:jl_array_typetagdata, Ptr{UInt8}, (Any,), dest) + doffs - 1,
339
              ccall(:jl_array_typetagdata, Ptr{UInt8}, (Any,), src) + soffs - 1,
340
              n)
341
    else
342
        _unsafe_copyto!(dest, doffs, src, soffs, n)
20,527,102✔
343
    end
344
    @_gc_preserve_end t2
127,421,431✔
345
    @_gc_preserve_end t1
127,421,431✔
346
    return dest
42,032,084✔
347
end
348

349
unsafe_copyto!(dest::Array, doffs, src::Array, soffs, n) =
5,368,592✔
350
    _unsafe_copyto!(dest, doffs, src, soffs, n)
351

352
"""
353
    copyto!(dest, do, src, so, N)
354

355
Copy `N` elements from collection `src` starting at the linear index `so`, to array `dest` starting at
356
the index `do`. Return `dest`.
357
"""
358
function copyto!(dest::Array, doffs::Integer, src::Array, soffs::Integer, n::Integer)
48,842✔
359
    return _copyto_impl!(dest, doffs, src, soffs, n)
10,714,467✔
360
end
361

362
# this is only needed to avoid possible ambiguities with methods added in some packages
363
function copyto!(dest::Array{T}, doffs::Integer, src::Array{T}, soffs::Integer, n::Integer) where T
253,031✔
364
    return _copyto_impl!(dest, doffs, src, soffs, n)
154,165,271✔
365
end
366

367
function _copyto_impl!(dest::Array, doffs::Integer, src::Array, soffs::Integer, n::Integer)
154,212,493✔
368
    n == 0 && return dest
159,533,342✔
369
    n > 0 || _throw_argerror("Number of elements to copy must be nonnegative.")
128,913,510✔
370
    @boundscheck checkbounds(dest, doffs:doffs+n-1)
128,913,529✔
371
    @boundscheck checkbounds(src, soffs:soffs+n-1)
128,913,490✔
372
    unsafe_copyto!(dest, doffs, src, soffs, n)
128,913,484✔
373
    return dest
128,913,243✔
374
end
375

376
# Outlining this because otherwise a catastrophic inference slowdown
377
# occurs, see discussion in #27874.
378
# It is also mitigated by using a constant string.
379
_throw_argerror(s) = (@noinline; throw(ArgumentError(s)))
4,317✔
380

381
copyto!(dest::Array, src::Array) = copyto!(dest, 1, src, 1, length(src))
10,685,480✔
382

383
# also to avoid ambiguities in packages
384
copyto!(dest::Array{T}, src::Array{T}) where {T} = copyto!(dest, 1, src, 1, length(src))
42,476,489✔
385

386
# N.B: The generic definition in multidimensional.jl covers, this, this is just here
387
# for bootstrapping purposes.
388
function fill!(dest::Array{T}, x) where T
93,235✔
389
    xT = x isa T ? x : convert(T, x)::T
93,183✔
390
    for i in eachindex(dest)
692,772,669✔
391
        @inbounds dest[i] = xT
5,366,787,398✔
392
    end
10,546,034,260✔
393
    return dest
505,232,133✔
394
end
395

396
"""
397
    copy(x)
398

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

403
See also [`copy!`](@ref Base.copy!), [`copyto!`](@ref), [`deepcopy`](@ref).
404
"""
405
copy
406

407
copy(a::T) where {T<:Array} = ccall(:jl_array_copy, Ref{T}, (Any,), a)
140,124,036✔
408

409
## Constructors ##
410

411
similar(a::Array{T,1}) where {T}                    = Vector{T}(undef, size(a,1))
9,000✔
412
similar(a::Array{T,2}) where {T}                    = Matrix{T}(undef, size(a,1), size(a,2))
4,106✔
413
similar(a::Array{T,1}, S::Type) where {T}           = Vector{S}(undef, size(a,1))
10,351✔
414
similar(a::Array{T,2}, S::Type) where {T}           = Matrix{S}(undef, size(a,1), size(a,2))
13,809✔
415
similar(a::Array{T}, m::Int) where {T}              = Vector{T}(undef, m)
1,797,957✔
416
similar(a::Array, T::Type, dims::Dims{N}) where {N} = Array{T,N}(undef, dims)
58,040,211✔
417
similar(a::Array{T}, dims::Dims{N}) where {T,N}     = Array{T,N}(undef, dims)
346✔
418

419
# T[x...] constructs Array{T,1}
420
"""
421
    getindex(type[, elements...])
422

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

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

434
julia> getindex(Int8, 1, 2, 3)
435
3-element Vector{Int8}:
436
 1
437
 2
438
 3
439
```
440
"""
441
function getindex(::Type{T}, vals...) where T
217,157✔
442
    @inline
98,050✔
443
    @_effect_free_terminates_locally_meta
98,050✔
444
    a = Vector{T}(undef, length(vals))
649,722,359✔
445
    if vals isa NTuple
98,226✔
446
        @_safeindex for i in 1:length(vals)
23,339,283✔
447
            a[i] = vals[i]
23,390,250✔
448
        end
170,207✔
449
    else
450
        # use afoldl to avoid type instability inside loop
451
        afoldl(1, vals...) do i, v
55,655✔
452
            @inbounds a[i] = v
115,069✔
453
            return i + 1
113,614✔
454
        end
455
    end
456
    return a
23,391,635✔
457
end
458

459
function getindex(::Type{Any}, @nospecialize vals...)
21,791,284✔
460
    @_effect_free_terminates_locally_meta
16,463✔
461
    a = Vector{Any}(undef, length(vals))
48,692,821✔
462
    @_safeindex for i = 1:length(vals)
64,804,286✔
463
        a[i] = vals[i]
93,055,051✔
464
    end
110,366,721✔
465
    return a
48,692,821✔
466
end
467
getindex(::Type{Any}) = Vector{Any}()
31,248,355✔
468

469
function fill!(a::Union{Array{UInt8}, Array{Int8}}, x::Integer)
10,726✔
470
    ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), a, x isa eltype(a) ? x : convert(eltype(a), x), length(a))
150,049,862✔
471
    return a
150,049,856✔
472
end
473

474
to_dim(d::Integer) = d
×
475
to_dim(d::OneTo) = last(d)
376✔
476

477
"""
478
    fill(value, dims::Tuple)
479
    fill(value, dims...)
480

481
Create an array of size `dims` with every location set to `value`.
482

483
For example, `fill(1.0, (5,5))` returns a 5×5 array of floats,
484
with `1.0` in every location of the array.
485

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

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

499
```jldoctest
500
julia> v = fill([], 3)
501
3-element Vector{Vector{Any}}:
502
 []
503
 []
504
 []
505

506
julia> v[1] === v[2] === v[3]
507
true
508

509
julia> value = v[1]
510
Any[]
511

512
julia> push!(value, 867_5309)
513
1-element Vector{Any}:
514
 8675309
515

516
julia> v
517
3-element Vector{Vector{Any}}:
518
 [8675309]
519
 [8675309]
520
 [8675309]
521
```
522

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

526
```jldoctest
527
julia> v2 = [[] for _ in 1:3]
528
3-element Vector{Vector{Any}}:
529
 []
530
 []
531
 []
532

533
julia> v2[1] === v2[2] === v2[3]
534
false
535

536
julia> push!(v2[1], 8675309)
537
1-element Vector{Any}:
538
 8675309
539

540
julia> v2
541
3-element Vector{Vector{Any}}:
542
 [8675309]
543
 []
544
 []
545
```
546

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

549
# Examples
550
```jldoctest
551
julia> fill(1.0, (2,3))
552
2×3 Matrix{Float64}:
553
 1.0  1.0  1.0
554
 1.0  1.0  1.0
555

556
julia> fill(42)
557
0-dimensional Array{Int64, 0}:
558
42
559

560
julia> A = fill(zeros(2), 2) # sets both elements to the same [0.0, 0.0] vector
561
2-element Vector{Vector{Float64}}:
562
 [0.0, 0.0]
563
 [0.0, 0.0]
564

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

567
julia> A # both A[1] and A[2] are the very same vector
568
2-element Vector{Vector{Float64}}:
569
 [42.0, 0.0]
570
 [42.0, 0.0]
571
```
572
"""
573
function fill end
574

575
fill(v, dims::DimOrInd...) = fill(v, dims)
3,675,642,979✔
576
fill(v, dims::NTuple{N, Union{Integer, OneTo}}) where {N} = fill(v, map(to_dim, dims))
×
577
fill(v, dims::NTuple{N, Integer}) where {N} = (a=Array{typeof(v),N}(undef, dims); fill!(a, v); a)
4,571,906,385✔
578
fill(v, dims::Tuple{}) = (a=Array{typeof(v),0}(undef, dims); fill!(a, v); a)
387✔
579

580
"""
581
    zeros([T=Float64,] dims::Tuple)
582
    zeros([T=Float64,] dims...)
583

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

587
# Examples
588
```jldoctest
589
julia> zeros(1)
590
1-element Vector{Float64}:
591
 0.0
592

593
julia> zeros(Int8, 2, 3)
594
2×3 Matrix{Int8}:
595
 0  0  0
596
 0  0  0
597
```
598
"""
599
function zeros end
600

601
"""
602
    ones([T=Float64,] dims::Tuple)
603
    ones([T=Float64,] dims...)
604

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

608
# Examples
609
```jldoctest
610
julia> ones(1,2)
611
1×2 Matrix{Float64}:
612
 1.0  1.0
613

614
julia> ones(ComplexF64, 2, 3)
615
2×3 Matrix{ComplexF64}:
616
 1.0+0.0im  1.0+0.0im  1.0+0.0im
617
 1.0+0.0im  1.0+0.0im  1.0+0.0im
618
```
619
"""
620
function ones end
621

622
for (fname, felt) in ((:zeros, :zero), (:ones, :one))
623
    @eval begin
624
        $fname(dims::DimOrInd...) = $fname(dims)
20,447,239✔
625
        $fname(::Type{T}, dims::DimOrInd...) where {T} = $fname(T, dims)
185,973,075✔
626
        $fname(dims::Tuple{Vararg{DimOrInd}}) = $fname(Float64, dims)
20,484,729✔
627
        $fname(::Type{T}, dims::NTuple{N, Union{Integer, OneTo}}) where {T,N} = $fname(T, map(to_dim, dims))
1,625✔
628
        function $fname(::Type{T}, dims::NTuple{N, Integer}) where {T,N}
46,409✔
629
            a = Array{T,N}(undef, dims)
53,721,292✔
630
            fill!(a, $felt(T))
612,932,414✔
631
            return a
53,721,292✔
632
        end
633
        function $fname(::Type{T}, dims::Tuple{}) where {T}
20✔
634
            a = Array{T}(undef)
20✔
635
            fill!(a, $felt(T))
20✔
636
            return a
20✔
637
        end
638
    end
639
end
640

641
function _one(unit::T, x::AbstractMatrix) where T
158✔
642
    require_one_based_indexing(x)
158✔
643
    m,n = size(x)
158✔
644
    m==n || throw(DimensionMismatch("multiplicative identity defined only for square matrices"))
158✔
645
    # Matrix{T}(I, m, m)
646
    I = zeros(T, m, m)
3,765✔
647
    for i in 1:m
316✔
648
        I[i,i] = unit
649✔
649
    end
1,140✔
650
    I
158✔
651
end
652

653
one(x::AbstractMatrix{T}) where {T} = _one(one(T), x)
133✔
654
oneunit(x::AbstractMatrix{T}) where {T} = _one(oneunit(T), x)
31✔
655

656
## Conversions ##
657

658
convert(::Type{T}, a::AbstractArray) where {T<:Array} = a isa T ? a : T(a)::T
27,355✔
659

660
promote_rule(a::Type{Array{T,n}}, b::Type{Array{S,n}}) where {T,n,S} = el_same(promote_type(T,S), a, b)
76✔
661

662
## Constructors ##
663

664
if nameof(@__MODULE__) === :Base  # avoid method overwrite
665
# constructors should make copies
666
Array{T,N}(x::AbstractArray{S,N})         where {T,N,S} = copyto_axcheck!(Array{T,N}(undef, size(x)), x)
28,880✔
667
AbstractArray{T,N}(A::AbstractArray{S,N}) where {T,N,S} = copyto_axcheck!(similar(A,T), A)
18,612✔
668
end
669

670
## copying iterators to containers
671

672
"""
673
    collect(element_type, collection)
674

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

678
# Examples
679
```jldoctest
680
julia> collect(Float64, 1:2:5)
681
3-element Vector{Float64}:
682
 1.0
683
 3.0
684
 5.0
685
```
686
"""
687
collect(::Type{T}, itr) where {T} = _collect(T, itr, IteratorSize(itr))
22,806,452✔
688

689
_collect(::Type{T}, itr, isz::Union{HasLength,HasShape}) where {T} =
10,638,516✔
690
    copyto!(_array_for(T, isz, _similar_shape(itr, isz)), itr)
691
function _collect(::Type{T}, itr, isz::SizeUnknown) where T
12,167,935✔
692
    a = Vector{T}()
12,167,935✔
693
    for x in itr
19,016,920✔
694
        push!(a, x)
8,497,296✔
695
    end
10,145,606✔
696
    return a
12,167,935✔
697
end
698

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

702
_similar_shape(itr, ::SizeUnknown) = nothing
1✔
703
_similar_shape(itr, ::HasLength) = length(itr)::Integer
35,890,620✔
704
_similar_shape(itr, ::HasShape) = axes(itr)
424,606,144✔
705

706
_similar_for(c::AbstractArray, ::Type{T}, itr, ::SizeUnknown, ::Nothing) where {T} =
1,050,795✔
707
    similar(c, T, 0)
708
_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasLength, len::Integer) where {T} =
4,080,604✔
709
    similar(c, T, len)
710
_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasShape, axs) where {T} =
142,022✔
711
    similar(c, T, axs)
712

713
# make a collection appropriate for collecting `itr::Generator`
714
_array_for(::Type{T}, ::SizeUnknown, ::Nothing) where {T} = Vector{T}(undef, 0)
493✔
715
_array_for(::Type{T}, ::HasLength, len::Integer) where {T} = Vector{T}(undef, Int(len))
28,994,766✔
716
_array_for(::Type{T}, ::HasShape{N}, axs) where {T,N} = similar(Array{T,N}, axs)
424,663,872✔
717

718
# used by syntax lowering for simple typed comprehensions
719
_array_for(::Type{T}, itr, isz) where {T} = _array_for(T, isz, _similar_shape(itr, isz))
450,749,658✔
720

721

722
"""
723
    collect(collection)
724

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

730
Used by comprehensions to turn a generator into an `Array`.
731

732
# Examples
733
```jldoctest
734
julia> collect(1:2:13)
735
7-element Vector{Int64}:
736
  1
737
  3
738
  5
739
  7
740
  9
741
 11
742
 13
743

744
julia> [x^2 for x in 1:8 if isodd(x)]
745
4-element Vector{Int64}:
746
  1
747
  9
748
 25
749
 49
750
```
751
"""
752
collect(itr) = _collect(1:1 #= Array =#, itr, IteratorEltype(itr), IteratorSize(itr))
5,381,050✔
753

754
collect(A::AbstractArray) = _collect_indices(axes(A), A)
136,983✔
755

756
collect_similar(cont, itr) = _collect(cont, itr, IteratorEltype(itr), IteratorSize(itr))
141,413✔
757

758
_collect(cont, itr, ::HasEltype, isz::Union{HasLength,HasShape}) =
4,330,404✔
759
    copyto!(_similar_for(cont, eltype(itr), itr, isz, _similar_shape(itr, isz)), itr)
760

761
function _collect(cont, itr, ::HasEltype, isz::SizeUnknown)
1,050,761✔
762
    a = _similar_for(cont, eltype(itr), itr, isz, nothing)
1,050,764✔
763
    for x in itr
2,100,518✔
764
        push!(a,x)
8,907,734✔
765
    end
15,157,732✔
766
    return a
1,050,760✔
767
end
768

769
_collect_indices(::Tuple{}, A) = copyto!(Array{eltype(A),0}(undef), A)
3✔
770
_collect_indices(indsA::Tuple{Vararg{OneTo}}, A) =
180,815✔
771
    copyto!(Array{eltype(A)}(undef, length.(indsA)), A)
772
function _collect_indices(indsA, A)
23✔
773
    B = Array{eltype(A)}(undef, length.(indsA))
23✔
774
    copyto!(B, CartesianIndices(axes(B)), A, CartesianIndices(indsA))
23✔
775
end
776

777
# NOTE: this function is not meant to be called, only inferred, for the
778
# purpose of bounding the types of values generated by an iterator.
779
function _iterator_upper_bound(itr)
6✔
780
    x = iterate(itr)
×
781
    while x !== nothing
×
782
        val = getfield(x, 1)
×
783
        if inferencebarrier(nothing)
×
784
            return val
×
785
        end
786
        x = iterate(itr, getfield(x, 2))
×
787
    end
×
788
    throw(nothing)
6✔
789
end
790

791
# define this as a macro so that the call to Core.Compiler
792
# gets inlined into the caller before recursion detection
793
# gets a chance to see it, so that recursive calls to the caller
794
# don't trigger the inference limiter
795
if isdefined(Core, :Compiler)
796
    macro default_eltype(itr)
1✔
797
        I = esc(itr)
1✔
798
        return quote
1✔
799
            if $I isa Generator && ($I).f isa Type
398,160✔
800
                T = ($I).f
13,239✔
801
            else
802
                T = Core.Compiler.return_type(_iterator_upper_bound, Tuple{typeof($I)})
195,800✔
803
            end
804
            promote_typejoin_union(T)
209,039✔
805
        end
806
    end
807
else
808
    macro default_eltype(itr)
809
        I = esc(itr)
810
        return quote
811
            if $I isa Generator && ($I).f isa Type
812
                promote_typejoin_union($I.f)
813
            else
814
                Any
815
            end
816
        end
817
    end
818
end
819

820
function collect(itr::Generator)
242,538✔
821
    isz = IteratorSize(itr.iter)
66,438✔
822
    et = @default_eltype(itr)
×
823
    if isa(isz, SizeUnknown)
66,438✔
824
        return grow_to!(Vector{et}(), itr)
84,281✔
825
    else
826
        shp = _similar_shape(itr, isz)
158,826✔
827
        y = iterate(itr)
306,242✔
828
        if y === nothing
158,628✔
829
            return _array_for(et, isz, shp)
813✔
830
        end
831
        v1, st = y
65,097✔
832
        dest = _array_for(typeof(v1), isz, shp)
157,933✔
833
        # The typeassert gives inference a helping hand on the element type and dimensionality
834
        # (work-around for #28382)
835
        et′ = et <: Type ? Type : et
65,097✔
836
        RT = dest isa AbstractArray ? AbstractArray{<:et′, ndims(dest)} : Any
65,158✔
837
        collect_to_with_first!(dest, v1, itr, st)::RT
10,151,866✔
838
    end
839
end
840

841
_collect(c, itr, ::EltypeUnknown, isz::SizeUnknown) =
34✔
842
    grow_to!(_similar_for(c, @default_eltype(itr), itr, isz, nothing), itr)
843

844
function _collect(c, itr, ::EltypeUnknown, isz::Union{HasLength,HasShape})
140,875✔
845
    et = @default_eltype(itr)
128,444✔
846
    shp = _similar_shape(itr, isz)
140,876✔
847
    y = iterate(itr)
280,069✔
848
    if y === nothing
140,873✔
849
        return _similar_for(c, et, itr, isz, shp)
1,294✔
850
    end
851
    v1, st = y
127,375✔
852
    dest = _similar_for(c, typeof(v1), itr, isz, shp)
139,595✔
853
    # The typeassert gives inference a helping hand on the element type and dimensionality
854
    # (work-around for #28382)
855
    et′ = et <: Type ? Type : et
127,328✔
856
    RT = dest isa AbstractArray ? AbstractArray{<:et′, ndims(dest)} : Any
127,347✔
857
    collect_to_with_first!(dest, v1, itr, st)::RT
140,145✔
858
end
859

860
function collect_to_with_first!(dest::AbstractArray, v1, itr, st)
192,524✔
861
    i1 = first(LinearIndices(dest))
192,425✔
862
    dest[i1] = v1
297,440✔
863
    return collect_to!(dest, itr, i1+1, st)
83,600,495✔
864
end
865

866
function collect_to_with_first!(dest, v1, itr, st)
×
867
    push!(dest, v1)
×
868
    return grow_to!(dest, itr, st)
×
869
end
870

871
function setindex_widen_up_to(dest::AbstractArray{T}, el, i) where T
416✔
872
    @inline
413✔
873
    new = similar(dest, promote_typejoin(T, typeof(el)))
420✔
874
    f = first(LinearIndices(dest))
413✔
875
    copyto!(new, first(LinearIndices(new)), dest, f, i-f)
827✔
876
    @inbounds new[i] = el
416✔
877
    return new
416✔
878
end
879

880
function collect_to!(dest::AbstractArray{T}, itr, offs, st) where T
229,764✔
881
    # collect to dest array, checking the type of each result. if a result does not
882
    # match, widen the result type and re-dispatch.
883
    i = offs
192,841✔
884
    while true
88,264,678✔
885
        y = iterate(itr, st)
176,230,524✔
886
        y === nothing && break
88,264,670✔
887
        el, st = y
87,513,685✔
888
        if el isa T
87,512,296✔
889
            @inbounds dest[i] = el
87,971,562✔
890
            i += 1
87,966,822✔
891
        else
892
            new = setindex_widen_up_to(dest, el, i)
541✔
893
            return collect_to!(new, itr, i+1, st)
416✔
894
        end
895
    end
87,966,822✔
896
    return dest
297,432✔
897
end
898

899
function grow_to!(dest, itr)
1,153✔
900
    y = iterate(itr)
1,395✔
901
    y === nothing && return dest
1,153✔
902
    dest2 = empty(dest, typeof(y[1]))
263✔
903
    push!(dest2, y[1])
283✔
904
    grow_to!(dest2, itr, y[2])
247✔
905
end
906

907
function push_widen(dest, el)
53✔
908
    @inline
53✔
909
    new = sizehint!(empty(dest, promote_typejoin(eltype(dest), typeof(el))), length(dest))
53✔
910
    if new isa AbstractSet
53✔
911
        # TODO: merge back these two branches when copy! is re-enabled for sets/vectors
912
        union!(new, dest)
1✔
913
    else
914
        append!(new, dest)
104✔
915
    end
916
    push!(new, el)
53✔
917
    return new
53✔
918
end
919

920
function grow_to!(dest, itr, st)
300✔
921
    T = eltype(dest)
198✔
922
    y = iterate(itr, st)
551✔
923
    while y !== nothing
3,890✔
924
        el, st = y
2,358✔
925
        if el isa T
2,358✔
926
            push!(dest, el)
3,593✔
927
        else
928
            new = push_widen(dest, el)
55✔
929
            return grow_to!(new, itr, st)
53✔
930
        end
931
        y = iterate(itr, st)
5,491✔
932
    end
3,590✔
933
    return dest
247✔
934
end
935

936
## Iteration ##
937

938
iterate(A::Array, i=1) = (@inline; (i % UInt) - 1 < length(A) ? (@inbounds A[i], i + 1) : nothing)
9,849,060,285✔
939

940
## Indexing: getindex ##
941

942
"""
943
    getindex(collection, key...)
944

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

948
See also [`get`](@ref), [`keys`](@ref), [`eachindex`](@ref).
949

950
# Examples
951
```jldoctest
952
julia> A = Dict("a" => 1, "b" => 2)
953
Dict{String, Int64} with 2 entries:
954
  "b" => 2
955
  "a" => 1
956

957
julia> getindex(A, "a")
958
1
959
```
960
"""
961
function getindex end
962

963
# Faster contiguous indexing using copyto! for AbstractUnitRange and Colon
964
function getindex(A::Array, I::AbstractUnitRange{<:Integer})
367,529✔
965
    @inline
75,342✔
966
    @boundscheck checkbounds(A, I)
57,641,886✔
967
    lI = length(I)
57,641,884✔
968
    X = similar(A, axes(I))
57,641,896✔
969
    if lI > 0
57,641,884✔
970
        copyto!(X, firstindex(X), A, first(I), lI)
51,736,858✔
971
    end
972
    return X
57,641,884✔
973
end
974

975
# getindex for carrying out logical indexing for AbstractUnitRange{Bool} as Bool <: Integer
976
getindex(a::Array, r::AbstractUnitRange{Bool}) = getindex(a, to_index(r))
18✔
977

978
function getindex(A::Array, c::Colon)
340✔
979
    lI = length(A)
1,792,287✔
980
    X = similar(A, lI)
1,792,287✔
981
    if lI > 0
1,792,287✔
982
        unsafe_copyto!(X, 1, A, 1, lI)
1,792,285✔
983
    end
984
    return X
1,792,287✔
985
end
986

987
# This is redundant with the abstract fallbacks, but needed for bootstrap
988
function getindex(A::Array{S}, I::AbstractRange{Int}) where S
4,603✔
989
    return S[ A[i] for i in I ]
24,524✔
990
end
991

992
## Indexing: setindex! ##
993

994
"""
995
    setindex!(collection, value, key...)
996

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

1000
# Examples
1001
```jldoctest
1002
julia> a = Dict("a"=>1)
1003
Dict{String, Int64} with 1 entry:
1004
  "a" => 1
1005

1006
julia> setindex!(a, 2, "b")
1007
Dict{String, Int64} with 2 entries:
1008
  "b" => 2
1009
  "a" => 1
1010
```
1011
"""
1012
function setindex! end
1013

1014
@eval setindex!(A::Array{T}, x, i1::Int) where {T} =
18,057,449,518✔
1015
    arrayset($(Expr(:boundscheck)), A, x isa T ? x : convert(T,x)::T, i1)
1016
@eval setindex!(A::Array{T}, x, i1::Int, i2::Int, I::Int...) where {T} =
55,938,262✔
1017
    (@inline; arrayset($(Expr(:boundscheck)), A, x isa T ? x : convert(T,x)::T, i1, i2, I...))
60,492,604✔
1018

1019
__inbounds_setindex!(A::Array{T}, x, i1::Int) where {T} =
1,337,235,838✔
1020
    arrayset(false, A, convert(T,x)::T, i1)
1021
__inbounds_setindex!(A::Array{T}, x, i1::Int, i2::Int, I::Int...) where {T} =
×
1022
    (@inline; arrayset(false, A, convert(T,x)::T, i1, i2, I...))
×
1023

1024
# This is redundant with the abstract fallbacks but needed and helpful for bootstrap
1025
function setindex!(A::Array, X::AbstractArray, I::AbstractVector{Int})
22,309✔
1026
    @_propagate_inbounds_meta
22,309✔
1027
    @boundscheck setindex_shape_check(X, length(I))
5,431,014✔
1028
    require_one_based_indexing(X)
22,309✔
1029
    X′ = unalias(A, X)
27,706✔
1030
    I′ = unalias(A, I)
22,741✔
1031
    count = 1
22,309✔
1032
    for i in I′
10,139,167✔
1033
        @inbounds x = X′[count]
10,065,561✔
1034
        A[i] = x
10,067,644✔
1035
        count += 1
10,065,561✔
1036
    end
15,375,462✔
1037
    return A
5,431,014✔
1038
end
1039

1040
# Faster contiguous setindex! with copyto!
1041
function setindex!(A::Array{T}, X::Array{T}, I::AbstractUnitRange{Int}) where T
8,358✔
1042
    @inline
7,878✔
1043
    @boundscheck checkbounds(A, I)
8,710✔
1044
    lI = length(I)
8,710✔
1045
    @boundscheck setindex_shape_check(X, lI)
8,710✔
1046
    if lI > 0
8,710✔
1047
        unsafe_copyto!(A, first(I), X, 1, lI)
8,607✔
1048
    end
1049
    return A
8,710✔
1050
end
1051
function setindex!(A::Array{T}, X::Array{T}, c::Colon) where T
47✔
1052
    @inline
47✔
1053
    lI = length(A)
47✔
1054
    @boundscheck setindex_shape_check(X, lI)
47✔
1055
    if lI > 0
47✔
1056
        unsafe_copyto!(A, 1, X, 1, lI)
47✔
1057
    end
1058
    return A
47✔
1059
end
1060

1061
# efficiently grow an array
1062

1063
_growbeg!(a::Vector, delta::Integer) =
5,101,067✔
1064
    ccall(:jl_array_grow_beg, Cvoid, (Any, UInt), a, delta)
1065
_growend!(a::Vector, delta::Integer) =
1,650,996,952✔
1066
    ccall(:jl_array_grow_end, Cvoid, (Any, UInt), a, delta)
1067
_growat!(a::Vector, i::Integer, delta::Integer) =
73,936,184✔
1068
    ccall(:jl_array_grow_at, Cvoid, (Any, Int, UInt), a, i - 1, delta)
1069

1070
# efficiently delete part of an array
1071

1072
_deletebeg!(a::Vector, delta::Integer) =
24,016,685✔
1073
    ccall(:jl_array_del_beg, Cvoid, (Any, UInt), a, delta)
1074
_deleteend!(a::Vector, delta::Integer) =
639,328,003✔
1075
    ccall(:jl_array_del_end, Cvoid, (Any, UInt), a, delta)
1076
_deleteat!(a::Vector, i::Integer, delta::Integer) =
530,011✔
1077
    ccall(:jl_array_del_at, Cvoid, (Any, Int, UInt), a, i - 1, delta)
1078

1079
## Dequeue functionality ##
1080

1081
"""
1082
    push!(collection, items...) -> collection
1083

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

1087
# Examples
1088
```jldoctest
1089
julia> push!([1, 2, 3], 4, 5, 6)
1090
6-element Vector{Int64}:
1091
 1
1092
 2
1093
 3
1094
 4
1095
 5
1096
 6
1097
```
1098

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

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

1105
See also [`pushfirst!`](@ref).
1106
"""
1107
function push! end
1108

1109
function push!(a::Vector{T}, item) where T
333,728✔
1110
    # convert first so we don't grow the array if the assignment won't work
1111
    itemT = item isa T ? item : convert(T, item)::T
26,078,753✔
1112
    _growend!(a, 1)
1,085,059,445✔
1113
    @_safeindex a[length(a)] = itemT
1,085,059,445✔
1114
    return a
11,157,333✔
1115
end
1116

1117
# specialize and optimize the single argument case
1118
function push!(a::Vector{Any}, @nospecialize x)
3,139,119✔
1119
    _growend!(a, 1)
98,770,294✔
1120
    @_safeindex a[length(a)] = x
98,770,294✔
1121
    return a
2,893,686✔
1122
end
1123
function push!(a::Vector{Any}, @nospecialize x...)
126,200✔
1124
    @_terminates_locally_meta
2✔
1125
    na = length(a)
126,200✔
1126
    nx = length(x)
2✔
1127
    _growend!(a, nx)
126,200✔
1128
    @_safeindex for i = 1:nx
126,200✔
1129
        a[na+i] = x[i]
261,600✔
1130
    end
378,604✔
1131
    return a
126,200✔
1132
end
1133

1134
"""
1135
    append!(collection, collections...) -> collection.
1136

1137
For an ordered container `collection`, add the elements of each `collections`
1138
to the end of it.
1139

1140
!!! compat "Julia 1.6"
1141
    Specifying multiple collections to be appended requires at least Julia 1.6.
1142

1143
# Examples
1144
```jldoctest
1145
julia> append!([1], [2, 3])
1146
3-element Vector{Int64}:
1147
 1
1148
 2
1149
 3
1150

1151
julia> append!([1, 2, 3], [4, 5], [6])
1152
6-element Vector{Int64}:
1153
 1
1154
 2
1155
 3
1156
 4
1157
 5
1158
 6
1159
```
1160

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

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

1167
See also [`vcat`](@ref) for vectors, [`union!`](@ref) for sets,
1168
and [`prepend!`](@ref) and [`pushfirst!`](@ref) for the opposite order.
1169
"""
1170
function append! end
1171

1172
function append!(a::Vector, items::AbstractVector)
70,748✔
1173
    itemindices = eachindex(items)
59,761,962✔
1174
    n = length(itemindices)
42,570✔
1175
    _growend!(a, n)
59,761,962✔
1176
    copyto!(a, length(a)-n+1, items, first(itemindices), n)
59,763,359✔
1177
    return a
59,761,962✔
1178
end
1179

1180
append!(a::AbstractVector, iter) = _append!(a, IteratorSize(iter), iter)
50,726,606✔
1181
push!(a::AbstractVector, iter...) = append!(a, iter)
3,923✔
1182

1183
append!(a::AbstractVector, iter...) = foldl(append!, iter, init=a)
77✔
1184

1185
function _append!(a::AbstractVector, ::Union{HasLength,HasShape}, iter)
17,887,839✔
1186
    @_terminates_locally_meta
1,828✔
1187
    n = length(a)
17,887,839✔
1188
    i = lastindex(a)
17,887,839✔
1189
    resize!(a, n+Int(length(iter))::Int)
28,911,355✔
1190
    for (i, item) in zip(i+1:lastindex(a), iter)
24,752,162✔
1191
        if isa(a, Vector) # give better effects for builtin vectors
7,900✔
1192
            @_safeindex a[i] = item
27,444,710✔
1193
        else
1194
            a[i] = item
×
1195
        end
1196
    end
48,021,853✔
1197
    a
17,887,839✔
1198
end
1199
function _append!(a::AbstractVector, ::IteratorSize, iter)
32,838,766✔
1200
    for item in iter
32,838,768✔
1201
        push!(a, item)
32,330,645✔
1202
    end
32,330,650✔
1203
    a
32,838,766✔
1204
end
1205

1206
"""
1207
    prepend!(a::Vector, collections...) -> collection
1208

1209
Insert the elements of each `collections` to the beginning of `a`.
1210

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

1214
!!! compat "Julia 1.6"
1215
    Specifying multiple collections to be prepended requires at least Julia 1.6.
1216

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

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

1237
function prepend!(a::Vector, items::AbstractVector)
4,237✔
1238
    itemindices = eachindex(items)
4,237✔
1239
    n = length(itemindices)
4,197✔
1240
    _growbeg!(a, n)
4,237✔
1241
    if a === items
4,237✔
1242
        copyto!(a, 1, items, n+1, n)
1✔
1243
    else
1244
        copyto!(a, 1, items, first(itemindices), n)
4,246✔
1245
    end
1246
    return a
4,237✔
1247
end
1248

1249
prepend!(a::Vector, iter) = _prepend!(a, IteratorSize(iter), iter)
13✔
1250
pushfirst!(a::Vector, iter...) = prepend!(a, iter)
7✔
1251

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

1254
function _prepend!(a::Vector, ::Union{HasLength,HasShape}, iter)
7✔
1255
    @_terminates_locally_meta
7✔
1256
    require_one_based_indexing(a)
7✔
1257
    n = length(iter)
7✔
1258
    _growbeg!(a, n)
7✔
1259
    i = 0
7✔
1260
    for item in iter
7✔
1261
        @_safeindex a[i += 1] = item
13✔
1262
    end
18✔
1263
    a
7✔
1264
end
1265
function _prepend!(a::Vector, ::IteratorSize, iter)
2✔
1266
    n = 0
2✔
1267
    for item in iter
3✔
1268
        n += 1
5✔
1269
        pushfirst!(a, item)
5✔
1270
    end
9✔
1271
    reverse!(a, 1, n)
2✔
1272
    a
2✔
1273
end
1274

1275
"""
1276
    resize!(a::Vector, n::Integer) -> Vector
1277

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

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

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

1292
julia> length(a)
1293
8
1294

1295
julia> a[1:6]
1296
6-element Vector{Int64}:
1297
 6
1298
 5
1299
 4
1300
 3
1301
 2
1302
 1
1303
```
1304
"""
1305
function resize!(a::Vector, nl::Integer)
5,904,166✔
1306
    l = length(a)
780,061,697✔
1307
    if nl > l
780,061,697✔
1308
        _growend!(a, nl-l)
282,474,346✔
1309
    elseif nl != l
497,587,353✔
1310
        if nl < 0
69,589,530✔
1311
            _throw_argerror("new length must be ≥ 0")
2✔
1312
        end
1313
        _deleteend!(a, l-nl)
256,173,366✔
1314
    end
1315
    return a
780,061,695✔
1316
end
1317

1318
"""
1319
    sizehint!(s, n) -> s
1320

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

1326
See also [`resize!`](@ref).
1327

1328
# Notes on the performance model
1329

1330
For types that support `sizehint!`,
1331

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

1336
2. `sizehint!` may control this preallocation. Again, it typically does this for types in
1337
   `Base`.
1338

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

1343
function sizehint!(a::Vector, sz::Integer)
457,820✔
1344
    ccall(:jl_array_sizehint, Cvoid, (Any, UInt), a, sz)
696,201✔
1345
    a
678,534✔
1346
end
1347

1348
"""
1349
    pop!(collection) -> item
1350

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

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

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

1365
julia> pop!(A)
1366
3
1367

1368
julia> A
1369
2-element Vector{Int64}:
1370
 1
1371
 2
1372

1373
julia> S = Set([1, 2])
1374
Set{Int64} with 2 elements:
1375
  2
1376
  1
1377

1378
julia> pop!(S)
1379
2
1380

1381
julia> S
1382
Set{Int64} with 1 element:
1383
  1
1384

1385
julia> pop!(Dict(1=>2))
1386
1 => 2
1387
```
1388
"""
1389
function pop!(a::Vector)
62,138✔
1390
    if isempty(a)
317,539,717✔
1391
        _throw_argerror("array must be non-empty")
1✔
1392
    end
1393
    item = a[end]
317,539,716✔
1394
    _deleteend!(a, 1)
317,539,716✔
1395
    return item
317,539,716✔
1396
end
1397

1398
"""
1399
    popat!(a::Vector, i::Integer, [default])
1400

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

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

1408
!!! compat "Julia 1.5"
1409
    This function is available as of Julia 1.5.
1410

1411
# Examples
1412
```jldoctest
1413
julia> a = [4, 3, 2, 1]; popat!(a, 2)
1414
3
1415

1416
julia> a
1417
3-element Vector{Int64}:
1418
 4
1419
 2
1420
 1
1421

1422
julia> popat!(a, 4, missing)
1423
missing
1424

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

1436
function popat!(a::Vector, i::Integer, default)
2✔
1437
    if 1 <= i <= length(a)
2✔
1438
        x = @inbounds a[i]
1✔
1439
        _deleteat!(a, i, 1)
1✔
1440
        x
1✔
1441
    else
1442
        default
1✔
1443
    end
1444
end
1445

1446
"""
1447
    pushfirst!(collection, items...) -> collection
1448

1449
Insert one or more `items` at the beginning of `collection`.
1450

1451
This function is called `unshift` in many other programming languages.
1452

1453
# Examples
1454
```jldoctest
1455
julia> pushfirst!([1, 2, 3, 4], 5, 6)
1456
6-element Vector{Int64}:
1457
 5
1458
 6
1459
 1
1460
 2
1461
 3
1462
 4
1463
```
1464
"""
1465
function pushfirst!(a::Vector{T}, item) where T
57,487✔
1466
    item = item isa T ? item : convert(T, item)::T
57,472✔
1467
    _growbeg!(a, 1)
4,088,300✔
1468
    @_safeindex a[1] = item
4,088,300✔
1469
    return a
57,487✔
1470
end
1471

1472
# specialize and optimize the single argument case
1473
function pushfirst!(a::Vector{Any}, @nospecialize x)
112✔
1474
    _growbeg!(a, 1)
791,483✔
1475
    @_safeindex a[1] = x
791,483✔
1476
    return a
112✔
1477
end
1478
function pushfirst!(a::Vector{Any}, @nospecialize x...)
724✔
1479
    @_terminates_locally_meta
2✔
1480
    na = length(a)
2✔
1481
    nx = length(x)
2✔
1482
    _growbeg!(a, nx)
724✔
1483
    @_safeindex for i = 1:nx
724✔
1484
        a[i] = x[i]
1,450✔
1485
    end
2,176✔
1486
    return a
724✔
1487
end
1488

1489
"""
1490
    popfirst!(collection) -> item
1491

1492
Remove the first `item` from `collection`.
1493

1494
This function is called `shift` in many other programming languages.
1495

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

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

1509
julia> popfirst!(A)
1510
1
1511

1512
julia> A
1513
5-element Vector{Int64}:
1514
 2
1515
 3
1516
 4
1517
 5
1518
 6
1519
```
1520
"""
1521
function popfirst!(a::Vector)
1,036,936✔
1522
    if isempty(a)
23,983,597✔
1523
        _throw_argerror("array must be non-empty")
1✔
1524
    end
1525
    item = a[1]
23,983,596✔
1526
    _deletebeg!(a, 1)
23,983,595✔
1527
    return item
23,983,596✔
1528
end
1529

1530
"""
1531
    insert!(a::Vector, index::Integer, item)
1532

1533
Insert an `item` into `a` at the given `index`. `index` is the index of `item` in
1534
the resulting `a`.
1535

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

1538
# Examples
1539
```jldoctest
1540
julia> insert!(Any[1:6;], 3, "here")
1541
7-element Vector{Any}:
1542
 1
1543
 2
1544
  "here"
1545
 3
1546
 4
1547
 5
1548
 6
1549
```
1550
"""
1551
function insert!(a::Array{T,1}, i::Integer, item) where T
207,094✔
1552
    # Throw convert error before changing the shape of the array
1553
    _item = item isa T ? item : convert(T, item)::T
207,087✔
1554
    _growat!(a, i, 1)
73,911,772✔
1555
    # _growat! already did bound check
1556
    @inbounds a[i] = _item
73,911,766✔
1557
    return a
207,088✔
1558
end
1559

1560
"""
1561
    deleteat!(a::Vector, i::Integer)
1562

1563
Remove the item at the given `i` and return the modified `a`. Subsequent items
1564
are shifted to fill the resulting gap.
1565

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

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

1585
function deleteat!(a::Vector, r::AbstractUnitRange{<:Integer})
75,580✔
1586
    if eltype(r) === Bool
75,580✔
1587
        return invoke(deleteat!, Tuple{Vector, AbstractVector{Bool}}, a, r)
6✔
1588
    else
1589
        n = length(a)
75,574✔
1590
        f = first(r)
75,669✔
1591
        f isa Bool && depwarn("passing Bool as an index is deprecated", :deleteat!)
75,574✔
1592
        isempty(r) || _deleteat!(a, f, length(r))
166,720✔
1593
        return a
85,179✔
1594
    end
1595
end
1596

1597
"""
1598
    deleteat!(a::Vector, inds)
1599

1600
Remove the items at the indices given by `inds`, and return the modified `a`.
1601
Subsequent items are shifted to fill the resulting gap.
1602

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

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

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

1620
julia> deleteat!([6, 5, 4, 3, 2, 1], (2, 2))
1621
ERROR: ArgumentError: indices must be unique and sorted
1622
Stacktrace:
1623
[...]
1624
```
1625
"""
1626
deleteat!(a::Vector, inds) = _deleteat!(a, inds)
19✔
1627
deleteat!(a::Vector, inds::AbstractVector) = _deleteat!(a, to_indices(a, (inds,))[1])
109,532✔
1628

1629
struct Nowhere; end
1630
push!(::Nowhere, _) = nothing
1,494,112✔
1631
_growend!(::Nowhere, _) = nothing
×
1632

1633
@inline function _push_deleted!(dltd, a::Vector, ind)
1,494,114✔
1634
    if @inbounds isassigned(a, ind)
1,574,029✔
1635
        push!(dltd, @inbounds a[ind])
1,574,042✔
1636
    else
1637
        _growend!(dltd, 1)
1✔
1638
    end
1639
end
1640

1641
@inline function _copy_item!(a::Vector, p, q)
4,377,601✔
1642
    if @inbounds isassigned(a, q)
4,425,198✔
1643
        @inbounds a[p] = a[q]
4,425,214✔
1644
    else
1645
        _unsetindex!(a, p)
1✔
1646
    end
1647
end
1648

1649
function _deleteat!(a::Vector, inds, dltd=Nowhere())
145,253✔
1650
    n = length(a)
219,103✔
1651
    y = iterate(inds)
109,779✔
1652
    y === nothing && return a
109,552✔
1653
    (p, s) = y
35,481✔
1654
    checkbounds(a, p)
109,337✔
1655
    _push_deleted!(dltd, a, p)
109,330✔
1656
    q = p+1
109,325✔
1657
    while true
1,574,029✔
1658
        y = iterate(inds, s)
1,683,348✔
1659
        y === nothing && break
1,574,029✔
1660
        (i,s) = y
1,458,639✔
1661
        if !(q <= i <= n)
1,464,706✔
1662
            if i < q
2✔
1663
                _throw_argerror("indices must be unique and sorted")
1✔
1664
            else
1665
                throw(BoundsError())
1✔
1666
            end
1667
        end
1668
        while q < i
2,886,643✔
1669
            _copy_item!(a, p, q)
1,421,951✔
1670
            p += 1; q += 1
2,843,878✔
1671
        end
1,421,939✔
1672
        _push_deleted!(dltd, a, i)
1,464,714✔
1673
        q = i+1
1,464,704✔
1674
    end
1,464,704✔
1675
    while q <= n
3,070,388✔
1676
        _copy_item!(a, p, q)
2,961,071✔
1677
        p += 1; q += 1
5,922,130✔
1678
    end
2,961,065✔
1679
    _deleteend!(a, n-p+1)
109,323✔
1680
    return a
109,323✔
1681
end
1682

1683
# Simpler and more efficient version for logical indexing
1684
function deleteat!(a::Vector, inds::AbstractVector{Bool})
4,029✔
1685
    n = length(a)
4,029✔
1686
    length(inds) == n || throw(BoundsError(a, inds))
4,034✔
1687
    p = 1
4,024✔
1688
    for (q, i) in enumerate(inds)
8,047✔
1689
        _copy_item!(a, p, q)
42,194✔
1690
        p += !i
42,194✔
1691
    end
80,365✔
1692
    _deleteend!(a, n-p+1)
4,024✔
1693
    return a
4,024✔
1694
end
1695

1696
const _default_splice = []
1697

1698
"""
1699
    splice!(a::Vector, index::Integer, [replacement]) -> item
1700

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

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

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

1713
julia> A
1714
5-element Vector{Int64}:
1715
 6
1716
 5
1717
 4
1718
 3
1719
 1
1720

1721
julia> splice!(A, 5, -1)
1722
1
1723

1724
julia> A
1725
5-element Vector{Int64}:
1726
  6
1727
  5
1728
  4
1729
  3
1730
 -1
1731

1732
julia> splice!(A, 1, [-1, -2, -3])
1733
6
1734

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

1746
To insert `replacement` before an index `n` without removing any items, use
1747
`splice!(collection, n:n-1, replacement)`.
1748
"""
1749
function splice!(a::Vector, i::Integer, ins=_default_splice)
3,704✔
1750
    v = a[i]
3,714✔
1751
    m = length(ins)
3,427✔
1752
    if m == 0
3,427✔
1753
        _deleteat!(a, i, 1)
552✔
1754
    elseif m == 1
2,875✔
1755
        a[i] = ins[1]
267✔
1756
    else
1757
        _growat!(a, i, m-1)
2,608✔
1758
        k = 1
2,608✔
1759
        for x in ins
2,608✔
1760
            a[i+k-1] = x
333,738✔
1761
            k += 1
333,738✔
1762
        end
333,738✔
1763
    end
1764
    return v
3,427✔
1765
end
1766

1767
"""
1768
    splice!(a::Vector, indices, [replacement]) -> items
1769

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

1776
To insert `replacement` before an index `n` without removing any items, use
1777
`splice!(collection, n:n-1, replacement)`.
1778

1779
!!! compat "Julia 1.5"
1780
    Prior to Julia 1.5, `indices` must always be a `UnitRange`.
1781

1782
!!! compat "Julia 1.8"
1783
    Prior to Julia 1.8, `indices` must be a `UnitRange` if splicing in replacement values.
1784

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

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

1810
    n = length(a)
34,643✔
1811
    f = first(r)
34,643✔
1812
    l = last(r)
34,643✔
1813
    d = length(r)
34,643✔
1814

1815
    if m < d
34,643✔
1816
        delta = d - m
12,734✔
1817
        _deleteat!(a, (f - 1 < n - l) ? f : (l - delta + 1), delta)
19,219✔
1818
    elseif m > d
21,909✔
1819
        _growat!(a, (f - 1 < n - l) ? f : (l + 1), m - d)
21,790✔
1820
    end
1821

1822
    k = 1
34,560✔
1823
    for x in ins
46,149✔
1824
        a[f+k-1] = x
5,367,750✔
1825
        k += 1
4,025,797✔
1826
    end
5,390,658✔
1827
    return v
34,643✔
1828
end
1829

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

1832
function empty!(a::Vector)
71,393✔
1833
    _deleteend!(a, length(a))
65,383,396✔
1834
    return a
65,383,396✔
1835
end
1836

1837
_memcmp(a, b, len) = ccall(:memcmp, Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), a, b, len % Csize_t) % Int
53,265✔
1838

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

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

1850
# this is ~20% faster than the generic implementation above for very small arrays
1851
function ==(a::Arr, b::Arr) where Arr <: BitIntegerArray{1}
8,712✔
1852
    len = length(a)
46,691✔
1853
    len == length(b) && 0 == _memcmp(a, b, sizeof(eltype(Arr)) * len)
46,693✔
1854
end
1855

1856
"""
1857
    reverse(v [, start=firstindex(v) [, stop=lastindex(v) ]] )
1858

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

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

1872
julia> reverse(A)
1873
5-element Vector{Int64}:
1874
 5
1875
 4
1876
 3
1877
 2
1878
 1
1879

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

1888
julia> reverse(A, 3, 5)
1889
5-element Vector{Int64}:
1890
 1
1891
 2
1892
 5
1893
 4
1894
 3
1895
```
1896
"""
1897
function reverse(A::AbstractVector, start::Integer, stop::Integer=lastindex(A))
5,614✔
1898
    s, n = Int(start), Int(stop)
584✔
1899
    B = similar(A)
5,615✔
1900
    for i = firstindex(A):s-1
5,618✔
1901
        B[i] = A[i]
14✔
1902
    end
24✔
1903
    for i = s:n
11,220✔
1904
        B[i] = A[n+s-i]
245,733✔
1905
    end
485,856✔
1906
    for i = n+1:lastindex(A)
5,618✔
1907
        B[i] = A[i]
20✔
1908
    end
36✔
1909
    return B
5,614✔
1910
end
1911

1912
# 1d special cases of reverse(A; dims) and reverse!(A; dims):
1913
for (f,_f) in ((:reverse,:_reverse), (:reverse!,:_reverse!))
1914
    @eval begin
1915
        $f(A::AbstractVector; dims=:) = $_f(A, dims)
182,192,594✔
1916
        $_f(A::AbstractVector, ::Colon) = $f(A, firstindex(A), lastindex(A))
7,533✔
1917
        $_f(A::AbstractVector, dim::Tuple{Integer}) = $_f(A, first(dim))
×
1918
        function $_f(A::AbstractVector, dim::Integer)
6✔
1919
            dim == 1 || _throw_argerror(LazyString("invalid dimension ", dim, " ≠ 1"))
10✔
1920
            return $_f(A, :)
3✔
1921
        end
1922
    end
1923
end
1924

1925
function reverseind(a::AbstractVector, i::Integer)
3✔
1926
    li = LinearIndices(a)
3✔
1927
    first(li) + last(li) - i
3✔
1928
end
1929

1930
# This implementation of `midpoint` is performance-optimized but safe
1931
# only if `lo <= hi`.
1932
midpoint(lo::T, hi::T) where T<:Integer = lo + ((hi - lo) >>> 0x01)
4,228,347✔
1933
midpoint(lo::Integer, hi::Integer) = midpoint(promote(lo, hi)...)
×
1934

1935
"""
1936
    reverse!(v [, start=firstindex(v) [, stop=lastindex(v) ]]) -> v
1937

1938
In-place version of [`reverse`](@ref).
1939

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

1950
julia> reverse!(A);
1951

1952
julia> A
1953
5-element Vector{Int64}:
1954
 5
1955
 4
1956
 3
1957
 2
1958
 1
1959
```
1960
"""
1961
function reverse!(v::AbstractVector, start::Integer, stop::Integer=lastindex(v))
75,565✔
1962
    s, n = Int(start), Int(stop)
8,399✔
1963
    if n > s # non-empty and non-trivial
75,562✔
1964
        liv = LinearIndices(v)
72,039✔
1965
        if !(first(liv) ≤ s ≤ last(liv))
72,039✔
1966
            throw(BoundsError(v, s))
3✔
1967
        elseif !(first(liv) ≤ n ≤ last(liv))
72,036✔
1968
            throw(BoundsError(v, n))
1✔
1969
        end
1970
        r = n
7,715✔
1971
        @inbounds for i in s:midpoint(s, n-1)
144,070✔
1972
            v[i], v[r] = v[r], v[i]
1,635,813✔
1973
            r -= 1
1,631,447✔
1974
        end
3,190,859✔
1975
    end
1976
    return v
75,558✔
1977
end
1978

1979
# concatenations of (in)homogeneous combinations of vectors, horizontal and vertical
1980

1981
vcat() = Vector{Any}()
10,655✔
1982
hcat() = Vector{Any}()
1✔
1983

1984
function hcat(V::Vector{T}...) where T
562✔
1985
    height = length(V[1])
562✔
1986
    for j = 2:length(V)
563✔
1987
        if length(V[j]) != height
628✔
1988
            throw(DimensionMismatch("vectors must have same lengths"))
1✔
1989
        end
1990
    end
725✔
1991
    return [ V[j][i]::T for i=1:length(V[1]), j=1:length(V) ]
561✔
1992
end
1993
hcat(A::Vector...) = cat(A...; dims=Val(2)) # more special than SparseArrays's hcat
4✔
1994

1995
function vcat(arrays::Vector{T}...) where T
36,450✔
1996
    n = 0
7,010✔
1997
    for a in arrays
36,450✔
1998
        n += length(a)
2,073,052✔
1999
    end
2,109,482✔
2000
    arr = Vector{T}(undef, n)
36,450✔
2001
    nd = 1
7,010✔
2002
    for a in arrays
36,450✔
2003
        na = length(a)
2,073,052✔
2004
        @assert nd + na <= 1 + length(arr) # Concurrent modification of arrays?
2,073,052✔
2005
        unsafe_copyto!(arr, nd, a, 1, na)
2,073,052✔
2006
        nd += na
2,073,052✔
2007
    end
2,109,482✔
2008
    return arr
36,450✔
2009
end
2010
vcat(A::Vector...) = cat(A...; dims=Val(1)) # more special than SparseArrays's vcat
71✔
2011

2012
# disambiguation with LinAlg/special.jl
2013
# Union{Number,Vector,Matrix} is for LinearAlgebra._DenseConcatGroup
2014
# VecOrMat{T} is for LinearAlgebra._TypedDenseConcatGroup
2015
hcat(A::Union{Number,Vector,Matrix}...) = cat(A...; dims=Val(2))
101✔
2016
hcat(A::VecOrMat{T}...) where {T} = typed_hcat(T, A...)
176✔
2017
vcat(A::Union{Number,Vector,Matrix}...) = cat(A...; dims=Val(1))
114✔
2018
vcat(A::VecOrMat{T}...) where {T} = typed_vcat(T, A...)
542✔
2019
hvcat(rows::Tuple{Vararg{Int}}, xs::Union{Number,Vector,Matrix}...) =
91✔
2020
    typed_hvcat(promote_eltypeof(xs...), rows, xs...)
2021
hvcat(rows::Tuple{Vararg{Int}}, xs::VecOrMat{T}...) where {T} =
65✔
2022
    typed_hvcat(T, rows, xs...)
2023

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

2026
## find ##
2027

2028
"""
2029
    findnext(A, i)
2030

2031
Find the next index after or including `i` of a `true` element of `A`,
2032
or `nothing` if not found.
2033

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

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

2046
julia> findnext(A, 1)
2047
3
2048

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

2051
julia> A = [false false; true false]
2052
2×2 Matrix{Bool}:
2053
 0  0
2054
 1  0
2055

2056
julia> findnext(A, CartesianIndex(1, 1))
2057
CartesianIndex(2, 1)
2058
```
2059
"""
2060
findnext(A, start) = findnext(identity, A, start)
77,842✔
2061

2062
"""
2063
    findfirst(A)
2064

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

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

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

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

2083
julia> findfirst(A)
2084
3
2085

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

2088
julia> A = [false false; true false]
2089
2×2 Matrix{Bool}:
2090
 0  0
2091
 1  0
2092

2093
julia> findfirst(A)
2094
CartesianIndex(2, 1)
2095
```
2096
"""
2097
findfirst(A) = findfirst(identity, A)
2✔
2098

2099
# Needed for bootstrap, and allows defining only an optimized findnext method
2100
findfirst(A::AbstractArray) = findnext(A, first(keys(A)))
11,849✔
2101

2102
"""
2103
    findnext(predicate::Function, A, i)
2104

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

2108
Indices are of the same type as those returned by [`keys(A)`](@ref)
2109
and [`pairs(A)`](@ref).
2110

2111
# Examples
2112
```jldoctest
2113
julia> A = [1, 4, 2, 2];
2114

2115
julia> findnext(isodd, A, 1)
2116
1
2117

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

2120
julia> A = [1 4; 2 2];
2121

2122
julia> findnext(isodd, A, CartesianIndex(1, 1))
2123
CartesianIndex(1, 1)
2124
```
2125
"""
2126
function findnext(testf::Function, A, start)
48,531✔
2127
    i = oftype(first(keys(A)), start)
46,411✔
2128
    l = last(keys(A))
45,486,743✔
2129
    i > l && return nothing
45,486,743✔
2130
    while true
179,109,701✔
2131
        testf(A[i]) && return i
179,113,560✔
2132
        i == l && break
178,543,168✔
2133
        # nextind(A, l) can throw/overflow
2134
        i = nextind(A, i)
174,333,386✔
2135
    end
174,333,367✔
2136
    return nothing
4,209,777✔
2137
end
2138

2139
"""
2140
    findfirst(predicate::Function, A)
2141

2142
Return the index or key of the first element of `A` for which `predicate` returns `true`.
2143
Return `nothing` if there is no such element.
2144

2145
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2146
and [`pairs(A)`](@ref).
2147

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

2157
julia> findfirst(iseven, A)
2158
2
2159

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

2162
julia> findfirst(isequal(4), A)
2163
2
2164

2165
julia> A = [1 4; 2 2]
2166
2×2 Matrix{Int64}:
2167
 1  4
2168
 2  2
2169

2170
julia> findfirst(iseven, A)
2171
CartesianIndex(2, 1)
2172
```
2173
"""
2174
function findfirst(testf::Function, A)
14✔
2175
    for (i, a) in pairs(A)
22✔
2176
        testf(a) && return i
14✔
2177
    end
11✔
2178
    return nothing
7✔
2179
end
2180

2181
# Needed for bootstrap, and allows defining only an optimized findnext method
2182
findfirst(testf::Function, A::Union{AbstractArray, AbstractString}) =
224,785,256✔
2183
    findnext(testf, A, first(keys(A)))
2184

2185
findfirst(p::Union{Fix2{typeof(isequal),Int},Fix2{typeof(==),Int}}, r::OneTo{Int}) =
×
2186
    1 <= p.x <= r.stop ? p.x : nothing
2187

2188
findfirst(p::Union{Fix2{typeof(isequal),T},Fix2{typeof(==),T}}, r::AbstractUnitRange) where {T<:Integer} =
×
2189
    first(r) <= p.x <= last(r) ? firstindex(r) + Int(p.x - first(r)) : nothing
2190

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

2199
"""
2200
    findprev(A, i)
2201

2202
Find the previous index before or including `i` of a `true` element of `A`,
2203
or `nothing` if not found.
2204

2205
Indices are of the same type as those returned by [`keys(A)`](@ref)
2206
and [`pairs(A)`](@ref).
2207

2208
See also: [`findnext`](@ref), [`findfirst`](@ref), [`findall`](@ref).
2209

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

2219
julia> findprev(A, 3)
2220
3
2221

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

2224
julia> A = [false false; true true]
2225
2×2 Matrix{Bool}:
2226
 0  0
2227
 1  1
2228

2229
julia> findprev(A, CartesianIndex(2, 1))
2230
CartesianIndex(2, 1)
2231
```
2232
"""
2233
findprev(A, start) = findprev(identity, A, start)
12,219✔
2234

2235
"""
2236
    findlast(A)
2237

2238
Return the index or key of the last `true` value in `A`.
2239
Return `nothing` if there is no `true` value in `A`.
2240

2241
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2242
and [`pairs(A)`](@ref).
2243

2244
See also: [`findfirst`](@ref), [`findprev`](@ref), [`findall`](@ref).
2245

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

2255
julia> findlast(A)
2256
3
2257

2258
julia> A = falses(2,2);
2259

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

2262
julia> A = [true false; true false]
2263
2×2 Matrix{Bool}:
2264
 1  0
2265
 1  0
2266

2267
julia> findlast(A)
2268
CartesianIndex(2, 1)
2269
```
2270
"""
2271
findlast(A) = findlast(identity, A)
23✔
2272

2273
# Needed for bootstrap, and allows defining only an optimized findprev method
2274
findlast(A::AbstractArray) = findprev(A, last(keys(A)))
4,019✔
2275

2276
"""
2277
    findprev(predicate::Function, A, i)
2278

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

2282
Indices are of the same type as those returned by [`keys(A)`](@ref)
2283
and [`pairs(A)`](@ref).
2284

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

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

2296
julia> findprev(isodd, A, 3)
2297
3
2298

2299
julia> A = [4 6; 1 2]
2300
2×2 Matrix{Int64}:
2301
 4  6
2302
 1  2
2303

2304
julia> findprev(isodd, A, CartesianIndex(1, 2))
2305
CartesianIndex(2, 1)
2306
```
2307
"""
2308
function findprev(testf::Function, A, start)
36,713✔
2309
    f = first(keys(A))
36,713✔
2310
    i = oftype(f, start)
36,724✔
2311
    i < f && return nothing
37,965✔
2312
    while true
175,613✔
2313
        testf(A[i]) && return i
175,656✔
2314
        i == f && break
137,737✔
2315
        # prevind(A, f) can throw/underflow
2316
        i = prevind(A, i)
137,677✔
2317
    end
137,649✔
2318
    return nothing
57✔
2319
end
2320

2321
"""
2322
    findlast(predicate::Function, A)
2323

2324
Return the index or key of the last element of `A` for which `predicate` returns `true`.
2325
Return `nothing` if there is no such element.
2326

2327
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2328
and [`pairs(A)`](@ref).
2329

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

2339
julia> findlast(isodd, A)
2340
3
2341

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

2344
julia> A = [1 2; 3 4]
2345
2×2 Matrix{Int64}:
2346
 1  2
2347
 3  4
2348

2349
julia> findlast(isodd, A)
2350
CartesianIndex(2, 1)
2351
```
2352
"""
2353
function findlast(testf::Function, A)
4✔
2354
    for (i, a) in Iterators.reverse(pairs(A))
4✔
2355
        testf(a) && return i
6✔
2356
    end
6✔
2357
    return nothing
2✔
2358
end
2359

2360
# Needed for bootstrap, and allows defining only an optimized findprev method
2361
findlast(testf::Function, A::Union{AbstractArray, AbstractString}) =
3,002✔
2362
    findprev(testf, A, last(keys(A)))
2363

2364
"""
2365
    findall(f::Function, A)
2366

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

2370
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2371
and [`pairs(A)`](@ref).
2372

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

2381
julia> findall(isodd, x)
2382
2-element Vector{Int64}:
2383
 1
2384
 2
2385

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

2395
julia> findall(!iszero, A)
2396
4-element Vector{CartesianIndex{2}}:
2397
 CartesianIndex(1, 1)
2398
 CartesianIndex(2, 1)
2399
 CartesianIndex(1, 2)
2400
 CartesianIndex(2, 2)
2401

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

2408
julia> findall(x -> x >= 0, d)
2409
2-element Vector{Symbol}:
2410
 :A
2411
 :C
2412

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

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

2425
"""
2426
    findall(A)
2427

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

2432
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2433
and [`pairs(A)`](@ref).
2434

2435
See also: [`findfirst`](@ref), [`searchsorted`](@ref).
2436

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

2446
julia> findall(A)
2447
2-element Vector{Int64}:
2448
 1
2449
 4
2450

2451
julia> A = [true false; false true]
2452
2×2 Matrix{Bool}:
2453
 1  0
2454
 0  1
2455

2456
julia> findall(A)
2457
2-element Vector{CartesianIndex{2}}:
2458
 CartesianIndex(1, 1)
2459
 CartesianIndex(2, 2)
2460

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

2469
# Allocating result upfront is faster (possible only when collection can be iterated twice)
2470
function _findall(f::Function, A::AbstractArray{Bool})
2,833✔
2471
    n = count(f, A)
2,838✔
2472
    I = Vector{eltype(keys(A))}(undef, n)
2,833✔
2473
    isempty(I) && return I
2,833✔
2474
    _findall(f, I, A)
2,462✔
2475
end
2476

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

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

2502
findall(f::Function, A::AbstractArray{Bool}) = _findall(f, A)
5✔
2503
findall(f::Fix2{typeof(in)}, A::AbstractArray{Bool}) = _findall(f, A)
×
2504
findall(A::AbstractArray{Bool}) = _findall(identity, A)
4,735✔
2505

2506
findall(x::Bool) = x ? [1] : Vector{Int}()
2✔
2507
findall(testf::Function, x::Number) = testf(x) ? [1] : Vector{Int}()
2✔
2508
findall(p::Fix2{typeof(in)}, x::Number) = x in p.x ? [1] : Vector{Int}()
2✔
2509

2510
# similar to Matlab's ismember
2511
"""
2512
    indexin(a, b)
2513

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

2518
See also: [`sortperm`](@ref), [`findfirst`](@ref).
2519

2520
# Examples
2521
```jldoctest
2522
julia> a = ['a', 'b', 'c', 'b', 'd', 'a'];
2523

2524
julia> b = ['a', 'b', 'c'];
2525

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

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

2553
function _findin(a::Union{AbstractArray, Tuple}, b)
373✔
2554
    ind  = Vector{eltype(keys(a))}()
559✔
2555
    bset = Set(b)
373✔
2556
    @inbounds for (i,ai) in pairs(a)
602✔
2557
        ai in bset && push!(ind, i)
90,394✔
2558
    end
180,559✔
2559
    ind
373✔
2560
end
2561

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

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

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

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

2642
## Filter ##
2643

2644
"""
2645
    filter(f, a)
2646

2647
Return a copy of collection `a`, removing elements for which `f` is `false`.
2648
The function `f` is passed one argument.
2649

2650
!!! compat "Julia 1.4"
2651
    Support for `a` as a tuple requires at least Julia 1.4.
2652

2653
See also: [`filter!`](@ref), [`Iterators.filter`](@ref).
2654

2655
# Examples
2656
```jldoctest
2657
julia> a = 1:10
2658
1:10
2659

2660
julia> filter(isodd, a)
2661
5-element Vector{Int64}:
2662
 1
2663
 3
2664
 5
2665
 7
2666
 9
2667
```
2668
"""
2669
function filter(f, a::Array{T, N}) where {T, N}
624,877✔
2670
    j = 1
443,121✔
2671
    b = Vector{T}(undef, length(a))
624,877✔
2672
    for ai in a
624,897✔
2673
        @inbounds b[j] = ai
4,003,861✔
2674
        j = ifelse(f(ai)::Bool, j+1, j)
4,008,771✔
2675
    end
4,628,632✔
2676
    resize!(b, j-1)
1,249,754✔
2677
    sizehint!(b, length(b))
624,877✔
2678
    b
624,877✔
2679
end
2680

2681
function filter(f, a::AbstractArray)
372✔
2682
    (IndexStyle(a) != IndexLinear()) && return a[map(f, a)::AbstractArray{Bool}]
372✔
2683

2684
    j = 1
372✔
2685
    idxs = Vector{Int}(undef, length(a))
375✔
2686
    for idx in eachindex(a)
615✔
2687
        @inbounds idxs[j] = idx
102,934✔
2688
        ai = @inbounds a[idx]
102,934✔
2689
        j = ifelse(f(ai)::Bool, j+1, j)
137,002✔
2690
    end
205,624✔
2691
    resize!(idxs, j-1)
742✔
2692
    res = a[idxs]
371✔
2693
    empty!(idxs)
371✔
2694
    sizehint!(idxs, 0)
371✔
2695
    return res
371✔
2696
end
2697

2698
"""
2699
    filter!(f, a)
2700

2701
Update collection `a`, removing elements for which `f` is `false`.
2702
The function `f` is passed one argument.
2703

2704
# Examples
2705
```jldoctest
2706
julia> filter!(isodd, Vector(1:10))
2707
5-element Vector{Int64}:
2708
 1
2709
 3
2710
 5
2711
 7
2712
 9
2713
```
2714
"""
2715
function filter!(f, a::AbstractVector)
870,312✔
2716
    j = firstindex(a)
1,011✔
2717
    for ai in a
917,800✔
2718
        @inbounds a[j] = ai
3,079,650✔
2719
        j = ifelse(f(ai)::Bool, nextind(a, j), j)
5,617,960✔
2720
    end
3,902,483✔
2721
    j > lastindex(a) && return a
870,312✔
2722
    if a isa Vector
457✔
2723
        resize!(a, j-1)
78,782✔
2724
        sizehint!(a, j-1)
39,391✔
2725
    else
2726
        deleteat!(a, j:lastindex(a))
1✔
2727
    end
2728
    return a
39,392✔
2729
end
2730

2731
"""
2732
    filter(f)
2733

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

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

2740
# Examples
2741
```jldoctest
2742
julia> (1, 2, Inf, 4, NaN, 6) |> filter(isfinite)
2743
(1, 2, 4, 6)
2744

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

2758
"""
2759
    keepat!(a::Vector, inds)
2760
    keepat!(a::BitVector, inds)
2761

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

2766
`inds` must be an iterator of sorted and unique integer indices.
2767
See also [`deleteat!`](@ref).
2768

2769
!!! compat "Julia 1.7"
2770
    This function is available as of Julia 1.7.
2771

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

2783
"""
2784
    keepat!(a::Vector, m::AbstractVector{Bool})
2785
    keepat!(a::BitVector, m::AbstractVector{Bool})
2786

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

2791
# Examples
2792
```jldoctest
2793
julia> a = [:a, :b, :c];
2794

2795
julia> keepat!(a, [true, false, true])
2796
2-element Vector{Symbol}:
2797
 :a
2798
 :c
2799

2800
julia> a
2801
2-element Vector{Symbol}:
2802
 :a
2803
 :c
2804
```
2805
"""
2806
keepat!(a::Vector, m::AbstractVector{Bool}) = _keepat!(a, m)
4✔
2807

2808
# set-like operators for vectors
2809
# These are moderately efficient, preserve order, and remove dupes.
2810

2811
_unique_filter!(pred::P, update!::U, state) where {P,U} = function (x)
15,967✔
2812
    # P, U force specialization
2813
    if pred(x, state)
14,915✔
2814
        update!(state, x)
7,507✔
2815
        true
7,507✔
2816
    else
2817
        false
7,408✔
2818
    end
2819
end
2820

2821
_grow_filter!(seen) = _unique_filter!(∉, push!, seen)
226✔
2822
_shrink_filter!(keep) = _unique_filter!(∈, pop!, keep)
1,068✔
2823

2824
function _grow!(pred!, v::AbstractVector, itrs)
251✔
2825
    filter!(pred!, v) # uniquify v
253✔
2826
    for itr in itrs
253✔
2827
        mapfilter(pred!, push!, itr, v)
493✔
2828
    end
726✔
2829
    return v
253✔
2830
end
2831

2832
union!(v::AbstractVector{T}, itrs...) where {T} =
220✔
2833
    _grow!(_grow_filter!(sizehint!(Set{T}(), length(v))), v, itrs)
2834

2835
symdiff!(v::AbstractVector{T}, itrs...) where {T} =
33✔
2836
    _grow!(_shrink_filter!(symdiff!(Set{T}(), v, itrs...)), v, itrs)
2837

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

2845
intersect!(v::AbstractVector, itrs...) = _shrink!(intersect!, v, itrs)
3✔
2846
setdiff!(  v::AbstractVector, itrs...) = _shrink!(setdiff!, v, itrs)
3✔
2847

2848
vectorfilter(T::Type, f, v) = T[x for x in v if f(x)]
1,035✔
2849

2850
function _shrink(shrinker!::F, itr, itrs) where F
974✔
2851
    T = promote_eltype(itr, itrs...)
896✔
2852
    keep = shrinker!(Set{T}(itr), itrs...)
1,989✔
2853
    vectorfilter(T, _shrink_filter!(keep), itr)
974✔
2854
end
2855

2856
intersect(itr, itrs...) = _shrink(intersect!, itr, itrs)
467✔
2857
setdiff(  itr, itrs...) = _shrink(setdiff!, itr, itrs)
507✔
2858

2859
function intersect(v::AbstractVector, r::AbstractRange)
57✔
2860
    T = promote_eltype(v, r)
9✔
2861
    common = Iterators.filter(in(r), v)
61✔
2862
    seen = Set{T}(common)
61✔
2863
    return vectorfilter(T, _shrink_filter!(seen), common)
61✔
2864
end
2865
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