Ruby 4.0.7p0 (2026-09-15 revision 229531a6cfbf07e3caef30dbac24a2a3f3fed482)
array.c
1/**********************************************************************
2
3 array.c -
4
5 $Author$
6 created at: Fri Aug 6 09:46:12 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
11
12**********************************************************************/
13
14#include "debug_counter.h"
15#include "id.h"
16#include "internal.h"
17#include "internal/array.h"
18#include "internal/compar.h"
19#include "internal/enum.h"
20#include "internal/gc.h"
21#include "internal/hash.h"
22#include "internal/numeric.h"
23#include "internal/object.h"
24#include "internal/proc.h"
25#include "internal/rational.h"
26#include "internal/vm.h"
27#include "probes.h"
28#include "ruby/encoding.h"
29#include "ruby/st.h"
30#include "ruby/thread.h"
31#include "ruby/util.h"
32#include "ruby/ractor.h"
33#include "vm_core.h"
34#include "builtin.h"
35
36#if !ARRAY_DEBUG
37# undef NDEBUG
38# define NDEBUG
39#endif
40#include "ruby_assert.h"
41
43VALUE rb_cArray_empty_frozen;
44
45/* Flags of RArray
46 *
47 * 0: RARRAY_SHARED_FLAG (equal to ELTS_SHARED)
48 * The array is shared. The buffer this array points to is owned by
49 * another array (the shared root).
50 * 1: RARRAY_EMBED_FLAG
51 * The array is embedded (its contents follow the header, rather than
52 * being on a separately allocated buffer).
53 * 3-9: RARRAY_EMBED_LEN
54 * The length of the array when RARRAY_EMBED_FLAG is set.
55 * 12: RARRAY_SHARED_ROOT_FLAG
56 * The array is a shared root that does reference counting. The buffer
57 * this array points to is owned by this array but may be pointed to
58 * by other arrays.
59 * Note: Frozen arrays may be a shared root without this flag being
60 * set. Frozen arrays do not have reference counting because
61 * they cannot be modified. Not updating the reference count
62 * improves copy-on-write performance. Their reference count is
63 * assumed to be infinity.
64 * 14: RARRAY_PTR_IN_USE_FLAG
65 * The buffer of the array is in use. This is only used during
66 * debugging.
67 */
68
69/* for OPTIMIZED_CMP: */
70#define id_cmp idCmp
71
72#define ARY_DEFAULT_SIZE 16
73#define ARY_MAX_SIZE (LONG_MAX / (int)sizeof(VALUE))
74#define SMALL_ARRAY_LEN 16
75
77static int
78should_be_T_ARRAY(VALUE ary)
79{
80 return RB_TYPE_P(ary, T_ARRAY);
81}
82
83#define ARY_HEAP_PTR(a) (RUBY_ASSERT(!ARY_EMBED_P(a)), RARRAY(a)->as.heap.ptr)
84#define ARY_HEAP_LEN(a) (RUBY_ASSERT(!ARY_EMBED_P(a)), RARRAY(a)->as.heap.len)
85#define ARY_HEAP_CAPA(a) (RUBY_ASSERT(!ARY_EMBED_P(a)), RUBY_ASSERT(!ARY_SHARED_ROOT_P(a)), \
86 RARRAY(a)->as.heap.aux.capa)
87
88#define ARY_EMBED_PTR(a) (RUBY_ASSERT(ARY_EMBED_P(a)), RARRAY(a)->as.ary)
89#define ARY_EMBED_LEN(a) \
90 (RUBY_ASSERT(ARY_EMBED_P(a)), \
91 (long)((RBASIC(a)->flags >> RARRAY_EMBED_LEN_SHIFT) & \
92 (RARRAY_EMBED_LEN_MASK >> RARRAY_EMBED_LEN_SHIFT)))
93#define ARY_HEAP_SIZE(a) (RUBY_ASSERT(!ARY_EMBED_P(a)), RUBY_ASSERT(ARY_OWNS_HEAP_P(a)), ARY_CAPA(a) * sizeof(VALUE))
94
95#define ARY_OWNS_HEAP_P(a) (RUBY_ASSERT(should_be_T_ARRAY((VALUE)(a))), \
96 !FL_TEST_RAW((a), RARRAY_SHARED_FLAG|RARRAY_EMBED_FLAG))
97
98#define FL_SET_EMBED(a) do { \
99 RUBY_ASSERT(!ARY_SHARED_P(a)); \
100 FL_SET((a), RARRAY_EMBED_FLAG); \
101 ary_verify(a); \
102} while (0)
103
104#define FL_UNSET_EMBED(ary) FL_UNSET((ary), RARRAY_EMBED_FLAG|RARRAY_EMBED_LEN_MASK)
105#define FL_SET_SHARED(ary) do { \
106 RUBY_ASSERT(!ARY_EMBED_P(ary)); \
107 FL_SET((ary), RARRAY_SHARED_FLAG); \
108} while (0)
109#define FL_UNSET_SHARED(ary) FL_UNSET((ary), RARRAY_SHARED_FLAG)
110
111#define ARY_SET_PTR_FORCE(ary, p) \
112 (RARRAY(ary)->as.heap.ptr = (p))
113#define ARY_SET_PTR(ary, p) do { \
114 RUBY_ASSERT(!ARY_EMBED_P(ary)); \
115 RUBY_ASSERT(!OBJ_FROZEN(ary)); \
116 ARY_SET_PTR_FORCE(ary, p); \
117} while (0)
118#define ARY_SET_EMBED_LEN(ary, n) do { \
119 long tmp_n = (n); \
120 RUBY_ASSERT(ARY_EMBED_P(ary)); \
121 RBASIC(ary)->flags &= ~RARRAY_EMBED_LEN_MASK; \
122 RBASIC(ary)->flags |= (tmp_n) << RARRAY_EMBED_LEN_SHIFT; \
123} while (0)
124#define ARY_SET_HEAP_LEN(ary, n) do { \
125 RUBY_ASSERT(!ARY_EMBED_P(ary)); \
126 RARRAY(ary)->as.heap.len = (n); \
127} while (0)
128#define ARY_SET_LEN(ary, n) do { \
129 if (ARY_EMBED_P(ary)) { \
130 ARY_SET_EMBED_LEN((ary), (n)); \
131 } \
132 else { \
133 ARY_SET_HEAP_LEN((ary), (n)); \
134 } \
135 RUBY_ASSERT(RARRAY_LEN(ary) == (n)); \
136} while (0)
137#define ARY_INCREASE_PTR(ary, n) do { \
138 RUBY_ASSERT(!ARY_EMBED_P(ary)); \
139 RUBY_ASSERT(!OBJ_FROZEN(ary)); \
140 RARRAY(ary)->as.heap.ptr += (n); \
141} while (0)
142#define ARY_INCREASE_LEN(ary, n) do { \
143 RUBY_ASSERT(!OBJ_FROZEN(ary)); \
144 if (ARY_EMBED_P(ary)) { \
145 ARY_SET_EMBED_LEN((ary), RARRAY_LEN(ary)+(n)); \
146 } \
147 else { \
148 RARRAY(ary)->as.heap.len += (n); \
149 } \
150} while (0)
151
152#define ARY_CAPA(ary) (ARY_EMBED_P(ary) ? ary_embed_capa(ary) : \
153 ARY_SHARED_ROOT_P(ary) ? RARRAY_LEN(ary) : ARY_HEAP_CAPA(ary))
154#define ARY_SET_CAPA_FORCE(ary, n) \
155 RARRAY(ary)->as.heap.aux.capa = (n);
156#define ARY_SET_CAPA(ary, n) do { \
157 RUBY_ASSERT(!ARY_EMBED_P(ary)); \
158 RUBY_ASSERT(!ARY_SHARED_P(ary)); \
159 RUBY_ASSERT(!OBJ_FROZEN(ary)); \
160 ARY_SET_CAPA_FORCE(ary, n); \
161} while (0)
162
163#define ARY_SHARED_ROOT_OCCUPIED(ary) (!OBJ_FROZEN(ary) && ARY_SHARED_ROOT_REFCNT(ary) == 1)
164#define ARY_SET_SHARED_ROOT_REFCNT(ary, value) do { \
165 RUBY_ASSERT(ARY_SHARED_ROOT_P(ary)); \
166 RUBY_ASSERT(!OBJ_FROZEN(ary)); \
167 RUBY_ASSERT((value) >= 0); \
168 RARRAY(ary)->as.heap.aux.capa = (value); \
169} while (0)
170#define FL_SET_SHARED_ROOT(ary) do { \
171 RUBY_ASSERT(!OBJ_FROZEN(ary)); \
172 RUBY_ASSERT(!ARY_EMBED_P(ary)); \
173 FL_SET((ary), RARRAY_SHARED_ROOT_FLAG); \
174} while (0)
175
176static inline void
177ARY_SET(VALUE a, long i, VALUE v)
178{
179 RUBY_ASSERT(!ARY_SHARED_P(a));
181
182 RARRAY_ASET(a, i, v);
183}
184#undef RARRAY_ASET
185
186static long
187ary_embed_capa(VALUE ary)
188{
189 size_t size = rb_gc_obj_slot_size(ary) - offsetof(struct RArray, as.ary);
190 RUBY_ASSERT(size % sizeof(VALUE) == 0);
191 return size / sizeof(VALUE);
192}
193
194static size_t
195ary_embed_size(long capa)
196{
197 size_t size = offsetof(struct RArray, as.ary) + (sizeof(VALUE) * capa);
198 if (size < sizeof(struct RArray)) size = sizeof(struct RArray);
199 return size;
200}
201
202static bool
203ary_embeddable_p(long capa)
204{
205 return rb_gc_size_allocatable_p(ary_embed_size(capa));
206}
207
208bool
209rb_ary_embeddable_p(VALUE ary)
210{
211 /* An array cannot be turned embeddable when the array is:
212 * - Shared root: other objects may point to the buffer of this array
213 * so we cannot make it embedded.
214 * - Frozen: this array may also be a shared root without the shared root
215 * flag.
216 * - Shared: we don't want to re-embed an array that points to a shared
217 * root (to save memory).
218 */
219 return !(ARY_SHARED_ROOT_P(ary) || OBJ_FROZEN(ary) || ARY_SHARED_P(ary));
220}
221
222size_t
223rb_ary_size_as_embedded(VALUE ary)
224{
225 size_t real_size;
226
227 if (ARY_EMBED_P(ary)) {
228 real_size = ary_embed_size(ARY_EMBED_LEN(ary));
229 }
230 else if (rb_ary_embeddable_p(ary)) {
231 real_size = ary_embed_size(ARY_HEAP_CAPA(ary));
232 }
233 else {
234 real_size = sizeof(struct RArray);
235 }
236 return real_size;
237}
238
239
240#if ARRAY_DEBUG
241#define ary_verify(ary) ary_verify_(ary, __FILE__, __LINE__)
242
243static VALUE
244ary_verify_(VALUE ary, const char *file, int line)
245{
246 RUBY_ASSERT(RB_TYPE_P(ary, T_ARRAY));
247
248 if (ARY_SHARED_P(ary)) {
249 VALUE root = ARY_SHARED_ROOT(ary);
250 const VALUE *ptr = ARY_HEAP_PTR(ary);
251 const VALUE *root_ptr = RARRAY_CONST_PTR(root);
252 long len = ARY_HEAP_LEN(ary), root_len = RARRAY_LEN(root);
253 RUBY_ASSERT(ARY_SHARED_ROOT_P(root) || OBJ_FROZEN(root));
254 RUBY_ASSERT(root_ptr <= ptr && ptr + len <= root_ptr + root_len);
255 ary_verify(root);
256 }
257 else if (ARY_EMBED_P(ary)) {
258 RUBY_ASSERT(!ARY_SHARED_P(ary));
259 RUBY_ASSERT(RARRAY_LEN(ary) <= ary_embed_capa(ary));
260 }
261 else {
262 const VALUE *ptr = RARRAY_CONST_PTR(ary);
263 long i, len = RARRAY_LEN(ary);
264 volatile VALUE v;
265 if (len > 1) len = 1; /* check only HEAD */
266 for (i=0; i<len; i++) {
267 v = ptr[i]; /* access check */
268 }
269 v = v;
270 }
271
272 return ary;
273}
274#else
275#define ary_verify(ary) ((void)0)
276#endif
277
278VALUE *
279rb_ary_ptr_use_start(VALUE ary)
280{
281#if ARRAY_DEBUG
282 FL_SET_RAW(ary, RARRAY_PTR_IN_USE_FLAG);
283#endif
284 return (VALUE *)RARRAY_CONST_PTR(ary);
285}
286
287void
288rb_ary_ptr_use_end(VALUE ary)
289{
290#if ARRAY_DEBUG
291 FL_UNSET_RAW(ary, RARRAY_PTR_IN_USE_FLAG);
292#endif
293}
294
295void
296rb_mem_clear(VALUE *mem, long size)
297{
298 while (size--) {
299 *mem++ = Qnil;
300 }
301}
302
303static void
304ary_mem_clear(VALUE ary, long beg, long size)
305{
306 RARRAY_PTR_USE(ary, ptr, {
307 rb_mem_clear(ptr + beg, size);
308 });
309}
310
311static inline void
312memfill(register VALUE *mem, register long size, register VALUE val)
313{
314 while (size--) {
315 *mem++ = val;
316 }
317}
318
319static void
320ary_memfill(VALUE ary, long beg, long size, VALUE val)
321{
322 RARRAY_PTR_USE(ary, ptr, {
323 memfill(ptr + beg, size, val);
324 RB_OBJ_WRITTEN(ary, Qundef, val);
325 });
326}
327
328static void
329ary_memcpy0(VALUE ary, long beg, long argc, const VALUE *argv, VALUE buff_owner_ary)
330{
331 RUBY_ASSERT(!ARY_SHARED_P(buff_owner_ary));
332
333 if (argc > (int)(128/sizeof(VALUE)) /* is magic number (cache line size) */) {
334 rb_gc_writebarrier_remember(buff_owner_ary);
335 RARRAY_PTR_USE(ary, ptr, {
336 MEMCPY(ptr+beg, argv, VALUE, argc);
337 });
338 }
339 else {
340 int i;
341 RARRAY_PTR_USE(ary, ptr, {
342 for (i=0; i<argc; i++) {
343 RB_OBJ_WRITE(buff_owner_ary, &ptr[i+beg], argv[i]);
344 }
345 });
346 }
347}
348
349static void
350ary_memcpy(VALUE ary, long beg, long argc, const VALUE *argv)
351{
352 ary_memcpy0(ary, beg, argc, argv, ary);
353}
354
355static VALUE *
356ary_heap_alloc_buffer(size_t capa)
357{
358 return ALLOC_N(VALUE, capa);
359}
360
361static void
362ary_heap_free_ptr(VALUE ary, const VALUE *ptr, long size)
363{
364 ruby_sized_xfree((void *)ptr, size);
365}
366
367static void
368ary_heap_free(VALUE ary)
369{
370 ary_heap_free_ptr(ary, ARY_HEAP_PTR(ary), ARY_HEAP_SIZE(ary));
371}
372
373static size_t
374ary_heap_realloc(VALUE ary, size_t new_capa)
375{
376 RUBY_ASSERT(!OBJ_FROZEN(ary));
377 SIZED_REALLOC_N(RARRAY(ary)->as.heap.ptr, VALUE, new_capa, ARY_HEAP_CAPA(ary));
378 ary_verify(ary);
379
380 return new_capa;
381}
382
383void
384rb_ary_make_embedded(VALUE ary)
385{
386 RUBY_ASSERT(rb_ary_embeddable_p(ary));
387 if (!ARY_EMBED_P(ary)) {
388 const VALUE *buf = ARY_HEAP_PTR(ary);
389 long len = ARY_HEAP_LEN(ary);
390
391 FL_SET_EMBED(ary);
392 ARY_SET_EMBED_LEN(ary, len);
393
394 MEMCPY((void *)ARY_EMBED_PTR(ary), (void *)buf, VALUE, len);
395
396 ary_heap_free_ptr(ary, buf, len * sizeof(VALUE));
397 }
398}
399
400static void
401ary_resize_capa(VALUE ary, long capacity)
402{
403 RUBY_ASSERT(RARRAY_LEN(ary) <= capacity);
404 RUBY_ASSERT(!OBJ_FROZEN(ary));
405 RUBY_ASSERT(!ARY_SHARED_P(ary));
406
407 if (capacity > ary_embed_capa(ary)) {
408 size_t new_capa = capacity;
409 if (ARY_EMBED_P(ary)) {
410 long len = ARY_EMBED_LEN(ary);
411 VALUE *ptr = ary_heap_alloc_buffer(capacity);
412
413 MEMCPY(ptr, ARY_EMBED_PTR(ary), VALUE, len);
414 FL_UNSET_EMBED(ary);
415 ARY_SET_PTR(ary, ptr);
416 ARY_SET_HEAP_LEN(ary, len);
417 }
418 else {
419 new_capa = ary_heap_realloc(ary, capacity);
420 }
421 ARY_SET_CAPA(ary, new_capa);
422 }
423 else {
424 if (!ARY_EMBED_P(ary)) {
425 long len = ARY_HEAP_LEN(ary);
426 long old_capa = ARY_HEAP_CAPA(ary);
427 const VALUE *ptr = ARY_HEAP_PTR(ary);
428
429 if (len > capacity) len = capacity;
430 MEMCPY((VALUE *)RARRAY(ary)->as.ary, ptr, VALUE, len);
431 ary_heap_free_ptr(ary, ptr, old_capa);
432
433 FL_SET_EMBED(ary);
434 ARY_SET_LEN(ary, len);
435 }
436 }
437
438 ary_verify(ary);
439}
440
441static inline void
442ary_shrink_capa(VALUE ary)
443{
444 long capacity = ARY_HEAP_LEN(ary);
445 long old_capa = ARY_HEAP_CAPA(ary);
446 RUBY_ASSERT(!ARY_SHARED_P(ary));
447 RUBY_ASSERT(old_capa >= capacity);
448 if (old_capa > capacity) {
449 size_t new_capa = ary_heap_realloc(ary, capacity);
450 ARY_SET_CAPA(ary, new_capa);
451 }
452
453 ary_verify(ary);
454}
455
456static void
457ary_double_capa(VALUE ary, long min)
458{
459 long new_capa = ARY_CAPA(ary) / 2;
460
461 if (new_capa < ARY_DEFAULT_SIZE) {
462 new_capa = ARY_DEFAULT_SIZE;
463 }
464 if (new_capa >= ARY_MAX_SIZE - min) {
465 new_capa = (ARY_MAX_SIZE - min) / 2;
466 }
467 new_capa += min;
468 ary_resize_capa(ary, new_capa);
469
470 ary_verify(ary);
471}
472
473static void
474rb_ary_decrement_share(VALUE shared_root)
475{
476 if (!OBJ_FROZEN(shared_root)) {
477 long num = ARY_SHARED_ROOT_REFCNT(shared_root);
478 ARY_SET_SHARED_ROOT_REFCNT(shared_root, num - 1);
479 }
480}
481
482static void
483rb_ary_unshare(VALUE ary)
484{
485 VALUE shared_root = ARY_SHARED_ROOT(ary);
486 rb_ary_decrement_share(shared_root);
487 FL_UNSET_SHARED(ary);
488}
489
490static void
491rb_ary_reset(VALUE ary)
492{
493 if (ARY_OWNS_HEAP_P(ary)) {
494 ary_heap_free(ary);
495 }
496 else if (ARY_SHARED_P(ary)) {
497 rb_ary_unshare(ary);
498 }
499
500 FL_SET_EMBED(ary);
501 ARY_SET_EMBED_LEN(ary, 0);
502}
503
504static VALUE
505rb_ary_increment_share(VALUE shared_root)
506{
507 if (!OBJ_FROZEN(shared_root)) {
508 long num = ARY_SHARED_ROOT_REFCNT(shared_root);
509 RUBY_ASSERT(num >= 0);
510 ARY_SET_SHARED_ROOT_REFCNT(shared_root, num + 1);
511 }
512 return shared_root;
513}
514
515static void
516rb_ary_set_shared(VALUE ary, VALUE shared_root)
517{
518 RUBY_ASSERT(!ARY_EMBED_P(ary));
519 RUBY_ASSERT(!OBJ_FROZEN(ary));
520 RUBY_ASSERT(ARY_SHARED_ROOT_P(shared_root) || OBJ_FROZEN(shared_root));
521
522 rb_ary_increment_share(shared_root);
523 FL_SET_SHARED(ary);
524 RB_OBJ_WRITE(ary, &RARRAY(ary)->as.heap.aux.shared_root, shared_root);
525
526 RB_DEBUG_COUNTER_INC(obj_ary_shared_create);
527}
528
529static inline void
530rb_ary_modify_check(VALUE ary)
531{
532 RUBY_ASSERT(ruby_thread_has_gvl_p());
533
534 rb_check_frozen(ary);
535 ary_verify(ary);
536}
537
538void
539rb_ary_cancel_sharing(VALUE ary)
540{
541 if (ARY_SHARED_P(ary)) {
542 long shared_len, len = RARRAY_LEN(ary);
543 VALUE shared_root = ARY_SHARED_ROOT(ary);
544
545 ary_verify(shared_root);
546
547 if (len <= ary_embed_capa(ary)) {
548 const VALUE *ptr = ARY_HEAP_PTR(ary);
549 FL_UNSET_SHARED(ary);
550 FL_SET_EMBED(ary);
551 MEMCPY((VALUE *)ARY_EMBED_PTR(ary), ptr, VALUE, len);
552 rb_ary_decrement_share(shared_root);
553 ARY_SET_EMBED_LEN(ary, len);
554 }
555 else if (ARY_SHARED_ROOT_OCCUPIED(shared_root) && len > ((shared_len = RARRAY_LEN(shared_root))>>1)) {
556 long shift = RARRAY_CONST_PTR(ary) - RARRAY_CONST_PTR(shared_root);
557 FL_UNSET_SHARED(ary);
558 ARY_SET_PTR(ary, RARRAY_CONST_PTR(shared_root));
559 ARY_SET_CAPA(ary, shared_len);
560 RARRAY_PTR_USE(ary, ptr, {
561 MEMMOVE(ptr, ptr+shift, VALUE, len);
562 });
563 FL_SET_EMBED(shared_root);
564 rb_ary_decrement_share(shared_root);
565 }
566 else {
567 VALUE *ptr = ary_heap_alloc_buffer(len);
568 MEMCPY(ptr, ARY_HEAP_PTR(ary), VALUE, len);
569 rb_ary_unshare(ary);
570 ARY_SET_CAPA_FORCE(ary, len);
571 ARY_SET_PTR_FORCE(ary, ptr);
572 }
573
574 rb_gc_writebarrier_remember(ary);
575 }
576 ary_verify(ary);
577}
578
579void
581{
582 rb_ary_modify_check(ary);
583 rb_ary_cancel_sharing(ary);
584}
585
586static VALUE
587ary_ensure_room_for_push(VALUE ary, long add_len)
588{
589 long old_len = RARRAY_LEN(ary);
590 long new_len = old_len + add_len;
591 long capa;
592
593 if (old_len > ARY_MAX_SIZE - add_len) {
594 rb_raise(rb_eIndexError, "index %ld too big", new_len);
595 }
596 if (ARY_SHARED_P(ary)) {
597 if (new_len > ary_embed_capa(ary)) {
598 VALUE shared_root = ARY_SHARED_ROOT(ary);
599 if (ARY_SHARED_ROOT_OCCUPIED(shared_root)) {
600 if (ARY_HEAP_PTR(ary) - RARRAY_CONST_PTR(shared_root) + new_len <= RARRAY_LEN(shared_root)) {
601 rb_ary_modify_check(ary);
602
603 ary_verify(ary);
604 ary_verify(shared_root);
605 return shared_root;
606 }
607 else {
608 /* if array is shared, then it is likely it participate in push/shift pattern */
609 rb_ary_modify(ary);
610 capa = ARY_CAPA(ary);
611 if (new_len > capa - (capa >> 6)) {
612 ary_double_capa(ary, new_len);
613 }
614 ary_verify(ary);
615 return ary;
616 }
617 }
618 }
619 ary_verify(ary);
620 rb_ary_modify(ary);
621 }
622 else {
623 rb_ary_modify_check(ary);
624 }
625 capa = ARY_CAPA(ary);
626 if (new_len > capa) {
627 ary_double_capa(ary, new_len);
628 }
629
630 ary_verify(ary);
631 return ary;
632}
633
634/*
635 * call-seq:
636 * freeze -> self
637 *
638 * Freezes +self+ (if not already frozen); returns +self+:
639 *
640 * a = []
641 * a.frozen? # => false
642 * a.freeze
643 * a.frozen? # => true
644 *
645 * No further changes may be made to +self+;
646 * raises FrozenError if a change is attempted.
647 *
648 * Related: Kernel#frozen?.
649 */
650
651VALUE
653{
654 RUBY_ASSERT(RB_TYPE_P(ary, T_ARRAY));
655
656 if (OBJ_FROZEN(ary)) return ary;
657
658 if (!ARY_EMBED_P(ary) && !ARY_SHARED_P(ary) && !ARY_SHARED_ROOT_P(ary)) {
659 ary_shrink_capa(ary);
660 }
661
662 return rb_obj_freeze(ary);
663}
664
665/* This can be used to take a snapshot of an array (with
666 e.g. rb_ary_replace) and check later whether the array has been
667 modified from the snapshot. The snapshot is cheap, though if
668 something does modify the array it will pay the cost of copying
669 it. If Array#pop or Array#shift has been called, the array will
670 be still shared with the snapshot, but the array length will
671 differ. */
672VALUE
674{
675 if (!ARY_EMBED_P(ary1) && ARY_SHARED_P(ary1) &&
676 !ARY_EMBED_P(ary2) && ARY_SHARED_P(ary2) &&
677 ARY_SHARED_ROOT(ary1) == ARY_SHARED_ROOT(ary2) &&
678 ARY_HEAP_LEN(ary1) == ARY_HEAP_LEN(ary2)) {
679 return Qtrue;
680 }
681 return Qfalse;
682}
683
684static VALUE
685ary_alloc_embed(VALUE klass, long capa)
686{
687 size_t size = ary_embed_size(capa);
688 RUBY_ASSERT(rb_gc_size_allocatable_p(size));
689 NEWOBJ_OF(ary, struct RArray, klass,
690 T_ARRAY | RARRAY_EMBED_FLAG | (RGENGC_WB_PROTECTED_ARRAY ? FL_WB_PROTECTED : 0),
691 size, 0);
692 /* Created array is:
693 * FL_SET_EMBED((VALUE)ary);
694 * ARY_SET_EMBED_LEN((VALUE)ary, 0);
695 */
696 return (VALUE)ary;
697}
698
699static VALUE
700ary_alloc_heap(VALUE klass)
701{
702 NEWOBJ_OF(ary, struct RArray, klass,
704 sizeof(struct RArray), 0);
705
706 ary->as.heap.len = 0;
707 ary->as.heap.aux.capa = 0;
708 ary->as.heap.ptr = NULL;
709
710 return (VALUE)ary;
711}
712
713static VALUE
714empty_ary_alloc(VALUE klass)
715{
716 RUBY_DTRACE_CREATE_HOOK(ARRAY, 0);
717 return ary_alloc_embed(klass, 0);
718}
719
720static VALUE
721ary_new(VALUE klass, long capa)
722{
723 RUBY_ASSERT(ruby_thread_has_gvl_p());
724
725 VALUE ary;
726
727 if (capa < 0) {
728 rb_raise(rb_eArgError, "negative array size (or size too big)");
729 }
730 if (capa > ARY_MAX_SIZE) {
731 rb_raise(rb_eArgError, "array size too big");
732 }
733
734 RUBY_DTRACE_CREATE_HOOK(ARRAY, capa);
735
736 if (ary_embeddable_p(capa)) {
737 ary = ary_alloc_embed(klass, capa);
738 }
739 else {
740 ary = ary_alloc_heap(klass);
741 ARY_SET_CAPA(ary, capa);
742 RUBY_ASSERT(!ARY_EMBED_P(ary));
743
744 ARY_SET_PTR(ary, ary_heap_alloc_buffer(capa));
745 ARY_SET_HEAP_LEN(ary, 0);
746 }
747
748 return ary;
749}
750
751VALUE
753{
754 return ary_new(rb_cArray, capa);
755}
756
757VALUE
758rb_ary_new(void)
759{
760 return rb_ary_new_capa(0);
761}
762
763VALUE
764(rb_ary_new_from_args)(long n, ...)
765{
766 va_list ar;
767 VALUE ary;
768 long i;
769
770 ary = rb_ary_new2(n);
771
772 va_start(ar, n);
773 for (i=0; i<n; i++) {
774 ARY_SET(ary, i, va_arg(ar, VALUE));
775 }
776 va_end(ar);
777
778 ARY_SET_LEN(ary, n);
779 return ary;
780}
781
782VALUE
783rb_ary_tmp_new_from_values(VALUE klass, long n, const VALUE *elts)
784{
785 VALUE ary;
786
787 ary = ary_new(klass, n);
788 if (n > 0 && elts) {
789 ary_memcpy(ary, 0, n, elts);
790 ARY_SET_LEN(ary, n);
791 }
792
793 return ary;
794}
795
796VALUE
797rb_ary_new_from_values(long n, const VALUE *elts)
798{
799 return rb_ary_tmp_new_from_values(rb_cArray, n, elts);
800}
801
802static VALUE
803ec_ary_alloc_embed(rb_execution_context_t *ec, VALUE klass, long capa)
804{
805 size_t size = ary_embed_size(capa);
806 RUBY_ASSERT(rb_gc_size_allocatable_p(size));
807 NEWOBJ_OF(ary, struct RArray, klass,
808 T_ARRAY | RARRAY_EMBED_FLAG | (RGENGC_WB_PROTECTED_ARRAY ? FL_WB_PROTECTED : 0),
809 size, ec);
810 /* Created array is:
811 * FL_SET_EMBED((VALUE)ary);
812 * ARY_SET_EMBED_LEN((VALUE)ary, 0);
813 */
814 return (VALUE)ary;
815}
816
817static VALUE
818ec_ary_alloc_heap(rb_execution_context_t *ec, VALUE klass)
819{
820 NEWOBJ_OF(ary, struct RArray, klass,
822 sizeof(struct RArray), ec);
823
824 ary->as.heap.len = 0;
825 ary->as.heap.aux.capa = 0;
826 ary->as.heap.ptr = NULL;
827
828 return (VALUE)ary;
829}
830
831static VALUE
832ec_ary_new(rb_execution_context_t *ec, VALUE klass, long capa)
833{
834 VALUE ary;
835
836 if (capa < 0) {
837 rb_raise(rb_eArgError, "negative array size (or size too big)");
838 }
839 if (capa > ARY_MAX_SIZE) {
840 rb_raise(rb_eArgError, "array size too big");
841 }
842
843 RUBY_DTRACE_CREATE_HOOK(ARRAY, capa);
844
845 if (ary_embeddable_p(capa)) {
846 ary = ec_ary_alloc_embed(ec, klass, capa);
847 }
848 else {
849 ary = ec_ary_alloc_heap(ec, klass);
850 ARY_SET_CAPA(ary, capa);
851 RUBY_ASSERT(!ARY_EMBED_P(ary));
852
853 ARY_SET_PTR(ary, ary_heap_alloc_buffer(capa));
854 ARY_SET_HEAP_LEN(ary, 0);
855 }
856
857 return ary;
858}
859
860VALUE
861rb_ec_ary_new_from_values(rb_execution_context_t *ec, long n, const VALUE *elts)
862{
863 VALUE ary;
864
865 ary = ec_ary_new(ec, rb_cArray, n);
866 if (n > 0 && elts) {
867 ary_memcpy(ary, 0, n, elts);
868 ARY_SET_LEN(ary, n);
869 }
870
871 return ary;
872}
873
874VALUE
876{
877 VALUE ary = ary_new(0, capa);
878 return ary;
879}
880
881VALUE
882rb_ary_hidden_new_fill(long capa)
883{
885 ary_memfill(ary, 0, capa, Qnil);
886 ARY_SET_LEN(ary, capa);
887 return ary;
888}
889
890void
892{
893 if (ARY_OWNS_HEAP_P(ary)) {
894 if (USE_DEBUG_COUNTER &&
895 !ARY_SHARED_ROOT_P(ary) &&
896 ARY_HEAP_CAPA(ary) > RARRAY_LEN(ary)) {
897 RB_DEBUG_COUNTER_INC(obj_ary_extracapa);
898 }
899
900 RB_DEBUG_COUNTER_INC(obj_ary_ptr);
901 ary_heap_free(ary);
902 }
903 else {
904 RB_DEBUG_COUNTER_INC(obj_ary_embed);
905 }
906
907 if (ARY_SHARED_P(ary)) {
908 RB_DEBUG_COUNTER_INC(obj_ary_shared);
909 }
910 if (ARY_SHARED_ROOT_P(ary) && ARY_SHARED_ROOT_OCCUPIED(ary)) {
911 RB_DEBUG_COUNTER_INC(obj_ary_shared_root_occupied);
912 }
913}
914
915static VALUE fake_ary_flags;
916
917static VALUE
918init_fake_ary_flags(void)
919{
920 struct RArray fake_ary = {0};
921 fake_ary.basic.flags = T_ARRAY;
922 VALUE ary = (VALUE)&fake_ary;
923 rb_ary_freeze(ary);
924 return fake_ary.basic.flags;
925}
926
927VALUE
928rb_setup_fake_ary(struct RArray *fake_ary, const VALUE *list, long len)
929{
930 fake_ary->basic.flags = fake_ary_flags;
931 RBASIC_CLEAR_CLASS((VALUE)fake_ary);
932
933 // bypass frozen checks
934 fake_ary->as.heap.ptr = list;
935 fake_ary->as.heap.len = len;
936 fake_ary->as.heap.aux.capa = len;
937 return (VALUE)fake_ary;
938}
939
940size_t
941rb_ary_memsize(VALUE ary)
942{
943 if (ARY_OWNS_HEAP_P(ary)) {
944 return ARY_CAPA(ary) * sizeof(VALUE);
945 }
946 else {
947 return 0;
948 }
949}
950
951static VALUE
952ary_make_shared(VALUE ary)
953{
954 ary_verify(ary);
955
956 if (ARY_SHARED_P(ary)) {
957 return ARY_SHARED_ROOT(ary);
958 }
959 else if (ARY_SHARED_ROOT_P(ary)) {
960 return ary;
961 }
962 else if (OBJ_FROZEN(ary)) {
963 return ary;
964 }
965 else {
966 long capa = ARY_CAPA(ary);
967 long len = RARRAY_LEN(ary);
968
969 /* Shared roots cannot be embedded because the reference count
970 * (refcnt) is stored in as.heap.aux.capa. */
971 VALUE shared = ary_alloc_heap(0);
972 FL_SET_SHARED_ROOT(shared);
973
974 if (ARY_EMBED_P(ary)) {
975 VALUE *ptr = ary_heap_alloc_buffer(capa);
976 ARY_SET_PTR(shared, ptr);
977 ary_memcpy(shared, 0, len, RARRAY_CONST_PTR(ary));
978
979 FL_UNSET_EMBED(ary);
980 ARY_SET_HEAP_LEN(ary, len);
981 ARY_SET_PTR(ary, ptr);
982 }
983 else {
984 ARY_SET_PTR(shared, RARRAY_CONST_PTR(ary));
985 }
986
987 ARY_SET_LEN(shared, capa);
988 ary_mem_clear(shared, len, capa - len);
989 rb_ary_set_shared(ary, shared);
990
991 ary_verify(shared);
992 ary_verify(ary);
993
994 return shared;
995 }
996}
997
998static VALUE
999ary_make_substitution(VALUE ary)
1000{
1001 long len = RARRAY_LEN(ary);
1002
1003 if (ary_embeddable_p(len)) {
1004 VALUE subst = rb_ary_new_capa(len);
1005 RUBY_ASSERT(ARY_EMBED_P(subst));
1006
1007 ary_memcpy(subst, 0, len, RARRAY_CONST_PTR(ary));
1008 ARY_SET_EMBED_LEN(subst, len);
1009 return subst;
1010 }
1011 else {
1012 return rb_ary_increment_share(ary_make_shared(ary));
1013 }
1014}
1015
1016VALUE
1017rb_assoc_new(VALUE car, VALUE cdr)
1018{
1019 return rb_ary_new3(2, car, cdr);
1020}
1021
1022VALUE
1023rb_to_array_type(VALUE ary)
1024{
1025 return rb_convert_type_with_id(ary, T_ARRAY, "Array", idTo_ary);
1026}
1027#define to_ary rb_to_array_type
1028
1029VALUE
1031{
1032 return rb_check_convert_type_with_id(ary, T_ARRAY, "Array", idTo_ary);
1033}
1034
1035VALUE
1036rb_check_to_array(VALUE ary)
1037{
1038 return rb_check_convert_type_with_id(ary, T_ARRAY, "Array", idTo_a);
1039}
1040
1041VALUE
1042rb_to_array(VALUE ary)
1043{
1044 return rb_convert_type_with_id(ary, T_ARRAY, "Array", idTo_a);
1045}
1046
1047/*
1048 * call-seq:
1049 * Array.try_convert(object) -> object, new_array, or nil
1050 *
1051 * Attempts to return an array, based on the given +object+.
1052 *
1053 * If +object+ is an array, returns +object+.
1054 *
1055 * Otherwise if +object+ responds to <tt>:to_ary</tt>.
1056 * calls <tt>object.to_ary</tt>:
1057 * if the return value is an array or +nil+, returns that value;
1058 * if not, raises TypeError.
1059 *
1060 * Otherwise returns +nil+.
1061 *
1062 * Related: see {Methods for Creating an Array}[rdoc-ref:Array@Methods+for+Creating+an+Array].
1063 */
1064
1065static VALUE
1066rb_ary_s_try_convert(VALUE dummy, VALUE ary)
1067{
1068 return rb_check_array_type(ary);
1069}
1070
1071/* :nodoc: */
1072static VALUE
1073rb_ary_s_new(int argc, VALUE *argv, VALUE klass)
1074{
1075 VALUE ary;
1076
1077 if (klass == rb_cArray) {
1078 long size = 0;
1079 if (argc > 0 && FIXNUM_P(argv[0])) {
1080 size = FIX2LONG(argv[0]);
1081 if (size < 0) size = 0;
1082 }
1083
1084 ary = ary_new(klass, size);
1085
1086 rb_obj_call_init_kw(ary, argc, argv, RB_PASS_CALLED_KEYWORDS);
1087 }
1088 else {
1089 ary = rb_class_new_instance_pass_kw(argc, argv, klass);
1090 }
1091
1092 return ary;
1093}
1094
1095/*
1096 * call-seq:
1097 * Array.new -> new_empty_array
1098 * Array.new(array) -> new_array
1099 * Array.new(size, default_value = nil) -> new_array
1100 * Array.new(size = 0) {|index| ... } -> new_array
1101 *
1102 * Returns a new array.
1103 *
1104 * With no block and no argument given, returns a new empty array:
1105 *
1106 * Array.new # => []
1107 *
1108 * With no block and array argument given, returns a new array with the same elements:
1109 *
1110 * Array.new([:foo, 'bar', 2]) # => [:foo, "bar", 2]
1111 *
1112 * With no block and integer argument given, returns a new array containing
1113 * that many instances of the given +default_value+:
1114 *
1115 * Array.new(0) # => []
1116 * Array.new(3) # => [nil, nil, nil]
1117 * Array.new(2, 3) # => [3, 3]
1118 *
1119 * With a block given, returns an array of the given +size+;
1120 * calls the block with each +index+ in the range <tt>(0...size)</tt>;
1121 * the element at that +index+ in the returned array is the blocks return value:
1122 *
1123 * Array.new(3) {|index| "Element #{index}" } # => ["Element 0", "Element 1", "Element 2"]
1124 *
1125 * A common pitfall for new Rubyists is providing an expression as +default_value+:
1126 *
1127 * array = Array.new(2, {})
1128 * array # => [{}, {}]
1129 * array[0][:a] = 1
1130 * array # => [{a: 1}, {a: 1}], as array[0] and array[1] are same object
1131 *
1132 * If you want the elements of the array to be distinct, you should pass a block:
1133 *
1134 * array = Array.new(2) { {} }
1135 * array # => [{}, {}]
1136 * array[0][:a] = 1
1137 * array # => [{a: 1}, {}], as array[0] and array[1] are different objects
1138 *
1139 * Raises TypeError if the first argument is not either an array
1140 * or an {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects]).
1141 * Raises ArgumentError if the first argument is a negative integer.
1142 *
1143 * Related: see {Methods for Creating an Array}[rdoc-ref:Array@Methods+for+Creating+an+Array].
1144 */
1145
1146static VALUE
1147rb_ary_initialize(int argc, VALUE *argv, VALUE ary)
1148{
1149 long len;
1150 VALUE size, val;
1151
1152 rb_ary_modify(ary);
1153 if (argc == 0) {
1154 rb_ary_reset(ary);
1155 RUBY_ASSERT(ARY_EMBED_P(ary));
1156 RUBY_ASSERT(ARY_EMBED_LEN(ary) == 0);
1157 if (rb_block_given_p()) {
1158 rb_warning("given block not used");
1159 }
1160 return ary;
1161 }
1162 rb_scan_args(argc, argv, "02", &size, &val);
1163 if (argc == 1 && !FIXNUM_P(size)) {
1164 val = rb_check_array_type(size);
1165 if (!NIL_P(val)) {
1166 rb_ary_replace(ary, val);
1167 return ary;
1168 }
1169 }
1170
1171 len = NUM2LONG(size);
1172 /* NUM2LONG() may call size.to_int, ary can be frozen, modified, etc */
1173 if (len < 0) {
1174 rb_raise(rb_eArgError, "negative array size");
1175 }
1176 if (len > ARY_MAX_SIZE) {
1177 rb_raise(rb_eArgError, "array size too big");
1178 }
1179 /* recheck after argument conversion */
1180 rb_ary_modify(ary);
1181 ary_resize_capa(ary, len);
1182 if (rb_block_given_p()) {
1183 long i;
1184
1185 if (argc == 2) {
1186 rb_warn("block supersedes default value argument");
1187 }
1188 for (i=0; i<len; i++) {
1189 rb_ary_store(ary, i, rb_yield(LONG2NUM(i)));
1190 ARY_SET_LEN(ary, i + 1);
1191 }
1192 }
1193 else {
1194 ary_memfill(ary, 0, len, val);
1195 ARY_SET_LEN(ary, len);
1196 }
1197 return ary;
1198}
1199
1200/*
1201 * Returns a new array, populated with the given objects:
1202 *
1203 * Array[1, 'a', /^A/] # => [1, "a", /^A/]
1204 * Array[] # => []
1205 * Array.[](1, 'a', /^A/) # => [1, "a", /^A/]
1206 *
1207 * Related: see {Methods for Creating an Array}[rdoc-ref:Array@Methods+for+Creating+an+Array].
1208 */
1209
1210static VALUE
1211rb_ary_s_create(int argc, VALUE *argv, VALUE klass)
1212{
1213 VALUE ary = ary_new(klass, argc);
1214 if (argc > 0 && argv) {
1215 ary_memcpy(ary, 0, argc, argv);
1216 ARY_SET_LEN(ary, argc);
1217 }
1218
1219 return ary;
1220}
1221
1222void
1223rb_ary_store(VALUE ary, long idx, VALUE val)
1224{
1225 long len = RARRAY_LEN(ary);
1226
1227 if (idx < 0) {
1228 idx += len;
1229 if (idx < 0) {
1230 rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld",
1231 idx - len, -len);
1232 }
1233 }
1234 else if (idx >= ARY_MAX_SIZE) {
1235 rb_raise(rb_eIndexError, "index %ld too big", idx);
1236 }
1237
1238 rb_ary_modify(ary);
1239 if (idx >= ARY_CAPA(ary)) {
1240 ary_double_capa(ary, idx);
1241 }
1242 if (idx > len) {
1243 ary_mem_clear(ary, len, idx - len + 1);
1244 }
1245
1246 if (idx >= len) {
1247 ARY_SET_LEN(ary, idx + 1);
1248 }
1249 ARY_SET(ary, idx, val);
1250}
1251
1252static VALUE
1253ary_make_partial(VALUE ary, VALUE klass, long offset, long len)
1254{
1255 RUBY_ASSERT(offset >= 0);
1256 RUBY_ASSERT(len >= 0);
1257 RUBY_ASSERT(offset+len <= RARRAY_LEN(ary));
1258
1259 VALUE result = ary_alloc_heap(klass);
1260 size_t embed_capa = ary_embed_capa(result);
1261 if ((size_t)len <= embed_capa) {
1262 FL_SET_EMBED(result);
1263 ary_memcpy(result, 0, len, RARRAY_CONST_PTR(ary) + offset);
1264 ARY_SET_EMBED_LEN(result, len);
1265 }
1266 else {
1267 VALUE shared = ary_make_shared(ary);
1268
1269 /* The ary_make_shared call may allocate, which can trigger a GC
1270 * compaction. This can cause the array to be embedded because it has
1271 * a length of 0. */
1272 FL_UNSET_EMBED(result);
1273
1274 ARY_SET_PTR(result, RARRAY_CONST_PTR(ary));
1275 ARY_SET_LEN(result, RARRAY_LEN(ary));
1276 rb_ary_set_shared(result, shared);
1277
1278 ARY_INCREASE_PTR(result, offset);
1279 ARY_SET_LEN(result, len);
1280
1281 ary_verify(shared);
1282 }
1283
1284 ary_verify(result);
1285 return result;
1286}
1287
1288static VALUE
1289ary_make_partial_step(VALUE ary, VALUE klass, long offset, long len, long step)
1290{
1291 RUBY_ASSERT(offset >= 0);
1292 RUBY_ASSERT(len >= 0);
1293 RUBY_ASSERT(offset+len <= RARRAY_LEN(ary));
1294 RUBY_ASSERT(step != 0);
1295
1296 const long orig_len = len;
1297
1298 if (step > 0 && step >= len) {
1299 VALUE result = ary_new(klass, 1);
1300 VALUE *ptr = (VALUE *)ARY_EMBED_PTR(result);
1301 const VALUE *values = RARRAY_CONST_PTR(ary);
1302
1303 RB_OBJ_WRITE(result, ptr, values[offset]);
1304 ARY_SET_EMBED_LEN(result, 1);
1305 return result;
1306 }
1307 else if (step < 0 && step < -len) {
1308 step = -len;
1309 }
1310
1311 long ustep = (step < 0) ? -step : step;
1312 len = roomof(len, ustep);
1313
1314 long i;
1315 long j = offset + ((step > 0) ? 0 : (orig_len - 1));
1316
1317 VALUE result = ary_new(klass, len);
1318 if (ARY_EMBED_P(result)) {
1319 VALUE *ptr = (VALUE *)ARY_EMBED_PTR(result);
1320 const VALUE *values = RARRAY_CONST_PTR(ary);
1321
1322 for (i = 0; i < len; ++i) {
1323 RB_OBJ_WRITE(result, ptr+i, values[j]);
1324 j += step;
1325 }
1326 ARY_SET_EMBED_LEN(result, len);
1327 }
1328 else {
1329 const VALUE *values = RARRAY_CONST_PTR(ary);
1330
1331 RARRAY_PTR_USE(result, ptr, {
1332 for (i = 0; i < len; ++i) {
1333 RB_OBJ_WRITE(result, ptr+i, values[j]);
1334 j += step;
1335 }
1336 });
1337 ARY_SET_LEN(result, len);
1338 }
1339
1340 return result;
1341}
1342
1343static VALUE
1344ary_make_shared_copy(VALUE ary)
1345{
1346 return ary_make_partial(ary, rb_cArray, 0, RARRAY_LEN(ary));
1347}
1348
1349enum ary_take_pos_flags
1350{
1351 ARY_TAKE_FIRST = 0,
1352 ARY_TAKE_LAST = 1
1353};
1354
1355static VALUE
1356ary_take_first_or_last_n(VALUE ary, long n, enum ary_take_pos_flags last)
1357{
1358 long len = RARRAY_LEN(ary);
1359 long offset = 0;
1360
1361 if (n > len) {
1362 n = len;
1363 }
1364 else if (n < 0) {
1365 rb_raise(rb_eArgError, "negative array size");
1366 }
1367 if (last) {
1368 offset = len - n;
1369 }
1370 return ary_make_partial(ary, rb_cArray, offset, n);
1371}
1372
1373static VALUE
1374ary_take_first_or_last(int argc, const VALUE *argv, VALUE ary, enum ary_take_pos_flags last)
1375{
1376 argc = rb_check_arity(argc, 0, 1);
1377 /* the case optional argument is omitted should be handled in
1378 * callers of this function. if another arity case is added,
1379 * this arity check needs to rewrite. */
1380 RUBY_ASSERT_ALWAYS(argc == 1);
1381 return ary_take_first_or_last_n(ary, NUM2LONG(argv[0]), last);
1382}
1383
1384/*
1385 * call-seq:
1386 * self << object -> self
1387 *
1388 * Appends +object+ as the last element in +self+; returns +self+:
1389 *
1390 * [:foo, 'bar', 2] << :baz # => [:foo, "bar", 2, :baz]
1391 *
1392 * Appends +object+ as a single element, even if it is another array:
1393 *
1394 * [:foo, 'bar', 2] << [3, 4] # => [:foo, "bar", 2, [3, 4]]
1395 *
1396 * Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
1397 */
1398
1399VALUE
1400rb_ary_push(VALUE ary, VALUE item)
1401{
1402 long idx = RARRAY_LEN((ary_verify(ary), ary));
1403 VALUE target_ary = ary_ensure_room_for_push(ary, 1);
1404 RARRAY_PTR_USE(ary, ptr, {
1405 RB_OBJ_WRITE(target_ary, &ptr[idx], item);
1406 });
1407 ARY_SET_LEN(ary, idx + 1);
1408 ary_verify(ary);
1409 return ary;
1410}
1411
1412VALUE
1413rb_ary_cat(VALUE ary, const VALUE *argv, long len)
1414{
1415 long oldlen = RARRAY_LEN(ary);
1416 VALUE target_ary = ary_ensure_room_for_push(ary, len);
1417 ary_memcpy0(ary, oldlen, len, argv, target_ary);
1418 ARY_SET_LEN(ary, oldlen + len);
1419 return ary;
1420}
1421
1422/*
1423 * call-seq:
1424 * push(*objects) -> self
1425 * append(*objects) -> self
1426 *
1427 * Appends each argument in +objects+ to +self+; returns +self+:
1428 *
1429 * a = [:foo, 'bar', 2] # => [:foo, "bar", 2]
1430 * a.push(:baz, :bat) # => [:foo, "bar", 2, :baz, :bat]
1431 *
1432 * Appends each argument as a single element, even if it is another array:
1433 *
1434 * a = [:foo, 'bar', 2] # => [:foo, "bar", 2]
1435 a.push([:baz, :bat], [:bam, :bad]) # => [:foo, "bar", 2, [:baz, :bat], [:bam, :bad]]
1436 *
1437 * Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
1438 */
1439
1440static VALUE
1441rb_ary_push_m(int argc, VALUE *argv, VALUE ary)
1442{
1443 return rb_ary_cat(ary, argv, argc);
1444}
1445
1446VALUE
1447rb_ary_pop(VALUE ary)
1448{
1449 long n;
1450 rb_ary_modify_check(ary);
1451 n = RARRAY_LEN(ary);
1452 if (n == 0) return Qnil;
1453 if (ARY_OWNS_HEAP_P(ary) &&
1454 n * 3 < ARY_CAPA(ary) &&
1455 ARY_CAPA(ary) > ARY_DEFAULT_SIZE)
1456 {
1457 ary_resize_capa(ary, n * 2);
1458 }
1459
1460 VALUE obj = RARRAY_AREF(ary, n - 1);
1461
1462 ARY_SET_LEN(ary, n - 1);
1463 ary_verify(ary);
1464 return obj;
1465}
1466
1467/*
1468 * call-seq:
1469 * pop -> object or nil
1470 * pop(count) -> new_array
1471 *
1472 * Removes and returns trailing elements of +self+.
1473 *
1474 * With no argument given, removes and returns the last element, if available;
1475 * otherwise returns +nil+:
1476 *
1477 * a = [:foo, 'bar', 2]
1478 * a.pop # => 2
1479 * a # => [:foo, "bar"]
1480 * [].pop # => nil
1481 *
1482 * With non-negative integer argument +count+ given,
1483 * returns a new array containing the trailing +count+ elements of +self+, as available:
1484 *
1485 * a = [:foo, 'bar', 2]
1486 * a.pop(2) # => ["bar", 2]
1487 * a # => [:foo]
1488 *
1489 * a = [:foo, 'bar', 2]
1490 * a.pop(50) # => [:foo, "bar", 2]
1491 * a # => []
1492 *
1493 * Related: Array#push;
1494 * see also {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
1495 */
1496
1497static VALUE
1498rb_ary_pop_m(int argc, VALUE *argv, VALUE ary)
1499{
1500 VALUE result;
1501
1502 if (argc == 0) {
1503 return rb_ary_pop(ary);
1504 }
1505
1506 rb_ary_modify_check(ary);
1507 result = ary_take_first_or_last(argc, argv, ary, ARY_TAKE_LAST);
1508 ARY_INCREASE_LEN(ary, -RARRAY_LEN(result));
1509 ary_verify(ary);
1510 return result;
1511}
1512
1513VALUE
1515{
1516 VALUE top;
1517 long len = RARRAY_LEN(ary);
1518
1519 if (len == 0) {
1520 rb_ary_modify_check(ary);
1521 return Qnil;
1522 }
1523
1524 top = RARRAY_AREF(ary, 0);
1525
1526 rb_ary_behead(ary, 1);
1527
1528 return top;
1529}
1530
1531/*
1532 * call-seq:
1533 * shift -> object or nil
1534 * shift(count) -> new_array or nil
1535 *
1536 * Removes and returns leading elements from +self+.
1537 *
1538 * With no argument, removes and returns one element, if available,
1539 * or +nil+ otherwise:
1540 *
1541 * a = [0, 1, 2, 3]
1542 * a.shift # => 0
1543 * a # => [1, 2, 3]
1544 * [].shift # => nil
1545 *
1546 * With non-negative numeric argument +count+ given,
1547 * removes and returns the first +count+ elements:
1548 *
1549 * a = [0, 1, 2, 3]
1550 * a.shift(2) # => [0, 1]
1551 * a # => [2, 3]
1552 * a.shift(1.1) # => [2]
1553 * a # => [3]
1554 * a.shift(0) # => []
1555 * a # => [3]
1556 *
1557 * If +count+ is large,
1558 * removes and returns all elements:
1559 *
1560 * a = [0, 1, 2, 3]
1561 * a.shift(50) # => [0, 1, 2, 3]
1562 * a # => []
1563 *
1564 * If +self+ is empty, returns a new empty array.
1565 *
1566 * Related: see {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
1567 */
1568
1569static VALUE
1570rb_ary_shift_m(int argc, VALUE *argv, VALUE ary)
1571{
1572 VALUE result;
1573 long n;
1574
1575 if (argc == 0) {
1576 return rb_ary_shift(ary);
1577 }
1578
1579 rb_ary_modify_check(ary);
1580 result = ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
1581 n = RARRAY_LEN(result);
1582 rb_ary_behead(ary,n);
1583
1584 return result;
1585}
1586
1587VALUE
1588rb_ary_behead(VALUE ary, long n)
1589{
1590 if (n <= 0) {
1591 return ary;
1592 }
1593
1594 rb_ary_modify_check(ary);
1595
1596 if (!ARY_SHARED_P(ary)) {
1597 if (ARY_EMBED_P(ary) || RARRAY_LEN(ary) < ARY_DEFAULT_SIZE) {
1598 RARRAY_PTR_USE(ary, ptr, {
1599 MEMMOVE(ptr, ptr + n, VALUE, RARRAY_LEN(ary) - n);
1600 }); /* WB: no new reference */
1601 ARY_INCREASE_LEN(ary, -n);
1602 ary_verify(ary);
1603 return ary;
1604 }
1605
1606 ary_mem_clear(ary, 0, n);
1607 ary_make_shared(ary);
1608 }
1609 else if (ARY_SHARED_ROOT_OCCUPIED(ARY_SHARED_ROOT(ary))) {
1610 ary_mem_clear(ary, 0, n);
1611 }
1612
1613 ARY_INCREASE_PTR(ary, n);
1614 ARY_INCREASE_LEN(ary, -n);
1615 ary_verify(ary);
1616
1617 return ary;
1618}
1619
1620static VALUE
1621make_room_for_unshift(VALUE ary, const VALUE *head, VALUE *sharedp, int argc, long capa, long len)
1622{
1623 if (head - sharedp < argc) {
1624 long room = capa - len - argc;
1625
1626 room -= room >> 4;
1627 MEMMOVE((VALUE *)sharedp + argc + room, head, VALUE, len);
1628 head = sharedp + argc + room;
1629 }
1630 ARY_SET_PTR(ary, head - argc);
1631 RUBY_ASSERT(ARY_SHARED_ROOT_OCCUPIED(ARY_SHARED_ROOT(ary)));
1632
1633 ary_verify(ary);
1634 return ARY_SHARED_ROOT(ary);
1635}
1636
1637static VALUE
1638ary_modify_for_unshift(VALUE ary, int argc)
1639{
1640 long len = RARRAY_LEN(ary);
1641 long new_len = len + argc;
1642 long capa;
1643 const VALUE *head, *sharedp;
1644
1645 rb_ary_modify(ary);
1646 capa = ARY_CAPA(ary);
1647 if (capa - (capa >> 6) <= new_len) {
1648 ary_double_capa(ary, new_len);
1649 }
1650
1651 /* use shared array for big "queues" */
1652 if (new_len > ARY_DEFAULT_SIZE * 4 && !ARY_EMBED_P(ary)) {
1653 ary_verify(ary);
1654
1655 /* make a room for unshifted items */
1656 capa = ARY_CAPA(ary);
1657 ary_make_shared(ary);
1658
1659 head = sharedp = RARRAY_CONST_PTR(ary);
1660 return make_room_for_unshift(ary, head, (void *)sharedp, argc, capa, len);
1661 }
1662 else {
1663 /* sliding items */
1664 RARRAY_PTR_USE(ary, ptr, {
1665 MEMMOVE(ptr + argc, ptr, VALUE, len);
1666 });
1667
1668 ary_verify(ary);
1669 return ary;
1670 }
1671}
1672
1673static VALUE
1674ary_ensure_room_for_unshift(VALUE ary, int argc)
1675{
1676 long len = RARRAY_LEN(ary);
1677 long new_len = len + argc;
1678
1679 if (len > ARY_MAX_SIZE - argc) {
1680 rb_raise(rb_eIndexError, "index %ld too big", new_len);
1681 }
1682 else if (! ARY_SHARED_P(ary)) {
1683 return ary_modify_for_unshift(ary, argc);
1684 }
1685 else {
1686 VALUE shared_root = ARY_SHARED_ROOT(ary);
1687 long capa = RARRAY_LEN(shared_root);
1688
1689 if (! ARY_SHARED_ROOT_OCCUPIED(shared_root)) {
1690 return ary_modify_for_unshift(ary, argc);
1691 }
1692 else if (new_len > capa) {
1693 return ary_modify_for_unshift(ary, argc);
1694 }
1695 else {
1696 const VALUE * head = RARRAY_CONST_PTR(ary);
1697 void *sharedp = (void *)RARRAY_CONST_PTR(shared_root);
1698
1699 rb_ary_modify_check(ary);
1700 return make_room_for_unshift(ary, head, sharedp, argc, capa, len);
1701 }
1702 }
1703}
1704
1705/*
1706 * call-seq:
1707 * unshift(*objects) -> self
1708 * prepend(*objects) -> self
1709 *
1710 * Prepends the given +objects+ to +self+:
1711 *
1712 * a = [:foo, 'bar', 2]
1713 * a.unshift(:bam, :bat) # => [:bam, :bat, :foo, "bar", 2]
1714 *
1715 * Related: Array#shift;
1716 * see also {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
1717 */
1718
1719VALUE
1720rb_ary_unshift_m(int argc, VALUE *argv, VALUE ary)
1721{
1722 long len = RARRAY_LEN(ary);
1723 VALUE target_ary;
1724
1725 if (argc == 0) {
1726 rb_ary_modify_check(ary);
1727 return ary;
1728 }
1729
1730 target_ary = ary_ensure_room_for_unshift(ary, argc);
1731 ary_memcpy0(ary, 0, argc, argv, target_ary);
1732 ARY_SET_LEN(ary, len + argc);
1733 return ary;
1734}
1735
1736VALUE
1737rb_ary_unshift(VALUE ary, VALUE item)
1738{
1739 return rb_ary_unshift_m(1, &item, ary);
1740}
1741
1742/* faster version - use this if you don't need to treat negative offset */
1743static inline VALUE
1744rb_ary_elt(VALUE ary, long offset)
1745{
1746 long len = RARRAY_LEN(ary);
1747 if (len == 0) return Qnil;
1748 if (offset < 0 || len <= offset) {
1749 return Qnil;
1750 }
1751 return RARRAY_AREF(ary, offset);
1752}
1753
1754VALUE
1755rb_ary_entry(VALUE ary, long offset)
1756{
1757 return rb_ary_entry_internal(ary, offset);
1758}
1759
1760VALUE
1761rb_ary_subseq_step(VALUE ary, long beg, long len, long step)
1762{
1763 VALUE klass;
1764 long alen = RARRAY_LEN(ary);
1765
1766 if (beg > alen) return Qnil;
1767 if (beg < 0 || len < 0) return Qnil;
1768
1769 if (alen < len || alen < beg + len) {
1770 len = alen - beg;
1771 }
1772 klass = rb_cArray;
1773 if (len == 0) return ary_new(klass, 0);
1774 if (step == 0)
1775 rb_raise(rb_eArgError, "slice step cannot be zero");
1776 if (step == 1)
1777 return ary_make_partial(ary, klass, beg, len);
1778 else
1779 return ary_make_partial_step(ary, klass, beg, len, step);
1780}
1781
1782VALUE
1783rb_ary_subseq(VALUE ary, long beg, long len)
1784{
1785 return rb_ary_subseq_step(ary, beg, len, 1);
1786}
1787
1788static VALUE rb_ary_aref2(VALUE ary, VALUE b, VALUE e);
1789
1790/*
1791 * call-seq:
1792 * self[index] -> object or nil
1793 * self[start, length] -> object or nil
1794 * self[range] -> object or nil
1795 * self[aseq] -> object or nil
1796 * slice(index) -> object or nil
1797 * slice(start, length) -> object or nil
1798 * slice(range) -> object or nil
1799 * slice(aseq) -> object or nil
1800 *
1801 * Returns elements from +self+; does not modify +self+.
1802 *
1803 * In brief:
1804 *
1805 * a = [:foo, 'bar', 2]
1806 *
1807 * # Single argument index: returns one element.
1808 * a[0] # => :foo # Zero-based index.
1809 * a[-1] # => 2 # Negative index counts backwards from end.
1810 *
1811 * # Arguments start and length: returns an array.
1812 * a[1, 2] # => ["bar", 2]
1813 * a[-2, 2] # => ["bar", 2] # Negative start counts backwards from end.
1814 *
1815 * # Single argument range: returns an array.
1816 * a[0..1] # => [:foo, "bar"]
1817 * a[0..-2] # => [:foo, "bar"] # Negative range-begin counts backwards from end.
1818 * a[-2..2] # => ["bar", 2] # Negative range-end counts backwards from end.
1819 *
1820 * When a single integer argument +index+ is given, returns the element at offset +index+:
1821 *
1822 * a = [:foo, 'bar', 2]
1823 * a[0] # => :foo
1824 * a[2] # => 2
1825 * a # => [:foo, "bar", 2]
1826 *
1827 * If +index+ is negative, counts backwards from the end of +self+:
1828 *
1829 * a = [:foo, 'bar', 2]
1830 * a[-1] # => 2
1831 * a[-2] # => "bar"
1832 *
1833 * If +index+ is out of range, returns +nil+.
1834 *
1835 * When two Integer arguments +start+ and +length+ are given,
1836 * returns a new array of size +length+ containing successive elements beginning at offset +start+:
1837 *
1838 * a = [:foo, 'bar', 2]
1839 * a[0, 2] # => [:foo, "bar"]
1840 * a[1, 2] # => ["bar", 2]
1841 *
1842 * If <tt>start + length</tt> is greater than <tt>self.length</tt>,
1843 * returns all elements from offset +start+ to the end:
1844 *
1845 * a = [:foo, 'bar', 2]
1846 * a[0, 4] # => [:foo, "bar", 2]
1847 * a[1, 3] # => ["bar", 2]
1848 * a[2, 2] # => [2]
1849 *
1850 * If <tt>start == self.size</tt> and <tt>length >= 0</tt>,
1851 * returns a new empty array.
1852 *
1853 * If +length+ is negative, returns +nil+.
1854 *
1855 * When a single Range argument +range+ is given,
1856 * treats <tt>range.min</tt> as +start+ above
1857 * and <tt>range.size</tt> as +length+ above:
1858 *
1859 * a = [:foo, 'bar', 2]
1860 * a[0..1] # => [:foo, "bar"]
1861 * a[1..2] # => ["bar", 2]
1862 *
1863 * Special case: If <tt>range.start == a.size</tt>, returns a new empty array.
1864 *
1865 * If <tt>range.end</tt> is negative, calculates the end index from the end:
1866 *
1867 * a = [:foo, 'bar', 2]
1868 * a[0..-1] # => [:foo, "bar", 2]
1869 * a[0..-2] # => [:foo, "bar"]
1870 * a[0..-3] # => [:foo]
1871 *
1872 * If <tt>range.start</tt> is negative, calculates the start index from the end:
1873 *
1874 * a = [:foo, 'bar', 2]
1875 * a[-1..2] # => [2]
1876 * a[-2..2] # => ["bar", 2]
1877 * a[-3..2] # => [:foo, "bar", 2]
1878 *
1879 * If <tt>range.start</tt> is larger than the array size, returns +nil+.
1880 *
1881 * a = [:foo, 'bar', 2]
1882 * a[4..1] # => nil
1883 * a[4..0] # => nil
1884 * a[4..-1] # => nil
1885 *
1886 * When a single Enumerator::ArithmeticSequence argument +aseq+ is given,
1887 * returns an array of elements corresponding to the indexes produced by
1888 * the sequence.
1889 *
1890 * a = ['--', 'data1', '--', 'data2', '--', 'data3']
1891 * a[(1..).step(2)] # => ["data1", "data2", "data3"]
1892 *
1893 * Unlike slicing with range, if the start or the end of the arithmetic sequence
1894 * is larger than array size, throws RangeError.
1895 *
1896 * a = ['--', 'data1', '--', 'data2', '--', 'data3']
1897 * a[(1..11).step(2)]
1898 * # RangeError (((1..11).step(2)) out of range)
1899 * a[(7..).step(2)]
1900 * # RangeError (((7..).step(2)) out of range)
1901 *
1902 * If given a single argument, and its type is not one of the listed, tries to
1903 * convert it to Integer, and raises if it is impossible:
1904 *
1905 * a = [:foo, 'bar', 2]
1906 * # Raises TypeError (no implicit conversion of Symbol into Integer):
1907 * a[:foo]
1908 *
1909 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
1910 */
1911
1912VALUE
1913rb_ary_aref(int argc, const VALUE *argv, VALUE ary)
1914{
1915 rb_check_arity(argc, 1, 2);
1916 if (argc == 2) {
1917 return rb_ary_aref2(ary, argv[0], argv[1]);
1918 }
1919 return rb_ary_aref1(ary, argv[0]);
1920}
1921
1922static VALUE
1923rb_ary_aref2(VALUE ary, VALUE b, VALUE e)
1924{
1925 long beg = NUM2LONG(b);
1926 long len = NUM2LONG(e);
1927 if (beg < 0) {
1928 beg += RARRAY_LEN(ary);
1929 }
1930 return rb_ary_subseq(ary, beg, len);
1931}
1932
1933VALUE
1934rb_ary_aref1(VALUE ary, VALUE arg)
1935{
1936 long beg, len, step;
1937
1938 /* special case - speeding up */
1939 if (FIXNUM_P(arg)) {
1940 return rb_ary_entry(ary, FIX2LONG(arg));
1941 }
1942 /* check if idx is Range or ArithmeticSequence */
1943 switch (rb_arithmetic_sequence_beg_len_step(arg, &beg, &len, &step, RARRAY_LEN(ary), 0)) {
1944 case Qfalse:
1945 break;
1946 case Qnil:
1947 return Qnil;
1948 default:
1949 return rb_ary_subseq_step(ary, beg, len, step);
1950 }
1951
1952 return rb_ary_entry(ary, NUM2LONG(arg));
1953}
1954
1955/*
1956 * call-seq:
1957 * at(index) -> object or nil
1958 *
1959 * Returns the element of +self+ specified by the given +index+
1960 * or +nil+ if there is no such element;
1961 * +index+ must be an
1962 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
1963 *
1964 * For non-negative +index+, returns the element of +self+ at offset +index+:
1965 *
1966 * a = [:foo, 'bar', 2]
1967 * a.at(0) # => :foo
1968 * a.at(2) # => 2
1969 * a.at(2.0) # => 2
1970 *
1971 * For negative +index+, counts backwards from the end of +self+:
1972 *
1973 * a.at(-2) # => "bar"
1974 *
1975 * Related: Array#[];
1976 * see also {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
1977 */
1978
1979VALUE
1980rb_ary_at(VALUE ary, VALUE pos)
1981{
1982 return rb_ary_entry(ary, NUM2LONG(pos));
1983}
1984
1985#if 0
1986static VALUE
1987rb_ary_first(int argc, VALUE *argv, VALUE ary)
1988{
1989 if (argc == 0) {
1990 if (RARRAY_LEN(ary) == 0) return Qnil;
1991 return RARRAY_AREF(ary, 0);
1992 }
1993 else {
1994 return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
1995 }
1996}
1997#endif
1998
1999static VALUE
2000ary_first(VALUE self)
2001{
2002 return (RARRAY_LEN(self) == 0) ? Qnil : RARRAY_AREF(self, 0);
2003}
2004
2005static VALUE
2006ary_last(VALUE self)
2007{
2008 long len = RARRAY_LEN(self);
2009 return (len == 0) ? Qnil : RARRAY_AREF(self, len-1);
2010}
2011
2012VALUE
2013rb_ary_last(int argc, const VALUE *argv, VALUE ary) // used by parse.y
2014{
2015 if (argc == 0) {
2016 return ary_last(ary);
2017 }
2018 else {
2019 return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_LAST);
2020 }
2021}
2022
2023/*
2024 * call-seq:
2025 * fetch(index) -> element
2026 * fetch(index, default_value) -> element or default_value
2027 * fetch(index) {|index| ... } -> element or block_return_value
2028 *
2029 * Returns the element of +self+ at offset +index+ if +index+ is in range; +index+ must be an
2030 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2031 *
2032 * With the single argument +index+ and no block,
2033 * returns the element at offset +index+:
2034 *
2035 * a = [:foo, 'bar', 2]
2036 * a.fetch(1) # => "bar"
2037 * a.fetch(1.1) # => "bar"
2038 *
2039 * If +index+ is negative, counts from the end of the array:
2040 *
2041 * a = [:foo, 'bar', 2]
2042 * a.fetch(-1) # => 2
2043 * a.fetch(-2) # => "bar"
2044 *
2045 * With arguments +index+ and +default_value+ (which may be any object) and no block,
2046 * returns +default_value+ if +index+ is out-of-range:
2047 *
2048 * a = [:foo, 'bar', 2]
2049 * a.fetch(1, nil) # => "bar"
2050 * a.fetch(3, :foo) # => :foo
2051 *
2052 * With argument +index+ and a block,
2053 * returns the element at offset +index+ if index is in range
2054 * (and the block is not called); otherwise calls the block with index and returns its return value:
2055 *
2056 * a = [:foo, 'bar', 2]
2057 * a.fetch(1) {|index| raise 'Cannot happen' } # => "bar"
2058 * a.fetch(50) {|index| "Value for #{index}" } # => "Value for 50"
2059 *
2060 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
2061 */
2062
2063static VALUE
2064rb_ary_fetch(int argc, VALUE *argv, VALUE ary)
2065{
2066 VALUE pos, ifnone;
2067 long block_given;
2068 long idx;
2069
2070 rb_scan_args(argc, argv, "11", &pos, &ifnone);
2071 block_given = rb_block_given_p();
2072 if (block_given && argc == 2) {
2073 rb_warn("block supersedes default value argument");
2074 }
2075 idx = NUM2LONG(pos);
2076
2077 if (idx < 0) {
2078 idx += RARRAY_LEN(ary);
2079 }
2080 if (idx < 0 || RARRAY_LEN(ary) <= idx) {
2081 if (block_given) return rb_yield(pos);
2082 if (argc == 1) {
2083 rb_raise(rb_eIndexError, "index %ld outside of array bounds: %ld...%ld",
2084 idx - (idx < 0 ? RARRAY_LEN(ary) : 0), -RARRAY_LEN(ary), RARRAY_LEN(ary));
2085 }
2086 return ifnone;
2087 }
2088 return RARRAY_AREF(ary, idx);
2089}
2090
2091/*
2092 * call-seq:
2093 * find(if_none_proc = nil) {|element| ... } -> object or nil
2094 * find(if_none_proc = nil) -> enumerator
2095 *
2096 * Returns the first element for which the block returns a truthy value.
2097 *
2098 * With a block given, calls the block with successive elements of the array;
2099 * returns the first element for which the block returns a truthy value:
2100 *
2101 * [1, 3, 5].find {|element| element > 2} # => 3
2102 *
2103 * If no such element is found, calls +if_none_proc+ and returns its return value.
2104 *
2105 * [1, 3, 5].find(proc {-1}) {|element| element > 12} # => -1
2106 *
2107 * With no block given, returns an Enumerator.
2108 *
2109 */
2110
2111static VALUE
2112rb_ary_find(int argc, VALUE *argv, VALUE ary)
2113{
2114 VALUE if_none;
2115 long idx;
2116
2117 RETURN_ENUMERATOR(ary, argc, argv);
2118 if_none = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
2119
2120 for (idx = 0; idx < RARRAY_LEN(ary); idx++) {
2121 VALUE elem = RARRAY_AREF(ary, idx);
2122 if (RTEST(rb_yield(elem))) {
2123 return elem;
2124 }
2125 }
2126
2127 if (!NIL_P(if_none)) {
2128 return rb_funcallv(if_none, idCall, 0, 0);
2129 }
2130 return Qnil;
2131}
2132
2133/*
2134 * call-seq:
2135 * rfind(if_none_proc = nil) {|element| ... } -> object or nil
2136 * rfind(if_none_proc = nil) -> enumerator
2137 *
2138 * Returns the last element for which the block returns a truthy value.
2139 *
2140 * With a block given, calls the block with successive elements of the array in
2141 * reverse order; returns the first element for which the block returns a truthy
2142 * value:
2143 *
2144 * [1, 2, 3, 4, 5, 6].rfind {|element| element < 5} # => 4
2145 *
2146 * If no such element is found, calls +if_none_proc+ and returns its return value.
2147 *
2148 * [1, 2, 3, 4].rfind(proc {0}) {|element| element < -2} # => 0
2149 *
2150 * With no block given, returns an Enumerator.
2151 *
2152 */
2153
2154static VALUE
2155rb_ary_rfind(int argc, VALUE *argv, VALUE ary)
2156{
2157 VALUE if_none;
2158 long len, idx;
2159
2160 RETURN_ENUMERATOR(ary, argc, argv);
2161 if_none = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
2162
2163 idx = RARRAY_LEN(ary);
2164 while (idx--) {
2165 VALUE elem = RARRAY_AREF(ary, idx);
2166 if (RTEST(rb_yield(elem))) {
2167 return elem;
2168 }
2169
2170 len = RARRAY_LEN(ary);
2171 idx = (idx >= len) ? len : idx;
2172 }
2173
2174 if (!NIL_P(if_none)) {
2175 return rb_funcallv(if_none, idCall, 0, 0);
2176 }
2177 return Qnil;
2178}
2179
2180/*
2181 * call-seq:
2182 * find_index(object) -> integer or nil
2183 * find_index {|element| ... } -> integer or nil
2184 * find_index -> new_enumerator
2185 * index(object) -> integer or nil
2186 * index {|element| ... } -> integer or nil
2187 * index -> new_enumerator
2188 *
2189 * Returns the zero-based integer index of a specified element, or +nil+.
2190 *
2191 * With only argument +object+ given,
2192 * returns the index of the first element +element+
2193 * for which <tt>object == element</tt>:
2194 *
2195 * a = [:foo, 'bar', 2, 'bar']
2196 * a.index('bar') # => 1
2197 *
2198 * Returns +nil+ if no such element found.
2199 *
2200 * With only a block given,
2201 * calls the block with each successive element;
2202 * returns the index of the first element for which the block returns a truthy value:
2203 *
2204 * a = [:foo, 'bar', 2, 'bar']
2205 * a.index {|element| element == 'bar' } # => 1
2206 *
2207 * Returns +nil+ if the block never returns a truthy value.
2208 *
2209 * With neither an argument nor a block given, returns a new Enumerator.
2210 *
2211 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
2212 */
2213
2214static VALUE
2215rb_ary_index(int argc, VALUE *argv, VALUE ary)
2216{
2217 VALUE val;
2218 long i;
2219
2220 if (argc == 0) {
2221 RETURN_ENUMERATOR(ary, 0, 0);
2222 for (i=0; i<RARRAY_LEN(ary); i++) {
2223 if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) {
2224 return LONG2NUM(i);
2225 }
2226 }
2227 return Qnil;
2228 }
2229 rb_check_arity(argc, 0, 1);
2230 val = argv[0];
2231 if (rb_block_given_p())
2232 rb_warn("given block not used");
2233 for (i=0; i<RARRAY_LEN(ary); i++) {
2234 VALUE e = RARRAY_AREF(ary, i);
2235 if (rb_equal(e, val)) {
2236 return LONG2NUM(i);
2237 }
2238 }
2239 return Qnil;
2240}
2241
2242/*
2243 * call-seq:
2244 * rindex(object) -> integer or nil
2245 * rindex {|element| ... } -> integer or nil
2246 * rindex -> new_enumerator
2247 *
2248 * Returns the index of the last element for which <tt>object == element</tt>.
2249 *
2250 * With argument +object+ given, returns the index of the last such element found:
2251 *
2252 * a = [:foo, 'bar', 2, 'bar']
2253 * a.rindex('bar') # => 3
2254 *
2255 * Returns +nil+ if no such object found.
2256 *
2257 * With a block given, calls the block with each successive element;
2258 * returns the index of the last element for which the block returns a truthy value:
2259 *
2260 * a = [:foo, 'bar', 2, 'bar']
2261 * a.rindex {|element| element == 'bar' } # => 3
2262 *
2263 * Returns +nil+ if the block never returns a truthy value.
2264 *
2265 * When neither an argument nor a block is given, returns a new Enumerator.
2266 *
2267 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
2268 */
2269
2270static VALUE
2271rb_ary_rindex(int argc, VALUE *argv, VALUE ary)
2272{
2273 VALUE val;
2274 long i = RARRAY_LEN(ary), len;
2275
2276 if (argc == 0) {
2277 RETURN_ENUMERATOR(ary, 0, 0);
2278 while (i--) {
2279 if (RTEST(rb_yield(RARRAY_AREF(ary, i))))
2280 return LONG2NUM(i);
2281 if (i > (len = RARRAY_LEN(ary))) {
2282 i = len;
2283 }
2284 }
2285 return Qnil;
2286 }
2287 rb_check_arity(argc, 0, 1);
2288 val = argv[0];
2289 if (rb_block_given_p())
2290 rb_warn("given block not used");
2291 while (i--) {
2292 VALUE e = RARRAY_AREF(ary, i);
2293 if (rb_equal(e, val)) {
2294 return LONG2NUM(i);
2295 }
2296 if (i > RARRAY_LEN(ary)) {
2297 break;
2298 }
2299 }
2300 return Qnil;
2301}
2302
2303VALUE
2305{
2306 VALUE tmp = rb_check_array_type(obj);
2307
2308 if (!NIL_P(tmp)) return tmp;
2309 return rb_ary_new3(1, obj);
2310}
2311
2312static void
2313rb_ary_splice(VALUE ary, long beg, long len, const VALUE *rptr, long rlen, int self_insert)
2314{
2315 long olen;
2316
2317 if (len < 0) rb_raise(rb_eIndexError, "negative length (%ld)", len);
2318 olen = RARRAY_LEN(ary);
2319 if (beg < 0) {
2320 beg += olen;
2321 if (beg < 0) {
2322 rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld",
2323 beg - olen, -olen);
2324 }
2325 }
2326 if (olen < len || olen < beg + len) {
2327 len = olen - beg;
2328 }
2329
2330 if (beg >= olen) {
2331 VALUE target_ary;
2332 if (beg > ARY_MAX_SIZE - rlen) {
2333 rb_raise(rb_eIndexError, "index %ld too big", beg);
2334 }
2335 target_ary = ary_ensure_room_for_push(ary, rlen-len); /* len is 0 or negative */
2336 len = beg + rlen;
2337 ary_mem_clear(ary, olen, beg - olen);
2338 if (rlen > 0) {
2339 /* ary's storage may have moved; only ary itself needs re-deriving. */
2340 if (self_insert) rptr = RARRAY_CONST_PTR(ary);
2341 ary_memcpy0(ary, beg, rlen, rptr, target_ary);
2342 }
2343 ARY_SET_LEN(ary, len);
2344 }
2345 else {
2346 long alen;
2347
2348 if (olen - len > ARY_MAX_SIZE - rlen) {
2349 rb_raise(rb_eIndexError, "index %ld too big", olen + rlen - len);
2350 }
2351 rb_ary_modify(ary);
2352 alen = olen + rlen - len;
2353 if (alen >= ARY_CAPA(ary)) {
2354 ary_double_capa(ary, alen);
2355 }
2356
2357 if (len != rlen) {
2358 RARRAY_PTR_USE(ary, ptr,
2359 MEMMOVE(ptr + beg + rlen, ptr + beg + len,
2360 VALUE, olen - (beg + len)));
2361 ARY_SET_LEN(ary, alen);
2362 }
2363 if (rlen > 0) {
2364 if (!self_insert) {
2365 rb_gc_writebarrier_remember(ary);
2366 }
2367 else {
2368 /* In this case, we're copying from a region in this array, so
2369 * we don't need to fire the write barrier. */
2370 rptr = RARRAY_CONST_PTR(ary);
2371 }
2372
2373 /* do not use RARRAY_PTR() because it can causes GC.
2374 * ary can contain T_NONE object because it is not cleared.
2375 */
2376 RARRAY_PTR_USE(ary, ptr,
2377 MEMMOVE(ptr + beg, rptr, VALUE, rlen));
2378 }
2379 }
2380}
2381
2382void
2383rb_ary_set_len(VALUE ary, long len)
2384{
2385 long capa;
2386
2387 rb_ary_modify_check(ary);
2388 if (ARY_SHARED_P(ary)) {
2389 rb_raise(rb_eRuntimeError, "can't set length of shared ");
2390 }
2391 if (len > (capa = (long)ARY_CAPA(ary))) {
2392 rb_bug("probable buffer overflow: %ld for %ld", len, capa);
2393 }
2394 ARY_SET_LEN(ary, len);
2395}
2396
2397VALUE
2398rb_ary_resize(VALUE ary, long len)
2399{
2400 long olen;
2401
2402 rb_ary_modify(ary);
2403 olen = RARRAY_LEN(ary);
2404 if (len == olen) return ary;
2405 if (len > ARY_MAX_SIZE) {
2406 rb_raise(rb_eIndexError, "index %ld too big", len);
2407 }
2408 if (len > olen) {
2409 if (len > ARY_CAPA(ary)) {
2410 ary_double_capa(ary, len);
2411 }
2412 ary_mem_clear(ary, olen, len - olen);
2413 ARY_SET_LEN(ary, len);
2414 }
2415 else if (ARY_EMBED_P(ary)) {
2416 ARY_SET_EMBED_LEN(ary, len);
2417 }
2418 else if (len <= ary_embed_capa(ary)) {
2419 const VALUE *ptr = ARY_HEAP_PTR(ary);
2420 long ptr_capa = ARY_HEAP_SIZE(ary);
2421 bool is_malloc_ptr = !ARY_SHARED_P(ary);
2422
2423 FL_SET_EMBED(ary);
2424
2425 MEMCPY((VALUE *)ARY_EMBED_PTR(ary), ptr, VALUE, len); /* WB: no new reference */
2426 ARY_SET_EMBED_LEN(ary, len);
2427
2428 if (is_malloc_ptr) ruby_sized_xfree((void *)ptr, ptr_capa);
2429 }
2430 else {
2431 if (olen > len + ARY_DEFAULT_SIZE) {
2432 size_t new_capa = ary_heap_realloc(ary, len);
2433 ARY_SET_CAPA(ary, new_capa);
2434 }
2435 ARY_SET_HEAP_LEN(ary, len);
2436 }
2437 ary_verify(ary);
2438 return ary;
2439}
2440
2441static VALUE
2442ary_aset_by_rb_ary_store(VALUE ary, long key, VALUE val)
2443{
2444 rb_ary_store(ary, key, val);
2445 return val;
2446}
2447
2448static VALUE
2449ary_aset_by_rb_ary_splice(VALUE ary, long beg, long len, VALUE val)
2450{
2451 VALUE rpl = rb_ary_to_ary(val);
2452 rb_ary_splice(ary, beg, len, RARRAY_CONST_PTR(rpl), RARRAY_LEN(rpl), ary == rpl);
2453 RB_GC_GUARD(rpl);
2454 return val;
2455}
2456
2457/*
2458 * call-seq:
2459 * self[index] = object -> object
2460 * self[start, length] = object -> object
2461 * self[range] = object -> object
2462 *
2463 * Assigns elements in +self+, based on the given +object+; returns +object+.
2464 *
2465 * In brief:
2466 *
2467 * a_orig = [:foo, 'bar', 2]
2468 *
2469 * # With argument index.
2470 * a = a_orig.dup
2471 * a[0] = 'foo' # => "foo"
2472 * a # => ["foo", "bar", 2]
2473 * a = a_orig.dup
2474 * a[7] = 'foo' # => "foo"
2475 * a # => [:foo, "bar", 2, nil, nil, nil, nil, "foo"]
2476 *
2477 * # With arguments start and length.
2478 * a = a_orig.dup
2479 * a[0, 2] = 'foo' # => "foo"
2480 * a # => ["foo", 2]
2481 * a = a_orig.dup
2482 * a[6, 50] = 'foo' # => "foo"
2483 * a # => [:foo, "bar", 2, nil, nil, nil, "foo"]
2484 *
2485 * # With argument range.
2486 * a = a_orig.dup
2487 * a[0..1] = 'foo' # => "foo"
2488 * a # => ["foo", 2]
2489 * a = a_orig.dup
2490 * a[6..50] = 'foo' # => "foo"
2491 * a # => [:foo, "bar", 2, nil, nil, nil, "foo"]
2492 *
2493 * When Integer argument +index+ is given, assigns +object+ to an element in +self+.
2494 *
2495 * If +index+ is non-negative, assigns +object+ the element at offset +index+:
2496 *
2497 * a = [:foo, 'bar', 2]
2498 * a[0] = 'foo' # => "foo"
2499 * a # => ["foo", "bar", 2]
2500 *
2501 * If +index+ is greater than <tt>self.length</tt>, extends the array:
2502 *
2503 * a = [:foo, 'bar', 2]
2504 * a[7] = 'foo' # => "foo"
2505 * a # => [:foo, "bar", 2, nil, nil, nil, nil, "foo"]
2506 *
2507 * If +index+ is negative, counts backwards from the end of the array:
2508 *
2509 * a = [:foo, 'bar', 2]
2510 * a[-1] = 'two' # => "two"
2511 * a # => [:foo, "bar", "two"]
2512 *
2513 * When Integer arguments +start+ and +length+ are given and +object+ is not an array,
2514 * removes <tt>length - 1</tt> elements beginning at offset +start+,
2515 * and assigns +object+ at offset +start+:
2516 *
2517 * a = [:foo, 'bar', 2]
2518 * a[0, 2] = 'foo' # => "foo"
2519 * a # => ["foo", 2]
2520 *
2521 * If +start+ is negative, counts backwards from the end of the array:
2522 *
2523 * a = [:foo, 'bar', 2]
2524 * a[-2, 2] = 'foo' # => "foo"
2525 * a # => [:foo, "foo"]
2526 *
2527 * If +start+ is non-negative and outside the array (<tt> >= self.size</tt>),
2528 * extends the array with +nil+, assigns +object+ at offset +start+,
2529 * and ignores +length+:
2530 *
2531 * a = [:foo, 'bar', 2]
2532 * a[6, 50] = 'foo' # => "foo"
2533 * a # => [:foo, "bar", 2, nil, nil, nil, "foo"]
2534 *
2535 * If +length+ is zero, shifts elements at and following offset +start+
2536 * and assigns +object+ at offset +start+:
2537 *
2538 * a = [:foo, 'bar', 2]
2539 * a[1, 0] = 'foo' # => "foo"
2540 * a # => [:foo, "foo", "bar", 2]
2541 *
2542 * If +length+ is too large for the existing array, does not extend the array:
2543 *
2544 * a = [:foo, 'bar', 2]
2545 * a[1, 5] = 'foo' # => "foo"
2546 * a # => [:foo, "foo"]
2547 *
2548 * When Range argument +range+ is given and +object+ is not an array,
2549 * removes <tt>length - 1</tt> elements beginning at offset +start+,
2550 * and assigns +object+ at offset +start+:
2551 *
2552 * a = [:foo, 'bar', 2]
2553 * a[0..1] = 'foo' # => "foo"
2554 * a # => ["foo", 2]
2555 *
2556 * if <tt>range.begin</tt> is negative, counts backwards from the end of the array:
2557 *
2558 * a = [:foo, 'bar', 2]
2559 * a[-2..2] = 'foo' # => "foo"
2560 * a # => [:foo, "foo"]
2561 *
2562 * If the array length is less than <tt>range.begin</tt>,
2563 * extends the array with +nil+, assigns +object+ at offset <tt>range.begin</tt>,
2564 * and ignores +length+:
2565 *
2566 * a = [:foo, 'bar', 2]
2567 * a[6..50] = 'foo' # => "foo"
2568 * a # => [:foo, "bar", 2, nil, nil, nil, "foo"]
2569 *
2570 * If <tt>range.end</tt> is zero, shifts elements at and following offset +start+
2571 * and assigns +object+ at offset +start+:
2572 *
2573 * a = [:foo, 'bar', 2]
2574 * a[1..0] = 'foo' # => "foo"
2575 * a # => [:foo, "foo", "bar", 2]
2576 *
2577 * If <tt>range.end</tt> is negative, assigns +object+ at offset +start+,
2578 * retains <tt>range.end.abs -1</tt> elements past that, and removes those beyond:
2579 *
2580 * a = [:foo, 'bar', 2]
2581 * a[1..-1] = 'foo' # => "foo"
2582 * a # => [:foo, "foo"]
2583 * a = [:foo, 'bar', 2]
2584 * a[1..-2] = 'foo' # => "foo"
2585 * a # => [:foo, "foo", 2]
2586 * a = [:foo, 'bar', 2]
2587 * a[1..-3] = 'foo' # => "foo"
2588 * a # => [:foo, "foo", "bar", 2]
2589 * a = [:foo, 'bar', 2]
2590 *
2591 * If <tt>range.end</tt> is too large for the existing array,
2592 * replaces array elements, but does not extend the array with +nil+ values:
2593 *
2594 * a = [:foo, 'bar', 2]
2595 * a[1..5] = 'foo' # => "foo"
2596 * a # => [:foo, "foo"]
2597 *
2598 * Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
2599 */
2600
2601static VALUE
2602rb_ary_aset(int argc, VALUE *argv, VALUE ary)
2603{
2604 long offset, beg, len;
2605
2606 rb_check_arity(argc, 2, 3);
2607 rb_ary_modify_check(ary);
2608 if (argc == 3) {
2609 beg = NUM2LONG(argv[0]);
2610 len = NUM2LONG(argv[1]);
2611 return ary_aset_by_rb_ary_splice(ary, beg, len, argv[2]);
2612 }
2613 if (FIXNUM_P(argv[0])) {
2614 offset = FIX2LONG(argv[0]);
2615 return ary_aset_by_rb_ary_store(ary, offset, argv[1]);
2616 }
2617 if (rb_range_beg_len(argv[0], &beg, &len, RARRAY_LEN(ary), 1)) {
2618 /* check if idx is Range */
2619 return ary_aset_by_rb_ary_splice(ary, beg, len, argv[1]);
2620 }
2621
2622 offset = NUM2LONG(argv[0]);
2623 return ary_aset_by_rb_ary_store(ary, offset, argv[1]);
2624}
2625
2626/*
2627 * call-seq:
2628 * insert(index, *objects) -> self
2629 *
2630 * Inserts the given +objects+ as elements of +self+;
2631 * returns +self+.
2632 *
2633 * When +index+ is non-negative, inserts +objects+
2634 * _before_ the element at offset +index+:
2635 *
2636 * a = ['a', 'b', 'c'] # => ["a", "b", "c"]
2637 * a.insert(1, :x, :y, :z) # => ["a", :x, :y, :z, "b", "c"]
2638 *
2639 * Extends the array if +index+ is beyond the array (<tt>index >= self.size</tt>):
2640 *
2641 * a = ['a', 'b', 'c'] # => ["a", "b", "c"]
2642 * a.insert(5, :x, :y, :z) # => ["a", "b", "c", nil, nil, :x, :y, :z]
2643 *
2644 * When +index+ is negative, inserts +objects+
2645 * _after_ the element at offset <tt>index + self.size</tt>:
2646 *
2647 * a = ['a', 'b', 'c'] # => ["a", "b", "c"]
2648 * a.insert(-2, :x, :y, :z) # => ["a", "b", :x, :y, :z, "c"]
2649 *
2650 * With no +objects+ given, does nothing:
2651 *
2652 * a = ['a', 'b', 'c'] # => ["a", "b", "c"]
2653 * a.insert(1) # => ["a", "b", "c"]
2654 * a.insert(50) # => ["a", "b", "c"]
2655 * a.insert(-50) # => ["a", "b", "c"]
2656 *
2657 * Raises IndexError if +objects+ are given and +index+ is negative and out of range.
2658 *
2659 * Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
2660 */
2661
2662static VALUE
2663rb_ary_insert(int argc, VALUE *argv, VALUE ary)
2664{
2665 long pos;
2666
2667 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
2668 rb_ary_modify_check(ary);
2669 pos = NUM2LONG(argv[0]);
2670 if (argc == 1) return ary;
2671 if (pos == -1) {
2672 pos = RARRAY_LEN(ary);
2673 }
2674 else if (pos < 0) {
2675 long minpos = -RARRAY_LEN(ary) - 1;
2676 if (pos < minpos) {
2677 rb_raise(rb_eIndexError, "index %ld too small for array; minimum: %ld",
2678 pos, minpos);
2679 }
2680 pos++;
2681 }
2682 rb_ary_splice(ary, pos, 0, argv + 1, argc - 1, FALSE);
2683 return ary;
2684}
2685
2686static VALUE
2687rb_ary_length(VALUE ary);
2688
2689static VALUE
2690ary_enum_length(VALUE ary, VALUE args, VALUE eobj)
2691{
2692 return rb_ary_length(ary);
2693}
2694
2695// Primitive to avoid a race condition in Array#each.
2696// Return `true` and write `value` and `index` if the element exists.
2697static VALUE
2698ary_fetch_next(VALUE self, VALUE *index, VALUE *value)
2699{
2700 long i = NUM2LONG(*index);
2701 if (i >= RARRAY_LEN(self)) {
2702 return Qfalse;
2703 }
2704 *value = RARRAY_AREF(self, i);
2705 *index = LONG2NUM(i + 1);
2706 return Qtrue;
2707}
2708
2709/*
2710 * call-seq:
2711 * each {|element| ... } -> self
2712 * each -> new_enumerator
2713 *
2714 * With a block given, iterates over the elements of +self+,
2715 * passing each element to the block;
2716 * returns +self+:
2717 *
2718 * a = [:foo, 'bar', 2]
2719 * a.each {|element| puts "#{element.class} #{element}" }
2720 *
2721 * Output:
2722 *
2723 * Symbol foo
2724 * String bar
2725 * Integer 2
2726 *
2727 * Allows the array to be modified during iteration:
2728 *
2729 * a = [:foo, 'bar', 2]
2730 * a.each {|element| puts element; a.clear if element.to_s.start_with?('b') }
2731 *
2732 * Output:
2733 *
2734 * foo
2735 * bar
2736 *
2737 * With no block given, returns a new Enumerator.
2738 *
2739 * Related: see {Methods for Iterating}[rdoc-ref:Array@Methods+for+Iterating].
2740 */
2741
2742VALUE
2743rb_ary_each(VALUE ary)
2744{
2745 long i;
2746 ary_verify(ary);
2747 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
2748 for (i=0; i<RARRAY_LEN(ary); i++) {
2749 rb_yield(RARRAY_AREF(ary, i));
2750 }
2751 return ary;
2752}
2753
2754/*
2755 * call-seq:
2756 * each_index {|index| ... } -> self
2757 * each_index -> new_enumerator
2758 *
2759 * With a block given, iterates over the elements of +self+,
2760 * passing each <i>array index</i> to the block;
2761 * returns +self+:
2762 *
2763 * a = [:foo, 'bar', 2]
2764 * a.each_index {|index| puts "#{index} #{a[index]}" }
2765 *
2766 * Output:
2767 *
2768 * 0 foo
2769 * 1 bar
2770 * 2 2
2771 *
2772 * Allows the array to be modified during iteration:
2773 *
2774 * a = [:foo, 'bar', 2]
2775 * a.each_index {|index| puts index; a.clear if index > 0 }
2776 * a # => []
2777 *
2778 * Output:
2779 *
2780 * 0
2781 * 1
2782 *
2783 * With no block given, returns a new Enumerator.
2784 *
2785 * Related: see {Methods for Iterating}[rdoc-ref:Array@Methods+for+Iterating].
2786 */
2787
2788static VALUE
2789rb_ary_each_index(VALUE ary)
2790{
2791 long i;
2792 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
2793
2794 for (i=0; i<RARRAY_LEN(ary); i++) {
2795 rb_yield(LONG2NUM(i));
2796 }
2797 return ary;
2798}
2799
2800/*
2801 * call-seq:
2802 * reverse_each {|element| ... } -> self
2803 * reverse_each -> Enumerator
2804 *
2805 * When a block given, iterates backwards over the elements of +self+,
2806 * passing, in reverse order, each element to the block;
2807 * returns +self+:
2808 *
2809 * a = []
2810 * [0, 1, 2].reverse_each {|element| a.push(element) }
2811 * a # => [2, 1, 0]
2812 *
2813 * Allows the array to be modified during iteration:
2814 *
2815 * a = ['a', 'b', 'c']
2816 * a.reverse_each {|element| a.clear if element.start_with?('b') }
2817 * a # => []
2818 *
2819 * When no block given, returns a new Enumerator.
2820 *
2821 * Related: see {Methods for Iterating}[rdoc-ref:Array@Methods+for+Iterating].
2822 */
2823
2824static VALUE
2825rb_ary_reverse_each(VALUE ary)
2826{
2827 long len;
2828
2829 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
2830 len = RARRAY_LEN(ary);
2831 while (len--) {
2832 long nlen;
2833 rb_yield(RARRAY_AREF(ary, len));
2834 nlen = RARRAY_LEN(ary);
2835 if (nlen < len) {
2836 len = nlen;
2837 }
2838 }
2839 return ary;
2840}
2841
2842/*
2843 * call-seq:
2844 * length -> integer
2845 * size -> integer
2846 *
2847 * Returns the count of elements in +self+:
2848 *
2849 * [0, 1, 2].length # => 3
2850 * [].length # => 0
2851 *
2852 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
2853 */
2854
2855static VALUE
2856rb_ary_length(VALUE ary)
2857{
2858 long len = RARRAY_LEN(ary);
2859 return LONG2NUM(len);
2860}
2861
2862/*
2863 * call-seq:
2864 * empty? -> true or false
2865 *
2866 * Returns +true+ if the count of elements in +self+ is zero,
2867 * +false+ otherwise.
2868 *
2869 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
2870 */
2871
2872static VALUE
2873rb_ary_empty_p(VALUE ary)
2874{
2875 return RBOOL(RARRAY_LEN(ary) == 0);
2876}
2877
2878VALUE
2879rb_ary_dup(VALUE ary)
2880{
2881 long len = RARRAY_LEN(ary);
2882 VALUE dup = rb_ary_new2(len);
2883 ary_memcpy(dup, 0, len, RARRAY_CONST_PTR(ary));
2884 ARY_SET_LEN(dup, len);
2885
2886 ary_verify(ary);
2887 ary_verify(dup);
2888 return dup;
2889}
2890
2891VALUE
2893{
2894 return ary_make_partial(ary, rb_cArray, 0, RARRAY_LEN(ary));
2895}
2896
2897extern VALUE rb_output_fs;
2898
2899static void ary_join_1(VALUE obj, VALUE ary, VALUE sep, long i, VALUE result, int *first);
2900
2901static VALUE
2902recursive_join(VALUE obj, VALUE argp, int recur)
2903{
2904 VALUE *arg = (VALUE *)argp;
2905 VALUE ary = arg[0];
2906 VALUE sep = arg[1];
2907 VALUE result = arg[2];
2908 int *first = (int *)arg[3];
2909
2910 if (recur) {
2911 rb_raise(rb_eArgError, "recursive array join");
2912 }
2913 else {
2914 ary_join_1(obj, ary, sep, 0, result, first);
2915 }
2916 return Qnil;
2917}
2918
2919static long
2920ary_join_0(VALUE ary, VALUE sep, long max, VALUE result)
2921{
2922 long i;
2923 VALUE val;
2924
2925 if (max > 0) rb_enc_copy(result, RARRAY_AREF(ary, 0));
2926 for (i=0; i<max; i++) {
2927 val = RARRAY_AREF(ary, i);
2928 if (!RB_TYPE_P(val, T_STRING)) break;
2929 if (i > 0 && !NIL_P(sep))
2930 rb_str_buf_append(result, sep);
2931 rb_str_buf_append(result, val);
2932 }
2933 return i;
2934}
2935
2936static void
2937ary_join_1_str(VALUE dst, VALUE src, int *first)
2938{
2939 rb_str_buf_append(dst, src);
2940 if (*first) {
2941 rb_enc_copy(dst, src);
2942 *first = FALSE;
2943 }
2944}
2945
2946static void
2947ary_join_1_ary(VALUE obj, VALUE ary, VALUE sep, VALUE result, VALUE val, int *first)
2948{
2949 if (val == ary) {
2950 rb_raise(rb_eArgError, "recursive array join");
2951 }
2952 else {
2953 VALUE args[4];
2954
2955 *first = FALSE;
2956 args[0] = val;
2957 args[1] = sep;
2958 args[2] = result;
2959 args[3] = (VALUE)first;
2960 rb_exec_recursive(recursive_join, obj, (VALUE)args);
2961 }
2962}
2963
2964static void
2965ary_join_1(VALUE obj, VALUE ary, VALUE sep, long i, VALUE result, int *first)
2966{
2967 VALUE val, tmp;
2968
2969 for (; i<RARRAY_LEN(ary); i++) {
2970 if (i > 0 && !NIL_P(sep))
2971 rb_str_buf_append(result, sep);
2972
2973 val = RARRAY_AREF(ary, i);
2974 if (RB_TYPE_P(val, T_STRING)) {
2975 ary_join_1_str(result, val, first);
2976 }
2977 else if (RB_TYPE_P(val, T_ARRAY)) {
2978 ary_join_1_ary(val, ary, sep, result, val, first);
2979 }
2980 else if (!NIL_P(tmp = rb_check_string_type(val))) {
2981 ary_join_1_str(result, tmp, first);
2982 }
2983 else if (!NIL_P(tmp = rb_check_array_type(val))) {
2984 ary_join_1_ary(val, ary, sep, result, tmp, first);
2985 }
2986 else {
2987 ary_join_1_str(result, rb_obj_as_string(val), first);
2988 }
2989 }
2990}
2991
2992VALUE
2993rb_ary_join(VALUE ary, VALUE sep)
2994{
2995 long len = 1, i;
2996 VALUE val, tmp, result;
2997
2998 if (RARRAY_LEN(ary) == 0) return rb_usascii_str_new(0, 0);
2999
3000 if (!NIL_P(sep)) {
3001 StringValue(sep);
3002 len += RSTRING_LEN(sep) * (RARRAY_LEN(ary) - 1);
3003 }
3004 long len_memo = RARRAY_LEN(ary);
3005 for (i=0; i < len_memo; i++) {
3006 val = RARRAY_AREF(ary, i);
3007 if (RB_UNLIKELY(!RB_TYPE_P(val, T_STRING))) {
3008 tmp = rb_check_string_type(val);
3009 if (NIL_P(tmp) || tmp != val) {
3010 int first;
3011 long n = RARRAY_LEN(ary);
3012 if (i > n) i = n;
3013 result = rb_str_buf_new(len + (n-i)*10);
3014 rb_enc_associate(result, rb_usascii_encoding());
3015 i = ary_join_0(ary, sep, i, result);
3016 first = i == 0;
3017 ary_join_1(ary, ary, sep, i, result, &first);
3018 return result;
3019 }
3020 len += RSTRING_LEN(tmp);
3021 len_memo = RARRAY_LEN(ary);
3022 }
3023 else {
3024 len += RSTRING_LEN(val);
3025 }
3026 }
3027
3028 result = rb_str_new(0, len);
3029 rb_str_set_len(result, 0);
3030
3031 ary_join_0(ary, sep, RARRAY_LEN(ary), result);
3032
3033 return result;
3034}
3035
3036/*
3037 * call-seq:
3038 * join(separator = $,) -> new_string
3039 *
3040 * Returns the new string formed by joining the converted elements of +self+;
3041 * for each element +element+:
3042 *
3043 * - Converts recursively using <tt>element.join(separator)</tt>
3044 * if +element+ is a <tt>kind_of?(Array)</tt>.
3045 * - Otherwise, converts using <tt>element.to_s</tt>.
3046 *
3047 * With no argument given, joins using the output field separator, <tt>$,</tt>:
3048 *
3049 * a = [:foo, 'bar', 2]
3050 * $, # => nil
3051 * a.join # => "foobar2"
3052 *
3053 * With string argument +separator+ given, joins using that separator:
3054 *
3055 * a = [:foo, 'bar', 2]
3056 * a.join("\n") # => "foo\nbar\n2"
3057 *
3058 * Joins recursively for nested arrays:
3059 *
3060 * a = [:foo, [:bar, [:baz, :bat]]]
3061 * a.join # => "foobarbazbat"
3062 *
3063 * Related: see {Methods for Converting}[rdoc-ref:Array@Methods+for+Converting].
3064 */
3065static VALUE
3066rb_ary_join_m(int argc, VALUE *argv, VALUE ary)
3067{
3068 VALUE sep;
3069
3070 if (rb_check_arity(argc, 0, 1) == 0 || NIL_P(sep = argv[0])) {
3071 sep = rb_output_fs;
3072 if (!NIL_P(sep)) {
3073 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "$, is set to non-nil value");
3074 }
3075 }
3076
3077 return rb_ary_join(ary, sep);
3078}
3079
3080static VALUE
3081inspect_ary(VALUE ary, VALUE dummy, int recur)
3082{
3083 long i;
3084 VALUE s, str;
3085
3086 if (recur) return rb_usascii_str_new_cstr("[...]");
3087 str = rb_str_buf_new2("[");
3088 for (i=0; i<RARRAY_LEN(ary); i++) {
3089 s = rb_inspect(RARRAY_AREF(ary, i));
3090 if (i > 0) rb_str_buf_cat2(str, ", ");
3091 else rb_enc_copy(str, s);
3092 rb_str_buf_append(str, s);
3093 }
3094 rb_str_buf_cat2(str, "]");
3095 return str;
3096}
3097
3098/*
3099 * call-seq:
3100 * inspect -> new_string
3101 * to_s -> new_string
3102 *
3103 * Returns the new string formed by calling method <tt>#inspect</tt>
3104 * on each array element:
3105 *
3106 * a = [:foo, 'bar', 2]
3107 * a.inspect # => "[:foo, \"bar\", 2]"
3108 *
3109 * Related: see {Methods for Converting}[rdoc-ref:Array@Methods+for+Converting].
3110 */
3111
3112static VALUE
3113rb_ary_inspect(VALUE ary)
3114{
3115 if (RARRAY_LEN(ary) == 0) return rb_usascii_str_new2("[]");
3116 return rb_exec_recursive(inspect_ary, ary, 0);
3117}
3118
3119VALUE
3120rb_ary_to_s(VALUE ary)
3121{
3122 return rb_ary_inspect(ary);
3123}
3124
3125/*
3126 * call-seq:
3127 * to_a -> self or new_array
3128 *
3129 * When +self+ is an instance of \Array, returns +self+.
3130 *
3131 * Otherwise, returns a new array containing the elements of +self+:
3132 *
3133 * class MyArray < Array; end
3134 * my_a = MyArray.new(['foo', 'bar', 'two'])
3135 * a = my_a.to_a
3136 * a # => ["foo", "bar", "two"]
3137 * a.class # => Array # Not MyArray.
3138 *
3139 * Related: see {Methods for Converting}[rdoc-ref:Array@Methods+for+Converting].
3140 */
3141
3142static VALUE
3143rb_ary_to_a(VALUE ary)
3144{
3145 if (rb_obj_class(ary) != rb_cArray) {
3146 VALUE dup = rb_ary_new2(RARRAY_LEN(ary));
3147 rb_ary_replace(dup, ary);
3148 return dup;
3149 }
3150 return ary;
3151}
3152
3153/*
3154 * call-seq:
3155 * to_h -> new_hash
3156 * to_h {|element| ... } -> new_hash
3157 *
3158 * Returns a new hash formed from +self+.
3159 *
3160 * With no block given, each element of +self+ must be a 2-element sub-array;
3161 * forms each sub-array into a key-value pair in the new hash:
3162 *
3163 * a = [['foo', 'zero'], ['bar', 'one'], ['baz', 'two']]
3164 * a.to_h # => {"foo"=>"zero", "bar"=>"one", "baz"=>"two"}
3165 * [].to_h # => {}
3166 *
3167 * With a block given, the block must return a 2-element array;
3168 * calls the block with each element of +self+;
3169 * forms each returned array into a key-value pair in the returned hash:
3170 *
3171 * a = ['foo', :bar, 1, [2, 3], {baz: 4}]
3172 * a.to_h {|element| [element, element.class] }
3173 * # => {"foo"=>String, :bar=>Symbol, 1=>Integer, [2, 3]=>Array, {:baz=>4}=>Hash}
3174 *
3175 * Related: see {Methods for Converting}[rdoc-ref:Array@Methods+for+Converting].
3176 */
3177
3178static VALUE
3179rb_ary_to_h(VALUE ary)
3180{
3181 long i;
3182 VALUE hash = rb_hash_new_with_size(RARRAY_LEN(ary));
3183 int block_given = rb_block_given_p();
3184
3185 for (i=0; i<RARRAY_LEN(ary); i++) {
3186 const VALUE e = rb_ary_elt(ary, i);
3187 const VALUE elt = block_given ? rb_yield_force_blockarg(e) : e;
3188 const VALUE key_value_pair = rb_check_array_type(elt);
3189 if (NIL_P(key_value_pair)) {
3190 rb_raise(rb_eTypeError, "wrong element type %"PRIsVALUE" at %ld (expected array)",
3191 rb_obj_class(elt), i);
3192 }
3193 if (RARRAY_LEN(key_value_pair) != 2) {
3194 rb_raise(rb_eArgError, "wrong array length at %ld (expected 2, was %ld)",
3195 i, RARRAY_LEN(key_value_pair));
3196 }
3197 rb_hash_aset(hash, RARRAY_AREF(key_value_pair, 0), RARRAY_AREF(key_value_pair, 1));
3198 }
3199 return hash;
3200}
3201
3202/*
3203 * call-seq:
3204 * to_ary -> self
3205 *
3206 * Returns +self+.
3207 */
3208
3209static VALUE
3210rb_ary_to_ary_m(VALUE ary)
3211{
3212 return ary;
3213}
3214
3215static void
3216ary_reverse(VALUE *p1, VALUE *p2)
3217{
3218 while (p1 < p2) {
3219 VALUE tmp = *p1;
3220 *p1++ = *p2;
3221 *p2-- = tmp;
3222 }
3223}
3224
3225VALUE
3227{
3228 VALUE *p2;
3229 long len = RARRAY_LEN(ary);
3230
3231 rb_ary_modify(ary);
3232 if (len > 1) {
3233 RARRAY_PTR_USE(ary, p1, {
3234 p2 = p1 + len - 1; /* points last item */
3235 ary_reverse(p1, p2);
3236 }); /* WB: no new reference */
3237 }
3238 return ary;
3239}
3240
3241/*
3242 * call-seq:
3243 * reverse! -> self
3244 *
3245 * Reverses the order of the elements of +self+;
3246 * returns +self+:
3247 *
3248 * a = [0, 1, 2]
3249 * a.reverse! # => [2, 1, 0]
3250 * a # => [2, 1, 0]
3251 *
3252 * Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
3253 */
3254
3255static VALUE
3256rb_ary_reverse_bang(VALUE ary)
3257{
3258 return rb_ary_reverse(ary);
3259}
3260
3261/*
3262 * call-seq:
3263 * reverse -> new_array
3264 *
3265 * Returns a new array containing the elements of +self+ in reverse order:
3266 *
3267 * [0, 1, 2].reverse # => [2, 1, 0]
3268 *
3269 * Related: see {Methods for Combining}[rdoc-ref:Array@Methods+for+Combining].
3270 */
3271
3272static VALUE
3273rb_ary_reverse_m(VALUE ary)
3274{
3275 long len = RARRAY_LEN(ary);
3276 VALUE dup = rb_ary_new2(len);
3277
3278 if (len > 0) {
3279 const VALUE *p1 = RARRAY_CONST_PTR(ary);
3280 VALUE *p2 = (VALUE *)RARRAY_CONST_PTR(dup) + len - 1;
3281 do *p2-- = *p1++; while (--len > 0);
3282 }
3283 ARY_SET_LEN(dup, RARRAY_LEN(ary));
3284 return dup;
3285}
3286
3287static inline long
3288rotate_count(long cnt, long len)
3289{
3290 return (cnt < 0) ? (len - (~cnt % len) - 1) : (cnt % len);
3291}
3292
3293static void
3294ary_rotate_ptr(VALUE *ptr, long len, long cnt)
3295{
3296 if (cnt == 1) {
3297 VALUE tmp = *ptr;
3298 memmove(ptr, ptr + 1, sizeof(VALUE)*(len - 1));
3299 *(ptr + len - 1) = tmp;
3300 }
3301 else if (cnt == len - 1) {
3302 VALUE tmp = *(ptr + len - 1);
3303 memmove(ptr + 1, ptr, sizeof(VALUE)*(len - 1));
3304 *ptr = tmp;
3305 }
3306 else {
3307 --len;
3308 if (cnt < len) ary_reverse(ptr + cnt, ptr + len);
3309 if (--cnt > 0) ary_reverse(ptr, ptr + cnt);
3310 if (len > 0) ary_reverse(ptr, ptr + len);
3311 }
3312}
3313
3314VALUE
3315rb_ary_rotate(VALUE ary, long cnt)
3316{
3317 rb_ary_modify(ary);
3318
3319 if (cnt != 0) {
3320 long len = RARRAY_LEN(ary);
3321 if (len > 1 && (cnt = rotate_count(cnt, len)) > 0) {
3322 RARRAY_PTR_USE(ary, ptr, ary_rotate_ptr(ptr, len, cnt));
3323 return ary;
3324 }
3325 }
3326 return Qnil;
3327}
3328
3329/*
3330 * call-seq:
3331 * rotate!(count = 1) -> self
3332 *
3333 * Rotates +self+ in place by moving elements from one end to the other; returns +self+.
3334 *
3335 * With non-negative numeric +count+,
3336 * rotates +count+ elements from the beginning to the end:
3337 *
3338 * [0, 1, 2, 3].rotate!(2) # => [2, 3, 0, 1]
3339 [0, 1, 2, 3].rotate!(2.1) # => [2, 3, 0, 1]
3340 *
3341 * If +count+ is large, uses <tt>count % array.size</tt> as the count:
3342 *
3343 * [0, 1, 2, 3].rotate!(21) # => [1, 2, 3, 0]
3344 *
3345 * If +count+ is zero, rotates no elements:
3346 *
3347 * [0, 1, 2, 3].rotate!(0) # => [0, 1, 2, 3]
3348 *
3349 * With a negative numeric +count+, rotates in the opposite direction,
3350 * from end to beginning:
3351 *
3352 * [0, 1, 2, 3].rotate!(-1) # => [3, 0, 1, 2]
3353 *
3354 * If +count+ is small (far from zero), uses <tt>count % array.size</tt> as the count:
3355 *
3356 * [0, 1, 2, 3].rotate!(-21) # => [3, 0, 1, 2]
3357 *
3358 * Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
3359 */
3360
3361static VALUE
3362rb_ary_rotate_bang(int argc, VALUE *argv, VALUE ary)
3363{
3364 long n = (rb_check_arity(argc, 0, 1) ? NUM2LONG(argv[0]) : 1);
3365 rb_ary_rotate(ary, n);
3366 return ary;
3367}
3368
3369/*
3370 * call-seq:
3371 * rotate(count = 1) -> new_array
3372 *
3373 * Returns a new array formed from +self+ with elements
3374 * rotated from one end to the other.
3375 *
3376 * With non-negative numeric +count+,
3377 * rotates elements from the beginning to the end:
3378 *
3379 * [0, 1, 2, 3].rotate(2) # => [2, 3, 0, 1]
3380 * [0, 1, 2, 3].rotate(2.1) # => [2, 3, 0, 1]
3381 *
3382 * If +count+ is large, uses <tt>count % array.size</tt> as the count:
3383 *
3384 * [0, 1, 2, 3].rotate(22) # => [2, 3, 0, 1]
3385 *
3386 * With a +count+ of zero, rotates no elements:
3387 *
3388 * [0, 1, 2, 3].rotate(0) # => [0, 1, 2, 3]
3389 *
3390 * With negative numeric +count+, rotates in the opposite direction,
3391 * from the end to the beginning:
3392 *
3393 * [0, 1, 2, 3].rotate(-1) # => [3, 0, 1, 2]
3394 *
3395 * If +count+ is small (far from zero), uses <tt>count % array.size</tt> as the count:
3396 *
3397 * [0, 1, 2, 3].rotate(-21) # => [3, 0, 1, 2]
3398 *
3399 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
3400 */
3401
3402static VALUE
3403rb_ary_rotate_m(int argc, VALUE *argv, VALUE ary)
3404{
3405 VALUE rotated;
3406 const VALUE *ptr;
3407 long len;
3408 long cnt = (rb_check_arity(argc, 0, 1) ? NUM2LONG(argv[0]) : 1);
3409
3410 len = RARRAY_LEN(ary);
3411 rotated = rb_ary_new2(len);
3412 if (len > 0) {
3413 cnt = rotate_count(cnt, len);
3414 ptr = RARRAY_CONST_PTR(ary);
3415 len -= cnt;
3416 ary_memcpy(rotated, 0, len, ptr + cnt);
3417 ary_memcpy(rotated, len, cnt, ptr);
3418 }
3419 ARY_SET_LEN(rotated, RARRAY_LEN(ary));
3420 return rotated;
3421}
3422
3423struct ary_sort_data {
3424 VALUE ary;
3425 VALUE receiver;
3426};
3427
3428static VALUE
3429sort_reentered(VALUE ary)
3430{
3431 if (RBASIC(ary)->klass) {
3432 rb_raise(rb_eRuntimeError, "sort reentered");
3433 }
3434 return Qnil;
3435}
3436
3437static void
3438sort_returned(struct ary_sort_data *data)
3439{
3440 if (rb_obj_frozen_p(data->receiver)) {
3441 rb_raise(rb_eFrozenError, "array frozen during sort");
3442 }
3443 sort_reentered(data->ary);
3444}
3445
3446static int
3447sort_1(const void *ap, const void *bp, void *dummy)
3448{
3449 struct ary_sort_data *data = dummy;
3450 VALUE retval = sort_reentered(data->ary);
3451 VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
3452 VALUE args[2];
3453 int n;
3454
3455 args[0] = a;
3456 args[1] = b;
3457 retval = rb_yield_values2(2, args);
3458 n = rb_cmpint(retval, a, b);
3459 sort_returned(data);
3460 return n;
3461}
3462
3463static int
3464sort_2(const void *ap, const void *bp, void *dummy)
3465{
3466 struct ary_sort_data *data = dummy;
3467 VALUE retval = sort_reentered(data->ary);
3468 VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
3469 int n;
3470
3471 if (FIXNUM_P(a) && FIXNUM_P(b) && CMP_OPTIMIZABLE(INTEGER)) {
3472 if ((long)a > (long)b) return 1;
3473 if ((long)a < (long)b) return -1;
3474 return 0;
3475 }
3476 if (STRING_P(a) && STRING_P(b) && CMP_OPTIMIZABLE(STRING)) {
3477 return rb_str_cmp(a, b);
3478 }
3479 if (RB_FLOAT_TYPE_P(a) && CMP_OPTIMIZABLE(FLOAT)) {
3480 return rb_float_cmp(a, b);
3481 }
3482
3483 retval = rb_funcallv(a, id_cmp, 1, &b);
3484 n = rb_cmpint(retval, a, b);
3485 sort_returned(data);
3486
3487 return n;
3488}
3489
3490/*
3491 * call-seq:
3492 * sort! -> self
3493 * sort! {|a, b| ... } -> self
3494 *
3495 * Like Array#sort, but returns +self+ with its elements sorted in place.
3496 *
3497 * Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
3498 */
3499
3500VALUE
3502{
3503 rb_ary_modify(ary);
3504 RUBY_ASSERT(!ARY_SHARED_P(ary));
3505 if (RARRAY_LEN(ary) > 1) {
3506 VALUE tmp = ary_make_substitution(ary); /* only ary refers tmp */
3507 struct ary_sort_data data;
3508 long len = RARRAY_LEN(ary);
3509 RBASIC_CLEAR_CLASS(tmp);
3510 data.ary = tmp;
3511 data.receiver = ary;
3512 RARRAY_PTR_USE(tmp, ptr, {
3513 ruby_qsort(ptr, len, sizeof(VALUE),
3514 rb_block_given_p()?sort_1:sort_2, &data);
3515 }); /* WB: no new reference */
3516 rb_ary_modify(ary);
3517 if (ARY_EMBED_P(tmp)) {
3518 if (ARY_SHARED_P(ary)) { /* ary might be destructively operated in the given block */
3519 rb_ary_unshare(ary);
3520 FL_SET_EMBED(ary);
3521 }
3522 if (ARY_EMBED_LEN(tmp) > ARY_CAPA(ary)) {
3523 ary_resize_capa(ary, ARY_EMBED_LEN(tmp));
3524 }
3525 ary_memcpy(ary, 0, ARY_EMBED_LEN(tmp), ARY_EMBED_PTR(tmp));
3526 ARY_SET_LEN(ary, ARY_EMBED_LEN(tmp));
3527 }
3528 else {
3529 if (!ARY_EMBED_P(ary) && ARY_HEAP_PTR(ary) == ARY_HEAP_PTR(tmp)) {
3530 FL_UNSET_SHARED(ary);
3531 ARY_SET_CAPA(ary, RARRAY_LEN(tmp));
3532 }
3533 else {
3534 RUBY_ASSERT(!ARY_SHARED_P(tmp));
3535 if (ARY_EMBED_P(ary)) {
3536 FL_UNSET_EMBED(ary);
3537 }
3538 else if (ARY_SHARED_P(ary)) {
3539 /* ary might be destructively operated in the given block */
3540 rb_ary_unshare(ary);
3541 }
3542 else {
3543 ary_heap_free(ary);
3544 }
3545 ARY_SET_PTR(ary, ARY_HEAP_PTR(tmp));
3546 ARY_SET_HEAP_LEN(ary, len);
3547 ARY_SET_CAPA(ary, ARY_HEAP_LEN(tmp));
3548 }
3549 /* tmp was lost ownership for the ptr */
3550 FL_SET_EMBED(tmp);
3551 ARY_SET_EMBED_LEN(tmp, 0);
3552 OBJ_FREEZE(tmp);
3553 }
3554 /* tmp will be GC'ed. */
3555 RBASIC_SET_CLASS_RAW(tmp, rb_cArray); /* rb_cArray must be marked */
3556 }
3557 ary_verify(ary);
3558 return ary;
3559}
3560
3561/*
3562 * call-seq:
3563 * sort -> new_array
3564 * sort {|a, b| ... } -> new_array
3565 *
3566 * Returns a new array containing the elements of +self+, sorted.
3567 *
3568 * With no block given, compares elements using operator <tt>#<=></tt>
3569 * (see Object#<=>):
3570 *
3571 * [0, 2, 3, 1].sort # => [0, 1, 2, 3]
3572 *
3573 * With a block given, calls the block with each combination of pairs of elements from +self+;
3574 * for each pair +a+ and +b+, the block should return a numeric:
3575 *
3576 * - Negative when +b+ is to follow +a+.
3577 * - Zero when +a+ and +b+ are equivalent.
3578 * - Positive when +a+ is to follow +b+.
3579 *
3580 * Example:
3581 *
3582 * a = [3, 2, 0, 1]
3583 * a.sort {|a, b| a <=> b } # => [0, 1, 2, 3]
3584 * a.sort {|a, b| b <=> a } # => [3, 2, 1, 0]
3585 *
3586 * When the block returns zero, the order for +a+ and +b+ is indeterminate,
3587 * and may be unstable.
3588 *
3589 * See an example in Numeric#nonzero? for the idiom to sort more
3590 * complex structure.
3591 *
3592 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
3593 */
3594
3595VALUE
3596rb_ary_sort(VALUE ary)
3597{
3598 ary = rb_ary_dup(ary);
3599 rb_ary_sort_bang(ary);
3600 return ary;
3601}
3602
3603static VALUE rb_ary_bsearch_index(VALUE ary);
3604
3605/*
3606 * call-seq:
3607 * bsearch {|element| ... } -> found_element or nil
3608 * bsearch -> new_enumerator
3609 *
3610 * Returns the element from +self+ found by a binary search,
3611 * or +nil+ if the search found no suitable element.
3612 *
3613 * See {Binary Searching}[rdoc-ref:language/bsearch.rdoc].
3614 *
3615 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
3616 */
3617
3618static VALUE
3619rb_ary_bsearch(VALUE ary)
3620{
3621 VALUE index_result = rb_ary_bsearch_index(ary);
3622
3623 if (FIXNUM_P(index_result)) {
3624 return rb_ary_entry(ary, FIX2LONG(index_result));
3625 }
3626 return index_result;
3627}
3628
3629/*
3630 * call-seq:
3631 * bsearch_index {|element| ... } -> integer or nil
3632 * bsearch_index -> new_enumerator
3633 *
3634 * Returns the integer index of the element from +self+ found by a binary search,
3635 * or +nil+ if the search found no suitable element.
3636 *
3637 * See {Binary Searching}[rdoc-ref:language/bsearch.rdoc].
3638 *
3639 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
3640 */
3641
3642static VALUE
3643rb_ary_bsearch_index(VALUE ary)
3644{
3645 long low = 0, high = RARRAY_LEN(ary), mid;
3646 int smaller = 0, satisfied = 0;
3647 VALUE v, val;
3648
3649 RETURN_ENUMERATOR(ary, 0, 0);
3650 while (low < high) {
3651 mid = low + ((high - low) / 2);
3652 val = rb_ary_entry(ary, mid);
3653 v = rb_yield(val);
3654 if (FIXNUM_P(v)) {
3655 if (v == INT2FIX(0)) return INT2FIX(mid);
3656 smaller = (SIGNED_VALUE)v < 0; /* Fixnum preserves its sign-bit */
3657 }
3658 else if (v == Qtrue) {
3659 satisfied = 1;
3660 smaller = 1;
3661 }
3662 else if (!RTEST(v)) {
3663 smaller = 0;
3664 }
3665 else if (rb_obj_is_kind_of(v, rb_cNumeric)) {
3666 const VALUE zero = INT2FIX(0);
3667 switch (rb_cmpint(rb_funcallv(v, id_cmp, 1, &zero), v, zero)) {
3668 case 0: return INT2FIX(mid);
3669 case 1: smaller = 0; break;
3670 case -1: smaller = 1;
3671 }
3672 }
3673 else {
3674 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE
3675 " (must be numeric, true, false or nil)",
3676 rb_obj_class(v));
3677 }
3678 if (smaller) {
3679 high = mid;
3680 }
3681 else {
3682 low = mid + 1;
3683 }
3684 }
3685 if (!satisfied) return Qnil;
3686 return INT2FIX(low);
3687}
3688
3689
3690static VALUE
3691sort_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, dummy))
3692{
3693 return rb_yield(i);
3694}
3695
3696/*
3697 * call-seq:
3698 * sort_by! {|element| ... } -> self
3699 * sort_by! -> new_enumerator
3700 *
3701 * With a block given, sorts the elements of +self+ in place;
3702 * returns self.
3703 *
3704 * Calls the block with each successive element;
3705 * sorts elements based on the values returned from the block:
3706 *
3707 * a = ['aaaa', 'bbb', 'cc', 'd']
3708 * a.sort_by! {|element| element.size }
3709 * a # => ["d", "cc", "bbb", "aaaa"]
3710 *
3711 * For duplicate values returned by the block, the ordering is indeterminate, and may be unstable.
3712 *
3713 * With no block given, returns a new Enumerator.
3714 *
3715 * Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
3716 */
3717
3718static VALUE
3719rb_ary_sort_by_bang(VALUE ary)
3720{
3721 VALUE sorted;
3722
3723 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
3724 rb_ary_modify(ary);
3725 if (RARRAY_LEN(ary) > 1) {
3726 sorted = rb_block_call(ary, rb_intern("sort_by"), 0, 0, sort_by_i, 0);
3727 rb_ary_replace(ary, sorted);
3728 }
3729 return ary;
3730}
3731
3732
3733/*
3734 * call-seq:
3735 * collect {|element| ... } -> new_array
3736 * collect -> new_enumerator
3737 * map {|element| ... } -> new_array
3738 * map -> new_enumerator
3739 *
3740 * With a block given, calls the block with each element of +self+;
3741 * returns a new array whose elements are the return values from the block:
3742 *
3743 * a = [:foo, 'bar', 2]
3744 * a1 = a.map {|element| element.class }
3745 * a1 # => [Symbol, String, Integer]
3746 *
3747 * With no block given, returns a new Enumerator.
3748 *
3749 * Related: #collect!;
3750 * see also {Methods for Converting}[rdoc-ref:Array@Methods+for+Converting].
3751 */
3752
3753static VALUE
3754rb_ary_collect(VALUE ary)
3755{
3756 long i;
3757 VALUE collect;
3758
3759 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
3760 collect = rb_ary_new2(RARRAY_LEN(ary));
3761 for (i = 0; i < RARRAY_LEN(ary); i++) {
3762 rb_ary_push(collect, rb_yield(RARRAY_AREF(ary, i)));
3763 }
3764 return collect;
3765}
3766
3767
3768/*
3769 * call-seq:
3770 * collect! {|element| ... } -> self
3771 * collect! -> new_enumerator
3772 * map! {|element| ... } -> self
3773 * map! -> new_enumerator
3774 *
3775 * With a block given, calls the block with each element of +self+
3776 * and replaces the element with the block's return value;
3777 * returns +self+:
3778 *
3779 * a = [:foo, 'bar', 2]
3780 * a.map! { |element| element.class } # => [Symbol, String, Integer]
3781 *
3782 * With no block given, returns a new Enumerator.
3783 *
3784 * Related: #collect;
3785 * see also {Methods for Converting}[rdoc-ref:Array@Methods+for+Converting].
3786 */
3787
3788static VALUE
3789rb_ary_collect_bang(VALUE ary)
3790{
3791 long i;
3792
3793 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
3794 rb_ary_modify(ary);
3795 for (i = 0; i < RARRAY_LEN(ary); i++) {
3796 rb_ary_store(ary, i, rb_yield(RARRAY_AREF(ary, i)));
3797 }
3798 return ary;
3799}
3800
3801VALUE
3802rb_get_values_at(VALUE obj, long olen, int argc, const VALUE *argv, VALUE (*func) (VALUE, long))
3803{
3804 VALUE result = rb_ary_new2(argc);
3805 long beg, len, i, j;
3806
3807 for (i=0; i<argc; i++) {
3808 if (FIXNUM_P(argv[i])) {
3809 rb_ary_push(result, (*func)(obj, FIX2LONG(argv[i])));
3810 continue;
3811 }
3812 /* check if idx is Range */
3813 if (rb_range_beg_len(argv[i], &beg, &len, olen, 1)) {
3814 long end = olen < beg+len ? olen : beg+len;
3815 for (j = beg; j < end; j++) {
3816 rb_ary_push(result, (*func)(obj, j));
3817 }
3818 if (beg + len > j)
3819 rb_ary_resize(result, RARRAY_LEN(result) + (beg + len) - j);
3820 continue;
3821 }
3822 rb_ary_push(result, (*func)(obj, NUM2LONG(argv[i])));
3823 }
3824 return result;
3825}
3826
3827static VALUE
3828append_values_at_single(VALUE result, VALUE ary, long olen, VALUE idx)
3829{
3830 long beg, len;
3831 if (FIXNUM_P(idx)) {
3832 beg = FIX2LONG(idx);
3833 }
3834 /* check if idx is Range */
3835 else if (rb_range_beg_len(idx, &beg, &len, olen, 1)) {
3836 if (len > 0) {
3837 const VALUE *const src = RARRAY_CONST_PTR(ary);
3838 const long end = beg + len;
3839 const long prevlen = RARRAY_LEN(result);
3840 if (beg < olen) {
3841 rb_ary_cat(result, src + beg, end > olen ? olen-beg : len);
3842 }
3843 if (end > olen) {
3844 rb_ary_store(result, prevlen + len - 1, Qnil);
3845 }
3846 }
3847 return result;
3848 }
3849 else {
3850 beg = NUM2LONG(idx);
3851 }
3852 return rb_ary_push(result, rb_ary_entry(ary, beg));
3853}
3854
3855/*
3856 * call-seq:
3857 * values_at(*specifiers) -> new_array
3858 *
3859 * Returns elements from +self+ in a new array; does not modify +self+.
3860 *
3861 * The objects included in the returned array are the elements of +self+
3862 * selected by the given +specifiers+,
3863 * each of which must be a numeric index or a Range.
3864 *
3865 * In brief:
3866 *
3867 * a = ['a', 'b', 'c', 'd']
3868 *
3869 * # Index specifiers.
3870 * a.values_at(2, 0, 2, 0) # => ["c", "a", "c", "a"] # May repeat.
3871 * a.values_at(-4, -3, -2, -1) # => ["a", "b", "c", "d"] # Counts backwards if negative.
3872 * a.values_at(-50, 50) # => [nil, nil] # Outside of self.
3873 *
3874 * # Range specifiers.
3875 * a.values_at(1..3) # => ["b", "c", "d"] # From range.begin to range.end.
3876 * a.values_at(1...3) # => ["b", "c"] # End excluded.
3877 * a.values_at(3..1) # => [] # No such elements.
3878 *
3879 * a.values_at(-3..3) # => ["b", "c", "d"] # Negative range.begin counts backwards.
3880 * a.values_at(-50..3) # Raises RangeError.
3881 *
3882 * a.values_at(1..-2) # => ["b", "c"] # Negative range.end counts backwards.
3883 * a.values_at(1..-50) # => [] # No such elements.
3884 *
3885 * # Mixture of specifiers.
3886 * a.values_at(2..3, 3, 0..1, 0) # => ["c", "d", "d", "a", "b", "a"]
3887 *
3888 * With no +specifiers+ given, returns a new empty array:
3889 *
3890 * a = ['a', 'b', 'c', 'd']
3891 * a.values_at # => []
3892 *
3893 * For each numeric specifier +index+, includes an element:
3894 *
3895 * - For each non-negative numeric specifier +index+ that is in-range (less than <tt>self.size</tt>),
3896 * includes the element at offset +index+:
3897 *
3898 * a.values_at(0, 2) # => ["a", "c"]
3899 * a.values_at(0.1, 2.9) # => ["a", "c"]
3900 *
3901 * - For each negative numeric +index+ that is in-range (greater than or equal to <tt>- self.size</tt>),
3902 * counts backwards from the end of +self+:
3903 *
3904 * a.values_at(-1, -4) # => ["d", "a"]
3905 *
3906 * The given indexes may be in any order, and may repeat:
3907 *
3908 * a.values_at(2, 0, 1, 0, 2) # => ["c", "a", "b", "a", "c"]
3909 *
3910 * For each +index+ that is out-of-range, includes +nil+:
3911 *
3912 * a.values_at(4, -5) # => [nil, nil]
3913 *
3914 * For each Range specifier +range+, includes elements
3915 * according to <tt>range.begin</tt> and <tt>range.end</tt>:
3916 *
3917 * - If both <tt>range.begin</tt> and <tt>range.end</tt>
3918 * are non-negative and in-range (less than <tt>self.size</tt>),
3919 * includes elements from index <tt>range.begin</tt>
3920 * through <tt>range.end - 1</tt> (if <tt>range.exclude_end?</tt>),
3921 * or through <tt>range.end</tt> (otherwise):
3922 *
3923 * a.values_at(1..2) # => ["b", "c"]
3924 * a.values_at(1...2) # => ["b"]
3925 *
3926 * - If <tt>range.begin</tt> is negative and in-range (greater than or equal to <tt>- self.size</tt>),
3927 * counts backwards from the end of +self+:
3928 *
3929 * a.values_at(-2..3) # => ["c", "d"]
3930 *
3931 * - If <tt>range.begin</tt> is negative and out-of-range, raises an exception:
3932 *
3933 * a.values_at(-5..3) # Raises RangeError.
3934 *
3935 * - If <tt>range.end</tt> is positive and out-of-range,
3936 * extends the returned array with +nil+ elements:
3937 *
3938 * a.values_at(1..5) # => ["b", "c", "d", nil, nil]
3939 *
3940 * - If <tt>range.end</tt> is negative and in-range,
3941 * counts backwards from the end of +self+:
3942 *
3943 * a.values_at(1..-2) # => ["b", "c"]
3944 *
3945 * - If <tt>range.end</tt> is negative and out-of-range,
3946 * returns an empty array:
3947 *
3948 * a.values_at(1..-5) # => []
3949 *
3950 * The given ranges may be in any order and may repeat:
3951 *
3952 * a.values_at(2..3, 0..1, 2..3) # => ["c", "d", "a", "b", "c", "d"]
3953 *
3954 * The given specifiers may be any mixture of indexes and ranges:
3955 *
3956 * a.values_at(3, 1..2, 0, 2..3) # => ["d", "b", "c", "a", "c", "d"]
3957 *
3958 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
3959 */
3960
3961static VALUE
3962rb_ary_values_at(int argc, VALUE *argv, VALUE ary)
3963{
3964 long i, olen = RARRAY_LEN(ary);
3965 VALUE result = rb_ary_new_capa(argc);
3966 for (i = 0; i < argc; ++i) {
3967 append_values_at_single(result, ary, olen, argv[i]);
3968 }
3969 RB_GC_GUARD(ary);
3970 return result;
3971}
3972
3973
3974/*
3975 * call-seq:
3976 * select {|element| ... } -> new_array
3977 * select -> new_enumerator
3978 * filter {|element| ... } -> new_array
3979 * filter -> new_enumerator
3980 *
3981 * With a block given, calls the block with each element of +self+;
3982 * returns a new array containing those elements of +self+
3983 * for which the block returns a truthy value:
3984 *
3985 * a = [:foo, 'bar', 2, :bam]
3986 * a.select {|element| element.to_s.start_with?('b') }
3987 * # => ["bar", :bam]
3988 *
3989 * With no block given, returns a new Enumerator.
3990 *
3991 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
3992 */
3993
3994static VALUE
3995rb_ary_select(VALUE ary)
3996{
3997 VALUE result;
3998 long i;
3999
4000 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
4001 result = rb_ary_new2(RARRAY_LEN(ary));
4002 for (i = 0; i < RARRAY_LEN(ary); i++) {
4003 if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) {
4004 rb_ary_push(result, rb_ary_elt(ary, i));
4005 }
4006 }
4007 return result;
4008}
4009
4010struct select_bang_arg {
4011 VALUE ary;
4012 long len[2];
4013};
4014
4015static VALUE
4016select_bang_i(VALUE a)
4017{
4018 volatile struct select_bang_arg *arg = (void *)a;
4019 VALUE ary = arg->ary;
4020 long i1, i2;
4021
4022 for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); arg->len[0] = ++i1) {
4023 VALUE v = RARRAY_AREF(ary, i1);
4024 if (!RTEST(rb_yield(v))) continue;
4025 if (i1 != i2) {
4026 rb_ary_store(ary, i2, v);
4027 }
4028 arg->len[1] = ++i2;
4029 }
4030 return (i1 == i2) ? Qnil : ary;
4031}
4032
4033static VALUE
4034select_bang_ensure(VALUE a)
4035{
4036 volatile struct select_bang_arg *arg = (void *)a;
4037 VALUE ary = arg->ary;
4038 long len = RARRAY_LEN(ary);
4039 long i1 = arg->len[0], i2 = arg->len[1];
4040
4041 if (i2 < len && i2 < i1) {
4042 long tail = 0;
4043 rb_ary_modify(ary);
4044 if (i1 < len) {
4045 tail = len - i1;
4046 RARRAY_PTR_USE(ary, ptr, {
4047 MEMMOVE(ptr + i2, ptr + i1, VALUE, tail);
4048 });
4049 }
4050 ARY_SET_LEN(ary, i2 + tail);
4051 }
4052 return ary;
4053}
4054
4055/*
4056 * call-seq:
4057 * select! {|element| ... } -> self or nil
4058 * select! -> new_enumerator
4059 * filter! {|element| ... } -> self or nil
4060 * filter! -> new_enumerator
4061 *
4062 * With a block given, calls the block with each element of +self+;
4063 * removes from +self+ those elements for which the block returns +false+ or +nil+.
4064 *
4065 * Returns +self+ if any elements were removed:
4066 *
4067 * a = [:foo, 'bar', 2, :bam]
4068 * a.select! {|element| element.to_s.start_with?('b') } # => ["bar", :bam]
4069 *
4070 * Returns +nil+ if no elements were removed.
4071 *
4072 * With no block given, returns a new Enumerator.
4073 *
4074 * Related: see {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
4075 */
4076
4077static VALUE
4078rb_ary_select_bang(VALUE ary)
4079{
4080 struct select_bang_arg args;
4081
4082 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
4083 rb_ary_modify(ary);
4084
4085 args.ary = ary;
4086 args.len[0] = args.len[1] = 0;
4087 return rb_ensure(select_bang_i, (VALUE)&args, select_bang_ensure, (VALUE)&args);
4088}
4089
4090/*
4091 * call-seq:
4092 * keep_if {|element| ... } -> self
4093 * keep_if -> new_enumerator
4094 *
4095 * With a block given, calls the block with each element of +self+;
4096 * removes the element from +self+ if the block does not return a truthy value:
4097 *
4098 * a = [:foo, 'bar', 2, :bam]
4099 * a.keep_if {|element| element.to_s.start_with?('b') } # => ["bar", :bam]
4100 *
4101 * With no block given, returns a new Enumerator.
4102 *
4103 * Related: see {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
4104 */
4105
4106static VALUE
4107rb_ary_keep_if(VALUE ary)
4108{
4109 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
4110 rb_ary_select_bang(ary);
4111 return ary;
4112}
4113
4114static void
4115ary_resize_smaller(VALUE ary, long len)
4116{
4117 rb_ary_modify(ary);
4118 if (RARRAY_LEN(ary) > len) {
4119 ARY_SET_LEN(ary, len);
4120 if (len * 2 < ARY_CAPA(ary) &&
4121 ARY_CAPA(ary) > ARY_DEFAULT_SIZE) {
4122 ary_resize_capa(ary, len * 2);
4123 }
4124 }
4125}
4126
4127/*
4128 * call-seq:
4129 * delete(object) -> last_removed_object
4130 * delete(object) {|element| ... } -> last_removed_object or block_return
4131 *
4132 * Removes zero or more elements from +self+.
4133 *
4134 * With no block given,
4135 * removes from +self+ each element +ele+ such that <tt>ele == object</tt>;
4136 * returns the last removed element:
4137 *
4138 * a = [0, 1, 2, 2.0]
4139 * a.delete(2) # => 2.0
4140 * a # => [0, 1]
4141 *
4142 * Returns +nil+ if no elements removed:
4143 *
4144 * a.delete(2) # => nil
4145 *
4146 * With a block given,
4147 * removes from +self+ each element +ele+ such that <tt>ele == object</tt>.
4148 *
4149 * If any such elements are found, ignores the block
4150 * and returns the last removed element:
4151 *
4152 * a = [0, 1, 2, 2.0]
4153 * a.delete(2) {|element| fail 'Cannot happen' } # => 2.0
4154 * a # => [0, 1]
4155 *
4156 * If no such element is found, returns the block's return value:
4157 *
4158 * a.delete(2) {|element| "Element #{element} not found." }
4159 * # => "Element 2 not found."
4160 *
4161 * Related: see {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
4162 */
4163
4164VALUE
4165rb_ary_delete(VALUE ary, VALUE item)
4166{
4167 VALUE v = item;
4168 long i1, i2;
4169
4170 for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) {
4171 VALUE e = RARRAY_AREF(ary, i1);
4172
4173 if (rb_equal(e, item)) {
4174 v = e;
4175 continue;
4176 }
4177 if (i1 != i2) {
4178 rb_ary_store(ary, i2, e);
4179 }
4180 i2++;
4181 }
4182 if (RARRAY_LEN(ary) == i2) {
4183 if (rb_block_given_p()) {
4184 return rb_yield(item);
4185 }
4186 return Qnil;
4187 }
4188
4189 ary_resize_smaller(ary, i2);
4190
4191 ary_verify(ary);
4192 return v;
4193}
4194
4195void
4196rb_ary_delete_same(VALUE ary, VALUE item)
4197{
4198 long i1, i2;
4199
4200 for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) {
4201 VALUE e = RARRAY_AREF(ary, i1);
4202
4203 if (e == item) {
4204 continue;
4205 }
4206 if (i1 != i2) {
4207 rb_ary_store(ary, i2, e);
4208 }
4209 i2++;
4210 }
4211 if (RARRAY_LEN(ary) == i2) {
4212 return;
4213 }
4214
4215 ary_resize_smaller(ary, i2);
4216}
4217
4218VALUE
4219rb_ary_delete_at(VALUE ary, long pos)
4220{
4221 long len = RARRAY_LEN(ary);
4222 VALUE del;
4223
4224 if (pos >= len) return Qnil;
4225 if (pos < 0) {
4226 pos += len;
4227 if (pos < 0) return Qnil;
4228 }
4229
4230 rb_ary_modify(ary);
4231 del = RARRAY_AREF(ary, pos);
4232 RARRAY_PTR_USE(ary, ptr, {
4233 MEMMOVE(ptr+pos, ptr+pos+1, VALUE, len-pos-1);
4234 });
4235 ARY_INCREASE_LEN(ary, -1);
4236 ary_verify(ary);
4237 return del;
4238}
4239
4240/*
4241 * call-seq:
4242 * delete_at(index) -> removed_object or nil
4243 *
4244 * Removes the element of +self+ at the given +index+, which must be an
4245 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
4246 *
4247 * When +index+ is non-negative, deletes the element at offset +index+:
4248 *
4249 * a = [:foo, 'bar', 2]
4250 * a.delete_at(1) # => "bar"
4251 * a # => [:foo, 2]
4252 *
4253 * When +index+ is negative, counts backward from the end of the array:
4254 *
4255 * a = [:foo, 'bar', 2]
4256 * a.delete_at(-2) # => "bar"
4257 * a # => [:foo, 2]
4258 *
4259 * When +index+ is out of range, returns +nil+.
4260 *
4261 * a = [:foo, 'bar', 2]
4262 * a.delete_at(3) # => nil
4263 * a.delete_at(-4) # => nil
4264 *
4265 * Related: see {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
4266 */
4267
4268static VALUE
4269rb_ary_delete_at_m(VALUE ary, VALUE pos)
4270{
4271 return rb_ary_delete_at(ary, NUM2LONG(pos));
4272}
4273
4274static VALUE
4275ary_slice_bang_by_rb_ary_splice(VALUE ary, long pos, long len)
4276{
4277 const long orig_len = RARRAY_LEN(ary);
4278
4279 if (len < 0) {
4280 return Qnil;
4281 }
4282 else if (pos < -orig_len) {
4283 return Qnil;
4284 }
4285 else if (pos < 0) {
4286 pos += orig_len;
4287 }
4288 else if (orig_len < pos) {
4289 return Qnil;
4290 }
4291 if (orig_len < pos + len) {
4292 len = orig_len - pos;
4293 }
4294 if (len == 0) {
4295 return rb_ary_new2(0);
4296 }
4297 else {
4298 VALUE arg2 = rb_ary_new4(len, RARRAY_CONST_PTR(ary)+pos);
4299 rb_ary_splice(ary, pos, len, 0, 0, FALSE);
4300 return arg2;
4301 }
4302}
4303
4304/*
4305 * call-seq:
4306 * slice!(index) -> object or nil
4307 * slice!(start, length) -> new_array or nil
4308 * slice!(range) -> new_array or nil
4309 *
4310 * Removes and returns elements from +self+.
4311 *
4312 * With numeric argument +index+ given,
4313 * removes and returns the element at offset +index+:
4314 *
4315 * a = ['a', 'b', 'c', 'd']
4316 * a.slice!(2) # => "c"
4317 * a # => ["a", "b", "d"]
4318 * a.slice!(2.1) # => "d"
4319 * a # => ["a", "b"]
4320 *
4321 * If +index+ is negative, counts backwards from the end of +self+:
4322 *
4323 * a = ['a', 'b', 'c', 'd']
4324 * a.slice!(-2) # => "c"
4325 * a # => ["a", "b", "d"]
4326 *
4327 * If +index+ is out of range, returns +nil+.
4328 *
4329 * With numeric arguments +start+ and +length+ given,
4330 * removes +length+ elements from +self+ beginning at zero-based offset +start+;
4331 * returns the removed objects in a new array:
4332 *
4333 * a = ['a', 'b', 'c', 'd']
4334 * a.slice!(1, 2) # => ["b", "c"]
4335 * a # => ["a", "d"]
4336 * a.slice!(0.1, 1.1) # => ["a"]
4337 * a # => ["d"]
4338 *
4339 * If +start+ is negative, counts backwards from the end of +self+:
4340 *
4341 * a = ['a', 'b', 'c', 'd']
4342 * a.slice!(-2, 1) # => ["c"]
4343 * a # => ["a", "b", "d"]
4344 *
4345 * If +start+ is out-of-range, returns +nil+:
4346 *
4347 * a = ['a', 'b', 'c', 'd']
4348 * a.slice!(5, 1) # => nil
4349 * a.slice!(-5, 1) # => nil
4350 *
4351 * If <tt>start + length</tt> exceeds the array size,
4352 * removes and returns all elements from offset +start+ to the end:
4353 *
4354 * a = ['a', 'b', 'c', 'd']
4355 * a.slice!(2, 50) # => ["c", "d"]
4356 * a # => ["a", "b"]
4357 *
4358 * If <tt>start == a.size</tt> and +length+ is non-negative,
4359 * returns a new empty array.
4360 *
4361 * If +length+ is negative, returns +nil+.
4362 *
4363 * With Range argument +range+ given,
4364 * treats <tt>range.min</tt> as +start+ (as above)
4365 * and <tt>range.size</tt> as +length+ (as above):
4366 *
4367 * a = ['a', 'b', 'c', 'd']
4368 * a.slice!(1..2) # => ["b", "c"]
4369 * a # => ["a", "d"]
4370 *
4371 * If <tt>range.start == a.size</tt>, returns a new empty array:
4372 *
4373 * a = ['a', 'b', 'c', 'd']
4374 * a.slice!(4..5) # => []
4375 *
4376 * If <tt>range.start</tt> is larger than the array size, returns +nil+:
4377 *
4378 * a = ['a', 'b', 'c', 'd']
4379 a.slice!(5..6) # => nil
4380 *
4381 * If <tt>range.start</tt> is negative,
4382 * calculates the start index by counting backwards from the end of +self+:
4383 *
4384 * a = ['a', 'b', 'c', 'd']
4385 * a.slice!(-2..2) # => ["c"]
4386 *
4387 * If <tt>range.end</tt> is negative,
4388 * calculates the end index by counting backwards from the end of +self+:
4389 *
4390 * a = ['a', 'b', 'c', 'd']
4391 * a.slice!(0..-2) # => ["a", "b", "c"]
4392 *
4393 * Related: see {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
4394 */
4395
4396static VALUE
4397rb_ary_slice_bang(int argc, VALUE *argv, VALUE ary)
4398{
4399 VALUE arg1;
4400 long pos, len;
4401
4402 rb_ary_modify_check(ary);
4403 rb_check_arity(argc, 1, 2);
4404 arg1 = argv[0];
4405
4406 if (argc == 2) {
4407 pos = NUM2LONG(argv[0]);
4408 len = NUM2LONG(argv[1]);
4409 return ary_slice_bang_by_rb_ary_splice(ary, pos, len);
4410 }
4411
4412 if (!FIXNUM_P(arg1)) {
4413 switch (rb_range_beg_len(arg1, &pos, &len, RARRAY_LEN(ary), 0)) {
4414 case Qtrue:
4415 /* valid range */
4416 return ary_slice_bang_by_rb_ary_splice(ary, pos, len);
4417 case Qnil:
4418 /* invalid range */
4419 return Qnil;
4420 default:
4421 /* not a range */
4422 break;
4423 }
4424 }
4425
4426 return rb_ary_delete_at(ary, NUM2LONG(arg1));
4427}
4428
4429static VALUE
4430ary_reject(VALUE orig, VALUE result)
4431{
4432 long i;
4433
4434 for (i = 0; i < RARRAY_LEN(orig); i++) {
4435 VALUE v = RARRAY_AREF(orig, i);
4436
4437 if (!RTEST(rb_yield(v))) {
4438 rb_ary_push(result, v);
4439 }
4440 }
4441 return result;
4442}
4443
4444static VALUE
4445reject_bang_i(VALUE a)
4446{
4447 volatile struct select_bang_arg *arg = (void *)a;
4448 VALUE ary = arg->ary;
4449 long i1, i2;
4450
4451 for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); arg->len[0] = ++i1) {
4452 VALUE v = RARRAY_AREF(ary, i1);
4453 if (RTEST(rb_yield(v))) continue;
4454 if (i1 != i2) {
4455 rb_ary_store(ary, i2, v);
4456 }
4457 arg->len[1] = ++i2;
4458 }
4459 return (i1 == i2) ? Qnil : ary;
4460}
4461
4462static VALUE
4463ary_reject_bang(VALUE ary)
4464{
4465 struct select_bang_arg args;
4466 rb_ary_modify_check(ary);
4467 args.ary = ary;
4468 args.len[0] = args.len[1] = 0;
4469 return rb_ensure(reject_bang_i, (VALUE)&args, select_bang_ensure, (VALUE)&args);
4470}
4471
4472/*
4473 * call-seq:
4474 * reject! {|element| ... } -> self or nil
4475 * reject! -> new_enumerator
4476 *
4477 * With a block given, calls the block with each element of +self+;
4478 * removes each element for which the block returns a truthy value.
4479 *
4480 * Returns +self+ if any elements removed:
4481 *
4482 * a = [:foo, 'bar', 2, 'bat']
4483 * a.reject! {|element| element.to_s.start_with?('b') } # => [:foo, 2]
4484 *
4485 * Returns +nil+ if no elements removed.
4486 *
4487 * With no block given, returns a new Enumerator.
4488 *
4489 * Related: see {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
4490 */
4491
4492static VALUE
4493rb_ary_reject_bang(VALUE ary)
4494{
4495 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
4496 rb_ary_modify(ary);
4497 return ary_reject_bang(ary);
4498}
4499
4500/*
4501 * call-seq:
4502 * reject {|element| ... } -> new_array
4503 * reject -> new_enumerator
4504 *
4505 * With a block given, returns a new array whose elements are all those from +self+
4506 * for which the block returns +false+ or +nil+:
4507 *
4508 * a = [:foo, 'bar', 2, 'bat']
4509 * a1 = a.reject {|element| element.to_s.start_with?('b') }
4510 * a1 # => [:foo, 2]
4511 *
4512 * With no block given, returns a new Enumerator.
4513 *
4514 * Related: {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
4515 */
4516
4517static VALUE
4518rb_ary_reject(VALUE ary)
4519{
4520 VALUE rejected_ary;
4521
4522 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
4523 rejected_ary = rb_ary_new();
4524 ary_reject(ary, rejected_ary);
4525 return rejected_ary;
4526}
4527
4528/*
4529 * call-seq:
4530 * delete_if {|element| ... } -> self
4531 * delete_if -> new_numerator
4532 *
4533 * With a block given, calls the block with each element of +self+;
4534 * removes the element if the block returns a truthy value;
4535 * returns +self+:
4536 *
4537 * a = [:foo, 'bar', 2, 'bat']
4538 * a.delete_if {|element| element.to_s.start_with?('b') } # => [:foo, 2]
4539 *
4540 * With no block given, returns a new Enumerator.
4541 *
4542 * Related: see {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
4543 */
4544
4545static VALUE
4546rb_ary_delete_if(VALUE ary)
4547{
4548 ary_verify(ary);
4549 RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
4550 ary_reject_bang(ary);
4551 return ary;
4552}
4553
4554static VALUE
4555take_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, cbarg))
4556{
4557 VALUE *args = (VALUE *)cbarg;
4558 if (argc > 1) val = rb_ary_new4(argc, argv);
4559 rb_ary_push(args[0], val);
4560 if (--args[1] == 0) rb_iter_break();
4561 return Qnil;
4562}
4563
4564static VALUE
4565take_items(VALUE obj, long n)
4566{
4567 VALUE result = rb_check_array_type(obj);
4568 VALUE args[2];
4569
4570 if (n == 0) return result;
4571 if (!NIL_P(result)) return rb_ary_subseq(result, 0, n);
4572 result = rb_ary_new2(n);
4573 args[0] = result; args[1] = (VALUE)n;
4574 if (UNDEF_P(rb_check_block_call(obj, idEach, 0, 0, take_i, (VALUE)args)))
4575 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (must respond to :each)",
4576 rb_obj_class(obj));
4577 return result;
4578}
4579
4580
4581/*
4582 * call-seq:
4583 * zip(*other_arrays) -> new_array
4584 * zip(*other_arrays) {|sub_array| ... } -> nil
4585 *
4586 * With no block given, combines +self+ with the collection of +other_arrays+;
4587 * returns a new array of sub-arrays:
4588 *
4589 * [0, 1].zip(['zero', 'one'], [:zero, :one])
4590 * # => [[0, "zero", :zero], [1, "one", :one]]
4591 *
4592 * Returned:
4593 *
4594 * - The outer array is of size <tt>self.size</tt>.
4595 * - Each sub-array is of size <tt>other_arrays.size + 1</tt>.
4596 * - The _nth_ sub-array contains (in order):
4597 *
4598 * - The _nth_ element of +self+.
4599 * - The _nth_ element of each of the other arrays, as available.
4600 *
4601 * Example:
4602 *
4603 * a = [0, 1]
4604 * zipped = a.zip(['zero', 'one'], [:zero, :one])
4605 * # => [[0, "zero", :zero], [1, "one", :one]]
4606 * zipped.size # => 2 # Same size as a.
4607 * zipped.first.size # => 3 # Size of other arrays plus 1.
4608 *
4609 * When the other arrays are all the same size as +self+,
4610 * the returned sub-arrays are a rearrangement containing exactly elements of all the arrays
4611 * (including +self+), with no omissions or additions:
4612 *
4613 * a = [:a0, :a1, :a2, :a3]
4614 * b = [:b0, :b1, :b2, :b3]
4615 * c = [:c0, :c1, :c2, :c3]
4616 * d = a.zip(b, c)
4617 * pp d
4618 * # =>
4619 * [[:a0, :b0, :c0],
4620 * [:a1, :b1, :c1],
4621 * [:a2, :b2, :c2],
4622 * [:a3, :b3, :c3]]
4623 *
4624 * When one of the other arrays is smaller than +self+,
4625 * pads the corresponding sub-array with +nil+ elements:
4626 *
4627 * a = [:a0, :a1, :a2, :a3]
4628 * b = [:b0, :b1, :b2]
4629 * c = [:c0, :c1]
4630 * d = a.zip(b, c)
4631 * pp d
4632 * # =>
4633 * [[:a0, :b0, :c0],
4634 * [:a1, :b1, :c1],
4635 * [:a2, :b2, nil],
4636 * [:a3, nil, nil]]
4637 *
4638 * When one of the other arrays is larger than +self+,
4639 * _ignores_ its trailing elements:
4640 *
4641 * a = [:a0, :a1, :a2, :a3]
4642 * b = [:b0, :b1, :b2, :b3, :b4]
4643 * c = [:c0, :c1, :c2, :c3, :c4, :c5]
4644 * d = a.zip(b, c)
4645 * pp d
4646 * # =>
4647 * [[:a0, :b0, :c0],
4648 * [:a1, :b1, :c1],
4649 * [:a2, :b2, :c2],
4650 * [:a3, :b3, :c3]]
4651 *
4652 * With a block given, calls the block with each of the other arrays;
4653 * returns +nil+:
4654 *
4655 * d = []
4656 * a = [:a0, :a1, :a2, :a3]
4657 * b = [:b0, :b1, :b2, :b3]
4658 * c = [:c0, :c1, :c2, :c3]
4659 * a.zip(b, c) {|sub_array| d.push(sub_array.reverse) } # => nil
4660 * pp d
4661 * # =>
4662 * [[:c0, :b0, :a0],
4663 * [:c1, :b1, :a1],
4664 * [:c2, :b2, :a2],
4665 * [:c3, :b3, :a3]]
4666 *
4667 * For an *object* in *other_arrays* that is not actually an array,
4668 * forms the "other array" as <tt>object.to_ary</tt>, if defined,
4669 * or as <tt>object.each.to_a</tt> otherwise.
4670 *
4671 * Related: see {Methods for Converting}[rdoc-ref:Array@Methods+for+Converting].
4672 */
4673
4674static VALUE
4675rb_ary_zip(int argc, VALUE *argv, VALUE ary)
4676{
4677 int i, j;
4678 long len = RARRAY_LEN(ary);
4679 VALUE result = Qnil;
4680
4681 for (i=0; i<argc; i++) {
4682 argv[i] = take_items(argv[i], len);
4683 }
4684
4685 if (rb_block_given_p()) {
4686 int arity = rb_block_arity();
4687
4688 if (arity > 1) {
4689 VALUE work, *tmp;
4690
4691 tmp = ALLOCV_N(VALUE, work, argc+1);
4692
4693 for (i=0; i<RARRAY_LEN(ary); i++) {
4694 tmp[0] = RARRAY_AREF(ary, i);
4695 for (j=0; j<argc; j++) {
4696 tmp[j+1] = rb_ary_elt(argv[j], i);
4697 }
4698 rb_yield_values2(argc+1, tmp);
4699 }
4700
4701 if (work) ALLOCV_END(work);
4702 }
4703 else {
4704 for (i=0; i<RARRAY_LEN(ary); i++) {
4705 VALUE tmp = rb_ary_new2(argc+1);
4706
4707 rb_ary_push(tmp, RARRAY_AREF(ary, i));
4708 for (j=0; j<argc; j++) {
4709 rb_ary_push(tmp, rb_ary_elt(argv[j], i));
4710 }
4711 rb_yield(tmp);
4712 }
4713 }
4714 }
4715 else {
4716 result = rb_ary_new_capa(len);
4717
4718 for (i=0; i<len; i++) {
4719 VALUE tmp = rb_ary_new_capa(argc+1);
4720
4721 rb_ary_push(tmp, RARRAY_AREF(ary, i));
4722 for (j=0; j<argc; j++) {
4723 rb_ary_push(tmp, rb_ary_elt(argv[j], i));
4724 }
4725 rb_ary_push(result, tmp);
4726 }
4727 }
4728
4729 return result;
4730}
4731
4732/*
4733 * call-seq:
4734 * transpose -> new_array
4735 *
4736 * Returns a new array that is +self+
4737 * as a {transposed matrix}[https://en.wikipedia.org/wiki/Transpose]:
4738 *
4739 * a = [[:a0, :a1], [:b0, :b1], [:c0, :c1]]
4740 * a.transpose # => [[:a0, :b0, :c0], [:a1, :b1, :c1]]
4741 *
4742 * The elements of +self+ must all be the same size.
4743 *
4744 * Related: see {Methods for Converting}[rdoc-ref:Array@Methods+for+Converting].
4745 */
4746
4747static VALUE
4748rb_ary_transpose(VALUE ary)
4749{
4750 long elen = -1, alen, i, j;
4751 VALUE tmp, result = 0;
4752
4753 alen = RARRAY_LEN(ary);
4754 if (alen == 0) return rb_ary_dup(ary);
4755 for (i=0; i<alen; i++) {
4756 tmp = to_ary(rb_ary_elt(ary, i));
4757 if (elen < 0) { /* first element */
4758 elen = RARRAY_LEN(tmp);
4759 result = rb_ary_new2(elen);
4760 for (j=0; j<elen; j++) {
4761 rb_ary_store(result, j, rb_ary_new2(alen));
4762 }
4763 }
4764 else if (elen != RARRAY_LEN(tmp)) {
4765 rb_raise(rb_eIndexError, "element size differs (%ld should be %ld)",
4766 RARRAY_LEN(tmp), elen);
4767 }
4768 for (j=0; j<elen; j++) {
4769 rb_ary_store(rb_ary_elt(result, j), i, rb_ary_elt(tmp, j));
4770 }
4771 }
4772 return result;
4773}
4774
4775/*
4776 * call-seq:
4777 * initialize_copy(other_array) -> self
4778 * replace(other_array) -> self
4779 *
4780 * Replaces the elements of +self+ with the elements of +other_array+, which must be an
4781 * {array-convertible object}[rdoc-ref:implicit_conversion.rdoc@Array-Convertible+Objects];
4782 * returns +self+:
4783 *
4784 * a = ['a', 'b', 'c'] # => ["a", "b", "c"]
4785 * a.replace(['d', 'e']) # => ["d", "e"]
4786 *
4787 * Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
4788 */
4789
4790VALUE
4791rb_ary_replace(VALUE copy, VALUE orig)
4792{
4793 rb_ary_modify_check(copy);
4794 orig = to_ary(orig);
4795 if (copy == orig) return copy;
4796
4797 rb_ary_reset(copy);
4798
4799 /* orig has enough space to embed the contents of orig. */
4800 if (RARRAY_LEN(orig) <= ary_embed_capa(copy)) {
4801 RUBY_ASSERT(ARY_EMBED_P(copy));
4802 ary_memcpy(copy, 0, RARRAY_LEN(orig), RARRAY_CONST_PTR(orig));
4803 ARY_SET_EMBED_LEN(copy, RARRAY_LEN(orig));
4804 }
4805 /* orig is embedded but copy does not have enough space to embed the
4806 * contents of orig. */
4807 else if (ARY_EMBED_P(orig)) {
4808 long len = ARY_EMBED_LEN(orig);
4809 VALUE *ptr = ary_heap_alloc_buffer(len);
4810
4811 FL_UNSET_EMBED(copy);
4812 ARY_SET_PTR(copy, ptr);
4813 ARY_SET_LEN(copy, len);
4814 ARY_SET_CAPA(copy, len);
4815
4816 // No allocation and exception expected that could leave `copy` in a
4817 // bad state from the edits above.
4818 ary_memcpy(copy, 0, len, RARRAY_CONST_PTR(orig));
4819 }
4820 /* Otherwise, orig is on heap and copy does not have enough space to embed
4821 * the contents of orig. */
4822 else {
4823 VALUE shared_root = ary_make_shared(orig);
4824 FL_UNSET_EMBED(copy);
4825 ARY_SET_PTR(copy, ARY_HEAP_PTR(orig));
4826 ARY_SET_LEN(copy, ARY_HEAP_LEN(orig));
4827 rb_ary_set_shared(copy, shared_root);
4828
4829 RUBY_ASSERT(RB_OBJ_SHAREABLE_P(copy) ? RB_OBJ_SHAREABLE_P(shared_root) : 1);
4830 }
4831 ary_verify(copy);
4832 return copy;
4833}
4834
4835/*
4836 * call-seq:
4837 * clear -> self
4838 *
4839 * Removes all elements from +self+; returns +self+:
4840 *
4841 * a = [:foo, 'bar', 2]
4842 * a.clear # => []
4843 *
4844 * Related: see {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
4845 */
4846
4847VALUE
4849{
4850 rb_ary_modify_check(ary);
4851 if (ARY_SHARED_P(ary)) {
4852 rb_ary_unshare(ary);
4853 FL_SET_EMBED(ary);
4854 ARY_SET_EMBED_LEN(ary, 0);
4855 }
4856 else {
4857 ARY_SET_LEN(ary, 0);
4858 if (ARY_DEFAULT_SIZE * 2 < ARY_CAPA(ary)) {
4859 ary_resize_capa(ary, ARY_DEFAULT_SIZE * 2);
4860 }
4861 }
4862 ary_verify(ary);
4863 return ary;
4864}
4865
4866/*
4867 * call-seq:
4868 * fill(object, start = nil, count = nil) -> self
4869 * fill(object, range) -> self
4870 * fill(start = nil, count = nil) {|element| ... } -> self
4871 * fill(range) {|element| ... } -> self
4872 *
4873 * Replaces selected elements in +self+;
4874 * may add elements to +self+;
4875 * always returns +self+ (never a new array).
4876 *
4877 * In brief:
4878 *
4879 * # Non-negative start.
4880 * ['a', 'b', 'c', 'd'].fill('-', 1, 2) # => ["a", "-", "-", "d"]
4881 * ['a', 'b', 'c', 'd'].fill(1, 2) {|e| e.to_s } # => ["a", "1", "2", "d"]
4882 *
4883 * # Extends with specified values if necessary.
4884 * ['a', 'b', 'c', 'd'].fill('-', 3, 2) # => ["a", "b", "c", "-", "-"]
4885 * ['a', 'b', 'c', 'd'].fill(3, 2) {|e| e.to_s } # => ["a", "b", "c", "3", "4"]
4886 *
4887 * # Fills with nils if necessary.
4888 * ['a', 'b', 'c', 'd'].fill('-', 6, 2) # => ["a", "b", "c", "d", nil, nil, "-", "-"]
4889 * ['a', 'b', 'c', 'd'].fill(6, 2) {|e| e.to_s } # => ["a", "b", "c", "d", nil, nil, "6", "7"]
4890 *
4891 * # For negative start, counts backwards from the end.
4892 * ['a', 'b', 'c', 'd'].fill('-', -3, 3) # => ["a", "-", "-", "-"]
4893 * ['a', 'b', 'c', 'd'].fill(-3, 3) {|e| e.to_s } # => ["a", "1", "2", "3"]
4894 *
4895 * # Range.
4896 * ['a', 'b', 'c', 'd'].fill('-', 1..2) # => ["a", "-", "-", "d"]
4897 * ['a', 'b', 'c', 'd'].fill(1..2) {|e| e.to_s } # => ["a", "1", "2", "d"]
4898 *
4899 * When arguments +start+ and +count+ are given,
4900 * they select the elements of +self+ to be replaced;
4901 * each must be an
4902 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects]
4903 * (or +nil+):
4904 *
4905 * - +start+ specifies the zero-based offset of the first element to be replaced;
4906 * +nil+ means zero.
4907 * - +count+ is the number of consecutive elements to be replaced;
4908 * +nil+ means "all the rest."
4909 *
4910 * With argument +object+ given,
4911 * that one object is used for all replacements:
4912 *
4913 * o = Object.new # => #<Object:0x0000014e7bff7600>
4914 * a = ['a', 'b', 'c', 'd'] # => ["a", "b", "c", "d"]
4915 * a.fill(o, 1, 2)
4916 * # => ["a", #<Object:0x0000014e7bff7600>, #<Object:0x0000014e7bff7600>, "d"]
4917 *
4918 * With a block given, the block is called once for each element to be replaced;
4919 * the value passed to the block is the _index_ of the element to be replaced
4920 * (not the element itself);
4921 * the block's return value replaces the element:
4922 *
4923 * a = ['a', 'b', 'c', 'd'] # => ["a", "b", "c", "d"]
4924 * a.fill(1, 2) {|element| element.to_s } # => ["a", "1", "2", "d"]
4925 *
4926 * For arguments +start+ and +count+:
4927 *
4928 * - If +start+ is non-negative,
4929 * replaces +count+ elements beginning at offset +start+:
4930 *
4931 * ['a', 'b', 'c', 'd'].fill('-', 0, 2) # => ["-", "-", "c", "d"]
4932 * ['a', 'b', 'c', 'd'].fill('-', 1, 2) # => ["a", "-", "-", "d"]
4933 * ['a', 'b', 'c', 'd'].fill('-', 2, 2) # => ["a", "b", "-", "-"]
4934 *
4935 * ['a', 'b', 'c', 'd'].fill(0, 2) {|e| e.to_s } # => ["0", "1", "c", "d"]
4936 * ['a', 'b', 'c', 'd'].fill(1, 2) {|e| e.to_s } # => ["a", "1", "2", "d"]
4937 * ['a', 'b', 'c', 'd'].fill(2, 2) {|e| e.to_s } # => ["a", "b", "2", "3"]
4938 *
4939 * Extends +self+ if necessary:
4940 *
4941 * ['a', 'b', 'c', 'd'].fill('-', 3, 2) # => ["a", "b", "c", "-", "-"]
4942 * ['a', 'b', 'c', 'd'].fill('-', 4, 2) # => ["a", "b", "c", "d", "-", "-"]
4943 *
4944 * ['a', 'b', 'c', 'd'].fill(3, 2) {|e| e.to_s } # => ["a", "b", "c", "3", "4"]
4945 * ['a', 'b', 'c', 'd'].fill(4, 2) {|e| e.to_s } # => ["a", "b", "c", "d", "4", "5"]
4946 *
4947 * Fills with +nil+ if necessary:
4948 *
4949 * ['a', 'b', 'c', 'd'].fill('-', 5, 2) # => ["a", "b", "c", "d", nil, "-", "-"]
4950 * ['a', 'b', 'c', 'd'].fill('-', 6, 2) # => ["a", "b", "c", "d", nil, nil, "-", "-"]
4951 *
4952 * ['a', 'b', 'c', 'd'].fill(5, 2) {|e| e.to_s } # => ["a", "b", "c", "d", nil, "5", "6"]
4953 * ['a', 'b', 'c', 'd'].fill(6, 2) {|e| e.to_s } # => ["a", "b", "c", "d", nil, nil, "6", "7"]
4954 *
4955 * Does nothing if +count+ is non-positive:
4956 *
4957 * ['a', 'b', 'c', 'd'].fill('-', 2, 0) # => ["a", "b", "c", "d"]
4958 * ['a', 'b', 'c', 'd'].fill('-', 2, -100) # => ["a", "b", "c", "d"]
4959 * ['a', 'b', 'c', 'd'].fill('-', 6, -100) # => ["a", "b", "c", "d"]
4960 *
4961 * ['a', 'b', 'c', 'd'].fill(2, 0) {|e| fail 'Cannot happen' } # => ["a", "b", "c", "d"]
4962 * ['a', 'b', 'c', 'd'].fill(2, -100) {|e| fail 'Cannot happen' } # => ["a", "b", "c", "d"]
4963 * ['a', 'b', 'c', 'd'].fill(6, -100) {|e| fail 'Cannot happen' } # => ["a", "b", "c", "d"]
4964 *
4965 * - If +start+ is negative, counts backwards from the end of +self+:
4966 *
4967 * ['a', 'b', 'c', 'd'].fill('-', -4, 3) # => ["-", "-", "-", "d"]
4968 * ['a', 'b', 'c', 'd'].fill('-', -3, 3) # => ["a", "-", "-", "-"]
4969 *
4970 * ['a', 'b', 'c', 'd'].fill(-4, 3) {|e| e.to_s } # => ["0", "1", "2", "d"]
4971 * ['a', 'b', 'c', 'd'].fill(-3, 3) {|e| e.to_s } # => ["a", "1", "2", "3"]
4972 *
4973 * Extends +self+ if necessary:
4974 *
4975 * ['a', 'b', 'c', 'd'].fill('-', -2, 3) # => ["a", "b", "-", "-", "-"]
4976 * ['a', 'b', 'c', 'd'].fill('-', -1, 3) # => ["a", "b", "c", "-", "-", "-"]
4977 *
4978 * ['a', 'b', 'c', 'd'].fill(-2, 3) {|e| e.to_s } # => ["a", "b", "2", "3", "4"]
4979 * ['a', 'b', 'c', 'd'].fill(-1, 3) {|e| e.to_s } # => ["a", "b", "c", "3", "4", "5"]
4980 *
4981 * Starts at the beginning of +self+ if +start+ is negative and out-of-range:
4982 *
4983 * ['a', 'b', 'c', 'd'].fill('-', -5, 2) # => ["-", "-", "c", "d"]
4984 * ['a', 'b', 'c', 'd'].fill('-', -6, 2) # => ["-", "-", "c", "d"]
4985 *
4986 * ['a', 'b', 'c', 'd'].fill(-5, 2) {|e| e.to_s } # => ["0", "1", "c", "d"]
4987 * ['a', 'b', 'c', 'd'].fill(-6, 2) {|e| e.to_s } # => ["0", "1", "c", "d"]
4988 *
4989 * Does nothing if +count+ is non-positive:
4990 *
4991 * ['a', 'b', 'c', 'd'].fill('-', -2, 0) # => ["a", "b", "c", "d"]
4992 * ['a', 'b', 'c', 'd'].fill('-', -2, -1) # => ["a", "b", "c", "d"]
4993 *
4994 * ['a', 'b', 'c', 'd'].fill(-2, 0) {|e| fail 'Cannot happen' } # => ["a", "b", "c", "d"]
4995 * ['a', 'b', 'c', 'd'].fill(-2, -1) {|e| fail 'Cannot happen' } # => ["a", "b", "c", "d"]
4996 *
4997 * When argument +range+ is given,
4998 * it must be a Range object whose members are numeric;
4999 * its +begin+ and +end+ values determine the elements of +self+
5000 * to be replaced:
5001 *
5002 * - If both +begin+ and +end+ are positive, they specify the first and last elements
5003 * to be replaced:
5004 *
5005 * ['a', 'b', 'c', 'd'].fill('-', 1..2) # => ["a", "-", "-", "d"]
5006 * ['a', 'b', 'c', 'd'].fill(1..2) {|e| e.to_s } # => ["a", "1", "2", "d"]
5007 *
5008 * If +end+ is smaller than +begin+, replaces no elements:
5009 *
5010 * ['a', 'b', 'c', 'd'].fill('-', 2..1) # => ["a", "b", "c", "d"]
5011 * ['a', 'b', 'c', 'd'].fill(2..1) {|e| e.to_s } # => ["a", "b", "c", "d"]
5012 *
5013 * - If either is negative (or both are negative), counts backwards from the end of +self+:
5014 *
5015 * ['a', 'b', 'c', 'd'].fill('-', -3..2) # => ["a", "-", "-", "d"]
5016 * ['a', 'b', 'c', 'd'].fill('-', 1..-2) # => ["a", "-", "-", "d"]
5017 * ['a', 'b', 'c', 'd'].fill('-', -3..-2) # => ["a", "-", "-", "d"]
5018 *
5019 * ['a', 'b', 'c', 'd'].fill(-3..2) {|e| e.to_s } # => ["a", "1", "2", "d"]
5020 * ['a', 'b', 'c', 'd'].fill(1..-2) {|e| e.to_s } # => ["a", "1", "2", "d"]
5021 * ['a', 'b', 'c', 'd'].fill(-3..-2) {|e| e.to_s } # => ["a", "1", "2", "d"]
5022 *
5023 * - If the +end+ value is excluded (see Range#exclude_end?), omits the last replacement:
5024 *
5025 * ['a', 'b', 'c', 'd'].fill('-', 1...2) # => ["a", "-", "c", "d"]
5026 * ['a', 'b', 'c', 'd'].fill('-', 1...-2) # => ["a", "-", "c", "d"]
5027 *
5028 * ['a', 'b', 'c', 'd'].fill(1...2) {|e| e.to_s } # => ["a", "1", "c", "d"]
5029 * ['a', 'b', 'c', 'd'].fill(1...-2) {|e| e.to_s } # => ["a", "1", "c", "d"]
5030 *
5031 * - If the range is endless (see {Endless Ranges}[rdoc-ref:Range@Endless+Ranges]),
5032 * replaces elements to the end of +self+:
5033 *
5034 * ['a', 'b', 'c', 'd'].fill('-', 1..) # => ["a", "-", "-", "-"]
5035 * ['a', 'b', 'c', 'd'].fill(1..) {|e| e.to_s } # => ["a", "1", "2", "3"]
5036 *
5037 * - If the range is beginless (see {Beginless Ranges}[rdoc-ref:Range@Beginless+Ranges]),
5038 * replaces elements from the beginning of +self+:
5039 *
5040 * ['a', 'b', 'c', 'd'].fill('-', ..2) # => ["-", "-", "-", "d"]
5041 * ['a', 'b', 'c', 'd'].fill(..2) {|e| e.to_s } # => ["0", "1", "2", "d"]
5042 *
5043 * Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
5044 */
5045
5046static VALUE
5047rb_ary_fill(int argc, VALUE *argv, VALUE ary)
5048{
5049 VALUE item = Qundef, arg1, arg2;
5050 long beg = 0, end = 0, len = 0;
5051
5052 if (rb_block_given_p()) {
5053 rb_scan_args(argc, argv, "02", &arg1, &arg2);
5054 argc += 1; /* hackish */
5055 }
5056 else {
5057 rb_scan_args(argc, argv, "12", &item, &arg1, &arg2);
5058 }
5059 switch (argc) {
5060 case 1:
5061 beg = 0;
5062 len = RARRAY_LEN(ary);
5063 break;
5064 case 2:
5065 if (rb_range_beg_len(arg1, &beg, &len, RARRAY_LEN(ary), 1)) {
5066 break;
5067 }
5068 /* fall through */
5069 case 3:
5070 beg = NIL_P(arg1) ? 0 : NUM2LONG(arg1);
5071 if (beg < 0) {
5072 beg = RARRAY_LEN(ary) + beg;
5073 if (beg < 0) beg = 0;
5074 }
5075 len = NIL_P(arg2) ? RARRAY_LEN(ary) - beg : NUM2LONG(arg2);
5076 break;
5077 }
5078 rb_ary_modify(ary);
5079 if (len < 0) {
5080 return ary;
5081 }
5082 if (beg >= ARY_MAX_SIZE || len > ARY_MAX_SIZE - beg) {
5083 rb_raise(rb_eArgError, "argument too big");
5084 }
5085 end = beg + len;
5086 if (RARRAY_LEN(ary) < end) {
5087 if (end >= ARY_CAPA(ary)) {
5088 ary_resize_capa(ary, end);
5089 }
5090 ary_mem_clear(ary, RARRAY_LEN(ary), end - RARRAY_LEN(ary));
5091 ARY_SET_LEN(ary, end);
5092 }
5093
5094 if (UNDEF_P(item)) {
5095 VALUE v;
5096 long i;
5097
5098 for (i=beg; i<end; i++) {
5099 v = rb_yield(LONG2NUM(i));
5100 if (i>=RARRAY_LEN(ary)) break;
5101 ARY_SET(ary, i, v);
5102 }
5103 }
5104 else {
5105 ary_memfill(ary, beg, len, item);
5106 }
5107 return ary;
5108}
5109
5110/*
5111 * call-seq:
5112 * self + other_array -> new_array
5113 *
5114 * Returns a new array containing all elements of +self+
5115 * followed by all elements of +other_array+:
5116 *
5117 * a = [0, 1] + [2, 3]
5118 * a # => [0, 1, 2, 3]
5119 *
5120 * Related: see {Methods for Combining}[rdoc-ref:Array@Methods+for+Combining].
5121 */
5122
5123VALUE
5125{
5126 VALUE z;
5127 long len, xlen, ylen;
5128
5129 y = to_ary(y);
5130 xlen = RARRAY_LEN(x);
5131 ylen = RARRAY_LEN(y);
5132 len = xlen + ylen;
5133 z = rb_ary_new2(len);
5134
5135 ary_memcpy(z, 0, xlen, RARRAY_CONST_PTR(x));
5136 ary_memcpy(z, xlen, ylen, RARRAY_CONST_PTR(y));
5137 ARY_SET_LEN(z, len);
5138 return z;
5139}
5140
5141static VALUE
5142ary_append(VALUE x, VALUE y)
5143{
5144 long n = RARRAY_LEN(y);
5145 if (n > 0) {
5146 rb_ary_splice(x, RARRAY_LEN(x), 0, RARRAY_CONST_PTR(y), n, x == y);
5147 }
5148 RB_GC_GUARD(y);
5149 return x;
5150}
5151
5152/*
5153 * call-seq:
5154 * concat(*other_arrays) -> self
5155 *
5156 * Adds to +self+ all elements from each array in +other_arrays+; returns +self+:
5157 *
5158 * a = [0, 1]
5159 * a.concat(['two', 'three'], [:four, :five], a)
5160 * # => [0, 1, "two", "three", :four, :five, 0, 1]
5161 *
5162 * Related: see {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
5163 */
5164
5165static VALUE
5166rb_ary_concat_multi(int argc, VALUE *argv, VALUE ary)
5167{
5168 rb_ary_modify_check(ary);
5169
5170 if (argc == 1) {
5171 rb_ary_concat(ary, argv[0]);
5172 }
5173 else if (argc > 1) {
5174 int i;
5175 VALUE args = rb_ary_hidden_new(argc);
5176 for (i = 0; i < argc; i++) {
5177 rb_ary_concat(args, argv[i]);
5178 }
5179 ary_append(ary, args);
5180 }
5181
5182 ary_verify(ary);
5183 return ary;
5184}
5185
5186VALUE
5188{
5189 return ary_append(x, to_ary(y));
5190}
5191
5192/*
5193 * call-seq:
5194 * self * n -> new_array
5195 * self * string_separator -> new_string
5196 *
5197 * When non-negative integer argument +n+ is given,
5198 * returns a new array built by concatenating +n+ copies of +self+:
5199 *
5200 * a = ['x', 'y']
5201 * a * 3 # => ["x", "y", "x", "y", "x", "y"]
5202 *
5203 * When string argument +string_separator+ is given,
5204 * equivalent to <tt>self.join(string_separator)</tt>:
5205 *
5206 * [0, [0, 1], {foo: 0}] * ', ' # => "0, 0, 1, {foo: 0}"
5207 *
5208 */
5209
5210static VALUE
5211rb_ary_times(VALUE ary, VALUE times)
5212{
5213 VALUE ary2, tmp;
5214 const VALUE *ptr;
5215 long t, len;
5216
5217 tmp = rb_check_string_type(times);
5218 if (!NIL_P(tmp)) {
5219 return rb_ary_join(ary, tmp);
5220 }
5221
5222 len = NUM2LONG(times);
5223 if (len == 0) {
5224 ary2 = ary_new(rb_cArray, 0);
5225 goto out;
5226 }
5227 if (len < 0) {
5228 rb_raise(rb_eArgError, "negative argument");
5229 }
5230 if (ARY_MAX_SIZE/len < RARRAY_LEN(ary)) {
5231 rb_raise(rb_eArgError, "argument too big");
5232 }
5233 len *= RARRAY_LEN(ary);
5234
5235 ary2 = ary_new(rb_cArray, len);
5236 ARY_SET_LEN(ary2, len);
5237
5238 ptr = RARRAY_CONST_PTR(ary);
5239 t = RARRAY_LEN(ary);
5240 if (0 < t) {
5241 ary_memcpy(ary2, 0, t, ptr);
5242 while (t <= len/2) {
5243 ary_memcpy(ary2, t, t, RARRAY_CONST_PTR(ary2));
5244 t *= 2;
5245 }
5246 if (t < len) {
5247 ary_memcpy(ary2, t, len-t, RARRAY_CONST_PTR(ary2));
5248 }
5249 }
5250 out:
5251 return ary2;
5252}
5253
5254/*
5255 * call-seq:
5256 * assoc(object) -> found_array or nil
5257 *
5258 * Returns the first element +ele+ in +self+ such that +ele+ is an array
5259 * and <tt>ele[0] == object</tt>:
5260 *
5261 * a = [{foo: 0}, [2, 4], [4, 5, 6], [4, 5]]
5262 * a.assoc(4) # => [4, 5, 6]
5263 *
5264 * Returns +nil+ if no such element is found.
5265 *
5266 * Related: Array#rassoc;
5267 * see also {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
5268 */
5269
5270VALUE
5271rb_ary_assoc(VALUE ary, VALUE key)
5272{
5273 long i;
5274 VALUE v;
5275
5276 for (i = 0; i < RARRAY_LEN(ary); ++i) {
5277 v = rb_check_array_type(RARRAY_AREF(ary, i));
5278 if (!NIL_P(v) && RARRAY_LEN(v) > 0 &&
5279 rb_equal(RARRAY_AREF(v, 0), key))
5280 return v;
5281 }
5282 return Qnil;
5283}
5284
5285/*
5286 * call-seq:
5287 * rassoc(object) -> found_array or nil
5288 *
5289 * Returns the first element +ele+ in +self+ such that +ele+ is an array
5290 * and <tt>ele[1] == object</tt>:
5291 *
5292 * a = [{foo: 0}, [2, 4], [4, 5, 6], [4, 5]]
5293 * a.rassoc(4) # => [2, 4]
5294 * a.rassoc(5) # => [4, 5, 6]
5295 *
5296 * Returns +nil+ if no such element is found.
5297 *
5298 * Related: Array#assoc;
5299 * see also {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
5300 */
5301
5302VALUE
5303rb_ary_rassoc(VALUE ary, VALUE value)
5304{
5305 long i;
5306 VALUE v;
5307
5308 for (i = 0; i < RARRAY_LEN(ary); ++i) {
5309 v = rb_check_array_type(RARRAY_AREF(ary, i));
5310 if (RB_TYPE_P(v, T_ARRAY) &&
5311 RARRAY_LEN(v) > 1 &&
5312 rb_equal(RARRAY_AREF(v, 1), value))
5313 return v;
5314 }
5315 return Qnil;
5316}
5317
5318static VALUE
5319recursive_equal(VALUE ary1, VALUE ary2, int recur)
5320{
5321 long i, len1;
5322 const VALUE *p1, *p2;
5323
5324 if (recur) return Qtrue; /* Subtle! */
5325
5326 /* rb_equal() can evacuate ptrs */
5327 p1 = RARRAY_CONST_PTR(ary1);
5328 p2 = RARRAY_CONST_PTR(ary2);
5329 len1 = RARRAY_LEN(ary1);
5330
5331 for (i = 0; i < len1; i++) {
5332 if (*p1 != *p2) {
5333 if (rb_equal(*p1, *p2)) {
5334 len1 = RARRAY_LEN(ary1);
5335 if (len1 != RARRAY_LEN(ary2))
5336 return Qfalse;
5337 if (len1 < i)
5338 return Qtrue;
5339 p1 = RARRAY_CONST_PTR(ary1) + i;
5340 p2 = RARRAY_CONST_PTR(ary2) + i;
5341 }
5342 else {
5343 return Qfalse;
5344 }
5345 }
5346 p1++;
5347 p2++;
5348 }
5349 return Qtrue;
5350}
5351
5352/*
5353 * call-seq:
5354 * self == other_array -> true or false
5355 *
5356 * Returns whether both:
5357 *
5358 * - +self+ and +other_array+ are the same size.
5359 * - Their corresponding elements are the same;
5360 * that is, for each index +i+ in <tt>(0...self.size)</tt>,
5361 * <tt>self[i] == other_array[i]</tt>.
5362 *
5363 * Examples:
5364 *
5365 * [:foo, 'bar', 2] == [:foo, 'bar', 2] # => true
5366 * [:foo, 'bar', 2] == [:foo, 'bar', 2.0] # => true
5367 * [:foo, 'bar', 2] == [:foo, 'bar'] # => false # Different sizes.
5368 * [:foo, 'bar', 2] == [:foo, 'bar', 3] # => false # Different elements.
5369 *
5370 * This method is different from method Array#eql?,
5371 * which compares elements using <tt>Object#eql?</tt>.
5372 *
5373 * Related: see {Methods for Comparing}[rdoc-ref:Array@Methods+for+Comparing].
5374 */
5375
5376static VALUE
5377rb_ary_equal(VALUE ary1, VALUE ary2)
5378{
5379 if (ary1 == ary2) return Qtrue;
5380 if (!RB_TYPE_P(ary2, T_ARRAY)) {
5381 if (!rb_respond_to(ary2, idTo_ary)) {
5382 return Qfalse;
5383 }
5384 return rb_equal(ary2, ary1);
5385 }
5386 if (RARRAY_LEN(ary1) != RARRAY_LEN(ary2)) return Qfalse;
5387 if (RARRAY_CONST_PTR(ary1) == RARRAY_CONST_PTR(ary2)) return Qtrue;
5388 return rb_exec_recursive_paired(recursive_equal, ary1, ary2, ary2);
5389}
5390
5391static VALUE
5392recursive_eql(VALUE ary1, VALUE ary2, int recur)
5393{
5394 long i;
5395
5396 if (recur) return Qtrue; /* Subtle! */
5397 for (i=0; i<RARRAY_LEN(ary1); i++) {
5398 if (!rb_eql(rb_ary_elt(ary1, i), rb_ary_elt(ary2, i)))
5399 return Qfalse;
5400 }
5401 return Qtrue;
5402}
5403
5404/*
5405 * call-seq:
5406 * eql?(other_array) -> true or false
5407 *
5408 * Returns +true+ if +self+ and +other_array+ are the same size,
5409 * and if, for each index +i+ in +self+, <tt>self[i].eql?(other_array[i])</tt>:
5410 *
5411 * a0 = [:foo, 'bar', 2]
5412 * a1 = [:foo, 'bar', 2]
5413 * a1.eql?(a0) # => true
5414 *
5415 * Otherwise, returns +false+.
5416 *
5417 * This method is different from method Array#==,
5418 * which compares using method <tt>Object#==</tt>.
5419 *
5420 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
5421 */
5422
5423static VALUE
5424rb_ary_eql(VALUE ary1, VALUE ary2)
5425{
5426 if (ary1 == ary2) return Qtrue;
5427 if (!RB_TYPE_P(ary2, T_ARRAY)) return Qfalse;
5428 if (RARRAY_LEN(ary1) != RARRAY_LEN(ary2)) return Qfalse;
5429 if (RARRAY_CONST_PTR(ary1) == RARRAY_CONST_PTR(ary2)) return Qtrue;
5430 return rb_exec_recursive_paired(recursive_eql, ary1, ary2, ary2);
5431}
5432
5433static VALUE
5434ary_hash_values(long len, const VALUE *elements, const VALUE ary)
5435{
5436 long i;
5437 st_index_t h;
5438 VALUE n;
5439
5440 h = rb_hash_start(len);
5441 h = rb_hash_uint(h, (st_index_t)rb_ary_hash_values);
5442 for (i=0; i<len; i++) {
5443 n = rb_hash(elements[i]);
5444 h = rb_hash_uint(h, NUM2LONG(n));
5445 if (ary) {
5446 len = RARRAY_LEN(ary);
5447 elements = RARRAY_CONST_PTR(ary);
5448 }
5449 }
5450 h = rb_hash_end(h);
5451 return ST2FIX(h);
5452}
5453
5454VALUE
5455rb_ary_hash_values(long len, const VALUE *elements)
5456{
5457 return ary_hash_values(len, elements, 0);
5458}
5459
5460/*
5461 * call-seq:
5462 * hash -> integer
5463 *
5464 * Returns the integer hash value for +self+.
5465 *
5466 * Two arrays with the same content will have the same hash value
5467 * (and will compare using eql?):
5468 *
5469 * ['a', 'b'].hash == ['a', 'b'].hash # => true
5470 * ['a', 'b'].hash == ['a', 'c'].hash # => false
5471 * ['a', 'b'].hash == ['a'].hash # => false
5472 *
5473 */
5474
5475static VALUE
5476rb_ary_hash(VALUE ary)
5477{
5479 return ary_hash_values(RARRAY_LEN(ary), RARRAY_CONST_PTR(ary), ary);
5480}
5481
5482/*
5483 * call-seq:
5484 * include?(object) -> true or false
5485 *
5486 * Returns whether for some element +element+ in +self+,
5487 * <tt>object == element</tt>:
5488 *
5489 * [0, 1, 2].include?(2) # => true
5490 * [0, 1, 2].include?(2.0) # => true
5491 * [0, 1, 2].include?(2.1) # => false
5492 *
5493 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
5494 */
5495
5496VALUE
5497rb_ary_includes(VALUE ary, VALUE item)
5498{
5499 long i;
5500 VALUE e;
5501
5502 for (i=0; i<RARRAY_LEN(ary); i++) {
5503 e = RARRAY_AREF(ary, i);
5504 if (rb_equal(e, item)) {
5505 return Qtrue;
5506 }
5507 }
5508 return Qfalse;
5509}
5510
5511static VALUE
5512rb_ary_includes_by_eql(VALUE ary, VALUE item)
5513{
5514 long i;
5515 VALUE e;
5516
5517 for (i=0; i<RARRAY_LEN(ary); i++) {
5518 e = RARRAY_AREF(ary, i);
5519 if (rb_eql(item, e)) {
5520 return Qtrue;
5521 }
5522 }
5523 return Qfalse;
5524}
5525
5526static VALUE
5527recursive_cmp(VALUE ary1, VALUE ary2, int recur)
5528{
5529 long i, len;
5530
5531 if (recur) return Qundef; /* Subtle! */
5532 len = RARRAY_LEN(ary1);
5533 if (len > RARRAY_LEN(ary2)) {
5534 len = RARRAY_LEN(ary2);
5535 }
5536 for (i=0; i<len; i++) {
5537 VALUE e1 = rb_ary_elt(ary1, i), e2 = rb_ary_elt(ary2, i);
5538 VALUE v = rb_funcallv(e1, id_cmp, 1, &e2);
5539 if (v != INT2FIX(0)) {
5540 return v;
5541 }
5542 }
5543 return Qundef;
5544}
5545
5546/*
5547 * call-seq:
5548 * self <=> other_array -> -1, 0, or 1
5549 *
5550 * Returns -1, 0, or 1 as +self+ is determined
5551 * to be less than, equal to, or greater than +other_array+.
5552 *
5553 * Iterates over each index +i+ in <tt>(0...self.size)</tt>:
5554 *
5555 * - Computes <tt>result[i]</tt> as <tt>self[i] <=> other_array[i]</tt>.
5556 * - Immediately returns 1 if <tt>result[i]</tt> is 1:
5557 *
5558 * [0, 1, 2] <=> [0, 0, 2] # => 1
5559 *
5560 * - Immediately returns -1 if <tt>result[i]</tt> is -1:
5561 *
5562 * [0, 1, 2] <=> [0, 2, 2] # => -1
5563 *
5564 * - Continues if <tt>result[i]</tt> is 0.
5565 *
5566 * When every +result+ is 0,
5567 * returns <tt>self.size <=> other_array.size</tt>
5568 * (see Integer#<=>):
5569 *
5570 * [0, 1, 2] <=> [0, 1] # => 1
5571 * [0, 1, 2] <=> [0, 1, 2] # => 0
5572 * [0, 1, 2] <=> [0, 1, 2, 3] # => -1
5573 *
5574 * Note that when +other_array+ is larger than +self+,
5575 * its trailing elements do not affect the result:
5576 *
5577 * [0, 1, 2] <=> [0, 1, 2, -3] # => -1
5578 * [0, 1, 2] <=> [0, 1, 2, 0] # => -1
5579 * [0, 1, 2] <=> [0, 1, 2, 3] # => -1
5580 *
5581 * Related: see {Methods for Comparing}[rdoc-ref:Array@Methods+for+Comparing].
5582 */
5583
5584VALUE
5585rb_ary_cmp(VALUE ary1, VALUE ary2)
5586{
5587 long len;
5588 VALUE v;
5589
5590 ary2 = rb_check_array_type(ary2);
5591 if (NIL_P(ary2)) return Qnil;
5592 if (ary1 == ary2) return INT2FIX(0);
5593 v = rb_exec_recursive_paired(recursive_cmp, ary1, ary2, ary2);
5594 if (!UNDEF_P(v)) return v;
5595 len = RARRAY_LEN(ary1) - RARRAY_LEN(ary2);
5596 if (len == 0) return INT2FIX(0);
5597 if (len > 0) return INT2FIX(1);
5598 return INT2FIX(-1);
5599}
5600
5601static VALUE
5602ary_add_hash(VALUE hash, VALUE ary)
5603{
5604 long i;
5605
5606 for (i=0; i<RARRAY_LEN(ary); i++) {
5607 VALUE elt = RARRAY_AREF(ary, i);
5608 rb_hash_add_new_element(hash, elt, elt);
5609 }
5610 return hash;
5611}
5612
5613static inline VALUE
5614ary_tmp_hash_new(VALUE ary)
5615{
5616 long size = RARRAY_LEN(ary);
5617 VALUE hash = rb_hash_new_with_size(size);
5618
5619 RBASIC_CLEAR_CLASS(hash);
5620 return hash;
5621}
5622
5623static VALUE
5624ary_make_hash(VALUE ary)
5625{
5626 VALUE hash = ary_tmp_hash_new(ary);
5627 return ary_add_hash(hash, ary);
5628}
5629
5630static VALUE
5631ary_add_hash_by(VALUE hash, VALUE ary)
5632{
5633 long i;
5634
5635 for (i = 0; i < RARRAY_LEN(ary); ++i) {
5636 VALUE v = rb_ary_elt(ary, i), k = rb_yield(v);
5637 rb_hash_add_new_element(hash, k, v);
5638 }
5639 return hash;
5640}
5641
5642static VALUE
5643ary_make_hash_by(VALUE ary)
5644{
5645 VALUE hash = ary_tmp_hash_new(ary);
5646 return ary_add_hash_by(hash, ary);
5647}
5648
5649/*
5650 * call-seq:
5651 * self - other_array -> new_array
5652 *
5653 * Returns a new array containing only those elements of +self+
5654 * that are not found in +other_array+;
5655 * the order from +self+ is preserved:
5656 *
5657 * [0, 1, 1, 2, 1, 1, 3, 1, 1] - [1] # => [0, 2, 3]
5658 * [0, 1, 1, 2, 1, 1, 3, 1, 1] - [3, 2, 0, :foo] # => [1, 1, 1, 1, 1, 1]
5659 * [0, 1, 2] - [:foo] # => [0, 1, 2]
5660 *
5661 * Element are compared using method <tt>#eql?</tt>
5662 * (as defined in each element of +self+).
5663 *
5664 * Related: see {Methods for Combining}[rdoc-ref:Array@Methods+for+Combining].
5665 */
5666
5667VALUE
5668rb_ary_diff(VALUE ary1, VALUE ary2)
5669{
5670 VALUE ary3;
5671 VALUE hash;
5672 long i;
5673
5674 ary2 = to_ary(ary2);
5675 if (RARRAY_LEN(ary2) == 0) { return ary_make_shared_copy(ary1); }
5676 ary3 = rb_ary_new();
5677
5678 if (RARRAY_LEN(ary1) <= SMALL_ARRAY_LEN || RARRAY_LEN(ary2) <= SMALL_ARRAY_LEN) {
5679 for (i=0; i<RARRAY_LEN(ary1); i++) {
5680 VALUE elt = rb_ary_elt(ary1, i);
5681 if (rb_ary_includes_by_eql(ary2, elt)) continue;
5682 rb_ary_push(ary3, elt);
5683 }
5684 return ary3;
5685 }
5686
5687 hash = ary_make_hash(ary2);
5688 for (i=0; i<RARRAY_LEN(ary1); i++) {
5689 if (rb_hash_stlike_lookup(hash, RARRAY_AREF(ary1, i), NULL)) continue;
5690 rb_ary_push(ary3, rb_ary_elt(ary1, i));
5691 }
5692
5693 return ary3;
5694}
5695
5696/*
5697 * call-seq:
5698 * difference(*other_arrays = []) -> new_array
5699 *
5700 * Returns a new array containing only those elements from +self+
5701 * that are not found in any of the given +other_arrays+;
5702 * items are compared using <tt>eql?</tt>; order from +self+ is preserved:
5703 *
5704 * [0, 1, 1, 2, 1, 1, 3, 1, 1].difference([1]) # => [0, 2, 3]
5705 * [0, 1, 2, 3].difference([3, 0], [1, 3]) # => [2]
5706 * [0, 1, 2].difference([4]) # => [0, 1, 2]
5707 * [0, 1, 2].difference # => [0, 1, 2]
5708 *
5709 * Returns a copy of +self+ if no arguments are given.
5710 *
5711 * Related: Array#-;
5712 * see also {Methods for Combining}[rdoc-ref:Array@Methods+for+Combining].
5713 */
5714
5715static VALUE
5716rb_ary_difference_multi(int argc, VALUE *argv, VALUE ary)
5717{
5718 VALUE ary_diff;
5719 long i, length;
5720 volatile VALUE t0;
5721 bool *is_hash = ALLOCV_N(bool, t0, argc);
5722 ary_diff = rb_ary_new();
5723 length = RARRAY_LEN(ary);
5724
5725 for (i = 0; i < argc; i++) {
5726 argv[i] = to_ary(argv[i]);
5727 is_hash[i] = (length > SMALL_ARRAY_LEN && RARRAY_LEN(argv[i]) > SMALL_ARRAY_LEN);
5728 if (is_hash[i]) argv[i] = ary_make_hash(argv[i]);
5729 }
5730
5731 for (i = 0; i < RARRAY_LEN(ary); i++) {
5732 int j;
5733 VALUE elt = rb_ary_elt(ary, i);
5734 for (j = 0; j < argc; j++) {
5735 if (is_hash[j]) {
5736 if (rb_hash_stlike_lookup(argv[j], elt, NULL))
5737 break;
5738 }
5739 else {
5740 if (rb_ary_includes_by_eql(argv[j], elt)) break;
5741 }
5742 }
5743 if (j == argc) rb_ary_push(ary_diff, elt);
5744 }
5745
5746 ALLOCV_END(t0);
5747
5748 return ary_diff;
5749}
5750
5751
5752/*
5753 * call-seq:
5754 * self & other_array -> new_array
5755 *
5756 * Returns a new array containing the _intersection_ of +self+ and +other_array+;
5757 * that is, containing those elements found in both +self+ and +other_array+:
5758 *
5759 * [0, 1, 2, 3] & [1, 2] # => [1, 2]
5760 *
5761 * Omits duplicates:
5762 *
5763 * [0, 1, 1, 0] & [0, 1] # => [0, 1]
5764 *
5765 * Preserves order from +self+:
5766 *
5767 * [0, 1, 2] & [3, 2, 1, 0] # => [0, 1, 2]
5768 *
5769 * Identifies common elements using method <tt>#eql?</tt>
5770 * (as defined in each element of +self+).
5771 *
5772 * Related: see {Methods for Combining}[rdoc-ref:Array@Methods+for+Combining].
5773 */
5774
5775
5776static VALUE
5777rb_ary_and(VALUE ary1, VALUE ary2)
5778{
5779 VALUE hash, ary3, v;
5780 st_data_t vv;
5781 long i;
5782
5783 ary2 = to_ary(ary2);
5784 ary3 = rb_ary_new();
5785 if (RARRAY_LEN(ary1) == 0 || RARRAY_LEN(ary2) == 0) return ary3;
5786
5787 if (RARRAY_LEN(ary1) <= SMALL_ARRAY_LEN && RARRAY_LEN(ary2) <= SMALL_ARRAY_LEN) {
5788 for (i=0; i<RARRAY_LEN(ary1); i++) {
5789 v = RARRAY_AREF(ary1, i);
5790 if (!rb_ary_includes_by_eql(ary2, v)) continue;
5791 if (rb_ary_includes_by_eql(ary3, v)) continue;
5792 rb_ary_push(ary3, v);
5793 }
5794 return ary3;
5795 }
5796
5797 hash = ary_make_hash(ary2);
5798
5799 for (i=0; i<RARRAY_LEN(ary1); i++) {
5800 v = RARRAY_AREF(ary1, i);
5801 vv = (st_data_t)v;
5802 if (rb_hash_stlike_delete(hash, &vv, 0)) {
5803 rb_ary_push(ary3, v);
5804 }
5805 }
5806
5807 return ary3;
5808}
5809
5810/*
5811 * call-seq:
5812 * intersection(*other_arrays) -> new_array
5813 *
5814 * Returns a new array containing each element in +self+ that is +#eql?+
5815 * to at least one element in each of the given +other_arrays+;
5816 * duplicates are omitted:
5817 *
5818 * [0, 0, 1, 1, 2, 3].intersection([0, 1, 2], [0, 1, 3]) # => [0, 1]
5819 *
5820 * Each element must correctly implement method <tt>#hash</tt>.
5821 *
5822 * Order from +self+ is preserved:
5823 *
5824 * [0, 1, 2].intersection([2, 1, 0]) # => [0, 1, 2]
5825 *
5826 * Returns a copy of +self+ if no arguments are given.
5827 *
5828 * Related: see {Methods for Combining}[rdoc-ref:Array@Methods+for+Combining].
5829 */
5830
5831static VALUE
5832rb_ary_intersection_multi(int argc, VALUE *argv, VALUE ary)
5833{
5834 VALUE result = rb_ary_dup(ary);
5835 int i;
5836
5837 for (i = 0; i < argc; i++) {
5838 result = rb_ary_and(result, argv[i]);
5839 }
5840
5841 return result;
5842}
5843
5844static int
5845ary_hash_orset(st_data_t *key, st_data_t *value, st_data_t arg, int existing)
5846{
5847 if (existing) return ST_STOP;
5848 *key = *value = (VALUE)arg;
5849 return ST_CONTINUE;
5850}
5851
5852static void
5853rb_ary_union(VALUE ary_union, VALUE ary)
5854{
5855 long i;
5856 for (i = 0; i < RARRAY_LEN(ary); i++) {
5857 VALUE elt = rb_ary_elt(ary, i);
5858 if (rb_ary_includes_by_eql(ary_union, elt)) continue;
5859 rb_ary_push(ary_union, elt);
5860 }
5861}
5862
5863static void
5864rb_ary_union_hash(VALUE hash, VALUE ary2)
5865{
5866 long i;
5867 for (i = 0; i < RARRAY_LEN(ary2); i++) {
5868 VALUE elt = RARRAY_AREF(ary2, i);
5869 if (!rb_hash_stlike_update(hash, (st_data_t)elt, ary_hash_orset, (st_data_t)elt)) {
5870 RB_OBJ_WRITTEN(hash, Qundef, elt);
5871 }
5872 }
5873}
5874
5875/*
5876 * call-seq:
5877 * self | other_array -> new_array
5878 *
5879 * Returns the union of +self+ and +other_array+;
5880 * duplicates are removed; order is preserved;
5881 * items are compared using <tt>eql?</tt>:
5882 *
5883 * [0, 1] | [2, 3] # => [0, 1, 2, 3]
5884 * [0, 1, 1] | [2, 2, 3] # => [0, 1, 2, 3]
5885 * [0, 1, 2] | [3, 2, 1, 0] # => [0, 1, 2, 3]
5886 *
5887 * Related: see {Methods for Combining}[rdoc-ref:Array@Methods+for+Combining].
5888 */
5889
5890static VALUE
5891rb_ary_or(VALUE ary1, VALUE ary2)
5892{
5893 VALUE hash;
5894
5895 ary2 = to_ary(ary2);
5896 if (RARRAY_LEN(ary1) + RARRAY_LEN(ary2) <= SMALL_ARRAY_LEN) {
5897 VALUE ary3 = rb_ary_new();
5898 rb_ary_union(ary3, ary1);
5899 rb_ary_union(ary3, ary2);
5900 return ary3;
5901 }
5902
5903 hash = ary_make_hash(ary1);
5904 rb_ary_union_hash(hash, ary2);
5905
5906 return rb_hash_values(hash);
5907}
5908
5909/*
5910 * call-seq:
5911 * union(*other_arrays) -> new_array
5912 *
5913 * Returns a new array that is the union of the elements of +self+
5914 * and all given arrays +other_arrays+;
5915 * items are compared using <tt>eql?</tt>:
5916 *
5917 * [0, 1, 2, 3].union([4, 5], [6, 7]) # => [0, 1, 2, 3, 4, 5, 6, 7]
5918 *
5919 * Removes duplicates (preserving the first found):
5920 *
5921 * [0, 1, 1].union([2, 1], [3, 1]) # => [0, 1, 2, 3]
5922 *
5923 * Preserves order (preserving the position of the first found):
5924 *
5925 * [3, 2, 1, 0].union([5, 3], [4, 2]) # => [3, 2, 1, 0, 5, 4]
5926 *
5927 * With no arguments given, returns a copy of +self+.
5928 *
5929 * Related: see {Methods for Combining}[rdoc-ref:Array@Methods+for+Combining].
5930 */
5931
5932static VALUE
5933rb_ary_union_multi(int argc, VALUE *argv, VALUE ary)
5934{
5935 int i;
5936 long sum;
5937 VALUE hash;
5938
5939 sum = RARRAY_LEN(ary);
5940 for (i = 0; i < argc; i++) {
5941 argv[i] = to_ary(argv[i]);
5942 sum += RARRAY_LEN(argv[i]);
5943 }
5944
5945 if (sum <= SMALL_ARRAY_LEN) {
5946 VALUE ary_union = rb_ary_new();
5947
5948 rb_ary_union(ary_union, ary);
5949 for (i = 0; i < argc; i++) rb_ary_union(ary_union, argv[i]);
5950
5951 return ary_union;
5952 }
5953
5954 hash = ary_make_hash(ary);
5955 for (i = 0; i < argc; i++) rb_ary_union_hash(hash, argv[i]);
5956
5957 return rb_hash_values(hash);
5958}
5959
5960/*
5961 * call-seq:
5962 * intersect?(other_array) -> true or false
5963 *
5964 * Returns whether +other_array+ has at least one element that is +#eql?+ to some element of +self+:
5965 *
5966 * [1, 2, 3].intersect?([3, 4, 5]) # => true
5967 * [1, 2, 3].intersect?([4, 5, 6]) # => false
5968 *
5969 * Each element must correctly implement method <tt>#hash</tt>.
5970 *
5971 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
5972 */
5973
5974static VALUE
5975rb_ary_intersect_p(VALUE ary1, VALUE ary2)
5976{
5977 VALUE hash, v, result, shorter, longer;
5978 st_data_t vv;
5979 long i;
5980
5981 ary2 = to_ary(ary2);
5982 if (RARRAY_LEN(ary1) == 0 || RARRAY_LEN(ary2) == 0) return Qfalse;
5983
5984 if (RARRAY_LEN(ary1) <= SMALL_ARRAY_LEN && RARRAY_LEN(ary2) <= SMALL_ARRAY_LEN) {
5985 for (i=0; i<RARRAY_LEN(ary1); i++) {
5986 v = RARRAY_AREF(ary1, i);
5987 if (rb_ary_includes_by_eql(ary2, v)) return Qtrue;
5988 }
5989 return Qfalse;
5990 }
5991
5992 shorter = ary1;
5993 longer = ary2;
5994 if (RARRAY_LEN(ary1) > RARRAY_LEN(ary2)) {
5995 longer = ary1;
5996 shorter = ary2;
5997 }
5998
5999 hash = ary_make_hash(shorter);
6000 result = Qfalse;
6001
6002 for (i=0; i<RARRAY_LEN(longer); i++) {
6003 v = RARRAY_AREF(longer, i);
6004 vv = (st_data_t)v;
6005 if (rb_hash_stlike_lookup(hash, vv, 0)) {
6006 result = Qtrue;
6007 break;
6008 }
6009 }
6010
6011 return result;
6012}
6013
6014static VALUE
6015ary_max_generic(VALUE ary, long i, VALUE vmax)
6016{
6017 RUBY_ASSERT(i > 0 && i < RARRAY_LEN(ary));
6018
6019 VALUE v;
6020 for (; i < RARRAY_LEN(ary); ++i) {
6021 v = RARRAY_AREF(ary, i);
6022
6023 if (rb_cmpint(rb_funcallv(vmax, id_cmp, 1, &v), vmax, v) < 0) {
6024 vmax = v;
6025 }
6026 }
6027
6028 return vmax;
6029}
6030
6031static VALUE
6032ary_max_opt_fixnum(VALUE ary, long i, VALUE vmax)
6033{
6034 const long n = RARRAY_LEN(ary);
6035 RUBY_ASSERT(i > 0 && i < n);
6036 RUBY_ASSERT(FIXNUM_P(vmax));
6037
6038 VALUE v;
6039 for (; i < n; ++i) {
6040 v = RARRAY_AREF(ary, i);
6041
6042 if (FIXNUM_P(v)) {
6043 if ((long)vmax < (long)v) {
6044 vmax = v;
6045 }
6046 }
6047 else {
6048 return ary_max_generic(ary, i, vmax);
6049 }
6050 }
6051
6052 return vmax;
6053}
6054
6055static VALUE
6056ary_max_opt_float(VALUE ary, long i, VALUE vmax)
6057{
6058 const long n = RARRAY_LEN(ary);
6059 RUBY_ASSERT(i > 0 && i < n);
6060 RUBY_ASSERT(RB_FLOAT_TYPE_P(vmax));
6061
6062 VALUE v;
6063 for (; i < n; ++i) {
6064 v = RARRAY_AREF(ary, i);
6065
6066 if (RB_FLOAT_TYPE_P(v)) {
6067 if (rb_float_cmp(vmax, v) < 0) {
6068 vmax = v;
6069 }
6070 }
6071 else {
6072 return ary_max_generic(ary, i, vmax);
6073 }
6074 }
6075
6076 return vmax;
6077}
6078
6079static VALUE
6080ary_max_opt_string(VALUE ary, long i, VALUE vmax)
6081{
6082 const long n = RARRAY_LEN(ary);
6083 RUBY_ASSERT(i > 0 && i < n);
6084 RUBY_ASSERT(STRING_P(vmax));
6085
6086 VALUE v;
6087 for (; i < n; ++i) {
6088 v = RARRAY_AREF(ary, i);
6089
6090 if (STRING_P(v)) {
6091 if (rb_str_cmp(vmax, v) < 0) {
6092 vmax = v;
6093 }
6094 }
6095 else {
6096 return ary_max_generic(ary, i, vmax);
6097 }
6098 }
6099
6100 return vmax;
6101}
6102
6103/*
6104 * call-seq:
6105 * max -> element
6106 * max(count) -> new_array
6107 * max {|a, b| ... } -> element
6108 * max(count) {|a, b| ... } -> new_array
6109 *
6110 * Returns one of the following:
6111 *
6112 * - The maximum-valued element from +self+.
6113 * - A new array of maximum-valued elements from +self+.
6114 *
6115 * Does not modify +self+.
6116 *
6117 * With no block given, each element in +self+ must respond to method <tt>#<=></tt>
6118 * with a numeric.
6119 *
6120 * With no argument and no block, returns the element in +self+
6121 * having the maximum value per method <tt>#<=></tt>:
6122 *
6123 * [1, 0, 3, 2].max # => 3
6124 *
6125 * With non-negative numeric argument +count+ and no block,
6126 * returns a new array with at most +count+ elements,
6127 * in descending order, per method <tt>#<=></tt>:
6128 *
6129 * [1, 0, 3, 2].max(3) # => [3, 2, 1]
6130 * [1, 0, 3, 2].max(3.0) # => [3, 2, 1]
6131 * [1, 0, 3, 2].max(9) # => [3, 2, 1, 0]
6132 * [1, 0, 3, 2].max(0) # => []
6133 *
6134 * With a block given, the block must return a numeric.
6135 *
6136 * With a block and no argument, calls the block <tt>self.size - 1</tt> times to compare elements;
6137 * returns the element having the maximum value per the block:
6138 *
6139 * ['0', '', '000', '00'].max {|a, b| a.size <=> b.size }
6140 * # => "000"
6141 *
6142 * With non-negative numeric argument +count+ and a block,
6143 * returns a new array with at most +count+ elements,
6144 * in descending order, per the block:
6145 *
6146 * ['0', '', '000', '00'].max(2) {|a, b| a.size <=> b.size }
6147 * # => ["000", "00"]
6148 *
6149 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
6150 */
6151static VALUE
6152rb_ary_max(int argc, VALUE *argv, VALUE ary)
6153{
6154 VALUE result = Qundef, v;
6155 VALUE num;
6156 long i;
6157
6158 if (rb_check_arity(argc, 0, 1) && !NIL_P(num = argv[0]))
6159 return rb_nmin_run(ary, num, 0, 1, 1);
6160
6161 const long n = RARRAY_LEN(ary);
6162 if (rb_block_given_p()) {
6163 for (i = 0; i < RARRAY_LEN(ary); i++) {
6164 v = RARRAY_AREF(ary, i);
6165 if (UNDEF_P(result) || rb_cmpint(rb_yield_values(2, v, result), v, result) > 0) {
6166 result = v;
6167 }
6168 }
6169 }
6170 else if (n > 0) {
6171 result = RARRAY_AREF(ary, 0);
6172 if (n > 1) {
6173 if (FIXNUM_P(result) && CMP_OPTIMIZABLE(INTEGER)) {
6174 return ary_max_opt_fixnum(ary, 1, result);
6175 }
6176 else if (STRING_P(result) && CMP_OPTIMIZABLE(STRING)) {
6177 return ary_max_opt_string(ary, 1, result);
6178 }
6179 else if (RB_FLOAT_TYPE_P(result) && CMP_OPTIMIZABLE(FLOAT)) {
6180 return ary_max_opt_float(ary, 1, result);
6181 }
6182 else {
6183 return ary_max_generic(ary, 1, result);
6184 }
6185 }
6186 }
6187 if (UNDEF_P(result)) return Qnil;
6188 return result;
6189}
6190
6191static VALUE
6192ary_min_generic(VALUE ary, long i, VALUE vmin)
6193{
6194 RUBY_ASSERT(i > 0 && i < RARRAY_LEN(ary));
6195
6196 VALUE v;
6197 for (; i < RARRAY_LEN(ary); ++i) {
6198 v = RARRAY_AREF(ary, i);
6199
6200 if (rb_cmpint(rb_funcallv(vmin, id_cmp, 1, &v), vmin, v) > 0) {
6201 vmin = v;
6202 }
6203 }
6204
6205 return vmin;
6206}
6207
6208static VALUE
6209ary_min_opt_fixnum(VALUE ary, long i, VALUE vmin)
6210{
6211 const long n = RARRAY_LEN(ary);
6212 RUBY_ASSERT(i > 0 && i < n);
6213 RUBY_ASSERT(FIXNUM_P(vmin));
6214
6215 VALUE a;
6216 for (; i < n; ++i) {
6217 a = RARRAY_AREF(ary, i);
6218
6219 if (FIXNUM_P(a)) {
6220 if ((long)vmin > (long)a) {
6221 vmin = a;
6222 }
6223 }
6224 else {
6225 return ary_min_generic(ary, i, vmin);
6226 }
6227 }
6228
6229 return vmin;
6230}
6231
6232static VALUE
6233ary_min_opt_float(VALUE ary, long i, VALUE vmin)
6234{
6235 const long n = RARRAY_LEN(ary);
6236 RUBY_ASSERT(i > 0 && i < n);
6237 RUBY_ASSERT(RB_FLOAT_TYPE_P(vmin));
6238
6239 VALUE a;
6240 for (; i < n; ++i) {
6241 a = RARRAY_AREF(ary, i);
6242
6243 if (RB_FLOAT_TYPE_P(a)) {
6244 if (rb_float_cmp(vmin, a) > 0) {
6245 vmin = a;
6246 }
6247 }
6248 else {
6249 return ary_min_generic(ary, i, vmin);
6250 }
6251 }
6252
6253 return vmin;
6254}
6255
6256static VALUE
6257ary_min_opt_string(VALUE ary, long i, VALUE vmin)
6258{
6259 const long n = RARRAY_LEN(ary);
6260 RUBY_ASSERT(i > 0 && i < n);
6261 RUBY_ASSERT(STRING_P(vmin));
6262
6263 VALUE a;
6264 for (; i < n; ++i) {
6265 a = RARRAY_AREF(ary, i);
6266
6267 if (STRING_P(a)) {
6268 if (rb_str_cmp(vmin, a) > 0) {
6269 vmin = a;
6270 }
6271 }
6272 else {
6273 return ary_min_generic(ary, i, vmin);
6274 }
6275 }
6276
6277 return vmin;
6278}
6279
6280/*
6281 * call-seq:
6282 * min -> element
6283 * min(count) -> new_array
6284 * min {|a, b| ... } -> element
6285 * min(count) {|a, b| ... } -> new_array
6286 *
6287 * Returns one of the following:
6288 *
6289 * - The minimum-valued element from +self+.
6290 * - A new array of minimum-valued elements from +self+.
6291 *
6292 * Does not modify +self+.
6293 *
6294 * With no block given, each element in +self+ must respond to method <tt>#<=></tt>
6295 * with a numeric.
6296 *
6297 * With no argument and no block, returns the element in +self+
6298 * having the minimum value per method <tt>#<=></tt>:
6299 *
6300 * [1, 0, 3, 2].min # => 0
6301 *
6302 * With non-negative numeric argument +count+ and no block,
6303 * returns a new array with at most +count+ elements,
6304 * in ascending order, per method <tt>#<=></tt>:
6305 *
6306 * [1, 0, 3, 2].min(3) # => [0, 1, 2]
6307 * [1, 0, 3, 2].min(3.0) # => [0, 1, 2]
6308 * [1, 0, 3, 2].min(9) # => [0, 1, 2, 3]
6309 * [1, 0, 3, 2].min(0) # => []
6310 *
6311 * With a block given, the block must return a numeric.
6312 *
6313 * With a block and no argument, calls the block <tt>self.size - 1</tt> times to compare elements;
6314 * returns the element having the minimum value per the block:
6315 *
6316 * ['0', '', '000', '00'].min {|a, b| a.size <=> b.size }
6317 * # => ""
6318 *
6319 * With non-negative numeric argument +count+ and a block,
6320 * returns a new array with at most +count+ elements,
6321 * in ascending order, per the block:
6322 *
6323 * ['0', '', '000', '00'].min(2) {|a, b| a.size <=> b.size }
6324 * # => ["", "0"]
6325 *
6326 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
6327 */
6328static VALUE
6329rb_ary_min(int argc, VALUE *argv, VALUE ary)
6330{
6331 VALUE result = Qundef, v;
6332 VALUE num;
6333 long i;
6334
6335 if (rb_check_arity(argc, 0, 1) && !NIL_P(num = argv[0]))
6336 return rb_nmin_run(ary, num, 0, 0, 1);
6337
6338 const long n = RARRAY_LEN(ary);
6339 if (rb_block_given_p()) {
6340 for (i = 0; i < RARRAY_LEN(ary); i++) {
6341 v = RARRAY_AREF(ary, i);
6342 if (UNDEF_P(result) || rb_cmpint(rb_yield_values(2, v, result), v, result) < 0) {
6343 result = v;
6344 }
6345 }
6346 }
6347 else if (n > 0) {
6348 result = RARRAY_AREF(ary, 0);
6349 if (n > 1) {
6350 if (FIXNUM_P(result) && CMP_OPTIMIZABLE(INTEGER)) {
6351 return ary_min_opt_fixnum(ary, 1, result);
6352 }
6353 else if (STRING_P(result) && CMP_OPTIMIZABLE(STRING)) {
6354 return ary_min_opt_string(ary, 1, result);
6355 }
6356 else if (RB_FLOAT_TYPE_P(result) && CMP_OPTIMIZABLE(FLOAT)) {
6357 return ary_min_opt_float(ary, 1, result);
6358 }
6359 else {
6360 return ary_min_generic(ary, 1, result);
6361 }
6362 }
6363 }
6364 if (UNDEF_P(result)) return Qnil;
6365 return result;
6366}
6367
6368/*
6369 * call-seq:
6370 * minmax -> array
6371 * minmax {|a, b| ... } -> array
6372 *
6373 * Returns a 2-element array containing the minimum-valued and maximum-valued
6374 * elements from +self+;
6375 * does not modify +self+.
6376 *
6377 * With no block given, the minimum and maximum values are determined using method <tt>#<=></tt>:
6378 *
6379 * [1, 0, 3, 2].minmax # => [0, 3]
6380 *
6381 * With a block given, the block must return a numeric;
6382 * the block is called <tt>self.size - 1</tt> times to compare elements;
6383 * returns the elements having the minimum and maximum values per the block:
6384 *
6385 * ['0', '', '000', '00'].minmax {|a, b| a.size <=> b.size }
6386 * # => ["", "000"]
6387 *
6388 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
6389 */
6390static VALUE
6391rb_ary_minmax(VALUE ary)
6392{
6393 if (rb_block_given_p()) {
6394 return rb_call_super(0, NULL);
6395 }
6396 return rb_assoc_new(rb_ary_min(0, 0, ary), rb_ary_max(0, 0, ary));
6397}
6398
6399static int
6400push_value(st_data_t key, st_data_t val, st_data_t ary)
6401{
6402 rb_ary_push((VALUE)ary, (VALUE)val);
6403 return ST_CONTINUE;
6404}
6405
6406/*
6407 * call-seq:
6408 * uniq! -> self or nil
6409 * uniq! {|element| ... } -> self or nil
6410 *
6411 * Removes duplicate elements from +self+, the first occurrence always being retained;
6412 * returns +self+ if any elements removed, +nil+ otherwise.
6413 *
6414 * With no block given, identifies and removes elements using method <tt>eql?</tt>
6415 * to compare elements:
6416 *
6417 * a = [0, 0, 1, 1, 2, 2]
6418 * a.uniq! # => [0, 1, 2]
6419 * a.uniq! # => nil
6420 *
6421 * With a block given, calls the block for each element;
6422 * identifies and omits "duplicate" elements using method <tt>eql?</tt>
6423 * to compare <i>block return values</i>;
6424 * that is, an element is a duplicate if its block return value
6425 * is the same as that of a previous element:
6426 *
6427 * a = ['a', 'aa', 'aaa', 'b', 'bb', 'bbb']
6428 * a.uniq! {|element| element.size } # => ["a", "aa", "aaa"]
6429 * a.uniq! {|element| element.size } # => nil
6430 *
6431 * Related: see {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
6432 */
6433static VALUE
6434rb_ary_uniq_bang(VALUE ary)
6435{
6436 VALUE hash;
6437 long hash_size;
6438
6439 rb_ary_modify_check(ary);
6440 if (RARRAY_LEN(ary) <= 1)
6441 return Qnil;
6442 if (rb_block_given_p())
6443 hash = ary_make_hash_by(ary);
6444 else
6445 hash = ary_make_hash(ary);
6446
6447 hash_size = RHASH_SIZE(hash);
6448 if (RARRAY_LEN(ary) == hash_size) {
6449 return Qnil;
6450 }
6451 rb_ary_modify_check(ary);
6452 ARY_SET_LEN(ary, 0);
6453 if (ARY_SHARED_P(ary)) {
6454 rb_ary_unshare(ary);
6455 FL_SET_EMBED(ary);
6456 }
6457 ary_resize_capa(ary, hash_size);
6458 rb_hash_foreach(hash, push_value, ary);
6459
6460 return ary;
6461}
6462
6463/*
6464 * call-seq:
6465 * uniq -> new_array
6466 * uniq {|element| ... } -> new_array
6467 *
6468 * Returns a new array containing those elements from +self+ that are not duplicates,
6469 * the first occurrence always being retained.
6470 *
6471 * With no block given, identifies and omits duplicate elements using method <tt>eql?</tt>
6472 * to compare elements:
6473 *
6474 * a = [0, 0, 1, 1, 2, 2]
6475 * a.uniq # => [0, 1, 2]
6476 *
6477 * With a block given, calls the block for each element;
6478 * identifies and omits "duplicate" elements using method <tt>eql?</tt>
6479 * to compare <i>block return values</i>;
6480 * that is, an element is a duplicate if its block return value
6481 * is the same as that of a previous element:
6482 *
6483 * a = ['a', 'aa', 'aaa', 'b', 'bb', 'bbb']
6484 * a.uniq {|element| element.size } # => ["a", "aa", "aaa"]
6485 *
6486 * Related: {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
6487 */
6488
6489static VALUE
6490rb_ary_uniq(VALUE ary)
6491{
6492 VALUE hash, uniq;
6493
6494 if (RARRAY_LEN(ary) <= 1) {
6495 hash = 0;
6496 uniq = rb_ary_dup(ary);
6497 }
6498 else if (rb_block_given_p()) {
6499 hash = ary_make_hash_by(ary);
6500 uniq = rb_hash_values(hash);
6501 }
6502 else {
6503 hash = ary_make_hash(ary);
6504 uniq = rb_hash_values(hash);
6505 }
6506
6507 return uniq;
6508}
6509
6510/*
6511 * call-seq:
6512 * compact! -> self or nil
6513 *
6514 * Removes all +nil+ elements from +self+;
6515 * Returns +self+ if any elements are removed, +nil+ otherwise:
6516 *
6517 * a = [nil, 0, nil, false, nil, '', nil, [], nil, {}]
6518 * a.compact! # => [0, false, "", [], {}]
6519 * a # => [0, false, "", [], {}]
6520 * a.compact! # => nil
6521 *
6522 * Related: Array#compact;
6523 * see also {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
6524 */
6525
6526VALUE
6527rb_ary_compact_bang(VALUE ary)
6528{
6529 VALUE *p, *t, *end;
6530 long n;
6531
6532 rb_ary_modify(ary);
6533 p = t = (VALUE *)RARRAY_CONST_PTR(ary); /* WB: no new reference */
6534 end = p + RARRAY_LEN(ary);
6535
6536 while (t < end) {
6537 if (NIL_P(*t)) t++;
6538 else *p++ = *t++;
6539 }
6540 n = p - RARRAY_CONST_PTR(ary);
6541 if (RARRAY_LEN(ary) == n) {
6542 return Qnil;
6543 }
6544 ary_resize_smaller(ary, n);
6545
6546 return ary;
6547}
6548
6549/*
6550 * call-seq:
6551 * compact -> new_array
6552 *
6553 * Returns a new array containing only the non-+nil+ elements from +self+;
6554 * element order is preserved:
6555 *
6556 * a = [nil, 0, nil, false, nil, '', nil, [], nil, {}]
6557 * a.compact # => [0, false, "", [], {}]
6558 *
6559 * Related: Array#compact!;
6560 * see also {Methods for Deleting}[rdoc-ref:Array@Methods+for+Deleting].
6561 */
6562
6563static VALUE
6564rb_ary_compact(VALUE ary)
6565{
6566 ary = rb_ary_dup(ary);
6567 rb_ary_compact_bang(ary);
6568 return ary;
6569}
6570
6571/*
6572 * call-seq:
6573 * count -> integer
6574 * count(object) -> integer
6575 * count {|element| ... } -> integer
6576 *
6577 * Returns a count of specified elements.
6578 *
6579 * With no argument and no block, returns the count of all elements:
6580 *
6581 * [0, :one, 'two', 3, 3.0].count # => 5
6582 *
6583 * With argument +object+ given, returns the count of elements <tt>==</tt> to +object+:
6584 *
6585 * [0, :one, 'two', 3, 3.0].count(3) # => 2
6586 *
6587 * With no argument and a block given, calls the block with each element;
6588 * returns the count of elements for which the block returns a truthy value:
6589 *
6590 * [0, 1, 2, 3].count {|element| element > 1 } # => 2
6591 *
6592 * With argument +object+ and a block given, issues a warning, ignores the block,
6593 * and returns the count of elements <tt>==</tt> to +object+.
6594 *
6595 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
6596 */
6597
6598static VALUE
6599rb_ary_count(int argc, VALUE *argv, VALUE ary)
6600{
6601 long i, n = 0;
6602
6603 if (rb_check_arity(argc, 0, 1) == 0) {
6604 VALUE v;
6605
6606 if (!rb_block_given_p())
6607 return LONG2NUM(RARRAY_LEN(ary));
6608
6609 for (i = 0; i < RARRAY_LEN(ary); i++) {
6610 v = RARRAY_AREF(ary, i);
6611 if (RTEST(rb_yield(v))) n++;
6612 }
6613 }
6614 else {
6615 VALUE obj = argv[0];
6616
6617 if (rb_block_given_p()) {
6618 rb_warn("given block not used");
6619 }
6620 for (i = 0; i < RARRAY_LEN(ary); i++) {
6621 if (rb_equal(RARRAY_AREF(ary, i), obj)) n++;
6622 }
6623 }
6624
6625 return LONG2NUM(n);
6626}
6627
6628static VALUE
6629flatten(VALUE ary, int level)
6630{
6631 long i;
6632 VALUE stack, result, tmp = 0, elt;
6633 VALUE memo = Qfalse;
6634
6635 for (i = 0; i < RARRAY_LEN(ary); i++) {
6636 elt = RARRAY_AREF(ary, i);
6637 tmp = rb_check_array_type(elt);
6638 if (!NIL_P(tmp)) {
6639 break;
6640 }
6641 }
6642 if (i == RARRAY_LEN(ary)) {
6643 return ary;
6644 }
6645
6646 result = ary_new(0, RARRAY_LEN(ary));
6647 ary_memcpy(result, 0, i, RARRAY_CONST_PTR(ary));
6648 ARY_SET_LEN(result, i);
6649
6650 stack = ary_new(0, ARY_DEFAULT_SIZE);
6651 rb_ary_push(stack, ary);
6652 rb_ary_push(stack, LONG2NUM(i + 1));
6653
6654 if (level < 0) {
6655 memo = rb_obj_hide(rb_ident_hash_new());
6656 rb_hash_aset(memo, ary, Qtrue);
6657 rb_hash_aset(memo, tmp, Qtrue);
6658 }
6659
6660 ary = tmp;
6661 i = 0;
6662
6663 while (1) {
6664 while (i < RARRAY_LEN(ary)) {
6665 elt = RARRAY_AREF(ary, i++);
6666 if (level >= 0 && RARRAY_LEN(stack) / 2 >= level) {
6667 rb_ary_push(result, elt);
6668 continue;
6669 }
6670 tmp = rb_check_array_type(elt);
6671 if (RBASIC(result)->klass) {
6672 if (RTEST(memo)) {
6673 rb_hash_clear(memo);
6674 }
6675 rb_raise(rb_eRuntimeError, "flatten reentered");
6676 }
6677 if (NIL_P(tmp)) {
6678 rb_ary_push(result, elt);
6679 }
6680 else {
6681 if (memo) {
6682 if (rb_hash_aref(memo, tmp) == Qtrue) {
6683 rb_hash_clear(memo);
6684 rb_raise(rb_eArgError, "tried to flatten recursive array");
6685 }
6686 rb_hash_aset(memo, tmp, Qtrue);
6687 }
6688 rb_ary_push(stack, ary);
6689 rb_ary_push(stack, LONG2NUM(i));
6690 ary = tmp;
6691 i = 0;
6692 }
6693 }
6694 if (RARRAY_LEN(stack) == 0) {
6695 break;
6696 }
6697 if (memo) {
6698 rb_hash_delete(memo, ary);
6699 }
6700 tmp = rb_ary_pop(stack);
6701 i = NUM2LONG(tmp);
6702 ary = rb_ary_pop(stack);
6703 }
6704
6705 if (memo) {
6706 rb_hash_clear(memo);
6707 }
6708
6709 RBASIC_SET_CLASS(result, rb_cArray);
6710 return result;
6711}
6712
6713/*
6714 * call-seq:
6715 * flatten!(depth = nil) -> self or nil
6716 *
6717 * Returns +self+ as a recursively flattening of +self+ to +depth+ levels of recursion;
6718 * +depth+ must be an
6719 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects],
6720 * or +nil+.
6721 * At each level of recursion:
6722 *
6723 * - Each element that is an array is "flattened"
6724 * (that is, replaced by its individual array elements).
6725 * - Each element that is not an array is unchanged
6726 * (even if the element is an object that has instance method +flatten+).
6727 *
6728 * Returns +nil+ if no elements were flattened.
6729 *
6730 * With non-negative integer argument +depth+, flattens recursively through +depth+ levels:
6731 *
6732 * a = [ 0, [ 1, [2, 3], 4 ], 5, {foo: 0}, Set.new([6, 7]) ]
6733 * a # => [0, [1, [2, 3], 4], 5, {:foo=>0}, #<Set: {6, 7}>]
6734 * a.dup.flatten!(1) # => [0, 1, [2, 3], 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6735 * a.dup.flatten!(1.1) # => [0, 1, [2, 3], 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6736 * a.dup.flatten!(2) # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6737 * a.dup.flatten!(3) # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6738 *
6739 * With +nil+ or negative argument +depth+, flattens all levels:
6740 *
6741 * a.dup.flatten! # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6742 * a.dup.flatten!(-1) # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6743 *
6744 * Related: Array#flatten;
6745 * see also {Methods for Assigning}[rdoc-ref:Array@Methods+for+Assigning].
6746 */
6747
6748static VALUE
6749rb_ary_flatten_bang(int argc, VALUE *argv, VALUE ary)
6750{
6751 int mod = 0, level = -1;
6752 VALUE result, lv;
6753
6754 lv = (rb_check_arity(argc, 0, 1) ? argv[0] : Qnil);
6755 rb_ary_modify_check(ary);
6756 if (!NIL_P(lv)) level = NUM2INT(lv);
6757 if (level == 0) return Qnil;
6758
6759 result = flatten(ary, level);
6760 if (result == ary) {
6761 return Qnil;
6762 }
6763 if (!(mod = ARY_EMBED_P(result))) rb_ary_freeze(result);
6764 rb_ary_replace(ary, result);
6765 if (mod) ARY_SET_EMBED_LEN(result, 0);
6766
6767 return ary;
6768}
6769
6770/*
6771 * call-seq:
6772 * flatten(depth = nil) -> new_array
6773 *
6774 * Returns a new array that is a recursive flattening of +self+
6775 * to +depth+ levels of recursion;
6776 * +depth+ must be an
6777 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects]
6778 * or +nil+.
6779 * At each level of recursion:
6780 *
6781 * - Each element that is an array is "flattened"
6782 * (that is, replaced by its individual array elements).
6783 * - Each element that is not an array is unchanged
6784 * (even if the element is an object that has instance method +flatten+).
6785 *
6786 * With non-negative integer argument +depth+, flattens recursively through +depth+ levels:
6787 *
6788 * a = [ 0, [ 1, [2, 3], 4 ], 5, {foo: 0}, Set.new([6, 7]) ]
6789 * a # => [0, [1, [2, 3], 4], 5, {:foo=>0}, #<Set: {6, 7}>]
6790 * a.flatten(0) # => [0, [1, [2, 3], 4], 5, {:foo=>0}, #<Set: {6, 7}>]
6791 * a.flatten(1 ) # => [0, 1, [2, 3], 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6792 * a.flatten(1.1) # => [0, 1, [2, 3], 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6793 * a.flatten(2) # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6794 * a.flatten(3) # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6795 *
6796 * With +nil+ or negative +depth+, flattens all levels.
6797 *
6798 * a.flatten # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6799 * a.flatten(-1) # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]
6800 *
6801 * Related: Array#flatten!;
6802 * see also {Methods for Converting}[rdoc-ref:Array@Methods+for+Converting].
6803 */
6804
6805static VALUE
6806rb_ary_flatten(int argc, VALUE *argv, VALUE ary)
6807{
6808 int level = -1;
6809 VALUE result;
6810
6811 if (rb_check_arity(argc, 0, 1) && !NIL_P(argv[0])) {
6812 level = NUM2INT(argv[0]);
6813 if (level == 0) return ary_make_shared_copy(ary);
6814 }
6815
6816 result = flatten(ary, level);
6817 if (result == ary) {
6818 result = ary_make_shared_copy(ary);
6819 }
6820
6821 return result;
6822}
6823
6824#define RAND_UPTO(max) (long)rb_random_ulong_limited((randgen), (max)-1)
6825
6826static VALUE
6827rb_ary_shuffle_bang(rb_execution_context_t *ec, VALUE ary, VALUE randgen)
6828{
6829 long i, len;
6830
6831 rb_ary_modify(ary);
6832 i = len = RARRAY_LEN(ary);
6833 RARRAY_PTR_USE(ary, ptr, {
6834 while (i > 1) {
6835 long j = RAND_UPTO(i);
6836 VALUE tmp;
6837 if (len != RARRAY_LEN(ary) || ptr != RARRAY_CONST_PTR(ary)) {
6838 rb_raise(rb_eRuntimeError, "modified during shuffle");
6839 }
6840 tmp = ptr[--i];
6841 ptr[i] = ptr[j];
6842 ptr[j] = tmp;
6843 }
6844 }); /* WB: no new reference */
6845 return ary;
6846}
6847
6848static VALUE
6849rb_ary_shuffle(rb_execution_context_t *ec, VALUE ary, VALUE randgen)
6850{
6851 ary = rb_ary_dup(ary);
6852 rb_ary_shuffle_bang(ec, ary, randgen);
6853 return ary;
6854}
6855
6856static const rb_data_type_t ary_sample_memo_type = {
6857 .wrap_struct_name = "ary_sample_memo",
6858 .function = {
6859 .dfree = (RUBY_DATA_FUNC)st_free_table,
6860 },
6861 .flags = RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY
6862};
6863
6864static VALUE
6865ary_sample(rb_execution_context_t *ec, VALUE ary, VALUE randgen, VALUE nv, VALUE to_array)
6866{
6867 VALUE result;
6868 long n, len, i, j, k, idx[10];
6869 long rnds[numberof(idx)];
6870 long memo_threshold;
6871
6872 len = RARRAY_LEN(ary);
6873 if (!to_array) {
6874 if (len < 2)
6875 i = 0;
6876 else
6877 i = RAND_UPTO(len);
6878
6879 return rb_ary_elt(ary, i);
6880 }
6881 n = NUM2LONG(nv);
6882 if (n < 0) rb_raise(rb_eArgError, "negative sample number");
6883 if (n > len) n = len;
6884 if (n <= numberof(idx)) {
6885 for (i = 0; i < n; ++i) {
6886 rnds[i] = RAND_UPTO(len - i);
6887 }
6888 }
6889 k = len;
6890 len = RARRAY_LEN(ary);
6891 if (len < k && n <= numberof(idx)) {
6892 for (i = 0; i < n; ++i) {
6893 if (rnds[i] >= len) return rb_ary_new_capa(0);
6894 }
6895 }
6896 if (n > len) n = len;
6897 switch (n) {
6898 case 0:
6899 return rb_ary_new_capa(0);
6900 case 1:
6901 i = rnds[0];
6902 return rb_ary_new_from_args(1, RARRAY_AREF(ary, i));
6903 case 2:
6904 i = rnds[0];
6905 j = rnds[1];
6906 if (j >= i) j++;
6907 return rb_ary_new_from_args(2, RARRAY_AREF(ary, i), RARRAY_AREF(ary, j));
6908 case 3:
6909 i = rnds[0];
6910 j = rnds[1];
6911 k = rnds[2];
6912 {
6913 long l = j, g = i;
6914 if (j >= i) l = i, g = ++j;
6915 if (k >= l && (++k >= g)) ++k;
6916 }
6917 return rb_ary_new_from_args(3, RARRAY_AREF(ary, i), RARRAY_AREF(ary, j), RARRAY_AREF(ary, k));
6918 }
6919 memo_threshold =
6920 len < 2560 ? len / 128 :
6921 len < 5120 ? len / 64 :
6922 len < 10240 ? len / 32 :
6923 len / 16;
6924 if (n <= numberof(idx)) {
6925 long sorted[numberof(idx)];
6926 sorted[0] = idx[0] = rnds[0];
6927 for (i=1; i<n; i++) {
6928 k = rnds[i];
6929 for (j = 0; j < i; ++j) {
6930 if (k < sorted[j]) break;
6931 ++k;
6932 }
6933 memmove(&sorted[j+1], &sorted[j], sizeof(sorted[0])*(i-j));
6934 sorted[j] = idx[i] = k;
6935 }
6936 result = rb_ary_new_capa(n);
6937 RARRAY_PTR_USE(result, ptr_result, {
6938 for (i=0; i<n; i++) {
6939 ptr_result[i] = RARRAY_AREF(ary, idx[i]);
6940 }
6941 });
6942 }
6943 else if (n <= memo_threshold / 2) {
6944 long max_idx = 0;
6945 VALUE vmemo = TypedData_Wrap_Struct(0, &ary_sample_memo_type, 0);
6946 st_table *memo = st_init_numtable_with_size(n);
6947 RTYPEDDATA_DATA(vmemo) = memo;
6948 result = rb_ary_new_capa(n);
6949 RARRAY_PTR_USE(result, ptr_result, {
6950 for (i=0; i<n; i++) {
6951 long r = RAND_UPTO(len-i) + i;
6952 ptr_result[i] = r;
6953 if (r > max_idx) max_idx = r;
6954 }
6955 len = RARRAY_LEN(ary);
6956 if (len <= max_idx) n = 0;
6957 else if (n > len) n = len;
6958 RARRAY_PTR_USE(ary, ptr_ary, {
6959 for (i=0; i<n; i++) {
6960 long j2 = j = ptr_result[i];
6961 long i2 = i;
6962 st_data_t value;
6963 if (st_lookup(memo, (st_data_t)i, &value)) i2 = (long)value;
6964 if (st_lookup(memo, (st_data_t)j, &value)) j2 = (long)value;
6965 st_insert(memo, (st_data_t)j, (st_data_t)i2);
6966 ptr_result[i] = ptr_ary[j2];
6967 }
6968 });
6969 });
6970 RTYPEDDATA_DATA(vmemo) = 0;
6971 st_free_table(memo);
6972 RB_GC_GUARD(vmemo);
6973 }
6974 else {
6975 result = rb_ary_dup(ary);
6976 RBASIC_CLEAR_CLASS(result);
6977 RB_GC_GUARD(ary);
6978 RARRAY_PTR_USE(result, ptr_result, {
6979 for (i=0; i<n; i++) {
6980 j = RAND_UPTO(len-i) + i;
6981 nv = ptr_result[j];
6982 ptr_result[j] = ptr_result[i];
6983 ptr_result[i] = nv;
6984 }
6985 });
6986 RBASIC_SET_CLASS_RAW(result, rb_cArray);
6987 }
6988 ARY_SET_LEN(result, n);
6989
6990 return result;
6991}
6992
6993static VALUE
6994ary_sized_alloc(rb_execution_context_t *ec, VALUE self)
6995{
6996 return rb_ary_new2(RARRAY_LEN(self));
6997}
6998
6999static VALUE
7000ary_sample0(rb_execution_context_t *ec, VALUE ary)
7001{
7002 return ary_sample(ec, ary, rb_cRandom, Qfalse, Qfalse);
7003}
7004
7005static VALUE
7006rb_ary_cycle_size(VALUE self, VALUE args, VALUE eobj)
7007{
7008 long mul;
7009 VALUE n = Qnil;
7010 if (args && (RARRAY_LEN(args) > 0)) {
7011 n = RARRAY_AREF(args, 0);
7012 }
7013 if (RARRAY_LEN(self) == 0) return INT2FIX(0);
7014 if (NIL_P(n)) return DBL2NUM(HUGE_VAL);
7015 mul = NUM2LONG(n);
7016 if (mul <= 0) return INT2FIX(0);
7017 n = LONG2FIX(mul);
7018 return rb_fix_mul_fix(rb_ary_length(self), n);
7019}
7020
7021/*
7022 * call-seq:
7023 * cycle(count = nil) {|element| ... } -> nil
7024 * cycle(count = nil) -> new_enumerator
7025 *
7026 * With a block given, may call the block, depending on the value of argument +count+;
7027 * +count+ must be an
7028 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects],
7029 * or +nil+.
7030 *
7031 * When +count+ is positive,
7032 * calls the block with each element, then does so repeatedly,
7033 * until it has done so +count+ times; returns +nil+:
7034 *
7035 * output = []
7036 * [0, 1].cycle(2) {|element| output.push(element) } # => nil
7037 * output # => [0, 1, 0, 1]
7038 *
7039 * When +count+ is zero or negative, does not call the block:
7040 *
7041 * [0, 1].cycle(0) {|element| fail 'Cannot happen' } # => nil
7042 * [0, 1].cycle(-1) {|element| fail 'Cannot happen' } # => nil
7043 *
7044 * When +count+ is +nil+, cycles forever:
7045 *
7046 * # Prints 0 and 1 forever.
7047 * [0, 1].cycle {|element| puts element }
7048 * [0, 1].cycle(nil) {|element| puts element }
7049 *
7050 * With no block given, returns a new Enumerator.
7051 *
7052 * Related: see {Methods for Iterating}[rdoc-ref:Array@Methods+for+Iterating].
7053 */
7054static VALUE
7055rb_ary_cycle(int argc, VALUE *argv, VALUE ary)
7056{
7057 long n, i;
7058
7059 rb_check_arity(argc, 0, 1);
7060
7061 RETURN_SIZED_ENUMERATOR(ary, argc, argv, rb_ary_cycle_size);
7062 if (argc == 0 || NIL_P(argv[0])) {
7063 n = -1;
7064 }
7065 else {
7066 n = NUM2LONG(argv[0]);
7067 if (n <= 0) return Qnil;
7068 }
7069
7070 while (RARRAY_LEN(ary) > 0 && (n < 0 || 0 < n--)) {
7071 for (i=0; i<RARRAY_LEN(ary); i++) {
7072 rb_yield(RARRAY_AREF(ary, i));
7073 }
7074 }
7075 return Qnil;
7076}
7077
7078/*
7079 * Build a ruby array of the corresponding values and yield it to the
7080 * associated block.
7081 * Return the class of +values+ for reentry check.
7082 */
7083static int
7084yield_indexed_values(const VALUE values, const long r, const long *const p)
7085{
7086 const VALUE result = rb_ary_new2(r);
7087 long i;
7088
7089 for (i = 0; i < r; i++) ARY_SET(result, i, RARRAY_AREF(values, p[i]));
7090 ARY_SET_LEN(result, r);
7091 rb_yield(result);
7092 return !RBASIC(values)->klass;
7093}
7094
7095/*
7096 * Compute permutations of +r+ elements of the set <code>[0..n-1]</code>.
7097 *
7098 * When we have a complete permutation of array indices, copy the values
7099 * at those indices into a new array and yield that array.
7100 *
7101 * n: the size of the set
7102 * r: the number of elements in each permutation
7103 * p: the array (of size r) that we're filling in
7104 * used: an array of booleans: whether a given index is already used
7105 * values: the Ruby array that holds the actual values to permute
7106 */
7107static void
7108permute0(const long n, const long r, long *const p, char *const used, const VALUE values)
7109{
7110 long i = 0, index = 0;
7111
7112 for (;;) {
7113 const char *const unused = memchr(&used[i], 0, n-i);
7114 if (!unused) {
7115 if (!index) break;
7116 i = p[--index]; /* pop index */
7117 used[i++] = 0; /* index unused */
7118 }
7119 else {
7120 i = unused - used;
7121 p[index] = i;
7122 used[i] = 1; /* mark index used */
7123 ++index;
7124 if (index < r-1) { /* if not done yet */
7125 p[index] = i = 0;
7126 continue;
7127 }
7128 for (i = 0; i < n; ++i) {
7129 if (used[i]) continue;
7130 p[index] = i;
7131 if (!yield_indexed_values(values, r, p)) {
7132 rb_raise(rb_eRuntimeError, "permute reentered");
7133 }
7134 }
7135 i = p[--index]; /* pop index */
7136 used[i] = 0; /* index unused */
7137 p[index] = ++i;
7138 }
7139 }
7140}
7141
7142/*
7143 * Returns the product of from, from-1, ..., from - how_many + 1.
7144 * https://en.wikipedia.org/wiki/Pochhammer_symbol
7145 */
7146static VALUE
7147descending_factorial(long from, long how_many)
7148{
7149 VALUE cnt;
7150 if (how_many > 0) {
7151 cnt = LONG2FIX(from);
7152 while (--how_many > 0) {
7153 long v = --from;
7154 cnt = rb_int_mul(cnt, LONG2FIX(v));
7155 }
7156 }
7157 else {
7158 cnt = LONG2FIX(how_many == 0);
7159 }
7160 return cnt;
7161}
7162
7163static VALUE
7164binomial_coefficient(long comb, long size)
7165{
7166 VALUE r;
7167 long i;
7168 if (comb > size-comb) {
7169 comb = size-comb;
7170 }
7171 if (comb < 0) {
7172 return LONG2FIX(0);
7173 }
7174 else if (comb == 0) {
7175 return LONG2FIX(1);
7176 }
7177 r = LONG2FIX(size);
7178 for (i = 1; i < comb; ++i) {
7179 r = rb_int_mul(r, LONG2FIX(size - i));
7180 r = rb_int_idiv(r, LONG2FIX(i + 1));
7181 }
7182 return r;
7183}
7184
7185static VALUE
7186rb_ary_permutation_size(VALUE ary, VALUE args, VALUE eobj)
7187{
7188 long n = RARRAY_LEN(ary);
7189 long k = (args && (RARRAY_LEN(args) > 0)) ? NUM2LONG(RARRAY_AREF(args, 0)) : n;
7190
7191 return descending_factorial(n, k);
7192}
7193
7194/*
7195 * call-seq:
7196 * permutation(count = self.size) {|permutation| ... } -> self
7197 * permutation(count = self.size) -> new_enumerator
7198 *
7199 * Iterates over permutations of the elements of +self+;
7200 * the order of permutations is indeterminate.
7201 *
7202 * With a block and an in-range positive integer argument +count+ (<tt>0 < count <= self.size</tt>) given,
7203 * calls the block with each permutation of +self+ of size +count+;
7204 * returns +self+:
7205 *
7206 * a = [0, 1, 2]
7207 * perms = []
7208 * a.permutation(1) {|perm| perms.push(perm) }
7209 * perms # => [[0], [1], [2]]
7210 *
7211 * perms = []
7212 * a.permutation(2) {|perm| perms.push(perm) }
7213 * perms # => [[0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]]
7214 *
7215 * perms = []
7216 * a.permutation(3) {|perm| perms.push(perm) }
7217 * perms # => [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]
7218 *
7219 * When +count+ is zero, calls the block once with a new empty array:
7220 *
7221 * perms = []
7222 * a.permutation(0) {|perm| perms.push(perm) }
7223 * perms # => [[]]
7224 *
7225 * When +count+ is out of range (negative or larger than <tt>self.size</tt>),
7226 * does not call the block:
7227 *
7228 * a.permutation(-1) {|permutation| fail 'Cannot happen' }
7229 * a.permutation(4) {|permutation| fail 'Cannot happen' }
7230 *
7231 * With no block given, returns a new Enumerator.
7232 *
7233 * Related: {Methods for Iterating}[rdoc-ref:Array@Methods+for+Iterating].
7234 */
7235
7236static VALUE
7237rb_ary_permutation(int argc, VALUE *argv, VALUE ary)
7238{
7239 long r, n, i;
7240
7241 n = RARRAY_LEN(ary); /* Array length */
7242 RETURN_SIZED_ENUMERATOR(ary, argc, argv, rb_ary_permutation_size); /* Return enumerator if no block */
7243 r = n;
7244 if (rb_check_arity(argc, 0, 1) && !NIL_P(argv[0]))
7245 r = NUM2LONG(argv[0]); /* Permutation size from argument */
7246
7247 if (r < 0 || n < r) {
7248 /* no permutations: yield nothing */
7249 }
7250 else if (r == 0) { /* exactly one permutation: the zero-length array */
7252 }
7253 else if (r == 1) { /* this is a special, easy case */
7254 for (i = 0; i < RARRAY_LEN(ary); i++) {
7255 rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i)));
7256 }
7257 }
7258 else { /* this is the general case */
7259 volatile VALUE t0;
7260 long *p = ALLOCV_N(long, t0, r+roomof(n, sizeof(long)));
7261 char *used = (char*)(p + r);
7262 VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
7263 RBASIC_CLEAR_CLASS(ary0);
7264
7265 MEMZERO(used, char, n); /* initialize array */
7266
7267 permute0(n, r, p, used, ary0); /* compute and yield permutations */
7268 ALLOCV_END(t0);
7269 RBASIC_SET_CLASS_RAW(ary0, rb_cArray);
7270 }
7271 return ary;
7272}
7273
7274static void
7275combinate0(const long len, const long n, long *const stack, const VALUE values)
7276{
7277 long lev = 0;
7278
7279 MEMZERO(stack+1, long, n);
7280 stack[0] = -1;
7281 for (;;) {
7282 for (lev++; lev < n; lev++) {
7283 stack[lev+1] = stack[lev]+1;
7284 }
7285 if (!yield_indexed_values(values, n, stack+1)) {
7286 rb_raise(rb_eRuntimeError, "combination reentered");
7287 }
7288 do {
7289 if (lev == 0) return;
7290 stack[lev--]++;
7291 } while (stack[lev+1]+n == len+lev+1);
7292 }
7293}
7294
7295static VALUE
7296rb_ary_combination_size(VALUE ary, VALUE args, VALUE eobj)
7297{
7298 long n = RARRAY_LEN(ary);
7299 long k = NUM2LONG(RARRAY_AREF(args, 0));
7300
7301 return binomial_coefficient(k, n);
7302}
7303
7304/*
7305 * call-seq:
7306 * combination(count) {|element| ... } -> self
7307 * combination(count) -> new_enumerator
7308 *
7309 * When a block and a positive
7310 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects]
7311 * argument +count+ (<tt>0 < count <= self.size</tt>)
7312 * are given, calls the block with each combination of +self+ of size +count+;
7313 * returns +self+:
7314 *
7315 * a = %w[a b c] # => ["a", "b", "c"]
7316 * a.combination(2) {|combination| p combination } # => ["a", "b", "c"]
7317 *
7318 * Output:
7319 *
7320 * ["a", "b"]
7321 * ["a", "c"]
7322 * ["b", "c"]
7323 *
7324 * The order of the yielded combinations is not guaranteed.
7325 *
7326 * When +count+ is zero, calls the block once with a new empty array:
7327 *
7328 * a.combination(0) {|combination| p combination }
7329 * [].combination(0) {|combination| p combination }
7330 *
7331 * Output:
7332 *
7333 * []
7334 * []
7335 *
7336 * When +count+ is negative or larger than +self.size+ and +self+ is non-empty,
7337 * does not call the block:
7338 *
7339 * a.combination(-1) {|combination| fail 'Cannot happen' } # => ["a", "b", "c"]
7340 * a.combination(4) {|combination| fail 'Cannot happen' } # => ["a", "b", "c"]
7341 *
7342 * With no block given, returns a new Enumerator.
7343 *
7344 * Related: Array#permutation;
7345 * see also {Methods for Iterating}[rdoc-ref:Array@Methods+for+Iterating].
7346 */
7347
7348static VALUE
7349rb_ary_combination(VALUE ary, VALUE num)
7350{
7351 long i, n, len;
7352
7353 n = NUM2LONG(num);
7354 RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_combination_size);
7355 len = RARRAY_LEN(ary);
7356 if (n < 0 || len < n) {
7357 /* yield nothing */
7358 }
7359 else if (n == 0) {
7361 }
7362 else if (n == 1) {
7363 for (i = 0; i < RARRAY_LEN(ary); i++) {
7364 rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i)));
7365 }
7366 }
7367 else {
7368 VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
7369 volatile VALUE t0;
7370 long *stack = ALLOCV_N(long, t0, n+1);
7371
7372 RBASIC_CLEAR_CLASS(ary0);
7373 combinate0(len, n, stack, ary0);
7374 ALLOCV_END(t0);
7375 RBASIC_SET_CLASS_RAW(ary0, rb_cArray);
7376 }
7377 return ary;
7378}
7379
7380/*
7381 * Compute repeated permutations of +r+ elements of the set
7382 * <code>[0..n-1]</code>.
7383 *
7384 * When we have a complete repeated permutation of array indices, copy the
7385 * values at those indices into a new array and yield that array.
7386 *
7387 * n: the size of the set
7388 * r: the number of elements in each permutation
7389 * p: the array (of size r) that we're filling in
7390 * values: the Ruby array that holds the actual values to permute
7391 */
7392static void
7393rpermute0(const long n, const long r, long *const p, const VALUE values)
7394{
7395 long i = 0, index = 0;
7396
7397 p[index] = i;
7398 for (;;) {
7399 if (++index < r-1) {
7400 p[index] = i = 0;
7401 continue;
7402 }
7403 for (i = 0; i < n; ++i) {
7404 p[index] = i;
7405 if (!yield_indexed_values(values, r, p)) {
7406 rb_raise(rb_eRuntimeError, "repeated permute reentered");
7407 }
7408 }
7409 do {
7410 if (index <= 0) return;
7411 } while ((i = ++p[--index]) >= n);
7412 }
7413}
7414
7415static VALUE
7416rb_ary_repeated_permutation_size(VALUE ary, VALUE args, VALUE eobj)
7417{
7418 long n = RARRAY_LEN(ary);
7419 long k = NUM2LONG(RARRAY_AREF(args, 0));
7420
7421 if (k < 0) {
7422 return LONG2FIX(0);
7423 }
7424 if (n <= 0) {
7425 return LONG2FIX(!k);
7426 }
7427 return rb_int_positive_pow(n, (unsigned long)k);
7428}
7429
7430/*
7431 * call-seq:
7432 * repeated_permutation(size) {|permutation| ... } -> self
7433 * repeated_permutation(size) -> new_enumerator
7434 *
7435 * With a block given, calls the block with each repeated permutation of length +size+
7436 * of the elements of +self+;
7437 * each permutation is an array;
7438 * returns +self+. The order of the permutations is indeterminate.
7439 *
7440 * If a positive integer argument +size+ is given,
7441 * calls the block with each +size+-tuple repeated permutation of the elements of +self+.
7442 * The number of permutations is <tt>self.size**size</tt>.
7443 *
7444 * Examples:
7445 *
7446 * - +size+ is 1:
7447 *
7448 * p = []
7449 * [0, 1, 2].repeated_permutation(1) {|permutation| p.push(permutation) }
7450 * p # => [[0], [1], [2]]
7451 *
7452 * - +size+ is 2:
7453 *
7454 * p = []
7455 * [0, 1, 2].repeated_permutation(2) {|permutation| p.push(permutation) }
7456 * p # => [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
7457 *
7458 * If +size+ is zero, calls the block once with an empty array.
7459 *
7460 * If +size+ is negative, does not call the block:
7461 *
7462 * [0, 1, 2].repeated_permutation(-1) {|permutation| fail 'Cannot happen' }
7463 *
7464 * With no block given, returns a new Enumerator.
7465 *
7466 * Related: see {Methods for Combining}[rdoc-ref:Array@Methods+for+Combining].
7467 */
7468static VALUE
7469rb_ary_repeated_permutation(VALUE ary, VALUE num)
7470{
7471 long r, n, i;
7472
7473 n = RARRAY_LEN(ary); /* Array length */
7474 RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_repeated_permutation_size); /* Return Enumerator if no block */
7475 r = NUM2LONG(num); /* Permutation size from argument */
7476
7477 if (r < 0) {
7478 /* no permutations: yield nothing */
7479 }
7480 else if (r == 0) { /* exactly one permutation: the zero-length array */
7482 }
7483 else if (r == 1) { /* this is a special, easy case */
7484 for (i = 0; i < RARRAY_LEN(ary); i++) {
7485 rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i)));
7486 }
7487 }
7488 else { /* this is the general case */
7489 volatile VALUE t0;
7490 long *p = ALLOCV_N(long, t0, r);
7491 VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
7492 RBASIC_CLEAR_CLASS(ary0);
7493
7494 rpermute0(n, r, p, ary0); /* compute and yield repeated permutations */
7495 ALLOCV_END(t0);
7496 RBASIC_SET_CLASS_RAW(ary0, rb_cArray);
7497 }
7498 return ary;
7499}
7500
7501static void
7502rcombinate0(const long n, const long r, long *const p, const long rest, const VALUE values)
7503{
7504 long i = 0, index = 0;
7505
7506 p[index] = i;
7507 for (;;) {
7508 if (++index < r-1) {
7509 p[index] = i;
7510 continue;
7511 }
7512 for (; i < n; ++i) {
7513 p[index] = i;
7514 if (!yield_indexed_values(values, r, p)) {
7515 rb_raise(rb_eRuntimeError, "repeated combination reentered");
7516 }
7517 }
7518 do {
7519 if (index <= 0) return;
7520 } while ((i = ++p[--index]) >= n);
7521 }
7522}
7523
7524static VALUE
7525rb_ary_repeated_combination_size(VALUE ary, VALUE args, VALUE eobj)
7526{
7527 long n = RARRAY_LEN(ary);
7528 long k = NUM2LONG(RARRAY_AREF(args, 0));
7529 if (k == 0) {
7530 return LONG2FIX(1);
7531 }
7532 return binomial_coefficient(k, n + k - 1);
7533}
7534
7535/*
7536 * call-seq:
7537 * repeated_combination(size) {|combination| ... } -> self
7538 * repeated_combination(size) -> new_enumerator
7539 *
7540 * With a block given, calls the block with each repeated combination of length +size+
7541 * of the elements of +self+;
7542 * each combination is an array;
7543 * returns +self+. The order of the combinations is indeterminate.
7544 *
7545 * If a positive integer argument +size+ is given,
7546 * calls the block with each +size+-tuple repeated combination of the elements of +self+.
7547 * The number of combinations is <tt>(size+1)(size+2)/2</tt>.
7548 *
7549 * Examples:
7550 *
7551 * - +size+ is 1:
7552 *
7553 * c = []
7554 * [0, 1, 2].repeated_combination(1) {|combination| c.push(combination) }
7555 * c # => [[0], [1], [2]]
7556 *
7557 * - +size+ is 2:
7558 *
7559 * c = []
7560 * [0, 1, 2].repeated_combination(2) {|combination| c.push(combination) }
7561 * c # => [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
7562 *
7563 * If +size+ is zero, calls the block once with an empty array.
7564 *
7565 * If +size+ is negative, does not call the block:
7566 *
7567 * [0, 1, 2].repeated_combination(-1) {|combination| fail 'Cannot happen' }
7568 *
7569 * With no block given, returns a new Enumerator.
7570 *
7571 * Related: see {Methods for Combining}[rdoc-ref:Array@Methods+for+Combining].
7572 */
7573
7574static VALUE
7575rb_ary_repeated_combination(VALUE ary, VALUE num)
7576{
7577 long n, i, len;
7578
7579 n = NUM2LONG(num); /* Combination size from argument */
7580 RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_repeated_combination_size); /* Return enumerator if no block */
7581 len = RARRAY_LEN(ary);
7582 if (n < 0) {
7583 /* yield nothing */
7584 }
7585 else if (n == 0) {
7587 }
7588 else if (n == 1) {
7589 for (i = 0; i < RARRAY_LEN(ary); i++) {
7590 rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i)));
7591 }
7592 }
7593 else if (len == 0) {
7594 /* yield nothing */
7595 }
7596 else {
7597 volatile VALUE t0;
7598 long *p = ALLOCV_N(long, t0, n);
7599 VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
7600 RBASIC_CLEAR_CLASS(ary0);
7601
7602 rcombinate0(len, n, p, n, ary0); /* compute and yield repeated combinations */
7603 ALLOCV_END(t0);
7604 RBASIC_SET_CLASS_RAW(ary0, rb_cArray);
7605 }
7606 return ary;
7607}
7608
7609/*
7610 * call-seq:
7611 * product(*other_arrays) -> new_array
7612 * product(*other_arrays) {|combination| ... } -> self
7613 *
7614 * Computes all combinations of elements from all the arrays,
7615 * including both +self+ and +other_arrays+:
7616 *
7617 * - The number of combinations is the product of the sizes of all the arrays,
7618 * including both +self+ and +other_arrays+.
7619 * - The order of the returned combinations is indeterminate.
7620 *
7621 * With no block given, returns the combinations as an array of arrays:
7622 *
7623 * p = [0, 1].product([2, 3])
7624 * # => [[0, 2], [0, 3], [1, 2], [1, 3]]
7625 * p.size # => 4
7626 * p = [0, 1].product([2, 3], [4, 5])
7627 * # => [[0, 2, 4], [0, 2, 5], [0, 3, 4], [0, 3, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3,...
7628 * p.size # => 8
7629 *
7630 * If +self+ or any argument is empty, returns an empty array:
7631 *
7632 * [].product([2, 3], [4, 5]) # => []
7633 * [0, 1].product([2, 3], []) # => []
7634 *
7635 * If no argument is given, returns an array of 1-element arrays,
7636 * each containing an element of +self+:
7637 *
7638 * a.product # => [[0], [1], [2]]
7639 *
7640 * With a block given, calls the block with each combination; returns +self+:
7641 *
7642 * p = []
7643 * [0, 1].product([2, 3]) {|combination| p.push(combination) }
7644 * p # => [[0, 2], [0, 3], [1, 2], [1, 3]]
7645 *
7646 * If +self+ or any argument is empty, does not call the block:
7647 *
7648 * [].product([2, 3], [4, 5]) {|combination| fail 'Cannot happen' }
7649 * # => []
7650 * [0, 1].product([2, 3], []) {|combination| fail 'Cannot happen' }
7651 * # => [0, 1]
7652 *
7653 * If no argument is given, calls the block with each element of +self+ as a 1-element array:
7654 *
7655 * p = []
7656 * [0, 1].product {|combination| p.push(combination) }
7657 * p # => [[0], [1]]
7658 *
7659 * Related: see {Methods for Combining}[rdoc-ref:Array@Methods+for+Combining].
7660 */
7661
7662static VALUE
7663rb_ary_product(int argc, VALUE *argv, VALUE ary)
7664{
7665 int n = argc+1; /* How many arrays we're operating on */
7666 volatile VALUE t0 = rb_ary_hidden_new(n);
7667 volatile VALUE t1 = Qundef;
7668 VALUE *arrays = RARRAY_PTR(t0); /* The arrays we're computing the product of */
7669 int *counters = ALLOCV_N(int, t1, n); /* The current position in each one */
7670 VALUE result = Qnil; /* The array we'll be returning, when no block given */
7671 long i,j;
7672 long resultlen = 1;
7673
7674 RBASIC_CLEAR_CLASS(t0);
7675
7676 /* initialize the arrays of arrays */
7677 ARY_SET_LEN(t0, n);
7678 arrays[0] = ary;
7679 for (i = 1; i < n; i++) arrays[i] = Qnil;
7680 for (i = 1; i < n; i++) arrays[i] = to_ary(argv[i-1]);
7681
7682 /* initialize the counters for the arrays */
7683 for (i = 0; i < n; i++) counters[i] = 0;
7684
7685 /* Otherwise, allocate and fill in an array of results */
7686 if (rb_block_given_p()) {
7687 /* Make defensive copies of arrays; exit if any is empty */
7688 for (i = 0; i < n; i++) {
7689 if (RARRAY_LEN(arrays[i]) == 0) goto done;
7690 arrays[i] = ary_make_shared_copy(arrays[i]);
7691 }
7692 }
7693 else {
7694 /* Compute the length of the result array; return [] if any is empty */
7695 for (i = 0; i < n; i++) {
7696 long k = RARRAY_LEN(arrays[i]);
7697 if (k == 0) {
7698 result = rb_ary_new2(0);
7699 goto done;
7700 }
7701 if (MUL_OVERFLOW_LONG_P(resultlen, k))
7702 rb_raise(rb_eRangeError, "too big to product");
7703 resultlen *= k;
7704 }
7705 result = rb_ary_new2(resultlen);
7706 }
7707 for (;;) {
7708 int m;
7709 /* fill in one subarray */
7710 VALUE subarray = rb_ary_new2(n);
7711 for (j = 0; j < n; j++) {
7712 rb_ary_push(subarray, rb_ary_entry(arrays[j], counters[j]));
7713 }
7714
7715 /* put it on the result array */
7716 if (NIL_P(result)) {
7717 FL_SET(t0, RARRAY_SHARED_ROOT_FLAG);
7718 rb_yield(subarray);
7719 if (!FL_TEST(t0, RARRAY_SHARED_ROOT_FLAG)) {
7720 rb_raise(rb_eRuntimeError, "product reentered");
7721 }
7722 else {
7723 FL_UNSET(t0, RARRAY_SHARED_ROOT_FLAG);
7724 }
7725 }
7726 else {
7727 rb_ary_push(result, subarray);
7728 }
7729
7730 /*
7731 * Increment the last counter. If it overflows, reset to 0
7732 * and increment the one before it.
7733 */
7734 m = n-1;
7735 counters[m]++;
7736 while (counters[m] == RARRAY_LEN(arrays[m])) {
7737 counters[m] = 0;
7738 /* If the first counter overflows, we are done */
7739 if (--m < 0) goto done;
7740 counters[m]++;
7741 }
7742 }
7743
7744done:
7745 ALLOCV_END(t1);
7746
7747 return NIL_P(result) ? ary : result;
7748}
7749
7750/*
7751 * call-seq:
7752 * take(count) -> new_array
7753 *
7754 * Returns a new array containing the first +count+ element of +self+
7755 * (as available);
7756 * +count+ must be a non-negative numeric;
7757 * does not modify +self+:
7758 *
7759 * a = ['a', 'b', 'c', 'd']
7760 * a.take(2) # => ["a", "b"]
7761 * a.take(2.1) # => ["a", "b"]
7762 * a.take(50) # => ["a", "b", "c", "d"]
7763 * a.take(0) # => []
7764 *
7765 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
7766 */
7767
7768static VALUE
7769rb_ary_take(VALUE obj, VALUE n)
7770{
7771 long len = NUM2LONG(n);
7772 if (len < 0) {
7773 rb_raise(rb_eArgError, "attempt to take negative size");
7774 }
7775 return rb_ary_subseq(obj, 0, len);
7776}
7777
7778/*
7779 * call-seq:
7780 * take_while {|element| ... } -> new_array
7781 * take_while -> new_enumerator
7782 *
7783 * With a block given, calls the block with each successive element of +self+;
7784 * stops iterating if the block returns +false+ or +nil+;
7785 * returns a new array containing those elements for which the block returned a truthy value:
7786 *
7787 * a = [0, 1, 2, 3, 4, 5]
7788 * a.take_while {|element| element < 3 } # => [0, 1, 2]
7789 * a.take_while {|element| true } # => [0, 1, 2, 3, 4, 5]
7790 * a.take_while {|element| false } # => []
7791 *
7792 * With no block given, returns a new Enumerator.
7793 *
7794 * Does not modify +self+.
7795 *
7796 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
7797 */
7798
7799static VALUE
7800rb_ary_take_while(VALUE ary)
7801{
7802 long i;
7803
7804 RETURN_ENUMERATOR(ary, 0, 0);
7805 for (i = 0; i < RARRAY_LEN(ary); i++) {
7806 if (!RTEST(rb_yield(RARRAY_AREF(ary, i)))) break;
7807 }
7808 return rb_ary_take(ary, LONG2FIX(i));
7809}
7810
7811/*
7812 * call-seq:
7813 * drop(count) -> new_array
7814 *
7815 * Returns a new array containing all but the first +count+ element of +self+,
7816 * where +count+ is a non-negative integer;
7817 * does not modify +self+.
7818 *
7819 * Examples:
7820 *
7821 * a = [0, 1, 2, 3, 4, 5]
7822 * a.drop(0) # => [0, 1, 2, 3, 4, 5]
7823 * a.drop(1) # => [1, 2, 3, 4, 5]
7824 * a.drop(2) # => [2, 3, 4, 5]
7825 * a.drop(9) # => []
7826 *
7827 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
7828 */
7829
7830static VALUE
7831rb_ary_drop(VALUE ary, VALUE n)
7832{
7833 VALUE result;
7834 long pos = NUM2LONG(n);
7835 if (pos < 0) {
7836 rb_raise(rb_eArgError, "attempt to drop negative size");
7837 }
7838
7839 result = rb_ary_subseq(ary, pos, RARRAY_LEN(ary));
7840 if (NIL_P(result)) result = rb_ary_new();
7841 return result;
7842}
7843
7844/*
7845 * call-seq:
7846 * drop_while {|element| ... } -> new_array
7847 * drop_while -> new_enumerator
7848 *
7849 * With a block given, calls the block with each successive element of +self+;
7850 * stops if the block returns +false+ or +nil+;
7851 * returns a new array _omitting_ those elements for which the block returned a truthy value;
7852 * does not modify +self+:
7853 *
7854 * a = [0, 1, 2, 3, 4, 5]
7855 * a.drop_while {|element| element < 3 } # => [3, 4, 5]
7856 *
7857 * With no block given, returns a new Enumerator.
7858 *
7859 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
7860 */
7861
7862static VALUE
7863rb_ary_drop_while(VALUE ary)
7864{
7865 long i;
7866
7867 RETURN_ENUMERATOR(ary, 0, 0);
7868 for (i = 0; i < RARRAY_LEN(ary); i++) {
7869 if (!RTEST(rb_yield(RARRAY_AREF(ary, i)))) break;
7870 }
7871 return rb_ary_drop(ary, LONG2FIX(i));
7872}
7873
7874/*
7875 * call-seq:
7876 * any? -> true or false
7877 * any?(object) -> true or false
7878 * any? {|element| ... } -> true or false
7879 *
7880 * Returns whether for any element of +self+, a given criterion is satisfied.
7881 *
7882 * With no block and no argument, returns whether any element of +self+ is truthy:
7883 *
7884 * [nil, false, []].any? # => true # Array object is truthy.
7885 * [nil, false, {}].any? # => true # Hash object is truthy.
7886 * [nil, false, ''].any? # => true # String object is truthy.
7887 * [nil, false].any? # => false # Nil and false are not truthy.
7888 *
7889 * With argument +object+ given,
7890 * returns whether <tt>object === ele</tt> for any element +ele+ in +self+:
7891 *
7892 * [nil, false, 0].any?(0) # => true
7893 * [nil, false, 1].any?(0) # => false
7894 * [nil, false, 'food'].any?(/foo/) # => true
7895 * [nil, false, 'food'].any?(/bar/) # => false
7896 *
7897 * With a block given,
7898 * calls the block with each element in +self+;
7899 * returns whether the block returns any truthy value:
7900 *
7901 * [0, 1, 2].any? {|ele| ele < 1 } # => true
7902 * [0, 1, 2].any? {|ele| ele < 0 } # => false
7903 *
7904 * With both a block and argument +object+ given,
7905 * ignores the block and uses +object+ as above.
7906 *
7907 * <b>Special case</b>: returns +false+ if +self+ is empty
7908 * (regardless of any given argument or block).
7909 *
7910 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
7911 */
7912
7913static VALUE
7914rb_ary_any_p(int argc, VALUE *argv, VALUE ary)
7915{
7916 long i, len = RARRAY_LEN(ary);
7917
7918 rb_check_arity(argc, 0, 1);
7919 if (!len) return Qfalse;
7920 if (argc) {
7921 if (rb_block_given_p()) {
7922 rb_warn("given block not used");
7923 }
7924 for (i = 0; i < RARRAY_LEN(ary); ++i) {
7925 if (RTEST(rb_funcall(argv[0], idEqq, 1, RARRAY_AREF(ary, i)))) return Qtrue;
7926 }
7927 }
7928 else if (!rb_block_given_p()) {
7929 for (i = 0; i < len; ++i) {
7930 if (RTEST(RARRAY_AREF(ary, i))) return Qtrue;
7931 }
7932 }
7933 else {
7934 for (i = 0; i < RARRAY_LEN(ary); ++i) {
7935 if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qtrue;
7936 }
7937 }
7938 return Qfalse;
7939}
7940
7941/*
7942 * call-seq:
7943 * all? -> true or false
7944 * all?(object) -> true or false
7945 * all? {|element| ... } -> true or false
7946 *
7947 * Returns whether for every element of +self+,
7948 * a given criterion is satisfied.
7949 *
7950 * With no block and no argument,
7951 * returns whether every element of +self+ is truthy:
7952 *
7953 * [[], {}, '', 0, 0.0, Object.new].all? # => true # All truthy objects.
7954 * [[], {}, '', 0, 0.0, nil].all? # => false # nil is not truthy.
7955 * [[], {}, '', 0, 0.0, false].all? # => false # false is not truthy.
7956 *
7957 * With argument +object+ given, returns whether <tt>object === ele</tt>
7958 * for every element +ele+ in +self+:
7959 *
7960 * [0, 0, 0].all?(0) # => true
7961 * [0, 1, 2].all?(1) # => false
7962 * ['food', 'fool', 'foot'].all?(/foo/) # => true
7963 * ['food', 'drink'].all?(/foo/) # => false
7964 *
7965 * With a block given, calls the block with each element in +self+;
7966 * returns whether the block returns only truthy values:
7967 *
7968 * [0, 1, 2].all? { |ele| ele < 3 } # => true
7969 * [0, 1, 2].all? { |ele| ele < 2 } # => false
7970 *
7971 * With both a block and argument +object+ given,
7972 * ignores the block and uses +object+ as above.
7973 *
7974 * <b>Special case</b>: returns +true+ if +self+ is empty
7975 * (regardless of any given argument or block).
7976 *
7977 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
7978 */
7979
7980static VALUE
7981rb_ary_all_p(int argc, VALUE *argv, VALUE ary)
7982{
7983 long i, len = RARRAY_LEN(ary);
7984
7985 rb_check_arity(argc, 0, 1);
7986 if (!len) return Qtrue;
7987 if (argc) {
7988 if (rb_block_given_p()) {
7989 rb_warn("given block not used");
7990 }
7991 for (i = 0; i < RARRAY_LEN(ary); ++i) {
7992 if (!RTEST(rb_funcall(argv[0], idEqq, 1, RARRAY_AREF(ary, i)))) return Qfalse;
7993 }
7994 }
7995 else if (!rb_block_given_p()) {
7996 for (i = 0; i < len; ++i) {
7997 if (!RTEST(RARRAY_AREF(ary, i))) return Qfalse;
7998 }
7999 }
8000 else {
8001 for (i = 0; i < RARRAY_LEN(ary); ++i) {
8002 if (!RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qfalse;
8003 }
8004 }
8005 return Qtrue;
8006}
8007
8008/*
8009 * call-seq:
8010 * none? -> true or false
8011 * none?(object) -> true or false
8012 * none? {|element| ... } -> true or false
8013 *
8014 * Returns +true+ if no element of +self+ meets a given criterion, +false+ otherwise.
8015 *
8016 * With no block given and no argument, returns +true+ if +self+ has no truthy elements,
8017 * +false+ otherwise:
8018 *
8019 * [nil, false].none? # => true
8020 * [nil, 0, false].none? # => false
8021 * [].none? # => true
8022 *
8023 * With argument +object+ given, returns +false+ if for any element +element+,
8024 * <tt>object === element</tt>; +true+ otherwise:
8025 *
8026 * ['food', 'drink'].none?(/bar/) # => true
8027 * ['food', 'drink'].none?(/foo/) # => false
8028 * [].none?(/foo/) # => true
8029 * [0, 1, 2].none?(3) # => true
8030 * [0, 1, 2].none?(1) # => false
8031 *
8032 * With a block given, calls the block with each element in +self+;
8033 * returns +true+ if the block returns no truthy value, +false+ otherwise:
8034 *
8035 * [0, 1, 2].none? {|element| element > 3 } # => true
8036 * [0, 1, 2].none? {|element| element > 1 } # => false
8037 *
8038 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
8039 */
8040
8041static VALUE
8042rb_ary_none_p(int argc, VALUE *argv, VALUE ary)
8043{
8044 long i, len = RARRAY_LEN(ary);
8045
8046 rb_check_arity(argc, 0, 1);
8047 if (!len) return Qtrue;
8048 if (argc) {
8049 if (rb_block_given_p()) {
8050 rb_warn("given block not used");
8051 }
8052 for (i = 0; i < RARRAY_LEN(ary); ++i) {
8053 if (RTEST(rb_funcall(argv[0], idEqq, 1, RARRAY_AREF(ary, i)))) return Qfalse;
8054 }
8055 }
8056 else if (!rb_block_given_p()) {
8057 for (i = 0; i < len; ++i) {
8058 if (RTEST(RARRAY_AREF(ary, i))) return Qfalse;
8059 }
8060 }
8061 else {
8062 for (i = 0; i < RARRAY_LEN(ary); ++i) {
8063 if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qfalse;
8064 }
8065 }
8066 return Qtrue;
8067}
8068
8069/*
8070 * call-seq:
8071 * one? -> true or false
8072 * one? {|element| ... } -> true or false
8073 * one?(object) -> true or false
8074 *
8075 * Returns +true+ if exactly one element of +self+ meets a given criterion.
8076 *
8077 * With no block given and no argument, returns +true+ if +self+ has exactly one truthy element,
8078 * +false+ otherwise:
8079 *
8080 * [nil, 0].one? # => true
8081 * [0, 0].one? # => false
8082 * [nil, nil].one? # => false
8083 * [].one? # => false
8084 *
8085 * With a block given, calls the block with each element in +self+;
8086 * returns +true+ if the block a truthy value for exactly one element, +false+ otherwise:
8087 *
8088 * [0, 1, 2].one? {|element| element > 0 } # => false
8089 * [0, 1, 2].one? {|element| element > 1 } # => true
8090 * [0, 1, 2].one? {|element| element > 2 } # => false
8091 *
8092 * With argument +object+ given, returns +true+ if for exactly one element +element+, <tt>object === element</tt>;
8093 * +false+ otherwise:
8094 *
8095 * [0, 1, 2].one?(0) # => true
8096 * [0, 0, 1].one?(0) # => false
8097 * [1, 1, 2].one?(0) # => false
8098 * ['food', 'drink'].one?(/bar/) # => false
8099 * ['food', 'drink'].one?(/foo/) # => true
8100 * [].one?(/foo/) # => false
8101 *
8102 * Related: see {Methods for Querying}[rdoc-ref:Array@Methods+for+Querying].
8103 */
8104
8105static VALUE
8106rb_ary_one_p(int argc, VALUE *argv, VALUE ary)
8107{
8108 long i, len = RARRAY_LEN(ary);
8109 VALUE result = Qfalse;
8110
8111 rb_check_arity(argc, 0, 1);
8112 if (!len) return Qfalse;
8113 if (argc) {
8114 if (rb_block_given_p()) {
8115 rb_warn("given block not used");
8116 }
8117 for (i = 0; i < RARRAY_LEN(ary); ++i) {
8118 if (RTEST(rb_funcall(argv[0], idEqq, 1, RARRAY_AREF(ary, i)))) {
8119 if (result) return Qfalse;
8120 result = Qtrue;
8121 }
8122 }
8123 }
8124 else if (!rb_block_given_p()) {
8125 for (i = 0; i < len; ++i) {
8126 if (RTEST(RARRAY_AREF(ary, i))) {
8127 if (result) return Qfalse;
8128 result = Qtrue;
8129 }
8130 }
8131 }
8132 else {
8133 for (i = 0; i < RARRAY_LEN(ary); ++i) {
8134 if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) {
8135 if (result) return Qfalse;
8136 result = Qtrue;
8137 }
8138 }
8139 }
8140 return result;
8141}
8142
8143/*
8144 * call-seq:
8145 * dig(index, *identifiers) -> object
8146 *
8147 * Finds and returns the object in nested object
8148 * specified by +index+ and +identifiers+;
8149 * the nested objects may be instances of various classes.
8150 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
8151 *
8152 * Examples:
8153 *
8154 * a = [:foo, [:bar, :baz, [:bat, :bam]]]
8155 * a.dig(1) # => [:bar, :baz, [:bat, :bam]]
8156 * a.dig(1, 2) # => [:bat, :bam]
8157 * a.dig(1, 2, 0) # => :bat
8158 * a.dig(1, 2, 3) # => nil
8159 *
8160 * Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
8161 */
8162
8163static VALUE
8164rb_ary_dig(int argc, VALUE *argv, VALUE self)
8165{
8166 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
8167 self = rb_ary_at(self, *argv);
8168 if (!--argc) return self;
8169 ++argv;
8170 return rb_obj_dig(argc, argv, self, Qnil);
8171}
8172
8173static inline VALUE
8174finish_exact_sum(long n, VALUE r, VALUE v, int z)
8175{
8176 if (n != 0)
8177 v = rb_fix_plus(LONG2FIX(n), v);
8178 if (!UNDEF_P(r)) {
8179 v = rb_rational_plus(r, v);
8180 }
8181 else if (!n && z) {
8182 v = rb_fix_plus(LONG2FIX(0), v);
8183 }
8184 return v;
8185}
8186
8187/*
8188 * call-seq:
8189 * sum(init = 0) -> object
8190 * sum(init = 0) {|element| ... } -> object
8191 *
8192 * With no block given, returns the sum of +init+ and all elements of +self+;
8193 * for array +array+ and value +init+, equivalent to:
8194 *
8195 * sum = init
8196 * array.each {|element| sum += element }
8197 * sum
8198 *
8199 * For example, <tt>[e0, e1, e2].sum</tt> returns <tt>init + e0 + e1 + e2</tt>.
8200 *
8201 * Examples:
8202 *
8203 * [0, 1, 2, 3].sum # => 6
8204 * [0, 1, 2, 3].sum(100) # => 106
8205 * ['abc', 'def', 'ghi'].sum('jkl') # => "jklabcdefghi"
8206 * [[:foo, :bar], ['foo', 'bar']].sum([2, 3])
8207 * # => [2, 3, :foo, :bar, "foo", "bar"]
8208 *
8209 * The +init+ value and elements need not be numeric, but must all be <tt>+</tt>-compatible:
8210 *
8211 * # Raises TypeError: Array can't be coerced into Integer.
8212 * [[:foo, :bar], ['foo', 'bar']].sum(2)
8213 *
8214 * With a block given, calls the block with each element of +self+;
8215 * the block's return value (instead of the element itself) is used as the addend:
8216 *
8217 * ['zero', 1, :two].sum('Coerced and concatenated: ') {|element| element.to_s }
8218 * # => "Coerced and concatenated: zero1two"
8219 *
8220 * Notes:
8221 *
8222 * - Array#join and Array#flatten may be faster than Array#sum
8223 * for an array of strings or an array of arrays.
8224 * - Array#sum method may not respect method redefinition of "+" methods such as Integer#+.
8225 *
8226 */
8227
8228static VALUE
8229rb_ary_sum(int argc, VALUE *argv, VALUE ary)
8230{
8231 VALUE e, v, r;
8232 long i, n;
8233 int block_given;
8234
8235 v = (rb_check_arity(argc, 0, 1) ? argv[0] : LONG2FIX(0));
8236
8237 block_given = rb_block_given_p();
8238
8239 if (RARRAY_LEN(ary) == 0)
8240 return v;
8241
8242 n = 0;
8243 r = Qundef;
8244
8245 bool init_is_float = RB_FLOAT_TYPE_P(v);
8246 if (init_is_float) {
8247 v = LONG2FIX(0);
8248 }
8249 else if (!RB_INTEGER_TYPE_P(v) && !RB_TYPE_P(v, T_RATIONAL)) {
8250 i = 0;
8251 goto init_is_a_value;
8252 }
8253
8254 for (i = 0; i < RARRAY_LEN(ary); i++) {
8255 e = RARRAY_AREF(ary, i);
8256 if (block_given)
8257 e = rb_yield(e);
8258 if (FIXNUM_P(e)) {
8259 n += FIX2LONG(e); /* should not overflow long type */
8260 if (!FIXABLE(n)) {
8261 v = rb_big_plus(LONG2NUM(n), v);
8262 n = 0;
8263 }
8264 }
8265 else if (RB_BIGNUM_TYPE_P(e))
8266 v = rb_big_plus(e, v);
8267 else if (RB_TYPE_P(e, T_RATIONAL)) {
8268 if (UNDEF_P(r))
8269 r = e;
8270 else
8271 r = rb_rational_plus(r, e);
8272 }
8273 else
8274 goto not_exact;
8275 }
8276 v = finish_exact_sum(n, r, v, argc!=0);
8277 if (init_is_float) v = rb_float_plus(argv[0], v);
8278 return v;
8279
8280 not_exact:
8281 v = finish_exact_sum(n, r, v, i!=0);
8282
8283 if (init_is_float ? (--i, e = argv[0], true) : RB_FLOAT_TYPE_P(e)) {
8284 /*
8285 * Kahan-Babuska balancing compensated summation algorithm
8286 * See https://link.springer.com/article/10.1007/s00607-005-0139-x
8287 */
8288 double f, c;
8289 double x, t;
8290
8291 f = NUM2DBL(v);
8292 c = 0.0;
8293 goto has_float_value;
8294 for (; i < RARRAY_LEN(ary); i++) {
8295 e = RARRAY_AREF(ary, i);
8296 if (block_given)
8297 e = rb_yield(e);
8298 if (RB_FLOAT_TYPE_P(e))
8299 has_float_value:
8300 x = RFLOAT_VALUE(e);
8301 else if (FIXNUM_P(e))
8302 x = FIX2LONG(e);
8303 else if (RB_BIGNUM_TYPE_P(e))
8304 x = rb_big2dbl(e);
8305 else if (RB_TYPE_P(e, T_RATIONAL))
8306 x = rb_num2dbl(e);
8307 else
8308 goto not_float;
8309
8310 if (isnan(f)) continue;
8311 if (isnan(x)) {
8312 f = x;
8313 continue;
8314 }
8315 if (isinf(x)) {
8316 if (isinf(f) && signbit(x) != signbit(f))
8317 f = NAN;
8318 else
8319 f = x;
8320 continue;
8321 }
8322 if (isinf(f)) continue;
8323
8324 t = f + x;
8325 if (fabs(f) >= fabs(x))
8326 c += ((f - t) + x);
8327 else
8328 c += ((x - t) + f);
8329 f = t;
8330 }
8331 f += c;
8332 return DBL2NUM(f);
8333
8334 not_float:
8335 v = DBL2NUM(f);
8336 }
8337
8338 goto has_some_value;
8339 init_is_a_value:
8340 for (; i < RARRAY_LEN(ary); i++) {
8341 e = RARRAY_AREF(ary, i);
8342 if (block_given)
8343 e = rb_yield(e);
8344 has_some_value:
8345 v = rb_funcall(v, idPLUS, 1, e);
8346 }
8347 return v;
8348}
8349
8350/* :nodoc: */
8351static VALUE
8352rb_ary_deconstruct(VALUE ary)
8353{
8354 return ary;
8355}
8356
8357/*
8358 * An \Array object is an ordered, integer-indexed collection of objects,
8359 * called _elements_;
8360 * the object represents
8361 * an {array data structure}[https://en.wikipedia.org/wiki/Array_(data_structure)].
8362 *
8363 * An element may be any object (even another array);
8364 * elements may be any mixture of objects of different types.
8365 *
8366 * Important data structures that use arrays include:
8367 *
8368 * - {Coordinate vector}[https://en.wikipedia.org/wiki/Coordinate_vector].
8369 * - {Matrix}[https://en.wikipedia.org/wiki/Matrix_(mathematics)].
8370 * - {Heap}[https://en.wikipedia.org/wiki/Heap_(data_structure)].
8371 * - {Hash table}[https://en.wikipedia.org/wiki/Hash_table].
8372 * - {Deque (double-ended queue)}[https://en.wikipedia.org/wiki/Double-ended_queue].
8373 * - {Queue}[https://en.wikipedia.org/wiki/Queue_(abstract_data_type)].
8374 * - {Stack}[https://en.wikipedia.org/wiki/Stack_(abstract_data_type)].
8375 *
8376 * There are also array-like data structures:
8377 *
8378 * - {Associative array}[https://en.wikipedia.org/wiki/Associative_array] (see Hash).
8379 * - {Directory}[https://en.wikipedia.org/wiki/Directory_(computing)] (see Dir).
8380 * - {Environment}[https://en.wikipedia.org/wiki/Environment_variable] (see ENV).
8381 * - {Set}[https://en.wikipedia.org/wiki/Set_(abstract_data_type)] (see Set).
8382 * - {String}[https://en.wikipedia.org/wiki/String_(computer_science)] (see String).
8383 *
8384 * == \Array Indexes
8385 *
8386 * \Array indexing starts at 0, as in C or Java.
8387 *
8388 * A non-negative index is an offset from the first element:
8389 *
8390 * - Index 0 indicates the first element.
8391 * - Index 1 indicates the second element.
8392 * - ...
8393 *
8394 * A negative index is an offset, backwards, from the end of the array:
8395 *
8396 * - Index -1 indicates the last element.
8397 * - Index -2 indicates the next-to-last element.
8398 * - ...
8399 *
8400 *
8401 * === In-Range and Out-of-Range Indexes
8402 *
8403 * A non-negative index is <i>in range</i> if and only if it is smaller than
8404 * the size of the array. For a 3-element array:
8405 *
8406 * - Indexes 0 through 2 are in range.
8407 * - Index 3 is out of range.
8408 *
8409 * A negative index is <i>in range</i> if and only if its absolute value is
8410 * not larger than the size of the array. For a 3-element array:
8411 *
8412 * - Indexes -1 through -3 are in range.
8413 * - Index -4 is out of range.
8414 *
8415 * === Effective Index
8416 *
8417 * Although the effective index into an array is always an integer,
8418 * some methods (both within class \Array and elsewhere)
8419 * accept one or more non-integer arguments that are
8420 * {integer-convertible objects}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
8421 *
8422 * == Creating Arrays
8423 *
8424 * You can create an \Array object explicitly with:
8425 *
8426 * - An {array literal}[rdoc-ref:syntax/literals.rdoc@Array+Literals]:
8427 *
8428 * [1, 'one', :one, [2, 'two', :two]]
8429 *
8430 * - A {%w or %W string-array Literal}[rdoc-ref:syntax/literals.rdoc@25w+and+-25W-3A+String-Array+Literals]:
8431 *
8432 * %w[foo bar baz] # => ["foo", "bar", "baz"]
8433 * %w[1 % *] # => ["1", "%", "*"]
8434 *
8435 * - A {%i or %I symbol-array Literal}[rdoc-ref:syntax/literals.rdoc@25i+and+-25I-3A+Symbol-Array+Literals]:
8436 *
8437 * %i[foo bar baz] # => [:foo, :bar, :baz]
8438 * %i[1 % *] # => [:"1", :%, :*]
8439 *
8440 * - Method Kernel#Array:
8441 *
8442 * Array(["a", "b"]) # => ["a", "b"]
8443 * Array(1..5) # => [1, 2, 3, 4, 5]
8444 * Array(key: :value) # => [[:key, :value]]
8445 * Array(nil) # => []
8446 * Array(1) # => [1]
8447 * Array({:a => "a", :b => "b"}) # => [[:a, "a"], [:b, "b"]]
8448 *
8449 * - Method Array.new:
8450 *
8451 * Array.new # => []
8452 * Array.new(3) # => [nil, nil, nil]
8453 * Array.new(4) {Hash.new} # => [{}, {}, {}, {}]
8454 * Array.new(3, true) # => [true, true, true]
8455 *
8456 * Note that the last example above populates the array
8457 * with references to the same object.
8458 * This is recommended only in cases where that object is a natively immutable object
8459 * such as a symbol, a numeric, +nil+, +true+, or +false+.
8460 *
8461 * Another way to create an array with various objects, using a block;
8462 * this usage is safe for mutable objects such as hashes, strings or
8463 * other arrays:
8464 *
8465 * Array.new(4) {|i| i.to_s } # => ["0", "1", "2", "3"]
8466 *
8467 * Here is a way to create a multi-dimensional array:
8468 *
8469 * Array.new(3) {Array.new(3)}
8470 * # => [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
8471 *
8472 * A number of Ruby methods, both in the core and in the standard library,
8473 * provide instance method +to_a+, which converts an object to an array.
8474 *
8475 * - ARGF#to_a
8476 * - Array#to_a
8477 * - Enumerable#to_a
8478 * - Hash#to_a
8479 * - MatchData#to_a
8480 * - NilClass#to_a
8481 * - OptionParser#to_a
8482 * - Range#to_a
8483 * - Set#to_a
8484 * - Struct#to_a
8485 * - Time#to_a
8486 * - Benchmark::Tms#to_a
8487 * - CSV::Table#to_a
8488 * - Enumerator::Lazy#to_a
8489 * - Gem::List#to_a
8490 * - Gem::NameTuple#to_a
8491 * - Gem::Platform#to_a
8492 * - Gem::RequestSet::Lockfile::Tokenizer#to_a
8493 * - Gem::SourceList#to_a
8494 * - OpenSSL::X509::Extension#to_a
8495 * - OpenSSL::X509::Name#to_a
8496 * - Racc::ISet#to_a
8497 * - Rinda::RingFinger#to_a
8498 * - Ripper::Lexer::Elem#to_a
8499 * - RubyVM::InstructionSequence#to_a
8500 * - YAML::DBM#to_a
8501 *
8502 * == Example Usage
8503 *
8504 * In addition to the methods it mixes in through the Enumerable module,
8505 * class \Array has proprietary methods for accessing, searching and otherwise
8506 * manipulating arrays.
8507 *
8508 * Some of the more common ones are illustrated below.
8509 *
8510 * == Accessing Elements
8511 *
8512 * Elements in an array can be retrieved using the Array#[] method. It can
8513 * take a single integer argument (a numeric index), a pair of arguments
8514 * (start and length) or a range. Negative indices start counting from the end,
8515 * with -1 being the last element.
8516 *
8517 * arr = [1, 2, 3, 4, 5, 6]
8518 * arr[2] #=> 3
8519 * arr[100] #=> nil
8520 * arr[-3] #=> 4
8521 * arr[2, 3] #=> [3, 4, 5]
8522 * arr[1..4] #=> [2, 3, 4, 5]
8523 * arr[1..-3] #=> [2, 3, 4]
8524 *
8525 * Another way to access a particular array element is by using the #at method
8526 *
8527 * arr.at(0) #=> 1
8528 *
8529 * The #slice method works in an identical manner to Array#[].
8530 *
8531 * To raise an error for indices outside of the array bounds or else to
8532 * provide a default value when that happens, you can use #fetch.
8533 *
8534 * arr = ['a', 'b', 'c', 'd', 'e', 'f']
8535 * arr.fetch(100) #=> IndexError: index 100 outside of array bounds: -6...6
8536 * arr.fetch(100, "oops") #=> "oops"
8537 *
8538 * The special methods #first and #last will return the first and last
8539 * elements of an array, respectively.
8540 *
8541 * arr.first #=> 1
8542 * arr.last #=> 6
8543 *
8544 * To return the first +n+ elements of an array, use #take
8545 *
8546 * arr.take(3) #=> [1, 2, 3]
8547 *
8548 * #drop does the opposite of #take, by returning the elements after +n+
8549 * elements have been dropped:
8550 *
8551 * arr.drop(3) #=> [4, 5, 6]
8552 *
8553 * == Obtaining Information about an \Array
8554 *
8555 * An array keeps track of its own length at all times. To query an array
8556 * about the number of elements it contains, use #length, #count or #size.
8557 *
8558 * browsers = ['Chrome', 'Firefox', 'Safari', 'Opera', 'IE']
8559 * browsers.length #=> 5
8560 * browsers.count #=> 5
8561 *
8562 * To check whether an array contains any elements at all
8563 *
8564 * browsers.empty? #=> false
8565 *
8566 * To check whether a particular item is included in the array
8567 *
8568 * browsers.include?('Konqueror') #=> false
8569 *
8570 * == Adding Items to an \Array
8571 *
8572 * Items can be added to the end of an array by using either #push or #<<
8573 *
8574 * arr = [1, 2, 3, 4]
8575 * arr.push(5) #=> [1, 2, 3, 4, 5]
8576 * arr << 6 #=> [1, 2, 3, 4, 5, 6]
8577 *
8578 * #unshift will add a new item to the beginning of an array.
8579 *
8580 * arr.unshift(0) #=> [0, 1, 2, 3, 4, 5, 6]
8581 *
8582 * With #insert you can add a new element to an array at any position.
8583 *
8584 * arr.insert(3, 'apple') #=> [0, 1, 2, 'apple', 3, 4, 5, 6]
8585 *
8586 * Using the #insert method, you can also insert multiple values at once:
8587 *
8588 * arr.insert(3, 'orange', 'pear', 'grapefruit')
8589 * #=> [0, 1, 2, "orange", "pear", "grapefruit", "apple", 3, 4, 5, 6]
8590 *
8591 * == Removing Items from an \Array
8592 *
8593 * The method #pop removes the last element in an array and returns it:
8594 *
8595 * arr = [1, 2, 3, 4, 5, 6]
8596 * arr.pop #=> 6
8597 * arr #=> [1, 2, 3, 4, 5]
8598 *
8599 * To retrieve and at the same time remove the first item, use #shift:
8600 *
8601 * arr.shift #=> 1
8602 * arr #=> [2, 3, 4, 5]
8603 *
8604 * To delete an element at a particular index:
8605 *
8606 * arr.delete_at(2) #=> 4
8607 * arr #=> [2, 3, 5]
8608 *
8609 * To delete a particular element anywhere in an array, use #delete:
8610 *
8611 * arr = [1, 2, 2, 3]
8612 * arr.delete(2) #=> 2
8613 * arr #=> [1,3]
8614 *
8615 * A useful method if you need to remove +nil+ values from an array is
8616 * #compact:
8617 *
8618 * arr = ['foo', 0, nil, 'bar', 7, 'baz', nil]
8619 * arr.compact #=> ['foo', 0, 'bar', 7, 'baz']
8620 * arr #=> ['foo', 0, nil, 'bar', 7, 'baz', nil]
8621 * arr.compact! #=> ['foo', 0, 'bar', 7, 'baz']
8622 * arr #=> ['foo', 0, 'bar', 7, 'baz']
8623 *
8624 * Another common need is to remove duplicate elements from an array.
8625 *
8626 * It has the non-destructive #uniq, and destructive method #uniq!
8627 *
8628 * arr = [2, 5, 6, 556, 6, 6, 8, 9, 0, 123, 556]
8629 * arr.uniq #=> [2, 5, 6, 556, 8, 9, 0, 123]
8630 *
8631 * == Iterating over an \Array
8632 *
8633 * Like all classes that include the Enumerable module, class \Array has an each
8634 * method, which defines what elements should be iterated over and how. In
8635 * case of Array#each, all elements in +self+ are yielded to
8636 * the supplied block in sequence.
8637 *
8638 * Note that this operation leaves the array unchanged.
8639 *
8640 * arr = [1, 2, 3, 4, 5]
8641 * arr.each {|a| print a -= 10, " "}
8642 * # prints: -9 -8 -7 -6 -5
8643 * #=> [1, 2, 3, 4, 5]
8644 *
8645 * Another sometimes useful iterator is #reverse_each which will iterate over
8646 * the elements in the array in reverse order.
8647 *
8648 * words = %w[first second third fourth fifth sixth]
8649 * str = ""
8650 * words.reverse_each {|word| str += "#{word} "}
8651 * p str #=> "sixth fifth fourth third second first "
8652 *
8653 * The #map method can be used to create a new array based on the original
8654 * array, but with the values modified by the supplied block:
8655 *
8656 * arr.map {|a| 2*a} #=> [2, 4, 6, 8, 10]
8657 * arr #=> [1, 2, 3, 4, 5]
8658 * arr.map! {|a| a**2} #=> [1, 4, 9, 16, 25]
8659 * arr #=> [1, 4, 9, 16, 25]
8660 *
8661 *
8662 * == Selecting Items from an \Array
8663 *
8664 * Elements can be selected from an array according to criteria defined in a
8665 * block. The selection can happen in a destructive or a non-destructive
8666 * manner. While the destructive operations will modify the array they were
8667 * called on, the non-destructive methods usually return a new array with the
8668 * selected elements, but leave the original array unchanged.
8669 *
8670 * === Non-destructive Selection
8671 *
8672 * arr = [1, 2, 3, 4, 5, 6]
8673 * arr.select {|a| a > 3} #=> [4, 5, 6]
8674 * arr.reject {|a| a < 3} #=> [3, 4, 5, 6]
8675 * arr.drop_while {|a| a < 4} #=> [4, 5, 6]
8676 * arr #=> [1, 2, 3, 4, 5, 6]
8677 *
8678 * === Destructive Selection
8679 *
8680 * #select! and #reject! are the corresponding destructive methods to #select
8681 * and #reject
8682 *
8683 * Similar to #select vs. #reject, #delete_if and #keep_if have the exact
8684 * opposite result when supplied with the same block:
8685 *
8686 * arr.delete_if {|a| a < 4} #=> [4, 5, 6]
8687 * arr #=> [4, 5, 6]
8688 *
8689 * arr = [1, 2, 3, 4, 5, 6]
8690 * arr.keep_if {|a| a < 4} #=> [1, 2, 3]
8691 * arr #=> [1, 2, 3]
8692 *
8693 * == What's Here
8694 *
8695 * First, what's elsewhere. Class \Array:
8696 *
8697 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
8698 * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
8699 * which provides dozens of additional methods.
8700 *
8701 * Here, class \Array provides methods that are useful for:
8702 *
8703 * - {Creating an Array}[rdoc-ref:Array@Methods+for+Creating+an+Array]
8704 * - {Querying}[rdoc-ref:Array@Methods+for+Querying]
8705 * - {Comparing}[rdoc-ref:Array@Methods+for+Comparing]
8706 * - {Fetching}[rdoc-ref:Array@Methods+for+Fetching]
8707 * - {Assigning}[rdoc-ref:Array@Methods+for+Assigning]
8708 * - {Deleting}[rdoc-ref:Array@Methods+for+Deleting]
8709 * - {Combining}[rdoc-ref:Array@Methods+for+Combining]
8710 * - {Iterating}[rdoc-ref:Array@Methods+for+Iterating]
8711 * - {Converting}[rdoc-ref:Array@Methods+for+Converting]
8712 * - {And more....}[rdoc-ref:Array@Other+Methods]
8713 *
8714 * === Methods for Creating an \Array
8715 *
8716 * - ::[]: Returns a new array populated with given objects.
8717 * - ::new: Returns a new array.
8718 * - ::try_convert: Returns a new array created from a given object.
8719 *
8720 * See also {Creating Arrays}[rdoc-ref:Array@Creating+Arrays].
8721 *
8722 * === Methods for Querying
8723 *
8724 * - #all?: Returns whether all elements meet a given criterion.
8725 * - #any?: Returns whether any element meets a given criterion.
8726 * - #count: Returns the count of elements that meet a given criterion.
8727 * - #empty?: Returns whether there are no elements.
8728 * - #find_index (aliased as #index): Returns the index of the first element that meets a given criterion.
8729 * - #hash: Returns the integer hash code.
8730 * - #include?: Returns whether any element <tt>==</tt> a given object.
8731 * - #length (aliased as #size): Returns the count of elements.
8732 * - #none?: Returns whether no element <tt>==</tt> a given object.
8733 * - #one?: Returns whether exactly one element <tt>==</tt> a given object.
8734 * - #rindex: Returns the index of the last element that meets a given criterion.
8735 *
8736 * === Methods for Comparing
8737 *
8738 * - #<=>: Returns -1, 0, or 1, as +self+ is less than, equal to, or greater than a given object.
8739 * - #==: Returns whether each element in +self+ is <tt>==</tt> to the corresponding element in a given object.
8740 * - #eql?: Returns whether each element in +self+ is <tt>eql?</tt> to the corresponding element in a given object.
8741
8742 * === Methods for Fetching
8743 *
8744 * These methods do not modify +self+.
8745 *
8746 * - #[] (aliased as #slice): Returns consecutive elements as determined by a given argument.
8747 * - #assoc: Returns the first element that is an array whose first element <tt>==</tt> a given object.
8748 * - #at: Returns the element at a given offset.
8749 * - #bsearch: Returns an element selected via a binary search as determined by a given block.
8750 * - #bsearch_index: Returns the index of an element selected via a binary search as determined by a given block.
8751 * - #compact: Returns an array containing all non-+nil+ elements.
8752 * - #dig: Returns the object in nested objects that is specified by a given index and additional arguments.
8753 * - #drop: Returns trailing elements as determined by a given index.
8754 * - #drop_while: Returns trailing elements as determined by a given block.
8755 * - #fetch: Returns the element at a given offset.
8756 * - #fetch_values: Returns elements at given offsets.
8757 * - #first: Returns one or more leading elements.
8758 * - #last: Returns one or more trailing elements.
8759 * - #max: Returns one or more maximum-valued elements, as determined by <tt>#<=></tt> or a given block.
8760 * - #min: Returns one or more minimum-valued elements, as determined by <tt>#<=></tt> or a given block.
8761 * - #minmax: Returns the minimum-valued and maximum-valued elements, as determined by <tt>#<=></tt> or a given block.
8762 * - #rassoc: Returns the first element that is an array whose second element <tt>==</tt> a given object.
8763 * - #reject: Returns an array containing elements not rejected by a given block.
8764 * - #reverse: Returns all elements in reverse order.
8765 * - #rotate: Returns all elements with some rotated from one end to the other.
8766 * - #sample: Returns one or more random elements.
8767 * - #select (aliased as #filter): Returns an array containing elements selected by a given block.
8768 * - #shuffle: Returns elements in a random order.
8769 * - #sort: Returns all elements in an order determined by <tt>#<=></tt> or a given block.
8770 * - #take: Returns leading elements as determined by a given index.
8771 * - #take_while: Returns leading elements as determined by a given block.
8772 * - #uniq: Returns an array containing non-duplicate elements.
8773 * - #values_at: Returns the elements at given offsets.
8774 *
8775 * === Methods for Assigning
8776 *
8777 * These methods add, replace, or reorder elements in +self+.
8778 *
8779 * - #<<: Appends an element.
8780 * - #[]=: Assigns specified elements with a given object.
8781 * - #concat: Appends all elements from given arrays.
8782 * - #fill: Replaces specified elements with specified objects.
8783 * - #flatten!: Replaces each nested array in +self+ with the elements from that array.
8784 * - #initialize_copy (aliased as #replace): Replaces the content of +self+ with the content of a given array.
8785 * - #insert: Inserts given objects at a given offset; does not replace elements.
8786 * - #push (aliased as #append): Appends elements.
8787 * - #reverse!: Replaces +self+ with its elements reversed.
8788 * - #rotate!: Replaces +self+ with its elements rotated.
8789 * - #shuffle!: Replaces +self+ with its elements in random order.
8790 * - #sort!: Replaces +self+ with its elements sorted, as determined by <tt>#<=></tt> or a given block.
8791 * - #sort_by!: Replaces +self+ with its elements sorted, as determined by a given block.
8792 * - #unshift (aliased as #prepend): Prepends leading elements.
8793 *
8794 * === Methods for Deleting
8795 *
8796 * Each of these methods removes elements from +self+:
8797 *
8798 * - #clear: Removes all elements.
8799 * - #compact!: Removes all +nil+ elements.
8800 * - #delete: Removes elements equal to a given object.
8801 * - #delete_at: Removes the element at a given offset.
8802 * - #delete_if: Removes elements specified by a given block.
8803 * - #keep_if: Removes elements not specified by a given block.
8804 * - #pop: Removes and returns the last element.
8805 * - #reject!: Removes elements specified by a given block.
8806 * - #select! (aliased as #filter!): Removes elements not specified by a given block.
8807 * - #shift: Removes and returns the first element.
8808 * - #slice!: Removes and returns a sequence of elements.
8809 * - #uniq!: Removes duplicates.
8810 *
8811 * === Methods for Combining
8812 *
8813 * - #&: Returns an array containing elements found both in +self+ and a given array.
8814 * - #+: Returns an array containing all elements of +self+ followed by all elements of a given array.
8815 * - #-: Returns an array containing all elements of +self+ that are not found in a given array.
8816 * - #|: Returns an array containing all element of +self+ and all elements of a given array, duplicates removed.
8817 * - #difference: Returns an array containing all elements of +self+ that are not found in any of the given arrays..
8818 * - #intersection: Returns an array containing elements found both in +self+ and in each given array.
8819 * - #product: Returns or yields all combinations of elements from +self+ and given arrays.
8820 * - #reverse: Returns an array containing all elements of +self+ in reverse order.
8821 * - #union: Returns an array containing all elements of +self+ and all elements of given arrays, duplicates removed.
8822 *
8823 * === Methods for Iterating
8824 *
8825 * - #combination: Calls a given block with combinations of elements of +self+; a combination does not use the same element more than once.
8826 * - #cycle: Calls a given block with each element, then does so again, for a specified number of times, or forever.
8827 * - #each: Passes each element to a given block.
8828 * - #each_index: Passes each element index to a given block.
8829 * - #permutation: Calls a given block with permutations of elements of +self+; a permutation does not use the same element more than once.
8830 * - #repeated_combination: Calls a given block with combinations of elements of +self+; a combination may use the same element more than once.
8831 * - #repeated_permutation: Calls a given block with permutations of elements of +self+; a permutation may use the same element more than once.
8832 * - #reverse_each: Passes each element, in reverse order, to a given block.
8833 *
8834 * === Methods for Converting
8835 *
8836 * - #collect (aliased as #map): Returns an array containing the block return-value for each element.
8837 * - #collect! (aliased as #map!): Replaces each element with a block return-value.
8838 * - #flatten: Returns an array that is a recursive flattening of +self+.
8839 * - #inspect (aliased as #to_s): Returns a new String containing the elements.
8840 * - #join: Returns a new String containing the elements joined by the field separator.
8841 * - #to_a: Returns +self+ or a new array containing all elements.
8842 * - #to_ary: Returns +self+.
8843 * - #to_h: Returns a new hash formed from the elements.
8844 * - #transpose: Transposes +self+, which must be an array of arrays.
8845 * - #zip: Returns a new array of arrays containing +self+ and given arrays.
8846 *
8847 * === Other Methods
8848 *
8849 * - #*: Returns one of the following:
8850 *
8851 * - With integer argument +n+, a new array that is the concatenation
8852 * of +n+ copies of +self+.
8853 * - With string argument +field_separator+, a new string that is equivalent to
8854 * <tt>join(field_separator)</tt>.
8855 *
8856 * - #pack: Packs the elements into a binary sequence.
8857 * - #sum: Returns a sum of elements according to either <tt>+</tt> or a given block.
8858 */
8859
8860void
8861Init_Array(void)
8862{
8863 fake_ary_flags = init_fake_ary_flags();
8864
8865 rb_cArray = rb_define_class("Array", rb_cObject);
8867
8868 rb_define_alloc_func(rb_cArray, empty_ary_alloc);
8869 rb_define_singleton_method(rb_cArray, "new", rb_ary_s_new, -1);
8870 rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -1);
8871 rb_define_singleton_method(rb_cArray, "try_convert", rb_ary_s_try_convert, 1);
8872 rb_define_method(rb_cArray, "initialize", rb_ary_initialize, -1);
8873 rb_define_method(rb_cArray, "initialize_copy", rb_ary_replace, 1);
8874
8875 rb_define_method(rb_cArray, "inspect", rb_ary_inspect, 0);
8876 rb_define_alias(rb_cArray, "to_s", "inspect");
8877 rb_define_method(rb_cArray, "to_a", rb_ary_to_a, 0);
8878 rb_define_method(rb_cArray, "to_h", rb_ary_to_h, 0);
8879 rb_define_method(rb_cArray, "to_ary", rb_ary_to_ary_m, 0);
8880
8881 rb_define_method(rb_cArray, "==", rb_ary_equal, 1);
8882 rb_define_method(rb_cArray, "eql?", rb_ary_eql, 1);
8883 rb_define_method(rb_cArray, "hash", rb_ary_hash, 0);
8884
8886 rb_define_method(rb_cArray, "[]=", rb_ary_aset, -1);
8887 rb_define_method(rb_cArray, "at", rb_ary_at, 1);
8888 rb_define_method(rb_cArray, "fetch", rb_ary_fetch, -1);
8889 rb_define_method(rb_cArray, "concat", rb_ary_concat_multi, -1);
8890 rb_define_method(rb_cArray, "union", rb_ary_union_multi, -1);
8891 rb_define_method(rb_cArray, "difference", rb_ary_difference_multi, -1);
8892 rb_define_method(rb_cArray, "intersection", rb_ary_intersection_multi, -1);
8893 rb_define_method(rb_cArray, "intersect?", rb_ary_intersect_p, 1);
8895 rb_define_method(rb_cArray, "push", rb_ary_push_m, -1);
8896 rb_define_alias(rb_cArray, "append", "push");
8897 rb_define_method(rb_cArray, "pop", rb_ary_pop_m, -1);
8898 rb_define_method(rb_cArray, "shift", rb_ary_shift_m, -1);
8899 rb_define_method(rb_cArray, "unshift", rb_ary_unshift_m, -1);
8900 rb_define_alias(rb_cArray, "prepend", "unshift");
8901 rb_define_method(rb_cArray, "insert", rb_ary_insert, -1);
8903 rb_define_method(rb_cArray, "each_index", rb_ary_each_index, 0);
8904 rb_define_method(rb_cArray, "reverse_each", rb_ary_reverse_each, 0);
8905 rb_define_method(rb_cArray, "length", rb_ary_length, 0);
8906 rb_define_method(rb_cArray, "size", rb_ary_length, 0);
8907 rb_define_method(rb_cArray, "empty?", rb_ary_empty_p, 0);
8908 rb_define_method(rb_cArray, "find", rb_ary_find, -1);
8909 rb_define_method(rb_cArray, "detect", rb_ary_find, -1);
8910 rb_define_method(rb_cArray, "rfind", rb_ary_rfind, -1);
8911 rb_define_method(rb_cArray, "find_index", rb_ary_index, -1);
8912 rb_define_method(rb_cArray, "index", rb_ary_index, -1);
8913 rb_define_method(rb_cArray, "rindex", rb_ary_rindex, -1);
8914 rb_define_method(rb_cArray, "join", rb_ary_join_m, -1);
8915 rb_define_method(rb_cArray, "reverse", rb_ary_reverse_m, 0);
8916 rb_define_method(rb_cArray, "reverse!", rb_ary_reverse_bang, 0);
8917 rb_define_method(rb_cArray, "rotate", rb_ary_rotate_m, -1);
8918 rb_define_method(rb_cArray, "rotate!", rb_ary_rotate_bang, -1);
8921 rb_define_method(rb_cArray, "sort_by!", rb_ary_sort_by_bang, 0);
8922 rb_define_method(rb_cArray, "collect", rb_ary_collect, 0);
8923 rb_define_method(rb_cArray, "collect!", rb_ary_collect_bang, 0);
8924 rb_define_method(rb_cArray, "map", rb_ary_collect, 0);
8925 rb_define_method(rb_cArray, "map!", rb_ary_collect_bang, 0);
8926 rb_define_method(rb_cArray, "select", rb_ary_select, 0);
8927 rb_define_method(rb_cArray, "select!", rb_ary_select_bang, 0);
8928 rb_define_method(rb_cArray, "filter", rb_ary_select, 0);
8929 rb_define_method(rb_cArray, "filter!", rb_ary_select_bang, 0);
8930 rb_define_method(rb_cArray, "keep_if", rb_ary_keep_if, 0);
8931 rb_define_method(rb_cArray, "values_at", rb_ary_values_at, -1);
8933 rb_define_method(rb_cArray, "delete_at", rb_ary_delete_at_m, 1);
8934 rb_define_method(rb_cArray, "delete_if", rb_ary_delete_if, 0);
8935 rb_define_method(rb_cArray, "reject", rb_ary_reject, 0);
8936 rb_define_method(rb_cArray, "reject!", rb_ary_reject_bang, 0);
8937 rb_define_method(rb_cArray, "zip", rb_ary_zip, -1);
8938 rb_define_method(rb_cArray, "transpose", rb_ary_transpose, 0);
8941 rb_define_method(rb_cArray, "fill", rb_ary_fill, -1);
8944
8945 rb_define_method(rb_cArray, "slice", rb_ary_aref, -1);
8946 rb_define_method(rb_cArray, "slice!", rb_ary_slice_bang, -1);
8947
8950
8952 rb_define_method(rb_cArray, "*", rb_ary_times, 1);
8953
8954 rb_define_method(rb_cArray, "-", rb_ary_diff, 1);
8955 rb_define_method(rb_cArray, "&", rb_ary_and, 1);
8956 rb_define_method(rb_cArray, "|", rb_ary_or, 1);
8957
8958 rb_define_method(rb_cArray, "max", rb_ary_max, -1);
8959 rb_define_method(rb_cArray, "min", rb_ary_min, -1);
8960 rb_define_method(rb_cArray, "minmax", rb_ary_minmax, 0);
8961
8962 rb_define_method(rb_cArray, "uniq", rb_ary_uniq, 0);
8963 rb_define_method(rb_cArray, "uniq!", rb_ary_uniq_bang, 0);
8964 rb_define_method(rb_cArray, "compact", rb_ary_compact, 0);
8965 rb_define_method(rb_cArray, "compact!", rb_ary_compact_bang, 0);
8966 rb_define_method(rb_cArray, "flatten", rb_ary_flatten, -1);
8967 rb_define_method(rb_cArray, "flatten!", rb_ary_flatten_bang, -1);
8968 rb_define_method(rb_cArray, "count", rb_ary_count, -1);
8969 rb_define_method(rb_cArray, "cycle", rb_ary_cycle, -1);
8970 rb_define_method(rb_cArray, "permutation", rb_ary_permutation, -1);
8971 rb_define_method(rb_cArray, "combination", rb_ary_combination, 1);
8972 rb_define_method(rb_cArray, "repeated_permutation", rb_ary_repeated_permutation, 1);
8973 rb_define_method(rb_cArray, "repeated_combination", rb_ary_repeated_combination, 1);
8974 rb_define_method(rb_cArray, "product", rb_ary_product, -1);
8975
8976 rb_define_method(rb_cArray, "take", rb_ary_take, 1);
8977 rb_define_method(rb_cArray, "take_while", rb_ary_take_while, 0);
8978 rb_define_method(rb_cArray, "drop", rb_ary_drop, 1);
8979 rb_define_method(rb_cArray, "drop_while", rb_ary_drop_while, 0);
8980 rb_define_method(rb_cArray, "bsearch", rb_ary_bsearch, 0);
8981 rb_define_method(rb_cArray, "bsearch_index", rb_ary_bsearch_index, 0);
8982 rb_define_method(rb_cArray, "any?", rb_ary_any_p, -1);
8983 rb_define_method(rb_cArray, "all?", rb_ary_all_p, -1);
8984 rb_define_method(rb_cArray, "none?", rb_ary_none_p, -1);
8985 rb_define_method(rb_cArray, "one?", rb_ary_one_p, -1);
8986 rb_define_method(rb_cArray, "dig", rb_ary_dig, -1);
8987 rb_define_method(rb_cArray, "sum", rb_ary_sum, -1);
8989
8990 rb_define_method(rb_cArray, "deconstruct", rb_ary_deconstruct, 0);
8991
8992 rb_cArray_empty_frozen = RB_OBJ_SET_SHAREABLE(rb_ary_freeze(rb_ary_new()));
8993 rb_vm_register_global_object(rb_cArray_empty_frozen);
8994}
8995
8996#include "array.rbinc"
#define RUBY_ASSERT_ALWAYS(expr,...)
A variant of RUBY_ASSERT that does not interface with RUBY_DEBUG.
Definition assert.h:199
#define RBIMPL_ASSERT_OR_ASSUME(...)
This is either RUBY_ASSERT or RBIMPL_ASSUME, depending on RUBY_DEBUG.
Definition assert.h:311
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1691
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1484
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2860
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3150
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1021
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
Definition fl_type.h:133
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1683
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:136
#define rb_str_buf_new2
Old name of rb_str_buf_new_cstr.
Definition string.h:1680
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:134
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:128
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1681
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:130
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FL_UNSET
Old name of RB_FL_UNSET.
Definition fl_type.h:132
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:129
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:476
void rb_iter_break(void)
Breaks from a block.
Definition vm.c:2283
VALUE rb_eFrozenError
FrozenError exception.
Definition error.c:1430
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1435
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1433
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
Definition eval.c:1172
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:497
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
VALUE rb_cArray
Array class.
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:27
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:100
VALUE rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
Identical to rb_class_new_instance(), except it passes the passed keywords if any to the #initialize ...
Definition object.c:2226
VALUE rb_obj_frozen_p(VALUE obj)
Just calls RB_OBJ_FROZEN() inside.
Definition object.c:1354
int rb_eql(VALUE lhs, VALUE rhs)
Checks for equality of the passed objects, in terms of Object#eql?.
Definition object.c:189
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:198
VALUE rb_cRandom
Random class.
Definition random.c:245
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:686
double rb_num2dbl(VALUE num)
Converts an instance of rb_cNumeric into C's double.
Definition object.c:3829
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:176
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:923
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1342
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:615
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
Encoding relates APIs.
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1117
VALUE rb_call_super(int argc, const VALUE *argv)
This resembles ruby's super.
Definition vm_eval.c:362
#define RGENGC_WB_PROTECTED_ARRAY
This is a compile-time flag to enable/disable write barrier for struct RArray.
Definition gc.h:446
VALUE rb_ary_rotate(VALUE ary, long rot)
Destructively rotates the passed array in-place to towards its end.
VALUE rb_ary_new_from_values(long n, const VALUE *elts)
Identical to rb_ary_new_from_args(), except how objects are passed.
VALUE rb_ary_cmp(VALUE lhs, VALUE rhs)
Recursively compares each elements of the two arrays one-by-one using <=>.
VALUE rb_ary_rassoc(VALUE alist, VALUE key)
Identical to rb_ary_assoc(), except it scans the passed array from the opposite direction.
VALUE rb_ary_concat(VALUE lhs, VALUE rhs)
Destructively appends the contents of latter into the end of former.
VALUE rb_ary_assoc(VALUE alist, VALUE key)
Looks up the passed key, assuming the passed array is an alist.
VALUE rb_ary_reverse(VALUE ary)
Destructively reverses the passed array in-place.
VALUE rb_ary_shared_with_p(VALUE lhs, VALUE rhs)
Queries if the passed two arrays share the same backend storage.
VALUE rb_ary_shift(VALUE ary)
Destructively deletes an element from the beginning of the passed array and returns what was deleted.
VALUE rb_ary_sort(VALUE ary)
Creates a copy of the passed array, whose elements are sorted according to their <=> result.
VALUE rb_ary_resurrect(VALUE ary)
I guess there is no use case of this function in extension libraries, but this is a routine identical...
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_includes(VALUE ary, VALUE elem)
Queries if the passed array has the passed entry.
VALUE rb_ary_aref(int argc, const VALUE *argv, VALUE ary)
Queries element(s) of an array.
VALUE rb_get_values_at(VALUE obj, long olen, int argc, const VALUE *argv, VALUE(*func)(VALUE obj, long oidx))
This was a generalisation of Array#values_at, Struct#values_at, and MatchData#values_at.
void rb_ary_free(VALUE ary)
Destroys the given array for no reason.
VALUE rb_ary_each(VALUE ary)
Iteratively yields each element of the passed array to the implicitly passed block if any.
VALUE rb_ary_delete_at(VALUE ary, long pos)
Destructively removes an element which resides at the specific index of the passed array.
VALUE rb_ary_plus(VALUE lhs, VALUE rhs)
Creates a new array, concatenating the former to the latter.
VALUE rb_ary_cat(VALUE ary, const VALUE *train, long len)
Destructively appends multiple elements at the end of the array.
void rb_ary_modify(VALUE ary)
Declares that the array is about to be modified.
VALUE rb_ary_replace(VALUE copy, VALUE orig)
Replaces the contents of the former object with the contents of the latter.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_to_ary(VALUE obj)
Force converts an object to an array.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_resize(VALUE ary, long len)
Expands or shrinks the passed array to the passed length.
VALUE rb_ary_pop(VALUE ary)
Destructively deletes an element from the end of the passed array and returns what was deleted.
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
VALUE rb_ary_subseq(VALUE ary, long beg, long len)
Obtains a part of the passed array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
VALUE rb_ary_to_s(VALUE ary)
Converts an array into a human-readable string.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
VALUE rb_ary_sort_bang(VALUE ary)
Destructively sorts the passed array in-place, according to each elements' <=> result.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
void rb_mem_clear(VALUE *buf, long len)
Fills the memory region with a series of RUBY_Qnil.
VALUE rb_ary_delete(VALUE ary, VALUE elem)
Destructively removes elements from the passed array, so that there would be no elements inside that ...
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
#define RETURN_ENUMERATOR(obj, argc, argv)
Identical to RETURN_SIZED_ENUMERATOR(), except its size is unknown.
Definition enumerator.h:242
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
VALUE rb_output_fs
The field separator character for outputs, or the $,.
Definition io.c:204
VALUE rb_int_positive_pow(long x, unsigned long y)
Raises the passed x to the power of y.
Definition numeric.c:4701
VALUE rb_range_beg_len(VALUE range, long *begp, long *lenp, long len, int err)
Deconstructs a numerical range.
Definition range.c:1950
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:943
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:946
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1533
#define rb_usascii_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "US ASCII" encoding.
Definition string.h:1568
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition string.c:3765
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3389
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1776
int rb_str_cmp(VALUE lhs, VALUE rhs)
Compares two strings, as in strcmp(3).
Definition string.c:4216
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2952
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
Definition string.c:1718
VALUE rb_obj_as_string(VALUE obj)
Try converting an object to its stringised representation using its to_s method, if any.
Definition string.c:1850
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5607
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
Definition thread.c:5618
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3471
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
int capa
Designed capacity of the buffer.
Definition io.h:11
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition io.h:2
int len
Length of the buffer.
Definition io.h:8
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:235
void ruby_qsort(void *, const size_t, const size_t, int(*)(const void *, const void *, void *), void *)
Reentrant implementation of quick sort.
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition iterator.h:58
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
Definition vm_eval.c:1395
VALUE rb_yield_values2(int n, const VALUE *argv)
Identical to rb_yield_values(), except it takes the parameters as a C array instead of variadic argum...
Definition vm_eval.c:1417
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1372
#define RBIMPL_ATTR_MAYBE_UNUSED()
Wraps (or simulates) [[maybe_unused]].
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:360
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define MEMMOVE(p1, p2, type, n)
Handy macro to call memmove.
Definition memory.h:384
VALUE rb_block_call(VALUE q, ID w, int e, const VALUE *r, type *t, VALUE y)
Call a method with a block.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY(obj)
Convenient casting macro.
Definition rarray.h:44
#define RARRAY_PTR_USE(ary, ptr_name, expr)
Declares a section of code where raw pointers are used.
Definition rarray.h:348
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
void(*) RUBY_DATA_FUNC(void *)
This is the type of callbacks registered to RData.
Definition rdata.h:104
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:69
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define RTYPEDDATA_DATA(v)
Convenient getter macro.
Definition rtypeddata.h:103
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:461
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:205
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition scan_args.h:78
#define RTEST
This is an old name of RB_TEST.
Ruby's array.
Definition rarray.h:128
struct RBasic basic
Basic part, including flags and class.
Definition rarray.h:131
VALUE flags
Per-object flags.
Definition rbasic.h:81
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40