Ruby: enum.c Source File

Ruby 3.3.6p108 (2024-11-05 revision 75015d4c1f6965b5e85e96fb309f1f2129f933c0)

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