Ruby 4.1.0dev (2026-10-26 revision 29264f878a52d2c36c75bfca6d04adaefeacbb30)
enum.c (29264f878a52d2c36c75bfca6d04adaefeacbb30)
1/**********************************************************************
2
3 enum.c -
4
5 $Author$
6 created at: Fri Oct 1 15:15:19 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "id.h"
13#include "internal.h"
14#include "internal/compar.h"
15#include "internal/enum.h"
16#include "internal/hash.h"
17#include "internal/imemo.h"
18#include "internal/numeric.h"
19#include "internal/object.h"
20#include "internal/proc.h"
21#include "internal/rational.h"
22#include "internal/re.h"
23#include "internal/set.h"
24#include "ruby/util.h"
25#include "ruby_assert.h"
26#include "symbol.h"
27
29
30static ID id_next;
31static ID id__alone;
32static ID id__separator;
33static ID id_chunk_categorize;
34static ID id_chunk_enumerable;
35static ID id_sliceafter_enum;
36static ID id_sliceafter_pat;
37static ID id_sliceafter_pred;
38static ID id_slicebefore_enumerable;
39static ID id_slicebefore_sep_pat;
40static ID id_slicebefore_sep_pred;
41static ID id_slicewhen_enum;
42static ID id_slicewhen_inverted;
43static ID id_slicewhen_pred;
44
45#define id_div idDiv
46#define id_each idEach
47#define id_eqq idEqq
48#define id_cmp idCmp
49#define id_lshift idLTLT
50#define id_call idCall
51#define id_size idSize
52
54rb_enum_values_pack(int argc, const VALUE *argv)
55{
56 if (argc == 0) return Qnil;
57 if (argc == 1) return argv[0];
58 return rb_ary_new4(argc, argv);
59}
60
61#define ENUM_WANT_SVALUE() do { \
62 i = rb_enum_values_pack(argc, argv); \
63} while (0)
64
65static VALUE
66enum_yield(int argc, VALUE ary)
67{
68 if (argc > 1)
69 return rb_yield_force_blockarg(ary);
70 if (argc == 1)
71 return rb_yield(ary);
72 return rb_yield_values2(0, 0);
73}
74
75static VALUE
76enum_yield_array(VALUE ary)
77{
78 rb_len_t len = RARRAY_LEN(ary);
79
80 if (len > 1)
81 return rb_yield_force_blockarg(ary);
82 if (len == 1)
83 return rb_yield(RARRAY_AREF(ary, 0));
84 return rb_yield_values2(0, 0);
85}
86
87static VALUE
88grep_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
89{
90 struct MEMO *memo = MEMO_CAST(args);
91 ENUM_WANT_SVALUE();
92
93 if (RTEST(rb_funcallv(memo->v1, id_eqq, 1, &i)) == RTEST(memo->u3.value)) {
94 rb_ary_push(memo->v2, i);
95 }
96 return Qnil;
97}
98
99static VALUE
100grep_regexp_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
101{
102 struct MEMO *memo = MEMO_CAST(args);
103 VALUE converted_element, match;
104 ENUM_WANT_SVALUE();
105
106 /* In case element can't be converted to a Symbol or String: not a match (don't raise) */
107 converted_element = SYMBOL_P(i) ? i : rb_check_string_type(i);
108 match = NIL_P(converted_element) ? Qfalse : rb_reg_match_p(memo->v1, i, 0);
109 if (match == memo->u3.value) {
110 rb_ary_push(memo->v2, i);
111 }
112 return Qnil;
113}
114
115static VALUE
116grep_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
117{
118 struct MEMO *memo = MEMO_CAST(args);
119 ENUM_WANT_SVALUE();
120
121 if (RTEST(rb_funcallv(memo->v1, id_eqq, 1, &i)) == RTEST(memo->u3.value)) {
122 rb_ary_push(memo->v2, enum_yield(argc, i));
123 }
124 return Qnil;
125}
126
127static VALUE
128enum_grep0(VALUE obj, VALUE pat, VALUE test)
129{
130 VALUE ary = rb_ary_new();
131 struct MEMO *memo = rb_imemo_memo_new_value(pat, ary, test);
133 if (rb_block_given_p()) {
134 fn = grep_iter_i;
135 }
136 else if (RB_TYPE_P(pat, T_REGEXP) &&
137 LIKELY(rb_method_basic_definition_p(CLASS_OF(pat), idEqq))) {
138 fn = grep_regexp_i;
139 }
140 else {
141 fn = grep_i;
142 }
143 rb_block_call(obj, id_each, 0, 0, fn, (VALUE)memo);
144
145 return ary;
146}
147
148/*
149 * call-seq:
150 * grep(pattern) -> array
151 * grep(pattern) {|element| ... } -> array
152 *
153 * Returns an array of objects based elements of +self+ that match the given pattern.
154 *
155 * With no block given, returns an array containing each element
156 * for which <tt>pattern === element</tt> is +true+:
157 *
158 * a = ['foo', 'bar', 'car', 'moo']
159 * a.grep(/ar/) # => ["bar", "car"]
160 * (1..10).grep(3..8) # => [3, 4, 5, 6, 7, 8]
161 * ['a', 'b', 0, 1].grep(Integer) # => [0, 1]
162 *
163 * With a block given,
164 * calls the block with each matching element and returns an array containing each
165 * object returned by the block:
166 *
167 * a = ['foo', 'bar', 'car', 'moo']
168 * a.grep(/ar/) {|element| element.upcase } # => ["BAR", "CAR"]
169 *
170 * Related: #grep_v.
171 */
172
173static VALUE
174enum_grep(VALUE obj, VALUE pat)
175{
176 return enum_grep0(obj, pat, Qtrue);
177}
178
179/*
180 * call-seq:
181 * grep_v(pattern) -> array
182 * grep_v(pattern) {|element| ... } -> array
183 *
184 * Returns an array of objects based on elements of +self+
185 * that <em>don't</em> match the given pattern.
186 *
187 * With no block given, returns an array containing each element
188 * for which <tt>pattern === element</tt> is +false+:
189 *
190 * a = ['foo', 'bar', 'car', 'moo']
191 * a.grep_v(/ar/) # => ["foo", "moo"]
192 * (1..10).grep_v(3..8) # => [1, 2, 9, 10]
193 * ['a', 'b', 0, 1].grep_v(Integer) # => ["a", "b"]
194 *
195 * With a block given,
196 * calls the block with each non-matching element and returns an array containing each
197 * object returned by the block:
198 *
199 * a = ['foo', 'bar', 'car', 'moo']
200 * a.grep_v(/ar/) {|element| element.upcase } # => ["FOO", "MOO"]
201 *
202 * Related: #grep.
203 */
204
205static VALUE
206enum_grep_v(VALUE obj, VALUE pat)
207{
208 return enum_grep0(obj, pat, Qfalse);
209}
210
211static inline void
212MEMO_V3_SET(struct MEMO *m, VALUE v)
213{
214 RB_OBJ_WRITE(m, &m->u3.value, v);
215 m->flags |= MEMO_U3_IS_VALUE;
216}
217
218static void
219imemo_count_up(struct MEMO *memo)
220{
221 if (memo->flags & MEMO_U3_IS_VALUE) {
222 RUBY_ASSERT(RB_TYPE_P(memo->u3.value, T_BIGNUM));
223 MEMO_V3_SET(memo, rb_int_succ(memo->u3.value));
224 }
225 else if (++memo->u3.ucnt == 0) {
226 /* overflow */
227 MEMO_V3_SET(memo, rb_int_succ(ULEN2NUM(RB_ULEN_MAX)));
228 }
229}
230
231static VALUE
232imemo_count_value(struct MEMO *memo)
233{
234 if (memo->flags & MEMO_U3_IS_VALUE) {
235 RUBY_ASSERT(RB_TYPE_P(memo->u3.value, T_BIGNUM));
236 return memo->u3.value;
237 }
238 else {
239 return ULEN2NUM(memo->u3.ucnt);
240 }
241}
242
243static VALUE
244count_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
245{
246 struct MEMO *memo = MEMO_CAST(memop);
247
248 ENUM_WANT_SVALUE();
249
250 if (rb_equal(i, memo->v1)) {
251 imemo_count_up(memo);
252 }
253 return Qnil;
254}
255
256static VALUE
257count_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
258{
259 struct MEMO *memo = MEMO_CAST(memop);
260
261 if (RTEST(rb_yield_values2(argc, argv))) {
262 imemo_count_up(memo);
263 }
264 return Qnil;
265}
266
267static VALUE
268count_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
269{
270 struct MEMO *memo = MEMO_CAST(memop);
271
272 imemo_count_up(memo);
273 return Qnil;
274}
275
276/*
277 * call-seq:
278 * count -> integer
279 * count(object) -> integer
280 * count {|element| ... } -> integer
281 *
282 * Returns the count of elements, based on an argument or block criterion, if given.
283 *
284 * With no argument and no block given, returns the number of elements:
285 *
286 * [0, 1, 2].count # => 3
287 * {foo: 0, bar: 1, baz: 2}.count # => 3
288 *
289 * With argument +object+ given,
290 * returns the number of elements that are <tt>==</tt> to +object+:
291 *
292 * [0, 1, 2, 1].count(1) # => 2
293 *
294 * With a block given, calls the block with each element
295 * and returns the number of elements for which the block returns a truthy value:
296 *
297 * [0, 1, 2, 3].count {|element| element < 2} # => 2
298 * {foo: 0, bar: 1, baz: 2}.count {|key, value| value < 2} # => 2
299 *
300 */
301
302static VALUE
303enum_count(int argc, VALUE *argv, VALUE obj)
304{
305 VALUE item = Qnil;
306 struct MEMO *memo;
307 rb_block_call_func *func;
308
309 if (argc == 0) {
310 if (rb_block_given_p()) {
311 func = count_iter_i;
312 }
313 else {
314 func = count_all_i;
315 }
316 }
317 else {
318 rb_scan_args(argc, argv, "1", &item);
319 if (rb_block_given_p()) {
320 rb_warn("given block not used");
321 }
322 func = count_i;
323 }
324
325 memo = rb_imemo_memo_new(item, 0, 0);
326 rb_block_call(obj, id_each, 0, 0, func, (VALUE)memo);
327 return imemo_count_value(memo);
328}
329
330NORETURN(static void found(VALUE i, VALUE memop));
331static void
332found(VALUE i, VALUE memop)
333{
334 struct MEMO *memo = MEMO_CAST(memop);
335 MEMO_V1_SET(memo, i);
336 memo->u3.cnt = 1;
338}
339
340static VALUE
341find_i_fast(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
342{
343 if (RTEST(rb_yield_values2(argc, argv))) {
344 ENUM_WANT_SVALUE();
345 found(i, memop);
346 }
347 return Qnil;
348}
349
350static VALUE
351find_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
352{
353 ENUM_WANT_SVALUE();
354
355 if (RTEST(enum_yield(argc, i))) {
356 found(i, memop);
357 }
358 return Qnil;
359}
360
361/*
362 * call-seq:
363 * find(if_none_proc = nil) {|element| ... } -> object or nil
364 * find(if_none_proc = nil) -> enumerator
365 *
366 * Returns the first element for which the block returns a truthy value.
367 *
368 * With a block given, calls the block with successive elements of the collection;
369 * returns the first element for which the block returns a truthy value:
370 *
371 * (0..9).find {|element| element > 2} # => 3
372 *
373 * If no such element is found, calls +if_none_proc+ and returns its return value.
374 *
375 * (0..9).find(proc {false}) {|element| element > 12} # => false
376 * {foo: 0, bar: 1, baz: 2}.find {|key, value| key.start_with?('b') } # => [:bar, 1]
377 * {foo: 0, bar: 1, baz: 2}.find(proc {[]}) {|key, value| key.start_with?('c') } # => []
378 *
379 * With no block given, returns an Enumerator.
380 *
381 */
382static VALUE
383enum_find(int argc, VALUE *argv, VALUE obj)
384{
385 struct MEMO *memo;
386 VALUE if_none;
387
388 if_none = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
389 RETURN_ENUMERATOR(obj, argc, argv);
390 memo = rb_imemo_memo_new(Qundef, 0, 0);
391 if (rb_block_pair_yield_optimizable())
392 rb_block_call2(obj, id_each, 0, 0, find_i_fast, (VALUE)memo, RB_BLOCK_NO_USE_PACKED_ARGS);
393 else
394 rb_block_call2(obj, id_each, 0, 0, find_i, (VALUE)memo, RB_BLOCK_NO_USE_PACKED_ARGS);
395 if (memo->u3.cnt) {
396 return memo->v1;
397 }
398 if (!NIL_P(if_none)) {
399 return rb_funcallv(if_none, id_call, 0, 0);
400 }
401 return Qnil;
402}
403
404static VALUE
405find_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
406{
407 struct MEMO *memo = MEMO_CAST(memop);
408
409 ENUM_WANT_SVALUE();
410
411 if (rb_equal(i, memo->v2)) {
412 MEMO_V1_SET(memo, imemo_count_value(memo));
414 }
415 imemo_count_up(memo);
416 return Qnil;
417}
418
419static VALUE
420find_index_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
421{
422 struct MEMO *memo = MEMO_CAST(memop);
423
424 if (RTEST(rb_yield_values2(argc, argv))) {
425 MEMO_V1_SET(memo, imemo_count_value(memo));
427 }
428 imemo_count_up(memo);
429 return Qnil;
430}
431
432/*
433 * call-seq:
434 * find_index(object) -> integer or nil
435 * find_index {|element| ... } -> integer or nil
436 * find_index -> enumerator
437 *
438 * Returns the index of the first element that meets a specified criterion,
439 * or +nil+ if no such element is found.
440 *
441 * With argument +object+ given,
442 * returns the index of the first element that is <tt>==</tt> +object+:
443 *
444 * ['a', 'b', 'c', 'b'].find_index('b') # => 1
445 *
446 * With a block given, calls the block with successive elements;
447 * returns the first element for which the block returns a truthy value:
448 *
449 * ['a', 'b', 'c', 'b'].find_index {|element| element.start_with?('b') } # => 1
450 * {foo: 0, bar: 1, baz: 2}.find_index {|key, value| value > 1 } # => 2
451 *
452 * With no argument and no block given, returns an Enumerator.
453 *
454 */
455
456static VALUE
457enum_find_index(int argc, VALUE *argv, VALUE obj)
458{
459 struct MEMO *memo; /* [return value, current index, ] */
460 VALUE condition_value = Qnil;
461 rb_block_call_func *func;
462
463 if (argc == 0) {
464 RETURN_ENUMERATOR(obj, 0, 0);
465 func = find_index_iter_i;
466 }
467 else {
468 rb_scan_args(argc, argv, "1", &condition_value);
469 if (rb_block_given_p()) {
470 rb_warn("given block not used");
471 }
472 func = find_index_i;
473 }
474
475 memo = rb_imemo_memo_new(Qnil, condition_value, 0);
476 rb_block_call(obj, id_each, 0, 0, func, (VALUE)memo);
477 return memo->v1;
478}
479
480static VALUE
481find_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
482{
483 ENUM_WANT_SVALUE();
484
485 if (RTEST(enum_yield(argc, i))) {
486 rb_ary_push(ary, i);
487 }
488 return Qnil;
489}
490
491static VALUE
492enum_size(VALUE self, VALUE args, VALUE eobj)
493{
494 return rb_check_funcall_default(self, id_size, 0, 0, Qnil);
495}
496
497static rb_len_t
498limit_by_enum_size(VALUE obj, rb_len_t n)
499{
500 rb_ulen_t limit;
501 VALUE size = rb_check_funcall(obj, id_size, 0, 0);
502 if (!FIXNUM_P(size)) return n;
503 limit = FIX2ULONG(size);
504 return ((rb_ulen_t)n > limit) ? (rb_len_t)limit : n;
505}
506
507static int
508enum_size_over_p(VALUE obj, rb_len_t n)
509{
510 VALUE size = rb_check_funcall(obj, id_size, 0, 0);
511 if (!FIXNUM_P(size)) return 0;
512 return ((rb_ulen_t)n > FIX2ULONG(size));
513}
514
515/*
516 * call-seq:
517 * select {|element| ... } -> array
518 * select -> enumerator
519 *
520 * Returns an array containing elements selected by the block.
521 *
522 * With a block given, calls the block with successive elements;
523 * returns an array of those elements for which the block returns a truthy value:
524 *
525 * (0..9).select {|element| element % 3 == 0 } # => [0, 3, 6, 9]
526 * a = {foo: 0, bar: 1, baz: 2}.select {|key, value| key.start_with?('b') }
527 * a # => {:bar=>1, :baz=>2}
528 *
529 * With no block given, returns an Enumerator.
530 *
531 * Related: #reject.
532 */
533static VALUE
534enum_find_all(VALUE obj)
535{
536 VALUE ary;
537
538 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
539
540 ary = rb_ary_new();
541 rb_block_call(obj, id_each, 0, 0, find_all_i, ary);
542
543 return ary;
544}
545
546static VALUE
547filter_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
548{
549 i = rb_yield_values2(argc, argv);
550
551 if (RTEST(i)) {
552 rb_ary_push(ary, i);
553 }
554
555 return Qnil;
556}
557
558/*
559 * call-seq:
560 * filter_map {|element| ... } -> array
561 * filter_map -> enumerator
562 *
563 * Returns an array containing truthy elements returned by the block.
564 *
565 * With a block given, calls the block with successive elements;
566 * returns an array containing each truthy value returned by the block:
567 *
568 * (0..9).filter_map {|i| i * 2 if i.even? } # => [0, 4, 8, 12, 16]
569 * {foo: 0, bar: 1, baz: 2}.filter_map {|key, value| key if value.even? } # => [:foo, :baz]
570 *
571 * When no block given, returns an Enumerator.
572 *
573 */
574static VALUE
575enum_filter_map(VALUE obj)
576{
577 VALUE ary;
578
579 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
580
581 ary = rb_ary_new();
582 rb_block_call(obj, id_each, 0, 0, filter_map_i, ary);
583
584 return ary;
585}
586
587
588static VALUE
589reject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
590{
591 ENUM_WANT_SVALUE();
592
593 if (!RTEST(enum_yield(argc, i))) {
594 rb_ary_push(ary, i);
595 }
596 return Qnil;
597}
598
599/*
600 * call-seq:
601 * reject {|element| ... } -> array
602 * reject -> enumerator
603 *
604 * Returns an array of objects rejected by the block.
605 *
606 * With a block given, calls the block with successive elements;
607 * returns an array of those elements for which the block returns +nil+ or +false+:
608 *
609 * (0..9).reject {|i| i * 2 if i.even? } # => [1, 3, 5, 7, 9]
610 * {foo: 0, bar: 1, baz: 2}.reject {|key, value| key if value.odd? } # => {:foo=>0, :baz=>2}
611 *
612 * When no block given, returns an Enumerator.
613 *
614 * Related: #select.
615 */
616
617static VALUE
618enum_reject(VALUE obj)
619{
620 VALUE ary;
621
622 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
623
624 ary = rb_ary_new();
625 rb_block_call(obj, id_each, 0, 0, reject_i, ary);
626
627 return ary;
628}
629
630static VALUE
631collect_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
632{
633 rb_ary_push(ary, rb_yield_values2(argc, argv));
634
635 return Qnil;
636}
637
638static VALUE
639collect_all(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
640{
641 rb_ary_push(ary, rb_enum_values_pack(argc, argv));
642
643 return Qnil;
644}
645
646/*
647 * call-seq:
648 * map {|element| ... } -> array
649 * map -> enumerator
650 *
651 * Returns an array of objects returned by the block.
652 *
653 * With a block given, calls the block with successive elements;
654 * returns an array of the objects returned by the block:
655 *
656 * (0..4).map {|i| i*i } # => [0, 1, 4, 9, 16]
657 * {foo: 0, bar: 1, baz: 2}.map {|key, value| value*2} # => [0, 2, 4]
658 *
659 * With no block given, returns an Enumerator.
660 *
661 */
662static VALUE
663enum_collect(VALUE obj)
664{
665 VALUE ary;
666 int min_argc, max_argc;
667
668 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
669
670 ary = rb_ary_new();
671 min_argc = rb_block_min_max_arity(&max_argc);
672 rb_lambda_call(obj, id_each, 0, 0, collect_i, min_argc, max_argc, ary);
673
674 return ary;
675}
676
677static VALUE
678flat_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
679{
680 VALUE tmp;
681
682 i = rb_yield_values2(argc, argv);
683 tmp = rb_check_array_type(i);
684
685 if (NIL_P(tmp)) {
686 rb_ary_push(ary, i);
687 }
688 else {
689 rb_ary_concat(ary, tmp);
690 }
691 return Qnil;
692}
693
694/*
695 * call-seq:
696 * flat_map {|element| ... } -> array
697 * flat_map -> enumerator
698 *
699 * Returns an array of flattened objects returned by the block.
700 *
701 * With a block given, calls the block with successive elements;
702 * returns a flattened array of objects returned by the block:
703 *
704 * [0, 1, 2, 3].flat_map {|element| -element } # => [0, -1, -2, -3]
705 * [0, 1, 2, 3].flat_map {|element| [element, -element] } # => [0, 0, 1, -1, 2, -2, 3, -3]
706 * [[0, 1], [2, 3]].flat_map {|e| e + [100] } # => [0, 1, 100, 2, 3, 100]
707 * {foo: 0, bar: 1, baz: 2}.flat_map {|key, value| [key, value] } # => [:foo, 0, :bar, 1, :baz, 2]
708 *
709 * With no block given, returns an Enumerator.
710 *
711 * Alias: #collect_concat.
712 */
713static VALUE
714enum_flat_map(VALUE obj)
715{
716 VALUE ary;
717
718 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
719
720 ary = rb_ary_new();
721 rb_block_call(obj, id_each, 0, 0, flat_map_i, ary);
722
723 return ary;
724}
725
726/*
727 * call-seq:
728 * to_a(*args) -> array
729 *
730 * Returns an array containing the items in +self+:
731 *
732 * (0..4).to_a # => [0, 1, 2, 3, 4]
733 *
734 */
735static VALUE
736enum_to_a(int argc, VALUE *argv, VALUE obj)
737{
738 VALUE ary = rb_ary_new();
739
740 rb_block_call_kw(obj, id_each, argc, argv, collect_all, ary, RB_PASS_CALLED_KEYWORDS);
741
742 return ary;
743}
744
745static VALUE
746enum_hashify_into(VALUE obj, int argc, const VALUE *argv, rb_block_call_func *iter, VALUE hash)
747{
748 rb_block_call(obj, id_each, argc, argv, iter, hash);
749 return hash;
750}
751
752static VALUE
753enum_hashify(VALUE obj, int argc, const VALUE *argv, rb_block_call_func *iter)
754{
755 return enum_hashify_into(obj, argc, argv, iter, rb_hash_new());
756}
757
758static VALUE
759enum_to_h_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
760{
761 ENUM_WANT_SVALUE();
762 return rb_hash_set_pair(hash, i);
763}
764
765static VALUE
766enum_to_h_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
767{
768 return rb_hash_set_pair(hash, rb_yield_values2(argc, argv));
769}
770
771/*
772 * call-seq:
773 * to_h(*args) -> hash
774 * to_h(*args) {|element| ... } -> hash
775 *
776 * When +self+ consists of 2-element arrays,
777 * returns a hash each of whose entries is the key-value pair
778 * formed from one of those arrays:
779 *
780 * [[:foo, 0], [:bar, 1], [:baz, 2]].to_h # => {:foo=>0, :bar=>1, :baz=>2}
781 *
782 * When a block is given, the block is called with each element of +self+;
783 * the block should return a 2-element array which becomes a key-value pair
784 * in the returned hash:
785 *
786 * (0..3).to_h {|i| [i, i ** 2]} # => {0=>0, 1=>1, 2=>4, 3=>9}
787 *
788 * Raises an exception if an element of +self+ is not a 2-element array,
789 * and a block is not passed.
790 */
791
792static VALUE
793enum_to_h(int argc, VALUE *argv, VALUE obj)
794{
795 rb_block_call_func *iter = rb_block_given_p() ? enum_to_h_ii : enum_to_h_i;
796 return enum_hashify(obj, argc, argv, iter);
797}
798
799static VALUE
800inject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
801{
802 struct MEMO *memo = MEMO_CAST(p);
803
804 ENUM_WANT_SVALUE();
805
806 if (UNDEF_P(memo->v1)) {
807 MEMO_V1_SET(memo, i);
808 }
809 else {
810 MEMO_V1_SET(memo, rb_yield_values(2, memo->v1, i));
811 }
812 return Qnil;
813}
814
815static VALUE
816inject_op_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
817{
818 struct MEMO *memo = MEMO_CAST(p);
819 VALUE name;
820
821 ENUM_WANT_SVALUE();
822
823 if (UNDEF_P(memo->v1)) {
824 MEMO_V1_SET(memo, i);
825 }
826 else if (SYMBOL_P(name = memo->u3.value)) {
827 const ID mid = SYM2ID(name);
828 MEMO_V1_SET(memo, rb_funcallv_public(memo->v1, mid, 1, &i));
829 }
830 else {
831 VALUE args[2];
832 args[0] = name;
833 args[1] = i;
834 MEMO_V1_SET(memo, rb_f_send(numberof(args), args, memo->v1));
835 }
836 return Qnil;
837}
838
839static VALUE
840ary_inject_op(VALUE ary, VALUE init, VALUE op)
841{
842 ID id;
843 VALUE v, e;
844 rb_len_t i;
845 long n;
846
847 if (RARRAY_LEN(ary) == 0)
848 return UNDEF_P(init) ? Qnil : init;
849
850 if (UNDEF_P(init)) {
851 v = RARRAY_AREF(ary, 0);
852 i = 1;
853 if (RARRAY_LEN(ary) == 1)
854 return v;
855 }
856 else {
857 v = init;
858 i = 0;
859 }
860
861 id = SYM2ID(op);
862 if (id == idPLUS) {
863 if (RB_INTEGER_TYPE_P(v) &&
865 rb_obj_respond_to(v, idPLUS, FALSE)) {
866 n = 0;
867 for (; i < RARRAY_LEN(ary); i++) {
868 e = RARRAY_AREF(ary, i);
869 if (FIXNUM_P(e)) {
870 n += FIX2LONG(e); /* should not overflow long type */
871 if (!FIXABLE(n)) {
872 v = rb_big_plus(LONG2NUM(n), v);
873 n = 0;
874 }
875 }
876 else if (RB_BIGNUM_TYPE_P(e))
877 v = rb_big_plus(e, v);
878 else
879 goto not_integer;
880 }
881 if (n != 0)
882 v = rb_fix_plus(LONG2FIX(n), v);
883 return v;
884
885 not_integer:
886 if (n != 0)
887 v = rb_fix_plus(LONG2FIX(n), v);
888 }
889 }
890 for (; i < RARRAY_LEN(ary); i++) {
891 VALUE arg = RARRAY_AREF(ary, i);
892 v = rb_funcallv_public(v, id, 1, &arg);
893 }
894 return v;
895}
896
897/*
898 * call-seq:
899 * inject(symbol) -> object
900 * inject(initial_value, symbol) -> object
901 * inject {|memo, value| ... } -> object
902 * inject(initial_value) {|memo, value| ... } -> object
903 *
904 * Returns the result of applying a reducer to an initial value and
905 * the first element of the Enumerable. It then takes the result and applies the
906 * function to it and the second element of the collection, and so on. The
907 * return value is the result returned by the final call to the function.
908 *
909 * You can think of
910 *
911 * [ a, b, c, d ].inject(i) { |r, v| fn(r, v) }
912 *
913 * as being
914 *
915 * fn(fn(fn(fn(i, a), b), c), d)
916 *
917 * In a way the +inject+ function _injects_ the function
918 * between the elements of the enumerable.
919 *
920 * +inject+ is aliased as +reduce+. You use it when you want to
921 * _reduce_ a collection to a single value.
922 *
923 * <b>The Calling Sequences</b>
924 *
925 * Let's start with the most verbose:
926 *
927 * enum.inject(initial_value) do |result, next_value|
928 * # do something with +result+ and +next_value+
929 * # the value returned by the block becomes the
930 * # value passed in to the next iteration
931 * # as +result+
932 * end
933 *
934 * For example:
935 *
936 * product = [ 2, 3, 4 ].inject(1) do |result, next_value|
937 * result * next_value
938 * end
939 * product #=> 24
940 *
941 * When this runs, the block is first called with +1+ (the initial value) and
942 * +2+ (the first element of the array). The block returns <tt>1*2</tt>, so on
943 * the next iteration the block is called with +2+ (the previous result) and
944 * +3+. The block returns +6+, and is called one last time with +6+ and +4+.
945 * The result of the block, +24+ becomes the value returned by +inject+. This
946 * code returns the product of the elements in the enumerable.
947 *
948 * <b>First Shortcut: Default Initial value</b>
949 *
950 * In the case of the previous example, the initial value, +1+, wasn't really
951 * necessary: the calculation of the product of a list of numbers is self-contained.
952 *
953 * In these circumstances, you can omit the +initial_value+ parameter. +inject+
954 * will then initially call the block with the first element of the collection
955 * as the +result+ parameter and the second element as the +next_value+.
956 *
957 * [ 2, 3, 4 ].inject do |result, next_value|
958 * result * next_value
959 * end
960 *
961 * This shortcut is convenient, but can only be used when the block produces a result
962 * which can be passed back to it as a first parameter.
963 *
964 * Here's an example where that's not the case: it returns a hash where the keys are words
965 * and the values are the number of occurrences of that word in the enumerable.
966 *
967 * freqs = File.read("README.md")
968 * .scan(/\w{2,}/)
969 * .reduce(Hash.new(0)) do |counts, word|
970 * counts[word] += 1
971 * counts
972 * end
973 * freqs #=> {"Actions"=>4,
974 * "Status"=>5,
975 * "MinGW"=>3,
976 * "https"=>27,
977 * "github"=>10,
978 * "com"=>15, ...
979 *
980 * Note that the last line of the block is just the word +counts+. This ensures the
981 * return value of the block is the result that's being calculated.
982 *
983 * <b>Second Shortcut: a Reducer function</b>
984 *
985 * A <i>reducer function</i> is a function that takes a partial result and the next value,
986 * returning the next partial result. The block that is given to +inject+ is a reducer.
987 *
988 * You can also write a reducer as a function and pass the name of that function
989 * (as a symbol) to +inject+. However, for this to work, the function
990 *
991 * 1. Must be defined on the type of the result value
992 * 2. Must accept a single parameter, the next value in the collection, and
993 * 3. Must return an updated result which will also implement the function.
994 *
995 * Here's an example that adds elements to a string. The two calls invoke the functions
996 * String#concat and String#+ on the result so far, passing it the next value.
997 *
998 * s = [ "cat", " ", "dog" ].inject("", :concat)
999 * s #=> "cat dog"
1000 * s = [ "cat", " ", "dog" ].inject("The result is:", :+)
1001 * s #=> "The result is: cat dog"
1002 *
1003 * Here's a more complex example when the result object maintains
1004 * state of a different type to the enumerable elements.
1005 *
1006 * class Turtle
1007 *
1008 * def initialize
1009 * @x = @y = 0
1010 * end
1011 *
1012 * def move(dir)
1013 * case dir
1014 * when "n" then @y += 1
1015 * when "s" then @y -= 1
1016 * when "e" then @x += 1
1017 * when "w" then @x -= 1
1018 * end
1019 * self
1020 * end
1021 * end
1022 *
1023 * position = "nnneesw".chars.reduce(Turtle.new, :move)
1024 * position #=> #<Turtle:0x00000001052f4698 @y=2, @x=1>
1025 *
1026 * <b>Third Shortcut: Reducer With no Initial Value</b>
1027 *
1028 * If your reducer returns a value that it can accept as a parameter, then you
1029 * don't have to pass in an initial value. Here <tt>:*</tt> is the name of the
1030 * _times_ function:
1031 *
1032 * product = [ 2, 3, 4 ].inject(:*)
1033 * product # => 24
1034 *
1035 * String concatenation again:
1036 *
1037 * s = [ "cat", " ", "dog" ].inject(:+)
1038 * s #=> "cat dog"
1039 *
1040 * And an example that converts a hash to an array of two-element subarrays.
1041 *
1042 * nested = {foo: 0, bar: 1}.inject([], :push)
1043 * nested # => [[:foo, 0], [:bar, 1]]
1044 *
1045 *
1046 */
1047static VALUE
1048enum_inject(int argc, VALUE *argv, VALUE obj)
1049{
1050 struct MEMO *memo;
1051 VALUE init, op;
1052 rb_block_call_func *iter = inject_i;
1053 ID id;
1054 int num_args;
1055
1056 if (rb_block_given_p()) {
1057 num_args = rb_scan_args(argc, argv, "02", &init, &op);
1058 }
1059 else {
1060 num_args = rb_scan_args(argc, argv, "11", &init, &op);
1061 }
1062
1063 switch (num_args) {
1064 case 0:
1065 init = Qundef;
1066 break;
1067 case 1:
1068 if (rb_block_given_p()) {
1069 break;
1070 }
1071 id = rb_check_id(&init);
1072 op = id ? ID2SYM(id) : init;
1073 init = Qundef;
1074 iter = inject_op_i;
1075 break;
1076 case 2:
1077 if (rb_block_given_p()) {
1078 rb_warning("given block not used");
1079 }
1080 id = rb_check_id(&op);
1081 if (id) op = ID2SYM(id);
1082 iter = inject_op_i;
1083 break;
1084 }
1085
1086 if (iter == inject_op_i &&
1087 SYMBOL_P(op) &&
1088 RB_TYPE_P(obj, T_ARRAY) &&
1089 rb_method_basic_definition_p(CLASS_OF(obj), id_each)) {
1090 return ary_inject_op(obj, init, op);
1091 }
1092
1093 memo = rb_imemo_memo_new_value(init, Qnil, op);
1094 rb_block_call(obj, id_each, 0, 0, iter, (VALUE)memo);
1095 if (UNDEF_P(memo->v1)) return Qnil;
1096 return memo->v1;
1097}
1098
1099static VALUE
1100partition_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, arys))
1101{
1102 struct MEMO *memo = MEMO_CAST(arys);
1103 VALUE ary;
1104 ENUM_WANT_SVALUE();
1105
1106 if (RTEST(enum_yield(argc, i))) {
1107 ary = memo->v1;
1108 }
1109 else {
1110 ary = memo->v2;
1111 }
1112 rb_ary_push(ary, i);
1113 return Qnil;
1114}
1115
1116/*
1117 * call-seq:
1118 * partition {|element| ... } -> [true_array, false_array]
1119 * partition -> enumerator
1120 *
1121 * With a block given, returns an array of two arrays:
1122 *
1123 * - The first having those elements for which the block returns a truthy value.
1124 * - The other having all other elements.
1125 *
1126 * Examples:
1127 *
1128 * p = (1..4).partition {|i| i.even? }
1129 * p # => [[2, 4], [1, 3]]
1130 * p = ('a'..'d').partition {|c| c < 'c' }
1131 * p # => [["a", "b"], ["c", "d"]]
1132 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
1133 * p = h.partition {|key, value| key.start_with?('b') }
1134 * p # => [[[:bar, 1], [:baz, 2], [:bat, 3]], [[:foo, 0]]]
1135 * p = h.partition {|key, value| value < 2 }
1136 * p # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]]]
1137 *
1138 * With no block given, returns an Enumerator.
1139 *
1140 * Related: Enumerable#group_by.
1141 *
1142 */
1143
1144static VALUE
1145enum_partition(VALUE obj)
1146{
1147 struct MEMO *memo;
1148
1149 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
1150
1151 memo = rb_imemo_memo_new(rb_ary_new(), rb_ary_new(), 0);
1152 rb_block_call(obj, id_each, 0, 0, partition_i, (VALUE)memo);
1153
1154 return rb_assoc_new(memo->v1, memo->v2);
1155}
1156
1157static VALUE
1158group_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
1159{
1160 VALUE group;
1161 VALUE values;
1162
1163 ENUM_WANT_SVALUE();
1164
1165 group = enum_yield(argc, i);
1166 values = rb_hash_aref(hash, group);
1167 if (!RB_TYPE_P(values, T_ARRAY)) {
1168 values = rb_ary_new3(1, i);
1169 rb_hash_aset(hash, group, values);
1170 }
1171 else {
1172 rb_ary_push(values, i);
1173 }
1174 return Qnil;
1175}
1176
1177/*
1178 * call-seq:
1179 * group_by {|element| ... } -> hash
1180 * group_by -> enumerator
1181 *
1182 * With a block given returns a hash:
1183 *
1184 * - Each key is a return value from the block.
1185 * - Each value is an array of those elements for which the block returned that key.
1186 *
1187 * Examples:
1188 *
1189 * g = (1..6).group_by {|i| i%3 }
1190 * g # => {1=>[1, 4], 2=>[2, 5], 0=>[3, 6]}
1191 * h = {foo: 0, bar: 1, baz: 0, bat: 1}
1192 * g = h.group_by {|key, value| value }
1193 * g # => {0=>[[:foo, 0], [:baz, 0]], 1=>[[:bar, 1], [:bat, 1]]}
1194 *
1195 * With no block given, returns an Enumerator.
1196 *
1197 */
1198
1199static VALUE
1200enum_group_by(VALUE obj)
1201{
1202 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
1203
1204 return enum_hashify(obj, 0, 0, group_by_i);
1205}
1206
1207static int
1208tally_up(st_data_t *group, st_data_t *value, st_data_t arg, int existing)
1209{
1210 VALUE tally = (VALUE)*value;
1211 VALUE hash = (VALUE)arg;
1212 if (!existing) {
1213 tally = INT2FIX(1);
1214 }
1215 else if (FIXNUM_P(tally) && tally < INT2FIX(FIXNUM_MAX)) {
1216 tally += INT2FIX(1) & ~FIXNUM_FLAG;
1217 }
1218 else {
1219 Check_Type(tally, T_BIGNUM);
1220 tally = rb_big_plus(tally, INT2FIX(1));
1221 RB_OBJ_WRITTEN(hash, Qundef, tally);
1222 }
1223 *value = (st_data_t)tally;
1224 return ST_CONTINUE;
1225}
1226
1227static VALUE
1228rb_enum_tally_up(VALUE hash, VALUE group)
1229{
1230 if (!rb_hash_stlike_update(hash, group, tally_up, (st_data_t)hash)) {
1231 RB_OBJ_WRITTEN(hash, Qundef, group);
1232 }
1233 return hash;
1234}
1235
1236static VALUE
1237tally_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
1238{
1239 ENUM_WANT_SVALUE();
1240 rb_enum_tally_up(hash, i);
1241 return Qnil;
1242}
1243
1244/*
1245 * call-seq:
1246 * tally(hash = {}) -> hash
1247 *
1248 * When argument +hash+ is not given,
1249 * returns a new hash whose keys are the distinct elements in +self+;
1250 * each integer value is the count of occurrences of each element:
1251 *
1252 * %w[a b c b c a c b].tally # => {"a"=>2, "b"=>3, "c"=>3}
1253 *
1254 * When argument +hash+ is given,
1255 * returns +hash+, possibly augmented; for each element +ele+ in +self+:
1256 *
1257 * - Adds it as a key with a zero value if that key does not already exist:
1258 *
1259 * hash[ele] = 0 unless hash.include?(ele)
1260 *
1261 * - Increments the value of key +ele+:
1262 *
1263 * hash[ele] += 1
1264 *
1265 * This is useful for accumulating tallies across multiple enumerables:
1266 *
1267 * h = {} # => {}
1268 * %w[a c d b c a].tally(h) # => {"a"=>2, "c"=>2, "d"=>1, "b"=>1}
1269 * %w[b a z].tally(h) # => {"a"=>3, "c"=>2, "d"=>1, "b"=>2, "z"=>1}
1270 * %w[b a m].tally(h) # => {"a"=>4, "c"=>2, "d"=>1, "b"=>3, "z"=>1, "m"=>1}
1271 *
1272 * The key to be added or found for an element depends on the class of +self+;
1273 * see {Enumerable in Ruby Classes}[rdoc-ref:Enumerable@Enumerable+in+Ruby+Classes].
1274 *
1275 * Examples:
1276 *
1277 * - Array (and certain array-like classes):
1278 * the key is the element (as above).
1279 * - Hash (and certain hash-like classes):
1280 * the key is the 2-element array formed from the key-value pair:
1281 *
1282 * h = {} # => {}
1283 * {foo: 'a', bar: 'b'}.tally(h) # => {[:foo, "a"]=>1, [:bar, "b"]=>1}
1284 * {foo: 'c', bar: 'd'}.tally(h) # => {[:foo, "a"]=>1, [:bar, "b"]=>1, [:foo, "c"]=>1, [:bar, "d"]=>1}
1285 * {foo: 'a', bar: 'b'}.tally(h) # => {[:foo, "a"]=>2, [:bar, "b"]=>2, [:foo, "c"]=>1, [:bar, "d"]=>1}
1286 * {foo: 'c', bar: 'd'}.tally(h) # => {[:foo, "a"]=>2, [:bar, "b"]=>2, [:foo, "c"]=>2, [:bar, "d"]=>2}
1287 *
1288 */
1289
1290static VALUE
1291enum_tally(int argc, VALUE *argv, VALUE obj)
1292{
1293 VALUE hash;
1294 if (rb_check_arity(argc, 0, 1)) {
1295 hash = rb_to_hash_type(argv[0]);
1296 rb_check_frozen(hash);
1297 }
1298 else {
1299 hash = rb_hash_new();
1300 }
1301
1302 return enum_hashify_into(obj, 0, 0, tally_i, hash);
1303}
1304
1305NORETURN(static VALUE first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, params)));
1306static VALUE
1307first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, params))
1308{
1309 struct MEMO *memo = MEMO_CAST(params);
1310 ENUM_WANT_SVALUE();
1311
1312 MEMO_V1_SET(memo, i);
1313 rb_iter_break();
1314
1316}
1317
1318static VALUE enum_take(VALUE obj, VALUE n);
1319
1320/*
1321 * call-seq:
1322 * first -> element or nil
1323 * first(n) -> array
1324 *
1325 * Returns the first element or elements.
1326 *
1327 * With no argument, returns the first element, or +nil+ if there is none:
1328 *
1329 * (1..4).first # => 1
1330 * %w[a b c].first # => "a"
1331 * {foo: 1, bar: 1, baz: 2}.first # => [:foo, 1]
1332 * [].first # => nil
1333 *
1334 * With integer argument +n+, returns an array
1335 * containing the first +n+ elements that exist:
1336 *
1337 * (1..4).first(2) # => [1, 2]
1338 * %w[a b c d].first(3) # => ["a", "b", "c"]
1339 * %w[a b c d].first(50) # => ["a", "b", "c", "d"]
1340 * {foo: 1, bar: 1, baz: 2}.first(2) # => [[:foo, 1], [:bar, 1]]
1341 * [].first(2) # => []
1342 *
1343 */
1344
1345static VALUE
1346enum_first(int argc, VALUE *argv, VALUE obj)
1347{
1348 struct MEMO *memo;
1349 rb_check_arity(argc, 0, 1);
1350 if (argc > 0) {
1351 return enum_take(obj, argv[0]);
1352 }
1353 else {
1354 memo = rb_imemo_memo_new(Qnil, 0, 0);
1355 rb_block_call(obj, id_each, 0, 0, first_i, (VALUE)memo);
1356 return memo->v1;
1357 }
1358}
1359
1360/*
1361 * call-seq:
1362 * sort -> array
1363 * sort {|a, b| ... } -> array
1364 *
1365 * Returns an array containing the sorted elements of +self+.
1366 * The ordering of equal elements is indeterminate and may be unstable.
1367 *
1368 * With no block given, the sort compares
1369 * using the elements' own method <tt>#<=></tt>:
1370 *
1371 * %w[b c a d].sort # => ["a", "b", "c", "d"]
1372 * {foo: 0, bar: 1, baz: 2}.sort # => [[:bar, 1], [:baz, 2], [:foo, 0]]
1373 *
1374 * With a block given, comparisons in the block determine the ordering.
1375 * The block is called with two elements +a+ and +b+, and must return:
1376 *
1377 * - A negative integer if <tt>a < b</tt>.
1378 * - Zero if <tt>a == b</tt>.
1379 * - A positive integer if <tt>a > b</tt>.
1380 *
1381 * Examples:
1382 *
1383 * a = %w[b c a d]
1384 * a.sort {|a, b| b <=> a } # => ["d", "c", "b", "a"]
1385 * h = {foo: 0, bar: 1, baz: 2}
1386 * h.sort {|a, b| b <=> a } # => [[:foo, 0], [:baz, 2], [:bar, 1]]
1387 *
1388 * See also #sort_by. It implements a Schwartzian transform
1389 * which is useful when key computation or comparison is expensive.
1390 */
1391
1392static VALUE
1393enum_sort(VALUE obj)
1394{
1395 return rb_ary_sort_bang(enum_to_a(0, 0, obj));
1396}
1397
1398#define SORT_BY_BUFSIZE 16
1399#define SORT_BY_UNIFORMED(num, flo, fix) (((num&1)<<2)|((flo&1)<<1)|fix)
1401 const VALUE ary;
1402 const VALUE buf;
1403 uint8_t n;
1404 uint8_t primitive_uniformed;
1405};
1406
1407static VALUE
1408sort_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _data))
1409{
1410 struct sort_by_data *data = (struct sort_by_data *)&MEMO_CAST(_data)->v1;
1411 VALUE ary = data->ary;
1412 VALUE v;
1413
1414 ENUM_WANT_SVALUE();
1415
1416 v = enum_yield(argc, i);
1417
1418 if (RBASIC(ary)->klass) {
1419 rb_raise(rb_eRuntimeError, "sort_by reentered");
1420 }
1421 if (RARRAY_LEN(data->buf) != SORT_BY_BUFSIZE*2) {
1422 rb_raise(rb_eRuntimeError, "sort_by reentered");
1423 }
1424
1425 if (data->primitive_uniformed) {
1426 data->primitive_uniformed &= SORT_BY_UNIFORMED((FIXNUM_P(v)) || (RB_FLOAT_TYPE_P(v)),
1427 RB_FLOAT_TYPE_P(v),
1428 FIXNUM_P(v));
1429 }
1430 RARRAY_ASET(data->buf, data->n*2, v);
1431 RARRAY_ASET(data->buf, data->n*2+1, i);
1432 data->n++;
1433 if (data->n == SORT_BY_BUFSIZE) {
1434 rb_ary_concat(ary, data->buf);
1435 data->n = 0;
1436 }
1437 return Qnil;
1438}
1439
1440static int
1441sort_by_cmp(const void *ap, const void *bp, void *data)
1442{
1443 VALUE a;
1444 VALUE b;
1445 VALUE ary = (VALUE)data;
1446
1447 if (RBASIC(ary)->klass) {
1448 rb_raise(rb_eRuntimeError, "sort_by reentered");
1449 }
1450
1451 a = *(VALUE *)ap;
1452 b = *(VALUE *)bp;
1453
1454 return OPTIMIZED_CMP(a, b);
1455}
1456
1457
1458/*
1459 This is parts of uniform sort
1460*/
1461
1462#define uless rb_uniform_is_less
1463#define UNIFORM_SWAP(a,b)\
1464 do{struct rb_uniform_sort_data tmp = a; a = b; b = tmp;} while(0)
1465
1467 VALUE v;
1468 VALUE i;
1469};
1470
1471static inline bool
1472rb_uniform_is_less(VALUE a, VALUE b)
1473{
1474
1475 if (FIXNUM_P(a) && FIXNUM_P(b)) {
1476 return (SIGNED_VALUE)a < (SIGNED_VALUE)b;
1477 }
1478 else if (FIXNUM_P(a)) {
1480 return rb_float_cmp(b, a) > 0;
1481 }
1482 else {
1484 return rb_float_cmp(a, b) < 0;
1485 }
1486}
1487
1488static inline bool
1489rb_uniform_is_larger(VALUE a, VALUE b)
1490{
1491
1492 if (FIXNUM_P(a) && FIXNUM_P(b)) {
1493 return (SIGNED_VALUE)a > (SIGNED_VALUE)b;
1494 }
1495 else if (FIXNUM_P(a)) {
1497 return rb_float_cmp(b, a) < 0;
1498 }
1499 else {
1501 return rb_float_cmp(a, b) > 0;
1502 }
1503}
1504
1505#define med3_val(a,b,c) (uless(a,b)?(uless(b,c)?b:uless(c,a)?a:c):(uless(c,b)?b:uless(a,c)?a:c))
1506
1507static void
1508rb_uniform_insertionsort_2(struct rb_uniform_sort_data* ptr_begin,
1509 struct rb_uniform_sort_data* ptr_end)
1510{
1511 if ((ptr_end - ptr_begin) < 2) return;
1512 struct rb_uniform_sort_data tmp, *j, *k,
1513 *index = ptr_begin+1;
1514 for (; index < ptr_end; index++) {
1515 tmp = *index;
1516 j = k = index;
1517 if (uless(tmp.v, ptr_begin->v)) {
1518 while (ptr_begin < j) {
1519 *j = *(--k);
1520 j = k;
1521 }
1522 }
1523 else {
1524 while (uless(tmp.v, (--k)->v)) {
1525 *j = *k;
1526 j = k;
1527 }
1528 }
1529 *j = tmp;
1530 }
1531}
1532
1533static inline void
1534rb_uniform_heap_down_2(struct rb_uniform_sort_data* ptr_begin,
1535 size_t offset, size_t len)
1536{
1537 size_t c;
1538 struct rb_uniform_sort_data tmp = ptr_begin[offset];
1539 while ((c = (offset<<1)+1) <= len) {
1540 if (c < len && uless(ptr_begin[c].v, ptr_begin[c+1].v)) {
1541 c++;
1542 }
1543 if (!uless(tmp.v, ptr_begin[c].v)) break;
1544 ptr_begin[offset] = ptr_begin[c];
1545 offset = c;
1546 }
1547 ptr_begin[offset] = tmp;
1548}
1549
1550static void
1551rb_uniform_heapsort_2(struct rb_uniform_sort_data* ptr_begin,
1552 struct rb_uniform_sort_data* ptr_end)
1553{
1554 size_t n = ptr_end - ptr_begin;
1555 if (n < 2) return;
1556
1557 for (size_t offset = n>>1; offset > 0;) {
1558 rb_uniform_heap_down_2(ptr_begin, --offset, n-1);
1559 }
1560 for (size_t offset = n-1; offset > 0;) {
1561 UNIFORM_SWAP(*ptr_begin, ptr_begin[offset]);
1562 rb_uniform_heap_down_2(ptr_begin, 0, --offset);
1563 }
1564}
1565
1566
1567static void
1568rb_uniform_quicksort_intro_2(struct rb_uniform_sort_data* ptr_begin,
1569 struct rb_uniform_sort_data* ptr_end, size_t d)
1570{
1571
1572 if (ptr_end - ptr_begin <= 16) {
1573 rb_uniform_insertionsort_2(ptr_begin, ptr_end);
1574 return;
1575 }
1576 if (d == 0) {
1577 rb_uniform_heapsort_2(ptr_begin, ptr_end);
1578 return;
1579 }
1580
1581 VALUE x = med3_val(ptr_begin->v,
1582 ptr_begin[(ptr_end - ptr_begin)>>1].v,
1583 ptr_end[-1].v);
1584 struct rb_uniform_sort_data *i = ptr_begin;
1585 struct rb_uniform_sort_data *j = ptr_end-1;
1586
1587 do {
1588 while (uless(i->v, x)) i++;
1589 while (uless(x, j->v)) j--;
1590 if (i <= j) {
1591 UNIFORM_SWAP(*i, *j);
1592 i++;
1593 j--;
1594 }
1595 } while (i <= j);
1596 j++;
1597 if (ptr_end - j > 1) rb_uniform_quicksort_intro_2(j, ptr_end, d-1);
1598 if (i - ptr_begin > 1) rb_uniform_quicksort_intro_2(ptr_begin, i, d-1);
1599}
1600
1606static void
1607rb_uniform_intro_sort_2(struct rb_uniform_sort_data* ptr_begin,
1608 struct rb_uniform_sort_data* ptr_end)
1609{
1610 size_t n = ptr_end - ptr_begin;
1611 size_t d = CHAR_BIT * sizeof(n) - nlz_intptr(n) - 1;
1612 bool sorted_flag = true;
1613
1614 for (struct rb_uniform_sort_data* ptr = ptr_begin+1; ptr < ptr_end; ptr++) {
1615 if (rb_uniform_is_larger((ptr-1)->v, (ptr)->v)) {
1616 sorted_flag = false;
1617 break;
1618 }
1619 }
1620
1621 if (sorted_flag) {
1622 return;
1623 }
1624 rb_uniform_quicksort_intro_2(ptr_begin, ptr_end, d<<1);
1625}
1626
1627#undef uless
1628
1629
1630/*
1631 * call-seq:
1632 * sort_by {|element| ... } -> array
1633 * sort_by -> enumerator
1634 *
1635 * With a block given, returns an array of elements of +self+,
1636 * sorted according to the value returned by the block for each element.
1637 * The ordering of equal elements is indeterminate and may be unstable.
1638 *
1639 * Examples:
1640 *
1641 * a = %w[xx xxx x xxxx]
1642 * a.sort_by {|s| s.size } # => ["x", "xx", "xxx", "xxxx"]
1643 * a.sort_by {|s| -s.size } # => ["xxxx", "xxx", "xx", "x"]
1644 * h = {foo: 2, bar: 1, baz: 0}
1645 * h.sort_by{|key, value| value } # => [[:baz, 0], [:bar, 1], [:foo, 2]]
1646 * h.sort_by{|key, value| key } # => [[:bar, 1], [:baz, 0], [:foo, 2]]
1647 *
1648 * With no block given, returns an Enumerator.
1649 *
1650 * The current implementation of #sort_by generates an array of
1651 * tuples containing the original collection element and the mapped
1652 * value. This makes #sort_by fairly expensive when the keysets are
1653 * simple.
1654 *
1655 * require 'benchmark'
1656 *
1657 * a = (1..100000).map { rand(100000) }
1658 *
1659 * Benchmark.bm(10) do |b|
1660 * b.report("Sort") { a.sort }
1661 * b.report("Sort by") { a.sort_by { |a| a } }
1662 * end
1663 *
1664 * <em>produces:</em>
1665 *
1666 * user system total real
1667 * Sort 0.180000 0.000000 0.180000 ( 0.175469)
1668 * Sort by 1.980000 0.040000 2.020000 ( 2.013586)
1669 *
1670 * However, consider the case where comparing the keys is a non-trivial
1671 * operation. The following code sorts some files on modification time
1672 * using the basic #sort method.
1673 *
1674 * files = Dir["*"]
1675 * sorted = files.sort { |a, b| File.new(a).mtime <=> File.new(b).mtime }
1676 * sorted #=> ["mon", "tues", "wed", "thurs"]
1677 *
1678 * This sort is inefficient: it generates two new File
1679 * objects during every comparison. A slightly better technique is to
1680 * use the Kernel#test method to generate the modification
1681 * times directly.
1682 *
1683 * files = Dir["*"]
1684 * sorted = files.sort { |a, b|
1685 * test(?M, a) <=> test(?M, b)
1686 * }
1687 * sorted #=> ["mon", "tues", "wed", "thurs"]
1688 *
1689 * This still generates many unnecessary Time objects. A more
1690 * efficient technique is to cache the sort keys (modification times
1691 * in this case) before the sort. Perl users often call this approach
1692 * a Schwartzian transform, after Randal Schwartz. We construct a
1693 * temporary array, where each element is an array containing our
1694 * sort key along with the filename. We sort this array, and then
1695 * extract the filename from the result.
1696 *
1697 * sorted = Dir["*"].collect { |f|
1698 * [test(?M, f), f]
1699 * }.sort.collect { |f| f[1] }
1700 * sorted #=> ["mon", "tues", "wed", "thurs"]
1701 *
1702 * This is exactly what #sort_by does internally.
1703 *
1704 * sorted = Dir["*"].sort_by { |f| test(?M, f) }
1705 * sorted #=> ["mon", "tues", "wed", "thurs"]
1706 *
1707 * To produce the reverse of a specific order, the following can be used:
1708 *
1709 * ary.sort_by { ... }.reverse!
1710 */
1711
1712static VALUE
1713enum_sort_by(VALUE obj)
1714{
1715 VALUE ary, buf;
1716 struct MEMO *memo;
1717 rb_len_t i;
1718 struct sort_by_data *data;
1719
1720 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
1721
1722 if (RB_TYPE_P(obj, T_ARRAY) && RARRAY_LEN(obj) <= RB_LEN_MAX/2) {
1723 ary = rb_ary_new2(RARRAY_LEN(obj)*2);
1724 }
1725 else {
1726 ary = rb_ary_new();
1727 }
1728 RBASIC_CLEAR_CLASS(ary);
1729 buf = rb_ary_hidden_new(SORT_BY_BUFSIZE*2);
1730 rb_ary_store(buf, SORT_BY_BUFSIZE*2-1, Qnil);
1731 memo = rb_imemo_memo_new(0, 0, 0);
1732 data = (struct sort_by_data *)&memo->v1;
1733 RB_OBJ_WRITE(memo, &data->ary, ary);
1734 RB_OBJ_WRITE(memo, &data->buf, buf);
1735 data->n = 0;
1736 data->primitive_uniformed = SORT_BY_UNIFORMED((CMP_OPTIMIZABLE(FLOAT) && CMP_OPTIMIZABLE(INTEGER)),
1737 CMP_OPTIMIZABLE(FLOAT),
1738 CMP_OPTIMIZABLE(INTEGER));
1739 rb_block_call(obj, id_each, 0, 0, sort_by_i, (VALUE)memo);
1740 ary = data->ary;
1741 buf = data->buf;
1742 if (data->n) {
1743 rb_ary_resize(buf, data->n*2);
1744 rb_ary_concat(ary, buf);
1745 }
1746 if (RARRAY_LEN(ary) > 2) {
1747 if (data->primitive_uniformed) {
1748 RARRAY_PTR_USE(ary, ptr,
1749 rb_uniform_intro_sort_2((struct rb_uniform_sort_data*)ptr,
1750 (struct rb_uniform_sort_data*)(ptr + RARRAY_LEN(ary))));
1751 }
1752 else {
1753 RARRAY_PTR_USE(ary, ptr,
1754 ruby_qsort(ptr, RARRAY_LEN(ary)/2, 2*sizeof(VALUE),
1755 sort_by_cmp, (void *)ary));
1756 }
1757 }
1758 if (RBASIC(ary)->klass) {
1759 rb_raise(rb_eRuntimeError, "sort_by reentered");
1760 }
1761 for (i=1; i<RARRAY_LEN(ary); i+=2) {
1762 RARRAY_ASET(ary, i/2, RARRAY_AREF(ary, i));
1763 }
1764 rb_ary_resize(ary, RARRAY_LEN(ary)/2);
1765 RBASIC_SET_CLASS_RAW(ary, rb_cArray);
1766
1767 return ary;
1768}
1769
1770#define ENUMFUNC(name) argc ? name##_eqq : rb_block_given_p() ? name##_iter_i : name##_i
1771
1772#define ENUM_BLOCK_CALL(name) \
1773 rb_block_call2(obj, id_each, 0, 0, ENUMFUNC(name), (VALUE)memo, rb_block_given_p() && rb_block_pair_yield_optimizable() ? RB_BLOCK_NO_USE_PACKED_ARGS : 0);
1774
1775#define MEMO_ENUM_NEW(v1) (rb_check_arity(argc, 0, 1), rb_imemo_memo_new((v1), (argc ? *argv : 0), 0))
1776
1777#define DEFINE_ENUMFUNCS(name) \
1778static VALUE enum_##name##_func(VALUE result, struct MEMO *memo); \
1779\
1780static VALUE \
1781name##_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
1782{ \
1783 return enum_##name##_func(rb_enum_values_pack(argc, argv), MEMO_CAST(memo)); \
1784} \
1785\
1786static VALUE \
1787name##_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
1788{ \
1789 return enum_##name##_func(rb_yield_values2(argc, argv), MEMO_CAST(memo)); \
1790} \
1791\
1792static VALUE \
1793name##_eqq(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
1794{ \
1795 ENUM_WANT_SVALUE(); \
1796 return enum_##name##_func(rb_funcallv(MEMO_CAST(memo)->v2, id_eqq, 1, &i), MEMO_CAST(memo)); \
1797} \
1798\
1799static VALUE \
1800enum_##name##_func(VALUE result, struct MEMO *memo)
1801
1802#define WARN_UNUSED_BLOCK(argc) do { \
1803 if ((argc) > 0 && rb_block_given_p()) { \
1804 rb_warn("given block not used"); \
1805 } \
1806} while (0)
1807
1808DEFINE_ENUMFUNCS(all)
1809{
1810 if (!RTEST(result)) {
1811 MEMO_V1_SET(memo, Qfalse);
1812 rb_iter_break();
1813 }
1814 return Qnil;
1815}
1816
1817/*
1818 * call-seq:
1819 * all? -> true or false
1820 * all?(pattern) -> true or false
1821 * all? {|element| ... } -> true or false
1822 *
1823 * Returns whether every element meets a given criterion.
1824 *
1825 * If +self+ has no element, returns +true+ and argument or block
1826 * are not used.
1827 *
1828 * With no argument and no block,
1829 * returns whether every element is truthy:
1830 *
1831 * (1..4).all? # => true
1832 * %w[a b c d].all? # => true
1833 * [1, 2, nil].all? # => false
1834 * ['a','b', false].all? # => false
1835 * [].all? # => true
1836 *
1837 * With argument +pattern+ and no block,
1838 * returns whether for each element +element+,
1839 * <tt>pattern === element</tt>:
1840 *
1841 * (1..4).all?(Integer) # => true
1842 * (1..4).all?(Numeric) # => true
1843 * (1..4).all?(Float) # => false
1844 * %w[bar baz bat bam].all?(/ba/) # => true
1845 * %w[bar baz bat bam].all?(/bar/) # => false
1846 * %w[bar baz bat bam].all?('ba') # => false
1847 * {foo: 0, bar: 1, baz: 2}.all?(Array) # => true
1848 * {foo: 0, bar: 1, baz: 2}.all?(Hash) # => false
1849 * [].all?(Integer) # => true
1850 *
1851 * With a block given, returns whether the block returns a truthy value
1852 * for every element:
1853 *
1854 * (1..4).all? {|element| element < 5 } # => true
1855 * (1..4).all? {|element| element < 4 } # => false
1856 * {foo: 0, bar: 1, baz: 2}.all? {|key, value| value < 3 } # => true
1857 * {foo: 0, bar: 1, baz: 2}.all? {|key, value| value < 2 } # => false
1858 *
1859 * Related: #any?, #none? #one?.
1860 *
1861 */
1862
1863static VALUE
1864enum_all(int argc, VALUE *argv, VALUE obj)
1865{
1866 struct MEMO *memo = MEMO_ENUM_NEW(Qtrue);
1867 WARN_UNUSED_BLOCK(argc);
1868 ENUM_BLOCK_CALL(all);
1869 return memo->v1;
1870}
1871
1872DEFINE_ENUMFUNCS(any)
1873{
1874 if (RTEST(result)) {
1875 MEMO_V1_SET(memo, Qtrue);
1876 rb_iter_break();
1877 }
1878 return Qnil;
1879}
1880
1881/*
1882 * call-seq:
1883 * any? -> true or false
1884 * any?(pattern) -> true or false
1885 * any? {|element| ... } -> true or false
1886 *
1887 * Returns whether any element meets a given criterion.
1888 *
1889 * If +self+ has no element, returns +false+ and argument or block
1890 * are not used.
1891 *
1892 * With no argument and no block,
1893 * returns whether any element is truthy:
1894 *
1895 * (1..4).any? # => true
1896 * %w[a b c d].any? # => true
1897 * [1, false, nil].any? # => true
1898 * [].any? # => false
1899 *
1900 * With argument +pattern+ and no block,
1901 * returns whether for any element +element+,
1902 * <tt>pattern === element</tt>:
1903 *
1904 * [nil, false, 0].any?(Integer) # => true
1905 * [nil, false, 0].any?(Numeric) # => true
1906 * [nil, false, 0].any?(Float) # => false
1907 * %w[bar baz bat bam].any?(/m/) # => true
1908 * %w[bar baz bat bam].any?(/foo/) # => false
1909 * %w[bar baz bat bam].any?('ba') # => false
1910 * {foo: 0, bar: 1, baz: 2}.any?(Array) # => true
1911 * {foo: 0, bar: 1, baz: 2}.any?(Hash) # => false
1912 * [].any?(Integer) # => false
1913 *
1914 * With a block given, returns whether the block returns a truthy value
1915 * for any element:
1916 *
1917 * (1..4).any? {|element| element < 2 } # => true
1918 * (1..4).any? {|element| element < 1 } # => false
1919 * {foo: 0, bar: 1, baz: 2}.any? {|key, value| value < 1 } # => true
1920 * {foo: 0, bar: 1, baz: 2}.any? {|key, value| value < 0 } # => false
1921 *
1922 * Related: #all?, #none?, #one?.
1923 */
1924
1925static VALUE
1926enum_any(int argc, VALUE *argv, VALUE obj)
1927{
1928 struct MEMO *memo = MEMO_ENUM_NEW(Qfalse);
1929 WARN_UNUSED_BLOCK(argc);
1930 ENUM_BLOCK_CALL(any);
1931 return memo->v1;
1932}
1933
1934DEFINE_ENUMFUNCS(one)
1935{
1936 if (RTEST(result)) {
1937 if (UNDEF_P(memo->v1)) {
1938 MEMO_V1_SET(memo, Qtrue);
1939 }
1940 else if (memo->v1 == Qtrue) {
1941 MEMO_V1_SET(memo, Qfalse);
1942 rb_iter_break();
1943 }
1944 }
1945 return Qnil;
1946}
1947
1949 VALUE buf;
1950 VALUE limit;
1951 rb_len_t n;
1952 rb_len_t bufmax;
1953 rb_len_t curlen;
1954 int (*cmpfunc)(const void *, const void *, void *);
1955 int rev: 1; /* max if 1 */
1956 int by: 1; /* min_by if 1 */
1957};
1958
1959static VALUE
1960cmpint_reenter_check(struct nmin_data *data, VALUE val)
1961{
1962 if (RBASIC(data->buf)->klass) {
1963 rb_raise(rb_eRuntimeError, "%s%s reentered",
1964 data->rev ? "max" : "min",
1965 data->by ? "_by" : "");
1966 }
1967 return val;
1968}
1969
1970static int
1971nmin_cmp(const void *ap, const void *bp, void *_data)
1972{
1973 struct nmin_data *data = (struct nmin_data *)_data;
1974 VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
1975#define rb_cmpint(cmp, a, b) rb_cmpint(cmpint_reenter_check(data, (cmp)), a, b)
1976 return OPTIMIZED_CMP(a, b);
1977#undef rb_cmpint
1978}
1979
1980static int
1981nmin_block_cmp(const void *ap, const void *bp, void *_data)
1982{
1983 struct nmin_data *data = (struct nmin_data *)_data;
1984 VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
1985 VALUE cmp = rb_yield_values(2, a, b);
1986 cmpint_reenter_check(data, cmp);
1987 return rb_cmpint(cmp, a, b);
1988}
1989
1990static void
1991nmin_filter(struct nmin_data *data)
1992{
1993 rb_len_t n;
1994 VALUE *beg;
1995 int eltsize;
1996 rb_len_t numelts;
1997
1998 rb_len_t left, right;
1999 rb_len_t store_index;
2000
2001 rb_len_t i, j;
2002
2003 if (data->curlen <= data->n)
2004 return;
2005
2006 n = data->n;
2007 beg = RARRAY_PTR(data->buf);
2008 eltsize = data->by ? 2 : 1;
2009 numelts = data->curlen;
2010
2011 left = 0;
2012 right = numelts-1;
2013
2014#define GETPTR(i) (beg+(i)*eltsize)
2015
2016#define SWAP(i, j) do { \
2017 VALUE tmp[2]; \
2018 memcpy(tmp, GETPTR(i), sizeof(VALUE)*eltsize); \
2019 memcpy(GETPTR(i), GETPTR(j), sizeof(VALUE)*eltsize); \
2020 memcpy(GETPTR(j), tmp, sizeof(VALUE)*eltsize); \
2021} while (0)
2022
2023 while (1) {
2024 rb_len_t pivot_index = left + (right-left)/2;
2025 rb_len_t num_pivots = 1;
2026
2027 SWAP(pivot_index, right);
2028 pivot_index = right;
2029
2030 store_index = left;
2031 i = left;
2032 while (i <= right-num_pivots) {
2033 int c = data->cmpfunc(GETPTR(i), GETPTR(pivot_index), data);
2034 if (data->rev)
2035 c = -c;
2036 if (c == 0) {
2037 SWAP(i, right-num_pivots);
2038 num_pivots++;
2039 continue;
2040 }
2041 if (c < 0) {
2042 SWAP(i, store_index);
2043 store_index++;
2044 }
2045 i++;
2046 }
2047 j = store_index;
2048 for (i = right; right-num_pivots < i; i--) {
2049 if (i <= j)
2050 break;
2051 SWAP(j, i);
2052 j++;
2053 }
2054
2055 if (store_index <= n && n <= store_index+num_pivots)
2056 break;
2057
2058 if (n < store_index) {
2059 right = store_index-1;
2060 }
2061 else {
2062 left = store_index+num_pivots;
2063 }
2064 }
2065#undef GETPTR
2066#undef SWAP
2067
2068 data->limit = RARRAY_AREF(data->buf, store_index*eltsize); /* the last pivot */
2069 data->curlen = data->n;
2070 rb_ary_resize(data->buf, data->n * eltsize);
2071}
2072
2073static VALUE
2074nmin_i_ary(VALUE i, struct nmin_data *data, int argc)
2075{
2076 VALUE cmpv;
2077
2078 if (data->by)
2079 cmpv = enum_yield(argc, i);
2080 else
2081 cmpv = i;
2082
2083 if (!UNDEF_P(data->limit)) {
2084 int c = data->cmpfunc(&cmpv, &data->limit, data);
2085 if (data->rev)
2086 c = -c;
2087 if (c >= 0)
2088 return Qnil;
2089 }
2090
2091 if (data->by)
2092 rb_ary_push(data->buf, cmpv);
2093 rb_ary_push(data->buf, i);
2094
2095 data->curlen++;
2096
2097 if (data->curlen == data->bufmax) {
2098 nmin_filter(data);
2099 }
2100
2101 return Qnil;
2102}
2103
2104static VALUE
2105nmin_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, data))
2106{
2107 ENUM_WANT_SVALUE();
2108
2109 return nmin_i_ary(i, MEMO_FOR(struct nmin_data, data), argc);
2110}
2111
2112VALUE
2113rb_nmin_run(VALUE obj, VALUE num, int by, int rev, int ary)
2114{
2115 VALUE result;
2116 struct nmin_data data;
2117
2118 data.n = NUM2LEN(num);
2119 if (data.n < 0)
2120 rb_raise(rb_eArgError, "negative size (%"PRIdLEN")", data.n);
2121 if (data.n == 0)
2122 return rb_ary_new2(0);
2123 if (RB_LEN_MAX/4/(by ? 2 : 1) < data.n)
2124 rb_raise(rb_eArgError, "too big size");
2125 data.bufmax = data.n * 4;
2126 data.curlen = 0;
2127 data.buf = rb_ary_hidden_new(data.bufmax * (by ? 2 : 1));
2128 data.limit = Qundef;
2129 data.cmpfunc = by ? nmin_cmp :
2130 rb_block_given_p() ? nmin_block_cmp :
2131 nmin_cmp;
2132 data.rev = rev;
2133 data.by = by;
2134
2135 VALUE memo;
2136 struct nmin_data *m = &data;
2137 if (!ary || data.cmpfunc == nmin_block_cmp) {
2138 *(m = NEW_PARTIAL_MEMO_FOR(struct nmin_data, memo, n)) = data;
2139 }
2140 if (ary) {
2141 rb_len_t i;
2142 for (i = 0; i < RARRAY_LEN(obj); i++) {
2143 nmin_i_ary(RARRAY_AREF(obj, i), m, 1);
2144 }
2145 }
2146 else {
2147 rb_block_call(obj, id_each, 0, 0, nmin_i, memo);
2148 }
2149 if (m != &data) data = *m;
2150 RB_GC_GUARD(memo);
2151
2152 nmin_filter(&data);
2153 result = data.buf;
2154 if (by) {
2155 rb_len_t i;
2156 RARRAY_PTR_USE(result, ptr, {
2157 ruby_qsort(ptr,
2158 RARRAY_LEN(result)/2,
2159 sizeof(VALUE)*2,
2160 data.cmpfunc, (void *)&data);
2161 for (i=1; i<RARRAY_LEN(result); i+=2) {
2162 ptr[i/2] = ptr[i];
2163 }
2164 });
2165 rb_ary_resize(result, RARRAY_LEN(result)/2);
2166 }
2167 else {
2168 RARRAY_PTR_USE(result, ptr, {
2169 ruby_qsort(ptr, RARRAY_LEN(result), sizeof(VALUE),
2170 data.cmpfunc, (void *)&data);
2171 });
2172 }
2173 if (rev) {
2174 rb_ary_reverse(result);
2175 }
2176 RBASIC_SET_CLASS(result, rb_cArray);
2177 return result;
2178
2179}
2180
2181/*
2182 * call-seq:
2183 * one? -> true or false
2184 * one?(pattern) -> true or false
2185 * one? {|element| ... } -> true or false
2186 *
2187 * Returns whether exactly one element meets a given criterion.
2188 *
2189 * With no argument and no block,
2190 * returns whether exactly one element is truthy:
2191 *
2192 * (1..1).one? # => true
2193 * [1, nil, false].one? # => true
2194 * (1..4).one? # => false
2195 * {foo: 0}.one? # => true
2196 * {foo: 0, bar: 1}.one? # => false
2197 * [].one? # => false
2198 *
2199 * With argument +pattern+ and no block,
2200 * returns whether for exactly one element +element+,
2201 * <tt>pattern === element</tt>:
2202 *
2203 * [nil, false, 0].one?(Integer) # => true
2204 * [nil, false, 0].one?(Numeric) # => true
2205 * [nil, false, 0].one?(Float) # => false
2206 * %w[bar baz bat bam].one?(/m/) # => true
2207 * %w[bar baz bat bam].one?(/foo/) # => false
2208 * %w[bar baz bat bam].one?('ba') # => false
2209 * {foo: 0, bar: 1, baz: 2}.one?(Array) # => false
2210 * {foo: 0}.one?(Array) # => true
2211 * [].one?(Integer) # => false
2212 *
2213 * With a block given, returns whether the block returns a truthy value
2214 * for exactly one element:
2215 *
2216 * (1..4).one? {|element| element < 2 } # => true
2217 * (1..4).one? {|element| element < 1 } # => false
2218 * {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 1 } # => true
2219 * {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 2 } # => false
2220 *
2221 * Related: #none?, #all?, #any?.
2222 *
2223 */
2224static VALUE
2225enum_one(int argc, VALUE *argv, VALUE obj)
2226{
2227 struct MEMO *memo = MEMO_ENUM_NEW(Qundef);
2228 VALUE result;
2229
2230 WARN_UNUSED_BLOCK(argc);
2231 ENUM_BLOCK_CALL(one);
2232 result = memo->v1;
2233 if (UNDEF_P(result)) return Qfalse;
2234 return result;
2235}
2236
2237DEFINE_ENUMFUNCS(none)
2238{
2239 if (RTEST(result)) {
2240 MEMO_V1_SET(memo, Qfalse);
2241 rb_iter_break();
2242 }
2243 return Qnil;
2244}
2245
2246/*
2247 * call-seq:
2248 * none? -> true or false
2249 * none?(pattern) -> true or false
2250 * none? {|element| ... } -> true or false
2251 *
2252 * Returns whether no element meets a given criterion.
2253 *
2254 * With no argument and no block,
2255 * returns whether no element is truthy:
2256 *
2257 * (1..4).none? # => false
2258 * [nil, false].none? # => true
2259 * {foo: 0}.none? # => false
2260 * {foo: 0, bar: 1}.none? # => false
2261 * [].none? # => true
2262 *
2263 * With argument +pattern+ and no block,
2264 * returns whether for no element +element+,
2265 * <tt>pattern === element</tt>:
2266 *
2267 * [nil, false, 1.1].none?(Integer) # => true
2268 * %w[bar baz bat bam].none?(/m/) # => false
2269 * %w[bar baz bat bam].none?(/foo/) # => true
2270 * %w[bar baz bat bam].none?('ba') # => true
2271 * {foo: 0, bar: 1, baz: 2}.none?(Hash) # => true
2272 * {foo: 0}.none?(Array) # => false
2273 * [].none?(Integer) # => true
2274 *
2275 * With a block given, returns whether the block returns a truthy value
2276 * for no element:
2277 *
2278 * (1..4).none? {|element| element < 1 } # => true
2279 * (1..4).none? {|element| element < 2 } # => false
2280 * {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 0 } # => true
2281 * {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 1 } # => false
2282 *
2283 * Related: #one?, #all?, #any?.
2284 *
2285 */
2286static VALUE
2287enum_none(int argc, VALUE *argv, VALUE obj)
2288{
2289 struct MEMO *memo = MEMO_ENUM_NEW(Qtrue);
2290
2291 WARN_UNUSED_BLOCK(argc);
2292 ENUM_BLOCK_CALL(none);
2293 return memo->v1;
2294}
2295
2296struct min_t {
2297 VALUE min;
2298};
2299
2300static VALUE
2301min_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2302{
2303 struct min_t *memo = MEMO_FOR(struct min_t, args);
2304
2305 ENUM_WANT_SVALUE();
2306
2307 if (UNDEF_P(memo->min)) {
2308 memo->min = i;
2309 }
2310 else {
2311 if (OPTIMIZED_CMP(i, memo->min) < 0) {
2312 memo->min = i;
2313 }
2314 }
2315 return Qnil;
2316}
2317
2318static VALUE
2319min_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2320{
2321 VALUE cmp;
2322 struct min_t *memo = MEMO_FOR(struct min_t, args);
2323
2324 ENUM_WANT_SVALUE();
2325
2326 if (UNDEF_P(memo->min)) {
2327 memo->min = i;
2328 }
2329 else {
2330 cmp = rb_yield_values(2, i, memo->min);
2331 if (rb_cmpint(cmp, i, memo->min) < 0) {
2332 memo->min = i;
2333 }
2334 }
2335 return Qnil;
2336}
2337
2338
2339/*
2340 * call-seq:
2341 * min -> element
2342 * min(n) -> array
2343 * min {|a, b| ... } -> element
2344 * min(n) {|a, b| ... } -> array
2345 *
2346 * Returns the element with the minimum element according to a given criterion.
2347 * The ordering of equal elements is indeterminate and may be unstable.
2348 *
2349 * With no argument and no block, returns the minimum element,
2350 * using the elements' own method <tt>#<=></tt> for comparison:
2351 *
2352 * (1..4).min # => 1
2353 * (-4..-1).min # => -4
2354 * %w[d c b a].min # => "a"
2355 * {foo: 0, bar: 1, baz: 2}.min # => [:bar, 1]
2356 * [].min # => nil
2357 *
2358 * With positive integer argument +n+ given, and no block,
2359 * returns an array containing the first +n+ minimum elements that exist:
2360 *
2361 * (1..4).min(2) # => [1, 2]
2362 * (-4..-1).min(2) # => [-4, -3]
2363 * %w[d c b a].min(2) # => ["a", "b"]
2364 * {foo: 0, bar: 1, baz: 2}.min(2) # => [[:bar, 1], [:baz, 2]]
2365 * [].min(2) # => []
2366 *
2367 * With a block given, the block determines the minimum elements.
2368 * The block is called with two elements +a+ and +b+, and must return:
2369 *
2370 * - A negative integer if <tt>a < b</tt>.
2371 * - Zero if <tt>a == b</tt>.
2372 * - A positive integer if <tt>a > b</tt>.
2373 *
2374 * With a block given and no argument,
2375 * returns the minimum element as determined by the block:
2376 *
2377 * %w[xxx x xxxx xx].min {|a, b| a.size <=> b.size } # => "x"
2378 * h = {foo: 0, bar: 1, baz: 2}
2379 * h.min {|pair1, pair2| pair1[1] <=> pair2[1] } # => [:foo, 0]
2380 * [].min {|a, b| a <=> b } # => nil
2381 *
2382 * With a block given and positive integer argument +n+ given,
2383 * returns an array containing the first +n+ minimum elements that exist,
2384 * as determined by the block.
2385 *
2386 * %w[xxx x xxxx xx].min(2) {|a, b| a.size <=> b.size } # => ["x", "xx"]
2387 * h = {foo: 0, bar: 1, baz: 2}
2388 * h.min(2) {|pair1, pair2| pair1[1] <=> pair2[1] }
2389 * # => [[:foo, 0], [:bar, 1]]
2390 * [].min(2) {|a, b| a <=> b } # => []
2391 *
2392 * Related: #min_by, #minmax, #max.
2393 *
2394 */
2395
2396static VALUE
2397enum_min(int argc, VALUE *argv, VALUE obj)
2398{
2399 VALUE memo;
2400 struct min_t *m = NEW_MEMO_FOR(struct min_t, memo);
2401 VALUE result;
2402 VALUE num;
2403
2404 if (rb_check_arity(argc, 0, 1) && !NIL_P(num = argv[0]))
2405 return rb_nmin_run(obj, num, 0, 0, 0);
2406
2407 m->min = Qundef;
2408 if (rb_block_given_p()) {
2409 rb_block_call(obj, id_each, 0, 0, min_ii, memo);
2410 }
2411 else {
2412 rb_block_call(obj, id_each, 0, 0, min_i, memo);
2413 }
2414 result = m->min;
2415 if (UNDEF_P(result)) return Qnil;
2416 return result;
2417}
2418
2419struct max_t {
2420 VALUE max;
2421};
2422
2423static VALUE
2424max_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2425{
2426 struct max_t *memo = MEMO_FOR(struct max_t, args);
2427
2428 ENUM_WANT_SVALUE();
2429
2430 if (UNDEF_P(memo->max)) {
2431 memo->max = i;
2432 }
2433 else {
2434 if (OPTIMIZED_CMP(i, memo->max) > 0) {
2435 memo->max = i;
2436 }
2437 }
2438 return Qnil;
2439}
2440
2441static VALUE
2442max_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2443{
2444 struct max_t *memo = MEMO_FOR(struct max_t, args);
2445 VALUE cmp;
2446
2447 ENUM_WANT_SVALUE();
2448
2449 if (UNDEF_P(memo->max)) {
2450 memo->max = i;
2451 }
2452 else {
2453 cmp = rb_yield_values(2, i, memo->max);
2454 if (rb_cmpint(cmp, i, memo->max) > 0) {
2455 memo->max = i;
2456 }
2457 }
2458 return Qnil;
2459}
2460
2461/*
2462 * call-seq:
2463 * max -> element
2464 * max(n) -> array
2465 * max {|a, b| ... } -> element
2466 * max(n) {|a, b| ... } -> array
2467 *
2468 * Returns the element with the maximum element according to a given criterion.
2469 * The ordering of equal elements is indeterminate and may be unstable.
2470 *
2471 * With no argument and no block, returns the maximum element,
2472 * using the elements' own method <tt>#<=></tt> for comparison:
2473 *
2474 * (1..4).max # => 4
2475 * (-4..-1).max # => -1
2476 * %w[d c b a].max # => "d"
2477 * {foo: 0, bar: 1, baz: 2}.max # => [:foo, 0]
2478 * [].max # => nil
2479 *
2480 * With positive integer argument +n+ given, and no block,
2481 * returns an array containing the first +n+ maximum elements that exist:
2482 *
2483 * (1..4).max(2) # => [4, 3]
2484 * (-4..-1).max(2) # => [-1, -2]
2485 * %w[d c b a].max(2) # => ["d", "c"]
2486 * {foo: 0, bar: 1, baz: 2}.max(2) # => [[:foo, 0], [:baz, 2]]
2487 * [].max(2) # => []
2488 *
2489 * With a block given, the block determines the maximum elements.
2490 * The block is called with two elements +a+ and +b+, and must return:
2491 *
2492 * - A negative integer if <tt>a < b</tt>.
2493 * - Zero if <tt>a == b</tt>.
2494 * - A positive integer if <tt>a > b</tt>.
2495 *
2496 * With a block given and no argument,
2497 * returns the maximum element as determined by the block:
2498 *
2499 * %w[xxx x xxxx xx].max {|a, b| a.size <=> b.size } # => "xxxx"
2500 * h = {foo: 0, bar: 1, baz: 2}
2501 * h.max {|pair1, pair2| pair1[1] <=> pair2[1] } # => [:baz, 2]
2502 * [].max {|a, b| a <=> b } # => nil
2503 *
2504 * With a block given and positive integer argument +n+ given,
2505 * returns an array containing the first +n+ maximum elements that exist,
2506 * as determined by the block.
2507 *
2508 * %w[xxx x xxxx xx].max(2) {|a, b| a.size <=> b.size } # => ["xxxx", "xxx"]
2509 * h = {foo: 0, bar: 1, baz: 2}
2510 * h.max(2) {|pair1, pair2| pair1[1] <=> pair2[1] }
2511 * # => [[:baz, 2], [:bar, 1]]
2512 * [].max(2) {|a, b| a <=> b } # => []
2513 *
2514 * Related: #min, #minmax, #max_by.
2515 *
2516 */
2517
2518static VALUE
2519enum_max(int argc, VALUE *argv, VALUE obj)
2520{
2521 VALUE memo;
2522 struct max_t *m = NEW_MEMO_FOR(struct max_t, memo);
2523 VALUE result;
2524 VALUE num;
2525
2526 if (rb_check_arity(argc, 0, 1) && !NIL_P(num = argv[0]))
2527 return rb_nmin_run(obj, num, 0, 1, 0);
2528
2529 m->max = Qundef;
2530 if (rb_block_given_p()) {
2531 rb_block_call(obj, id_each, 0, 0, max_ii, (VALUE)memo);
2532 }
2533 else {
2534 rb_block_call(obj, id_each, 0, 0, max_i, (VALUE)memo);
2535 }
2536 result = m->max;
2537 if (UNDEF_P(result)) return Qnil;
2538 return result;
2539}
2540
2541struct minmax_t {
2542 VALUE min;
2543 VALUE max;
2544 VALUE last;
2545};
2546
2547static void
2548minmax_i_update(VALUE i, VALUE j, struct minmax_t *memo)
2549{
2550 int n;
2551
2552 if (UNDEF_P(memo->min)) {
2553 memo->min = i;
2554 memo->max = j;
2555 }
2556 else {
2557 n = OPTIMIZED_CMP(i, memo->min);
2558 if (n < 0) {
2559 memo->min = i;
2560 }
2561 n = OPTIMIZED_CMP(j, memo->max);
2562 if (n > 0) {
2563 memo->max = j;
2564 }
2565 }
2566}
2567
2568static VALUE
2569minmax_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
2570{
2571 struct minmax_t *memo = MEMO_FOR(struct minmax_t, _memo);
2572 int n;
2573 VALUE j;
2574
2575 ENUM_WANT_SVALUE();
2576
2577 if (UNDEF_P(memo->last)) {
2578 memo->last = i;
2579 return Qnil;
2580 }
2581 j = memo->last;
2582 memo->last = Qundef;
2583
2584 n = OPTIMIZED_CMP(j, i);
2585 if (n == 0)
2586 i = j;
2587 else if (n < 0) {
2588 VALUE tmp;
2589 tmp = i;
2590 i = j;
2591 j = tmp;
2592 }
2593
2594 minmax_i_update(i, j, memo);
2595
2596 return Qnil;
2597}
2598
2599static void
2600minmax_ii_update(VALUE i, VALUE j, struct minmax_t *memo)
2601{
2602 int n;
2603
2604 if (UNDEF_P(memo->min)) {
2605 memo->min = i;
2606 memo->max = j;
2607 }
2608 else {
2609 n = rb_cmpint(rb_yield_values(2, i, memo->min), i, memo->min);
2610 if (n < 0) {
2611 memo->min = i;
2612 }
2613 n = rb_cmpint(rb_yield_values(2, j, memo->max), j, memo->max);
2614 if (n > 0) {
2615 memo->max = j;
2616 }
2617 }
2618}
2619
2620static VALUE
2621minmax_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
2622{
2623 struct minmax_t *memo = MEMO_FOR(struct minmax_t, _memo);
2624 int n;
2625 VALUE j;
2626
2627 ENUM_WANT_SVALUE();
2628
2629 if (UNDEF_P(memo->last)) {
2630 memo->last = i;
2631 return Qnil;
2632 }
2633 j = memo->last;
2634 memo->last = Qundef;
2635
2636 n = rb_cmpint(rb_yield_values(2, j, i), j, i);
2637 if (n == 0)
2638 i = j;
2639 else if (n < 0) {
2640 VALUE tmp;
2641 tmp = i;
2642 i = j;
2643 j = tmp;
2644 }
2645
2646 minmax_ii_update(i, j, memo);
2647
2648 return Qnil;
2649}
2650
2651/*
2652 * call-seq:
2653 * minmax -> [minimum, maximum]
2654 * minmax {|a, b| ... } -> [minimum, maximum]
2655 *
2656 * Returns a 2-element array containing the minimum and maximum elements
2657 * according to a given criterion.
2658 * The ordering of equal elements is indeterminate and may be unstable.
2659 *
2660 * With no argument and no block, returns the minimum and maximum elements,
2661 * using the elements' own method <tt>#<=></tt> for comparison:
2662 *
2663 * (1..4).minmax # => [1, 4]
2664 * (-4..-1).minmax # => [-4, -1]
2665 * %w[d c b a].minmax # => ["a", "d"]
2666 * {foo: 0, bar: 1, baz: 2}.minmax # => [[:bar, 1], [:foo, 0]]
2667 * [].minmax # => [nil, nil]
2668 *
2669 * With a block given, returns the minimum and maximum elements
2670 * as determined by the block:
2671 *
2672 * %w[xxx x xxxx xx].minmax {|a, b| a.size <=> b.size } # => ["x", "xxxx"]
2673 * h = {foo: 0, bar: 1, baz: 2}
2674 * h.minmax {|pair1, pair2| pair1[1] <=> pair2[1] }
2675 * # => [[:foo, 0], [:baz, 2]]
2676 * [].minmax {|a, b| a <=> b } # => [nil, nil]
2677 *
2678 * Related: #min, #max, #minmax_by.
2679 *
2680 */
2681
2682static VALUE
2683enum_minmax(VALUE obj)
2684{
2685 VALUE memo;
2686 struct minmax_t *m = NEW_MEMO_FOR(struct minmax_t, memo);
2687
2688 m->min = Qundef;
2689 m->last = Qundef;
2690 if (rb_block_given_p()) {
2691 rb_block_call(obj, id_each, 0, 0, minmax_ii, memo);
2692 if (!UNDEF_P(m->last))
2693 minmax_ii_update(m->last, m->last, m);
2694 }
2695 else {
2696 rb_block_call(obj, id_each, 0, 0, minmax_i, memo);
2697 if (!UNDEF_P(m->last))
2698 minmax_i_update(m->last, m->last, m);
2699 }
2700 if (!UNDEF_P(m->min)) {
2701 return rb_assoc_new(m->min, m->max);
2702 }
2703 return rb_assoc_new(Qnil, Qnil);
2704}
2705
2706static VALUE
2707min_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2708{
2709 struct MEMO *memo = MEMO_CAST(args);
2710 VALUE v;
2711
2712 ENUM_WANT_SVALUE();
2713
2714 v = enum_yield(argc, i);
2715 if (UNDEF_P(memo->v1)) {
2716 MEMO_V1_SET(memo, v);
2717 MEMO_V2_SET(memo, i);
2718 }
2719 else if (OPTIMIZED_CMP(v, memo->v1) < 0) {
2720 MEMO_V1_SET(memo, v);
2721 MEMO_V2_SET(memo, i);
2722 }
2723 return Qnil;
2724}
2725
2726/*
2727 * call-seq:
2728 * min_by {|element| ... } -> element
2729 * min_by(n) {|element| ... } -> array
2730 * min_by -> enumerator
2731 * min_by(n) -> enumerator
2732 *
2733 * Returns the elements for which the block returns the minimum values.
2734 *
2735 * With a block given and no argument,
2736 * returns the element for which the block returns the minimum value:
2737 *
2738 * (1..4).min_by {|element| -element } # => 4
2739 * %w[a b c d].min_by {|element| -element.ord } # => "d"
2740 * {foo: 0, bar: 1, baz: 2}.min_by {|key, value| -value } # => [:baz, 2]
2741 * [].min_by {|element| -element } # => nil
2742 *
2743 * With a block given and positive integer argument +n+ given,
2744 * returns an array containing the +n+ elements
2745 * for which the block returns minimum values:
2746 *
2747 * (1..4).min_by(2) {|element| -element }
2748 * # => [4, 3]
2749 * %w[a b c d].min_by(2) {|element| -element.ord }
2750 * # => ["d", "c"]
2751 * {foo: 0, bar: 1, baz: 2}.min_by(2) {|key, value| -value }
2752 * # => [[:baz, 2], [:bar, 1]]
2753 * [].min_by(2) {|element| -element }
2754 * # => []
2755 *
2756 * Returns an Enumerator if no block is given.
2757 *
2758 * Related: #min, #minmax, #max_by.
2759 *
2760 */
2761
2762static VALUE
2763enum_min_by(int argc, VALUE *argv, VALUE obj)
2764{
2765 struct MEMO *memo;
2766 VALUE num;
2767
2768 rb_check_arity(argc, 0, 1);
2769
2770 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
2771
2772 if (argc && !NIL_P(num = argv[0]))
2773 return rb_nmin_run(obj, num, 1, 0, 0);
2774
2775 memo = rb_imemo_memo_new(Qundef, Qnil, 0);
2776 rb_block_call(obj, id_each, 0, 0, min_by_i, (VALUE)memo);
2777 return memo->v2;
2778}
2779
2780static VALUE
2781max_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2782{
2783 struct MEMO *memo = MEMO_CAST(args);
2784 VALUE v;
2785
2786 ENUM_WANT_SVALUE();
2787
2788 v = enum_yield(argc, i);
2789 if (UNDEF_P(memo->v1)) {
2790 MEMO_V1_SET(memo, v);
2791 MEMO_V2_SET(memo, i);
2792 }
2793 else if (OPTIMIZED_CMP(v, memo->v1) > 0) {
2794 MEMO_V1_SET(memo, v);
2795 MEMO_V2_SET(memo, i);
2796 }
2797 return Qnil;
2798}
2799
2800/*
2801 * call-seq:
2802 * max_by {|element| ... } -> element
2803 * max_by(n) {|element| ... } -> array
2804 * max_by -> enumerator
2805 * max_by(n) -> enumerator
2806 *
2807 * Returns the elements for which the block returns the maximum values.
2808 *
2809 * With a block given and no argument,
2810 * returns the element for which the block returns the maximum value:
2811 *
2812 * (1..4).max_by {|element| -element } # => 1
2813 * %w[a b c d].max_by {|element| -element.ord } # => "a"
2814 * {foo: 0, bar: 1, baz: 2}.max_by {|key, value| -value } # => [:foo, 0]
2815 * [].max_by {|element| -element } # => nil
2816 *
2817 * With a block given and positive integer argument +n+ given,
2818 * returns an array containing the +n+ elements
2819 * for which the block returns maximum values:
2820 *
2821 * (1..4).max_by(2) {|element| -element }
2822 * # => [1, 2]
2823 * %w[a b c d].max_by(2) {|element| -element.ord }
2824 * # => ["a", "b"]
2825 * {foo: 0, bar: 1, baz: 2}.max_by(2) {|key, value| -value }
2826 * # => [[:foo, 0], [:bar, 1]]
2827 * [].max_by(2) {|element| -element }
2828 * # => []
2829 *
2830 * Returns an Enumerator if no block is given.
2831 *
2832 * Related: #max, #minmax, #min_by.
2833 *
2834 */
2835
2836static VALUE
2837enum_max_by(int argc, VALUE *argv, VALUE obj)
2838{
2839 struct MEMO *memo;
2840 VALUE num;
2841
2842 rb_check_arity(argc, 0, 1);
2843
2844 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
2845
2846 if (argc && !NIL_P(num = argv[0]))
2847 return rb_nmin_run(obj, num, 1, 1, 0);
2848
2849 memo = rb_imemo_memo_new(Qundef, Qnil, 0);
2850 rb_block_call(obj, id_each, 0, 0, max_by_i, (VALUE)memo);
2851 return memo->v2;
2852}
2853
2855 VALUE min_bv;
2856 VALUE max_bv;
2857 VALUE min;
2858 VALUE max;
2859 VALUE last_bv;
2860 VALUE last;
2861};
2862
2863static void
2864minmax_by_i_update(VALUE v1, VALUE v2, VALUE i1, VALUE i2, struct minmax_by_t *memo)
2865{
2866 if (UNDEF_P(memo->min_bv)) {
2867 memo->min_bv = v1;
2868 memo->max_bv = v2;
2869 memo->min = i1;
2870 memo->max = i2;
2871 }
2872 else {
2873 if (OPTIMIZED_CMP(v1, memo->min_bv) < 0) {
2874 memo->min_bv = v1;
2875 memo->min = i1;
2876 }
2877 if (OPTIMIZED_CMP(v2, memo->max_bv) > 0) {
2878 memo->max_bv = v2;
2879 memo->max = i2;
2880 }
2881 }
2882}
2883
2884static VALUE
2885minmax_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
2886{
2887 struct minmax_by_t *memo = MEMO_FOR(struct minmax_by_t, _memo);
2888 VALUE vi, vj, j;
2889 int n;
2890
2891 ENUM_WANT_SVALUE();
2892
2893 vi = enum_yield(argc, i);
2894
2895 if (UNDEF_P(memo->last_bv)) {
2896 memo->last_bv = vi;
2897 memo->last = i;
2898 return Qnil;
2899 }
2900 vj = memo->last_bv;
2901 j = memo->last;
2902 memo->last_bv = Qundef;
2903
2904 n = OPTIMIZED_CMP(vj, vi);
2905 if (n == 0) {
2906 i = j;
2907 vi = vj;
2908 }
2909 else if (n < 0) {
2910 VALUE tmp;
2911 tmp = i;
2912 i = j;
2913 j = tmp;
2914 tmp = vi;
2915 vi = vj;
2916 vj = tmp;
2917 }
2918
2919 minmax_by_i_update(vi, vj, i, j, memo);
2920
2921 return Qnil;
2922}
2923
2924/*
2925 * call-seq:
2926 * minmax_by {|element| ... } -> [minimum, maximum]
2927 * minmax_by -> enumerator
2928 *
2929 * Returns a 2-element array containing the elements
2930 * for which the block returns minimum and maximum values:
2931 *
2932 * (1..4).minmax_by {|element| -element }
2933 * # => [4, 1]
2934 * %w[a b c d].minmax_by {|element| -element.ord }
2935 * # => ["d", "a"]
2936 * {foo: 0, bar: 1, baz: 2}.minmax_by {|key, value| -value }
2937 * # => [[:baz, 2], [:foo, 0]]
2938 * [].minmax_by {|element| -element }
2939 * # => [nil, nil]
2940 *
2941 * Returns an Enumerator if no block is given.
2942 *
2943 * Related: #max_by, #minmax, #min_by.
2944 *
2945 */
2946
2947static VALUE
2948enum_minmax_by(VALUE obj)
2949{
2950 VALUE memo;
2951 struct minmax_by_t *m = NEW_MEMO_FOR(struct minmax_by_t, memo);
2952
2953 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
2954
2955 m->min_bv = Qundef;
2956 m->max_bv = Qundef;
2957 m->min = Qnil;
2958 m->max = Qnil;
2959 m->last_bv = Qundef;
2960 m->last = Qundef;
2961 rb_block_call(obj, id_each, 0, 0, minmax_by_i, memo);
2962 if (!UNDEF_P(m->last_bv))
2963 minmax_by_i_update(m->last_bv, m->last_bv, m->last, m->last, m);
2964 m = MEMO_FOR(struct minmax_by_t, memo);
2965 return rb_assoc_new(m->min, m->max);
2966}
2967
2968static VALUE
2969member_i(RB_BLOCK_CALL_FUNC_ARGLIST(iter, args))
2970{
2971 struct MEMO *memo = MEMO_CAST(args);
2972
2973 if (rb_equal(rb_enum_values_pack(argc, argv), memo->v1)) {
2974 MEMO_V2_SET(memo, Qtrue);
2975 rb_iter_break();
2976 }
2977 return Qnil;
2978}
2979
2980/*
2981 * call-seq:
2982 * include?(object) -> true or false
2983 *
2984 * Returns whether for any element <tt>object == element</tt>:
2985 *
2986 * (1..4).include?(2) # => true
2987 * (1..4).include?(5) # => false
2988 * (1..4).include?('2') # => false
2989 * %w[a b c d].include?('b') # => true
2990 * %w[a b c d].include?('2') # => false
2991 * {foo: 0, bar: 1, baz: 2}.include?(:foo) # => true
2992 * {foo: 0, bar: 1, baz: 2}.include?('foo') # => false
2993 * {foo: 0, bar: 1, baz: 2}.include?(0) # => false
2994 *
2995 */
2996
2997static VALUE
2998enum_member(VALUE obj, VALUE val)
2999{
3000 struct MEMO *memo = rb_imemo_memo_new(val, Qfalse, 0);
3001
3002 rb_block_call(obj, id_each, 0, 0, member_i, (VALUE)memo);
3003 return memo->v2;
3004}
3005
3006static VALUE
3007each_with_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(_, index))
3008{
3009 struct vm_ifunc *ifunc = rb_current_ifunc();
3010 ifunc->data = (const void *)rb_int_succ(index);
3011
3012 return rb_yield_values(2, rb_enum_values_pack(argc, argv), index);
3013}
3014
3015/*
3016 * call-seq:
3017 * each_with_index(*args) {|element, i| ..... } -> self
3018 * each_with_index(*args) -> enumerator
3019 *
3020 * Invoke <tt>self.each</tt> with <tt>*args</tt>.
3021 * With a block given, the block receives each element and its index;
3022 * returns +self+:
3023 *
3024 * h = {}
3025 * (1..4).each_with_index {|element, i| h[element] = i } # => 1..4
3026 * h # => {1=>0, 2=>1, 3=>2, 4=>3}
3027 *
3028 * h = {}
3029 * %w[a b c d].each_with_index {|element, i| h[element] = i }
3030 * # => ["a", "b", "c", "d"]
3031 * h # => {"a"=>0, "b"=>1, "c"=>2, "d"=>3}
3032 *
3033 * a = []
3034 * h = {foo: 0, bar: 1, baz: 2}
3035 * h.each_with_index {|element, i| a.push([i, element]) }
3036 * # => {:foo=>0, :bar=>1, :baz=>2}
3037 * a # => [[0, [:foo, 0]], [1, [:bar, 1]], [2, [:baz, 2]]]
3038 *
3039 * With no block given, returns an Enumerator.
3040 *
3041 */
3042
3043static VALUE
3044enum_each_with_index(int argc, VALUE *argv, VALUE obj)
3045{
3046 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
3047
3048 rb_block_call(obj, id_each, argc, argv, each_with_index_i, INT2FIX(0));
3049 return obj;
3050}
3051
3052
3053/*
3054 * call-seq:
3055 * reverse_each(*args) {|element| ... } -> self
3056 * reverse_each(*args) -> enumerator
3057 *
3058 * With a block given, calls the block with each element,
3059 * but in reverse order; returns +self+:
3060 *
3061 * a = []
3062 * (1..4).reverse_each {|element| a.push(-element) } # => 1..4
3063 * a # => [-4, -3, -2, -1]
3064 *
3065 * a = []
3066 * %w[a b c d].reverse_each {|element| a.push(element) }
3067 * # => ["a", "b", "c", "d"]
3068 * a # => ["d", "c", "b", "a"]
3069 *
3070 * a = []
3071 * h.reverse_each {|element| a.push(element) }
3072 * # => {:foo=>0, :bar=>1, :baz=>2}
3073 * a # => [[:baz, 2], [:bar, 1], [:foo, 0]]
3074 *
3075 * With no block given, returns an Enumerator.
3076 *
3077 */
3078
3079static VALUE
3080enum_reverse_each(int argc, VALUE *argv, VALUE obj)
3081{
3082 VALUE ary;
3083 rb_len_t len;
3084
3085 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
3086
3087 ary = enum_to_a(argc, argv, obj);
3088
3089 len = RARRAY_LEN(ary);
3090 while (len--) {
3091 rb_len_t nlen;
3092 rb_yield(RARRAY_AREF(ary, len));
3093 nlen = RARRAY_LEN(ary);
3094 if (nlen < len) {
3095 len = nlen;
3096 }
3097 }
3098
3099 return obj;
3100}
3101
3102
3103static VALUE
3104each_val_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
3105{
3106 ENUM_WANT_SVALUE();
3107 enum_yield(argc, i);
3108 return Qnil;
3109}
3110
3111/*
3112 * call-seq:
3113 * each_entry(*args) {|element| ... } -> self
3114 * each_entry(*args) -> enumerator
3115 *
3116 * Calls the given block with each element,
3117 * converting multiple values from yield to an array; returns +self+:
3118 *
3119 * a = []
3120 * (1..4).each_entry {|element| a.push(element) } # => 1..4
3121 * a # => [1, 2, 3, 4]
3122 *
3123 * a = []
3124 * h = {foo: 0, bar: 1, baz:2}
3125 * h.each_entry {|element| a.push(element) }
3126 * # => {:foo=>0, :bar=>1, :baz=>2}
3127 * a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3128 *
3129 * class Foo
3130 * include Enumerable
3131 * def each
3132 * yield 1
3133 * yield 1, 2
3134 * yield
3135 * end
3136 * end
3137 * Foo.new.each_entry {|yielded| p yielded }
3138 *
3139 * Output:
3140 *
3141 * 1
3142 * [1, 2]
3143 * nil
3144 *
3145 * With no block given, returns an Enumerator.
3146 *
3147 */
3148
3149static VALUE
3150enum_each_entry(int argc, VALUE *argv, VALUE obj)
3151{
3152 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
3153 rb_block_call(obj, id_each, argc, argv, each_val_i, 0);
3154 return obj;
3155}
3156
3157static VALUE
3158add_int(VALUE x, rb_len_t n)
3159{
3160 const VALUE y = LEN2NUM(n);
3161 if (RB_INTEGER_TYPE_P(x)) return rb_int_plus(x, y);
3162 return rb_funcallv(x, '+', 1, &y);
3163}
3164
3165static VALUE
3166div_int(VALUE x, rb_len_t n)
3167{
3168 const VALUE y = LEN2NUM(n);
3169 if (RB_INTEGER_TYPE_P(x)) return rb_int_idiv(x, y);
3170 return rb_funcallv(x, id_div, 1, &y);
3171}
3172
3173#define dont_recycle_block_arg(arity) ((arity) == 1 || (arity) < 0)
3174
3175static VALUE
3176each_slice_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, m))
3177{
3178 struct MEMO *memo = MEMO_CAST(m);
3179 VALUE ary = memo->v1;
3180 VALUE v = Qnil;
3181 rb_len_t size = memo->u3.cnt;
3182 ENUM_WANT_SVALUE();
3183
3184 rb_ary_push(ary, i);
3185
3186 if (RARRAY_LEN(ary) == size) {
3187 v = rb_yield(ary);
3188
3189 if (memo->v2) {
3190 MEMO_V1_SET(memo, rb_ary_new2(size));
3191 }
3192 else {
3193 rb_ary_clear(ary);
3194 }
3195 }
3196
3197 return v;
3198}
3199
3200static VALUE
3201enum_each_slice_size(VALUE obj, VALUE args, VALUE eobj)
3202{
3203 VALUE n, size;
3204 rb_len_t slice_size = NUM2LEN(RARRAY_AREF(args, 0));
3205 ID infinite_p;
3206 CONST_ID(infinite_p, "infinite?");
3207 if (slice_size <= 0) rb_raise(rb_eArgError, "invalid slice size");
3208
3209 size = enum_size(obj, 0, 0);
3210 if (NIL_P(size)) return Qnil;
3211 if (RB_FLOAT_TYPE_P(size) && RTEST(rb_funcall(size, infinite_p, 0))) {
3212 return size;
3213 }
3214
3215 n = add_int(size, slice_size-1);
3216 return div_int(n, slice_size);
3217}
3218
3219/*
3220 * call-seq:
3221 * each_slice(n) { ... } -> self
3222 * each_slice(n) -> enumerator
3223 *
3224 * Calls the block with each successive disjoint +n+-tuple of elements;
3225 * returns +self+:
3226 *
3227 * a = []
3228 * (1..10).each_slice(3) {|tuple| a.push(tuple) }
3229 * a # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
3230 *
3231 * a = []
3232 * h = {foo: 0, bar: 1, baz: 2, bat: 3, bam: 4}
3233 * h.each_slice(2) {|tuple| a.push(tuple) }
3234 * a # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]], [[:bam, 4]]]
3235 *
3236 * With no block given, returns an Enumerator.
3237 *
3238 */
3239static VALUE
3240enum_each_slice(VALUE obj, VALUE n)
3241{
3242 rb_len_t size = NUM2LEN(n);
3243 VALUE ary;
3244 struct MEMO *memo;
3245 int arity;
3246
3247 if (size <= 0) rb_raise(rb_eArgError, "invalid slice size");
3248 RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_slice_size);
3249 size = limit_by_enum_size(obj, size);
3250 ary = rb_ary_new2(size);
3251 arity = rb_block_arity();
3252 memo = rb_imemo_memo_new(ary, dont_recycle_block_arg(arity), size);
3253 rb_block_call(obj, id_each, 0, 0, each_slice_i, (VALUE)memo);
3254 ary = memo->v1;
3255 if (RARRAY_LEN(ary) > 0) rb_yield(ary);
3256
3257 return obj;
3258}
3259
3260static VALUE
3261each_cons_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3262{
3263 struct MEMO *memo = MEMO_CAST(args);
3264 VALUE ary = memo->v1;
3265 VALUE v = Qnil;
3266 rb_len_t size = memo->u3.cnt;
3267 ENUM_WANT_SVALUE();
3268
3269 if (RARRAY_LEN(ary) == size) {
3270 rb_ary_shift(ary);
3271 }
3272 rb_ary_push(ary, i);
3273 if (RARRAY_LEN(ary) == size) {
3274 if (memo->v2) {
3275 ary = rb_ary_dup(ary);
3276 }
3277 v = rb_yield(ary);
3278 }
3279 return v;
3280}
3281
3282static VALUE
3283enum_each_cons_size(VALUE obj, VALUE args, VALUE eobj)
3284{
3285 const VALUE zero = LONG2FIX(0);
3286 VALUE n, size;
3287 rb_len_t cons_size = NUM2LEN(RARRAY_AREF(args, 0));
3288 if (cons_size <= 0) rb_raise(rb_eArgError, "invalid size");
3289
3290 size = enum_size(obj, 0, 0);
3291 if (NIL_P(size)) return Qnil;
3292
3293 n = add_int(size, 1 - cons_size);
3294 return (OPTIMIZED_CMP(n, zero) == -1) ? zero : n;
3295}
3296
3297/*
3298 * call-seq:
3299 * each_cons(n) { ... } -> self
3300 * each_cons(n) -> enumerator
3301 *
3302 * Calls the block with each successive overlapped +n+-tuple of elements;
3303 * returns +self+:
3304 *
3305 * a = []
3306 * (1..5).each_cons(3) {|element| a.push(element) }
3307 * a # => [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
3308 *
3309 * a = []
3310 * h = {foo: 0, bar: 1, baz: 2, bam: 3}
3311 * h.each_cons(2) {|element| a.push(element) }
3312 * a # => [[[:foo, 0], [:bar, 1]], [[:bar, 1], [:baz, 2]], [[:baz, 2], [:bam, 3]]]
3313 *
3314 * With no block given, returns an Enumerator.
3315 *
3316 */
3317static VALUE
3318enum_each_cons(VALUE obj, VALUE n)
3319{
3320 rb_len_t size = NUM2LEN(n);
3321 struct MEMO *memo;
3322 int arity;
3323
3324 if (size <= 0) rb_raise(rb_eArgError, "invalid size");
3325 RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_cons_size);
3326 arity = rb_block_arity();
3327 if (enum_size_over_p(obj, size)) return obj;
3328 memo = rb_imemo_memo_new(rb_ary_new2(size), dont_recycle_block_arg(arity), size);
3329 rb_block_call(obj, id_each, 0, 0, each_cons_i, (VALUE)memo);
3330
3331 return obj;
3332}
3333
3334static VALUE
3335each_with_object_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo))
3336{
3337 ENUM_WANT_SVALUE();
3338 return rb_yield_values(2, i, memo);
3339}
3340
3341/*
3342 * call-seq:
3343 * each_with_object(object) { |(*args), memo_object| ... } -> object
3344 * each_with_object(object) -> enumerator
3345 *
3346 * Calls the block once for each element, passing both the element
3347 * and the given object:
3348 *
3349 * (1..4).each_with_object([]) {|i, a| a.push(i**2) }
3350 * # => [1, 4, 9, 16]
3351 *
3352 * {foo: 0, bar: 1, baz: 2}.each_with_object({}) {|(k, v), h| h[v] = k }
3353 * # => {0=>:foo, 1=>:bar, 2=>:baz}
3354 *
3355 * With no block given, returns an Enumerator.
3356 *
3357 */
3358static VALUE
3359enum_each_with_object(VALUE obj, VALUE memo)
3360{
3361 RETURN_SIZED_ENUMERATOR(obj, 1, &memo, enum_size);
3362
3363 rb_block_call(obj, id_each, 0, 0, each_with_object_i, memo);
3364
3365 return memo;
3366}
3367
3368static VALUE
3369zip_ary(RB_BLOCK_CALL_FUNC_ARGLIST(val, memoval))
3370{
3371 struct MEMO *memo = (struct MEMO *)memoval;
3372 VALUE result = memo->v1;
3373 VALUE args = memo->v2;
3374 rb_len_t n = memo->u3.cnt++;
3375 VALUE tmp;
3376 int i;
3377
3378 tmp = rb_ary_new2(RARRAY_LEN(args) + 1);
3379 rb_ary_store(tmp, 0, rb_enum_values_pack(argc, argv));
3380 for (i=0; i<RARRAY_LEN(args); i++) {
3381 VALUE e = RARRAY_AREF(args, i);
3382
3383 if (RARRAY_LEN(e) <= n) {
3384 rb_ary_push(tmp, Qnil);
3385 }
3386 else {
3387 rb_ary_push(tmp, RARRAY_AREF(e, n));
3388 }
3389 }
3390 if (NIL_P(result)) {
3391 enum_yield_array(tmp);
3392 }
3393 else {
3394 rb_ary_push(result, tmp);
3395 }
3396
3397 RB_GC_GUARD(args);
3398
3399 return Qnil;
3400}
3401
3402static VALUE
3403call_next(VALUE w)
3404{
3405 VALUE *v = (VALUE *)w;
3406 return v[0] = rb_funcallv(v[1], id_next, 0, 0);
3407}
3408
3409static VALUE
3410call_stop(VALUE w, VALUE _)
3411{
3412 VALUE *v = (VALUE *)w;
3413 return v[0] = Qundef;
3414}
3415
3416static VALUE
3417zip_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, memoval))
3418{
3419 struct MEMO *memo = (struct MEMO *)memoval;
3420 VALUE result = memo->v1;
3421 VALUE args = memo->v2;
3422 VALUE tmp;
3423 int i;
3424
3425 tmp = rb_ary_new2(RARRAY_LEN(args) + 1);
3426 rb_ary_store(tmp, 0, rb_enum_values_pack(argc, argv));
3427 for (i=0; i<RARRAY_LEN(args); i++) {
3428 if (NIL_P(RARRAY_AREF(args, i))) {
3429 rb_ary_push(tmp, Qnil);
3430 }
3431 else {
3432 VALUE v[2];
3433
3434 v[1] = RARRAY_AREF(args, i);
3435 rb_rescue2(call_next, (VALUE)v, call_stop, (VALUE)v, rb_eStopIteration, (VALUE)0);
3436 if (UNDEF_P(v[0])) {
3437 RARRAY_ASET(args, i, Qnil);
3438 v[0] = Qnil;
3439 }
3440 rb_ary_push(tmp, v[0]);
3441 }
3442 }
3443 if (NIL_P(result)) {
3444 enum_yield_array(tmp);
3445 }
3446 else {
3447 rb_ary_push(result, tmp);
3448 }
3449
3450 RB_GC_GUARD(args);
3451
3452 return Qnil;
3453}
3454
3455/*
3456 * call-seq:
3457 * zip(*other_enums) -> array
3458 * zip(*other_enums) {|array| ... } -> nil
3459 *
3460 * With no block given, returns a new array +new_array+ of size self.size
3461 * whose elements are arrays.
3462 * Each nested array <tt>new_array[n]</tt>
3463 * is of size <tt>other_enums.size+1</tt>, and contains:
3464 *
3465 * - The +n+-th element of self.
3466 * - The +n+-th element of each of the +other_enums+.
3467 *
3468 * If all +other_enums+ and self are the same size,
3469 * all elements are included in the result, and there is no +nil+-filling:
3470 *
3471 * a = [:a0, :a1, :a2, :a3]
3472 * b = [:b0, :b1, :b2, :b3]
3473 * c = [:c0, :c1, :c2, :c3]
3474 * d = a.zip(b, c)
3475 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
3476 *
3477 * f = {foo: 0, bar: 1, baz: 2}
3478 * g = {goo: 3, gar: 4, gaz: 5}
3479 * h = {hoo: 6, har: 7, haz: 8}
3480 * d = f.zip(g, h)
3481 * d # => [
3482 * # [[:foo, 0], [:goo, 3], [:hoo, 6]],
3483 * # [[:bar, 1], [:gar, 4], [:har, 7]],
3484 * # [[:baz, 2], [:gaz, 5], [:haz, 8]]
3485 * # ]
3486 *
3487 * If any enumerable in other_enums is smaller than self,
3488 * fills to <tt>self.size</tt> with +nil+:
3489 *
3490 * a = [:a0, :a1, :a2, :a3]
3491 * b = [:b0, :b1, :b2]
3492 * c = [:c0, :c1]
3493 * d = a.zip(b, c)
3494 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, nil], [:a3, nil, nil]]
3495 *
3496 * If any enumerable in other_enums is larger than self,
3497 * its trailing elements are ignored:
3498 *
3499 * a = [:a0, :a1, :a2, :a3]
3500 * b = [:b0, :b1, :b2, :b3, :b4]
3501 * c = [:c0, :c1, :c2, :c3, :c4, :c5]
3502 * d = a.zip(b, c)
3503 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
3504 *
3505 * When a block is given, calls the block with each of the sub-arrays
3506 * (formed as above); returns nil:
3507 *
3508 * a = [:a0, :a1, :a2, :a3]
3509 * b = [:b0, :b1, :b2, :b3]
3510 * c = [:c0, :c1, :c2, :c3]
3511 * a.zip(b, c) {|sub_array| p sub_array} # => nil
3512 *
3513 * Output:
3514 *
3515 * [:a0, :b0, :c0]
3516 * [:a1, :b1, :c1]
3517 * [:a2, :b2, :c2]
3518 * [:a3, :b3, :c3]
3519 *
3520 */
3521
3522static VALUE
3523enum_zip(int argc, VALUE *argv, VALUE obj)
3524{
3525 int i;
3526 ID conv;
3527 struct MEMO *memo;
3528 VALUE result = Qnil;
3529 VALUE args = rb_ary_new4(argc, argv);
3530 int allary = TRUE;
3531
3532 argv = RARRAY_PTR(args);
3533 for (i=0; i<argc; i++) {
3534 VALUE ary = rb_check_array_type(argv[i]);
3535 if (NIL_P(ary)) {
3536 allary = FALSE;
3537 break;
3538 }
3539 argv[i] = ary;
3540 }
3541 if (!allary) {
3542 static const VALUE sym_each = STATIC_ID2SYM(id_each);
3543 CONST_ID(conv, "to_enum");
3544 for (i=0; i<argc; i++) {
3545 if (!rb_respond_to(argv[i], id_each)) {
3546 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (must respond to :each)",
3547 rb_obj_class(argv[i]));
3548 }
3549 argv[i] = rb_funcallv(argv[i], conv, 1, &sym_each);
3550 }
3551 }
3552 if (!rb_block_given_p()) {
3553 result = rb_ary_new();
3554 }
3555
3556 /* TODO: use NODE_DOT2 as memo(v, v, -) */
3557 memo = rb_imemo_memo_new(result, args, 0);
3558 rb_block_call(obj, id_each, 0, 0, allary ? zip_ary : zip_i, (VALUE)memo);
3559
3560 return result;
3561}
3562
3563static VALUE
3564take_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3565{
3566 struct MEMO *memo = MEMO_CAST(args);
3567 rb_ary_push(memo->v1, rb_enum_values_pack(argc, argv));
3568 if (--memo->u3.cnt == 0) rb_iter_break();
3569 return Qnil;
3570}
3571
3572/*
3573 * call-seq:
3574 * take(n) -> array
3575 *
3576 * For non-negative integer +n+, returns the first +n+ elements:
3577 *
3578 * r = (1..4)
3579 * r.take(2) # => [1, 2]
3580 * r.take(0) # => []
3581 *
3582 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
3583 * h.take(2) # => [[:foo, 0], [:bar, 1]]
3584 *
3585 */
3586
3587static VALUE
3588enum_take(VALUE obj, VALUE n)
3589{
3590 struct MEMO *memo;
3591 VALUE result;
3592 rb_len_t len = NUM2LEN(n);
3593
3594 if (len < 0) {
3595 rb_raise(rb_eArgError, "attempt to take negative size");
3596 }
3597
3598 if (len == 0) return rb_ary_new2(0);
3599 result = rb_ary_new2(len);
3600 memo = rb_imemo_memo_new(result, 0, len);
3601 rb_block_call(obj, id_each, 0, 0, take_i, (VALUE)memo);
3602 return result;
3603}
3604
3605
3606static VALUE
3607take_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
3608{
3609 if (!RTEST(rb_yield_values2(argc, argv))) rb_iter_break();
3610 rb_ary_push(ary, rb_enum_values_pack(argc, argv));
3611 return Qnil;
3612}
3613
3614/*
3615 * call-seq:
3616 * take_while {|element| ... } -> array
3617 * take_while -> enumerator
3618 *
3619 * Calls the block with successive elements as long as the block
3620 * returns a truthy value;
3621 * returns an array of all elements up to that point:
3622 *
3623 *
3624 * (1..4).take_while{|i| i < 3 } # => [1, 2]
3625 * h = {foo: 0, bar: 1, baz: 2}
3626 * h.take_while{|element| key, value = *element; value < 2 }
3627 * # => [[:foo, 0], [:bar, 1]]
3628 *
3629 * With no block given, returns an Enumerator.
3630 *
3631 */
3632
3633static VALUE
3634enum_take_while(VALUE obj)
3635{
3636 VALUE ary;
3637
3638 RETURN_ENUMERATOR(obj, 0, 0);
3639 ary = rb_ary_new();
3640 rb_block_call(obj, id_each, 0, 0, take_while_i, ary);
3641 return ary;
3642}
3643
3644static VALUE
3645drop_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3646{
3647 struct MEMO *memo = MEMO_CAST(args);
3648 if (memo->u3.cnt == 0) {
3649 rb_ary_push(memo->v1, rb_enum_values_pack(argc, argv));
3650 }
3651 else {
3652 memo->u3.cnt--;
3653 }
3654 return Qnil;
3655}
3656
3657/*
3658 * call-seq:
3659 * drop(n) -> array
3660 *
3661 * For positive integer +n+, returns an array containing
3662 * all but the first +n+ elements:
3663 *
3664 * r = (1..4)
3665 * r.drop(3) # => [4]
3666 * r.drop(2) # => [3, 4]
3667 * r.drop(1) # => [2, 3, 4]
3668 * r.drop(0) # => [1, 2, 3, 4]
3669 * r.drop(50) # => []
3670 *
3671 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
3672 * h.drop(2) # => [[:baz, 2], [:bat, 3]]
3673 *
3674 */
3675
3676static VALUE
3677enum_drop(VALUE obj, VALUE n)
3678{
3679 VALUE result;
3680 struct MEMO *memo;
3681 rb_len_t len = NUM2LEN(n);
3682
3683 if (len < 0) {
3684 rb_raise(rb_eArgError, "attempt to drop negative size");
3685 }
3686
3687 result = rb_ary_new();
3688 memo = rb_imemo_memo_new(result, 0, len);
3689 rb_block_call(obj, id_each, 0, 0, drop_i, (VALUE)memo);
3690 return result;
3691}
3692
3693
3694static VALUE
3695drop_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3696{
3697 struct MEMO *memo = MEMO_CAST(args);
3698 ENUM_WANT_SVALUE();
3699
3700 if (!memo->u3.state && !RTEST(enum_yield(argc, i))) {
3701 memo->u3.state = TRUE;
3702 }
3703 if (memo->u3.state) {
3704 rb_ary_push(memo->v1, i);
3705 }
3706 return Qnil;
3707}
3708
3709/*
3710 * call-seq:
3711 * drop_while {|element| ... } -> array
3712 * drop_while -> enumerator
3713 *
3714 * Calls the block with successive elements as long as the block
3715 * returns a truthy value;
3716 * returns an array of all elements after that point:
3717 *
3718 *
3719 * (1..4).drop_while{|i| i < 3 } # => [3, 4]
3720 * h = {foo: 0, bar: 1, baz: 2}
3721 * a = h.drop_while{|element| key, value = *element; value < 2 }
3722 * a # => [[:baz, 2]]
3723 *
3724 * With no block given, returns an Enumerator.
3725 *
3726 * e = (1..4).drop_while
3727 * p e #=> #<Enumerator: 1..4:drop_while>
3728 * i = e.next; p i; e.feed(i < 3) #=> 1
3729 * i = e.next; p i; e.feed(i < 3) #=> 2
3730 * i = e.next; p i; e.feed(i < 3) #=> 3
3731 * begin
3732 * e.next
3733 * rescue StopIteration
3734 * p $!.result #=> [3, 4]
3735 * end
3736 *
3737 */
3738
3739static VALUE
3740enum_drop_while(VALUE obj)
3741{
3742 VALUE result;
3743 struct MEMO *memo;
3744
3745 RETURN_ENUMERATOR(obj, 0, 0);
3746 result = rb_ary_new();
3747 memo = rb_imemo_memo_new(result, 0, FALSE);
3748 rb_block_call(obj, id_each, 0, 0, drop_while_i, (VALUE)memo);
3749 return result;
3750}
3751
3752static VALUE
3753cycle_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
3754{
3755 ENUM_WANT_SVALUE();
3756
3757 rb_ary_push(ary, argc > 1 ? i : rb_ary_new_from_values(argc, argv));
3758 enum_yield(argc, i);
3759 return Qnil;
3760}
3761
3762static VALUE
3763enum_cycle_size(VALUE self, VALUE args, VALUE eobj)
3764{
3765 rb_len_t mul = 0;
3766 VALUE n = Qnil;
3767 VALUE size;
3768
3769 if (args && (RARRAY_LEN(args) > 0)) {
3770 n = RARRAY_AREF(args, 0);
3771 if (!NIL_P(n)) mul = NUM2LEN(n);
3772 }
3773
3774 size = enum_size(self, args, 0);
3775 if (NIL_P(size) || FIXNUM_ZERO_P(size)) return size;
3776
3777 if (NIL_P(n)) return DBL2NUM(HUGE_VAL);
3778 if (mul <= 0) return INT2FIX(0);
3779 n = LEN2NUM(mul);
3780 return rb_funcallv(size, '*', 1, &n);
3781}
3782
3783/*
3784 * call-seq:
3785 * cycle(n = nil) {|element| ...} -> nil
3786 * cycle(n = nil) -> enumerator
3787 *
3788 * When called with positive integer argument +n+ and a block,
3789 * calls the block with each element, then does so again,
3790 * until it has done so +n+ times; returns +nil+:
3791 *
3792 * a = []
3793 * (1..4).cycle(3) {|element| a.push(element) } # => nil
3794 * a # => [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
3795 * a = []
3796 * ('a'..'d').cycle(2) {|element| a.push(element) }
3797 * a # => ["a", "b", "c", "d", "a", "b", "c", "d"]
3798 * a = []
3799 * {foo: 0, bar: 1, baz: 2}.cycle(2) {|element| a.push(element) }
3800 * a # => [[:foo, 0], [:bar, 1], [:baz, 2], [:foo, 0], [:bar, 1], [:baz, 2]]
3801 *
3802 * If count is zero or negative, does not call the block.
3803 *
3804 * When called with a block and +n+ is +nil+, cycles forever.
3805 *
3806 * When no block is given, returns an Enumerator.
3807 *
3808 */
3809
3810static VALUE
3811enum_cycle(int argc, VALUE *argv, VALUE obj)
3812{
3813 VALUE ary;
3814 VALUE nv = Qnil;
3815 rb_len_t n;
3816 rb_len_t i, len;
3817
3818 rb_check_arity(argc, 0, 1);
3819
3820 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_cycle_size);
3821 if (!argc || NIL_P(nv = argv[0])) {
3822 n = -1;
3823 }
3824 else {
3825 n = NUM2LEN(nv);
3826 if (n <= 0) return Qnil;
3827 }
3828 ary = rb_ary_new();
3829 RBASIC_CLEAR_CLASS(ary);
3830 rb_block_call(obj, id_each, 0, 0, cycle_i, ary);
3831 len = RARRAY_LEN(ary);
3832 if (len == 0) return Qnil;
3833 while (n < 0 || 0 < --n) {
3834 for (i=0; i<len; i++) {
3835 enum_yield_array(RARRAY_AREF(ary, i));
3836 }
3837 }
3838 return Qnil;
3839}
3840
3842 VALUE categorize;
3843 VALUE prev_value;
3844 VALUE prev_elts;
3845 VALUE yielder;
3846};
3847
3848static VALUE
3849chunk_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
3850{
3851 struct chunk_arg *argp = MEMO_FOR(struct chunk_arg, _argp);
3852 VALUE v, s;
3853 VALUE alone = ID2SYM(id__alone);
3854 VALUE separator = ID2SYM(id__separator);
3855
3856 ENUM_WANT_SVALUE();
3857
3858 v = rb_funcallv(argp->categorize, id_call, 1, &i);
3859
3860 if (v == alone) {
3861 if (!NIL_P(argp->prev_value)) {
3862 s = rb_assoc_new(argp->prev_value, argp->prev_elts);
3863 rb_funcallv(argp->yielder, id_lshift, 1, &s);
3864 argp->prev_value = argp->prev_elts = Qnil;
3865 }
3866 v = rb_assoc_new(v, rb_ary_new3(1, i));
3867 rb_funcallv(argp->yielder, id_lshift, 1, &v);
3868 }
3869 else if (NIL_P(v) || v == separator) {
3870 if (!NIL_P(argp->prev_value)) {
3871 v = rb_assoc_new(argp->prev_value, argp->prev_elts);
3872 rb_funcallv(argp->yielder, id_lshift, 1, &v);
3873 argp->prev_value = argp->prev_elts = Qnil;
3874 }
3875 }
3876 else if (SYMBOL_P(v) && (s = rb_sym2str(v), RSTRING_PTR(s)[0] == '_')) {
3877 rb_raise(rb_eRuntimeError, "symbols beginning with an underscore are reserved");
3878 }
3879 else {
3880 if (NIL_P(argp->prev_value)) {
3881 argp->prev_value = v;
3882 argp->prev_elts = rb_ary_new3(1, i);
3883 }
3884 else {
3885 if (rb_equal(argp->prev_value, v)) {
3886 rb_ary_push(argp->prev_elts, i);
3887 }
3888 else {
3889 s = rb_assoc_new(argp->prev_value, argp->prev_elts);
3890 rb_funcallv(argp->yielder, id_lshift, 1, &s);
3891 argp->prev_value = v;
3892 argp->prev_elts = rb_ary_new3(1, i);
3893 }
3894 }
3895 }
3896 return Qnil;
3897}
3898
3899static VALUE
3901{
3902 VALUE enumerable;
3903 VALUE arg;
3904 struct chunk_arg *memo = NEW_MEMO_FOR(struct chunk_arg, arg);
3905
3906 enumerable = rb_ivar_get(enumerator, id_chunk_enumerable);
3907 memo->categorize = rb_ivar_get(enumerator, id_chunk_categorize);
3908 memo->prev_value = Qnil;
3909 memo->prev_elts = Qnil;
3910 memo->yielder = yielder;
3911
3912 rb_block_call(enumerable, id_each, 0, 0, chunk_ii, arg);
3913 memo = MEMO_FOR(struct chunk_arg, arg);
3914 if (!NIL_P(memo->prev_elts)) {
3915 arg = rb_assoc_new(memo->prev_value, memo->prev_elts);
3916 rb_funcallv(memo->yielder, id_lshift, 1, &arg);
3917 }
3918 return Qnil;
3919}
3920
3921/*
3922 * call-seq:
3923 * chunk {|array| ... } -> enumerator
3924 *
3925 * Each element in the returned enumerator is a 2-element array consisting of:
3926 *
3927 * - A value returned by the block.
3928 * - An array ("chunk") containing the element for which that value was returned,
3929 * and all following elements for which the block returned the same value:
3930 *
3931 * So that:
3932 *
3933 * - Each block return value that is different from its predecessor
3934 * begins a new chunk.
3935 * - Each block return value that is the same as its predecessor
3936 * continues the same chunk.
3937 *
3938 * Example:
3939 *
3940 * e = (0..10).chunk {|i| (i / 3).floor } # => #<Enumerator: ...>
3941 * # The enumerator elements.
3942 * e.next # => [0, [0, 1, 2]]
3943 * e.next # => [1, [3, 4, 5]]
3944 * e.next # => [2, [6, 7, 8]]
3945 * e.next # => [3, [9, 10]]
3946 *
3947 * Method +chunk+ is especially useful for an enumerable that is already sorted.
3948 * This example counts words for each initial letter in a large array of words:
3949 *
3950 * # Get sorted words from a web page.
3951 * url = 'https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt'
3952 * words = URI::open(url).readlines
3953 * # Make chunks, one for each letter.
3954 * e = words.chunk {|word| word.upcase[0] } # => #<Enumerator: ...>
3955 * # Display 'A' through 'F'.
3956 * e.each {|c, words| p [c, words.length]; break if c == 'F' }
3957 *
3958 * Output:
3959 *
3960 * ["A", 17096]
3961 * ["B", 11070]
3962 * ["C", 19901]
3963 * ["D", 10896]
3964 * ["E", 8736]
3965 * ["F", 6860]
3966 *
3967 * You can use the special symbol <tt>:_alone</tt> to force an element
3968 * into its own separate chunk:
3969 *
3970 * a = [0, 0, 1, 1]
3971 * e = a.chunk{|i| i.even? ? :_alone : true }
3972 * e.to_a # => [[:_alone, [0]], [:_alone, [0]], [true, [1, 1]]]
3973 *
3974 * For example, you can put each line that contains a URL into its own chunk:
3975 *
3976 * pattern = /http/
3977 * open(filename) { |f|
3978 * f.chunk { |line| line =~ pattern ? :_alone : true }.each { |key, lines|
3979 * pp lines
3980 * }
3981 * }
3982 *
3983 * You can use the special symbol <tt>:_separator</tt> or +nil+
3984 * to force an element to be ignored (not included in any chunk):
3985 *
3986 * a = [0, 0, -1, 1, 1]
3987 * e = a.chunk{|i| i < 0 ? :_separator : true }
3988 * e.to_a # => [[true, [0, 0]], [true, [1, 1]]]
3989 *
3990 * Note that the separator does end the chunk:
3991 *
3992 * a = [0, 0, -1, 1, -1, 1]
3993 * e = a.chunk{|i| i < 0 ? :_separator : true }
3994 * e.to_a # => [[true, [0, 0]], [true, [1]], [true, [1]]]
3995 *
3996 * For example, the sequence of hyphens in svn log can be eliminated as follows:
3997 *
3998 * sep = "-"*72 + "\n"
3999 * IO.popen("svn log README") { |f|
4000 * f.chunk { |line|
4001 * line != sep || nil
4002 * }.each { |_, lines|
4003 * pp lines
4004 * }
4005 * }
4006 * #=> ["r20018 | knu | 2008-10-29 13:20:42 +0900 (Wed, 29 Oct 2008) | 2 lines\n",
4007 * # "\n",
4008 * # "* README, README.ja: Update the portability section.\n",
4009 * # "\n"]
4010 * # ["r16725 | knu | 2008-05-31 23:34:23 +0900 (Sat, 31 May 2008) | 2 lines\n",
4011 * # "\n",
4012 * # "* README, README.ja: Add a note about default C flags.\n",
4013 * # "\n"]
4014 * # ...
4015 *
4016 * Paragraphs separated by empty lines can be parsed as follows:
4017 *
4018 * File.foreach("README").chunk { |line|
4019 * /\A\s*\z/ !~ line || nil
4020 * }.each { |_, lines|
4021 * pp lines
4022 * }
4023 *
4024 */
4025static VALUE
4026enum_chunk(VALUE enumerable)
4027{
4029
4030 RETURN_SIZED_ENUMERATOR(enumerable, 0, 0, enum_size);
4031
4033 rb_ivar_set(enumerator, id_chunk_enumerable, enumerable);
4034 rb_ivar_set(enumerator, id_chunk_categorize, rb_block_proc());
4035 rb_block_call(enumerator, idInitialize, 0, 0, chunk_i, enumerator);
4036 return enumerator;
4037}
4038
4039
4041 VALUE sep_pred;
4042 VALUE sep_pat;
4043 VALUE prev_elts;
4044 VALUE yielder;
4045};
4046
4047static VALUE
4048slicebefore_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
4049{
4050 struct slicebefore_arg *argp = MEMO_FOR(struct slicebefore_arg, _argp);
4051 VALUE header_p;
4052
4053 ENUM_WANT_SVALUE();
4054
4055 if (!NIL_P(argp->sep_pat))
4056 header_p = rb_funcallv(argp->sep_pat, id_eqq, 1, &i);
4057 else
4058 header_p = rb_funcallv(argp->sep_pred, id_call, 1, &i);
4059 if (RTEST(header_p)) {
4060 if (!NIL_P(argp->prev_elts))
4061 rb_funcallv(argp->yielder, id_lshift, 1, &argp->prev_elts);
4062 argp->prev_elts = rb_ary_new3(1, i);
4063 }
4064 else {
4065 if (NIL_P(argp->prev_elts))
4066 argp->prev_elts = rb_ary_new3(1, i);
4067 else
4068 rb_ary_push(argp->prev_elts, i);
4069 }
4070
4071 return Qnil;
4072}
4073
4074static VALUE
4076{
4077 VALUE enumerable;
4078 VALUE arg;
4079 struct slicebefore_arg *memo = NEW_MEMO_FOR(struct slicebefore_arg, arg);
4080
4081 enumerable = rb_ivar_get(enumerator, id_slicebefore_enumerable);
4082 memo->sep_pred = rb_attr_get(enumerator, id_slicebefore_sep_pred);
4083 memo->sep_pat = NIL_P(memo->sep_pred) ? rb_ivar_get(enumerator, id_slicebefore_sep_pat) : Qnil;
4084 memo->prev_elts = Qnil;
4085 memo->yielder = yielder;
4086
4087 rb_block_call(enumerable, id_each, 0, 0, slicebefore_ii, arg);
4088 memo = MEMO_FOR(struct slicebefore_arg, arg);
4089 if (!NIL_P(memo->prev_elts))
4090 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4091 return Qnil;
4092}
4093
4094/*
4095 * call-seq:
4096 * slice_before(pattern) -> enumerator
4097 * slice_before {|elt| ... } -> enumerator
4098 *
4099 * With argument +pattern+, returns an enumerator that uses the pattern
4100 * to partition elements into arrays ("slices").
4101 * An element begins a new slice if <tt>element === pattern</tt>
4102 * (or if it is the first element).
4103 *
4104 * a = %w[foo bar fop for baz fob fog bam foy]
4105 * e = a.slice_before(/ba/) # => #<Enumerator: ...>
4106 * e.each {|array| p array }
4107 *
4108 * Output:
4109 *
4110 * ["foo"]
4111 * ["bar", "fop", "for"]
4112 * ["baz", "fob", "fog"]
4113 * ["bam", "foy"]
4114 *
4115 * With a block, returns an enumerator that uses the block
4116 * to partition elements into arrays.
4117 * An element begins a new slice if its block return is a truthy value
4118 * (or if it is the first element):
4119 *
4120 * e = (1..20).slice_before {|i| i % 4 == 2 } # => #<Enumerator: ...>
4121 * e.each {|array| p array }
4122 *
4123 * Output:
4124 *
4125 * [1]
4126 * [2, 3, 4, 5]
4127 * [6, 7, 8, 9]
4128 * [10, 11, 12, 13]
4129 * [14, 15, 16, 17]
4130 * [18, 19, 20]
4131 *
4132 * Other methods of the Enumerator class and Enumerable module,
4133 * such as +to_a+, +map+, etc., are also usable.
4134 *
4135 * For example, iteration over ChangeLog entries can be implemented as
4136 * follows:
4137 *
4138 * # iterate over ChangeLog entries.
4139 * open("ChangeLog") { |f|
4140 * f.slice_before(/\A\S/).each { |e| pp e }
4141 * }
4142 *
4143 * # same as above. block is used instead of pattern argument.
4144 * open("ChangeLog") { |f|
4145 * f.slice_before { |line| /\A\S/ === line }.each { |e| pp e }
4146 * }
4147 *
4148 * "svn proplist -R" produces multiline output for each file.
4149 * They can be chunked as follows:
4150 *
4151 * IO.popen([{"LC_ALL"=>"C"}, "svn", "proplist", "-R"]) { |f|
4152 * f.lines.slice_before(/\AProp/).each { |lines| p lines }
4153 * }
4154 * #=> ["Properties on '.':\n", " svn:ignore\n", " svk:merge\n"]
4155 * # ["Properties on 'goruby.c':\n", " svn:eol-style\n"]
4156 * # ["Properties on 'complex.c':\n", " svn:mime-type\n", " svn:eol-style\n"]
4157 * # ["Properties on 'regparse.c':\n", " svn:eol-style\n"]
4158 * # ...
4159 *
4160 * If the block needs to maintain state over multiple elements,
4161 * local variables can be used.
4162 * For example, three or more consecutive increasing numbers can be squashed
4163 * as follows (see +chunk_while+ for a better way):
4164 *
4165 * a = [0, 2, 3, 4, 6, 7, 9]
4166 * prev = a[0]
4167 * p a.slice_before { |e|
4168 * prev, prev2 = e, prev
4169 * prev2 + 1 != e
4170 * }.map { |es|
4171 * es.length <= 2 ? es.join(",") : "#{es.first}-#{es.last}"
4172 * }.join(",")
4173 * #=> "0,2-4,6,7,9"
4174 *
4175 * However local variables should be used carefully
4176 * if the result enumerator is enumerated twice or more.
4177 * The local variables should be initialized for each enumeration.
4178 * Enumerator.new can be used to do it.
4179 *
4180 * # Word wrapping. This assumes all characters have same width.
4181 * def wordwrap(words, maxwidth)
4182 * Enumerator.new {|y|
4183 * # cols is initialized in Enumerator.new.
4184 * cols = 0
4185 * words.slice_before { |w|
4186 * cols += 1 if cols != 0
4187 * cols += w.length
4188 * if maxwidth < cols
4189 * cols = w.length
4190 * true
4191 * else
4192 * false
4193 * end
4194 * }.each {|ws| y.yield ws }
4195 * }
4196 * end
4197 * text = (1..20).to_a.join(" ")
4198 * enum = wordwrap(text.split(/\s+/), 10)
4199 * puts "-"*10
4200 * enum.each { |ws| puts ws.join(" ") } # first enumeration.
4201 * puts "-"*10
4202 * enum.each { |ws| puts ws.join(" ") } # second enumeration generates same result as the first.
4203 * puts "-"*10
4204 * #=> ----------
4205 * # 1 2 3 4 5
4206 * # 6 7 8 9 10
4207 * # 11 12 13
4208 * # 14 15 16
4209 * # 17 18 19
4210 * # 20
4211 * # ----------
4212 * # 1 2 3 4 5
4213 * # 6 7 8 9 10
4214 * # 11 12 13
4215 * # 14 15 16
4216 * # 17 18 19
4217 * # 20
4218 * # ----------
4219 *
4220 * mbox contains series of mails which start with Unix From line.
4221 * So each mail can be extracted by slice before Unix From line.
4222 *
4223 * # parse mbox
4224 * open("mbox") { |f|
4225 * f.slice_before { |line|
4226 * line.start_with? "From "
4227 * }.each { |mail|
4228 * unix_from = mail.shift
4229 * i = mail.index("\n")
4230 * header = mail[0...i]
4231 * body = mail[(i+1)..-1]
4232 * body.pop if body.last == "\n"
4233 * fields = header.slice_before { |line| !" \t".include?(line[0]) }.to_a
4234 * p unix_from
4235 * pp fields
4236 * pp body
4237 * }
4238 * }
4239 *
4240 * # split mails in mbox (slice before Unix From line after an empty line)
4241 * open("mbox") { |f|
4242 * emp = true
4243 * f.slice_before { |line|
4244 * prevemp = emp
4245 * emp = line == "\n"
4246 * prevemp && line.start_with?("From ")
4247 * }.each { |mail|
4248 * mail.pop if mail.last == "\n"
4249 * pp mail
4250 * }
4251 * }
4252 *
4253 */
4254static VALUE
4255enum_slice_before(int argc, VALUE *argv, VALUE enumerable)
4256{
4258
4259 if (rb_block_given_p()) {
4260 if (argc != 0)
4261 rb_error_arity(argc, 0, 0);
4263 rb_ivar_set(enumerator, id_slicebefore_sep_pred, rb_block_proc());
4264 }
4265 else {
4266 VALUE sep_pat;
4267 rb_scan_args(argc, argv, "1", &sep_pat);
4269 rb_ivar_set(enumerator, id_slicebefore_sep_pat, sep_pat);
4270 }
4271 rb_ivar_set(enumerator, id_slicebefore_enumerable, enumerable);
4272 rb_block_call(enumerator, idInitialize, 0, 0, slicebefore_i, enumerator);
4273 return enumerator;
4274}
4275
4276
4278 VALUE pat;
4279 VALUE pred;
4280 VALUE prev_elts;
4281 VALUE yielder;
4282};
4283
4284static VALUE
4285sliceafter_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
4286{
4287#define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct sliceafter_arg, _memo)))
4288 struct sliceafter_arg *memo;
4289 int split_p;
4290 UPDATE_MEMO;
4291
4292 ENUM_WANT_SVALUE();
4293
4294 if (NIL_P(memo->prev_elts)) {
4295 memo->prev_elts = rb_ary_new3(1, i);
4296 }
4297 else {
4298 rb_ary_push(memo->prev_elts, i);
4299 }
4300
4301 if (NIL_P(memo->pred)) {
4302 split_p = RTEST(rb_funcallv(memo->pat, id_eqq, 1, &i));
4303 UPDATE_MEMO;
4304 }
4305 else {
4306 split_p = RTEST(rb_funcallv(memo->pred, id_call, 1, &i));
4307 UPDATE_MEMO;
4308 }
4309
4310 if (split_p) {
4311 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4312 UPDATE_MEMO;
4313 memo->prev_elts = Qnil;
4314 }
4315
4316 return Qnil;
4317#undef UPDATE_MEMO
4318}
4319
4320static VALUE
4322{
4323 VALUE enumerable;
4324 VALUE arg;
4325 struct sliceafter_arg *memo = NEW_MEMO_FOR(struct sliceafter_arg, arg);
4326
4327 enumerable = rb_ivar_get(enumerator, id_sliceafter_enum);
4328 memo->pat = rb_ivar_get(enumerator, id_sliceafter_pat);
4329 memo->pred = rb_attr_get(enumerator, id_sliceafter_pred);
4330 memo->prev_elts = Qnil;
4331 memo->yielder = yielder;
4332
4333 rb_block_call(enumerable, id_each, 0, 0, sliceafter_ii, arg);
4334 memo = MEMO_FOR(struct sliceafter_arg, arg);
4335 if (!NIL_P(memo->prev_elts))
4336 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4337 return Qnil;
4338}
4339
4340/*
4341 * call-seq:
4342 * enum.slice_after(pattern) -> an_enumerator
4343 * enum.slice_after { |elt| bool } -> an_enumerator
4344 *
4345 * Creates an enumerator for each chunked elements.
4346 * The ends of chunks are defined by _pattern_ and the block.
4347 *
4348 * If <code>_pattern_ === _elt_</code> returns <code>true</code> or the block
4349 * returns <code>true</code> for the element, the element is end of a
4350 * chunk.
4351 *
4352 * The <code>===</code> and _block_ is called from the first element to the last
4353 * element of _enum_.
4354 *
4355 * The result enumerator yields the chunked elements as an array.
4356 * So +each+ method can be called as follows:
4357 *
4358 * enum.slice_after(pattern).each { |ary| ... }
4359 * enum.slice_after { |elt| bool }.each { |ary| ... }
4360 *
4361 * Other methods of the Enumerator class and Enumerable module,
4362 * such as +map+, etc., are also usable.
4363 *
4364 * For example, continuation lines (lines end with backslash) can be
4365 * concatenated as follows:
4366 *
4367 * lines = ["foo\n", "bar\\\n", "baz\n", "\n", "qux\n"]
4368 * e = lines.slice_after(/(?<!\\‍)\n\z/)
4369 * p e.to_a
4370 * #=> [["foo\n"], ["bar\\\n", "baz\n"], ["\n"], ["qux\n"]]
4371 * p e.map {|ll| ll[0...-1].map {|l| l.sub(/\\\n\z/, "") }.join + ll.last }
4372 * #=>["foo\n", "barbaz\n", "\n", "qux\n"]
4373 *
4374 */
4375
4376static VALUE
4377enum_slice_after(int argc, VALUE *argv, VALUE enumerable)
4378{
4380 VALUE pat = Qnil, pred = Qnil;
4381
4382 if (rb_block_given_p()) {
4383 if (0 < argc)
4384 rb_raise(rb_eArgError, "both pattern and block are given");
4385 pred = rb_block_proc();
4386 }
4387 else {
4388 rb_scan_args(argc, argv, "1", &pat);
4389 }
4390
4392 rb_ivar_set(enumerator, id_sliceafter_enum, enumerable);
4393 rb_ivar_set(enumerator, id_sliceafter_pat, pat);
4394 rb_ivar_set(enumerator, id_sliceafter_pred, pred);
4395
4396 rb_block_call(enumerator, idInitialize, 0, 0, sliceafter_i, enumerator);
4397 return enumerator;
4398}
4399
4401 VALUE pred;
4402 VALUE prev_elt;
4403 VALUE prev_elts;
4404 VALUE yielder;
4405 int inverted; /* 0 for slice_when and 1 for chunk_while. */
4406};
4407
4408static VALUE
4409slicewhen_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
4410{
4411#define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct slicewhen_arg, _memo)))
4412 struct slicewhen_arg *memo;
4413 int split_p;
4414 UPDATE_MEMO;
4415
4416 ENUM_WANT_SVALUE();
4417
4418 if (UNDEF_P(memo->prev_elt)) {
4419 /* The first element */
4420 memo->prev_elt = i;
4421 memo->prev_elts = rb_ary_new3(1, i);
4422 }
4423 else {
4424 VALUE args[2];
4425 args[0] = memo->prev_elt;
4426 args[1] = i;
4427 split_p = RTEST(rb_funcallv(memo->pred, id_call, 2, args));
4428 UPDATE_MEMO;
4429
4430 if (memo->inverted)
4431 split_p = !split_p;
4432
4433 if (split_p) {
4434 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4435 UPDATE_MEMO;
4436 memo->prev_elts = rb_ary_new3(1, i);
4437 }
4438 else {
4439 rb_ary_push(memo->prev_elts, i);
4440 }
4441
4442 memo->prev_elt = i;
4443 }
4444
4445 return Qnil;
4446#undef UPDATE_MEMO
4447}
4448
4449static VALUE
4451{
4452 VALUE enumerable;
4453 VALUE arg;
4454 struct slicewhen_arg *memo =
4455 NEW_PARTIAL_MEMO_FOR(struct slicewhen_arg, arg, inverted);
4456
4457 enumerable = rb_ivar_get(enumerator, id_slicewhen_enum);
4458 memo->pred = rb_attr_get(enumerator, id_slicewhen_pred);
4459 memo->prev_elt = Qundef;
4460 memo->prev_elts = Qnil;
4461 memo->yielder = yielder;
4462 memo->inverted = RTEST(rb_attr_get(enumerator, id_slicewhen_inverted));
4463
4464 rb_block_call(enumerable, id_each, 0, 0, slicewhen_ii, arg);
4465 memo = MEMO_FOR(struct slicewhen_arg, arg);
4466 if (!NIL_P(memo->prev_elts))
4467 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4468 return Qnil;
4469}
4470
4471/*
4472 * call-seq:
4473 * enum.slice_when {|elt_before, elt_after| bool } -> an_enumerator
4474 *
4475 * Creates an enumerator for each chunked elements.
4476 * The beginnings of chunks are defined by the block.
4477 *
4478 * This method splits each chunk using adjacent elements,
4479 * _elt_before_ and _elt_after_,
4480 * in the receiver enumerator.
4481 * This method split chunks between _elt_before_ and _elt_after_ where
4482 * the block returns <code>true</code>.
4483 *
4484 * The block is called the length of the receiver enumerator minus one.
4485 *
4486 * The result enumerator yields the chunked elements as an array.
4487 * So +each+ method can be called as follows:
4488 *
4489 * enum.slice_when { |elt_before, elt_after| bool }.each { |ary| ... }
4490 *
4491 * Other methods of the Enumerator class and Enumerable module,
4492 * such as +to_a+, +map+, etc., are also usable.
4493 *
4494 * For example, one-by-one increasing subsequence can be chunked as follows:
4495 *
4496 * a = [1,2,4,9,10,11,12,15,16,19,20,21]
4497 * b = a.slice_when {|i, j| i+1 != j }
4498 * p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
4499 * c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
4500 * p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
4501 * d = c.join(",")
4502 * p d #=> "1,2,4,9-12,15,16,19-21"
4503 *
4504 * Near elements (threshold: 6) in sorted array can be chunked as follows:
4505 *
4506 * a = [3, 11, 14, 25, 28, 29, 29, 41, 55, 57]
4507 * p a.slice_when {|i, j| 6 < j - i }.to_a
4508 * #=> [[3], [11, 14], [25, 28, 29, 29], [41], [55, 57]]
4509 *
4510 * Increasing (non-decreasing) subsequence can be chunked as follows:
4511 *
4512 * a = [0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
4513 * p a.slice_when {|i, j| i > j }.to_a
4514 * #=> [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
4515 *
4516 * Adjacent evens and odds can be chunked as follows:
4517 * (Enumerable#chunk is another way to do it.)
4518 *
4519 * a = [7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
4520 * p a.slice_when {|i, j| i.even? != j.even? }.to_a
4521 * #=> [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
4522 *
4523 * Paragraphs (non-empty lines with trailing empty lines) can be chunked as follows:
4524 * (See Enumerable#chunk to ignore empty lines.)
4525 *
4526 * lines = ["foo\n", "bar\n", "\n", "baz\n", "qux\n"]
4527 * p lines.slice_when {|l1, l2| /\A\s*\z/ =~ l1 && /\S/ =~ l2 }.to_a
4528 * #=> [["foo\n", "bar\n", "\n"], ["baz\n", "qux\n"]]
4529 *
4530 * Enumerable#chunk_while does the same, except splitting when the block
4531 * returns <code>false</code> instead of <code>true</code>.
4532 */
4533static VALUE
4534enum_slice_when(VALUE enumerable)
4535{
4537 VALUE pred;
4538
4539 pred = rb_block_proc();
4540
4542 rb_ivar_set(enumerator, id_slicewhen_enum, enumerable);
4543 rb_ivar_set(enumerator, id_slicewhen_pred, pred);
4544 rb_ivar_set(enumerator, id_slicewhen_inverted, Qfalse);
4545
4546 rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
4547 return enumerator;
4548}
4549
4550/*
4551 * call-seq:
4552 * enum.chunk_while {|elt_before, elt_after| bool } -> an_enumerator
4553 *
4554 * Creates an enumerator for each chunked elements.
4555 * The beginnings of chunks are defined by the block.
4556 *
4557 * This method splits each chunk using adjacent elements,
4558 * _elt_before_ and _elt_after_,
4559 * in the receiver enumerator.
4560 * This method split chunks between _elt_before_ and _elt_after_ where
4561 * the block returns <code>false</code>.
4562 *
4563 * The block is called the length of the receiver enumerator minus one.
4564 *
4565 * The result enumerator yields the chunked elements as an array.
4566 * So +each+ method can be called as follows:
4567 *
4568 * enum.chunk_while { |elt_before, elt_after| bool }.each { |ary| ... }
4569 *
4570 * Other methods of the Enumerator class and Enumerable module,
4571 * such as +to_a+, +map+, etc., are also usable.
4572 *
4573 * For example, one-by-one increasing subsequence can be chunked as follows:
4574 *
4575 * a = [1,2,4,9,10,11,12,15,16,19,20,21]
4576 * b = a.chunk_while {|i, j| i+1 == j }
4577 * p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
4578 * c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
4579 * p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
4580 * d = c.join(",")
4581 * p d #=> "1,2,4,9-12,15,16,19-21"
4582 *
4583 * Increasing (non-decreasing) subsequence can be chunked as follows:
4584 *
4585 * a = [0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
4586 * p a.chunk_while {|i, j| i <= j }.to_a
4587 * #=> [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
4588 *
4589 * Adjacent evens and odds can be chunked as follows:
4590 * (Enumerable#chunk is another way to do it.)
4591 *
4592 * a = [7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
4593 * p a.chunk_while {|i, j| i.even? == j.even? }.to_a
4594 * #=> [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
4595 *
4596 * Enumerable#slice_when does the same, except splitting when the block
4597 * returns <code>true</code> instead of <code>false</code>.
4598 */
4599static VALUE
4600enum_chunk_while(VALUE enumerable)
4601{
4603 VALUE pred;
4604
4605 pred = rb_block_proc();
4606
4608 rb_ivar_set(enumerator, id_slicewhen_enum, enumerable);
4609 rb_ivar_set(enumerator, id_slicewhen_pred, pred);
4610 rb_ivar_set(enumerator, id_slicewhen_inverted, Qtrue);
4611
4612 rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
4613 return enumerator;
4614}
4615
4617 VALUE v, r;
4618 long n;
4619 double f, c;
4620 int block_given;
4621 int float_value;
4622};
4623
4624static void
4625sum_iter_normalize_memo(struct enum_sum_memo *memo)
4626{
4627 RUBY_ASSERT(FIXABLE(memo->n));
4628 memo->v = rb_fix_plus(LONG2FIX(memo->n), memo->v);
4629 memo->n = 0;
4630
4631 switch (TYPE(memo->r)) {
4632 case T_RATIONAL: memo->v = rb_rational_plus(memo->r, memo->v); break;
4633 case T_UNDEF: break;
4634 default: UNREACHABLE; /* or ...? */
4635 }
4636 memo->r = Qundef;
4637}
4638
4639static void
4640sum_iter_fixnum(VALUE i, struct enum_sum_memo *memo)
4641{
4642 memo->n += FIX2LONG(i); /* should not overflow long type */
4643 if (! FIXABLE(memo->n)) {
4644 memo->v = rb_big_plus(LONG2NUM(memo->n), memo->v);
4645 memo->n = 0;
4646 }
4647}
4648
4649static void
4650sum_iter_bignum(VALUE i, struct enum_sum_memo *memo)
4651{
4652 memo->v = rb_big_plus(i, memo->v);
4653}
4654
4655static void
4656sum_iter_rational(VALUE i, struct enum_sum_memo *memo)
4657{
4658 if (UNDEF_P(memo->r)) {
4659 memo->r = i;
4660 }
4661 else {
4662 memo->r = rb_rational_plus(memo->r, i);
4663 }
4664}
4665
4666static void
4667sum_iter_some_value(VALUE i, struct enum_sum_memo *memo)
4668{
4669 memo->v = rb_funcallv(memo->v, idPLUS, 1, &i);
4670}
4671
4672static void
4673sum_iter_Kahan_Babuska(VALUE i, struct enum_sum_memo *memo)
4674{
4675 /*
4676 * Kahan-Babuska balancing compensated summation algorithm
4677 * See https://link.springer.com/article/10.1007/s00607-005-0139-x
4678 */
4679 double x;
4680
4681 switch (TYPE(i)) {
4682 case T_FLOAT: x = RFLOAT_VALUE(i); break;
4683 case T_FIXNUM: x = FIX2LONG(i); break;
4684 case T_BIGNUM: x = rb_big2dbl(i); break;
4685 case T_RATIONAL: x = rb_num2dbl(i); break;
4686 default:
4687 memo->v = DBL2NUM(memo->f);
4688 memo->float_value = 0;
4689 sum_iter_some_value(i, memo);
4690 return;
4691 }
4692
4693 double f = memo->f;
4694
4695 if (isnan(f)) {
4696 return;
4697 }
4698 else if (! isfinite(x)) {
4699 if (isinf(x) && isinf(f) && signbit(x) != signbit(f)) {
4700 i = DBL2NUM(f);
4701 x = nan("");
4702 }
4703 memo->v = i;
4704 memo->f = x;
4705 return;
4706 }
4707 else if (isinf(f)) {
4708 return;
4709 }
4710
4711 double c = memo->c;
4712 double t = f + x;
4713
4714 if (fabs(f) >= fabs(x)) {
4715 c += ((f - t) + x);
4716 }
4717 else {
4718 c += ((x - t) + f);
4719 }
4720 f = t;
4721
4722 memo->f = f;
4723 memo->c = c;
4724}
4725
4726static void
4727sum_iter(VALUE i, struct enum_sum_memo *memo)
4728{
4729 RUBY_ASSERT(memo != NULL);
4730 if (memo->block_given) {
4731 i = rb_yield(i);
4732 }
4733
4734 if (memo->float_value) {
4735 sum_iter_Kahan_Babuska(i, memo);
4736 }
4737 else switch (TYPE(memo->v)) {
4738 default: sum_iter_some_value(i, memo); return;
4739 case T_FLOAT:
4740 case T_FIXNUM:
4741 case T_BIGNUM:
4742 case T_RATIONAL:
4743 switch (TYPE(i)) {
4744 case T_FIXNUM: sum_iter_fixnum(i, memo); return;
4745 case T_BIGNUM: sum_iter_bignum(i, memo); return;
4746 case T_RATIONAL: sum_iter_rational(i, memo); return;
4747 case T_FLOAT:
4748 sum_iter_normalize_memo(memo);
4749 memo->f = NUM2DBL(memo->v);
4750 memo->c = 0.0;
4751 memo->float_value = 1;
4752 sum_iter_Kahan_Babuska(i, memo);
4753 return;
4754 default:
4755 sum_iter_normalize_memo(memo);
4756 sum_iter_some_value(i, memo);
4757 return;
4758 }
4759 }
4760}
4761
4762static VALUE
4763enum_sum_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
4764{
4765 ENUM_WANT_SVALUE();
4766 sum_iter(i, MEMO_FOR(struct enum_sum_memo, args));
4767 return Qnil;
4768}
4769
4770static int
4771hash_sum_i(VALUE key, VALUE value, VALUE arg)
4772{
4773 sum_iter(rb_assoc_new(key, value), (struct enum_sum_memo *) arg);
4774 return ST_CONTINUE;
4775}
4776
4777static void
4778hash_sum(VALUE hash, struct enum_sum_memo *memo)
4779{
4781 RUBY_ASSERT(memo != NULL);
4782
4783 rb_hash_foreach(hash, hash_sum_i, (VALUE)memo);
4784}
4785
4786static VALUE
4787int_range_sum(VALUE beg, VALUE end, int excl, VALUE init)
4788{
4789 if (excl) {
4790 if (FIXNUM_P(end))
4791 end = LONG2FIX(FIX2LONG(end) - 1);
4792 else
4793 end = rb_big_minus(end, LONG2FIX(1));
4794 }
4795
4796 if (rb_int_ge(end, beg)) {
4797 VALUE a;
4798 a = rb_int_plus(rb_int_minus(end, beg), LONG2FIX(1));
4799 a = rb_int_mul(a, rb_int_plus(end, beg));
4800 a = rb_int_idiv(a, LONG2FIX(2));
4801 return rb_int_plus(init, a);
4802 }
4803
4804 return init;
4805}
4806
4807/*
4808 * call-seq:
4809 * sum(initial_value = 0) -> number
4810 * sum(initial_value = 0) {|element| ... } -> object
4811 *
4812 * With no block given,
4813 * returns the sum of +initial_value+ and the elements:
4814 *
4815 * (1..100).sum # => 5050
4816 * (1..100).sum(1) # => 5051
4817 * ('a'..'d').sum('foo') # => "fooabcd"
4818 *
4819 * Generally, the sum is computed using methods <tt>+</tt> and +each+;
4820 * for performance optimizations, those methods may not be used,
4821 * and so any redefinition of those methods may not have effect here.
4822 *
4823 * One such optimization: When possible, computes using Gauss's summation
4824 * formula <em>n(n+1)/2</em>:
4825 *
4826 * 100 * (100 + 1) / 2 # => 5050
4827 *
4828 * With a block given, calls the block with each element;
4829 * returns the sum of +initial_value+ and the block return values:
4830 *
4831 * (1..4).sum {|i| i*i } # => 30
4832 * (1..4).sum(100) {|i| i*i } # => 130
4833 * h = {a: 0, b: 1, c: 2, d: 3, e: 4, f: 5}
4834 * h.sum {|key, value| value.odd? ? value : 0 } # => 9
4835 * ('a'..'f').sum('x') {|c| c < 'd' ? c : '' } # => "xabc"
4836 *
4837 */
4838static VALUE
4839enum_sum(int argc, VALUE* argv, VALUE obj)
4840{
4841 struct enum_sum_memo memo;
4842 VALUE beg, end;
4843 int excl;
4844
4845 memo.v = (rb_check_arity(argc, 0, 1) == 0) ? LONG2FIX(0) : argv[0];
4846 memo.block_given = rb_block_given_p();
4847 memo.n = 0;
4848 memo.r = Qundef;
4849
4850 if ((memo.float_value = RB_FLOAT_TYPE_P(memo.v))) {
4851 memo.f = RFLOAT_VALUE(memo.v);
4852 memo.c = 0.0;
4853 }
4854 else {
4855 memo.f = 0.0;
4856 memo.c = 0.0;
4857 }
4858
4859 if (RTEST(rb_range_values(obj, &beg, &end, &excl))) {
4860 if (!memo.block_given && !memo.float_value &&
4861 (FIXNUM_P(beg) || RB_BIGNUM_TYPE_P(beg)) &&
4862 (FIXNUM_P(end) || RB_BIGNUM_TYPE_P(end))) {
4863 return int_range_sum(beg, end, excl, memo.v);
4864 }
4865 }
4866
4867 if (RB_TYPE_P(obj, T_HASH) &&
4868 rb_method_basic_definition_p(CLASS_OF(obj), id_each)) {
4869 hash_sum(obj, &memo);
4870 }
4871 else {
4872 VALUE arg;
4873 struct enum_sum_memo *m = NEW_PARTIAL_MEMO_FOR(struct enum_sum_memo, arg, n);
4874 *m = memo;
4875 rb_block_call(obj, id_each, 0, 0, enum_sum_i, arg);
4876 memo = *m;
4877 RB_GC_GUARD(arg);
4878 }
4879
4880 if (memo.float_value) {
4881 return DBL2NUM(memo.f + memo.c);
4882 }
4883 else {
4884 if (memo.n != 0)
4885 memo.v = rb_fix_plus(LONG2FIX(memo.n), memo.v);
4886 if (!UNDEF_P(memo.r)) {
4887 memo.v = rb_rational_plus(memo.r, memo.v);
4888 }
4889 return memo.v;
4890 }
4891}
4892
4893static VALUE
4894uniq_func(RB_BLOCK_CALL_FUNC_ARGLIST(i, set))
4895{
4896 ENUM_WANT_SVALUE();
4897 rb_set_add_no_check(set, i);
4898 return Qnil;
4899}
4900
4901static VALUE
4902uniq_iter(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
4903{
4904 ENUM_WANT_SVALUE();
4905 rb_hash_add_new_element(hash, rb_yield_values2(argc, argv), i);
4906 return Qnil;
4907}
4908
4909/*
4910 * call-seq:
4911 * uniq -> array
4912 * uniq {|element| ... } -> array
4913 *
4914 * With no block, returns a new array containing only unique elements;
4915 * the array has no two elements +e0+ and +e1+ such that <tt>e0.eql?(e1)</tt>:
4916 *
4917 * %w[a b c c b a a b c].uniq # => ["a", "b", "c"]
4918 * [0, 1, 2, 2, 1, 0, 0, 1, 2].uniq # => [0, 1, 2]
4919 *
4920 * With a block, returns a new array containing elements only for which the block
4921 * returns a unique value:
4922 *
4923 * a = [0, 1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
4924 * a.uniq {|i| i.even? ? i : 0 } # => [0, 2, 4]
4925 * a = %w[a b c d e e d c b a a b c d e]
4926 * a.uniq {|c| c < 'c' } # => ["a", "c"]
4927 *
4928 */
4929
4930static VALUE
4931enum_uniq(VALUE obj)
4932{
4933 VALUE ret;
4934 if (rb_block_given_p()) {
4935 VALUE hash = rb_obj_hide(rb_hash_new());
4936 rb_block_call(obj, id_each, 0, 0, uniq_iter, hash);
4937 ret = rb_hash_values(hash);
4938 rb_hash_clear(hash);
4939 }
4940 else {
4941 VALUE set = rb_obj_hide(rb_set_new());
4942 rb_block_call(obj, id_each, 0, 0, uniq_func, set);
4943 ret = rb_set_to_a(set);
4944 rb_set_clear(set);
4945 }
4946 return ret;
4947}
4948
4949static VALUE
4950compact_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
4951{
4952 ENUM_WANT_SVALUE();
4953
4954 if (!NIL_P(i)) {
4955 rb_ary_push(ary, i);
4956 }
4957 return Qnil;
4958}
4959
4960/*
4961 * call-seq:
4962 * compact -> array
4963 *
4964 * Returns an array of all non-+nil+ elements:
4965 *
4966 * a = [nil, 0, nil, 'a', false, nil, false, nil, 'a', nil, 0, nil]
4967 * a.compact # => [0, "a", false, false, "a", 0]
4968 *
4969 */
4970
4971static VALUE
4972enum_compact(VALUE obj)
4973{
4974 VALUE ary;
4975
4976 ary = rb_ary_new();
4977 rb_block_call(obj, id_each, 0, 0, compact_i, ary);
4978
4979 return ary;
4980}
4981
4982
4983/*
4984 * == What's Here
4985 *
4986 * Module \Enumerable provides methods that are useful to a collection class for:
4987 *
4988 * - {Querying}[rdoc-ref:Enumerable@Methods+for+Querying]
4989 * - {Fetching}[rdoc-ref:Enumerable@Methods+for+Fetching]
4990 * - {Searching and Filtering}[rdoc-ref:Enumerable@Methods+for+Searching+and+Filtering]
4991 * - {Sorting}[rdoc-ref:Enumerable@Methods+for+Sorting]
4992 * - {Iterating}[rdoc-ref:Enumerable@Methods+for+Iterating]
4993 * - {And more....}[rdoc-ref:Enumerable@Other+Methods]
4994 *
4995 * === Methods for Querying
4996 *
4997 * These methods return information about the \Enumerable other than the elements themselves:
4998 *
4999 * - #member? (aliased as #include?): Returns +true+ if <tt>self == object</tt>, +false+ otherwise.
5000 * - #all?: Returns +true+ if all elements meet a specified criterion; +false+ otherwise.
5001 * - #any?: Returns +true+ if any element meets a specified criterion; +false+ otherwise.
5002 * - #none?: Returns +true+ if no element meets a specified criterion; +false+ otherwise.
5003 * - #one?: Returns +true+ if exactly one element meets a specified criterion; +false+ otherwise.
5004 * - #count: Returns the count of elements,
5005 * based on an argument or block criterion, if given.
5006 * - #tally: Returns a new Hash containing the counts of occurrences of each element.
5007 *
5008 * === Methods for Fetching
5009 *
5010 * These methods return entries from the \Enumerable, without modifying it:
5011 *
5012 * <i>Leading, trailing, or all elements</i>:
5013 *
5014 * - #to_a (aliased as #entries): Returns all elements.
5015 * - #first: Returns the first element or leading elements.
5016 * - #take: Returns a specified number of leading elements.
5017 * - #drop: Returns a specified number of trailing elements.
5018 * - #take_while: Returns leading elements as specified by the given block.
5019 * - #drop_while: Returns trailing elements as specified by the given block.
5020 *
5021 * <i>Minimum and maximum value elements</i>:
5022 *
5023 * - #min: Returns the elements whose values are smallest among the elements,
5024 * as determined by <tt>#<=></tt> or a given block.
5025 * - #max: Returns the elements whose values are largest among the elements,
5026 * as determined by <tt>#<=></tt> or a given block.
5027 * - #minmax: Returns a 2-element Array containing the smallest and largest elements.
5028 * - #min_by: Returns the smallest element, as determined by the given block.
5029 * - #max_by: Returns the largest element, as determined by the given block.
5030 * - #minmax_by: Returns the smallest and largest elements, as determined by the given block.
5031 *
5032 * <i>Groups, slices, and partitions</i>:
5033 *
5034 * - #group_by: Returns a Hash that partitions the elements into groups.
5035 * - #partition: Returns elements partitioned into two new Arrays, as determined by the given block.
5036 * - #slice_after: Returns a new Enumerator whose entries are a partition of +self+,
5037 * based either on a given +object+ or a given block.
5038 * - #slice_before: Returns a new Enumerator whose entries are a partition of +self+,
5039 * based either on a given +object+ or a given block.
5040 * - #slice_when: Returns a new Enumerator whose entries are a partition of +self+
5041 * based on the given block.
5042 * - #chunk: Returns elements organized into chunks as specified by the given block.
5043 * - #chunk_while: Returns elements organized into chunks as specified by the given block.
5044 *
5045 * === Methods for Searching and Filtering
5046 *
5047 * These methods return elements that meet a specified criterion:
5048 *
5049 * - #find (aliased as #detect): Returns an element selected by the block.
5050 * - #find_all (aliased as #filter, #select): Returns elements selected by the block.
5051 * - #find_index: Returns the index of an element selected by a given object or block.
5052 * - #reject: Returns elements not rejected by the block.
5053 * - #uniq: Returns elements that are not duplicates.
5054 *
5055 * === Methods for Sorting
5056 *
5057 * These methods return elements in sorted order:
5058 *
5059 * - #sort: Returns the elements, sorted by <tt>#<=></tt> or the given block.
5060 * - #sort_by: Returns the elements, sorted by the given block.
5061 *
5062 * === Methods for Iterating
5063 *
5064 * - #each_entry: Calls the block with each successive element
5065 * (slightly different from #each).
5066 * - #each_with_index: Calls the block with each successive element and its index.
5067 * - #each_with_object: Calls the block with each successive element and a given object.
5068 * - #each_slice: Calls the block with successive non-overlapping slices.
5069 * - #each_cons: Calls the block with successive overlapping slices.
5070 * (different from #each_slice).
5071 * - #reverse_each: Calls the block with each successive element, in reverse order.
5072 *
5073 * === Other Methods
5074 *
5075 * - #collect (aliased as #map): Returns objects returned by the block.
5076 * - #filter_map: Returns truthy objects returned by the block.
5077 * - #flat_map (aliased as #collect_concat): Returns flattened objects returned by the block.
5078 * - #grep: Returns elements selected by a given object
5079 * or objects returned by a given block.
5080 * - #grep_v: Returns elements not selected by a given object
5081 * or objects returned by a given block.
5082 * - #inject (aliased as #reduce): Returns the object formed by combining all elements.
5083 * - #sum: Returns the sum of the elements, using method <tt>+</tt>.
5084 * - #zip: Combines each element with elements from other enumerables;
5085 * returns the n-tuples or calls the block with each.
5086 * - #cycle: Calls the block with each element, cycling repeatedly.
5087 *
5088 * == Usage
5089 *
5090 * To use module \Enumerable in a collection class:
5091 *
5092 * - Include it:
5093 *
5094 * include Enumerable
5095 *
5096 * - Implement method <tt>#each</tt>
5097 * which must yield successive elements of the collection.
5098 * The method will be called by almost any \Enumerable method.
5099 *
5100 * Example:
5101 *
5102 * class Foo
5103 * include Enumerable
5104 * def each
5105 * yield 1
5106 * yield 1, 2
5107 * yield
5108 * end
5109 * end
5110 * Foo.new.each_entry{ |element| p element }
5111 *
5112 * Output:
5113 *
5114 * 1
5115 * [1, 2]
5116 * nil
5117 *
5118 * == \Enumerable in Ruby Classes
5119 *
5120 * These Ruby core classes include (or extend) \Enumerable:
5121 *
5122 * - ARGF
5123 * - Array
5124 * - Dir
5125 * - Enumerator
5126 * - ENV (extends)
5127 * - Hash
5128 * - IO
5129 * - Range
5130 * - Struct
5131 *
5132 * These Ruby standard library classes include \Enumerable:
5133 *
5134 * - CSV
5135 * - CSV::Table
5136 * - CSV::Row
5137 * - Set
5138 *
5139 * Virtually all methods in \Enumerable call method +#each+ in the including class:
5140 *
5141 * - <tt>Hash#each</tt> yields the next key-value pair as a 2-element Array.
5142 * - <tt>Struct#each</tt> yields the next name-value pair as a 2-element Array.
5143 * - For the other classes above, +#each+ yields the next object from the collection.
5144 *
5145 * == About the Examples
5146 *
5147 * The example code snippets for the \Enumerable methods:
5148 *
5149 * - Always show the use of one or more Array-like classes (often Array itself).
5150 * - Sometimes show the use of a Hash-like class.
5151 * For some methods, though, the usage would not make sense,
5152 * and so it is not shown. Example: #tally would find exactly one of each Hash entry.
5153 *
5154 * == Extended Methods
5155 *
5156 * A Enumerable class may define extended methods. This section describes the standard
5157 * behavior of extension methods for reference purposes.
5158 *
5159 * === #size
5160 *
5161 * \Enumerator has a #size method.
5162 * It uses the size function argument passed to +Enumerator.new+.
5163 *
5164 * e = Enumerator.new(-> { 3 }) {|y| p y; y.yield :a; y.yield :b; y.yield :c; :z }
5165 * p e.size #=> 3
5166 * p e.next #=> :a
5167 * p e.next #=> :b
5168 * p e.next #=> :c
5169 * begin
5170 * e.next
5171 * rescue StopIteration
5172 * p $!.result #=> :z
5173 * end
5174 *
5175 * The result of the size function should represent the number of iterations
5176 * (i.e., the number of times you yield to the block argument).
5177 * In the above example, the block calls #yield three times, and
5178 * the size function, +-> { 3 }+, returns 3 accordingly.
5179 * The result of the size function can be an integer, +Float::INFINITY+,
5180 * or +nil+.
5181 * An integer means the exact number of times #yield will be called,
5182 * as shown above.
5183 * +Float::INFINITY+ indicates an infinite number of #yield calls.
5184 * +nil+ means the number of #yield calls is difficult or impossible to
5185 * determine.
5186 *
5187 * Many iteration methods return an \Enumerator object with an
5188 * appropriate size function if no block is given.
5189 *
5190 * Examples:
5191 *
5192 * ["a", "b", "c"].each.size #=> 3
5193 * {a: "x", b: "y", c: "z"}.each.size #=> 3
5194 * (0..20).to_a.permutation.size #=> 51090942171709440000
5195 * loop.size #=> Float::INFINITY
5196 * (1..100).drop_while.size #=> nil # size depends on the block's behavior
5197 * STDIN.each.size #=> nil # cannot be computed without consuming input
5198 * File.open("/etc/resolv.conf").each.size #=> nil # cannot be computed without reading the file
5199 *
5200 * The behavior of #size for Range-based enumerators depends on the #begin element:
5201 *
5202 * - If the #begin element is an Integer, the #size method returns an Integer or +Float::INFINITY+.
5203 * - If the #begin element is an object with a #succ method (other than Integer), #size returns +nil+.
5204 * (Computing the size would require repeatedly calling #succ, which may be too slow.)
5205 * - If the #begin element does not have a #succ method, #size raises a TypeError.
5206 *
5207 * Examples:
5208 *
5209 * (10..42).each.size #=> 33
5210 * (10..42.9).each.size #=> 33 (the #end element may be a non-integer numeric)
5211 * (10..).each.size #=> Float::INFINITY
5212 * ("a".."z").each.size #=> nil
5213 * ("a"..).each.size #=> nil
5214 * (1.0..9.0).each.size # raises TypeError (Float does not have #succ)
5215 * (..10).each.size # raises TypeError (beginless range has nil as its #begin)
5216 *
5217 * The \Enumerable module itself does not define a #size method.
5218 * A class that includes \Enumerable may define its own #size method.
5219 * It is recommended that such a #size method be consistent with
5220 * Enumerator#size.
5221 *
5222 * Array and Hash implement #size and return values consistent with
5223 * Enumerator#size.
5224 * IO and Dir do not define #size, which is also consistent because the
5225 * corresponding enumerator's size function returns +nil+.
5226 *
5227 * However, it is not strictly required for a class's #size method to match Enumerator#size.
5228 * For example, File#size returns the number of bytes in the file, not the number of lines.
5229 *
5230 */
5231
5232void
5233Init_Enumerable(void)
5234{
5235 rb_mEnumerable = rb_define_module("Enumerable");
5236
5237 rb_define_method(rb_mEnumerable, "to_a", enum_to_a, -1);
5238 rb_define_method(rb_mEnumerable, "entries", enum_to_a, -1);
5239 rb_define_method(rb_mEnumerable, "to_h", enum_to_h, -1);
5240
5241 rb_define_method(rb_mEnumerable, "sort", enum_sort, 0);
5242 rb_define_method(rb_mEnumerable, "sort_by", enum_sort_by, 0);
5243 rb_define_method(rb_mEnumerable, "grep", enum_grep, 1);
5244 rb_define_method(rb_mEnumerable, "grep_v", enum_grep_v, 1);
5245 rb_define_method(rb_mEnumerable, "count", enum_count, -1);
5246 rb_define_method(rb_mEnumerable, "find", enum_find, -1);
5247 rb_define_method(rb_mEnumerable, "detect", enum_find, -1);
5248 rb_define_method(rb_mEnumerable, "find_index", enum_find_index, -1);
5249 rb_define_method(rb_mEnumerable, "find_all", enum_find_all, 0);
5250 rb_define_method(rb_mEnumerable, "select", enum_find_all, 0);
5251 rb_define_method(rb_mEnumerable, "filter", enum_find_all, 0);
5252 rb_define_method(rb_mEnumerable, "filter_map", enum_filter_map, 0);
5253 rb_define_method(rb_mEnumerable, "reject", enum_reject, 0);
5254 rb_define_method(rb_mEnumerable, "collect", enum_collect, 0);
5255 rb_define_method(rb_mEnumerable, "map", enum_collect, 0);
5256 rb_define_method(rb_mEnumerable, "flat_map", enum_flat_map, 0);
5257 rb_define_method(rb_mEnumerable, "collect_concat", enum_flat_map, 0);
5258 rb_define_method(rb_mEnumerable, "inject", enum_inject, -1);
5259 rb_define_method(rb_mEnumerable, "reduce", enum_inject, -1);
5260 rb_define_method(rb_mEnumerable, "partition", enum_partition, 0);
5261 rb_define_method(rb_mEnumerable, "group_by", enum_group_by, 0);
5262 rb_define_method(rb_mEnumerable, "tally", enum_tally, -1);
5263 rb_define_method(rb_mEnumerable, "first", enum_first, -1);
5264 rb_define_method(rb_mEnumerable, "all?", enum_all, -1);
5265 rb_define_method(rb_mEnumerable, "any?", enum_any, -1);
5266 rb_define_method(rb_mEnumerable, "one?", enum_one, -1);
5267 rb_define_method(rb_mEnumerable, "none?", enum_none, -1);
5268 rb_define_method(rb_mEnumerable, "min", enum_min, -1);
5269 rb_define_method(rb_mEnumerable, "max", enum_max, -1);
5270 rb_define_method(rb_mEnumerable, "minmax", enum_minmax, 0);
5271 rb_define_method(rb_mEnumerable, "min_by", enum_min_by, -1);
5272 rb_define_method(rb_mEnumerable, "max_by", enum_max_by, -1);
5273 rb_define_method(rb_mEnumerable, "minmax_by", enum_minmax_by, 0);
5274 rb_define_method(rb_mEnumerable, "member?", enum_member, 1);
5275 rb_define_method(rb_mEnumerable, "include?", enum_member, 1);
5276 rb_define_method(rb_mEnumerable, "each_with_index", enum_each_with_index, -1);
5277 rb_define_method(rb_mEnumerable, "reverse_each", enum_reverse_each, -1);
5278 rb_define_method(rb_mEnumerable, "each_entry", enum_each_entry, -1);
5279 rb_define_method(rb_mEnumerable, "each_slice", enum_each_slice, 1);
5280 rb_define_method(rb_mEnumerable, "each_cons", enum_each_cons, 1);
5281 rb_define_method(rb_mEnumerable, "each_with_object", enum_each_with_object, 1);
5282 rb_define_method(rb_mEnumerable, "zip", enum_zip, -1);
5283 rb_define_method(rb_mEnumerable, "take", enum_take, 1);
5284 rb_define_method(rb_mEnumerable, "take_while", enum_take_while, 0);
5285 rb_define_method(rb_mEnumerable, "drop", enum_drop, 1);
5286 rb_define_method(rb_mEnumerable, "drop_while", enum_drop_while, 0);
5287 rb_define_method(rb_mEnumerable, "cycle", enum_cycle, -1);
5288 rb_define_method(rb_mEnumerable, "chunk", enum_chunk, 0);
5289 rb_define_method(rb_mEnumerable, "slice_before", enum_slice_before, -1);
5290 rb_define_method(rb_mEnumerable, "slice_after", enum_slice_after, -1);
5291 rb_define_method(rb_mEnumerable, "slice_when", enum_slice_when, 0);
5292 rb_define_method(rb_mEnumerable, "chunk_while", enum_chunk_while, 0);
5293 rb_define_method(rb_mEnumerable, "sum", enum_sum, -1);
5294 rb_define_method(rb_mEnumerable, "uniq", enum_uniq, 0);
5295 rb_define_method(rb_mEnumerable, "compact", enum_compact, 0);
5296
5297 id__alone = rb_intern_const("_alone");
5298 id__separator = rb_intern_const("_separator");
5299 id_chunk_categorize = rb_intern_const("chunk_categorize");
5300 id_chunk_enumerable = rb_intern_const("chunk_enumerable");
5301 id_next = rb_intern_const("next");
5302 id_sliceafter_enum = rb_intern_const("sliceafter_enum");
5303 id_sliceafter_pat = rb_intern_const("sliceafter_pat");
5304 id_sliceafter_pred = rb_intern_const("sliceafter_pred");
5305 id_slicebefore_enumerable = rb_intern_const("slicebefore_enumerable");
5306 id_slicebefore_sep_pat = rb_intern_const("slicebefore_sep_pat");
5307 id_slicebefore_sep_pred = rb_intern_const("slicebefore_sep_pred");
5308 id_slicewhen_enum = rb_intern_const("slicewhen_enum");
5309 id_slicewhen_inverted = rb_intern_const("slicewhen_inverted");
5310 id_slicewhen_pred = rb_intern_const("slicewhen_pred");
5311}
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
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:3350
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1035
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define LEN2NUM
Old name of RB_LEN2NUM.
Definition len_t.h:33
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define ULEN2NUM
Old name of RB_ULEN2NUM.
Definition len_t.h:35
#define FIX2ULONG
Old name of RB_FIX2ULONG.
Definition long.h:47
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#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 T_UNDEF
Old name of RUBY_T_UNDEF.
Definition value_type.h:82
#define Qtrue
Old name of RUBY_Qtrue.
#define FIXNUM_MAX
Old name of RUBY_FIXNUM_MAX.
Definition fixnum.h:26
#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 DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define NUM2LEN
Old name of RB_NUM2LEN.
Definition len_t.h:34
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
#define T_REGEXP
Old name of RUBY_T_REGEXP.
Definition value_type.h:77
void rb_iter_break(void)
Breaks from a block.
Definition vm.c:2403
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
VALUE rb_eStopIteration
StopIteration exception.
Definition enumerator.c:196
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:495
VALUE rb_cArray
Array class.
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2274
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:28
VALUE rb_cEnumerator
Enumerator class.
Definition enumerator.c:179
VALUE rb_cInteger
Module class.
Definition numeric.c:202
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:240
double rb_num2dbl(VALUE num)
Converts an instance of rb_cNumeric into C's double.
Definition object.c:3855
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:140
#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
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1124
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:1082
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:1175
VALUE rb_ary_concat(VALUE lhs, VALUE rhs)
Destructively appends the contents of latter into the end of former.
VALUE rb_ary_reverse(VALUE ary)
Destructively reverses the passed array in-place.
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_dup(VALUE ary)
Duplicates an array.
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_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_new(void)
Allocates a new, empty array.
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_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_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
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_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:1580
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1857
VALUE rb_set_clear(VALUE set)
Removes all entries from set.
Definition set.c:2376
VALUE rb_set_new(void)
Creates a new, empty set object.
Definition set.c:2352
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:3072
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2150
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition variable.c:1645
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3715
int rb_method_basic_definition_p(VALUE klass, ID mid)
Well... Let us hesitate from describing what a "basic definition" is.
Definition vm_method.c:3593
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:692
int rb_obj_respond_to(VALUE obj, ID mid, int private_p)
Identical to rb_respond_to(), except it additionally takes the visibility parameter.
Definition vm_method.c:3699
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1289
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1148
int len
Length of the buffer.
Definition io.h:8
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:1402
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:1424
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1379
rb_block_call_func * rb_block_call_func_t
Shorthand type that represents an iterator-written-in-C function pointer.
Definition iterator.h:88
VALUE rb_block_call_func(RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg))
This is the type of a function that the interpreter expect for C-backended blocks.
Definition iterator.h:83
VALUE rb_block_call_kw(VALUE obj, ID mid, int argc, const VALUE *argv, rb_block_call_func_t proc, VALUE data2, int kw_splat)
Identical to rb_funcallv_kw(), except it additionally passes a function as a block.
Definition vm_eval.c:1571
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE rb_block_call(VALUE q, ID w, int e, const VALUE *r, type *t, VALUE y)
Call a method with a block.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
VALUE rb_rescue2(type *q, VALUE w, type *e, VALUE r,...)
An equivalent of rescue clause.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY_PTR_USE(ary, ptr_name, expr)
Declares a section of code where raw pointers are used.
Definition rarray.h:347
static VALUE * RARRAY_PTR(VALUE ary)
Wild use of a C pointer.
Definition rarray.h:365
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:421
static void RARRAY_ASET(VALUE ary, rb_len_t i, VALUE v)
Assigns an object in an array.
Definition rarray.h:385
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#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.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
MEMO.
Definition imemo.h:118
Definition enum.c:2419
Definition enum.c:2296
IFUNC (Internal FUNCtion)
Definition imemo.h:89
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_ULEN_MAX
Maximum possible value that a rb_ulen_t can take.
Definition value.h:162
#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
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 void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:425
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