Ruby  2.0.0p576(2014-09-19revision47628)
array.c
Go to the documentation of this file.
00001 /**********************************************************************
00002 
00003   array.c -
00004 
00005   $Author: usa $
00006   created at: Fri Aug  6 09:46:12 JST 1993
00007 
00008   Copyright (C) 1993-2007 Yukihiro Matsumoto
00009   Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
00010   Copyright (C) 2000  Information-technology Promotion Agency, Japan
00011 
00012 **********************************************************************/
00013 
00014 #include "ruby/ruby.h"
00015 #include "ruby/util.h"
00016 #include "ruby/st.h"
00017 #include "ruby/encoding.h"
00018 #include "internal.h"
00019 #include "probes.h"
00020 #include "id.h"
00021 
00022 #ifndef ARRAY_DEBUG
00023 # define NDEBUG
00024 #endif
00025 #include <assert.h>
00026 
00027 #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
00028 
00029 VALUE rb_cArray;
00030 
00031 static ID id_cmp, id_div, id_power;
00032 
00033 #define ARY_DEFAULT_SIZE 16
00034 #define ARY_MAX_SIZE (LONG_MAX / (int)sizeof(VALUE))
00035 
00036 void
00037 rb_mem_clear(register VALUE *mem, register long size)
00038 {
00039     while (size--) {
00040         *mem++ = Qnil;
00041     }
00042 }
00043 
00044 static inline void
00045 memfill(register VALUE *mem, register long size, register VALUE val)
00046 {
00047     while (size--) {
00048         *mem++ = val;
00049     }
00050 }
00051 
00052 # define ARY_SHARED_P(ary) \
00053     (assert(!FL_TEST((ary), ELTS_SHARED) || !FL_TEST((ary), RARRAY_EMBED_FLAG)), \
00054      FL_TEST((ary),ELTS_SHARED)!=0)
00055 # define ARY_EMBED_P(ary) \
00056     (assert(!FL_TEST((ary), ELTS_SHARED) || !FL_TEST((ary), RARRAY_EMBED_FLAG)), \
00057      FL_TEST((ary), RARRAY_EMBED_FLAG)!=0)
00058 
00059 #define ARY_HEAP_PTR(a) (assert(!ARY_EMBED_P(a)), RARRAY(a)->as.heap.ptr)
00060 #define ARY_HEAP_LEN(a) (assert(!ARY_EMBED_P(a)), RARRAY(a)->as.heap.len)
00061 #define ARY_EMBED_PTR(a) (assert(ARY_EMBED_P(a)), RARRAY(a)->as.ary)
00062 #define ARY_EMBED_LEN(a) \
00063     (assert(ARY_EMBED_P(a)), \
00064      (long)((RBASIC(a)->flags >> RARRAY_EMBED_LEN_SHIFT) & \
00065          (RARRAY_EMBED_LEN_MASK >> RARRAY_EMBED_LEN_SHIFT)))
00066 
00067 #define ARY_OWNS_HEAP_P(a) (!FL_TEST((a), ELTS_SHARED|RARRAY_EMBED_FLAG))
00068 #define FL_SET_EMBED(a) do { \
00069     assert(!ARY_SHARED_P(a)); \
00070     FL_SET((a), RARRAY_EMBED_FLAG); \
00071 } while (0)
00072 #define FL_UNSET_EMBED(ary) FL_UNSET((ary), RARRAY_EMBED_FLAG|RARRAY_EMBED_LEN_MASK)
00073 #define FL_SET_SHARED(ary) do { \
00074     assert(!ARY_EMBED_P(ary)); \
00075     FL_SET((ary), ELTS_SHARED); \
00076 } while (0)
00077 #define FL_UNSET_SHARED(ary) FL_UNSET((ary), ELTS_SHARED)
00078 
00079 #define ARY_SET_PTR(ary, p) do { \
00080     assert(!ARY_EMBED_P(ary)); \
00081     assert(!OBJ_FROZEN(ary)); \
00082     RARRAY(ary)->as.heap.ptr = (p); \
00083 } while (0)
00084 #define ARY_SET_EMBED_LEN(ary, n) do { \
00085     long tmp_n = (n); \
00086     assert(ARY_EMBED_P(ary)); \
00087     assert(!OBJ_FROZEN(ary)); \
00088     RBASIC(ary)->flags &= ~RARRAY_EMBED_LEN_MASK; \
00089     RBASIC(ary)->flags |= (tmp_n) << RARRAY_EMBED_LEN_SHIFT; \
00090 } while (0)
00091 #define ARY_SET_HEAP_LEN(ary, n) do { \
00092     assert(!ARY_EMBED_P(ary)); \
00093     RARRAY(ary)->as.heap.len = (n); \
00094 } while (0)
00095 #define ARY_SET_LEN(ary, n) do { \
00096     if (ARY_EMBED_P(ary)) { \
00097         ARY_SET_EMBED_LEN((ary), (n)); \
00098     } \
00099     else { \
00100         ARY_SET_HEAP_LEN((ary), (n)); \
00101     } \
00102     assert(RARRAY_LEN(ary) == (n)); \
00103 } while (0)
00104 #define ARY_INCREASE_PTR(ary, n) do  { \
00105     assert(!ARY_EMBED_P(ary)); \
00106     assert(!OBJ_FROZEN(ary)); \
00107     RARRAY(ary)->as.heap.ptr += (n); \
00108 } while (0)
00109 #define ARY_INCREASE_LEN(ary, n) do  { \
00110     assert(!OBJ_FROZEN(ary)); \
00111     if (ARY_EMBED_P(ary)) { \
00112         ARY_SET_EMBED_LEN((ary), RARRAY_LEN(ary)+(n)); \
00113     } \
00114     else { \
00115         RARRAY(ary)->as.heap.len += (n); \
00116     } \
00117 } while (0)
00118 
00119 #define ARY_CAPA(ary) (ARY_EMBED_P(ary) ? RARRAY_EMBED_LEN_MAX : \
00120                        ARY_SHARED_ROOT_P(ary) ? RARRAY_LEN(ary) : RARRAY(ary)->as.heap.aux.capa)
00121 #define ARY_SET_CAPA(ary, n) do { \
00122     assert(!ARY_EMBED_P(ary)); \
00123     assert(!ARY_SHARED_P(ary)); \
00124     assert(!OBJ_FROZEN(ary)); \
00125     RARRAY(ary)->as.heap.aux.capa = (n); \
00126 } while (0)
00127 
00128 #define ARY_SHARED(ary) (assert(ARY_SHARED_P(ary)), RARRAY(ary)->as.heap.aux.shared)
00129 #define ARY_SET_SHARED(ary, value) do { \
00130     assert(!ARY_EMBED_P(ary)); \
00131     assert(ARY_SHARED_P(ary)); \
00132     assert(ARY_SHARED_ROOT_P(value)); \
00133     RARRAY(ary)->as.heap.aux.shared = (value); \
00134 } while (0)
00135 #define RARRAY_SHARED_ROOT_FLAG FL_USER5
00136 #define ARY_SHARED_ROOT_P(ary) (FL_TEST((ary), RARRAY_SHARED_ROOT_FLAG))
00137 #define ARY_SHARED_NUM(ary) \
00138     (assert(ARY_SHARED_ROOT_P(ary)), RARRAY(ary)->as.heap.aux.capa)
00139 #define ARY_SET_SHARED_NUM(ary, value) do { \
00140     assert(ARY_SHARED_ROOT_P(ary)); \
00141     RARRAY(ary)->as.heap.aux.capa = (value); \
00142 } while (0)
00143 #define FL_SET_SHARED_ROOT(ary) do { \
00144     assert(!ARY_EMBED_P(ary)); \
00145     FL_SET((ary), RARRAY_SHARED_ROOT_FLAG); \
00146 } while (0)
00147 
00148 static void
00149 ary_resize_capa(VALUE ary, long capacity)
00150 {
00151     assert(RARRAY_LEN(ary) <= capacity);
00152     assert(!OBJ_FROZEN(ary));
00153     assert(!ARY_SHARED_P(ary));
00154     if (capacity > RARRAY_EMBED_LEN_MAX) {
00155         if (ARY_EMBED_P(ary)) {
00156             long len = ARY_EMBED_LEN(ary);
00157             VALUE *ptr = ALLOC_N(VALUE, (capacity));
00158             MEMCPY(ptr, ARY_EMBED_PTR(ary), VALUE, len);
00159             FL_UNSET_EMBED(ary);
00160             ARY_SET_PTR(ary, ptr);
00161             ARY_SET_HEAP_LEN(ary, len);
00162         }
00163         else {
00164             REALLOC_N(RARRAY(ary)->as.heap.ptr, VALUE, (capacity));
00165         }
00166         ARY_SET_CAPA(ary, (capacity));
00167     }
00168     else {
00169         if (!ARY_EMBED_P(ary)) {
00170             long len = RARRAY_LEN(ary);
00171             VALUE *ptr = RARRAY_PTR(ary);
00172             if (len > capacity) len = capacity;
00173             MEMCPY(RARRAY(ary)->as.ary, ptr, VALUE, len);
00174             FL_SET_EMBED(ary);
00175             ARY_SET_LEN(ary, len);
00176             xfree(ptr);
00177         }
00178     }
00179 }
00180 
00181 static void
00182 ary_double_capa(VALUE ary, long min)
00183 {
00184     long new_capa = ARY_CAPA(ary) / 2;
00185 
00186     if (new_capa < ARY_DEFAULT_SIZE) {
00187         new_capa = ARY_DEFAULT_SIZE;
00188     }
00189     if (new_capa >= ARY_MAX_SIZE - min) {
00190         new_capa = (ARY_MAX_SIZE - min) / 2;
00191     }
00192     new_capa += min;
00193     ary_resize_capa(ary, new_capa);
00194 }
00195 
00196 static void
00197 rb_ary_decrement_share(VALUE shared)
00198 {
00199     if (shared) {
00200         long num = ARY_SHARED_NUM(shared) - 1;
00201         if (num == 0) {
00202             rb_ary_free(shared);
00203             rb_gc_force_recycle(shared);
00204         }
00205         else if (num > 0) {
00206             ARY_SET_SHARED_NUM(shared, num);
00207         }
00208     }
00209 }
00210 
00211 static void
00212 rb_ary_unshare(VALUE ary)
00213 {
00214     VALUE shared = RARRAY(ary)->as.heap.aux.shared;
00215     rb_ary_decrement_share(shared);
00216     FL_UNSET_SHARED(ary);
00217 }
00218 
00219 static inline void
00220 rb_ary_unshare_safe(VALUE ary)
00221 {
00222     if (ARY_SHARED_P(ary) && !ARY_EMBED_P(ary)) {
00223         rb_ary_unshare(ary);
00224     }
00225 }
00226 
00227 static VALUE
00228 rb_ary_increment_share(VALUE shared)
00229 {
00230     long num = ARY_SHARED_NUM(shared);
00231     if (num >= 0) {
00232         ARY_SET_SHARED_NUM(shared, num + 1);
00233     }
00234     return shared;
00235 }
00236 
00237 static void
00238 rb_ary_set_shared(VALUE ary, VALUE shared)
00239 {
00240     rb_ary_increment_share(shared);
00241     FL_SET_SHARED(ary);
00242     ARY_SET_SHARED(ary, shared);
00243 }
00244 
00245 static inline void
00246 rb_ary_modify_check(VALUE ary)
00247 {
00248     rb_check_frozen(ary);
00249     if (!OBJ_UNTRUSTED(ary) && rb_safe_level() >= 4)
00250         rb_raise(rb_eSecurityError, "Insecure: can't modify array");
00251 }
00252 
00253 void
00254 rb_ary_modify(VALUE ary)
00255 {
00256     rb_ary_modify_check(ary);
00257     if (ARY_SHARED_P(ary)) {
00258         long len = RARRAY_LEN(ary);
00259         VALUE shared = ARY_SHARED(ary);
00260         if (len <= RARRAY_EMBED_LEN_MAX) {
00261             VALUE *ptr = ARY_HEAP_PTR(ary);
00262             FL_UNSET_SHARED(ary);
00263             FL_SET_EMBED(ary);
00264             MEMCPY(ARY_EMBED_PTR(ary), ptr, VALUE, len);
00265             rb_ary_decrement_share(shared);
00266             ARY_SET_EMBED_LEN(ary, len);
00267         }
00268         else if (ARY_SHARED_NUM(shared) == 1 && len > (RARRAY_LEN(shared)>>1)) {
00269             long shift = RARRAY_PTR(ary) - RARRAY_PTR(shared);
00270             FL_UNSET_SHARED(ary);
00271             ARY_SET_PTR(ary, RARRAY_PTR(shared));
00272             ARY_SET_CAPA(ary, RARRAY_LEN(shared));
00273             MEMMOVE(RARRAY_PTR(ary), RARRAY_PTR(ary)+shift, VALUE, len);
00274             FL_SET_EMBED(shared);
00275             rb_ary_decrement_share(shared);
00276         }
00277         else {
00278             VALUE *ptr = ALLOC_N(VALUE, len);
00279             MEMCPY(ptr, RARRAY_PTR(ary), VALUE, len);
00280             rb_ary_unshare(ary);
00281             ARY_SET_CAPA(ary, len);
00282             ARY_SET_PTR(ary, ptr);
00283         }
00284     }
00285 }
00286 
00287 static void
00288 ary_ensure_room_for_push(VALUE ary, long add_len)
00289 {
00290     long new_len = RARRAY_LEN(ary) + add_len;
00291     long capa;
00292 
00293     if (ARY_SHARED_P(ary)) {
00294         if (new_len > RARRAY_EMBED_LEN_MAX) {
00295             VALUE shared = ARY_SHARED(ary);
00296             if (ARY_SHARED_NUM(shared) == 1) {
00297                 if (RARRAY_PTR(ary) - RARRAY_PTR(shared) + new_len <= RARRAY_LEN(shared)) {
00298                     rb_ary_modify_check(ary);
00299                 }
00300                 else {
00301                     /* if array is shared, than it is likely it participate in push/shift pattern */
00302                     rb_ary_modify(ary);
00303                     capa = ARY_CAPA(ary);
00304                     if (new_len > capa - (capa >> 6)) {
00305                         ary_double_capa(ary, new_len);
00306                     }
00307                 }
00308                 return;
00309             }
00310         }
00311     }
00312     rb_ary_modify(ary);
00313     capa = ARY_CAPA(ary);
00314     if (new_len > capa) {
00315         ary_double_capa(ary, new_len);
00316     }
00317 }
00318 
00319 /*
00320  *  call-seq:
00321  *      ary.freeze -> ary
00322  *
00323  *  Calls Object#freeze on +ary+ to prevent any further
00324  *  modification. A RuntimeError will be raised if a modification
00325  *  attempt is made.
00326  *
00327  */
00328 
00329 VALUE
00330 rb_ary_freeze(VALUE ary)
00331 {
00332     return rb_obj_freeze(ary);
00333 }
00334 
00335 /*
00336  *  call-seq:
00337  *     ary.frozen?  -> true or false
00338  *
00339  *  Return +true+ if this array is frozen (or temporarily frozen
00340  *  while being sorted). See also Object#frozen?
00341  */
00342 
00343 static VALUE
00344 rb_ary_frozen_p(VALUE ary)
00345 {
00346     if (OBJ_FROZEN(ary)) return Qtrue;
00347     return Qfalse;
00348 }
00349 
00350 /* This can be used to take a snapshot of an array (with
00351    e.g. rb_ary_replace) and check later whether the array has been
00352    modified from the snapshot.  The snapshot is cheap, though if
00353    something does modify the array it will pay the cost of copying
00354    it.  If Array#pop or Array#shift has been called, the array will
00355    be still shared with the snapshot, but the array length will
00356    differ. */
00357 VALUE
00358 rb_ary_shared_with_p(VALUE ary1, VALUE ary2)
00359 {
00360     if (!ARY_EMBED_P(ary1) && ARY_SHARED_P(ary1) &&
00361         !ARY_EMBED_P(ary2) && ARY_SHARED_P(ary2) &&
00362         RARRAY(ary1)->as.heap.aux.shared == RARRAY(ary2)->as.heap.aux.shared &&
00363         RARRAY(ary1)->as.heap.len == RARRAY(ary2)->as.heap.len) {
00364         return Qtrue;
00365     }
00366     return Qfalse;
00367 }
00368 
00369 static VALUE
00370 ary_alloc(VALUE klass)
00371 {
00372     NEWOBJ_OF(ary, struct RArray, klass, T_ARRAY);
00373     FL_SET_EMBED((VALUE)ary);
00374     ARY_SET_EMBED_LEN((VALUE)ary, 0);
00375 
00376     return (VALUE)ary;
00377 }
00378 
00379 static VALUE
00380 empty_ary_alloc(VALUE klass)
00381 {
00382     if (RUBY_DTRACE_ARRAY_CREATE_ENABLED()) {
00383         RUBY_DTRACE_ARRAY_CREATE(0, rb_sourcefile(), rb_sourceline());
00384     }
00385 
00386     return ary_alloc(klass);
00387 }
00388 
00389 static VALUE
00390 ary_new(VALUE klass, long capa)
00391 {
00392     VALUE ary;
00393 
00394     if (capa < 0) {
00395         rb_raise(rb_eArgError, "negative array size (or size too big)");
00396     }
00397     if (capa > ARY_MAX_SIZE) {
00398         rb_raise(rb_eArgError, "array size too big");
00399     }
00400 
00401     if (RUBY_DTRACE_ARRAY_CREATE_ENABLED()) {
00402         RUBY_DTRACE_ARRAY_CREATE(capa, rb_sourcefile(), rb_sourceline());
00403     }
00404 
00405     ary = ary_alloc(klass);
00406     if (capa > RARRAY_EMBED_LEN_MAX) {
00407         FL_UNSET_EMBED(ary);
00408         ARY_SET_PTR(ary, ALLOC_N(VALUE, capa));
00409         ARY_SET_CAPA(ary, capa);
00410         ARY_SET_HEAP_LEN(ary, 0);
00411     }
00412 
00413     return ary;
00414 }
00415 
00416 VALUE
00417 rb_ary_new2(long capa)
00418 {
00419     return ary_new(rb_cArray, capa);
00420 }
00421 
00422 
00423 VALUE
00424 rb_ary_new(void)
00425 {
00426     return rb_ary_new2(RARRAY_EMBED_LEN_MAX);
00427 }
00428 
00429 #include <stdarg.h>
00430 
00431 VALUE
00432 rb_ary_new3(long n, ...)
00433 {
00434     va_list ar;
00435     VALUE ary;
00436     long i;
00437 
00438     ary = rb_ary_new2(n);
00439 
00440     va_start(ar, n);
00441     for (i=0; i<n; i++) {
00442         RARRAY_PTR(ary)[i] = va_arg(ar, VALUE);
00443     }
00444     va_end(ar);
00445 
00446     ARY_SET_LEN(ary, n);
00447     return ary;
00448 }
00449 
00450 VALUE
00451 rb_ary_new4(long n, const VALUE *elts)
00452 {
00453     VALUE ary;
00454 
00455     ary = rb_ary_new2(n);
00456     if (n > 0 && elts) {
00457         MEMCPY(RARRAY_PTR(ary), elts, VALUE, n);
00458         ARY_SET_LEN(ary, n);
00459     }
00460 
00461     return ary;
00462 }
00463 
00464 VALUE
00465 rb_ary_tmp_new(long capa)
00466 {
00467     return ary_new(0, capa);
00468 }
00469 
00470 void
00471 rb_ary_free(VALUE ary)
00472 {
00473     if (ARY_OWNS_HEAP_P(ary)) {
00474         xfree(ARY_HEAP_PTR(ary));
00475     }
00476 }
00477 
00478 RUBY_FUNC_EXPORTED size_t
00479 rb_ary_memsize(VALUE ary)
00480 {
00481     if (ARY_OWNS_HEAP_P(ary)) {
00482         return RARRAY(ary)->as.heap.aux.capa * sizeof(VALUE);
00483     }
00484     else {
00485         return 0;
00486     }
00487 }
00488 
00489 static inline void
00490 ary_discard(VALUE ary)
00491 {
00492     rb_ary_free(ary);
00493     RBASIC(ary)->flags |= RARRAY_EMBED_FLAG;
00494     RBASIC(ary)->flags &= ~RARRAY_EMBED_LEN_MASK;
00495 }
00496 
00497 static VALUE
00498 ary_make_shared(VALUE ary)
00499 {
00500     assert(!ARY_EMBED_P(ary));
00501     if (ARY_SHARED_P(ary)) {
00502         return ARY_SHARED(ary);
00503     }
00504     else if (ARY_SHARED_ROOT_P(ary)) {
00505         return ary;
00506     }
00507     else if (OBJ_FROZEN(ary)) {
00508         ary_resize_capa(ary, ARY_HEAP_LEN(ary));
00509         FL_SET_SHARED_ROOT(ary);
00510         ARY_SET_SHARED_NUM(ary, 1);
00511         return ary;
00512     }
00513     else {
00514         NEWOBJ_OF(shared, struct RArray, 0, T_ARRAY);
00515         FL_UNSET_EMBED(shared);
00516 
00517         ARY_SET_LEN((VALUE)shared, ARY_CAPA(ary));
00518         ARY_SET_PTR((VALUE)shared, RARRAY_PTR(ary));
00519         rb_mem_clear(RARRAY_PTR(shared) + RARRAY_LEN(ary), ARY_CAPA(ary) - RARRAY_LEN(ary));
00520         FL_SET_SHARED_ROOT(shared);
00521         ARY_SET_SHARED_NUM((VALUE)shared, 1);
00522         FL_SET_SHARED(ary);
00523         ARY_SET_SHARED(ary, (VALUE)shared);
00524         OBJ_FREEZE(shared);
00525         return (VALUE)shared;
00526     }
00527 }
00528 
00529 
00530 static VALUE
00531 ary_make_substitution(VALUE ary)
00532 {
00533     if (RARRAY_LEN(ary) <= RARRAY_EMBED_LEN_MAX) {
00534         VALUE subst = rb_ary_new2(RARRAY_LEN(ary));
00535         MEMCPY(ARY_EMBED_PTR(subst), RARRAY_PTR(ary), VALUE, RARRAY_LEN(ary));
00536         ARY_SET_EMBED_LEN(subst, RARRAY_LEN(ary));
00537         return subst;
00538     }
00539     else {
00540         return rb_ary_increment_share(ary_make_shared(ary));
00541     }
00542 }
00543 
00544 VALUE
00545 rb_assoc_new(VALUE car, VALUE cdr)
00546 {
00547     return rb_ary_new3(2, car, cdr);
00548 }
00549 
00550 static VALUE
00551 to_ary(VALUE ary)
00552 {
00553     return rb_convert_type(ary, T_ARRAY, "Array", "to_ary");
00554 }
00555 
00556 VALUE
00557 rb_check_array_type(VALUE ary)
00558 {
00559     return rb_check_convert_type(ary, T_ARRAY, "Array", "to_ary");
00560 }
00561 
00562 /*
00563  *  call-seq:
00564  *     Array.try_convert(obj) -> array or nil
00565  *
00566  *  Tries to convert +obj+ into an array, using +to_ary+ method.  Returns the
00567  *  converted array or +nil+ if +obj+ cannot be converted for any reason.
00568  *  This method can be used to check if an argument is an array.
00569  *
00570  *     Array.try_convert([1])   #=> [1]
00571  *     Array.try_convert("1")   #=> nil
00572  *
00573  *     if tmp = Array.try_convert(arg)
00574  *       # the argument is an array
00575  *     elsif tmp = String.try_convert(arg)
00576  *       # the argument is a string
00577  *     end
00578  *
00579  */
00580 
00581 static VALUE
00582 rb_ary_s_try_convert(VALUE dummy, VALUE ary)
00583 {
00584     return rb_check_array_type(ary);
00585 }
00586 
00587 /*
00588  *  call-seq:
00589  *     Array.new(size=0, obj=nil)
00590  *     Array.new(array)
00591  *     Array.new(size) {|index| block }
00592  *
00593  *  Returns a new array.
00594  *
00595  *  In the first form, if no arguments are sent, the new array will be empty.
00596  *  When a +size+ and an optional +obj+ are sent, an array is created with
00597  *  +size+ copies of +obj+.  Take notice that all elements will reference the
00598  *  same object +obj+.
00599  *
00600  *  The second form creates a copy of the array passed as a parameter (the
00601  *  array is generated by calling to_ary on the parameter).
00602  *
00603  *    first_array = ["Matz", "Guido"]
00604  *
00605  *    second_array = Array.new(first_array) #=> ["Matz", "Guido"]
00606  *
00607  *    first_array.equal? second_array       #=> false
00608  *
00609  *  In the last form, an array of the given size is created.  Each element in
00610  *  this array is created by passing the element's index to the given block
00611  *  and storing the return value.
00612  *
00613  *    Array.new(3){ |index| index ** 2 }
00614  *    # => [0, 1, 4]
00615  *
00616  *  == Common gotchas
00617  *
00618  *  When sending the second parameter, the same object will be used as the
00619  *  value for all the array elements:
00620  *
00621  *     a = Array.new(2, Hash.new)
00622  *     # => [{}, {}]
00623  *
00624  *     a[0]['cat'] = 'feline'
00625  *     a # => [{"cat"=>"feline"}, {"cat"=>"feline"}]
00626  *
00627  *     a[1]['cat'] = 'Felix'
00628  *     a # => [{"cat"=>"Felix"}, {"cat"=>"Felix"}]
00629  *
00630  *  Since all the Array elements store the same hash, changes to one of them
00631  *  will affect them all.
00632  *
00633  *  If multiple copies are what you want, you should use the block
00634  *  version which uses the result of that block each time an element
00635  *  of the array needs to be initialized:
00636  *
00637  *     a = Array.new(2) { Hash.new }
00638  *     a[0]['cat'] = 'feline'
00639  *     a # => [{"cat"=>"feline"}, {}]
00640  *
00641  */
00642 
00643 static VALUE
00644 rb_ary_initialize(int argc, VALUE *argv, VALUE ary)
00645 {
00646     long len;
00647     VALUE size, val;
00648 
00649     rb_ary_modify(ary);
00650     if (argc == 0) {
00651         if (ARY_OWNS_HEAP_P(ary) && RARRAY_PTR(ary)) {
00652             xfree(RARRAY_PTR(ary));
00653         }
00654         rb_ary_unshare_safe(ary);
00655         FL_SET_EMBED(ary);
00656         ARY_SET_EMBED_LEN(ary, 0);
00657         if (rb_block_given_p()) {
00658             rb_warning("given block not used");
00659         }
00660         return ary;
00661     }
00662     rb_scan_args(argc, argv, "02", &size, &val);
00663     if (argc == 1 && !FIXNUM_P(size)) {
00664         val = rb_check_array_type(size);
00665         if (!NIL_P(val)) {
00666             rb_ary_replace(ary, val);
00667             return ary;
00668         }
00669     }
00670 
00671     len = NUM2LONG(size);
00672     if (len < 0) {
00673         rb_raise(rb_eArgError, "negative array size");
00674     }
00675     if (len > ARY_MAX_SIZE) {
00676         rb_raise(rb_eArgError, "array size too big");
00677     }
00678     rb_ary_modify(ary);
00679     ary_resize_capa(ary, len);
00680     if (rb_block_given_p()) {
00681         long i;
00682 
00683         if (argc == 2) {
00684             rb_warn("block supersedes default value argument");
00685         }
00686         for (i=0; i<len; i++) {
00687             rb_ary_store(ary, i, rb_yield(LONG2NUM(i)));
00688             ARY_SET_LEN(ary, i + 1);
00689         }
00690     }
00691     else {
00692         memfill(RARRAY_PTR(ary), len, val);
00693         ARY_SET_LEN(ary, len);
00694     }
00695     return ary;
00696 }
00697 
00698 /*
00699  * Returns a new array populated with the given objects.
00700  *
00701  *   Array.[]( 1, 'a', /^A/ ) # => [1, "a", /^A/]
00702  *   Array[ 1, 'a', /^A/ ]    # => [1, "a", /^A/]
00703  *   [ 1, 'a', /^A/ ]         # => [1, "a", /^A/]
00704  */
00705 
00706 static VALUE
00707 rb_ary_s_create(int argc, VALUE *argv, VALUE klass)
00708 {
00709     VALUE ary = ary_new(klass, argc);
00710     if (argc > 0 && argv) {
00711         MEMCPY(RARRAY_PTR(ary), argv, VALUE, argc);
00712         ARY_SET_LEN(ary, argc);
00713     }
00714 
00715     return ary;
00716 }
00717 
00718 void
00719 rb_ary_store(VALUE ary, long idx, VALUE val)
00720 {
00721     if (idx < 0) {
00722         idx += RARRAY_LEN(ary);
00723         if (idx < 0) {
00724             rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld",
00725                      idx - RARRAY_LEN(ary), -RARRAY_LEN(ary));
00726         }
00727     }
00728     else if (idx >= ARY_MAX_SIZE) {
00729         rb_raise(rb_eIndexError, "index %ld too big", idx);
00730     }
00731 
00732     rb_ary_modify(ary);
00733     if (idx >= ARY_CAPA(ary)) {
00734         ary_double_capa(ary, idx);
00735     }
00736     if (idx > RARRAY_LEN(ary)) {
00737         rb_mem_clear(RARRAY_PTR(ary) + RARRAY_LEN(ary),
00738                      idx-RARRAY_LEN(ary) + 1);
00739     }
00740 
00741     if (idx >= RARRAY_LEN(ary)) {
00742         ARY_SET_LEN(ary, idx + 1);
00743     }
00744     RARRAY_PTR(ary)[idx] = val;
00745 }
00746 
00747 static VALUE
00748 ary_make_partial(VALUE ary, VALUE klass, long offset, long len)
00749 {
00750     assert(offset >= 0);
00751     assert(len >= 0);
00752     assert(offset+len <= RARRAY_LEN(ary));
00753 
00754     if (len <= RARRAY_EMBED_LEN_MAX) {
00755         VALUE result = ary_alloc(klass);
00756         MEMCPY(ARY_EMBED_PTR(result), RARRAY_PTR(ary) + offset, VALUE, len);
00757         ARY_SET_EMBED_LEN(result, len);
00758         return result;
00759     }
00760     else {
00761         VALUE shared, result = ary_alloc(klass);
00762         FL_UNSET_EMBED(result);
00763 
00764         shared = ary_make_shared(ary);
00765         ARY_SET_PTR(result, RARRAY_PTR(ary));
00766         ARY_SET_LEN(result, RARRAY_LEN(ary));
00767         rb_ary_set_shared(result, shared);
00768 
00769         ARY_INCREASE_PTR(result, offset);
00770         ARY_SET_LEN(result, len);
00771         return result;
00772     }
00773 }
00774 
00775 static VALUE
00776 ary_make_shared_copy(VALUE ary)
00777 {
00778     return ary_make_partial(ary, rb_obj_class(ary), 0, RARRAY_LEN(ary));
00779 }
00780 
00781 enum ary_take_pos_flags
00782 {
00783     ARY_TAKE_FIRST = 0,
00784     ARY_TAKE_LAST = 1
00785 };
00786 
00787 static VALUE
00788 ary_take_first_or_last(int argc, VALUE *argv, VALUE ary, enum ary_take_pos_flags last)
00789 {
00790     VALUE nv;
00791     long n;
00792     long offset = 0;
00793 
00794     rb_scan_args(argc, argv, "1", &nv);
00795     n = NUM2LONG(nv);
00796     if (n > RARRAY_LEN(ary)) {
00797         n = RARRAY_LEN(ary);
00798     }
00799     else if (n < 0) {
00800         rb_raise(rb_eArgError, "negative array size");
00801     }
00802     if (last) {
00803         offset = RARRAY_LEN(ary) - n;
00804     }
00805     return ary_make_partial(ary, rb_cArray, offset, n);
00806 }
00807 
00808 /*
00809  *  call-seq:
00810  *     ary << obj            -> ary
00811  *
00812  *  Append---Pushes the given object on to the end of this array. This
00813  *  expression returns the array itself, so several appends
00814  *  may be chained together.
00815  *
00816  *     [ 1, 2 ] << "c" << "d" << [ 3, 4 ]
00817  *             #=>  [ 1, 2, "c", "d", [ 3, 4 ] ]
00818  *
00819  */
00820 
00821 VALUE
00822 rb_ary_push(VALUE ary, VALUE item)
00823 {
00824     long idx = RARRAY_LEN(ary);
00825 
00826     ary_ensure_room_for_push(ary, 1);
00827     RARRAY_PTR(ary)[idx] = item;
00828     ARY_SET_LEN(ary, idx + 1);
00829     return ary;
00830 }
00831 
00832 VALUE
00833 rb_ary_cat(VALUE ary, const VALUE *ptr, long len)
00834 {
00835     long oldlen = RARRAY_LEN(ary);
00836 
00837     ary_ensure_room_for_push(ary, len);
00838     MEMCPY(RARRAY_PTR(ary) + oldlen, ptr, VALUE, len);
00839     ARY_SET_LEN(ary, oldlen + len);
00840     return ary;
00841 }
00842 
00843 /*
00844  *  call-seq:
00845  *     ary.push(obj, ... )   -> ary
00846  *
00847  *  Append --- Pushes the given object(s) on to the end of this array. This
00848  *  expression returns the array itself, so several appends
00849  *  may be chained together. See also Array#pop for the opposite
00850  *  effect.
00851  *
00852  *     a = [ "a", "b", "c" ]
00853  *     a.push("d", "e", "f")
00854  *             #=> ["a", "b", "c", "d", "e", "f"]
00855  *     [1, 2, 3,].push(4).push(5)
00856  *             #=> [1, 2, 3, 4, 5]
00857  */
00858 
00859 static VALUE
00860 rb_ary_push_m(int argc, VALUE *argv, VALUE ary)
00861 {
00862     return rb_ary_cat(ary, argv, argc);
00863 }
00864 
00865 VALUE
00866 rb_ary_pop(VALUE ary)
00867 {
00868     long n;
00869     rb_ary_modify_check(ary);
00870     if (RARRAY_LEN(ary) == 0) return Qnil;
00871     if (ARY_OWNS_HEAP_P(ary) &&
00872         RARRAY_LEN(ary) * 3 < ARY_CAPA(ary) &&
00873         ARY_CAPA(ary) > ARY_DEFAULT_SIZE)
00874     {
00875         ary_resize_capa(ary, RARRAY_LEN(ary) * 2);
00876     }
00877     n = RARRAY_LEN(ary)-1;
00878     ARY_SET_LEN(ary, n);
00879     return RARRAY_PTR(ary)[n];
00880 }
00881 
00882 /*
00883  *  call-seq:
00884  *     ary.pop    -> obj or nil
00885  *     ary.pop(n) -> new_ary
00886  *
00887  *  Removes the last element from +self+ and returns it, or
00888  *  +nil+ if the array is empty.
00889  *
00890  *  If a number +n+ is given, returns an array of the last +n+ elements
00891  *  (or less) just like <code>array.slice!(-n, n)</code> does. See also
00892  *  Array#push for the opposite effect.
00893  *
00894  *     a = [ "a", "b", "c", "d" ]
00895  *     a.pop     #=> "d"
00896  *     a.pop(2)  #=> ["b", "c"]
00897  *     a         #=> ["a"]
00898  */
00899 
00900 static VALUE
00901 rb_ary_pop_m(int argc, VALUE *argv, VALUE ary)
00902 {
00903     VALUE result;
00904 
00905     if (argc == 0) {
00906         return rb_ary_pop(ary);
00907     }
00908 
00909     rb_ary_modify_check(ary);
00910     result = ary_take_first_or_last(argc, argv, ary, ARY_TAKE_LAST);
00911     ARY_INCREASE_LEN(ary, -RARRAY_LEN(result));
00912     return result;
00913 }
00914 
00915 VALUE
00916 rb_ary_shift(VALUE ary)
00917 {
00918     VALUE top;
00919 
00920     rb_ary_modify_check(ary);
00921     if (RARRAY_LEN(ary) == 0) return Qnil;
00922     top = RARRAY_PTR(ary)[0];
00923     if (!ARY_SHARED_P(ary)) {
00924         if (RARRAY_LEN(ary) < ARY_DEFAULT_SIZE) {
00925             MEMMOVE(RARRAY_PTR(ary), RARRAY_PTR(ary)+1, VALUE, RARRAY_LEN(ary)-1);
00926             ARY_INCREASE_LEN(ary, -1);
00927             return top;
00928         }
00929         assert(!ARY_EMBED_P(ary)); /* ARY_EMBED_LEN_MAX < ARY_DEFAULT_SIZE */
00930 
00931         RARRAY_PTR(ary)[0] = Qnil;
00932         ary_make_shared(ary);
00933     }
00934     else if (ARY_SHARED_NUM(ARY_SHARED(ary)) == 1) {
00935         RARRAY_PTR(ary)[0] = Qnil;
00936     }
00937     ARY_INCREASE_PTR(ary, 1);           /* shift ptr */
00938     ARY_INCREASE_LEN(ary, -1);
00939 
00940     return top;
00941 }
00942 
00943 /*
00944  *  call-seq:
00945  *     ary.shift    -> obj or nil
00946  *     ary.shift(n) -> new_ary
00947  *
00948  *  Removes the first element of +self+ and returns it (shifting all
00949  *  other elements down by one). Returns +nil+ if the array
00950  *  is empty.
00951  *
00952  *  If a number +n+ is given, returns an array of the first +n+ elements
00953  *  (or less) just like <code>array.slice!(0, n)</code> does. With +ary+
00954  *  containing only the remainder elements, not including what was shifted to
00955  *  +new_ary+. See also Array#unshift for the opposite effect.
00956  *
00957  *     args = [ "-m", "-q", "filename" ]
00958  *     args.shift     #=> "-m"
00959  *     args           #=> ["-q", "filename"]
00960  *
00961  *     args = [ "-m", "-q", "filename" ]
00962  *     args.shift(2)  #=> ["-m", "-q"]
00963  *     args           #=> ["filename"]
00964  */
00965 
00966 static VALUE
00967 rb_ary_shift_m(int argc, VALUE *argv, VALUE ary)
00968 {
00969     VALUE result;
00970     long n;
00971 
00972     if (argc == 0) {
00973         return rb_ary_shift(ary);
00974     }
00975 
00976     rb_ary_modify_check(ary);
00977     result = ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
00978     n = RARRAY_LEN(result);
00979     if (ARY_SHARED_P(ary)) {
00980         if (ARY_SHARED_NUM(ARY_SHARED(ary)) == 1) {
00981             rb_mem_clear(RARRAY_PTR(ary), n);
00982         }
00983         ARY_INCREASE_PTR(ary, n);
00984     }
00985     else {
00986         MEMMOVE(RARRAY_PTR(ary), RARRAY_PTR(ary)+n, VALUE, RARRAY_LEN(ary)-n);
00987     }
00988     ARY_INCREASE_LEN(ary, -n);
00989 
00990     return result;
00991 }
00992 
00993 static void
00994 ary_ensure_room_for_unshift(VALUE ary, int argc)
00995 {
00996     long len = RARRAY_LEN(ary);
00997     long new_len = len + argc;
00998     long capa;
00999     VALUE *head, *sharedp;
01000 
01001     if (ARY_SHARED_P(ary)) {
01002         VALUE shared = ARY_SHARED(ary);
01003         capa = RARRAY_LEN(shared);
01004         if (ARY_SHARED_NUM(shared) == 1 && capa > new_len) {
01005             head = RARRAY_PTR(ary);
01006             sharedp = RARRAY_PTR(shared);
01007             goto makeroom_if_need;
01008         }
01009     }
01010 
01011     rb_ary_modify(ary);
01012     capa = ARY_CAPA(ary);
01013     if (capa - (capa >> 6) <= new_len) {
01014         ary_double_capa(ary, new_len);
01015     }
01016 
01017     /* use shared array for big "queues" */
01018     if (new_len > ARY_DEFAULT_SIZE * 4) {
01019         /* make a room for unshifted items */
01020         capa = ARY_CAPA(ary);
01021         ary_make_shared(ary);
01022 
01023         head = sharedp = RARRAY_PTR(ary);
01024         goto makeroom;
01025       makeroom_if_need:
01026         if (head - sharedp < argc) {
01027             long room;
01028           makeroom:
01029             room = capa - new_len;
01030             room -= room >> 4;
01031             MEMMOVE(sharedp + argc + room, head, VALUE, len);
01032             head = sharedp + argc + room;
01033         }
01034         ARY_SET_PTR(ary, head - argc);
01035     }
01036     else {
01037         /* sliding items */
01038         MEMMOVE(RARRAY_PTR(ary) + argc, RARRAY_PTR(ary), VALUE, len);
01039     }
01040 }
01041 
01042 /*
01043  *  call-seq:
01044  *     ary.unshift(obj, ...)  -> ary
01045  *
01046  *  Prepends objects to the front of +self+, moving other elements upwards.
01047  *  See also Array#shift for the opposite effect.
01048  *
01049  *     a = [ "b", "c", "d" ]
01050  *     a.unshift("a")   #=> ["a", "b", "c", "d"]
01051  *     a.unshift(1, 2)  #=> [ 1, 2, "a", "b", "c", "d"]
01052  */
01053 
01054 static VALUE
01055 rb_ary_unshift_m(int argc, VALUE *argv, VALUE ary)
01056 {
01057     long len = RARRAY_LEN(ary);
01058 
01059     if (argc == 0) {
01060         rb_ary_modify_check(ary);
01061         return ary;
01062     }
01063 
01064     ary_ensure_room_for_unshift(ary, argc);
01065     MEMCPY(RARRAY_PTR(ary), argv, VALUE, argc);
01066     ARY_SET_LEN(ary, len + argc);
01067     return ary;
01068 }
01069 
01070 VALUE
01071 rb_ary_unshift(VALUE ary, VALUE item)
01072 {
01073     return rb_ary_unshift_m(1,&item,ary);
01074 }
01075 
01076 /* faster version - use this if you don't need to treat negative offset */
01077 static inline VALUE
01078 rb_ary_elt(VALUE ary, long offset)
01079 {
01080     if (RARRAY_LEN(ary) == 0) return Qnil;
01081     if (offset < 0 || RARRAY_LEN(ary) <= offset) {
01082         return Qnil;
01083     }
01084     return RARRAY_PTR(ary)[offset];
01085 }
01086 
01087 VALUE
01088 rb_ary_entry(VALUE ary, long offset)
01089 {
01090     if (offset < 0) {
01091         offset += RARRAY_LEN(ary);
01092     }
01093     return rb_ary_elt(ary, offset);
01094 }
01095 
01096 VALUE
01097 rb_ary_subseq(VALUE ary, long beg, long len)
01098 {
01099     VALUE klass;
01100 
01101     if (beg > RARRAY_LEN(ary)) return Qnil;
01102     if (beg < 0 || len < 0) return Qnil;
01103 
01104     if (RARRAY_LEN(ary) < len || RARRAY_LEN(ary) < beg + len) {
01105         len = RARRAY_LEN(ary) - beg;
01106     }
01107     klass = rb_obj_class(ary);
01108     if (len == 0) return ary_new(klass, 0);
01109 
01110     return ary_make_partial(ary, klass, beg, len);
01111 }
01112 
01113 /*
01114  *  call-seq:
01115  *     ary[index]                -> obj     or nil
01116  *     ary[start, length]        -> new_ary or nil
01117  *     ary[range]                -> new_ary or nil
01118  *     ary.slice(index)          -> obj     or nil
01119  *     ary.slice(start, length)  -> new_ary or nil
01120  *     ary.slice(range)          -> new_ary or nil
01121  *
01122  *  Element Reference --- Returns the element at +index+, or returns a
01123  *  subarray starting at the +start+ index and continuing for +length+
01124  *  elements, or returns a subarray specified by +range+ of indices.
01125  *
01126  *  Negative indices count backward from the end of the array (-1 is the last
01127  *  element).  For +start+ and +range+ cases the starting index is just before
01128  *  an element.  Additionally, an empty array is returned when the starting
01129  *  index for an element range is at the end of the array.
01130  *
01131  *  Returns +nil+ if the index (or starting index) are out of range.
01132  *
01133  *     a = [ "a", "b", "c", "d", "e" ]
01134  *     a[2] +  a[0] + a[1]    #=> "cab"
01135  *     a[6]                   #=> nil
01136  *     a[1, 2]                #=> [ "b", "c" ]
01137  *     a[1..3]                #=> [ "b", "c", "d" ]
01138  *     a[4..7]                #=> [ "e" ]
01139  *     a[6..10]               #=> nil
01140  *     a[-3, 3]               #=> [ "c", "d", "e" ]
01141  *     # special cases
01142  *     a[5]                   #=> nil
01143  *     a[6, 1]                #=> nil
01144  *     a[5, 1]                #=> []
01145  *     a[5..10]               #=> []
01146  *
01147  */
01148 
01149 VALUE
01150 rb_ary_aref(int argc, VALUE *argv, VALUE ary)
01151 {
01152     VALUE arg;
01153     long beg, len;
01154 
01155     if (argc == 2) {
01156         beg = NUM2LONG(argv[0]);
01157         len = NUM2LONG(argv[1]);
01158         if (beg < 0) {
01159             beg += RARRAY_LEN(ary);
01160         }
01161         return rb_ary_subseq(ary, beg, len);
01162     }
01163     if (argc != 1) {
01164         rb_scan_args(argc, argv, "11", NULL, NULL);
01165     }
01166     arg = argv[0];
01167     /* special case - speeding up */
01168     if (FIXNUM_P(arg)) {
01169         return rb_ary_entry(ary, FIX2LONG(arg));
01170     }
01171     /* check if idx is Range */
01172     switch (rb_range_beg_len(arg, &beg, &len, RARRAY_LEN(ary), 0)) {
01173       case Qfalse:
01174         break;
01175       case Qnil:
01176         return Qnil;
01177       default:
01178         return rb_ary_subseq(ary, beg, len);
01179     }
01180     return rb_ary_entry(ary, NUM2LONG(arg));
01181 }
01182 
01183 /*
01184  *  call-seq:
01185  *     ary.at(index)   ->   obj  or nil
01186  *
01187  *  Returns the element at +index+. A negative index counts from the end of
01188  *  +self+. Returns +nil+ if the index is out of range. See also
01189  *  Array#[].
01190  *
01191  *     a = [ "a", "b", "c", "d", "e" ]
01192  *     a.at(0)     #=> "a"
01193  *     a.at(-1)    #=> "e"
01194  */
01195 
01196 static VALUE
01197 rb_ary_at(VALUE ary, VALUE pos)
01198 {
01199     return rb_ary_entry(ary, NUM2LONG(pos));
01200 }
01201 
01202 /*
01203  *  call-seq:
01204  *     ary.first     ->   obj or nil
01205  *     ary.first(n)  ->   new_ary
01206  *
01207  *  Returns the first element, or the first +n+ elements, of the array.
01208  *  If the array is empty, the first form returns +nil+, and the
01209  *  second form returns an empty array. See also Array#last for
01210  *  the opposite effect.
01211  *
01212  *     a = [ "q", "r", "s", "t" ]
01213  *     a.first     #=> "q"
01214  *     a.first(2)  #=> ["q", "r"]
01215  */
01216 
01217 static VALUE
01218 rb_ary_first(int argc, VALUE *argv, VALUE ary)
01219 {
01220     if (argc == 0) {
01221         if (RARRAY_LEN(ary) == 0) return Qnil;
01222         return RARRAY_PTR(ary)[0];
01223     }
01224     else {
01225         return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
01226     }
01227 }
01228 
01229 /*
01230  *  call-seq:
01231  *     ary.last     ->  obj or nil
01232  *     ary.last(n)  ->  new_ary
01233  *
01234  *  Returns the last element(s) of +self+. If the array is empty,
01235  *  the first form returns +nil+.
01236  *
01237  *  See also Array#first for the opposite effect.
01238  *
01239  *     a = [ "w", "x", "y", "z" ]
01240  *     a.last     #=> "z"
01241  *     a.last(2)  #=> ["y", "z"]
01242  */
01243 
01244 VALUE
01245 rb_ary_last(int argc, VALUE *argv, VALUE ary)
01246 {
01247     if (argc == 0) {
01248         if (RARRAY_LEN(ary) == 0) return Qnil;
01249         return RARRAY_PTR(ary)[RARRAY_LEN(ary)-1];
01250     }
01251     else {
01252         return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_LAST);
01253     }
01254 }
01255 
01256 /*
01257  *  call-seq:
01258  *     ary.fetch(index)                    -> obj
01259  *     ary.fetch(index, default)           -> obj
01260  *     ary.fetch(index) { |index| block }  -> obj
01261  *
01262  *  Tries to return the element at position +index+, but throws an IndexError
01263  *  exception if the referenced +index+ lies outside of the array bounds.  This
01264  *  error can be prevented by supplying a second argument, which will act as a
01265  *  +default+ value.
01266  *
01267  *  Alternatively, if a block is given it will only be executed when an
01268  *  invalid +index+ is referenced.  Negative values of +index+ count from the
01269  *  end of the array.
01270  *
01271  *     a = [ 11, 22, 33, 44 ]
01272  *     a.fetch(1)               #=> 22
01273  *     a.fetch(-1)              #=> 44
01274  *     a.fetch(4, 'cat')        #=> "cat"
01275  *     a.fetch(100) { |i| puts "#{i} is out of bounds" }
01276  *                              #=> "100 is out of bounds"
01277  */
01278 
01279 static VALUE
01280 rb_ary_fetch(int argc, VALUE *argv, VALUE ary)
01281 {
01282     VALUE pos, ifnone;
01283     long block_given;
01284     long idx;
01285 
01286     rb_scan_args(argc, argv, "11", &pos, &ifnone);
01287     block_given = rb_block_given_p();
01288     if (block_given && argc == 2) {
01289         rb_warn("block supersedes default value argument");
01290     }
01291     idx = NUM2LONG(pos);
01292 
01293     if (idx < 0) {
01294         idx +=  RARRAY_LEN(ary);
01295     }
01296     if (idx < 0 || RARRAY_LEN(ary) <= idx) {
01297         if (block_given) return rb_yield(pos);
01298         if (argc == 1) {
01299             rb_raise(rb_eIndexError, "index %ld outside of array bounds: %ld...%ld",
01300                         idx - (idx < 0 ? RARRAY_LEN(ary) : 0), -RARRAY_LEN(ary), RARRAY_LEN(ary));
01301         }
01302         return ifnone;
01303     }
01304     return RARRAY_PTR(ary)[idx];
01305 }
01306 
01307 /*
01308  *  call-seq:
01309  *     ary.index(obj)             ->  int or nil
01310  *     ary.index { |item| block } ->  int or nil
01311  *     ary.index                  ->  Enumerator
01312  *
01313  *  Returns the _index_ of the first object in +ary+ such that the object is
01314  *  <code>==</code> to +obj+.
01315  *
01316  *  If a block is given instead of an argument, returns the _index_ of the
01317  *  first object for which the block returns +true+.  Returns +nil+ if no
01318  *  match is found.
01319  *
01320  *  See also Array#rindex.
01321  *
01322  *  An Enumerator is returned if neither a block nor argument is given.
01323  *
01324  *     a = [ "a", "b", "c" ]
01325  *     a.index("b")              #=> 1
01326  *     a.index("z")              #=> nil
01327  *     a.index { |x| x == "b" }  #=> 1
01328  *
01329  *  This is an alias of Array#find_index.
01330  */
01331 
01332 static VALUE
01333 rb_ary_index(int argc, VALUE *argv, VALUE ary)
01334 {
01335     VALUE val;
01336     long i;
01337 
01338     if (argc == 0) {
01339         RETURN_ENUMERATOR(ary, 0, 0);
01340         for (i=0; i<RARRAY_LEN(ary); i++) {
01341             if (RTEST(rb_yield(RARRAY_PTR(ary)[i]))) {
01342                 return LONG2NUM(i);
01343             }
01344         }
01345         return Qnil;
01346     }
01347     rb_scan_args(argc, argv, "1", &val);
01348     if (rb_block_given_p())
01349         rb_warn("given block not used");
01350     for (i=0; i<RARRAY_LEN(ary); i++) {
01351         if (rb_equal(RARRAY_PTR(ary)[i], val))
01352             return LONG2NUM(i);
01353     }
01354     return Qnil;
01355 }
01356 
01357 /*
01358  *  call-seq:
01359  *     ary.rindex(obj)             ->  int or nil
01360  *     ary.rindex { |item| block } ->  int or nil
01361  *     ary.rindex                  ->  Enumerator
01362  *
01363  *  Returns the _index_ of the last object in +self+ <code>==</code> to +obj+.
01364  *
01365  *  If a block is given instead of an argument, returns the _index_ of the
01366  *  first object for which the block returns +true+, starting from the last
01367  *  object.
01368  *
01369  *  Returns +nil+ if no match is found.
01370  *
01371  *  See also Array#index.
01372  *
01373  *  If neither block nor argument is given, an Enumerator is returned instead.
01374  *
01375  *     a = [ "a", "b", "b", "b", "c" ]
01376  *     a.rindex("b")             #=> 3
01377  *     a.rindex("z")             #=> nil
01378  *     a.rindex { |x| x == "b" } #=> 3
01379  */
01380 
01381 static VALUE
01382 rb_ary_rindex(int argc, VALUE *argv, VALUE ary)
01383 {
01384     VALUE val;
01385     long i = RARRAY_LEN(ary);
01386 
01387     if (argc == 0) {
01388         RETURN_ENUMERATOR(ary, 0, 0);
01389         while (i--) {
01390             if (RTEST(rb_yield(RARRAY_PTR(ary)[i])))
01391                 return LONG2NUM(i);
01392             if (i > RARRAY_LEN(ary)) {
01393                 i = RARRAY_LEN(ary);
01394             }
01395         }
01396         return Qnil;
01397     }
01398     rb_scan_args(argc, argv, "1", &val);
01399     if (rb_block_given_p())
01400         rb_warn("given block not used");
01401     while (i--) {
01402         if (rb_equal(RARRAY_PTR(ary)[i], val))
01403             return LONG2NUM(i);
01404         if (i > RARRAY_LEN(ary)) {
01405             i = RARRAY_LEN(ary);
01406         }
01407     }
01408     return Qnil;
01409 }
01410 
01411 VALUE
01412 rb_ary_to_ary(VALUE obj)
01413 {
01414     VALUE tmp = rb_check_array_type(obj);
01415 
01416     if (!NIL_P(tmp)) return tmp;
01417     return rb_ary_new3(1, obj);
01418 }
01419 
01420 static void
01421 rb_ary_splice(VALUE ary, long beg, long len, VALUE rpl)
01422 {
01423     long rlen;
01424 
01425     if (len < 0) rb_raise(rb_eIndexError, "negative length (%ld)", len);
01426     if (beg < 0) {
01427         beg += RARRAY_LEN(ary);
01428         if (beg < 0) {
01429             rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld",
01430                      beg - RARRAY_LEN(ary), -RARRAY_LEN(ary));
01431         }
01432     }
01433     if (RARRAY_LEN(ary) < len || RARRAY_LEN(ary) < beg + len) {
01434         len = RARRAY_LEN(ary) - beg;
01435     }
01436 
01437     if (rpl == Qundef) {
01438         rlen = 0;
01439     }
01440     else {
01441         rpl = rb_ary_to_ary(rpl);
01442         rlen = RARRAY_LEN(rpl);
01443     }
01444     if (beg >= RARRAY_LEN(ary)) {
01445         if (beg > ARY_MAX_SIZE - rlen) {
01446             rb_raise(rb_eIndexError, "index %ld too big", beg);
01447         }
01448         ary_ensure_room_for_push(ary, rlen-len); /* len is 0 or negative */
01449         len = beg + rlen;
01450         rb_mem_clear(RARRAY_PTR(ary) + RARRAY_LEN(ary), beg - RARRAY_LEN(ary));
01451         if (rlen > 0) {
01452             MEMCPY(RARRAY_PTR(ary) + beg, RARRAY_PTR(rpl), VALUE, rlen);
01453         }
01454         ARY_SET_LEN(ary, len);
01455     }
01456     else {
01457         long alen;
01458 
01459         rb_ary_modify(ary);
01460         alen = RARRAY_LEN(ary) + rlen - len;
01461         if (alen >= ARY_CAPA(ary)) {
01462             ary_double_capa(ary, alen);
01463         }
01464 
01465         if (len != rlen) {
01466             MEMMOVE(RARRAY_PTR(ary) + beg + rlen, RARRAY_PTR(ary) + beg + len,
01467                     VALUE, RARRAY_LEN(ary) - (beg + len));
01468             ARY_SET_LEN(ary, alen);
01469         }
01470         if (rlen > 0) {
01471             MEMMOVE(RARRAY_PTR(ary) + beg, RARRAY_PTR(rpl), VALUE, rlen);
01472         }
01473     }
01474 }
01475 
01476 void
01477 rb_ary_set_len(VALUE ary, long len)
01478 {
01479     long capa;
01480 
01481     rb_ary_modify_check(ary);
01482     if (ARY_SHARED_P(ary)) {
01483         rb_raise(rb_eRuntimeError, "can't set length of shared ");
01484     }
01485     if (len > (capa = (long)ARY_CAPA(ary))) {
01486         rb_bug("probable buffer overflow: %ld for %ld", len, capa);
01487     }
01488     ARY_SET_LEN(ary, len);
01489 }
01490 
01499 VALUE
01500 rb_ary_resize(VALUE ary, long len)
01501 {
01502     long olen;
01503 
01504     rb_ary_modify(ary);
01505     olen = RARRAY_LEN(ary);
01506     if (len == olen) return ary;
01507     if (len > ARY_MAX_SIZE) {
01508         rb_raise(rb_eIndexError, "index %ld too big", len);
01509     }
01510     if (len > olen) {
01511         if (len >= ARY_CAPA(ary)) {
01512             ary_double_capa(ary, len);
01513         }
01514         rb_mem_clear(RARRAY_PTR(ary) + olen, len - olen);
01515         ARY_SET_LEN(ary, len);
01516     }
01517     else if (ARY_EMBED_P(ary)) {
01518         ARY_SET_EMBED_LEN(ary, len);
01519     }
01520     else if (len <= RARRAY_EMBED_LEN_MAX) {
01521         VALUE tmp[RARRAY_EMBED_LEN_MAX];
01522         MEMCPY(tmp, ARY_HEAP_PTR(ary), VALUE, len);
01523         ary_discard(ary);
01524         MEMCPY(ARY_EMBED_PTR(ary), tmp, VALUE, len);
01525         ARY_SET_EMBED_LEN(ary, len);
01526     }
01527     else {
01528         if (olen > len + ARY_DEFAULT_SIZE) {
01529             REALLOC_N(RARRAY(ary)->as.heap.ptr, VALUE, len);
01530             ARY_SET_CAPA(ary, len);
01531         }
01532         ARY_SET_HEAP_LEN(ary, len);
01533     }
01534     return ary;
01535 }
01536 
01537 /*
01538  *  call-seq:
01539  *     ary[index]         = obj                      ->  obj
01540  *     ary[start, length] = obj or other_ary or nil  ->  obj or other_ary or nil
01541  *     ary[range]         = obj or other_ary or nil  ->  obj or other_ary or nil
01542  *
01543  *  Element Assignment --- Sets the element at +index+, or replaces a subarray
01544  *  from the +start+ index for +length+ elements, or replaces a subarray
01545  *  specified by the +range+ of indices.
01546  *
01547  *  If indices are greater than the current capacity of the array, the array
01548  *  grows automatically.  Elements are inserted into the array at +start+ if
01549  *  +length+ is zero.
01550  *
01551  *  Negative indices will count backward from the end of the array.  For
01552  *  +start+ and +range+ cases the starting index is just before an element.
01553  *
01554  *  An IndexError is raised if a negative index points past the beginning of
01555  *  the array.
01556  *
01557  *  See also Array#push, and Array#unshift.
01558  *
01559  *     a = Array.new
01560  *     a[4] = "4";                 #=> [nil, nil, nil, nil, "4"]
01561  *     a[0, 3] = [ 'a', 'b', 'c' ] #=> ["a", "b", "c", nil, "4"]
01562  *     a[1..2] = [ 1, 2 ]          #=> ["a", 1, 2, nil, "4"]
01563  *     a[0, 2] = "?"               #=> ["?", 2, nil, "4"]
01564  *     a[0..2] = "A"               #=> ["A", "4"]
01565  *     a[-1]   = "Z"               #=> ["A", "Z"]
01566  *     a[1..-1] = nil              #=> ["A", nil]
01567  *     a[1..-1] = []               #=> ["A"]
01568  *     a[0, 0] = [ 1, 2 ]          #=> [1, 2, "A"]
01569  *     a[3, 0] = "B"               #=> [1, 2, "A", "B"]
01570  */
01571 
01572 static VALUE
01573 rb_ary_aset(int argc, VALUE *argv, VALUE ary)
01574 {
01575     long offset, beg, len;
01576 
01577     if (argc == 3) {
01578         rb_ary_modify_check(ary);
01579         beg = NUM2LONG(argv[0]);
01580         len = NUM2LONG(argv[1]);
01581         rb_ary_splice(ary, beg, len, argv[2]);
01582         return argv[2];
01583     }
01584     rb_check_arity(argc, 2, 2);
01585     rb_ary_modify_check(ary);
01586     if (FIXNUM_P(argv[0])) {
01587         offset = FIX2LONG(argv[0]);
01588         goto fixnum;
01589     }
01590     if (rb_range_beg_len(argv[0], &beg, &len, RARRAY_LEN(ary), 1)) {
01591         /* check if idx is Range */
01592         rb_ary_splice(ary, beg, len, argv[1]);
01593         return argv[1];
01594     }
01595 
01596     offset = NUM2LONG(argv[0]);
01597 fixnum:
01598     rb_ary_store(ary, offset, argv[1]);
01599     return argv[1];
01600 }
01601 
01602 /*
01603  *  call-seq:
01604  *     ary.insert(index, obj...)  -> ary
01605  *
01606  *  Inserts the given values before the element with the given +index+.
01607  *
01608  *  Negative indices count backwards from the end of the array, where +-1+ is
01609  *  the last element.
01610  *
01611  *     a = %w{ a b c d }
01612  *     a.insert(2, 99)         #=> ["a", "b", 99, "c", "d"]
01613  *     a.insert(-2, 1, 2, 3)   #=> ["a", "b", 99, "c", 1, 2, 3, "d"]
01614  */
01615 
01616 static VALUE
01617 rb_ary_insert(int argc, VALUE *argv, VALUE ary)
01618 {
01619     long pos;
01620 
01621     rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
01622     rb_ary_modify_check(ary);
01623     if (argc == 1) return ary;
01624     pos = NUM2LONG(argv[0]);
01625     if (pos == -1) {
01626         pos = RARRAY_LEN(ary);
01627     }
01628     if (pos < 0) {
01629         pos++;
01630     }
01631     rb_ary_splice(ary, pos, 0, rb_ary_new4(argc - 1, argv + 1));
01632     return ary;
01633 }
01634 
01635 static VALUE
01636 rb_ary_length(VALUE ary);
01637 
01638 /*
01639  *  call-seq:
01640  *     ary.each { |item| block }  -> ary
01641  *     ary.each                   -> Enumerator
01642  *
01643  *  Calls the given block once for each element in +self+, passing that element
01644  *  as a parameter.
01645  *
01646  *  An Enumerator is returned if no block is given.
01647  *
01648  *     a = [ "a", "b", "c" ]
01649  *     a.each {|x| print x, " -- " }
01650  *
01651  *  produces:
01652  *
01653  *     a -- b -- c --
01654  */
01655 
01656 VALUE
01657 rb_ary_each(VALUE array)
01658 {
01659     long i;
01660     volatile VALUE ary = array;
01661 
01662     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
01663     for (i=0; i<RARRAY_LEN(ary); i++) {
01664         rb_yield(RARRAY_PTR(ary)[i]);
01665     }
01666     return ary;
01667 }
01668 
01669 /*
01670  *  call-seq:
01671  *     ary.each_index { |index| block }  -> ary
01672  *     ary.each_index                    -> Enumerator
01673  *
01674  *  Same as Array#each, but passes the +index+ of the element instead of the
01675  *  element itself.
01676  *
01677  *  An Enumerator is returned if no block is given.
01678  *
01679  *     a = [ "a", "b", "c" ]
01680  *     a.each_index {|x| print x, " -- " }
01681  *
01682  *  produces:
01683  *
01684  *     0 -- 1 -- 2 --
01685  */
01686 
01687 static VALUE
01688 rb_ary_each_index(VALUE ary)
01689 {
01690     long i;
01691     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
01692 
01693     for (i=0; i<RARRAY_LEN(ary); i++) {
01694         rb_yield(LONG2NUM(i));
01695     }
01696     return ary;
01697 }
01698 
01699 /*
01700  *  call-seq:
01701  *     ary.reverse_each { |item| block }  -> ary
01702  *     ary.reverse_each                   -> Enumerator
01703  *
01704  *  Same as Array#each, but traverses +self+ in reverse order.
01705  *
01706  *     a = [ "a", "b", "c" ]
01707  *     a.reverse_each {|x| print x, " " }
01708  *
01709  *  produces:
01710  *
01711  *     c b a
01712  */
01713 
01714 static VALUE
01715 rb_ary_reverse_each(VALUE ary)
01716 {
01717     long len;
01718 
01719     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
01720     len = RARRAY_LEN(ary);
01721     while (len--) {
01722         rb_yield(RARRAY_PTR(ary)[len]);
01723         if (RARRAY_LEN(ary) < len) {
01724             len = RARRAY_LEN(ary);
01725         }
01726     }
01727     return ary;
01728 }
01729 
01730 /*
01731  *  call-seq:
01732  *     ary.length -> int
01733  *
01734  *  Returns the number of elements in +self+. May be zero.
01735  *
01736  *     [ 1, 2, 3, 4, 5 ].length   #=> 5
01737  *     [].length                  #=> 0
01738  */
01739 
01740 static VALUE
01741 rb_ary_length(VALUE ary)
01742 {
01743     long len = RARRAY_LEN(ary);
01744     return LONG2NUM(len);
01745 }
01746 
01747 /*
01748  *  call-seq:
01749  *     ary.empty?   -> true or false
01750  *
01751  *  Returns +true+ if +self+ contains no elements.
01752  *
01753  *     [].empty?   #=> true
01754  */
01755 
01756 static VALUE
01757 rb_ary_empty_p(VALUE ary)
01758 {
01759     if (RARRAY_LEN(ary) == 0)
01760         return Qtrue;
01761     return Qfalse;
01762 }
01763 
01764 VALUE
01765 rb_ary_dup(VALUE ary)
01766 {
01767     VALUE dup = rb_ary_new2(RARRAY_LEN(ary));
01768     MEMCPY(RARRAY_PTR(dup), RARRAY_PTR(ary), VALUE, RARRAY_LEN(ary));
01769     ARY_SET_LEN(dup, RARRAY_LEN(ary));
01770     return dup;
01771 }
01772 
01773 VALUE
01774 rb_ary_resurrect(VALUE ary)
01775 {
01776     return rb_ary_new4(RARRAY_LEN(ary), RARRAY_PTR(ary));
01777 }
01778 
01779 extern VALUE rb_output_fs;
01780 
01781 static void ary_join_1(VALUE obj, VALUE ary, VALUE sep, long i, VALUE result, int *first);
01782 
01783 static VALUE
01784 recursive_join(VALUE obj, VALUE argp, int recur)
01785 {
01786     VALUE *arg = (VALUE *)argp;
01787     VALUE ary = arg[0];
01788     VALUE sep = arg[1];
01789     VALUE result = arg[2];
01790     int *first = (int *)arg[3];
01791 
01792     if (recur) {
01793         rb_raise(rb_eArgError, "recursive array join");
01794     }
01795     else {
01796         ary_join_1(obj, ary, sep, 0, result, first);
01797     }
01798     return Qnil;
01799 }
01800 
01801 static void
01802 ary_join_0(VALUE ary, VALUE sep, long max, VALUE result)
01803 {
01804     long i;
01805     VALUE val;
01806 
01807     if (max > 0) rb_enc_copy(result, RARRAY_PTR(ary)[0]);
01808     for (i=0; i<max; i++) {
01809         val = RARRAY_PTR(ary)[i];
01810         if (i > 0 && !NIL_P(sep))
01811             rb_str_buf_append(result, sep);
01812         rb_str_buf_append(result, val);
01813         if (OBJ_TAINTED(val)) OBJ_TAINT(result);
01814         if (OBJ_UNTRUSTED(val)) OBJ_TAINT(result);
01815     }
01816 }
01817 
01818 static void
01819 ary_join_1(VALUE obj, VALUE ary, VALUE sep, long i, VALUE result, int *first)
01820 {
01821     VALUE val, tmp;
01822 
01823     for (; i<RARRAY_LEN(ary); i++) {
01824         if (i > 0 && !NIL_P(sep))
01825             rb_str_buf_append(result, sep);
01826 
01827         val = RARRAY_PTR(ary)[i];
01828         switch (TYPE(val)) {
01829           case T_STRING:
01830           str_join:
01831             rb_str_buf_append(result, val);
01832             *first = FALSE;
01833             break;
01834           case T_ARRAY:
01835             obj = val;
01836           ary_join:
01837             if (val == ary) {
01838                 rb_raise(rb_eArgError, "recursive array join");
01839             }
01840             else {
01841                 VALUE args[4];
01842 
01843                 args[0] = val;
01844                 args[1] = sep;
01845                 args[2] = result;
01846                 args[3] = (VALUE)first;
01847                 rb_exec_recursive(recursive_join, obj, (VALUE)args);
01848             }
01849             break;
01850           default:
01851             tmp = rb_check_string_type(val);
01852             if (!NIL_P(tmp)) {
01853                 val = tmp;
01854                 goto str_join;
01855             }
01856             tmp = rb_check_convert_type(val, T_ARRAY, "Array", "to_ary");
01857             if (!NIL_P(tmp)) {
01858                 obj = val;
01859                 val = tmp;
01860                 goto ary_join;
01861             }
01862             val = rb_obj_as_string(val);
01863             if (*first) {
01864                 rb_enc_copy(result, val);
01865                 *first = FALSE;
01866             }
01867             goto str_join;
01868         }
01869     }
01870 }
01871 
01872 VALUE
01873 rb_ary_join(VALUE ary, VALUE sep)
01874 {
01875     long len = 1, i;
01876     int taint = FALSE;
01877     int untrust = FALSE;
01878     VALUE val, tmp, result;
01879 
01880     if (RARRAY_LEN(ary) == 0) return rb_usascii_str_new(0, 0);
01881     if (OBJ_TAINTED(ary)) taint = TRUE;
01882     if (OBJ_UNTRUSTED(ary)) untrust = TRUE;
01883 
01884     if (!NIL_P(sep)) {
01885         StringValue(sep);
01886         len += RSTRING_LEN(sep) * (RARRAY_LEN(ary) - 1);
01887     }
01888     for (i=0; i<RARRAY_LEN(ary); i++) {
01889         val = RARRAY_PTR(ary)[i];
01890         tmp = rb_check_string_type(val);
01891 
01892         if (NIL_P(tmp) || tmp != val) {
01893             int first;
01894             result = rb_str_buf_new(len + (RARRAY_LEN(ary)-i)*10);
01895             rb_enc_associate(result, rb_usascii_encoding());
01896             if (taint) OBJ_TAINT(result);
01897             if (untrust) OBJ_UNTRUST(result);
01898             ary_join_0(ary, sep, i, result);
01899             first = i == 0;
01900             ary_join_1(ary, ary, sep, i, result, &first);
01901             return result;
01902         }
01903 
01904         len += RSTRING_LEN(tmp);
01905     }
01906 
01907     result = rb_str_buf_new(len);
01908     if (taint) OBJ_TAINT(result);
01909     if (untrust) OBJ_UNTRUST(result);
01910     ary_join_0(ary, sep, RARRAY_LEN(ary), result);
01911 
01912     return result;
01913 }
01914 
01915 /*
01916  *  call-seq:
01917  *     ary.join(separator=$,)    -> str
01918  *
01919  *  Returns a string created by converting each element of the array to
01920  *  a string, separated by the given +separator+.
01921  *  If the +separator+ is +nil+, it uses current $,.
01922  *  If both the +separator+ and $, are nil, it uses empty string.
01923  *
01924  *     [ "a", "b", "c" ].join        #=> "abc"
01925  *     [ "a", "b", "c" ].join("-")   #=> "a-b-c"
01926  */
01927 
01928 static VALUE
01929 rb_ary_join_m(int argc, VALUE *argv, VALUE ary)
01930 {
01931     VALUE sep;
01932 
01933     rb_scan_args(argc, argv, "01", &sep);
01934     if (NIL_P(sep)) sep = rb_output_fs;
01935 
01936     return rb_ary_join(ary, sep);
01937 }
01938 
01939 static VALUE
01940 inspect_ary(VALUE ary, VALUE dummy, int recur)
01941 {
01942     int tainted = OBJ_TAINTED(ary);
01943     int untrust = OBJ_UNTRUSTED(ary);
01944     long i;
01945     VALUE s, str;
01946 
01947     if (recur) return rb_usascii_str_new_cstr("[...]");
01948     str = rb_str_buf_new2("[");
01949     for (i=0; i<RARRAY_LEN(ary); i++) {
01950         s = rb_inspect(RARRAY_PTR(ary)[i]);
01951         if (OBJ_TAINTED(s)) tainted = TRUE;
01952         if (OBJ_UNTRUSTED(s)) untrust = TRUE;
01953         if (i > 0) rb_str_buf_cat2(str, ", ");
01954         else rb_enc_copy(str, s);
01955         rb_str_buf_append(str, s);
01956     }
01957     rb_str_buf_cat2(str, "]");
01958     if (tainted) OBJ_TAINT(str);
01959     if (untrust) OBJ_UNTRUST(str);
01960     return str;
01961 }
01962 
01963 /*
01964  *  call-seq:
01965  *     ary.inspect  -> string
01966  *     ary.to_s     -> string
01967  *
01968  *  Creates a string representation of +self+.
01969  *
01970  *     [ "a", "b", "c" ].to_s     #=> "[\"a\", \"b\", \"c\"]"
01971  */
01972 
01973 static VALUE
01974 rb_ary_inspect(VALUE ary)
01975 {
01976     if (RARRAY_LEN(ary) == 0) return rb_usascii_str_new2("[]");
01977     return rb_exec_recursive(inspect_ary, ary, 0);
01978 }
01979 
01980 VALUE
01981 rb_ary_to_s(VALUE ary)
01982 {
01983     return rb_ary_inspect(ary);
01984 }
01985 
01986 /*
01987  *  call-seq:
01988  *     ary.to_a     -> ary
01989  *
01990  *  Returns +self+.
01991  *
01992  *  If called on a subclass of Array, converts the receiver to an Array object.
01993  */
01994 
01995 static VALUE
01996 rb_ary_to_a(VALUE ary)
01997 {
01998     if (rb_obj_class(ary) != rb_cArray) {
01999         VALUE dup = rb_ary_new2(RARRAY_LEN(ary));
02000         rb_ary_replace(dup, ary);
02001         return dup;
02002     }
02003     return ary;
02004 }
02005 
02006 /*
02007  *  call-seq:
02008  *     ary.to_ary -> ary
02009  *
02010  *  Returns +self+.
02011  */
02012 
02013 static VALUE
02014 rb_ary_to_ary_m(VALUE ary)
02015 {
02016     return ary;
02017 }
02018 
02019 static void
02020 ary_reverse(VALUE *p1, VALUE *p2)
02021 {
02022     while (p1 < p2) {
02023         VALUE tmp = *p1;
02024         *p1++ = *p2;
02025         *p2-- = tmp;
02026     }
02027 }
02028 
02029 VALUE
02030 rb_ary_reverse(VALUE ary)
02031 {
02032     VALUE *p1, *p2;
02033 
02034     rb_ary_modify(ary);
02035     if (RARRAY_LEN(ary) > 1) {
02036         p1 = RARRAY_PTR(ary);
02037         p2 = p1 + RARRAY_LEN(ary) - 1;  /* points last item */
02038         ary_reverse(p1, p2);
02039     }
02040     return ary;
02041 }
02042 
02043 /*
02044  *  call-seq:
02045  *     ary.reverse!   -> ary
02046  *
02047  *  Reverses +self+ in place.
02048  *
02049  *     a = [ "a", "b", "c" ]
02050  *     a.reverse!       #=> ["c", "b", "a"]
02051  *     a                #=> ["c", "b", "a"]
02052  */
02053 
02054 static VALUE
02055 rb_ary_reverse_bang(VALUE ary)
02056 {
02057     return rb_ary_reverse(ary);
02058 }
02059 
02060 /*
02061  *  call-seq:
02062  *     ary.reverse    -> new_ary
02063  *
02064  *  Returns a new array containing +self+'s elements in reverse order.
02065  *
02066  *     [ "a", "b", "c" ].reverse   #=> ["c", "b", "a"]
02067  *     [ 1 ].reverse               #=> [1]
02068  */
02069 
02070 static VALUE
02071 rb_ary_reverse_m(VALUE ary)
02072 {
02073     long len = RARRAY_LEN(ary);
02074     VALUE dup = rb_ary_new2(len);
02075 
02076     if (len > 0) {
02077         VALUE *p1 = RARRAY_PTR(ary);
02078         VALUE *p2 = RARRAY_PTR(dup) + len - 1;
02079         do *p2-- = *p1++; while (--len > 0);
02080     }
02081     ARY_SET_LEN(dup, RARRAY_LEN(ary));
02082     return dup;
02083 }
02084 
02085 static inline long
02086 rotate_count(long cnt, long len)
02087 {
02088     return (cnt < 0) ? (len - (~cnt % len) - 1) : (cnt % len);
02089 }
02090 
02091 VALUE
02092 rb_ary_rotate(VALUE ary, long cnt)
02093 {
02094     rb_ary_modify(ary);
02095 
02096     if (cnt != 0) {
02097         VALUE *ptr = RARRAY_PTR(ary);
02098         long len = RARRAY_LEN(ary);
02099 
02100         if (len > 0 && (cnt = rotate_count(cnt, len)) > 0) {
02101             --len;
02102             if (cnt < len) ary_reverse(ptr + cnt, ptr + len);
02103             if (--cnt > 0) ary_reverse(ptr, ptr + cnt);
02104             if (len > 0) ary_reverse(ptr, ptr + len);
02105             return ary;
02106         }
02107     }
02108 
02109     return Qnil;
02110 }
02111 
02112 /*
02113  *  call-seq:
02114  *     ary.rotate!(count=1)   -> ary
02115  *
02116  *  Rotates +self+ in place so that the element at +count+ comes first, and
02117  *  returns +self+.
02118  *
02119  *  If +count+ is negative then it rotates in the opposite direction, starting
02120  *  from the end of the array where +-1+ is the last element.
02121  *
02122  *     a = [ "a", "b", "c", "d" ]
02123  *     a.rotate!        #=> ["b", "c", "d", "a"]
02124  *     a                #=> ["b", "c", "d", "a"]
02125  *     a.rotate!(2)     #=> ["d", "a", "b", "c"]
02126  *     a.rotate!(-3)    #=> ["a", "b", "c", "d"]
02127  */
02128 
02129 static VALUE
02130 rb_ary_rotate_bang(int argc, VALUE *argv, VALUE ary)
02131 {
02132     long n = 1;
02133 
02134     switch (argc) {
02135       case 1: n = NUM2LONG(argv[0]);
02136       case 0: break;
02137       default: rb_scan_args(argc, argv, "01", NULL);
02138     }
02139     rb_ary_rotate(ary, n);
02140     return ary;
02141 }
02142 
02143 /*
02144  *  call-seq:
02145  *     ary.rotate(count=1)    -> new_ary
02146  *
02147  *  Returns a new array by rotating +self+ so that the element at +count+ is
02148  *  the first element of the new array.
02149  *
02150  *  If +count+ is negative then it rotates in the opposite direction, starting
02151  *  from the end of +self+ where +-1+ is the last element.
02152  *
02153  *     a = [ "a", "b", "c", "d" ]
02154  *     a.rotate         #=> ["b", "c", "d", "a"]
02155  *     a                #=> ["a", "b", "c", "d"]
02156  *     a.rotate(2)      #=> ["c", "d", "a", "b"]
02157  *     a.rotate(-3)     #=> ["b", "c", "d", "a"]
02158  */
02159 
02160 static VALUE
02161 rb_ary_rotate_m(int argc, VALUE *argv, VALUE ary)
02162 {
02163     VALUE rotated, *ptr, *ptr2;
02164     long len, cnt = 1;
02165 
02166     switch (argc) {
02167       case 1: cnt = NUM2LONG(argv[0]);
02168       case 0: break;
02169       default: rb_scan_args(argc, argv, "01", NULL);
02170     }
02171 
02172     len = RARRAY_LEN(ary);
02173     rotated = rb_ary_new2(len);
02174     if (len > 0) {
02175         cnt = rotate_count(cnt, len);
02176         ptr = RARRAY_PTR(ary);
02177         ptr2 = RARRAY_PTR(rotated);
02178         len -= cnt;
02179         MEMCPY(ptr2, ptr + cnt, VALUE, len);
02180         MEMCPY(ptr2 + len, ptr, VALUE, cnt);
02181     }
02182     ARY_SET_LEN(rotated, RARRAY_LEN(ary));
02183     return rotated;
02184 }
02185 
02186 struct ary_sort_data {
02187     VALUE ary;
02188     int opt_methods;
02189     int opt_inited;
02190 };
02191 
02192 enum {
02193     sort_opt_Fixnum,
02194     sort_opt_String,
02195     sort_optimizable_count
02196 };
02197 
02198 #define STRING_P(s) (RB_TYPE_P((s), T_STRING) && CLASS_OF(s) == rb_cString)
02199 
02200 #define SORT_OPTIMIZABLE_BIT(type) (1U << TOKEN_PASTE(sort_opt_,type))
02201 #define SORT_OPTIMIZABLE(data, type) \
02202     (((data)->opt_inited & SORT_OPTIMIZABLE_BIT(type)) ? \
02203      ((data)->opt_methods & SORT_OPTIMIZABLE_BIT(type)) : \
02204      (((data)->opt_inited |= SORT_OPTIMIZABLE_BIT(type)), \
02205       rb_method_basic_definition_p(TOKEN_PASTE(rb_c,type), id_cmp) && \
02206       ((data)->opt_methods |= SORT_OPTIMIZABLE_BIT(type))))
02207 
02208 static VALUE
02209 sort_reentered(VALUE ary)
02210 {
02211     if (RBASIC(ary)->klass) {
02212         rb_raise(rb_eRuntimeError, "sort reentered");
02213     }
02214     return Qnil;
02215 }
02216 
02217 static int
02218 sort_1(const void *ap, const void *bp, void *dummy)
02219 {
02220     struct ary_sort_data *data = dummy;
02221     VALUE retval = sort_reentered(data->ary);
02222     VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
02223     int n;
02224 
02225     retval = rb_yield_values(2, a, b);
02226     n = rb_cmpint(retval, a, b);
02227     sort_reentered(data->ary);
02228     return n;
02229 }
02230 
02231 static int
02232 sort_2(const void *ap, const void *bp, void *dummy)
02233 {
02234     struct ary_sort_data *data = dummy;
02235     VALUE retval = sort_reentered(data->ary);
02236     VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
02237     int n;
02238 
02239     if (FIXNUM_P(a) && FIXNUM_P(b) && SORT_OPTIMIZABLE(data, Fixnum)) {
02240         if ((long)a > (long)b) return 1;
02241         if ((long)a < (long)b) return -1;
02242         return 0;
02243     }
02244     if (STRING_P(a) && STRING_P(b) && SORT_OPTIMIZABLE(data, String)) {
02245         return rb_str_cmp(a, b);
02246     }
02247 
02248     retval = rb_funcall(a, id_cmp, 1, b);
02249     n = rb_cmpint(retval, a, b);
02250     sort_reentered(data->ary);
02251 
02252     return n;
02253 }
02254 
02255 /*
02256  *  call-seq:
02257  *     ary.sort!                   -> ary
02258  *     ary.sort! { |a, b| block }  -> ary
02259  *
02260  *  Sorts +self+ in place.
02261  *
02262  *  Comparisons for the sort will be done using the <code><=></code> operator
02263  *  or using an optional code block.
02264  *
02265  *  The block must implement a comparison between +a+ and +b+, and return
02266  *  +-1+, when +a+ follows +b+, +0+ when +a+ and +b+ are equivalent, or ++1+
02267  *  if +b+ follows +a+.
02268  *
02269  *  See also Enumerable#sort_by.
02270  *
02271  *     a = [ "d", "a", "e", "c", "b" ]
02272  *     a.sort!                    #=> ["a", "b", "c", "d", "e"]
02273  *     a.sort! { |x,y| y <=> x }  #=> ["e", "d", "c", "b", "a"]
02274  */
02275 
02276 VALUE
02277 rb_ary_sort_bang(VALUE ary)
02278 {
02279     rb_ary_modify(ary);
02280     assert(!ARY_SHARED_P(ary));
02281     if (RARRAY_LEN(ary) > 1) {
02282         VALUE tmp = ary_make_substitution(ary); /* only ary refers tmp */
02283         struct ary_sort_data data;
02284         long len = RARRAY_LEN(ary);
02285 
02286         RBASIC(tmp)->klass = 0;
02287         data.ary = tmp;
02288         data.opt_methods = 0;
02289         data.opt_inited = 0;
02290         ruby_qsort(RARRAY_PTR(tmp), len, sizeof(VALUE),
02291                    rb_block_given_p()?sort_1:sort_2, &data);
02292 
02293         if (ARY_EMBED_P(tmp)) {
02294             assert(ARY_EMBED_P(tmp));
02295             if (ARY_SHARED_P(ary)) { /* ary might be destructively operated in the given block */
02296                 rb_ary_unshare(ary);
02297             }
02298             FL_SET_EMBED(ary);
02299             MEMCPY(RARRAY_PTR(ary), ARY_EMBED_PTR(tmp), VALUE, ARY_EMBED_LEN(tmp));
02300             ARY_SET_LEN(ary, ARY_EMBED_LEN(tmp));
02301         }
02302         else {
02303             assert(!ARY_EMBED_P(tmp));
02304             if (ARY_HEAP_PTR(ary) == ARY_HEAP_PTR(tmp)) {
02305                 assert(!ARY_EMBED_P(ary));
02306                 FL_UNSET_SHARED(ary);
02307                 ARY_SET_CAPA(ary, RARRAY_LEN(tmp));
02308             }
02309             else {
02310                 assert(!ARY_SHARED_P(tmp));
02311                 if (ARY_EMBED_P(ary)) {
02312                     FL_UNSET_EMBED(ary);
02313                 }
02314                 else if (ARY_SHARED_P(ary)) {
02315                     /* ary might be destructively operated in the given block */
02316                     rb_ary_unshare(ary);
02317                 }
02318                 else {
02319                     xfree(ARY_HEAP_PTR(ary));
02320                 }
02321                 ARY_SET_PTR(ary, RARRAY_PTR(tmp));
02322                 ARY_SET_HEAP_LEN(ary, len);
02323                 ARY_SET_CAPA(ary, RARRAY_LEN(tmp));
02324             }
02325             /* tmp was lost ownership for the ptr */
02326             FL_UNSET(tmp, FL_FREEZE);
02327             FL_SET_EMBED(tmp);
02328             ARY_SET_EMBED_LEN(tmp, 0);
02329             FL_SET(tmp, FL_FREEZE);
02330         }
02331         /* tmp will be GC'ed. */
02332         RBASIC(tmp)->klass = rb_cArray;
02333     }
02334     return ary;
02335 }
02336 
02337 /*
02338  *  call-seq:
02339  *     ary.sort                   -> new_ary
02340  *     ary.sort { |a, b| block }  -> new_ary
02341  *
02342  *  Returns a new array created by sorting +self+.
02343  *
02344  *  Comparisons for the sort will be done using the <code><=></code> operator
02345  *  or using an optional code block.
02346  *
02347  *  The block must implement a comparison between +a+ and +b+, and return
02348  *  +-1+, when +a+ follows +b+, +0+ when +a+ and +b+ are equivalent, or ++1+
02349  *  if +b+ follows +a+.
02350  *
02351  *
02352  *  See also Enumerable#sort_by.
02353  *
02354  *     a = [ "d", "a", "e", "c", "b" ]
02355  *     a.sort                    #=> ["a", "b", "c", "d", "e"]
02356  *     a.sort { |x,y| y <=> x }  #=> ["e", "d", "c", "b", "a"]
02357  */
02358 
02359 VALUE
02360 rb_ary_sort(VALUE ary)
02361 {
02362     ary = rb_ary_dup(ary);
02363     rb_ary_sort_bang(ary);
02364     return ary;
02365 }
02366 
02367 /*
02368  *  call-seq:
02369  *     ary.bsearch {|x| block }  -> elem
02370  *
02371  *  By using binary search, finds a value from this array which meets
02372  *  the given condition in O(log n) where n is the size of the array.
02373  *
02374  *  You can use this method in two use cases: a find-minimum mode and
02375  *  a find-any mode.  In either case, the elements of the array must be
02376  *  monotone (or sorted) with respect to the block.
02377  *
02378  *  In find-minimum mode (this is a good choice for typical use case),
02379  *  the block must return true or false, and there must be an index i
02380  *  (0 <= i <= ary.size) so that:
02381  *
02382  *  - the block returns false for any element whose index is less than
02383  *    i, and
02384  *  - the block returns true for any element whose index is greater
02385  *    than or equal to i.
02386  *
02387  *  This method returns the i-th element.  If i is equal to ary.size,
02388  *  it returns nil.
02389  *
02390  *     ary = [0, 4, 7, 10, 12]
02391  *     ary.bsearch {|x| x >=   4 } #=> 4
02392  *     ary.bsearch {|x| x >=   6 } #=> 7
02393  *     ary.bsearch {|x| x >=  -1 } #=> 0
02394  *     ary.bsearch {|x| x >= 100 } #=> nil
02395  *
02396  *  In find-any mode (this behaves like libc's bsearch(3)), the block
02397  *  must return a number, and there must be two indices i and j
02398  *  (0 <= i <= j <= ary.size) so that:
02399  *
02400  *  - the block returns a positive number for ary[k] if 0 <= k < i,
02401  *  - the block returns zero for ary[k] if i <= k < j, and
02402  *  - the block returns a negative number for ary[k] if
02403  *    j <= k < ary.size.
02404  *
02405  *  Under this condition, this method returns any element whose index
02406  *  is within i...j.  If i is equal to j (i.e., there is no element
02407  *  that satisfies the block), this method returns nil.
02408  *
02409  *     ary = [0, 4, 7, 10, 12]
02410  *     # try to find v such that 4 <= v < 8
02411  *     ary.bsearch {|x| 1 - x / 4 } #=> 4 or 7
02412  *     # try to find v such that 8 <= v < 10
02413  *     ary.bsearch {|x| 4 - x / 2 } #=> nil
02414  *
02415  *  You must not mix the two modes at a time; the block must always
02416  *  return either true/false, or always return a number.  It is
02417  *  undefined which value is actually picked up at each iteration.
02418  */
02419 
02420 static VALUE
02421 rb_ary_bsearch(VALUE ary)
02422 {
02423     long low = 0, high = RARRAY_LEN(ary), mid;
02424     int smaller = 0, satisfied = 0;
02425     VALUE v, val;
02426 
02427     RETURN_ENUMERATOR(ary, 0, 0);
02428     while (low < high) {
02429         mid = low + ((high - low) / 2);
02430         val = rb_ary_entry(ary, mid);
02431         v = rb_yield(val);
02432         if (FIXNUM_P(v)) {
02433             if (FIX2INT(v) == 0) return val;
02434             smaller = FIX2INT(v) < 0;
02435         }
02436         else if (v == Qtrue) {
02437             satisfied = 1;
02438             smaller = 1;
02439         }
02440         else if (v == Qfalse || v == Qnil) {
02441             smaller = 0;
02442         }
02443         else if (rb_obj_is_kind_of(v, rb_cNumeric)) {
02444             switch (rb_cmpint(rb_funcall(v, id_cmp, 1, INT2FIX(0)), v, INT2FIX(0))) {
02445                 case 0: return val;
02446                 case 1: smaller = 1; break;
02447                 case -1: smaller = 0;
02448             }
02449         }
02450         else {
02451             rb_raise(rb_eTypeError, "wrong argument type %s"
02452                 " (must be numeric, true, false or nil)",
02453                 rb_obj_classname(v));
02454         }
02455         if (smaller) {
02456             high = mid;
02457         }
02458         else {
02459             low = mid + 1;
02460         }
02461     }
02462     if (low == RARRAY_LEN(ary)) return Qnil;
02463     if (!satisfied) return Qnil;
02464     return rb_ary_entry(ary, low);
02465 }
02466 
02467 
02468 static VALUE
02469 sort_by_i(VALUE i)
02470 {
02471     return rb_yield(i);
02472 }
02473 
02474 /*
02475  *  call-seq:
02476  *     ary.sort_by! { |obj| block }    -> ary
02477  *     ary.sort_by!                    -> Enumerator
02478  *
02479  *  Sorts +self+ in place using a set of keys generated by mapping the
02480  *  values in +self+ through the given block.
02481  *
02482  *  If no block is given, an Enumerator is returned instead.
02483  *
02484  */
02485 
02486 static VALUE
02487 rb_ary_sort_by_bang(VALUE ary)
02488 {
02489     VALUE sorted;
02490 
02491     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
02492     rb_ary_modify(ary);
02493     sorted = rb_block_call(ary, rb_intern("sort_by"), 0, 0, sort_by_i, 0);
02494     rb_ary_replace(ary, sorted);
02495     return ary;
02496 }
02497 
02498 
02499 /*
02500  *  call-seq:
02501  *     ary.collect { |item| block }  -> new_ary
02502  *     ary.map     { |item| block }  -> new_ary
02503  *     ary.collect                   -> Enumerator
02504  *     ary.map                       -> Enumerator
02505  *
02506  *  Invokes the given block once for each element of +self+.
02507  *
02508  *  Creates a new array containing the values returned by the block.
02509  *
02510  *  See also Enumerable#collect.
02511  *
02512  *  If no block is given, an Enumerator is returned instead.
02513  *
02514  *     a = [ "a", "b", "c", "d" ]
02515  *     a.map { |x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
02516  *     a                       #=> ["a", "b", "c", "d"]
02517  */
02518 
02519 static VALUE
02520 rb_ary_collect(VALUE ary)
02521 {
02522     long i;
02523     VALUE collect;
02524 
02525     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
02526     collect = rb_ary_new2(RARRAY_LEN(ary));
02527     for (i = 0; i < RARRAY_LEN(ary); i++) {
02528         rb_ary_push(collect, rb_yield(RARRAY_PTR(ary)[i]));
02529     }
02530     return collect;
02531 }
02532 
02533 
02534 /*
02535  *  call-seq:
02536  *     ary.collect! {|item| block }   -> ary
02537  *     ary.map!     {|item| block }   -> ary
02538  *     ary.collect!                   -> Enumerator
02539  *     ary.map!                       -> Enumerator
02540  *
02541  *  Invokes the given block once for each element of +self+, replacing the
02542  *  element with the value returned by the block.
02543  *
02544  *  See also Enumerable#collect.
02545  *
02546  *  If no block is given, an Enumerator is returned instead.
02547  *
02548  *     a = [ "a", "b", "c", "d" ]
02549  *     a.map! {|x| x + "!" }
02550  *     a #=>  [ "a!", "b!", "c!", "d!" ]
02551  */
02552 
02553 static VALUE
02554 rb_ary_collect_bang(VALUE ary)
02555 {
02556     long i;
02557 
02558     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
02559     rb_ary_modify(ary);
02560     for (i = 0; i < RARRAY_LEN(ary); i++) {
02561         rb_ary_store(ary, i, rb_yield(RARRAY_PTR(ary)[i]));
02562     }
02563     return ary;
02564 }
02565 
02566 VALUE
02567 rb_get_values_at(VALUE obj, long olen, int argc, VALUE *argv, VALUE (*func) (VALUE, long))
02568 {
02569     VALUE result = rb_ary_new2(argc);
02570     long beg, len, i, j;
02571 
02572     for (i=0; i<argc; i++) {
02573         if (FIXNUM_P(argv[i])) {
02574             rb_ary_push(result, (*func)(obj, FIX2LONG(argv[i])));
02575             continue;
02576         }
02577         /* check if idx is Range */
02578         if (rb_range_beg_len(argv[i], &beg, &len, olen, 1)) {
02579             long end = olen < beg+len ? olen : beg+len;
02580             for (j = beg; j < end; j++) {
02581                 rb_ary_push(result, (*func)(obj, j));
02582             }
02583             if (beg + len > j)
02584                 rb_ary_resize(result, RARRAY_LEN(result) + (beg + len) - j);
02585             continue;
02586         }
02587         rb_ary_push(result, (*func)(obj, NUM2LONG(argv[i])));
02588     }
02589     return result;
02590 }
02591 
02592 /*
02593  *  call-seq:
02594  *     ary.values_at(selector, ...)  -> new_ary
02595  *
02596  *  Returns an array containing the elements in +self+ corresponding to the
02597  *  given +selector+(s).
02598  *
02599  *  The selectors may be either integer indices or ranges.
02600  *
02601  *  See also Array#select.
02602  *
02603  *     a = %w{ a b c d e f }
02604  *     a.values_at(1, 3, 5)          # => ["b", "d", "f"]
02605  *     a.values_at(1, 3, 5, 7)       # => ["b", "d", "f", nil]
02606  *     a.values_at(-1, -2, -2, -7)   # => ["f", "e", "e", nil]
02607  *     a.values_at(4..6, 3...6)      # => ["e", "f", nil, "d", "e", "f"]
02608  */
02609 
02610 static VALUE
02611 rb_ary_values_at(int argc, VALUE *argv, VALUE ary)
02612 {
02613     return rb_get_values_at(ary, RARRAY_LEN(ary), argc, argv, rb_ary_entry);
02614 }
02615 
02616 
02617 /*
02618  *  call-seq:
02619  *     ary.select { |item| block } -> new_ary
02620  *     ary.select                  -> Enumerator
02621  *
02622  *  Returns a new array containing all elements of +ary+
02623  *  for which the given +block+ returns a true value.
02624  *
02625  *  If no block is given, an Enumerator is returned instead.
02626  *
02627  *     [1,2,3,4,5].select { |num|  num.even?  }   #=> [2, 4]
02628  *
02629  *     a = %w{ a b c d e f }
02630  *     a.select { |v| v =~ /[aeiou]/ }  #=> ["a", "e"]
02631  *
02632  *  See also Enumerable#select.
02633  */
02634 
02635 static VALUE
02636 rb_ary_select(VALUE ary)
02637 {
02638     VALUE result;
02639     long i;
02640 
02641     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
02642     result = rb_ary_new2(RARRAY_LEN(ary));
02643     for (i = 0; i < RARRAY_LEN(ary); i++) {
02644         if (RTEST(rb_yield(RARRAY_PTR(ary)[i]))) {
02645             rb_ary_push(result, rb_ary_elt(ary, i));
02646         }
02647     }
02648     return result;
02649 }
02650 
02651 /*
02652  *  call-seq:
02653  *     ary.select!  {|item| block } -> ary or nil
02654  *     ary.select!                  -> Enumerator
02655  *
02656  *  Invokes the given block passing in successive elements from +self+,
02657  *  deleting elements for which the block returns a +false+ value.
02658  *
02659  *  If changes were made, it will return +self+, otherwise it returns +nil+.
02660  *
02661  *  See also Array#keep_if
02662  *
02663  *  If no block is given, an Enumerator is returned instead.
02664  *
02665  */
02666 
02667 static VALUE
02668 rb_ary_select_bang(VALUE ary)
02669 {
02670     long i1, i2;
02671 
02672     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
02673     rb_ary_modify(ary);
02674     for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) {
02675         VALUE v = RARRAY_PTR(ary)[i1];
02676         if (!RTEST(rb_yield(v))) continue;
02677         if (i1 != i2) {
02678             rb_ary_store(ary, i2, v);
02679         }
02680         i2++;
02681     }
02682 
02683     if (RARRAY_LEN(ary) == i2) return Qnil;
02684     if (i2 < RARRAY_LEN(ary))
02685         ARY_SET_LEN(ary, i2);
02686     return ary;
02687 }
02688 
02689 /*
02690  *  call-seq:
02691  *     ary.keep_if { |item| block } -> ary
02692  *     ary.keep_if                  -> Enumerator
02693  *
02694  *  Deletes every element of +self+ for which the given block evaluates to
02695  *  +false+.
02696  *
02697  *  See also Array#select!
02698  *
02699  *  If no block is given, an Enumerator is returned instead.
02700  *
02701  *     a = %w{ a b c d e f }
02702  *     a.keep_if { |v| v =~ /[aeiou]/ }  #=> ["a", "e"]
02703  */
02704 
02705 static VALUE
02706 rb_ary_keep_if(VALUE ary)
02707 {
02708     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
02709     rb_ary_select_bang(ary);
02710     return ary;
02711 }
02712 
02713 static void
02714 ary_resize_smaller(VALUE ary, long len)
02715 {
02716     rb_ary_modify(ary);
02717     if (RARRAY_LEN(ary) > len) {
02718         ARY_SET_LEN(ary, len);
02719         if (len * 2 < ARY_CAPA(ary) &&
02720             ARY_CAPA(ary) > ARY_DEFAULT_SIZE) {
02721             ary_resize_capa(ary, len * 2);
02722         }
02723     }
02724 }
02725 
02726 /*
02727  *  call-seq:
02728  *     ary.delete(obj)            -> item or nil
02729  *     ary.delete(obj) { block }  -> item or result of block
02730  *
02731  *  Deletes all items from +self+ that are equal to +obj+.
02732  *
02733  *  Returns the last deleted item, or +nil+ if no matching item is found.
02734  *
02735  *  If the optional code block is given, the result of the block is returned if
02736  *  the item is not found.  (To remove +nil+ elements and get an informative
02737  *  return value, use Array#compact!)
02738  *
02739  *     a = [ "a", "b", "b", "b", "c" ]
02740  *     a.delete("b")                   #=> "b"
02741  *     a                               #=> ["a", "c"]
02742  *     a.delete("z")                   #=> nil
02743  *     a.delete("z") { "not found" }   #=> "not found"
02744  */
02745 
02746 VALUE
02747 rb_ary_delete(VALUE ary, VALUE item)
02748 {
02749     VALUE v = item;
02750     long i1, i2;
02751 
02752     for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) {
02753         VALUE e = RARRAY_PTR(ary)[i1];
02754 
02755         if (rb_equal(e, item)) {
02756             v = e;
02757             continue;
02758         }
02759         if (i1 != i2) {
02760             rb_ary_store(ary, i2, e);
02761         }
02762         i2++;
02763     }
02764     if (RARRAY_LEN(ary) == i2) {
02765         if (rb_block_given_p()) {
02766             return rb_yield(item);
02767         }
02768         return Qnil;
02769     }
02770 
02771     ary_resize_smaller(ary, i2);
02772 
02773     return v;
02774 }
02775 
02776 void
02777 rb_ary_delete_same(VALUE ary, VALUE item)
02778 {
02779     long i1, i2;
02780 
02781     for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) {
02782         VALUE e = RARRAY_PTR(ary)[i1];
02783 
02784         if (e == item) {
02785             continue;
02786         }
02787         if (i1 != i2) {
02788             rb_ary_store(ary, i2, e);
02789         }
02790         i2++;
02791     }
02792     if (RARRAY_LEN(ary) == i2) {
02793         return;
02794     }
02795 
02796     ary_resize_smaller(ary, i2);
02797 }
02798 
02799 VALUE
02800 rb_ary_delete_at(VALUE ary, long pos)
02801 {
02802     long len = RARRAY_LEN(ary);
02803     VALUE del;
02804 
02805     if (pos >= len) return Qnil;
02806     if (pos < 0) {
02807         pos += len;
02808         if (pos < 0) return Qnil;
02809     }
02810 
02811     rb_ary_modify(ary);
02812     del = RARRAY_PTR(ary)[pos];
02813     MEMMOVE(RARRAY_PTR(ary)+pos, RARRAY_PTR(ary)+pos+1, VALUE,
02814             RARRAY_LEN(ary)-pos-1);
02815     ARY_INCREASE_LEN(ary, -1);
02816 
02817     return del;
02818 }
02819 
02820 /*
02821  *  call-seq:
02822  *     ary.delete_at(index)  -> obj or nil
02823  *
02824  *  Deletes the element at the specified +index+, returning that element, or
02825  *  +nil+ if the +index+ is out of range.
02826  *
02827  *  See also Array#slice!
02828  *
02829  *     a = ["ant", "bat", "cat", "dog"]
02830  *     a.delete_at(2)    #=> "cat"
02831  *     a                 #=> ["ant", "bat", "dog"]
02832  *     a.delete_at(99)   #=> nil
02833  */
02834 
02835 static VALUE
02836 rb_ary_delete_at_m(VALUE ary, VALUE pos)
02837 {
02838     return rb_ary_delete_at(ary, NUM2LONG(pos));
02839 }
02840 
02841 /*
02842  *  call-seq:
02843  *     ary.slice!(index)         -> obj or nil
02844  *     ary.slice!(start, length) -> new_ary or nil
02845  *     ary.slice!(range)         -> new_ary or nil
02846  *
02847  *  Deletes the element(s) given by an +index+ (optionally up to +length+
02848  *  elements) or by a +range+.
02849  *
02850  *  Returns the deleted object (or objects), or +nil+ if the +index+ is out of
02851  *  range.
02852  *
02853  *     a = [ "a", "b", "c" ]
02854  *     a.slice!(1)     #=> "b"
02855  *     a               #=> ["a", "c"]
02856  *     a.slice!(-1)    #=> "c"
02857  *     a               #=> ["a"]
02858  *     a.slice!(100)   #=> nil
02859  *     a               #=> ["a"]
02860  */
02861 
02862 static VALUE
02863 rb_ary_slice_bang(int argc, VALUE *argv, VALUE ary)
02864 {
02865     VALUE arg1, arg2;
02866     long pos, len, orig_len;
02867 
02868     rb_ary_modify_check(ary);
02869     if (argc == 2) {
02870         pos = NUM2LONG(argv[0]);
02871         len = NUM2LONG(argv[1]);
02872       delete_pos_len:
02873         if (len < 0) return Qnil;
02874         orig_len = RARRAY_LEN(ary);
02875         if (pos < 0) {
02876             pos += orig_len;
02877             if (pos < 0) return Qnil;
02878         }
02879         else if (orig_len < pos) return Qnil;
02880         if (orig_len < pos + len) {
02881             len = orig_len - pos;
02882         }
02883         if (len == 0) return rb_ary_new2(0);
02884         arg2 = rb_ary_new4(len, RARRAY_PTR(ary)+pos);
02885         RBASIC(arg2)->klass = rb_obj_class(ary);
02886         rb_ary_splice(ary, pos, len, Qundef);
02887         return arg2;
02888     }
02889 
02890     if (argc != 1) {
02891         /* error report */
02892         rb_scan_args(argc, argv, "11", NULL, NULL);
02893     }
02894     arg1 = argv[0];
02895 
02896     if (!FIXNUM_P(arg1)) {
02897         switch (rb_range_beg_len(arg1, &pos, &len, RARRAY_LEN(ary), 0)) {
02898           case Qtrue:
02899             /* valid range */
02900             goto delete_pos_len;
02901           case Qnil:
02902             /* invalid range */
02903             return Qnil;
02904           default:
02905             /* not a range */
02906             break;
02907         }
02908     }
02909 
02910     return rb_ary_delete_at(ary, NUM2LONG(arg1));
02911 }
02912 
02913 static VALUE
02914 ary_reject(VALUE orig, VALUE result)
02915 {
02916     long i;
02917 
02918     for (i = 0; i < RARRAY_LEN(orig); i++) {
02919         VALUE v = RARRAY_PTR(orig)[i];
02920         if (!RTEST(rb_yield(v))) {
02921             rb_ary_push(result, v);
02922         }
02923     }
02924     return result;
02925 }
02926 
02927 static VALUE
02928 ary_reject_bang(VALUE ary)
02929 {
02930     long i;
02931     VALUE result = Qnil;
02932 
02933     rb_ary_modify_check(ary);
02934     for (i = 0; i < RARRAY_LEN(ary); ) {
02935         VALUE v = RARRAY_PTR(ary)[i];
02936         if (RTEST(rb_yield(v))) {
02937             rb_ary_delete_at(ary, i);
02938             result = ary;
02939         }
02940         else {
02941             i++;
02942         }
02943     }
02944     return result;
02945 }
02946 
02947 /*
02948  *  call-seq:
02949  *     ary.reject! { |item| block }  -> ary or nil
02950  *     ary.reject!                   -> Enumerator
02951  *
02952  *  Equivalent to Array#delete_if, deleting elements from +self+ for which the
02953  *  block evaluates to +true+, but returns +nil+ if no changes were made.
02954  *
02955  *  The array is changed instantly every time the block is called, not after
02956  *  the iteration is over.
02957  *
02958  *  See also Enumerable#reject and Array#delete_if.
02959  *
02960  *  If no block is given, an Enumerator is returned instead.
02961  */
02962 
02963 static VALUE
02964 rb_ary_reject_bang(VALUE ary)
02965 {
02966     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
02967     return ary_reject_bang(ary);
02968 }
02969 
02970 /*
02971  *  call-seq:
02972  *     ary.reject  {|item| block }  -> new_ary
02973  *     ary.reject                   -> Enumerator
02974  *
02975  *  Returns a new array containing the items in +self+ for which the given
02976  *  block is not +true+.
02977  *
02978  *  See also Array#delete_if
02979  *
02980  *  If no block is given, an Enumerator is returned instead.
02981  */
02982 
02983 static VALUE
02984 rb_ary_reject(VALUE ary)
02985 {
02986     VALUE rejected_ary;
02987 
02988     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
02989     rejected_ary = rb_ary_new();
02990     ary_reject(ary, rejected_ary);
02991     return rejected_ary;
02992 }
02993 
02994 /*
02995  *  call-seq:
02996  *     ary.delete_if { |item| block }  -> ary
02997  *     ary.delete_if                   -> Enumerator
02998  *
02999  *  Deletes every element of +self+ for which block evaluates to +true+.
03000  *
03001  *  The array is changed instantly every time the block is called, not after
03002  *  the iteration is over.
03003  *
03004  *  See also Array#reject!
03005  *
03006  *  If no block is given, an Enumerator is returned instead.
03007  *
03008  *     a = [ "a", "b", "c" ]
03009  *     a.delete_if {|x| x >= "b" }   #=> ["a"]
03010  */
03011 
03012 static VALUE
03013 rb_ary_delete_if(VALUE ary)
03014 {
03015     RETURN_SIZED_ENUMERATOR(ary, 0, 0, rb_ary_length);
03016     ary_reject_bang(ary);
03017     return ary;
03018 }
03019 
03020 static VALUE
03021 take_i(VALUE val, VALUE *args, int argc, VALUE *argv)
03022 {
03023     if (args[1]-- == 0) rb_iter_break();
03024     if (argc > 1) val = rb_ary_new4(argc, argv);
03025     rb_ary_push(args[0], val);
03026     return Qnil;
03027 }
03028 
03029 static VALUE
03030 take_items(VALUE obj, long n)
03031 {
03032     VALUE result = rb_check_array_type(obj);
03033     VALUE args[2];
03034 
03035     if (!NIL_P(result)) return rb_ary_subseq(result, 0, n);
03036     result = rb_ary_new2(n);
03037     args[0] = result; args[1] = (VALUE)n;
03038     if (rb_check_block_call(obj, idEach, 0, 0, take_i, (VALUE)args) == Qundef)
03039         rb_raise(rb_eTypeError, "wrong argument type %s (must respond to :each)",
03040             rb_obj_classname(obj));
03041     return result;
03042 }
03043 
03044 
03045 /*
03046  *  call-seq:
03047  *     ary.zip(arg, ...)                  -> new_ary
03048  *     ary.zip(arg, ...) { |arr| block }  -> nil
03049  *
03050  *  Converts any arguments to arrays, then merges elements of +self+ with
03051  *  corresponding elements from each argument.
03052  *
03053  *  This generates a sequence of <code>ary.size</code> _n_-element arrays,
03054  *  where _n_ is one more than the count of arguments.
03055  *
03056  *  If the size of any argument is less than the size of the initial array,
03057  *  +nil+ values are supplied.
03058  *
03059  *  If a block is given, it is invoked for each output +array+, otherwise an
03060  *  array of arrays is returned.
03061  *
03062  *     a = [ 4, 5, 6 ]
03063  *     b = [ 7, 8, 9 ]
03064  *     [1, 2, 3].zip(a, b)   #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
03065  *     [1, 2].zip(a, b)      #=> [[1, 4, 7], [2, 5, 8]]
03066  *     a.zip([1, 2], [8])    #=> [[4, 1, 8], [5, 2, nil], [6, nil, nil]]
03067  */
03068 
03069 static VALUE
03070 rb_ary_zip(int argc, VALUE *argv, VALUE ary)
03071 {
03072     int i, j;
03073     long len;
03074     VALUE result = Qnil;
03075 
03076     len = RARRAY_LEN(ary);
03077     for (i=0; i<argc; i++) {
03078         argv[i] = take_items(argv[i], len);
03079     }
03080     if (!rb_block_given_p()) {
03081         result = rb_ary_new2(len);
03082     }
03083 
03084     for (i=0; i<RARRAY_LEN(ary); i++) {
03085         VALUE tmp = rb_ary_new2(argc+1);
03086 
03087         rb_ary_push(tmp, rb_ary_elt(ary, i));
03088         for (j=0; j<argc; j++) {
03089             rb_ary_push(tmp, rb_ary_elt(argv[j], i));
03090         }
03091         if (NIL_P(result)) {
03092             rb_yield(tmp);
03093         }
03094         else {
03095             rb_ary_push(result, tmp);
03096         }
03097     }
03098     return result;
03099 }
03100 
03101 /*
03102  *  call-seq:
03103  *     ary.transpose -> new_ary
03104  *
03105  *  Assumes that +self+ is an array of arrays and transposes the rows and
03106  *  columns.
03107  *
03108  *     a = [[1,2], [3,4], [5,6]]
03109  *     a.transpose   #=> [[1, 3, 5], [2, 4, 6]]
03110  *
03111  *  If the length of the subarrays don't match, an IndexError is raised.
03112  */
03113 
03114 static VALUE
03115 rb_ary_transpose(VALUE ary)
03116 {
03117     long elen = -1, alen, i, j;
03118     VALUE tmp, result = 0;
03119 
03120     alen = RARRAY_LEN(ary);
03121     if (alen == 0) return rb_ary_dup(ary);
03122     for (i=0; i<alen; i++) {
03123         tmp = to_ary(rb_ary_elt(ary, i));
03124         if (elen < 0) {         /* first element */
03125             elen = RARRAY_LEN(tmp);
03126             result = rb_ary_new2(elen);
03127             for (j=0; j<elen; j++) {
03128                 rb_ary_store(result, j, rb_ary_new2(alen));
03129             }
03130         }
03131         else if (elen != RARRAY_LEN(tmp)) {
03132             rb_raise(rb_eIndexError, "element size differs (%ld should be %ld)",
03133                      RARRAY_LEN(tmp), elen);
03134         }
03135         for (j=0; j<elen; j++) {
03136             rb_ary_store(rb_ary_elt(result, j), i, rb_ary_elt(tmp, j));
03137         }
03138     }
03139     return result;
03140 }
03141 
03142 /*
03143  *  call-seq:
03144  *     ary.replace(other_ary)  -> ary
03145  *
03146  *  Replaces the contents of +self+ with the contents of +other_ary+,
03147  *  truncating or expanding if necessary.
03148  *
03149  *     a = [ "a", "b", "c", "d", "e" ]
03150  *     a.replace([ "x", "y", "z" ])   #=> ["x", "y", "z"]
03151  *     a                              #=> ["x", "y", "z"]
03152  */
03153 
03154 VALUE
03155 rb_ary_replace(VALUE copy, VALUE orig)
03156 {
03157     rb_ary_modify_check(copy);
03158     orig = to_ary(orig);
03159     if (copy == orig) return copy;
03160 
03161     if (RARRAY_LEN(orig) <= RARRAY_EMBED_LEN_MAX) {
03162         VALUE *ptr;
03163         VALUE shared = 0;
03164 
03165         if (ARY_OWNS_HEAP_P(copy)) {
03166             xfree(RARRAY_PTR(copy));
03167         }
03168         else if (ARY_SHARED_P(copy)) {
03169             shared = ARY_SHARED(copy);
03170             FL_UNSET_SHARED(copy);
03171         }
03172         FL_SET_EMBED(copy);
03173         ptr = RARRAY_PTR(orig);
03174         MEMCPY(RARRAY_PTR(copy), ptr, VALUE, RARRAY_LEN(orig));
03175         if (shared) {
03176             rb_ary_decrement_share(shared);
03177         }
03178         ARY_SET_LEN(copy, RARRAY_LEN(orig));
03179     }
03180     else {
03181         VALUE shared = ary_make_shared(orig);
03182         if (ARY_OWNS_HEAP_P(copy)) {
03183             xfree(RARRAY_PTR(copy));
03184         }
03185         else {
03186             rb_ary_unshare_safe(copy);
03187         }
03188         FL_UNSET_EMBED(copy);
03189         ARY_SET_PTR(copy, RARRAY_PTR(orig));
03190         ARY_SET_LEN(copy, RARRAY_LEN(orig));
03191         rb_ary_set_shared(copy, shared);
03192     }
03193     return copy;
03194 }
03195 
03196 /*
03197  *  call-seq:
03198  *     ary.clear    -> ary
03199  *
03200  *  Removes all elements from +self+.
03201  *
03202  *     a = [ "a", "b", "c", "d", "e" ]
03203  *     a.clear    #=> [ ]
03204  */
03205 
03206 VALUE
03207 rb_ary_clear(VALUE ary)
03208 {
03209     rb_ary_modify_check(ary);
03210     ARY_SET_LEN(ary, 0);
03211     if (ARY_SHARED_P(ary)) {
03212         if (!ARY_EMBED_P(ary)) {
03213             rb_ary_unshare(ary);
03214             FL_SET_EMBED(ary);
03215         }
03216     }
03217     else if (ARY_DEFAULT_SIZE * 2 < ARY_CAPA(ary)) {
03218         ary_resize_capa(ary, ARY_DEFAULT_SIZE * 2);
03219     }
03220     return ary;
03221 }
03222 
03223 /*
03224  *  call-seq:
03225  *     ary.fill(obj)                                 -> ary
03226  *     ary.fill(obj, start [, length])               -> ary
03227  *     ary.fill(obj, range )                         -> ary
03228  *     ary.fill { |index| block }                    -> ary
03229  *     ary.fill(start [, length] ) { |index| block } -> ary
03230  *     ary.fill(range) { |index| block }             -> ary
03231  *
03232  *  The first three forms set the selected elements of +self+ (which
03233  *  may be the entire array) to +obj+.
03234  *
03235  *  A +start+ of +nil+ is equivalent to zero.
03236  *
03237  *  A +length+ of +nil+ is equivalent to the length of the array.
03238  *
03239  *  The last three forms fill the array with the value of the given block,
03240  *  which is passed the absolute index of each element to be filled.
03241  *
03242  *  Negative values of +start+ count from the end of the array, where +-1+ is
03243  *  the last element.
03244  *
03245  *     a = [ "a", "b", "c", "d" ]
03246  *     a.fill("x")              #=> ["x", "x", "x", "x"]
03247  *     a.fill("z", 2, 2)        #=> ["x", "x", "z", "z"]
03248  *     a.fill("y", 0..1)        #=> ["y", "y", "z", "z"]
03249  *     a.fill { |i| i*i }       #=> [0, 1, 4, 9]
03250  *     a.fill(-2) { |i| i*i*i } #=> [0, 1, 8, 27]
03251  */
03252 
03253 static VALUE
03254 rb_ary_fill(int argc, VALUE *argv, VALUE ary)
03255 {
03256     VALUE item, arg1, arg2;
03257     long beg = 0, end = 0, len = 0;
03258     VALUE *p, *pend;
03259     int block_p = FALSE;
03260 
03261     if (rb_block_given_p()) {
03262         block_p = TRUE;
03263         rb_scan_args(argc, argv, "02", &arg1, &arg2);
03264         argc += 1;              /* hackish */
03265     }
03266     else {
03267         rb_scan_args(argc, argv, "12", &item, &arg1, &arg2);
03268     }
03269     switch (argc) {
03270       case 1:
03271         beg = 0;
03272         len = RARRAY_LEN(ary);
03273         break;
03274       case 2:
03275         if (rb_range_beg_len(arg1, &beg, &len, RARRAY_LEN(ary), 1)) {
03276             break;
03277         }
03278         /* fall through */
03279       case 3:
03280         beg = NIL_P(arg1) ? 0 : NUM2LONG(arg1);
03281         if (beg < 0) {
03282             beg = RARRAY_LEN(ary) + beg;
03283             if (beg < 0) beg = 0;
03284         }
03285         len = NIL_P(arg2) ? RARRAY_LEN(ary) - beg : NUM2LONG(arg2);
03286         break;
03287     }
03288     rb_ary_modify(ary);
03289     if (len < 0) {
03290         return ary;
03291     }
03292     if (beg >= ARY_MAX_SIZE || len > ARY_MAX_SIZE - beg) {
03293         rb_raise(rb_eArgError, "argument too big");
03294     }
03295     end = beg + len;
03296     if (RARRAY_LEN(ary) < end) {
03297         if (end >= ARY_CAPA(ary)) {
03298             ary_resize_capa(ary, end);
03299         }
03300         rb_mem_clear(RARRAY_PTR(ary) + RARRAY_LEN(ary), end - RARRAY_LEN(ary));
03301         ARY_SET_LEN(ary, end);
03302     }
03303 
03304     if (block_p) {
03305         VALUE v;
03306         long i;
03307 
03308         for (i=beg; i<end; i++) {
03309             v = rb_yield(LONG2NUM(i));
03310             if (i>=RARRAY_LEN(ary)) break;
03311             RARRAY_PTR(ary)[i] = v;
03312         }
03313     }
03314     else {
03315         p = RARRAY_PTR(ary) + beg;
03316         pend = p + len;
03317         while (p < pend) {
03318             *p++ = item;
03319         }
03320     }
03321     return ary;
03322 }
03323 
03324 /*
03325  *  call-seq:
03326  *     ary + other_ary   -> new_ary
03327  *
03328  *  Concatenation --- Returns a new array built by concatenating the
03329  *  two arrays together to produce a third array.
03330  *
03331  *     [ 1, 2, 3 ] + [ 4, 5 ]    #=> [ 1, 2, 3, 4, 5 ]
03332  *     a = [ "a", "b", "c" ]
03333  *     a + [ "d", "e", "f" ]
03334  *     a                         #=> [ "a", "b", "c", "d", "e", "f" ]
03335  *
03336  *  See also Array#concat.
03337  */
03338 
03339 VALUE
03340 rb_ary_plus(VALUE x, VALUE y)
03341 {
03342     VALUE z;
03343     long len;
03344 
03345     y = to_ary(y);
03346     len = RARRAY_LEN(x) + RARRAY_LEN(y);
03347     z = rb_ary_new2(len);
03348     MEMCPY(RARRAY_PTR(z), RARRAY_PTR(x), VALUE, RARRAY_LEN(x));
03349     MEMCPY(RARRAY_PTR(z) + RARRAY_LEN(x), RARRAY_PTR(y), VALUE, RARRAY_LEN(y));
03350     ARY_SET_LEN(z, len);
03351     return z;
03352 }
03353 
03354 /*
03355  *  call-seq:
03356  *     ary.concat(other_ary)   -> ary
03357  *
03358  *  Appends the elements of +other_ary+ to +self+.
03359  *
03360  *     [ "a", "b" ].concat( ["c", "d"] ) #=> [ "a", "b", "c", "d" ]
03361  *     a = [ 1, 2, 3 ]
03362  *     a.concat( [ 4, 5 ] )
03363  *     a                                 #=> [ 1, 2, 3, 4, 5 ]
03364  *
03365  *  See also Array#+.
03366  */
03367 
03368 VALUE
03369 rb_ary_concat(VALUE x, VALUE y)
03370 {
03371     rb_ary_modify_check(x);
03372     y = to_ary(y);
03373     if (RARRAY_LEN(y) > 0) {
03374         rb_ary_splice(x, RARRAY_LEN(x), 0, y);
03375     }
03376     return x;
03377 }
03378 
03379 
03380 /*
03381  *  call-seq:
03382  *     ary * int     -> new_ary
03383  *     ary * str     -> new_string
03384  *
03385  *  Repetition --- With a String argument, equivalent to
03386  *  <code>ary.join(str)</code>.
03387  *
03388  *  Otherwise, returns a new array built by concatenating the +int+ copies of
03389  *  +self+.
03390  *
03391  *
03392  *     [ 1, 2, 3 ] * 3    #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
03393  *     [ 1, 2, 3 ] * ","  #=> "1,2,3"
03394  *
03395  */
03396 
03397 static VALUE
03398 rb_ary_times(VALUE ary, VALUE times)
03399 {
03400     VALUE ary2, tmp, *ptr, *ptr2;
03401     long t, len;
03402 
03403     tmp = rb_check_string_type(times);
03404     if (!NIL_P(tmp)) {
03405         return rb_ary_join(ary, tmp);
03406     }
03407 
03408     len = NUM2LONG(times);
03409     if (len == 0) {
03410         ary2 = ary_new(rb_obj_class(ary), 0);
03411         goto out;
03412     }
03413     if (len < 0) {
03414         rb_raise(rb_eArgError, "negative argument");
03415     }
03416     if (ARY_MAX_SIZE/len < RARRAY_LEN(ary)) {
03417         rb_raise(rb_eArgError, "argument too big");
03418     }
03419     len *= RARRAY_LEN(ary);
03420 
03421     ary2 = ary_new(rb_obj_class(ary), len);
03422     ARY_SET_LEN(ary2, len);
03423 
03424     ptr = RARRAY_PTR(ary);
03425     ptr2 = RARRAY_PTR(ary2);
03426     t = RARRAY_LEN(ary);
03427     if (0 < t) {
03428         MEMCPY(ptr2, ptr, VALUE, t);
03429         while (t <= len/2) {
03430             MEMCPY(ptr2+t, ptr2, VALUE, t);
03431             t *= 2;
03432         }
03433         if (t < len) {
03434             MEMCPY(ptr2+t, ptr2, VALUE, len-t);
03435         }
03436     }
03437   out:
03438     OBJ_INFECT(ary2, ary);
03439 
03440     return ary2;
03441 }
03442 
03443 /*
03444  *  call-seq:
03445  *     ary.assoc(obj)   -> new_ary  or  nil
03446  *
03447  *  Searches through an array whose elements are also arrays comparing +obj+
03448  *  with the first element of each contained array using <code>obj.==</code>.
03449  *
03450  *  Returns the first contained array that matches (that is, the first
03451  *  associated array), or +nil+ if no match is found.
03452  *
03453  *  See also Array#rassoc
03454  *
03455  *     s1 = [ "colors", "red", "blue", "green" ]
03456  *     s2 = [ "letters", "a", "b", "c" ]
03457  *     s3 = "foo"
03458  *     a  = [ s1, s2, s3 ]
03459  *     a.assoc("letters")  #=> [ "letters", "a", "b", "c" ]
03460  *     a.assoc("foo")      #=> nil
03461  */
03462 
03463 VALUE
03464 rb_ary_assoc(VALUE ary, VALUE key)
03465 {
03466     long i;
03467     VALUE v;
03468 
03469     for (i = 0; i < RARRAY_LEN(ary); ++i) {
03470         v = rb_check_array_type(RARRAY_PTR(ary)[i]);
03471         if (!NIL_P(v) && RARRAY_LEN(v) > 0 &&
03472             rb_equal(RARRAY_PTR(v)[0], key))
03473             return v;
03474     }
03475     return Qnil;
03476 }
03477 
03478 /*
03479  *  call-seq:
03480  *     ary.rassoc(obj) -> new_ary or nil
03481  *
03482  *  Searches through the array whose elements are also arrays.
03483  *
03484  *  Compares +obj+ with the second element of each contained array using
03485  *  <code>obj.==</code>.
03486  *
03487  *  Returns the first contained array that matches +obj+.
03488  *
03489  *  See also Array#assoc.
03490  *
03491  *     a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ]
03492  *     a.rassoc("two")    #=> [2, "two"]
03493  *     a.rassoc("four")   #=> nil
03494  */
03495 
03496 VALUE
03497 rb_ary_rassoc(VALUE ary, VALUE value)
03498 {
03499     long i;
03500     VALUE v;
03501 
03502     for (i = 0; i < RARRAY_LEN(ary); ++i) {
03503         v = RARRAY_PTR(ary)[i];
03504         if (RB_TYPE_P(v, T_ARRAY) &&
03505             RARRAY_LEN(v) > 1 &&
03506             rb_equal(RARRAY_PTR(v)[1], value))
03507             return v;
03508     }
03509     return Qnil;
03510 }
03511 
03512 static VALUE
03513 recursive_equal(VALUE ary1, VALUE ary2, int recur)
03514 {
03515     long i, len1;
03516     VALUE *p1, *p2;
03517 
03518     if (recur) return Qtrue; /* Subtle! */
03519 
03520     p1 = RARRAY_PTR(ary1);
03521     p2 = RARRAY_PTR(ary2);
03522     len1 = RARRAY_LEN(ary1);
03523 
03524     for (i = 0; i < len1; i++) {
03525         if (*p1 != *p2) {
03526             if (rb_equal(*p1, *p2)) {
03527                 len1 = RARRAY_LEN(ary1);
03528                 if (len1 != RARRAY_LEN(ary2))
03529                     return Qfalse;
03530                 if (len1 < i)
03531                     return Qtrue;
03532                 p1 = RARRAY_PTR(ary1) + i;
03533                 p2 = RARRAY_PTR(ary2) + i;
03534             }
03535             else {
03536                 return Qfalse;
03537             }
03538         }
03539         p1++;
03540         p2++;
03541     }
03542     return Qtrue;
03543 }
03544 
03545 /*
03546  *  call-seq:
03547  *     ary == other_ary   ->   bool
03548  *
03549  *  Equality --- Two arrays are equal if they contain the same number of
03550  *  elements and if each element is equal to (according to Object#==) the
03551  *  corresponding element in +other_ary+.
03552  *
03553  *     [ "a", "c" ]    == [ "a", "c", 7 ]     #=> false
03554  *     [ "a", "c", 7 ] == [ "a", "c", 7 ]     #=> true
03555  *     [ "a", "c", 7 ] == [ "a", "d", "f" ]   #=> false
03556  *
03557  */
03558 
03559 static VALUE
03560 rb_ary_equal(VALUE ary1, VALUE ary2)
03561 {
03562     if (ary1 == ary2) return Qtrue;
03563     if (!RB_TYPE_P(ary2, T_ARRAY)) {
03564         if (!rb_respond_to(ary2, rb_intern("to_ary"))) {
03565             return Qfalse;
03566         }
03567         return rb_equal(ary2, ary1);
03568     }
03569     if (RARRAY_LEN(ary1) != RARRAY_LEN(ary2)) return Qfalse;
03570     return rb_exec_recursive_paired(recursive_equal, ary1, ary2, ary2);
03571 }
03572 
03573 static VALUE
03574 recursive_eql(VALUE ary1, VALUE ary2, int recur)
03575 {
03576     long i;
03577 
03578     if (recur) return Qtrue; /* Subtle! */
03579     for (i=0; i<RARRAY_LEN(ary1); i++) {
03580         if (!rb_eql(rb_ary_elt(ary1, i), rb_ary_elt(ary2, i)))
03581             return Qfalse;
03582     }
03583     return Qtrue;
03584 }
03585 
03586 /*
03587  *  call-seq:
03588  *     ary.eql?(other)  -> true or false
03589  *
03590  *  Returns +true+ if +self+ and +other+ are the same object,
03591  *  or are both arrays with the same content (according to Object#eql?).
03592  */
03593 
03594 static VALUE
03595 rb_ary_eql(VALUE ary1, VALUE ary2)
03596 {
03597     if (ary1 == ary2) return Qtrue;
03598     if (!RB_TYPE_P(ary2, T_ARRAY)) return Qfalse;
03599     if (RARRAY_LEN(ary1) != RARRAY_LEN(ary2)) return Qfalse;
03600     return rb_exec_recursive_paired(recursive_eql, ary1, ary2, ary2);
03601 }
03602 
03603 static VALUE
03604 recursive_hash(VALUE ary, VALUE dummy, int recur)
03605 {
03606     long i;
03607     st_index_t h;
03608     VALUE n;
03609 
03610     h = rb_hash_start(RARRAY_LEN(ary));
03611     if (recur) {
03612         h = rb_hash_uint(h, NUM2LONG(rb_hash(rb_cArray)));
03613     }
03614     else {
03615         for (i=0; i<RARRAY_LEN(ary); i++) {
03616             n = rb_hash(RARRAY_PTR(ary)[i]);
03617             h = rb_hash_uint(h, NUM2LONG(n));
03618         }
03619     }
03620     h = rb_hash_end(h);
03621     return LONG2FIX(h);
03622 }
03623 
03624 /*
03625  *  call-seq:
03626  *     ary.hash   -> fixnum
03627  *
03628  *  Compute a hash-code for this array.
03629  *
03630  *  Two arrays with the same content will have the same hash code (and will
03631  *  compare using #eql?).
03632  */
03633 
03634 static VALUE
03635 rb_ary_hash(VALUE ary)
03636 {
03637     return rb_exec_recursive_outer(recursive_hash, ary, 0);
03638 }
03639 
03640 /*
03641  *  call-seq:
03642  *     ary.include?(object)   -> true or false
03643  *
03644  *  Returns +true+ if the given +object+ is present in +self+ (that is, if any
03645  *  element <code>==</code> +object+), otherwise returns +false+.
03646  *
03647  *     a = [ "a", "b", "c" ]
03648  *     a.include?("b")   #=> true
03649  *     a.include?("z")   #=> false
03650  */
03651 
03652 VALUE
03653 rb_ary_includes(VALUE ary, VALUE item)
03654 {
03655     long i;
03656 
03657     for (i=0; i<RARRAY_LEN(ary); i++) {
03658         if (rb_equal(RARRAY_PTR(ary)[i], item)) {
03659             return Qtrue;
03660         }
03661     }
03662     return Qfalse;
03663 }
03664 
03665 
03666 static VALUE
03667 recursive_cmp(VALUE ary1, VALUE ary2, int recur)
03668 {
03669     long i, len;
03670 
03671     if (recur) return Qundef;   /* Subtle! */
03672     len = RARRAY_LEN(ary1);
03673     if (len > RARRAY_LEN(ary2)) {
03674         len = RARRAY_LEN(ary2);
03675     }
03676     for (i=0; i<len; i++) {
03677         VALUE v = rb_funcall(rb_ary_elt(ary1, i), id_cmp, 1, rb_ary_elt(ary2, i));
03678         if (v != INT2FIX(0)) {
03679             return v;
03680         }
03681     }
03682     return Qundef;
03683 }
03684 
03685 /*
03686  *  call-seq:
03687  *     ary <=> other_ary   ->  -1, 0, +1 or nil
03688  *
03689  *  Comparison --- Returns an integer (+-1+, +0+, or <code>+1</code>) if this
03690  *  array is less than, equal to, or greater than +other_ary+.
03691  *
03692  *  +nil+ is returned if the two values are incomparable.
03693  *
03694  *  Each object in each array is compared (using the <=> operator).
03695  *
03696  *  Arrays are compared in an "element-wise" manner; the first two elements
03697  *  that are not equal will determine the return value for the whole
03698  *  comparison.
03699  *
03700  *  If all the values are equal, then the return is based on a comparison of
03701  *  the array lengths. Thus, two arrays are "equal" according to Array#<=> if,
03702  *  and only if, they have the same length and the value of each element is
03703  *  equal to the value of the corresponding element in the other array.
03704  *
03705  *     [ "a", "a", "c" ]    <=> [ "a", "b", "c" ]   #=> -1
03706  *     [ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ]            #=> +1
03707  *
03708  */
03709 
03710 VALUE
03711 rb_ary_cmp(VALUE ary1, VALUE ary2)
03712 {
03713     long len;
03714     VALUE v;
03715 
03716     ary2 = rb_check_array_type(ary2);
03717     if (NIL_P(ary2)) return Qnil;
03718     if (ary1 == ary2) return INT2FIX(0);
03719     v = rb_exec_recursive_paired(recursive_cmp, ary1, ary2, ary2);
03720     if (v != Qundef) return v;
03721     len = RARRAY_LEN(ary1) - RARRAY_LEN(ary2);
03722     if (len == 0) return INT2FIX(0);
03723     if (len > 0) return INT2FIX(1);
03724     return INT2FIX(-1);
03725 }
03726 
03727 static VALUE
03728 ary_add_hash(VALUE hash, VALUE ary)
03729 {
03730     long i;
03731 
03732     for (i=0; i<RARRAY_LEN(ary); i++) {
03733         rb_hash_aset(hash, RARRAY_PTR(ary)[i], Qtrue);
03734     }
03735     return hash;
03736 }
03737 
03738 static inline VALUE
03739 ary_tmp_hash_new(void)
03740 {
03741     VALUE hash = rb_hash_new();
03742 
03743     RBASIC(hash)->klass = 0;
03744     return hash;
03745 }
03746 
03747 static VALUE
03748 ary_make_hash(VALUE ary)
03749 {
03750     VALUE hash = ary_tmp_hash_new();
03751     return ary_add_hash(hash, ary);
03752 }
03753 
03754 static VALUE
03755 ary_add_hash_by(VALUE hash, VALUE ary)
03756 {
03757     long i;
03758 
03759     for (i = 0; i < RARRAY_LEN(ary); ++i) {
03760         VALUE v = rb_ary_elt(ary, i), k = rb_yield(v);
03761         if (rb_hash_lookup2(hash, k, Qundef) == Qundef) {
03762             rb_hash_aset(hash, k, v);
03763         }
03764     }
03765     return hash;
03766 }
03767 
03768 static VALUE
03769 ary_make_hash_by(VALUE ary)
03770 {
03771     VALUE hash = ary_tmp_hash_new();
03772     return ary_add_hash_by(hash, ary);
03773 }
03774 
03775 static inline void
03776 ary_recycle_hash(VALUE hash)
03777 {
03778     if (RHASH(hash)->ntbl) {
03779         st_table *tbl = RHASH(hash)->ntbl;
03780         RHASH(hash)->ntbl = 0;
03781         st_free_table(tbl);
03782     }
03783 }
03784 
03785 /*
03786  *  call-seq:
03787  *     ary - other_ary    -> new_ary
03788  *
03789  *  Array Difference
03790  *
03791  *  Returns a new array that is a copy of the original array, removing any
03792  *  items that also appear in +other_ary+. The order is preserved from the
03793  *  original array.
03794  *
03795  *  It compares elements using their #hash and #eql? methods for efficiency.
03796  *
03797  *     [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]
03798  *
03799  *  If you need set-like behavior, see the library class Set.
03800  */
03801 
03802 static VALUE
03803 rb_ary_diff(VALUE ary1, VALUE ary2)
03804 {
03805     VALUE ary3;
03806     volatile VALUE hash;
03807     long i;
03808 
03809     hash = ary_make_hash(to_ary(ary2));
03810     ary3 = rb_ary_new();
03811 
03812     for (i=0; i<RARRAY_LEN(ary1); i++) {
03813         if (st_lookup(RHASH_TBL(hash), RARRAY_PTR(ary1)[i], 0)) continue;
03814         rb_ary_push(ary3, rb_ary_elt(ary1, i));
03815     }
03816     ary_recycle_hash(hash);
03817     return ary3;
03818 }
03819 
03820 /*
03821  *  call-seq:
03822  *     ary & other_ary      -> new_ary
03823  *
03824  *  Set Intersection --- Returns a new array containing elements common to the
03825  *  two arrays, excluding any duplicates. The order is preserved from the
03826  *  original array.
03827  *
03828  *  It compares elements using their #hash and #eql? methods for efficiency.
03829  *
03830  *     [ 1, 1, 3, 5 ] & [ 1, 2, 3 ]                 #=> [ 1, 3 ]
03831  *     [ 'a', 'b', 'b', 'z' ] & [ 'a', 'b', 'c' ]   #=> [ 'a', 'b' ]
03832  *
03833  *  See also Array#uniq.
03834  */
03835 
03836 
03837 static VALUE
03838 rb_ary_and(VALUE ary1, VALUE ary2)
03839 {
03840     VALUE hash, ary3, v;
03841     st_data_t vv;
03842     long i;
03843 
03844     ary2 = to_ary(ary2);
03845     ary3 = rb_ary_new2(RARRAY_LEN(ary1) < RARRAY_LEN(ary2) ?
03846             RARRAY_LEN(ary1) : RARRAY_LEN(ary2));
03847     hash = ary_make_hash(ary2);
03848 
03849     if (RHASH_EMPTY_P(hash))
03850         return ary3;
03851 
03852     for (i=0; i<RARRAY_LEN(ary1); i++) {
03853         vv = (st_data_t)(v = rb_ary_elt(ary1, i));
03854         if (st_delete(RHASH_TBL(hash), &vv, 0)) {
03855             rb_ary_push(ary3, v);
03856         }
03857     }
03858     ary_recycle_hash(hash);
03859 
03860     return ary3;
03861 }
03862 
03863 /*
03864  *  call-seq:
03865  *     ary | other_ary     -> new_ary
03866  *
03867  *  Set Union --- Returns a new array by joining +ary+ with +other_ary+,
03868  *  excluding any duplicates and preserving the order from the original array.
03869  *
03870  *  It compares elements using their #hash and #eql? methods for efficiency.
03871  *
03872  *     [ "a", "b", "c" ] | [ "c", "d", "a" ]    #=> [ "a", "b", "c", "d" ]
03873  *
03874  *  See also Array#uniq.
03875  */
03876 
03877 static VALUE
03878 rb_ary_or(VALUE ary1, VALUE ary2)
03879 {
03880     VALUE hash, ary3, v;
03881     st_data_t vv;
03882     long i;
03883 
03884     ary2 = to_ary(ary2);
03885     ary3 = rb_ary_new2(RARRAY_LEN(ary1)+RARRAY_LEN(ary2));
03886     hash = ary_add_hash(ary_make_hash(ary1), ary2);
03887 
03888     for (i=0; i<RARRAY_LEN(ary1); i++) {
03889         vv = (st_data_t)(v = rb_ary_elt(ary1, i));
03890         if (st_delete(RHASH_TBL(hash), &vv, 0)) {
03891             rb_ary_push(ary3, v);
03892         }
03893     }
03894     for (i=0; i<RARRAY_LEN(ary2); i++) {
03895         vv = (st_data_t)(v = rb_ary_elt(ary2, i));
03896         if (st_delete(RHASH_TBL(hash), &vv, 0)) {
03897             rb_ary_push(ary3, v);
03898         }
03899     }
03900     ary_recycle_hash(hash);
03901     return ary3;
03902 }
03903 
03904 static int
03905 push_value(st_data_t key, st_data_t val, st_data_t ary)
03906 {
03907     rb_ary_push((VALUE)ary, (VALUE)val);
03908     return ST_CONTINUE;
03909 }
03910 
03911 /*
03912  *  call-seq:
03913  *     ary.uniq!                -> ary or nil
03914  *     ary.uniq! { |item| ... } -> ary or nil
03915  *
03916  *  Removes duplicate elements from +self+.
03917  *
03918  *  If a block is given, it will use the return value of the block for
03919  *  comparison.
03920  *
03921  *  It compares values using their #hash and #eql? methods for efficiency.
03922  *
03923  *  Returns +nil+ if no changes are made (that is, no duplicates are found).
03924  *
03925  *     a = [ "a", "a", "b", "b", "c" ]
03926  *     a.uniq!   # => ["a", "b", "c"]
03927  *
03928  *     b = [ "a", "b", "c" ]
03929  *     b.uniq!   # => nil
03930  *
03931  *     c = [["student","sam"], ["student","george"], ["teacher","matz"]]
03932  *     c.uniq! { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
03933  *
03934  */
03935 
03936 static VALUE
03937 rb_ary_uniq_bang(VALUE ary)
03938 {
03939     VALUE hash, v;
03940     long i, j;
03941 
03942     rb_ary_modify_check(ary);
03943     if (RARRAY_LEN(ary) <= 1)
03944         return Qnil;
03945     if (rb_block_given_p()) {
03946         hash = ary_make_hash_by(ary);
03947         if (RARRAY_LEN(ary) == (i = RHASH_SIZE(hash))) {
03948             return Qnil;
03949         }
03950         ARY_SET_LEN(ary, 0);
03951         if (ARY_SHARED_P(ary) && !ARY_EMBED_P(ary)) {
03952             rb_ary_unshare(ary);
03953             FL_SET_EMBED(ary);
03954         }
03955         ary_resize_capa(ary, i);
03956         st_foreach(RHASH_TBL(hash), push_value, ary);
03957     }
03958     else {
03959         hash = ary_make_hash(ary);
03960         if (RARRAY_LEN(ary) == (long)RHASH_SIZE(hash)) {
03961             return Qnil;
03962         }
03963         for (i=j=0; i<RARRAY_LEN(ary); i++) {
03964             st_data_t vv = (st_data_t)(v = rb_ary_elt(ary, i));
03965             if (st_delete(RHASH_TBL(hash), &vv, 0)) {
03966                 rb_ary_store(ary, j++, v);
03967             }
03968         }
03969         ARY_SET_LEN(ary, j);
03970     }
03971     ary_recycle_hash(hash);
03972 
03973     return ary;
03974 }
03975 
03976 /*
03977  *  call-seq:
03978  *     ary.uniq                -> new_ary
03979  *     ary.uniq { |item| ... } -> new_ary
03980  *
03981  *  Returns a new array by removing duplicate values in +self+.
03982  *
03983  *  If a block is given, it will use the return value of the block for comparison.
03984  *
03985  *  It compares values using their #hash and #eql? methods for efficiency.
03986  *
03987  *     a = [ "a", "a", "b", "b", "c" ]
03988  *     a.uniq   # => ["a", "b", "c"]
03989  *
03990  *     b = [["student","sam"], ["student","george"], ["teacher","matz"]]
03991  *     b.uniq { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
03992  *
03993  */
03994 
03995 static VALUE
03996 rb_ary_uniq(VALUE ary)
03997 {
03998     VALUE hash, uniq, v;
03999     long i;
04000 
04001     if (RARRAY_LEN(ary) <= 1)
04002         return rb_ary_dup(ary);
04003     if (rb_block_given_p()) {
04004         hash = ary_make_hash_by(ary);
04005         uniq = ary_new(rb_obj_class(ary), RHASH_SIZE(hash));
04006         st_foreach(RHASH_TBL(hash), push_value, uniq);
04007     }
04008     else {
04009         hash = ary_make_hash(ary);
04010         uniq = ary_new(rb_obj_class(ary), RHASH_SIZE(hash));
04011         for (i=0; i<RARRAY_LEN(ary); i++) {
04012             st_data_t vv = (st_data_t)(v = rb_ary_elt(ary, i));
04013             if (st_delete(RHASH_TBL(hash), &vv, 0)) {
04014                 rb_ary_push(uniq, v);
04015             }
04016         }
04017     }
04018     ary_recycle_hash(hash);
04019 
04020     return uniq;
04021 }
04022 
04023 /*
04024  *  call-seq:
04025  *     ary.compact!    -> ary  or  nil
04026  *
04027  *  Removes +nil+ elements from the array.
04028  *
04029  *  Returns +nil+ if no changes were made, otherwise returns the array.
04030  *
04031  *     [ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
04032  *     [ "a", "b", "c" ].compact!           #=> nil
04033  */
04034 
04035 static VALUE
04036 rb_ary_compact_bang(VALUE ary)
04037 {
04038     VALUE *p, *t, *end;
04039     long n;
04040 
04041     rb_ary_modify(ary);
04042     p = t = RARRAY_PTR(ary);
04043     end = p + RARRAY_LEN(ary);
04044 
04045     while (t < end) {
04046         if (NIL_P(*t)) t++;
04047         else *p++ = *t++;
04048     }
04049     n = p - RARRAY_PTR(ary);
04050     if (RARRAY_LEN(ary) == n) {
04051         return Qnil;
04052     }
04053     ARY_SET_LEN(ary, n);
04054     if (n * 2 < ARY_CAPA(ary) && ARY_DEFAULT_SIZE * 2 < ARY_CAPA(ary)) {
04055         ary_resize_capa(ary, n * 2);
04056     }
04057 
04058     return ary;
04059 }
04060 
04061 /*
04062  *  call-seq:
04063  *     ary.compact     -> new_ary
04064  *
04065  *  Returns a copy of +self+ with all +nil+ elements removed.
04066  *
04067  *     [ "a", nil, "b", nil, "c", nil ].compact
04068  *                       #=> [ "a", "b", "c" ]
04069  */
04070 
04071 static VALUE
04072 rb_ary_compact(VALUE ary)
04073 {
04074     ary = rb_ary_dup(ary);
04075     rb_ary_compact_bang(ary);
04076     return ary;
04077 }
04078 
04079 /*
04080  *  call-seq:
04081  *     ary.count                   -> int
04082  *     ary.count(obj)              -> int
04083  *     ary.count { |item| block }  -> int
04084  *
04085  *  Returns the number of elements.
04086  *
04087  *  If an argument is given, counts the number of elements which equal +obj+
04088  *  using <code>===</code>.
04089  *
04090  *  If a block is given, counts the number of elements for which the block
04091  *  returns a true value.
04092  *
04093  *     ary = [1, 2, 4, 2]
04094  *     ary.count                  #=> 4
04095  *     ary.count(2)               #=> 2
04096  *     ary.count { |x| x%2 == 0 } #=> 3
04097  *
04098  */
04099 
04100 static VALUE
04101 rb_ary_count(int argc, VALUE *argv, VALUE ary)
04102 {
04103     long i, n = 0;
04104 
04105     if (argc == 0) {
04106         VALUE v;
04107 
04108         if (!rb_block_given_p())
04109             return LONG2NUM(RARRAY_LEN(ary));
04110 
04111         for (i = 0; i < RARRAY_LEN(ary); i++) {
04112             v = RARRAY_PTR(ary)[i];
04113             if (RTEST(rb_yield(v))) n++;
04114         }
04115     }
04116     else {
04117         VALUE obj;
04118 
04119         rb_scan_args(argc, argv, "1", &obj);
04120         if (rb_block_given_p()) {
04121             rb_warn("given block not used");
04122         }
04123         for (i = 0; i < RARRAY_LEN(ary); i++) {
04124             if (rb_equal(RARRAY_PTR(ary)[i], obj)) n++;
04125         }
04126     }
04127 
04128     return LONG2NUM(n);
04129 }
04130 
04131 static VALUE
04132 flatten(VALUE ary, int level, int *modified)
04133 {
04134     long i = 0;
04135     VALUE stack, result, tmp, elt;
04136     st_table *memo;
04137     st_data_t id;
04138 
04139     stack = ary_new(0, ARY_DEFAULT_SIZE);
04140     result = ary_new(0, RARRAY_LEN(ary));
04141     memo = st_init_numtable();
04142     st_insert(memo, (st_data_t)ary, (st_data_t)Qtrue);
04143     *modified = 0;
04144 
04145     while (1) {
04146         while (i < RARRAY_LEN(ary)) {
04147             elt = RARRAY_PTR(ary)[i++];
04148             tmp = rb_check_array_type(elt);
04149             if (RBASIC(result)->klass) {
04150                 rb_raise(rb_eRuntimeError, "flatten reentered");
04151             }
04152             if (NIL_P(tmp) || (level >= 0 && RARRAY_LEN(stack) / 2 >= level)) {
04153                 rb_ary_push(result, elt);
04154             }
04155             else {
04156                 *modified = 1;
04157                 id = (st_data_t)tmp;
04158                 if (st_lookup(memo, id, 0)) {
04159                     st_free_table(memo);
04160                     rb_raise(rb_eArgError, "tried to flatten recursive array");
04161                 }
04162                 st_insert(memo, id, (st_data_t)Qtrue);
04163                 rb_ary_push(stack, ary);
04164                 rb_ary_push(stack, LONG2NUM(i));
04165                 ary = tmp;
04166                 i = 0;
04167             }
04168         }
04169         if (RARRAY_LEN(stack) == 0) {
04170             break;
04171         }
04172         id = (st_data_t)ary;
04173         st_delete(memo, &id, 0);
04174         tmp = rb_ary_pop(stack);
04175         i = NUM2LONG(tmp);
04176         ary = rb_ary_pop(stack);
04177     }
04178 
04179     st_free_table(memo);
04180 
04181     RBASIC(result)->klass = rb_class_of(ary);
04182     return result;
04183 }
04184 
04185 /*
04186  *  call-seq:
04187  *     ary.flatten!        -> ary or nil
04188  *     ary.flatten!(level) -> ary or nil
04189  *
04190  *  Flattens +self+ in place.
04191  *
04192  *  Returns +nil+ if no modifications were made (i.e., the array contains no
04193  *  subarrays.)
04194  *
04195  *  The optional +level+ argument determines the level of recursion to flatten.
04196  *
04197  *     a = [ 1, 2, [3, [4, 5] ] ]
04198  *     a.flatten!   #=> [1, 2, 3, 4, 5]
04199  *     a.flatten!   #=> nil
04200  *     a            #=> [1, 2, 3, 4, 5]
04201  *     a = [ 1, 2, [3, [4, 5] ] ]
04202  *     a.flatten!(1) #=> [1, 2, 3, [4, 5]]
04203  */
04204 
04205 static VALUE
04206 rb_ary_flatten_bang(int argc, VALUE *argv, VALUE ary)
04207 {
04208     int mod = 0, level = -1;
04209     VALUE result, lv;
04210 
04211     rb_scan_args(argc, argv, "01", &lv);
04212     rb_ary_modify_check(ary);
04213     if (!NIL_P(lv)) level = NUM2INT(lv);
04214     if (level == 0) return Qnil;
04215 
04216     result = flatten(ary, level, &mod);
04217     if (mod == 0) {
04218         ary_discard(result);
04219         return Qnil;
04220     }
04221     if (!(mod = ARY_EMBED_P(result))) rb_obj_freeze(result);
04222     rb_ary_replace(ary, result);
04223     if (mod) ARY_SET_EMBED_LEN(result, 0);
04224 
04225     return ary;
04226 }
04227 
04228 /*
04229  *  call-seq:
04230  *     ary.flatten -> new_ary
04231  *     ary.flatten(level) -> new_ary
04232  *
04233  *  Returns a new array that is a one-dimensional flattening of +self+
04234  *  (recursively).
04235  *
04236  *  That is, for every element that is an array, extract its elements into
04237  *  the new array.
04238  *
04239  *  The optional +level+ argument determines the level of recursion to
04240  *  flatten.
04241  *
04242  *     s = [ 1, 2, 3 ]           #=> [1, 2, 3]
04243  *     t = [ 4, 5, 6, [7, 8] ]   #=> [4, 5, 6, [7, 8]]
04244  *     a = [ s, t, 9, 10 ]       #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
04245  *     a.flatten                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
04246  *     a = [ 1, 2, [3, [4, 5] ] ]
04247  *     a.flatten(1)              #=> [1, 2, 3, [4, 5]]
04248  */
04249 
04250 static VALUE
04251 rb_ary_flatten(int argc, VALUE *argv, VALUE ary)
04252 {
04253     int mod = 0, level = -1;
04254     VALUE result, lv;
04255 
04256     rb_scan_args(argc, argv, "01", &lv);
04257     if (!NIL_P(lv)) level = NUM2INT(lv);
04258     if (level == 0) return ary_make_shared_copy(ary);
04259 
04260     result = flatten(ary, level, &mod);
04261     OBJ_INFECT(result, ary);
04262 
04263     return result;
04264 }
04265 
04266 #define OPTHASH_GIVEN_P(opts) \
04267     (argc > 0 && !NIL_P((opts) = rb_check_hash_type(argv[argc-1])) && (--argc, 1))
04268 static VALUE sym_random;
04269 
04270 #define RAND_UPTO(max) (long)rb_random_ulong_limited((randgen), (max)-1)
04271 
04272 /*
04273  *  call-seq:
04274  *     ary.shuffle!              -> ary
04275  *     ary.shuffle!(random: rng) -> ary
04276  *
04277  *  Shuffles elements in +self+ in place.
04278  *
04279  *  The optional +rng+ argument will be used as the random number generator.
04280  */
04281 
04282 static VALUE
04283 rb_ary_shuffle_bang(int argc, VALUE *argv, VALUE ary)
04284 {
04285     VALUE *ptr, opts, *snap_ptr, randgen = rb_cRandom;
04286     long i, snap_len;
04287 
04288     if (OPTHASH_GIVEN_P(opts)) {
04289         randgen = rb_hash_lookup2(opts, sym_random, randgen);
04290     }
04291     rb_check_arity(argc, 0, 0);
04292     rb_ary_modify(ary);
04293     i = RARRAY_LEN(ary);
04294     ptr = RARRAY_PTR(ary);
04295     snap_len = i;
04296     snap_ptr = ptr;
04297     while (i) {
04298         long j = RAND_UPTO(i);
04299         VALUE tmp;
04300         if (snap_len != RARRAY_LEN(ary) || snap_ptr != RARRAY_PTR(ary)) {
04301             rb_raise(rb_eRuntimeError, "modified during shuffle");
04302         }
04303         tmp = ptr[--i];
04304         ptr[i] = ptr[j];
04305         ptr[j] = tmp;
04306     }
04307     return ary;
04308 }
04309 
04310 
04311 /*
04312  *  call-seq:
04313  *     ary.shuffle              -> new_ary
04314  *     ary.shuffle(random: rng) -> new_ary
04315  *
04316  *  Returns a new array with elements of +self+ shuffled.
04317  *
04318  *     a = [ 1, 2, 3 ]           #=> [1, 2, 3]
04319  *     a.shuffle                 #=> [2, 3, 1]
04320  *
04321  *  The optional +rng+ argument will be used as the random number generator.
04322  *
04323  *     a.shuffle(random: Random.new(1))  #=> [1, 3, 2]
04324  */
04325 
04326 static VALUE
04327 rb_ary_shuffle(int argc, VALUE *argv, VALUE ary)
04328 {
04329     ary = rb_ary_dup(ary);
04330     rb_ary_shuffle_bang(argc, argv, ary);
04331     return ary;
04332 }
04333 
04334 
04335 /*
04336  *  call-seq:
04337  *     ary.sample                  -> obj
04338  *     ary.sample(random: rng)     -> obj
04339  *     ary.sample(n)               -> new_ary
04340  *     ary.sample(n, random: rng)  -> new_ary
04341  *
04342  *  Choose a random element or +n+ random elements from the array.
04343  *
04344  *  The elements are chosen by using random and unique indices into the array
04345  *  in order to ensure that an element doesn't repeat itself unless the array
04346  *  already contained duplicate elements.
04347  *
04348  *  If the array is empty the first form returns +nil+ and the second form
04349  *  returns an empty array.
04350  *
04351  *  The optional +rng+ argument will be used as the random number generator.
04352  *
04353  *     a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
04354  *     a.sample         #=> 7
04355  *     a.sample(4)      #=> [6, 4, 2, 5]
04356  */
04357 
04358 
04359 static VALUE
04360 rb_ary_sample(int argc, VALUE *argv, VALUE ary)
04361 {
04362     VALUE nv, result, *ptr;
04363     VALUE opts, randgen = rb_cRandom;
04364     long n, len, i, j, k, idx[10];
04365     long rnds[numberof(idx)];
04366 
04367     if (OPTHASH_GIVEN_P(opts)) {
04368         randgen = rb_hash_lookup2(opts, sym_random, randgen);
04369     }
04370     ptr = RARRAY_PTR(ary);
04371     len = RARRAY_LEN(ary);
04372     if (argc == 0) {
04373         if (len == 0) return Qnil;
04374         if (len == 1) {
04375             i = 0;
04376         }
04377         else {
04378             i = RAND_UPTO(len);
04379             if ((len = RARRAY_LEN(ary)) <= i) return Qnil;
04380             ptr = RARRAY_PTR(ary);
04381         }
04382         return ptr[i];
04383     }
04384     rb_scan_args(argc, argv, "1", &nv);
04385     n = NUM2LONG(nv);
04386     if (n < 0) rb_raise(rb_eArgError, "negative sample number");
04387     if (n > len) n = len;
04388     if (n <= numberof(idx)) {
04389         for (i = 0; i < n; ++i) {
04390             rnds[i] = RAND_UPTO(len - i);
04391         }
04392     }
04393     k = len;
04394     len = RARRAY_LEN(ary);
04395     ptr = RARRAY_PTR(ary);
04396     if (len < k) {
04397         if (n <= numberof(idx)) {
04398             for (i = 0; i < n; ++i) {
04399                 if (rnds[i] >= len) {
04400                     return rb_ary_new2(0);
04401                 }
04402             }
04403         }
04404     }
04405     if (n > len) n = len;
04406     switch (n) {
04407       case 0:
04408         return rb_ary_new2(0);
04409       case 1:
04410         i = rnds[0];
04411         return rb_ary_new4(1, &ptr[i]);
04412       case 2:
04413         i = rnds[0];
04414         j = rnds[1];
04415         if (j >= i) j++;
04416         return rb_ary_new3(2, ptr[i], ptr[j]);
04417       case 3:
04418         i = rnds[0];
04419         j = rnds[1];
04420         k = rnds[2];
04421         {
04422             long l = j, g = i;
04423             if (j >= i) l = i, g = ++j;
04424             if (k >= l && (++k >= g)) ++k;
04425         }
04426         return rb_ary_new3(3, ptr[i], ptr[j], ptr[k]);
04427     }
04428     if (n <= numberof(idx)) {
04429         VALUE *ptr_result;
04430         long sorted[numberof(idx)];
04431         sorted[0] = idx[0] = rnds[0];
04432         for (i=1; i<n; i++) {
04433             k = rnds[i];
04434             for (j = 0; j < i; ++j) {
04435                 if (k < sorted[j]) break;
04436                 ++k;
04437             }
04438             memmove(&sorted[j+1], &sorted[j], sizeof(sorted[0])*(i-j));
04439             sorted[j] = idx[i] = k;
04440         }
04441         result = rb_ary_new2(n);
04442         ptr_result = RARRAY_PTR(result);
04443         for (i=0; i<n; i++) {
04444             ptr_result[i] = ptr[idx[i]];
04445         }
04446     }
04447     else {
04448         VALUE *ptr_result;
04449         result = rb_ary_new4(len, ptr);
04450         RBASIC(result)->klass = 0;
04451         ptr_result = RARRAY_PTR(result);
04452         RB_GC_GUARD(ary);
04453         for (i=0; i<n; i++) {
04454             j = RAND_UPTO(len-i) + i;
04455             nv = ptr_result[j];
04456             ptr_result[j] = ptr_result[i];
04457             ptr_result[i] = nv;
04458         }
04459         RBASIC(result)->klass = rb_cArray;
04460     }
04461     ARY_SET_LEN(result, n);
04462 
04463     return result;
04464 }
04465 
04466 static VALUE
04467 rb_ary_cycle_size(VALUE self, VALUE args)
04468 {
04469     long mul;
04470     VALUE n = Qnil;
04471     if (args && (RARRAY_LEN(args) > 0)) {
04472         n = RARRAY_PTR(args)[0];
04473     }
04474     if (RARRAY_LEN(self) == 0) return INT2FIX(0);
04475     if (n == Qnil) return DBL2NUM(INFINITY);
04476     mul = NUM2LONG(n);
04477     if (mul <= 0) return INT2FIX(0);
04478     return rb_funcall(rb_ary_length(self), '*', 1, LONG2FIX(mul));
04479 }
04480 
04481 /*
04482  *  call-seq:
04483  *     ary.cycle(n=nil) { |obj| block }  -> nil
04484  *     ary.cycle(n=nil)                  -> Enumerator
04485  *
04486  *  Calls the given block for each element +n+ times or forever if +nil+ is
04487  *  given.
04488  *
04489  *  Does nothing if a non-positive number is given or the array is empty.
04490  *
04491  *  Returns +nil+ if the loop has finished without getting interrupted.
04492  *
04493  *  If no block is given, an Enumerator is returned instead.
04494  *
04495  *     a = ["a", "b", "c"]
04496  *     a.cycle { |x| puts x }     # print, a, b, c, a, b, c,.. forever.
04497  *     a.cycle(2) { |x| puts x }  # print, a, b, c, a, b, c.
04498  *
04499  */
04500 
04501 static VALUE
04502 rb_ary_cycle(int argc, VALUE *argv, VALUE ary)
04503 {
04504     long n, i;
04505     VALUE nv = Qnil;
04506 
04507     rb_scan_args(argc, argv, "01", &nv);
04508 
04509     RETURN_SIZED_ENUMERATOR(ary, argc, argv, rb_ary_cycle_size);
04510     if (NIL_P(nv)) {
04511         n = -1;
04512     }
04513     else {
04514         n = NUM2LONG(nv);
04515         if (n <= 0) return Qnil;
04516     }
04517 
04518     while (RARRAY_LEN(ary) > 0 && (n < 0 || 0 < n--)) {
04519         for (i=0; i<RARRAY_LEN(ary); i++) {
04520             rb_yield(RARRAY_PTR(ary)[i]);
04521         }
04522     }
04523     return Qnil;
04524 }
04525 
04526 #define tmpbuf(n, size) rb_str_tmp_new((n)*(size))
04527 #define tmpbuf_discard(s) (rb_str_resize((s), 0L), RBASIC(s)->klass = rb_cString)
04528 #define tmpary(n) rb_ary_tmp_new(n)
04529 #define tmpary_discard(a) (ary_discard(a), RBASIC(a)->klass = rb_cArray)
04530 
04531 /*
04532  * Build a ruby array of the corresponding values and yield it to the
04533  * associated block.
04534  * Return the class of +values+ for reentry check.
04535  */
04536 static int
04537 yield_indexed_values(const VALUE values, const long r, const long *const p)
04538 {
04539     const VALUE result = rb_ary_new2(r);
04540     VALUE *const result_array = RARRAY_PTR(result);
04541     const VALUE *const values_array = RARRAY_PTR(values);
04542     long i;
04543 
04544     for (i = 0; i < r; i++) result_array[i] = values_array[p[i]];
04545     ARY_SET_LEN(result, r);
04546     rb_yield(result);
04547     return !RBASIC(values)->klass;
04548 }
04549 
04550 /*
04551  * Recursively compute permutations of +r+ elements of the set
04552  * <code>[0..n-1]</code>.
04553  *
04554  * When we have a complete permutation of array indexes, copy the values
04555  * at those indexes into a new array and yield that array.
04556  *
04557  * n: the size of the set
04558  * r: the number of elements in each permutation
04559  * p: the array (of size r) that we're filling in
04560  * index: what index we're filling in now
04561  * used: an array of booleans: whether a given index is already used
04562  * values: the Ruby array that holds the actual values to permute
04563  */
04564 static void
04565 permute0(long n, long r, long *p, long index, char *used, VALUE values)
04566 {
04567     long i;
04568     for (i = 0; i < n; i++) {
04569         if (used[i] == 0) {
04570             p[index] = i;
04571             if (index < r-1) {             /* if not done yet */
04572                 used[i] = 1;               /* mark index used */
04573                 permute0(n, r, p, index+1, /* recurse */
04574                          used, values);
04575                 used[i] = 0;               /* index unused */
04576             }
04577             else {
04578                 if (!yield_indexed_values(values, r, p)) {
04579                     rb_raise(rb_eRuntimeError, "permute reentered");
04580                 }
04581             }
04582         }
04583     }
04584 }
04585 
04586 /*
04587  * Returns the product of from, from-1, ..., from - how_many + 1.
04588  * http://en.wikipedia.org/wiki/Pochhammer_symbol
04589  */
04590 static VALUE
04591 descending_factorial(long from, long how_many)
04592 {
04593     VALUE cnt = LONG2FIX(how_many >= 0);
04594     while (how_many-- > 0) {
04595         cnt = rb_funcall(cnt, '*', 1, LONG2FIX(from--));
04596     }
04597     return cnt;
04598 }
04599 
04600 static VALUE
04601 binomial_coefficient(long comb, long size)
04602 {
04603     if (comb > size-comb) {
04604         comb = size-comb;
04605     }
04606     if (comb < 0) {
04607         return LONG2FIX(0);
04608     }
04609     return rb_funcall(descending_factorial(size, comb), id_div, 1, descending_factorial(comb, comb));
04610 }
04611 
04612 static VALUE
04613 rb_ary_permutation_size(VALUE ary, VALUE args)
04614 {
04615     long n = RARRAY_LEN(ary);
04616     long k = (args && (RARRAY_LEN(args) > 0)) ? NUM2LONG(RARRAY_PTR(args)[0]) : n;
04617 
04618     return descending_factorial(n, k);
04619 }
04620 
04621 /*
04622  *  call-seq:
04623  *     ary.permutation { |p| block }          -> ary
04624  *     ary.permutation                        -> Enumerator
04625  *     ary.permutation(n) { |p| block }       -> ary
04626  *     ary.permutation(n)                     -> Enumerator
04627  *
04628  * When invoked with a block, yield all permutations of length +n+ of the
04629  * elements of the array, then return the array itself.
04630  *
04631  * If +n+ is not specified, yield all permutations of all elements.
04632  *
04633  * The implementation makes no guarantees about the order in which the
04634  * permutations are yielded.
04635  *
04636  * If no block is given, an Enumerator is returned instead.
04637  *
04638  * Examples:
04639  *
04640  *   a = [1, 2, 3]
04641  *   a.permutation.to_a    #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
04642  *   a.permutation(1).to_a #=> [[1],[2],[3]]
04643  *   a.permutation(2).to_a #=> [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
04644  *   a.permutation(3).to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
04645  *   a.permutation(0).to_a #=> [[]] # one permutation of length 0
04646  *   a.permutation(4).to_a #=> []   # no permutations of length 4
04647  */
04648 
04649 static VALUE
04650 rb_ary_permutation(int argc, VALUE *argv, VALUE ary)
04651 {
04652     VALUE num;
04653     long r, n, i;
04654 
04655     n = RARRAY_LEN(ary);                  /* Array length */
04656     RETURN_SIZED_ENUMERATOR(ary, argc, argv, rb_ary_permutation_size);   /* Return enumerator if no block */
04657     rb_scan_args(argc, argv, "01", &num);
04658     r = NIL_P(num) ? n : NUM2LONG(num);   /* Permutation size from argument */
04659 
04660     if (r < 0 || n < r) {
04661         /* no permutations: yield nothing */
04662     }
04663     else if (r == 0) { /* exactly one permutation: the zero-length array */
04664         rb_yield(rb_ary_new2(0));
04665     }
04666     else if (r == 1) { /* this is a special, easy case */
04667         for (i = 0; i < RARRAY_LEN(ary); i++) {
04668             rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
04669         }
04670     }
04671     else {             /* this is the general case */
04672         volatile VALUE t0 = tmpbuf(r,sizeof(long));
04673         long *p = (long*)RSTRING_PTR(t0);
04674         volatile VALUE t1 = tmpbuf(n,sizeof(char));
04675         char *used = (char*)RSTRING_PTR(t1);
04676         VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
04677         RBASIC(ary0)->klass = 0;
04678 
04679         MEMZERO(used, char, n); /* initialize array */
04680 
04681         permute0(n, r, p, 0, used, ary0); /* compute and yield permutations */
04682         tmpbuf_discard(t0);
04683         tmpbuf_discard(t1);
04684         RBASIC(ary0)->klass = rb_cArray;
04685     }
04686     return ary;
04687 }
04688 
04689 static VALUE
04690 rb_ary_combination_size(VALUE ary, VALUE args)
04691 {
04692     long n = RARRAY_LEN(ary);
04693     long k = NUM2LONG(RARRAY_PTR(args)[0]);
04694 
04695     return binomial_coefficient(k, n);
04696 }
04697 
04698 /*
04699  *  call-seq:
04700  *     ary.combination(n) { |c| block }    -> ary
04701  *     ary.combination(n)                  -> Enumerator
04702  *
04703  * When invoked with a block, yields all combinations of length +n+ of elements
04704  * from the array and then returns the array itself.
04705  *
04706  * The implementation makes no guarantees about the order in which the
04707  * combinations are yielded.
04708  *
04709  * If no block is given, an Enumerator is returned instead.
04710  *
04711  * Examples:
04712  *
04713  *     a = [1, 2, 3, 4]
04714  *     a.combination(1).to_a  #=> [[1],[2],[3],[4]]
04715  *     a.combination(2).to_a  #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
04716  *     a.combination(3).to_a  #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
04717  *     a.combination(4).to_a  #=> [[1,2,3,4]]
04718  *     a.combination(0).to_a  #=> [[]] # one combination of length 0
04719  *     a.combination(5).to_a  #=> []   # no combinations of length 5
04720  *
04721  */
04722 
04723 static VALUE
04724 rb_ary_combination(VALUE ary, VALUE num)
04725 {
04726     long n, i, len;
04727 
04728     n = NUM2LONG(num);
04729     RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_combination_size);
04730     len = RARRAY_LEN(ary);
04731     if (n < 0 || len < n) {
04732         /* yield nothing */
04733     }
04734     else if (n == 0) {
04735         rb_yield(rb_ary_new2(0));
04736     }
04737     else if (n == 1) {
04738         for (i = 0; i < len; i++) {
04739             rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
04740         }
04741     }
04742     else {
04743         VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
04744         volatile VALUE t0;
04745         long *stack = ALLOCV_N(long, t0, n+1);
04746         long lev = 0;
04747 
04748         RBASIC(ary0)->klass = 0;
04749         MEMZERO(stack+1, long, n);
04750         stack[0] = -1;
04751         for (;;) {
04752             for (lev++; lev < n; lev++) {
04753                 stack[lev+1] = stack[lev]+1;
04754             }
04755             if (!yield_indexed_values(ary0, n, stack+1)) {
04756                 rb_raise(rb_eRuntimeError, "combination reentered");
04757             }
04758             do {
04759                 if (lev == 0) goto done;
04760                 stack[lev--]++;
04761             } while (stack[lev+1]+n == len+lev+1);
04762         }
04763     done:
04764         ALLOCV_END(t0);
04765         RBASIC(ary0)->klass = rb_cArray;
04766     }
04767     return ary;
04768 }
04769 
04770 /*
04771  * Recursively compute repeated permutations of +r+ elements of the set
04772  * <code>[0..n-1]</code>.
04773  *
04774  * When we have a complete repeated permutation of array indexes, copy the
04775  * values at those indexes into a new array and yield that array.
04776  *
04777  * n: the size of the set
04778  * r: the number of elements in each permutation
04779  * p: the array (of size r) that we're filling in
04780  * index: what index we're filling in now
04781  * values: the Ruby array that holds the actual values to permute
04782  */
04783 static void
04784 rpermute0(long n, long r, long *p, long index, VALUE values)
04785 {
04786     long i;
04787     for (i = 0; i < n; i++) {
04788         p[index] = i;
04789         if (index < r-1) {              /* if not done yet */
04790             rpermute0(n, r, p, index+1, values); /* recurse */
04791         }
04792         else {
04793             if (!yield_indexed_values(values, r, p)) {
04794                 rb_raise(rb_eRuntimeError, "repeated permute reentered");
04795             }
04796         }
04797     }
04798 }
04799 
04800 static VALUE
04801 rb_ary_repeated_permutation_size(VALUE ary, VALUE args)
04802 {
04803     long n = RARRAY_LEN(ary);
04804     long k = NUM2LONG(RARRAY_PTR(args)[0]);
04805 
04806     if (k < 0) {
04807         return LONG2FIX(0);
04808     }
04809 
04810     return rb_funcall(LONG2NUM(n), id_power, 1, LONG2NUM(k));
04811 }
04812 
04813 /*
04814  *  call-seq:
04815  *     ary.repeated_permutation(n) { |p| block } -> ary
04816  *     ary.repeated_permutation(n)               -> Enumerator
04817  *
04818  * When invoked with a block, yield all repeated permutations of length +n+ of
04819  * the elements of the array, then return the array itself.
04820  *
04821  * The implementation makes no guarantees about the order in which the repeated
04822  * permutations are yielded.
04823  *
04824  * If no block is given, an Enumerator is returned instead.
04825  *
04826  * Examples:
04827  *
04828  *     a = [1, 2]
04829  *     a.repeated_permutation(1).to_a  #=> [[1], [2]]
04830  *     a.repeated_permutation(2).to_a  #=> [[1,1],[1,2],[2,1],[2,2]]
04831  *     a.repeated_permutation(3).to_a  #=> [[1,1,1],[1,1,2],[1,2,1],[1,2,2],
04832  *                                     #    [2,1,1],[2,1,2],[2,2,1],[2,2,2]]
04833  *     a.repeated_permutation(0).to_a  #=> [[]] # one permutation of length 0
04834  */
04835 
04836 static VALUE
04837 rb_ary_repeated_permutation(VALUE ary, VALUE num)
04838 {
04839     long r, n, i;
04840 
04841     n = RARRAY_LEN(ary);                  /* Array length */
04842     RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_repeated_permutation_size);      /* Return Enumerator if no block */
04843     r = NUM2LONG(num);                    /* Permutation size from argument */
04844 
04845     if (r < 0) {
04846         /* no permutations: yield nothing */
04847     }
04848     else if (r == 0) { /* exactly one permutation: the zero-length array */
04849         rb_yield(rb_ary_new2(0));
04850     }
04851     else if (r == 1) { /* this is a special, easy case */
04852         for (i = 0; i < RARRAY_LEN(ary); i++) {
04853             rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
04854         }
04855     }
04856     else {             /* this is the general case */
04857         volatile VALUE t0 = tmpbuf(r, sizeof(long));
04858         long *p = (long*)RSTRING_PTR(t0);
04859         VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
04860         RBASIC(ary0)->klass = 0;
04861 
04862         rpermute0(n, r, p, 0, ary0); /* compute and yield repeated permutations */
04863         tmpbuf_discard(t0);
04864         RBASIC(ary0)->klass = rb_cArray;
04865     }
04866     return ary;
04867 }
04868 
04869 static void
04870 rcombinate0(long n, long r, long *p, long index, long rest, VALUE values)
04871 {
04872     if (rest > 0) {
04873         for (; index < n; ++index) {
04874             p[r-rest] = index;
04875             rcombinate0(n, r, p, index, rest-1, values);
04876         }
04877     }
04878     else {
04879         if (!yield_indexed_values(values, r, p)) {
04880             rb_raise(rb_eRuntimeError, "repeated combination reentered");
04881         }
04882     }
04883 }
04884 
04885 static VALUE
04886 rb_ary_repeated_combination_size(VALUE ary, VALUE args)
04887 {
04888     long n = RARRAY_LEN(ary);
04889     long k = NUM2LONG(RARRAY_PTR(args)[0]);
04890     if (k == 0) {
04891         return LONG2FIX(1);
04892     }
04893     return binomial_coefficient(k, n + k - 1);
04894 }
04895 
04896 /*
04897  *  call-seq:
04898  *     ary.repeated_combination(n) { |c| block } -> ary
04899  *     ary.repeated_combination(n)               -> Enumerator
04900  *
04901  * When invoked with a block, yields all repeated combinations of length +n+ of
04902  * elements from the array and then returns the array itself.
04903  *
04904  * The implementation makes no guarantees about the order in which the repeated
04905  * combinations are yielded.
04906  *
04907  * If no block is given, an Enumerator is returned instead.
04908  *
04909  * Examples:
04910  *
04911  *   a = [1, 2, 3]
04912  *   a.repeated_combination(1).to_a  #=> [[1], [2], [3]]
04913  *   a.repeated_combination(2).to_a  #=> [[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]]
04914  *   a.repeated_combination(3).to_a  #=> [[1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3],
04915  *                                   #    [1,3,3],[2,2,2],[2,2,3],[2,3,3],[3,3,3]]
04916  *   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],
04917  *                                   #    [1,1,3,3],[1,2,2,2],[1,2,2,3],[1,2,3,3],[1,3,3,3],
04918  *                                   #    [2,2,2,2],[2,2,2,3],[2,2,3,3],[2,3,3,3],[3,3,3,3]]
04919  *   a.repeated_combination(0).to_a  #=> [[]] # one combination of length 0
04920  *
04921  */
04922 
04923 static VALUE
04924 rb_ary_repeated_combination(VALUE ary, VALUE num)
04925 {
04926     long n, i, len;
04927 
04928     n = NUM2LONG(num);                 /* Combination size from argument */
04929     RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_repeated_combination_size);   /* Return enumerator if no block */
04930     len = RARRAY_LEN(ary);
04931     if (n < 0) {
04932         /* yield nothing */
04933     }
04934     else if (n == 0) {
04935         rb_yield(rb_ary_new2(0));
04936     }
04937     else if (n == 1) {
04938         for (i = 0; i < len; i++) {
04939             rb_yield(rb_ary_new3(1, RARRAY_PTR(ary)[i]));
04940         }
04941     }
04942     else if (len == 0) {
04943         /* yield nothing */
04944     }
04945     else {
04946         volatile VALUE t0 = tmpbuf(n, sizeof(long));
04947         long *p = (long*)RSTRING_PTR(t0);
04948         VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
04949         RBASIC(ary0)->klass = 0;
04950 
04951         rcombinate0(len, n, p, 0, n, ary0); /* compute and yield repeated combinations */
04952         tmpbuf_discard(t0);
04953         RBASIC(ary0)->klass = rb_cArray;
04954     }
04955     return ary;
04956 }
04957 
04958 /*
04959  *  call-seq:
04960  *     ary.product(other_ary, ...)                -> new_ary
04961  *     ary.product(other_ary, ...) { |p| block }  -> ary
04962  *
04963  *  Returns an array of all combinations of elements from all arrays.
04964  *
04965  *  The length of the returned array is the product of the length of +self+ and
04966  *  the argument arrays.
04967  *
04968  *  If given a block, #product will yield all combinations and return +self+
04969  *  instead.
04970  *
04971  *     [1,2,3].product([4,5])     #=> [[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]
04972  *     [1,2].product([1,2])       #=> [[1,1],[1,2],[2,1],[2,2]]
04973  *     [1,2].product([3,4],[5,6]) #=> [[1,3,5],[1,3,6],[1,4,5],[1,4,6],
04974  *                                #     [2,3,5],[2,3,6],[2,4,5],[2,4,6]]
04975  *     [1,2].product()            #=> [[1],[2]]
04976  *     [1,2].product([])          #=> []
04977  */
04978 
04979 static VALUE
04980 rb_ary_product(int argc, VALUE *argv, VALUE ary)
04981 {
04982     int n = argc+1;    /* How many arrays we're operating on */
04983     volatile VALUE t0 = tmpary(n);
04984     volatile VALUE t1 = tmpbuf(n, sizeof(int));
04985     VALUE *arrays = RARRAY_PTR(t0); /* The arrays we're computing the product of */
04986     int *counters = (int*)RSTRING_PTR(t1); /* The current position in each one */
04987     VALUE result = Qnil;      /* The array we'll be returning, when no block given */
04988     long i,j;
04989     long resultlen = 1;
04990 
04991     RBASIC(t0)->klass = 0;
04992     RBASIC(t1)->klass = 0;
04993 
04994     /* initialize the arrays of arrays */
04995     ARY_SET_LEN(t0, n);
04996     arrays[0] = ary;
04997     for (i = 1; i < n; i++) arrays[i] = Qnil;
04998     for (i = 1; i < n; i++) arrays[i] = to_ary(argv[i-1]);
04999 
05000     /* initialize the counters for the arrays */
05001     for (i = 0; i < n; i++) counters[i] = 0;
05002 
05003     /* Otherwise, allocate and fill in an array of results */
05004     if (rb_block_given_p()) {
05005         /* Make defensive copies of arrays; exit if any is empty */
05006         for (i = 0; i < n; i++) {
05007             if (RARRAY_LEN(arrays[i]) == 0) goto done;
05008             arrays[i] = ary_make_shared_copy(arrays[i]);
05009         }
05010     }
05011     else {
05012         /* Compute the length of the result array; return [] if any is empty */
05013         for (i = 0; i < n; i++) {
05014             long k = RARRAY_LEN(arrays[i]);
05015             if (k == 0) {
05016                 result = rb_ary_new2(0);
05017                 goto done;
05018             }
05019             if (MUL_OVERFLOW_LONG_P(resultlen, k))
05020                 rb_raise(rb_eRangeError, "too big to product");
05021             resultlen *= k;
05022         }
05023         result = rb_ary_new2(resultlen);
05024     }
05025     for (;;) {
05026         int m;
05027         /* fill in one subarray */
05028         VALUE subarray = rb_ary_new2(n);
05029         for (j = 0; j < n; j++) {
05030             rb_ary_push(subarray, rb_ary_entry(arrays[j], counters[j]));
05031         }
05032 
05033         /* put it on the result array */
05034         if (NIL_P(result)) {
05035             FL_SET(t0, FL_USER5);
05036             rb_yield(subarray);
05037             if (! FL_TEST(t0, FL_USER5)) {
05038                 rb_raise(rb_eRuntimeError, "product reentered");
05039             }
05040             else {
05041                 FL_UNSET(t0, FL_USER5);
05042             }
05043         }
05044         else {
05045             rb_ary_push(result, subarray);
05046         }
05047 
05048         /*
05049          * Increment the last counter.  If it overflows, reset to 0
05050          * and increment the one before it.
05051          */
05052         m = n-1;
05053         counters[m]++;
05054         while (counters[m] == RARRAY_LEN(arrays[m])) {
05055             counters[m] = 0;
05056             /* If the first counter overflows, we are done */
05057             if (--m < 0) goto done;
05058             counters[m]++;
05059         }
05060     }
05061 done:
05062     tmpary_discard(t0);
05063     tmpbuf_discard(t1);
05064 
05065     return NIL_P(result) ? ary : result;
05066 }
05067 
05068 /*
05069  *  call-seq:
05070  *     ary.take(n)               -> new_ary
05071  *
05072  *  Returns first +n+ elements from the array.
05073  *
05074  *  If a negative number is given, raises an ArgumentError.
05075  *
05076  *  See also Array#drop
05077  *
05078  *     a = [1, 2, 3, 4, 5, 0]
05079  *     a.take(3)             #=> [1, 2, 3]
05080  *
05081  */
05082 
05083 static VALUE
05084 rb_ary_take(VALUE obj, VALUE n)
05085 {
05086     long len = NUM2LONG(n);
05087     if (len < 0) {
05088         rb_raise(rb_eArgError, "attempt to take negative size");
05089     }
05090     return rb_ary_subseq(obj, 0, len);
05091 }
05092 
05093 /*
05094  *  call-seq:
05095  *     ary.take_while { |arr| block }  -> new_ary
05096  *     ary.take_while                  -> Enumerator
05097  *
05098  *  Passes elements to the block until the block returns +nil+ or +false+, then
05099  *  stops iterating and returns an array of all prior elements.
05100  *
05101  *  If no block is given, an Enumerator is returned instead.
05102  *
05103  *  See also Array#drop_while
05104  *
05105  *     a = [1, 2, 3, 4, 5, 0]
05106  *     a.take_while { |i| i < 3 }  #=> [1, 2]
05107  *
05108  */
05109 
05110 static VALUE
05111 rb_ary_take_while(VALUE ary)
05112 {
05113     long i;
05114 
05115     RETURN_ENUMERATOR(ary, 0, 0);
05116     for (i = 0; i < RARRAY_LEN(ary); i++) {
05117         if (!RTEST(rb_yield(RARRAY_PTR(ary)[i]))) break;
05118     }
05119     return rb_ary_take(ary, LONG2FIX(i));
05120 }
05121 
05122 /*
05123  *  call-seq:
05124  *     ary.drop(n)               -> new_ary
05125  *
05126  *  Drops first +n+ elements from +ary+ and returns the rest of the elements in
05127  *  an array.
05128  *
05129  *  If a negative number is given, raises an ArgumentError.
05130  *
05131  *  See also Array#take
05132  *
05133  *     a = [1, 2, 3, 4, 5, 0]
05134  *     a.drop(3)             #=> [4, 5, 0]
05135  *
05136  */
05137 
05138 static VALUE
05139 rb_ary_drop(VALUE ary, VALUE n)
05140 {
05141     VALUE result;
05142     long pos = NUM2LONG(n);
05143     if (pos < 0) {
05144         rb_raise(rb_eArgError, "attempt to drop negative size");
05145     }
05146 
05147     result = rb_ary_subseq(ary, pos, RARRAY_LEN(ary));
05148     if (result == Qnil) result = rb_ary_new();
05149     return result;
05150 }
05151 
05152 /*
05153  *  call-seq:
05154  *     ary.drop_while { |arr| block }   -> new_ary
05155  *     ary.drop_while                  -> Enumerator
05156  *
05157  *  Drops elements up to, but not including, the first element for which the
05158  *  block returns +nil+ or +false+ and returns an array containing the
05159  *  remaining elements.
05160  *
05161  *  If no block is given, an Enumerator is returned instead.
05162  *
05163  *  See also Array#take_while
05164  *
05165  *     a = [1, 2, 3, 4, 5, 0]
05166  *     a.drop_while {|i| i < 3 }   #=> [3, 4, 5, 0]
05167  *
05168  */
05169 
05170 static VALUE
05171 rb_ary_drop_while(VALUE ary)
05172 {
05173     long i;
05174 
05175     RETURN_ENUMERATOR(ary, 0, 0);
05176     for (i = 0; i < RARRAY_LEN(ary); i++) {
05177         if (!RTEST(rb_yield(RARRAY_PTR(ary)[i]))) break;
05178     }
05179     return rb_ary_drop(ary, LONG2FIX(i));
05180 }
05181 
05182 /*
05183  *  Arrays are ordered, integer-indexed collections of any object.
05184  *
05185  *  Array indexing starts at 0, as in C or Java.  A negative index is assumed
05186  *  to be relative to the end of the array---that is, an index of -1 indicates
05187  *  the last element of the array, -2 is the next to last element in the
05188  *  array, and so on.
05189  *
05190  *  == Creating Arrays
05191  *
05192  *  A new array can be created by using the literal constructor
05193  *  <code>[]</code>.  Arrays can contain different types of objects.  For
05194  *  example, the array below contains an Integer, a String and a Float:
05195  *
05196  *     ary = [1, "two", 3.0] #=> [1, "two", 3.0]
05197  *
05198  *  An array can also be created by explicitly calling Array.new with zero, one
05199  *  (the initial size of the Array) or two arguments (the initial size and a
05200  *  default object).
05201  *
05202  *     ary = Array.new    #=> []
05203  *     Array.new(3)       #=> [nil, nil, nil]
05204  *     Array.new(3, true) #=> [true, true, true]
05205  *
05206  *  Note that the second argument populates the array with references to the
05207  *  same object.  Therefore, it is only recommended in cases when you need to
05208  *  instantiate arrays with natively immutable objects such as Symbols,
05209  *  numbers, true or false.
05210  *
05211  *  To create an array with separate objects a block can be passed instead.
05212  *  This method is safe to use with mutable objects such as hashes, strings or
05213  *  other arrays:
05214  *
05215  *     Array.new(4) { Hash.new } #=> [{}, {}, {}, {}]
05216  *
05217  *  This is also a quick way to build up multi-dimensional arrays:
05218  *
05219  *     empty_table = Array.new(3) { Array.new(3) }
05220  *     #=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
05221  *
05222  *  An array can also be created by using the Array() method, provided by
05223  *  Kernel, which tries to call #to_ary, then #to_a on its argument.
05224  *
05225  *      Array({:a => "a", :b => "b"}) #=> [[:a, "a"], [:b, "b"]]
05226  *
05227  *  == Example Usage
05228  *
05229  *  In addition to the methods it mixes in through the Enumerable module, the
05230  *  Array class has proprietary methods for accessing, searching and otherwise
05231  *  manipulating arrays.
05232  *
05233  *  Some of the more common ones are illustrated below.
05234  *
05235  *  == Accessing Elements
05236  *
05237  *  Elements in an array can be retrieved using the Array#[] method.  It can
05238  *  take a single integer argument (a numeric index), a pair of arguments
05239  *  (start and length) or a range.
05240  *
05241  *     arr = [1, 2, 3, 4, 5, 6]
05242  *     arr[2]    #=> 3
05243  *     arr[100]  #=> nil
05244  *     arr[-3]   #=> 4
05245  *     arr[2, 3] #=> [3, 4, 5]
05246  *     arr[1..4] #=> [2, 3, 4, 5]
05247  *
05248  *  Another way to access a particular array element is by using the #at method
05249  *
05250  *     arr.at(0) #=> 1
05251  *
05252  *  The #slice method works in an identical manner to Array#[].
05253  *
05254  *  To raise an error for indices outside of the array bounds or else to
05255  *  provide a default value when that happens, you can use #fetch.
05256  *
05257  *     arr = ['a', 'b', 'c', 'd', 'e', 'f']
05258  *     arr.fetch(100) #=> IndexError: index 100 outside of array bounds: -6...6
05259  *     arr.fetch(100, "oops") #=> "oops"
05260  *
05261  *  The special methods #first and #last will return the first and last
05262  *  elements of an array, respectively.
05263  *
05264  *     arr.first #=> 1
05265  *     arr.last  #=> 6
05266  *
05267  *  To return the first +n+ elements of an array, use #take
05268  *
05269  *     arr.take(3) #=> [1, 2, 3]
05270  *
05271  *  #drop does the opposite of #take, by returning the elements after +n+
05272  *  elements have been dropped:
05273  *
05274  *     arr.drop(3) #=> [4, 5, 6]
05275  *
05276  *  == Obtaining Information about an Array
05277  *
05278  *  Arrays keep track of their own length at all times.  To query an array
05279  *  about the number of elements it contains, use #length, #count or #size.
05280  *
05281  *    browsers = ['Chrome', 'Firefox', 'Safari', 'Opera', 'IE']
05282  *    browsers.length #=> 5
05283  *    browsers.count #=> 5
05284  *
05285  *  To check whether an array contains any elements at all
05286  *
05287  *    browsers.empty? #=> false
05288  *
05289  *  To check whether a particular item is included in the array
05290  *
05291  *    browsers.include?('Konqueror') #=> false
05292  *
05293  *  == Adding Items to Arrays
05294  *
05295  *  Items can be added to the end of an array by using either #push or #<<
05296  *
05297  *    arr = [1, 2, 3, 4]
05298  *    arr.push(5) #=> [1, 2, 3, 4, 5]
05299  *    arr << 6    #=> [1, 2, 3, 4, 5, 6]
05300  *
05301  *  #unshift will add a new item to the beginning of an array.
05302  *
05303  *     arr.unshift(0) #=> [0, 1, 2, 3, 4, 5, 6]
05304  *
05305  *  With #insert you can add a new element to an array at any position.
05306  *
05307  *     arr.insert(3, 'apple')  #=> [0, 1, 2, 'apple', 3, 4, 5, 6]
05308  *
05309  *  Using the #insert method, you can also insert multiple values at once:
05310  *
05311  *     arr.insert(3, 'orange', 'pear', 'grapefruit')
05312  *     #=> [0, 1, 2, "orange", "pear", "grapefruit", "apple", 3, 4, 5, 6]
05313  *
05314  *  == Removing Items from an Array
05315  *
05316  *  The method #pop removes the last element in an array and returns it:
05317  *
05318  *     arr =  [1, 2, 3, 4, 5, 6]
05319  *     arr.pop #=> 6
05320  *     arr #=> [1, 2, 3, 4, 5]
05321  *
05322  *  To retrieve and at the same time remove the first item, use #shift:
05323  *
05324  *     arr.shift #=> 1
05325  *     arr #=> [2, 3, 4, 5]
05326  *
05327  *  To delete an element at a particular index:
05328  *
05329  *     arr.delete_at(2) #=> 4
05330  *     arr #=> [2, 3, 5]
05331  *
05332  *  To delete a particular element anywhere in an array, use #delete:
05333  *
05334  *     arr = [1, 2, 2, 3]
05335  *     arr.delete(2) #=> [1, 3]
05336  *
05337  *  A useful method if you need to remove +nil+ values from an array is
05338  *  #compact:
05339  *
05340  *     arr = ['foo', 0, nil, 'bar', 7, 'baz', nil]
05341  *     arr.compact  #=> ['foo', 0, 'bar', 7, 'baz']
05342  *     arr          #=> ['foo', 0, nil, 'bar', 7, 'baz', nil]
05343  *     arr.compact! #=> ['foo', 0, 'bar', 7, 'baz']
05344  *     arr          #=> ['foo', 0, 'bar', 7, 'baz']
05345  *
05346  *  Another common need is to remove duplicate elements from an array.
05347  *
05348  *  It has the non-destructive #uniq, and destructive method #uniq!
05349  *
05350  *     arr = [2, 5, 6, 556, 6, 6, 8, 9, 0, 123, 556]
05351  *     arr.uniq #=> [2, 5, 6, 556, 8, 9, 0, 123]
05352  *
05353  *  == Iterating over Arrays
05354  *
05355  *  Like all classes that include the Enumerable module, Array has an each
05356  *  method, which defines what elements should be iterated over and how.  In
05357  *  case of Array's #each, all elements in the Array instance are yielded to
05358  *  the supplied block in sequence.
05359  *
05360  *  Note that this operation leaves the array unchanged.
05361  *
05362  *     arr = [1, 2, 3, 4, 5]
05363  *     arr.each { |a| print a -= 10, " " }
05364  *     # prints: -9 -8 -7 -6 -5
05365  *     #=> [1, 2, 3, 4, 5]
05366  *
05367  *  Another sometimes useful iterator is #reverse_each which will iterate over
05368  *  the elements in the array in reverse order.
05369  *
05370  *     words = %w[rats live on no evil star]
05371  *     str = ""
05372  *     words.reverse_each { |word| str += "#{word.reverse} " }
05373  *     str #=> "rats live on no evil star "
05374  *
05375  *  The #map method can be used to create a new array based on the original
05376  *  array, but with the values modified by the supplied block:
05377  *
05378  *     arr.map { |a| 2*a }   #=> [2, 4, 6, 8, 10]
05379  *     arr                   #=> [1, 2, 3, 4, 5]
05380  *     arr.map! { |a| a**2 } #=> [1, 4, 9, 16, 25]
05381  *     arr                   #=> [1, 4, 9, 16, 25]
05382  *
05383  *  == Selecting Items from an Array
05384  *
05385  *  Elements can be selected from an array according to criteria defined in a
05386  *  block.  The selection can happen in a destructive or a non-destructive
05387  *  manner.  While the destructive operations will modify the array they were
05388  *  called on, the non-destructive methods usually return a new array with the
05389  *  selected elements, but leave the original array unchanged.
05390  *
05391  *  === Non-destructive Selection
05392  *
05393  *     arr = [1, 2, 3, 4, 5, 6]
05394  *     arr.select { |a| a > 3 }     #=> [4, 5, 6]
05395  *     arr.reject { |a| a < 3 }     #=> [3, 4, 5, 6]
05396  *     arr.drop_while { |a| a < 4 } #=> [4, 5, 6]
05397  *     arr                          #=> [1, 2, 3, 4, 5, 6]
05398  *
05399  *  === Destructive Selection
05400  *
05401  *  #select! and #reject! are the corresponding destructive methods to #select
05402  *  and #reject
05403  *
05404  *  Similar to #select vs. #reject, #delete_if and #keep_if have the exact
05405  *  opposite result when supplied with the same block:
05406  *
05407  *     arr.delete_if { |a| a < 4 } #=> [4, 5, 6]
05408  *     arr                         #=> [4, 5, 6]
05409  *
05410  *     arr = [1, 2, 3, 4, 5, 6]
05411  *     arr.keep_if { |a| a < 4 } #=> [1, 2, 3]
05412  *     arr                       #=> [1, 2, 3]
05413  *
05414  */
05415 
05416 void
05417 Init_Array(void)
05418 {
05419 #undef rb_intern
05420 #define rb_intern(str) rb_intern_const(str)
05421 
05422     rb_cArray  = rb_define_class("Array", rb_cObject);
05423     rb_include_module(rb_cArray, rb_mEnumerable);
05424 
05425     rb_define_alloc_func(rb_cArray, empty_ary_alloc);
05426     rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -1);
05427     rb_define_singleton_method(rb_cArray, "try_convert", rb_ary_s_try_convert, 1);
05428     rb_define_method(rb_cArray, "initialize", rb_ary_initialize, -1);
05429     rb_define_method(rb_cArray, "initialize_copy", rb_ary_replace, 1);
05430 
05431     rb_define_method(rb_cArray, "inspect", rb_ary_inspect, 0);
05432     rb_define_alias(rb_cArray,  "to_s", "inspect");
05433     rb_define_method(rb_cArray, "to_a", rb_ary_to_a, 0);
05434     rb_define_method(rb_cArray, "to_ary", rb_ary_to_ary_m, 0);
05435     rb_define_method(rb_cArray, "frozen?",  rb_ary_frozen_p, 0);
05436 
05437     rb_define_method(rb_cArray, "==", rb_ary_equal, 1);
05438     rb_define_method(rb_cArray, "eql?", rb_ary_eql, 1);
05439     rb_define_method(rb_cArray, "hash", rb_ary_hash, 0);
05440 
05441     rb_define_method(rb_cArray, "[]", rb_ary_aref, -1);
05442     rb_define_method(rb_cArray, "[]=", rb_ary_aset, -1);
05443     rb_define_method(rb_cArray, "at", rb_ary_at, 1);
05444     rb_define_method(rb_cArray, "fetch", rb_ary_fetch, -1);
05445     rb_define_method(rb_cArray, "first", rb_ary_first, -1);
05446     rb_define_method(rb_cArray, "last", rb_ary_last, -1);
05447     rb_define_method(rb_cArray, "concat", rb_ary_concat, 1);
05448     rb_define_method(rb_cArray, "<<", rb_ary_push, 1);
05449     rb_define_method(rb_cArray, "push", rb_ary_push_m, -1);
05450     rb_define_method(rb_cArray, "pop", rb_ary_pop_m, -1);
05451     rb_define_method(rb_cArray, "shift", rb_ary_shift_m, -1);
05452     rb_define_method(rb_cArray, "unshift", rb_ary_unshift_m, -1);
05453     rb_define_method(rb_cArray, "insert", rb_ary_insert, -1);
05454     rb_define_method(rb_cArray, "each", rb_ary_each, 0);
05455     rb_define_method(rb_cArray, "each_index", rb_ary_each_index, 0);
05456     rb_define_method(rb_cArray, "reverse_each", rb_ary_reverse_each, 0);
05457     rb_define_method(rb_cArray, "length", rb_ary_length, 0);
05458     rb_define_alias(rb_cArray,  "size", "length");
05459     rb_define_method(rb_cArray, "empty?", rb_ary_empty_p, 0);
05460     rb_define_method(rb_cArray, "find_index", rb_ary_index, -1);
05461     rb_define_method(rb_cArray, "index", rb_ary_index, -1);
05462     rb_define_method(rb_cArray, "rindex", rb_ary_rindex, -1);
05463     rb_define_method(rb_cArray, "join", rb_ary_join_m, -1);
05464     rb_define_method(rb_cArray, "reverse", rb_ary_reverse_m, 0);
05465     rb_define_method(rb_cArray, "reverse!", rb_ary_reverse_bang, 0);
05466     rb_define_method(rb_cArray, "rotate", rb_ary_rotate_m, -1);
05467     rb_define_method(rb_cArray, "rotate!", rb_ary_rotate_bang, -1);
05468     rb_define_method(rb_cArray, "sort", rb_ary_sort, 0);
05469     rb_define_method(rb_cArray, "sort!", rb_ary_sort_bang, 0);
05470     rb_define_method(rb_cArray, "sort_by!", rb_ary_sort_by_bang, 0);
05471     rb_define_method(rb_cArray, "collect", rb_ary_collect, 0);
05472     rb_define_method(rb_cArray, "collect!", rb_ary_collect_bang, 0);
05473     rb_define_method(rb_cArray, "map", rb_ary_collect, 0);
05474     rb_define_method(rb_cArray, "map!", rb_ary_collect_bang, 0);
05475     rb_define_method(rb_cArray, "select", rb_ary_select, 0);
05476     rb_define_method(rb_cArray, "select!", rb_ary_select_bang, 0);
05477     rb_define_method(rb_cArray, "keep_if", rb_ary_keep_if, 0);
05478     rb_define_method(rb_cArray, "values_at", rb_ary_values_at, -1);
05479     rb_define_method(rb_cArray, "delete", rb_ary_delete, 1);
05480     rb_define_method(rb_cArray, "delete_at", rb_ary_delete_at_m, 1);
05481     rb_define_method(rb_cArray, "delete_if", rb_ary_delete_if, 0);
05482     rb_define_method(rb_cArray, "reject", rb_ary_reject, 0);
05483     rb_define_method(rb_cArray, "reject!", rb_ary_reject_bang, 0);
05484     rb_define_method(rb_cArray, "zip", rb_ary_zip, -1);
05485     rb_define_method(rb_cArray, "transpose", rb_ary_transpose, 0);
05486     rb_define_method(rb_cArray, "replace", rb_ary_replace, 1);
05487     rb_define_method(rb_cArray, "clear", rb_ary_clear, 0);
05488     rb_define_method(rb_cArray, "fill", rb_ary_fill, -1);
05489     rb_define_method(rb_cArray, "include?", rb_ary_includes, 1);
05490     rb_define_method(rb_cArray, "<=>", rb_ary_cmp, 1);
05491 
05492     rb_define_method(rb_cArray, "slice", rb_ary_aref, -1);
05493     rb_define_method(rb_cArray, "slice!", rb_ary_slice_bang, -1);
05494 
05495     rb_define_method(rb_cArray, "assoc", rb_ary_assoc, 1);
05496     rb_define_method(rb_cArray, "rassoc", rb_ary_rassoc, 1);
05497 
05498     rb_define_method(rb_cArray, "+", rb_ary_plus, 1);
05499     rb_define_method(rb_cArray, "*", rb_ary_times, 1);
05500 
05501     rb_define_method(rb_cArray, "-", rb_ary_diff, 1);
05502     rb_define_method(rb_cArray, "&", rb_ary_and, 1);
05503     rb_define_method(rb_cArray, "|", rb_ary_or, 1);
05504 
05505     rb_define_method(rb_cArray, "uniq", rb_ary_uniq, 0);
05506     rb_define_method(rb_cArray, "uniq!", rb_ary_uniq_bang, 0);
05507     rb_define_method(rb_cArray, "compact", rb_ary_compact, 0);
05508     rb_define_method(rb_cArray, "compact!", rb_ary_compact_bang, 0);
05509     rb_define_method(rb_cArray, "flatten", rb_ary_flatten, -1);
05510     rb_define_method(rb_cArray, "flatten!", rb_ary_flatten_bang, -1);
05511     rb_define_method(rb_cArray, "count", rb_ary_count, -1);
05512     rb_define_method(rb_cArray, "shuffle!", rb_ary_shuffle_bang, -1);
05513     rb_define_method(rb_cArray, "shuffle", rb_ary_shuffle, -1);
05514     rb_define_method(rb_cArray, "sample", rb_ary_sample, -1);
05515     rb_define_method(rb_cArray, "cycle", rb_ary_cycle, -1);
05516     rb_define_method(rb_cArray, "permutation", rb_ary_permutation, -1);
05517     rb_define_method(rb_cArray, "combination", rb_ary_combination, 1);
05518     rb_define_method(rb_cArray, "repeated_permutation", rb_ary_repeated_permutation, 1);
05519     rb_define_method(rb_cArray, "repeated_combination", rb_ary_repeated_combination, 1);
05520     rb_define_method(rb_cArray, "product", rb_ary_product, -1);
05521 
05522     rb_define_method(rb_cArray, "take", rb_ary_take, 1);
05523     rb_define_method(rb_cArray, "take_while", rb_ary_take_while, 0);
05524     rb_define_method(rb_cArray, "drop", rb_ary_drop, 1);
05525     rb_define_method(rb_cArray, "drop_while", rb_ary_drop_while, 0);
05526     rb_define_method(rb_cArray, "bsearch", rb_ary_bsearch, 0);
05527 
05528     id_cmp = rb_intern("<=>");
05529     sym_random = ID2SYM(rb_intern("random"));
05530     id_div = rb_intern("div");
05531     id_power = rb_intern("**");
05532 }
05533