forked from crystal-lang/crystal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray.cr
2158 lines (1927 loc) · 56.6 KB
/
array.cr
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
# An `Array` is an ordered, integer-indexed collection of objects of type T.
#
# Array indexing starts at 0. A negative index is assumed to be
# relative to the end of the array: -1 indicates the last element,
# -2 is the next to last element, and so on.
#
# An `Array` can be created using the usual `new` method (several are provided), or with an array literal:
#
# ```
# Array(Int32).new # => []
# [1, 2, 3] # Array(Int32)
# [1, "hello", 'x'] # Array(Int32 | String | Char)
# ```
#
# See [`Array` literals](https://crystal-lang.org/reference/syntax_and_semantics/literals/array.html) in the language reference.
#
# An `Array` can have mixed types, meaning T will be a union of types, but these are determined
# when the array is created, either by specifying T or by using an array literal. In the latter
# case, T will be set to the union of the array literal elements' types.
#
# When creating an empty array you must always specify T:
#
# ```
# [] of Int32 # same as Array(Int32)
# [] # syntax error
# ```
#
# An `Array` is implemented using an internal buffer of some capacity
# and is reallocated when elements are pushed to it when more capacity
# is needed. This is normally known as a [dynamic array](http://en.wikipedia.org/wiki/Dynamic_array).
#
# You can use a special array literal syntax with other types too, as long as they define an argless
# `new` method and a `<<` method. `Set` is one such type:
#
# ```
# set = Set{1, 2, 3} # => Set{1, 2, 3}
# set.class # => Set(Int32)
# ```
#
# The above is the same as this:
#
# ```
# set = Set(typeof(1, 2, 3)).new
# set << 1
# set << 2
# set << 3
# ```
class Array(T)
include Indexable::Mutable(T)
include Comparable(Array)
# Size of an Array that we consider small to do linear scans or other optimizations.
private SMALL_ARRAY_SIZE = 16
# The size of this array.
@size : Int32
# The capacity of `@buffer`.
# Note that, because `@buffer` moves on shift, the actual
# capacity (the allocated memory) starts at `@buffer - @offset_to_buffer`.
# The actual capacity is also given by the `remaining_capacity` internal method.
@capacity : Int32
# Offset to the buffer that was originally allocated, and which needs to
# be reallocated on resize. On shift this value gets increased, together with
# `@buffer`. To reach the root buffer you have to do `@buffer - @offset_to_buffer`,
# and this is also provided by the `root_buffer` internal method.
@offset_to_buffer : Int32 = 0
# The buffer where elements start.
@buffer : Pointer(T)
# In 64 bits the Array is composed then by:
# - type_id : Int32 # 4 bytes -|
# - size : Int32 # 4 bytes |- packed as 8 bytes
#
# - capacity : Int32 # 4 bytes -|
# - offset_to_buffer : Int32 # 4 bytes |- packed as 8 bytes
#
# - buffer : Pointer # 8 bytes |- another 8 bytes
#
# So in total 24 bytes. Without offset_to_buffer it's the same,
# because of aligning to 8 bytes (at least in 64 bits), and that's
# why we chose to include this value, because with it we can optimize
# `shift` to let Array be used as a queue/deque.
# Creates a new empty `Array`.
def initialize
@size = 0
@capacity = 0
@buffer = Pointer(T).null
end
# Creates a new empty `Array` backed by a buffer that is initially
# `initial_capacity` big.
#
# The *initial_capacity* is useful to avoid unnecessary reallocations
# of the internal buffer in case of growth. If you have an estimate
# of the maximum number of elements an array will hold, the array should
# be initialized with that capacity for improved performance.
#
# ```
# ary = Array(Int32).new(5)
# ary.size # => 0
# ```
def initialize(initial_capacity : Int)
if initial_capacity < 0
raise ArgumentError.new("Negative array size: #{initial_capacity}")
end
@size = 0
@capacity = initial_capacity.to_i
if initial_capacity == 0
@buffer = Pointer(T).null
else
@buffer = Pointer(T).malloc(initial_capacity)
end
end
# Creates a new `Array` of the given *size* filled with the same *value* in each position.
#
# ```
# Array.new(3, 'a') # => ['a', 'a', 'a']
#
# ary = Array.new(3, [1])
# ary # => [[1], [1], [1]]
# ary[0][0] = 2
# ary # => [[2], [2], [2]]
# ```
def initialize(size : Int, value : T)
if size < 0
raise ArgumentError.new("Negative array size: #{size}")
end
@size = size.to_i
@capacity = size.to_i
if size == 0
@buffer = Pointer(T).null
else
@buffer = Pointer(T).malloc(size, value)
end
end
# Creates a new `Array` of the given *size* and invokes the given block once
# for each index of `self`, assigning the block's value in that index.
#
# ```
# Array.new(3) { |i| (i + 1) ** 2 } # => [1, 4, 9]
#
# ary = Array.new(3) { [1] }
# ary # => [[1], [1], [1]]
# ary[0][0] = 2
# ary # => [[2], [1], [1]]
# ```
def self.new(size : Int, & : Int32 -> T)
Array(T).build(size) do |buffer|
size.to_i.times do |i|
buffer[i] = yield i
end
size
end
end
# Creates a new `Array`, allocating an internal buffer with the given *capacity*,
# and yielding that buffer. The given block must return the desired size of the array.
#
# This method is **unsafe**, but is usually used to initialize the buffer
# by passing it to a C function.
#
# ```
# Array.build(3) do |buffer|
# LibSome.fill_buffer_and_return_number_of_elements_filled(buffer)
# end
# ```
def self.build(capacity : Int, & : Pointer(T) ->) : self
ary = Array(T).new(capacity)
ary.size = (yield ary.to_unsafe).to_i
ary
end
# :nodoc:
#
# This method is used by LiteralExpander to efficiently create an Array
# instance from a literal.
def self.unsafe_build(capacity : Int) : self
ary = Array(T).new(capacity)
ary.size = capacity
ary
end
# Returns the number of elements in the array.
#
# ```
# [:foo, :bar].size # => 2
# ```
getter size : Int32
# Equality. Returns `true` if each element in `self` is equal to each
# corresponding element in *other*.
#
# ```
# ary = [1, 2, 3]
# ary == [1, 2, 3] # => true
# ary == [2, 3] # => false
# ```
def ==(other : Array)
equals?(other) { |x, y| x == y }
end
def ==(other)
false
end
# Combined comparison operator.
#
# Returns `-1`, `0` or `1` depending on whether `self` is less than *other*, equals *other*
# or is greater than *other*.
#
# It compares the elements of both arrays in the same position using the
# `<=>` operator. As soon as one of such comparisons returns a non-zero
# value, that result is the return value of the comparison.
#
# If all elements are equal, the comparison is based on the size of the arrays.
#
# ```
# [8] <=> [1, 2, 3] # => 1
# [2] <=> [4, 2, 3] # => -1
# [1, 2] <=> [1, 2] # => 0
# ```
def <=>(other : Array)
min_size = Math.min(size, other.size)
0.upto(min_size - 1) do |i|
n = @buffer[i] <=> other.to_unsafe[i]
return n if n != 0
end
size <=> other.size
end
# Set intersection: returns a new `Array` containing elements common to `self`
# and *other*, excluding any duplicates. The order is preserved from `self`.
#
# ```
# [1, 1, 3, 5] & [1, 2, 3] # => [ 1, 3 ]
# ['a', 'b', 'b', 'z'] & ['a', 'b', 'c'] # => [ 'a', 'b' ]
# ```
#
# See also: `#uniq`.
def &(other : Array(U)) forall U
return Array(T).new if self.empty? || other.empty?
# Heuristic: for small arrays we do a linear scan, which is usually
# faster than creating an intermediate Hash.
if self.size + other.size <= SMALL_ARRAY_SIZE * 2
ary = Array(T).new
each do |elem|
ary << elem if !ary.includes?(elem) && other.includes?(elem)
end
return ary
end
hash = other.to_lookup_hash
hash_size = hash.size
Array(T).build(Math.min(size, other.size)) do |buffer|
i = 0
each do |obj|
hash.delete(obj)
new_hash_size = hash.size
if hash_size != new_hash_size
hash_size = new_hash_size
buffer[i] = obj
i += 1
end
end
i
end
end
# Set union: returns a new `Array` by joining `self` with *other*, excluding
# any duplicates, and preserving the order from `self`.
#
# ```
# ["a", "b", "c"] | ["c", "d", "a"] # => [ "a", "b", "c", "d" ]
# ```
#
# See also: `#uniq`.
def |(other : Array(U)) forall U
# Heuristic: if the combined size is small we just do a linear scan
# instead of using a Hash for lookup.
if size + other.size <= SMALL_ARRAY_SIZE
ary = Array(T | U).new
each do |elem|
ary << elem unless ary.includes?(elem)
end
other.each do |elem|
ary << elem unless ary.includes?(elem)
end
return ary
end
Array(T | U).build(size + other.size) do |buffer|
hash = Hash(T, Bool).new
i = 0
each do |obj|
unless hash.has_key?(obj)
buffer[i] = obj
hash[obj] = true
i += 1
end
end
other.each do |obj|
unless hash.has_key?(obj)
buffer[i] = obj
hash[obj] = true
i += 1
end
end
i
end
end
# Concatenation. Returns a new `Array` built by concatenating `self` and *other*.
# The type of the new array is the union of the types of both the original arrays.
#
# ```
# [1, 2] + ["a"] # => [1,2,"a"] of (Int32 | String)
# [1, 2] + [2, 3] # => [1,2,2,3]
# ```
def +(other : Array(U)) forall U
new_size = size + other.size
Array(T | U).build(new_size) do |buffer|
buffer.copy_from(@buffer, size)
(buffer + size).copy_from(other.to_unsafe, other.size)
new_size
end
end
# Returns the additive identity of this type.
#
# This is an empty array.
def self.additive_identity : self
self.new
end
# Difference. Returns a new `Array` that is a copy of `self`, removing any items
# that appear in *other*. The order of `self` is preserved.
#
# ```
# [1, 2, 3] - [2, 1] # => [3]
# ```
def -(other : Array(U)) forall U
# Heuristic: if any of the arrays is small we just do a linear scan
# instead of using a Hash for lookup.
if size <= SMALL_ARRAY_SIZE || other.size <= SMALL_ARRAY_SIZE
ary = Array(T).new
each do |elem|
ary << elem unless other.includes?(elem)
end
return ary
end
ary = Array(T).new(Math.max(size - other.size, 0))
hash = other.to_lookup_hash
each do |obj|
ary << obj unless hash.has_key?(obj)
end
ary
end
# Repetition: Returns a new `Array` built by concatenating *times* copies of `self`.
#
# ```
# ["a", "b", "c"] * 2 # => [ "a", "b", "c", "a", "b", "c" ]
# ```
def *(times : Int)
if times == 0 || empty?
return Array(T).new
end
if times == 1
return dup
end
if size == 1
return Array(T).new(times, first)
end
new_size = size * times
Array(T).build(new_size) do |buffer|
buffer.copy_from(to_unsafe, size)
n = size
while n <= new_size // 2
(buffer + n).copy_from(buffer, n)
n *= 2
end
(buffer + n).copy_from(buffer, new_size - n)
new_size
end
end
# Append. Alias for `push`.
#
# ```
# a = [1, 2]
# a << 3 # => [1,2,3]
# ```
def <<(value : T)
push(value)
end
# Replaces a subrange with a single value. All elements in the range
# `index...index+count` are removed and replaced by a single element
# *value*.
#
# If *count* is zero, *value* is inserted at *index*.
#
# Negative values of *index* count from the end of the array.
#
# ```
# a = [1, 2, 3, 4, 5]
# a[1, 3] = 6
# a # => [1, 6, 5]
#
# a = [1, 2, 3, 4, 5]
# a[1, 0] = 6
# a # => [1, 6, 2, 3, 4, 5]
# ```
def []=(index : Int, count : Int, value : T)
index, count = normalize_start_and_count(index, count)
case count
when 0
insert index, value
when 1
@buffer[index] = value
else
diff = count - 1
# If index is 0 we can avoid a memcpy by doing a shift.
# For example if we have:
#
# a = ['a', 'b', 'c', 'd']
#
# and someone does:
#
# a[0..2] = 'x'
#
# we can change the value at 2 to 'x' and repoint `@offset_to_buffer`:
#
# [-, -, 'x', 'd']
# ^
#
# (we also have to clear the elements before that)
if index == 0
@buffer.clear(diff)
shift_buffer_by(diff)
@buffer.value = value
else
(@buffer + index + 1).move_from(@buffer + index + count, size - index - count)
(@buffer + @size - diff).clear(diff)
@buffer[index] = value
end
@size -= diff
end
value
end
# Replaces a subrange with a single value.
#
# ```
# a = [1, 2, 3, 4, 5]
# a[1..3] = 6
# a # => [1, 6, 5]
#
# a = [1, 2, 3, 4, 5]
# a[1...1] = 6
# a # => [1, 6, 2, 3, 4, 5]
#
# a = [1, 2, 3, 4, 5]
# a[2...] = 6
# a # => [1, 2, 6]
# ```
def []=(range : Range, value : T)
self[*Indexable.range_to_index_and_count(range, size) || raise IndexError.new] = value
end
# Replaces a subrange with the elements of the given array.
#
# ```
# a = [1, 2, 3, 4, 5]
# a[1, 3] = [6, 7, 8]
# a # => [1, 6, 7, 8, 5]
#
# a = [1, 2, 3, 4, 5]
# a[1, 3] = [6, 7]
# a # => [1, 6, 7, 5]
#
# a = [1, 2, 3, 4, 5]
# a[1, 3] = [6, 7, 8, 9, 10]
# a # => [1, 6, 7, 8, 9, 10, 5]
# ```
def []=(index : Int, count : Int, values : Array(T))
index, count = normalize_start_and_count(index, count)
diff = values.size - count
if diff == 0
# Replace values directly
(@buffer + index).copy_from(values.to_unsafe, values.size)
elsif diff < 0
# Need to shrink
diff = -diff
(@buffer + index).copy_from(values.to_unsafe, values.size)
(@buffer + index + values.size).move_from(@buffer + index + count, size - index - count)
(@buffer + @size - diff).clear(diff)
@size -= diff
else
# Need to grow
resize_to_capacity(Math.pw2ceil(@size + diff))
(@buffer + index + values.size).move_from(@buffer + index + count, size - index - count)
(@buffer + index).copy_from(values.to_unsafe, values.size)
@size += diff
end
values
end
# Replaces a subrange with the elements of the given array.
#
# ```
# a = [1, 2, 3, 4, 5]
# a[1..3] = [6, 7, 8]
# a # => [1, 6, 7, 8, 5]
#
# a = [1, 2, 3, 4, 5]
# a[1..3] = [6, 7]
# a # => [1, 6, 7, 5]
#
# a = [1, 2, 3, 4, 5]
# a[1..3] = [6, 7, 8, 9, 10]
# a # => [1, 6, 7, 8, 9, 10, 5]
#
# a = [1, 2, 3, 4, 5]
# a[2..] = [6, 7, 8, 9, 10]
# a # => [1, 2, 6, 7, 8, 9, 10]
# ```
def []=(range : Range, values : Array(T))
self[*Indexable.range_to_index_and_count(range, size) || raise IndexError.new] = values
end
# Returns all elements that are within the given range.
#
# The first element in the returned array is `self[range.begin]` followed
# by the next elements up to index `range.end` (or `self[range.end - 1]` if
# the range is exclusive).
# If there are fewer elements in `self`, the returned array is shorter than
# `range.size`.
#
# ```
# a = ["a", "b", "c", "d", "e"]
# a[1..3] # => ["b", "c", "d"]
# # range.end > array.size
# a[3..7] # => ["d", "e"]
# ```
#
# Open ended ranges are clamped at the start and end of the array, respectively.
#
# ```
# # open ended ranges
# a[2..] # => ["c", "d", "e"]
# a[..2] # => ["a", "b", "c"]
# ```
#
# Negative range values are added to `self.size`, thus they are treated as
# indices counting from the end of the array, `-1` designating the last element.
#
# ```
# # negative indices, both ranges are equivalent for `a`
# a[1..3] # => ["b", "c", "d"]
# a[-4..-2] # => ["b", "c", "d"]
# # Mixing negative and positive indices, both ranges are equivalent for `a`
# a[1..-2] # => ["b", "c", "d"]
# a[-4..3] # => ["b", "c", "d"]
# ```
#
# Raises `IndexError` if the start index is out of range (`range.begin >
# self.size || range.begin < -self.size`). If `range.begin == self.size` an
# empty array is returned. If `range.begin > range.end`, an empty array is
# returned.
#
# ```
# # range.begin > array.size
# a[6..10] # raise IndexError
# # range.begin == array.size
# a[5..10] # => []
# # range.begin > range.end
# a[3..1] # => []
# a[-2..-4] # => []
# a[-2..1] # => []
# a[3..-4] # => []
# ```
def [](range : Range) : Array(T)
self[*Indexable.range_to_index_and_count(range, size) || raise IndexError.new]
end
# Like `#[](Range)`, but returns `nil` if `range.begin` is out of range.
#
# ```
# a = ["a", "b", "c", "d", "e"]
# a[6..10]? # => nil
# a[6..]? # => nil
# ```
def []?(range : Range) : Array(T)?
self[*Indexable.range_to_index_and_count(range, size) || return nil]?
end
# Returns count or less (if there aren't enough) elements starting at the
# given start index.
#
# Negative *start* is added to `self.size`, thus it's treated as
# index counting from the end of the array, `-1` designating the last element.
#
# Raises `IndexError` if *start* index is out of bounds.
# Raises `ArgumentError` if *count* is negative.
#
# ```
# a = ["a", "b", "c", "d", "e"]
# a[-3, 3] # => ["c", "d", "e"]
# a[1, 2] # => ["b", "c"]
# a[5, 1] # => []
# a[6, 1] # raises IndexError
# ```
def [](start : Int, count : Int) : Array(T)
self[start, count]? || raise IndexError.new
end
# Like `#[](Int, Int)` but returns `nil` if the *start* index is out of range.
def []?(start : Int, count : Int) : Array(T)?
start, count = normalize_start_and_count(start, count) { return nil }
return Array(T).new if count == 0
Array(T).build(count) do |buffer|
buffer.copy_from(@buffer + start, count)
count
end
end
@[AlwaysInline]
def unsafe_fetch(index : Int) : T
@buffer[index]
end
@[AlwaysInline]
def unsafe_put(index : Int, value : T)
@buffer[index] = value
end
# Removes all elements from self.
#
# ```
# a = ["a", "b", "c", "d", "e"]
# a.clear # => []
# ```
def clear : self
@buffer.clear(@size)
@size = 0
self
end
# Returns a new `Array` that has `self`'s elements cloned.
# That is, it returns a deep copy of `self`.
#
# Use `#dup` if you want a shallow copy.
#
# ```
# ary = [[1, 2], [3, 4]]
# ary2 = ary.clone
# ary[0][0] = 5
# ary # => [[5, 2], [3, 4]]
# ary2 # => [[1, 2], [3, 4]]
#
# ary2 << [7, 8]
# ary # => [[5, 2], [3, 4]]
# ary2 # => [[1, 2], [3, 4], [7, 8]]
# ```
def clone
{% if T == ::Bool || T == ::Char || T == ::String || T == ::Symbol || T < ::Number::Primitive %}
Array(T).new(size) { |i| @buffer[i].clone.as(T) }
{% else %}
exec_recursive_clone do |hash|
clone = Array(T).new(size)
hash[object_id] = clone.object_id
each do |element|
clone << element.clone.as(T)
end
clone
end
{% end %}
end
# Returns a copy of `self` with all `nil` elements removed.
#
# ```
# ["a", nil, "b", nil, "c", nil].compact # => ["a", "b", "c"]
# ```
def compact
compact_map &.itself
end
# Removes all `nil` elements from `self` and returns `self`.
#
# ```
# ary = ["a", nil, "b", nil, "c"]
# ary.compact!
# ary # => ["a", "b", "c"]
# ```
def compact! : self
reject! &.nil?
end
# Appends the elements of *other* to `self`, and returns `self`.
#
# ```
# ary = ["a", "b"]
# ary.concat(["c", "d"])
# ary # => ["a", "b", "c", "d"]
# ```
def concat(other : Array)
other_size = other.size
resize_if_cant_insert(other_size)
(@buffer + @size).copy_from(other.to_unsafe, other_size)
@size += other_size
self
end
# :ditto:
def concat(other : Enumerable)
left_before_resize = remaining_capacity - @size
len = @size
buf = @buffer + len
other.each do |elem|
if left_before_resize == 0
double_capacity
left_before_resize = remaining_capacity - len
buf = @buffer + len
end
buf.value = elem
buf += 1
len += 1
left_before_resize -= 1
end
@size = len
self
end
# Removes all items from `self` that are equal to *obj*.
#
# Returns the last found element that was equal to *obj*,
# if any, or `nil` if not found.
#
# ```
# a = ["a", "b", "b", "b", "c"]
# a.delete("b") # => "b"
# a # => ["a", "c"]
#
# a.delete("x") # => nil
# a # => ["a", "c"]
# ```
def delete(obj) : T?
internal_delete { |e| e == obj }[1]
end
# Removes the element at *index*, returning that element.
# Raises `IndexError` if *index* is out of range.
#
# ```
# a = ["ant", "bat", "cat", "dog"]
# a.delete_at(2) # => "cat"
# a # => ["ant", "bat", "dog"]
# a.delete_at(99) # raises IndexError
# ```
def delete_at(index : Int)
index = check_index_out_of_bounds index
# Deleting the first element is the same as a shift
if index == 0
return shift_when_not_empty
end
elem = @buffer[index]
(@buffer + index).move_from(@buffer + index + 1, size - index - 1)
@size -= 1
(@buffer + @size).clear
elem
end
# Removes all elements within the given *range*.
# Returns an array of the removed elements with the original order of `self` preserved.
# Raises `IndexError` if the index is out of range.
#
# ```
# a = ["ant", "bat", "cat", "dog"]
# a.delete_at(1..2) # => ["bat", "cat"]
# a # => ["ant", "dog"]
# a.delete_at(99..100) # raises IndexError
# ```
def delete_at(range : Range) : self
index, count = Indexable.range_to_index_and_count(range, self.size) || raise IndexError.new
delete_at(index, count)
end
# Removes *count* elements from `self` starting at *index*.
# If the size of `self` is less than *count*, removes values to the end of the array without error.
# Returns an array of the removed elements with the original order of `self` preserved.
# Raises `IndexError` if *index* is out of range.
#
# ```
# a = ["ant", "bat", "cat", "dog"]
# a.delete_at(1, 2) # => ["bat", "cat"]
# a # => ["ant", "dog"]
# a.delete_at(99, 1) # raises IndexError
# ```
def delete_at(index : Int, count : Int) : self
index, count = normalize_start_and_count(index, count)
val = self[index, count]
(@buffer + index).move_from(@buffer + index + count, size - index - count)
@size -= count
(@buffer + @size).clear(count)
val
end
# Returns a new `Array` that has exactly `self`'s elements.
# That is, it returns a shallow copy of `self`.
#
# Use `#clone` if you want a deep copy.
#
# ```
# ary = [[1, 2], [3, 4]]
# ary2 = ary.dup
# ary[0][0] = 5
# ary # => [[5, 2], [3, 4]]
# ary2 # => [[5, 2], [3, 4]]
#
# ary2 << [7, 8]
# ary # => [[5, 2], [3, 4]]
# ary2 # => [[5, 2], [3, 4], [7, 8]]
# ```
def dup
Array(T).build(@size) do |buffer|
buffer.copy_from(@buffer, size)
size
end
end
# Yields each index of `self`, starting at *from*, to the given block and then assigns
# the block's value in that position. Returns `self`.
#
# Negative values of *from* count from the end of the array.
#
# Raises `IndexError` if *from* is outside the array range.
#
# ```
# a = [1, 2, 3, 4]
# a.fill(2) { |i| i * i } # => [1, 2, 4, 9]
# ```
def fill(from : Int, & : Int32 -> T) : self
from += size if from < 0
raise IndexError.new unless 0 <= from < size
to_unsafe_slice(from, size - from).fill(offset: from) { |i| yield i }
self
end
# Yields each index of `self`, starting at *from* and just *count* times,
# to the given block and then assigns the block's value in that position. Returns `self`.
#
# Negative values of *from* count from the end of the array.
#
# Raises `IndexError` if *from* is outside the array range.
#
# Has no effect if *count* is zero or negative.
#
# ```
# a = [1, 2, 3, 4, 5, 6]
# a.fill(2, 2) { |i| i * i } # => [1, 2, 4, 9, 5, 6]
# ```
def fill(from : Int, count : Int, & : Int32 -> T) : self
return self if count <= 0
from += size if from < 0
raise IndexError.new unless 0 <= from < size && from + count <= size
to_unsafe_slice(from, count).fill(offset: from) { |i| yield i }
self
end
# Yields each index of `self`, in the given *range*, to the given block and then assigns
# the block's value in that position. Returns `self`.
#
# ```
# a = [1, 2, 3, 4, 5, 6]
# a.fill(2..3) { |i| i * i } # => [1, 2, 4, 9, 5, 6]
# ```
def fill(range : Range, & : Int32 -> T) : self
fill(*Indexable.range_to_index_and_count(range, size) || raise IndexError.new) do |i|
yield i
end
end
# :inherit:
def fill(value : T) : self
# enable memset optimization
to_unsafe_slice.fill(value)
self
end
# Replaces every element in `self`, starting at *from*, with the given *value*. Returns `self`.
#
# Negative values of *from* count from the end of the array.
#
# ```
# a = [1, 2, 3, 4, 5]
# a.fill(9, 2) # => [1, 2, 9, 9, 9]
# ```
def fill(value : T, from : Int) : self
from += size if from < 0
raise IndexError.new unless 0 <= from < size
to_unsafe_slice(from, size - from).fill(value)
self
end
# Replaces every element in `self`, starting at *from* and only *count* times,
# with the given *value*. Returns `self`.
#
# Negative values of *from* count from the end of the array.
#
# ```
# a = [1, 2, 3, 4, 5]
# a.fill(9, 2, 2) # => [1, 2, 9, 9, 5]
# ```
def fill(value : T, from : Int, count : Int) : self
return self if count <= 0
from += size if from < 0
raise IndexError.new unless 0 <= from < size && from + count <= size
to_unsafe_slice(from, count).fill(value)
self
end
# Replaces every element in *range* with *value*. Returns `self`.
#
# Negative values of *from* count from the end of the array.
#
# ```
# a = [1, 2, 3, 4, 5]
# a.fill(9, 2..3) # => [1, 2, 9, 9, 5]
# ```
def fill(value : T, range : Range) : self
fill(value, *Indexable.range_to_index_and_count(range, size) || raise IndexError.new)
end
# Returns the first *n* elements of the array.
#
# ```
# [1, 2, 3].first(2) # => [1, 2]
# [1, 2, 3].first(4) # => [1, 2, 3]
# ```
def first(n : Int) : Array(T)
self[0, n]
end
# Insert *object* before the element at *index* and shifting successive elements, if any.
# Returns `self`.
#
# Negative values of *index* count from the end of the array.
#
# ```
# a = ["a", "b", "c"]
# a.insert(0, "x") # => ["x", "a", "b", "c"]
# a.insert(2, "y") # => ["x", "a", "y", "b", "c"]