Ruby  2.0.0p195(2013-05-14revision40734)
array.c
Go to the documentation of this file.
1 /**********************************************************************
2 
3  array.c -
4 
5  $Author: nagachika $
6  created at: Fri Aug 6 09:46:12 JST 1993
7 
8  Copyright (C) 1993-2007 Yukihiro Matsumoto
9  Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10  Copyright (C) 2000 Information-technology Promotion Agency, Japan
11 
12 **********************************************************************/
13 
14 #include "ruby/ruby.h"
15 #include "ruby/util.h"
16 #include "ruby/st.h"
17 #include "ruby/encoding.h"
18 #include "internal.h"
19 #include "probes.h"
20 #include "id.h"
21 
22 #ifndef ARRAY_DEBUG
23 # define NDEBUG
24 #endif
25 #include <assert.h>
26 
27 #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
28 
30 
32 
33 #define ARY_DEFAULT_SIZE 16
34 #define ARY_MAX_SIZE (LONG_MAX / (int)sizeof(VALUE))
35 
36 void
37 rb_mem_clear(register VALUE *mem, register long size)
38 {
39  while (size--) {
40  *mem++ = Qnil;
41  }
42 }
43 
44 static inline void
45 memfill(register VALUE *mem, register long size, register VALUE val)
46 {
47  while (size--) {
48  *mem++ = val;
49  }
50 }
51 
52 # define ARY_SHARED_P(ary) \
53  (assert(!FL_TEST((ary), ELTS_SHARED) || !FL_TEST((ary), RARRAY_EMBED_FLAG)), \
54  FL_TEST((ary),ELTS_SHARED)!=0)
55 # define ARY_EMBED_P(ary) \
56  (assert(!FL_TEST((ary), ELTS_SHARED) || !FL_TEST((ary), RARRAY_EMBED_FLAG)), \
57  FL_TEST((ary), RARRAY_EMBED_FLAG)!=0)
58 
59 #define ARY_HEAP_PTR(a) (assert(!ARY_EMBED_P(a)), RARRAY(a)->as.heap.ptr)
60 #define ARY_HEAP_LEN(a) (assert(!ARY_EMBED_P(a)), RARRAY(a)->as.heap.len)
61 #define ARY_EMBED_PTR(a) (assert(ARY_EMBED_P(a)), RARRAY(a)->as.ary)
62 #define ARY_EMBED_LEN(a) \
63  (assert(ARY_EMBED_P(a)), \
64  (long)((RBASIC(a)->flags >> RARRAY_EMBED_LEN_SHIFT) & \
65  (RARRAY_EMBED_LEN_MASK >> RARRAY_EMBED_LEN_SHIFT)))
66 
67 #define ARY_OWNS_HEAP_P(a) (!FL_TEST((a), ELTS_SHARED|RARRAY_EMBED_FLAG))
68 #define FL_SET_EMBED(a) do { \
69  assert(!ARY_SHARED_P(a)); \
70  assert(!OBJ_FROZEN(a)); \
71  FL_SET((a), RARRAY_EMBED_FLAG); \
72 } while (0)
73 #define FL_UNSET_EMBED(ary) FL_UNSET((ary), RARRAY_EMBED_FLAG|RARRAY_EMBED_LEN_MASK)
74 #define FL_SET_SHARED(ary) do { \
75  assert(!ARY_EMBED_P(ary)); \
76  FL_SET((ary), ELTS_SHARED); \
77 } while (0)
78 #define FL_UNSET_SHARED(ary) FL_UNSET((ary), ELTS_SHARED)
79 
80 #define ARY_SET_PTR(ary, p) do { \
81  assert(!ARY_EMBED_P(ary)); \
82  assert(!OBJ_FROZEN(ary)); \
83  RARRAY(ary)->as.heap.ptr = (p); \
84 } while (0)
85 #define ARY_SET_EMBED_LEN(ary, n) do { \
86  long tmp_n = (n); \
87  assert(ARY_EMBED_P(ary)); \
88  assert(!OBJ_FROZEN(ary)); \
89  RBASIC(ary)->flags &= ~RARRAY_EMBED_LEN_MASK; \
90  RBASIC(ary)->flags |= (tmp_n) << RARRAY_EMBED_LEN_SHIFT; \
91 } while (0)
92 #define ARY_SET_HEAP_LEN(ary, n) do { \
93  assert(!ARY_EMBED_P(ary)); \
94  RARRAY(ary)->as.heap.len = (n); \
95 } while (0)
96 #define ARY_SET_LEN(ary, n) do { \
97  if (ARY_EMBED_P(ary)) { \
98  ARY_SET_EMBED_LEN((ary), (n)); \
99  } \
100  else { \
101  ARY_SET_HEAP_LEN((ary), (n)); \
102  } \
103  assert(RARRAY_LEN(ary) == (n)); \
104 } while (0)
105 #define ARY_INCREASE_PTR(ary, n) do { \
106  assert(!ARY_EMBED_P(ary)); \
107  assert(!OBJ_FROZEN(ary)); \
108  RARRAY(ary)->as.heap.ptr += (n); \
109 } while (0)
110 #define ARY_INCREASE_LEN(ary, n) do { \
111  assert(!OBJ_FROZEN(ary)); \
112  if (ARY_EMBED_P(ary)) { \
113  ARY_SET_EMBED_LEN((ary), RARRAY_LEN(ary)+(n)); \
114  } \
115  else { \
116  RARRAY(ary)->as.heap.len += (n); \
117  } \
118 } while (0)
119 
120 #define ARY_CAPA(ary) (ARY_EMBED_P(ary) ? RARRAY_EMBED_LEN_MAX : \
121  ARY_SHARED_ROOT_P(ary) ? RARRAY_LEN(ary) : RARRAY(ary)->as.heap.aux.capa)
122 #define ARY_SET_CAPA(ary, n) do { \
123  assert(!ARY_EMBED_P(ary)); \
124  assert(!ARY_SHARED_P(ary)); \
125  assert(!OBJ_FROZEN(ary)); \
126  RARRAY(ary)->as.heap.aux.capa = (n); \
127 } while (0)
128 
129 #define ARY_SHARED(ary) (assert(ARY_SHARED_P(ary)), RARRAY(ary)->as.heap.aux.shared)
130 #define ARY_SET_SHARED(ary, value) do { \
131  assert(!ARY_EMBED_P(ary)); \
132  assert(ARY_SHARED_P(ary)); \
133  assert(ARY_SHARED_ROOT_P(value)); \
134  RARRAY(ary)->as.heap.aux.shared = (value); \
135 } while (0)
136 #define RARRAY_SHARED_ROOT_FLAG FL_USER5
137 #define ARY_SHARED_ROOT_P(ary) (FL_TEST((ary), RARRAY_SHARED_ROOT_FLAG))
138 #define ARY_SHARED_NUM(ary) \
139  (assert(ARY_SHARED_ROOT_P(ary)), RARRAY(ary)->as.heap.aux.capa)
140 #define ARY_SET_SHARED_NUM(ary, value) do { \
141  assert(ARY_SHARED_ROOT_P(ary)); \
142  RARRAY(ary)->as.heap.aux.capa = (value); \
143 } while (0)
144 #define FL_SET_SHARED_ROOT(ary) do { \
145  assert(!ARY_EMBED_P(ary)); \
146  FL_SET((ary), RARRAY_SHARED_ROOT_FLAG); \
147 } while (0)
148 
149 static void
150 ary_resize_capa(VALUE ary, long capacity)
151 {
152  assert(RARRAY_LEN(ary) <= capacity);
153  assert(!OBJ_FROZEN(ary));
154  assert(!ARY_SHARED_P(ary));
155  if (capacity > RARRAY_EMBED_LEN_MAX) {
156  if (ARY_EMBED_P(ary)) {
157  long len = ARY_EMBED_LEN(ary);
158  VALUE *ptr = ALLOC_N(VALUE, (capacity));
159  MEMCPY(ptr, ARY_EMBED_PTR(ary), VALUE, len);
160  FL_UNSET_EMBED(ary);
161  ARY_SET_PTR(ary, ptr);
162  ARY_SET_HEAP_LEN(ary, len);
163  }
164  else {
165  REALLOC_N(RARRAY(ary)->as.heap.ptr, VALUE, (capacity));
166  }
167  ARY_SET_CAPA(ary, (capacity));
168  }
169  else {
170  if (!ARY_EMBED_P(ary)) {
171  long len = RARRAY_LEN(ary);
172  VALUE *ptr = RARRAY_PTR(ary);
173  if (len > capacity) len = capacity;
174  MEMCPY(RARRAY(ary)->as.ary, ptr, VALUE, len);
175  FL_SET_EMBED(ary);
176  ARY_SET_LEN(ary, len);
177  xfree(ptr);
178  }
179  }
180 }
181 
182 static void
183 ary_double_capa(VALUE ary, long min)
184 {
185  long new_capa = ARY_CAPA(ary) / 2;
186 
187  if (new_capa < ARY_DEFAULT_SIZE) {
188  new_capa = ARY_DEFAULT_SIZE;
189  }
190  if (new_capa >= ARY_MAX_SIZE - min) {
191  new_capa = (ARY_MAX_SIZE - min) / 2;
192  }
193  new_capa += min;
194  ary_resize_capa(ary, new_capa);
195 }
196 
197 static void
199 {
200  if (shared) {
201  long num = ARY_SHARED_NUM(shared) - 1;
202  if (num == 0) {
203  rb_ary_free(shared);
204  rb_gc_force_recycle(shared);
205  }
206  else if (num > 0) {
207  ARY_SET_SHARED_NUM(shared, num);
208  }
209  }
210 }
211 
212 static void
214 {
215  VALUE shared = RARRAY(ary)->as.heap.aux.shared;
216  rb_ary_decrement_share(shared);
217  FL_UNSET_SHARED(ary);
218 }
219 
220 static inline void
222 {
223  if (ARY_SHARED_P(ary) && !ARY_EMBED_P(ary)) {
224  rb_ary_unshare(ary);
225  }
226 }
227 
228 static VALUE
230 {
231  long num = ARY_SHARED_NUM(shared);
232  if (num >= 0) {
233  ARY_SET_SHARED_NUM(shared, num + 1);
234  }
235  return shared;
236 }
237 
238 static void
240 {
241  rb_ary_increment_share(shared);
242  FL_SET_SHARED(ary);
243  ARY_SET_SHARED(ary, shared);
244 }
245 
246 static inline void
248 {
249  rb_check_frozen(ary);
250  if (!OBJ_UNTRUSTED(ary) && rb_safe_level() >= 4)
251  rb_raise(rb_eSecurityError, "Insecure: can't modify array");
252 }
253 
254 void
256 {
257  rb_ary_modify_check(ary);
258  if (ARY_SHARED_P(ary)) {
259  long len = RARRAY_LEN(ary);
260  VALUE shared = ARY_SHARED(ary);
261  if (len <= RARRAY_EMBED_LEN_MAX) {
262  VALUE *ptr = ARY_HEAP_PTR(ary);
263  FL_UNSET_SHARED(ary);
264  FL_SET_EMBED(ary);
265  MEMCPY(ARY_EMBED_PTR(ary), ptr, VALUE, len);
266  rb_ary_decrement_share(shared);
267  ARY_SET_EMBED_LEN(ary, len);
268  }
269  else if (ARY_SHARED_NUM(shared) == 1 && len > (RARRAY_LEN(shared)>>1)) {
270  long shift = RARRAY_PTR(ary) - RARRAY_PTR(shared);
271  ARY_SET_PTR(ary, RARRAY_PTR(shared));
272  ARY_SET_CAPA(ary, RARRAY_LEN(shared));
273  MEMMOVE(RARRAY_PTR(ary), RARRAY_PTR(ary)+shift, VALUE, len);
274  FL_UNSET_SHARED(ary);
275  FL_SET_EMBED(shared);
276  rb_ary_decrement_share(shared);
277  }
278  else {
279  VALUE *ptr = ALLOC_N(VALUE, len);
280  MEMCPY(ptr, RARRAY_PTR(ary), VALUE, len);
281  rb_ary_unshare(ary);
282  ARY_SET_CAPA(ary, len);
283  ARY_SET_PTR(ary, ptr);
284  }
285  }
286 }
287 
288 static void
289 ary_ensure_room_for_push(VALUE ary, long add_len)
290 {
291  long new_len = RARRAY_LEN(ary) + add_len;
292  long capa;
293 
294  if (ARY_SHARED_P(ary)) {
295  if (new_len > RARRAY_EMBED_LEN_MAX) {
296  VALUE shared = ARY_SHARED(ary);
297  if (ARY_SHARED_NUM(shared) == 1) {
298  if (RARRAY_PTR(ary) - RARRAY_PTR(shared) + new_len <= RARRAY_LEN(shared)) {
299  rb_ary_modify_check(ary);
300  }
301  else {
302  /* if array is shared, than it is likely it participate in push/shift pattern */
303  rb_ary_modify(ary);
304  capa = ARY_CAPA(ary);
305  if (new_len > capa - (capa >> 6)) {
306  ary_double_capa(ary, new_len);
307  }
308  }
309  return;
310  }
311  }
312  }
313  rb_ary_modify(ary);
314  capa = ARY_CAPA(ary);
315  if (new_len > capa) {
316  ary_double_capa(ary, new_len);
317  }
318 }
319 
320 /*
321  * call-seq:
322  * ary.freeze -> ary
323  *
324  * Calls Object#freeze on +ary+ to prevent any further
325  * modification. A RuntimeError will be raised if a modification
326  * attempt is made.
327  *
328  */
329 
330 VALUE
332 {
333  return rb_obj_freeze(ary);
334 }
335 
336 /*
337  * call-seq:
338  * ary.frozen? -> true or false
339  *
340  * Return +true+ if this array is frozen (or temporarily frozen
341  * while being sorted). See also Object#frozen?
342  */
343 
344 static VALUE
346 {
347  if (OBJ_FROZEN(ary)) return Qtrue;
348  return Qfalse;
349 }
350 
351 /* This can be used to take a snapshot of an array (with
352  e.g. rb_ary_replace) and check later whether the array has been
353  modified from the snapshot. The snapshot is cheap, though if
354  something does modify the array it will pay the cost of copying
355  it. If Array#pop or Array#shift has been called, the array will
356  be still shared with the snapshot, but the array length will
357  differ. */
358 VALUE
360 {
361  if (!ARY_EMBED_P(ary1) && ARY_SHARED_P(ary1) &&
362  !ARY_EMBED_P(ary2) && ARY_SHARED_P(ary2) &&
363  RARRAY(ary1)->as.heap.aux.shared == RARRAY(ary2)->as.heap.aux.shared &&
364  RARRAY(ary1)->as.heap.len == RARRAY(ary2)->as.heap.len) {
365  return Qtrue;
366  }
367  return Qfalse;
368 }
369 
370 static VALUE
372 {
373  NEWOBJ_OF(ary, struct RArray, klass, T_ARRAY);
374  FL_SET_EMBED((VALUE)ary);
375  ARY_SET_EMBED_LEN((VALUE)ary, 0);
376 
377  return (VALUE)ary;
378 }
379 
380 static VALUE
382 {
385  }
386 
387  return ary_alloc(klass);
388 }
389 
390 static VALUE
391 ary_new(VALUE klass, long capa)
392 {
393  VALUE ary;
394 
395  if (capa < 0) {
396  rb_raise(rb_eArgError, "negative array size (or size too big)");
397  }
398  if (capa > ARY_MAX_SIZE) {
399  rb_raise(rb_eArgError, "array size too big");
400  }
401 
404  }
405 
406  ary = ary_alloc(klass);
407  if (capa > RARRAY_EMBED_LEN_MAX) {
408  FL_UNSET_EMBED(ary);
409  ARY_SET_PTR(ary, ALLOC_N(VALUE, capa));
410  ARY_SET_CAPA(ary, capa);
411  ARY_SET_HEAP_LEN(ary, 0);
412  }
413 
414  return ary;
415 }
416 
417 VALUE
418 rb_ary_new2(long capa)
419 {
420  return ary_new(rb_cArray, capa);
421 }
422 
423 
424 VALUE
426 {
428 }
429 
430 #include <stdarg.h>
431 
432 VALUE
433 rb_ary_new3(long n, ...)
434 {
435  va_list ar;
436  VALUE ary;
437  long i;
438 
439  ary = rb_ary_new2(n);
440 
441  va_start(ar, n);
442  for (i=0; i<n; i++) {
443  RARRAY_PTR(ary)[i] = va_arg(ar, VALUE);
444  }
445  va_end(ar);
446 
447  ARY_SET_LEN(ary, n);
448  return ary;
449 }
450 
451 VALUE
452 rb_ary_new4(long n, const VALUE *elts)
453 {
454  VALUE ary;
455 
456  ary = rb_ary_new2(n);
457  if (n > 0 && elts) {
458  MEMCPY(RARRAY_PTR(ary), elts, VALUE, n);
459  ARY_SET_LEN(ary, n);
460  }
461 
462  return ary;
463 }
464 
465 VALUE
466 rb_ary_tmp_new(long capa)
467 {
468  return ary_new(0, capa);
469 }
470 
471 void
473 {
474  if (ARY_OWNS_HEAP_P(ary)) {
475  xfree(ARY_HEAP_PTR(ary));
476  }
477 }
478 
479 RUBY_FUNC_EXPORTED size_t
481 {
482  if (ARY_OWNS_HEAP_P(ary)) {
483  return RARRAY(ary)->as.heap.aux.capa * sizeof(VALUE);
484  }
485  else {
486  return 0;
487  }
488 }
489 
490 static inline void
492 {
493  rb_ary_free(ary);
494  RBASIC(ary)->flags |= RARRAY_EMBED_FLAG;
495  RBASIC(ary)->flags &= ~RARRAY_EMBED_LEN_MASK;
496 }
497 
498 static VALUE
500 {
501  assert(!ARY_EMBED_P(ary));
502  if (ARY_SHARED_P(ary)) {
503  return ARY_SHARED(ary);
504  }
505  else if (ARY_SHARED_ROOT_P(ary)) {
506  return ary;
507  }
508  else if (OBJ_FROZEN(ary)) {
509  ary_resize_capa(ary, ARY_HEAP_LEN(ary));
510  FL_SET_SHARED_ROOT(ary);
511  ARY_SET_SHARED_NUM(ary, 1);
512  return ary;
513  }
514  else {
515  NEWOBJ_OF(shared, struct RArray, 0, T_ARRAY);
516  FL_UNSET_EMBED(shared);
517 
518  ARY_SET_LEN((VALUE)shared, ARY_CAPA(ary));
519  ARY_SET_PTR((VALUE)shared, RARRAY_PTR(ary));
520  rb_mem_clear(RARRAY_PTR(shared) + RARRAY_LEN(ary), ARY_CAPA(ary) - RARRAY_LEN(ary));
521  FL_SET_SHARED_ROOT(shared);
522  ARY_SET_SHARED_NUM((VALUE)shared, 1);
523  FL_SET_SHARED(ary);
524  ARY_SET_SHARED(ary, (VALUE)shared);
525  OBJ_FREEZE(shared);
526  return (VALUE)shared;
527  }
528 }
529 
530 
531 static VALUE
533 {
534  if (RARRAY_LEN(ary) <= RARRAY_EMBED_LEN_MAX) {
535  VALUE subst = rb_ary_new2(RARRAY_LEN(ary));
536  MEMCPY(ARY_EMBED_PTR(subst), RARRAY_PTR(ary), VALUE, RARRAY_LEN(ary));
537  ARY_SET_EMBED_LEN(subst, RARRAY_LEN(ary));
538  return subst;
539  }
540  else {
542  }
543 }
544 
545 VALUE
547 {
548  return rb_ary_new3(2, car, cdr);
549 }
550 
551 static VALUE
553 {
554  return rb_convert_type(ary, T_ARRAY, "Array", "to_ary");
555 }
556 
557 VALUE
559 {
560  return rb_check_convert_type(ary, T_ARRAY, "Array", "to_ary");
561 }
562 
563 /*
564  * call-seq:
565  * Array.try_convert(obj) -> array or nil
566  *
567  * Tries to convert +obj+ into an array, using +to_ary+ method. Returns the
568  * converted array or +nil+ if +obj+ cannot be converted for any reason.
569  * This method can be used to check if an argument is an array.
570  *
571  * Array.try_convert([1]) #=> [1]
572  * Array.try_convert("1") #=> nil
573  *
574  * if tmp = Array.try_convert(arg)
575  * # the argument is an array
576  * elsif tmp = String.try_convert(arg)
577  * # the argument is a string
578  * end
579  *
580  */
581 
582 static VALUE
584 {
585  return rb_check_array_type(ary);
586 }
587 
588 /*
589  * call-seq:
590  * Array.new(size=0, obj=nil)
591  * Array.new(array)
592  * Array.new(size) {|index| block }
593  *
594  * Returns a new array.
595  *
596  * In the first form, if no arguments are sent, the new array will be empty.
597  * When a +size+ and an optional +obj+ are sent, an array is created with
598  * +size+ copies of +obj+. Take notice that all elements will reference the
599  * same object +obj+.
600  *
601  * The second form creates a copy of the array passed as a parameter (the
602  * array is generated by calling to_ary on the parameter).
603  *
604  * first_array = ["Matz", "Guido"]
605  *
606  * second_array = Array.new(first_array) #=> ["Matz", "Guido"]
607  *
608  * first_array.equal? second_array #=> false
609  *
610  * In the last form, an array of the given size is created. Each element in
611  * this array is created by passing the element's index to the given block
612  * and storing the return value.
613  *
614  * Array.new(3){ |index| index ** 2 }
615  * # => [0, 1, 4]
616  *
617  * == Common gotchas
618  *
619  * When sending the second parameter, the same object will be used as the
620  * value for all the array elements:
621  *
622  * a = Array.new(2, Hash.new)
623  * # => [{}, {}]
624  *
625  * a[0]['cat'] = 'feline'
626  * a # => [{"cat"=>"feline"}, {"cat"=>"feline"}]
627  *
628  * a[1]['cat'] = 'Felix'
629  * a # => [{"cat"=>"Felix"}, {"cat"=>"Felix"}]
630  *
631  * Since all the Array elements store the same hash, changes to one of them
632  * will affect them all.
633  *
634  * If multiple copies are what you want, you should use the block
635  * version which uses the result of that block each time an element
636  * of the array needs to be initialized:
637  *
638  * a = Array.new(2) { Hash.new }
639  * a[0]['cat'] = 'feline'
640  * a # => [{"cat"=>"feline"}, {}]
641  *
642  */
643 
644 static VALUE
646 {
647  long len;
648  VALUE size, val;
649 
650  rb_ary_modify(ary);
651  if (argc == 0) {
652  if (ARY_OWNS_HEAP_P(ary) && RARRAY_PTR(ary)) {
653  xfree(RARRAY_PTR(ary));
654  }
655  rb_ary_unshare_safe(ary);
656  FL_SET_EMBED(ary);
657  ARY_SET_EMBED_LEN(ary, 0);
658  if (rb_block_given_p()) {
659  rb_warning("given block not used");
660  }
661  return ary;
662  }
663  rb_scan_args(argc, argv, "02", &size, &val);
664  if (argc == 1 && !FIXNUM_P(size)) {
665  val = rb_check_array_type(size);
666  if (!NIL_P(val)) {
667  rb_ary_replace(ary, val);
668  return ary;
669  }
670  }
671 
672  len = NUM2LONG(size);
673  if (len < 0) {
674  rb_raise(rb_eArgError, "negative array size");
675  }
676  if (len > ARY_MAX_SIZE) {
677  rb_raise(rb_eArgError, "array size too big");
678  }
679  rb_ary_modify(ary);
680  ary_resize_capa(ary, len);
681  if (rb_block_given_p()) {
682  long i;
683 
684  if (argc == 2) {
685  rb_warn("block supersedes default value argument");
686  }
687  for (i=0; i<len; i++) {
688  rb_ary_store(ary, i, rb_yield(LONG2NUM(i)));
689  ARY_SET_LEN(ary, i + 1);
690  }
691  }
692  else {
693  memfill(RARRAY_PTR(ary), len, val);
694  ARY_SET_LEN(ary, len);
695  }
696  return ary;
697 }
698 
699 /*
700  * Returns a new array populated with the given objects.
701  *
702  * Array.[]( 1, 'a', /^A/ ) # => [1, "a", /^A/]
703  * Array[ 1, 'a', /^A/ ] # => [1, "a", /^A/]
704  * [ 1, 'a', /^A/ ] # => [1, "a", /^A/]
705  */
706 
707 static VALUE
709 {
710  VALUE ary = ary_new(klass, argc);
711  if (argc > 0 && argv) {
712  MEMCPY(RARRAY_PTR(ary), argv, VALUE, argc);
713  ARY_SET_LEN(ary, argc);
714  }
715 
716  return ary;
717 }
718 
719 void
720 rb_ary_store(VALUE ary, long idx, VALUE val)
721 {
722  if (idx < 0) {
723  idx += RARRAY_LEN(ary);
724  if (idx < 0) {
725  rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld",
726  idx - RARRAY_LEN(ary), -RARRAY_LEN(ary));
727  }
728  }
729  else if (idx >= ARY_MAX_SIZE) {
730  rb_raise(rb_eIndexError, "index %ld too big", idx);
731  }
732 
733  rb_ary_modify(ary);
734  if (idx >= ARY_CAPA(ary)) {
735  ary_double_capa(ary, idx);
736  }
737  if (idx > RARRAY_LEN(ary)) {
738  rb_mem_clear(RARRAY_PTR(ary) + RARRAY_LEN(ary),
739  idx-RARRAY_LEN(ary) + 1);
740  }
741 
742  if (idx >= RARRAY_LEN(ary)) {
743  ARY_SET_LEN(ary, idx + 1);
744  }
745  RARRAY_PTR(ary)[idx] = val;
746 }
747 
748 static VALUE
749 ary_make_partial(VALUE ary, VALUE klass, long offset, long len)
750 {
751  assert(offset >= 0);
752  assert(len >= 0);
753  assert(offset+len <= RARRAY_LEN(ary));
754 
755  if (len <= RARRAY_EMBED_LEN_MAX) {
756  VALUE result = ary_alloc(klass);
757  MEMCPY(ARY_EMBED_PTR(result), RARRAY_PTR(ary) + offset, VALUE, len);
758  ARY_SET_EMBED_LEN(result, len);
759  return result;
760  }
761  else {
762  VALUE shared, result = ary_alloc(klass);
763  FL_UNSET_EMBED(result);
764 
765  shared = ary_make_shared(ary);
766  ARY_SET_PTR(result, RARRAY_PTR(ary));
767  ARY_SET_LEN(result, RARRAY_LEN(ary));
768  rb_ary_set_shared(result, shared);
769 
770  ARY_INCREASE_PTR(result, offset);
771  ARY_SET_LEN(result, len);
772  return result;
773  }
774 }
775 
776 static VALUE
778 {
779  return ary_make_partial(ary, rb_obj_class(ary), 0, RARRAY_LEN(ary));
780 }
781 
783 {
786 };
787 
788 static VALUE
790 {
791  VALUE nv;
792  long n;
793  long offset = 0;
794 
795  rb_scan_args(argc, argv, "1", &nv);
796  n = NUM2LONG(nv);
797  if (n > RARRAY_LEN(ary)) {
798  n = RARRAY_LEN(ary);
799  }
800  else if (n < 0) {
801  rb_raise(rb_eArgError, "negative array size");
802  }
803  if (last) {
804  offset = RARRAY_LEN(ary) - n;
805  }
806  return ary_make_partial(ary, rb_cArray, offset, n);
807 }
808 
809 /*
810  * call-seq:
811  * ary << obj -> ary
812  *
813  * Append---Pushes the given object on to the end of this array. This
814  * expression returns the array itself, so several appends
815  * may be chained together.
816  *
817  * [ 1, 2 ] << "c" << "d" << [ 3, 4 ]
818  * #=> [ 1, 2, "c", "d", [ 3, 4 ] ]
819  *
820  */
821 
822 VALUE
824 {
825  long idx = RARRAY_LEN(ary);
826 
827  ary_ensure_room_for_push(ary, 1);
828  RARRAY_PTR(ary)[idx] = item;
829  ARY_SET_LEN(ary, idx + 1);
830  return ary;
831 }
832 
833 static VALUE
835 {
836  long idx = RARRAY_LEN(ary);
837 
838  if (idx >= ARY_CAPA(ary)) {
839  ary_double_capa(ary, idx);
840  }
841  RARRAY_PTR(ary)[idx] = item;
842  ARY_SET_LEN(ary, idx + 1);
843  return ary;
844 }
845 
846 VALUE
847 rb_ary_cat(VALUE ary, const VALUE *ptr, long len)
848 {
849  long oldlen = RARRAY_LEN(ary);
850 
851  ary_ensure_room_for_push(ary, len);
852  MEMCPY(RARRAY_PTR(ary) + oldlen, ptr, VALUE, len);
853  ARY_SET_LEN(ary, oldlen + len);
854  return ary;
855 }
856 
857 /*
858  * call-seq:
859  * ary.push(obj, ... ) -> ary
860  *
861  * Append --- Pushes the given object(s) on to the end of this array. This
862  * expression returns the array itself, so several appends
863  * may be chained together. See also Array#pop for the opposite
864  * effect.
865  *
866  * a = [ "a", "b", "c" ]
867  * a.push("d", "e", "f")
868  * #=> ["a", "b", "c", "d", "e", "f"]
869  * [1, 2, 3,].push(4).push(5)
870  * #=> [1, 2, 3, 4, 5]
871  */
872 
873 static VALUE
875 {
876  return rb_ary_cat(ary, argv, argc);
877 }
878 
879 VALUE
881 {
882  long n;
883  rb_ary_modify_check(ary);
884  if (RARRAY_LEN(ary) == 0) return Qnil;
885  if (ARY_OWNS_HEAP_P(ary) &&
886  RARRAY_LEN(ary) * 3 < ARY_CAPA(ary) &&
887  ARY_CAPA(ary) > ARY_DEFAULT_SIZE)
888  {
889  ary_resize_capa(ary, RARRAY_LEN(ary) * 2);
890  }
891  n = RARRAY_LEN(ary)-1;
892  ARY_SET_LEN(ary, n);
893  return RARRAY_PTR(ary)[n];
894 }
895 
896 /*
897  * call-seq:
898  * ary.pop -> obj or nil
899  * ary.pop(n) -> new_ary
900  *
901  * Removes the last element from +self+ and returns it, or
902  * +nil+ if the array is empty.
903  *
904  * If a number +n+ is given, returns an array of the last +n+ elements
905  * (or less) just like <code>array.slice!(-n, n)</code> does. See also
906  * Array#push for the opposite effect.
907  *
908  * a = [ "a", "b", "c", "d" ]
909  * a.pop #=> "d"
910  * a.pop(2) #=> ["b", "c"]
911  * a #=> ["a"]
912  */
913 
914 static VALUE
916 {
917  VALUE result;
918 
919  if (argc == 0) {
920  return rb_ary_pop(ary);
921  }
922 
923  rb_ary_modify_check(ary);
924  result = ary_take_first_or_last(argc, argv, ary, ARY_TAKE_LAST);
925  ARY_INCREASE_LEN(ary, -RARRAY_LEN(result));
926  return result;
927 }
928 
929 VALUE
931 {
932  VALUE top;
933 
934  rb_ary_modify_check(ary);
935  if (RARRAY_LEN(ary) == 0) return Qnil;
936  top = RARRAY_PTR(ary)[0];
937  if (!ARY_SHARED_P(ary)) {
938  if (RARRAY_LEN(ary) < ARY_DEFAULT_SIZE) {
939  MEMMOVE(RARRAY_PTR(ary), RARRAY_PTR(ary)+1, VALUE, RARRAY_LEN(ary)-1);
940  ARY_INCREASE_LEN(ary, -1);
941  return top;
942  }
943  assert(!ARY_EMBED_P(ary)); /* ARY_EMBED_LEN_MAX < ARY_DEFAULT_SIZE */
944 
945  RARRAY_PTR(ary)[0] = Qnil;
946  ary_make_shared(ary);
947  }
948  else if (ARY_SHARED_NUM(ARY_SHARED(ary)) == 1) {
949  RARRAY_PTR(ary)[0] = Qnil;
950  }
951  ARY_INCREASE_PTR(ary, 1); /* shift ptr */
952  ARY_INCREASE_LEN(ary, -1);
953 
954  return top;
955 }
956 
957 /*
958  * call-seq:
959  * ary.shift -> obj or nil
960  * ary.shift(n) -> new_ary
961  *
962  * Removes the first element of +self+ and returns it (shifting all
963  * other elements down by one). Returns +nil+ if the array
964  * is empty.
965  *
966  * If a number +n+ is given, returns an array of the first +n+ elements
967  * (or less) just like <code>array.slice!(0, n)</code> does. With +ary+
968  * containing only the remainder elements, not including what was shifted to
969  * +new_ary+. See also Array#unshift for the opposite effect.
970  *
971  * args = [ "-m", "-q", "filename" ]
972  * args.shift #=> "-m"
973  * args #=> ["-q", "filename"]
974  *
975  * args = [ "-m", "-q", "filename" ]
976  * args.shift(2) #=> ["-m", "-q"]
977  * args #=> ["filename"]
978  */
979 
980 static VALUE
982 {
983  VALUE result;
984  long n;
985 
986  if (argc == 0) {
987  return rb_ary_shift(ary);
988  }
989 
990  rb_ary_modify_check(ary);
991  result = ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
992  n = RARRAY_LEN(result);
993  if (ARY_SHARED_P(ary)) {
994  if (ARY_SHARED_NUM(ARY_SHARED(ary)) == 1) {
995  rb_mem_clear(RARRAY_PTR(ary), n);
996  }
997  ARY_INCREASE_PTR(ary, n);
998  }
999  else {
1000  MEMMOVE(RARRAY_PTR(ary), RARRAY_PTR(ary)+n, VALUE, RARRAY_LEN(ary)-n);
1001  }
1002  ARY_INCREASE_LEN(ary, -n);
1003 
1004  return result;
1005 }
1006 
1007 static void
1009 {
1010  long len = RARRAY_LEN(ary);
1011  long new_len = len + argc;
1012  long capa;
1013  VALUE *head, *sharedp;
1014 
1015  if (ARY_SHARED_P(ary)) {
1016  VALUE shared = ARY_SHARED(ary);
1017  capa = RARRAY_LEN(shared);
1018  if (ARY_SHARED_NUM(shared) == 1 && capa > new_len) {
1019  head = RARRAY_PTR(ary);
1020  sharedp = RARRAY_PTR(shared);
1021  goto makeroom_if_need;
1022  }
1023  }
1024 
1025  rb_ary_modify(ary);
1026  capa = ARY_CAPA(ary);
1027  if (capa - (capa >> 6) <= new_len) {
1028  ary_double_capa(ary, new_len);
1029  }
1030 
1031  /* use shared array for big "queues" */
1032  if (new_len > ARY_DEFAULT_SIZE * 4) {
1033  /* make a room for unshifted items */
1034  capa = ARY_CAPA(ary);
1035  ary_make_shared(ary);
1036 
1037  head = sharedp = RARRAY_PTR(ary);
1038  goto makeroom;
1039  makeroom_if_need:
1040  if (head - sharedp < argc) {
1041  long room;
1042  makeroom:
1043  room = capa - new_len;
1044  room -= room >> 4;
1045  MEMMOVE(sharedp + argc + room, head, VALUE, len);
1046  head = sharedp + argc + room;
1047  }
1048  ARY_SET_PTR(ary, head - argc);
1049  }
1050  else {
1051  /* sliding items */
1052  MEMMOVE(RARRAY_PTR(ary) + argc, RARRAY_PTR(ary), VALUE, len);
1053  }
1054 }
1055 
1056 /*
1057  * call-seq:
1058  * ary.unshift(obj, ...) -> ary
1059  *
1060  * Prepends objects to the front of +self+, moving other elements upwards.
1061  * See also Array#shift for the opposite effect.
1062  *
1063  * a = [ "b", "c", "d" ]
1064  * a.unshift("a") #=> ["a", "b", "c", "d"]
1065  * a.unshift(1, 2) #=> [ 1, 2, "a", "b", "c", "d"]
1066  */
1067 
1068 static VALUE
1070 {
1071  long len = RARRAY_LEN(ary);
1072 
1073  if (argc == 0) {
1074  rb_ary_modify_check(ary);
1075  return ary;
1076  }
1077 
1078  ary_ensure_room_for_unshift(ary, argc);
1079  MEMCPY(RARRAY_PTR(ary), argv, VALUE, argc);
1080  ARY_SET_LEN(ary, len + argc);
1081  return ary;
1082 }
1083 
1084 VALUE
1086 {
1087  return rb_ary_unshift_m(1,&item,ary);
1088 }
1089 
1090 /* faster version - use this if you don't need to treat negative offset */
1091 static inline VALUE
1092 rb_ary_elt(VALUE ary, long offset)
1093 {
1094  if (RARRAY_LEN(ary) == 0) return Qnil;
1095  if (offset < 0 || RARRAY_LEN(ary) <= offset) {
1096  return Qnil;
1097  }
1098  return RARRAY_PTR(ary)[offset];
1099 }
1100 
1101 VALUE
1102 rb_ary_entry(VALUE ary, long offset)
1103 {
1104  if (offset < 0) {
1105  offset += RARRAY_LEN(ary);
1106  }
1107  return rb_ary_elt(ary, offset);
1108 }
1109 
1110 VALUE
1111 rb_ary_subseq(VALUE ary, long beg, long len)
1112 {
1113  VALUE klass;
1114 
1115  if (beg > RARRAY_LEN(ary)) return Qnil;
1116  if (beg < 0 || len < 0) return Qnil;
1117 
1118  if (RARRAY_LEN(ary) < len || RARRAY_LEN(ary) < beg + len) {
1119  len = RARRAY_LEN(ary) - beg;
1120  }
1121  klass = rb_obj_class(ary);
1122  if (len == 0) return ary_new(klass, 0);
1123 
1124  return ary_make_partial(ary, klass, beg, len);
1125 }
1126 
1127 /*
1128  * call-seq:
1129  * ary[index] -> obj or nil
1130  * ary[start, length] -> new_ary or nil
1131  * ary[range] -> new_ary or nil
1132  * ary.slice(index) -> obj or nil
1133  * ary.slice(start, length) -> new_ary or nil
1134  * ary.slice(range) -> new_ary or nil
1135  *
1136  * Element Reference --- Returns the element at +index+, or returns a
1137  * subarray starting at the +start+ index and continuing for +length+
1138  * elements, or returns a subarray specified by +range+ of indices.
1139  *
1140  * Negative indices count backward from the end of the array (-1 is the last
1141  * element). For +start+ and +range+ cases the starting index is just before
1142  * an element. Additionally, an empty array is returned when the starting
1143  * index for an element range is at the end of the array.
1144  *
1145  * Returns +nil+ if the index (or starting index) are out of range.
1146  *
1147  * a = [ "a", "b", "c", "d", "e" ]
1148  * a[2] + a[0] + a[1] #=> "cab"
1149  * a[6] #=> nil
1150  * a[1, 2] #=> [ "b", "c" ]
1151  * a[1..3] #=> [ "b", "c", "d" ]
1152  * a[4..7] #=> [ "e" ]
1153  * a[6..10] #=> nil
1154  * a[-3, 3] #=> [ "c", "d", "e" ]
1155  * # special cases
1156  * a[5] #=> nil
1157  * a[6, 1] #=> nil
1158  * a[5, 1] #=> []
1159  * a[5..10] #=> []
1160  *
1161  */
1162 
1163 VALUE
1165 {
1166  VALUE arg;
1167  long beg, len;
1168 
1169  if (argc == 2) {
1170  beg = NUM2LONG(argv[0]);
1171  len = NUM2LONG(argv[1]);
1172  if (beg < 0) {
1173  beg += RARRAY_LEN(ary);
1174  }
1175  return rb_ary_subseq(ary, beg, len);
1176  }
1177  if (argc != 1) {
1178  rb_scan_args(argc, argv, "11", NULL, NULL);
1179  }
1180  arg = argv[0];
1181  /* special case - speeding up */
1182  if (FIXNUM_P(arg)) {
1183  return rb_ary_entry(ary, FIX2LONG(arg));
1184  }
1185  /* check if idx is Range */
1186  switch (rb_range_beg_len(arg, &beg, &len, RARRAY_LEN(ary), 0)) {
1187  case Qfalse:
1188  break;
1189  case Qnil:
1190  return Qnil;
1191  default:
1192  return rb_ary_subseq(ary, beg, len);
1193  }
1194  return rb_ary_entry(ary, NUM2LONG(arg));
1195 }
1196 
1197 /*
1198  * call-seq:
1199  * ary.at(index) -> obj or nil
1200  *
1201  * Returns the element at +index+. A negative index counts from the end of
1202  * +self+. Returns +nil+ if the index is out of range. See also
1203  * Array#[].
1204  *
1205  * a = [ "a", "b", "c", "d", "e" ]
1206  * a.at(0) #=> "a"
1207  * a.at(-1) #=> "e"
1208  */
1209 
1210 static VALUE
1212 {
1213  return rb_ary_entry(ary, NUM2LONG(pos));
1214 }
1215 
1216 /*
1217  * call-seq:
1218  * ary.first -> obj or nil
1219  * ary.first(n) -> new_ary
1220  *
1221  * Returns the first element, or the first +n+ elements, of the array.
1222  * If the array is empty, the first form returns +nil+, and the
1223  * second form returns an empty array. See also Array#last for
1224  * the opposite effect.
1225  *
1226  * a = [ "q", "r", "s", "t" ]
1227  * a.first #=> "q"
1228  * a.first(2) #=> ["q", "r"]
1229  */
1230 
1231 static VALUE
1233 {
1234  if (argc == 0) {
1235  if (RARRAY_LEN(ary) == 0) return Qnil;
1236  return RARRAY_PTR(ary)[0];
1237  }
1238  else {
1239  return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
1240  }
1241 }
1242 
1243 /*
1244  * call-seq:
1245  * ary.last -> obj or nil
1246  * ary.last(n) -> new_ary
1247  *
1248  * Returns the last element(s) of +self+. If the array is empty,
1249  * the first form returns +nil+.
1250  *
1251  * See also Array#first for the opposite effect.
1252  *
1253  * a = [ "w", "x", "y", "z" ]
1254  * a.last #=> "z"
1255  * a.last(2) #=> ["y", "z"]
1256  */
1257 
1258 VALUE
1260 {
1261  if (argc == 0) {
1262  if (RARRAY_LEN(ary) == 0) return Qnil;
1263  return RARRAY_PTR(ary)[RARRAY_LEN(ary)-1];
1264  }
1265  else {
1266  return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_LAST);
1267  }
1268 }
1269 
1270 /*
1271  * call-seq:
1272  * ary.fetch(index) -> obj
1273  * ary.fetch(index, default) -> obj
1274  * ary.fetch(index) { |index| block } -> obj
1275  *
1276  * Tries to return the element at position +index+, but throws an IndexError
1277  * exception if the referenced +index+ lies outside of the array bounds. This
1278  * error can be prevented by supplying a second argument, which will act as a
1279  * +default+ value.
1280  *
1281  * Alternatively, if a block is given it will only be executed when an
1282  * invalid +index+ is referenced. Negative values of +index+ count from the
1283  * end of the array.
1284  *
1285  * a = [ 11, 22, 33, 44 ]
1286  * a.fetch(1) #=> 22
1287  * a.fetch(-1) #=> 44
1288  * a.fetch(4, 'cat') #=> "cat"
1289  * a.fetch(100) { |i| puts "#{i} is out of bounds" }
1290  * #=> "100 is out of bounds"
1291  */
1292 
1293 static VALUE
1295 {
1296  VALUE pos, ifnone;
1297  long block_given;
1298  long idx;
1299 
1300  rb_scan_args(argc, argv, "11", &pos, &ifnone);
1301  block_given = rb_block_given_p();
1302  if (block_given && argc == 2) {
1303  rb_warn("block supersedes default value argument");
1304  }
1305  idx = NUM2LONG(pos);
1306 
1307  if (idx < 0) {
1308  idx += RARRAY_LEN(ary);
1309  }
1310  if (idx < 0 || RARRAY_LEN(ary) <= idx) {
1311  if (block_given) return rb_yield(pos);
1312  if (argc == 1) {
1313  rb_raise(rb_eIndexError, "index %ld outside of array bounds: %ld...%ld",
1314  idx - (idx < 0 ? RARRAY_LEN(ary) : 0), -RARRAY_LEN(ary), RARRAY_LEN(ary));
1315  }
1316  return ifnone;
1317  }
1318  return RARRAY_PTR(ary)[idx];
1319 }
1320 
1321 /*
1322  * call-seq:
1323  * ary.index(obj) -> int or nil
1324  * ary.index { |item| block } -> int or nil
1325  * ary.index -> Enumerator
1326  *
1327  * Returns the _index_ of the first object in +ary+ such that the object is
1328  * <code>==</code> to +obj+.
1329  *
1330  * If a block is given instead of an argument, returns the _index_ of the
1331  * first object for which the block returns +true+. Returns +nil+ if no
1332  * match is found.
1333  *
1334  * See also Array#rindex.
1335  *
1336  * An Enumerator is returned if neither a block nor argument is given.
1337  *
1338  * a = [ "a", "b", "c" ]
1339  * a.index("b") #=> 1
1340  * a.index("z") #=> nil
1341  * a.index { |x| x == "b" } #=> 1
1342  *
1343  * This is an alias of Array#find_index.
1344  */
1345 
1346 static VALUE
1348 {
1349  VALUE val;
1350  long i;
1351 
1352  if (argc == 0) {
1353  RETURN_ENUMERATOR(ary, 0, 0);
1354  for (i=0; i<RARRAY_LEN(ary); i++) {
1355  if (RTEST(rb_yield(RARRAY_PTR(ary)[i]))) {
1356  return LONG2NUM(i);
1357  }
1358  }
1359  return Qnil;
1360  }
1361  rb_scan_args(argc, argv, "1", &val);
1362  if (rb_block_given_p())
1363  rb_warn("given block not used");
1364  for (i=0; i<RARRAY_LEN(ary); i++) {
1365  if (rb_equal(RARRAY_PTR(ary)[i], val))
1366  return LONG2NUM(i);
1367  }
1368  return Qnil;
1369 }
1370 
1371 /*
1372  * call-seq:
1373  * ary.rindex(obj) -> int or nil
1374  * ary.rindex { |item| block } -> int or nil
1375  * ary.rindex -> Enumerator
1376  *
1377  * Returns the _index_ of the last object in +self+ <code>==</code> to +obj+.
1378  *
1379  * If a block is given instead of an argument, returns the _index_ of the
1380  * first object for which the block returns +true+, starting from the last
1381  * object.
1382  *
1383  * Returns +nil+ if no match is found.
1384  *
1385  * See also Array#index.
1386  *
1387  * If neither block nor argument is given, an Enumerator is returned instead.
1388  *
1389  * a = [ "a", "b", "b", "b", "c" ]
1390  * a.rindex("b") #=> 3
1391  * a.rindex("z") #=> nil
1392  * a.rindex { |x| x == "b" } #=> 3
1393  */
1394 
1395 static VALUE
1397 {
1398  VALUE val;
1399  long i = RARRAY_LEN(ary);
1400 
1401  if (argc == 0) {
1402  RETURN_ENUMERATOR(ary, 0, 0);
1403  while (i--) {
1404  if (RTEST(rb_yield(RARRAY_PTR(ary)[i])))
1405  return LONG2NUM(i);
1406  if (i > RARRAY_LEN(ary)) {
1407  i = RARRAY_LEN(ary);
1408  }
1409  }
1410  return Qnil;
1411  }
1412  rb_scan_args(argc, argv, "1", &val);
1413  if (rb_block_given_p())
1414  rb_warn("given block not used");
1415  while (i--) {
1416  if (rb_equal(RARRAY_PTR(ary)[i], val))
1417  return LONG2NUM(i);
1418  if (i > RARRAY_LEN(ary)) {
1419  i = RARRAY_LEN(ary);
1420  }
1421  }
1422  return Qnil;
1423 }
1424 
1425 VALUE
1427 {
1428  VALUE tmp = rb_check_array_type(obj);
1429 
1430  if (!NIL_P(tmp)) return tmp;
1431  return rb_ary_new3(1, obj);
1432 }
1433 
1434 static void
1435 rb_ary_splice(VALUE ary, long beg, long len, VALUE rpl)
1436 {
1437  long rlen;
1438 
1439  if (len < 0) rb_raise(rb_eIndexError, "negative length (%ld)", len);
1440  if (beg < 0) {
1441  beg += RARRAY_LEN(ary);
1442  if (beg < 0) {
1443  rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld",
1444  beg - RARRAY_LEN(ary), -RARRAY_LEN(ary));
1445  }
1446  }
1447  if (RARRAY_LEN(ary) < len || RARRAY_LEN(ary) < beg + len) {
1448  len = RARRAY_LEN(ary) - beg;
1449  }
1450 
1451  if (rpl == Qundef) {
1452  rlen = 0;
1453  }
1454  else {
1455  rpl = rb_ary_to_ary(rpl);
1456  rlen = RARRAY_LEN(rpl);
1457  }
1458  if (beg >= RARRAY_LEN(ary)) {
1459  if (beg > ARY_MAX_SIZE - rlen) {
1460  rb_raise(rb_eIndexError, "index %ld too big", beg);
1461  }
1462  ary_ensure_room_for_push(ary, rlen-len); /* len is 0 or negative */
1463  len = beg + rlen;
1464  rb_mem_clear(RARRAY_PTR(ary) + RARRAY_LEN(ary), beg - RARRAY_LEN(ary));
1465  if (rlen > 0) {
1466  MEMCPY(RARRAY_PTR(ary) + beg, RARRAY_PTR(rpl), VALUE, rlen);
1467  }
1468  ARY_SET_LEN(ary, len);
1469  }
1470  else {
1471  long alen;
1472 
1473  rb_ary_modify(ary);
1474  alen = RARRAY_LEN(ary) + rlen - len;
1475  if (alen >= ARY_CAPA(ary)) {
1476  ary_double_capa(ary, alen);
1477  }
1478 
1479  if (len != rlen) {
1480  MEMMOVE(RARRAY_PTR(ary) + beg + rlen, RARRAY_PTR(ary) + beg + len,
1481  VALUE, RARRAY_LEN(ary) - (beg + len));
1482  ARY_SET_LEN(ary, alen);
1483  }
1484  if (rlen > 0) {
1485  MEMMOVE(RARRAY_PTR(ary) + beg, RARRAY_PTR(rpl), VALUE, rlen);
1486  }
1487  }
1488 }
1489 
1490 void
1491 rb_ary_set_len(VALUE ary, long len)
1492 {
1493  long capa;
1494 
1495  rb_ary_modify_check(ary);
1496  if (ARY_SHARED_P(ary)) {
1497  rb_raise(rb_eRuntimeError, "can't set length of shared ");
1498  }
1499  if (len > (capa = (long)ARY_CAPA(ary))) {
1500  rb_bug("probable buffer overflow: %ld for %ld", len, capa);
1501  }
1502  ARY_SET_LEN(ary, len);
1503 }
1504 
1513 VALUE
1514 rb_ary_resize(VALUE ary, long len)
1515 {
1516  long olen;
1517 
1518  rb_ary_modify(ary);
1519  olen = RARRAY_LEN(ary);
1520  if (len == olen) return ary;
1521  if (len > ARY_MAX_SIZE) {
1522  rb_raise(rb_eIndexError, "index %ld too big", len);
1523  }
1524  if (len > olen) {
1525  if (len >= ARY_CAPA(ary)) {
1526  ary_double_capa(ary, len);
1527  }
1528  rb_mem_clear(RARRAY_PTR(ary) + olen, len - olen);
1529  ARY_SET_LEN(ary, len);
1530  }
1531  else if (ARY_EMBED_P(ary)) {
1532  ARY_SET_EMBED_LEN(ary, len);
1533  }
1534  else if (len <= RARRAY_EMBED_LEN_MAX) {
1536  MEMCPY(tmp, ARY_HEAP_PTR(ary), VALUE, len);
1537  ary_discard(ary);
1538  MEMCPY(ARY_EMBED_PTR(ary), tmp, VALUE, len);
1539  ARY_SET_EMBED_LEN(ary, len);
1540  }
1541  else {
1542  if (olen > len + ARY_DEFAULT_SIZE) {
1543  REALLOC_N(RARRAY(ary)->as.heap.ptr, VALUE, len);
1544  ARY_SET_CAPA(ary, len);
1545  }
1546  ARY_SET_HEAP_LEN(ary, len);
1547  }
1548  return ary;
1549 }
1550 
1551 /*
1552  * call-seq:
1553  * ary[index] = obj -> obj
1554  * ary[start, length] = obj or other_ary or nil -> obj or other_ary or nil
1555  * ary[range] = obj or other_ary or nil -> obj or other_ary or nil
1556  *
1557  * Element Assignment --- Sets the element at +index+, or replaces a subarray
1558  * from the +start+ index for +length+ elements, or replaces a subarray
1559  * specified by the +range+ of indices.
1560  *
1561  * If indices are greater than the current capacity of the array, the array
1562  * grows automatically. Elements are inserted into the array at +start+ if
1563  * +length+ is zero.
1564  *
1565  * Negative indices will count backward from the end of the array. For
1566  * +start+ and +range+ cases the starting index is just before an element.
1567  *
1568  * An IndexError is raised if a negative index points past the beginning of
1569  * the array.
1570  *
1571  * See also Array#push, and Array#unshift.
1572  *
1573  * a = Array.new
1574  * a[4] = "4"; #=> [nil, nil, nil, nil, "4"]
1575  * a[0, 3] = [ 'a', 'b', 'c' ] #=> ["a", "b", "c", nil, "4"]
1576  * a[1..2] = [ 1, 2 ] #=> ["a", 1, 2, nil, "4"]
1577  * a[0, 2] = "?" #=> ["?", 2, nil, "4"]
1578  * a[0..2] = "A" #=> ["A", "4"]
1579  * a[-1] = "Z" #=> ["A", "Z"]
1580  * a[1..-1] = nil #=> ["A", nil]
1581  * a[1..-1] = [] #=> ["A"]
1582  * a[0, 0] = [ 1, 2 ] #=> [1, 2, "A"]
1583  * a[3, 0] = "B" #=> [1, 2, "A", "B"]
1584  */
1585 
1586 static VALUE
1588 {
1589  long offset, beg, len;
1590 
1591  if (argc == 3) {
1592  rb_ary_modify_check(ary);
1593  beg = NUM2LONG(argv[0]);
1594  len = NUM2LONG(argv[1]);
1595  rb_ary_splice(ary, beg, len, argv[2]);
1596  return argv[2];
1597  }
1598  rb_check_arity(argc, 2, 2);
1599  rb_ary_modify_check(ary);
1600  if (FIXNUM_P(argv[0])) {
1601  offset = FIX2LONG(argv[0]);
1602  goto fixnum;
1603  }
1604  if (rb_range_beg_len(argv[0], &beg, &len, RARRAY_LEN(ary), 1)) {
1605  /* check if idx is Range */
1606  rb_ary_splice(ary, beg, len, argv[1]);
1607  return argv[1];
1608  }
1609 
1610  offset = NUM2LONG(argv[0]);
1611 fixnum:
1612  rb_ary_store(ary, offset, argv[1]);
1613  return argv[1];
1614 }
1615 
1616 /*
1617  * call-seq:
1618  * ary.insert(index, obj...) -> ary
1619  *
1620  * Inserts the given values before the element with the given +index+.
1621  *
1622  * Negative indices count backwards from the end of the array, where +-1+ is
1623  * the last element.
1624  *
1625  * a = %w{ a b c d }
1626  * a.insert(2, 99) #=> ["a", "b", 99, "c", "d"]
1627  * a.insert(-2, 1, 2, 3) #=> ["a", "b", 99, "c", 1, 2, 3, "d"]
1628  */
1629 
1630 static VALUE
1632 {
1633  long pos;
1634 
1636  rb_ary_modify_check(ary);
1637  if (argc == 1) return ary;
1638  pos = NUM2LONG(argv[0]);
1639  if (pos == -1) {
1640  pos = RARRAY_LEN(ary);
1641  }
1642  if (pos < 0) {
1643  pos++;
1644  }
1645  rb_ary_splice(ary, pos, 0, rb_ary_new4(argc - 1, argv + 1));
1646  return ary;
1647 }
1648 
1649 static VALUE
1650 rb_ary_length(VALUE ary);
1651 
1652 /*
1653  * call-seq:
1654  * ary.each { |item| block } -> ary
1655  * ary.each -> Enumerator
1656  *
1657  * Calls the given block once for each element in +self+, passing that element
1658  * as a parameter.
1659  *
1660  * An Enumerator is returned if no block is given.
1661  *
1662  * a = [ "a", "b", "c" ]
1663  * a.each {|x| print x, " -- " }
1664  *
1665  * produces:
1666  *
1667  * a -- b -- c --
1668  */
1669 
1670 VALUE
1672 {
1673  long i;
1674  volatile VALUE ary = array;
1675 
1677  for (i=0; i<RARRAY_LEN(ary); i++) {
1678  rb_yield(RARRAY_PTR(ary)[i]);
1679  }
1680  return ary;
1681 }
1682 
1683 /*
1684  * call-seq:
1685  * ary.each_index { |index| block } -> ary
1686  * ary.each_index -> Enumerator
1687  *
1688  * Same as Array#each, but passes the +index+ of the element instead of the
1689  * element itself.
1690  *
1691  * An Enumerator is returned if no block is given.
1692  *
1693  * a = [ "a", "b", "c" ]
1694  * a.each_index {|x| print x, " -- " }
1695  *
1696  * produces:
1697  *
1698  * 0 -- 1 -- 2 --
1699  */
1700 
1701 static VALUE
1703 {
1704  long i;
1706 
1707  for (i=0; i<RARRAY_LEN(ary); i++) {
1708  rb_yield(LONG2NUM(i));
1709  }
1710  return ary;
1711 }
1712 
1713 /*
1714  * call-seq:
1715  * ary.reverse_each { |item| block } -> ary
1716  * ary.reverse_each -> Enumerator
1717  *
1718  * Same as Array#each, but traverses +self+ in reverse order.
1719  *
1720  * a = [ "a", "b", "c" ]
1721  * a.reverse_each {|x| print x, " " }
1722  *
1723  * produces:
1724  *
1725  * c b a
1726  */
1727 
1728 static VALUE
1730 {
1731  long len;
1732 
1734  len = RARRAY_LEN(ary);
1735  while (len--) {
1736  rb_yield(RARRAY_PTR(ary)[len]);
1737  if (RARRAY_LEN(ary) < len) {
1738  len = RARRAY_LEN(ary);
1739  }
1740  }
1741  return ary;
1742 }
1743 
1744 /*
1745  * call-seq:
1746  * ary.length -> int
1747  *
1748  * Returns the number of elements in +self+. May be zero.
1749  *
1750  * [ 1, 2, 3, 4, 5 ].length #=> 5
1751  * [].length #=> 0
1752  */
1753 
1754 static VALUE
1756 {
1757  long len = RARRAY_LEN(ary);
1758  return LONG2NUM(len);
1759 }
1760 
1761 /*
1762  * call-seq:
1763  * ary.empty? -> true or false
1764  *
1765  * Returns +true+ if +self+ contains no elements.
1766  *
1767  * [].empty? #=> true
1768  */
1769 
1770 static VALUE
1772 {
1773  if (RARRAY_LEN(ary) == 0)
1774  return Qtrue;
1775  return Qfalse;
1776 }
1777 
1778 VALUE
1780 {
1781  VALUE dup = rb_ary_new2(RARRAY_LEN(ary));
1782  MEMCPY(RARRAY_PTR(dup), RARRAY_PTR(ary), VALUE, RARRAY_LEN(ary));
1783  ARY_SET_LEN(dup, RARRAY_LEN(ary));
1784  return dup;
1785 }
1786 
1787 VALUE
1789 {
1790  return rb_ary_new4(RARRAY_LEN(ary), RARRAY_PTR(ary));
1791 }
1792 
1793 extern VALUE rb_output_fs;
1794 
1795 static void ary_join_1(VALUE obj, VALUE ary, VALUE sep, long i, VALUE result, int *first);
1796 
1797 static VALUE
1799 {
1800  VALUE *arg = (VALUE *)argp;
1801  VALUE ary = arg[0];
1802  VALUE sep = arg[1];
1803  VALUE result = arg[2];
1804  int *first = (int *)arg[3];
1805 
1806  if (recur) {
1807  rb_raise(rb_eArgError, "recursive array join");
1808  }
1809  else {
1810  ary_join_1(obj, ary, sep, 0, result, first);
1811  }
1812  return Qnil;
1813 }
1814 
1815 static void
1817 {
1818  long i;
1819  VALUE val;
1820 
1821  if (max > 0) rb_enc_copy(result, RARRAY_PTR(ary)[0]);
1822  for (i=0; i<max; i++) {
1823  val = RARRAY_PTR(ary)[i];
1824  if (i > 0 && !NIL_P(sep))
1825  rb_str_buf_append(result, sep);
1826  rb_str_buf_append(result, val);
1827  if (OBJ_TAINTED(val)) OBJ_TAINT(result);
1828  if (OBJ_UNTRUSTED(val)) OBJ_TAINT(result);
1829  }
1830 }
1831 
1832 static void
1833 ary_join_1(VALUE obj, VALUE ary, VALUE sep, long i, VALUE result, int *first)
1834 {
1835  VALUE val, tmp;
1836 
1837  for (; i<RARRAY_LEN(ary); i++) {
1838  if (i > 0 && !NIL_P(sep))
1839  rb_str_buf_append(result, sep);
1840 
1841  val = RARRAY_PTR(ary)[i];
1842  switch (TYPE(val)) {
1843  case T_STRING:
1844  str_join:
1845  rb_str_buf_append(result, val);
1846  *first = FALSE;
1847  break;
1848  case T_ARRAY:
1849  obj = val;
1850  ary_join:
1851  if (val == ary) {
1852  rb_raise(rb_eArgError, "recursive array join");
1853  }
1854  else {
1855  VALUE args[4];
1856 
1857  args[0] = val;
1858  args[1] = sep;
1859  args[2] = result;
1860  args[3] = (VALUE)first;
1861  rb_exec_recursive(recursive_join, obj, (VALUE)args);
1862  }
1863  break;
1864  default:
1865  tmp = rb_check_string_type(val);
1866  if (!NIL_P(tmp)) {
1867  val = tmp;
1868  goto str_join;
1869  }
1870  tmp = rb_check_convert_type(val, T_ARRAY, "Array", "to_ary");
1871  if (!NIL_P(tmp)) {
1872  obj = val;
1873  val = tmp;
1874  goto ary_join;
1875  }
1876  val = rb_obj_as_string(val);
1877  if (*first) {
1878  rb_enc_copy(result, val);
1879  *first = FALSE;
1880  }
1881  goto str_join;
1882  }
1883  }
1884 }
1885 
1886 VALUE
1888 {
1889  long len = 1, i;
1890  int taint = FALSE;
1891  int untrust = FALSE;
1892  VALUE val, tmp, result;
1893 
1894  if (RARRAY_LEN(ary) == 0) return rb_usascii_str_new(0, 0);
1895  if (OBJ_TAINTED(ary)) taint = TRUE;
1896  if (OBJ_UNTRUSTED(ary)) untrust = TRUE;
1897 
1898  if (!NIL_P(sep)) {
1899  StringValue(sep);
1900  len += RSTRING_LEN(sep) * (RARRAY_LEN(ary) - 1);
1901  }
1902  for (i=0; i<RARRAY_LEN(ary); i++) {
1903  val = RARRAY_PTR(ary)[i];
1904  tmp = rb_check_string_type(val);
1905 
1906  if (NIL_P(tmp) || tmp != val) {
1907  int first;
1908  result = rb_str_buf_new(len + (RARRAY_LEN(ary)-i)*10);
1910  if (taint) OBJ_TAINT(result);
1911  if (untrust) OBJ_UNTRUST(result);
1912  ary_join_0(ary, sep, i, result);
1913  first = i == 0;
1914  ary_join_1(ary, ary, sep, i, result, &first);
1915  return result;
1916  }
1917 
1918  len += RSTRING_LEN(tmp);
1919  }
1920 
1921  result = rb_str_buf_new(len);
1922  if (taint) OBJ_TAINT(result);
1923  if (untrust) OBJ_UNTRUST(result);
1924  ary_join_0(ary, sep, RARRAY_LEN(ary), result);
1925 
1926  return result;
1927 }
1928 
1929 /*
1930  * call-seq:
1931  * ary.join(separator=$,) -> str
1932  *
1933  * Returns a string created by converting each element of the array to
1934  * a string, separated by the given +separator+.
1935  * If the +separator+ is +nil+, it uses current $,.
1936  * If both the +separator+ and $, are nil, it uses empty string.
1937  *
1938  * [ "a", "b", "c" ].join #=> "abc"
1939  * [ "a", "b", "c" ].join("-") #=> "a-b-c"
1940  */
1941 
1942 static VALUE
1944 {
1945  VALUE sep;
1946 
1947  rb_scan_args(argc, argv, "01", &sep);
1948  if (NIL_P(sep)) sep = rb_output_fs;
1949 
1950  return rb_ary_join(ary, sep);
1951 }
1952 
1953 static VALUE
1954 inspect_ary(VALUE ary, VALUE dummy, int recur)
1955 {
1956  int tainted = OBJ_TAINTED(ary);
1957  int untrust = OBJ_UNTRUSTED(ary);
1958  long i;
1959  VALUE s, str;
1960 
1961  if (recur) return rb_usascii_str_new_cstr("[...]");
1962  str = rb_str_buf_new2("[");
1963  for (i=0; i<RARRAY_LEN(ary); i++) {
1964  s = rb_inspect(RARRAY_PTR(ary)[i]);
1965  if (OBJ_TAINTED(s)) tainted = TRUE;
1966  if (OBJ_UNTRUSTED(s)) untrust = TRUE;
1967  if (i > 0) rb_str_buf_cat2(str, ", ");
1968  else rb_enc_copy(str, s);
1969  rb_str_buf_append(str, s);
1970  }
1971  rb_str_buf_cat2(str, "]");
1972  if (tainted) OBJ_TAINT(str);
1973  if (untrust) OBJ_UNTRUST(str);
1974  return str;
1975 }
1976 
1977 /*
1978  * call-seq:
1979  * ary.inspect -> string
1980  * ary.to_s -> string
1981  *
1982  * Creates a string representation of +self+.
1983  *
1984  * [ "a", "b", "c" ].to_s #=> "[\"a\", \"b\", \"c\"]"
1985  */
1986 
1987 static VALUE
1989 {
1990  if (RARRAY_LEN(ary) == 0) return rb_usascii_str_new2("[]");
1991  return rb_exec_recursive(inspect_ary, ary, 0);
1992 }
1993 
1994 VALUE
1996 {
1997  return rb_ary_inspect(ary);
1998 }
1999 
2000 /*
2001  * call-seq:
2002  * ary.to_a -> ary
2003  *
2004  * Returns +self+.
2005  *
2006  * If called on a subclass of Array, converts the receiver to an Array object.
2007  */
2008 
2009 static VALUE
2011 {
2012  if (rb_obj_class(ary) != rb_cArray) {
2013  VALUE dup = rb_ary_new2(RARRAY_LEN(ary));
2014  rb_ary_replace(dup, ary);
2015  return dup;
2016  }
2017  return ary;
2018 }
2019 
2020 /*
2021  * call-seq:
2022  * ary.to_ary -> ary
2023  *
2024  * Returns +self+.
2025  */
2026 
2027 static VALUE
2029 {
2030  return ary;
2031 }
2032 
2033 static void
2035 {
2036  while (p1 < p2) {
2037  VALUE tmp = *p1;
2038  *p1++ = *p2;
2039  *p2-- = tmp;
2040  }
2041 }
2042 
2043 VALUE
2045 {
2046  VALUE *p1, *p2;
2047 
2048  rb_ary_modify(ary);
2049  if (RARRAY_LEN(ary) > 1) {
2050  p1 = RARRAY_PTR(ary);
2051  p2 = p1 + RARRAY_LEN(ary) - 1; /* points last item */
2052  ary_reverse(p1, p2);
2053  }
2054  return ary;
2055 }
2056 
2057 /*
2058  * call-seq:
2059  * ary.reverse! -> ary
2060  *
2061  * Reverses +self+ in place.
2062  *
2063  * a = [ "a", "b", "c" ]
2064  * a.reverse! #=> ["c", "b", "a"]
2065  * a #=> ["c", "b", "a"]
2066  */
2067 
2068 static VALUE
2070 {
2071  return rb_ary_reverse(ary);
2072 }
2073 
2074 /*
2075  * call-seq:
2076  * ary.reverse -> new_ary
2077  *
2078  * Returns a new array containing +self+'s elements in reverse order.
2079  *
2080  * [ "a", "b", "c" ].reverse #=> ["c", "b", "a"]
2081  * [ 1 ].reverse #=> [1]
2082  */
2083 
2084 static VALUE
2086 {
2087  long len = RARRAY_LEN(ary);
2088  VALUE dup = rb_ary_new2(len);
2089 
2090  if (len > 0) {
2091  VALUE *p1 = RARRAY_PTR(ary);
2092  VALUE *p2 = RARRAY_PTR(dup) + len - 1;
2093  do *p2-- = *p1++; while (--len > 0);
2094  }
2095  ARY_SET_LEN(dup, RARRAY_LEN(ary));
2096  return dup;
2097 }
2098 
2099 static inline long
2100 rotate_count(long cnt, long len)
2101 {
2102  return (cnt < 0) ? (len - (~cnt % len) - 1) : (cnt % len);
2103 }
2104 
2105 VALUE
2107 {
2108  rb_ary_modify(ary);
2109 
2110  if (cnt != 0) {
2111  VALUE *ptr = RARRAY_PTR(ary);
2112  long len = RARRAY_LEN(ary);
2113 
2114  if (len > 0 && (cnt = rotate_count(cnt, len)) > 0) {
2115  --len;
2116  if (cnt < len) ary_reverse(ptr + cnt, ptr + len);
2117  if (--cnt > 0) ary_reverse(ptr, ptr + cnt);
2118  if (len > 0) ary_reverse(ptr, ptr + len);
2119  return ary;
2120  }
2121  }
2122 
2123  return Qnil;
2124 }
2125 
2126 /*
2127  * call-seq:
2128  * ary.rotate!(count=1) -> ary
2129  *
2130  * Rotates +self+ in place so that the element at +count+ comes first, and
2131  * returns +self+.
2132  *
2133  * If +count+ is negative then it rotates in the opposite direction, starting
2134  * from the end of the array where +-1+ is the last element.
2135  *
2136  * a = [ "a", "b", "c", "d" ]
2137  * a.rotate! #=> ["b", "c", "d", "a"]
2138  * a #=> ["b", "c", "d", "a"]
2139  * a.rotate!(2) #=> ["d", "a", "b", "c"]
2140  * a.rotate!(-3) #=> ["a", "b", "c", "d"]
2141  */
2142 
2143 static VALUE
2145 {
2146  long n = 1;
2147 
2148  switch (argc) {
2149  case 1: n = NUM2LONG(argv[0]);
2150  case 0: break;
2151  default: rb_scan_args(argc, argv, "01", NULL);
2152  }
2153  rb_ary_rotate(ary, n);
2154  return ary;
2155 }
2156 
2157 /*
2158  * call-seq:
2159  * ary.rotate(count=1) -> new_ary
2160  *
2161  * Returns a new array by rotating +self+ so that the element at +count+ is
2162  * the first element of the new array.
2163  *
2164  * If +count+ is negative then it rotates in the opposite direction, starting
2165  * from the end of +self+ where +-1+ is the last element.
2166  *
2167  * a = [ "a", "b", "c", "d" ]
2168  * a.rotate #=> ["b", "c", "d", "a"]
2169  * a #=> ["a", "b", "c", "d"]
2170  * a.rotate(2) #=> ["c", "d", "a", "b"]
2171  * a.rotate(-3) #=> ["b", "c", "d", "a"]
2172  */
2173 
2174 static VALUE
2176 {
2177  VALUE rotated, *ptr, *ptr2;
2178  long len, cnt = 1;
2179 
2180  switch (argc) {
2181  case 1: cnt = NUM2LONG(argv[0]);
2182  case 0: break;
2183  default: rb_scan_args(argc, argv, "01", NULL);
2184  }
2185 
2186  len = RARRAY_LEN(ary);
2187  rotated = rb_ary_new2(len);
2188  if (len > 0) {
2189  cnt = rotate_count(cnt, len);
2190  ptr = RARRAY_PTR(ary);
2191  ptr2 = RARRAY_PTR(rotated);
2192  len -= cnt;
2193  MEMCPY(ptr2, ptr + cnt, VALUE, len);
2194  MEMCPY(ptr2 + len, ptr, VALUE, cnt);
2195  }
2196  ARY_SET_LEN(rotated, RARRAY_LEN(ary));
2197  return rotated;
2198 }
2199 
2204 };
2205 
2206 enum {
2210 };
2211 
2212 #define STRING_P(s) (RB_TYPE_P((s), T_STRING) && CLASS_OF(s) == rb_cString)
2213 
2214 #define SORT_OPTIMIZABLE_BIT(type) (1U << TOKEN_PASTE(sort_opt_,type))
2215 #define SORT_OPTIMIZABLE(data, type) \
2216  (((data)->opt_inited & SORT_OPTIMIZABLE_BIT(type)) ? \
2217  ((data)->opt_methods & SORT_OPTIMIZABLE_BIT(type)) : \
2218  (((data)->opt_inited |= SORT_OPTIMIZABLE_BIT(type)), \
2219  rb_method_basic_definition_p(TOKEN_PASTE(rb_c,type), id_cmp) && \
2220  ((data)->opt_methods |= SORT_OPTIMIZABLE_BIT(type))))
2221 
2222 static VALUE
2224 {
2225  if (RBASIC(ary)->klass) {
2226  rb_raise(rb_eRuntimeError, "sort reentered");
2227  }
2228  return Qnil;
2229 }
2230 
2231 static int
2232 sort_1(const void *ap, const void *bp, void *dummy)
2233 {
2234  struct ary_sort_data *data = dummy;
2235  VALUE retval = sort_reentered(data->ary);
2236  VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
2237  int n;
2238 
2239  retval = rb_yield_values(2, a, b);
2240  n = rb_cmpint(retval, a, b);
2241  sort_reentered(data->ary);
2242  return n;
2243 }
2244 
2245 static int
2246 sort_2(const void *ap, const void *bp, void *dummy)
2247 {
2248  struct ary_sort_data *data = dummy;
2249  VALUE retval = sort_reentered(data->ary);
2250  VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
2251  int n;
2252 
2253  if (FIXNUM_P(a) && FIXNUM_P(b) && SORT_OPTIMIZABLE(data, Fixnum)) {
2254  if ((long)a > (long)b) return 1;
2255  if ((long)a < (long)b) return -1;
2256  return 0;
2257  }
2258  if (STRING_P(a) && STRING_P(b) && SORT_OPTIMIZABLE(data, String)) {
2259  return rb_str_cmp(a, b);
2260  }
2261 
2262  retval = rb_funcall(a, id_cmp, 1, b);
2263  n = rb_cmpint(retval, a, b);
2264  sort_reentered(data->ary);
2265 
2266  return n;
2267 }
2268 
2269 /*
2270  * call-seq:
2271  * ary.sort! -> ary
2272  * ary.sort! { |a, b| block } -> ary
2273  *
2274  * Sorts +self+ in place.
2275  *
2276  * Comparisons for the sort will be done using the <code><=></code> operator
2277  * or using an optional code block.
2278  *
2279  * The block must implement a comparison between +a+ and +b+, and return
2280  * +-1+, when +a+ follows +b+, +0+ when +a+ and +b+ are equivalent, or ++1+
2281  * if +b+ follows +a+.
2282  *
2283  * See also Enumerable#sort_by.
2284  *
2285  * a = [ "d", "a", "e", "c", "b" ]
2286  * a.sort! #=> ["a", "b", "c", "d", "e"]
2287  * a.sort! { |x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
2288  */
2289 
2290 VALUE
2292 {
2293  rb_ary_modify(ary);
2294  assert(!ARY_SHARED_P(ary));
2295  if (RARRAY_LEN(ary) > 1) {
2296  VALUE tmp = ary_make_substitution(ary); /* only ary refers tmp */
2297  struct ary_sort_data data;
2298  long len = RARRAY_LEN(ary);
2299 
2300  RBASIC(tmp)->klass = 0;
2301  data.ary = tmp;
2302  data.opt_methods = 0;
2303  data.opt_inited = 0;
2304  ruby_qsort(RARRAY_PTR(tmp), len, sizeof(VALUE),
2305  rb_block_given_p()?sort_1:sort_2, &data);
2306 
2307  if (ARY_EMBED_P(tmp)) {
2308  assert(ARY_EMBED_P(tmp));
2309  if (ARY_SHARED_P(ary)) { /* ary might be destructively operated in the given block */
2310  rb_ary_unshare(ary);
2311  }
2312  FL_SET_EMBED(ary);
2313  MEMCPY(RARRAY_PTR(ary), ARY_EMBED_PTR(tmp), VALUE, ARY_EMBED_LEN(tmp));
2314  ARY_SET_LEN(ary, ARY_EMBED_LEN(tmp));
2315  }
2316  else {
2317  assert(!ARY_EMBED_P(tmp));
2318  if (ARY_HEAP_PTR(ary) == ARY_HEAP_PTR(tmp)) {
2319  assert(!ARY_EMBED_P(ary));
2320  FL_UNSET_SHARED(ary);
2321  ARY_SET_CAPA(ary, RARRAY_LEN(tmp));
2322  }
2323  else {
2324  assert(!ARY_SHARED_P(tmp));
2325  if (ARY_EMBED_P(ary)) {
2326  FL_UNSET_EMBED(ary);
2327  }
2328  else if (ARY_SHARED_P(ary)) {
2329  /* ary might be destructively operated in the given block */
2330  rb_ary_unshare(ary);
2331  }
2332  else {
2333  xfree(ARY_HEAP_PTR(ary));
2334  }
2335  ARY_SET_PTR(ary, RARRAY_PTR(tmp));
2336  ARY_SET_HEAP_LEN(ary, len);
2337  ARY_SET_CAPA(ary, RARRAY_LEN(tmp));
2338  }
2339  /* tmp was lost ownership for the ptr */
2340  FL_UNSET(tmp, FL_FREEZE);
2341  FL_SET_EMBED(tmp);
2342  ARY_SET_EMBED_LEN(tmp, 0);
2343  FL_SET(tmp, FL_FREEZE);
2344  }
2345  /* tmp will be GC'ed. */
2346  RBASIC(tmp)->klass = rb_cArray;
2347  }
2348  return ary;
2349 }
2350 
2351 /*
2352  * call-seq:
2353  * ary.sort -> new_ary
2354  * ary.sort { |a, b| block } -> new_ary
2355  *
2356  * Returns a new array created by sorting +self+.
2357  *
2358  * Comparisons for the sort will be done using the <code><=></code> operator
2359  * or using an optional code block.
2360  *
2361  * The block must implement a comparison between +a+ and +b+, and return
2362  * +-1+, when +a+ follows +b+, +0+ when +a+ and +b+ are equivalent, or ++1+
2363  * if +b+ follows +a+.
2364  *
2365  *
2366  * See also Enumerable#sort_by.
2367  *
2368  * a = [ "d", "a", "e", "c", "b" ]
2369  * a.sort #=> ["a", "b", "c", "d", "e"]
2370  * a.sort { |x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
2371  */
2372 
2373 VALUE
2375 {
2376  ary = rb_ary_dup(ary);
2377  rb_ary_sort_bang(ary);
2378  return ary;
2379 }
2380 
2381 /*
2382  * call-seq:
2383  * ary.bsearch {|x| block } -> elem
2384  *
2385  * By using binary search, finds a value from this array which meets
2386  * the given condition in O(log n) where n is the size of the array.
2387  *
2388  * You can use this method in two use cases: a find-minimum mode and
2389  * a find-any mode. In either case, the elements of the array must be
2390  * monotone (or sorted) with respect to the block.
2391  *
2392  * In find-minimum mode (this is a good choice for typical use case),
2393  * the block must return true or false, and there must be an index i
2394  * (0 <= i <= ary.size) so that:
2395  *
2396  * - the block returns false for any element whose index is less than
2397  * i, and
2398  * - the block returns true for any element whose index is greater
2399  * than or equal to i.
2400  *
2401  * This method returns the i-th element. If i is equal to ary.size,
2402  * it returns nil.
2403  *
2404  * ary = [0, 4, 7, 10, 12]
2405  * ary.bsearch {|x| x >= 4 } #=> 4
2406  * ary.bsearch {|x| x >= 6 } #=> 7
2407  * ary.bsearch {|x| x >= -1 } #=> 0
2408  * ary.bsearch {|x| x >= 100 } #=> nil
2409  *
2410  * In find-any mode (this behaves like libc's bsearch(3)), the block
2411  * must return a number, and there must be two indices i and j
2412  * (0 <= i <= j <= ary.size) so that:
2413  *
2414  * - the block returns a positive number for ary[k] if 0 <= k < i,
2415  * - the block returns zero for ary[k] if i <= k < j, and
2416  * - the block returns a negative number for ary[k] if
2417  * j <= k < ary.size.
2418  *
2419  * Under this condition, this method returns any element whose index
2420  * is within i...j. If i is equal to j (i.e., there is no element
2421  * that satisfies the block), this method returns nil.
2422  *
2423  * ary = [0, 4, 7, 10, 12]
2424  * # try to find v such that 4 <= v < 8
2425  * ary.bsearch {|x| 1 - x / 4 } #=> 4 or 7
2426  * # try to find v such that 8 <= v < 10
2427  * ary.bsearch {|x| 4 - x / 2 } #=> nil
2428  *
2429  * You must not mix the two modes at a time; the block must always
2430  * return either true/false, or always return a number. It is
2431  * undefined which value is actually picked up at each iteration.
2432  */
2433 
2434 static VALUE
2436 {
2437  long low = 0, high = RARRAY_LEN(ary), mid;
2438  int smaller = 0, satisfied = 0;
2439  VALUE v, val;
2440 
2441  RETURN_ENUMERATOR(ary, 0, 0);
2442  while (low < high) {
2443  mid = low + ((high - low) / 2);
2444  val = rb_ary_entry(ary, mid);
2445  v = rb_yield(val);
2446  if (FIXNUM_P(v)) {
2447  if (FIX2INT(v) == 0) return val;
2448  smaller = FIX2INT(v) < 0;
2449  }
2450  else if (v == Qtrue) {
2451  satisfied = 1;
2452  smaller = 1;
2453  }
2454  else if (v == Qfalse || v == Qnil) {
2455  smaller = 0;
2456  }
2457  else if (rb_obj_is_kind_of(v, rb_cNumeric)) {
2458  switch (rb_cmpint(rb_funcall(v, id_cmp, 1, INT2FIX(0)), v, INT2FIX(0))) {
2459  case 0: return val;
2460  case 1: smaller = 1; break;
2461  case -1: smaller = 0;
2462  }
2463  }
2464  else {
2465  rb_raise(rb_eTypeError, "wrong argument type %s"
2466  " (must be numeric, true, false or nil)",
2467  rb_obj_classname(v));
2468  }
2469  if (smaller) {
2470  high = mid;
2471  }
2472  else {
2473  low = mid + 1;
2474  }
2475  }
2476  if (low == RARRAY_LEN(ary)) return Qnil;
2477  if (!satisfied) return Qnil;
2478  return rb_ary_entry(ary, low);
2479 }
2480 
2481 
2482 static VALUE
2484 {
2485  return rb_yield(i);
2486 }
2487 
2488 /*
2489  * call-seq:
2490  * ary.sort_by! { |obj| block } -> ary
2491  * ary.sort_by! -> Enumerator
2492  *
2493  * Sorts +self+ in place using a set of keys generated by mapping the
2494  * values in +self+ through the given block.
2495  *
2496  * If no block is given, an Enumerator is returned instead.
2497  *
2498  */
2499 
2500 static VALUE
2502 {
2503  VALUE sorted;
2504 
2506  rb_ary_modify(ary);
2507  sorted = rb_block_call(ary, rb_intern("sort_by"), 0, 0, sort_by_i, 0);
2508  rb_ary_replace(ary, sorted);
2509  return ary;
2510 }
2511 
2512 
2513 /*
2514  * call-seq:
2515  * ary.collect { |item| block } -> new_ary
2516  * ary.map { |item| block } -> new_ary
2517  * ary.collect -> Enumerator
2518  * ary.map -> Enumerator
2519  *
2520  * Invokes the given block once for each element of +self+.
2521  *
2522  * Creates a new array containing the values returned by the block.
2523  *
2524  * See also Enumerable#collect.
2525  *
2526  * If no block is given, an Enumerator is returned instead.
2527  *
2528  * a = [ "a", "b", "c", "d" ]
2529  * a.map { |x| x + "!" } #=> ["a!", "b!", "c!", "d!"]
2530  * a #=> ["a", "b", "c", "d"]
2531  */
2532 
2533 static VALUE
2535 {
2536  long i;
2537  VALUE collect;
2538 
2540  collect = rb_ary_new2(RARRAY_LEN(ary));
2541  for (i = 0; i < RARRAY_LEN(ary); i++) {
2542  rb_ary_push(collect, rb_yield(RARRAY_PTR(ary)[i]));
2543  }
2544  return collect;
2545 }
2546 
2547 
2548 /*
2549  * call-seq:
2550  * ary.collect! {|item| block } -> ary
2551  * ary.map! {|item| block } -> ary
2552  * ary.collect! -> Enumerator
2553  * ary.map! -> Enumerator
2554  *
2555  * Invokes the given block once for each element of +self+, replacing the
2556  * element with the value returned by the block.
2557  *
2558  * See also Enumerable#collect.
2559  *
2560  * If no block is given, an Enumerator is returned instead.
2561  *
2562  * a = [ "a", "b", "c", "d" ]
2563  * a.map! {|x| x + "!" }
2564  * a #=> [ "a!", "b!", "c!", "d!" ]
2565  */
2566 
2567 static VALUE
2569 {
2570  long i;
2571 
2573  rb_ary_modify(ary);
2574  for (i = 0; i < RARRAY_LEN(ary); i++) {
2575  rb_ary_store(ary, i, rb_yield(RARRAY_PTR(ary)[i]));
2576  }
2577  return ary;
2578 }
2579 
2580 VALUE
2581 rb_get_values_at(VALUE obj, long olen, int argc, VALUE *argv, VALUE (*func) (VALUE, long))
2582 {
2583  VALUE result = rb_ary_new2(argc);
2584  long beg, len, i, j;
2585 
2586  for (i=0; i<argc; i++) {
2587  if (FIXNUM_P(argv[i])) {
2588  rb_ary_push(result, (*func)(obj, FIX2LONG(argv[i])));
2589  continue;
2590  }
2591  /* check if idx is Range */
2592  if (rb_range_beg_len(argv[i], &beg, &len, olen, 1)) {
2593  long end = olen < beg+len ? olen : beg+len;
2594  for (j = beg; j < end; j++) {
2595  rb_ary_push(result, (*func)(obj, j));
2596  }
2597  if (beg + len > j)
2598  rb_ary_resize(result, RARRAY_LEN(result) + (beg + len) - j);
2599  continue;
2600  }
2601  rb_ary_push(result, (*func)(obj, NUM2LONG(argv[i])));
2602  }
2603  return result;
2604 }
2605 
2606 /*
2607  * call-seq:
2608  * ary.values_at(selector, ...) -> new_ary
2609  *
2610  * Returns an array containing the elements in +self+ corresponding to the
2611  * given +selector+(s).
2612  *
2613  * The selectors may be either integer indices or ranges.
2614  *
2615  * See also Array#select.
2616  *
2617  * a = %w{ a b c d e f }
2618  * a.values_at(1, 3, 5) # => ["b", "d", "f"]
2619  * a.values_at(1, 3, 5, 7) # => ["b", "d", "f", nil]
2620  * a.values_at(-1, -2, -2, -7) # => ["f", "e", "e", nil]
2621  * a.values_at(4..6, 3...6) # => ["e", "f", nil, "d", "e", "f"]
2622  */
2623 
2624 static VALUE
2625 rb_ary_values_at(int argc, VALUE *argv, VALUE ary)
2626 {
2627  return rb_get_values_at(ary, RARRAY_LEN(ary), argc, argv, rb_ary_entry);
2628 }
2629 
2630 
2631 /*
2632  * call-seq:
2633  * ary.select { |item| block } -> new_ary
2634  * ary.select -> Enumerator
2635  *
2636  * Returns a new array containing all elements of +ary+
2637  * for which the given +block+ returns a true value.
2638  *
2639  * If no block is given, an Enumerator is returned instead.
2640  *
2641  * [1,2,3,4,5].select { |num| num.even? } #=> [2, 4]
2642  *
2643  * a = %w{ a b c d e f }
2644  * a.select { |v| v =~ /[aeiou]/ } #=> ["a", "e"]
2645  *
2646  * See also Enumerable#select.
2647  */
2648 
2649 static VALUE
2651 {
2652  VALUE result;
2653  long i;
2654 
2656  result = rb_ary_new2(RARRAY_LEN(ary));
2657  for (i = 0; i < RARRAY_LEN(ary); i++) {
2658  if (RTEST(rb_yield(RARRAY_PTR(ary)[i]))) {
2659  rb_ary_push(result, rb_ary_elt(ary, i));
2660  }
2661  }
2662  return result;
2663 }
2664 
2665 /*
2666  * call-seq:
2667  * ary.select! {|item| block } -> ary or nil
2668  * ary.select! -> Enumerator
2669  *
2670  * Invokes the given block passing in successive elements from +self+,
2671  * deleting elements for which the block returns a +false+ value.
2672  *
2673  * If changes were made, it will return +self+, otherwise it returns +nil+.
2674  *
2675  * See also Array#keep_if
2676  *
2677  * If no block is given, an Enumerator is returned instead.
2678  *
2679  */
2680 
2681 static VALUE
2683 {
2684  long i1, i2;
2685 
2687  rb_ary_modify(ary);
2688  for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) {
2689  VALUE v = RARRAY_PTR(ary)[i1];
2690  if (!RTEST(rb_yield(v))) continue;
2691  if (i1 != i2) {
2692  rb_ary_store(ary, i2, v);
2693  }
2694  i2++;
2695  }
2696 
2697  if (RARRAY_LEN(ary) == i2) return Qnil;
2698  if (i2 < RARRAY_LEN(ary))
2699  ARY_SET_LEN(ary, i2);
2700  return ary;
2701 }
2702 
2703 /*
2704  * call-seq:
2705  * ary.keep_if { |item| block } -> ary
2706  * ary.keep_if -> Enumerator
2707  *
2708  * Deletes every element of +self+ for which the given block evaluates to
2709  * +false+.
2710  *
2711  * See also Array#select!
2712  *
2713  * If no block is given, an Enumerator is returned instead.
2714  *
2715  * a = %w{ a b c d e f }
2716  * a.keep_if { |v| v =~ /[aeiou]/ } #=> ["a", "e"]
2717  */
2718 
2719 static VALUE
2721 {
2723  rb_ary_select_bang(ary);
2724  return ary;
2725 }
2726 
2727 static void
2729 {
2730  rb_ary_modify(ary);
2731  if (RARRAY_LEN(ary) > len) {
2732  ARY_SET_LEN(ary, len);
2733  if (len * 2 < ARY_CAPA(ary) &&
2734  ARY_CAPA(ary) > ARY_DEFAULT_SIZE) {
2735  ary_resize_capa(ary, len * 2);
2736  }
2737  }
2738 }
2739 
2740 /*
2741  * call-seq:
2742  * ary.delete(obj) -> item or nil
2743  * ary.delete(obj) { block } -> item or result of block
2744  *
2745  * Deletes all items from +self+ that are equal to +obj+.
2746  *
2747  * Returns the last deleted item, or +nil+ if no matching item is found.
2748  *
2749  * If the optional code block is given, the result of the block is returned if
2750  * the item is not found. (To remove +nil+ elements and get an informative
2751  * return value, use Array#compact!)
2752  *
2753  * a = [ "a", "b", "b", "b", "c" ]
2754  * a.delete("b") #=> "b"
2755  * a #=> ["a", "c"]
2756  * a.delete("z") #=> nil
2757  * a.delete("z") { "not found" } #=> "not found"
2758  */
2759 
2760 VALUE
2762 {
2763  VALUE v = item;
2764  long i1, i2;
2765 
2766  for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) {
2767  VALUE e = RARRAY_PTR(ary)[i1];
2768 
2769  if (rb_equal(e, item)) {
2770  v = e;
2771  continue;
2772  }
2773  if (i1 != i2) {
2774  rb_ary_store(ary, i2, e);
2775  }
2776  i2++;
2777  }
2778  if (RARRAY_LEN(ary) == i2) {
2779  if (rb_block_given_p()) {
2780  return rb_yield(item);
2781  }
2782  return Qnil;
2783  }
2784 
2785  ary_resize_smaller(ary, i2);
2786 
2787  return v;
2788 }
2789 
2790 void
2792 {
2793  long i1, i2;
2794 
2795  for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) {
2796  VALUE e = RARRAY_PTR(ary)[i1];
2797 
2798  if (e == item) {
2799  continue;
2800  }
2801  if (i1 != i2) {
2802  rb_ary_store(ary, i2, e);
2803  }
2804  i2++;
2805  }
2806  if (RARRAY_LEN(ary) == i2) {
2807  return;
2808  }
2809 
2810  ary_resize_smaller(ary, i2);
2811 }
2812 
2813 VALUE
2815 {
2816  long len = RARRAY_LEN(ary);
2817  VALUE del;
2818 
2819  if (pos >= len) return Qnil;
2820  if (pos < 0) {
2821  pos += len;
2822  if (pos < 0) return Qnil;
2823  }
2824 
2825  rb_ary_modify(ary);
2826  del = RARRAY_PTR(ary)[pos];
2827  MEMMOVE(RARRAY_PTR(ary)+pos, RARRAY_PTR(ary)+pos+1, VALUE,
2828  RARRAY_LEN(ary)-pos-1);
2829  ARY_INCREASE_LEN(ary, -1);
2830 
2831  return del;
2832 }
2833 
2834 /*
2835  * call-seq:
2836  * ary.delete_at(index) -> obj or nil
2837  *
2838  * Deletes the element at the specified +index+, returning that element, or
2839  * +nil+ if the +index+ is out of range.
2840  *
2841  * See also Array#slice!
2842  *
2843  * a = ["ant", "bat", "cat", "dog"]
2844  * a.delete_at(2) #=> "cat"
2845  * a #=> ["ant", "bat", "dog"]
2846  * a.delete_at(99) #=> nil
2847  */
2848 
2849 static VALUE
2851 {
2852  return rb_ary_delete_at(ary, NUM2LONG(pos));
2853 }
2854 
2855 /*
2856  * call-seq:
2857  * ary.slice!(index) -> obj or nil
2858  * ary.slice!(start, length) -> new_ary or nil
2859  * ary.slice!(range) -> new_ary or nil
2860  *
2861  * Deletes the element(s) given by an +index+ (optionally up to +length+
2862  * elements) or by a +range+.
2863  *
2864  * Returns the deleted object (or objects), or +nil+ if the +index+ is out of
2865  * range.
2866  *
2867  * a = [ "a", "b", "c" ]
2868  * a.slice!(1) #=> "b"
2869  * a #=> ["a", "c"]
2870  * a.slice!(-1) #=> "c"
2871  * a #=> ["a"]
2872  * a.slice!(100) #=> nil
2873  * a #=> ["a"]
2874  */
2875 
2876 static VALUE
2878 {
2879  VALUE arg1, arg2;
2880  long pos, len, orig_len;
2881 
2882  rb_ary_modify_check(ary);
2883  if (argc == 2) {
2884  pos = NUM2LONG(argv[0]);
2885  len = NUM2LONG(argv[1]);
2886  delete_pos_len:
2887  if (len < 0) return Qnil;
2888  orig_len = RARRAY_LEN(ary);
2889  if (pos < 0) {
2890  pos += orig_len;
2891  if (pos < 0) return Qnil;
2892  }
2893  else if (orig_len < pos) return Qnil;
2894  if (orig_len < pos + len) {
2895  len = orig_len - pos;
2896  }
2897  if (len == 0) return rb_ary_new2(0);
2898  arg2 = rb_ary_new4(len, RARRAY_PTR(ary)+pos);
2899  RBASIC(arg2)->klass = rb_obj_class(ary);
2900  rb_ary_splice(ary, pos, len, Qundef);
2901  return arg2;
2902  }
2903 
2904  if (argc != 1) {
2905  /* error report */
2906  rb_scan_args(argc, argv, "11", NULL, NULL);
2907  }
2908  arg1 = argv[0];
2909 
2910  if (!FIXNUM_P(arg1)) {
2911  switch (rb_range_beg_len(arg1, &pos, &len, RARRAY_LEN(ary), 0)) {
2912  case Qtrue:
2913  /* valid range */
2914  goto delete_pos_len;
2915  case Qnil:
2916  /* invalid range */
2917  return Qnil;
2918  default:
2919  /* not a range */
2920  break;
2921  }
2922  }
2923 
2924  return rb_ary_delete_at(ary, NUM2LONG(arg1));
2925 }
2926 
2927 static VALUE
2929 {
2930  long i;
2931 
2932  for (i = 0; i < RARRAY_LEN(orig); i++) {
2933  VALUE v = RARRAY_PTR(orig)[i];
2934  if (!RTEST(rb_yield(v))) {
2935  rb_ary_push_1(result, v);
2936  }
2937  }
2938  return result;
2939 }
2940 
2941 static VALUE
2943 {
2944  long i;
2945  VALUE result = Qnil;
2946 
2947  rb_ary_modify_check(ary);
2948  for (i = 0; i < RARRAY_LEN(ary); ) {
2949  VALUE v = RARRAY_PTR(ary)[i];
2950  if (RTEST(rb_yield(v))) {
2951  rb_ary_delete_at(ary, i);
2952  result = ary;
2953  }
2954  else {
2955  i++;
2956  }
2957  }
2958  return result;
2959 }
2960 
2961 /*
2962  * call-seq:
2963  * ary.reject! { |item| block } -> ary or nil
2964  * ary.reject! -> Enumerator
2965  *
2966  * Equivalent to Array#delete_if, deleting elements from +self+ for which the
2967  * block evaluates to +true+, but returns +nil+ if no changes were made.
2968  *
2969  * The array is changed instantly every time the block is called, not after
2970  * the iteration is over.
2971  *
2972  * See also Enumerable#reject and Array#delete_if.
2973  *
2974  * If no block is given, an Enumerator is returned instead.
2975  */
2976 
2977 static VALUE
2979 {
2981  return ary_reject_bang(ary);
2982 }
2983 
2984 /*
2985  * call-seq:
2986  * ary.reject {|item| block } -> new_ary
2987  * ary.reject -> Enumerator
2988  *
2989  * Returns a new array containing the items in +self+ for which the given
2990  * block is not +true+.
2991  *
2992  * See also Array#delete_if
2993  *
2994  * If no block is given, an Enumerator is returned instead.
2995  */
2996 
2997 static VALUE
2999 {
3000  VALUE rejected_ary;
3001 
3003  rejected_ary = rb_ary_new();
3004  ary_reject(ary, rejected_ary);
3005  return rejected_ary;
3006 }
3007 
3008 /*
3009  * call-seq:
3010  * ary.delete_if { |item| block } -> ary
3011  * ary.delete_if -> Enumerator
3012  *
3013  * Deletes every element of +self+ for which block evaluates to +true+.
3014  *
3015  * The array is changed instantly every time the block is called, not after
3016  * the iteration is over.
3017  *
3018  * See also Array#reject!
3019  *
3020  * If no block is given, an Enumerator is returned instead.
3021  *
3022  * a = [ "a", "b", "c" ]
3023  * a.delete_if {|x| x >= "b" } #=> ["a"]
3024  */
3025 
3026 static VALUE
3028 {
3030  ary_reject_bang(ary);
3031  return ary;
3032 }
3033 
3034 static VALUE
3035 take_i(VALUE val, VALUE *args, int argc, VALUE *argv)
3036 {
3037  if (args[1]-- == 0) rb_iter_break();
3038  if (argc > 1) val = rb_ary_new4(argc, argv);
3039  rb_ary_push(args[0], val);
3040  return Qnil;
3041 }
3042 
3043 static VALUE
3044 take_items(VALUE obj, long n)
3045 {
3047  VALUE args[2];
3048 
3049  if (!NIL_P(result)) return rb_ary_subseq(result, 0, n);
3050  result = rb_ary_new2(n);
3051  args[0] = result; args[1] = (VALUE)n;
3052  if (rb_check_block_call(obj, idEach, 0, 0, take_i, (VALUE)args) == Qundef)
3053  rb_raise(rb_eTypeError, "wrong argument type %s (must respond to :each)",
3054  rb_obj_classname(obj));
3055  return result;
3056 }
3057 
3058 
3059 /*
3060  * call-seq:
3061  * ary.zip(arg, ...) -> new_ary
3062  * ary.zip(arg, ...) { |arr| block } -> nil
3063  *
3064  * Converts any arguments to arrays, then merges elements of +self+ with
3065  * corresponding elements from each argument.
3066  *
3067  * This generates a sequence of <code>ary.size</code> _n_-element arrays,
3068  * where _n_ is one more that the count of arguments.
3069  *
3070  * If the size of any argument is less than the size of the initial array,
3071  * +nil+ values are supplied.
3072  *
3073  * If a block is given, it is invoked for each output +array+, otherwise an
3074  * array of arrays is returned.
3075  *
3076  * a = [ 4, 5, 6 ]
3077  * b = [ 7, 8, 9 ]
3078  * [1, 2, 3].zip(a, b) #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
3079  * [1, 2].zip(a, b) #=> [[1, 4, 7], [2, 5, 8]]
3080  * a.zip([1, 2], [8]) #=> [[4, 1, 8], [5, 2, nil], [6, nil, nil]]
3081  */
3082 
3083 static VALUE
3084 rb_ary_zip(int argc, VALUE *argv, VALUE ary)
3085 {
3086  int i, j;
3087  long len;
3088  VALUE result = Qnil;
3089 
3090  len = RARRAY_LEN(ary);
3091  for (i=0; i<argc; i++) {
3092  argv[i] = take_items(argv[i], len);
3093  }
3094  if (!rb_block_given_p()) {
3095  result = rb_ary_new2(len);
3096  }
3097 
3098  for (i=0; i<RARRAY_LEN(ary); i++) {
3099  VALUE tmp = rb_ary_new2(argc+1);
3100 
3101  rb_ary_push(tmp, rb_ary_elt(ary, i));
3102  for (j=0; j<argc; j++) {
3103  rb_ary_push(tmp, rb_ary_elt(argv[j], i));
3104  }
3105  if (NIL_P(result)) {
3106  rb_yield(tmp);
3107  }
3108  else {
3109  rb_ary_push(result, tmp);
3110  }
3111  }
3112  return result;
3113 }
3114 
3115 /*
3116  * call-seq:
3117  * ary.transpose -> new_ary
3118  *
3119  * Assumes that +self+ is an array of arrays and transposes the rows and
3120  * columns.
3121  *
3122  * a = [[1,2], [3,4], [5,6]]
3123  * a.transpose #=> [[1, 3, 5], [2, 4, 6]]
3124  *
3125  * If the length of the subarrays don't match, an IndexError is raised.
3126  */
3127 
3128 static VALUE
3130 {
3131  long elen = -1, alen, i, j;
3132  VALUE tmp, result = 0;
3133 
3134  alen = RARRAY_LEN(ary);
3135  if (alen == 0) return rb_ary_dup(ary);
3136  for (i=0; i<alen; i++) {
3137  tmp = to_ary(rb_ary_elt(ary, i));
3138  if (elen < 0) { /* first element */
3139  elen = RARRAY_LEN(tmp);
3140  result = rb_ary_new2(elen);
3141  for (j=0; j<elen; j++) {
3142  rb_ary_store(result, j, rb_ary_new2(alen));
3143  }
3144  }
3145  else if (elen != RARRAY_LEN(tmp)) {
3146  rb_raise(rb_eIndexError, "element size differs (%ld should be %ld)",
3147  RARRAY_LEN(tmp), elen);
3148  }
3149  for (j=0; j<elen; j++) {
3150  rb_ary_store(rb_ary_elt(result, j), i, rb_ary_elt(tmp, j));
3151  }
3152  }
3153  return result;
3154 }
3155 
3156 /*
3157  * call-seq:
3158  * ary.replace(other_ary) -> ary
3159  *
3160  * Replaces the contents of +self+ with the contents of +other_ary+,
3161  * truncating or expanding if necessary.
3162  *
3163  * a = [ "a", "b", "c", "d", "e" ]
3164  * a.replace([ "x", "y", "z" ]) #=> ["x", "y", "z"]
3165  * a #=> ["x", "y", "z"]
3166  */
3167 
3168 VALUE
3170 {
3171  rb_ary_modify_check(copy);
3172  orig = to_ary(orig);
3173  if (copy == orig) return copy;
3174 
3175  if (RARRAY_LEN(orig) <= RARRAY_EMBED_LEN_MAX) {
3176  VALUE *ptr;
3177  VALUE shared = 0;
3178 
3179  if (ARY_OWNS_HEAP_P(copy)) {
3180  xfree(RARRAY_PTR(copy));
3181  }
3182  else if (ARY_SHARED_P(copy)) {
3183  shared = ARY_SHARED(copy);
3184  FL_UNSET_SHARED(copy);
3185  }
3186  FL_SET_EMBED(copy);
3187  ptr = RARRAY_PTR(orig);
3188  MEMCPY(RARRAY_PTR(copy), ptr, VALUE, RARRAY_LEN(orig));
3189  if (shared) {
3190  rb_ary_decrement_share(shared);
3191  }
3192  ARY_SET_LEN(copy, RARRAY_LEN(orig));
3193  }
3194  else {
3195  VALUE shared = ary_make_shared(orig);
3196  if (ARY_OWNS_HEAP_P(copy)) {
3197  xfree(RARRAY_PTR(copy));
3198  }
3199  else {
3200  rb_ary_unshare_safe(copy);
3201  }
3202  FL_UNSET_EMBED(copy);
3203  ARY_SET_PTR(copy, RARRAY_PTR(orig));
3204  ARY_SET_LEN(copy, RARRAY_LEN(orig));
3205  rb_ary_set_shared(copy, shared);
3206  }
3207  return copy;
3208 }
3209 
3210 /*
3211  * call-seq:
3212  * ary.clear -> ary
3213  *
3214  * Removes all elements from +self+.
3215  *
3216  * a = [ "a", "b", "c", "d", "e" ]
3217  * a.clear #=> [ ]
3218  */
3219 
3220 VALUE
3222 {
3223  rb_ary_modify_check(ary);
3224  ARY_SET_LEN(ary, 0);
3225  if (ARY_SHARED_P(ary)) {
3226  if (!ARY_EMBED_P(ary)) {
3227  rb_ary_unshare(ary);
3228  FL_SET_EMBED(ary);
3229  }
3230  }
3231  else if (ARY_DEFAULT_SIZE * 2 < ARY_CAPA(ary)) {
3233  }
3234  return ary;
3235 }
3236 
3237 /*
3238  * call-seq:
3239  * ary.fill(obj) -> ary
3240  * ary.fill(obj, start [, length]) -> ary
3241  * ary.fill(obj, range ) -> ary
3242  * ary.fill { |index| block } -> ary
3243  * ary.fill(start [, length] ) { |index| block } -> ary
3244  * ary.fill(range) { |index| block } -> ary
3245  *
3246  * The first three forms set the selected elements of +self+ (which
3247  * may be the entire array) to +obj+.
3248  *
3249  * A +start+ of +nil+ is equivalent to zero.
3250  *
3251  * A +length+ of +nil+ is equivalent to the length of the array.
3252  *
3253  * The last three forms fill the array with the value of the given block,
3254  * which is passed the absolute index of each element to be filled.
3255  *
3256  * Negative values of +start+ count from the end of the array, where +-1+ is
3257  * the last element.
3258  *
3259  * a = [ "a", "b", "c", "d" ]
3260  * a.fill("x") #=> ["x", "x", "x", "x"]
3261  * a.fill("z", 2, 2) #=> ["x", "x", "z", "z"]
3262  * a.fill("y", 0..1) #=> ["y", "y", "z", "z"]
3263  * a.fill { |i| i*i } #=> [0, 1, 4, 9]
3264  * a.fill(-2) { |i| i*i*i } #=> [0, 1, 8, 27]
3265  */
3266 
3267 static VALUE
3268 rb_ary_fill(int argc, VALUE *argv, VALUE ary)
3269 {
3270  VALUE item, arg1, arg2;
3271  long beg = 0, end = 0, len = 0;
3272  VALUE *p, *pend;
3273  int block_p = FALSE;
3274 
3275  if (rb_block_given_p()) {
3276  block_p = TRUE;
3277  rb_scan_args(argc, argv, "02", &arg1, &arg2);
3278  argc += 1; /* hackish */
3279  }
3280  else {
3281  rb_scan_args(argc, argv, "12", &item, &arg1, &arg2);
3282  }
3283  switch (argc) {
3284  case 1:
3285  beg = 0;
3286  len = RARRAY_LEN(ary);
3287  break;
3288  case 2:
3289  if (rb_range_beg_len(arg1, &beg, &len, RARRAY_LEN(ary), 1)) {
3290  break;
3291  }
3292  /* fall through */
3293  case 3:
3294  beg = NIL_P(arg1) ? 0 : NUM2LONG(arg1);
3295  if (beg < 0) {
3296  beg = RARRAY_LEN(ary) + beg;
3297  if (beg < 0) beg = 0;
3298  }
3299  len = NIL_P(arg2) ? RARRAY_LEN(ary) - beg : NUM2LONG(arg2);
3300  break;
3301  }
3302  rb_ary_modify(ary);
3303  if (len < 0) {
3304  return ary;
3305  }
3306  if (beg >= ARY_MAX_SIZE || len > ARY_MAX_SIZE - beg) {
3307  rb_raise(rb_eArgError, "argument too big");
3308  }
3309  end = beg + len;
3310  if (RARRAY_LEN(ary) < end) {
3311  if (end >= ARY_CAPA(ary)) {
3312  ary_resize_capa(ary, end);
3313  }
3314  rb_mem_clear(RARRAY_PTR(ary) + RARRAY_LEN(ary), end - RARRAY_LEN(ary));
3315  ARY_SET_LEN(ary, end);
3316  }
3317 
3318  if (block_p) {
3319  VALUE v;
3320  long i;
3321 
3322  for (i=beg; i<end; i++) {
3323  v = rb_yield(LONG2NUM(i));
3324  if (i>=RARRAY_LEN(ary)) break;
3325  RARRAY_PTR(ary)[i] = v;
3326  }
3327  }
3328  else {
3329  p = RARRAY_PTR(ary) + beg;
3330  pend = p + len;
3331  while (p < pend) {
3332  *p++ = item;
3333  }
3334  }
3335  return ary;
3336 }
3337 
3338 /*
3339  * call-seq:
3340  * ary + other_ary -> new_ary
3341  *
3342  * Concatenation --- Returns a new array built by concatenating the
3343  * two arrays together to produce a third array.
3344  *
3345  * [ 1, 2, 3 ] + [ 4, 5 ] #=> [ 1, 2, 3, 4, 5 ]
3346  * a = [ "a", "b", "c" ]
3347  * a + [ "d", "e", "f" ]
3348  * a #=> [ "a", "b", "c", "d", "e", "f" ]
3349  *
3350  * See also Array#concat.
3351  */
3352 
3353 VALUE
3355 {
3356  VALUE z;
3357  long len;
3358 
3359  y = to_ary(y);
3360  len = RARRAY_LEN(x) + RARRAY_LEN(y);
3361  z = rb_ary_new2(len);
3364  ARY_SET_LEN(z, len);
3365  return z;
3366 }
3367 
3368 /*
3369  * call-seq:
3370  * ary.concat(other_ary) -> ary
3371  *
3372  * Appends the elements of +other_ary+ to +self+.
3373  *
3374  * [ "a", "b" ].concat( ["c", "d"] ) #=> [ "a", "b", "c", "d" ]
3375  * a = [ 1, 2, 3 ]
3376  * a.concat( [ 4, 5 ] )
3377  * a #=> [ 1, 2, 3, 4, 5 ]
3378  *
3379  * See also Array#+.
3380  */
3381 
3382 VALUE
3384 {
3386  y = to_ary(y);
3387  if (RARRAY_LEN(y) > 0) {
3388  rb_ary_splice(x, RARRAY_LEN(x), 0, y);
3389  }
3390  return x;
3391 }
3392 
3393 
3394 /*
3395  * call-seq:
3396  * ary * int -> new_ary
3397  * ary * str -> new_string
3398  *
3399  * Repetition --- With a String argument, equivalent to
3400  * <code>ary.join(str)</code>.
3401  *
3402  * Otherwise, returns a new array built by concatenating the +int+ copies of
3403  * +self+.
3404  *
3405  *
3406  * [ 1, 2, 3 ] * 3 #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
3407  * [ 1, 2, 3 ] * "," #=> "1,2,3"
3408  *
3409  */
3410 
3411 static VALUE
3413 {
3414  VALUE ary2, tmp, *ptr, *ptr2;
3415  long t, len;
3416 
3417  tmp = rb_check_string_type(times);
3418  if (!NIL_P(tmp)) {
3419  return rb_ary_join(ary, tmp);
3420  }
3421 
3422  len = NUM2LONG(times);
3423  if (len == 0) {
3424  ary2 = ary_new(rb_obj_class(ary), 0);
3425  goto out;
3426  }
3427  if (len < 0) {
3428  rb_raise(rb_eArgError, "negative argument");
3429  }
3430  if (ARY_MAX_SIZE/len < RARRAY_LEN(ary)) {
3431  rb_raise(rb_eArgError, "argument too big");
3432  }
3433  len *= RARRAY_LEN(ary);
3434 
3435  ary2 = ary_new(rb_obj_class(ary), len);
3436  ARY_SET_LEN(ary2, len);
3437 
3438  ptr = RARRAY_PTR(ary);
3439  ptr2 = RARRAY_PTR(ary2);
3440  t = RARRAY_LEN(ary);
3441  if (0 < t) {
3442  MEMCPY(ptr2, ptr, VALUE, t);
3443  while (t <= len/2) {
3444  MEMCPY(ptr2+t, ptr2, VALUE, t);
3445  t *= 2;
3446  }
3447  if (t < len) {
3448  MEMCPY(ptr2+t, ptr2, VALUE, len-t);
3449  }
3450  }
3451  out:
3452  OBJ_INFECT(ary2, ary);
3453 
3454  return ary2;
3455 }
3456 
3457 /*
3458  * call-seq:
3459  * ary.assoc(obj) -> new_ary or nil
3460  *
3461  * Searches through an array whose elements are also arrays comparing +obj+
3462  * with the first element of each contained array using <code>obj.==</code>.
3463  *
3464  * Returns the first contained array that matches (that is, the first
3465  * associated array), or +nil+ if no match is found.
3466  *
3467  * See also Array#rassoc
3468  *
3469  * s1 = [ "colors", "red", "blue", "green" ]
3470  * s2 = [ "letters", "a", "b", "c" ]
3471  * s3 = "foo"
3472  * a = [ s1, s2, s3 ]
3473  * a.assoc("letters") #=> [ "letters", "a", "b", "c" ]
3474  * a.assoc("foo") #=> nil
3475  */
3476 
3477 VALUE
3479 {
3480  long i;
3481  VALUE v;
3482 
3483  for (i = 0; i < RARRAY_LEN(ary); ++i) {
3484  v = rb_check_array_type(RARRAY_PTR(ary)[i]);
3485  if (!NIL_P(v) && RARRAY_LEN(v) > 0 &&
3486  rb_equal(RARRAY_PTR(v)[0], key))
3487  return v;
3488  }
3489  return Qnil;
3490 }
3491 
3492 /*
3493  * call-seq:
3494  * ary.rassoc(obj) -> new_ary or nil
3495  *
3496  * Searches through the array whose elements are also arrays.
3497  *
3498  * Compares +obj+ with the second element of each contained array using
3499  * <code>obj.==</code>.
3500  *
3501  * Returns the first contained array that matches +obj+.
3502  *
3503  * See also Array#assoc.
3504  *
3505  * a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ]
3506  * a.rassoc("two") #=> [2, "two"]
3507  * a.rassoc("four") #=> nil
3508  */
3509 
3510 VALUE
3512 {
3513  long i;
3514  VALUE v;
3515 
3516  for (i = 0; i < RARRAY_LEN(ary); ++i) {
3517  v = RARRAY_PTR(ary)[i];
3518  if (RB_TYPE_P(v, T_ARRAY) &&
3519  RARRAY_LEN(v) > 1 &&
3520  rb_equal(RARRAY_PTR(v)[1], value))
3521  return v;
3522  }
3523  return Qnil;
3524 }
3525 
3526 static VALUE
3528 {
3529  long i, len1;
3530  VALUE *p1, *p2;
3531 
3532  if (recur) return Qtrue; /* Subtle! */
3533 
3534  p1 = RARRAY_PTR(ary1);
3535  p2 = RARRAY_PTR(ary2);
3536  len1 = RARRAY_LEN(ary1);
3537 
3538  for (i = 0; i < len1; i++) {
3539  if (*p1 != *p2) {
3540  if (rb_equal(*p1, *p2)) {
3541  len1 = RARRAY_LEN(ary1);
3542  if (len1 != RARRAY_LEN(ary2))
3543  return Qfalse;
3544  if (len1 < i)
3545  return Qtrue;
3546  p1 = RARRAY_PTR(ary1) + i;
3547  p2 = RARRAY_PTR(ary2) + i;
3548  }
3549  else {
3550  return Qfalse;
3551  }
3552  }
3553  p1++;
3554  p2++;
3555  }
3556  return Qtrue;
3557 }
3558 
3559 /*
3560  * call-seq:
3561  * ary == other_ary -> bool
3562  *
3563  * Equality --- Two arrays are equal if they contain the same number of
3564  * elements and if each element is equal to (according to Object#==) the
3565  * corresponding element in +other_ary+.
3566  *
3567  * [ "a", "c" ] == [ "a", "c", 7 ] #=> false
3568  * [ "a", "c", 7 ] == [ "a", "c", 7 ] #=> true
3569  * [ "a", "c", 7 ] == [ "a", "d", "f" ] #=> false
3570  *
3571  */
3572 
3573 static VALUE
3575 {
3576  if (ary1 == ary2) return Qtrue;
3577  if (!RB_TYPE_P(ary2, T_ARRAY)) {
3578  if (!rb_respond_to(ary2, rb_intern("to_ary"))) {
3579  return Qfalse;
3580  }
3581  return rb_equal(ary2, ary1);
3582  }
3583  if (RARRAY_LEN(ary1) != RARRAY_LEN(ary2)) return Qfalse;
3584  return rb_exec_recursive_paired(recursive_equal, ary1, ary2, ary2);
3585 }
3586 
3587 static VALUE
3588 recursive_eql(VALUE ary1, VALUE ary2, int recur)
3589 {
3590  long i;
3591 
3592  if (recur) return Qtrue; /* Subtle! */
3593  for (i=0; i<RARRAY_LEN(ary1); i++) {
3594  if (!rb_eql(rb_ary_elt(ary1, i), rb_ary_elt(ary2, i)))
3595  return Qfalse;
3596  }
3597  return Qtrue;
3598 }
3599 
3600 /*
3601  * call-seq:
3602  * ary.eql?(other) -> true or false
3603  *
3604  * Returns +true+ if +self+ and +other+ are the same object,
3605  * or are both arrays with the same content (according to Object#eql?).
3606  */
3607 
3608 static VALUE
3610 {
3611  if (ary1 == ary2) return Qtrue;
3612  if (!RB_TYPE_P(ary2, T_ARRAY)) return Qfalse;
3613  if (RARRAY_LEN(ary1) != RARRAY_LEN(ary2)) return Qfalse;
3614  return rb_exec_recursive_paired(recursive_eql, ary1, ary2, ary2);
3615 }
3616 
3617 static VALUE
3619 {
3620  long i;
3621  st_index_t h;
3622  VALUE n;
3623 
3624  h = rb_hash_start(RARRAY_LEN(ary));
3625  if (recur) {
3627  }
3628  else {
3629  for (i=0; i<RARRAY_LEN(ary); i++) {
3630  n = rb_hash(RARRAY_PTR(ary)[i]);
3631  h = rb_hash_uint(h, NUM2LONG(n));
3632  }
3633  }
3634  h = rb_hash_end(h);
3635  return LONG2FIX(h);
3636 }
3637 
3638 /*
3639  * call-seq:
3640  * ary.hash -> fixnum
3641  *
3642  * Compute a hash-code for this array.
3643  *
3644  * Two arrays with the same content will have the same hash code (and will
3645  * compare using #eql?).
3646  */
3647 
3648 static VALUE
3650 {
3651  return rb_exec_recursive_outer(recursive_hash, ary, 0);
3652 }
3653 
3654 /*
3655  * call-seq:
3656  * ary.include?(object) -> true or false
3657  *
3658  * Returns +true+ if the given +object+ is present in +self+ (that is, if any
3659  * element <code>==</code> +object+), otherwise returns +false+.
3660  *
3661  * a = [ "a", "b", "c" ]
3662  * a.include?("b") #=> true
3663  * a.include?("z") #=> false
3664  */
3665 
3666 VALUE
3668 {
3669  long i;
3670 
3671  for (i=0; i<RARRAY_LEN(ary); i++) {
3672  if (rb_equal(RARRAY_PTR(ary)[i], item)) {
3673  return Qtrue;
3674  }
3675  }
3676  return Qfalse;
3677 }
3678 
3679 
3680 static VALUE
3681 recursive_cmp(VALUE ary1, VALUE ary2, int recur)
3682 {
3683  long i, len;
3684 
3685  if (recur) return Qundef; /* Subtle! */
3686  len = RARRAY_LEN(ary1);
3687  if (len > RARRAY_LEN(ary2)) {
3688  len = RARRAY_LEN(ary2);
3689  }
3690  for (i=0; i<len; i++) {
3691  VALUE v = rb_funcall(rb_ary_elt(ary1, i), id_cmp, 1, rb_ary_elt(ary2, i));
3692  if (v != INT2FIX(0)) {
3693  return v;
3694  }
3695  }
3696  return Qundef;
3697 }
3698 
3699 /*
3700  * call-seq:
3701  * ary <=> other_ary -> -1, 0, +1 or nil
3702  *
3703  * Comparison --- Returns an integer (+-1+, +0+, or <code>+1</code>) if this
3704  * array is less than, equal to, or greater than +other_ary+.
3705  *
3706  * +nil+ is returned if the two values are incomparable.
3707  *
3708  * Each object in each array is compared (using the <=> operator).
3709  *
3710  * Arrays are compared in an "element-wise" manner; the first two elements
3711  * that are not equal will determine the return value for the whole
3712  * comparison.
3713  *
3714  * If all the values are equal, then the return is based on a comparison of
3715  * the array lengths. Thus, two arrays are "equal" according to Array#<=> if,
3716  * and only if, they have the same length and the value of each element is
3717  * equal to the value of the corresponding element in the other array.
3718  *
3719  * [ "a", "a", "c" ] <=> [ "a", "b", "c" ] #=> -1
3720  * [ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ] #=> +1
3721  *
3722  */
3723 
3724 VALUE
3726 {
3727  long len;
3728  VALUE v;
3729 
3730  ary2 = rb_check_array_type(ary2);
3731  if (NIL_P(ary2)) return Qnil;
3732  if (ary1 == ary2) return INT2FIX(0);
3733  v = rb_exec_recursive_paired(recursive_cmp, ary1, ary2, ary2);
3734  if (v != Qundef) return v;
3735  len = RARRAY_LEN(ary1) - RARRAY_LEN(ary2);
3736  if (len == 0) return INT2FIX(0);
3737  if (len > 0) return INT2FIX(1);
3738  return INT2FIX(-1);
3739 }
3740 
3741 static VALUE
3743 {
3744  long i;
3745 
3746  for (i=0; i<RARRAY_LEN(ary); i++) {
3747  rb_hash_aset(hash, RARRAY_PTR(ary)[i], Qtrue);
3748  }
3749  return hash;
3750 }
3751 
3752 static inline VALUE
3754 {
3755  VALUE hash = rb_hash_new();
3756 
3757  RBASIC(hash)->klass = 0;
3758  return hash;
3759 }
3760 
3761 static VALUE
3763 {
3765  return ary_add_hash(hash, ary);
3766 }
3767 
3768 static VALUE
3770 {
3771  long i;
3772 
3773  for (i = 0; i < RARRAY_LEN(ary); ++i) {
3774  VALUE v = rb_ary_elt(ary, i), k = rb_yield(v);
3775  if (rb_hash_lookup2(hash, k, Qundef) == Qundef) {
3776  rb_hash_aset(hash, k, v);
3777  }
3778  }
3779  return hash;
3780 }
3781 
3782 static VALUE
3784 {
3786  return ary_add_hash_by(hash, ary);
3787 }
3788 
3789 static inline void
3791 {
3792  if (RHASH(hash)->ntbl) {
3793  st_table *tbl = RHASH(hash)->ntbl;
3794  RHASH(hash)->ntbl = 0;
3795  st_free_table(tbl);
3796  }
3797 }
3798 
3799 /*
3800  * call-seq:
3801  * ary - other_ary -> new_ary
3802  *
3803  * Array Difference
3804  *
3805  * Returns a new array that is a copy of the original array, removing any
3806  * items that also appear in +other_ary+. The order is preserved from the
3807  * original array.
3808  *
3809  * It compares elements using their #hash and #eql? methods for efficiency.
3810  *
3811  * [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]
3812  *
3813  * If you need set-like behavior, see the library class Set.
3814  */
3815 
3816 static VALUE
3818 {
3819  VALUE ary3;
3820  volatile VALUE hash;
3821  long i;
3822 
3823  hash = ary_make_hash(to_ary(ary2));
3824  ary3 = rb_ary_new();
3825 
3826  for (i=0; i<RARRAY_LEN(ary1); i++) {
3827  if (st_lookup(RHASH_TBL(hash), RARRAY_PTR(ary1)[i], 0)) continue;
3828  rb_ary_push(ary3, rb_ary_elt(ary1, i));
3829  }
3830  ary_recycle_hash(hash);
3831  return ary3;
3832 }
3833 
3834 /*
3835  * call-seq:
3836  * ary & other_ary -> new_ary
3837  *
3838  * Set Intersection --- Returns a new array containing elements common to the
3839  * two arrays, excluding any duplicates. The order is preserved from the
3840  * original array.
3841  *
3842  * It compares elements using their #hash and #eql? methods for efficiency.
3843  *
3844  * [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]
3845  * [ 'a', 'b', 'b', 'z' ] & [ 'a', 'b', 'c' ] #=> [ 'a', 'b' ]
3846  *
3847  * See also Array#uniq.
3848  */
3849 
3850 
3851 static VALUE
3853 {
3854  VALUE hash, ary3, v;
3855  st_data_t vv;
3856  long i;
3857 
3858  ary2 = to_ary(ary2);
3859  ary3 = rb_ary_new2(RARRAY_LEN(ary1) < RARRAY_LEN(ary2) ?
3860  RARRAY_LEN(ary1) : RARRAY_LEN(ary2));
3861  hash = ary_make_hash(ary2);
3862 
3863  if (RHASH_EMPTY_P(hash))
3864  return ary3;
3865 
3866  for (i=0; i<RARRAY_LEN(ary1); i++) {
3867  vv = (st_data_t)(v = rb_ary_elt(ary1, i));
3868  if (st_delete(RHASH_TBL(hash), &vv, 0)) {
3869  rb_ary_push(ary3, v);
3870  }
3871  }
3872  ary_recycle_hash(hash);
3873 
3874  return ary3;
3875 }
3876 
3877 /*
3878  * call-seq:
3879  * ary | other_ary -> new_ary
3880  *
3881  * Set Union --- Returns a new array by joining +ary+ with +other_ary+,
3882  * excluding any duplicates and preserving the order from the original array.
3883  *
3884  * It compares elements using their #hash and #eql? methods for efficiency.
3885  *
3886  * [ "a", "b", "c" ] | [ "c", "d", "a" ] #=> [ "a", "b", "c", "d" ]
3887  *
3888  * See also Array#uniq.
3889  */
3890 
3891 static VALUE
3892 rb_ary_or(VALUE ary1, VALUE ary2)
3893 {
3894  VALUE hash, ary3, v;
3895  st_data_t vv;
3896  long i;
3897 
3898  ary2 = to_ary(ary2);
3899  ary3 = rb_ary_new2(RARRAY_LEN(ary1)+RARRAY_LEN(ary2));
3900  hash = ary_add_hash(ary_make_hash(ary1), ary2);
3901 
3902  for (i=0; i<RARRAY_LEN(ary1); i++) {
3903  vv = (st_data_t)(v = rb_ary_elt(ary1, i));
3904  if (st_delete(RHASH_TBL(hash), &vv, 0)) {
3905  rb_ary_push(ary3, v);
3906  }
3907  }
3908  for (i=0; i<RARRAY_LEN(ary2); i++) {
3909  vv = (st_data_t)(v = rb_ary_elt(ary2, i));
3910  if (st_delete(RHASH_TBL(hash), &vv, 0)) {
3911  rb_ary_push(ary3, v);
3912  }
3913  }
3914  ary_recycle_hash(hash);
3915  return ary3;
3916 }
3917 
3918 static int
3920 {
3921  rb_ary_push((VALUE)ary, (VALUE)val);
3922  return ST_CONTINUE;
3923 }
3924 
3925 /*
3926  * call-seq:
3927  * ary.uniq! -> ary or nil
3928  * ary.uniq! { |item| ... } -> ary or nil
3929  *
3930  * Removes duplicate elements from +self+.
3931  *
3932  * If a block is given, it will use the return value of the block for
3933  * comparison.
3934  *
3935  * It compares values using their #hash and #eql? methods for efficiency.
3936  *
3937  * Returns +nil+ if no changes are made (that is, no duplicates are found).
3938  *
3939  * a = [ "a", "a", "b", "b", "c" ]
3940  * a.uniq! # => ["a", "b", "c"]
3941  *
3942  * b = [ "a", "b", "c" ]
3943  * b.uniq! # => nil
3944  *
3945  * c = [["student","sam"], ["student","george"], ["teacher","matz"]]
3946  * c.uniq! { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
3947  *
3948  */
3949 
3950 static VALUE
3952 {
3953  VALUE hash, v;
3954  long i, j;
3955 
3956  rb_ary_modify_check(ary);
3957  if (RARRAY_LEN(ary) <= 1)
3958  return Qnil;
3959  if (rb_block_given_p()) {
3960  hash = ary_make_hash_by(ary);
3961  if (RARRAY_LEN(ary) == (i = RHASH_SIZE(hash))) {
3962  return Qnil;
3963  }
3964  ARY_SET_LEN(ary, 0);
3965  if (ARY_SHARED_P(ary) && !ARY_EMBED_P(ary)) {
3966  rb_ary_unshare(ary);
3967  FL_SET_EMBED(ary);
3968  }
3969  ary_resize_capa(ary, i);
3970  st_foreach(RHASH_TBL(hash), push_value, ary);
3971  }
3972  else {
3973  hash = ary_make_hash(ary);
3974  if (RARRAY_LEN(ary) == (long)RHASH_SIZE(hash)) {
3975  return Qnil;
3976  }
3977  for (i=j=0; i<RARRAY_LEN(ary); i++) {
3978  st_data_t vv = (st_data_t)(v = rb_ary_elt(ary, i));
3979  if (st_delete(RHASH_TBL(hash), &vv, 0)) {
3980  rb_ary_store(ary, j++, v);
3981  }
3982  }
3983  ARY_SET_LEN(ary, j);
3984  }
3985  ary_recycle_hash(hash);
3986 
3987  return ary;
3988 }
3989 
3990 /*
3991  * call-seq:
3992  * ary.uniq -> new_ary
3993  * ary.uniq { |item| ... } -> new_ary
3994  *
3995  * Returns a new array by removing duplicate values in +self+.
3996  *
3997  * If a block is given, it will use the return value of the block for comparison.
3998  *
3999  * It compares values using their #hash and #eql? methods for efficiency.
4000  *
4001  * a = [ "a", "a", "b", "b", "c" ]
4002  * a.uniq # => ["a", "b", "c"]
4003  *
4004  * b = [["student","sam"], ["student","george"], ["teacher","matz"]]
4005  * b.uniq { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
4006  *
4007  */
4008 
4009 static VALUE
4011 {
4012  VALUE hash, uniq, v;
4013  long i;
4014 
4015  if (RARRAY_LEN(ary) <= 1)
4016  return rb_ary_dup(ary);
4017  if (rb_block_given_p()) {
4018  hash = ary_make_hash_by(ary);
4019  uniq = ary_new(rb_obj_class(ary), RHASH_SIZE(hash));
4020  st_foreach(RHASH_TBL(hash), push_value, uniq);
4021  }
4022  else {
4023  hash = ary_make_hash(ary);
4024  uniq = ary_new(rb_obj_class(ary), RHASH_SIZE(hash));
4025  for (i=0; i<RARRAY_LEN(ary); i++) {
4026  st_data_t vv = (st_data_t)(v = rb_ary_elt(ary, i));
4027  if (st_delete(RHASH_TBL(hash), &vv, 0)) {
4028  rb_ary_push(uniq, v);
4029  }
4030  }
4031  }
4032  ary_recycle_hash(hash);
4033 
4034  return uniq;
4035 }
4036 
4037 /*
4038  * call-seq:
4039  * ary.compact! -> ary or nil
4040  *
4041  * Removes +nil+ elements from the array.
4042  *
4043  * Returns +nil+ if no changes were made, otherwise returns the array.
4044  *
4045  * [ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
4046  * [ "a", "b", "c" ].compact! #=> nil
4047  */
4048 
4049 static VALUE
4051 {
4052  VALUE *p, *t, *end;
4053  long n;
4054 
4055  rb_ary_modify(ary);
4056  p = t = RARRAY_PTR(ary);
4057  end = p + RARRAY_LEN(ary);
4058 
4059  while (t < end) {
4060  if (NIL_P(*t)) t++;
4061  else *p++ = *t++;
4062  }
4063  n = p - RARRAY_PTR(ary);
4064  if (RARRAY_LEN(ary) == n) {
4065  return Qnil;
4066  }
4067  ARY_SET_LEN(ary, n);
4068  if (n * 2 < ARY_CAPA(ary) && ARY_DEFAULT_SIZE * 2 < ARY_CAPA(ary)) {
4069  ary_resize_capa(ary, n * 2);
4070  }
4071 
4072  return ary;
4073 }
4074 
4075 /*
4076  * call-seq:
4077  * ary.compact -> new_ary
4078  *
4079  * Returns a copy of +self+ with all +nil+ elements removed.
4080  *
4081  * [ "a", nil, "b", nil, "c", nil ].compact
4082  * #=> [ "a", "b", "c" ]
4083  */
4084 
4085 static VALUE
4087 {
4088  ary = rb_ary_dup(ary);
4089  rb_ary_compact_bang(ary);
4090  return ary;
4091 }
4092 
4093 /*
4094  * call-seq:
4095  * ary.count -> int
4096  * ary.count(obj) -> int
4097  * ary.count { |item| block } -> int
4098  *
4099  * Returns the number of elements.
4100  *
4101  * If an argument is given, counts the number of elements which equal +obj+
4102  * using <code>===</code>.
4103  *
4104  * If a block is given, counts the number of elements for which the block
4105  * returns a true value.
4106  *
4107  * ary = [1, 2, 4, 2]
4108  * ary.count #=> 4
4109  * ary.count(2) #=> 2
4110  * ary.count { |x| x%2 == 0 } #=> 3
4111  *
4112  */
4113 
4114 static VALUE
4115 rb_ary_count(int argc, VALUE *argv, VALUE ary)
4116 {
4117  long n = 0;
4118 
4119  if (argc == 0) {
4120  VALUE *p, *pend;
4121 
4122  if (!rb_block_given_p())
4123  return LONG2NUM(RARRAY_LEN(ary));
4124 
4125  for (p = RARRAY_PTR(ary), pend = p + RARRAY_LEN(ary); p < pend; p++) {
4126  if (RTEST(rb_yield(*p))) n++;
4127  }
4128  }
4129  else {
4130  VALUE obj, *p, *pend;
4131 
4132  rb_scan_args(argc, argv, "1", &obj);
4133  if (rb_block_given_p()) {
4134  rb_warn("given block not used");
4135  }
4136  for (p = RARRAY_PTR(ary), pend = p + RARRAY_LEN(ary); p < pend; p++) {
4137  if (rb_equal(*p, obj)) n++;
4138  }
4139  }
4140 
4141  return LONG2NUM(n);
4142 }
4143 
4144 static VALUE
4145 flatten(VALUE ary, int level, int *modified)
4146 {
4147  long i = 0;
4148  VALUE stack, result, tmp, elt;
4149  st_table *memo;
4150  st_data_t id;
4151 
4152  stack = ary_new(0, ARY_DEFAULT_SIZE);
4153  result = ary_new(0, RARRAY_LEN(ary));
4154  memo = st_init_numtable();
4155  st_insert(memo, (st_data_t)ary, (st_data_t)Qtrue);
4156  *modified = 0;
4157 
4158  while (1) {
4159  while (i < RARRAY_LEN(ary)) {
4160  elt = RARRAY_PTR(ary)[i++];
4161  tmp = rb_check_array_type(elt);
4162  if (RBASIC(result)->klass) {
4163  rb_raise(rb_eRuntimeError, "flatten reentered");
4164  }
4165  if (NIL_P(tmp) || (level >= 0 && RARRAY_LEN(stack) / 2 >= level)) {
4166  rb_ary_push(result, elt);
4167  }
4168  else {
4169  *modified = 1;
4170  id = (st_data_t)tmp;
4171  if (st_lookup(memo, id, 0)) {
4172  st_free_table(memo);
4173  rb_raise(rb_eArgError, "tried to flatten recursive array");
4174  }
4175  st_insert(memo, id, (st_data_t)Qtrue);
4176  rb_ary_push(stack, ary);
4177  rb_ary_push(stack, LONG2NUM(i));
4178  ary = tmp;
4179  i = 0;
4180  }
4181  }
4182  if (RARRAY_LEN(stack) == 0) {
4183  break;
4184  }
4185  id = (st_data_t)ary;
4186  st_delete(memo, &id, 0);
4187  tmp = rb_ary_pop(stack);
4188  i = NUM2LONG(tmp);
4189  ary = rb_ary_pop(stack);
4190  }
4191 
4192  st_free_table(memo);
4193 
4194  RBASIC(result)->klass = rb_class_of(ary);
4195  return result;
4196 }
4197 
4198 /*
4199  * call-seq:
4200  * ary.flatten! -> ary or nil
4201  * ary.flatten!(level) -> ary or nil
4202  *
4203  * Flattens +self+ in place.
4204  *
4205  * Returns +nil+ if no modifications were made (i.e., the array contains no
4206  * subarrays.)
4207  *
4208  * The optional +level+ argument determines the level of recursion to flatten.
4209  *
4210  * a = [ 1, 2, [3, [4, 5] ] ]
4211  * a.flatten! #=> [1, 2, 3, 4, 5]
4212  * a.flatten! #=> nil
4213  * a #=> [1, 2, 3, 4, 5]
4214  * a = [ 1, 2, [3, [4, 5] ] ]
4215  * a.flatten!(1) #=> [1, 2, 3, [4, 5]]
4216  */
4217 
4218 static VALUE
4220 {
4221  int mod = 0, level = -1;
4222  VALUE result, lv;
4223 
4224  rb_scan_args(argc, argv, "01", &lv);
4225  rb_ary_modify_check(ary);
4226  if (!NIL_P(lv)) level = NUM2INT(lv);
4227  if (level == 0) return Qnil;
4228 
4229  result = flatten(ary, level, &mod);
4230  if (mod == 0) {
4231  ary_discard(result);
4232  return Qnil;
4233  }
4234  if (!(mod = ARY_EMBED_P(result))) rb_obj_freeze(result);
4235  rb_ary_replace(ary, result);
4236  if (mod) ARY_SET_EMBED_LEN(result, 0);
4237 
4238  return ary;
4239 }
4240 
4241 /*
4242  * call-seq:
4243  * ary.flatten -> new_ary
4244  * ary.flatten(level) -> new_ary
4245  *
4246  * Returns a new array that is a one-dimensional flattening of +self+
4247  * (recursively).
4248  *
4249  * That is, for every element that is an array, extract its elements into
4250  * the new array.
4251  *
4252  * The optional +level+ argument determines the level of recursion to
4253  * flatten.
4254  *
4255  * s = [ 1, 2, 3 ] #=> [1, 2, 3]
4256  * t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
4257  * a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
4258  * a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4259  * a = [ 1, 2, [3, [4, 5] ] ]
4260  * a.flatten(1) #=> [1, 2, 3, [4, 5]]
4261  */
4262 
4263 static VALUE
4264 rb_ary_flatten(int argc, VALUE *argv, VALUE ary)
4265 {
4266  int mod = 0, level = -1;
4267  VALUE result, lv;
4268 
4269  rb_scan_args(argc, argv, "01", &lv);
4270  if (!NIL_P(lv)) level = NUM2INT(lv);
4271  if (level == 0) return ary_make_shared_copy(ary);
4272 
4273  result = flatten(ary, level, &mod);
4274  OBJ_INFECT(result, ary);
4275 
4276  return result;
4277 }
4278 
4279 #define OPTHASH_GIVEN_P(opts) \
4280  (argc > 0 && !NIL_P((opts) = rb_check_hash_type(argv[argc-1])) && (--argc, 1))
4282 
4283 #define RAND_UPTO(max) (long)rb_random_ulong_limited((randgen), (max)-1)
4284 
4285 /*
4286  * call-seq:
4287  * ary.shuffle! -> ary
4288  * ary.shuffle!(random: rng) -> ary
4289  *
4290  * Shuffles elements in +self+ in place.
4291  *
4292  * The optional +rng+ argument will be used as the random number generator.
4293  */
4294 
4295 static VALUE
4297 {
4298  VALUE *ptr, opts, *snap_ptr, randgen = rb_cRandom;
4299  long i, snap_len;
4300 
4301  if (OPTHASH_GIVEN_P(opts)) {
4302  randgen = rb_hash_lookup2(opts, sym_random, randgen);
4303  }
4304  rb_check_arity(argc, 0, 0);
4305  rb_ary_modify(ary);
4306  i = RARRAY_LEN(ary);
4307  ptr = RARRAY_PTR(ary);
4308  snap_len = i;
4309  snap_ptr = ptr;
4310  while (i) {
4311  long j = RAND_UPTO(i);
4312  VALUE tmp;
4313  if (snap_len != RARRAY_LEN(ary) || snap_ptr != RARRAY_PTR(ary)) {
4314  rb_raise(rb_eRuntimeError, "modified during shuffle");
4315  }
4316  tmp = ptr[--i];
4317  ptr[i] = ptr[j];
4318  ptr[j] = tmp;
4319  }
4320  return ary;
4321 }
4322 
4323 
4324 /*
4325  * call-seq:
4326  * ary.shuffle -> new_ary
4327  * ary.shuffle(random: rng) -> new_ary
4328  *
4329  * Returns a new array with elements of +self+ shuffled.
4330  *
4331  * a = [ 1, 2, 3 ] #=> [1, 2, 3]
4332  * a.shuffle #=> [2, 3, 1]
4333  *
4334  * The optional +rng+ argument will be used as the random number generator.
4335  *
4336  * a.shuffle(random: Random.new(1)) #=> [1, 3, 2]
4337  */
4338 
4339 static VALUE
4340 rb_ary_shuffle(int argc, VALUE *argv, VALUE ary)
4341 {
4342  ary = rb_ary_dup(ary);
4343  rb_ary_shuffle_bang(argc, argv, ary);
4344  return ary;
4345 }
4346 
4347 
4348 /*
4349  * call-seq:
4350  * ary.sample -> obj
4351  * ary.sample(random: rng) -> obj
4352  * ary.sample(n) -> new_ary
4353  * ary.sample(n, random: rng) -> new_ary
4354  *
4355  * Choose a random element or +n+ random elements from the array.
4356  *
4357  * The elements are chosen by using random and unique indices into the array
4358  * in order to ensure that an element doesn't repeat itself unless the array
4359  * already contained duplicate elements.
4360  *
4361  * If the array is empty the first form returns +nil+ and the second form
4362  * returns an empty array.
4363  *
4364  * The optional +rng+ argument will be used as the random number generator.
4365  *
4366  * a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
4367  * a.sample #=> 7
4368  * a.sample(4) #=> [6, 4, 2, 5]
4369  */
4370 
4371 
4372 static VALUE
4373 rb_ary_sample(int argc, VALUE *argv, VALUE ary)
4374 {
4375  VALUE nv, result, *ptr;
4376  VALUE opts, randgen = rb_cRandom;
4377  long n, len, i, j, k, idx[10];
4378  long rnds[numberof(idx)];
4379 
4380  if (OPTHASH_GIVEN_P(opts)) {
4381  randgen = rb_hash_lookup2(opts, sym_random, randgen);
4382  }
4383  ptr = RARRAY_PTR(ary);
4384  len = RARRAY_LEN(ary);
4385  if (argc == 0) {
4386  if (len == 0) return Qnil;
4387  if (len == 1) {
4388  i = 0;
4389  }
4390  else {
4391  i = RAND_UPTO(len);
4392  if ((len = RARRAY_LEN(ary)) <= i) return Qnil;
4393  ptr = RARRAY_PTR(ary);
4394  }
4395  return ptr[i];
4396  }
4397  rb_scan_args(argc, argv, "1", &nv);
4398  n = NUM2LONG(nv);
4399  if (n < 0) rb_raise(rb_eArgError, "negative sample number");
4400  if (n > len) n = len;
4401  if (n <= numberof(idx)) {
4402  for (i = 0; i < n; ++i) {
4403  rnds[i] = RAND_UPTO(len - i);
4404  }
4405  }
4406  k = len;
4407  len = RARRAY_LEN(ary);
4408  ptr = RARRAY_PTR(ary);
4409  if (len < k) {
4410  if (n <= numberof(idx)) {
4411  for (i = 0; i < n; ++i) {
4412  if (rnds[i] >= len) {
4413  return rb_ary_new2(0);
4414  }
4415  }
4416  }
4417  }
4418  if (n > len) n = len;
4419  switch (n) {
4420  case 0:
4421  return rb_ary_new2(0);
4422  case 1:
4423  i = rnds[0];
4424  return rb_ary_new4(1, &ptr[i]);
4425  case 2:
4426  i = rnds[0];
4427  j = rnds[1];
4428  if (j >= i) j++;
4429  return rb_ary_new3(2, ptr[i], ptr[j]);
4430  case 3:
4431  i = rnds[0];
4432  j = rnds[1];
4433  k = rnds[2];
4434  {
4435  long l = j, g = i;
4436  if (j >= i) l = i, g = ++j;
4437  if (k >= l && (++k >= g)) ++k;
4438  }
4439  return rb_ary_new3(3, ptr[i], ptr[j], ptr[k]);
4440  }
4441  if (n <= numberof(idx)) {
4442  VALUE *ptr_result;
4443  long sorted[numberof(idx)];
4444  sorted[0] = idx[0] = rnds[0];
4445  for (i=1; i<n; i++) {
4446  k = rnds[i];
4447  for (j = 0; j < i; ++j) {
4448  if (k < sorted[j]) break;
4449  ++k;
4450  }
4451  memmove(&sorted[j+1], &sorted[j], sizeof(sorted[0])*(i-j));
4452  sorted[j] = idx[i] = k;
4453  }
4454  result = rb_ary_new2(n);
4455  ptr_result = RARRAY_PTR(result);
4456  for (i=0; i<n; i++) {
4457  ptr_result[i] = ptr[idx[i]];
4458  }
4459  }
4460  else {
4461  VALUE *ptr_result;
4462  result = rb_ary_new4(len, ptr);
4463  RBASIC(result)->klass = 0;
4464  ptr_result = RARRAY_PTR(result);
4465  RB_GC_GUARD(ary);
4466  for (i=0; i<n; i++) {
4467  j = RAND_UPTO(len-i) + i;
4468  nv = ptr_result[j];
4469  ptr_result[j] = ptr_result[i];
4470  ptr_result[i] = nv;
4471  }
4472  RBASIC(result)->klass = rb_cArray;
4473  }
4474  ARY_SET_LEN(result, n);
4475 
4476  return result;
4477 }
4478 
4479 static VALUE
4481 {
4482  long mul;
4483  VALUE n = Qnil;
4484  if (args && (RARRAY_LEN(args) > 0)) {
4485  n = RARRAY_PTR(args)[0];
4486  }
4487  if (RARRAY_LEN(self) == 0) return INT2FIX(0);
4488  if (n == Qnil) return DBL2NUM(INFINITY);
4489  mul = NUM2LONG(n);
4490  if (mul <= 0) return INT2FIX(0);
4491  return rb_funcall(rb_ary_length(self), '*', 1, LONG2FIX(mul));
4492 }
4493 
4494 /*
4495  * call-seq:
4496  * ary.cycle(n=nil) { |obj| block } -> nil
4497  * ary.cycle(n=nil) -> Enumerator
4498  *
4499  * Calls the given block for each element +n+ times or forever if +nil+ is
4500  * given.
4501  *
4502  * Does nothing if a non-positive number is given or the array is empty.
4503  *
4504  * Returns +nil+ if the loop has finished without getting interrupted.
4505  *
4506  * If no block is given, an Enumerator is returned instead.
4507  *
4508  * a = ["a", "b", "c"]
4509  * a.cycle { |x| puts x } # print, a, b, c, a, b, c,.. forever.
4510  * a.cycle(2) { |x| puts x } # print, a, b, c, a, b, c.
4511  *
4512  */
4513 
4514 static VALUE
4515 rb_ary_cycle(int argc, VALUE *argv, VALUE ary)
4516 {
4517  long n, i;
4518  VALUE nv = Qnil;
4519 
4520  rb_scan_args(argc, argv, "01", &nv);
4521 
4522  RETURN_SIZED_ENUMERATOR(ary, argc, argv, rb_ary_cycle_size);
4523  if (NIL_P(nv)) {
4524  n = -1;
4525  }
4526  else {
4527  n = NUM2LONG(nv);
4528  if (n <= 0) return Qnil;
4529  }
4530 
4531  while (RARRAY_LEN(ary) > 0 && (n < 0 || 0 < n--)) {
4532  for (i=0; i<RARRAY_LEN(ary); i++) {
4533  rb_yield(RARRAY_PTR(ary)[i]);
4534  }
4535  }
4536  return Qnil;
4537 }
4538 
4539 #define tmpbuf(n, size) rb_str_tmp_new((n)*(size))
4540 #define tmpbuf_discard(s) (rb_str_resize((s), 0L), RBASIC(s)->klass = rb_cString)
4541 #define tmpary(n) rb_ary_tmp_new(n)
4542 #define tmpary_discard(a) (ary_discard(a), RBASIC(a)->klass = rb_cArray)
4543 
4544 /*
4545  * Recursively compute permutations of +r+ elements of the set
4546  * <code>[0..n-1]</code>.
4547  *
4548  * When we have a complete permutation of array indexes, copy the values
4549  * at those indexes into a new array and yield that array.
4550  *
4551  * n: the size of the set
4552  * r: the number of elements in each permutation
4553  * p: the array (of size r) that we're filling in
4554  * index: what index we're filling in now
4555  * used: an array of booleans: whether a given index is already used
4556  * values: the Ruby array that holds the actual values to permute
4557  */
4558 static void
4559 permute0(long n, long r, long *p, long index, char *used, VALUE values)
4560 {
4561  long i,j;
4562  for (i = 0; i < n; i++) {
4563  if (used[i] == 0) {
4564  p[index] = i;
4565  if (index < r-1) { /* if not done yet */
4566  used[i] = 1; /* mark index used */
4567  permute0(n, r, p, index+1, /* recurse */
4568  used, values);
4569  used[i] = 0; /* index unused */
4570  }
4571  else {
4572  /* We have a complete permutation of array indexes */
4573  /* Build a ruby array of the corresponding values */
4574  /* And yield it to the associated block */
4575  VALUE result = rb_ary_new2(r);
4576  VALUE *result_array = RARRAY_PTR(result);
4577  const VALUE *values_array = RARRAY_PTR(values);
4578 
4579  for (j = 0; j < r; j++) result_array[j] = values_array[p[j]];
4580  ARY_SET_LEN(result, r);
4581  rb_yield(result);
4582  if (RBASIC(values)->klass) {
4583  rb_raise(rb_eRuntimeError, "permute reentered");
4584  }
4585  }
4586  }
4587  }
4588 }
4589 
4590 /*
4591  * Returns the product of from, from-1, ..., from - how_many + 1.
4592  * http://en.wikipedia.org/wiki/Pochhammer_symbol
4593  */
4594 static VALUE
4595 descending_factorial(long from, long how_many)
4596 {
4597  VALUE cnt = LONG2FIX(how_many >= 0);
4598  while (how_many-- > 0) {
4599  cnt = rb_funcall(cnt, '*', 1, LONG2FIX(from--));
4600  }
4601  return cnt;
4602 }
4603 
4604 static VALUE
4605 binomial_coefficient(long comb, long size)
4606 {
4607  if (comb > size-comb) {
4608  comb = size-comb;
4609  }
4610  if (comb < 0) {
4611  return LONG2FIX(0);
4612  }
4613  return rb_funcall(descending_factorial(size, comb), id_div, 1, descending_factorial(comb, comb));
4614 }
4615 
4616 static VALUE
4618 {
4619  long n = RARRAY_LEN(ary);
4620  long k = (args && (RARRAY_LEN(args) > 0)) ? NUM2LONG(RARRAY_PTR(args)[0]) : n;
4621 
4622  return descending_factorial(n, k);
4623 }
4624 
4625 /*
4626  * call-seq:
4627  * ary.permutation { |p| block } -> ary
4628  * ary.permutation -> Enumerator
4629  * ary.permutation(n) { |p| block } -> ary
4630  * ary.permutation(n) -> Enumerator
4631  *
4632  * When invoked with a block, yield all permutations of length +n+ of the
4633  * elements of the array, then return the array itself.
4634  *
4635  * If +n+ is not specified, yield all permutations of all elements.
4636  *
4637  * The implementation makes no guarantees about the order in which the
4638  * permutations are yielded.
4639  *
4640  * If no block is given, an Enumerator is returned instead.
4641  *
4642  * Examples:
4643  *
4644  * a = [1, 2, 3]
4645  * a.permutation.to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
4646  * a.permutation(1).to_a #=> [[1],[2],[3]]
4647  * a.permutation(2).to_a #=> [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
4648  * a.permutation(3).to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
4649  * a.permutation(0).to_a #=> [[]] # one permutation of length 0
4650  * a.permutation(4).to_a #=> [] # no permutations of length 4
4651  */
4652 
4653 static VALUE
4655 {
4656  VALUE num;
4657  long r, n, i;
4658 
4659  n = RARRAY_LEN(ary); /* Array length */
4660  RETURN_SIZED_ENUMERATOR(ary, argc, argv, rb_ary_permutation_size); /* Return enumerator if no block */
4661  rb_scan_args(argc, argv, "01", &num);
4662  r = NIL_P(num) ? n : NUM2LONG(num); /* Permutation size from argument */
4663 
4664  if (r < 0 || n < r) {
4665  /* no permutations: yield nothing */
4666  }
4667  else if (r == 0) { /* exactly one permutation: the zero-length array */
4668  rb_yield(rb_ary_new2(0));
4669  }
4670  else if (r == 1) { /* this is a special, easy case */
4671  for (i = 0; i < RARRAY_LEN(ary); i++) {
4672  rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
4673  }
4674  }
4675  else { /* this is the general case */
4676  volatile VALUE t0 = tmpbuf(n,sizeof(long));
4677  long *p = (long*)RSTRING_PTR(t0);
4678  volatile VALUE t1 = tmpbuf(n,sizeof(char));
4679  char *used = (char*)RSTRING_PTR(t1);
4680  VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
4681  RBASIC(ary0)->klass = 0;
4682 
4683  MEMZERO(used, char, n); /* initialize array */
4684 
4685  permute0(n, r, p, 0, used, ary0); /* compute and yield permutations */
4686  tmpbuf_discard(t0);
4687  tmpbuf_discard(t1);
4688  RBASIC(ary0)->klass = rb_cArray;
4689  }
4690  return ary;
4691 }
4692 
4693 static VALUE
4695 {
4696  long n = RARRAY_LEN(ary);
4697  long k = NUM2LONG(RARRAY_PTR(args)[0]);
4698 
4699  return binomial_coefficient(k, n);
4700 }
4701 
4702 /*
4703  * call-seq:
4704  * ary.combination(n) { |c| block } -> ary
4705  * ary.combination(n) -> Enumerator
4706  *
4707  * When invoked with a block, yields all combinations of length +n+ of elements
4708  * from the array and then returns the array itself.
4709  *
4710  * The implementation makes no guarantees about the order in which the
4711  * combinations are yielded.
4712  *
4713  * If no block is given, an Enumerator is returned instead.
4714  *
4715  * Examples:
4716  *
4717  * a = [1, 2, 3, 4]
4718  * a.combination(1).to_a #=> [[1],[2],[3],[4]]
4719  * a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
4720  * a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
4721  * a.combination(4).to_a #=> [[1,2,3,4]]
4722  * a.combination(0).to_a #=> [[]] # one combination of length 0
4723  * a.combination(5).to_a #=> [] # no combinations of length 5
4724  *
4725  */
4726 
4727 static VALUE
4729 {
4730  long n, i, len;
4731 
4732  n = NUM2LONG(num);
4734  len = RARRAY_LEN(ary);
4735  if (n < 0 || len < n) {
4736  /* yield nothing */
4737  }
4738  else if (n == 0) {
4739  rb_yield(rb_ary_new2(0));
4740  }
4741  else if (n == 1) {
4742  for (i = 0; i < len; i++) {
4743  rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
4744  }
4745  }
4746  else {
4747  volatile VALUE t0 = tmpbuf(n+1, sizeof(long));
4748  long *stack = (long*)RSTRING_PTR(t0);
4749  volatile VALUE cc = tmpary(n);
4750  VALUE *chosen = RARRAY_PTR(cc);
4751  long lev = 0;
4752 
4753  MEMZERO(stack, long, n);
4754  stack[0] = -1;
4755  for (;;) {
4756  chosen[lev] = RARRAY_PTR(ary)[stack[lev+1]];
4757  for (lev++; lev < n; lev++) {
4758  chosen[lev] = RARRAY_PTR(ary)[stack[lev+1] = stack[lev]+1];
4759  }
4760  rb_yield(rb_ary_new4(n, chosen));
4761  if (RBASIC(t0)->klass) {
4762  rb_raise(rb_eRuntimeError, "combination reentered");
4763  }
4764  do {
4765  if (lev == 0) goto done;
4766  stack[lev--]++;
4767  } while (stack[lev+1]+n == len+lev+1);
4768  }
4769  done:
4770  tmpbuf_discard(t0);
4771  tmpary_discard(cc);
4772  }
4773  return ary;
4774 }
4775 
4776 /*
4777  * Recursively compute repeated permutations of +r+ elements of the set
4778  * <code>[0..n-1]</code>.
4779  *
4780  * When we have a complete repeated permutation of array indexes, copy the
4781  * values at those indexes into a new array and yield that array.
4782  *
4783  * n: the size of the set
4784  * r: the number of elements in each permutation
4785  * p: the array (of size r) that we're filling in
4786  * index: what index we're filling in now
4787  * values: the Ruby array that holds the actual values to permute
4788  */
4789 static void
4790 rpermute0(long n, long r, long *p, long index, VALUE values)
4791 {
4792  long i, j;
4793  for (i = 0; i < n; i++) {
4794  p[index] = i;
4795  if (index < r-1) { /* if not done yet */
4796  rpermute0(n, r, p, index+1, values); /* recurse */
4797  }
4798  else {
4799  /* We have a complete permutation of array indexes */
4800  /* Build a ruby array of the corresponding values */
4801  /* And yield it to the associated block */
4802  VALUE result = rb_ary_new2(r);
4803  VALUE *result_array = RARRAY_PTR(result);
4804  const VALUE *values_array = RARRAY_PTR(values);
4805 
4806  for (j = 0; j < r; j++) result_array[j] = values_array[p[j]];
4807  ARY_SET_LEN(result, r);
4808  rb_yield(result);
4809  if (RBASIC(values)->klass) {
4810  rb_raise(rb_eRuntimeError, "repeated permute reentered");
4811  }
4812  }
4813  }
4814 }
4815 
4816 static VALUE
4818 {
4819  long n = RARRAY_LEN(ary);
4820  long k = NUM2LONG(RARRAY_PTR(args)[0]);
4821 
4822  if (k < 0) {
4823  return LONG2FIX(0);
4824  }
4825 
4826  return rb_funcall(LONG2NUM(n), id_power, 1, LONG2NUM(k));
4827 }
4828 
4829 /*
4830  * call-seq:
4831  * ary.repeated_permutation(n) { |p| block } -> ary
4832  * ary.repeated_permutation(n) -> Enumerator
4833  *
4834  * When invoked with a block, yield all repeated permutations of length +n+ of
4835  * the elements of the array, then return the array itself.
4836  *
4837  * The implementation makes no guarantees about the order in which the repeated
4838  * permutations are yielded.
4839  *
4840  * If no block is given, an Enumerator is returned instead.
4841  *
4842  * Examples:
4843  *
4844  * a = [1, 2]
4845  * a.repeated_permutation(1).to_a #=> [[1], [2]]
4846  * a.repeated_permutation(2).to_a #=> [[1,1],[1,2],[2,1],[2,2]]
4847  * a.repeated_permutation(3).to_a #=> [[1,1,1],[1,1,2],[1,2,1],[1,2,2],
4848  * # [2,1,1],[2,1,2],[2,2,1],[2,2,2]]
4849  * a.repeated_permutation(0).to_a #=> [[]] # one permutation of length 0
4850  */
4851 
4852 static VALUE
4854 {
4855  long r, n, i;
4856 
4857  n = RARRAY_LEN(ary); /* Array length */
4858  RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_repeated_permutation_size); /* Return Enumerator if no block */
4859  r = NUM2LONG(num); /* Permutation size from argument */
4860 
4861  if (r < 0) {
4862  /* no permutations: yield nothing */
4863  }
4864  else if (r == 0) { /* exactly one permutation: the zero-length array */
4865  rb_yield(rb_ary_new2(0));
4866  }
4867  else if (r == 1) { /* this is a special, easy case */
4868  for (i = 0; i < RARRAY_LEN(ary); i++) {
4869  rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
4870  }
4871  }
4872  else { /* this is the general case */
4873  volatile VALUE t0 = tmpbuf(r, sizeof(long));
4874  long *p = (long*)RSTRING_PTR(t0);
4875  VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
4876  RBASIC(ary0)->klass = 0;
4877 
4878  rpermute0(n, r, p, 0, ary0); /* compute and yield repeated permutations */
4879  tmpbuf_discard(t0);
4880  RBASIC(ary0)->klass = rb_cArray;
4881  }
4882  return ary;
4883 }
4884 
4885 static void
4886 rcombinate0(long n, long r, long *p, long index, long rest, VALUE values)
4887 {
4888  long j;
4889  if (rest > 0) {
4890  for (; index < n; ++index) {
4891  p[r-rest] = index;
4892  rcombinate0(n, r, p, index, rest-1, values);
4893  }
4894  }
4895  else {
4896  VALUE result = rb_ary_new2(r);
4897  VALUE *result_array = RARRAY_PTR(result);
4898  const VALUE *values_array = RARRAY_PTR(values);
4899 
4900  for (j = 0; j < r; ++j) result_array[j] = values_array[p[j]];
4901  ARY_SET_LEN(result, r);
4902  rb_yield(result);
4903  if (RBASIC(values)->klass) {
4904  rb_raise(rb_eRuntimeError, "repeated combination reentered");
4905  }
4906  }
4907 }
4908 
4909 static VALUE
4911 {
4912  long n = RARRAY_LEN(ary);
4913  long k = NUM2LONG(RARRAY_PTR(args)[0]);
4914  if (k == 0) {
4915  return LONG2FIX(1);
4916  }
4917  return binomial_coefficient(k, n + k - 1);
4918 }
4919 
4920 /*
4921  * call-seq:
4922  * ary.repeated_combination(n) { |c| block } -> ary
4923  * ary.repeated_combination(n) -> Enumerator
4924  *
4925  * When invoked with a block, yields all repeated combinations of length +n+ of
4926  * elements from the array and then returns the array itself.
4927  *
4928  * The implementation makes no guarantees about the order in which the repeated
4929  * combinations are yielded.
4930  *
4931  * If no block is given, an Enumerator is returned instead.
4932  *
4933  * Examples:
4934  *
4935  * a = [1, 2, 3]
4936  * a.repeated_combination(1).to_a #=> [[1], [2], [3]]
4937  * a.repeated_combination(2).to_a #=> [[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]]
4938  * a.repeated_combination(3).to_a #=> [[1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3],
4939  * # [1,3,3],[2,2,2],[2,2,3],[2,3,3],[3,3,3]]
4940  * a.repeated_combination(4).to_a #=> [[1,1,1,1],[1,1,1,2],[1,1,1,3],[1,1,2,2],[1,1,2,3],
4941  * # [1,1,3,3],[1,2,2,2],[1,2,2,3],[1,2,3,3],[1,3,3,3],
4942  * # [2,2,2,2],[2,2,2,3],[2,2,3,3],[2,3,3,3],[3,3,3,3]]
4943  * a.repeated_combination(0).to_a #=> [[]] # one combination of length 0
4944  *
4945  */
4946 
4947 static VALUE
4949 {
4950  long n, i, len;
4951 
4952  n = NUM2LONG(num); /* Combination size from argument */
4953  RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_repeated_combination_size); /* Return enumerator if no block */
4954  len = RARRAY_LEN(ary);
4955  if (n < 0) {
4956  /* yield nothing */
4957  }
4958  else if (n == 0) {
4959  rb_yield(rb_ary_new2(0));
4960  }
4961  else if (n == 1) {
4962  for (i = 0; i < len; i++) {
4963  rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
4964  }
4965  }
4966  else if (len == 0) {
4967  /* yield nothing */
4968  }
4969  else {
4970  volatile VALUE t0 = tmpbuf(n, sizeof(long));
4971  long *p = (long*)RSTRING_PTR(t0);
4972  VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
4973  RBASIC(ary0)->klass = 0;
4974 
4975  rcombinate0(len, n, p, 0, n, ary0); /* compute and yield repeated combinations */
4976  tmpbuf_discard(t0);
4977  RBASIC(ary0)->klass = rb_cArray;
4978  }
4979  return ary;
4980 }
4981 
4982 /*
4983  * call-seq:
4984  * ary.product(other_ary, ...) -> new_ary
4985  * ary.product(other_ary, ...) { |p| block } -> ary
4986  *
4987  * Returns an array of all combinations of elements from all arrays.
4988  *
4989  * The length of the returned array is the product of the length of +self+ and
4990  * the argument arrays.
4991  *
4992  * If given a block, #product will yield all combinations and return +self+
4993  * instead.
4994  *
4995  * [1,2,3].product([4,5]) #=> [[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]
4996  * [1,2].product([1,2]) #=> [[1,1],[1,2],[2,1],[2,2]]
4997  * [1,2].product([3,4],[5,6]) #=> [[1,3,5],[1,3,6],[1,4,5],[1,4,6],
4998  * # [2,3,5],[2,3,6],[2,4,5],[2,4,6]]
4999  * [1,2].product() #=> [[1],[2]]
5000  * [1,2].product([]) #=> []
5001  */
5002 
5003 static VALUE
5004 rb_ary_product(int argc, VALUE *argv, VALUE ary)
5005 {
5006  int n = argc+1; /* How many arrays we're operating on */
5007  volatile VALUE t0 = tmpary(n);
5008  volatile VALUE t1 = tmpbuf(n, sizeof(int));
5009  VALUE *arrays = RARRAY_PTR(t0); /* The arrays we're computing the product of */
5010  int *counters = (int*)RSTRING_PTR(t1); /* The current position in each one */
5011  VALUE result = Qnil; /* The array we'll be returning, when no block given */
5012  long i,j;
5013  long resultlen = 1;
5014 
5015  RBASIC(t0)->klass = 0;
5016  RBASIC(t1)->klass = 0;
5017 
5018  /* initialize the arrays of arrays */
5019  ARY_SET_LEN(t0, n);
5020  arrays[0] = ary;
5021  for (i = 1; i < n; i++) arrays[i] = Qnil;
5022  for (i = 1; i < n; i++) arrays[i] = to_ary(argv[i-1]);
5023 
5024  /* initialize the counters for the arrays */
5025  for (i = 0; i < n; i++) counters[i] = 0;
5026 
5027  /* Otherwise, allocate and fill in an array of results */
5028  if (rb_block_given_p()) {
5029  /* Make defensive copies of arrays; exit if any is empty */
5030  for (i = 0; i < n; i++) {
5031  if (RARRAY_LEN(arrays[i]) == 0) goto done;
5032  arrays[i] = ary_make_shared_copy(arrays[i]);
5033  }
5034  }
5035  else {
5036  /* Compute the length of the result array; return [] if any is empty */
5037  for (i = 0; i < n; i++) {
5038  long k = RARRAY_LEN(arrays[i]);
5039  if (k == 0) {
5040  result = rb_ary_new2(0);
5041  goto done;
5042  }
5043  if (MUL_OVERFLOW_LONG_P(resultlen, k))
5044  rb_raise(rb_eRangeError, "too big to product");
5045  resultlen *= k;
5046  }
5047  result = rb_ary_new2(resultlen);
5048  }
5049  for (;;) {
5050  int m;
5051  /* fill in one subarray */
5052  VALUE subarray = rb_ary_new2(n);
5053  for (j = 0; j < n; j++) {
5054  rb_ary_push(subarray, rb_ary_entry(arrays[j], counters[j]));
5055  }
5056 
5057  /* put it on the result array */
5058  if (NIL_P(result)) {
5059  FL_SET(t0, FL_USER5);
5060  rb_yield(subarray);
5061  if (! FL_TEST(t0, FL_USER5)) {
5062  rb_raise(rb_eRuntimeError, "product reentered");
5063  }
5064  else {
5065  FL_UNSET(t0, FL_USER5);
5066  }
5067  }
5068  else {
5069  rb_ary_push(result, subarray);
5070  }
5071 
5072  /*
5073  * Increment the last counter. If it overflows, reset to 0
5074  * and increment the one before it.
5075  */
5076  m = n-1;
5077  counters[m]++;
5078  while (counters[m] == RARRAY_LEN(arrays[m])) {
5079  counters[m] = 0;
5080  /* If the first counter overflows, we are done */
5081  if (--m < 0) goto done;
5082  counters[m]++;
5083  }
5084  }
5085 done:
5086  tmpary_discard(t0);
5087  tmpbuf_discard(t1);
5088 
5089  return NIL_P(result) ? ary : result;
5090 }
5091 
5092 /*
5093  * call-seq:
5094  * ary.take(n) -> new_ary
5095  *
5096  * Returns first +n+ elements from the array.
5097  *
5098  * If a negative number is given, raises an ArgumentError.
5099  *
5100  * See also Array#drop
5101  *
5102  * a = [1, 2, 3, 4, 5, 0]
5103  * a.take(3) #=> [1, 2, 3]
5104  *
5105  */
5106 
5107 static VALUE
5109 {
5110  long len = NUM2LONG(n);
5111  if (len < 0) {
5112  rb_raise(rb_eArgError, "attempt to take negative size");
5113  }
5114  return rb_ary_subseq(obj, 0, len);
5115 }
5116 
5117 /*
5118  * call-seq:
5119  * ary.take_while { |arr| block } -> new_ary
5120  * ary.take_while -> Enumerator
5121  *
5122  * Passes elements to the block until the block returns +nil+ or +false+, then
5123  * stops iterating and returns an array of all prior elements.
5124  *
5125  * If no block is given, an Enumerator is returned instead.
5126  *
5127  * See also Array#drop_while
5128  *
5129  * a = [1, 2, 3, 4, 5, 0]
5130  * a.take_while { |i| i < 3 } #=> [1, 2]
5131  *
5132  */
5133 
5134 static VALUE
5136 {
5137  long i;
5138 
5139  RETURN_ENUMERATOR(ary, 0, 0);
5140  for (i = 0; i < RARRAY_LEN(ary); i++) {
5141  if (!RTEST(rb_yield(RARRAY_PTR(ary)[i]))) break;
5142  }
5143  return rb_ary_take(ary, LONG2FIX(i));
5144 }
5145 
5146 /*
5147  * call-seq:
5148  * ary.drop(n) -> new_ary
5149  *
5150  * Drops first +n+ elements from +ary+ and returns the rest of the elements in
5151  * an array.
5152  *
5153  * If a negative number is given, raises an ArgumentError.
5154  *
5155  * See also Array#take
5156  *
5157  * a = [1, 2, 3, 4, 5, 0]
5158  * a.drop(3) #=> [4, 5, 0]
5159  *
5160  */
5161 
5162 static VALUE
5164 {
5165  VALUE result;
5166  long pos = NUM2LONG(n);
5167  if (pos < 0) {
5168  rb_raise(rb_eArgError, "attempt to drop negative size");
5169  }
5170 
5171  result = rb_ary_subseq(ary, pos, RARRAY_LEN(ary));
5172  if (result == Qnil) result = rb_ary_new();
5173  return result;
5174 }
5175 
5176 /*
5177  * call-seq:
5178  * ary.drop_while { |arr| block } -> new_ary
5179  * ary.drop_while -> Enumerator
5180  *
5181  * Drops elements up to, but not including, the first element for which the
5182  * block returns +nil+ or +false+ and returns an array containing the
5183  * remaining elements.
5184  *
5185  * If no block is given, an Enumerator is returned instead.
5186  *
5187  * See also Array#take_while
5188  *
5189  * a = [1, 2, 3, 4, 5, 0]
5190  * a.drop_while {|i| i < 3 } #=> [3, 4, 5, 0]
5191  *
5192  */
5193 
5194 static VALUE
5196 {
5197  long i;
5198 
5199  RETURN_ENUMERATOR(ary, 0, 0);
5200  for (i = 0; i < RARRAY_LEN(ary); i++) {
5201  if (!RTEST(rb_yield(RARRAY_PTR(ary)[i]))) break;
5202  }
5203  return rb_ary_drop(ary, LONG2FIX(i));
5204 }
5205 
5206 /*
5207  * Arrays are ordered, integer-indexed collections of any object.
5208  *
5209  * Array indexing starts at 0, as in C or Java. A negative index is assumed
5210  * to be relative to the end of the array---that is, an index of -1 indicates
5211  * the last element of the array, -2 is the next to last element in the
5212  * array, and so on.
5213  *
5214  * == Creating Arrays
5215  *
5216  * A new array can be created by using the literal constructor
5217  * <code>[]</code>. Arrays can contain different types of objects. For
5218  * example, the array below contains an Integer, a String and a Float:
5219  *
5220  * ary = [1, "two", 3.0] #=> [1, "two", 3.0]
5221  *
5222  * An array can also be created by explicitly calling Array.new with zero, one
5223  * (the initial size of the Array) or two arguments (the initial size and a
5224  * default object).
5225  *
5226  * ary = Array.new #=> []
5227  * Array.new(3) #=> [nil, nil, nil]
5228  * Array.new(3, true) #=> [true, true, true]
5229  *
5230  * Note that the second argument populates the array with references to the
5231  * same object. Therefore, it is only recommended in cases when you need to
5232  * instantiate arrays with natively immutable objects such as Symbols,
5233  * numbers, true or false.
5234  *
5235  * To create an array with separate objects a block can be passed instead.
5236  * This method is safe to use with mutable objects such as hashes, strings or
5237  * other arrays:
5238  *
5239  * Array.new(4) { Hash.new } #=> [{}, {}, {}, {}]
5240  *
5241  * This is also a quick way to build up multi-dimensional arrays:
5242  *
5243  * empty_table = Array.new(3) { Array.new(3) }
5244  * #=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
5245  *
5246  * An array can also be created by using the Array() method, provided by
5247  * Kernel, which tries to call #to_ary, then #to_a on its argument.
5248  *
5249  * Array({:a => "a", :b => "b"}) #=> [[:a, "a"], [:b, "b"]]
5250  *
5251  * == Example Usage
5252  *
5253  * In addition to the methods it mixes in through the Enumerable module, the
5254  * Array class has proprietary methods for accessing, searching and otherwise
5255  * manipulating arrays.
5256  *
5257  * Some of the more common ones are illustrated below.
5258  *
5259  * == Accessing Elements
5260  *
5261  * Elements in an array can be retrieved using the Array#[] method. It can
5262  * take a single integer argument (a numeric index), a pair of arguments
5263  * (start and length) or a range.
5264  *
5265  * arr = [1, 2, 3, 4, 5, 6]
5266  * arr[2] #=> 3
5267  * arr[100] #=> nil
5268  * arr[-3] #=> 4
5269  * arr[2, 3] #=> [3, 4, 5]
5270  * arr[1..4] #=> [2, 3, 4, 5]
5271  *
5272  * Another way to access a particular array element is by using the #at method
5273  *
5274  * arr.at(0) #=> 1
5275  *
5276  * The #slice method works in an identical manner to Array#[].
5277  *
5278  * To raise an error for indices outside of the array bounds or else to
5279  * provide a default value when that happens, you can use #fetch.
5280  *
5281  * arr = ['a', 'b', 'c', 'd', 'e', 'f']
5282  * arr.fetch(100) #=> IndexError: index 100 outside of array bounds: -6...6
5283  * arr.fetch(100, "oops") #=> "oops"
5284  *
5285  * The special methods #first and #last will return the first and last
5286  * elements of an array, respectively.
5287  *
5288  * arr.first #=> 1
5289  * arr.last #=> 6
5290  *
5291  * To return the first +n+ elements of an array, use #take
5292  *
5293  * arr.take(3) #=> [1, 2, 3]
5294  *
5295  * #drop does the opposite of #take, by returning the elements after +n+
5296  * elements have been dropped:
5297  *
5298  * arr.drop(3) #=> [4, 5, 6]
5299  *
5300  * == Obtaining Information about an Array
5301  *
5302  * Arrays keep track of their own length at all times. To query an array
5303  * about the number of elements it contains, use #length, #count or #size.
5304  *
5305  * browsers = ['Chrome', 'Firefox', 'Safari', 'Opera', 'IE']
5306  * browsers.length #=> 5
5307  * browsers.count #=> 5
5308  *
5309  * To check whether an array contains any elements at all
5310  *
5311  * browsers.empty? #=> false
5312  *
5313  * To check whether a particular item is included in the array
5314  *
5315  * browsers.include?('Konqueror') #=> false
5316  *
5317  * == Adding Items to Arrays
5318  *
5319  * Items can be added to the end of an array by using either #push or #<<
5320  *
5321  * arr = [1, 2, 3, 4]
5322  * arr.push(5) #=> [1, 2, 3, 4, 5]
5323  * arr << 6 #=> [1, 2, 3, 4, 5, 6]
5324  *
5325  * #unshift will add a new item to the beginning of an array.
5326  *
5327  * arr.unshift(0) #=> [0, 1, 2, 3, 4, 5, 6]
5328  *
5329  * With #insert you can add a new element to an array at any position.
5330  *
5331  * arr.insert(3, 'apple') #=> [0, 1, 2, 'apple', 3, 4, 5, 6]
5332  *
5333  * Using the #insert method, you can also insert multiple values at once:
5334  *
5335  * arr.insert(3, 'orange', 'pear', 'grapefruit')
5336  * #=> [0, 1, 2, "orange", "pear", "grapefruit", "apple", 3, 4, 5, 6]
5337  *
5338  * == Removing Items from an Array
5339  *
5340  * The method #pop removes the last element in an array and returns it:
5341  *
5342  * arr = [1, 2, 3, 4, 5, 6]
5343  * arr.pop #=> 6
5344  * arr #=> [1, 2, 3, 4, 5]
5345  *
5346  * To retrieve and at the same time remove the first item, use #shift:
5347  *
5348  * arr.shift #=> 1
5349  * arr #=> [2, 3, 4, 5]
5350  *
5351  * To delete an element at a particular index:
5352  *
5353  * arr.delete_at(2) #=> 4
5354  * arr #=> [2, 3, 5]
5355  *
5356  * To delete a particular element anywhere in an array, use #delete:
5357  *
5358  * arr = [1, 2, 2, 3]
5359  * arr.delete(2) #=> [1, 3]
5360  *
5361  * A useful method if you need to remove +nil+ values from an array is
5362  * #compact:
5363  *
5364  * arr = ['foo', 0, nil, 'bar', 7, 'baz', nil]
5365  * arr.compact #=> ['foo', 0, 'bar', 7, 'baz']
5366  * arr #=> ['foo', 0, nil, 'bar', 7, 'baz', nil]
5367  * arr.compact! #=> ['foo', 0, 'bar', 7, 'baz']
5368  * arr #=> ['foo', 0, 'bar', 7, 'baz']
5369  *
5370  * Another common need is to remove duplicate elements from an array.
5371  *
5372  * It has the non-destructive #uniq, and destructive method #uniq!
5373  *
5374  * arr = [2, 5, 6, 556, 6, 6, 8, 9, 0, 123, 556]
5375  * arr.uniq #=> [2, 5, 6, 556, 8, 9, 0, 123]
5376  *
5377  * == Iterating over Arrays
5378  *
5379  * Like all classes that include the Enumerable module, Array has an each
5380  * method, which defines what elements should be iterated over and how. In
5381  * case of Array's #each, all elements in the Array instance are yielded to
5382  * the supplied block in sequence.
5383  *
5384  * Note that this operation leaves the array unchanged.
5385  *
5386  * arr = [1, 2, 3, 4, 5]
5387  * arr.each { |a| print a -= 10, " " }
5388  * # prints: -9 -8 -7 -6 -5
5389  * #=> [1, 2, 3, 4, 5]
5390  *
5391  * Another sometimes useful iterator is #reverse_each which will iterate over
5392  * the elements in the array in reverse order.
5393  *
5394  * words = %w[rats live on no evil star]
5395  * str = ""
5396  * words.reverse_each { |word| str += "#{word.reverse} " }
5397  * str #=> "rats live on no evil star "
5398  *
5399  * The #map method can be used to create a new array based on the original
5400  * array, but with the values modified by the supplied block:
5401  *
5402  * arr.map { |a| 2*a } #=> [2, 4, 6, 8, 10]
5403  * arr #=> [1, 2, 3, 4, 5]
5404  * arr.map! { |a| a**2 } #=> [1, 4, 9, 16, 25]
5405  * arr #=> [1, 4, 9, 16, 25]
5406  *
5407  * == Selecting Items from an Array
5408  *
5409  * Elements can be selected from an array according to criteria defined in a
5410  * block. The selection can happen in a destructive or a non-destructive
5411  * manner. While the destructive operations will modify the array they were
5412  * called on, the non-destructive methods usually return a new array with the
5413  * selected elements, but leave the original array unchanged.
5414  *
5415  * === Non-destructive Selection
5416  *
5417  * arr = [1, 2, 3, 4, 5, 6]
5418  * arr.select { |a| a > 3 } #=> [4, 5, 6]
5419  * arr.reject { |a| a < 3 } #=> [4, 5, 6]
5420  * arr.drop_while { |a| a < 4 } #=> [4, 5, 6]
5421  * arr #=> [1, 2, 3, 4, 5, 6]
5422  *
5423  * === Destructive Selection
5424  *
5425  * #select! and #reject! are the corresponding destructive methods to #select
5426  * and #reject
5427  *
5428  * Similar to #select vs. #reject, #delete_if and #keep_if have the exact
5429  * opposite result when supplied with the same block:
5430  *
5431  * arr.delete_if { |a| a < 4 } #=> [4, 5, 6]
5432  * arr #=> [4, 5, 6]
5433  *
5434  * arr = [1, 2, 3, 4, 5, 6]
5435  * arr.keep_if { |a| a < 4 } #=> [1, 2, 3]
5436  * arr #=> [1, 2, 3]
5437  *
5438  */
5439 
5440 void
5442 {
5443 #undef rb_intern
5444 #define rb_intern(str) rb_intern_const(str)
5445 
5446  rb_cArray = rb_define_class("Array", rb_cObject);
5448 
5452  rb_define_method(rb_cArray, "initialize", rb_ary_initialize, -1);
5453  rb_define_method(rb_cArray, "initialize_copy", rb_ary_replace, 1);
5454 
5455  rb_define_method(rb_cArray, "inspect", rb_ary_inspect, 0);
5456  rb_define_alias(rb_cArray, "to_s", "inspect");
5457  rb_define_method(rb_cArray, "to_a", rb_ary_to_a, 0);
5459  rb_define_method(rb_cArray, "frozen?", rb_ary_frozen_p, 0);
5460 
5462  rb_define_method(rb_cArray, "eql?", rb_ary_eql, 1);
5463  rb_define_method(rb_cArray, "hash", rb_ary_hash, 0);
5464 
5466  rb_define_method(rb_cArray, "[]=", rb_ary_aset, -1);
5468  rb_define_method(rb_cArray, "fetch", rb_ary_fetch, -1);
5469  rb_define_method(rb_cArray, "first", rb_ary_first, -1);
5470  rb_define_method(rb_cArray, "last", rb_ary_last, -1);
5471  rb_define_method(rb_cArray, "concat", rb_ary_concat, 1);
5475  rb_define_method(rb_cArray, "shift", rb_ary_shift_m, -1);
5476  rb_define_method(rb_cArray, "unshift", rb_ary_unshift_m, -1);
5477  rb_define_method(rb_cArray, "insert", rb_ary_insert, -1);
5478  rb_define_method(rb_cArray, "each", rb_ary_each, 0);
5479  rb_define_method(rb_cArray, "each_index", rb_ary_each_index, 0);
5480  rb_define_method(rb_cArray, "reverse_each", rb_ary_reverse_each, 0);
5481  rb_define_method(rb_cArray, "length", rb_ary_length, 0);
5482  rb_define_alias(rb_cArray, "size", "length");
5483  rb_define_method(rb_cArray, "empty?", rb_ary_empty_p, 0);
5484  rb_define_method(rb_cArray, "find_index", rb_ary_index, -1);
5485  rb_define_method(rb_cArray, "index", rb_ary_index, -1);
5486  rb_define_method(rb_cArray, "rindex", rb_ary_rindex, -1);
5490  rb_define_method(rb_cArray, "rotate", rb_ary_rotate_m, -1);
5492  rb_define_method(rb_cArray, "sort", rb_ary_sort, 0);
5495  rb_define_method(rb_cArray, "collect", rb_ary_collect, 0);
5499  rb_define_method(rb_cArray, "select", rb_ary_select, 0);
5501  rb_define_method(rb_cArray, "keep_if", rb_ary_keep_if, 0);
5502  rb_define_method(rb_cArray, "values_at", rb_ary_values_at, -1);
5503  rb_define_method(rb_cArray, "delete", rb_ary_delete, 1);
5504  rb_define_method(rb_cArray, "delete_at", rb_ary_delete_at_m, 1);
5505  rb_define_method(rb_cArray, "delete_if", rb_ary_delete_if, 0);
5506  rb_define_method(rb_cArray, "reject", rb_ary_reject, 0);
5508  rb_define_method(rb_cArray, "zip", rb_ary_zip, -1);
5509  rb_define_method(rb_cArray, "transpose", rb_ary_transpose, 0);
5510  rb_define_method(rb_cArray, "replace", rb_ary_replace, 1);
5511  rb_define_method(rb_cArray, "clear", rb_ary_clear, 0);
5512  rb_define_method(rb_cArray, "fill", rb_ary_fill, -1);
5513  rb_define_method(rb_cArray, "include?", rb_ary_includes, 1);
5515 
5516  rb_define_method(rb_cArray, "slice", rb_ary_aref, -1);
5518 
5519  rb_define_method(rb_cArray, "assoc", rb_ary_assoc, 1);
5520  rb_define_method(rb_cArray, "rassoc", rb_ary_rassoc, 1);
5521 
5524 
5528 
5529  rb_define_method(rb_cArray, "uniq", rb_ary_uniq, 0);
5531  rb_define_method(rb_cArray, "compact", rb_ary_compact, 0);
5533  rb_define_method(rb_cArray, "flatten", rb_ary_flatten, -1);
5535  rb_define_method(rb_cArray, "count", rb_ary_count, -1);
5537  rb_define_method(rb_cArray, "shuffle", rb_ary_shuffle, -1);
5538  rb_define_method(rb_cArray, "sample", rb_ary_sample, -1);
5539  rb_define_method(rb_cArray, "cycle", rb_ary_cycle, -1);
5540  rb_define_method(rb_cArray, "permutation", rb_ary_permutation, -1);
5541  rb_define_method(rb_cArray, "combination", rb_ary_combination, 1);
5542  rb_define_method(rb_cArray, "repeated_permutation", rb_ary_repeated_permutation, 1);
5543  rb_define_method(rb_cArray, "repeated_combination", rb_ary_repeated_combination, 1);
5544  rb_define_method(rb_cArray, "product", rb_ary_product, -1);
5545 
5546  rb_define_method(rb_cArray, "take", rb_ary_take, 1);
5547  rb_define_method(rb_cArray, "take_while", rb_ary_take_while, 0);
5548  rb_define_method(rb_cArray, "drop", rb_ary_drop, 1);
5549  rb_define_method(rb_cArray, "drop_while", rb_ary_drop_while, 0);
5550  rb_define_method(rb_cArray, "bsearch", rb_ary_bsearch, 0);
5551 
5552  id_cmp = rb_intern("<=>");
5553  sym_random = ID2SYM(rb_intern("random"));
5554  id_div = rb_intern("div");
5555  id_power = rb_intern("**");
5556 }
5557