Ruby  1.9.3p392(2013-02-22revision39386)
array.c
Go to the documentation of this file.
1 /**********************************************************************
2 
3  array.c -
4 
5  $Author: marcandre $
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 
20 #ifndef ARRAY_DEBUG
21 # define NDEBUG
22 #endif
23 #include <assert.h>
24 
25 #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
26 
28 
29 static ID id_cmp;
30 
31 #define ARY_DEFAULT_SIZE 16
32 #define ARY_MAX_SIZE (LONG_MAX / (int)sizeof(VALUE))
33 
34 void
35 rb_mem_clear(register VALUE *mem, register long size)
36 {
37  while (size--) {
38  *mem++ = Qnil;
39  }
40 }
41 
42 static inline void
43 memfill(register VALUE *mem, register long size, register VALUE val)
44 {
45  while (size--) {
46  *mem++ = val;
47  }
48 }
49 
50 # define ARY_SHARED_P(ary) \
51  (assert(!FL_TEST((ary), ELTS_SHARED) || !FL_TEST((ary), RARRAY_EMBED_FLAG)), \
52  FL_TEST((ary),ELTS_SHARED)!=0)
53 # define ARY_EMBED_P(ary) \
54  (assert(!FL_TEST((ary), ELTS_SHARED) || !FL_TEST((ary), RARRAY_EMBED_FLAG)), \
55  FL_TEST((ary), RARRAY_EMBED_FLAG)!=0)
56 
57 #define ARY_HEAP_PTR(a) (assert(!ARY_EMBED_P(a)), RARRAY(a)->as.heap.ptr)
58 #define ARY_HEAP_LEN(a) (assert(!ARY_EMBED_P(a)), RARRAY(a)->as.heap.len)
59 #define ARY_EMBED_PTR(a) (assert(ARY_EMBED_P(a)), RARRAY(a)->as.ary)
60 #define ARY_EMBED_LEN(a) \
61  (assert(ARY_EMBED_P(a)), \
62  (long)((RBASIC(a)->flags >> RARRAY_EMBED_LEN_SHIFT) & \
63  (RARRAY_EMBED_LEN_MASK >> RARRAY_EMBED_LEN_SHIFT)))
64 
65 #define ARY_OWNS_HEAP_P(a) (!FL_TEST((a), ELTS_SHARED|RARRAY_EMBED_FLAG))
66 #define FL_SET_EMBED(a) do { \
67  assert(!ARY_SHARED_P(a)); \
68  assert(!OBJ_FROZEN(a)); \
69  FL_SET((a), RARRAY_EMBED_FLAG); \
70 } while (0)
71 #define FL_UNSET_EMBED(ary) FL_UNSET((ary), RARRAY_EMBED_FLAG|RARRAY_EMBED_LEN_MASK)
72 #define FL_SET_SHARED(ary) do { \
73  assert(!ARY_EMBED_P(ary)); \
74  FL_SET((ary), ELTS_SHARED); \
75 } while (0)
76 #define FL_UNSET_SHARED(ary) FL_UNSET((ary), ELTS_SHARED)
77 
78 #define ARY_SET_PTR(ary, p) do { \
79  assert(!ARY_EMBED_P(ary)); \
80  assert(!OBJ_FROZEN(ary)); \
81  RARRAY(ary)->as.heap.ptr = (p); \
82 } while (0)
83 #define ARY_SET_EMBED_LEN(ary, n) do { \
84  long tmp_n = (n); \
85  assert(ARY_EMBED_P(ary)); \
86  assert(!OBJ_FROZEN(ary)); \
87  RBASIC(ary)->flags &= ~RARRAY_EMBED_LEN_MASK; \
88  RBASIC(ary)->flags |= (tmp_n) << RARRAY_EMBED_LEN_SHIFT; \
89 } while (0)
90 #define ARY_SET_HEAP_LEN(ary, n) do { \
91  assert(!ARY_EMBED_P(ary)); \
92  RARRAY(ary)->as.heap.len = (n); \
93 } while (0)
94 #define ARY_SET_LEN(ary, n) do { \
95  if (ARY_EMBED_P(ary)) { \
96  ARY_SET_EMBED_LEN((ary), (n)); \
97  } \
98  else { \
99  ARY_SET_HEAP_LEN((ary), (n)); \
100  } \
101  assert(RARRAY_LEN(ary) == (n)); \
102 } while (0)
103 #define ARY_INCREASE_PTR(ary, n) do { \
104  assert(!ARY_EMBED_P(ary)); \
105  assert(!OBJ_FROZEN(ary)); \
106  RARRAY(ary)->as.heap.ptr += (n); \
107 } while (0)
108 #define ARY_INCREASE_LEN(ary, n) do { \
109  assert(!OBJ_FROZEN(ary)); \
110  if (ARY_EMBED_P(ary)) { \
111  ARY_SET_EMBED_LEN((ary), RARRAY_LEN(ary)+(n)); \
112  } \
113  else { \
114  RARRAY(ary)->as.heap.len += (n); \
115  } \
116 } while (0)
117 
118 #define ARY_CAPA(ary) (ARY_EMBED_P(ary) ? RARRAY_EMBED_LEN_MAX : \
119  ARY_SHARED_ROOT_P(ary) ? RARRAY_LEN(ary) : RARRAY(ary)->as.heap.aux.capa)
120 #define ARY_SET_CAPA(ary, n) do { \
121  assert(!ARY_EMBED_P(ary)); \
122  assert(!ARY_SHARED_P(ary)); \
123  assert(!OBJ_FROZEN(ary)); \
124  RARRAY(ary)->as.heap.aux.capa = (n); \
125 } while (0)
126 
127 #define ARY_SHARED(ary) (assert(ARY_SHARED_P(ary)), RARRAY(ary)->as.heap.aux.shared)
128 #define ARY_SET_SHARED(ary, value) do { \
129  assert(!ARY_EMBED_P(ary)); \
130  assert(ARY_SHARED_P(ary)); \
131  assert(ARY_SHARED_ROOT_P(value)); \
132  RARRAY(ary)->as.heap.aux.shared = (value); \
133 } while (0)
134 #define RARRAY_SHARED_ROOT_FLAG FL_USER5
135 #define ARY_SHARED_ROOT_P(ary) (FL_TEST((ary), RARRAY_SHARED_ROOT_FLAG))
136 #define ARY_SHARED_NUM(ary) \
137  (assert(ARY_SHARED_ROOT_P(ary)), RARRAY(ary)->as.heap.aux.capa)
138 #define ARY_SET_SHARED_NUM(ary, value) do { \
139  assert(ARY_SHARED_ROOT_P(ary)); \
140  RARRAY(ary)->as.heap.aux.capa = (value); \
141 } while (0)
142 #define FL_SET_SHARED_ROOT(ary) do { \
143  assert(!ARY_EMBED_P(ary)); \
144  FL_SET((ary), RARRAY_SHARED_ROOT_FLAG); \
145 } while (0)
146 
147 static void
148 ary_resize_capa(VALUE ary, long capacity)
149 {
150  assert(RARRAY_LEN(ary) <= capacity);
151  assert(!OBJ_FROZEN(ary));
152  assert(!ARY_SHARED_P(ary));
153  if (capacity > RARRAY_EMBED_LEN_MAX) {
154  if (ARY_EMBED_P(ary)) {
155  long len = ARY_EMBED_LEN(ary);
156  VALUE *ptr = ALLOC_N(VALUE, (capacity));
157  MEMCPY(ptr, ARY_EMBED_PTR(ary), VALUE, len);
158  FL_UNSET_EMBED(ary);
159  ARY_SET_PTR(ary, ptr);
160  ARY_SET_HEAP_LEN(ary, len);
161  }
162  else {
163  REALLOC_N(RARRAY(ary)->as.heap.ptr, VALUE, (capacity));
164  }
165  ARY_SET_CAPA(ary, (capacity));
166  }
167  else {
168  if (!ARY_EMBED_P(ary)) {
169  long len = RARRAY_LEN(ary);
170  VALUE *ptr = RARRAY_PTR(ary);
171  if (len > capacity) len = capacity;
172  MEMCPY(RARRAY(ary)->as.ary, ptr, VALUE, len);
173  FL_SET_EMBED(ary);
174  ARY_SET_LEN(ary, len);
175  xfree(ptr);
176  }
177  }
178 }
179 
180 static void
182 {
183  long new_capa = ARY_CAPA(ary) / 2;
184 
185  if (new_capa < ARY_DEFAULT_SIZE) {
186  new_capa = ARY_DEFAULT_SIZE;
187  }
188  if (new_capa >= ARY_MAX_SIZE - min) {
189  new_capa = (ARY_MAX_SIZE - min) / 2;
190  }
191  new_capa += min;
192  ary_resize_capa(ary, new_capa);
193 }
194 
195 static void
197 {
198  if (shared) {
199  long num = ARY_SHARED_NUM(shared) - 1;
200  if (num == 0) {
201  rb_ary_free(shared);
202  rb_gc_force_recycle(shared);
203  }
204  else if (num > 0) {
205  ARY_SET_SHARED_NUM(shared, num);
206  }
207  }
208 }
209 
210 static void
212 {
213  VALUE shared = RARRAY(ary)->as.heap.aux.shared;
214  rb_ary_decrement_share(shared);
215  FL_UNSET_SHARED(ary);
216 }
217 
218 static inline void
220 {
221  if (ARY_SHARED_P(ary) && !ARY_EMBED_P(ary)) {
222  rb_ary_unshare(ary);
223  }
224 }
225 
226 static VALUE
228 {
229  long num = ARY_SHARED_NUM(shared);
230  if (num >= 0) {
231  ARY_SET_SHARED_NUM(shared, num + 1);
232  }
233  return shared;
234 }
235 
236 static void
238 {
239  rb_ary_increment_share(shared);
240  FL_SET_SHARED(ary);
241  ARY_SET_SHARED(ary, shared);
242 }
243 
244 static inline void
246 {
247  rb_check_frozen(ary);
248  if (!OBJ_UNTRUSTED(ary) && rb_safe_level() >= 4)
249  rb_raise(rb_eSecurityError, "Insecure: can't modify array");
250 }
251 
252 void
254 {
255  rb_ary_modify_check(ary);
256  if (ARY_SHARED_P(ary)) {
257  long len = RARRAY_LEN(ary);
258  if (len <= RARRAY_EMBED_LEN_MAX) {
259  VALUE *ptr = ARY_HEAP_PTR(ary);
260  VALUE shared = ARY_SHARED(ary);
261  FL_UNSET_SHARED(ary);
262  FL_SET_EMBED(ary);
263  MEMCPY(ARY_EMBED_PTR(ary), ptr, VALUE, len);
264  rb_ary_decrement_share(shared);
265  ARY_SET_EMBED_LEN(ary, len);
266  }
267  else {
268  VALUE *ptr = ALLOC_N(VALUE, len);
269  MEMCPY(ptr, RARRAY_PTR(ary), VALUE, len);
270  rb_ary_unshare(ary);
271  ARY_SET_CAPA(ary, len);
272  ARY_SET_PTR(ary, ptr);
273  }
274  }
275 }
276 
277 VALUE
279 {
280  return rb_obj_freeze(ary);
281 }
282 
283 /*
284  * call-seq:
285  * ary.frozen? -> true or false
286  *
287  * Return <code>true</code> if this array is frozen (or temporarily frozen
288  * while being sorted).
289  */
290 
291 static VALUE
293 {
294  if (OBJ_FROZEN(ary)) return Qtrue;
295  return Qfalse;
296 }
297 
298 static VALUE
300 {
301  NEWOBJ(ary, struct RArray);
302  OBJSETUP(ary, klass, T_ARRAY);
303  FL_SET_EMBED((VALUE)ary);
304  ARY_SET_EMBED_LEN((VALUE)ary, 0);
305 
306  return (VALUE)ary;
307 }
308 
309 static VALUE
310 ary_new(VALUE klass, long capa)
311 {
312  VALUE ary;
313 
314  if (capa < 0) {
315  rb_raise(rb_eArgError, "negative array size (or size too big)");
316  }
317  if (capa > ARY_MAX_SIZE) {
318  rb_raise(rb_eArgError, "array size too big");
319  }
320  ary = ary_alloc(klass);
321  if (capa > RARRAY_EMBED_LEN_MAX) {
322  FL_UNSET_EMBED(ary);
323  ARY_SET_PTR(ary, ALLOC_N(VALUE, capa));
324  ARY_SET_CAPA(ary, capa);
325  ARY_SET_HEAP_LEN(ary, 0);
326  }
327 
328  return ary;
329 }
330 
331 VALUE
332 rb_ary_new2(long capa)
333 {
334  return ary_new(rb_cArray, capa);
335 }
336 
337 
338 VALUE
340 {
342 }
343 
344 #include <stdarg.h>
345 
346 VALUE
347 rb_ary_new3(long n, ...)
348 {
349  va_list ar;
350  VALUE ary;
351  long i;
352 
353  ary = rb_ary_new2(n);
354 
355  va_start(ar, n);
356  for (i=0; i<n; i++) {
357  RARRAY_PTR(ary)[i] = va_arg(ar, VALUE);
358  }
359  va_end(ar);
360 
361  ARY_SET_LEN(ary, n);
362  return ary;
363 }
364 
365 VALUE
366 rb_ary_new4(long n, const VALUE *elts)
367 {
368  VALUE ary;
369 
370  ary = rb_ary_new2(n);
371  if (n > 0 && elts) {
372  MEMCPY(RARRAY_PTR(ary), elts, VALUE, n);
373  ARY_SET_LEN(ary, n);
374  }
375 
376  return ary;
377 }
378 
379 VALUE
380 rb_ary_tmp_new(long capa)
381 {
382  return ary_new(0, capa);
383 }
384 
385 void
387 {
388  if (ARY_OWNS_HEAP_P(ary)) {
389  xfree(ARY_HEAP_PTR(ary));
390  }
391 }
392 
393 RUBY_FUNC_EXPORTED size_t
395 {
396  if (ARY_OWNS_HEAP_P(ary)) {
397  return RARRAY(ary)->as.heap.aux.capa * sizeof(VALUE);
398  }
399  else {
400  return 0;
401  }
402 }
403 
404 static inline void
406 {
407  rb_ary_free(ary);
408  RBASIC(ary)->flags |= RARRAY_EMBED_FLAG;
409  RBASIC(ary)->flags &= ~RARRAY_EMBED_LEN_MASK;
410 }
411 
412 static VALUE
414 {
415  assert(!ARY_EMBED_P(ary));
416  if (ARY_SHARED_P(ary)) {
417  return ARY_SHARED(ary);
418  }
419  else if (ARY_SHARED_ROOT_P(ary)) {
420  return ary;
421  }
422  else if (OBJ_FROZEN(ary)) {
423  ary_resize_capa(ary, ARY_HEAP_LEN(ary));
424  FL_SET_SHARED_ROOT(ary);
425  ARY_SET_SHARED_NUM(ary, 1);
426  return ary;
427  }
428  else {
429  NEWOBJ(shared, struct RArray);
430  OBJSETUP(shared, 0, T_ARRAY);
431  FL_UNSET_EMBED(shared);
432 
433  ARY_SET_LEN((VALUE)shared, RARRAY_LEN(ary));
434  ARY_SET_PTR((VALUE)shared, RARRAY_PTR(ary));
435  FL_SET_SHARED_ROOT(shared);
436  ARY_SET_SHARED_NUM((VALUE)shared, 1);
437  FL_SET_SHARED(ary);
438  ARY_SET_SHARED(ary, (VALUE)shared);
439  OBJ_FREEZE(shared);
440  return (VALUE)shared;
441  }
442 }
443 
444 
445 static VALUE
447 {
448  if (RARRAY_LEN(ary) <= RARRAY_EMBED_LEN_MAX) {
449  VALUE subst = rb_ary_new2(RARRAY_LEN(ary));
450  MEMCPY(ARY_EMBED_PTR(subst), RARRAY_PTR(ary), VALUE, RARRAY_LEN(ary));
451  ARY_SET_EMBED_LEN(subst, RARRAY_LEN(ary));
452  return subst;
453  }
454  else {
456  }
457 }
458 
459 VALUE
461 {
462  return rb_ary_new3(2, car, cdr);
463 }
464 
465 static VALUE
467 {
468  return rb_convert_type(ary, T_ARRAY, "Array", "to_ary");
469 }
470 
471 VALUE
473 {
474  return rb_check_convert_type(ary, T_ARRAY, "Array", "to_ary");
475 }
476 
477 /*
478  * call-seq:
479  * Array.try_convert(obj) -> array or nil
480  *
481  * Tries to convert +obj+ into an array, using +to_ary+ method. Returns the
482  * converted array or +nil+ if +obj+ cannot be converted for any reason.
483  * This method can be used to check if an argument is an array.
484  *
485  * Array.try_convert([1]) #=> [1]
486  * Array.try_convert("1") #=> nil
487  *
488  * if tmp = Array.try_convert(arg)
489  * # the argument is an array
490  * elsif tmp = String.try_convert(arg)
491  * # the argument is a string
492  * end
493  *
494  */
495 
496 static VALUE
498 {
499  return rb_check_array_type(ary);
500 }
501 
502 /*
503  * call-seq:
504  * Array.new(size=0, obj=nil)
505  * Array.new(array)
506  * Array.new(size) {|index| block }
507  *
508  * Returns a new array.
509  *
510  * In the first form, if no arguments are sent, the new array will be empty.
511  * When a +size+ and an optional +obj+ are sent, an array is created with
512  * +size+ copies of +obj+. Take notice that all elements will reference the
513  * same object +obj+.
514  *
515  * The second form creates a copy of the array passed as a parameter (the
516  * array is generated by calling to_ary on the parameter).
517  *
518  * first_array = ["Matz", "Guido"]
519  *
520  * second_array = Array.new(first_array) #=> ["Matz", "Guido"]
521  *
522  * first_array.equal? second_array #=> false
523  *
524  * In the last form, an array of the given size is created. Each element in
525  * this array is created by passing the element's index to the given block
526  * and storing the return value.
527  *
528  * Array.new(3){ |index| index ** 2 }
529  * # => [0, 1, 4]
530  *
531  * == Common gotchas
532  *
533  * When sending the second parameter, the same object will be used as the
534  * value for all the array elements:
535  *
536  * a = Array.new(2, Hash.new)
537  * # => [{}, {}]
538  *
539  * a[0]['cat'] = 'feline'
540  * a # => [{"cat"=>"feline"}, {"cat"=>"feline"}]
541  *
542  * a[1]['cat'] = 'Felix'
543  * a # => [{"cat"=>"Felix"}, {"cat"=>"Felix"}]
544  *
545  * Since all the Array elements store the same hash, changes to one of them
546  * will affect them all.
547  *
548  * If multiple copies are what you want, you should use the block
549  * version which uses the result of that block each time an element
550  * of the array needs to be initialized:
551  *
552  * a = Array.new(2) { Hash.new }
553  * a[0]['cat'] = 'feline'
554  * a # => [{"cat"=>"feline"}, {}]
555  *
556  */
557 
558 static VALUE
560 {
561  long len;
562  VALUE size, val;
563 
564  rb_ary_modify(ary);
565  if (argc == 0) {
566  if (ARY_OWNS_HEAP_P(ary) && RARRAY_PTR(ary)) {
567  xfree(RARRAY_PTR(ary));
568  }
569  rb_ary_unshare_safe(ary);
570  FL_SET_EMBED(ary);
571  ARY_SET_EMBED_LEN(ary, 0);
572  if (rb_block_given_p()) {
573  rb_warning("given block not used");
574  }
575  return ary;
576  }
577  rb_scan_args(argc, argv, "02", &size, &val);
578  if (argc == 1 && !FIXNUM_P(size)) {
579  val = rb_check_array_type(size);
580  if (!NIL_P(val)) {
581  rb_ary_replace(ary, val);
582  return ary;
583  }
584  }
585 
586  len = NUM2LONG(size);
587  if (len < 0) {
588  rb_raise(rb_eArgError, "negative array size");
589  }
590  if (len > ARY_MAX_SIZE) {
591  rb_raise(rb_eArgError, "array size too big");
592  }
593  rb_ary_modify(ary);
594  ary_resize_capa(ary, len);
595  if (rb_block_given_p()) {
596  long i;
597 
598  if (argc == 2) {
599  rb_warn("block supersedes default value argument");
600  }
601  for (i=0; i<len; i++) {
602  rb_ary_store(ary, i, rb_yield(LONG2NUM(i)));
603  ARY_SET_LEN(ary, i + 1);
604  }
605  }
606  else {
607  memfill(RARRAY_PTR(ary), len, val);
608  ARY_SET_LEN(ary, len);
609  }
610  return ary;
611 }
612 
613 
614 /*
615 * Returns a new array populated with the given objects.
616 *
617 * Array.[]( 1, 'a', /^A/ )
618 * Array[ 1, 'a', /^A/ ]
619 * [ 1, 'a', /^A/ ]
620 */
621 
622 static VALUE
624 {
625  VALUE ary = ary_new(klass, argc);
626  if (argc > 0 && argv) {
627  MEMCPY(RARRAY_PTR(ary), argv, VALUE, argc);
628  ARY_SET_LEN(ary, argc);
629  }
630 
631  return ary;
632 }
633 
634 void
635 rb_ary_store(VALUE ary, long idx, VALUE val)
636 {
637  if (idx < 0) {
638  idx += RARRAY_LEN(ary);
639  if (idx < 0) {
640  rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld",
641  idx - RARRAY_LEN(ary), -RARRAY_LEN(ary));
642  }
643  }
644  else if (idx >= ARY_MAX_SIZE) {
645  rb_raise(rb_eIndexError, "index %ld too big", idx);
646  }
647 
648  rb_ary_modify(ary);
649  if (idx >= ARY_CAPA(ary)) {
650  ary_double_capa(ary, idx);
651  }
652  if (idx > RARRAY_LEN(ary)) {
653  rb_mem_clear(RARRAY_PTR(ary) + RARRAY_LEN(ary),
654  idx-RARRAY_LEN(ary) + 1);
655  }
656 
657  if (idx >= RARRAY_LEN(ary)) {
658  ARY_SET_LEN(ary, idx + 1);
659  }
660  RARRAY_PTR(ary)[idx] = val;
661 }
662 
663 static VALUE
664 ary_make_partial(VALUE ary, VALUE klass, long offset, long len)
665 {
666  assert(offset >= 0);
667  assert(len >= 0);
668  assert(offset+len <= RARRAY_LEN(ary));
669 
670  if (len <= RARRAY_EMBED_LEN_MAX) {
671  VALUE result = ary_alloc(klass);
672  MEMCPY(ARY_EMBED_PTR(result), RARRAY_PTR(ary) + offset, VALUE, len);
673  ARY_SET_EMBED_LEN(result, len);
674  return result;
675  }
676  else {
677  VALUE shared, result = ary_alloc(klass);
678  FL_UNSET_EMBED(result);
679 
680  shared = ary_make_shared(ary);
681  ARY_SET_PTR(result, RARRAY_PTR(ary));
682  ARY_SET_LEN(result, RARRAY_LEN(ary));
683  rb_ary_set_shared(result, shared);
684 
685  ARY_INCREASE_PTR(result, offset);
686  ARY_SET_LEN(result, len);
687  return result;
688  }
689 }
690 
691 static VALUE
693 {
694  return ary_make_partial(ary, rb_obj_class(ary), 0, RARRAY_LEN(ary));
695 }
696 
698 {
701 };
702 
703 static VALUE
705 {
706  VALUE nv;
707  long n;
708  long offset = 0;
709 
710  rb_scan_args(argc, argv, "1", &nv);
711  n = NUM2LONG(nv);
712  if (n > RARRAY_LEN(ary)) {
713  n = RARRAY_LEN(ary);
714  }
715  else if (n < 0) {
716  rb_raise(rb_eArgError, "negative array size");
717  }
718  if (last) {
719  offset = RARRAY_LEN(ary) - n;
720  }
721  return ary_make_partial(ary, rb_cArray, offset, n);
722 }
723 
724 static VALUE rb_ary_push_1(VALUE ary, VALUE item);
725 
726 /*
727  * call-seq:
728  * ary << obj -> ary
729  *
730  * Append---Pushes the given object on to the end of this array. This
731  * expression returns the array itself, so several appends
732  * may be chained together.
733  *
734  * [ 1, 2 ] << "c" << "d" << [ 3, 4 ]
735  * #=> [ 1, 2, "c", "d", [ 3, 4 ] ]
736  *
737  */
738 
739 VALUE
741 {
742  rb_ary_modify(ary);
743  return rb_ary_push_1(ary, item);
744 }
745 
746 static VALUE
748 {
749  long idx = RARRAY_LEN(ary);
750 
751  if (idx >= ARY_CAPA(ary)) {
752  ary_double_capa(ary, idx);
753  }
754  RARRAY_PTR(ary)[idx] = item;
755  ARY_SET_LEN(ary, idx + 1);
756  return ary;
757 }
758 
759 /*
760  * call-seq:
761  * ary.push(obj, ... ) -> ary
762  *
763  * Append---Pushes the given object(s) on to the end of this array. This
764  * expression returns the array itself, so several appends
765  * may be chained together.
766  *
767  * a = [ "a", "b", "c" ]
768  * a.push("d", "e", "f")
769  * #=> ["a", "b", "c", "d", "e", "f"]
770  */
771 
772 static VALUE
774 {
775  rb_ary_modify(ary);
776  while (argc--) {
777  rb_ary_push_1(ary, *argv++);
778  }
779  return ary;
780 }
781 
782 VALUE
784 {
785  long n;
786  rb_ary_modify_check(ary);
787  if (RARRAY_LEN(ary) == 0) return Qnil;
788  if (ARY_OWNS_HEAP_P(ary) &&
789  RARRAY_LEN(ary) * 3 < ARY_CAPA(ary) &&
790  ARY_CAPA(ary) > ARY_DEFAULT_SIZE)
791  {
792  ary_resize_capa(ary, RARRAY_LEN(ary) * 2);
793  }
794  n = RARRAY_LEN(ary)-1;
795  ARY_SET_LEN(ary, n);
796  return RARRAY_PTR(ary)[n];
797 }
798 
799 /*
800  * call-seq:
801  * ary.pop -> obj or nil
802  * ary.pop(n) -> new_ary
803  *
804  * Removes the last element from +self+ and returns it, or
805  * <code>nil</code> if the array is empty.
806  *
807  * If a number _n_ is given, returns an array of the last n elements
808  * (or less) just like <code>array.slice!(-n, n)</code> does.
809  *
810  * a = [ "a", "b", "c", "d" ]
811  * a.pop #=> "d"
812  * a.pop(2) #=> ["b", "c"]
813  * a #=> ["a"]
814  */
815 
816 static VALUE
818 {
819  VALUE result;
820 
821  if (argc == 0) {
822  return rb_ary_pop(ary);
823  }
824 
825  rb_ary_modify_check(ary);
826  result = ary_take_first_or_last(argc, argv, ary, ARY_TAKE_LAST);
827  ARY_INCREASE_LEN(ary, -RARRAY_LEN(result));
828  return result;
829 }
830 
831 VALUE
833 {
834  VALUE top;
835 
836  rb_ary_modify_check(ary);
837  if (RARRAY_LEN(ary) == 0) return Qnil;
838  top = RARRAY_PTR(ary)[0];
839  if (!ARY_SHARED_P(ary)) {
840  if (RARRAY_LEN(ary) < ARY_DEFAULT_SIZE) {
841  MEMMOVE(RARRAY_PTR(ary), RARRAY_PTR(ary)+1, VALUE, RARRAY_LEN(ary)-1);
842  ARY_INCREASE_LEN(ary, -1);
843  return top;
844  }
845  assert(!ARY_EMBED_P(ary)); /* ARY_EMBED_LEN_MAX < ARY_DEFAULT_SIZE */
846 
847  RARRAY_PTR(ary)[0] = Qnil;
848  ary_make_shared(ary);
849  }
850  else if (ARY_SHARED_NUM(ARY_SHARED(ary)) == 1) {
851  RARRAY_PTR(ary)[0] = Qnil;
852  }
853  ARY_INCREASE_PTR(ary, 1); /* shift ptr */
854  ARY_INCREASE_LEN(ary, -1);
855 
856  return top;
857 }
858 
859 /*
860  * call-seq:
861  * ary.shift -> obj or nil
862  * ary.shift(n) -> new_ary
863  *
864  * Returns the first element of +self+ and removes it (shifting all
865  * other elements down by one). Returns <code>nil</code> if the array
866  * is empty.
867  *
868  * If a number _n_ is given, returns an array of the first n elements
869  * (or less) just like <code>array.slice!(0, n)</code> does.
870  *
871  * args = [ "-m", "-q", "filename" ]
872  * args.shift #=> "-m"
873  * args #=> ["-q", "filename"]
874  *
875  * args = [ "-m", "-q", "filename" ]
876  * args.shift(2) #=> ["-m", "-q"]
877  * args #=> ["filename"]
878  */
879 
880 static VALUE
882 {
883  VALUE result;
884  long n;
885 
886  if (argc == 0) {
887  return rb_ary_shift(ary);
888  }
889 
890  rb_ary_modify_check(ary);
891  result = ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
892  n = RARRAY_LEN(result);
893  if (ARY_SHARED_P(ary)) {
894  if (ARY_SHARED_NUM(ARY_SHARED(ary)) == 1) {
895  rb_mem_clear(RARRAY_PTR(ary), n);
896  }
897  ARY_INCREASE_PTR(ary, n);
898  }
899  else {
900  MEMMOVE(RARRAY_PTR(ary), RARRAY_PTR(ary)+n, VALUE, RARRAY_LEN(ary)-n);
901  }
902  ARY_INCREASE_LEN(ary, -n);
903 
904  return result;
905 }
906 
907 /*
908  * call-seq:
909  * ary.unshift(obj, ...) -> ary
910  *
911  * Prepends objects to the front of +self+,
912  * moving other elements upwards.
913  *
914  * a = [ "b", "c", "d" ]
915  * a.unshift("a") #=> ["a", "b", "c", "d"]
916  * a.unshift(1, 2) #=> [ 1, 2, "a", "b", "c", "d"]
917  */
918 
919 static VALUE
921 {
922  long len;
923 
924  rb_ary_modify(ary);
925  if (argc == 0) return ary;
926  if (ARY_CAPA(ary) <= (len = RARRAY_LEN(ary)) + argc) {
927  ary_double_capa(ary, len + argc);
928  }
929 
930  /* sliding items */
931  MEMMOVE(RARRAY_PTR(ary) + argc, RARRAY_PTR(ary), VALUE, len);
932  MEMCPY(RARRAY_PTR(ary), argv, VALUE, argc);
933  ARY_INCREASE_LEN(ary, argc);
934 
935  return ary;
936 }
937 
938 VALUE
940 {
941  return rb_ary_unshift_m(1,&item,ary);
942 }
943 
944 /* faster version - use this if you don't need to treat negative offset */
945 static inline VALUE
946 rb_ary_elt(VALUE ary, long offset)
947 {
948  if (RARRAY_LEN(ary) == 0) return Qnil;
949  if (offset < 0 || RARRAY_LEN(ary) <= offset) {
950  return Qnil;
951  }
952  return RARRAY_PTR(ary)[offset];
953 }
954 
955 VALUE
956 rb_ary_entry(VALUE ary, long offset)
957 {
958  if (offset < 0) {
959  offset += RARRAY_LEN(ary);
960  }
961  return rb_ary_elt(ary, offset);
962 }
963 
964 VALUE
965 rb_ary_subseq(VALUE ary, long beg, long len)
966 {
967  VALUE klass;
968 
969  if (beg > RARRAY_LEN(ary)) return Qnil;
970  if (beg < 0 || len < 0) return Qnil;
971 
972  if (RARRAY_LEN(ary) < len || RARRAY_LEN(ary) < beg + len) {
973  len = RARRAY_LEN(ary) - beg;
974  }
975  klass = rb_obj_class(ary);
976  if (len == 0) return ary_new(klass, 0);
977 
978  return ary_make_partial(ary, klass, beg, len);
979 }
980 
981 /*
982  * call-seq:
983  * ary[index] -> obj or nil
984  * ary[start, length] -> new_ary or nil
985  * ary[range] -> new_ary or nil
986  * ary.slice(index) -> obj or nil
987  * ary.slice(start, length) -> new_ary or nil
988  * ary.slice(range) -> new_ary or nil
989  *
990  * Element Reference---Returns the element at _index_,
991  * or returns a subarray starting at _start_ and
992  * continuing for _length_ elements, or returns a subarray
993  * specified by _range_.
994  * Negative indices count backward from the end of the
995  * array (-1 is the last element). Returns +nil+ if the index
996  * (or starting index) are out of range.
997  *
998  * a = [ "a", "b", "c", "d", "e" ]
999  * a[2] + a[0] + a[1] #=> "cab"
1000  * a[6] #=> nil
1001  * a[1, 2] #=> [ "b", "c" ]
1002  * a[1..3] #=> [ "b", "c", "d" ]
1003  * a[4..7] #=> [ "e" ]
1004  * a[6..10] #=> nil
1005  * a[-3, 3] #=> [ "c", "d", "e" ]
1006  * # special cases
1007  * a[5] #=> nil
1008  * a[5, 1] #=> []
1009  * a[5..10] #=> []
1010  *
1011  */
1012 
1013 VALUE
1015 {
1016  VALUE arg;
1017  long beg, len;
1018 
1019  if (argc == 2) {
1020  beg = NUM2LONG(argv[0]);
1021  len = NUM2LONG(argv[1]);
1022  if (beg < 0) {
1023  beg += RARRAY_LEN(ary);
1024  }
1025  return rb_ary_subseq(ary, beg, len);
1026  }
1027  if (argc != 1) {
1028  rb_scan_args(argc, argv, "11", 0, 0);
1029  }
1030  arg = argv[0];
1031  /* special case - speeding up */
1032  if (FIXNUM_P(arg)) {
1033  return rb_ary_entry(ary, FIX2LONG(arg));
1034  }
1035  /* check if idx is Range */
1036  switch (rb_range_beg_len(arg, &beg, &len, RARRAY_LEN(ary), 0)) {
1037  case Qfalse:
1038  break;
1039  case Qnil:
1040  return Qnil;
1041  default:
1042  return rb_ary_subseq(ary, beg, len);
1043  }
1044  return rb_ary_entry(ary, NUM2LONG(arg));
1045 }
1046 
1047 /*
1048  * call-seq:
1049  * ary.at(index) -> obj or nil
1050  *
1051  * Returns the element at _index_. A
1052  * negative index counts from the end of +self+. Returns +nil+
1053  * if the index is out of range. See also <code>Array#[]</code>.
1054  *
1055  * a = [ "a", "b", "c", "d", "e" ]
1056  * a.at(0) #=> "a"
1057  * a.at(-1) #=> "e"
1058  */
1059 
1060 static VALUE
1062 {
1063  return rb_ary_entry(ary, NUM2LONG(pos));
1064 }
1065 
1066 /*
1067  * call-seq:
1068  * ary.first -> obj or nil
1069  * ary.first(n) -> new_ary
1070  *
1071  * Returns the first element, or the first +n+ elements, of the array.
1072  * If the array is empty, the first form returns <code>nil</code>, and the
1073  * second form returns an empty array.
1074  *
1075  * a = [ "q", "r", "s", "t" ]
1076  * a.first #=> "q"
1077  * a.first(2) #=> ["q", "r"]
1078  */
1079 
1080 static VALUE
1082 {
1083  if (argc == 0) {
1084  if (RARRAY_LEN(ary) == 0) return Qnil;
1085  return RARRAY_PTR(ary)[0];
1086  }
1087  else {
1088  return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
1089  }
1090 }
1091 
1092 /*
1093  * call-seq:
1094  * ary.last -> obj or nil
1095  * ary.last(n) -> new_ary
1096  *
1097  * Returns the last element(s) of +self+. If the array is empty,
1098  * the first form returns <code>nil</code>.
1099  *
1100  * a = [ "w", "x", "y", "z" ]
1101  * a.last #=> "z"
1102  * a.last(2) #=> ["y", "z"]
1103  */
1104 
1105 VALUE
1107 {
1108  if (argc == 0) {
1109  if (RARRAY_LEN(ary) == 0) return Qnil;
1110  return RARRAY_PTR(ary)[RARRAY_LEN(ary)-1];
1111  }
1112  else {
1113  return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_LAST);
1114  }
1115 }
1116 
1117 /*
1118  * call-seq:
1119  * ary.fetch(index) -> obj
1120  * ary.fetch(index, default ) -> obj
1121  * ary.fetch(index) {|index| block } -> obj
1122  *
1123  * Tries to return the element at position <i>index</i>. If the index
1124  * lies outside the array, the first form throws an
1125  * <code>IndexError</code> exception, the second form returns
1126  * <i>default</i>, and the third form returns the value of invoking
1127  * the block, passing in the index. Negative values of <i>index</i>
1128  * count from the end of the array.
1129  *
1130  * a = [ 11, 22, 33, 44 ]
1131  * a.fetch(1) #=> 22
1132  * a.fetch(-1) #=> 44
1133  * a.fetch(4, 'cat') #=> "cat"
1134  * a.fetch(4) { |i| i*i } #=> 16
1135  */
1136 
1137 static VALUE
1139 {
1140  VALUE pos, ifnone;
1141  long block_given;
1142  long idx;
1143 
1144  rb_scan_args(argc, argv, "11", &pos, &ifnone);
1145  block_given = rb_block_given_p();
1146  if (block_given && argc == 2) {
1147  rb_warn("block supersedes default value argument");
1148  }
1149  idx = NUM2LONG(pos);
1150 
1151  if (idx < 0) {
1152  idx += RARRAY_LEN(ary);
1153  }
1154  if (idx < 0 || RARRAY_LEN(ary) <= idx) {
1155  if (block_given) return rb_yield(pos);
1156  if (argc == 1) {
1157  rb_raise(rb_eIndexError, "index %ld outside of array bounds: %ld...%ld",
1158  idx - (idx < 0 ? RARRAY_LEN(ary) : 0), -RARRAY_LEN(ary), RARRAY_LEN(ary));
1159  }
1160  return ifnone;
1161  }
1162  return RARRAY_PTR(ary)[idx];
1163 }
1164 
1165 /*
1166  * call-seq:
1167  * ary.index(obj) -> int or nil
1168  * ary.index {|item| block} -> int or nil
1169  * ary.index -> an_enumerator
1170  *
1171  * Returns the index of the first object in +self+ such that the object is
1172  * <code>==</code> to <i>obj</i>. If a block is given instead of an
1173  * argument, returns index of first object for which <em>block</em> is true.
1174  * Returns <code>nil</code> if no match is found.
1175  * See also <code>Array#rindex</code>.
1176  *
1177  * If neither block nor argument is given, an enumerator is returned instead.
1178  *
1179  * a = [ "a", "b", "c" ]
1180  * a.index("b") #=> 1
1181  * a.index("z") #=> nil
1182  * a.index{|x|x=="b"} #=> 1
1183  *
1184  * This is an alias of <code>#find_index</code>.
1185  */
1186 
1187 static VALUE
1189 {
1190  VALUE val;
1191  long i;
1192 
1193  if (argc == 0) {
1194  RETURN_ENUMERATOR(ary, 0, 0);
1195  for (i=0; i<RARRAY_LEN(ary); i++) {
1196  if (RTEST(rb_yield(RARRAY_PTR(ary)[i]))) {
1197  return LONG2NUM(i);
1198  }
1199  }
1200  return Qnil;
1201  }
1202  rb_scan_args(argc, argv, "1", &val);
1203  if (rb_block_given_p())
1204  rb_warn("given block not used");
1205  for (i=0; i<RARRAY_LEN(ary); i++) {
1206  if (rb_equal(RARRAY_PTR(ary)[i], val))
1207  return LONG2NUM(i);
1208  }
1209  return Qnil;
1210 }
1211 
1212 /*
1213  * call-seq:
1214  * ary.rindex(obj) -> int or nil
1215  * ary.rindex {|item| block} -> int or nil
1216  * ary.rindex -> an_enumerator
1217  *
1218  * Returns the index of the last object in +self+
1219  * <code>==</code> to <i>obj</i>. If a block is given instead of an
1220  * argument, returns index of first object for which <em>block</em> is
1221  * true, starting from the last object.
1222  * Returns <code>nil</code> if no match is found.
1223  * See also <code>Array#index</code>.
1224  *
1225  * If neither block nor argument is given, an enumerator is returned instead.
1226  *
1227  * a = [ "a", "b", "b", "b", "c" ]
1228  * a.rindex("b") #=> 3
1229  * a.rindex("z") #=> nil
1230  * a.rindex { |x| x == "b" } #=> 3
1231  */
1232 
1233 static VALUE
1235 {
1236  VALUE val;
1237  long i = RARRAY_LEN(ary);
1238 
1239  if (argc == 0) {
1240  RETURN_ENUMERATOR(ary, 0, 0);
1241  while (i--) {
1242  if (RTEST(rb_yield(RARRAY_PTR(ary)[i])))
1243  return LONG2NUM(i);
1244  if (i > RARRAY_LEN(ary)) {
1245  i = RARRAY_LEN(ary);
1246  }
1247  }
1248  return Qnil;
1249  }
1250  rb_scan_args(argc, argv, "1", &val);
1251  if (rb_block_given_p())
1252  rb_warn("given block not used");
1253  while (i--) {
1254  if (rb_equal(RARRAY_PTR(ary)[i], val))
1255  return LONG2NUM(i);
1256  if (i > RARRAY_LEN(ary)) {
1257  i = RARRAY_LEN(ary);
1258  }
1259  }
1260  return Qnil;
1261 }
1262 
1263 VALUE
1265 {
1266  VALUE tmp = rb_check_array_type(obj);
1267 
1268  if (!NIL_P(tmp)) return tmp;
1269  return rb_ary_new3(1, obj);
1270 }
1271 
1272 static void
1273 rb_ary_splice(VALUE ary, long beg, long len, VALUE rpl)
1274 {
1275  long rlen;
1276 
1277  if (len < 0) rb_raise(rb_eIndexError, "negative length (%ld)", len);
1278  if (beg < 0) {
1279  beg += RARRAY_LEN(ary);
1280  if (beg < 0) {
1281  rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld",
1282  beg - RARRAY_LEN(ary), -RARRAY_LEN(ary));
1283  }
1284  }
1285  if (RARRAY_LEN(ary) < len || RARRAY_LEN(ary) < beg + len) {
1286  len = RARRAY_LEN(ary) - beg;
1287  }
1288 
1289  if (rpl == Qundef) {
1290  rlen = 0;
1291  }
1292  else {
1293  rpl = rb_ary_to_ary(rpl);
1294  rlen = RARRAY_LEN(rpl);
1295  }
1296  rb_ary_modify(ary);
1297  if (beg >= RARRAY_LEN(ary)) {
1298  if (beg > ARY_MAX_SIZE - rlen) {
1299  rb_raise(rb_eIndexError, "index %ld too big", beg);
1300  }
1301  len = beg + rlen;
1302  if (len >= ARY_CAPA(ary)) {
1303  ary_double_capa(ary, len);
1304  }
1305  rb_mem_clear(RARRAY_PTR(ary) + RARRAY_LEN(ary), beg - RARRAY_LEN(ary));
1306  if (rlen > 0) {
1307  MEMCPY(RARRAY_PTR(ary) + beg, RARRAY_PTR(rpl), VALUE, rlen);
1308  }
1309  ARY_SET_LEN(ary, len);
1310  }
1311  else {
1312  long alen;
1313 
1314  alen = RARRAY_LEN(ary) + rlen - len;
1315  if (alen >= ARY_CAPA(ary)) {
1316  ary_double_capa(ary, alen);
1317  }
1318 
1319  if (len != rlen) {
1320  MEMMOVE(RARRAY_PTR(ary) + beg + rlen, RARRAY_PTR(ary) + beg + len,
1321  VALUE, RARRAY_LEN(ary) - (beg + len));
1322  ARY_SET_LEN(ary, alen);
1323  }
1324  if (rlen > 0) {
1325  MEMMOVE(RARRAY_PTR(ary) + beg, RARRAY_PTR(rpl), VALUE, rlen);
1326  }
1327  }
1328 }
1329 
1338 VALUE
1340 {
1341  long olen;
1342 
1343  rb_ary_modify(ary);
1344  olen = RARRAY_LEN(ary);
1345  if (len == olen) return ary;
1346  if (len > ARY_MAX_SIZE) {
1347  rb_raise(rb_eIndexError, "index %ld too big", len);
1348  }
1349  if (len > olen) {
1350  if (len >= ARY_CAPA(ary)) {
1351  ary_double_capa(ary, len);
1352  }
1353  rb_mem_clear(RARRAY_PTR(ary) + olen, len - olen);
1354  ARY_SET_LEN(ary, len);
1355  }
1356  else if (ARY_EMBED_P(ary)) {
1357  ARY_SET_EMBED_LEN(ary, len);
1358  }
1359  else if (len <= RARRAY_EMBED_LEN_MAX) {
1361  MEMCPY(tmp, ARY_HEAP_PTR(ary), VALUE, len);
1362  ary_discard(ary);
1363  MEMCPY(ARY_EMBED_PTR(ary), tmp, VALUE, len);
1364  ARY_SET_EMBED_LEN(ary, len);
1365  }
1366  else {
1367  if (olen > len + ARY_DEFAULT_SIZE) {
1368  REALLOC_N(RARRAY(ary)->as.heap.ptr, VALUE, len);
1369  ARY_SET_CAPA(ary, len);
1370  }
1371  ARY_SET_HEAP_LEN(ary, len);
1372  }
1373  return ary;
1374 }
1375 
1376 /*
1377  * call-seq:
1378  * ary[index] = obj -> obj
1379  * ary[start, length] = obj or other_ary or nil -> obj or other_ary or nil
1380  * ary[range] = obj or other_ary or nil -> obj or other_ary or nil
1381  *
1382  * Element Assignment---Sets the element at _index_,
1383  * or replaces a subarray starting at _start_ and
1384  * continuing for _length_ elements, or replaces a subarray
1385  * specified by _range_. If indices are greater than
1386  * the current capacity of the array, the array grows
1387  * automatically. A negative indices will count backward
1388  * from the end of the array. Inserts elements if _length_ is
1389  * zero. An +IndexError+ is raised if a negative index points
1390  * past the beginning of the array. See also
1391  * <code>Array#push</code>, and <code>Array#unshift</code>.
1392  *
1393  * a = Array.new
1394  * a[4] = "4"; #=> [nil, nil, nil, nil, "4"]
1395  * a[0, 3] = [ 'a', 'b', 'c' ] #=> ["a", "b", "c", nil, "4"]
1396  * a[1..2] = [ 1, 2 ] #=> ["a", 1, 2, nil, "4"]
1397  * a[0, 2] = "?" #=> ["?", 2, nil, "4"]
1398  * a[0..2] = "A" #=> ["A", "4"]
1399  * a[-1] = "Z" #=> ["A", "Z"]
1400  * a[1..-1] = nil #=> ["A", nil]
1401  * a[1..-1] = [] #=> ["A"]
1402  */
1403 
1404 static VALUE
1406 {
1407  long offset, beg, len;
1408 
1409  if (argc == 3) {
1410  rb_ary_modify_check(ary);
1411  beg = NUM2LONG(argv[0]);
1412  len = NUM2LONG(argv[1]);
1413  rb_ary_splice(ary, beg, len, argv[2]);
1414  return argv[2];
1415  }
1416  if (argc != 2) {
1417  rb_raise(rb_eArgError, "wrong number of arguments (%d for 2)", argc);
1418  }
1419  rb_ary_modify_check(ary);
1420  if (FIXNUM_P(argv[0])) {
1421  offset = FIX2LONG(argv[0]);
1422  goto fixnum;
1423  }
1424  if (rb_range_beg_len(argv[0], &beg, &len, RARRAY_LEN(ary), 1)) {
1425  /* check if idx is Range */
1426  rb_ary_splice(ary, beg, len, argv[1]);
1427  return argv[1];
1428  }
1429 
1430  offset = NUM2LONG(argv[0]);
1431 fixnum:
1432  rb_ary_store(ary, offset, argv[1]);
1433  return argv[1];
1434 }
1435 
1436 /*
1437  * call-seq:
1438  * ary.insert(index, obj...) -> ary
1439  *
1440  * Inserts the given values before the element with the given index
1441  * (which may be negative).
1442  *
1443  * a = %w{ a b c d }
1444  * a.insert(2, 99) #=> ["a", "b", 99, "c", "d"]
1445  * a.insert(-2, 1, 2, 3) #=> ["a", "b", 99, "c", 1, 2, 3, "d"]
1446  */
1447 
1448 static VALUE
1450 {
1451  long pos;
1452 
1453  if (argc < 1) {
1454  rb_raise(rb_eArgError, "wrong number of arguments (at least 1)");
1455  }
1456  rb_ary_modify_check(ary);
1457  if (argc == 1) return ary;
1458  pos = NUM2LONG(argv[0]);
1459  if (pos == -1) {
1460  pos = RARRAY_LEN(ary);
1461  }
1462  if (pos < 0) {
1463  pos++;
1464  }
1465  rb_ary_splice(ary, pos, 0, rb_ary_new4(argc - 1, argv + 1));
1466  return ary;
1467 }
1468 
1469 /*
1470  * call-seq:
1471  * ary.each {|item| block } -> ary
1472  * ary.each -> an_enumerator
1473  *
1474  * Calls <i>block</i> once for each element in +self+, passing that
1475  * element as a parameter.
1476  *
1477  * If no block is given, an enumerator is returned instead.
1478  *
1479  * a = [ "a", "b", "c" ]
1480  * a.each {|x| print x, " -- " }
1481  *
1482  * produces:
1483  *
1484  * a -- b -- c --
1485  */
1486 
1487 VALUE
1489 {
1490  long i;
1491  volatile VALUE ary = array;
1492 
1493  RETURN_ENUMERATOR(ary, 0, 0);
1494  for (i=0; i<RARRAY_LEN(ary); i++) {
1495  rb_yield(RARRAY_PTR(ary)[i]);
1496  }
1497  return ary;
1498 }
1499 
1500 /*
1501  * call-seq:
1502  * ary.each_index {|index| block } -> ary
1503  * ary.each_index -> an_enumerator
1504  *
1505  * Same as <code>Array#each</code>, but passes the index of the element
1506  * instead of the element itself.
1507  *
1508  * If no block is given, an enumerator is returned instead.
1509  *
1510  *
1511  * a = [ "a", "b", "c" ]
1512  * a.each_index {|x| print x, " -- " }
1513  *
1514  * produces:
1515  *
1516  * 0 -- 1 -- 2 --
1517  */
1518 
1519 static VALUE
1521 {
1522  long i;
1523  RETURN_ENUMERATOR(ary, 0, 0);
1524 
1525  for (i=0; i<RARRAY_LEN(ary); i++) {
1526  rb_yield(LONG2NUM(i));
1527  }
1528  return ary;
1529 }
1530 
1531 /*
1532  * call-seq:
1533  * ary.reverse_each {|item| block } -> ary
1534  * ary.reverse_each -> an_enumerator
1535  *
1536  * Same as <code>Array#each</code>, but traverses +self+ in reverse
1537  * order.
1538  *
1539  * a = [ "a", "b", "c" ]
1540  * a.reverse_each {|x| print x, " " }
1541  *
1542  * produces:
1543  *
1544  * c b a
1545  */
1546 
1547 static VALUE
1549 {
1550  long len;
1551 
1552  RETURN_ENUMERATOR(ary, 0, 0);
1553  len = RARRAY_LEN(ary);
1554  while (len--) {
1555  rb_yield(RARRAY_PTR(ary)[len]);
1556  if (RARRAY_LEN(ary) < len) {
1557  len = RARRAY_LEN(ary);
1558  }
1559  }
1560  return ary;
1561 }
1562 
1563 /*
1564  * call-seq:
1565  * ary.length -> int
1566  *
1567  * Returns the number of elements in +self+. May be zero.
1568  *
1569  * [ 1, 2, 3, 4, 5 ].length #=> 5
1570  */
1571 
1572 static VALUE
1574 {
1575  long len = RARRAY_LEN(ary);
1576  return LONG2NUM(len);
1577 }
1578 
1579 /*
1580  * call-seq:
1581  * ary.empty? -> true or false
1582  *
1583  * Returns <code>true</code> if +self+ contains no elements.
1584  *
1585  * [].empty? #=> true
1586  */
1587 
1588 static VALUE
1590 {
1591  if (RARRAY_LEN(ary) == 0)
1592  return Qtrue;
1593  return Qfalse;
1594 }
1595 
1596 VALUE
1598 {
1599  VALUE dup = rb_ary_new2(RARRAY_LEN(ary));
1600  MEMCPY(RARRAY_PTR(dup), RARRAY_PTR(ary), VALUE, RARRAY_LEN(ary));
1601  ARY_SET_LEN(dup, RARRAY_LEN(ary));
1602  return dup;
1603 }
1604 
1605 VALUE
1607 {
1608  return rb_ary_new4(RARRAY_LEN(ary), RARRAY_PTR(ary));
1609 }
1610 
1611 extern VALUE rb_output_fs;
1612 
1613 static void ary_join_1(VALUE obj, VALUE ary, VALUE sep, long i, VALUE result, int *first);
1614 
1615 static VALUE
1617 {
1618  VALUE *arg = (VALUE *)argp;
1619  VALUE ary = arg[0];
1620  VALUE sep = arg[1];
1621  VALUE result = arg[2];
1622  int *first = (int *)arg[3];
1623 
1624  if (recur) {
1625  rb_raise(rb_eArgError, "recursive array join");
1626  }
1627  else {
1628  ary_join_1(obj, ary, sep, 0, result, first);
1629  }
1630  return Qnil;
1631 }
1632 
1633 static void
1635 {
1636  long i;
1637  VALUE val;
1638 
1639  if (max > 0) rb_enc_copy(result, RARRAY_PTR(ary)[0]);
1640  for (i=0; i<max; i++) {
1641  val = RARRAY_PTR(ary)[i];
1642  if (i > 0 && !NIL_P(sep))
1643  rb_str_buf_append(result, sep);
1644  rb_str_buf_append(result, val);
1645  if (OBJ_TAINTED(val)) OBJ_TAINT(result);
1646  if (OBJ_UNTRUSTED(val)) OBJ_TAINT(result);
1647  }
1648 }
1649 
1650 static void
1651 ary_join_1(VALUE obj, VALUE ary, VALUE sep, long i, VALUE result, int *first)
1652 {
1653  VALUE val, tmp;
1654 
1655  for (; i<RARRAY_LEN(ary); i++) {
1656  if (i > 0 && !NIL_P(sep))
1657  rb_str_buf_append(result, sep);
1658 
1659  val = RARRAY_PTR(ary)[i];
1660  switch (TYPE(val)) {
1661  case T_STRING:
1662  str_join:
1663  rb_str_buf_append(result, val);
1664  *first = FALSE;
1665  break;
1666  case T_ARRAY:
1667  obj = val;
1668  ary_join:
1669  if (val == ary) {
1670  rb_raise(rb_eArgError, "recursive array join");
1671  }
1672  else {
1673  VALUE args[4];
1674 
1675  args[0] = val;
1676  args[1] = sep;
1677  args[2] = result;
1678  args[3] = (VALUE)first;
1679  rb_exec_recursive(recursive_join, obj, (VALUE)args);
1680  }
1681  break;
1682  default:
1683  tmp = rb_check_string_type(val);
1684  if (!NIL_P(tmp)) {
1685  val = tmp;
1686  goto str_join;
1687  }
1688  tmp = rb_check_convert_type(val, T_ARRAY, "Array", "to_ary");
1689  if (!NIL_P(tmp)) {
1690  obj = val;
1691  val = tmp;
1692  goto ary_join;
1693  }
1694  val = rb_obj_as_string(val);
1695  if (*first) {
1696  rb_enc_copy(result, val);
1697  *first = FALSE;
1698  }
1699  goto str_join;
1700  }
1701  }
1702 }
1703 
1704 VALUE
1706 {
1707  long len = 1, i;
1708  int taint = FALSE;
1709  int untrust = FALSE;
1710  VALUE val, tmp, result;
1711 
1712  if (RARRAY_LEN(ary) == 0) return rb_usascii_str_new(0, 0);
1713  if (OBJ_TAINTED(ary) || OBJ_TAINTED(sep)) taint = TRUE;
1714  if (OBJ_UNTRUSTED(ary) || OBJ_UNTRUSTED(sep)) untrust = TRUE;
1715 
1716  if (!NIL_P(sep)) {
1717  StringValue(sep);
1718  len += RSTRING_LEN(sep) * (RARRAY_LEN(ary) - 1);
1719  }
1720  for (i=0; i<RARRAY_LEN(ary); i++) {
1721  val = RARRAY_PTR(ary)[i];
1722  tmp = rb_check_string_type(val);
1723 
1724  if (NIL_P(tmp) || tmp != val) {
1725  int first;
1726  result = rb_str_buf_new(len + (RARRAY_LEN(ary)-i)*10);
1728  if (taint) OBJ_TAINT(result);
1729  if (untrust) OBJ_UNTRUST(result);
1730  ary_join_0(ary, sep, i, result);
1731  first = i == 0;
1732  ary_join_1(ary, ary, sep, i, result, &first);
1733  return result;
1734  }
1735 
1736  len += RSTRING_LEN(tmp);
1737  }
1738 
1739  result = rb_str_buf_new(len);
1740  if (taint) OBJ_TAINT(result);
1741  if (untrust) OBJ_UNTRUST(result);
1742  ary_join_0(ary, sep, RARRAY_LEN(ary), result);
1743 
1744  return result;
1745 }
1746 
1747 /*
1748  * call-seq:
1749  * ary.join(sep=$,) -> str
1750  *
1751  * Returns a string created by converting each element of the array to
1752  * a string, separated by <i>sep</i>.
1753  *
1754  * [ "a", "b", "c" ].join #=> "abc"
1755  * [ "a", "b", "c" ].join("-") #=> "a-b-c"
1756  */
1757 
1758 static VALUE
1760 {
1761  VALUE sep;
1762 
1763  rb_scan_args(argc, argv, "01", &sep);
1764  if (NIL_P(sep)) sep = rb_output_fs;
1765 
1766  return rb_ary_join(ary, sep);
1767 }
1768 
1769 static VALUE
1770 inspect_ary(VALUE ary, VALUE dummy, int recur)
1771 {
1772  int tainted = OBJ_TAINTED(ary);
1773  int untrust = OBJ_UNTRUSTED(ary);
1774  long i;
1775  VALUE s, str;
1776 
1777  if (recur) return rb_usascii_str_new_cstr("[...]");
1778  str = rb_str_buf_new2("[");
1779  for (i=0; i<RARRAY_LEN(ary); i++) {
1780  s = rb_inspect(RARRAY_PTR(ary)[i]);
1781  if (OBJ_TAINTED(s)) tainted = TRUE;
1782  if (OBJ_UNTRUSTED(s)) untrust = TRUE;
1783  if (i > 0) rb_str_buf_cat2(str, ", ");
1784  else rb_enc_copy(str, s);
1785  rb_str_buf_append(str, s);
1786  }
1787  rb_str_buf_cat2(str, "]");
1788  if (tainted) OBJ_TAINT(str);
1789  if (untrust) OBJ_UNTRUST(str);
1790  return str;
1791 }
1792 
1793 /*
1794  * call-seq:
1795  * ary.to_s -> string
1796  * ary.inspect -> string
1797  *
1798  * Creates a string representation of +self+.
1799  */
1800 
1801 static VALUE
1803 {
1804  if (RARRAY_LEN(ary) == 0) return rb_usascii_str_new2("[]");
1805  return rb_exec_recursive(inspect_ary, ary, 0);
1806 }
1807 
1808 VALUE
1810 {
1811  return rb_ary_inspect(ary);
1812 }
1813 
1814 /*
1815  * call-seq:
1816  * ary.to_a -> ary
1817  *
1818  * Returns +self+. If called on a subclass of Array, converts
1819  * the receiver to an Array object.
1820  */
1821 
1822 static VALUE
1824 {
1825  if (rb_obj_class(ary) != rb_cArray) {
1826  VALUE dup = rb_ary_new2(RARRAY_LEN(ary));
1827  rb_ary_replace(dup, ary);
1828  return dup;
1829  }
1830  return ary;
1831 }
1832 
1833 /*
1834  * call-seq:
1835  * ary.to_ary -> ary
1836  *
1837  * Returns +self+.
1838  */
1839 
1840 static VALUE
1842 {
1843  return ary;
1844 }
1845 
1846 static void
1848  VALUE *p1, *p2;
1849 {
1850  while (p1 < p2) {
1851  VALUE tmp = *p1;
1852  *p1++ = *p2;
1853  *p2-- = tmp;
1854  }
1855 }
1856 
1857 VALUE
1859 {
1860  VALUE *p1, *p2;
1861 
1862  rb_ary_modify(ary);
1863  if (RARRAY_LEN(ary) > 1) {
1864  p1 = RARRAY_PTR(ary);
1865  p2 = p1 + RARRAY_LEN(ary) - 1; /* points last item */
1866  ary_reverse(p1, p2);
1867  }
1868  return ary;
1869 }
1870 
1871 /*
1872  * call-seq:
1873  * ary.reverse! -> ary
1874  *
1875  * Reverses +self+ in place.
1876  *
1877  * a = [ "a", "b", "c" ]
1878  * a.reverse! #=> ["c", "b", "a"]
1879  * a #=> ["c", "b", "a"]
1880  */
1881 
1882 static VALUE
1884 {
1885  return rb_ary_reverse(ary);
1886 }
1887 
1888 /*
1889  * call-seq:
1890  * ary.reverse -> new_ary
1891  *
1892  * Returns a new array containing +self+'s elements in reverse order.
1893  *
1894  * [ "a", "b", "c" ].reverse #=> ["c", "b", "a"]
1895  * [ 1 ].reverse #=> [1]
1896  */
1897 
1898 static VALUE
1900 {
1901  long len = RARRAY_LEN(ary);
1902  VALUE dup = rb_ary_new2(len);
1903 
1904  if (len > 0) {
1905  VALUE *p1 = RARRAY_PTR(ary);
1906  VALUE *p2 = RARRAY_PTR(dup) + len - 1;
1907  do *p2-- = *p1++; while (--len > 0);
1908  }
1909  ARY_SET_LEN(dup, RARRAY_LEN(ary));
1910  return dup;
1911 }
1912 
1913 static inline long
1914 rotate_count(long cnt, long len)
1915 {
1916  return (cnt < 0) ? (len - (~cnt % len) - 1) : (cnt % len);
1917 }
1918 
1919 VALUE
1921 {
1922  rb_ary_modify(ary);
1923 
1924  if (cnt != 0) {
1925  VALUE *ptr = RARRAY_PTR(ary);
1926  long len = RARRAY_LEN(ary);
1927 
1928  if (len > 0 && (cnt = rotate_count(cnt, len)) > 0) {
1929  --len;
1930  if (cnt < len) ary_reverse(ptr + cnt, ptr + len);
1931  if (--cnt > 0) ary_reverse(ptr, ptr + cnt);
1932  if (len > 0) ary_reverse(ptr, ptr + len);
1933  return ary;
1934  }
1935  }
1936 
1937  return Qnil;
1938 }
1939 
1940 /*
1941  * call-seq:
1942  * ary.rotate!(cnt=1) -> ary
1943  *
1944  * Rotates +self+ in place so that the element at +cnt+ comes first,
1945  * and returns +self+. If +cnt+ is negative then it rotates in
1946  * the opposite direction.
1947  *
1948  * a = [ "a", "b", "c", "d" ]
1949  * a.rotate! #=> ["b", "c", "d", "a"]
1950  * a #=> ["b", "c", "d", "a"]
1951  * a.rotate!(2) #=> ["d", "a", "b", "c"]
1952  * a.rotate!(-3) #=> ["a", "b", "c", "d"]
1953  */
1954 
1955 static VALUE
1957 {
1958  long n = 1;
1959 
1960  switch (argc) {
1961  case 1: n = NUM2LONG(argv[0]);
1962  case 0: break;
1963  default: rb_scan_args(argc, argv, "01", NULL);
1964  }
1965  rb_ary_rotate(ary, n);
1966  return ary;
1967 }
1968 
1969 /*
1970  * call-seq:
1971  * ary.rotate(cnt=1) -> new_ary
1972  *
1973  * Returns new array by rotating +self+ so that the element at
1974  * +cnt+ in +self+ is the first element of the new array. If +cnt+
1975  * is negative then it rotates in the opposite direction.
1976  *
1977  * a = [ "a", "b", "c", "d" ]
1978  * a.rotate #=> ["b", "c", "d", "a"]
1979  * a #=> ["a", "b", "c", "d"]
1980  * a.rotate(2) #=> ["c", "d", "a", "b"]
1981  * a.rotate(-3) #=> ["b", "c", "d", "a"]
1982  */
1983 
1984 static VALUE
1986 {
1987  VALUE rotated, *ptr, *ptr2;
1988  long len, cnt = 1;
1989 
1990  switch (argc) {
1991  case 1: cnt = NUM2LONG(argv[0]);
1992  case 0: break;
1993  default: rb_scan_args(argc, argv, "01", NULL);
1994  }
1995 
1996  len = RARRAY_LEN(ary);
1997  rotated = rb_ary_new2(len);
1998  if (len > 0) {
1999  cnt = rotate_count(cnt, len);
2000  ptr = RARRAY_PTR(ary);
2001  ptr2 = RARRAY_PTR(rotated);
2002  len -= cnt;
2003  MEMCPY(ptr2, ptr + cnt, VALUE, len);
2004  MEMCPY(ptr2 + len, ptr, VALUE, cnt);
2005  }
2006  ARY_SET_LEN(rotated, RARRAY_LEN(ary));
2007  return rotated;
2008 }
2009 
2014 };
2015 
2016 enum {
2020 };
2021 
2022 #define STRING_P(s) (TYPE(s) == T_STRING && CLASS_OF(s) == rb_cString)
2023 
2024 #define SORT_OPTIMIZABLE_BIT(type) (1U << TOKEN_PASTE(sort_opt_,type))
2025 #define SORT_OPTIMIZABLE(data, type) \
2026  (((data)->opt_inited & SORT_OPTIMIZABLE_BIT(type)) ? \
2027  ((data)->opt_methods & SORT_OPTIMIZABLE_BIT(type)) : \
2028  (((data)->opt_inited |= SORT_OPTIMIZABLE_BIT(type)), \
2029  rb_method_basic_definition_p(TOKEN_PASTE(rb_c,type), id_cmp) && \
2030  ((data)->opt_methods |= SORT_OPTIMIZABLE_BIT(type))))
2031 
2032 static VALUE
2034 {
2035  if (RBASIC(ary)->klass) {
2036  rb_raise(rb_eRuntimeError, "sort reentered");
2037  }
2038  return Qnil;
2039 }
2040 
2041 static int
2042 sort_1(const void *ap, const void *bp, void *dummy)
2043 {
2044  struct ary_sort_data *data = dummy;
2045  VALUE retval = sort_reentered(data->ary);
2046  VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
2047  int n;
2048 
2049  retval = rb_yield_values(2, a, b);
2050  n = rb_cmpint(retval, a, b);
2051  sort_reentered(data->ary);
2052  return n;
2053 }
2054 
2055 static int
2056 sort_2(const void *ap, const void *bp, void *dummy)
2057 {
2058  struct ary_sort_data *data = dummy;
2059  VALUE retval = sort_reentered(data->ary);
2060  VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
2061  int n;
2062 
2063  if (FIXNUM_P(a) && FIXNUM_P(b) && SORT_OPTIMIZABLE(data, Fixnum)) {
2064  if ((long)a > (long)b) return 1;
2065  if ((long)a < (long)b) return -1;
2066  return 0;
2067  }
2068  if (STRING_P(a) && STRING_P(b) && SORT_OPTIMIZABLE(data, String)) {
2069  return rb_str_cmp(a, b);
2070  }
2071 
2072  retval = rb_funcall(a, id_cmp, 1, b);
2073  n = rb_cmpint(retval, a, b);
2074  sort_reentered(data->ary);
2075 
2076  return n;
2077 }
2078 
2079 /*
2080  * call-seq:
2081  * ary.sort! -> ary
2082  * ary.sort! {| a,b | block } -> ary
2083  *
2084  * Sorts +self+. Comparisons for
2085  * the sort will be done using the <code><=></code> operator or using
2086  * an optional code block. The block implements a comparison between
2087  * <i>a</i> and <i>b</i>, returning -1, 0, or +1. See also
2088  * <code>Enumerable#sort_by</code>.
2089  *
2090  * a = [ "d", "a", "e", "c", "b" ]
2091  * a.sort! #=> ["a", "b", "c", "d", "e"]
2092  * a.sort! {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
2093  */
2094 
2095 VALUE
2097 {
2098  rb_ary_modify(ary);
2099  assert(!ARY_SHARED_P(ary));
2100  if (RARRAY_LEN(ary) > 1) {
2101  VALUE tmp = ary_make_substitution(ary); /* only ary refers tmp */
2102  struct ary_sort_data data;
2103 
2104  RBASIC(tmp)->klass = 0;
2105  data.ary = tmp;
2106  data.opt_methods = 0;
2107  data.opt_inited = 0;
2108  ruby_qsort(RARRAY_PTR(tmp), RARRAY_LEN(tmp), sizeof(VALUE),
2109  rb_block_given_p()?sort_1:sort_2, &data);
2110 
2111  if (ARY_EMBED_P(tmp)) {
2112  assert(ARY_EMBED_P(tmp));
2113  if (ARY_SHARED_P(ary)) { /* ary might be destructively operated in the given block */
2114  rb_ary_unshare(ary);
2115  }
2116  FL_SET_EMBED(ary);
2117  MEMCPY(RARRAY_PTR(ary), ARY_EMBED_PTR(tmp), VALUE, ARY_EMBED_LEN(tmp));
2118  ARY_SET_LEN(ary, ARY_EMBED_LEN(tmp));
2119  }
2120  else {
2121  assert(!ARY_EMBED_P(tmp));
2122  if (ARY_HEAP_PTR(ary) == ARY_HEAP_PTR(tmp)) {
2123  assert(!ARY_EMBED_P(ary));
2124  FL_UNSET_SHARED(ary);
2125  ARY_SET_CAPA(ary, ARY_CAPA(tmp));
2126  }
2127  else {
2128  assert(!ARY_SHARED_P(tmp));
2129  if (ARY_EMBED_P(ary)) {
2130  FL_UNSET_EMBED(ary);
2131  }
2132  else if (ARY_SHARED_P(ary)) {
2133  /* ary might be destructively operated in the given block */
2134  rb_ary_unshare(ary);
2135  }
2136  else {
2137  xfree(ARY_HEAP_PTR(ary));
2138  }
2139  ARY_SET_PTR(ary, RARRAY_PTR(tmp));
2140  ARY_SET_HEAP_LEN(ary, RARRAY_LEN(tmp));
2141  ARY_SET_CAPA(ary, ARY_CAPA(tmp));
2142  }
2143  /* tmp was lost ownership for the ptr */
2144  FL_UNSET(tmp, FL_FREEZE);
2145  FL_SET_EMBED(tmp);
2146  ARY_SET_EMBED_LEN(tmp, 0);
2147  FL_SET(tmp, FL_FREEZE);
2148  }
2149  /* tmp will be GC'ed. */
2150  RBASIC(tmp)->klass = rb_cArray;
2151  }
2152  return ary;
2153 }
2154 
2155 /*
2156  * call-seq:
2157  * ary.sort -> new_ary
2158  * ary.sort {| a,b | block } -> new_ary
2159  *
2160  * Returns a new array created by sorting +self+. Comparisons for
2161  * the sort will be done using the <code><=></code> operator or using
2162  * an optional code block. The block implements a comparison between
2163  * <i>a</i> and <i>b</i>, returning -1, 0, or +1. See also
2164  * <code>Enumerable#sort_by</code>.
2165  *
2166  * a = [ "d", "a", "e", "c", "b" ]
2167  * a.sort #=> ["a", "b", "c", "d", "e"]
2168  * a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
2169  */
2170 
2171 VALUE
2173 {
2174  ary = rb_ary_dup(ary);
2175  rb_ary_sort_bang(ary);
2176  return ary;
2177 }
2178 
2179 
2180 static VALUE
2182 {
2183  return rb_yield(i);
2184 }
2185 
2186 /*
2187  * call-seq:
2188  * ary.sort_by! {| obj | block } -> ary
2189  * ary.sort_by! -> an_enumerator
2190  *
2191  * Sorts +self+ in place using a set of keys generated by mapping the
2192  * values in +self+ through the given block.
2193  *
2194  * If no block is given, an enumerator is returned instead.
2195  *
2196  */
2197 
2198 static VALUE
2200 {
2201  VALUE sorted;
2202 
2203  RETURN_ENUMERATOR(ary, 0, 0);
2204  rb_ary_modify(ary);
2205  sorted = rb_block_call(ary, rb_intern("sort_by"), 0, 0, sort_by_i, 0);
2206  rb_ary_replace(ary, sorted);
2207  return ary;
2208 }
2209 
2210 
2211 /*
2212  * call-seq:
2213  * ary.collect {|item| block } -> new_ary
2214  * ary.map {|item| block } -> new_ary
2215  * ary.collect -> an_enumerator
2216  * ary.map -> an_enumerator
2217  *
2218  * Invokes <i>block</i> once for each element of +self+. Creates a
2219  * new array containing the values returned by the block.
2220  * See also <code>Enumerable#collect</code>.
2221  *
2222  * If no block is given, an enumerator is returned instead.
2223  *
2224  * a = [ "a", "b", "c", "d" ]
2225  * a.collect {|x| x + "!" } #=> ["a!", "b!", "c!", "d!"]
2226  * a #=> ["a", "b", "c", "d"]
2227  */
2228 
2229 static VALUE
2231 {
2232  long i;
2233  VALUE collect;
2234 
2235  RETURN_ENUMERATOR(ary, 0, 0);
2236  collect = rb_ary_new2(RARRAY_LEN(ary));
2237  for (i = 0; i < RARRAY_LEN(ary); i++) {
2238  rb_ary_push(collect, rb_yield(RARRAY_PTR(ary)[i]));
2239  }
2240  return collect;
2241 }
2242 
2243 
2244 /*
2245  * call-seq:
2246  * ary.collect! {|item| block } -> ary
2247  * ary.map! {|item| block } -> ary
2248  * ary.collect -> an_enumerator
2249  * ary.map -> an_enumerator
2250  *
2251  * Invokes the block once for each element of +self+, replacing the
2252  * element with the value returned by _block_.
2253  * See also <code>Enumerable#collect</code>.
2254  *
2255  * If no block is given, an enumerator is returned instead.
2256  *
2257  * a = [ "a", "b", "c", "d" ]
2258  * a.collect! {|x| x + "!" }
2259  * a #=> [ "a!", "b!", "c!", "d!" ]
2260  */
2261 
2262 static VALUE
2264 {
2265  long i;
2266 
2267  RETURN_ENUMERATOR(ary, 0, 0);
2268  rb_ary_modify(ary);
2269  for (i = 0; i < RARRAY_LEN(ary); i++) {
2270  rb_ary_store(ary, i, rb_yield(RARRAY_PTR(ary)[i]));
2271  }
2272  return ary;
2273 }
2274 
2275 VALUE
2276 rb_get_values_at(VALUE obj, long olen, int argc, VALUE *argv, VALUE (*func) (VALUE, long))
2277 {
2278  VALUE result = rb_ary_new2(argc);
2279  long beg, len, i, j;
2280 
2281  for (i=0; i<argc; i++) {
2282  if (FIXNUM_P(argv[i])) {
2283  rb_ary_push(result, (*func)(obj, FIX2LONG(argv[i])));
2284  continue;
2285  }
2286  /* check if idx is Range */
2287  switch (rb_range_beg_len(argv[i], &beg, &len, olen, 0)) {
2288  case Qfalse:
2289  break;
2290  case Qnil:
2291  continue;
2292  default:
2293  for (j=0; j<len; j++) {
2294  rb_ary_push(result, (*func)(obj, j+beg));
2295  }
2296  continue;
2297  }
2298  rb_ary_push(result, (*func)(obj, NUM2LONG(argv[i])));
2299  }
2300  return result;
2301 }
2302 
2303 /*
2304  * call-seq:
2305  * ary.values_at(selector,... ) -> new_ary
2306  *
2307  * Returns an array containing the elements in
2308  * +self+ corresponding to the given selector(s). The selectors
2309  * may be either integer indices or ranges.
2310  * See also <code>Array#select</code>.
2311  *
2312  * a = %w{ a b c d e f }
2313  * a.values_at(1, 3, 5)
2314  * a.values_at(1, 3, 5, 7)
2315  * a.values_at(-1, -3, -5, -7)
2316  * a.values_at(1..3, 2...5)
2317  */
2318 
2319 static VALUE
2320 rb_ary_values_at(int argc, VALUE *argv, VALUE ary)
2321 {
2322  return rb_get_values_at(ary, RARRAY_LEN(ary), argc, argv, rb_ary_entry);
2323 }
2324 
2325 
2326 /*
2327  * call-seq:
2328  * ary.select {|item| block } -> new_ary
2329  * ary.select -> an_enumerator
2330  *
2331  * Invokes the block passing in successive elements from +self+,
2332  * returning an array containing those elements for which the block
2333  * returns a true value (equivalent to <code>Enumerable#select</code>).
2334  *
2335  * If no block is given, an enumerator is returned instead.
2336  *
2337  * a = %w{ a b c d e f }
2338  * a.select {|v| v =~ /[aeiou]/} #=> ["a", "e"]
2339  */
2340 
2341 static VALUE
2343 {
2344  VALUE result;
2345  long i;
2346 
2347  RETURN_ENUMERATOR(ary, 0, 0);
2348  result = rb_ary_new2(RARRAY_LEN(ary));
2349  for (i = 0; i < RARRAY_LEN(ary); i++) {
2350  if (RTEST(rb_yield(RARRAY_PTR(ary)[i]))) {
2351  rb_ary_push(result, rb_ary_elt(ary, i));
2352  }
2353  }
2354  return result;
2355 }
2356 
2357 /*
2358  * call-seq:
2359  * ary.select! {|item| block } -> ary or nil
2360  * ary.select! -> an_enumerator
2361  *
2362  * Invokes the block passing in successive elements from
2363  * +self+, deleting elements for which the block returns a
2364  * false value. It returns +self+ if changes were made,
2365  * otherwise it returns <code>nil</code>.
2366  * See also <code>Array#keep_if</code>
2367  *
2368  * If no block is given, an enumerator is returned instead.
2369  *
2370  */
2371 
2372 static VALUE
2374 {
2375  long i1, i2;
2376 
2377  RETURN_ENUMERATOR(ary, 0, 0);
2378  rb_ary_modify(ary);
2379  for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) {
2380  VALUE v = RARRAY_PTR(ary)[i1];
2381  if (!RTEST(rb_yield(v))) continue;
2382  if (i1 != i2) {
2383  rb_ary_store(ary, i2, v);
2384  }
2385  i2++;
2386  }
2387 
2388  if (RARRAY_LEN(ary) == i2) return Qnil;
2389  if (i2 < RARRAY_LEN(ary))
2390  ARY_SET_LEN(ary, i2);
2391  return ary;
2392 }
2393 
2394 /*
2395  * call-seq:
2396  * ary.keep_if {|item| block } -> ary
2397  * ary.keep_if -> an_enumerator
2398  *
2399  * Deletes every element of +self+ for which <i>block</i> evaluates
2400  * to false.
2401  * See also <code>Array#select!</code>
2402  *
2403  * If no block is given, an enumerator is returned instead.
2404  *
2405  * a = %w{ a b c d e f }
2406  * a.keep_if {|v| v =~ /[aeiou]/} #=> ["a", "e"]
2407  */
2408 
2409 static VALUE
2411 {
2412  RETURN_ENUMERATOR(ary, 0, 0);
2413  rb_ary_select_bang(ary);
2414  return ary;
2415 }
2416 
2417 /*
2418  * call-seq:
2419  * ary.delete(obj) -> obj or nil
2420  * ary.delete(obj) { block } -> obj or nil
2421  *
2422  * Deletes items from +self+ that are equal to <i>obj</i>.
2423  * If any items are found, returns <i>obj</i>. If
2424  * the item is not found, returns <code>nil</code>. If the optional
2425  * code block is given, returns the result of <i>block</i> if the item
2426  * is not found. (To remove <code>nil</code> elements and
2427  * get an informative return value, use #compact!)
2428  *
2429  * a = [ "a", "b", "b", "b", "c" ]
2430  * a.delete("b") #=> "b"
2431  * a #=> ["a", "c"]
2432  * a.delete("z") #=> nil
2433  * a.delete("z") { "not found" } #=> "not found"
2434  */
2435 
2436 VALUE
2438 {
2439  VALUE v = item;
2440  long i1, i2;
2441 
2442  for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) {
2443  VALUE e = RARRAY_PTR(ary)[i1];
2444 
2445  if (rb_equal(e, item)) {
2446  v = e;
2447  continue;
2448  }
2449  if (i1 != i2) {
2450  rb_ary_store(ary, i2, e);
2451  }
2452  i2++;
2453  }
2454  if (RARRAY_LEN(ary) == i2) {
2455  if (rb_block_given_p()) {
2456  return rb_yield(item);
2457  }
2458  return Qnil;
2459  }
2460 
2461  rb_ary_modify(ary);
2462  if (RARRAY_LEN(ary) > i2) {
2463  ARY_SET_LEN(ary, i2);
2464  if (i2 * 2 < ARY_CAPA(ary) &&
2465  ARY_CAPA(ary) > ARY_DEFAULT_SIZE) {
2466  ary_resize_capa(ary, i2*2);
2467  }
2468  }
2469 
2470  return v;
2471 }
2472 
2473 VALUE
2475 {
2476  long len = RARRAY_LEN(ary);
2477  VALUE del;
2478 
2479  if (pos >= len) return Qnil;
2480  if (pos < 0) {
2481  pos += len;
2482  if (pos < 0) return Qnil;
2483  }
2484 
2485  rb_ary_modify(ary);
2486  del = RARRAY_PTR(ary)[pos];
2487  MEMMOVE(RARRAY_PTR(ary)+pos, RARRAY_PTR(ary)+pos+1, VALUE,
2488  RARRAY_LEN(ary)-pos-1);
2489  ARY_INCREASE_LEN(ary, -1);
2490 
2491  return del;
2492 }
2493 
2494 /*
2495  * call-seq:
2496  * ary.delete_at(index) -> obj or nil
2497  *
2498  * Deletes the element at the specified index, returning that element,
2499  * or <code>nil</code> if the index is out of range. See also
2500  * <code>Array#slice!</code>.
2501  *
2502  * a = %w( ant bat cat dog )
2503  * a.delete_at(2) #=> "cat"
2504  * a #=> ["ant", "bat", "dog"]
2505  * a.delete_at(99) #=> nil
2506  */
2507 
2508 static VALUE
2510 {
2511  return rb_ary_delete_at(ary, NUM2LONG(pos));
2512 }
2513 
2514 /*
2515  * call-seq:
2516  * ary.slice!(index) -> obj or nil
2517  * ary.slice!(start, length) -> new_ary or nil
2518  * ary.slice!(range) -> new_ary or nil
2519  *
2520  * Deletes the element(s) given by an index (optionally with a length)
2521  * or by a range. Returns the deleted object (or objects), or
2522  * <code>nil</code> if the index is out of range.
2523  *
2524  * a = [ "a", "b", "c" ]
2525  * a.slice!(1) #=> "b"
2526  * a #=> ["a", "c"]
2527  * a.slice!(-1) #=> "c"
2528  * a #=> ["a"]
2529  * a.slice!(100) #=> nil
2530  * a #=> ["a"]
2531  */
2532 
2533 static VALUE
2535 {
2536  VALUE arg1, arg2;
2537  long pos, len, orig_len;
2538 
2539  rb_ary_modify_check(ary);
2540  if (argc == 2) {
2541  pos = NUM2LONG(argv[0]);
2542  len = NUM2LONG(argv[1]);
2543  delete_pos_len:
2544  if (len < 0) return Qnil;
2545  orig_len = RARRAY_LEN(ary);
2546  if (pos < 0) {
2547  pos += orig_len;
2548  if (pos < 0) return Qnil;
2549  }
2550  else if (orig_len < pos) return Qnil;
2551  if (orig_len < pos + len) {
2552  len = orig_len - pos;
2553  }
2554  if (len == 0) return rb_ary_new2(0);
2555  arg2 = rb_ary_new4(len, RARRAY_PTR(ary)+pos);
2556  RBASIC(arg2)->klass = rb_obj_class(ary);
2557  rb_ary_splice(ary, pos, len, Qundef);
2558  return arg2;
2559  }
2560 
2561  if (argc != 1) {
2562  /* error report */
2563  rb_scan_args(argc, argv, "11", NULL, NULL);
2564  }
2565  arg1 = argv[0];
2566 
2567  if (!FIXNUM_P(arg1)) {
2568  switch (rb_range_beg_len(arg1, &pos, &len, RARRAY_LEN(ary), 0)) {
2569  case Qtrue:
2570  /* valid range */
2571  goto delete_pos_len;
2572  case Qnil:
2573  /* invalid range */
2574  return Qnil;
2575  default:
2576  /* not a range */
2577  break;
2578  }
2579  }
2580 
2581  return rb_ary_delete_at(ary, NUM2LONG(arg1));
2582 }
2583 
2584 static VALUE
2586 {
2587  long i;
2588 
2589  for (i = 0; i < RARRAY_LEN(orig); i++) {
2590  VALUE v = RARRAY_PTR(orig)[i];
2591  if (!RTEST(rb_yield(v))) {
2592  rb_ary_push_1(result, v);
2593  }
2594  }
2595  return result;
2596 }
2597 
2598 static VALUE
2600 {
2601  long i;
2602  VALUE result = Qnil;
2603 
2604  rb_ary_modify_check(ary);
2605  for (i = 0; i < RARRAY_LEN(ary); ) {
2606  VALUE v = RARRAY_PTR(ary)[i];
2607  if (RTEST(rb_yield(v))) {
2608  rb_ary_delete_at(ary, i);
2609  result = ary;
2610  }
2611  else {
2612  i++;
2613  }
2614  }
2615  return result;
2616 }
2617 
2618 /*
2619  * call-seq:
2620  * ary.reject! {|item| block } -> ary or nil
2621  * ary.reject! -> an_enumerator
2622  *
2623  * Equivalent to <code>Array#delete_if</code>, deleting elements from
2624  * +self+ for which the block evaluates to true, but returns
2625  * <code>nil</code> if no changes were made.
2626  * The array is changed instantly every time the block is called and
2627  * not after the iteration is over.
2628  * See also <code>Enumerable#reject</code> and <code>Array#delete_if</code>.
2629  *
2630  * If no block is given, an enumerator is returned instead.
2631  *
2632  */
2633 
2634 static VALUE
2636 {
2637  RETURN_ENUMERATOR(ary, 0, 0);
2638  return ary_reject_bang(ary);
2639 }
2640 
2641 /*
2642  * call-seq:
2643  * ary.reject {|item| block } -> new_ary
2644  * ary.reject -> an_enumerator
2645  *
2646  * Returns a new array containing the items in +self+
2647  * for which the block is not true.
2648  * See also <code>Array#delete_if</code>
2649  *
2650  * If no block is given, an enumerator is returned instead.
2651  *
2652  */
2653 
2654 static VALUE
2656 {
2657  VALUE rejected_ary;
2658 
2659  RETURN_ENUMERATOR(ary, 0, 0);
2660  rejected_ary = rb_ary_new();
2661  ary_reject(ary, rejected_ary);
2662  return rejected_ary;
2663 }
2664 
2665 /*
2666  * call-seq:
2667  * ary.delete_if {|item| block } -> ary
2668  * ary.delete_if -> an_enumerator
2669  *
2670  * Deletes every element of +self+ for which <i>block</i> evaluates
2671  * to true.
2672  * The array is changed instantly every time the block is called and
2673  * not after the iteration is over.
2674  * See also <code>Array#reject!</code>
2675  *
2676  * If no block is given, an enumerator is returned instead.
2677  *
2678  * a = [ "a", "b", "c" ]
2679  * a.delete_if {|x| x >= "b" } #=> ["a"]
2680  */
2681 
2682 static VALUE
2684 {
2685  RETURN_ENUMERATOR(ary, 0, 0);
2686  ary_reject_bang(ary);
2687  return ary;
2688 }
2689 
2690 static VALUE
2691 take_i(VALUE val, VALUE *args, int argc, VALUE *argv)
2692 {
2693  if (args[1]-- == 0) rb_iter_break();
2694  if (argc > 1) val = rb_ary_new4(argc, argv);
2695  rb_ary_push(args[0], val);
2696  return Qnil;
2697 }
2698 
2699 static VALUE
2700 take_items(VALUE obj, long n)
2701 {
2703  VALUE args[2];
2704 
2705  if (!NIL_P(result)) return rb_ary_subseq(result, 0, n);
2706  result = rb_ary_new2(n);
2707  args[0] = result; args[1] = (VALUE)n;
2708  rb_block_call(obj, rb_intern("each"), 0, 0, take_i, (VALUE)args);
2709  return result;
2710 }
2711 
2712 
2713 /*
2714  * call-seq:
2715  * ary.zip(arg, ...) -> new_ary
2716  * ary.zip(arg, ...) {| arr | block } -> nil
2717  *
2718  * Converts any arguments to arrays, then merges elements of
2719  * +self+ with corresponding elements from each argument. This
2720  * generates a sequence of <code>self.size</code> <em>n</em>-element
2721  * arrays, where <em>n</em> is one more that the count of arguments. If
2722  * the size of any argument is less than <code>enumObj.size</code>,
2723  * <code>nil</code> values are supplied. If a block is given, it is
2724  * invoked for each output array, otherwise an array of arrays is
2725  * returned.
2726  *
2727  * a = [ 4, 5, 6 ]
2728  * b = [ 7, 8, 9 ]
2729  * [1,2,3].zip(a, b) #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
2730  * [1,2].zip(a,b) #=> [[1, 4, 7], [2, 5, 8]]
2731  * a.zip([1,2],[8]) #=> [[4,1,8], [5,2,nil], [6,nil,nil]]
2732  */
2733 
2734 static VALUE
2735 rb_ary_zip(int argc, VALUE *argv, VALUE ary)
2736 {
2737  int i, j;
2738  long len;
2739  VALUE result = Qnil;
2740 
2741  len = RARRAY_LEN(ary);
2742  for (i=0; i<argc; i++) {
2743  argv[i] = take_items(argv[i], len);
2744  }
2745  if (!rb_block_given_p()) {
2746  result = rb_ary_new2(len);
2747  }
2748 
2749  for (i=0; i<RARRAY_LEN(ary); i++) {
2750  VALUE tmp = rb_ary_new2(argc+1);
2751 
2752  rb_ary_push(tmp, rb_ary_elt(ary, i));
2753  for (j=0; j<argc; j++) {
2754  rb_ary_push(tmp, rb_ary_elt(argv[j], i));
2755  }
2756  if (NIL_P(result)) {
2757  rb_yield(tmp);
2758  }
2759  else {
2760  rb_ary_push(result, tmp);
2761  }
2762  }
2763  return result;
2764 }
2765 
2766 /*
2767  * call-seq:
2768  * ary.transpose -> new_ary
2769  *
2770  * Assumes that +self+ is an array of arrays and transposes the
2771  * rows and columns.
2772  *
2773  * a = [[1,2], [3,4], [5,6]]
2774  * a.transpose #=> [[1, 3, 5], [2, 4, 6]]
2775  */
2776 
2777 static VALUE
2779 {
2780  long elen = -1, alen, i, j;
2781  VALUE tmp, result = 0;
2782 
2783  alen = RARRAY_LEN(ary);
2784  if (alen == 0) return rb_ary_dup(ary);
2785  for (i=0; i<alen; i++) {
2786  tmp = to_ary(rb_ary_elt(ary, i));
2787  if (elen < 0) { /* first element */
2788  elen = RARRAY_LEN(tmp);
2789  result = rb_ary_new2(elen);
2790  for (j=0; j<elen; j++) {
2791  rb_ary_store(result, j, rb_ary_new2(alen));
2792  }
2793  }
2794  else if (elen != RARRAY_LEN(tmp)) {
2795  rb_raise(rb_eIndexError, "element size differs (%ld should be %ld)",
2796  RARRAY_LEN(tmp), elen);
2797  }
2798  for (j=0; j<elen; j++) {
2799  rb_ary_store(rb_ary_elt(result, j), i, rb_ary_elt(tmp, j));
2800  }
2801  }
2802  return result;
2803 }
2804 
2805 /*
2806  * call-seq:
2807  * ary.replace(other_ary) -> ary
2808  *
2809  * Replaces the contents of +self+ with the contents of
2810  * <i>other_ary</i>, truncating or expanding if necessary.
2811  *
2812  * a = [ "a", "b", "c", "d", "e" ]
2813  * a.replace([ "x", "y", "z" ]) #=> ["x", "y", "z"]
2814  * a #=> ["x", "y", "z"]
2815  */
2816 
2817 VALUE
2819 {
2820  rb_ary_modify_check(copy);
2821  orig = to_ary(orig);
2822  if (copy == orig) return copy;
2823 
2824  if (RARRAY_LEN(orig) <= RARRAY_EMBED_LEN_MAX) {
2825  VALUE *ptr;
2826  VALUE shared = 0;
2827 
2828  if (ARY_OWNS_HEAP_P(copy)) {
2829  xfree(RARRAY_PTR(copy));
2830  }
2831  else if (ARY_SHARED_P(copy)) {
2832  shared = ARY_SHARED(copy);
2833  FL_UNSET_SHARED(copy);
2834  }
2835  FL_SET_EMBED(copy);
2836  ptr = RARRAY_PTR(orig);
2837  MEMCPY(RARRAY_PTR(copy), ptr, VALUE, RARRAY_LEN(orig));
2838  if (shared) {
2839  rb_ary_decrement_share(shared);
2840  }
2841  ARY_SET_LEN(copy, RARRAY_LEN(orig));
2842  }
2843  else {
2844  VALUE shared = ary_make_shared(orig);
2845  if (ARY_OWNS_HEAP_P(copy)) {
2846  xfree(RARRAY_PTR(copy));
2847  }
2848  else {
2849  rb_ary_unshare_safe(copy);
2850  }
2851  FL_UNSET_EMBED(copy);
2852  ARY_SET_PTR(copy, RARRAY_PTR(orig));
2853  ARY_SET_LEN(copy, RARRAY_LEN(orig));
2854  rb_ary_set_shared(copy, shared);
2855  }
2856  return copy;
2857 }
2858 
2859 /*
2860  * call-seq:
2861  * ary.clear -> ary
2862  *
2863  * Removes all elements from +self+.
2864  *
2865  * a = [ "a", "b", "c", "d", "e" ]
2866  * a.clear #=> [ ]
2867  */
2868 
2869 VALUE
2871 {
2872  rb_ary_modify_check(ary);
2873  ARY_SET_LEN(ary, 0);
2874  if (ARY_SHARED_P(ary)) {
2875  if (!ARY_EMBED_P(ary)) {
2876  rb_ary_unshare(ary);
2877  FL_SET_EMBED(ary);
2878  }
2879  }
2880  else if (ARY_DEFAULT_SIZE * 2 < ARY_CAPA(ary)) {
2882  }
2883  return ary;
2884 }
2885 
2886 /*
2887  * call-seq:
2888  * ary.fill(obj) -> ary
2889  * ary.fill(obj, start [, length]) -> ary
2890  * ary.fill(obj, range ) -> ary
2891  * ary.fill {|index| block } -> ary
2892  * ary.fill(start [, length] ) {|index| block } -> ary
2893  * ary.fill(range) {|index| block } -> ary
2894  *
2895  * The first three forms set the selected elements of +self+ (which
2896  * may be the entire array) to <i>obj</i>. A <i>start</i> of
2897  * <code>nil</code> is equivalent to zero. A <i>length</i> of
2898  * <code>nil</code> is equivalent to <i>self.length</i>. The last three
2899  * forms fill the array with the value of the block. The block is
2900  * passed the absolute index of each element to be filled.
2901  * Negative values of <i>start</i> count from the end of the array.
2902  *
2903  * a = [ "a", "b", "c", "d" ]
2904  * a.fill("x") #=> ["x", "x", "x", "x"]
2905  * a.fill("z", 2, 2) #=> ["x", "x", "z", "z"]
2906  * a.fill("y", 0..1) #=> ["y", "y", "z", "z"]
2907  * a.fill {|i| i*i} #=> [0, 1, 4, 9]
2908  * a.fill(-2) {|i| i*i*i} #=> [0, 1, 8, 27]
2909  */
2910 
2911 static VALUE
2912 rb_ary_fill(int argc, VALUE *argv, VALUE ary)
2913 {
2914  VALUE item, arg1, arg2;
2915  long beg = 0, end = 0, len = 0;
2916  VALUE *p, *pend;
2917  int block_p = FALSE;
2918 
2919  if (rb_block_given_p()) {
2920  block_p = TRUE;
2921  rb_scan_args(argc, argv, "02", &arg1, &arg2);
2922  argc += 1; /* hackish */
2923  }
2924  else {
2925  rb_scan_args(argc, argv, "12", &item, &arg1, &arg2);
2926  }
2927  switch (argc) {
2928  case 1:
2929  beg = 0;
2930  len = RARRAY_LEN(ary);
2931  break;
2932  case 2:
2933  if (rb_range_beg_len(arg1, &beg, &len, RARRAY_LEN(ary), 1)) {
2934  break;
2935  }
2936  /* fall through */
2937  case 3:
2938  beg = NIL_P(arg1) ? 0 : NUM2LONG(arg1);
2939  if (beg < 0) {
2940  beg = RARRAY_LEN(ary) + beg;
2941  if (beg < 0) beg = 0;
2942  }
2943  len = NIL_P(arg2) ? RARRAY_LEN(ary) - beg : NUM2LONG(arg2);
2944  break;
2945  }
2946  rb_ary_modify(ary);
2947  if (len < 0) {
2948  return ary;
2949  }
2950  if (beg >= ARY_MAX_SIZE || len > ARY_MAX_SIZE - beg) {
2951  rb_raise(rb_eArgError, "argument too big");
2952  }
2953  end = beg + len;
2954  if (RARRAY_LEN(ary) < end) {
2955  if (end >= ARY_CAPA(ary)) {
2956  ary_resize_capa(ary, end);
2957  }
2958  rb_mem_clear(RARRAY_PTR(ary) + RARRAY_LEN(ary), end - RARRAY_LEN(ary));
2959  ARY_SET_LEN(ary, end);
2960  }
2961 
2962  if (block_p) {
2963  VALUE v;
2964  long i;
2965 
2966  for (i=beg; i<end; i++) {
2967  v = rb_yield(LONG2NUM(i));
2968  if (i>=RARRAY_LEN(ary)) break;
2969  RARRAY_PTR(ary)[i] = v;
2970  }
2971  }
2972  else {
2973  p = RARRAY_PTR(ary) + beg;
2974  pend = p + len;
2975  while (p < pend) {
2976  *p++ = item;
2977  }
2978  }
2979  return ary;
2980 }
2981 
2982 /*
2983  * call-seq:
2984  * ary + other_ary -> new_ary
2985  *
2986  * Concatenation---Returns a new array built by concatenating the
2987  * two arrays together to produce a third array.
2988  *
2989  * [ 1, 2, 3 ] + [ 4, 5 ] #=> [ 1, 2, 3, 4, 5 ]
2990  */
2991 
2992 VALUE
2994 {
2995  VALUE z;
2996  long len;
2997 
2998  y = to_ary(y);
2999  len = RARRAY_LEN(x) + RARRAY_LEN(y);
3000  z = rb_ary_new2(len);
3003  ARY_SET_LEN(z, len);
3004  return z;
3005 }
3006 
3007 /*
3008  * call-seq:
3009  * ary.concat(other_ary) -> ary
3010  *
3011  * Appends the elements of <i>other_ary</i> to +self+.
3012  *
3013  * [ "a", "b" ].concat( ["c", "d"] ) #=> [ "a", "b", "c", "d" ]
3014  */
3015 
3016 
3017 VALUE
3019 {
3021  y = to_ary(y);
3022  if (RARRAY_LEN(y) > 0) {
3023  rb_ary_splice(x, RARRAY_LEN(x), 0, y);
3024  }
3025  return x;
3026 }
3027 
3028 
3029 /*
3030  * call-seq:
3031  * ary * int -> new_ary
3032  * ary * str -> new_string
3033  *
3034  * Repetition---With a String argument, equivalent to
3035  * self.join(str). Otherwise, returns a new array
3036  * built by concatenating the _int_ copies of +self+.
3037  *
3038  *
3039  * [ 1, 2, 3 ] * 3 #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
3040  * [ 1, 2, 3 ] * "," #=> "1,2,3"
3041  *
3042  */
3043 
3044 static VALUE
3046 {
3047  VALUE ary2, tmp, *ptr, *ptr2;
3048  long t, len;
3049 
3050  tmp = rb_check_string_type(times);
3051  if (!NIL_P(tmp)) {
3052  return rb_ary_join(ary, tmp);
3053  }
3054 
3055  len = NUM2LONG(times);
3056  if (len == 0) {
3057  ary2 = ary_new(rb_obj_class(ary), 0);
3058  goto out;
3059  }
3060  if (len < 0) {
3061  rb_raise(rb_eArgError, "negative argument");
3062  }
3063  if (ARY_MAX_SIZE/len < RARRAY_LEN(ary)) {
3064  rb_raise(rb_eArgError, "argument too big");
3065  }
3066  len *= RARRAY_LEN(ary);
3067 
3068  ary2 = ary_new(rb_obj_class(ary), len);
3069  ARY_SET_LEN(ary2, len);
3070 
3071  ptr = RARRAY_PTR(ary);
3072  ptr2 = RARRAY_PTR(ary2);
3073  t = RARRAY_LEN(ary);
3074  if (0 < t) {
3075  MEMCPY(ptr2, ptr, VALUE, t);
3076  while (t <= len/2) {
3077  MEMCPY(ptr2+t, ptr2, VALUE, t);
3078  t *= 2;
3079  }
3080  if (t < len) {
3081  MEMCPY(ptr2+t, ptr2, VALUE, len-t);
3082  }
3083  }
3084  out:
3085  OBJ_INFECT(ary2, ary);
3086 
3087  return ary2;
3088 }
3089 
3090 /*
3091  * call-seq:
3092  * ary.assoc(obj) -> new_ary or nil
3093  *
3094  * Searches through an array whose elements are also arrays
3095  * comparing _obj_ with the first element of each contained array
3096  * using obj.==.
3097  * Returns the first contained array that matches (that
3098  * is, the first associated array),
3099  * or +nil+ if no match is found.
3100  * See also <code>Array#rassoc</code>.
3101  *
3102  * s1 = [ "colors", "red", "blue", "green" ]
3103  * s2 = [ "letters", "a", "b", "c" ]
3104  * s3 = "foo"
3105  * a = [ s1, s2, s3 ]
3106  * a.assoc("letters") #=> [ "letters", "a", "b", "c" ]
3107  * a.assoc("foo") #=> nil
3108  */
3109 
3110 VALUE
3112 {
3113  long i;
3114  VALUE v;
3115 
3116  for (i = 0; i < RARRAY_LEN(ary); ++i) {
3117  v = rb_check_array_type(RARRAY_PTR(ary)[i]);
3118  if (!NIL_P(v) && RARRAY_LEN(v) > 0 &&
3119  rb_equal(RARRAY_PTR(v)[0], key))
3120  return v;
3121  }
3122  return Qnil;
3123 }
3124 
3125 /*
3126  * call-seq:
3127  * ary.rassoc(obj) -> new_ary or nil
3128  *
3129  * Searches through the array whose elements are also arrays. Compares
3130  * _obj_ with the second element of each contained array using
3131  * <code>==</code>. Returns the first contained array that matches. See
3132  * also <code>Array#assoc</code>.
3133  *
3134  * a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ]
3135  * a.rassoc("two") #=> [2, "two"]
3136  * a.rassoc("four") #=> nil
3137  */
3138 
3139 VALUE
3141 {
3142  long i;
3143  VALUE v;
3144 
3145  for (i = 0; i < RARRAY_LEN(ary); ++i) {
3146  v = RARRAY_PTR(ary)[i];
3147  if (TYPE(v) == T_ARRAY &&
3148  RARRAY_LEN(v) > 1 &&
3149  rb_equal(RARRAY_PTR(v)[1], value))
3150  return v;
3151  }
3152  return Qnil;
3153 }
3154 
3155 static VALUE
3157 {
3158  long i;
3159 
3160  if (recur) return Qtrue; /* Subtle! */
3161  for (i=0; i<RARRAY_LEN(ary1); i++) {
3162  if (!rb_equal(rb_ary_elt(ary1, i), rb_ary_elt(ary2, i)))
3163  return Qfalse;
3164  }
3165  return Qtrue;
3166 }
3167 
3168 /*
3169  * call-seq:
3170  * ary == other_ary -> bool
3171  *
3172  * Equality---Two arrays are equal if they contain the same number
3173  * of elements and if each element is equal to (according to
3174  * Object.==) the corresponding element in the other array.
3175  *
3176  * [ "a", "c" ] == [ "a", "c", 7 ] #=> false
3177  * [ "a", "c", 7 ] == [ "a", "c", 7 ] #=> true
3178  * [ "a", "c", 7 ] == [ "a", "d", "f" ] #=> false
3179  *
3180  */
3181 
3182 static VALUE
3184 {
3185  if (ary1 == ary2) return Qtrue;
3186  if (TYPE(ary2) != T_ARRAY) {
3187  if (!rb_respond_to(ary2, rb_intern("to_ary"))) {
3188  return Qfalse;
3189  }
3190  return rb_equal(ary2, ary1);
3191  }
3192  if (RARRAY_LEN(ary1) != RARRAY_LEN(ary2)) return Qfalse;
3193  return rb_exec_recursive_paired(recursive_equal, ary1, ary2, ary2);
3194 }
3195 
3196 static VALUE
3197 recursive_eql(VALUE ary1, VALUE ary2, int recur)
3198 {
3199  long i;
3200 
3201  if (recur) return Qtrue; /* Subtle! */
3202  for (i=0; i<RARRAY_LEN(ary1); i++) {
3203  if (!rb_eql(rb_ary_elt(ary1, i), rb_ary_elt(ary2, i)))
3204  return Qfalse;
3205  }
3206  return Qtrue;
3207 }
3208 
3209 /*
3210  * call-seq:
3211  * ary.eql?(other) -> true or false
3212  *
3213  * Returns <code>true</code> if +self+ and _other_ are the same object,
3214  * or are both arrays with the same content.
3215  */
3216 
3217 static VALUE
3219 {
3220  if (ary1 == ary2) return Qtrue;
3221  if (TYPE(ary2) != T_ARRAY) return Qfalse;
3222  if (RARRAY_LEN(ary1) != RARRAY_LEN(ary2)) return Qfalse;
3223  return rb_exec_recursive_paired(recursive_eql, ary1, ary2, ary2);
3224 }
3225 
3226 static VALUE
3228 {
3229  long i;
3230  st_index_t h;
3231  VALUE n;
3232 
3233  h = rb_hash_start(RARRAY_LEN(ary));
3234  if (recur) {
3236  }
3237  else {
3238  for (i=0; i<RARRAY_LEN(ary); i++) {
3239  n = rb_hash(RARRAY_PTR(ary)[i]);
3240  h = rb_hash_uint(h, NUM2LONG(n));
3241  }
3242  }
3243  h = rb_hash_end(h);
3244  return LONG2FIX(h);
3245 }
3246 
3247 /*
3248  * call-seq:
3249  * ary.hash -> fixnum
3250  *
3251  * Compute a hash-code for this array. Two arrays with the same content
3252  * will have the same hash code (and will compare using <code>eql?</code>).
3253  */
3254 
3255 static VALUE
3257 {
3258  return rb_exec_recursive_outer(recursive_hash, ary, 0);
3259 }
3260 
3261 /*
3262  * call-seq:
3263  * ary.include?(obj) -> true or false
3264  *
3265  * Returns <code>true</code> if the given object is present in
3266  * +self+ (that is, if any object <code>==</code> <i>anObject</i>),
3267  * <code>false</code> otherwise.
3268  *
3269  * a = [ "a", "b", "c" ]
3270  * a.include?("b") #=> true
3271  * a.include?("z") #=> false
3272  */
3273 
3274 VALUE
3276 {
3277  long i;
3278 
3279  for (i=0; i<RARRAY_LEN(ary); i++) {
3280  if (rb_equal(RARRAY_PTR(ary)[i], item)) {
3281  return Qtrue;
3282  }
3283  }
3284  return Qfalse;
3285 }
3286 
3287 
3288 static VALUE
3289 recursive_cmp(VALUE ary1, VALUE ary2, int recur)
3290 {
3291  long i, len;
3292 
3293  if (recur) return Qundef; /* Subtle! */
3294  len = RARRAY_LEN(ary1);
3295  if (len > RARRAY_LEN(ary2)) {
3296  len = RARRAY_LEN(ary2);
3297  }
3298  for (i=0; i<len; i++) {
3299  VALUE v = rb_funcall(rb_ary_elt(ary1, i), id_cmp, 1, rb_ary_elt(ary2, i));
3300  if (v != INT2FIX(0)) {
3301  return v;
3302  }
3303  }
3304  return Qundef;
3305 }
3306 
3307 /*
3308  * call-seq:
3309  * ary <=> other_ary -> -1, 0, +1 or nil
3310  *
3311  * Comparison---Returns an integer (-1, 0,
3312  * or +1) if this array is less than, equal to, or greater than
3313  * <i>other_ary</i>. Each object in each array is compared
3314  * (using <=>). If any value isn't
3315  * equal, then that inequality is the return value. If all the
3316  * values found are equal, then the return is based on a
3317  * comparison of the array lengths. Thus, two arrays are
3318  * ``equal'' according to <code>Array#<=></code> if and only if they have
3319  * the same length and the value of each element is equal to the
3320  * value of the corresponding element in the other array.
3321  *
3322  * [ "a", "a", "c" ] <=> [ "a", "b", "c" ] #=> -1
3323  * [ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ] #=> +1
3324  *
3325  */
3326 
3327 VALUE
3329 {
3330  long len;
3331  VALUE v;
3332 
3333  ary2 = rb_check_array_type(ary2);
3334  if (NIL_P(ary2)) return Qnil;
3335  if (ary1 == ary2) return INT2FIX(0);
3336  v = rb_exec_recursive_paired(recursive_cmp, ary1, ary2, ary2);
3337  if (v != Qundef) return v;
3338  len = RARRAY_LEN(ary1) - RARRAY_LEN(ary2);
3339  if (len == 0) return INT2FIX(0);
3340  if (len > 0) return INT2FIX(1);
3341  return INT2FIX(-1);
3342 }
3343 
3344 static VALUE
3346 {
3347  long i;
3348 
3349  for (i=0; i<RARRAY_LEN(ary); i++) {
3350  rb_hash_aset(hash, RARRAY_PTR(ary)[i], Qtrue);
3351  }
3352  return hash;
3353 }
3354 
3355 static inline VALUE
3357 {
3358  VALUE hash = rb_hash_new();
3359 
3360  RBASIC(hash)->klass = 0;
3361  return hash;
3362 }
3363 
3364 static VALUE
3366 {
3368  return ary_add_hash(hash, ary);
3369 }
3370 
3371 static VALUE
3373 {
3374  long i;
3375 
3376  for (i = 0; i < RARRAY_LEN(ary); ++i) {
3377  VALUE v = rb_ary_elt(ary, i), k = rb_yield(v);
3378  if (rb_hash_lookup2(hash, k, Qundef) == Qundef) {
3379  rb_hash_aset(hash, k, v);
3380  }
3381  }
3382  return hash;
3383 }
3384 
3385 static VALUE
3387 {
3389  return ary_add_hash_by(hash, ary);
3390 }
3391 
3392 static inline void
3394 {
3395  if (RHASH(hash)->ntbl) {
3396  st_table *tbl = RHASH(hash)->ntbl;
3397  RHASH(hash)->ntbl = 0;
3398  st_free_table(tbl);
3399  }
3400 }
3401 
3402 /*
3403  * call-seq:
3404  * ary - other_ary -> new_ary
3405  *
3406  * Array Difference---Returns a new array that is a copy of
3407  * the original array, removing any items that also appear in
3408  * <i>other_ary</i>. (If you need set-like behavior, see the
3409  * library class Set.)
3410  *
3411  * [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]
3412  */
3413 
3414 static VALUE
3416 {
3417  VALUE ary3;
3418  volatile VALUE hash;
3419  long i;
3420 
3421  hash = ary_make_hash(to_ary(ary2));
3422  ary3 = rb_ary_new();
3423 
3424  for (i=0; i<RARRAY_LEN(ary1); i++) {
3425  if (st_lookup(RHASH_TBL(hash), RARRAY_PTR(ary1)[i], 0)) continue;
3426  rb_ary_push(ary3, rb_ary_elt(ary1, i));
3427  }
3428  ary_recycle_hash(hash);
3429  return ary3;
3430 }
3431 
3432 /*
3433  * call-seq:
3434  * ary & other_ary -> new_ary
3435  *
3436  * Set Intersection---Returns a new array
3437  * containing elements common to the two arrays, with no duplicates.
3438  *
3439  * [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]
3440  */
3441 
3442 
3443 static VALUE
3445 {
3446  VALUE hash, ary3, v;
3447  st_data_t vv;
3448  long i;
3449 
3450  ary2 = to_ary(ary2);
3451  ary3 = rb_ary_new2(RARRAY_LEN(ary1) < RARRAY_LEN(ary2) ?
3452  RARRAY_LEN(ary1) : RARRAY_LEN(ary2));
3453  hash = ary_make_hash(ary2);
3454 
3455  if (RHASH_EMPTY_P(hash))
3456  return ary3;
3457 
3458  for (i=0; i<RARRAY_LEN(ary1); i++) {
3459  vv = (st_data_t)(v = rb_ary_elt(ary1, i));
3460  if (st_delete(RHASH_TBL(hash), &vv, 0)) {
3461  rb_ary_push(ary3, v);
3462  }
3463  }
3464  ary_recycle_hash(hash);
3465 
3466  return ary3;
3467 }
3468 
3469 /*
3470  * call-seq:
3471  * ary | other_ary -> new_ary
3472  *
3473  * Set Union---Returns a new array by joining this array with
3474  * <i>other_ary</i>, removing duplicates.
3475  *
3476  * [ "a", "b", "c" ] | [ "c", "d", "a" ]
3477  * #=> [ "a", "b", "c", "d" ]
3478  */
3479 
3480 static VALUE
3481 rb_ary_or(VALUE ary1, VALUE ary2)
3482 {
3483  VALUE hash, ary3, v;
3484  st_data_t vv;
3485  long i;
3486 
3487  ary2 = to_ary(ary2);
3488  ary3 = rb_ary_new2(RARRAY_LEN(ary1)+RARRAY_LEN(ary2));
3489  hash = ary_add_hash(ary_make_hash(ary1), ary2);
3490 
3491  for (i=0; i<RARRAY_LEN(ary1); i++) {
3492  vv = (st_data_t)(v = rb_ary_elt(ary1, i));
3493  if (st_delete(RHASH_TBL(hash), &vv, 0)) {
3494  rb_ary_push(ary3, v);
3495  }
3496  }
3497  for (i=0; i<RARRAY_LEN(ary2); i++) {
3498  vv = (st_data_t)(v = rb_ary_elt(ary2, i));
3499  if (st_delete(RHASH_TBL(hash), &vv, 0)) {
3500  rb_ary_push(ary3, v);
3501  }
3502  }
3503  ary_recycle_hash(hash);
3504  return ary3;
3505 }
3506 
3507 static int
3509 {
3510  rb_ary_push((VALUE)ary, (VALUE)val);
3511  return ST_CONTINUE;
3512 }
3513 
3514 /*
3515  * call-seq:
3516  * ary.uniq! -> ary or nil
3517  * ary.uniq! { |item| ... } -> ary or nil
3518  *
3519  * Removes duplicate elements from +self+. If a block is given,
3520  * it will use the return value of the block for comparison.
3521  * Returns <code>nil</code> if no changes are made (that is, no
3522  * duplicates are found).
3523  *
3524  * a = [ "a", "a", "b", "b", "c" ]
3525  * a.uniq! # => ["a", "b", "c"]
3526  *
3527  * b = [ "a", "b", "c" ]
3528  * b.uniq! # => nil
3529  *
3530  * c = [["student","sam"], ["student","george"], ["teacher","matz"]]
3531  * c.uniq! { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
3532  *
3533  */
3534 
3535 static VALUE
3537 {
3538  VALUE hash, v;
3539  long i, j;
3540 
3541  rb_ary_modify_check(ary);
3542  if (RARRAY_LEN(ary) <= 1)
3543  return Qnil;
3544  if (rb_block_given_p()) {
3545  hash = ary_make_hash_by(ary);
3546  if (RARRAY_LEN(ary) == (i = RHASH_SIZE(hash))) {
3547  return Qnil;
3548  }
3549  ARY_SET_LEN(ary, 0);
3550  if (ARY_SHARED_P(ary) && !ARY_EMBED_P(ary)) {
3551  rb_ary_unshare(ary);
3552  FL_SET_EMBED(ary);
3553  }
3554  ary_resize_capa(ary, i);
3555  st_foreach(RHASH_TBL(hash), push_value, ary);
3556  }
3557  else {
3558  hash = ary_make_hash(ary);
3559  if (RARRAY_LEN(ary) == (long)RHASH_SIZE(hash)) {
3560  return Qnil;
3561  }
3562  for (i=j=0; i<RARRAY_LEN(ary); i++) {
3563  st_data_t vv = (st_data_t)(v = rb_ary_elt(ary, i));
3564  if (st_delete(RHASH_TBL(hash), &vv, 0)) {
3565  rb_ary_store(ary, j++, v);
3566  }
3567  }
3568  ARY_SET_LEN(ary, j);
3569  }
3570  ary_recycle_hash(hash);
3571 
3572  return ary;
3573 }
3574 
3575 /*
3576  * call-seq:
3577  * ary.uniq -> new_ary
3578  * ary.uniq { |item| ... } -> new_ary
3579  *
3580  * Returns a new array by removing duplicate values in +self+. If a block
3581  * is given, it will use the return value of the block for comparison.
3582  *
3583  * a = [ "a", "a", "b", "b", "c" ]
3584  * a.uniq # => ["a", "b", "c"]
3585  *
3586  * b = [["student","sam"], ["student","george"], ["teacher","matz"]]
3587  * b.uniq { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
3588  *
3589  */
3590 
3591 static VALUE
3593 {
3594  VALUE hash, uniq, v;
3595  long i;
3596 
3597  if (RARRAY_LEN(ary) <= 1)
3598  return rb_ary_dup(ary);
3599  if (rb_block_given_p()) {
3600  hash = ary_make_hash_by(ary);
3601  uniq = ary_new(rb_obj_class(ary), RHASH_SIZE(hash));
3602  st_foreach(RHASH_TBL(hash), push_value, uniq);
3603  }
3604  else {
3605  hash = ary_make_hash(ary);
3606  uniq = ary_new(rb_obj_class(ary), RHASH_SIZE(hash));
3607  for (i=0; i<RARRAY_LEN(ary); i++) {
3608  st_data_t vv = (st_data_t)(v = rb_ary_elt(ary, i));
3609  if (st_delete(RHASH_TBL(hash), &vv, 0)) {
3610  rb_ary_push(uniq, v);
3611  }
3612  }
3613  }
3614  ary_recycle_hash(hash);
3615 
3616  return uniq;
3617 }
3618 
3619 /*
3620  * call-seq:
3621  * ary.compact! -> ary or nil
3622  *
3623  * Removes +nil+ elements from the array.
3624  * Returns +nil+ if no changes were made, otherwise returns
3625  * <i>ary</i>.
3626  *
3627  * [ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
3628  * [ "a", "b", "c" ].compact! #=> nil
3629  */
3630 
3631 static VALUE
3633 {
3634  VALUE *p, *t, *end;
3635  long n;
3636 
3637  rb_ary_modify(ary);
3638  p = t = RARRAY_PTR(ary);
3639  end = p + RARRAY_LEN(ary);
3640 
3641  while (t < end) {
3642  if (NIL_P(*t)) t++;
3643  else *p++ = *t++;
3644  }
3645  n = p - RARRAY_PTR(ary);
3646  if (RARRAY_LEN(ary) == n) {
3647  return Qnil;
3648  }
3649  ARY_SET_LEN(ary, n);
3650  if (n * 2 < ARY_CAPA(ary) && ARY_DEFAULT_SIZE * 2 < ARY_CAPA(ary)) {
3651  ary_resize_capa(ary, n * 2);
3652  }
3653 
3654  return ary;
3655 }
3656 
3657 /*
3658  * call-seq:
3659  * ary.compact -> new_ary
3660  *
3661  * Returns a copy of +self+ with all +nil+ elements removed.
3662  *
3663  * [ "a", nil, "b", nil, "c", nil ].compact
3664  * #=> [ "a", "b", "c" ]
3665  */
3666 
3667 static VALUE
3669 {
3670  ary = rb_ary_dup(ary);
3671  rb_ary_compact_bang(ary);
3672  return ary;
3673 }
3674 
3675 /*
3676  * call-seq:
3677  * ary.count -> int
3678  * ary.count(obj) -> int
3679  * ary.count { |item| block } -> int
3680  *
3681  * Returns the number of elements. If an argument is given, counts
3682  * the number of elements which equals to <i>obj</i>. If a block is
3683  * given, counts the number of elements yielding a true value.
3684  *
3685  * ary = [1, 2, 4, 2]
3686  * ary.count #=> 4
3687  * ary.count(2) #=> 2
3688  * ary.count{|x|x%2==0} #=> 3
3689  *
3690  */
3691 
3692 static VALUE
3693 rb_ary_count(int argc, VALUE *argv, VALUE ary)
3694 {
3695  long n = 0;
3696 
3697  if (argc == 0) {
3698  VALUE *p, *pend;
3699 
3700  if (!rb_block_given_p())
3701  return LONG2NUM(RARRAY_LEN(ary));
3702 
3703  for (p = RARRAY_PTR(ary), pend = p + RARRAY_LEN(ary); p < pend; p++) {
3704  if (RTEST(rb_yield(*p))) n++;
3705  }
3706  }
3707  else {
3708  VALUE obj, *p, *pend;
3709 
3710  rb_scan_args(argc, argv, "1", &obj);
3711  if (rb_block_given_p()) {
3712  rb_warn("given block not used");
3713  }
3714  for (p = RARRAY_PTR(ary), pend = p + RARRAY_LEN(ary); p < pend; p++) {
3715  if (rb_equal(*p, obj)) n++;
3716  }
3717  }
3718 
3719  return LONG2NUM(n);
3720 }
3721 
3722 static VALUE
3723 flatten(VALUE ary, int level, int *modified)
3724 {
3725  long i = 0;
3726  VALUE stack, result, tmp, elt;
3727  st_table *memo;
3728  st_data_t id;
3729 
3730  stack = ary_new(0, ARY_DEFAULT_SIZE);
3731  result = ary_new(0, RARRAY_LEN(ary));
3732  memo = st_init_numtable();
3733  st_insert(memo, (st_data_t)ary, (st_data_t)Qtrue);
3734  *modified = 0;
3735 
3736  while (1) {
3737  while (i < RARRAY_LEN(ary)) {
3738  elt = RARRAY_PTR(ary)[i++];
3739  tmp = rb_check_array_type(elt);
3740  if (RBASIC(result)->klass) {
3741  rb_raise(rb_eRuntimeError, "flatten reentered");
3742  }
3743  if (NIL_P(tmp) || (level >= 0 && RARRAY_LEN(stack) / 2 >= level)) {
3744  rb_ary_push(result, elt);
3745  }
3746  else {
3747  *modified = 1;
3748  id = (st_data_t)tmp;
3749  if (st_lookup(memo, id, 0)) {
3750  st_free_table(memo);
3751  rb_raise(rb_eArgError, "tried to flatten recursive array");
3752  }
3753  st_insert(memo, id, (st_data_t)Qtrue);
3754  rb_ary_push(stack, ary);
3755  rb_ary_push(stack, LONG2NUM(i));
3756  ary = tmp;
3757  i = 0;
3758  }
3759  }
3760  if (RARRAY_LEN(stack) == 0) {
3761  break;
3762  }
3763  id = (st_data_t)ary;
3764  st_delete(memo, &id, 0);
3765  tmp = rb_ary_pop(stack);
3766  i = NUM2LONG(tmp);
3767  ary = rb_ary_pop(stack);
3768  }
3769 
3770  st_free_table(memo);
3771 
3772  RBASIC(result)->klass = rb_class_of(ary);
3773  return result;
3774 }
3775 
3776 /*
3777  * call-seq:
3778  * ary.flatten! -> ary or nil
3779  * ary.flatten!(level) -> array or nil
3780  *
3781  * Flattens +self+ in place.
3782  * Returns <code>nil</code> if no modifications were made (i.e.,
3783  * <i>ary</i> contains no subarrays.) If the optional <i>level</i>
3784  * argument determines the level of recursion to flatten.
3785  *
3786  * a = [ 1, 2, [3, [4, 5] ] ]
3787  * a.flatten! #=> [1, 2, 3, 4, 5]
3788  * a.flatten! #=> nil
3789  * a #=> [1, 2, 3, 4, 5]
3790  * a = [ 1, 2, [3, [4, 5] ] ]
3791  * a.flatten!(1) #=> [1, 2, 3, [4, 5]]
3792  */
3793 
3794 static VALUE
3796 {
3797  int mod = 0, level = -1;
3798  VALUE result, lv;
3799 
3800  rb_scan_args(argc, argv, "01", &lv);
3801  rb_ary_modify_check(ary);
3802  if (!NIL_P(lv)) level = NUM2INT(lv);
3803  if (level == 0) return Qnil;
3804 
3805  result = flatten(ary, level, &mod);
3806  if (mod == 0) {
3807  ary_discard(result);
3808  return Qnil;
3809  }
3810  if (!(mod = ARY_EMBED_P(result))) rb_obj_freeze(result);
3811  rb_ary_replace(ary, result);
3812  if (mod) ARY_SET_EMBED_LEN(result, 0);
3813 
3814  return ary;
3815 }
3816 
3817 /*
3818  * call-seq:
3819  * ary.flatten -> new_ary
3820  * ary.flatten(level) -> new_ary
3821  *
3822  * Returns a new array that is a one-dimensional flattening of this
3823  * array (recursively). That is, for every element that is an array,
3824  * extract its elements into the new array. If the optional
3825  * <i>level</i> argument determines the level of recursion to flatten.
3826  *
3827  * s = [ 1, 2, 3 ] #=> [1, 2, 3]
3828  * t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
3829  * a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
3830  * a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3831  * a = [ 1, 2, [3, [4, 5] ] ]
3832  * a.flatten(1) #=> [1, 2, 3, [4, 5]]
3833  */
3834 
3835 static VALUE
3836 rb_ary_flatten(int argc, VALUE *argv, VALUE ary)
3837 {
3838  int mod = 0, level = -1;
3839  VALUE result, lv;
3840 
3841  rb_scan_args(argc, argv, "01", &lv);
3842  if (!NIL_P(lv)) level = NUM2INT(lv);
3843  if (level == 0) return ary_make_shared_copy(ary);
3844 
3845  result = flatten(ary, level, &mod);
3846  OBJ_INFECT(result, ary);
3847 
3848  return result;
3849 }
3850 
3851 #define OPTHASH_GIVEN_P(opts) \
3852  (argc > 0 && !NIL_P((opts) = rb_check_hash_type(argv[argc-1])) && (--argc, 1))
3854 
3855 #define RAND_UPTO(max) (long)(rb_random_real(randgen)*(max))
3856 
3857 /*
3858  * call-seq:
3859  * ary.shuffle! -> ary
3860  * ary.shuffle!(random: rng) -> ary
3861  *
3862  * Shuffles elements in +self+ in place.
3863  * If +rng+ is given, it will be used as the random number generator.
3864  */
3865 
3866 static VALUE
3868 {
3869  VALUE *ptr, opts, *snap_ptr, randgen = rb_cRandom;
3870  long i, snap_len;
3871 
3872  if (OPTHASH_GIVEN_P(opts)) {
3873  randgen = rb_hash_lookup2(opts, sym_random, randgen);
3874  }
3875  if (argc > 0) {
3876  rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
3877  }
3878  rb_ary_modify(ary);
3879  i = RARRAY_LEN(ary);
3880  ptr = RARRAY_PTR(ary);
3881  snap_len = i;
3882  snap_ptr = ptr;
3883  while (i) {
3884  long j = RAND_UPTO(i);
3885  VALUE tmp;
3886  if (snap_len != RARRAY_LEN(ary) || snap_ptr != RARRAY_PTR(ary)) {
3887  rb_raise(rb_eRuntimeError, "modified during shuffle");
3888  }
3889  tmp = ptr[--i];
3890  ptr[i] = ptr[j];
3891  ptr[j] = tmp;
3892  }
3893  return ary;
3894 }
3895 
3896 
3897 /*
3898  * call-seq:
3899  * ary.shuffle -> new_ary
3900  * ary.shuffle(random: rng) -> new_ary
3901  *
3902  * Returns a new array with elements of this array shuffled.
3903  *
3904  * a = [ 1, 2, 3 ] #=> [1, 2, 3]
3905  * a.shuffle #=> [2, 3, 1]
3906  *
3907  * If +rng+ is given, it will be used as the random number generator.
3908  *
3909  * a.shuffle(random: Random.new(1)) #=> [1, 3, 2]
3910  */
3911 
3912 static VALUE
3913 rb_ary_shuffle(int argc, VALUE *argv, VALUE ary)
3914 {
3915  ary = rb_ary_dup(ary);
3916  rb_ary_shuffle_bang(argc, argv, ary);
3917  return ary;
3918 }
3919 
3920 
3921 /*
3922  * call-seq:
3923  * ary.sample -> obj
3924  * ary.sample(random: rng) -> obj
3925  * ary.sample(n) -> new_ary
3926  * ary.sample(n, random: rng) -> new_ary
3927  *
3928  * Choose a random element or +n+ random elements from the array. The elements
3929  * are chosen by using random and unique indices into the array in order to
3930  * ensure that an element doesn't repeat itself unless the array already
3931  * contained duplicate elements. If the array is empty the first form returns
3932  * <code>nil</code> and the second form returns an empty array.
3933  *
3934  * If +rng+ is given, it will be used as the random number generator.
3935  */
3936 
3937 
3938 static VALUE
3939 rb_ary_sample(int argc, VALUE *argv, VALUE ary)
3940 {
3941  VALUE nv, result, *ptr;
3942  VALUE opts, randgen = rb_cRandom;
3943  long n, len, i, j, k, idx[10];
3944  double rnds[numberof(idx)];
3945 
3946  if (OPTHASH_GIVEN_P(opts)) {
3947  randgen = rb_hash_lookup2(opts, sym_random, randgen);
3948  }
3949  ptr = RARRAY_PTR(ary);
3950  len = RARRAY_LEN(ary);
3951  if (argc == 0) {
3952  if (len == 0) return Qnil;
3953  if (len == 1) {
3954  i = 0;
3955  }
3956  else {
3957  double x = rb_random_real(randgen);
3958  if ((len = RARRAY_LEN(ary)) == 0) return Qnil;
3959  i = (long)(x * len);
3960  }
3961  return RARRAY_PTR(ary)[i];
3962  }
3963  rb_scan_args(argc, argv, "1", &nv);
3964  n = NUM2LONG(nv);
3965  if (n < 0) rb_raise(rb_eArgError, "negative sample number");
3966  if (n > len) n = len;
3967  if (n <= numberof(idx)) {
3968  for (i = 0; i < n; ++i) {
3969  rnds[i] = rb_random_real(randgen);
3970  }
3971  }
3972  len = RARRAY_LEN(ary);
3973  ptr = RARRAY_PTR(ary);
3974  if (n > len) n = len;
3975  switch (n) {
3976  case 0:
3977  return rb_ary_new2(0);
3978  case 1:
3979  i = (long)(rnds[0] * len);
3980  return rb_ary_new4(1, &ptr[i]);
3981  case 2:
3982  i = (long)(rnds[0] * len);
3983  j = (long)(rnds[1] * (len-1));
3984  if (j >= i) j++;
3985  return rb_ary_new3(2, ptr[i], ptr[j]);
3986  case 3:
3987  i = (long)(rnds[0] * len);
3988  j = (long)(rnds[1] * (len-1));
3989  k = (long)(rnds[2] * (len-2));
3990  {
3991  long l = j, g = i;
3992  if (j >= i) l = i, g = ++j;
3993  if (k >= l && (++k >= g)) ++k;
3994  }
3995  return rb_ary_new3(3, ptr[i], ptr[j], ptr[k]);
3996  }
3997  if (n <= numberof(idx)) {
3998  VALUE *ptr_result;
3999  long sorted[numberof(idx)];
4000  sorted[0] = idx[0] = (long)(rnds[0] * len);
4001  for (i=1; i<n; i++) {
4002  k = (long)(rnds[i] * --len);
4003  for (j = 0; j < i; ++j) {
4004  if (k < sorted[j]) break;
4005  ++k;
4006  }
4007  memmove(&sorted[j+1], &sorted[j], sizeof(sorted[0])*(i-j));
4008  sorted[j] = idx[i] = k;
4009  }
4010  result = rb_ary_new2(n);
4011  ptr_result = RARRAY_PTR(result);
4012  for (i=0; i<n; i++) {
4013  ptr_result[i] = ptr[idx[i]];
4014  }
4015  }
4016  else {
4017  VALUE *ptr_result;
4018  result = rb_ary_new4(len, ptr);
4019  RBASIC(result)->klass = 0;
4020  ptr_result = RARRAY_PTR(result);
4021  RB_GC_GUARD(ary);
4022  for (i=0; i<n; i++) {
4023  j = RAND_UPTO(len-i) + i;
4024  nv = ptr_result[j];
4025  ptr_result[j] = ptr_result[i];
4026  ptr_result[i] = nv;
4027  }
4028  RBASIC(result)->klass = rb_cArray;
4029  }
4030  ARY_SET_LEN(result, n);
4031 
4032  return result;
4033 }
4034 
4035 
4036 /*
4037  * call-seq:
4038  * ary.cycle(n=nil) {|obj| block } -> nil
4039  * ary.cycle(n=nil) -> an_enumerator
4040  *
4041  * Calls <i>block</i> for each element repeatedly _n_ times or
4042  * forever if none or +nil+ is given. If a non-positive number is
4043  * given or the array is empty, does nothing. Returns +nil+ if the
4044  * loop has finished without getting interrupted.
4045  *
4046  * If no block is given, an enumerator is returned instead.
4047  *
4048  *
4049  * a = ["a", "b", "c"]
4050  * a.cycle {|x| puts x } # print, a, b, c, a, b, c,.. forever.
4051  * a.cycle(2) {|x| puts x } # print, a, b, c, a, b, c.
4052  *
4053  */
4054 
4055 static VALUE
4056 rb_ary_cycle(int argc, VALUE *argv, VALUE ary)
4057 {
4058  long n, i;
4059  VALUE nv = Qnil;
4060 
4061  rb_scan_args(argc, argv, "01", &nv);
4062 
4063  RETURN_ENUMERATOR(ary, argc, argv);
4064  if (NIL_P(nv)) {
4065  n = -1;
4066  }
4067  else {
4068  n = NUM2LONG(nv);
4069  if (n <= 0) return Qnil;
4070  }
4071 
4072  while (RARRAY_LEN(ary) > 0 && (n < 0 || 0 < n--)) {
4073  for (i=0; i<RARRAY_LEN(ary); i++) {
4074  rb_yield(RARRAY_PTR(ary)[i]);
4075  }
4076  }
4077  return Qnil;
4078 }
4079 
4080 #define tmpbuf(n, size) rb_str_tmp_new((n)*(size))
4081 #define tmpbuf_discard(s) (rb_str_resize((s), 0L), RBASIC(s)->klass = rb_cString)
4082 #define tmpary(n) rb_ary_tmp_new(n)
4083 #define tmpary_discard(a) (ary_discard(a), RBASIC(a)->klass = rb_cArray)
4084 
4085 /*
4086  * Recursively compute permutations of r elements of the set [0..n-1].
4087  * When we have a complete permutation of array indexes, copy the values
4088  * at those indexes into a new array and yield that array.
4089  *
4090  * n: the size of the set
4091  * r: the number of elements in each permutation
4092  * p: the array (of size r) that we're filling in
4093  * index: what index we're filling in now
4094  * used: an array of booleans: whether a given index is already used
4095  * values: the Ruby array that holds the actual values to permute
4096  */
4097 static void
4098 permute0(long n, long r, long *p, long index, char *used, VALUE values)
4099 {
4100  long i,j;
4101  for (i = 0; i < n; i++) {
4102  if (used[i] == 0) {
4103  p[index] = i;
4104  if (index < r-1) { /* if not done yet */
4105  used[i] = 1; /* mark index used */
4106  permute0(n, r, p, index+1, /* recurse */
4107  used, values);
4108  used[i] = 0; /* index unused */
4109  }
4110  else {
4111  /* We have a complete permutation of array indexes */
4112  /* Build a ruby array of the corresponding values */
4113  /* And yield it to the associated block */
4114  VALUE result = rb_ary_new2(r);
4115  VALUE *result_array = RARRAY_PTR(result);
4116  const VALUE *values_array = RARRAY_PTR(values);
4117 
4118  for (j = 0; j < r; j++) result_array[j] = values_array[p[j]];
4119  ARY_SET_LEN(result, r);
4120  rb_yield(result);
4121  if (RBASIC(values)->klass) {
4122  rb_raise(rb_eRuntimeError, "permute reentered");
4123  }
4124  }
4125  }
4126  }
4127 }
4128 
4129 /*
4130  * call-seq:
4131  * ary.permutation { |p| block } -> ary
4132  * ary.permutation -> an_enumerator
4133  * ary.permutation(n) { |p| block } -> ary
4134  * ary.permutation(n) -> an_enumerator
4135  *
4136  * When invoked with a block, yield all permutations of length <i>n</i>
4137  * of the elements of <i>ary</i>, then return the array itself.
4138  * If <i>n</i> is not specified, yield all permutations of all elements.
4139  * The implementation makes no guarantees about the order in which
4140  * the permutations are yielded.
4141  *
4142  * If no block is given, an enumerator is returned instead.
4143  *
4144  * Examples:
4145  *
4146  * a = [1, 2, 3]
4147  * a.permutation.to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
4148  * a.permutation(1).to_a #=> [[1],[2],[3]]
4149  * a.permutation(2).to_a #=> [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
4150  * a.permutation(3).to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
4151  * a.permutation(0).to_a #=> [[]] # one permutation of length 0
4152  * a.permutation(4).to_a #=> [] # no permutations of length 4
4153  */
4154 
4155 static VALUE
4157 {
4158  VALUE num;
4159  long r, n, i;
4160 
4161  n = RARRAY_LEN(ary); /* Array length */
4162  RETURN_ENUMERATOR(ary, argc, argv); /* Return enumerator if no block */
4163  rb_scan_args(argc, argv, "01", &num);
4164  r = NIL_P(num) ? n : NUM2LONG(num); /* Permutation size from argument */
4165 
4166  if (r < 0 || n < r) {
4167  /* no permutations: yield nothing */
4168  }
4169  else if (r == 0) { /* exactly one permutation: the zero-length array */
4170  rb_yield(rb_ary_new2(0));
4171  }
4172  else if (r == 1) { /* this is a special, easy case */
4173  for (i = 0; i < RARRAY_LEN(ary); i++) {
4174  rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
4175  }
4176  }
4177  else { /* this is the general case */
4178  volatile VALUE t0 = tmpbuf(n,sizeof(long));
4179  long *p = (long*)RSTRING_PTR(t0);
4180  volatile VALUE t1 = tmpbuf(n,sizeof(char));
4181  char *used = (char*)RSTRING_PTR(t1);
4182  VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
4183  RBASIC(ary0)->klass = 0;
4184 
4185  MEMZERO(used, char, n); /* initialize array */
4186 
4187  permute0(n, r, p, 0, used, ary0); /* compute and yield permutations */
4188  tmpbuf_discard(t0);
4189  tmpbuf_discard(t1);
4190  RBASIC(ary0)->klass = rb_cArray;
4191  }
4192  return ary;
4193 }
4194 
4195 /*
4196  * call-seq:
4197  * ary.combination(n) { |c| block } -> ary
4198  * ary.combination(n) -> an_enumerator
4199  *
4200  * When invoked with a block, yields all combinations of length <i>n</i>
4201  * of elements from <i>ary</i> and then returns <i>ary</i> itself.
4202  * The implementation makes no guarantees about the order in which
4203  * the combinations are yielded.
4204  *
4205  * If no block is given, an enumerator is returned instead.
4206  *
4207  * Examples:
4208  *
4209  * a = [1, 2, 3, 4]
4210  * a.combination(1).to_a #=> [[1],[2],[3],[4]]
4211  * a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
4212  * a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
4213  * a.combination(4).to_a #=> [[1,2,3,4]]
4214  * a.combination(0).to_a #=> [[]] # one combination of length 0
4215  * a.combination(5).to_a #=> [] # no combinations of length 5
4216  *
4217  */
4218 
4219 static VALUE
4221 {
4222  long n, i, len;
4223 
4224  n = NUM2LONG(num);
4225  RETURN_ENUMERATOR(ary, 1, &num);
4226  len = RARRAY_LEN(ary);
4227  if (n < 0 || len < n) {
4228  /* yield nothing */
4229  }
4230  else if (n == 0) {
4231  rb_yield(rb_ary_new2(0));
4232  }
4233  else if (n == 1) {
4234  for (i = 0; i < len; i++) {
4235  rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
4236  }
4237  }
4238  else {
4239  volatile VALUE t0 = tmpbuf(n+1, sizeof(long));
4240  long *stack = (long*)RSTRING_PTR(t0);
4241  volatile VALUE cc = tmpary(n);
4242  VALUE *chosen = RARRAY_PTR(cc);
4243  long lev = 0;
4244 
4245  MEMZERO(stack, long, n);
4246  stack[0] = -1;
4247  for (;;) {
4248  chosen[lev] = RARRAY_PTR(ary)[stack[lev+1]];
4249  for (lev++; lev < n; lev++) {
4250  chosen[lev] = RARRAY_PTR(ary)[stack[lev+1] = stack[lev]+1];
4251  }
4252  rb_yield(rb_ary_new4(n, chosen));
4253  if (RBASIC(t0)->klass) {
4254  rb_raise(rb_eRuntimeError, "combination reentered");
4255  }
4256  do {
4257  if (lev == 0) goto done;
4258  stack[lev--]++;
4259  } while (stack[lev+1]+n == len+lev+1);
4260  }
4261  done:
4262  tmpbuf_discard(t0);
4263  tmpary_discard(cc);
4264  }
4265  return ary;
4266 }
4267 
4268 /*
4269  * Recursively compute repeated permutations of r elements of the set
4270  * [0..n-1].
4271  * When we have a complete repeated permutation of array indexes, copy the
4272  * values at those indexes into a new array and yield that array.
4273  *
4274  * n: the size of the set
4275  * r: the number of elements in each permutation
4276  * p: the array (of size r) that we're filling in
4277  * index: what index we're filling in now
4278  * values: the Ruby array that holds the actual values to permute
4279  */
4280 static void
4281 rpermute0(long n, long r, long *p, long index, VALUE values)
4282 {
4283  long i, j;
4284  for (i = 0; i < n; i++) {
4285  p[index] = i;
4286  if (index < r-1) { /* if not done yet */
4287  rpermute0(n, r, p, index+1, values); /* recurse */
4288  }
4289  else {
4290  /* We have a complete permutation of array indexes */
4291  /* Build a ruby array of the corresponding values */
4292  /* And yield it to the associated block */
4293  VALUE result = rb_ary_new2(r);
4294  VALUE *result_array = RARRAY_PTR(result);
4295  const VALUE *values_array = RARRAY_PTR(values);
4296 
4297  for (j = 0; j < r; j++) result_array[j] = values_array[p[j]];
4298  ARY_SET_LEN(result, r);
4299  rb_yield(result);
4300  if (RBASIC(values)->klass) {
4301  rb_raise(rb_eRuntimeError, "repeated permute reentered");
4302  }
4303  }
4304  }
4305 }
4306 
4307 /*
4308  * call-seq:
4309  * ary.repeated_permutation(n) { |p| block } -> ary
4310  * ary.repeated_permutation(n) -> an_enumerator
4311  *
4312  * When invoked with a block, yield all repeated permutations of length
4313  * <i>n</i> of the elements of <i>ary</i>, then return the array itself.
4314  * The implementation makes no guarantees about the order in which
4315  * the repeated permutations are yielded.
4316  *
4317  * If no block is given, an enumerator is returned instead.
4318  *
4319  * Examples:
4320  *
4321  * a = [1, 2]
4322  * a.repeated_permutation(1).to_a #=> [[1], [2]]
4323  * a.repeated_permutation(2).to_a #=> [[1,1],[1,2],[2,1],[2,2]]
4324  * a.repeated_permutation(3).to_a #=> [[1,1,1],[1,1,2],[1,2,1],[1,2,2],
4325  * # [2,1,1],[2,1,2],[2,2,1],[2,2,2]]
4326  * a.repeated_permutation(0).to_a #=> [[]] # one permutation of length 0
4327  */
4328 
4329 static VALUE
4331 {
4332  long r, n, i;
4333 
4334  n = RARRAY_LEN(ary); /* Array length */
4335  RETURN_ENUMERATOR(ary, 1, &num); /* Return enumerator if no block */
4336  r = NUM2LONG(num); /* Permutation size from argument */
4337 
4338  if (r < 0) {
4339  /* no permutations: yield nothing */
4340  }
4341  else if (r == 0) { /* exactly one permutation: the zero-length array */
4342  rb_yield(rb_ary_new2(0));
4343  }
4344  else if (r == 1) { /* this is a special, easy case */
4345  for (i = 0; i < RARRAY_LEN(ary); i++) {
4346  rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
4347  }
4348  }
4349  else { /* this is the general case */
4350  volatile VALUE t0 = tmpbuf(r, sizeof(long));
4351  long *p = (long*)RSTRING_PTR(t0);
4352  VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
4353  RBASIC(ary0)->klass = 0;
4354 
4355  rpermute0(n, r, p, 0, ary0); /* compute and yield repeated permutations */
4356  tmpbuf_discard(t0);
4357  RBASIC(ary0)->klass = rb_cArray;
4358  }
4359  return ary;
4360 }
4361 
4362 static void
4363 rcombinate0(long n, long r, long *p, long index, long rest, VALUE values)
4364 {
4365  long j;
4366  if (rest > 0) {
4367  for (; index < n; ++index) {
4368  p[r-rest] = index;
4369  rcombinate0(n, r, p, index, rest-1, values);
4370  }
4371  }
4372  else {
4373  VALUE result = rb_ary_new2(r);
4374  VALUE *result_array = RARRAY_PTR(result);
4375  const VALUE *values_array = RARRAY_PTR(values);
4376 
4377  for (j = 0; j < r; ++j) result_array[j] = values_array[p[j]];
4378  ARY_SET_LEN(result, r);
4379  rb_yield(result);
4380  if (RBASIC(values)->klass) {
4381  rb_raise(rb_eRuntimeError, "repeated combination reentered");
4382  }
4383  }
4384 }
4385 
4386 /*
4387  * call-seq:
4388  * ary.repeated_combination(n) { |c| block } -> ary
4389  * ary.repeated_combination(n) -> an_enumerator
4390  *
4391  * When invoked with a block, yields all repeated combinations of
4392  * length <i>n</i> of elements from <i>ary</i> and then returns
4393  * <i>ary</i> itself.
4394  * The implementation makes no guarantees about the order in which
4395  * the repeated combinations are yielded.
4396  *
4397  * If no block is given, an enumerator is returned instead.
4398  *
4399  * Examples:
4400  *
4401  * a = [1, 2, 3]
4402  * a.repeated_combination(1).to_a #=> [[1], [2], [3]]
4403  * a.repeated_combination(2).to_a #=> [[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]]
4404  * a.repeated_combination(3).to_a #=> [[1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3],
4405  * # [1,3,3],[2,2,2],[2,2,3],[2,3,3],[3,3,3]]
4406  * 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],
4407  * # [1,1,3,3],[1,2,2,2],[1,2,2,3],[1,2,3,3],[1,3,3,3],
4408  * # [2,2,2,2],[2,2,2,3],[2,2,3,3],[2,3,3,3],[3,3,3,3]]
4409  * a.repeated_combination(0).to_a #=> [[]] # one combination of length 0
4410  *
4411  */
4412 
4413 static VALUE
4415 {
4416  long n, i, len;
4417 
4418  n = NUM2LONG(num); /* Combination size from argument */
4419  RETURN_ENUMERATOR(ary, 1, &num); /* Return enumerator if no block */
4420  len = RARRAY_LEN(ary);
4421  if (n < 0) {
4422  /* yield nothing */
4423  }
4424  else if (n == 0) {
4425  rb_yield(rb_ary_new2(0));
4426  }
4427  else if (n == 1) {
4428  for (i = 0; i < len; i++) {
4429  rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
4430  }
4431  }
4432  else if (len == 0) {
4433  /* yield nothing */
4434  }
4435  else {
4436  volatile VALUE t0 = tmpbuf(n, sizeof(long));
4437  long *p = (long*)RSTRING_PTR(t0);
4438  VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
4439  RBASIC(ary0)->klass = 0;
4440 
4441  rcombinate0(len, n, p, 0, n, ary0); /* compute and yield repeated combinations */
4442  tmpbuf_discard(t0);
4443  RBASIC(ary0)->klass = rb_cArray;
4444  }
4445  return ary;
4446 }
4447 
4448 /*
4449  * call-seq:
4450  * ary.product(other_ary, ...) -> new_ary
4451  * ary.product(other_ary, ...) { |p| block } -> ary
4452  *
4453  * Returns an array of all combinations of elements from all arrays.
4454  * The length of the returned array is the product of the length
4455  * of +self+ and the argument arrays.
4456  * If given a block, <i>product</i> will yield all combinations
4457  * and return +self+ instead.
4458  *
4459  *
4460  * [1,2,3].product([4,5]) #=> [[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]
4461  * [1,2].product([1,2]) #=> [[1,1],[1,2],[2,1],[2,2]]
4462  * [1,2].product([3,4],[5,6]) #=> [[1,3,5],[1,3,6],[1,4,5],[1,4,6],
4463  * # [2,3,5],[2,3,6],[2,4,5],[2,4,6]]
4464  * [1,2].product() #=> [[1],[2]]
4465  * [1,2].product([]) #=> []
4466  */
4467 
4468 static VALUE
4469 rb_ary_product(int argc, VALUE *argv, VALUE ary)
4470 {
4471  int n = argc+1; /* How many arrays we're operating on */
4472  volatile VALUE t0 = tmpary(n);
4473  volatile VALUE t1 = tmpbuf(n, sizeof(int));
4474  VALUE *arrays = RARRAY_PTR(t0); /* The arrays we're computing the product of */
4475  int *counters = (int*)RSTRING_PTR(t1); /* The current position in each one */
4476  VALUE result = Qnil; /* The array we'll be returning, when no block given */
4477  long i,j;
4478  long resultlen = 1;
4479 
4480  RBASIC(t0)->klass = 0;
4481  RBASIC(t1)->klass = 0;
4482 
4483  /* initialize the arrays of arrays */
4484  ARY_SET_LEN(t0, n);
4485  arrays[0] = ary;
4486  for (i = 1; i < n; i++) arrays[i] = Qnil;
4487  for (i = 1; i < n; i++) arrays[i] = to_ary(argv[i-1]);
4488 
4489  /* initialize the counters for the arrays */
4490  for (i = 0; i < n; i++) counters[i] = 0;
4491 
4492  /* Otherwise, allocate and fill in an array of results */
4493  if (rb_block_given_p()) {
4494  /* Make defensive copies of arrays; exit if any is empty */
4495  for (i = 0; i < n; i++) {
4496  if (RARRAY_LEN(arrays[i]) == 0) goto done;
4497  arrays[i] = ary_make_shared_copy(arrays[i]);
4498  }
4499  }
4500  else {
4501  /* Compute the length of the result array; return [] if any is empty */
4502  for (i = 0; i < n; i++) {
4503  long k = RARRAY_LEN(arrays[i]), l = resultlen;
4504  if (k == 0) {
4505  result = rb_ary_new2(0);
4506  goto done;
4507  }
4508  resultlen *= k;
4509  if (resultlen < k || resultlen < l || resultlen / k != l) {
4510  rb_raise(rb_eRangeError, "too big to product");
4511  }
4512  }
4513  result = rb_ary_new2(resultlen);
4514  }
4515  for (;;) {
4516  int m;
4517  /* fill in one subarray */
4518  VALUE subarray = rb_ary_new2(n);
4519  for (j = 0; j < n; j++) {
4520  rb_ary_push(subarray, rb_ary_entry(arrays[j], counters[j]));
4521  }
4522 
4523  /* put it on the result array */
4524  if(NIL_P(result)) {
4525  FL_SET(t0, FL_USER5);
4526  rb_yield(subarray);
4527  if (! FL_TEST(t0, FL_USER5)) {
4528  rb_raise(rb_eRuntimeError, "product reentered");
4529  }
4530  else {
4531  FL_UNSET(t0, FL_USER5);
4532  }
4533  }
4534  else {
4535  rb_ary_push(result, subarray);
4536  }
4537 
4538  /*
4539  * Increment the last counter. If it overflows, reset to 0
4540  * and increment the one before it.
4541  */
4542  m = n-1;
4543  counters[m]++;
4544  while (counters[m] == RARRAY_LEN(arrays[m])) {
4545  counters[m] = 0;
4546  /* If the first counter overflows, we are done */
4547  if (--m < 0) goto done;
4548  counters[m]++;
4549  }
4550  }
4551 done:
4552  tmpary_discard(t0);
4553  tmpbuf_discard(t1);
4554 
4555  return NIL_P(result) ? ary : result;
4556 }
4557 
4558 /*
4559  * call-seq:
4560  * ary.take(n) -> new_ary
4561  *
4562  * Returns first n elements from <i>ary</i>.
4563  *
4564  * a = [1, 2, 3, 4, 5, 0]
4565  * a.take(3) #=> [1, 2, 3]
4566  *
4567  */
4568 
4569 static VALUE
4571 {
4572  long len = NUM2LONG(n);
4573  if (len < 0) {
4574  rb_raise(rb_eArgError, "attempt to take negative size");
4575  }
4576  return rb_ary_subseq(obj, 0, len);
4577 }
4578 
4579 /*
4580  * call-seq:
4581  * ary.take_while {|arr| block } -> new_ary
4582  * ary.take_while -> an_enumerator
4583  *
4584  * Passes elements to the block until the block returns +nil+ or +false+,
4585  * then stops iterating and returns an array of all prior elements.
4586  *
4587  * If no block is given, an enumerator is returned instead.
4588  *
4589  * a = [1, 2, 3, 4, 5, 0]
4590  * a.take_while {|i| i < 3 } #=> [1, 2]
4591  *
4592  */
4593 
4594 static VALUE
4596 {
4597  long i;
4598 
4599  RETURN_ENUMERATOR(ary, 0, 0);
4600  for (i = 0; i < RARRAY_LEN(ary); i++) {
4601  if (!RTEST(rb_yield(RARRAY_PTR(ary)[i]))) break;
4602  }
4603  return rb_ary_take(ary, LONG2FIX(i));
4604 }
4605 
4606 /*
4607  * call-seq:
4608  * ary.drop(n) -> new_ary
4609  *
4610  * Drops first n elements from +ary+ and returns the rest of
4611  * the elements in an array.
4612  *
4613  * a = [1, 2, 3, 4, 5, 0]
4614  * a.drop(3) #=> [4, 5, 0]
4615  *
4616  */
4617 
4618 static VALUE
4620 {
4621  VALUE result;
4622  long pos = NUM2LONG(n);
4623  if (pos < 0) {
4624  rb_raise(rb_eArgError, "attempt to drop negative size");
4625  }
4626 
4627  result = rb_ary_subseq(ary, pos, RARRAY_LEN(ary));
4628  if (result == Qnil) result = rb_ary_new();
4629  return result;
4630 }
4631 
4632 /*
4633  * call-seq:
4634  * ary.drop_while {|arr| block } -> new_ary
4635  * ary.drop_while -> an_enumerator
4636  *
4637  * Drops elements up to, but not including, the first element for
4638  * which the block returns +nil+ or +false+ and returns an array
4639  * containing the remaining elements.
4640  *
4641  * If no block is given, an enumerator is returned instead.
4642  *
4643  * a = [1, 2, 3, 4, 5, 0]
4644  * a.drop_while {|i| i < 3 } #=> [3, 4, 5, 0]
4645  *
4646  */
4647 
4648 static VALUE
4650 {
4651  long i;
4652 
4653  RETURN_ENUMERATOR(ary, 0, 0);
4654  for (i = 0; i < RARRAY_LEN(ary); i++) {
4655  if (!RTEST(rb_yield(RARRAY_PTR(ary)[i]))) break;
4656  }
4657  return rb_ary_drop(ary, LONG2FIX(i));
4658 }
4659 
4660 
4661 
4662 /* Arrays are ordered, integer-indexed collections of any object.
4663  * Array indexing starts at 0, as in C or Java. A negative index is
4664  * assumed to be relative to the end of the array---that is, an index of -1
4665  * indicates the last element of the array, -2 is the next to last
4666  * element in the array, and so on.
4667  */
4668 
4669 void
4671 {
4672 #undef rb_intern
4673 #define rb_intern(str) rb_intern_const(str)
4674 
4675  rb_cArray = rb_define_class("Array", rb_cObject);
4677 
4681  rb_define_method(rb_cArray, "initialize", rb_ary_initialize, -1);
4682  rb_define_method(rb_cArray, "initialize_copy", rb_ary_replace, 1);
4683 
4684  rb_define_method(rb_cArray, "inspect", rb_ary_inspect, 0);
4685  rb_define_alias(rb_cArray, "to_s", "inspect");
4686  rb_define_method(rb_cArray, "to_a", rb_ary_to_a, 0);
4688  rb_define_method(rb_cArray, "frozen?", rb_ary_frozen_p, 0);
4689 
4691  rb_define_method(rb_cArray, "eql?", rb_ary_eql, 1);
4692  rb_define_method(rb_cArray, "hash", rb_ary_hash, 0);
4693 
4695  rb_define_method(rb_cArray, "[]=", rb_ary_aset, -1);
4697  rb_define_method(rb_cArray, "fetch", rb_ary_fetch, -1);
4698  rb_define_method(rb_cArray, "first", rb_ary_first, -1);
4699  rb_define_method(rb_cArray, "last", rb_ary_last, -1);
4700  rb_define_method(rb_cArray, "concat", rb_ary_concat, 1);
4704  rb_define_method(rb_cArray, "shift", rb_ary_shift_m, -1);
4705  rb_define_method(rb_cArray, "unshift", rb_ary_unshift_m, -1);
4706  rb_define_method(rb_cArray, "insert", rb_ary_insert, -1);
4707  rb_define_method(rb_cArray, "each", rb_ary_each, 0);
4708  rb_define_method(rb_cArray, "each_index", rb_ary_each_index, 0);
4709  rb_define_method(rb_cArray, "reverse_each", rb_ary_reverse_each, 0);
4710  rb_define_method(rb_cArray, "length", rb_ary_length, 0);
4711  rb_define_alias(rb_cArray, "size", "length");
4712  rb_define_method(rb_cArray, "empty?", rb_ary_empty_p, 0);
4713  rb_define_method(rb_cArray, "find_index", rb_ary_index, -1);
4714  rb_define_method(rb_cArray, "index", rb_ary_index, -1);
4715  rb_define_method(rb_cArray, "rindex", rb_ary_rindex, -1);
4719  rb_define_method(rb_cArray, "rotate", rb_ary_rotate_m, -1);
4721  rb_define_method(rb_cArray, "sort", rb_ary_sort, 0);
4724  rb_define_method(rb_cArray, "collect", rb_ary_collect, 0);
4728  rb_define_method(rb_cArray, "select", rb_ary_select, 0);
4730  rb_define_method(rb_cArray, "keep_if", rb_ary_keep_if, 0);
4731  rb_define_method(rb_cArray, "values_at", rb_ary_values_at, -1);
4732  rb_define_method(rb_cArray, "delete", rb_ary_delete, 1);
4733  rb_define_method(rb_cArray, "delete_at", rb_ary_delete_at_m, 1);
4734  rb_define_method(rb_cArray, "delete_if", rb_ary_delete_if, 0);
4735  rb_define_method(rb_cArray, "reject", rb_ary_reject, 0);
4737  rb_define_method(rb_cArray, "zip", rb_ary_zip, -1);
4738  rb_define_method(rb_cArray, "transpose", rb_ary_transpose, 0);
4739  rb_define_method(rb_cArray, "replace", rb_ary_replace, 1);
4740  rb_define_method(rb_cArray, "clear", rb_ary_clear, 0);
4741  rb_define_method(rb_cArray, "fill", rb_ary_fill, -1);
4742  rb_define_method(rb_cArray, "include?", rb_ary_includes, 1);
4744 
4745  rb_define_method(rb_cArray, "slice", rb_ary_aref, -1);
4747 
4748  rb_define_method(rb_cArray, "assoc", rb_ary_assoc, 1);
4749  rb_define_method(rb_cArray, "rassoc", rb_ary_rassoc, 1);
4750 
4753 
4757 
4758  rb_define_method(rb_cArray, "uniq", rb_ary_uniq, 0);
4760  rb_define_method(rb_cArray, "compact", rb_ary_compact, 0);
4762  rb_define_method(rb_cArray, "flatten", rb_ary_flatten, -1);
4764  rb_define_method(rb_cArray, "count", rb_ary_count, -1);
4766  rb_define_method(rb_cArray, "shuffle", rb_ary_shuffle, -1);
4767  rb_define_method(rb_cArray, "sample", rb_ary_sample, -1);
4768  rb_define_method(rb_cArray, "cycle", rb_ary_cycle, -1);
4769  rb_define_method(rb_cArray, "permutation", rb_ary_permutation, -1);
4770  rb_define_method(rb_cArray, "combination", rb_ary_combination, 1);
4771  rb_define_method(rb_cArray, "repeated_permutation", rb_ary_repeated_permutation, 1);
4772  rb_define_method(rb_cArray, "repeated_combination", rb_ary_repeated_combination, 1);
4773  rb_define_method(rb_cArray, "product", rb_ary_product, -1);
4774 
4775  rb_define_method(rb_cArray, "take", rb_ary_take, 1);
4776  rb_define_method(rb_cArray, "take_while", rb_ary_take_while, 0);
4777  rb_define_method(rb_cArray, "drop", rb_ary_drop, 1);
4778  rb_define_method(rb_cArray, "drop_while", rb_ary_drop_while, 0);
4779 
4780  id_cmp = rb_intern("<=>");
4781  sym_random = ID2SYM(rb_intern("random"));
4782 }
4783