forked from rubinius/rubinius
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray.rb
2337 lines (1839 loc) · 51.9 KB
/
array.rb
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
class Array
include Enumerable
def self.allocate
Rubinius.primitive :array_allocate
raise PrimitiveFailure, "Array.allocate primitive failed"
end
def size
@total
end
alias_method :length, :size
def new_range(start, count)
Rubinius.primitive :array_new_range
raise PrimitiveFailure, "Array.new_range primitive failed"
end
def new_reserved(count)
Rubinius.primitive :array_new_reserved
raise PrimitiveFailure, "Array.new_reserved primitive failed"
end
def []=(idx, ent)
Rubinius.check_frozen
if idx >= @tuple.fields
new_tuple = Rubinius::Tuple.new(idx + 10)
new_tuple.copy_from @tuple, @start, @total, 0
@tuple = new_tuple
end
@tuple.put @start + idx, ent
if idx >= @total - 1
@total = idx + 1
end
return ent
end
# Returns the element at the given index. If the
# index is negative, counts from the end of the
# Array. If the index is out of range, nil is
# returned. Slightly faster than +Array#[]+
def at(idx)
Rubinius.primitive :array_aref
idx = Rubinius::Type.coerce_to_collection_index idx
total = @start + @total
if idx < 0
idx += total
else
idx += @start
end
if idx >= @start and idx < total
return @tuple.at idx
end
end
# Passes each element in the Array to the given block
# and returns self.
def each
return to_enum(:each) { size } unless block_given?
i = @start
total = i + @total
tuple = @tuple
while i < total
yield tuple.at(i)
i += 1
end
self
end
# Creates a new Array from the return values of passing
# each element in self to the supplied block.
def map
return to_enum(:map) { size } unless block_given?
out = Array.new size
i = @start
total = i + @total
src = @tuple
dest = Rubinius::Mirror.reflect(out).tuple
j = 0
while i < total
dest[j] = yield src[i]
i += 1
j += 1
end
out
end
# Replaces each element in self with the return value
# of passing that element to the supplied block.
def map!
return to_enum(:map!) { size } unless block_given?
Rubinius.check_frozen
i = @start
total = i + @total
tuple = @tuple
while i < total
tuple[i] = yield tuple.at(i)
i += 1
end
self
end
def to_tuple
tuple = Rubinius::Tuple.new @total
tuple.copy_from @tuple, @start, @total, 0
tuple
end
# The flow control for many of these methods is
# pretty evil due to how MRI works. There is
# also a lot of duplication of code due to very
# subtle processing differences and, in some
# cases, to avoid mutual dependency. Apologies.
def self.[](*args)
ary = allocate
ary.replace args
ary
end
# Try to convert obj into an array, using to_ary method.
# Returns converted array or nil if obj cannot be converted
# for any reason. This method is to check if an argument is an array.
def self.try_convert(obj)
Rubinius::Type.try_convert obj, Array, :to_ary
end
def initialize(size_or_array=undefined, obj=undefined)
Rubinius.check_frozen
if undefined.equal?(size_or_array)
unless @total == 0
@total = @start = 0
@tuple = Rubinius::Tuple.new 8
end
return self
end
if undefined.equal?(obj)
obj = nil
ary = nil
if size_or_array.kind_of? Integer
# Do nothing, fall through to later case.
elsif size_or_array.kind_of? Array
ary = size_or_array
elsif Rubinius::Type.object_respond_to_ary?(size_or_array)
ary = Rubinius::Type.coerce_to size_or_array, Array, :to_ary
end
if ary
m = Rubinius::Mirror::Array.reflect ary
@tuple = m.tuple.dup
@start = m.start
@total = m.total
return self
end
end
size = Rubinius::Type.coerce_to_collection_length size_or_array
raise ArgumentError, "size must be positive" if size < 0
raise ArgumentError, "size must be <= #{Fixnum::MAX}" if size > Fixnum::MAX
if block_given?
@tuple = Rubinius::Tuple.new size
@total = i = 0
while i < size
@tuple.put i, yield(i)
@total = i += 1
end
else
@total = size
@tuple = Rubinius::Tuple.pattern size, obj
end
self
end
private :initialize
# Replaces contents of self with contents of other,
# adjusting size as needed.
def replace(other)
Rubinius.check_frozen
other = Rubinius::Type.coerce_to other, Array, :to_ary
m = Rubinius::Mirror::Array.reflect other
@tuple = m.tuple.dup
@total = m.total
@start = m.start
Rubinius::Type.infect(self, other)
self
end
alias_method :initialize_copy, :replace
private :initialize_copy
def [](arg1, arg2=nil)
case arg1
# This is split out from the generic case and put first because
# it is by far the most common case and we want to deal with it
# immediately, even at the expensive of duplicate code with the
# generic case below. In other words, don't refactor this unless
# you preserve the same or better performance.
when Fixnum
start_idx = arg1
# Convert negative indices
start_idx += @total if start_idx < 0
if arg2
count = Rubinius::Type.coerce_to_collection_index arg2
else
return nil if start_idx >= @total
begin
return @tuple.at(@start + start_idx)
# Tuple#at raises this if the index is negative or
# past the end. This is faster than checking explicitly
# since this is an exceptional case anyway.
rescue Rubinius::ObjectBoundsExceededError
return nil
end
end
when Range
start_idx = Rubinius::Type.coerce_to_collection_index arg1.begin
# Convert negative indices
start_idx += @total if start_idx < 0
# Check here because we must detect this boundary
# before we check the right index boundary cases
return nil if start_idx < 0 or start_idx > @total
right_idx = Rubinius::Type.coerce_to_collection_index arg1.end
right_idx += @total if right_idx < 0
right_idx -= 1 if arg1.exclude_end?
return new_range(0, 0) if right_idx < start_idx
count = right_idx - start_idx + 1
# Slower, less common generic coercion case.
else
start_idx = Rubinius::Type.coerce_to_collection_index arg1
# Convert negative indices
start_idx += @total if start_idx < 0
if arg2
count = Rubinius::Type.coerce_to_collection_index arg2
else
return nil if start_idx >= @total
begin
return @tuple.at(@start + start_idx)
# Tuple#at raises this if the index is negative or
# past the end. This is faster than checking explicitly
# since this is an exceptional case anyway.
rescue Rubinius::ObjectBoundsExceededError
return nil
end
end
end
# No need to go further
return nil if count < 0
# Check start boundaries
if start_idx >= @total
# Odd MRI boundary case
return new_range(0, 0) if start_idx == @total
return nil
end
return nil if start_idx < 0
# Check count boundaries
if start_idx + count > @total
count = @total - start_idx
end
# Construct the subrange
return new_range(@start + start_idx, count)
end
alias_method :slice, :[]
def <<(obj)
set_index(@total, obj)
self
end
alias_method :__append__, :<<
def *(multiplier)
if multiplier.respond_to? :to_str
return join(multiplier)
else
multiplier = Rubinius::Type.coerce_to_collection_index multiplier
raise ArgumentError, "Count cannot be negative" if multiplier < 0
case @total
when 0
# Edge case
out = self.class.allocate
Rubinius::Type.infect(out, self)
return out
when 1
# Easy case
tuple = Rubinius::Tuple.pattern multiplier, at(0)
out = self.class.allocate
m = Rubinius::Mirror::Array.reflect out
m.tuple = tuple
m.total = multiplier
Rubinius::Type.infect(out, self)
return out
end
new_total = multiplier * @total
new_tuple = Rubinius::Tuple.new(new_total)
out = self.class.allocate
m = Rubinius::Mirror::Array.reflect out
m.tuple = new_tuple
m.total = new_total
Rubinius::Type.infect(out, self)
offset = 0
while offset < new_total
new_tuple.copy_from @tuple, @start, @total, offset
offset += @total
end
out
end
end
def &(other)
other = Rubinius::Type.coerce_to other, Array, :to_ary
array = []
im = Rubinius::IdentityMap.from other
each { |x| array << x if im.delete x }
array
end
def |(other)
other = Rubinius::Type.coerce_to other, Array, :to_ary
im = Rubinius::IdentityMap.from self, other
im.to_array
end
def +(other)
other = Rubinius::Type.coerce_to other, Array, :to_ary
Array.new(self).concat(other)
end
def -(other)
other = Rubinius::Type.coerce_to other, Array, :to_ary
array = []
im = Rubinius::IdentityMap.from other
each { |x| array << x unless im.include? x }
array
end
def <=>(other)
other = Rubinius::Type.check_convert_type other, Array, :to_ary
return 0 if equal? other
return nil if other.nil?
total = Rubinius::Mirror::Array.reflect(other).total
Thread.detect_recursion self, other do
i = 0
count = total < @total ? total : @total
while i < count
order = self[i] <=> other[i]
return order unless order == 0
i += 1
end
end
# subtle: if we are recursing on that pair, then let's
# no go any further down into that pair;
# any difference will be found elsewhere if need be
@total <=> total
end
def ==(other)
return true if equal?(other)
unless other.kind_of?(Array)
return false unless other.respond_to?(:to_ary)
return other == self
end
return false unless size == other.size
Thread.detect_recursion(self, other) do
mirror = Rubinius::Mirror::Array.reflect(other)
self_tuple = @tuple
other_tuple = mirror.tuple
self_idx = @start
other_idx = mirror.start
total = self_idx + @total
while self_idx < total
return false unless self_tuple[self_idx] == other_tuple[other_idx]
self_idx += 1
other_idx += 1
end
end
true
end
def assoc(obj)
each do |x|
if x.kind_of? Array and x.first == obj
return x
end
end
nil
end
def bsearch(&block)
return to_enum :bsearch unless block
i = bsearch_index(&block)
return unless i
m = Rubinius::Mirror::Array.reflect self
tuple = m.tuple
tuple.at(i)
end
def bsearch_index
return to_enum :bsearch_index unless block_given?
m = Rubinius::Mirror::Array.reflect self
tuple = m.tuple
min = start = m.start
max = total = start + m.total
last_true = nil
i = start + m.total / 2
while max >= min and i >= start and i < total
x = yield tuple.at(i)
return i if x == 0
case x
when Numeric
if x > 0
min = i + 1
else
max = i - 1
end
when true
last_true = i
max = i - 1
when false, nil
min = i + 1
else
raise TypeError, "block must return Numeric or boolean"
end
i = min + (max - min) / 2
end
return i if max > min
return last_true if last_true
nil
end
def clear
Rubinius.check_frozen
@tuple = Rubinius::Tuple.new(1)
@total = 0
@start = 0
self
end
def combination(num)
num = Rubinius::Type.coerce_to_collection_index num
unless block_given?
return to_enum(:combination, num) do
Rubinius::Mirror::Array.reflect(self).combination_size(num)
end
end
if num == 0
yield []
elsif num == 1
each do |i|
yield [i]
end
elsif num == size
yield self.dup
elsif num >= 0 && num < size
stack = Rubinius::Tuple.pattern num + 1, 0
chosen = Rubinius::Tuple.new num
lev = 0
done = false
stack[0] = -1
until done
chosen[lev] = self.at(stack[lev+1])
while lev < num - 1
lev += 1
chosen[lev] = self.at(stack[lev+1] = stack[lev] + 1)
end
yield chosen.to_a
lev += 1
begin
done = lev == 0
stack[lev] += 1
lev -= 1
end while stack[lev+1] + num == size + lev + 1
end
end
self
end
def compact
out = dup
out.untaint if out.tainted?
Array.new(out.compact! || out)
end
def compact!
Rubinius.check_frozen
if (deleted = @tuple.delete(@start, @total, nil)) > 0
@total -= deleted
reallocate_shrink()
return self
else
return nil
end
end
def concat(other)
Rubinius.primitive :array_concat
other = Rubinius::Type.coerce_to(other, Array, :to_ary)
Rubinius.check_frozen
return self if other.empty?
concat other
end
def count(item = undefined)
seq = 0
if !undefined.equal?(item)
each { |o| seq += 1 if item == o }
elsif block_given?
each { |o| seq += 1 if yield(o) }
else
return @total
end
seq
end
def cycle(n=nil)
unless block_given?
return to_enum(:cycle, n) do
Rubinius::EnumerableHelper.cycle_size(size, n)
end
end
return nil if empty?
# Don't use nil? because, historically, lame code has overridden that method
if n.equal? nil
while true
each { |x| yield x }
end
else
n = Rubinius::Type.coerce_to_collection_index n
n.times do
each { |x| yield x }
end
end
nil
end
def delete(obj)
key = undefined
i = @start
total = i + @total
tuple = @tuple
while i < total
element = tuple.at i
if element == obj
# We MUST check frozen here, not at the top, because MRI
# requires that #delete not raise unless an element would
# be deleted.
Rubinius.check_frozen
tuple.put i, key
last_matched_element = element
end
i += 1
end
deleted = @tuple.delete @start, @total, key
if deleted > 0
@total -= deleted
reallocate_shrink()
return last_matched_element
end
if block_given?
yield
else
nil
end
end
def delete_at(idx)
Rubinius.check_frozen
idx = Rubinius::Type.coerce_to_collection_index idx
# Flip to positive and weed out out of bounds
idx += @total if idx < 0
return nil if idx < 0 or idx >= @total
# Grab the object and adjust the indices for the rest
obj = @tuple.at(@start + idx)
# Shift style.
if idx == 0
@tuple.put @start, nil
@start += 1
else
@tuple.copy_from(@tuple, @start+idx+1, @total-idx-1, @start+idx)
@tuple.put(@start + @total - 1, nil)
end
@total -= 1
obj
end
def delete_if
return to_enum(:delete_if) { size } unless block_given?
Rubinius.check_frozen
return self if empty?
i = pos = @start
total = i + @total
tuple = @tuple
while i < total
x = tuple.at i
unless yield x
# Ok, keep the value, so stick it back into the array at
# the insert position
tuple.put pos, x
pos += 1
end
i += 1
end
@total = pos - @start
self
end
def dig(index, *remaining_indeces)
item = self[index]
return item if remaining_indeces.empty? || item.nil?
raise TypeError, "#{item.class} does not have #dig method" unless item.respond_to?(:dig)
item.dig(*remaining_indeces)
end
def each_index
return to_enum(:each_index) { size } unless block_given?
i = 0
total = @total
while i < total
yield i
i += 1
end
self
end
# WARNING: This method does no boundary checking. It is expected that
# the caller handle that, eg #slice!
def delete_range(index, del_length)
# optimize for fast removal..
reg_start = index + del_length
reg_length = @total - reg_start
if reg_start <= @total
# If we're removing from the front, also reset @start to better
# use the Tuple
if index == 0
# Use a shift start optimization if we're only removing one
# element and the shift started isn't already huge.
if del_length == 1
@tuple.put @start, nil
@start += 1
else
@tuple.copy_from @tuple, reg_start + @start, reg_length, 0
@start = 0
end
else
@tuple.copy_from @tuple, reg_start + @start, reg_length,
@start + index
end
# TODO we leave the old references in the Tuple, we should
# probably clear them out though.
@total -= del_length
end
end
private :delete_range
def eql?(other)
return true if equal? other
return false unless other.kind_of?(Array)
return false if @total != other.size
Thread.detect_recursion self, other do
i = 0
each do |x|
return false unless x.eql? other[i]
i += 1
end
end
true
end
def empty?
@total == 0
end
def fetch(idx, default=undefined)
orig = idx
idx = Rubinius::Type.coerce_to_collection_index idx
idx += @total if idx < 0
if idx < 0 or idx >= @total
if block_given?
return yield(orig)
end
return default unless undefined.equal?(default)
raise IndexError, "index #{idx} out of bounds"
end
at(idx)
end
def fill(a=undefined, b=undefined, c=undefined)
Rubinius.check_frozen
if block_given?
unless undefined.equal?(c)
raise ArgumentError, "wrong number of arguments"
end
one = a
two = b
else
if undefined.equal?(a)
raise ArgumentError, "wrong number of arguments"
end
obj = a
one = b
two = c
end
if one.kind_of? Range
raise TypeError, "length invalid with range" unless undefined.equal?(two)
left = Rubinius::Type.coerce_to_collection_length one.begin
left += size if left < 0
raise RangeError, "#{one.inspect} out of range" if left < 0
right = Rubinius::Type.coerce_to_collection_length one.end
right += size if right < 0
right += 1 unless one.exclude_end?
return self if right <= left # Nothing to modify
elsif one and !undefined.equal?(one)
left = Rubinius::Type.coerce_to_collection_length one
left += size if left < 0
left = 0 if left < 0
if two and !undefined.equal?(two)
begin
right = Rubinius::Type.coerce_to_collection_length two
rescue TypeError
raise ArgumentError, "second argument must be a Fixnum"
end
return self if right == 0
right += left
else
right = size
end
else
left = 0
right = size
end
total = @start + right
if right > @total
reallocate total
@total = right
end
# Must be after the potential call to reallocate, since
# reallocate might change @tuple
tuple = @tuple
i = @start + left
if block_given?
while i < total
tuple.put i, yield(i-@start)
i += 1
end
else
while i < total
tuple.put i, obj
i += 1
end
end
self
end
def first(n = undefined)
return at(0) if undefined.equal?(n)
n = Rubinius::Type.coerce_to_collection_index n
raise ArgumentError, "Size must be positive" if n < 0
Array.new self[0, n]
end
def flatten(level=-1)
level = Rubinius::Type.coerce_to_collection_index level
return self.dup if level == 0
out = new_reserved size
recursively_flatten(self, out, level)
Rubinius::Type.infect(out, self)
out
end
def flatten!(level=-1)
Rubinius.check_frozen
level = Rubinius::Type.coerce_to_collection_index level
return nil if level == 0
out = new_reserved size
if recursively_flatten(self, out, level)
replace(out)
return self
end
nil
end
def hash
hash_val = size
mask = Fixnum::MAX >> 1
# This is duplicated and manually inlined code from Thread for performance
# reasons. Before refactoring it, please benchmark it and compare your
# refactoring against the original.
id = object_id
objects = Thread.current.recursive_objects
# If there is already an our version running...
if objects.key? :__detect_outermost_recursion__
# If we've seen self, unwind back to the outer version
if objects.key? id
raise Thread::InnerRecursionDetected
end
# .. or compute the hash value like normal
begin
objects[id] = true
each { |x| hash_val = ((hash_val & mask) << 1) ^ x.hash }
ensure
objects.delete id
end
return hash_val
else
# Otherwise, we're the outermost version of this code..
begin
objects[:__detect_outermost_recursion__] = true
objects[id] = true
each { |x| hash_val = ((hash_val & mask) << 1) ^ x.hash }
# An inner version will raise to return back here, indicating that
# the whole structure is recursive. In which case, abondon most of
# the work and return a simple hash value.
rescue Thread::InnerRecursionDetected
return size
ensure
objects.delete :__detect_outermost_recursion__
objects.delete id
end
end
return hash_val
end
def include?(obj)
# This explicit loop is for performance only. Preferably,
# this method would be implemented as:
#
# each { |x| return true if x == obj }
#
# but the JIT will currently not inline the block into the
# method that calls #include? which causes #include? to
# execute about 3x slower. Since this is a very commonly
# used method, this manual performance optimization is used.
# Ideally, this will be removed when the JIT can handle the
# block used here.
i = @start
total = i + @total
tuple = @tuple
while i < total
return true if tuple.at(i) == obj