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