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