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