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

JuliaLang / julia / #37487

pending completion
#37487

push

local

web-flow
Subtype: Add a fastpath for nested constructor with identity name. (#49159)

* Subtype: Add a fastpath for nested constructor with identity name.

* Update src/subtype.c

---------

Co-authored-by: Jameson Nash <vtjnash@gmail.com>

71468 of 82918 relevant lines covered (86.19%)

30575088.21 hits per line

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

95.3
/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,100✔
13
end
14
DimensionMismatch() = DimensionMismatch("")
8✔
15

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

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

25
"""
26
    AbstractMatrix{T}
27

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

33
"""
34
    AbstractVecOrMat{T}
35

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

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

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

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

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

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

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

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

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

73
"""
74
    VecOrMat{T}
75

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

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

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

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

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

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

100
"""
101
    DenseVector{T}
102

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

107
"""
108
    DenseMatrix{T}
109

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

114
"""
115
    DenseVecOrMat{T}
116

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

121
## Basic functions ##
122

123
using Core: arraysize, arrayset, const_arrayref
124

125
vect() = Vector{Any}()
20,086,957✔
126
vect(X::T...) where {T} = T[ X[i] for i = 1:length(X) ]
1,206,031✔
127

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

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

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

148
size(a::Array, d::Integer) = arraysize(a, convert(Int, d))
2,926,736✔
149
size(a::Vector) = (arraysize(a,1),)
4,881,042,606✔
150
size(a::Matrix) = (arraysize(a,1), arraysize(a,2))
7,106,303✔
151
size(a::Array{<:Any,N}) where {N} = (@inline; ntuple(M -> size(a, M), Val(N))::Dims)
2,707,110✔
152

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

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

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

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

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

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

174
function _unsetindex!(A::Array{T}, i::Int) where {T}
48,920✔
175
    @inline
1,505✔
176
    @boundscheck checkbounds(A, i)
3,096,108✔
177
    t = @_gc_preserve_begin A
3,096,694✔
178
    p = Ptr{Ptr{Cvoid}}(pointer(A, i))
3,096,069✔
179
    if !allocatedinline(T)
1,505✔
180
        Intrinsics.atomic_pointerset(p, C_NULL, :monotonic)
2,849,639✔
181
    elseif T isa DataType
246,959✔
182
        if !datatype_pointerfree(T)
1,399✔
183
            for j = 1:Core.sizeof(Ptr{Cvoid}):Core.sizeof(T)
1,385✔
184
                Intrinsics.atomic_pointerset(p + j - 1, C_NULL, :monotonic)
3,486✔
185
            end
5,505✔
186
        end
187
    end
188
    @_gc_preserve_end t
3,096,624✔
189
    return A
3,095,905✔
190
end
191

192

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

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

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

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

213
elsize(@nospecialize _::Type{A}) where {T,A<:Array{T}} = aligned_sizeof(T)
1,699,470✔
214
sizeof(a::Array) = Core.sizeof(a)
3,379,275✔
215

216
function isassigned(a::Array, i::Int...)
3,248,546✔
217
    @inline
2,449,907✔
218
    @boundscheck checkbounds(Bool, a, i...) || return false
1,813,195,457✔
219
    ii = (_sub2ind(size(a), i...) % UInt) - 1
1,763,482,200✔
220
    ccall(:jl_array_isassigned, Cint, (Any, UInt), a, ii) == 1
1,812,863,328✔
221
end
222

223
## copy ##
224

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

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

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

243

244
function _unsafe_copyto!(dest, doffs, src, soffs, n)
21,628,445✔
245
    destp = pointer(dest, doffs)
21,628,445✔
246
    srcp = pointer(src, soffs)
21,628,445✔
247
    @inbounds if destp < srcp || destp > srcp + n
35,521,366✔
248
        for i = 1:n
43,256,888✔
249
            if isassigned(src, soffs + i - 1)
115,014,885✔
250
                dest[doffs + i - 1] = src[soffs + i - 1]
115,014,329✔
251
            else
252
                _unsetindex!(dest, doffs + i - 1)
720✔
253
            end
254
        end
208,401,086✔
255
    else
256
        for i = n:-1:1
×
257
            if isassigned(src, soffs + i - 1)
×
258
                dest[doffs + i - 1] = src[soffs + i - 1]
×
259
            else
260
                _unsetindex!(dest, doffs + i - 1)
×
261
            end
262
        end
×
263
    end
264
    return dest
21,628,204✔
265
end
266

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

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

273
The `unsafe` prefix on this function indicates that no validation is performed to ensure
274
that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in
275
the same manner as C.
276
"""
277
function unsafe_copyto!(dest::Array{T}, doffs, src::Array{T}, soffs, n) where T
3,934,593✔
278
    t1 = @_gc_preserve_begin dest
110,028,126✔
279
    t2 = @_gc_preserve_begin src
110,028,126✔
280
    destp = pointer(dest, doffs)
110,028,126✔
281
    srcp = pointer(src, soffs)
110,028,137✔
282
    if !allocatedinline(T)
3,931,891✔
283
        ccall(:jl_array_ptr_copy, Cvoid, (Any, Ptr{Cvoid}, Any, Ptr{Cvoid}, Int),
56,673,120✔
284
              dest, destp, src, srcp, n)
285
    elseif isbitstype(T)
1,911,663✔
286
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
36,396,533✔
287
              destp, srcp, n * aligned_sizeof(T))
288
    elseif isbitsunion(T)
6,590✔
289
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
905✔
290
              destp, srcp, n * aligned_sizeof(T))
291
        # copy selector bytes
292
        ccall(:memmove, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
905✔
293
              ccall(:jl_array_typetagdata, Ptr{UInt8}, (Any,), dest) + doffs - 1,
294
              ccall(:jl_array_typetagdata, Ptr{UInt8}, (Any,), src) + soffs - 1,
295
              n)
296
    else
297
        _unsafe_copyto!(dest, doffs, src, soffs, n)
16,957,579✔
298
    end
299
    @_gc_preserve_end t2
110,028,126✔
300
    @_gc_preserve_end t1
110,028,126✔
301
    return dest
38,423,152✔
302
end
303

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

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

310
Copy `N` elements from collection `src` starting at the linear index `so`, to array `dest` starting at
311
the index `do`. Return `dest`.
312
"""
313
function copyto!(dest::Array, doffs::Integer, src::Array, soffs::Integer, n::Integer)
28,664✔
314
    return _copyto_impl!(dest, doffs, src, soffs, n)
9,342,808✔
315
end
316

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

322
function _copyto_impl!(dest::Array, doffs::Integer, src::Array, soffs::Integer, n::Integer)
132,256,383✔
323
    n == 0 && return dest
136,899,664✔
324
    n > 0 || _throw_argerror()
110,101,135✔
325
    @boundscheck checkbounds(dest, doffs:doffs+n-1)
110,101,154✔
326
    @boundscheck checkbounds(src, soffs:soffs+n-1)
110,101,115✔
327
    unsafe_copyto!(dest, doffs, src, soffs, n)
110,101,109✔
328
    return dest
110,100,868✔
329
end
330

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

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

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

344
# N.B: The generic definition in multidimensional.jl covers, this, this is just here
345
# for bootstrapping purposes.
346
function fill!(dest::Array{T}, x) where T
90,234✔
347
    xT = convert(T, x)
86,770✔
348
    for i in eachindex(dest)
756,144,824✔
349
        @inbounds dest[i] = xT
4,069,119,588✔
350
    end
7,975,351,665✔
351
    return dest
593,257,313✔
352
end
353

354
"""
355
    copy(x)
356

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

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

365
copy(a::T) where {T<:Array} = ccall(:jl_array_copy, Ref{T}, (Any,), a)
111,656,927✔
366

367
## Constructors ##
368

369
similar(a::Array{T,1}) where {T}                    = Vector{T}(undef, size(a,1))
8,314✔
370
similar(a::Array{T,2}) where {T}                    = Matrix{T}(undef, size(a,1), size(a,2))
4,141✔
371
similar(a::Array{T,1}, S::Type) where {T}           = Vector{S}(undef, size(a,1))
8,054✔
372
similar(a::Array{T,2}, S::Type) where {T}           = Matrix{S}(undef, size(a,1), size(a,2))
16,083✔
373
similar(a::Array{T}, m::Int) where {T}              = Vector{T}(undef, m)
1,521,159✔
374
similar(a::Array, T::Type, dims::Dims{N}) where {N} = Array{T,N}(undef, dims)
48,987,698✔
375
similar(a::Array{T}, dims::Dims{N}) where {T,N}     = Array{T,N}(undef, dims)
431✔
376

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

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

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

392
julia> getindex(Int8, 1, 2, 3)
393
3-element Vector{Int8}:
394
 1
395
 2
396
 3
397
```
398
"""
399
function getindex(::Type{T}, vals...) where T
200,928✔
400
    a = Vector{T}(undef, length(vals))
554,410,447✔
401
    if vals isa NTuple
50,782✔
402
        @inbounds for i in 1:length(vals)
19,854,127✔
403
            a[i] = vals[i]
19,901,787✔
404
        end
173,740✔
405
    else
406
        # use afoldl to avoid type instability inside loop
407
        afoldl(1, vals...) do i, v
2,913✔
408
            @inbounds a[i] = v
8,753✔
409
            return i + 1
7,316✔
410
        end
411
    end
412
    return a
19,853,399✔
413
end
414

415
function getindex(::Type{Any}, @nospecialize vals...)
18,690,211✔
416
    a = Vector{Any}(undef, length(vals))
41,882,252✔
417
    @inbounds for i = 1:length(vals)
55,787,273✔
418
        a[i] = vals[i]
79,636,708✔
419
    end
94,056,024✔
420
    return a
41,882,252✔
421
end
422
getindex(::Type{Any}) = Vector{Any}()
24,861,700✔
423

424
function fill!(a::Union{Array{UInt8}, Array{Int8}}, x::Integer)
11,042✔
425
    ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), a, convert(eltype(a), x), length(a))
131,530,916✔
426
    return a
131,530,910✔
427
end
428

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

530
fill(v, dims::DimOrInd...) = fill(v, dims)
3,025,883,294✔
531
fill(v, dims::NTuple{N, Union{Integer, OneTo}}) where {N} = fill(v, map(to_dim, dims))
×
532
fill(v, dims::NTuple{N, Integer}) where {N} = (a=Array{typeof(v),N}(undef, dims); fill!(a, v); a)
3,806,928,149✔
533
fill(v, dims::Tuple{}) = (a=Array{typeof(v),0}(undef, dims); fill!(a, v); a)
387✔
534

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

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

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

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

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

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

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

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

577
for (fname, felt) in ((:zeros, :zero), (:ones, :one))
578
    @eval begin
579
        $fname(dims::DimOrInd...) = $fname(dims)
20,215,887✔
580
        $fname(::Type{T}, dims::DimOrInd...) where {T} = $fname(T, dims)
303,970,304✔
581
        $fname(dims::Tuple{Vararg{DimOrInd}}) = $fname(Float64, dims)
20,243,574✔
582
        $fname(::Type{T}, dims::NTuple{N, Union{Integer, OneTo}}) where {T,N} = $fname(T, map(to_dim, dims))
1,625✔
583
        function $fname(::Type{T}, dims::NTuple{N, Integer}) where {T,N}
40,911✔
584
            a = Array{T,N}(undef, dims)
202,012,918✔
585
            fill!(a, $felt(T))
328,511,445✔
586
            return a
202,012,918✔
587
        end
588
        function $fname(::Type{T}, dims::Tuple{}) where {T}
16✔
589
            a = Array{T}(undef)
16✔
590
            fill!(a, $felt(T))
16✔
591
            return a
16✔
592
        end
593
    end
594
end
595

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

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

611
## Conversions ##
612

613
convert(::Type{T}, a::AbstractArray) where {T<:Array} = a isa T ? a : T(a)::T
113,526,800✔
614

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

617
## Constructors ##
618

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

625
## copying iterators to containers
626

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

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

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

644
_collect(::Type{T}, itr, isz::Union{HasLength,HasShape}) where {T} =
9,281,582✔
645
    copyto!(_array_for(T, isz, _similar_shape(itr, isz)), itr)
646
function _collect(::Type{T}, itr, isz::SizeUnknown) where T
9,497,264✔
647
    a = Vector{T}()
9,497,264✔
648
    for x in itr
14,354,315✔
649
        push!(a, x)
6,158,494✔
650
    end
7,459,936✔
651
    return a
9,497,264✔
652
end
653

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

657
_similar_shape(itr, ::SizeUnknown) = nothing
1✔
658
_similar_shape(itr, ::HasLength) = length(itr)::Integer
30,810,171✔
659
_similar_shape(itr, ::HasShape) = axes(itr)
358,909,797✔
660

661
_similar_for(c::AbstractArray, ::Type{T}, itr, ::SizeUnknown, ::Nothing) where {T} =
922,253✔
662
    similar(c, T, 0)
663
_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasLength, len::Integer) where {T} =
3,549,028✔
664
    similar(c, T, len)
665
_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasShape, axs) where {T} =
125,990✔
666
    similar(c, T, axs)
667

668
# make a collection appropriate for collecting `itr::Generator`
669
_array_for(::Type{T}, ::SizeUnknown, ::Nothing) where {T} = Vector{T}(undef, 0)
487✔
670
_array_for(::Type{T}, ::HasLength, len::Integer) where {T} = Vector{T}(undef, Int(len))
24,922,323✔
671
_array_for(::Type{T}, ::HasShape{N}, axs) where {T,N} = similar(Array{T,N}, axs)
360,028,319✔
672

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

676

677
"""
678
    collect(collection)
679

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

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

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

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

709
collect(A::AbstractArray) = _collect_indices(axes(A), A)
129,426✔
710

711
collect_similar(cont, itr) = _collect(cont, itr, IteratorEltype(itr), IteratorSize(itr))
125,380✔
712

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

716
function _collect(cont, itr, ::HasEltype, isz::SizeUnknown)
922,220✔
717
    a = _similar_for(cont, eltype(itr), itr, isz, nothing)
922,220✔
718
    for x in itr
1,843,437✔
719
        push!(a,x)
8,513,836✔
720
    end
14,498,462✔
721
    return a
922,219✔
722
end
723

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

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

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

775
function collect(itr::Generator)
572,240✔
776
    isz = IteratorSize(itr.iter)
153,087✔
777
    et = @default_eltype(itr)
×
778
    if isa(isz, SizeUnknown)
153,087✔
779
        return grow_to!(Vector{et}(), itr)
85,118✔
780
    else
781
        shp = _similar_shape(itr, isz)
487,697✔
782
        y = iterate(itr)
963,807✔
783
        if y === nothing
487,499✔
784
            return _array_for(et, isz, shp)
961✔
785
        end
786
        v1, st = y
67,595✔
787
        dest = _array_for(typeof(v1), isz, shp)
486,642✔
788
        # The typeassert gives inference a helping hand on the element type and dimensionality
789
        # (work-around for #28382)
790
        et′ = et <: Type ? Type : et
67,595✔
791
        RT = dest isa AbstractArray ? AbstractArray{<:et′, ndims(dest)} : Any
67,651✔
792
        collect_to_with_first!(dest, v1, itr, st)::RT
10,480,589✔
793
    end
794
end
795

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

799
function _collect(c, itr, ::EltypeUnknown, isz::Union{HasLength,HasShape})
124,842✔
800
    et = @default_eltype(itr)
90,289✔
801
    shp = _similar_shape(itr, isz)
124,843✔
802
    y = iterate(itr)
248,696✔
803
    if y === nothing
124,840✔
804
        return _similar_for(c, et, itr, isz, shp)
234✔
805
    end
806
    v1, st = y
90,275✔
807
    dest = _similar_for(c, typeof(v1), itr, isz, shp)
124,621✔
808
    # The typeassert gives inference a helping hand on the element type and dimensionality
809
    # (work-around for #28382)
810
    et′ = et <: Type ? Type : et
90,233✔
811
    RT = dest isa AbstractArray ? AbstractArray{<:et′, ndims(dest)} : Any
90,251✔
812
    collect_to_with_first!(dest, v1, itr, st)::RT
125,172✔
813
end
814

815
function collect_to_with_first!(dest::AbstractArray, v1, itr, st)
157,929✔
816
    i1 = first(LinearIndices(dest))
157,835✔
817
    dest[i1] = v1
611,190✔
818
    return collect_to!(dest, itr, i1+1, st)
82,711,961✔
819
end
820

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

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

835
function collect_to!(dest::AbstractArray{T}, itr, offs, st) where T
196,079✔
836
    # collect to dest array, checking the type of each result. if a result does not
837
    # match, widen the result type and re-dispatch.
838
    i = offs
158,569✔
839
    while true
84,486,549✔
840
        y = iterate(itr, st)
168,360,620✔
841
        y === nothing && break
84,486,541✔
842
        el, st = y
83,409,707✔
843
        if el isa T
83,408,422✔
844
            @inbounds dest[i] = el
83,880,835✔
845
            i += 1
83,874,625✔
846
        else
847
            new = setindex_widen_up_to(dest, el, i)
812✔
848
            return collect_to!(new, itr, i+1, st)
734✔
849
        end
850
    end
83,874,625✔
851
    return dest
611,182✔
852
end
853

854
function grow_to!(dest, itr)
85,148✔
855
    y = iterate(itr)
85,388✔
856
    y === nothing && return dest
85,148✔
857
    dest2 = empty(dest, typeof(y[1]))
260✔
858
    push!(dest2, y[1])
283✔
859
    grow_to!(dest2, itr, y[2])
245✔
860
end
861

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

875
function grow_to!(dest, itr, st)
297✔
876
    T = eltype(dest)
192✔
877
    y = iterate(itr, st)
541✔
878
    while y !== nothing
3,300✔
879
        el, st = y
1,744✔
880
        if el isa T
1,744✔
881
            push!(dest, el)
3,005✔
882
        else
883
            new = push_widen(dest, el)
54✔
884
            return grow_to!(new, itr, st)
52✔
885
        end
886
        y = iterate(itr, st)
4,662✔
887
    end
3,003✔
888
    return dest
245✔
889
end
890

891
## Iteration ##
892

893
iterate(A::Array, i=1) = (@inline; (i % UInt) - 1 < length(A) ? (@inbounds A[i], i + 1) : nothing)
7,697,291,498✔
894

895
## Indexing: getindex ##
896

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

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

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

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

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

918
# Faster contiguous indexing using copyto! for AbstractUnitRange and Colon
919
function getindex(A::Array, I::AbstractUnitRange{<:Integer})
815,078✔
920
    @inline
793,810✔
921
    @boundscheck checkbounds(A, I)
48,681,071✔
922
    lI = length(I)
48,681,071✔
923
    X = similar(A, axes(I))
48,681,083✔
924
    if lI > 0
48,681,071✔
925
        copyto!(X, firstindex(X), A, first(I), lI)
43,156,276✔
926
    end
927
    return X
48,681,071✔
928
end
929

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

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

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

947
## Indexing: setindex! ##
948

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

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

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

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

969
@eval setindex!(A::Array{T}, x, i1::Int) where {T} = arrayset($(Expr(:boundscheck)), A, convert(T,x)::T, i1)
15,812,383,303✔
970
@eval setindex!(A::Array{T}, x, i1::Int, i2::Int, I::Int...) where {T} =
52,776,013✔
971
    (@inline; arrayset($(Expr(:boundscheck)), A, convert(T,x)::T, i1, i2, I...))
55,473,872✔
972

973
# This is redundant with the abstract fallbacks but needed and helpful for bootstrap
974
function setindex!(A::Array, X::AbstractArray, I::AbstractVector{Int})
799,522✔
975
    @_propagate_inbounds_meta
799,522✔
976
    @boundscheck setindex_shape_check(X, length(I))
5,467,206✔
977
    require_one_based_indexing(X)
799,522✔
978
    X′ = unalias(A, X)
804,847✔
979
    I′ = unalias(A, I)
799,949✔
980
    count = 1
799,522✔
981
    for i in I′
10,217,959✔
982
        @inbounds x = X′[count]
13,435,557✔
983
        A[i] = x
13,437,640✔
984
        count += 1
13,435,557✔
985
    end
22,073,575✔
986
    return A
5,467,206✔
987
end
988

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

1010
# efficiently grow an array
1011

1012
_growbeg!(a::Vector, delta::Integer) =
981,347✔
1013
    ccall(:jl_array_grow_beg, Cvoid, (Any, UInt), a, delta)
1014
_growend!(a::Vector, delta::Integer) =
1,333,529,739✔
1015
    ccall(:jl_array_grow_end, Cvoid, (Any, UInt), a, delta)
1016
_growat!(a::Vector, i::Integer, delta::Integer) =
59,135,314✔
1017
    ccall(:jl_array_grow_at, Cvoid, (Any, Int, UInt), a, i - 1, delta)
1018

1019
# efficiently delete part of an array
1020

1021
_deletebeg!(a::Vector, delta::Integer) =
17,149,783✔
1022
    ccall(:jl_array_del_beg, Cvoid, (Any, UInt), a, delta)
1023
_deleteend!(a::Vector, delta::Integer) =
359,324,548✔
1024
    ccall(:jl_array_del_end, Cvoid, (Any, UInt), a, delta)
1025
_deleteat!(a::Vector, i::Integer, delta::Integer) =
219,599✔
1026
    ccall(:jl_array_del_at, Cvoid, (Any, Int, UInt), a, i - 1, delta)
1027

1028
## Dequeue functionality ##
1029

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

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

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

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

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

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

1058
function push!(a::Array{T,1}, item) where T
42,489,262✔
1059
    # convert first so we don't grow the array if the assignment won't work
1060
    itemT = convert(T, item)
21,222,550✔
1061
    _growend!(a, 1)
879,406,505✔
1062
    @inbounds a[end] = itemT
879,406,505✔
1063
    return a
27,414,404✔
1064
end
1065

1066
# specialize and optimize the single argument case
1067
function push!(a::Vector{Any}, @nospecialize x)
3,157,522✔
1068
    _growend!(a, 1)
76,658,094✔
1069
    arrayset(true, a, x, length(a))
76,658,092✔
1070
    return a
2,793,003✔
1071
end
1072
function push!(a::Vector{Any}, @nospecialize x...)
89,557✔
1073
    na = length(a)
89,557✔
1074
    nx = length(x)
2✔
1075
    _growend!(a, nx)
89,557✔
1076
    for i = 1:nx
89,557✔
1077
        arrayset(true, a, x[i], na+i)
179,116✔
1078
    end
268,675✔
1079
    return a
89,557✔
1080
end
1081

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

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

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

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

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

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

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

1115
See also [`vcat`](@ref) for vectors, [`union!`](@ref) for sets,
1116
and [`prepend!`](@ref) and [`pushfirst!`](@ref) for the opposite order.
1117
"""
1118
function append!(a::Vector, items::AbstractVector)
46,075✔
1119
    itemindices = eachindex(items)
51,552,580✔
1120
    n = length(itemindices)
29,896✔
1121
    _growend!(a, n)
51,552,580✔
1122
    copyto!(a, length(a)-n+1, items, first(itemindices), n)
51,553,898✔
1123
    return a
51,552,580✔
1124
end
1125

1126
append!(a::AbstractVector, iter) = _append!(a, IteratorSize(iter), iter)
36,876,583✔
1127
push!(a::AbstractVector, iter...) = append!(a, iter)
4,035✔
1128

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

1131
function _append!(a, ::Union{HasLength,HasShape}, iter)
14,516,405✔
1132
    n = length(a)
14,516,405✔
1133
    i = lastindex(a)
14,516,405✔
1134
    resize!(a, n+Int(length(iter))::Int)
24,827,329✔
1135
    @inbounds for (i, item) in zip(i+1:lastindex(a), iter)
18,721,886✔
1136
        a[i] = item
19,228,209✔
1137
    end
34,247,485✔
1138
    a
14,516,405✔
1139
end
1140

1141
function _append!(a, ::IteratorSize, iter)
22,360,178✔
1142
    for item in iter
22,360,180✔
1143
        push!(a, item)
23,070,798✔
1144
    end
23,070,803✔
1145
    a
22,360,178✔
1146
end
1147

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1233
julia> length(a)
1234
8
1235

1236
julia> a[1:6]
1237
6-element Vector{Int64}:
1238
 6
1239
 5
1240
 4
1241
 3
1242
 2
1243
 1
1244
```
1245
"""
1246
function resize!(a::Vector, nl::Integer)
5,241,272✔
1247
    l = length(a)
493,190,914✔
1248
    if nl > l
493,190,914✔
1249
        _growend!(a, nl-l)
220,549,485✔
1250
    elseif nl != l
272,641,431✔
1251
        if nl < 0
56,315,298✔
1252
            throw(ArgumentError("new length must be ≥ 0"))
2✔
1253
        end
1254
        _deleteend!(a, l-nl)
56,316,435✔
1255
    end
1256
    return a
493,190,913✔
1257
end
1258

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

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

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

1269
# Notes on the performance model
1270

1271
For types that support `sizehint!`,
1272

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

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

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

1284
function sizehint!(a::Vector, sz::Integer)
454,735✔
1285
    ccall(:jl_array_sizehint, Cvoid, (Any, UInt), a, sz)
154,733,165✔
1286
    a
621,663✔
1287
end
1288

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

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

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

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

1306
julia> pop!(A)
1307
3
1308

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

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

1319
julia> pop!(S)
1320
2
1321

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

1326
julia> pop!(Dict(1=>2))
1327
1 => 2
1328
```
1329
"""
1330
function pop!(a::Vector)
58,386✔
1331
    if isempty(a)
246,221,775✔
1332
        throw(ArgumentError("array must be non-empty"))
1✔
1333
    end
1334
    item = a[end]
246,221,774✔
1335
    _deleteend!(a, 1)
246,221,774✔
1336
    return item
246,221,774✔
1337
end
1338

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1449
julia> popfirst!(A)
1450
1
1451

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

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

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

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

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

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

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

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

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

1525
function deleteat!(a::Vector, r::AbstractUnitRange{<:Integer})
3,638✔
1526
    if eltype(r) === Bool
3,638✔
1527
        return invoke(deleteat!, Tuple{Vector, AbstractVector{Bool}}, a, r)
×
1528
    else
1529
        n = length(a)
3,638✔
1530
        f = first(r)
3,733✔
1531
        f isa Bool && depwarn("passing Bool as an index is deprecated", :deleteat!)
3,638✔
1532
        isempty(r) || _deleteat!(a, f, length(r))
18,609✔
1533
        return a
10,933✔
1534
    end
1535
end
1536

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

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

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

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

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

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

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

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

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

1589
function _deleteat!(a::Vector, inds, dltd=Nowhere())
43,745✔
1590
    n = length(a)
87,427✔
1591
    y = iterate(inds)
43,725✔
1592
    y === nothing && return a
43,714✔
1593
    (p, s) = y
27✔
1594
    checkbounds(a, p)
43,715✔
1595
    _push_deleted!(dltd, a, p)
43,708✔
1596
    q = p+1
43,703✔
1597
    while true
48,430✔
1598
        y = iterate(inds, s)
92,127✔
1599
        y === nothing && break
48,430✔
1600
        (i,s) = y
30✔
1601
        if !(q <= i <= n)
4,729✔
1602
            if i < q
2✔
1603
                throw(ArgumentError("indices must be unique and sorted"))
1✔
1604
            else
1605
                throw(BoundsError())
1✔
1606
            end
1607
        end
1608
        while q < i
6,246✔
1609
            _copy_item!(a, p, q)
1,528✔
1610
            p += 1; q += 1
3,038✔
1611
        end
1,519✔
1612
        _push_deleted!(dltd, a, i)
4,737✔
1613
        q = i+1
4,727✔
1614
    end
4,727✔
1615
    while q <= n
67,606✔
1616
        _copy_item!(a, p, q)
23,917✔
1617
        p += 1; q += 1
47,810✔
1618
    end
23,905✔
1619
    _deleteend!(a, n-p+1)
43,701✔
1620
    return a
43,701✔
1621
end
1622

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

1636
const _default_splice = []
1637

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1772
function empty!(a::Vector)
81,767✔
1773
    _deleteend!(a, length(a))
56,742,555✔
1774
    return a
56,742,555✔
1775
end
1776

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

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

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

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

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

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

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

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

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

1828
julia> reverse(A, 3, 5)
1829
5-element Vector{Int64}:
1830
 1
1831
 2
1832
 5
1833
 4
1834
 3
1835
```
1836
"""
1837
function reverse(A::AbstractVector, start::Integer, stop::Integer=lastindex(A))
4,524✔
1838
    s, n = Int(start), Int(stop)
59✔
1839
    B = similar(A)
4,525✔
1840
    for i = firstindex(A):s-1
4,528✔
1841
        B[i] = A[i]
14✔
1842
    end
24✔
1843
    for i = s:n
9,042✔
1844
        B[i] = A[n+s-i]
177,395✔
1845
    end
350,268✔
1846
    for i = n+1:lastindex(A)
4,528✔
1847
        B[i] = A[i]
20✔
1848
    end
36✔
1849
    return B
4,524✔
1850
end
1851

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

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

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

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

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

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

1890
julia> reverse!(A);
1891

1892
julia> A
1893
5-element Vector{Int64}:
1894
 5
1895
 4
1896
 3
1897
 2
1898
 1
1899
```
1900
"""
1901
function reverse!(v::AbstractVector, start::Integer, stop::Integer=lastindex(v))
74,537✔
1902
    s, n = Int(start), Int(stop)
7,843✔
1903
    if n > s # non-empty and non-trivial
74,534✔
1904
        liv = LinearIndices(v)
71,029✔
1905
        if !(first(liv) ≤ s ≤ last(liv))
71,029✔
1906
            throw(BoundsError(v, s))
3✔
1907
        elseif !(first(liv) ≤ n ≤ last(liv))
71,026✔
1908
            throw(BoundsError(v, n))
1✔
1909
        end
1910
        r = n
7,226✔
1911
        @inbounds for i in s:midpoint(s, n-1)
142,050✔
1912
            v[i], v[r] = v[r], v[i]
1,630,609✔
1913
            r -= 1
1,626,191✔
1914
        end
3,181,357✔
1915
    end
1916
    return v
74,530✔
1917
end
1918

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

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

1924
function hcat(V::Vector{T}...) where T
559✔
1925
    height = length(V[1])
559✔
1926
    for j = 2:length(V)
560✔
1927
        if length(V[j]) != height
626✔
1928
            throw(DimensionMismatch("vectors must have same lengths"))
1✔
1929
        end
1930
    end
723✔
1931
    return [ V[j][i]::T for i=1:length(V[1]), j=1:length(V) ]
558✔
1932
end
1933
hcat(A::Vector...) = cat(A...; dims=Val(2)) # more special than SparseArrays's hcat
6✔
1934

1935
function vcat(arrays::Vector{T}...) where T
35,770✔
1936
    n = 0
6,820✔
1937
    for a in arrays
35,770✔
1938
        n += length(a)
2,071,688✔
1939
    end
2,107,439✔
1940
    arr = Vector{T}(undef, n)
35,770✔
1941
    nd = 1
6,820✔
1942
    for a in arrays
35,770✔
1943
        na = length(a)
2,071,688✔
1944
        @assert nd + na <= 1 + length(arr) # Concurrent modification of arrays?
2,071,688✔
1945
        unsafe_copyto!(arr, nd, a, 1, na)
2,071,688✔
1946
        nd += na
2,071,688✔
1947
    end
2,107,439✔
1948
    return arr
35,770✔
1949
end
1950
vcat(A::Vector...) = cat(A...; dims=Val(1)) # more special than SparseArrays's vcat
71✔
1951

1952
# disambiguation with LinAlg/special.jl
1953
# Union{Number,Vector,Matrix} is for LinearAlgebra._DenseConcatGroup
1954
# VecOrMat{T} is for LinearAlgebra._TypedDenseConcatGroup
1955
hcat(A::Union{Number,Vector,Matrix}...) = cat(A...; dims=Val(2))
104✔
1956
hcat(A::VecOrMat{T}...) where {T} = typed_hcat(T, A...)
172✔
1957
vcat(A::Union{Number,Vector,Matrix}...) = cat(A...; dims=Val(1))
101✔
1958
vcat(A::VecOrMat{T}...) where {T} = typed_vcat(T, A...)
540✔
1959
hvcat(rows::Tuple{Vararg{Int}}, xs::Union{Number,Vector,Matrix}...) =
91✔
1960
    typed_hvcat(promote_eltypeof(xs...), rows, xs...)
1961
hvcat(rows::Tuple{Vararg{Int}}, xs::VecOrMat{T}...) where {T} =
65✔
1962
    typed_hvcat(T, rows, xs...)
1963

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

1966
## find ##
1967

1968
"""
1969
    findnext(A, i)
1970

1971
Find the next index after or including `i` of a `true` element of `A`,
1972
or `nothing` if not found.
1973

1974
Indices are of the same type as those returned by [`keys(A)`](@ref)
1975
and [`pairs(A)`](@ref).
1976

1977
# Examples
1978
```jldoctest
1979
julia> A = [false, false, true, false]
1980
4-element Vector{Bool}:
1981
 0
1982
 0
1983
 1
1984
 0
1985

1986
julia> findnext(A, 1)
1987
3
1988

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

1991
julia> A = [false false; true false]
1992
2×2 Matrix{Bool}:
1993
 0  0
1994
 1  0
1995

1996
julia> findnext(A, CartesianIndex(1, 1))
1997
CartesianIndex(2, 1)
1998
```
1999
"""
2000
findnext(A, start) = findnext(identity, A, start)
133✔
2001

2002
"""
2003
    findfirst(A)
2004

2005
Return the index or key of the first `true` value in `A`.
2006
Return `nothing` if no such value is found.
2007
To search for other kinds of values, pass a predicate as the first argument.
2008

2009
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2010
and [`pairs(A)`](@ref).
2011

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

2014
# Examples
2015
```jldoctest
2016
julia> A = [false, false, true, false]
2017
4-element Vector{Bool}:
2018
 0
2019
 0
2020
 1
2021
 0
2022

2023
julia> findfirst(A)
2024
3
2025

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

2028
julia> A = [false false; true false]
2029
2×2 Matrix{Bool}:
2030
 0  0
2031
 1  0
2032

2033
julia> findfirst(A)
2034
CartesianIndex(2, 1)
2035
```
2036
"""
2037
findfirst(A) = findfirst(identity, A)
2✔
2038

2039
# Needed for bootstrap, and allows defining only an optimized findnext method
2040
findfirst(A::AbstractArray) = findnext(A, first(keys(A)))
120✔
2041

2042
"""
2043
    findnext(predicate::Function, A, i)
2044

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

2048
Indices are of the same type as those returned by [`keys(A)`](@ref)
2049
and [`pairs(A)`](@ref).
2050

2051
# Examples
2052
```jldoctest
2053
julia> A = [1, 4, 2, 2];
2054

2055
julia> findnext(isodd, A, 1)
2056
1
2057

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

2060
julia> A = [1 4; 2 2];
2061

2062
julia> findnext(isodd, A, CartesianIndex(1, 1))
2063
CartesianIndex(1, 1)
2064
```
2065
"""
2066
function findnext(testf::Function, A, start)
19,744✔
2067
    i = oftype(first(keys(A)), start)
17,710✔
2068
    l = last(keys(A))
32,151,243✔
2069
    i > l && return nothing
32,151,243✔
2070
    while true
167,508,863✔
2071
        testf(A[i]) && return i
167,512,934✔
2072
        i == l && break
167,109,077✔
2073
        # nextind(A, l) can throw/overflow
2074
        i = nextind(A, i)
163,098,093✔
2075
    end
163,098,074✔
2076
    return nothing
4,010,979✔
2077
end
2078

2079
"""
2080
    findfirst(predicate::Function, A)
2081

2082
Return the index or key of the first element of `A` for which `predicate` returns `true`.
2083
Return `nothing` if there is no such element.
2084

2085
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2086
and [`pairs(A)`](@ref).
2087

2088
# Examples
2089
```jldoctest
2090
julia> A = [1, 4, 2, 2]
2091
4-element Vector{Int64}:
2092
 1
2093
 4
2094
 2
2095
 2
2096

2097
julia> findfirst(iseven, A)
2098
2
2099

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

2102
julia> findfirst(isequal(4), A)
2103
2
2104

2105
julia> A = [1 4; 2 2]
2106
2×2 Matrix{Int64}:
2107
 1  4
2108
 2  2
2109

2110
julia> findfirst(iseven, A)
2111
CartesianIndex(2, 1)
2112
```
2113
"""
2114
function findfirst(testf::Function, A)
14✔
2115
    for (i, a) in pairs(A)
22✔
2116
        testf(a) && return i
14✔
2117
    end
11✔
2118
    return nothing
7✔
2119
end
2120

2121
# Needed for bootstrap, and allows defining only an optimized findnext method
2122
findfirst(testf::Function, A::Union{AbstractArray, AbstractString}) =
200,387,910✔
2123
    findnext(testf, A, first(keys(A)))
2124

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

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

2131
function findfirst(p::Union{Fix2{typeof(isequal),T},Fix2{typeof(==),T}}, r::StepRange{T,S}) where {T,S}
6✔
2132
    isempty(r) && return nothing
6✔
2133
    minimum(r) <= p.x <= maximum(r) || return nothing
7✔
2134
    d = convert(S, p.x - first(r))
3✔
2135
    iszero(d % step(r)) || return nothing
3✔
2136
    return d ÷ step(r) + 1
3✔
2137
end
2138

2139
"""
2140
    findprev(A, i)
2141

2142
Find the previous index before or including `i` of a `true` element of `A`,
2143
or `nothing` if not found.
2144

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

2148
See also: [`findnext`](@ref), [`findfirst`](@ref), [`findall`](@ref).
2149

2150
# Examples
2151
```jldoctest
2152
julia> A = [false, false, true, true]
2153
4-element Vector{Bool}:
2154
 0
2155
 0
2156
 1
2157
 1
2158

2159
julia> findprev(A, 3)
2160
3
2161

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

2164
julia> A = [false false; true true]
2165
2×2 Matrix{Bool}:
2166
 0  0
2167
 1  1
2168

2169
julia> findprev(A, CartesianIndex(2, 1))
2170
CartesianIndex(2, 1)
2171
```
2172
"""
2173
findprev(A, start) = findprev(identity, A, start)
3,929✔
2174

2175
"""
2176
    findlast(A)
2177

2178
Return the index or key of the last `true` value in `A`.
2179
Return `nothing` if there is no `true` value in `A`.
2180

2181
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2182
and [`pairs(A)`](@ref).
2183

2184
See also: [`findfirst`](@ref), [`findprev`](@ref), [`findall`](@ref).
2185

2186
# Examples
2187
```jldoctest
2188
julia> A = [true, false, true, false]
2189
4-element Vector{Bool}:
2190
 1
2191
 0
2192
 1
2193
 0
2194

2195
julia> findlast(A)
2196
3
2197

2198
julia> A = falses(2,2);
2199

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

2202
julia> A = [true false; true false]
2203
2×2 Matrix{Bool}:
2204
 1  0
2205
 1  0
2206

2207
julia> findlast(A)
2208
CartesianIndex(2, 1)
2209
```
2210
"""
2211
findlast(A) = findlast(identity, A)
23✔
2212

2213
# Needed for bootstrap, and allows defining only an optimized findprev method
2214
findlast(A::AbstractArray) = findprev(A, last(keys(A)))
4,050✔
2215

2216
"""
2217
    findprev(predicate::Function, A, i)
2218

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

2222
Indices are of the same type as those returned by [`keys(A)`](@ref)
2223
and [`pairs(A)`](@ref).
2224

2225
# Examples
2226
```jldoctest
2227
julia> A = [4, 6, 1, 2]
2228
4-element Vector{Int64}:
2229
 4
2230
 6
2231
 1
2232
 2
2233

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

2236
julia> findprev(isodd, A, 3)
2237
3
2238

2239
julia> A = [4 6; 1 2]
2240
2×2 Matrix{Int64}:
2241
 4  6
2242
 1  2
2243

2244
julia> findprev(isodd, A, CartesianIndex(1, 2))
2245
CartesianIndex(2, 1)
2246
```
2247
"""
2248
function findprev(testf::Function, A, start)
28,391✔
2249
    f = first(keys(A))
28,391✔
2250
    i = oftype(f, start)
28,402✔
2251
    i < f && return nothing
29,924✔
2252
    while true
43,348✔
2253
        testf(A[i]) && return i
43,391✔
2254
        i == f && break
13,512✔
2255
        # prevind(A, f) can throw/underflow
2256
        i = prevind(A, i)
13,453✔
2257
    end
13,425✔
2258
    return nothing
56✔
2259
end
2260

2261
"""
2262
    findlast(predicate::Function, A)
2263

2264
Return the index or key of the last element of `A` for which `predicate` returns `true`.
2265
Return `nothing` if there is no such element.
2266

2267
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2268
and [`pairs(A)`](@ref).
2269

2270
# Examples
2271
```jldoctest
2272
julia> A = [1, 2, 3, 4]
2273
4-element Vector{Int64}:
2274
 1
2275
 2
2276
 3
2277
 4
2278

2279
julia> findlast(isodd, A)
2280
3
2281

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

2284
julia> A = [1 2; 3 4]
2285
2×2 Matrix{Int64}:
2286
 1  2
2287
 3  4
2288

2289
julia> findlast(isodd, A)
2290
CartesianIndex(2, 1)
2291
```
2292
"""
2293
function findlast(testf::Function, A)
4✔
2294
    for (i, a) in Iterators.reverse(pairs(A))
4✔
2295
        testf(a) && return i
6✔
2296
    end
6✔
2297
    return nothing
2✔
2298
end
2299

2300
# Needed for bootstrap, and allows defining only an optimized findprev method
2301
findlast(testf::Function, A::Union{AbstractArray, AbstractString}) =
12,733✔
2302
    findprev(testf, A, last(keys(A)))
2303

2304
"""
2305
    findall(f::Function, A)
2306

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

2310
Indices or keys are of the same type as those returned by [`keys(A)`](@ref)
2311
and [`pairs(A)`](@ref).
2312

2313
# Examples
2314
```jldoctest
2315
julia> x = [1, 3, 4]
2316
3-element Vector{Int64}:
2317
 1
2318
 3
2319
 4
2320

2321
julia> findall(isodd, x)
2322
2-element Vector{Int64}:
2323
 1
2324
 2
2325

2326
julia> A = [1 2 0; 3 4 0]
2327
2×3 Matrix{Int64}:
2328
 1  2  0
2329
 3  4  0
2330
julia> findall(isodd, A)
2331
2-element Vector{CartesianIndex{2}}:
2332
 CartesianIndex(1, 1)
2333
 CartesianIndex(2, 1)
2334

2335
julia> findall(!iszero, A)
2336
4-element Vector{CartesianIndex{2}}:
2337
 CartesianIndex(1, 1)
2338
 CartesianIndex(2, 1)
2339
 CartesianIndex(1, 2)
2340
 CartesianIndex(2, 2)
2341

2342
julia> d = Dict(:A => 10, :B => -1, :C => 0)
2343
Dict{Symbol, Int64} with 3 entries:
2344
  :A => 10
2345
  :B => -1
2346
  :C => 0
2347

2348
julia> findall(x -> x >= 0, d)
2349
2-element Vector{Symbol}:
2350
 :A
2351
 :C
2352

2353
```
2354
"""
2355
function findall(testf::Function, A)
52✔
2356
    T = eltype(keys(A))
52✔
2357
    gen = (first(p) for p in pairs(A) if testf(last(p)))
52✔
2358
    isconcretetype(T) ? collect(T, gen) : collect(gen)
52✔
2359
end
2360

2361
# Broadcasting is much faster for small testf, and computing
2362
# integer indices from logical index using findall has a negligible cost
2363
findall(testf::F, A::AbstractArray) where {F<:Function} = findall(testf.(A))
303✔
2364

2365
"""
2366
    findall(A)
2367

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

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

2375
See also: [`findfirst`](@ref), [`searchsorted`](@ref).
2376

2377
# Examples
2378
```jldoctest
2379
julia> A = [true, false, false, true]
2380
4-element Vector{Bool}:
2381
 1
2382
 0
2383
 0
2384
 1
2385

2386
julia> findall(A)
2387
2-element Vector{Int64}:
2388
 1
2389
 4
2390

2391
julia> A = [true false; false true]
2392
2×2 Matrix{Bool}:
2393
 1  0
2394
 0  1
2395

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

2401
julia> findall(falses(3))
2402
Int64[]
2403
```
2404
"""
2405
function findall(A)
3✔
2406
    collect(first(p) for p in pairs(A) if last(p))
3✔
2407
end
2408

2409
# Allocating result upfront is faster (possible only when collection can be iterated twice)
2410
function _findall(f::Function, A::AbstractArray{Bool})
18✔
2411
    n = count(f, A)
22✔
2412
    I = Vector{eltype(keys(A))}(undef, n)
18✔
2413
    isempty(I) && return I
18✔
2414
    _findall(f, I, A)
16✔
2415
end
2416

2417
function _findall(f::Function, I::Vector, A::AbstractArray{Bool})
5✔
2418
    cnt = 1
5✔
2419
    len = length(I)
5✔
2420
    for (k, v) in pairs(A)
10✔
2421
        @inbounds I[cnt] = k
57✔
2422
        cnt += f(v)
57✔
2423
        cnt > len && return I
57✔
2424
    end
104✔
2425
    # In case of impure f, this line could potentially be hit. In that case,
2426
    # we can't assume I is the correct length.
2427
    resize!(I, cnt - 1)
×
2428
end
2429

2430
function _findall(f::Function, I::Vector, A::AbstractVector{Bool})
11✔
2431
    i = firstindex(A)
11✔
2432
    cnt = 1
11✔
2433
    len = length(I)
11✔
2434
    while cnt ≤ len
214✔
2435
        @inbounds I[cnt] = i
203✔
2436
        cnt += f(@inbounds A[i])
203✔
2437
        i = nextind(A, i)
203✔
2438
    end
203✔
2439
    cnt - 1 == len ? I : resize!(I, cnt - 1)
11✔
2440
end
2441

2442
findall(f::Function, A::AbstractArray{Bool}) = _findall(f, A)
4✔
2443
findall(f::Fix2{typeof(in)}, A::AbstractArray{Bool}) = _findall(f, A)
×
2444
findall(A::AbstractArray{Bool}) = _findall(identity, A)
17✔
2445

2446
findall(x::Bool) = x ? [1] : Vector{Int}()
2✔
2447
findall(testf::Function, x::Number) = testf(x) ? [1] : Vector{Int}()
2✔
2448
findall(p::Fix2{typeof(in)}, x::Number) = x in p.x ? [1] : Vector{Int}()
2✔
2449

2450
# similar to Matlab's ismember
2451
"""
2452
    indexin(a, b)
2453

2454
Return an array containing the first index in `b` for
2455
each value in `a` that is a member of `b`. The output
2456
array contains `nothing` wherever `a` is not a member of `b`.
2457

2458
See also: [`sortperm`](@ref), [`findfirst`](@ref).
2459

2460
# Examples
2461
```jldoctest
2462
julia> a = ['a', 'b', 'c', 'b', 'd', 'a'];
2463

2464
julia> b = ['a', 'b', 'c'];
2465

2466
julia> indexin(a, b)
2467
6-element Vector{Union{Nothing, Int64}}:
2468
 1
2469
 2
2470
 3
2471
 2
2472
  nothing
2473
 1
2474

2475
julia> indexin(b, a)
2476
3-element Vector{Union{Nothing, Int64}}:
2477
 1
2478
 2
2479
 3
2480
```
2481
"""
2482
function indexin(a, b::AbstractArray)
7✔
2483
    inds = keys(b)
7✔
2484
    bdict = Dict{eltype(b),eltype(inds)}()
7✔
2485
    for (val, ind) in zip(b, inds)
14✔
2486
        get!(bdict, val, ind)
30✔
2487
    end
53✔
2488
    return Union{eltype(inds), Nothing}[
7✔
2489
        get(bdict, i, nothing) for i in a
2490
    ]
2491
end
2492

2493
function _findin(a::Union{AbstractArray, Tuple}, b)
375✔
2494
    ind  = Vector{eltype(keys(a))}()
561✔
2495
    bset = Set(b)
375✔
2496
    @inbounds for (i,ai) in pairs(a)
606✔
2497
        ai in bset && push!(ind, i)
90,524✔
2498
    end
180,565✔
2499
    ind
375✔
2500
end
2501

2502
# If two collections are already sorted, _findin can be computed with
2503
# a single traversal of the two collections. This is much faster than
2504
# using a hash table (although it has the same complexity).
2505
function _sortedfindin(v::Union{AbstractArray, Tuple}, w)
9✔
2506
    viter, witer = keys(v), eachindex(w)
9✔
2507
    out  = eltype(viter)[]
9✔
2508
    vy, wy = iterate(viter), iterate(witer)
17✔
2509
    if vy === nothing || wy === nothing
17✔
2510
        return out
2✔
2511
    end
2512
    viteri, i = vy
7✔
2513
    witerj, j = wy
7✔
2514
    @inbounds begin
7✔
2515
        vi, wj = v[viteri], w[witerj]
7✔
2516
        while true
54✔
2517
            if isless(vi, wj)
56✔
2518
                vy = iterate(viter, i)
25✔
2519
                if vy === nothing
14✔
2520
                    break
2✔
2521
                end
2522
                viteri, i = vy
12✔
2523
                vi        = v[viteri]
12✔
2524
            elseif isless(wj, vi)
40✔
2525
                wy = iterate(witer, j)
44✔
2526
                if wy === nothing
24✔
2527
                    break
4✔
2528
                end
2529
                witerj, j = wy
20✔
2530
                wj        = w[witerj]
20✔
2531
            else
2532
                push!(out, viteri)
16✔
2533
                vy = iterate(viter, i)
25✔
2534
                if vy === nothing
16✔
2535
                    break
1✔
2536
                end
2537
                # We only increment the v iterator because v can have
2538
                # repeated matches to a single value in w
2539
                viteri, i = vy
15✔
2540
                vi        = v[viteri]
15✔
2541
            end
2542
        end
47✔
2543
    end
2544
    return out
7✔
2545
end
2546

2547
function findall(pred::Fix2{typeof(in),<:Union{Array{<:Real},Real}}, x::Array{<:Real})
15✔
2548
    if issorted(x, Sort.Forward) && issorted(pred.x, Sort.Forward)
25✔
2549
        return _sortedfindin(x, pred.x)
9✔
2550
    else
2551
        return _findin(x, pred.x)
6✔
2552
    end
2553
end
2554
# issorted fails for some element types so the method above has to be restricted
2555
# to element with isless/< defined.
2556
findall(pred::Fix2{typeof(in)}, x::AbstractArray) = _findin(x, pred.x)
373✔
2557
findall(pred::Fix2{typeof(in)}, x::Tuple) = _findin(x, pred.x)
×
2558

2559
# Copying subregions
2560
function indcopy(sz::Dims, I::Vector)
1✔
2561
    n = length(I)
1✔
2562
    s = sz[n]
1✔
2563
    for i = n+1:length(sz)
1✔
2564
        s *= sz[i]
×
2565
    end
×
2566
    dst = eltype(I)[_findin(I[i], i < n ? (1:sz[i]) : (1:s)) for i = 1:n]
2✔
2567
    src = eltype(I)[I[i][_findin(I[i], i < n ? (1:sz[i]) : (1:s))] for i = 1:n]
2✔
2568
    dst, src
1✔
2569
end
2570

2571
function indcopy(sz::Dims, I::Tuple{Vararg{RangeIndex}})
1✔
2572
    n = length(I)
1✔
2573
    s = sz[n]
1✔
2574
    for i = n+1:length(sz)
1✔
2575
        s *= sz[i]
×
2576
    end
×
2577
    dst::typeof(I) = ntuple(i-> _findin(I[i], i < n ? (1:sz[i]) : (1:s)), n)::typeof(I)
3✔
2578
    src::typeof(I) = ntuple(i-> I[i][_findin(I[i], i < n ? (1:sz[i]) : (1:s))], n)::typeof(I)
3✔
2579
    dst, src
1✔
2580
end
2581

2582
## Filter ##
2583

2584
"""
2585
    filter(f, a)
2586

2587
Return a copy of collection `a`, removing elements for which `f` is `false`.
2588
The function `f` is passed one argument.
2589

2590
!!! compat "Julia 1.4"
2591
    Support for `a` as a tuple requires at least Julia 1.4.
2592

2593
See also: [`filter!`](@ref), [`Iterators.filter`](@ref).
2594

2595
# Examples
2596
```jldoctest
2597
julia> a = 1:10
2598
1:10
2599

2600
julia> filter(isodd, a)
2601
5-element Vector{Int64}:
2602
 1
2603
 3
2604
 5
2605
 7
2606
 9
2607
```
2608
"""
2609
function filter(f, a::Array{T, N}) where {T, N}
443,758✔
2610
    j = 1
442,920✔
2611
    b = Vector{T}(undef, length(a))
443,757✔
2612
    for ai in a
443,775✔
2613
        @inbounds b[j] = ai
1,396,697✔
2614
        j = ifelse(f(ai)::Bool, j+1, j)
1,401,715✔
2615
    end
1,840,352✔
2616
    resize!(b, j-1)
887,514✔
2617
    sizehint!(b, length(b))
443,758✔
2618
    b
443,758✔
2619
end
2620

2621
function filter(f, a::AbstractArray)
389✔
2622
    (IndexStyle(a) != IndexLinear()) && return a[map(f, a)::AbstractArray{Bool}]
389✔
2623

2624
    j = 1
389✔
2625
    idxs = Vector{Int}(undef, length(a))
392✔
2626
    for idx in eachindex(a)
649✔
2627
        @inbounds idxs[j] = idx
103,590✔
2628
        ai = @inbounds a[idx]
103,590✔
2629
        j = ifelse(f(ai)::Bool, j+1, j)
137,658✔
2630
    end
206,919✔
2631
    resize!(idxs, j-1)
776✔
2632
    res = a[idxs]
388✔
2633
    empty!(idxs)
388✔
2634
    sizehint!(idxs, 0)
388✔
2635
    return res
388✔
2636
end
2637

2638
"""
2639
    filter!(f, a)
2640

2641
Update collection `a`, removing elements for which `f` is `false`.
2642
The function `f` is passed one argument.
2643

2644
# Examples
2645
```jldoctest
2646
julia> filter!(isodd, Vector(1:10))
2647
5-element Vector{Int64}:
2648
 1
2649
 3
2650
 5
2651
 7
2652
 9
2653
```
2654
"""
2655
function filter!(f, a::AbstractVector)
901,044✔
2656
    j = firstindex(a)
707✔
2657
    for ai in a
924,231✔
2658
        @inbounds a[j] = ai
3,266,886✔
2659
        j = ifelse(f(ai)::Bool, nextind(a, j), j)
6,049,195✔
2660
    end
4,144,752✔
2661
    j > lastindex(a) && return a
901,044✔
2662
    if a isa Vector
432✔
2663
        resize!(a, j-1)
332,998✔
2664
        sizehint!(a, j-1)
166,499✔
2665
    else
2666
        deleteat!(a, j:lastindex(a))
1✔
2667
    end
2668
    return a
166,500✔
2669
end
2670

2671
"""
2672
    filter(f)
2673

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

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

2680
# Examples
2681
```jldoctest
2682
julia> (1, 2, Inf, 4, NaN, 6) |> filter(isfinite)
2683
(1, 2, 4, 6)
2684

2685
julia> map(filter(iseven), [1:3, 2:4, 3:5])
2686
3-element Vector{Vector{Int64}}:
2687
 [2]
2688
 [2, 4]
2689
 [4]
2690
```
2691
!!! compat "Julia 1.9"
2692
    This method requires at least Julia 1.9.
2693
"""
2694
function filter(f)
1✔
2695
    Fix1(filter, f)
1✔
2696
end
2697

2698
"""
2699
    keepat!(a::Vector, inds)
2700
    keepat!(a::BitVector, inds)
2701

2702
Remove the items at all the indices which are not given by `inds`,
2703
and return the modified `a`.
2704
Items which are kept are shifted to fill the resulting gaps.
2705

2706
`inds` must be an iterator of sorted and unique integer indices.
2707
See also [`deleteat!`](@ref).
2708

2709
!!! compat "Julia 1.7"
2710
    This function is available as of Julia 1.7.
2711

2712
# Examples
2713
```jldoctest
2714
julia> keepat!([6, 5, 4, 3, 2, 1], 1:2:5)
2715
3-element Vector{Int64}:
2716
 6
2717
 4
2718
 2
2719
```
2720
"""
2721
keepat!(a::Vector, inds) = _keepat!(a, inds)
9✔
2722

2723
"""
2724
    keepat!(a::Vector, m::AbstractVector{Bool})
2725
    keepat!(a::BitVector, m::AbstractVector{Bool})
2726

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

2731
# Examples
2732
```jldoctest
2733
julia> a = [:a, :b, :c];
2734

2735
julia> keepat!(a, [true, false, true])
2736
2-element Vector{Symbol}:
2737
 :a
2738
 :c
2739

2740
julia> a
2741
2-element Vector{Symbol}:
2742
 :a
2743
 :c
2744
```
2745
"""
2746
keepat!(a::Vector, m::AbstractVector{Bool}) = _keepat!(a, m)
4✔
2747

2748
# set-like operators for vectors
2749
# These are moderately efficient, preserve order, and remove dupes.
2750

2751
_unique_filter!(pred::P, update!::U, state) where {P,U} = function (x)
3,724✔
2752
    # P, U force specialization
2753
    if pred(x, state)
9,028✔
2754
        update!(state, x)
3,488✔
2755
        true
3,488✔
2756
    else
2757
        false
5,491✔
2758
    end
2759
end
2760

2761
_grow_filter!(seen) = _unique_filter!(∉, push!, seen)
199✔
2762
_shrink_filter!(keep) = _unique_filter!(∈, pop!, keep)
913✔
2763

2764
function _grow!(pred!, v::AbstractVector, itrs)
207✔
2765
    filter!(pred!, v) # uniquify v
209✔
2766
    for itr in itrs
209✔
2767
        mapfilter(pred!, push!, itr, v)
413✔
2768
    end
616✔
2769
    return v
209✔
2770
end
2771

2772
union!(v::AbstractVector{T}, itrs...) where {T} =
199✔
2773
    _grow!(_grow_filter!(sizehint!(Set{T}(), length(v))), v, itrs)
2774

2775
symdiff!(v::AbstractVector{T}, itrs...) where {T} =
10✔
2776
    _grow!(_shrink_filter!(symdiff!(Set{T}(), v, itrs...)), v, itrs)
2777

2778
function _shrink!(shrinker!::F, v::AbstractVector, itrs) where F
×
2779
    seen = Set{eltype(v)}()
×
2780
    filter!(_grow_filter!(seen), v)
×
2781
    shrinker!(seen, itrs...)
×
2782
    filter!(in(seen), v)
×
2783
end
2784

2785
intersect!(v::AbstractVector, itrs...) = _shrink!(intersect!, v, itrs)
×
2786
setdiff!(  v::AbstractVector, itrs...) = _shrink!(setdiff!, v, itrs)
×
2787

2788
vectorfilter(T::Type, f, v) = T[x for x in v if f(x)]
904✔
2789

2790
function _shrink(shrinker!::F, itr, itrs) where F
845✔
2791
    T = promote_eltype(itr, itrs...)
767✔
2792
    keep = shrinker!(Set{T}(itr), itrs...)
847✔
2793
    vectorfilter(T, _shrink_filter!(keep), itr)
845✔
2794
end
2795

2796
intersect(itr, itrs...) = _shrink(intersect!, itr, itrs)
398✔
2797
setdiff(  itr, itrs...) = _shrink(setdiff!, itr, itrs)
447✔
2798

2799
function intersect(v::AbstractVector, r::AbstractRange)
54✔
2800
    T = promote_eltype(v, r)
2✔
2801
    common = Iterators.filter(in(r), v)
58✔
2802
    seen = Set{T}(common)
58✔
2803
    return vectorfilter(T, _shrink_filter!(seen), common)
58✔
2804
end
2805
intersect(r::AbstractRange, v::AbstractVector) = intersect(v, r)
2✔
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