Ruby 4.1.0dev (2026-12-06 revision 6b501f5444cf675f4a654bda46c812e2c1df9fb8)
enum.c (6b501f5444cf675f4a654bda46c812e2c1df9fb8)
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 int
1960cmpint_reenter_check(struct nmin_data *data, VALUE cmp, VALUE a, VALUE b)
1961{
1962 int val = rb_cmpint(cmp, a, b);
1963 if (RBASIC(data->buf)->klass) {
1964 rb_raise(rb_eRuntimeError, "%s%s reentered",
1965 data->rev ? "max" : "min",
1966 data->by ? "_by" : "");
1967 }
1968 return val;
1969}
1970
1971static int
1972nmin_cmp(const void *ap, const void *bp, void *_data)
1973{
1974 struct nmin_data *data = (struct nmin_data *)_data;
1975 VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
1976#define rb_cmpint(cmp, a, b) cmpint_reenter_check(data, cmp, a, b)
1977 return OPTIMIZED_CMP(a, b);
1978#undef rb_cmpint
1979}
1980
1981static int
1982nmin_block_cmp(const void *ap, const void *bp, void *_data)
1983{
1984 struct nmin_data *data = (struct nmin_data *)_data;
1985 VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
1986 VALUE cmp = rb_yield_values(2, a, b);
1987 return cmpint_reenter_check(data, 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 /* m points into memo, and the last update may trigger GC, calling the
2701 * block or #<=>, before m is read. */
2702 RB_GC_GUARD(memo);
2703 if (!UNDEF_P(m->min)) {
2704 return rb_assoc_new(m->min, m->max);
2705 }
2706 return rb_assoc_new(Qnil, Qnil);
2707}
2708
2709static VALUE
2710min_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2711{
2712 struct MEMO *memo = MEMO_CAST(args);
2713 VALUE v;
2714
2715 ENUM_WANT_SVALUE();
2716
2717 v = enum_yield(argc, i);
2718 if (UNDEF_P(memo->v1)) {
2719 MEMO_V1_SET(memo, v);
2720 MEMO_V2_SET(memo, i);
2721 }
2722 else if (OPTIMIZED_CMP(v, memo->v1) < 0) {
2723 MEMO_V1_SET(memo, v);
2724 MEMO_V2_SET(memo, i);
2725 }
2726 return Qnil;
2727}
2728
2729/*
2730 * call-seq:
2731 * min_by {|element| ... } -> element
2732 * min_by(n) {|element| ... } -> array
2733 * min_by -> enumerator
2734 * min_by(n) -> enumerator
2735 *
2736 * Returns the elements for which the block returns the minimum values.
2737 *
2738 * With a block given and no argument,
2739 * returns the element for which the block returns the minimum value:
2740 *
2741 * (1..4).min_by {|element| -element } # => 4
2742 * %w[a b c d].min_by {|element| -element.ord } # => "d"
2743 * {foo: 0, bar: 1, baz: 2}.min_by {|key, value| -value } # => [:baz, 2]
2744 * [].min_by {|element| -element } # => nil
2745 *
2746 * With a block given and positive integer argument +n+ given,
2747 * returns an array containing the +n+ elements
2748 * for which the block returns minimum values:
2749 *
2750 * (1..4).min_by(2) {|element| -element }
2751 * # => [4, 3]
2752 * %w[a b c d].min_by(2) {|element| -element.ord }
2753 * # => ["d", "c"]
2754 * {foo: 0, bar: 1, baz: 2}.min_by(2) {|key, value| -value }
2755 * # => [[:baz, 2], [:bar, 1]]
2756 * [].min_by(2) {|element| -element }
2757 * # => []
2758 *
2759 * Returns an Enumerator if no block is given.
2760 *
2761 * Related: #min, #minmax, #max_by.
2762 *
2763 */
2764
2765static VALUE
2766enum_min_by(int argc, VALUE *argv, VALUE obj)
2767{
2768 struct MEMO *memo;
2769 VALUE num;
2770
2771 rb_check_arity(argc, 0, 1);
2772
2773 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
2774
2775 if (argc && !NIL_P(num = argv[0]))
2776 return rb_nmin_run(obj, num, 1, 0, 0);
2777
2778 memo = rb_imemo_memo_new(Qundef, Qnil, 0);
2779 rb_block_call(obj, id_each, 0, 0, min_by_i, (VALUE)memo);
2780 return memo->v2;
2781}
2782
2783static VALUE
2784max_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2785{
2786 struct MEMO *memo = MEMO_CAST(args);
2787 VALUE v;
2788
2789 ENUM_WANT_SVALUE();
2790
2791 v = enum_yield(argc, i);
2792 if (UNDEF_P(memo->v1)) {
2793 MEMO_V1_SET(memo, v);
2794 MEMO_V2_SET(memo, i);
2795 }
2796 else if (OPTIMIZED_CMP(v, memo->v1) > 0) {
2797 MEMO_V1_SET(memo, v);
2798 MEMO_V2_SET(memo, i);
2799 }
2800 return Qnil;
2801}
2802
2803/*
2804 * call-seq:
2805 * max_by {|element| ... } -> element
2806 * max_by(n) {|element| ... } -> array
2807 * max_by -> enumerator
2808 * max_by(n) -> enumerator
2809 *
2810 * Returns the elements for which the block returns the maximum values.
2811 *
2812 * With a block given and no argument,
2813 * returns the element for which the block returns the maximum value:
2814 *
2815 * (1..4).max_by {|element| -element } # => 1
2816 * %w[a b c d].max_by {|element| -element.ord } # => "a"
2817 * {foo: 0, bar: 1, baz: 2}.max_by {|key, value| -value } # => [:foo, 0]
2818 * [].max_by {|element| -element } # => nil
2819 *
2820 * With a block given and positive integer argument +n+ given,
2821 * returns an array containing the +n+ elements
2822 * for which the block returns maximum values:
2823 *
2824 * (1..4).max_by(2) {|element| -element }
2825 * # => [1, 2]
2826 * %w[a b c d].max_by(2) {|element| -element.ord }
2827 * # => ["a", "b"]
2828 * {foo: 0, bar: 1, baz: 2}.max_by(2) {|key, value| -value }
2829 * # => [[:foo, 0], [:bar, 1]]
2830 * [].max_by(2) {|element| -element }
2831 * # => []
2832 *
2833 * Returns an Enumerator if no block is given.
2834 *
2835 * Related: #max, #minmax, #min_by.
2836 *
2837 */
2838
2839static VALUE
2840enum_max_by(int argc, VALUE *argv, VALUE obj)
2841{
2842 struct MEMO *memo;
2843 VALUE num;
2844
2845 rb_check_arity(argc, 0, 1);
2846
2847 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
2848
2849 if (argc && !NIL_P(num = argv[0]))
2850 return rb_nmin_run(obj, num, 1, 1, 0);
2851
2852 memo = rb_imemo_memo_new(Qundef, Qnil, 0);
2853 rb_block_call(obj, id_each, 0, 0, max_by_i, (VALUE)memo);
2854 return memo->v2;
2855}
2856
2858 VALUE min_bv;
2859 VALUE max_bv;
2860 VALUE min;
2861 VALUE max;
2862 VALUE last_bv;
2863 VALUE last;
2864};
2865
2866static void
2867minmax_by_i_update(VALUE v1, VALUE v2, VALUE i1, VALUE i2, struct minmax_by_t *memo)
2868{
2869 if (UNDEF_P(memo->min_bv)) {
2870 memo->min_bv = v1;
2871 memo->max_bv = v2;
2872 memo->min = i1;
2873 memo->max = i2;
2874 }
2875 else {
2876 if (OPTIMIZED_CMP(v1, memo->min_bv) < 0) {
2877 memo->min_bv = v1;
2878 memo->min = i1;
2879 }
2880 if (OPTIMIZED_CMP(v2, memo->max_bv) > 0) {
2881 memo->max_bv = v2;
2882 memo->max = i2;
2883 }
2884 }
2885}
2886
2887static VALUE
2888minmax_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
2889{
2890 struct minmax_by_t *memo = MEMO_FOR(struct minmax_by_t, _memo);
2891 VALUE vi, vj, j;
2892 int n;
2893
2894 ENUM_WANT_SVALUE();
2895
2896 vi = enum_yield(argc, i);
2897
2898 if (UNDEF_P(memo->last_bv)) {
2899 memo->last_bv = vi;
2900 memo->last = i;
2901 return Qnil;
2902 }
2903 vj = memo->last_bv;
2904 j = memo->last;
2905 memo->last_bv = Qundef;
2906
2907 n = OPTIMIZED_CMP(vj, vi);
2908 if (n == 0) {
2909 i = j;
2910 vi = vj;
2911 }
2912 else if (n < 0) {
2913 VALUE tmp;
2914 tmp = i;
2915 i = j;
2916 j = tmp;
2917 tmp = vi;
2918 vi = vj;
2919 vj = tmp;
2920 }
2921
2922 minmax_by_i_update(vi, vj, i, j, memo);
2923
2924 return Qnil;
2925}
2926
2927/*
2928 * call-seq:
2929 * minmax_by {|element| ... } -> [minimum, maximum]
2930 * minmax_by -> enumerator
2931 *
2932 * Returns a 2-element array containing the elements
2933 * for which the block returns minimum and maximum values:
2934 *
2935 * (1..4).minmax_by {|element| -element }
2936 * # => [4, 1]
2937 * %w[a b c d].minmax_by {|element| -element.ord }
2938 * # => ["d", "a"]
2939 * {foo: 0, bar: 1, baz: 2}.minmax_by {|key, value| -value }
2940 * # => [[:baz, 2], [:foo, 0]]
2941 * [].minmax_by {|element| -element }
2942 * # => [nil, nil]
2943 *
2944 * Returns an Enumerator if no block is given.
2945 *
2946 * Related: #max_by, #minmax, #min_by.
2947 *
2948 */
2949
2950static VALUE
2951enum_minmax_by(VALUE obj)
2952{
2953 VALUE memo;
2954 struct minmax_by_t *m = NEW_MEMO_FOR(struct minmax_by_t, memo);
2955
2956 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
2957
2958 m->min_bv = Qundef;
2959 m->max_bv = Qundef;
2960 m->min = Qnil;
2961 m->max = Qnil;
2962 m->last_bv = Qundef;
2963 m->last = Qundef;
2964 rb_block_call(obj, id_each, 0, 0, minmax_by_i, memo);
2965 if (!UNDEF_P(m->last_bv))
2966 minmax_by_i_update(m->last_bv, m->last_bv, m->last, m->last, m);
2967 m = MEMO_FOR(struct minmax_by_t, memo);
2968 return rb_assoc_new(m->min, m->max);
2969}
2970
2971static VALUE
2972member_i(RB_BLOCK_CALL_FUNC_ARGLIST(iter, args))
2973{
2974 struct MEMO *memo = MEMO_CAST(args);
2975
2976 if (rb_equal(rb_enum_values_pack(argc, argv), memo->v1)) {
2977 MEMO_V2_SET(memo, Qtrue);
2978 rb_iter_break();
2979 }
2980 return Qnil;
2981}
2982
2983/*
2984 * call-seq:
2985 * include?(object) -> true or false
2986 *
2987 * Returns whether for any element <tt>object == element</tt>:
2988 *
2989 * (1..4).include?(2) # => true
2990 * (1..4).include?(5) # => false
2991 * (1..4).include?('2') # => false
2992 * %w[a b c d].include?('b') # => true
2993 * %w[a b c d].include?('2') # => false
2994 * {foo: 0, bar: 1, baz: 2}.include?(:foo) # => true
2995 * {foo: 0, bar: 1, baz: 2}.include?('foo') # => false
2996 * {foo: 0, bar: 1, baz: 2}.include?(0) # => false
2997 *
2998 */
2999
3000static VALUE
3001enum_member(VALUE obj, VALUE val)
3002{
3003 struct MEMO *memo = rb_imemo_memo_new(val, Qfalse, 0);
3004
3005 rb_block_call(obj, id_each, 0, 0, member_i, (VALUE)memo);
3006 return memo->v2;
3007}
3008
3009static VALUE
3010each_with_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(_, index))
3011{
3012 struct vm_ifunc *ifunc = rb_current_ifunc();
3013 ifunc->data = (const void *)rb_int_succ(index);
3014
3015 return rb_yield_values(2, rb_enum_values_pack(argc, argv), index);
3016}
3017
3018/*
3019 * call-seq:
3020 * each_with_index(*args) {|element, i| ..... } -> self
3021 * each_with_index(*args) -> enumerator
3022 *
3023 * Invoke <tt>self.each</tt> with <tt>*args</tt>.
3024 * With a block given, the block receives each element and its index;
3025 * returns +self+:
3026 *
3027 * h = {}
3028 * (1..4).each_with_index {|element, i| h[element] = i } # => 1..4
3029 * h # => {1=>0, 2=>1, 3=>2, 4=>3}
3030 *
3031 * h = {}
3032 * %w[a b c d].each_with_index {|element, i| h[element] = i }
3033 * # => ["a", "b", "c", "d"]
3034 * h # => {"a"=>0, "b"=>1, "c"=>2, "d"=>3}
3035 *
3036 * a = []
3037 * h = {foo: 0, bar: 1, baz: 2}
3038 * h.each_with_index {|element, i| a.push([i, element]) }
3039 * # => {:foo=>0, :bar=>1, :baz=>2}
3040 * a # => [[0, [:foo, 0]], [1, [:bar, 1]], [2, [:baz, 2]]]
3041 *
3042 * With no block given, returns an Enumerator.
3043 *
3044 */
3045
3046static VALUE
3047enum_each_with_index(int argc, VALUE *argv, VALUE obj)
3048{
3049 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
3050
3051 rb_block_call(obj, id_each, argc, argv, each_with_index_i, INT2FIX(0));
3052 return obj;
3053}
3054
3055
3056/*
3057 * call-seq:
3058 * reverse_each(*args) {|element| ... } -> self
3059 * reverse_each(*args) -> enumerator
3060 *
3061 * With a block given, calls the block with each element,
3062 * but in reverse order; returns +self+:
3063 *
3064 * a = []
3065 * (1..4).reverse_each {|element| a.push(-element) } # => 1..4
3066 * a # => [-4, -3, -2, -1]
3067 *
3068 * a = []
3069 * %w[a b c d].reverse_each {|element| a.push(element) }
3070 * # => ["a", "b", "c", "d"]
3071 * a # => ["d", "c", "b", "a"]
3072 *
3073 * a = []
3074 * h.reverse_each {|element| a.push(element) }
3075 * # => {:foo=>0, :bar=>1, :baz=>2}
3076 * a # => [[:baz, 2], [:bar, 1], [:foo, 0]]
3077 *
3078 * With no block given, returns an Enumerator.
3079 *
3080 */
3081
3082static VALUE
3083enum_reverse_each(int argc, VALUE *argv, VALUE obj)
3084{
3085 VALUE ary;
3086 rb_len_t len;
3087
3088 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
3089
3090 ary = enum_to_a(argc, argv, obj);
3091
3092 len = RARRAY_LEN(ary);
3093 while (len--) {
3094 rb_len_t nlen;
3095 rb_yield(RARRAY_AREF(ary, len));
3096 nlen = RARRAY_LEN(ary);
3097 if (nlen < len) {
3098 len = nlen;
3099 }
3100 }
3101
3102 return obj;
3103}
3104
3105
3106static VALUE
3107each_val_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
3108{
3109 ENUM_WANT_SVALUE();
3110 enum_yield(argc, i);
3111 return Qnil;
3112}
3113
3114/*
3115 * call-seq:
3116 * each_entry(*args) {|element| ... } -> self
3117 * each_entry(*args) -> enumerator
3118 *
3119 * Calls the given block with each element,
3120 * converting multiple values from yield to an array; returns +self+:
3121 *
3122 * a = []
3123 * (1..4).each_entry {|element| a.push(element) } # => 1..4
3124 * a # => [1, 2, 3, 4]
3125 *
3126 * a = []
3127 * h = {foo: 0, bar: 1, baz:2}
3128 * h.each_entry {|element| a.push(element) }
3129 * # => {:foo=>0, :bar=>1, :baz=>2}
3130 * a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3131 *
3132 * class Foo
3133 * include Enumerable
3134 * def each
3135 * yield 1
3136 * yield 1, 2
3137 * yield
3138 * end
3139 * end
3140 * Foo.new.each_entry {|yielded| p yielded }
3141 *
3142 * Output:
3143 *
3144 * 1
3145 * [1, 2]
3146 * nil
3147 *
3148 * With no block given, returns an Enumerator.
3149 *
3150 */
3151
3152static VALUE
3153enum_each_entry(int argc, VALUE *argv, VALUE obj)
3154{
3155 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
3156 rb_block_call(obj, id_each, argc, argv, each_val_i, 0);
3157 return obj;
3158}
3159
3160static VALUE
3161add_int(VALUE x, rb_len_t n)
3162{
3163 const VALUE y = LEN2NUM(n);
3164 if (RB_INTEGER_TYPE_P(x)) return rb_int_plus(x, y);
3165 return rb_funcallv(x, '+', 1, &y);
3166}
3167
3168static VALUE
3169div_int(VALUE x, rb_len_t n)
3170{
3171 const VALUE y = LEN2NUM(n);
3172 if (RB_INTEGER_TYPE_P(x)) return rb_int_idiv(x, y);
3173 return rb_funcallv(x, id_div, 1, &y);
3174}
3175
3176#define dont_recycle_block_arg(arity) ((arity) == 1 || (arity) < 0)
3177
3178static VALUE
3179each_slice_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, m))
3180{
3181 struct MEMO *memo = MEMO_CAST(m);
3182 VALUE ary = memo->v1;
3183 VALUE v = Qnil;
3184 rb_len_t size = memo->u3.cnt;
3185 ENUM_WANT_SVALUE();
3186
3187 rb_ary_push(ary, i);
3188
3189 if (RARRAY_LEN(ary) == size) {
3190 v = rb_yield(ary);
3191
3192 if (memo->v2) {
3193 MEMO_V1_SET(memo, rb_ary_new2(size));
3194 }
3195 else {
3196 rb_ary_clear(ary);
3197 }
3198 }
3199
3200 return v;
3201}
3202
3203static VALUE
3204enum_each_slice_size(VALUE obj, VALUE args, VALUE eobj)
3205{
3206 VALUE n, size;
3207 rb_len_t slice_size = NUM2LEN(RARRAY_AREF(args, 0));
3208 ID infinite_p;
3209 CONST_ID(infinite_p, "infinite?");
3210 if (slice_size <= 0) rb_raise(rb_eArgError, "invalid slice size");
3211
3212 size = enum_size(obj, 0, 0);
3213 if (NIL_P(size)) return Qnil;
3214 if (RB_FLOAT_TYPE_P(size) && RTEST(rb_funcall(size, infinite_p, 0))) {
3215 return size;
3216 }
3217
3218 n = add_int(size, slice_size-1);
3219 return div_int(n, slice_size);
3220}
3221
3222/*
3223 * call-seq:
3224 * each_slice(n) { ... } -> self
3225 * each_slice(n) -> enumerator
3226 *
3227 * Calls the block with each successive disjoint +n+-tuple of elements;
3228 * returns +self+:
3229 *
3230 * a = []
3231 * (1..10).each_slice(3) {|tuple| a.push(tuple) }
3232 * a # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
3233 *
3234 * a = []
3235 * h = {foo: 0, bar: 1, baz: 2, bat: 3, bam: 4}
3236 * h.each_slice(2) {|tuple| a.push(tuple) }
3237 * a # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]], [[:bam, 4]]]
3238 *
3239 * With no block given, returns an Enumerator.
3240 *
3241 */
3242static VALUE
3243enum_each_slice(VALUE obj, VALUE n)
3244{
3245 rb_len_t size = NUM2LEN(n);
3246 VALUE ary;
3247 struct MEMO *memo;
3248 int arity;
3249
3250 if (size <= 0) rb_raise(rb_eArgError, "invalid slice size");
3251 RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_slice_size);
3252 size = limit_by_enum_size(obj, size);
3253 ary = rb_ary_new2(size);
3254 arity = rb_block_arity();
3255 memo = rb_imemo_memo_new(ary, dont_recycle_block_arg(arity), size);
3256 rb_block_call(obj, id_each, 0, 0, each_slice_i, (VALUE)memo);
3257 ary = memo->v1;
3258 if (RARRAY_LEN(ary) > 0) rb_yield(ary);
3259
3260 return obj;
3261}
3262
3263static VALUE
3264each_cons_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3265{
3266 struct MEMO *memo = MEMO_CAST(args);
3267 VALUE ary = memo->v1;
3268 VALUE v = Qnil;
3269 rb_len_t size = memo->u3.cnt;
3270 ENUM_WANT_SVALUE();
3271
3272 if (RARRAY_LEN(ary) == size) {
3273 rb_ary_shift(ary);
3274 }
3275 rb_ary_push(ary, i);
3276 if (RARRAY_LEN(ary) == size) {
3277 if (memo->v2) {
3278 ary = rb_ary_dup(ary);
3279 }
3280 v = rb_yield(ary);
3281 }
3282 return v;
3283}
3284
3285static VALUE
3286enum_each_cons_size(VALUE obj, VALUE args, VALUE eobj)
3287{
3288 const VALUE zero = LONG2FIX(0);
3289 VALUE n, size;
3290 rb_len_t cons_size = NUM2LEN(RARRAY_AREF(args, 0));
3291 if (cons_size <= 0) rb_raise(rb_eArgError, "invalid size");
3292
3293 size = enum_size(obj, 0, 0);
3294 if (NIL_P(size)) return Qnil;
3295
3296 n = add_int(size, 1 - cons_size);
3297 return (OPTIMIZED_CMP(n, zero) == -1) ? zero : n;
3298}
3299
3300/*
3301 * call-seq:
3302 * each_cons(n) { ... } -> self
3303 * each_cons(n) -> enumerator
3304 *
3305 * Calls the block with each successive overlapped +n+-tuple of elements;
3306 * returns +self+:
3307 *
3308 * a = []
3309 * (1..5).each_cons(3) {|element| a.push(element) }
3310 * a # => [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
3311 *
3312 * a = []
3313 * h = {foo: 0, bar: 1, baz: 2, bam: 3}
3314 * h.each_cons(2) {|element| a.push(element) }
3315 * a # => [[[:foo, 0], [:bar, 1]], [[:bar, 1], [:baz, 2]], [[:baz, 2], [:bam, 3]]]
3316 *
3317 * With no block given, returns an Enumerator.
3318 *
3319 */
3320static VALUE
3321enum_each_cons(VALUE obj, VALUE n)
3322{
3323 rb_len_t size = NUM2LEN(n);
3324 struct MEMO *memo;
3325 int arity;
3326
3327 if (size <= 0) rb_raise(rb_eArgError, "invalid size");
3328 RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_cons_size);
3329 arity = rb_block_arity();
3330 if (enum_size_over_p(obj, size)) return obj;
3331 memo = rb_imemo_memo_new(rb_ary_new2(size), dont_recycle_block_arg(arity), size);
3332 rb_block_call(obj, id_each, 0, 0, each_cons_i, (VALUE)memo);
3333
3334 return obj;
3335}
3336
3337static VALUE
3338each_with_object_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo))
3339{
3340 ENUM_WANT_SVALUE();
3341 return rb_yield_values(2, i, memo);
3342}
3343
3344/*
3345 * call-seq:
3346 * each_with_object(object) { |(*args), memo_object| ... } -> object
3347 * each_with_object(object) -> enumerator
3348 *
3349 * Calls the block once for each element, passing both the element
3350 * and the given object:
3351 *
3352 * (1..4).each_with_object([]) {|i, a| a.push(i**2) }
3353 * # => [1, 4, 9, 16]
3354 *
3355 * {foo: 0, bar: 1, baz: 2}.each_with_object({}) {|(k, v), h| h[v] = k }
3356 * # => {0=>:foo, 1=>:bar, 2=>:baz}
3357 *
3358 * With no block given, returns an Enumerator.
3359 *
3360 */
3361static VALUE
3362enum_each_with_object(VALUE obj, VALUE memo)
3363{
3364 RETURN_SIZED_ENUMERATOR(obj, 1, &memo, enum_size);
3365
3366 rb_block_call(obj, id_each, 0, 0, each_with_object_i, memo);
3367
3368 return memo;
3369}
3370
3371static VALUE
3372zip_ary(RB_BLOCK_CALL_FUNC_ARGLIST(val, memoval))
3373{
3374 struct MEMO *memo = (struct MEMO *)memoval;
3375 VALUE result = memo->v1;
3376 VALUE args = memo->v2;
3377 rb_len_t n = memo->u3.cnt++;
3378 VALUE tmp;
3379 int i;
3380
3381 tmp = rb_ary_new2(RARRAY_LEN(args) + 1);
3382 rb_ary_store(tmp, 0, rb_enum_values_pack(argc, argv));
3383 for (i=0; i<RARRAY_LEN(args); i++) {
3384 VALUE e = RARRAY_AREF(args, i);
3385
3386 if (RARRAY_LEN(e) <= n) {
3387 rb_ary_push(tmp, Qnil);
3388 }
3389 else {
3390 rb_ary_push(tmp, RARRAY_AREF(e, n));
3391 }
3392 }
3393 if (NIL_P(result)) {
3394 enum_yield_array(tmp);
3395 }
3396 else {
3397 rb_ary_push(result, tmp);
3398 }
3399
3400 RB_GC_GUARD(args);
3401
3402 return Qnil;
3403}
3404
3405static VALUE
3406call_next(VALUE w)
3407{
3408 VALUE *v = (VALUE *)w;
3409 return v[0] = rb_funcallv(v[1], id_next, 0, 0);
3410}
3411
3412static VALUE
3413call_stop(VALUE w, VALUE _)
3414{
3415 VALUE *v = (VALUE *)w;
3416 return v[0] = Qundef;
3417}
3418
3419static VALUE
3420zip_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, memoval))
3421{
3422 struct MEMO *memo = (struct MEMO *)memoval;
3423 VALUE result = memo->v1;
3424 VALUE args = memo->v2;
3425 VALUE tmp;
3426 int i;
3427
3428 tmp = rb_ary_new2(RARRAY_LEN(args) + 1);
3429 rb_ary_store(tmp, 0, rb_enum_values_pack(argc, argv));
3430 for (i=0; i<RARRAY_LEN(args); i++) {
3431 if (NIL_P(RARRAY_AREF(args, i))) {
3432 rb_ary_push(tmp, Qnil);
3433 }
3434 else {
3435 VALUE v[2];
3436
3437 v[1] = RARRAY_AREF(args, i);
3438 rb_rescue2(call_next, (VALUE)v, call_stop, (VALUE)v, rb_eStopIteration, (VALUE)0);
3439 if (UNDEF_P(v[0])) {
3440 RARRAY_ASET(args, i, Qnil);
3441 v[0] = Qnil;
3442 }
3443 rb_ary_push(tmp, v[0]);
3444 }
3445 }
3446 if (NIL_P(result)) {
3447 enum_yield_array(tmp);
3448 }
3449 else {
3450 rb_ary_push(result, tmp);
3451 }
3452
3453 RB_GC_GUARD(args);
3454
3455 return Qnil;
3456}
3457
3458/*
3459 * call-seq:
3460 * zip(*other_enums) -> array
3461 * zip(*other_enums) {|array| ... } -> nil
3462 *
3463 * With no block given, returns a new array +new_array+ of size self.size
3464 * whose elements are arrays.
3465 * Each nested array <tt>new_array[n]</tt>
3466 * is of size <tt>other_enums.size+1</tt>, and contains:
3467 *
3468 * - The +n+-th element of self.
3469 * - The +n+-th element of each of the +other_enums+.
3470 *
3471 * If all +other_enums+ and self are the same size,
3472 * all elements are included in the result, and there is no +nil+-filling:
3473 *
3474 * a = [:a0, :a1, :a2, :a3]
3475 * b = [:b0, :b1, :b2, :b3]
3476 * c = [:c0, :c1, :c2, :c3]
3477 * d = a.zip(b, c)
3478 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
3479 *
3480 * f = {foo: 0, bar: 1, baz: 2}
3481 * g = {goo: 3, gar: 4, gaz: 5}
3482 * h = {hoo: 6, har: 7, haz: 8}
3483 * d = f.zip(g, h)
3484 * d # => [
3485 * # [[:foo, 0], [:goo, 3], [:hoo, 6]],
3486 * # [[:bar, 1], [:gar, 4], [:har, 7]],
3487 * # [[:baz, 2], [:gaz, 5], [:haz, 8]]
3488 * # ]
3489 *
3490 * If any enumerable in other_enums is smaller than self,
3491 * fills to <tt>self.size</tt> with +nil+:
3492 *
3493 * a = [:a0, :a1, :a2, :a3]
3494 * b = [:b0, :b1, :b2]
3495 * c = [:c0, :c1]
3496 * d = a.zip(b, c)
3497 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, nil], [:a3, nil, nil]]
3498 *
3499 * If any enumerable in other_enums is larger than self,
3500 * its trailing elements are ignored:
3501 *
3502 * a = [:a0, :a1, :a2, :a3]
3503 * b = [:b0, :b1, :b2, :b3, :b4]
3504 * c = [:c0, :c1, :c2, :c3, :c4, :c5]
3505 * d = a.zip(b, c)
3506 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
3507 *
3508 * When a block is given, calls the block with each of the sub-arrays
3509 * (formed as above); returns nil:
3510 *
3511 * a = [:a0, :a1, :a2, :a3]
3512 * b = [:b0, :b1, :b2, :b3]
3513 * c = [:c0, :c1, :c2, :c3]
3514 * a.zip(b, c) {|sub_array| p sub_array} # => nil
3515 *
3516 * Output:
3517 *
3518 * [:a0, :b0, :c0]
3519 * [:a1, :b1, :c1]
3520 * [:a2, :b2, :c2]
3521 * [:a3, :b3, :c3]
3522 *
3523 */
3524
3525static VALUE
3526enum_zip(int argc, VALUE *argv, VALUE obj)
3527{
3528 int i;
3529 ID conv;
3530 struct MEMO *memo;
3531 VALUE result = Qnil;
3532 VALUE args = rb_ary_new4(argc, argv);
3533 int allary = TRUE;
3534
3535 argv = RARRAY_PTR(args);
3536 for (i=0; i<argc; i++) {
3537 VALUE ary = rb_check_array_type(argv[i]);
3538 if (NIL_P(ary)) {
3539 allary = FALSE;
3540 break;
3541 }
3542 argv[i] = ary;
3543 }
3544 if (!allary) {
3545 static const VALUE sym_each = STATIC_ID2SYM(id_each);
3546 CONST_ID(conv, "to_enum");
3547 for (i=0; i<argc; i++) {
3548 if (!rb_respond_to(argv[i], id_each)) {
3549 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (must respond to :each)",
3550 rb_obj_class(argv[i]));
3551 }
3552 argv[i] = rb_funcallv(argv[i], conv, 1, &sym_each);
3553 }
3554 }
3555 if (!rb_block_given_p()) {
3556 result = rb_ary_new();
3557 }
3558
3559 /* TODO: use NODE_DOT2 as memo(v, v, -) */
3560 memo = rb_imemo_memo_new(result, args, 0);
3561 rb_block_call(obj, id_each, 0, 0, allary ? zip_ary : zip_i, (VALUE)memo);
3562
3563 return result;
3564}
3565
3566static VALUE
3567take_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3568{
3569 struct MEMO *memo = MEMO_CAST(args);
3570 rb_ary_push(memo->v1, rb_enum_values_pack(argc, argv));
3571 if (--memo->u3.cnt == 0) rb_iter_break();
3572 return Qnil;
3573}
3574
3575/*
3576 * call-seq:
3577 * take(n) -> array
3578 *
3579 * For non-negative integer +n+, returns the first +n+ elements:
3580 *
3581 * r = (1..4)
3582 * r.take(2) # => [1, 2]
3583 * r.take(0) # => []
3584 *
3585 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
3586 * h.take(2) # => [[:foo, 0], [:bar, 1]]
3587 *
3588 */
3589
3590static VALUE
3591enum_take(VALUE obj, VALUE n)
3592{
3593 struct MEMO *memo;
3594 VALUE result;
3595 rb_len_t len = NUM2LEN(n);
3596
3597 if (len < 0) {
3598 rb_raise(rb_eArgError, "attempt to take negative size");
3599 }
3600
3601 if (len == 0) return rb_ary_new2(0);
3602 result = rb_ary_new2(len);
3603 memo = rb_imemo_memo_new(result, 0, len);
3604 rb_block_call(obj, id_each, 0, 0, take_i, (VALUE)memo);
3605 return result;
3606}
3607
3608
3609static VALUE
3610take_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
3611{
3612 if (!RTEST(rb_yield_values2(argc, argv))) rb_iter_break();
3613 rb_ary_push(ary, rb_enum_values_pack(argc, argv));
3614 return Qnil;
3615}
3616
3617/*
3618 * call-seq:
3619 * take_while {|element| ... } -> array
3620 * take_while -> enumerator
3621 *
3622 * Calls the block with successive elements as long as the block
3623 * returns a truthy value;
3624 * returns an array of all elements up to that point:
3625 *
3626 *
3627 * (1..4).take_while{|i| i < 3 } # => [1, 2]
3628 * h = {foo: 0, bar: 1, baz: 2}
3629 * h.take_while{|element| key, value = *element; value < 2 }
3630 * # => [[:foo, 0], [:bar, 1]]
3631 *
3632 * With no block given, returns an Enumerator.
3633 *
3634 */
3635
3636static VALUE
3637enum_take_while(VALUE obj)
3638{
3639 VALUE ary;
3640
3641 RETURN_ENUMERATOR(obj, 0, 0);
3642 ary = rb_ary_new();
3643 rb_block_call(obj, id_each, 0, 0, take_while_i, ary);
3644 return ary;
3645}
3646
3647static VALUE
3648drop_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3649{
3650 struct MEMO *memo = MEMO_CAST(args);
3651 if (memo->u3.cnt == 0) {
3652 rb_ary_push(memo->v1, rb_enum_values_pack(argc, argv));
3653 }
3654 else {
3655 memo->u3.cnt--;
3656 }
3657 return Qnil;
3658}
3659
3660/*
3661 * call-seq:
3662 * drop(n) -> array
3663 *
3664 * For positive integer +n+, returns an array containing
3665 * all but the first +n+ elements:
3666 *
3667 * r = (1..4)
3668 * r.drop(3) # => [4]
3669 * r.drop(2) # => [3, 4]
3670 * r.drop(1) # => [2, 3, 4]
3671 * r.drop(0) # => [1, 2, 3, 4]
3672 * r.drop(50) # => []
3673 *
3674 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
3675 * h.drop(2) # => [[:baz, 2], [:bat, 3]]
3676 *
3677 */
3678
3679static VALUE
3680enum_drop(VALUE obj, VALUE n)
3681{
3682 VALUE result;
3683 struct MEMO *memo;
3684 rb_len_t len = NUM2LEN(n);
3685
3686 if (len < 0) {
3687 rb_raise(rb_eArgError, "attempt to drop negative size");
3688 }
3689
3690 result = rb_ary_new();
3691 memo = rb_imemo_memo_new(result, 0, len);
3692 rb_block_call(obj, id_each, 0, 0, drop_i, (VALUE)memo);
3693 return result;
3694}
3695
3696
3697static VALUE
3698drop_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3699{
3700 struct MEMO *memo = MEMO_CAST(args);
3701 ENUM_WANT_SVALUE();
3702
3703 if (!memo->u3.state && !RTEST(enum_yield(argc, i))) {
3704 memo->u3.state = TRUE;
3705 }
3706 if (memo->u3.state) {
3707 rb_ary_push(memo->v1, i);
3708 }
3709 return Qnil;
3710}
3711
3712/*
3713 * call-seq:
3714 * drop_while {|element| ... } -> array
3715 * drop_while -> enumerator
3716 *
3717 * Calls the block with successive elements as long as the block
3718 * returns a truthy value;
3719 * returns an array of all elements after that point:
3720 *
3721 *
3722 * (1..4).drop_while{|i| i < 3 } # => [3, 4]
3723 * h = {foo: 0, bar: 1, baz: 2}
3724 * a = h.drop_while{|element| key, value = *element; value < 2 }
3725 * a # => [[:baz, 2]]
3726 *
3727 * With no block given, returns an Enumerator.
3728 *
3729 * e = (1..4).drop_while
3730 * p e #=> #<Enumerator: 1..4:drop_while>
3731 * i = e.next; p i; e.feed(i < 3) #=> 1
3732 * i = e.next; p i; e.feed(i < 3) #=> 2
3733 * i = e.next; p i; e.feed(i < 3) #=> 3
3734 * begin
3735 * e.next
3736 * rescue StopIteration
3737 * p $!.result #=> [3, 4]
3738 * end
3739 *
3740 */
3741
3742static VALUE
3743enum_drop_while(VALUE obj)
3744{
3745 VALUE result;
3746 struct MEMO *memo;
3747
3748 RETURN_ENUMERATOR(obj, 0, 0);
3749 result = rb_ary_new();
3750 memo = rb_imemo_memo_new(result, 0, FALSE);
3751 rb_block_call(obj, id_each, 0, 0, drop_while_i, (VALUE)memo);
3752 return result;
3753}
3754
3755static VALUE
3756cycle_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
3757{
3758 ENUM_WANT_SVALUE();
3759
3760 rb_ary_push(ary, argc > 1 ? i : rb_ary_new_from_values(argc, argv));
3761 enum_yield(argc, i);
3762 return Qnil;
3763}
3764
3765static VALUE
3766enum_cycle_size(VALUE self, VALUE args, VALUE eobj)
3767{
3768 rb_len_t mul = 0;
3769 VALUE n = Qnil;
3770 VALUE size;
3771
3772 if (args && (RARRAY_LEN(args) > 0)) {
3773 n = RARRAY_AREF(args, 0);
3774 if (!NIL_P(n)) mul = NUM2LEN(n);
3775 }
3776
3777 size = enum_size(self, args, 0);
3778 if (NIL_P(size) || FIXNUM_ZERO_P(size)) return size;
3779
3780 if (NIL_P(n)) return DBL2NUM(HUGE_VAL);
3781 if (mul <= 0) return INT2FIX(0);
3782 n = LEN2NUM(mul);
3783 return rb_funcallv(size, '*', 1, &n);
3784}
3785
3786/*
3787 * call-seq:
3788 * cycle(n = nil) {|element| ...} -> nil
3789 * cycle(n = nil) -> enumerator
3790 *
3791 * When called with positive integer argument +n+ and a block,
3792 * calls the block with each element, then does so again,
3793 * until it has done so +n+ times; returns +nil+:
3794 *
3795 * a = []
3796 * (1..4).cycle(3) {|element| a.push(element) } # => nil
3797 * a # => [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
3798 * a = []
3799 * ('a'..'d').cycle(2) {|element| a.push(element) }
3800 * a # => ["a", "b", "c", "d", "a", "b", "c", "d"]
3801 * a = []
3802 * {foo: 0, bar: 1, baz: 2}.cycle(2) {|element| a.push(element) }
3803 * a # => [[:foo, 0], [:bar, 1], [:baz, 2], [:foo, 0], [:bar, 1], [:baz, 2]]
3804 *
3805 * If count is zero or negative, does not call the block.
3806 *
3807 * When called with a block and +n+ is +nil+, cycles forever.
3808 *
3809 * When no block is given, returns an Enumerator.
3810 *
3811 */
3812
3813static VALUE
3814enum_cycle(int argc, VALUE *argv, VALUE obj)
3815{
3816 VALUE ary;
3817 VALUE nv = Qnil;
3818 rb_len_t n;
3819 rb_len_t i, len;
3820
3821 rb_check_arity(argc, 0, 1);
3822
3823 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_cycle_size);
3824 if (!argc || NIL_P(nv = argv[0])) {
3825 n = -1;
3826 }
3827 else {
3828 n = NUM2LEN(nv);
3829 if (n <= 0) return Qnil;
3830 }
3831 ary = rb_ary_new();
3832 RBASIC_CLEAR_CLASS(ary);
3833 rb_block_call(obj, id_each, 0, 0, cycle_i, ary);
3834 len = RARRAY_LEN(ary);
3835 if (len == 0) return Qnil;
3836 while (n < 0 || 0 < --n) {
3837 for (i=0; i<len; i++) {
3838 enum_yield_array(RARRAY_AREF(ary, i));
3839 }
3840 }
3841 return Qnil;
3842}
3843
3845 VALUE categorize;
3846 VALUE prev_value;
3847 VALUE prev_elts;
3848 VALUE yielder;
3849};
3850
3851static VALUE
3852chunk_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
3853{
3854 struct chunk_arg *argp = MEMO_FOR(struct chunk_arg, _argp);
3855 VALUE v, s;
3856 VALUE alone = ID2SYM(id__alone);
3857 VALUE separator = ID2SYM(id__separator);
3858
3859 ENUM_WANT_SVALUE();
3860
3861 v = rb_funcallv(argp->categorize, id_call, 1, &i);
3862
3863 if (v == alone) {
3864 if (!NIL_P(argp->prev_value)) {
3865 s = rb_assoc_new(argp->prev_value, argp->prev_elts);
3866 rb_funcallv(argp->yielder, id_lshift, 1, &s);
3867 argp->prev_value = argp->prev_elts = Qnil;
3868 }
3869 v = rb_assoc_new(v, rb_ary_new3(1, i));
3870 rb_funcallv(argp->yielder, id_lshift, 1, &v);
3871 }
3872 else if (NIL_P(v) || v == separator) {
3873 if (!NIL_P(argp->prev_value)) {
3874 v = rb_assoc_new(argp->prev_value, argp->prev_elts);
3875 rb_funcallv(argp->yielder, id_lshift, 1, &v);
3876 argp->prev_value = argp->prev_elts = Qnil;
3877 }
3878 }
3879 else if (SYMBOL_P(v) && (s = rb_sym2str(v), RSTRING_PTR(s)[0] == '_')) {
3880 rb_raise(rb_eRuntimeError, "symbols beginning with an underscore are reserved");
3881 }
3882 else {
3883 if (NIL_P(argp->prev_value)) {
3884 argp->prev_value = v;
3885 argp->prev_elts = rb_ary_new3(1, i);
3886 }
3887 else {
3888 if (rb_equal(argp->prev_value, v)) {
3889 rb_ary_push(argp->prev_elts, i);
3890 }
3891 else {
3892 s = rb_assoc_new(argp->prev_value, argp->prev_elts);
3893 rb_funcallv(argp->yielder, id_lshift, 1, &s);
3894 argp->prev_value = v;
3895 argp->prev_elts = rb_ary_new3(1, i);
3896 }
3897 }
3898 }
3899 return Qnil;
3900}
3901
3902static VALUE
3904{
3905 VALUE enumerable;
3906 VALUE arg;
3907 struct chunk_arg *memo = NEW_MEMO_FOR(struct chunk_arg, arg);
3908
3909 enumerable = rb_ivar_get(enumerator, id_chunk_enumerable);
3910 memo->categorize = rb_ivar_get(enumerator, id_chunk_categorize);
3911 memo->prev_value = Qnil;
3912 memo->prev_elts = Qnil;
3913 memo->yielder = yielder;
3914
3915 rb_block_call(enumerable, id_each, 0, 0, chunk_ii, arg);
3916 memo = MEMO_FOR(struct chunk_arg, arg);
3917 if (!NIL_P(memo->prev_elts)) {
3918 arg = rb_assoc_new(memo->prev_value, memo->prev_elts);
3919 rb_funcallv(memo->yielder, id_lshift, 1, &arg);
3920 }
3921 return Qnil;
3922}
3923
3924/*
3925 * call-seq:
3926 * chunk {|array| ... } -> enumerator
3927 *
3928 * Each element in the returned enumerator is a 2-element array consisting of:
3929 *
3930 * - A value returned by the block.
3931 * - An array ("chunk") containing the element for which that value was returned,
3932 * and all following elements for which the block returned the same value:
3933 *
3934 * So that:
3935 *
3936 * - Each block return value that is different from its predecessor
3937 * begins a new chunk.
3938 * - Each block return value that is the same as its predecessor
3939 * continues the same chunk.
3940 *
3941 * Example:
3942 *
3943 * e = (0..10).chunk {|i| (i / 3).floor } # => #<Enumerator: ...>
3944 * # The enumerator elements.
3945 * e.next # => [0, [0, 1, 2]]
3946 * e.next # => [1, [3, 4, 5]]
3947 * e.next # => [2, [6, 7, 8]]
3948 * e.next # => [3, [9, 10]]
3949 *
3950 * Method +chunk+ is especially useful for an enumerable that is already sorted.
3951 * This example counts words for each initial letter in a large array of words:
3952 *
3953 * # Get sorted words from a web page.
3954 * url = 'https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt'
3955 * words = URI::open(url).readlines
3956 * # Make chunks, one for each letter.
3957 * e = words.chunk {|word| word.upcase[0] } # => #<Enumerator: ...>
3958 * # Display 'A' through 'F'.
3959 * e.each {|c, words| p [c, words.length]; break if c == 'F' }
3960 *
3961 * Output:
3962 *
3963 * ["A", 17096]
3964 * ["B", 11070]
3965 * ["C", 19901]
3966 * ["D", 10896]
3967 * ["E", 8736]
3968 * ["F", 6860]
3969 *
3970 * You can use the special symbol <tt>:_alone</tt> to force an element
3971 * into its own separate chunk:
3972 *
3973 * a = [0, 0, 1, 1]
3974 * e = a.chunk{|i| i.even? ? :_alone : true }
3975 * e.to_a # => [[:_alone, [0]], [:_alone, [0]], [true, [1, 1]]]
3976 *
3977 * For example, you can put each line that contains a URL into its own chunk:
3978 *
3979 * pattern = /http/
3980 * open(filename) { |f|
3981 * f.chunk { |line| line =~ pattern ? :_alone : true }.each { |key, lines|
3982 * pp lines
3983 * }
3984 * }
3985 *
3986 * You can use the special symbol <tt>:_separator</tt> or +nil+
3987 * to force an element to be ignored (not included in any chunk):
3988 *
3989 * a = [0, 0, -1, 1, 1]
3990 * e = a.chunk{|i| i < 0 ? :_separator : true }
3991 * e.to_a # => [[true, [0, 0]], [true, [1, 1]]]
3992 *
3993 * Note that the separator does end the chunk:
3994 *
3995 * a = [0, 0, -1, 1, -1, 1]
3996 * e = a.chunk{|i| i < 0 ? :_separator : true }
3997 * e.to_a # => [[true, [0, 0]], [true, [1]], [true, [1]]]
3998 *
3999 * For example, the sequence of hyphens in svn log can be eliminated as follows:
4000 *
4001 * sep = "-"*72 + "\n"
4002 * IO.popen("svn log README") { |f|
4003 * f.chunk { |line|
4004 * line != sep || nil
4005 * }.each { |_, lines|
4006 * pp lines
4007 * }
4008 * }
4009 * #=> ["r20018 | knu | 2008-10-29 13:20:42 +0900 (Wed, 29 Oct 2008) | 2 lines\n",
4010 * # "\n",
4011 * # "* README, README.ja: Update the portability section.\n",
4012 * # "\n"]
4013 * # ["r16725 | knu | 2008-05-31 23:34:23 +0900 (Sat, 31 May 2008) | 2 lines\n",
4014 * # "\n",
4015 * # "* README, README.ja: Add a note about default C flags.\n",
4016 * # "\n"]
4017 * # ...
4018 *
4019 * Paragraphs separated by empty lines can be parsed as follows:
4020 *
4021 * File.foreach("README").chunk { |line|
4022 * /\A\s*\z/ !~ line || nil
4023 * }.each { |_, lines|
4024 * pp lines
4025 * }
4026 *
4027 */
4028static VALUE
4029enum_chunk(VALUE enumerable)
4030{
4032
4033 RETURN_SIZED_ENUMERATOR(enumerable, 0, 0, enum_size);
4034
4036 rb_ivar_set(enumerator, id_chunk_enumerable, enumerable);
4037 rb_ivar_set(enumerator, id_chunk_categorize, rb_block_proc());
4038 rb_block_call(enumerator, idInitialize, 0, 0, chunk_i, enumerator);
4039 return enumerator;
4040}
4041
4042
4044 VALUE sep_pred;
4045 VALUE sep_pat;
4046 VALUE prev_elts;
4047 VALUE yielder;
4048};
4049
4050static VALUE
4051slicebefore_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
4052{
4053 struct slicebefore_arg *argp = MEMO_FOR(struct slicebefore_arg, _argp);
4054 VALUE header_p;
4055
4056 ENUM_WANT_SVALUE();
4057
4058 if (!NIL_P(argp->sep_pat))
4059 header_p = rb_funcallv(argp->sep_pat, id_eqq, 1, &i);
4060 else
4061 header_p = rb_funcallv(argp->sep_pred, id_call, 1, &i);
4062 if (RTEST(header_p)) {
4063 if (!NIL_P(argp->prev_elts))
4064 rb_funcallv(argp->yielder, id_lshift, 1, &argp->prev_elts);
4065 argp->prev_elts = rb_ary_new3(1, i);
4066 }
4067 else {
4068 if (NIL_P(argp->prev_elts))
4069 argp->prev_elts = rb_ary_new3(1, i);
4070 else
4071 rb_ary_push(argp->prev_elts, i);
4072 }
4073
4074 return Qnil;
4075}
4076
4077static VALUE
4079{
4080 VALUE enumerable;
4081 VALUE arg;
4082 struct slicebefore_arg *memo = NEW_MEMO_FOR(struct slicebefore_arg, arg);
4083
4084 enumerable = rb_ivar_get(enumerator, id_slicebefore_enumerable);
4085 memo->sep_pred = rb_attr_get(enumerator, id_slicebefore_sep_pred);
4086 memo->sep_pat = NIL_P(memo->sep_pred) ? rb_ivar_get(enumerator, id_slicebefore_sep_pat) : Qnil;
4087 memo->prev_elts = Qnil;
4088 memo->yielder = yielder;
4089
4090 rb_block_call(enumerable, id_each, 0, 0, slicebefore_ii, arg);
4091 memo = MEMO_FOR(struct slicebefore_arg, arg);
4092 if (!NIL_P(memo->prev_elts))
4093 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4094 /* &memo->prev_elts points into arg, and the call may trigger GC before
4095 * it reads the argument. */
4096 RB_GC_GUARD(arg);
4097 return Qnil;
4098}
4099
4100/*
4101 * call-seq:
4102 * slice_before(pattern) -> enumerator
4103 * slice_before {|elt| ... } -> enumerator
4104 *
4105 * With argument +pattern+, returns an enumerator that uses the pattern
4106 * to partition elements into arrays ("slices").
4107 * An element begins a new slice if <tt>element === pattern</tt>
4108 * (or if it is the first element).
4109 *
4110 * a = %w[foo bar fop for baz fob fog bam foy]
4111 * e = a.slice_before(/ba/) # => #<Enumerator: ...>
4112 * e.each {|array| p array }
4113 *
4114 * Output:
4115 *
4116 * ["foo"]
4117 * ["bar", "fop", "for"]
4118 * ["baz", "fob", "fog"]
4119 * ["bam", "foy"]
4120 *
4121 * With a block, returns an enumerator that uses the block
4122 * to partition elements into arrays.
4123 * An element begins a new slice if its block return is a truthy value
4124 * (or if it is the first element):
4125 *
4126 * e = (1..20).slice_before {|i| i % 4 == 2 } # => #<Enumerator: ...>
4127 * e.each {|array| p array }
4128 *
4129 * Output:
4130 *
4131 * [1]
4132 * [2, 3, 4, 5]
4133 * [6, 7, 8, 9]
4134 * [10, 11, 12, 13]
4135 * [14, 15, 16, 17]
4136 * [18, 19, 20]
4137 *
4138 * Other methods of the Enumerator class and Enumerable module,
4139 * such as +to_a+, +map+, etc., are also usable.
4140 *
4141 * For example, iteration over ChangeLog entries can be implemented as
4142 * follows:
4143 *
4144 * # iterate over ChangeLog entries.
4145 * open("ChangeLog") { |f|
4146 * f.slice_before(/\A\S/).each { |e| pp e }
4147 * }
4148 *
4149 * # same as above. block is used instead of pattern argument.
4150 * open("ChangeLog") { |f|
4151 * f.slice_before { |line| /\A\S/ === line }.each { |e| pp e }
4152 * }
4153 *
4154 * "svn proplist -R" produces multiline output for each file.
4155 * They can be chunked as follows:
4156 *
4157 * IO.popen([{"LC_ALL"=>"C"}, "svn", "proplist", "-R"]) { |f|
4158 * f.lines.slice_before(/\AProp/).each { |lines| p lines }
4159 * }
4160 * #=> ["Properties on '.':\n", " svn:ignore\n", " svk:merge\n"]
4161 * # ["Properties on 'goruby.c':\n", " svn:eol-style\n"]
4162 * # ["Properties on 'complex.c':\n", " svn:mime-type\n", " svn:eol-style\n"]
4163 * # ["Properties on 'regparse.c':\n", " svn:eol-style\n"]
4164 * # ...
4165 *
4166 * If the block needs to maintain state over multiple elements,
4167 * local variables can be used.
4168 * For example, three or more consecutive increasing numbers can be squashed
4169 * as follows (see +chunk_while+ for a better way):
4170 *
4171 * a = [0, 2, 3, 4, 6, 7, 9]
4172 * prev = a[0]
4173 * p a.slice_before { |e|
4174 * prev, prev2 = e, prev
4175 * prev2 + 1 != e
4176 * }.map { |es|
4177 * es.length <= 2 ? es.join(",") : "#{es.first}-#{es.last}"
4178 * }.join(",")
4179 * #=> "0,2-4,6,7,9"
4180 *
4181 * However local variables should be used carefully
4182 * if the result enumerator is enumerated twice or more.
4183 * The local variables should be initialized for each enumeration.
4184 * Enumerator.new can be used to do it.
4185 *
4186 * # Word wrapping. This assumes all characters have same width.
4187 * def wordwrap(words, maxwidth)
4188 * Enumerator.new {|y|
4189 * # cols is initialized in Enumerator.new.
4190 * cols = 0
4191 * words.slice_before { |w|
4192 * cols += 1 if cols != 0
4193 * cols += w.length
4194 * if maxwidth < cols
4195 * cols = w.length
4196 * true
4197 * else
4198 * false
4199 * end
4200 * }.each {|ws| y.yield ws }
4201 * }
4202 * end
4203 * text = (1..20).to_a.join(" ")
4204 * enum = wordwrap(text.split(/\s+/), 10)
4205 * puts "-"*10
4206 * enum.each { |ws| puts ws.join(" ") } # first enumeration.
4207 * puts "-"*10
4208 * enum.each { |ws| puts ws.join(" ") } # second enumeration generates same result as the first.
4209 * puts "-"*10
4210 * #=> ----------
4211 * # 1 2 3 4 5
4212 * # 6 7 8 9 10
4213 * # 11 12 13
4214 * # 14 15 16
4215 * # 17 18 19
4216 * # 20
4217 * # ----------
4218 * # 1 2 3 4 5
4219 * # 6 7 8 9 10
4220 * # 11 12 13
4221 * # 14 15 16
4222 * # 17 18 19
4223 * # 20
4224 * # ----------
4225 *
4226 * mbox contains series of mails which start with Unix From line.
4227 * So each mail can be extracted by slice before Unix From line.
4228 *
4229 * # parse mbox
4230 * open("mbox") { |f|
4231 * f.slice_before { |line|
4232 * line.start_with? "From "
4233 * }.each { |mail|
4234 * unix_from = mail.shift
4235 * i = mail.index("\n")
4236 * header = mail[0...i]
4237 * body = mail[(i+1)..-1]
4238 * body.pop if body.last == "\n"
4239 * fields = header.slice_before { |line| !" \t".include?(line[0]) }.to_a
4240 * p unix_from
4241 * pp fields
4242 * pp body
4243 * }
4244 * }
4245 *
4246 * # split mails in mbox (slice before Unix From line after an empty line)
4247 * open("mbox") { |f|
4248 * emp = true
4249 * f.slice_before { |line|
4250 * prevemp = emp
4251 * emp = line == "\n"
4252 * prevemp && line.start_with?("From ")
4253 * }.each { |mail|
4254 * mail.pop if mail.last == "\n"
4255 * pp mail
4256 * }
4257 * }
4258 *
4259 */
4260static VALUE
4261enum_slice_before(int argc, VALUE *argv, VALUE enumerable)
4262{
4264
4265 if (rb_block_given_p()) {
4266 if (argc != 0)
4267 rb_error_arity(argc, 0, 0);
4269 rb_ivar_set(enumerator, id_slicebefore_sep_pred, rb_block_proc());
4270 }
4271 else {
4272 VALUE sep_pat;
4273 rb_scan_args(argc, argv, "1", &sep_pat);
4275 rb_ivar_set(enumerator, id_slicebefore_sep_pat, sep_pat);
4276 }
4277 rb_ivar_set(enumerator, id_slicebefore_enumerable, enumerable);
4278 rb_block_call(enumerator, idInitialize, 0, 0, slicebefore_i, enumerator);
4279 return enumerator;
4280}
4281
4282
4284 VALUE pat;
4285 VALUE pred;
4286 VALUE prev_elts;
4287 VALUE yielder;
4288};
4289
4290static VALUE
4291sliceafter_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
4292{
4293#define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct sliceafter_arg, _memo)))
4294 struct sliceafter_arg *memo;
4295 int split_p;
4296 UPDATE_MEMO;
4297
4298 ENUM_WANT_SVALUE();
4299
4300 if (NIL_P(memo->prev_elts)) {
4301 memo->prev_elts = rb_ary_new3(1, i);
4302 }
4303 else {
4304 rb_ary_push(memo->prev_elts, i);
4305 }
4306
4307 if (NIL_P(memo->pred)) {
4308 split_p = RTEST(rb_funcallv(memo->pat, id_eqq, 1, &i));
4309 UPDATE_MEMO;
4310 }
4311 else {
4312 split_p = RTEST(rb_funcallv(memo->pred, id_call, 1, &i));
4313 UPDATE_MEMO;
4314 }
4315
4316 if (split_p) {
4317 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4318 UPDATE_MEMO;
4319 memo->prev_elts = Qnil;
4320 }
4321
4322 return Qnil;
4323#undef UPDATE_MEMO
4324}
4325
4326static VALUE
4328{
4329 VALUE enumerable;
4330 VALUE arg;
4331 struct sliceafter_arg *memo = NEW_MEMO_FOR(struct sliceafter_arg, arg);
4332
4333 enumerable = rb_ivar_get(enumerator, id_sliceafter_enum);
4334 memo->pat = rb_ivar_get(enumerator, id_sliceafter_pat);
4335 memo->pred = rb_attr_get(enumerator, id_sliceafter_pred);
4336 memo->prev_elts = Qnil;
4337 memo->yielder = yielder;
4338
4339 rb_block_call(enumerable, id_each, 0, 0, sliceafter_ii, arg);
4340 memo = MEMO_FOR(struct sliceafter_arg, arg);
4341 if (!NIL_P(memo->prev_elts))
4342 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4343 /* &memo->prev_elts points into arg, and the call may trigger GC before
4344 * it reads the argument. */
4345 RB_GC_GUARD(arg);
4346 return Qnil;
4347}
4348
4349/*
4350 * call-seq:
4351 * enum.slice_after(pattern) -> an_enumerator
4352 * enum.slice_after { |elt| bool } -> an_enumerator
4353 *
4354 * Creates an enumerator for each chunked elements.
4355 * The ends of chunks are defined by _pattern_ and the block.
4356 *
4357 * If <code>_pattern_ === _elt_</code> returns <code>true</code> or the block
4358 * returns <code>true</code> for the element, the element is end of a
4359 * chunk.
4360 *
4361 * The <code>===</code> and _block_ is called from the first element to the last
4362 * element of _enum_.
4363 *
4364 * The result enumerator yields the chunked elements as an array.
4365 * So +each+ method can be called as follows:
4366 *
4367 * enum.slice_after(pattern).each { |ary| ... }
4368 * enum.slice_after { |elt| bool }.each { |ary| ... }
4369 *
4370 * Other methods of the Enumerator class and Enumerable module,
4371 * such as +map+, etc., are also usable.
4372 *
4373 * For example, continuation lines (lines end with backslash) can be
4374 * concatenated as follows:
4375 *
4376 * lines = ["foo\n", "bar\\\n", "baz\n", "\n", "qux\n"]
4377 * e = lines.slice_after(/(?<!\\‍)\n\z/)
4378 * p e.to_a
4379 * #=> [["foo\n"], ["bar\\\n", "baz\n"], ["\n"], ["qux\n"]]
4380 * p e.map {|ll| ll[0...-1].map {|l| l.sub(/\\\n\z/, "") }.join + ll.last }
4381 * #=>["foo\n", "barbaz\n", "\n", "qux\n"]
4382 *
4383 */
4384
4385static VALUE
4386enum_slice_after(int argc, VALUE *argv, VALUE enumerable)
4387{
4389 VALUE pat = Qnil, pred = Qnil;
4390
4391 if (rb_block_given_p()) {
4392 if (0 < argc)
4393 rb_raise(rb_eArgError, "both pattern and block are given");
4394 pred = rb_block_proc();
4395 }
4396 else {
4397 rb_scan_args(argc, argv, "1", &pat);
4398 }
4399
4401 rb_ivar_set(enumerator, id_sliceafter_enum, enumerable);
4402 rb_ivar_set(enumerator, id_sliceafter_pat, pat);
4403 rb_ivar_set(enumerator, id_sliceafter_pred, pred);
4404
4405 rb_block_call(enumerator, idInitialize, 0, 0, sliceafter_i, enumerator);
4406 return enumerator;
4407}
4408
4410 VALUE pred;
4411 VALUE prev_elt;
4412 VALUE prev_elts;
4413 VALUE yielder;
4414 int inverted; /* 0 for slice_when and 1 for chunk_while. */
4415};
4416
4417static VALUE
4418slicewhen_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
4419{
4420#define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct slicewhen_arg, _memo)))
4421 struct slicewhen_arg *memo;
4422 int split_p;
4423 UPDATE_MEMO;
4424
4425 ENUM_WANT_SVALUE();
4426
4427 if (UNDEF_P(memo->prev_elt)) {
4428 /* The first element */
4429 memo->prev_elt = i;
4430 memo->prev_elts = rb_ary_new3(1, i);
4431 }
4432 else {
4433 VALUE args[2];
4434 args[0] = memo->prev_elt;
4435 args[1] = i;
4436 split_p = RTEST(rb_funcallv(memo->pred, id_call, 2, args));
4437 UPDATE_MEMO;
4438
4439 if (memo->inverted)
4440 split_p = !split_p;
4441
4442 if (split_p) {
4443 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4444 UPDATE_MEMO;
4445 memo->prev_elts = rb_ary_new3(1, i);
4446 }
4447 else {
4448 rb_ary_push(memo->prev_elts, i);
4449 }
4450
4451 memo->prev_elt = i;
4452 }
4453
4454 return Qnil;
4455#undef UPDATE_MEMO
4456}
4457
4458static VALUE
4460{
4461 VALUE enumerable;
4462 VALUE arg;
4463 struct slicewhen_arg *memo =
4464 NEW_PARTIAL_MEMO_FOR(struct slicewhen_arg, arg, inverted);
4465
4466 enumerable = rb_ivar_get(enumerator, id_slicewhen_enum);
4467 memo->pred = rb_attr_get(enumerator, id_slicewhen_pred);
4468 memo->prev_elt = Qundef;
4469 memo->prev_elts = Qnil;
4470 memo->yielder = yielder;
4471 memo->inverted = RTEST(rb_attr_get(enumerator, id_slicewhen_inverted));
4472
4473 rb_block_call(enumerable, id_each, 0, 0, slicewhen_ii, arg);
4474 memo = MEMO_FOR(struct slicewhen_arg, arg);
4475 if (!NIL_P(memo->prev_elts))
4476 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4477 /* &memo->prev_elts points into arg, and the call may trigger GC before
4478 * it reads the argument. */
4479 RB_GC_GUARD(arg);
4480 return Qnil;
4481}
4482
4483/*
4484 * call-seq:
4485 * enum.slice_when {|elt_before, elt_after| bool } -> an_enumerator
4486 *
4487 * Creates an enumerator for each chunked elements.
4488 * The beginnings of chunks are defined by the block.
4489 *
4490 * This method splits each chunk using adjacent elements,
4491 * _elt_before_ and _elt_after_,
4492 * in the receiver enumerator.
4493 * This method split chunks between _elt_before_ and _elt_after_ where
4494 * the block returns <code>true</code>.
4495 *
4496 * The block is called the length of the receiver enumerator minus one.
4497 *
4498 * The result enumerator yields the chunked elements as an array.
4499 * So +each+ method can be called as follows:
4500 *
4501 * enum.slice_when { |elt_before, elt_after| bool }.each { |ary| ... }
4502 *
4503 * Other methods of the Enumerator class and Enumerable module,
4504 * such as +to_a+, +map+, etc., are also usable.
4505 *
4506 * For example, one-by-one increasing subsequence can be chunked as follows:
4507 *
4508 * a = [1,2,4,9,10,11,12,15,16,19,20,21]
4509 * b = a.slice_when {|i, j| i+1 != j }
4510 * p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
4511 * c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
4512 * p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
4513 * d = c.join(",")
4514 * p d #=> "1,2,4,9-12,15,16,19-21"
4515 *
4516 * Near elements (threshold: 6) in sorted array can be chunked as follows:
4517 *
4518 * a = [3, 11, 14, 25, 28, 29, 29, 41, 55, 57]
4519 * p a.slice_when {|i, j| 6 < j - i }.to_a
4520 * #=> [[3], [11, 14], [25, 28, 29, 29], [41], [55, 57]]
4521 *
4522 * Increasing (non-decreasing) subsequence can be chunked as follows:
4523 *
4524 * a = [0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
4525 * p a.slice_when {|i, j| i > j }.to_a
4526 * #=> [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
4527 *
4528 * Adjacent evens and odds can be chunked as follows:
4529 * (Enumerable#chunk is another way to do it.)
4530 *
4531 * a = [7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
4532 * p a.slice_when {|i, j| i.even? != j.even? }.to_a
4533 * #=> [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
4534 *
4535 * Paragraphs (non-empty lines with trailing empty lines) can be chunked as follows:
4536 * (See Enumerable#chunk to ignore empty lines.)
4537 *
4538 * lines = ["foo\n", "bar\n", "\n", "baz\n", "qux\n"]
4539 * p lines.slice_when {|l1, l2| /\A\s*\z/ =~ l1 && /\S/ =~ l2 }.to_a
4540 * #=> [["foo\n", "bar\n", "\n"], ["baz\n", "qux\n"]]
4541 *
4542 * Enumerable#chunk_while does the same, except splitting when the block
4543 * returns <code>false</code> instead of <code>true</code>.
4544 */
4545static VALUE
4546enum_slice_when(VALUE enumerable)
4547{
4549 VALUE pred;
4550
4551 pred = rb_block_proc();
4552
4554 rb_ivar_set(enumerator, id_slicewhen_enum, enumerable);
4555 rb_ivar_set(enumerator, id_slicewhen_pred, pred);
4556 rb_ivar_set(enumerator, id_slicewhen_inverted, Qfalse);
4557
4558 rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
4559 return enumerator;
4560}
4561
4562/*
4563 * call-seq:
4564 * enum.chunk_while {|elt_before, elt_after| bool } -> an_enumerator
4565 *
4566 * Creates an enumerator for each chunked elements.
4567 * The beginnings of chunks are defined by the block.
4568 *
4569 * This method splits each chunk using adjacent elements,
4570 * _elt_before_ and _elt_after_,
4571 * in the receiver enumerator.
4572 * This method split chunks between _elt_before_ and _elt_after_ where
4573 * the block returns <code>false</code>.
4574 *
4575 * The block is called the length of the receiver enumerator minus one.
4576 *
4577 * The result enumerator yields the chunked elements as an array.
4578 * So +each+ method can be called as follows:
4579 *
4580 * enum.chunk_while { |elt_before, elt_after| bool }.each { |ary| ... }
4581 *
4582 * Other methods of the Enumerator class and Enumerable module,
4583 * such as +to_a+, +map+, etc., are also usable.
4584 *
4585 * For example, one-by-one increasing subsequence can be chunked as follows:
4586 *
4587 * a = [1,2,4,9,10,11,12,15,16,19,20,21]
4588 * b = a.chunk_while {|i, j| i+1 == j }
4589 * p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
4590 * c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
4591 * p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
4592 * d = c.join(",")
4593 * p d #=> "1,2,4,9-12,15,16,19-21"
4594 *
4595 * Increasing (non-decreasing) subsequence can be chunked as follows:
4596 *
4597 * a = [0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
4598 * p a.chunk_while {|i, j| i <= j }.to_a
4599 * #=> [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
4600 *
4601 * Adjacent evens and odds can be chunked as follows:
4602 * (Enumerable#chunk is another way to do it.)
4603 *
4604 * a = [7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
4605 * p a.chunk_while {|i, j| i.even? == j.even? }.to_a
4606 * #=> [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
4607 *
4608 * Enumerable#slice_when does the same, except splitting when the block
4609 * returns <code>true</code> instead of <code>false</code>.
4610 */
4611static VALUE
4612enum_chunk_while(VALUE enumerable)
4613{
4615 VALUE pred;
4616
4617 pred = rb_block_proc();
4618
4620 rb_ivar_set(enumerator, id_slicewhen_enum, enumerable);
4621 rb_ivar_set(enumerator, id_slicewhen_pred, pred);
4622 rb_ivar_set(enumerator, id_slicewhen_inverted, Qtrue);
4623
4624 rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
4625 return enumerator;
4626}
4627
4629 VALUE v, r;
4630 long n;
4631 double f, c;
4632 int block_given;
4633 int float_value;
4634};
4635
4636static void
4637sum_iter_normalize_memo(struct enum_sum_memo *memo)
4638{
4639 RUBY_ASSERT(FIXABLE(memo->n));
4640 memo->v = rb_fix_plus(LONG2FIX(memo->n), memo->v);
4641 memo->n = 0;
4642
4643 switch (TYPE(memo->r)) {
4644 case T_RATIONAL: memo->v = rb_rational_plus(memo->r, memo->v); break;
4645 case T_UNDEF: break;
4646 default: UNREACHABLE; /* or ...? */
4647 }
4648 memo->r = Qundef;
4649}
4650
4651static void
4652sum_iter_fixnum(VALUE i, struct enum_sum_memo *memo)
4653{
4654 memo->n += FIX2LONG(i); /* should not overflow long type */
4655 if (! FIXABLE(memo->n)) {
4656 memo->v = rb_big_plus(LONG2NUM(memo->n), memo->v);
4657 memo->n = 0;
4658 }
4659}
4660
4661static void
4662sum_iter_bignum(VALUE i, struct enum_sum_memo *memo)
4663{
4664 memo->v = rb_big_plus(i, memo->v);
4665}
4666
4667static void
4668sum_iter_rational(VALUE i, struct enum_sum_memo *memo)
4669{
4670 if (UNDEF_P(memo->r)) {
4671 memo->r = i;
4672 }
4673 else {
4674 memo->r = rb_rational_plus(memo->r, i);
4675 }
4676}
4677
4678static void
4679sum_iter_some_value(VALUE i, struct enum_sum_memo *memo)
4680{
4681 memo->v = rb_funcallv(memo->v, idPLUS, 1, &i);
4682}
4683
4684static void
4685sum_iter_Kahan_Babuska(VALUE i, struct enum_sum_memo *memo)
4686{
4687 /*
4688 * Kahan-Babuska balancing compensated summation algorithm
4689 * See https://link.springer.com/article/10.1007/s00607-005-0139-x
4690 */
4691 double x;
4692
4693 switch (TYPE(i)) {
4694 case T_FLOAT: x = RFLOAT_VALUE(i); break;
4695 case T_FIXNUM: x = FIX2LONG(i); break;
4696 case T_BIGNUM: x = rb_big2dbl(i); break;
4697 case T_RATIONAL: x = rb_num2dbl(i); break;
4698 default:
4699 memo->v = DBL2NUM(memo->f);
4700 memo->float_value = 0;
4701 sum_iter_some_value(i, memo);
4702 return;
4703 }
4704
4705 double f = memo->f;
4706
4707 if (isnan(f)) {
4708 return;
4709 }
4710 else if (! isfinite(x)) {
4711 if (isinf(x) && isinf(f) && signbit(x) != signbit(f)) {
4712 i = DBL2NUM(f);
4713 x = nan("");
4714 }
4715 memo->v = i;
4716 memo->f = x;
4717 return;
4718 }
4719 else if (isinf(f)) {
4720 return;
4721 }
4722
4723 double c = memo->c;
4724 double t = f + x;
4725
4726 if (fabs(f) >= fabs(x)) {
4727 c += ((f - t) + x);
4728 }
4729 else {
4730 c += ((x - t) + f);
4731 }
4732 f = t;
4733
4734 memo->f = f;
4735 memo->c = c;
4736}
4737
4738static void
4739sum_iter(VALUE i, struct enum_sum_memo *memo)
4740{
4741 RUBY_ASSERT(memo != NULL);
4742 if (memo->block_given) {
4743 i = rb_yield(i);
4744 }
4745
4746 if (memo->float_value) {
4747 sum_iter_Kahan_Babuska(i, memo);
4748 }
4749 else switch (TYPE(memo->v)) {
4750 default: sum_iter_some_value(i, memo); return;
4751 case T_FLOAT:
4752 case T_FIXNUM:
4753 case T_BIGNUM:
4754 case T_RATIONAL:
4755 switch (TYPE(i)) {
4756 case T_FIXNUM: sum_iter_fixnum(i, memo); return;
4757 case T_BIGNUM: sum_iter_bignum(i, memo); return;
4758 case T_RATIONAL: sum_iter_rational(i, memo); return;
4759 case T_FLOAT:
4760 sum_iter_normalize_memo(memo);
4761 memo->f = NUM2DBL(memo->v);
4762 memo->c = 0.0;
4763 memo->float_value = 1;
4764 sum_iter_Kahan_Babuska(i, memo);
4765 return;
4766 default:
4767 sum_iter_normalize_memo(memo);
4768 sum_iter_some_value(i, memo);
4769 return;
4770 }
4771 }
4772}
4773
4774static VALUE
4775enum_sum_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
4776{
4777 ENUM_WANT_SVALUE();
4778 sum_iter(i, MEMO_FOR(struct enum_sum_memo, args));
4779 return Qnil;
4780}
4781
4782static int
4783hash_sum_i(VALUE key, VALUE value, VALUE arg)
4784{
4785 sum_iter(rb_assoc_new(key, value), (struct enum_sum_memo *) arg);
4786 return ST_CONTINUE;
4787}
4788
4789static void
4790hash_sum(VALUE hash, struct enum_sum_memo *memo)
4791{
4793 RUBY_ASSERT(memo != NULL);
4794
4795 rb_hash_foreach(hash, hash_sum_i, (VALUE)memo);
4796}
4797
4798static VALUE
4799int_range_sum(VALUE beg, VALUE end, int excl, VALUE init)
4800{
4801 if (excl) {
4802 if (FIXNUM_P(end))
4803 end = LONG2FIX(FIX2LONG(end) - 1);
4804 else
4805 end = rb_big_minus(end, LONG2FIX(1));
4806 }
4807
4808 if (rb_int_ge(end, beg)) {
4809 VALUE a;
4810 a = rb_int_plus(rb_int_minus(end, beg), LONG2FIX(1));
4811 a = rb_int_mul(a, rb_int_plus(end, beg));
4812 a = rb_int_idiv(a, LONG2FIX(2));
4813 return rb_int_plus(init, a);
4814 }
4815
4816 return init;
4817}
4818
4819/*
4820 * call-seq:
4821 * sum(initial_value = 0) -> number
4822 * sum(initial_value = 0) {|element| ... } -> object
4823 *
4824 * With no block given,
4825 * returns the sum of +initial_value+ and the elements:
4826 *
4827 * (1..100).sum # => 5050
4828 * (1..100).sum(1) # => 5051
4829 * ('a'..'d').sum('foo') # => "fooabcd"
4830 *
4831 * Generally, the sum is computed using methods <tt>+</tt> and +each+;
4832 * for performance optimizations, those methods may not be used,
4833 * and so any redefinition of those methods may not have effect here.
4834 *
4835 * One such optimization: When possible, computes using Gauss's summation
4836 * formula <em>n(n+1)/2</em>:
4837 *
4838 * 100 * (100 + 1) / 2 # => 5050
4839 *
4840 * With a block given, calls the block with each element;
4841 * returns the sum of +initial_value+ and the block return values:
4842 *
4843 * (1..4).sum {|i| i*i } # => 30
4844 * (1..4).sum(100) {|i| i*i } # => 130
4845 * h = {a: 0, b: 1, c: 2, d: 3, e: 4, f: 5}
4846 * h.sum {|key, value| value.odd? ? value : 0 } # => 9
4847 * ('a'..'f').sum('x') {|c| c < 'd' ? c : '' } # => "xabc"
4848 *
4849 */
4850static VALUE
4851enum_sum(int argc, VALUE* argv, VALUE obj)
4852{
4853 struct enum_sum_memo memo;
4854 VALUE beg, end;
4855 int excl;
4856
4857 memo.v = (rb_check_arity(argc, 0, 1) == 0) ? LONG2FIX(0) : argv[0];
4858 memo.block_given = rb_block_given_p();
4859 memo.n = 0;
4860 memo.r = Qundef;
4861
4862 if ((memo.float_value = RB_FLOAT_TYPE_P(memo.v))) {
4863 memo.f = RFLOAT_VALUE(memo.v);
4864 memo.c = 0.0;
4865 }
4866 else {
4867 memo.f = 0.0;
4868 memo.c = 0.0;
4869 }
4870
4871 if (RTEST(rb_range_values(obj, &beg, &end, &excl))) {
4872 if (!memo.block_given && !memo.float_value &&
4873 (FIXNUM_P(beg) || RB_BIGNUM_TYPE_P(beg)) &&
4874 (FIXNUM_P(end) || RB_BIGNUM_TYPE_P(end))) {
4875 return int_range_sum(beg, end, excl, memo.v);
4876 }
4877 }
4878
4879 if (RB_TYPE_P(obj, T_HASH) &&
4880 rb_method_basic_definition_p(CLASS_OF(obj), id_each)) {
4881 hash_sum(obj, &memo);
4882 }
4883 else {
4884 VALUE arg;
4885 struct enum_sum_memo *m = NEW_PARTIAL_MEMO_FOR(struct enum_sum_memo, arg, n);
4886 *m = memo;
4887 rb_block_call(obj, id_each, 0, 0, enum_sum_i, arg);
4888 memo = *m;
4889 RB_GC_GUARD(arg);
4890 }
4891
4892 if (memo.float_value) {
4893 return DBL2NUM(memo.f + memo.c);
4894 }
4895 else {
4896 if (memo.n != 0)
4897 memo.v = rb_fix_plus(LONG2FIX(memo.n), memo.v);
4898 if (!UNDEF_P(memo.r)) {
4899 memo.v = rb_rational_plus(memo.r, memo.v);
4900 }
4901 return memo.v;
4902 }
4903}
4904
4905static VALUE
4906uniq_func(RB_BLOCK_CALL_FUNC_ARGLIST(i, set))
4907{
4908 ENUM_WANT_SVALUE();
4909 rb_set_add_no_check(set, i);
4910 return Qnil;
4911}
4912
4913static VALUE
4914uniq_iter(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
4915{
4916 ENUM_WANT_SVALUE();
4917 rb_hash_add_new_element(hash, rb_yield_values2(argc, argv), i);
4918 return Qnil;
4919}
4920
4921/*
4922 * call-seq:
4923 * uniq -> array
4924 * uniq {|element| ... } -> array
4925 *
4926 * With no block, returns a new array containing only unique elements;
4927 * the array has no two elements +e0+ and +e1+ such that <tt>e0.eql?(e1)</tt>:
4928 *
4929 * %w[a b c c b a a b c].uniq # => ["a", "b", "c"]
4930 * [0, 1, 2, 2, 1, 0, 0, 1, 2].uniq # => [0, 1, 2]
4931 *
4932 * With a block, returns a new array containing elements only for which the block
4933 * returns a unique value:
4934 *
4935 * a = [0, 1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
4936 * a.uniq {|i| i.even? ? i : 0 } # => [0, 2, 4]
4937 * a = %w[a b c d e e d c b a a b c d e]
4938 * a.uniq {|c| c < 'c' } # => ["a", "c"]
4939 *
4940 */
4941
4942static VALUE
4943enum_uniq(VALUE obj)
4944{
4945 VALUE ret;
4946 if (rb_block_given_p()) {
4947 VALUE hash = rb_obj_hide(rb_hash_new());
4948 rb_block_call(obj, id_each, 0, 0, uniq_iter, hash);
4949 ret = rb_hash_values(hash);
4950 rb_hash_clear(hash);
4951 }
4952 else {
4953 VALUE set = rb_obj_hide(rb_set_new());
4954 rb_block_call(obj, id_each, 0, 0, uniq_func, set);
4955 ret = rb_set_to_a(set);
4956 rb_set_clear(set);
4957 }
4958 return ret;
4959}
4960
4961static VALUE
4962compact_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
4963{
4964 ENUM_WANT_SVALUE();
4965
4966 if (!NIL_P(i)) {
4967 rb_ary_push(ary, i);
4968 }
4969 return Qnil;
4970}
4971
4972/*
4973 * call-seq:
4974 * compact -> array
4975 *
4976 * Returns an array of all non-+nil+ elements:
4977 *
4978 * a = [nil, 0, nil, 'a', false, nil, false, nil, 'a', nil, 0, nil]
4979 * a.compact # => [0, "a", false, false, "a", 0]
4980 *
4981 */
4982
4983static VALUE
4984enum_compact(VALUE obj)
4985{
4986 VALUE ary;
4987
4988 ary = rb_ary_new();
4989 rb_block_call(obj, id_each, 0, 0, compact_i, ary);
4990
4991 return ary;
4992}
4993
4994
4995/*
4996 * == What's Here
4997 *
4998 * Module \Enumerable provides methods that are useful to a collection class for:
4999 *
5000 * - {Querying}[rdoc-ref:Enumerable@Methods+for+Querying]
5001 * - {Fetching}[rdoc-ref:Enumerable@Methods+for+Fetching]
5002 * - {Searching and Filtering}[rdoc-ref:Enumerable@Methods+for+Searching+and+Filtering]
5003 * - {Sorting}[rdoc-ref:Enumerable@Methods+for+Sorting]
5004 * - {Iterating}[rdoc-ref:Enumerable@Methods+for+Iterating]
5005 * - {And more....}[rdoc-ref:Enumerable@Other+Methods]
5006 *
5007 * === Methods for Querying
5008 *
5009 * These methods return information about the \Enumerable other than the elements themselves:
5010 *
5011 * - #member? (aliased as #include?): Returns +true+ if <tt>self == object</tt>, +false+ otherwise.
5012 * - #all?: Returns +true+ if all elements meet a specified criterion; +false+ otherwise.
5013 * - #any?: Returns +true+ if any element meets a specified criterion; +false+ otherwise.
5014 * - #none?: Returns +true+ if no element meets a specified criterion; +false+ otherwise.
5015 * - #one?: Returns +true+ if exactly one element meets a specified criterion; +false+ otherwise.
5016 * - #count: Returns the count of elements,
5017 * based on an argument or block criterion, if given.
5018 * - #tally: Returns a new Hash containing the counts of occurrences of each element.
5019 *
5020 * === Methods for Fetching
5021 *
5022 * These methods return entries from the \Enumerable, without modifying it:
5023 *
5024 * <i>Leading, trailing, or all elements</i>:
5025 *
5026 * - #to_a (aliased as #entries): Returns all elements.
5027 * - #to_set: Returns a Set containing all elements.
5028 * - #first: Returns the first element or leading elements.
5029 * - #take: Returns a specified number of leading elements.
5030 * - #drop: Returns a specified number of trailing elements.
5031 * - #take_while: Returns leading elements as specified by the given block.
5032 * - #drop_while: Returns trailing elements as specified by the given block.
5033 *
5034 * <i>Minimum and maximum value elements</i>:
5035 *
5036 * - #min: Returns the elements whose values are smallest among the elements,
5037 * as determined by <tt>#<=></tt> or a given block.
5038 * - #max: Returns the elements whose values are largest among the elements,
5039 * as determined by <tt>#<=></tt> or a given block.
5040 * - #minmax: Returns a 2-element Array containing the smallest and largest elements.
5041 * - #min_by: Returns the smallest element, as determined by the given block.
5042 * - #max_by: Returns the largest element, as determined by the given block.
5043 * - #minmax_by: Returns the smallest and largest elements, as determined by the given block.
5044 *
5045 * <i>Groups, slices, and partitions</i>:
5046 *
5047 * - #group_by: Returns a Hash that partitions the elements into groups.
5048 * - #partition: Returns elements partitioned into two new Arrays, as determined by the given block.
5049 * - #slice_after: Returns a new Enumerator whose entries are a partition of +self+,
5050 * based either on a given +object+ or a given block.
5051 * - #slice_before: Returns a new Enumerator whose entries are a partition of +self+,
5052 * based either on a given +object+ or a given block.
5053 * - #slice_when: Returns a new Enumerator whose entries are a partition of +self+
5054 * based on the given block.
5055 * - #chunk: Returns elements organized into chunks as specified by the given block.
5056 * - #chunk_while: Returns elements organized into chunks as specified by the given block.
5057 *
5058 * === Methods for Searching and Filtering
5059 *
5060 * These methods return elements that meet a specified criterion:
5061 *
5062 * - #find (aliased as #detect): Returns an element selected by the block.
5063 * - #find_all (aliased as #filter, #select): Returns elements selected by the block.
5064 * - #find_index: Returns the index of an element selected by a given object or block.
5065 * - #reject: Returns elements not rejected by the block.
5066 * - #uniq: Returns elements that are not duplicates.
5067 *
5068 * === Methods for Sorting
5069 *
5070 * These methods return elements in sorted order:
5071 *
5072 * - #sort: Returns the elements, sorted by <tt>#<=></tt> or the given block.
5073 * - #sort_by: Returns the elements, sorted by the given block.
5074 *
5075 * === Methods for Iterating
5076 *
5077 * - #each_entry: Calls the block with each successive element
5078 * (slightly different from #each).
5079 * - #each_with_index: Calls the block with each successive element and its index.
5080 * - #each_with_object: Calls the block with each successive element and a given object.
5081 * - #each_slice: Calls the block with successive non-overlapping slices.
5082 * - #each_cons: Calls the block with successive overlapping slices.
5083 * (different from #each_slice).
5084 * - #reverse_each: Calls the block with each successive element, in reverse order.
5085 *
5086 * === Other Methods
5087 *
5088 * - #collect (aliased as #map): Returns objects returned by the block.
5089 * - #filter_map: Returns truthy objects returned by the block.
5090 * - #flat_map (aliased as #collect_concat): Returns flattened objects returned by the block.
5091 * - #grep: Returns elements selected by a given object
5092 * or objects returned by a given block.
5093 * - #grep_v: Returns elements not selected by a given object
5094 * or objects returned by a given block.
5095 * - #inject (aliased as #reduce): Returns the object formed by combining all elements.
5096 * - #sum: Returns the sum of the elements, using method <tt>+</tt>.
5097 * - #zip: Combines each element with elements from other enumerables;
5098 * returns the n-tuples or calls the block with each.
5099 * - #cycle: Calls the block with each element, cycling repeatedly.
5100 *
5101 * == Usage
5102 *
5103 * To use module \Enumerable in a collection class:
5104 *
5105 * - Include it:
5106 *
5107 * include Enumerable
5108 *
5109 * - Implement method <tt>#each</tt>
5110 * which must yield successive elements of the collection.
5111 * The method will be called by almost any \Enumerable method.
5112 *
5113 * Example:
5114 *
5115 * class Foo
5116 * include Enumerable
5117 * def each
5118 * yield 1
5119 * yield 1, 2
5120 * yield
5121 * end
5122 * end
5123 * Foo.new.each_entry{ |element| p element }
5124 *
5125 * Output:
5126 *
5127 * 1
5128 * [1, 2]
5129 * nil
5130 *
5131 * == \Enumerable in Ruby Classes
5132 *
5133 * These Ruby core classes include (or extend) \Enumerable:
5134 *
5135 * - ARGF
5136 * - Array
5137 * - Dir
5138 * - Enumerator
5139 * - ENV (extends)
5140 * - Hash
5141 * - IO
5142 * - Range
5143 * - Struct
5144 *
5145 * These Ruby standard library classes include \Enumerable:
5146 *
5147 * - CSV
5148 * - CSV::Table
5149 * - CSV::Row
5150 * - Set
5151 *
5152 * Virtually all methods in \Enumerable call method +#each+ in the including class:
5153 *
5154 * - <tt>Hash#each</tt> yields the next key-value pair as a 2-element Array.
5155 * - <tt>Struct#each</tt> yields the next name-value pair as a 2-element Array.
5156 * - For the other classes above, +#each+ yields the next object from the collection.
5157 *
5158 * == About the Examples
5159 *
5160 * The example code snippets for the \Enumerable methods:
5161 *
5162 * - Always show the use of one or more Array-like classes (often Array itself).
5163 * - Sometimes show the use of a Hash-like class.
5164 * For some methods, though, the usage would not make sense,
5165 * and so it is not shown. Example: #tally would find exactly one of each Hash entry.
5166 *
5167 * == Extended Methods
5168 *
5169 * A Enumerable class may define extended methods. This section describes the standard
5170 * behavior of extension methods for reference purposes.
5171 *
5172 * === #size
5173 *
5174 * \Enumerator has a #size method.
5175 * It uses the size function argument passed to +Enumerator.new+.
5176 *
5177 * e = Enumerator.new(-> { 3 }) {|y| p y; y.yield :a; y.yield :b; y.yield :c; :z }
5178 * p e.size #=> 3
5179 * p e.next #=> :a
5180 * p e.next #=> :b
5181 * p e.next #=> :c
5182 * begin
5183 * e.next
5184 * rescue StopIteration
5185 * p $!.result #=> :z
5186 * end
5187 *
5188 * The result of the size function should represent the number of iterations
5189 * (i.e., the number of times you yield to the block argument).
5190 * In the above example, the block calls #yield three times, and
5191 * the size function, +-> { 3 }+, returns 3 accordingly.
5192 * The result of the size function can be an integer, +Float::INFINITY+,
5193 * or +nil+.
5194 * An integer means the exact number of times #yield will be called,
5195 * as shown above.
5196 * +Float::INFINITY+ indicates an infinite number of #yield calls.
5197 * +nil+ means the number of #yield calls is difficult or impossible to
5198 * determine.
5199 *
5200 * Many iteration methods return an \Enumerator object with an
5201 * appropriate size function if no block is given.
5202 *
5203 * Examples:
5204 *
5205 * ["a", "b", "c"].each.size #=> 3
5206 * {a: "x", b: "y", c: "z"}.each.size #=> 3
5207 * (0..20).to_a.permutation.size #=> 51090942171709440000
5208 * loop.size #=> Float::INFINITY
5209 * (1..100).drop_while.size #=> nil # size depends on the block's behavior
5210 * STDIN.each.size #=> nil # cannot be computed without consuming input
5211 * File.open("/etc/resolv.conf").each.size #=> nil # cannot be computed without reading the file
5212 *
5213 * The behavior of #size for Range-based enumerators depends on the #begin element:
5214 *
5215 * - If the #begin element is an Integer, the #size method returns an Integer or +Float::INFINITY+.
5216 * - If the #begin element is an object with a #succ method (other than Integer), #size returns +nil+.
5217 * (Computing the size would require repeatedly calling #succ, which may be too slow.)
5218 * - If the #begin element does not have a #succ method, #size raises a TypeError.
5219 *
5220 * Examples:
5221 *
5222 * (10..42).each.size #=> 33
5223 * (10..42.9).each.size #=> 33 (the #end element may be a non-integer numeric)
5224 * (10..).each.size #=> Float::INFINITY
5225 * ("a".."z").each.size #=> nil
5226 * ("a"..).each.size #=> nil
5227 * (1.0..9.0).each.size # raises TypeError (Float does not have #succ)
5228 * (..10).each.size # raises TypeError (beginless range has nil as its #begin)
5229 *
5230 * The \Enumerable module itself does not define a #size method.
5231 * A class that includes \Enumerable may define its own #size method.
5232 * It is recommended that such a #size method be consistent with
5233 * Enumerator#size.
5234 *
5235 * Array and Hash implement #size and return values consistent with
5236 * Enumerator#size.
5237 * IO and Dir do not define #size, which is also consistent because the
5238 * corresponding enumerator's size function returns +nil+.
5239 *
5240 * However, it is not strictly required for a class's #size method to match Enumerator#size.
5241 * For example, File#size returns the number of bytes in the file, not the number of lines.
5242 *
5243 */
5244
5245void
5246Init_Enumerable(void)
5247{
5248 rb_mEnumerable = rb_define_module("Enumerable");
5249
5250 rb_define_method(rb_mEnumerable, "to_a", enum_to_a, -1);
5251 rb_define_method(rb_mEnumerable, "entries", enum_to_a, -1);
5252 rb_define_method(rb_mEnumerable, "to_h", enum_to_h, -1);
5253
5254 rb_define_method(rb_mEnumerable, "sort", enum_sort, 0);
5255 rb_define_method(rb_mEnumerable, "sort_by", enum_sort_by, 0);
5256 rb_define_method(rb_mEnumerable, "grep", enum_grep, 1);
5257 rb_define_method(rb_mEnumerable, "grep_v", enum_grep_v, 1);
5258 rb_define_method(rb_mEnumerable, "count", enum_count, -1);
5259 rb_define_method(rb_mEnumerable, "find", enum_find, -1);
5260 rb_define_method(rb_mEnumerable, "detect", enum_find, -1);
5261 rb_define_method(rb_mEnumerable, "find_index", enum_find_index, -1);
5262 rb_define_method(rb_mEnumerable, "find_all", enum_find_all, 0);
5263 rb_define_method(rb_mEnumerable, "select", enum_find_all, 0);
5264 rb_define_method(rb_mEnumerable, "filter", enum_find_all, 0);
5265 rb_define_method(rb_mEnumerable, "filter_map", enum_filter_map, 0);
5266 rb_define_method(rb_mEnumerable, "reject", enum_reject, 0);
5267 rb_define_method(rb_mEnumerable, "collect", enum_collect, 0);
5268 rb_define_method(rb_mEnumerable, "map", enum_collect, 0);
5269 rb_define_method(rb_mEnumerable, "flat_map", enum_flat_map, 0);
5270 rb_define_method(rb_mEnumerable, "collect_concat", enum_flat_map, 0);
5271 rb_define_method(rb_mEnumerable, "inject", enum_inject, -1);
5272 rb_define_method(rb_mEnumerable, "reduce", enum_inject, -1);
5273 rb_define_method(rb_mEnumerable, "partition", enum_partition, 0);
5274 rb_define_method(rb_mEnumerable, "group_by", enum_group_by, 0);
5275 rb_define_method(rb_mEnumerable, "tally", enum_tally, -1);
5276 rb_define_method(rb_mEnumerable, "first", enum_first, -1);
5277 rb_define_method(rb_mEnumerable, "all?", enum_all, -1);
5278 rb_define_method(rb_mEnumerable, "any?", enum_any, -1);
5279 rb_define_method(rb_mEnumerable, "one?", enum_one, -1);
5280 rb_define_method(rb_mEnumerable, "none?", enum_none, -1);
5281 rb_define_method(rb_mEnumerable, "min", enum_min, -1);
5282 rb_define_method(rb_mEnumerable, "max", enum_max, -1);
5283 rb_define_method(rb_mEnumerable, "minmax", enum_minmax, 0);
5284 rb_define_method(rb_mEnumerable, "min_by", enum_min_by, -1);
5285 rb_define_method(rb_mEnumerable, "max_by", enum_max_by, -1);
5286 rb_define_method(rb_mEnumerable, "minmax_by", enum_minmax_by, 0);
5287 rb_define_method(rb_mEnumerable, "member?", enum_member, 1);
5288 rb_define_method(rb_mEnumerable, "include?", enum_member, 1);
5289 rb_define_method(rb_mEnumerable, "each_with_index", enum_each_with_index, -1);
5290 rb_define_method(rb_mEnumerable, "reverse_each", enum_reverse_each, -1);
5291 rb_define_method(rb_mEnumerable, "each_entry", enum_each_entry, -1);
5292 rb_define_method(rb_mEnumerable, "each_slice", enum_each_slice, 1);
5293 rb_define_method(rb_mEnumerable, "each_cons", enum_each_cons, 1);
5294 rb_define_method(rb_mEnumerable, "each_with_object", enum_each_with_object, 1);
5295 rb_define_method(rb_mEnumerable, "zip", enum_zip, -1);
5296 rb_define_method(rb_mEnumerable, "take", enum_take, 1);
5297 rb_define_method(rb_mEnumerable, "take_while", enum_take_while, 0);
5298 rb_define_method(rb_mEnumerable, "drop", enum_drop, 1);
5299 rb_define_method(rb_mEnumerable, "drop_while", enum_drop_while, 0);
5300 rb_define_method(rb_mEnumerable, "cycle", enum_cycle, -1);
5301 rb_define_method(rb_mEnumerable, "chunk", enum_chunk, 0);
5302 rb_define_method(rb_mEnumerable, "slice_before", enum_slice_before, -1);
5303 rb_define_method(rb_mEnumerable, "slice_after", enum_slice_after, -1);
5304 rb_define_method(rb_mEnumerable, "slice_when", enum_slice_when, 0);
5305 rb_define_method(rb_mEnumerable, "chunk_while", enum_chunk_while, 0);
5306 rb_define_method(rb_mEnumerable, "sum", enum_sum, -1);
5307 rb_define_method(rb_mEnumerable, "uniq", enum_uniq, 0);
5308 rb_define_method(rb_mEnumerable, "compact", enum_compact, 0);
5309
5310 id__alone = rb_intern_const("_alone");
5311 id__separator = rb_intern_const("_separator");
5312 id_chunk_categorize = rb_intern_const("chunk_categorize");
5313 id_chunk_enumerable = rb_intern_const("chunk_enumerable");
5314 id_next = rb_intern_const("next");
5315 id_sliceafter_enum = rb_intern_const("sliceafter_enum");
5316 id_sliceafter_pat = rb_intern_const("sliceafter_pat");
5317 id_sliceafter_pred = rb_intern_const("sliceafter_pred");
5318 id_slicebefore_enumerable = rb_intern_const("slicebefore_enumerable");
5319 id_slicebefore_sep_pat = rb_intern_const("slicebefore_sep_pat");
5320 id_slicebefore_sep_pred = rb_intern_const("slicebefore_sep_pred");
5321 id_slicewhen_enum = rb_intern_const("slicewhen_enum");
5322 id_slicewhen_inverted = rb_intern_const("slicewhen_inverted");
5323 id_slicewhen_pred = rb_intern_const("slicewhen_pred");
5324}
#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:3407
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1042
#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 FIXNUM_FLAG
Old name of RUBY_FIXNUM_FLAG.
#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:2432
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:2264
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:230
double rb_num2dbl(VALUE num)
Converts an instance of rb_cNumeric into C's double.
Definition object.c:3845
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:504
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1162
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:1120
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:1213
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_hash_new(void)
Creates a new, empty hash object.
Definition hash.c:1670
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:1588
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1859
VALUE rb_set_clear(VALUE set)
Removes all entries from set.
Definition set.c:2408
VALUE rb_set_new(void)
Creates a new, empty set object.
Definition set.c:2384
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:3107
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:2177
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:1656
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3772
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:3650
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:729
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:3756
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:1334
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1191
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:1432
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:1454
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1409
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:1601
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
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:51
#define RARRAY_PTR_USE(ary, ptr_name, expr)
Declares a section of code where raw pointers are used.
Definition rarray.h:323
static VALUE * RARRAY_PTR(VALUE ary)
Wild use of a C pointer.
Definition rarray.h:341
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:398
static void RARRAY_ASET(VALUE ary, rb_len_t i, VALUE v)
Assigns an object in an array.
Definition rarray.h:362
#define 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:126
Definition enum.c:2419
Definition enum.c:2296
IFUNC (Internal FUNCtion).
Definition imemo.h:90
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