-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
array.jl
3183 lines (2687 loc) · 83.1 KB
/
array.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is a part of Julia. License is MIT: https://julialang.org/license
## array.jl: Dense arrays
"""
DimensionMismatch([msg])
The objects called do not have matching dimensionality. Optional argument `msg` is a
descriptive error string.
"""
struct DimensionMismatch <: Exception
msg::AbstractString
end
DimensionMismatch() = DimensionMismatch("")
## Type aliases for convenience ##
"""
AbstractVector{T}
Supertype for one-dimensional arrays (or array-like types) with
elements of type `T`. Alias for [`AbstractArray{T,1}`](@ref).
"""
const AbstractVector{T} = AbstractArray{T,1}
"""
AbstractMatrix{T}
Supertype for two-dimensional arrays (or array-like types) with
elements of type `T`. Alias for [`AbstractArray{T,2}`](@ref).
"""
const AbstractMatrix{T} = AbstractArray{T,2}
"""
AbstractVecOrMat{T}
Union type of [`AbstractVector{T}`](@ref) and [`AbstractMatrix{T}`](@ref).
"""
const AbstractVecOrMat{T} = Union{AbstractVector{T}, AbstractMatrix{T}}
const RangeIndex = Union{<:BitInteger, AbstractRange{<:BitInteger}}
const DimOrInd = Union{Integer, AbstractUnitRange}
const IntOrInd = Union{Int, AbstractUnitRange}
const DimsOrInds{N} = NTuple{N,DimOrInd}
const NeedsShaping = Union{Tuple{Integer,Vararg{Integer}}, Tuple{OneTo,Vararg{OneTo}}}
"""
Array{T,N} <: AbstractArray{T,N}
`N`-dimensional dense array with elements of type `T`.
"""
Array
"""
Vector{T} <: AbstractVector{T}
One-dimensional dense array with elements of type `T`, often used to represent
a mathematical vector. Alias for [`Array{T,1}`](@ref).
See also [`empty`](@ref), [`similar`](@ref) and [`zero`](@ref) for creating vectors.
"""
const Vector{T} = Array{T,1}
"""
Matrix{T} <: AbstractMatrix{T}
Two-dimensional dense array with elements of type `T`, often used to represent
a mathematical matrix. Alias for [`Array{T,2}`](@ref).
See also [`fill`](@ref), [`zeros`](@ref), [`undef`](@ref) and [`similar`](@ref)
for creating matrices.
"""
const Matrix{T} = Array{T,2}
"""
VecOrMat{T}
Union type of [`Vector{T}`](@ref) and [`Matrix{T}`](@ref) which allows functions to accept either a Matrix or a Vector.
# Examples
```jldoctest
julia> Vector{Float64} <: VecOrMat{Float64}
true
julia> Matrix{Float64} <: VecOrMat{Float64}
true
julia> Array{Float64, 3} <: VecOrMat{Float64}
false
```
"""
const VecOrMat{T} = Union{Vector{T}, Matrix{T}}
"""
DenseArray{T, N} <: AbstractArray{T,N}
`N`-dimensional dense array with elements of type `T`.
The elements of a dense array are stored contiguously in memory.
"""
DenseArray
"""
DenseVector{T}
One-dimensional [`DenseArray`](@ref) with elements of type `T`. Alias for `DenseArray{T,1}`.
"""
const DenseVector{T} = DenseArray{T,1}
"""
DenseMatrix{T}
Two-dimensional [`DenseArray`](@ref) with elements of type `T`. Alias for `DenseArray{T,2}`.
"""
const DenseMatrix{T} = DenseArray{T,2}
"""
DenseVecOrMat{T}
Union type of [`DenseVector{T}`](@ref) and [`DenseMatrix{T}`](@ref).
"""
const DenseVecOrMat{T} = Union{DenseVector{T}, DenseMatrix{T}}
## Basic functions ##
"""
@_safeindex
This internal macro converts:
- `getindex(xs::Tuple, i::Int)` -> `__safe_getindex(xs, i)`
- `setindex!(xs::Vector{T}, x, i::Int)` -> `__safe_setindex!(xs, x, i)`
to tell the compiler that indexing operations within the applied expression are always
inbounds and do not need to taint `:consistent` and `:nothrow`.
"""
macro _safeindex(ex)
return esc(_safeindex(ex))
end
function _safeindex(ex)
isa(ex, Expr) || return ex
if ex.head === :(=)
lhs = ex.args[1]
if isa(lhs, Expr) && lhs.head === :ref # xs[i] = x
rhs = ex.args[2]
xs = lhs.args[1]
args = Vector{Any}(undef, length(lhs.args)-1)
for i = 2:length(lhs.args)
args[i-1] = _safeindex(lhs.args[i])
end
return Expr(:call, GlobalRef(@__MODULE__, :__safe_setindex!), xs, _safeindex(rhs), args...)
end
elseif ex.head === :ref # xs[i]
return Expr(:call, GlobalRef(@__MODULE__, :__safe_getindex), ex.args...)
end
args = Vector{Any}(undef, length(ex.args))
for i = 1:length(ex.args)
args[i] = _safeindex(ex.args[i])
end
return Expr(ex.head, args...)
end
vect() = Vector{Any}()
function vect(X::T...) where T
@_terminates_locally_meta
vec = Vector{T}(undef, length(X))
@_safeindex for i = 1:length(X)
vec[i] = X[i]
end
return vec
end
"""
vect(X...)
Create a [`Vector`](@ref) with element type computed from the `promote_typeof` of the argument,
containing the argument list.
# Examples
```jldoctest
julia> a = Base.vect(UInt8(1), 2.5, 1//2)
3-element Vector{Float64}:
1.0
2.5
0.5
```
"""
function vect(X...)
T = promote_typeof(X...)
return T[X...]
end
size(a::Array, d::Integer) = size(a, Int(d)::Int)
function size(a::Array, d::Int)
d < 1 && error("arraysize: dimension out of range")
sz = getfield(a, :size)
return d > length(sz) ? 1 : getfield(sz, d, false) # @inbounds
end
size(a::Array) = getfield(a, :size)
asize_from(a::Array, n) = n > ndims(a) ? () : (size(a,n), asize_from(a, n+1)...)
allocatedinline(@nospecialize T::Type) = (@_total_meta; ccall(:jl_stored_inline, Cint, (Any,), T) != Cint(0))
"""
Base.isbitsunion(::Type{T})
Return whether a type is an "is-bits" Union type, meaning each type included in a Union is [`isbitstype`](@ref).
# Examples
```jldoctest
julia> Base.isbitsunion(Union{Float64, UInt8})
true
julia> Base.isbitsunion(Union{Float64, String})
false
```
"""
isbitsunion(u::Type) = u isa Union && allocatedinline(u)
function _unsetindex!(A::Array, i::Int)
@inline
@boundscheck checkbounds(A, i)
@inbounds _unsetindex!(memoryref(A.ref, i))
return A
end
# TODO: deprecate this (aligned_sizeof and/or elsize and/or sizeof(Some{T}) are more correct)
elsize(::Type{A}) where {T,A<:Array{T}} = aligned_sizeof(T)
function elsize(::Type{Ptr{T}}) where T
# this only must return something valid for values which satisfy is_valid_intrinsic_elptr(T),
# which includes Any and most concrete datatypes
T === Any && return sizeof(Ptr{Any})
T isa DataType || sizeof(Any) # throws
return LLT_ALIGN(Core.sizeof(T), datatype_alignment(T))
end
elsize(::Type{Union{}}, slurp...) = 0
sizeof(a::Array) = length(a) * elsize(typeof(a)) # n.b. this ignores bitsunion bytes, as a historical fact
function isassigned(a::Array, i::Int...)
@inline
@_noub_if_noinbounds_meta
@boundscheck checkbounds(Bool, a, i...) || return false
ii = _sub2ind(size(a), i...)
return @inbounds isassigned(memoryrefnew(a.ref, ii, false))
end
function isassigned(a::Vector, i::Int) # slight compiler simplification for the most common case
@inline
@_noub_if_noinbounds_meta
@boundscheck checkbounds(Bool, a, i) || return false
return @inbounds isassigned(memoryrefnew(a.ref, i, false))
end
## copy ##
"""
unsafe_copyto!(dest::Ptr{T}, src::Ptr{T}, N)
Copy `N` elements from a source pointer to a destination, with no checking. The size of an
element is determined by the type of the pointers.
The `unsafe` prefix on this function indicates that no validation is performed on the
pointers `dest` and `src` to ensure that they are valid. Incorrect usage may corrupt or
segfault your program, in the same manner as C.
"""
function unsafe_copyto!(dest::Ptr{T}, src::Ptr{T}, n) where T
# Do not use this to copy data between pointer arrays.
# It can't be made safe no matter how carefully you checked.
memmove(dest, src, n * aligned_sizeof(T))
return dest
end
"""
unsafe_copyto!(dest::Array, doffs, src::Array, soffs, n)
Copy `n` elements from a source array to a destination, starting at the linear index `soffs` in the
source and `doffs` in the destination (1-indexed).
The `unsafe` prefix on this function indicates that no validation is performed to ensure
that n is inbounds on either array. Incorrect usage may corrupt or segfault your program, in
the same manner as C.
"""
function unsafe_copyto!(dest::Array, doffs, src::Array, soffs, n)
n == 0 && return dest
unsafe_copyto!(memoryref(dest.ref, doffs), memoryref(src.ref, soffs), n)
return dest
end
"""
copyto!(dest, doffs, src, soffs, n)
Copy `n` elements from collection `src` starting at the linear index `soffs`, to array `dest` starting at
the index `doffs`. Return `dest`.
"""
copyto!(dest::Array, doffs::Integer, src::Array, soffs::Integer, n::Integer) = _copyto_impl!(dest, doffs, src, soffs, n)
copyto!(dest::Array, doffs::Integer, src::Memory, soffs::Integer, n::Integer) = _copyto_impl!(dest, doffs, src, soffs, n)
copyto!(dest::Memory, doffs::Integer, src::Array, soffs::Integer, n::Integer) = _copyto_impl!(dest, doffs, src, soffs, n)
# this is only needed to avoid possible ambiguities with methods added in some packages
copyto!(dest::Array{T}, doffs::Integer, src::Array{T}, soffs::Integer, n::Integer) where {T} = _copyto_impl!(dest, doffs, src, soffs, n)
function _copyto_impl!(dest::Union{Array,Memory}, doffs::Integer, src::Union{Array,Memory}, soffs::Integer, n::Integer)
n == 0 && return dest
n > 0 || _throw_argerror("Number of elements to copy must be non-negative.")
@boundscheck checkbounds(dest, doffs:doffs+n-1)
@boundscheck checkbounds(src, soffs:soffs+n-1)
@inbounds let dest = memoryref(dest isa Array ? getfield(dest, :ref) : dest, doffs),
src = memoryref(src isa Array ? getfield(src, :ref) : src, soffs)
unsafe_copyto!(dest, src, n)
end
return dest
end
# Outlining this because otherwise a catastrophic inference slowdown
# occurs, see discussion in #27874.
# It is also mitigated by using a constant string.
_throw_argerror(s) = (@noinline; throw(ArgumentError(s)))
copyto!(dest::Array, src::Array) = copyto!(dest, 1, src, 1, length(src))
# also to avoid ambiguities in packages
copyto!(dest::Array{T}, src::Array{T}) where {T} = copyto!(dest, 1, src, 1, length(src))
# N.B: The generic definition in multidimensional.jl covers, this, this is just here
# for bootstrapping purposes.
function fill!(dest::Array{T}, x) where T
@inline
x = x isa T ? x : convert(T, x)::T
return _fill!(dest, x)
end
function _fill!(dest::Array{T}, x::T) where T
for i in eachindex(dest)
@inbounds dest[i] = x
end
return dest
end
"""
copy(x)
Create a shallow copy of `x`: the outer structure is copied, but not all internal values.
For example, copying an array produces a new array with identically-same elements as the
original.
See also [`copy!`](@ref Base.copy!), [`copyto!`](@ref), [`deepcopy`](@ref).
"""
copy
@eval function copy(a::Array{T}) where {T}
# `jl_genericmemory_copy_slice` only throws when the size exceeds the max allocation
# size, but since we're copying an existing array, we're guaranteed that this will not happen.
@_nothrow_meta
ref = a.ref
newmem = ccall(:jl_genericmemory_copy_slice, Ref{Memory{T}}, (Any, Ptr{Cvoid}, Int), ref.mem, ref.ptr_or_offset, length(a))
return $(Expr(:new, :(typeof(a)), :(memoryref(newmem)), :(a.size)))
end
# a mutating version of copyto! that results in dst aliasing src afterwards
function _take!(dst::Array{T,N}, src::Array{T,N}) where {T,N}
if getfield(dst, :ref) !== getfield(src, :ref)
setfield!(dst, :ref, getfield(src, :ref))
end
if getfield(dst, :size) !== getfield(src, :size)
setfield!(dst, :size, getfield(src, :size))
end
return dst
end
## Constructors ##
similar(a::Array{T,1}) where {T} = Vector{T}(undef, size(a,1))
similar(a::Array{T,2}) where {T} = Matrix{T}(undef, size(a,1), size(a,2))
similar(a::Array{T,1}, S::Type) where {T} = Vector{S}(undef, size(a,1))
similar(a::Array{T,2}, S::Type) where {T} = Matrix{S}(undef, size(a,1), size(a,2))
similar(a::Array{T}, m::Int) where {T} = Vector{T}(undef, m)
similar(a::Array, T::Type, dims::Dims{N}) where {N} = Array{T,N}(undef, dims)
similar(a::Array{T}, dims::Dims{N}) where {T,N} = Array{T,N}(undef, dims)
# T[x...] constructs Array{T,1}
"""
getindex(type[, elements...])
Construct a 1-d array of the specified type. This is usually called with the syntax
`Type[]`. Element values can be specified using `Type[a,b,c,...]`.
# Examples
```jldoctest
julia> Int8[1, 2, 3]
3-element Vector{Int8}:
1
2
3
julia> getindex(Int8, 1, 2, 3)
3-element Vector{Int8}:
1
2
3
```
"""
function getindex(::Type{T}, vals...) where T
@inline
@_effect_free_terminates_locally_meta
a = Vector{T}(undef, length(vals))
if vals isa NTuple
@_safeindex for i in 1:length(vals)
a[i] = vals[i]
end
else
# use afoldl to avoid type instability inside loop
afoldl(1, vals...) do i, v
@inbounds a[i] = v
return i + 1
end
end
return a
end
function getindex(::Type{Any}, @nospecialize vals...)
@_effect_free_terminates_locally_meta
a = Vector{Any}(undef, length(vals))
@_safeindex for i = 1:length(vals)
a[i] = vals[i]
end
return a
end
getindex(::Type{Any}) = Vector{Any}()
function fill!(a::Union{Array{UInt8}, Array{Int8}}, x::Integer)
ref = a.ref
t = @_gc_preserve_begin ref
p = unsafe_convert(Ptr{Cvoid}, ref)
memset(p, x isa eltype(a) ? x : convert(eltype(a), x), length(a) % UInt)
@_gc_preserve_end t
return a
end
to_dim(d::Integer) = d
to_dim(d::OneTo) = last(d)
"""
fill(value, dims::Tuple)
fill(value, dims...)
Create an array of size `dims` with every location set to `value`.
For example, `fill(1.0, (5,5))` returns a 5×5 array of floats,
with `1.0` in every location of the array.
The dimension lengths `dims` may be specified as either a tuple or a sequence of arguments.
An `N`-length tuple or `N` arguments following the `value` specify an `N`-dimensional
array. Thus, a common idiom for creating a zero-dimensional array with its only location
set to `x` is `fill(x)`.
Every location of the returned array is set to (and is thus [`===`](@ref) to)
the `value` that was passed; this means that if the `value` is itself modified,
all elements of the `fill`ed array will reflect that modification because they're
_still_ that very `value`. This is of no concern with `fill(1.0, (5,5))` as the
`value` `1.0` is immutable and cannot itself be modified, but can be unexpected
with mutable values like — most commonly — arrays. For example, `fill([], 3)`
places _the very same_ empty array in all three locations of the returned vector:
```jldoctest
julia> v = fill([], 3)
3-element Vector{Vector{Any}}:
[]
[]
[]
julia> v[1] === v[2] === v[3]
true
julia> value = v[1]
Any[]
julia> push!(value, 867_5309)
1-element Vector{Any}:
8675309
julia> v
3-element Vector{Vector{Any}}:
[8675309]
[8675309]
[8675309]
```
To create an array of many independent inner arrays, use a [comprehension](@ref man-comprehensions) instead.
This creates a new and distinct array on each iteration of the loop:
```jldoctest
julia> v2 = [[] for _ in 1:3]
3-element Vector{Vector{Any}}:
[]
[]
[]
julia> v2[1] === v2[2] === v2[3]
false
julia> push!(v2[1], 8675309)
1-element Vector{Any}:
8675309
julia> v2
3-element Vector{Vector{Any}}:
[8675309]
[]
[]
```
See also: [`fill!`](@ref), [`zeros`](@ref), [`ones`](@ref), [`similar`](@ref).
# Examples
```jldoctest
julia> fill(1.0, (2,3))
2×3 Matrix{Float64}:
1.0 1.0 1.0
1.0 1.0 1.0
julia> fill(42)
0-dimensional Array{Int64, 0}:
42
julia> A = fill(zeros(2), 2) # sets both elements to the same [0.0, 0.0] vector
2-element Vector{Vector{Float64}}:
[0.0, 0.0]
[0.0, 0.0]
julia> A[1][1] = 42; # modifies the filled value to be [42.0, 0.0]
julia> A # both A[1] and A[2] are the very same vector
2-element Vector{Vector{Float64}}:
[42.0, 0.0]
[42.0, 0.0]
```
"""
function fill end
fill(v, dims::DimOrInd...) = fill(v, dims)
fill(v, dims::NTuple{N, Union{Integer, OneTo}}) where {N} = fill(v, map(to_dim, dims))
fill(v, dims::NTuple{N, Integer}) where {N} = (a=Array{typeof(v),N}(undef, dims); fill!(a, v); a)
fill(v, dims::NTuple{N, DimOrInd}) where {N} = (a=similar(Array{typeof(v),N}, dims); fill!(a, v); a)
fill(v, dims::Tuple{}) = (a=Array{typeof(v),0}(undef, dims); fill!(a, v); a)
"""
zeros([T=Float64,] dims::Tuple)
zeros([T=Float64,] dims...)
Create an `Array`, with element type `T`, of all zeros with size specified by `dims`.
See also [`fill`](@ref), [`ones`](@ref), [`zero`](@ref).
# Examples
```jldoctest
julia> zeros(1)
1-element Vector{Float64}:
0.0
julia> zeros(Int8, 2, 3)
2×3 Matrix{Int8}:
0 0 0
0 0 0
```
"""
function zeros end
"""
ones([T=Float64,] dims::Tuple)
ones([T=Float64,] dims...)
Create an `Array`, with element type `T`, of all ones with size specified by `dims`.
See also [`fill`](@ref), [`zeros`](@ref).
# Examples
```jldoctest
julia> ones(1,2)
1×2 Matrix{Float64}:
1.0 1.0
julia> ones(ComplexF64, 2, 3)
2×3 Matrix{ComplexF64}:
1.0+0.0im 1.0+0.0im 1.0+0.0im
1.0+0.0im 1.0+0.0im 1.0+0.0im
```
"""
function ones end
for (fname, felt) in ((:zeros, :zero), (:ones, :one))
@eval begin
$fname(dims::DimOrInd...) = $fname(dims)
$fname(::Type{T}, dims::DimOrInd...) where {T} = $fname(T, dims)
$fname(dims::Tuple{Vararg{DimOrInd}}) = $fname(Float64, dims)
$fname(::Type{T}, dims::NTuple{N, Union{Integer, OneTo}}) where {T,N} = $fname(T, map(to_dim, dims))
function $fname(::Type{T}, dims::NTuple{N, Integer}) where {T,N}
a = Array{T,N}(undef, dims)
fill!(a, $felt(T))
return a
end
function $fname(::Type{T}, dims::Tuple{}) where {T}
a = Array{T}(undef)
fill!(a, $felt(T))
return a
end
function $fname(::Type{T}, dims::NTuple{N, DimOrInd}) where {T,N}
a = similar(Array{T,N}, dims)
fill!(a, $felt(T))
return a
end
end
end
## Conversions ##
convert(::Type{T}, a::AbstractArray) where {T<:Array} = a isa T ? a : T(a)::T
promote_rule(a::Type{Array{T,n}}, b::Type{Array{S,n}}) where {T,n,S} = el_same(promote_type(T,S), a, b)
## Constructors ##
# constructors should make copies
Array{T,N}(x::AbstractArray{S,N}) where {T,N,S} = copyto_axcheck!(Array{T,N}(undef, size(x)), x)
AbstractArray{T,N}(A::AbstractArray{S,N}) where {T,N,S} = copyto_axcheck!(similar(A,T), A)
## copying iterators to containers
"""
collect(element_type, collection)
Return an `Array` with the given element type of all items in a collection or iterable.
The result has the same shape and number of dimensions as `collection`.
# Examples
```jldoctest
julia> collect(Float64, 1:2:5)
3-element Vector{Float64}:
1.0
3.0
5.0
```
"""
collect(::Type{T}, itr) where {T} = _collect(T, itr, IteratorSize(itr))
_collect(::Type{T}, itr, isz::Union{HasLength,HasShape}) where {T} =
copyto!(_array_for(T, isz, _similar_shape(itr, isz)), itr)
function _collect(::Type{T}, itr, isz::SizeUnknown) where T
a = Vector{T}()
for x in itr
push!(a, x)
end
return a
end
# make a collection similar to `c` and appropriate for collecting `itr`
_similar_for(c, ::Type{T}, itr, isz, shp) where {T} = similar(c, T)
_similar_shape(itr, ::SizeUnknown) = nothing
_similar_shape(itr, ::HasLength) = length(itr)::Integer
_similar_shape(itr, ::HasShape) = axes(itr)
_similar_for(c::AbstractArray, ::Type{T}, itr, ::SizeUnknown, ::Nothing) where {T} =
similar(c, T, 0)
_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasLength, len::Integer) where {T} =
similar(c, T, len)
_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasShape, axs) where {T} =
similar(c, T, axs)
# make a collection appropriate for collecting `itr::Generator`
_array_for(::Type{T}, ::SizeUnknown, ::Nothing) where {T} = Vector{T}(undef, 0)
_array_for(::Type{T}, ::HasLength, len::Integer) where {T} = Vector{T}(undef, Int(len))
_array_for(::Type{T}, ::HasShape{N}, axs) where {T,N} = similar(Array{T,N}, axs)
# used by syntax lowering for simple typed comprehensions
_array_for(::Type{T}, itr, isz) where {T} = _array_for(T, isz, _similar_shape(itr, isz))
"""
collect(iterator)
Return an `Array` of all items in a collection or iterator. For dictionaries, returns
a `Vector` of `key=>value` [Pair](@ref Pair)s. If the argument is array-like or is an iterator
with the [`HasShape`](@ref IteratorSize) trait, the result will have the same shape
and number of dimensions as the argument.
Used by [comprehensions](@ref man-comprehensions) to turn a [generator expression](@ref man-generators)
into an `Array`. Thus, *on generators*, the square-brackets notation may be used instead of calling `collect`,
see second example.
The element type of the returned array is based on the types of the values collected. However, if the
iterator is empty then the element type of the returned (empty) array is determined by type inference.
# Examples
Collect items from a `UnitRange{Int64}` collection:
```jldoctest
julia> collect(1:3)
3-element Vector{Int64}:
1
2
3
```
Collect items from a generator (same output as `[x^2 for x in 1:3]`):
```jldoctest
julia> collect(x^2 for x in 1:3)
3-element Vector{Int64}:
1
4
9
```
Collecting an empty iterator where the result type depends on type inference:
```jldoctest
julia> [rand(Bool) ? 1 : missing for _ in []]
Union{Missing, Int64}[]
```
When the iterator is non-empty, the result type depends only on values:
```julia-repl
julia> [rand(Bool) ? 1 : missing for _ in [""]]
1-element Vector{Int64}:
1
```
"""
collect(itr) = _collect(1:1 #= Array =#, itr, IteratorEltype(itr), IteratorSize(itr))
collect(A::AbstractArray) = _collect_indices(axes(A), A)
collect_similar(cont, itr) = _collect(cont, itr, IteratorEltype(itr), IteratorSize(itr))
_collect(cont, itr, ::HasEltype, isz::Union{HasLength,HasShape}) =
copyto!(_similar_for(cont, eltype(itr), itr, isz, _similar_shape(itr, isz)), itr)
function _collect(cont, itr, ::HasEltype, isz::SizeUnknown)
a = _similar_for(cont, eltype(itr), itr, isz, nothing)
for x in itr
push!(a,x)
end
return a
end
_collect_indices(::Tuple{}, A) = copyto!(Array{eltype(A),0}(undef), A)
_collect_indices(indsA::Tuple{Vararg{OneTo}}, A) =
copyto!(Array{eltype(A)}(undef, length.(indsA)), A)
function _collect_indices(indsA, A)
B = Array{eltype(A)}(undef, length.(indsA))
copyto!(B, CartesianIndices(axes(B)), A, CartesianIndices(indsA))
end
# NOTE: this function is not meant to be called, only inferred, for the
# purpose of bounding the types of values generated by an iterator.
function _iterator_upper_bound(itr)
x = iterate(itr)
while x !== nothing
val = getfield(x, 1)
if inferencebarrier(nothing)
return val
end
x = iterate(itr, getfield(x, 2))
end
throw(nothing)
end
# define this as a macro so that the call to Core.Compiler
# gets inlined into the caller before recursion detection
# gets a chance to see it, so that recursive calls to the caller
# don't trigger the inference limiter
macro default_eltype(itr)
I = esc(itr)
return quote
if $I isa Generator && ($I).f isa Type
T = ($I).f
else
T = Base._return_type(_iterator_upper_bound, Tuple{typeof($I)})
end
promote_typejoin_union(T)
end
end
function collect(itr::Generator)
isz = IteratorSize(itr.iter)
et = @default_eltype(itr)
if isa(isz, SizeUnknown)
return grow_to!(Vector{et}(), itr)
else
shp = _similar_shape(itr, isz)
y = iterate(itr)
if y === nothing
return _array_for(et, isz, shp)
end
v1, st = y
dest = _array_for(typeof(v1), isz, shp)
# The typeassert gives inference a helping hand on the element type and dimensionality
# (work-around for #28382)
et′ = et <: Type ? Type : et
RT = dest isa AbstractArray ? AbstractArray{<:et′, ndims(dest)} : Any
collect_to_with_first!(dest, v1, itr, st)::RT
end
end
_collect(c, itr, ::EltypeUnknown, isz::SizeUnknown) =
grow_to!(_similar_for(c, @default_eltype(itr), itr, isz, nothing), itr)
function _collect(c, itr, ::EltypeUnknown, isz::Union{HasLength,HasShape})
et = @default_eltype(itr)
shp = _similar_shape(itr, isz)
y = iterate(itr)
if y === nothing
return _similar_for(c, et, itr, isz, shp)
end
v1, st = y
dest = _similar_for(c, typeof(v1), itr, isz, shp)
# The typeassert gives inference a helping hand on the element type and dimensionality
# (work-around for #28382)
et′ = et <: Type ? Type : et
RT = dest isa AbstractArray ? AbstractArray{<:et′, ndims(dest)} : Any
collect_to_with_first!(dest, v1, itr, st)::RT
end
function collect_to_with_first!(dest::AbstractArray, v1, itr, st)
i1 = first(LinearIndices(dest))
dest[i1] = v1
return collect_to!(dest, itr, i1+1, st)
end
function collect_to_with_first!(dest, v1, itr, st)
push!(dest, v1)
return grow_to!(dest, itr, st)
end
function setindex_widen_up_to(dest::AbstractArray{T}, el, i) where T
@inline
new = similar(dest, promote_typejoin(T, typeof(el)))
f = first(LinearIndices(dest))
copyto!(new, first(LinearIndices(new)), dest, f, i-f)
@inbounds new[i] = el
return new
end
function collect_to!(dest::AbstractArray{T}, itr, offs, st) where T
# collect to dest array, checking the type of each result. if a result does not
# match, widen the result type and re-dispatch.
i = offs
while true
y = iterate(itr, st)
y === nothing && break
el, st = y
if el isa T
@inbounds dest[i] = el
i += 1
else
new = setindex_widen_up_to(dest, el, i)
return collect_to!(new, itr, i+1, st)
end
end
return dest
end
function grow_to!(dest, itr)
y = iterate(itr)
y === nothing && return dest
dest2 = empty(dest, typeof(y[1]))
push!(dest2, y[1])
grow_to!(dest2, itr, y[2])
end
function push_widen(dest, el)
@inline
new = sizehint!(empty(dest, promote_typejoin(eltype(dest), typeof(el))), length(dest))
if new isa AbstractSet
# TODO: merge back these two branches when copy! is re-enabled for sets/vectors
union!(new, dest)
else
append!(new, dest)
end
push!(new, el)
return new
end
function grow_to!(dest, itr, st)
T = eltype(dest)
y = iterate(itr, st)
while y !== nothing
el, st = y
if el isa T
push!(dest, el)
else
new = push_widen(dest, el)
return grow_to!(new, itr, st)
end
y = iterate(itr, st)
end
return dest
end
## Iteration ##
iterate(A::Array, i=1) = (@inline; (i - 1)%UInt < length(A)%UInt ? (@inbounds A[i], i + 1) : nothing)
## Indexing: getindex ##
"""
getindex(collection, key...)
Retrieve the value(s) stored at the given key or index within a collection. The syntax
`a[i,j,...]` is converted by the compiler to `getindex(a, i, j, ...)`.
See also [`get`](@ref), [`keys`](@ref), [`eachindex`](@ref).
# Examples
```jldoctest
julia> A = Dict("a" => 1, "b" => 2)
Dict{String, Int64} with 2 entries:
"b" => 2
"a" => 1
julia> getindex(A, "a")
1
```
"""
function getindex end
function getindex(A::Array, i1::Int, i2::Int, I::Int...)
@inline
@boundscheck checkbounds(A, i1, i2, I...) # generally _to_linear_index requires bounds checking
return @inbounds A[_to_linear_index(A, i1, i2, I...)]
end
# Faster contiguous indexing using copyto! for AbstractUnitRange and Colon
function getindex(A::Array, I::AbstractUnitRange{<:Integer})
@inline
@boundscheck checkbounds(A, I)
lI = length(I)
X = similar(A, axes(I))
if lI > 0
copyto!(X, firstindex(X), A, first(I), lI)
end
return X
end
# getindex for carrying out logical indexing for AbstractUnitRange{Bool} as Bool <: Integer
getindex(a::Array, r::AbstractUnitRange{Bool}) = getindex(a, to_index(r))
function getindex(A::Array, c::Colon)
lI = length(A)
X = similar(A, lI)
if lI > 0
unsafe_copyto!(X, 1, A, 1, lI)
end
return X
end
# This is redundant with the abstract fallbacks, but needed for bootstrap
function getindex(A::Array{S}, I::AbstractRange{Int}) where S
return S[ A[i] for i in I ]
end
## Indexing: setindex! ##
"""
setindex!(collection, value, key...)
Store the given value at the given key or index within a collection. The syntax `a[i,j,...] =
x` is converted by the compiler to `(setindex!(a, x, i, j, ...); x)`.
# Examples
```jldoctest
julia> a = Dict("a"=>1)
Dict{String, Int64} with 1 entry:
"a" => 1
julia> setindex!(a, 2, "b")
Dict{String, Int64} with 2 entries:
"b" => 2
"a" => 1
```
"""
function setindex! end
function setindex!(A::Array{T}, x, i::Int) where {T}
@_propagate_inbounds_meta
x = x isa T ? x : convert(T, x)::T
return _setindex!(A, x, i)
end
function _setindex!(A::Array{T}, x::T, i::Int) where {T}
@_noub_if_noinbounds_meta
@boundscheck (i - 1)%UInt < length(A)%UInt || throw_boundserror(A, (i,))
memoryrefset!(memoryrefnew(A.ref, i, false), x, :not_atomic, false)
return A
end
function setindex!(A::Array{T}, x, i1::Int, i2::Int, I::Int...) where {T}
@_propagate_inbounds_meta
x = x isa T ? x : convert(T, x)::T
return _setindex!(A, x, i1, i2, I...)
end
function _setindex!(A::Array{T}, x::T, i1::Int, i2::Int, I::Int...) where {T}
@inline
@_noub_if_noinbounds_meta