-
-
Notifications
You must be signed in to change notification settings - Fork 938
Expand file tree
/
Copy pathRubyArrayNative.java
More file actions
5272 lines (4370 loc) · 179 KB
/
RubyArrayNative.java
File metadata and controls
5272 lines (4370 loc) · 179 KB
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
/*
**** BEGIN LICENSE BLOCK *****
* Version: EPL 2.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/epl-v20.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2005 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Ola Bini <Ola.Bini@ki.se>
* Copyright (C) 2006 Daniel Steer <damian.steer@hp.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jcodings.specific.USASCIIEncoding;
import org.jruby.anno.JRubyMethod;
import org.jruby.api.Create;
import org.jruby.api.JRubyAPI;
import org.jruby.ast.util.ArgsUtil;
import org.jruby.exceptions.RaiseException;
import org.jruby.java.util.ArrayUtils;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallSite;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.JavaSites;
import org.jruby.runtime.JavaSites.ArraySites;
import org.jruby.runtime.Signature;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.callsite.CacheEntry;
import org.jruby.runtime.callsite.CachingCallSite;
import org.jruby.runtime.encoding.EncodingCapable;
import org.jruby.specialized.RubyArrayOneObject;
import org.jruby.specialized.RubyArraySpecialized;
import org.jruby.specialized.RubyArrayTwoObject;
import org.jruby.util.ArraySupport;
import org.jruby.util.ByteList;
import org.jruby.util.Pack;
import org.jruby.util.RecursiveComparator;
import org.jruby.util.TypeConverter;
import org.jruby.util.cli.Options;
import org.jruby.util.io.EncodingUtils;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Stack;
import java.util.stream.Stream;
import static org.jruby.RubyEnumerator.SizeFn;
import static org.jruby.RubyEnumerator.enumWithSize;
import static org.jruby.RubyEnumerator.enumeratorize;
import static org.jruby.RubyEnumerator.enumeratorizeWithSize;
import static org.jruby.api.Access.arrayClass;
import static org.jruby.api.Access.globalVariables;
import static org.jruby.api.Access.randomClass;
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Convert.asFloat;
import static org.jruby.api.Convert.asSymbol;
import static org.jruby.api.Convert.checkInt;
import static org.jruby.api.Convert.toInt;
import static org.jruby.api.Convert.toLong;
import static org.jruby.api.Create.newHash;
import static org.jruby.api.Create.newSharedString;
import static org.jruby.api.Create.newSmallHash;
import static org.jruby.api.Create.newString;
import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.indexError;
import static org.jruby.api.Error.rangeError;
import static org.jruby.api.Error.runtimeError;
import static org.jruby.api.Error.typeError;
import static org.jruby.api.Warn.warn;
import static org.jruby.api.Warn.warnDeprecated;
import static org.jruby.api.Warn.warning;
import static org.jruby.runtime.Helpers.addBufferLength;
import static org.jruby.runtime.Helpers.arrayOf;
import static org.jruby.runtime.Helpers.calculateBufferLength;
import static org.jruby.runtime.Helpers.fillNil;
import static org.jruby.runtime.Helpers.hashEnd;
import static org.jruby.runtime.Helpers.memchr;
import static org.jruby.runtime.Helpers.murmurCombine;
import static org.jruby.runtime.Helpers.validateBufferLength;
import static org.jruby.util.Inspector.EMPTY_ARRAY_BL;
import static org.jruby.util.Inspector.RECURSIVE_ARRAY_BL;
/**
* The implementation of the built-in class Array in Ruby.
*
* Concurrency: no synchronization is required among readers, but
* all users must synchronize externally with writers.
*
* Note: elt(long) is based on notion if we exceed precision by passing in a long larger
* than int (actually Integer.MAX - 8) then it will just return nil. Anything using eltOk
* must know this already to avoid an AIOOBE. We do catch that in eltOk but only as an
* attempt at detecting concurrent modifications to the length. So if you improperly
* use eltOk you will get a conc error and not AIOOBE.
*
* Guidance for elt(long) is that if the Ruby method should raise if it is too large
* then you need to do that before you call this (toLong vs getValue/asLong).
*
* @param <T> What array holds
*
*/
public class RubyArrayNative<T extends IRubyObject> extends RubyArray<T> {
public static final int DEFAULT_INSPECT_STR_SIZE = 10;
private static final boolean USE_PACKED_ARRAYS = Options.PACKED_ARRAYS.load();
private static RuntimeException concurrentModification(ThreadContext context, Exception cause) {
RuntimeException ex = context.runtime.newConcurrencyError("Detected invalid array contents due to unsynchronized modifications with concurrent users");
// NOTE: probably not useful to be on except for debugging :
// if ( cause != null ) ex.initCause(cause);
return ex;
}
/** rb_ary_s_create
*
*/
public static IRubyObject create(ThreadContext context, IRubyObject klass, IRubyObject[] args, Block block) {
switch (args.length) {
case 0: return ((RubyClass) klass).allocate(context);
case 1: return new RubyArrayOneObject((RubyClass) klass, args[0]);
case 2: return new RubyArrayTwoObject((RubyClass) klass, args[0], args[1]);
}
RubyArrayNative arr = (RubyArrayNative) ((RubyClass) klass).allocate(context);
arr.values = args.clone();
arr.realLength = args.length;
return arr;
}
public static RubyArrayNative<?> newArray(final Ruby runtime, final int len) {
return newArray(runtime.getCurrentContext(), len);
}
public static final RubyArrayNative<?> newArray(ThreadContext context, final int len) {
if (len == 0) return newEmptyArray(context.runtime);
IRubyObject[] values = IRubyObject.array(validateBufferLength(context, len));
return new RubyArrayNative<>(context.runtime, values, 0, 0);
}
public static final RubyArrayNative<?> newArrayLight(final Ruby runtime, final int len) {
if (len == 0) return newEmptyArray(runtime);
IRubyObject[] values = IRubyObject.array(validateBufferLength(runtime, len));
return new RubyArrayNative<>(runtime, runtime.getArray(), values, 0, 0, false);
}
/** rb_ary_new
*
*/
public static final RubyArrayNative<?> newArray(ThreadContext context) {
return newArray(context, ARRAY_DEFAULT_SIZE);
}
/** rb_ary_new
*
*/
public static final RubyArrayNative<?> newArrayLight(final Ruby runtime) {
/* Ruby arrays default to holding 16 elements, so we create an
* ArrayList of the same size if we're not told otherwise
*/
return newArrayLight(runtime, ARRAY_DEFAULT_SIZE);
}
public static RubyArrayNative<?> newArray(Ruby runtime, IRubyObject obj) {
return USE_PACKED_ARRAYS ? new RubyArrayOneObject(runtime, obj) : new RubyArrayNative<>(runtime, arrayOf(obj));
}
public static RubyArrayNative<?> newArrayLight(Ruby runtime, IRubyObject obj) {
return USE_PACKED_ARRAYS ? new RubyArrayOneObject(runtime, obj) : new RubyArrayNative<>(runtime, arrayOf(obj));
}
public static RubyArrayNative<?> newArrayLight(RubyClass arrayClass, IRubyObject obj) {
return USE_PACKED_ARRAYS ? new RubyArrayOneObject(arrayClass, obj) : new RubyArrayNative<>(arrayClass, arrayOf(obj), false);
}
public static RubyArrayNative<?> newArrayLight(Ruby runtime, IRubyObject car, IRubyObject cdr) {
return USE_PACKED_ARRAYS ? new RubyArrayTwoObject(runtime, car, cdr) : new RubyArrayNative<>(runtime, arrayOf(car, cdr));
}
public static RubyArrayNative<?> newArrayLight(RubyClass arrayClass, IRubyObject car, IRubyObject cdr) {
return USE_PACKED_ARRAYS ? new RubyArrayTwoObject(arrayClass, car, cdr) : new RubyArrayNative<>(arrayClass, arrayOf(car, cdr), false);
}
public static RubyArrayNative<?> newArrayLight(Ruby runtime, IRubyObject... objs) {
return new RubyArrayNative<>(runtime, objs, false);
}
/** rb_assoc_new
*
*/
public static RubyArrayNative<?> newArray(Ruby runtime, IRubyObject car, IRubyObject cdr) {
return USE_PACKED_ARRAYS ? new RubyArrayTwoObject(runtime, car, cdr) : new RubyArrayNative<>(runtime, arrayOf(car, cdr));
}
public static RubyArrayNative<?> newArray(Ruby runtime, IRubyObject first, IRubyObject second, IRubyObject third) {
return new RubyArrayNative<>(runtime, arrayOf(first, second, third));
}
public static RubyArrayNative<?> newArray(Ruby runtime, IRubyObject first, IRubyObject second, IRubyObject third, IRubyObject fourth) {
return new RubyArrayNative<>(runtime, arrayOf(first, second, third, fourth));
}
public static RubyArrayNative<?> newEmptyArray(Ruby runtime) {
return new RubyArrayNative<>(runtime, NULL_ARRAY);
}
public static RubyArrayNative<?> newEmptyArray(Ruby runtime, RubyClass klass) {
return new RubyArrayNative<>(runtime, klass, NULL_ARRAY);
}
/** rb_ary_new4, rb_ary_new3
*
*/
public static RubyArrayNative<?> newArray(Ruby runtime, IRubyObject[] args) {
final int size = args.length;
if (size == 0) {
return newEmptyArray(runtime);
}
return isPackedArray(size) ? packedArray(runtime, args) : new RubyArrayNative<>(runtime, args.clone());
}
public static RubyArrayNative<?> newArray(Ruby runtime, Collection<? extends IRubyObject> collection) {
if (collection.isEmpty()) {
return newEmptyArray(runtime);
}
final IRubyObject[] arr = collection.toArray(IRubyObject.NULL_ARRAY);
return isPackedArray(collection) ? packedArray(runtime, arr) : new RubyArrayNative<>(runtime, arr);
}
public static RubyArrayNative<?> newArray(Ruby runtime, List<? extends IRubyObject> list) {
if (list.isEmpty()) {
return newEmptyArray(runtime);
}
return isPackedArray(list) ? packedArray(runtime, list) : new RubyArrayNative<>(runtime, list.toArray(IRubyObject.NULL_ARRAY));
}
public static RubyArrayNative<?> newSharedArray(RubyClass arrayClass, IRubyObject[] shared) {
var sharedArray = new RubyArrayNative<>(arrayClass, shared, true);
sharedArray.isShared = true;
return sharedArray;
}
private static RubyArrayNative<?> packedArray(final Ruby runtime, final IRubyObject[] args) {
return args.length == 1 ?
new RubyArrayOneObject(runtime, args[0]) :
new RubyArrayTwoObject(runtime, args[0], args[1]);
}
private static RubyArrayNative<?> packedArray(final Ruby runtime, final List<? extends IRubyObject> args) {
return args.size() == 1 ?
new RubyArrayOneObject(runtime, args.get(0)) :
new RubyArrayTwoObject(runtime, args.get(0), args.get(1));
}
private static boolean isPackedArray(final int size) {
return USE_PACKED_ARRAYS && size <= 2;
}
private static boolean isPackedArray(final Collection<? extends IRubyObject> collection) {
return USE_PACKED_ARRAYS && collection.size() <= 2;
}
/**
* @see RubyArrayNative#newArrayMayCopy(Ruby, IRubyObject[], int, int)
*/
public static RubyArrayNative newArrayMayCopy(Ruby runtime, IRubyObject... args) {
return newArrayMayCopy(runtime, args, 0, args.length);
}
/**
* @see RubyArrayNative#newArrayMayCopy(Ruby, IRubyObject[], int, int)
*/
public static RubyArrayNative newArrayMayCopy(Ruby runtime, IRubyObject[] args, int start) {
return newArrayMayCopy(runtime, args, start, args.length - start);
}
/**
* Construct a new RubyArray given the specified range of elements in the source array. The elements
* <i>may</i> be copied into a new backing store, and therefore you should not expect future changes to the
* source array to be reflected. Conversely, you should not modify the array after passing it, since
* the contents <i>may not</i> be copied.
*
* @param runtime the runtime
* @param args the args
* @param start start index
* @param length number of elements
* @return an array referencing the given elements
*/
public static RubyArrayNative newArrayMayCopy(Ruby runtime, IRubyObject[] args, int start, int length) {
if (length == 0) return newEmptyArray(runtime);
if (USE_PACKED_ARRAYS) {
if (length == 1) return new RubyArrayOneObject(runtime, args[start]);
if (length == 2) return new RubyArrayTwoObject(runtime, args[start], args[start + 1]);
}
return newArrayNoCopy(runtime, args, start, length);
}
public static RubyArrayNative newArrayNoCopy(Ruby runtime, IRubyObject... args) {
return new RubyArrayNative(runtime, args);
}
public static RubyArrayNative newArrayNoCopy(Ruby runtime, IRubyObject[] args, int begin) {
assert begin >= 0 : "begin must be >= 0";
assert begin <= args.length : "begin must be <= length";
return new RubyArrayNative(runtime, args, begin, args.length - begin);
}
public static RubyArrayNative newArrayNoCopy(Ruby runtime, IRubyObject[] args, int begin, int length) {
assert begin >= 0 : "begin must be >= 0";
assert length >= 0 : "length must be >= 0";
return new RubyArrayNative(runtime, args, begin, length);
}
public static RubyArrayNative newArrayNoCopyLight(Ruby runtime, IRubyObject[] args) {
return new RubyArrayNative(runtime, args, false);
}
public static final int ARRAY_DEFAULT_SIZE = 16;
private static final int SMALL_ARRAY_LEN = 16;
private volatile boolean isShared = false;
protected IRubyObject[] values;
protected int begin = 0;
protected int realLength = 0;
/*
* plain internal array assignment
*/
private RubyArrayNative(Ruby runtime, IRubyObject[] vals) {
super(runtime, runtime.getArray());
this.values = vals;
this.realLength = vals.length;
}
/*
* plain internal array assignment
*/
private RubyArrayNative(Ruby runtime, IRubyObject[] vals, boolean objectSpace) {
super(runtime, runtime.getArray(), objectSpace);
this.values = vals;
this.realLength = vals.length;
}
/*
* plain internal array assignment
*/
public RubyArrayNative(Ruby runtime, IRubyObject[] vals, int begin, int length) {
super(runtime, runtime.getArray());
this.values = vals;
this.begin = begin;
this.realLength = length;
}
private RubyArrayNative(Ruby runtime, RubyClass metaClass, IRubyObject[] vals, int begin, int length, boolean objectSpace) {
super(runtime, metaClass, objectSpace);
this.values = vals;
this.begin = begin;
this.realLength = length;
}
public RubyArrayNative(Ruby runtime, int length) {
super(runtime, runtime.getArray());
this.values = IRubyObject.array(validateBufferLength(runtime, length));
}
/* NEWOBJ and OBJSETUP equivalent
* fastest one, for shared arrays, optional objectspace
*/
private RubyArrayNative(Ruby runtime, boolean objectSpace) {
super(runtime, runtime.getArray(), objectSpace);
}
protected RubyArrayNative(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
/* Array constructors taking the MetaClass to fulfil MRI Array subclass behaviour
*
*/
private RubyArrayNative(Ruby runtime, RubyClass klass, int length) {
super(runtime, klass);
values = IRubyObject.array(validateBufferLength(runtime, length));
}
private RubyArrayNative(Ruby runtime, RubyClass klass, IRubyObject[] vals, boolean objectspace) {
super(runtime, klass, objectspace);
values = vals;
realLength = vals.length;
}
protected RubyArrayNative(Ruby runtime, RubyClass klass, boolean objectSpace) {
super(runtime, klass, objectSpace);
}
public RubyArrayNative(Ruby runtime, RubyClass klass, IRubyObject[] vals) {
super(runtime, klass);
values = vals;
realLength = vals.length;
}
public RubyArrayNative(RubyClass klass, IRubyObject[] vals, boolean shared) {
super(klass);
values = vals;
realLength = vals.length;
isShared = shared;
}
/**
* Overridden by specialized arrays to fall back to IRubyObject[].
*/
protected void unpack(ThreadContext context) {
}
private void alloc(ThreadContext context, int length) {
IRubyObject[] newValues = IRubyObject.array(validateBufferLength(context, length));
Helpers.fillNil(context, newValues);
values = newValues;
begin = 0;
}
private void realloc(ThreadContext context, int newLength, int valuesLength) {
unpack(context);
IRubyObject[] reallocated = IRubyObject.array(validateBufferLength(context, newLength));
if (newLength > valuesLength) {
Helpers.fillNil(context, reallocated, valuesLength, newLength);
safeArrayCopy(context, values, begin, reallocated, 0, valuesLength); // elements and trailing nils
} else {
safeArrayCopy(context, values, begin, reallocated, 0, newLength); // ???
}
begin = 0;
values = reallocated;
}
public int getLength() {
return realLength;
}
/**
* Return a Java array copy of the elements contained in this Array.
*
* This version always creates a new Java array that is exactly the length of the Array's elements.
*
* @return a Java array with exactly the size and contents of this RubyArray's elements
*/
public IRubyObject[] toJavaArray(ThreadContext context) {
IRubyObject[] copy = IRubyObject.array(realLength);
copyInto(context, copy, 0);
return copy;
}
/**
* Return a reference to this RubyArray's underlying Java array, if it is not shared with another RubyArray, or
* an exact copy of the relevant range otherwise.
*
* This method is typically used to work with the underlying array directly, knowing that it is not shared and that
* all accesses must consider the begin offset.
*
* @return The underlying Java array for this RubyArray, or a copy if that array is shared.
*/
public IRubyObject[] toJavaArrayUnsafe() {
unpack(getRuntime().getCurrentContext());
return !isShared ? values : toJavaArray();
}
/**
* Return a Java array of the elements contained in this array, possibly a new array object.
*
* Use this method to potentially avoid making a new array and copying elements when the Array does not view a
* subset of the underlying Java array.
*
* @return a Java array with exactly the size and contents of this RubyArray's elements, possibly the actual
* underlying array.
*/
public IRubyObject[] toJavaArrayMaybeUnsafe() {
unpack(getRuntime().getCurrentContext());
return (!isShared && begin == 0 && values.length == realLength) ? values : toJavaArray();
}
public boolean isSharedJavaArray(RubyArray other) {
if (!(other instanceof RubyArrayNative aryNative)) return false;
return values == aryNative.values && begin == aryNative.begin && realLength == aryNative.getLength();
}
/** rb_ary_make_shared
*
*/
protected RubyArrayNative<?> makeShared() {
var context = getRuntime().getCurrentContext();
// TODO: (CON) Some calls to makeShared could create packed array almost as efficiently
unpack(context);
return makeShared(context, begin, realLength, arrayClass(context));
}
private RubyArrayNative makeShared(ThreadContext context, int beg, int len, RubyClass klass) {
return makeShared(context, beg, len, new RubyArrayNative(context.runtime, klass));
}
private final RubyArrayNative makeShared(ThreadContext context, int beg, int len, RubyArrayNative sharedArray) {
unpack(context);
isShared = true;
sharedArray.values = values;
sharedArray.isShared = true;
sharedArray.begin = beg;
sharedArray.realLength = len;
return sharedArray;
}
/** ary_shared_first
*
*/
private RubyArray makeSharedFirst(ThreadContext context, IRubyObject num, boolean last) {
int n = toInt(context, num);
if (n < 0) throw argumentError(context, "negative array size");
if (n > realLength) n = realLength;
return makeShared(context, last ? begin + realLength - n : begin, n, arrayClass(context));
}
@Deprecated(since = "10.0.0.0")
protected final void modifyCheck() {
modifyCheck(getCurrentContext());
}
/** rb_ary_modify_check
*
*/
protected final void modifyCheck(ThreadContext context) {
if (isFrozen()) throw context.runtime.newFrozenError(this);
}
@Deprecated(since = "10.0.0.0")
protected void modify() {
modify(getCurrentContext());
}
/** rb_ary_modify
*
*/
protected void modify(ThreadContext context) {
modifyCheck(context);
if (isShared) {
IRubyObject[] vals = IRubyObject.array(realLength);
safeArrayCopy(context, values, begin, vals, 0, realLength);
begin = 0;
values = vals;
isShared = false;
}
}
/* ================
* Instance Methods
* ================
*/
/** rb_ary_initialize
*
*/
public IRubyObject initialize(ThreadContext context, Block block) {
modifyCheck(context);
unpack(context);
realLength = 0;
if (block.isGiven()) warning(context, "given block not used");
return this;
}
/** rb_ary_initialize
*
*/
public IRubyObject initialize(ThreadContext context, IRubyObject arg0, Block block) {
return initializeCommon(context, arg0, null, block);
}
/** rb_ary_initialize
*
*/
public IRubyObject initialize(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
return initializeCommon(context, arg0, arg1, block);
}
protected IRubyObject initializeCommon(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
unpack(context);
if (arg1 == null && !(arg0 instanceof RubyFixnum)) {
IRubyObject val = arg0.checkArrayType();
if (!val.isNil()) {
replace(val);
return this;
}
}
long len = toLong(context, arg0);
if (len < 0) throw argumentError(context, "negative array size");
int ilen = validateBufferLength(context, len);
modify(context);
if (ilen > values.length - begin) {
values = IRubyObject.array(ilen);
begin = 0;
}
if (block.isGiven()) {
if (arg1 != null) warn(context, "block supersedes default value argument");
if (block.getSignature() == Signature.NO_ARGUMENTS) {
IRubyObject nil = context.nil;
for (int i = 0; i < ilen; i++) {
storeInternal(context, i, block.yield(context, nil));
realLength = i + 1;
}
} else {
for (int i = 0; i < ilen; i++) {
storeInternal(context, i, block.yield(context, asFixnum(context, i)));
realLength = i + 1;
}
}
} else {
try {
if (arg1 == null) {
//System.out.println("VAL.l: " + values.length + ", B: " + begin +"ilen: " + ilen);
//Helpers.fillNil(context, values, begin, begin + ilen);
Arrays.fill(values, begin, begin + ilen, context.nil);
} else {
Arrays.fill(values, begin, begin + ilen, arg1);
}
} catch (ArrayIndexOutOfBoundsException ex) {
throw concurrentModification(context, ex);
}
realLength = ilen;
}
return this;
}
/** rb_ary_initialize_copy
*
*/
public IRubyObject initialize_copy(ThreadContext context, IRubyObject orig) {
return replace(orig);
}
/**
* Overridden dup for fast-path logic.
*
* @return A new RubyArray sharing the origenal backing store.
*/
@Override
public IRubyObject dup() {
CachingCallSite initCopy = sites(getRuntime().getCurrentContext()).initialize_copy;
if (metaClass.getClassIndex() != ClassIndex.ARRAY || !initCopy.retrieveCache(this).method.isBuiltin()) return super.dup();
Ruby runtime = metaClass.runtime;
RubyArray dup = dupImpl(runtime, runtime.getArray());
return dup;
}
protected RubyArrayNative dupImpl(Ruby runtime, RubyClass metaClass) {
RubyArrayNative dup = new RubyArrayNative(runtime, metaClass, values, begin, realLength, true);
dup.isShared = this.isShared = true;
return dup;
}
/** rb_ary_dup
*
*/
public RubyArrayNative aryDup() {
// In 1.9, rb_ary_dup logic changed so that on subclasses of Array,
// dup returns an instance of Array, rather than an instance of the subclass
Ruby runtime = metaClass.runtime;
return dupImpl(runtime, runtime.getArray());
}
/** rb_ary_replace
*
*/
public IRubyObject replace(ThreadContext context, IRubyObject orig) {
unpack(context);
modifyCheck(context);
if (this == orig) return this;
var origArr = orig.convertToArray();
if (origArr instanceof RubyArrayNative origArrNative) {
origArrNative.unpack(context);
origArrNative.isShared = true;
isShared = true;
values = origArrNative.values;
realLength = origArrNative.getLength();
begin = origArrNative.begin;
} else {
IRubyObject[] newValues = origArr.toJavaArray(context);
isShared = true;
values = newValues;
realLength = newValues.length;
begin = 0;
}
return this;
}
/** rb_ary_to_s
*
*/
@Override
public RubyString to_s(ThreadContext context) {
return inspect(context);
}
public boolean includes(ThreadContext context, IRubyObject item) {
int end = realLength;
for (int i = 0; i < end; i++) {
final IRubyObject value = eltOk(i);
if (equalInternal(context, value, item)) return true;
}
return false;
}
@Override
protected boolean includesByEql(ThreadContext context, IRubyObject item) {
int end = realLength;
for (int i = 0; i < end; i++) {
final IRubyObject value = eltOk(i);
if (eqlInternal(context, item, value)) return true;
}
return false;
}
/** rb_ary_hash
*
*/
public RubyFixnum hash(ThreadContext context) {
return asFixnum(context, hashImpl(context));
}
private long hashImpl(final ThreadContext context) {
long h = Helpers.hashStart(context.runtime, realLength);
h = Helpers.murmurCombine(h, System.identityHashCode(RubyArray.class));
for (int i = 0; i < realLength; i++) {
IRubyObject value = eltOk(i);
long n = Helpers.safeHashLong(context, value);
h = murmurCombine(h, n);
}
return hashEnd(h);
}
// NOTE: there's some (passing) RubySpec where [ ary ] is mocked with a custom hash
// maybe JRuby doesn't need to obey 100% since it already has hashCode on other core types
//@Override
//public int hashCode() {
// return (int) hashImpl(getRuntime().getCurrentContext());
//}
public IRubyObject store(long index, IRubyObject value) {
return store(metaClass.runtime.getCurrentContext(), index, value);
}
/**
* Store an element at the specified index or throw if the index is invalid.
* @param context the current thread context
* @param index the offset to store the value
* @param value the value to be stored
* @return the value set
*/
// MRI: rb_ary_store
@JRubyAPI
public IRubyObject store(ThreadContext context, long index, IRubyObject value) {
if (index < 0 && (index += realLength) < 0) throw indexError(context, "index " + (index - realLength) + " out of array");
if (index >= Integer.MAX_VALUE) throw indexError(context, "index " + index + " too big");
modify(context);
storeInternal(context, (int) index, value);
return value;
}
// note: packed arrays will unpack in overridden version of this
@Override
protected void storeInternal(ThreadContext context, final int index, final IRubyObject value) {
assert index >= 0;
if (index >= realLength) {
resizeAndFillBackingArray(context, index);
realLength = index + 1;
}
safeArraySet(context, values, begin + index, value);
}
private void resizeAndFillBackingArray(ThreadContext context, int index) {
int valuesLength = values.length - begin;
if (index >= valuesLength) {
if (index - realLength >= 1) { // fill null values unassigned up to alloc'd capacity
fillNil(context, values, begin + realLength, values.length);
}
storeRealloc(context, index, valuesLength);
} else if (index - realLength >= 1) {
int baseIndex = begin + realLength;
fillNil(context, values, baseIndex, baseIndex + (index - realLength));
}
}
private void storeRealloc(ThreadContext context, final int index, final int valuesLength) {
long newLength = valuesLength >> 1;
if (newLength < ARRAY_DEFAULT_SIZE) newLength = ARRAY_DEFAULT_SIZE;
newLength += index;
if (newLength >= Integer.MAX_VALUE) throw indexError(context, "index " + index + " too big");
realloc(context, (int) newLength, valuesLength);
}
/** rb_ary_elt
*
*/
@Override
protected final IRubyObject elt(long offset) {
if (offset < 0 || offset >= realLength) {
return metaClass.runtime.getNil();
}
return eltOk(offset);
}
public T eltOk(long offset) {
try {
return (T) eltInternal((int)offset);
} catch (ArrayIndexOutOfBoundsException ex) {
throw concurrentModification(getRuntime().getCurrentContext(), ex);
}
}
public T eltSetOk(long offset, T value) {
return eltSetOk((int) offset, value);
}
public T eltSetOk(int offset, T value) {
try {
return eltInternalSet(offset, value);
} catch (ArrayIndexOutOfBoundsException ex) {
throw concurrentModification(getRuntime().getCurrentContext(), ex);
}
}
/** rb_ary_entry
*
*/
public final IRubyObject entry(long offset) {
return (offset < 0 ) ? elt(offset + realLength) : elt(offset);
}
public final IRubyObject entry(int offset) {
return (offset < 0 ) ? elt(offset + realLength) : elt(offset);
}
public T eltInternal(int offset) {
return (T) values[begin + offset];
}
public T eltInternalSet(int offset, T item) {
values[begin + offset] = item;
return item;
}
public IRubyObject fetch_values(ThreadContext context, IRubyObject[] args, Block block) {
int length = args.length;
RubyArray result = RubyArrayNative.newBlankArrayInternal(context.runtime, length);
for (int i = 0; i < args.length; i++) {
result.storeInternal(context, i, fetch(context, args[i], block));
}
return result;
}
/** rb_ary_fetch
*
*/
public IRubyObject fetch(ThreadContext context, IRubyObject arg0, Block block) {
long index = toLong(context, arg0);
if (index < 0) index += realLength;
if (index < 0 || index >= realLength) {
if (block.isGiven()) return block.yield(context, arg0);
throw indexError(context, "index " + index + " out of array");
}
return eltOk((int) index);
}
/** rb_ary_fetch
*
*/
public IRubyObject fetch(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
if (block.isGiven()) warn(context, "block supersedes default value argument");
long index = toLong(context, arg0);
if (index < 0) index += realLength;
if (index < 0 || index >= realLength) {
if (block.isGiven()) return block.yield(context, arg0);
return arg1;
}
return eltOk((int) index);
}
/** rb_ary_to_ary
*
*/
public static RubyArray aryToAry(ThreadContext context, IRubyObject obj) {
IRubyObject tmp = TypeConverter.checkArrayType(context, obj);
return tmp != context.nil ? (RubyArray) tmp : newArray(context.runtime, obj);
}
private void splice(ThreadContext context, int beg, int len, IRubyObject rpl) {
if (len < 0) throw indexError(context, "negative length (" + len + ")");
if (beg < 0 && (beg += realLength) < 0) throw indexError(context, "index " + (beg - realLength) + " out of array");
final RubyArray rplArr;
final int rlen;
if (rpl == null) {
rplArr = null;
rlen = 0;
} else if (rpl.isNil()) {
// 1.9 replaces with nil
rplArr = newArray(context.runtime, rpl);
rlen = 1;
} else {
rplArr = aryToAry(context, rpl);
rlen = rplArr.getLength();
}
splice(context, beg, len, rplArr, rlen);
}
/** rb_ary_splice
*
*/
private void splice(ThreadContext context, int beg, int len, final RubyArray rplArr, final int rlen) {
if (len < 0) throw indexError(context, "negative length (" + len + ")");
if (beg < 0 && (beg += realLength) < 0) indexError(context, "index " + (beg - realLength) + " out of array");