Ruby 3.5.0dev (2025-04-25 revision 62a7f17157c5c67956d95a2582f8f256df13f9e2)
enum.c (62a7f17157c5c67956d95a2582f8f256df13f9e2)
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{
329 struct MEMO *memo = MEMO_CAST(memop);
330 MEMO_V1_SET(memo, i);
331 memo->u3.cnt = 1;
333}
334
335static VALUE
336find_i_fast(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
337{
338 if (RTEST(rb_yield_values2(argc, argv))) {
339 ENUM_WANT_SVALUE();
340 found(i, memop);
341 }
342 return Qnil;
343}
344
345static VALUE
346find_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
347{
348 ENUM_WANT_SVALUE();
349
350 if (RTEST(enum_yield(argc, i))) {
351 found(i, memop);
352 }
353 return Qnil;
354}
355
356/*
357 * call-seq:
358 * find(if_none_proc = nil) {|element| ... } -> object or nil
359 * find(if_none_proc = nil) -> enumerator
360 *
361 * Returns the first element for which the block returns a truthy value.
362 *
363 * With a block given, calls the block with successive elements of the collection;
364 * returns the first element for which the block returns a truthy value:
365 *
366 * (0..9).find {|element| element > 2} # => 3
367 *
368 * If no such element is found, calls +if_none_proc+ and returns its return value.
369 *
370 * (0..9).find(proc {false}) {|element| element > 12} # => false
371 * {foo: 0, bar: 1, baz: 2}.find {|key, value| key.start_with?('b') } # => [:bar, 1]
372 * {foo: 0, bar: 1, baz: 2}.find(proc {[]}) {|key, value| key.start_with?('c') } # => []
373 *
374 * With no block given, returns an Enumerator.
375 *
376 */
377static VALUE
378enum_find(int argc, VALUE *argv, VALUE obj)
379{
380 struct MEMO *memo;
381 VALUE if_none;
382
383 if_none = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
384 RETURN_ENUMERATOR(obj, argc, argv);
385 memo = MEMO_NEW(Qundef, 0, 0);
386 if (rb_block_pair_yield_optimizable())
387 rb_block_call2(obj, id_each, 0, 0, find_i_fast, (VALUE)memo, RB_BLOCK_NO_USE_PACKED_ARGS);
388 else
389 rb_block_call2(obj, id_each, 0, 0, find_i, (VALUE)memo, RB_BLOCK_NO_USE_PACKED_ARGS);
390 if (memo->u3.cnt) {
391 return memo->v1;
392 }
393 if (!NIL_P(if_none)) {
394 return rb_funcallv(if_none, id_call, 0, 0);
395 }
396 return Qnil;
397}
398
399static VALUE
400find_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
401{
402 struct MEMO *memo = MEMO_CAST(memop);
403
404 ENUM_WANT_SVALUE();
405
406 if (rb_equal(i, memo->v2)) {
407 MEMO_V1_SET(memo, imemo_count_value(memo));
409 }
410 imemo_count_up(memo);
411 return Qnil;
412}
413
414static VALUE
415find_index_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
416{
417 struct MEMO *memo = MEMO_CAST(memop);
418
419 if (RTEST(rb_yield_values2(argc, argv))) {
420 MEMO_V1_SET(memo, imemo_count_value(memo));
422 }
423 imemo_count_up(memo);
424 return Qnil;
425}
426
427/*
428 * call-seq:
429 * find_index(object) -> integer or nil
430 * find_index {|element| ... } -> integer or nil
431 * find_index -> enumerator
432 *
433 * Returns the index of the first element that meets a specified criterion,
434 * or +nil+ if no such element is found.
435 *
436 * With argument +object+ given,
437 * returns the index of the first element that is <tt>==</tt> +object+:
438 *
439 * ['a', 'b', 'c', 'b'].find_index('b') # => 1
440 *
441 * With a block given, calls the block with successive elements;
442 * returns the first element for which the block returns a truthy value:
443 *
444 * ['a', 'b', 'c', 'b'].find_index {|element| element.start_with?('b') } # => 1
445 * {foo: 0, bar: 1, baz: 2}.find_index {|key, value| value > 1 } # => 2
446 *
447 * With no argument and no block given, returns an Enumerator.
448 *
449 */
450
451static VALUE
452enum_find_index(int argc, VALUE *argv, VALUE obj)
453{
454 struct MEMO *memo; /* [return value, current index, ] */
455 VALUE condition_value = Qnil;
456 rb_block_call_func *func;
457
458 if (argc == 0) {
459 RETURN_ENUMERATOR(obj, 0, 0);
460 func = find_index_iter_i;
461 }
462 else {
463 rb_scan_args(argc, argv, "1", &condition_value);
464 if (rb_block_given_p()) {
465 rb_warn("given block not used");
466 }
467 func = find_index_i;
468 }
469
470 memo = MEMO_NEW(Qnil, condition_value, 0);
471 rb_block_call(obj, id_each, 0, 0, func, (VALUE)memo);
472 return memo->v1;
473}
474
475static VALUE
476find_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
477{
478 ENUM_WANT_SVALUE();
479
480 if (RTEST(enum_yield(argc, i))) {
481 rb_ary_push(ary, i);
482 }
483 return Qnil;
484}
485
486static VALUE
487enum_size(VALUE self, VALUE args, VALUE eobj)
488{
489 return rb_check_funcall_default(self, id_size, 0, 0, Qnil);
490}
491
492static long
493limit_by_enum_size(VALUE obj, long n)
494{
495 unsigned long limit;
496 VALUE size = rb_check_funcall(obj, id_size, 0, 0);
497 if (!FIXNUM_P(size)) return n;
498 limit = FIX2ULONG(size);
499 return ((unsigned long)n > limit) ? (long)limit : n;
500}
501
502static int
503enum_size_over_p(VALUE obj, long n)
504{
505 VALUE size = rb_check_funcall(obj, id_size, 0, 0);
506 if (!FIXNUM_P(size)) return 0;
507 return ((unsigned long)n > FIX2ULONG(size));
508}
509
510/*
511 * call-seq:
512 * select {|element| ... } -> array
513 * select -> enumerator
514 *
515 * Returns an array containing elements selected by the block.
516 *
517 * With a block given, calls the block with successive elements;
518 * returns an array of those elements for which the block returns a truthy value:
519 *
520 * (0..9).select {|element| element % 3 == 0 } # => [0, 3, 6, 9]
521 * a = {foo: 0, bar: 1, baz: 2}.select {|key, value| key.start_with?('b') }
522 * a # => {:bar=>1, :baz=>2}
523 *
524 * With no block given, returns an Enumerator.
525 *
526 * Related: #reject.
527 */
528static VALUE
529enum_find_all(VALUE obj)
530{
531 VALUE ary;
532
533 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
534
535 ary = rb_ary_new();
536 rb_block_call(obj, id_each, 0, 0, find_all_i, ary);
537
538 return ary;
539}
540
541static VALUE
542filter_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
543{
544 i = rb_yield_values2(argc, argv);
545
546 if (RTEST(i)) {
547 rb_ary_push(ary, i);
548 }
549
550 return Qnil;
551}
552
553/*
554 * call-seq:
555 * filter_map {|element| ... } -> array
556 * filter_map -> enumerator
557 *
558 * Returns an array containing truthy elements returned by the block.
559 *
560 * With a block given, calls the block with successive elements;
561 * returns an array containing each truthy value returned by the block:
562 *
563 * (0..9).filter_map {|i| i * 2 if i.even? } # => [0, 4, 8, 12, 16]
564 * {foo: 0, bar: 1, baz: 2}.filter_map {|key, value| key if value.even? } # => [:foo, :baz]
565 *
566 * When no block given, returns an Enumerator.
567 *
568 */
569static VALUE
570enum_filter_map(VALUE obj)
571{
572 VALUE ary;
573
574 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
575
576 ary = rb_ary_new();
577 rb_block_call(obj, id_each, 0, 0, filter_map_i, ary);
578
579 return ary;
580}
581
582
583static VALUE
584reject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
585{
586 ENUM_WANT_SVALUE();
587
588 if (!RTEST(enum_yield(argc, i))) {
589 rb_ary_push(ary, i);
590 }
591 return Qnil;
592}
593
594/*
595 * call-seq:
596 * reject {|element| ... } -> array
597 * reject -> enumerator
598 *
599 * Returns an array of objects rejected by the block.
600 *
601 * With a block given, calls the block with successive elements;
602 * returns an array of those elements for which the block returns +nil+ or +false+:
603 *
604 * (0..9).reject {|i| i * 2 if i.even? } # => [1, 3, 5, 7, 9]
605 * {foo: 0, bar: 1, baz: 2}.reject {|key, value| key if value.odd? } # => {:foo=>0, :baz=>2}
606 *
607 * When no block given, returns an Enumerator.
608 *
609 * Related: #select.
610 */
611
612static VALUE
613enum_reject(VALUE obj)
614{
615 VALUE ary;
616
617 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
618
619 ary = rb_ary_new();
620 rb_block_call(obj, id_each, 0, 0, reject_i, ary);
621
622 return ary;
623}
624
625static VALUE
626collect_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
627{
628 rb_ary_push(ary, rb_yield_values2(argc, argv));
629
630 return Qnil;
631}
632
633static VALUE
634collect_all(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
635{
636 rb_ary_push(ary, rb_enum_values_pack(argc, argv));
637
638 return Qnil;
639}
640
641/*
642 * call-seq:
643 * map {|element| ... } -> array
644 * map -> enumerator
645 *
646 * Returns an array of objects returned by the block.
647 *
648 * With a block given, calls the block with successive elements;
649 * returns an array of the objects returned by the block:
650 *
651 * (0..4).map {|i| i*i } # => [0, 1, 4, 9, 16]
652 * {foo: 0, bar: 1, baz: 2}.map {|key, value| value*2} # => [0, 2, 4]
653 *
654 * With no block given, returns an Enumerator.
655 *
656 */
657static VALUE
658enum_collect(VALUE obj)
659{
660 VALUE ary;
661 int min_argc, max_argc;
662
663 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
664
665 ary = rb_ary_new();
666 min_argc = rb_block_min_max_arity(&max_argc);
667 rb_lambda_call(obj, id_each, 0, 0, collect_i, min_argc, max_argc, ary);
668
669 return ary;
670}
671
672static VALUE
673flat_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
674{
675 VALUE tmp;
676
677 i = rb_yield_values2(argc, argv);
678 tmp = rb_check_array_type(i);
679
680 if (NIL_P(tmp)) {
681 rb_ary_push(ary, i);
682 }
683 else {
684 rb_ary_concat(ary, tmp);
685 }
686 return Qnil;
687}
688
689/*
690 * call-seq:
691 * flat_map {|element| ... } -> array
692 * flat_map -> enumerator
693 *
694 * Returns an array of flattened objects returned by the block.
695 *
696 * With a block given, calls the block with successive elements;
697 * returns a flattened array of objects returned by the block:
698 *
699 * [0, 1, 2, 3].flat_map {|element| -element } # => [0, -1, -2, -3]
700 * [0, 1, 2, 3].flat_map {|element| [element, -element] } # => [0, 0, 1, -1, 2, -2, 3, -3]
701 * [[0, 1], [2, 3]].flat_map {|e| e + [100] } # => [0, 1, 100, 2, 3, 100]
702 * {foo: 0, bar: 1, baz: 2}.flat_map {|key, value| [key, value] } # => [:foo, 0, :bar, 1, :baz, 2]
703 *
704 * With no block given, returns an Enumerator.
705 *
706 * Alias: #collect_concat.
707 */
708static VALUE
709enum_flat_map(VALUE obj)
710{
711 VALUE ary;
712
713 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
714
715 ary = rb_ary_new();
716 rb_block_call(obj, id_each, 0, 0, flat_map_i, ary);
717
718 return ary;
719}
720
721/*
722 * call-seq:
723 * to_a(*args) -> array
724 *
725 * Returns an array containing the items in +self+:
726 *
727 * (0..4).to_a # => [0, 1, 2, 3, 4]
728 *
729 */
730static VALUE
731enum_to_a(int argc, VALUE *argv, VALUE obj)
732{
733 VALUE ary = rb_ary_new();
734
735 rb_block_call_kw(obj, id_each, argc, argv, collect_all, ary, RB_PASS_CALLED_KEYWORDS);
736
737 return ary;
738}
739
740static VALUE
741enum_hashify_into(VALUE obj, int argc, const VALUE *argv, rb_block_call_func *iter, VALUE hash)
742{
743 rb_block_call(obj, id_each, argc, argv, iter, hash);
744 return hash;
745}
746
747static VALUE
748enum_hashify(VALUE obj, int argc, const VALUE *argv, rb_block_call_func *iter)
749{
750 return enum_hashify_into(obj, argc, argv, iter, rb_hash_new());
751}
752
753static VALUE
754enum_to_h_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
755{
756 ENUM_WANT_SVALUE();
757 return rb_hash_set_pair(hash, i);
758}
759
760static VALUE
761enum_to_h_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
762{
763 return rb_hash_set_pair(hash, rb_yield_values2(argc, argv));
764}
765
766/*
767 * call-seq:
768 * to_h(*args) -> hash
769 * to_h(*args) {|element| ... } -> hash
770 *
771 * When +self+ consists of 2-element arrays,
772 * returns a hash each of whose entries is the key-value pair
773 * formed from one of those arrays:
774 *
775 * [[:foo, 0], [:bar, 1], [:baz, 2]].to_h # => {:foo=>0, :bar=>1, :baz=>2}
776 *
777 * When a block is given, the block is called with each element of +self+;
778 * the block should return a 2-element array which becomes a key-value pair
779 * in the returned hash:
780 *
781 * (0..3).to_h {|i| [i, i ** 2]} # => {0=>0, 1=>1, 2=>4, 3=>9}
782 *
783 * Raises an exception if an element of +self+ is not a 2-element array,
784 * and a block is not passed.
785 */
786
787static VALUE
788enum_to_h(int argc, VALUE *argv, VALUE obj)
789{
790 rb_block_call_func *iter = rb_block_given_p() ? enum_to_h_ii : enum_to_h_i;
791 return enum_hashify(obj, argc, argv, iter);
792}
793
794static VALUE
795inject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
796{
797 struct MEMO *memo = MEMO_CAST(p);
798
799 ENUM_WANT_SVALUE();
800
801 if (UNDEF_P(memo->v1)) {
802 MEMO_V1_SET(memo, i);
803 }
804 else {
805 MEMO_V1_SET(memo, rb_yield_values(2, memo->v1, i));
806 }
807 return Qnil;
808}
809
810static VALUE
811inject_op_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
812{
813 struct MEMO *memo = MEMO_CAST(p);
814 VALUE name;
815
816 ENUM_WANT_SVALUE();
817
818 if (UNDEF_P(memo->v1)) {
819 MEMO_V1_SET(memo, i);
820 }
821 else if (SYMBOL_P(name = memo->u3.value)) {
822 const ID mid = SYM2ID(name);
823 MEMO_V1_SET(memo, rb_funcallv_public(memo->v1, mid, 1, &i));
824 }
825 else {
826 VALUE args[2];
827 args[0] = name;
828 args[1] = i;
829 MEMO_V1_SET(memo, rb_f_send(numberof(args), args, memo->v1));
830 }
831 return Qnil;
832}
833
834static VALUE
835ary_inject_op(VALUE ary, VALUE init, VALUE op)
836{
837 ID id;
838 VALUE v, e;
839 long i, n;
840
841 if (RARRAY_LEN(ary) == 0)
842 return UNDEF_P(init) ? Qnil : init;
843
844 if (UNDEF_P(init)) {
845 v = RARRAY_AREF(ary, 0);
846 i = 1;
847 if (RARRAY_LEN(ary) == 1)
848 return v;
849 }
850 else {
851 v = init;
852 i = 0;
853 }
854
855 id = SYM2ID(op);
856 if (id == idPLUS) {
857 if (RB_INTEGER_TYPE_P(v) &&
858 rb_method_basic_definition_p(rb_cInteger, idPLUS) &&
859 rb_obj_respond_to(v, idPLUS, FALSE)) {
860 n = 0;
861 for (; i < RARRAY_LEN(ary); i++) {
862 e = RARRAY_AREF(ary, i);
863 if (FIXNUM_P(e)) {
864 n += FIX2LONG(e); /* should not overflow long type */
865 if (!FIXABLE(n)) {
866 v = rb_big_plus(LONG2NUM(n), v);
867 n = 0;
868 }
869 }
870 else if (RB_BIGNUM_TYPE_P(e))
871 v = rb_big_plus(e, v);
872 else
873 goto not_integer;
874 }
875 if (n != 0)
876 v = rb_fix_plus(LONG2FIX(n), v);
877 return v;
878
879 not_integer:
880 if (n != 0)
881 v = rb_fix_plus(LONG2FIX(n), v);
882 }
883 }
884 for (; i < RARRAY_LEN(ary); i++) {
885 VALUE arg = RARRAY_AREF(ary, i);
886 v = rb_funcallv_public(v, id, 1, &arg);
887 }
888 return v;
889}
890
891/*
892 * call-seq:
893 * inject(symbol) -> object
894 * inject(initial_value, symbol) -> object
895 * inject {|memo, value| ... } -> object
896 * inject(initial_value) {|memo, value| ... } -> object
897 *
898 * Returns the result of applying a reducer to an initial value and
899 * the first element of the Enumerable. It then takes the result and applies the
900 * function to it and the second element of the collection, and so on. The
901 * return value is the result returned by the final call to the function.
902 *
903 * You can think of
904 *
905 * [ a, b, c, d ].inject(i) { |r, v| fn(r, v) }
906 *
907 * as being
908 *
909 * fn(fn(fn(fn(i, a), b), c), d)
910 *
911 * In a way the +inject+ function _injects_ the function
912 * between the elements of the enumerable.
913 *
914 * +inject+ is aliased as +reduce+. You use it when you want to
915 * _reduce_ a collection to a single value.
916 *
917 * <b>The Calling Sequences</b>
918 *
919 * Let's start with the most verbose:
920 *
921 * enum.inject(initial_value) do |result, next_value|
922 * # do something with +result+ and +next_value+
923 * # the value returned by the block becomes the
924 * # value passed in to the next iteration
925 * # as +result+
926 * end
927 *
928 * For example:
929 *
930 * product = [ 2, 3, 4 ].inject(1) do |result, next_value|
931 * result * next_value
932 * end
933 * product #=> 24
934 *
935 * When this runs, the block is first called with +1+ (the initial value) and
936 * +2+ (the first element of the array). The block returns <tt>1*2</tt>, so on
937 * the next iteration the block is called with +2+ (the previous result) and
938 * +3+. The block returns +6+, and is called one last time with +6+ and +4+.
939 * The result of the block, +24+ becomes the value returned by +inject+. This
940 * code returns the product of the elements in the enumerable.
941 *
942 * <b>First Shortcut: Default Initial value</b>
943 *
944 * In the case of the previous example, the initial value, +1+, wasn't really
945 * necessary: the calculation of the product of a list of numbers is self-contained.
946 *
947 * In these circumstances, you can omit the +initial_value+ parameter. +inject+
948 * will then initially call the block with the first element of the collection
949 * as the +result+ parameter and the second element as the +next_value+.
950 *
951 * [ 2, 3, 4 ].inject do |result, next_value|
952 * result * next_value
953 * end
954 *
955 * This shortcut is convenient, but can only be used when the block produces a result
956 * which can be passed back to it as a first parameter.
957 *
958 * Here's an example where that's not the case: it returns a hash where the keys are words
959 * and the values are the number of occurrences of that word in the enumerable.
960 *
961 * freqs = File.read("README.md")
962 * .scan(/\w{2,}/)
963 * .reduce(Hash.new(0)) do |counts, word|
964 * counts[word] += 1
965 * counts
966 * end
967 * freqs #=> {"Actions"=>4,
968 * "Status"=>5,
969 * "MinGW"=>3,
970 * "https"=>27,
971 * "github"=>10,
972 * "com"=>15, ...
973 *
974 * Note that the last line of the block is just the word +counts+. This ensures the
975 * return value of the block is the result that's being calculated.
976 *
977 * <b>Second Shortcut: a Reducer function</b>
978 *
979 * A <i>reducer function</i> is a function that takes a partial result and the next value,
980 * returning the next partial result. The block that is given to +inject+ is a reducer.
981 *
982 * You can also write a reducer as a function and pass the name of that function
983 * (as a symbol) to +inject+. However, for this to work, the function
984 *
985 * 1. Must be defined on the type of the result value
986 * 2. Must accept a single parameter, the next value in the collection, and
987 * 3. Must return an updated result which will also implement the function.
988 *
989 * Here's an example that adds elements to a string. The two calls invoke the functions
990 * String#concat and String#+ on the result so far, passing it the next value.
991 *
992 * s = [ "cat", " ", "dog" ].inject("", :concat)
993 * s #=> "cat dog"
994 * s = [ "cat", " ", "dog" ].inject("The result is:", :+)
995 * s #=> "The result is: cat dog"
996 *
997 * Here's a more complex example when the result object maintains
998 * state of a different type to the enumerable elements.
999 *
1000 * class Turtle
1001 *
1002 * def initialize
1003 * @x = @y = 0
1004 * end
1005 *
1006 * def move(dir)
1007 * case dir
1008 * when "n" then @y += 1
1009 * when "s" then @y -= 1
1010 * when "e" then @x += 1
1011 * when "w" then @x -= 1
1012 * end
1013 * self
1014 * end
1015 * end
1016 *
1017 * position = "nnneesw".chars.reduce(Turtle.new, :move)
1018 * position #=>> #<Turtle:0x00000001052f4698 @y=2, @x=1>
1019 *
1020 * <b>Third Shortcut: Reducer With no Initial Value</b>
1021 *
1022 * If your reducer returns a value that it can accept as a parameter, then you
1023 * don't have to pass in an initial value. Here <tt>:*</tt> is the name of the
1024 * _times_ function:
1025 *
1026 * product = [ 2, 3, 4 ].inject(:*)
1027 * product # => 24
1028 *
1029 * String concatenation again:
1030 *
1031 * s = [ "cat", " ", "dog" ].inject(:+)
1032 * s #=> "cat dog"
1033 *
1034 * And an example that converts a hash to an array of two-element subarrays.
1035 *
1036 * nested = {foo: 0, bar: 1}.inject([], :push)
1037 * nested # => [[:foo, 0], [:bar, 1]]
1038 *
1039 *
1040 */
1041static VALUE
1042enum_inject(int argc, VALUE *argv, VALUE obj)
1043{
1044 struct MEMO *memo;
1045 VALUE init, op;
1046 rb_block_call_func *iter = inject_i;
1047 ID id;
1048 int num_args;
1049
1050 if (rb_block_given_p()) {
1051 num_args = rb_scan_args(argc, argv, "02", &init, &op);
1052 }
1053 else {
1054 num_args = rb_scan_args(argc, argv, "11", &init, &op);
1055 }
1056
1057 switch (num_args) {
1058 case 0:
1059 init = Qundef;
1060 break;
1061 case 1:
1062 if (rb_block_given_p()) {
1063 break;
1064 }
1065 id = rb_check_id(&init);
1066 op = id ? ID2SYM(id) : init;
1067 init = Qundef;
1068 iter = inject_op_i;
1069 break;
1070 case 2:
1071 if (rb_block_given_p()) {
1072 rb_warning("given block not used");
1073 }
1074 id = rb_check_id(&op);
1075 if (id) op = ID2SYM(id);
1076 iter = inject_op_i;
1077 break;
1078 }
1079
1080 if (iter == inject_op_i &&
1081 SYMBOL_P(op) &&
1082 RB_TYPE_P(obj, T_ARRAY) &&
1083 rb_method_basic_definition_p(CLASS_OF(obj), id_each)) {
1084 return ary_inject_op(obj, init, op);
1085 }
1086
1087 memo = MEMO_NEW(init, Qnil, op);
1088 rb_block_call(obj, id_each, 0, 0, iter, (VALUE)memo);
1089 if (UNDEF_P(memo->v1)) return Qnil;
1090 return memo->v1;
1091}
1092
1093static VALUE
1094partition_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, arys))
1095{
1096 struct MEMO *memo = MEMO_CAST(arys);
1097 VALUE ary;
1098 ENUM_WANT_SVALUE();
1099
1100 if (RTEST(enum_yield(argc, i))) {
1101 ary = memo->v1;
1102 }
1103 else {
1104 ary = memo->v2;
1105 }
1106 rb_ary_push(ary, i);
1107 return Qnil;
1108}
1109
1110/*
1111 * call-seq:
1112 * partition {|element| ... } -> [true_array, false_array]
1113 * partition -> enumerator
1114 *
1115 * With a block given, returns an array of two arrays:
1116 *
1117 * - The first having those elements for which the block returns a truthy value.
1118 * - The other having all other elements.
1119 *
1120 * Examples:
1121 *
1122 * p = (1..4).partition {|i| i.even? }
1123 * p # => [[2, 4], [1, 3]]
1124 * p = ('a'..'d').partition {|c| c < 'c' }
1125 * p # => [["a", "b"], ["c", "d"]]
1126 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
1127 * p = h.partition {|key, value| key.start_with?('b') }
1128 * p # => [[[:bar, 1], [:baz, 2], [:bat, 3]], [[:foo, 0]]]
1129 * p = h.partition {|key, value| value < 2 }
1130 * p # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]]]
1131 *
1132 * With no block given, returns an Enumerator.
1133 *
1134 * Related: Enumerable#group_by.
1135 *
1136 */
1137
1138static VALUE
1139enum_partition(VALUE obj)
1140{
1141 struct MEMO *memo;
1142
1143 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
1144
1145 memo = MEMO_NEW(rb_ary_new(), rb_ary_new(), 0);
1146 rb_block_call(obj, id_each, 0, 0, partition_i, (VALUE)memo);
1147
1148 return rb_assoc_new(memo->v1, memo->v2);
1149}
1150
1151static VALUE
1152group_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
1153{
1154 VALUE group;
1155 VALUE values;
1156
1157 ENUM_WANT_SVALUE();
1158
1159 group = enum_yield(argc, i);
1160 values = rb_hash_aref(hash, group);
1161 if (!RB_TYPE_P(values, T_ARRAY)) {
1162 values = rb_ary_new3(1, i);
1163 rb_hash_aset(hash, group, values);
1164 }
1165 else {
1166 rb_ary_push(values, i);
1167 }
1168 return Qnil;
1169}
1170
1171/*
1172 * call-seq:
1173 * group_by {|element| ... } -> hash
1174 * group_by -> enumerator
1175 *
1176 * With a block given returns a hash:
1177 *
1178 * - Each key is a return value from the block.
1179 * - Each value is an array of those elements for which the block returned that key.
1180 *
1181 * Examples:
1182 *
1183 * g = (1..6).group_by {|i| i%3 }
1184 * g # => {1=>[1, 4], 2=>[2, 5], 0=>[3, 6]}
1185 * h = {foo: 0, bar: 1, baz: 0, bat: 1}
1186 * g = h.group_by {|key, value| value }
1187 * g # => {0=>[[:foo, 0], [:baz, 0]], 1=>[[:bar, 1], [:bat, 1]]}
1188 *
1189 * With no block given, returns an Enumerator.
1190 *
1191 */
1192
1193static VALUE
1194enum_group_by(VALUE obj)
1195{
1196 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
1197
1198 return enum_hashify(obj, 0, 0, group_by_i);
1199}
1200
1201static int
1202tally_up(st_data_t *group, st_data_t *value, st_data_t arg, int existing)
1203{
1204 VALUE tally = (VALUE)*value;
1205 VALUE hash = (VALUE)arg;
1206 if (!existing) {
1207 tally = INT2FIX(1);
1208 }
1209 else if (FIXNUM_P(tally) && tally < INT2FIX(FIXNUM_MAX)) {
1210 tally += INT2FIX(1) & ~FIXNUM_FLAG;
1211 }
1212 else {
1213 Check_Type(tally, T_BIGNUM);
1214 tally = rb_big_plus(tally, INT2FIX(1));
1215 RB_OBJ_WRITTEN(hash, Qundef, tally);
1216 }
1217 *value = (st_data_t)tally;
1218 if (!SPECIAL_CONST_P(*group)) RB_OBJ_WRITTEN(hash, Qundef, *group);
1219 return ST_CONTINUE;
1220}
1221
1222static VALUE
1223rb_enum_tally_up(VALUE hash, VALUE group)
1224{
1225 rb_hash_stlike_update(hash, group, tally_up, (st_data_t)hash);
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 * e = (1..4).drop_while
3708 * p e #=> #<Enumerator: 1..4:drop_while>
3709 * i = e.next; p i; e.feed(i < 3) #=> 1
3710 * i = e.next; p i; e.feed(i < 3) #=> 2
3711 * i = e.next; p i; e.feed(i < 3) #=> 3
3712 * begin
3713 * e.next
3714 * rescue StopIteration
3715 * p $!.result #=> [3, 4]
3716 * end
3717 *
3718 */
3719
3720static VALUE
3721enum_drop_while(VALUE obj)
3722{
3723 VALUE result;
3724 struct MEMO *memo;
3725
3726 RETURN_ENUMERATOR(obj, 0, 0);
3727 result = rb_ary_new();
3728 memo = MEMO_NEW(result, 0, FALSE);
3729 rb_block_call(obj, id_each, 0, 0, drop_while_i, (VALUE)memo);
3730 return result;
3731}
3732
3733static VALUE
3734cycle_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
3735{
3736 ENUM_WANT_SVALUE();
3737
3738 rb_ary_push(ary, argc > 1 ? i : rb_ary_new_from_values(argc, argv));
3739 enum_yield(argc, i);
3740 return Qnil;
3741}
3742
3743static VALUE
3744enum_cycle_size(VALUE self, VALUE args, VALUE eobj)
3745{
3746 long mul = 0;
3747 VALUE n = Qnil;
3748 VALUE size;
3749
3750 if (args && (RARRAY_LEN(args) > 0)) {
3751 n = RARRAY_AREF(args, 0);
3752 if (!NIL_P(n)) mul = NUM2LONG(n);
3753 }
3754
3755 size = enum_size(self, args, 0);
3756 if (NIL_P(size) || FIXNUM_ZERO_P(size)) return size;
3757
3758 if (NIL_P(n)) return DBL2NUM(HUGE_VAL);
3759 if (mul <= 0) return INT2FIX(0);
3760 n = LONG2FIX(mul);
3761 return rb_funcallv(size, '*', 1, &n);
3762}
3763
3764/*
3765 * call-seq:
3766 * cycle(n = nil) {|element| ...} -> nil
3767 * cycle(n = nil) -> enumerator
3768 *
3769 * When called with positive integer argument +n+ and a block,
3770 * calls the block with each element, then does so again,
3771 * until it has done so +n+ times; returns +nil+:
3772 *
3773 * a = []
3774 * (1..4).cycle(3) {|element| a.push(element) } # => nil
3775 * a # => [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
3776 * a = []
3777 * ('a'..'d').cycle(2) {|element| a.push(element) }
3778 * a # => ["a", "b", "c", "d", "a", "b", "c", "d"]
3779 * a = []
3780 * {foo: 0, bar: 1, baz: 2}.cycle(2) {|element| a.push(element) }
3781 * a # => [[:foo, 0], [:bar, 1], [:baz, 2], [:foo, 0], [:bar, 1], [:baz, 2]]
3782 *
3783 * If count is zero or negative, does not call the block.
3784 *
3785 * When called with a block and +n+ is +nil+, cycles forever.
3786 *
3787 * When no block is given, returns an Enumerator.
3788 *
3789 */
3790
3791static VALUE
3792enum_cycle(int argc, VALUE *argv, VALUE obj)
3793{
3794 VALUE ary;
3795 VALUE nv = Qnil;
3796 long n, i, len;
3797
3798 rb_check_arity(argc, 0, 1);
3799
3800 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_cycle_size);
3801 if (!argc || NIL_P(nv = argv[0])) {
3802 n = -1;
3803 }
3804 else {
3805 n = NUM2LONG(nv);
3806 if (n <= 0) return Qnil;
3807 }
3808 ary = rb_ary_new();
3809 RBASIC_CLEAR_CLASS(ary);
3810 rb_block_call(obj, id_each, 0, 0, cycle_i, ary);
3811 len = RARRAY_LEN(ary);
3812 if (len == 0) return Qnil;
3813 while (n < 0 || 0 < --n) {
3814 for (i=0; i<len; i++) {
3815 enum_yield_array(RARRAY_AREF(ary, i));
3816 }
3817 }
3818 return Qnil;
3819}
3820
3822 VALUE categorize;
3823 VALUE prev_value;
3824 VALUE prev_elts;
3825 VALUE yielder;
3826};
3827
3828static VALUE
3829chunk_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
3830{
3831 struct chunk_arg *argp = MEMO_FOR(struct chunk_arg, _argp);
3832 VALUE v, s;
3833 VALUE alone = ID2SYM(id__alone);
3834 VALUE separator = ID2SYM(id__separator);
3835
3836 ENUM_WANT_SVALUE();
3837
3838 v = rb_funcallv(argp->categorize, id_call, 1, &i);
3839
3840 if (v == alone) {
3841 if (!NIL_P(argp->prev_value)) {
3842 s = rb_assoc_new(argp->prev_value, argp->prev_elts);
3843 rb_funcallv(argp->yielder, id_lshift, 1, &s);
3844 argp->prev_value = argp->prev_elts = Qnil;
3845 }
3846 v = rb_assoc_new(v, rb_ary_new3(1, i));
3847 rb_funcallv(argp->yielder, id_lshift, 1, &v);
3848 }
3849 else if (NIL_P(v) || v == separator) {
3850 if (!NIL_P(argp->prev_value)) {
3851 v = rb_assoc_new(argp->prev_value, argp->prev_elts);
3852 rb_funcallv(argp->yielder, id_lshift, 1, &v);
3853 argp->prev_value = argp->prev_elts = Qnil;
3854 }
3855 }
3856 else if (SYMBOL_P(v) && (s = rb_sym2str(v), RSTRING_PTR(s)[0] == '_')) {
3857 rb_raise(rb_eRuntimeError, "symbols beginning with an underscore are reserved");
3858 }
3859 else {
3860 if (NIL_P(argp->prev_value)) {
3861 argp->prev_value = v;
3862 argp->prev_elts = rb_ary_new3(1, i);
3863 }
3864 else {
3865 if (rb_equal(argp->prev_value, v)) {
3866 rb_ary_push(argp->prev_elts, i);
3867 }
3868 else {
3869 s = rb_assoc_new(argp->prev_value, argp->prev_elts);
3870 rb_funcallv(argp->yielder, id_lshift, 1, &s);
3871 argp->prev_value = v;
3872 argp->prev_elts = rb_ary_new3(1, i);
3873 }
3874 }
3875 }
3876 return Qnil;
3877}
3878
3879static VALUE
3881{
3882 VALUE enumerable;
3883 VALUE arg;
3884 struct chunk_arg *memo = NEW_MEMO_FOR(struct chunk_arg, arg);
3885
3886 enumerable = rb_ivar_get(enumerator, id_chunk_enumerable);
3887 memo->categorize = rb_ivar_get(enumerator, id_chunk_categorize);
3888 memo->prev_value = Qnil;
3889 memo->prev_elts = Qnil;
3890 memo->yielder = yielder;
3891
3892 rb_block_call(enumerable, id_each, 0, 0, chunk_ii, arg);
3893 memo = MEMO_FOR(struct chunk_arg, arg);
3894 if (!NIL_P(memo->prev_elts)) {
3895 arg = rb_assoc_new(memo->prev_value, memo->prev_elts);
3896 rb_funcallv(memo->yielder, id_lshift, 1, &arg);
3897 }
3898 return Qnil;
3899}
3900
3901/*
3902 * call-seq:
3903 * chunk {|array| ... } -> enumerator
3904 *
3905 * Each element in the returned enumerator is a 2-element array consisting of:
3906 *
3907 * - A value returned by the block.
3908 * - An array ("chunk") containing the element for which that value was returned,
3909 * and all following elements for which the block returned the same value:
3910 *
3911 * So that:
3912 *
3913 * - Each block return value that is different from its predecessor
3914 * begins a new chunk.
3915 * - Each block return value that is the same as its predecessor
3916 * continues the same chunk.
3917 *
3918 * Example:
3919 *
3920 * e = (0..10).chunk {|i| (i / 3).floor } # => #<Enumerator: ...>
3921 * # The enumerator elements.
3922 * e.next # => [0, [0, 1, 2]]
3923 * e.next # => [1, [3, 4, 5]]
3924 * e.next # => [2, [6, 7, 8]]
3925 * e.next # => [3, [9, 10]]
3926 *
3927 * Method +chunk+ is especially useful for an enumerable that is already sorted.
3928 * This example counts words for each initial letter in a large array of words:
3929 *
3930 * # Get sorted words from a web page.
3931 * url = 'https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt'
3932 * words = URI::open(url).readlines
3933 * # Make chunks, one for each letter.
3934 * e = words.chunk {|word| word.upcase[0] } # => #<Enumerator: ...>
3935 * # Display 'A' through 'F'.
3936 * e.each {|c, words| p [c, words.length]; break if c == 'F' }
3937 *
3938 * Output:
3939 *
3940 * ["A", 17096]
3941 * ["B", 11070]
3942 * ["C", 19901]
3943 * ["D", 10896]
3944 * ["E", 8736]
3945 * ["F", 6860]
3946 *
3947 * You can use the special symbol <tt>:_alone</tt> to force an element
3948 * into its own separate chuck:
3949 *
3950 * a = [0, 0, 1, 1]
3951 * e = a.chunk{|i| i.even? ? :_alone : true }
3952 * e.to_a # => [[:_alone, [0]], [:_alone, [0]], [true, [1, 1]]]
3953 *
3954 * For example, you can put each line that contains a URL into its own chunk:
3955 *
3956 * pattern = /http/
3957 * open(filename) { |f|
3958 * f.chunk { |line| line =~ pattern ? :_alone : true }.each { |key, lines|
3959 * pp lines
3960 * }
3961 * }
3962 *
3963 * You can use the special symbol <tt>:_separator</tt> or +nil+
3964 * to force an element to be ignored (not included in any chunk):
3965 *
3966 * a = [0, 0, -1, 1, 1]
3967 * e = a.chunk{|i| i < 0 ? :_separator : true }
3968 * e.to_a # => [[true, [0, 0]], [true, [1, 1]]]
3969 *
3970 * Note that the separator does end the chunk:
3971 *
3972 * a = [0, 0, -1, 1, -1, 1]
3973 * e = a.chunk{|i| i < 0 ? :_separator : true }
3974 * e.to_a # => [[true, [0, 0]], [true, [1]], [true, [1]]]
3975 *
3976 * For example, the sequence of hyphens in svn log can be eliminated as follows:
3977 *
3978 * sep = "-"*72 + "\n"
3979 * IO.popen("svn log README") { |f|
3980 * f.chunk { |line|
3981 * line != sep || nil
3982 * }.each { |_, lines|
3983 * pp lines
3984 * }
3985 * }
3986 * #=> ["r20018 | knu | 2008-10-29 13:20:42 +0900 (Wed, 29 Oct 2008) | 2 lines\n",
3987 * # "\n",
3988 * # "* README, README.ja: Update the portability section.\n",
3989 * # "\n"]
3990 * # ["r16725 | knu | 2008-05-31 23:34:23 +0900 (Sat, 31 May 2008) | 2 lines\n",
3991 * # "\n",
3992 * # "* README, README.ja: Add a note about default C flags.\n",
3993 * # "\n"]
3994 * # ...
3995 *
3996 * Paragraphs separated by empty lines can be parsed as follows:
3997 *
3998 * File.foreach("README").chunk { |line|
3999 * /\A\s*\z/ !~ line || nil
4000 * }.each { |_, lines|
4001 * pp lines
4002 * }
4003 *
4004 */
4005static VALUE
4006enum_chunk(VALUE enumerable)
4007{
4009
4010 RETURN_SIZED_ENUMERATOR(enumerable, 0, 0, enum_size);
4011
4013 rb_ivar_set(enumerator, id_chunk_enumerable, enumerable);
4014 rb_ivar_set(enumerator, id_chunk_categorize, rb_block_proc());
4015 rb_block_call(enumerator, idInitialize, 0, 0, chunk_i, enumerator);
4016 return enumerator;
4017}
4018
4019
4021 VALUE sep_pred;
4022 VALUE sep_pat;
4023 VALUE prev_elts;
4024 VALUE yielder;
4025};
4026
4027static VALUE
4028slicebefore_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
4029{
4030 struct slicebefore_arg *argp = MEMO_FOR(struct slicebefore_arg, _argp);
4031 VALUE header_p;
4032
4033 ENUM_WANT_SVALUE();
4034
4035 if (!NIL_P(argp->sep_pat))
4036 header_p = rb_funcallv(argp->sep_pat, id_eqq, 1, &i);
4037 else
4038 header_p = rb_funcallv(argp->sep_pred, id_call, 1, &i);
4039 if (RTEST(header_p)) {
4040 if (!NIL_P(argp->prev_elts))
4041 rb_funcallv(argp->yielder, id_lshift, 1, &argp->prev_elts);
4042 argp->prev_elts = rb_ary_new3(1, i);
4043 }
4044 else {
4045 if (NIL_P(argp->prev_elts))
4046 argp->prev_elts = rb_ary_new3(1, i);
4047 else
4048 rb_ary_push(argp->prev_elts, i);
4049 }
4050
4051 return Qnil;
4052}
4053
4054static VALUE
4056{
4057 VALUE enumerable;
4058 VALUE arg;
4059 struct slicebefore_arg *memo = NEW_MEMO_FOR(struct slicebefore_arg, arg);
4060
4061 enumerable = rb_ivar_get(enumerator, id_slicebefore_enumerable);
4062 memo->sep_pred = rb_attr_get(enumerator, id_slicebefore_sep_pred);
4063 memo->sep_pat = NIL_P(memo->sep_pred) ? rb_ivar_get(enumerator, id_slicebefore_sep_pat) : Qnil;
4064 memo->prev_elts = Qnil;
4065 memo->yielder = yielder;
4066
4067 rb_block_call(enumerable, id_each, 0, 0, slicebefore_ii, arg);
4068 memo = MEMO_FOR(struct slicebefore_arg, arg);
4069 if (!NIL_P(memo->prev_elts))
4070 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4071 return Qnil;
4072}
4073
4074/*
4075 * call-seq:
4076 * slice_before(pattern) -> enumerator
4077 * slice_before {|elt| ... } -> enumerator
4078 *
4079 * With argument +pattern+, returns an enumerator that uses the pattern
4080 * to partition elements into arrays ("slices").
4081 * An element begins a new slice if <tt>element === pattern</tt>
4082 * (or if it is the first element).
4083 *
4084 * a = %w[foo bar fop for baz fob fog bam foy]
4085 * e = a.slice_before(/ba/) # => #<Enumerator: ...>
4086 * e.each {|array| p array }
4087 *
4088 * Output:
4089 *
4090 * ["foo"]
4091 * ["bar", "fop", "for"]
4092 * ["baz", "fob", "fog"]
4093 * ["bam", "foy"]
4094 *
4095 * With a block, returns an enumerator that uses the block
4096 * to partition elements into arrays.
4097 * An element begins a new slice if its block return is a truthy value
4098 * (or if it is the first element):
4099 *
4100 * e = (1..20).slice_before {|i| i % 4 == 2 } # => #<Enumerator: ...>
4101 * e.each {|array| p array }
4102 *
4103 * Output:
4104 *
4105 * [1]
4106 * [2, 3, 4, 5]
4107 * [6, 7, 8, 9]
4108 * [10, 11, 12, 13]
4109 * [14, 15, 16, 17]
4110 * [18, 19, 20]
4111 *
4112 * Other methods of the Enumerator class and Enumerable module,
4113 * such as +to_a+, +map+, etc., are also usable.
4114 *
4115 * For example, iteration over ChangeLog entries can be implemented as
4116 * follows:
4117 *
4118 * # iterate over ChangeLog entries.
4119 * open("ChangeLog") { |f|
4120 * f.slice_before(/\A\S/).each { |e| pp e }
4121 * }
4122 *
4123 * # same as above. block is used instead of pattern argument.
4124 * open("ChangeLog") { |f|
4125 * f.slice_before { |line| /\A\S/ === line }.each { |e| pp e }
4126 * }
4127 *
4128 * "svn proplist -R" produces multiline output for each file.
4129 * They can be chunked as follows:
4130 *
4131 * IO.popen([{"LC_ALL"=>"C"}, "svn", "proplist", "-R"]) { |f|
4132 * f.lines.slice_before(/\AProp/).each { |lines| p lines }
4133 * }
4134 * #=> ["Properties on '.':\n", " svn:ignore\n", " svk:merge\n"]
4135 * # ["Properties on 'goruby.c':\n", " svn:eol-style\n"]
4136 * # ["Properties on 'complex.c':\n", " svn:mime-type\n", " svn:eol-style\n"]
4137 * # ["Properties on 'regparse.c':\n", " svn:eol-style\n"]
4138 * # ...
4139 *
4140 * If the block needs to maintain state over multiple elements,
4141 * local variables can be used.
4142 * For example, three or more consecutive increasing numbers can be squashed
4143 * as follows (see +chunk_while+ for a better way):
4144 *
4145 * a = [0, 2, 3, 4, 6, 7, 9]
4146 * prev = a[0]
4147 * p a.slice_before { |e|
4148 * prev, prev2 = e, prev
4149 * prev2 + 1 != e
4150 * }.map { |es|
4151 * es.length <= 2 ? es.join(",") : "#{es.first}-#{es.last}"
4152 * }.join(",")
4153 * #=> "0,2-4,6,7,9"
4154 *
4155 * However local variables should be used carefully
4156 * if the result enumerator is enumerated twice or more.
4157 * The local variables should be initialized for each enumeration.
4158 * Enumerator.new can be used to do it.
4159 *
4160 * # Word wrapping. This assumes all characters have same width.
4161 * def wordwrap(words, maxwidth)
4162 * Enumerator.new {|y|
4163 * # cols is initialized in Enumerator.new.
4164 * cols = 0
4165 * words.slice_before { |w|
4166 * cols += 1 if cols != 0
4167 * cols += w.length
4168 * if maxwidth < cols
4169 * cols = w.length
4170 * true
4171 * else
4172 * false
4173 * end
4174 * }.each {|ws| y.yield ws }
4175 * }
4176 * end
4177 * text = (1..20).to_a.join(" ")
4178 * enum = wordwrap(text.split(/\s+/), 10)
4179 * puts "-"*10
4180 * enum.each { |ws| puts ws.join(" ") } # first enumeration.
4181 * puts "-"*10
4182 * enum.each { |ws| puts ws.join(" ") } # second enumeration generates same result as the first.
4183 * puts "-"*10
4184 * #=> ----------
4185 * # 1 2 3 4 5
4186 * # 6 7 8 9 10
4187 * # 11 12 13
4188 * # 14 15 16
4189 * # 17 18 19
4190 * # 20
4191 * # ----------
4192 * # 1 2 3 4 5
4193 * # 6 7 8 9 10
4194 * # 11 12 13
4195 * # 14 15 16
4196 * # 17 18 19
4197 * # 20
4198 * # ----------
4199 *
4200 * mbox contains series of mails which start with Unix From line.
4201 * So each mail can be extracted by slice before Unix From line.
4202 *
4203 * # parse mbox
4204 * open("mbox") { |f|
4205 * f.slice_before { |line|
4206 * line.start_with? "From "
4207 * }.each { |mail|
4208 * unix_from = mail.shift
4209 * i = mail.index("\n")
4210 * header = mail[0...i]
4211 * body = mail[(i+1)..-1]
4212 * body.pop if body.last == "\n"
4213 * fields = header.slice_before { |line| !" \t".include?(line[0]) }.to_a
4214 * p unix_from
4215 * pp fields
4216 * pp body
4217 * }
4218 * }
4219 *
4220 * # split mails in mbox (slice before Unix From line after an empty line)
4221 * open("mbox") { |f|
4222 * emp = true
4223 * f.slice_before { |line|
4224 * prevemp = emp
4225 * emp = line == "\n"
4226 * prevemp && line.start_with?("From ")
4227 * }.each { |mail|
4228 * mail.pop if mail.last == "\n"
4229 * pp mail
4230 * }
4231 * }
4232 *
4233 */
4234static VALUE
4235enum_slice_before(int argc, VALUE *argv, VALUE enumerable)
4236{
4238
4239 if (rb_block_given_p()) {
4240 if (argc != 0)
4241 rb_error_arity(argc, 0, 0);
4243 rb_ivar_set(enumerator, id_slicebefore_sep_pred, rb_block_proc());
4244 }
4245 else {
4246 VALUE sep_pat;
4247 rb_scan_args(argc, argv, "1", &sep_pat);
4249 rb_ivar_set(enumerator, id_slicebefore_sep_pat, sep_pat);
4250 }
4251 rb_ivar_set(enumerator, id_slicebefore_enumerable, enumerable);
4252 rb_block_call(enumerator, idInitialize, 0, 0, slicebefore_i, enumerator);
4253 return enumerator;
4254}
4255
4256
4258 VALUE pat;
4259 VALUE pred;
4260 VALUE prev_elts;
4261 VALUE yielder;
4262};
4263
4264static VALUE
4265sliceafter_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
4266{
4267#define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct sliceafter_arg, _memo)))
4268 struct sliceafter_arg *memo;
4269 int split_p;
4270 UPDATE_MEMO;
4271
4272 ENUM_WANT_SVALUE();
4273
4274 if (NIL_P(memo->prev_elts)) {
4275 memo->prev_elts = rb_ary_new3(1, i);
4276 }
4277 else {
4278 rb_ary_push(memo->prev_elts, i);
4279 }
4280
4281 if (NIL_P(memo->pred)) {
4282 split_p = RTEST(rb_funcallv(memo->pat, id_eqq, 1, &i));
4283 UPDATE_MEMO;
4284 }
4285 else {
4286 split_p = RTEST(rb_funcallv(memo->pred, id_call, 1, &i));
4287 UPDATE_MEMO;
4288 }
4289
4290 if (split_p) {
4291 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4292 UPDATE_MEMO;
4293 memo->prev_elts = Qnil;
4294 }
4295
4296 return Qnil;
4297#undef UPDATE_MEMO
4298}
4299
4300static VALUE
4302{
4303 VALUE enumerable;
4304 VALUE arg;
4305 struct sliceafter_arg *memo = NEW_MEMO_FOR(struct sliceafter_arg, arg);
4306
4307 enumerable = rb_ivar_get(enumerator, id_sliceafter_enum);
4308 memo->pat = rb_ivar_get(enumerator, id_sliceafter_pat);
4309 memo->pred = rb_attr_get(enumerator, id_sliceafter_pred);
4310 memo->prev_elts = Qnil;
4311 memo->yielder = yielder;
4312
4313 rb_block_call(enumerable, id_each, 0, 0, sliceafter_ii, arg);
4314 memo = MEMO_FOR(struct sliceafter_arg, arg);
4315 if (!NIL_P(memo->prev_elts))
4316 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4317 return Qnil;
4318}
4319
4320/*
4321 * call-seq:
4322 * enum.slice_after(pattern) -> an_enumerator
4323 * enum.slice_after { |elt| bool } -> an_enumerator
4324 *
4325 * Creates an enumerator for each chunked elements.
4326 * The ends of chunks are defined by _pattern_ and the block.
4327 *
4328 * If <code>_pattern_ === _elt_</code> returns <code>true</code> or the block
4329 * returns <code>true</code> for the element, the element is end of a
4330 * chunk.
4331 *
4332 * The <code>===</code> and _block_ is called from the first element to the last
4333 * element of _enum_.
4334 *
4335 * The result enumerator yields the chunked elements as an array.
4336 * So +each+ method can be called as follows:
4337 *
4338 * enum.slice_after(pattern).each { |ary| ... }
4339 * enum.slice_after { |elt| bool }.each { |ary| ... }
4340 *
4341 * Other methods of the Enumerator class and Enumerable module,
4342 * such as +map+, etc., are also usable.
4343 *
4344 * For example, continuation lines (lines end with backslash) can be
4345 * concatenated as follows:
4346 *
4347 * lines = ["foo\n", "bar\\\n", "baz\n", "\n", "qux\n"]
4348 * e = lines.slice_after(/(?<!\\‍)\n\z/)
4349 * p e.to_a
4350 * #=> [["foo\n"], ["bar\\\n", "baz\n"], ["\n"], ["qux\n"]]
4351 * p e.map {|ll| ll[0...-1].map {|l| l.sub(/\\\n\z/, "") }.join + ll.last }
4352 * #=>["foo\n", "barbaz\n", "\n", "qux\n"]
4353 *
4354 */
4355
4356static VALUE
4357enum_slice_after(int argc, VALUE *argv, VALUE enumerable)
4358{
4360 VALUE pat = Qnil, pred = Qnil;
4361
4362 if (rb_block_given_p()) {
4363 if (0 < argc)
4364 rb_raise(rb_eArgError, "both pattern and block are given");
4365 pred = rb_block_proc();
4366 }
4367 else {
4368 rb_scan_args(argc, argv, "1", &pat);
4369 }
4370
4372 rb_ivar_set(enumerator, id_sliceafter_enum, enumerable);
4373 rb_ivar_set(enumerator, id_sliceafter_pat, pat);
4374 rb_ivar_set(enumerator, id_sliceafter_pred, pred);
4375
4376 rb_block_call(enumerator, idInitialize, 0, 0, sliceafter_i, enumerator);
4377 return enumerator;
4378}
4379
4381 VALUE pred;
4382 VALUE prev_elt;
4383 VALUE prev_elts;
4384 VALUE yielder;
4385 int inverted; /* 0 for slice_when and 1 for chunk_while. */
4386};
4387
4388static VALUE
4389slicewhen_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
4390{
4391#define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct slicewhen_arg, _memo)))
4392 struct slicewhen_arg *memo;
4393 int split_p;
4394 UPDATE_MEMO;
4395
4396 ENUM_WANT_SVALUE();
4397
4398 if (UNDEF_P(memo->prev_elt)) {
4399 /* The first element */
4400 memo->prev_elt = i;
4401 memo->prev_elts = rb_ary_new3(1, i);
4402 }
4403 else {
4404 VALUE args[2];
4405 args[0] = memo->prev_elt;
4406 args[1] = i;
4407 split_p = RTEST(rb_funcallv(memo->pred, id_call, 2, args));
4408 UPDATE_MEMO;
4409
4410 if (memo->inverted)
4411 split_p = !split_p;
4412
4413 if (split_p) {
4414 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4415 UPDATE_MEMO;
4416 memo->prev_elts = rb_ary_new3(1, i);
4417 }
4418 else {
4419 rb_ary_push(memo->prev_elts, i);
4420 }
4421
4422 memo->prev_elt = i;
4423 }
4424
4425 return Qnil;
4426#undef UPDATE_MEMO
4427}
4428
4429static VALUE
4431{
4432 VALUE enumerable;
4433 VALUE arg;
4434 struct slicewhen_arg *memo =
4435 NEW_PARTIAL_MEMO_FOR(struct slicewhen_arg, arg, inverted);
4436
4437 enumerable = rb_ivar_get(enumerator, id_slicewhen_enum);
4438 memo->pred = rb_attr_get(enumerator, id_slicewhen_pred);
4439 memo->prev_elt = Qundef;
4440 memo->prev_elts = Qnil;
4441 memo->yielder = yielder;
4442 memo->inverted = RTEST(rb_attr_get(enumerator, id_slicewhen_inverted));
4443
4444 rb_block_call(enumerable, id_each, 0, 0, slicewhen_ii, arg);
4445 memo = MEMO_FOR(struct slicewhen_arg, arg);
4446 if (!NIL_P(memo->prev_elts))
4447 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4448 return Qnil;
4449}
4450
4451/*
4452 * call-seq:
4453 * enum.slice_when {|elt_before, elt_after| bool } -> an_enumerator
4454 *
4455 * Creates an enumerator for each chunked elements.
4456 * The beginnings of chunks are defined by the block.
4457 *
4458 * This method splits each chunk using adjacent elements,
4459 * _elt_before_ and _elt_after_,
4460 * in the receiver enumerator.
4461 * This method split chunks between _elt_before_ and _elt_after_ where
4462 * the block returns <code>true</code>.
4463 *
4464 * The block is called the length of the receiver enumerator minus one.
4465 *
4466 * The result enumerator yields the chunked elements as an array.
4467 * So +each+ method can be called as follows:
4468 *
4469 * enum.slice_when { |elt_before, elt_after| bool }.each { |ary| ... }
4470 *
4471 * Other methods of the Enumerator class and Enumerable module,
4472 * such as +to_a+, +map+, etc., are also usable.
4473 *
4474 * For example, one-by-one increasing subsequence can be chunked as follows:
4475 *
4476 * a = [1,2,4,9,10,11,12,15,16,19,20,21]
4477 * b = a.slice_when {|i, j| i+1 != j }
4478 * p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
4479 * c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
4480 * p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
4481 * d = c.join(",")
4482 * p d #=> "1,2,4,9-12,15,16,19-21"
4483 *
4484 * Near elements (threshold: 6) in sorted array can be chunked as follows:
4485 *
4486 * a = [3, 11, 14, 25, 28, 29, 29, 41, 55, 57]
4487 * p a.slice_when {|i, j| 6 < j - i }.to_a
4488 * #=> [[3], [11, 14], [25, 28, 29, 29], [41], [55, 57]]
4489 *
4490 * Increasing (non-decreasing) subsequence can be chunked as follows:
4491 *
4492 * a = [0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
4493 * p a.slice_when {|i, j| i > j }.to_a
4494 * #=> [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
4495 *
4496 * Adjacent evens and odds can be chunked as follows:
4497 * (Enumerable#chunk is another way to do it.)
4498 *
4499 * a = [7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
4500 * p a.slice_when {|i, j| i.even? != j.even? }.to_a
4501 * #=> [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
4502 *
4503 * Paragraphs (non-empty lines with trailing empty lines) can be chunked as follows:
4504 * (See Enumerable#chunk to ignore empty lines.)
4505 *
4506 * lines = ["foo\n", "bar\n", "\n", "baz\n", "qux\n"]
4507 * p lines.slice_when {|l1, l2| /\A\s*\z/ =~ l1 && /\S/ =~ l2 }.to_a
4508 * #=> [["foo\n", "bar\n", "\n"], ["baz\n", "qux\n"]]
4509 *
4510 * Enumerable#chunk_while does the same, except splitting when the block
4511 * returns <code>false</code> instead of <code>true</code>.
4512 */
4513static VALUE
4514enum_slice_when(VALUE enumerable)
4515{
4517 VALUE pred;
4518
4519 pred = rb_block_proc();
4520
4522 rb_ivar_set(enumerator, id_slicewhen_enum, enumerable);
4523 rb_ivar_set(enumerator, id_slicewhen_pred, pred);
4524 rb_ivar_set(enumerator, id_slicewhen_inverted, Qfalse);
4525
4526 rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
4527 return enumerator;
4528}
4529
4530/*
4531 * call-seq:
4532 * enum.chunk_while {|elt_before, elt_after| bool } -> an_enumerator
4533 *
4534 * Creates an enumerator for each chunked elements.
4535 * The beginnings of chunks are defined by the block.
4536 *
4537 * This method splits each chunk using adjacent elements,
4538 * _elt_before_ and _elt_after_,
4539 * in the receiver enumerator.
4540 * This method split chunks between _elt_before_ and _elt_after_ where
4541 * the block returns <code>false</code>.
4542 *
4543 * The block is called the length of the receiver enumerator minus one.
4544 *
4545 * The result enumerator yields the chunked elements as an array.
4546 * So +each+ method can be called as follows:
4547 *
4548 * enum.chunk_while { |elt_before, elt_after| bool }.each { |ary| ... }
4549 *
4550 * Other methods of the Enumerator class and Enumerable module,
4551 * such as +to_a+, +map+, etc., are also usable.
4552 *
4553 * For example, one-by-one increasing subsequence can be chunked as follows:
4554 *
4555 * a = [1,2,4,9,10,11,12,15,16,19,20,21]
4556 * b = a.chunk_while {|i, j| i+1 == j }
4557 * p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
4558 * c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
4559 * p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
4560 * d = c.join(",")
4561 * p d #=> "1,2,4,9-12,15,16,19-21"
4562 *
4563 * Increasing (non-decreasing) subsequence can be chunked as follows:
4564 *
4565 * a = [0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
4566 * p a.chunk_while {|i, j| i <= j }.to_a
4567 * #=> [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
4568 *
4569 * Adjacent evens and odds can be chunked as follows:
4570 * (Enumerable#chunk is another way to do it.)
4571 *
4572 * a = [7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
4573 * p a.chunk_while {|i, j| i.even? == j.even? }.to_a
4574 * #=> [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
4575 *
4576 * Enumerable#slice_when does the same, except splitting when the block
4577 * returns <code>true</code> instead of <code>false</code>.
4578 */
4579static VALUE
4580enum_chunk_while(VALUE enumerable)
4581{
4583 VALUE pred;
4584
4585 pred = rb_block_proc();
4586
4588 rb_ivar_set(enumerator, id_slicewhen_enum, enumerable);
4589 rb_ivar_set(enumerator, id_slicewhen_pred, pred);
4590 rb_ivar_set(enumerator, id_slicewhen_inverted, Qtrue);
4591
4592 rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
4593 return enumerator;
4594}
4595
4597 VALUE v, r;
4598 long n;
4599 double f, c;
4600 int block_given;
4601 int float_value;
4602};
4603
4604static void
4605sum_iter_normalize_memo(struct enum_sum_memo *memo)
4606{
4607 RUBY_ASSERT(FIXABLE(memo->n));
4608 memo->v = rb_fix_plus(LONG2FIX(memo->n), memo->v);
4609 memo->n = 0;
4610
4611 switch (TYPE(memo->r)) {
4612 case T_RATIONAL: memo->v = rb_rational_plus(memo->r, memo->v); break;
4613 case T_UNDEF: break;
4614 default: UNREACHABLE; /* or ...? */
4615 }
4616 memo->r = Qundef;
4617}
4618
4619static void
4620sum_iter_fixnum(VALUE i, struct enum_sum_memo *memo)
4621{
4622 memo->n += FIX2LONG(i); /* should not overflow long type */
4623 if (! FIXABLE(memo->n)) {
4624 memo->v = rb_big_plus(LONG2NUM(memo->n), memo->v);
4625 memo->n = 0;
4626 }
4627}
4628
4629static void
4630sum_iter_bignum(VALUE i, struct enum_sum_memo *memo)
4631{
4632 memo->v = rb_big_plus(i, memo->v);
4633}
4634
4635static void
4636sum_iter_rational(VALUE i, struct enum_sum_memo *memo)
4637{
4638 if (UNDEF_P(memo->r)) {
4639 memo->r = i;
4640 }
4641 else {
4642 memo->r = rb_rational_plus(memo->r, i);
4643 }
4644}
4645
4646static void
4647sum_iter_some_value(VALUE i, struct enum_sum_memo *memo)
4648{
4649 memo->v = rb_funcallv(memo->v, idPLUS, 1, &i);
4650}
4651
4652static void
4653sum_iter_Kahan_Babuska(VALUE i, struct enum_sum_memo *memo)
4654{
4655 /*
4656 * Kahan-Babuska balancing compensated summation algorithm
4657 * See https://link.springer.com/article/10.1007/s00607-005-0139-x
4658 */
4659 double x;
4660
4661 switch (TYPE(i)) {
4662 case T_FLOAT: x = RFLOAT_VALUE(i); break;
4663 case T_FIXNUM: x = FIX2LONG(i); break;
4664 case T_BIGNUM: x = rb_big2dbl(i); break;
4665 case T_RATIONAL: x = rb_num2dbl(i); break;
4666 default:
4667 memo->v = DBL2NUM(memo->f);
4668 memo->float_value = 0;
4669 sum_iter_some_value(i, memo);
4670 return;
4671 }
4672
4673 double f = memo->f;
4674
4675 if (isnan(f)) {
4676 return;
4677 }
4678 else if (! isfinite(x)) {
4679 if (isinf(x) && isinf(f) && signbit(x) != signbit(f)) {
4680 i = DBL2NUM(f);
4681 x = nan("");
4682 }
4683 memo->v = i;
4684 memo->f = x;
4685 return;
4686 }
4687 else if (isinf(f)) {
4688 return;
4689 }
4690
4691 double c = memo->c;
4692 double t = f + x;
4693
4694 if (fabs(f) >= fabs(x)) {
4695 c += ((f - t) + x);
4696 }
4697 else {
4698 c += ((x - t) + f);
4699 }
4700 f = t;
4701
4702 memo->f = f;
4703 memo->c = c;
4704}
4705
4706static void
4707sum_iter(VALUE i, struct enum_sum_memo *memo)
4708{
4709 RUBY_ASSERT(memo != NULL);
4710 if (memo->block_given) {
4711 i = rb_yield(i);
4712 }
4713
4714 if (memo->float_value) {
4715 sum_iter_Kahan_Babuska(i, memo);
4716 }
4717 else switch (TYPE(memo->v)) {
4718 default: sum_iter_some_value(i, memo); return;
4719 case T_FLOAT:
4720 case T_FIXNUM:
4721 case T_BIGNUM:
4722 case T_RATIONAL:
4723 switch (TYPE(i)) {
4724 case T_FIXNUM: sum_iter_fixnum(i, memo); return;
4725 case T_BIGNUM: sum_iter_bignum(i, memo); return;
4726 case T_RATIONAL: sum_iter_rational(i, memo); return;
4727 case T_FLOAT:
4728 sum_iter_normalize_memo(memo);
4729 memo->f = NUM2DBL(memo->v);
4730 memo->c = 0.0;
4731 memo->float_value = 1;
4732 sum_iter_Kahan_Babuska(i, memo);
4733 return;
4734 default:
4735 sum_iter_normalize_memo(memo);
4736 sum_iter_some_value(i, memo);
4737 return;
4738 }
4739 }
4740}
4741
4742static VALUE
4743enum_sum_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
4744{
4745 ENUM_WANT_SVALUE();
4746 sum_iter(i, (struct enum_sum_memo *) args);
4747 return Qnil;
4748}
4749
4750static int
4751hash_sum_i(VALUE key, VALUE value, VALUE arg)
4752{
4753 sum_iter(rb_assoc_new(key, value), (struct enum_sum_memo *) arg);
4754 return ST_CONTINUE;
4755}
4756
4757static void
4758hash_sum(VALUE hash, struct enum_sum_memo *memo)
4759{
4761 RUBY_ASSERT(memo != NULL);
4762
4763 rb_hash_foreach(hash, hash_sum_i, (VALUE)memo);
4764}
4765
4766static VALUE
4767int_range_sum(VALUE beg, VALUE end, int excl, VALUE init)
4768{
4769 if (excl) {
4770 if (FIXNUM_P(end))
4771 end = LONG2FIX(FIX2LONG(end) - 1);
4772 else
4773 end = rb_big_minus(end, LONG2FIX(1));
4774 }
4775
4776 if (rb_int_ge(end, beg)) {
4777 VALUE a;
4778 a = rb_int_plus(rb_int_minus(end, beg), LONG2FIX(1));
4779 a = rb_int_mul(a, rb_int_plus(end, beg));
4780 a = rb_int_idiv(a, LONG2FIX(2));
4781 return rb_int_plus(init, a);
4782 }
4783
4784 return init;
4785}
4786
4787/*
4788 * call-seq:
4789 * sum(initial_value = 0) -> number
4790 * sum(initial_value = 0) {|element| ... } -> object
4791 *
4792 * With no block given,
4793 * returns the sum of +initial_value+ and the elements:
4794 *
4795 * (1..100).sum # => 5050
4796 * (1..100).sum(1) # => 5051
4797 * ('a'..'d').sum('foo') # => "fooabcd"
4798 *
4799 * Generally, the sum is computed using methods <tt>+</tt> and +each+;
4800 * for performance optimizations, those methods may not be used,
4801 * and so any redefinition of those methods may not have effect here.
4802 *
4803 * One such optimization: When possible, computes using Gauss's summation
4804 * formula <em>n(n+1)/2</em>:
4805 *
4806 * 100 * (100 + 1) / 2 # => 5050
4807 *
4808 * With a block given, calls the block with each element;
4809 * returns the sum of +initial_value+ and the block return values:
4810 *
4811 * (1..4).sum {|i| i*i } # => 30
4812 * (1..4).sum(100) {|i| i*i } # => 130
4813 * h = {a: 0, b: 1, c: 2, d: 3, e: 4, f: 5}
4814 * h.sum {|key, value| value.odd? ? value : 0 } # => 9
4815 * ('a'..'f').sum('x') {|c| c < 'd' ? c : '' } # => "xabc"
4816 *
4817 */
4818static VALUE
4819enum_sum(int argc, VALUE* argv, VALUE obj)
4820{
4821 struct enum_sum_memo memo;
4822 VALUE beg, end;
4823 int excl;
4824
4825 memo.v = (rb_check_arity(argc, 0, 1) == 0) ? LONG2FIX(0) : argv[0];
4826 memo.block_given = rb_block_given_p();
4827 memo.n = 0;
4828 memo.r = Qundef;
4829
4830 if ((memo.float_value = RB_FLOAT_TYPE_P(memo.v))) {
4831 memo.f = RFLOAT_VALUE(memo.v);
4832 memo.c = 0.0;
4833 }
4834 else {
4835 memo.f = 0.0;
4836 memo.c = 0.0;
4837 }
4838
4839 if (RTEST(rb_range_values(obj, &beg, &end, &excl))) {
4840 if (!memo.block_given && !memo.float_value &&
4841 (FIXNUM_P(beg) || RB_BIGNUM_TYPE_P(beg)) &&
4842 (FIXNUM_P(end) || RB_BIGNUM_TYPE_P(end))) {
4843 return int_range_sum(beg, end, excl, memo.v);
4844 }
4845 }
4846
4847 if (RB_TYPE_P(obj, T_HASH) &&
4848 rb_method_basic_definition_p(CLASS_OF(obj), id_each))
4849 hash_sum(obj, &memo);
4850 else
4851 rb_block_call(obj, id_each, 0, 0, enum_sum_i, (VALUE)&memo);
4852
4853 if (memo.float_value) {
4854 return DBL2NUM(memo.f + memo.c);
4855 }
4856 else {
4857 if (memo.n != 0)
4858 memo.v = rb_fix_plus(LONG2FIX(memo.n), memo.v);
4859 if (!UNDEF_P(memo.r)) {
4860 memo.v = rb_rational_plus(memo.r, memo.v);
4861 }
4862 return memo.v;
4863 }
4864}
4865
4866static VALUE
4867uniq_func(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
4868{
4869 ENUM_WANT_SVALUE();
4870 rb_hash_add_new_element(hash, i, i);
4871 return Qnil;
4872}
4873
4874static VALUE
4875uniq_iter(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
4876{
4877 ENUM_WANT_SVALUE();
4878 rb_hash_add_new_element(hash, rb_yield_values2(argc, argv), i);
4879 return Qnil;
4880}
4881
4882/*
4883 * call-seq:
4884 * uniq -> array
4885 * uniq {|element| ... } -> array
4886 *
4887 * With no block, returns a new array containing only unique elements;
4888 * the array has no two elements +e0+ and +e1+ such that <tt>e0.eql?(e1)</tt>:
4889 *
4890 * %w[a b c c b a a b c].uniq # => ["a", "b", "c"]
4891 * [0, 1, 2, 2, 1, 0, 0, 1, 2].uniq # => [0, 1, 2]
4892 *
4893 * With a block, returns a new array containing elements only for which the block
4894 * returns a unique value:
4895 *
4896 * a = [0, 1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
4897 * a.uniq {|i| i.even? ? i : 0 } # => [0, 2, 4]
4898 * a = %w[a b c d e e d c b a a b c d e]
4899 * a.uniq {|c| c < 'c' } # => ["a", "c"]
4900 *
4901 */
4902
4903static VALUE
4904enum_uniq(VALUE obj)
4905{
4906 VALUE hash, ret;
4907 rb_block_call_func *const func =
4908 rb_block_given_p() ? uniq_iter : uniq_func;
4909
4910 hash = rb_obj_hide(rb_hash_new());
4911 rb_block_call(obj, id_each, 0, 0, func, hash);
4912 ret = rb_hash_values(hash);
4913 rb_hash_clear(hash);
4914 return ret;
4915}
4916
4917static VALUE
4918compact_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
4919{
4920 ENUM_WANT_SVALUE();
4921
4922 if (!NIL_P(i)) {
4923 rb_ary_push(ary, i);
4924 }
4925 return Qnil;
4926}
4927
4928/*
4929 * call-seq:
4930 * compact -> array
4931 *
4932 * Returns an array of all non-+nil+ elements:
4933 *
4934 * a = [nil, 0, nil, 'a', false, nil, false, nil, 'a', nil, 0, nil]
4935 * a.compact # => [0, "a", false, false, "a", 0]
4936 *
4937 */
4938
4939static VALUE
4940enum_compact(VALUE obj)
4941{
4942 VALUE ary;
4943
4944 ary = rb_ary_new();
4945 rb_block_call(obj, id_each, 0, 0, compact_i, ary);
4946
4947 return ary;
4948}
4949
4950
4951/*
4952 * == What's Here
4953 *
4954 * Module \Enumerable provides methods that are useful to a collection class for:
4955 *
4956 * - {Querying}[rdoc-ref:Enumerable@Methods+for+Querying]
4957 * - {Fetching}[rdoc-ref:Enumerable@Methods+for+Fetching]
4958 * - {Searching and Filtering}[rdoc-ref:Enumerable@Methods+for+Searching+and+Filtering]
4959 * - {Sorting}[rdoc-ref:Enumerable@Methods+for+Sorting]
4960 * - {Iterating}[rdoc-ref:Enumerable@Methods+for+Iterating]
4961 * - {And more....}[rdoc-ref:Enumerable@Other+Methods]
4962 *
4963 * === Methods for Querying
4964 *
4965 * These methods return information about the \Enumerable other than the elements themselves:
4966 *
4967 * - #member? (aliased as #include?): Returns +true+ if <tt>self == object</tt>, +false+ otherwise.
4968 * - #all?: Returns +true+ if all elements meet a specified criterion; +false+ otherwise.
4969 * - #any?: Returns +true+ if any element meets a specified criterion; +false+ otherwise.
4970 * - #none?: Returns +true+ if no element meets a specified criterion; +false+ otherwise.
4971 * - #one?: Returns +true+ if exactly one element meets a specified criterion; +false+ otherwise.
4972 * - #count: Returns the count of elements,
4973 * based on an argument or block criterion, if given.
4974 * - #tally: Returns a new Hash containing the counts of occurrences of each element.
4975 *
4976 * === Methods for Fetching
4977 *
4978 * These methods return entries from the \Enumerable, without modifying it:
4979 *
4980 * <i>Leading, trailing, or all elements</i>:
4981 *
4982 * - #to_a (aliased as #entries): Returns all elements.
4983 * - #first: Returns the first element or leading elements.
4984 * - #take: Returns a specified number of leading elements.
4985 * - #drop: Returns a specified number of trailing elements.
4986 * - #take_while: Returns leading elements as specified by the given block.
4987 * - #drop_while: Returns trailing elements as specified by the given block.
4988 *
4989 * <i>Minimum and maximum value elements</i>:
4990 *
4991 * - #min: Returns the elements whose values are smallest among the elements,
4992 * as determined by <tt>#<=></tt> or a given block.
4993 * - #max: Returns the elements whose values are largest among the elements,
4994 * as determined by <tt>#<=></tt> or a given block.
4995 * - #minmax: Returns a 2-element Array containing the smallest and largest elements.
4996 * - #min_by: Returns the smallest element, as determined by the given block.
4997 * - #max_by: Returns the largest element, as determined by the given block.
4998 * - #minmax_by: Returns the smallest and largest elements, as determined by the given block.
4999 *
5000 * <i>Groups, slices, and partitions</i>:
5001 *
5002 * - #group_by: Returns a Hash that partitions the elements into groups.
5003 * - #partition: Returns elements partitioned into two new Arrays, as determined by the given block.
5004 * - #slice_after: Returns a new Enumerator whose entries are a partition of +self+,
5005 * based either on a given +object+ or a given block.
5006 * - #slice_before: Returns a new Enumerator whose entries are a partition of +self+,
5007 * based either on a given +object+ or a given block.
5008 * - #slice_when: Returns a new Enumerator whose entries are a partition of +self+
5009 * based on the given block.
5010 * - #chunk: Returns elements organized into chunks as specified by the given block.
5011 * - #chunk_while: Returns elements organized into chunks as specified by the given block.
5012 *
5013 * === Methods for Searching and Filtering
5014 *
5015 * These methods return elements that meet a specified criterion:
5016 *
5017 * - #find (aliased as #detect): Returns an element selected by the block.
5018 * - #find_all (aliased as #filter, #select): Returns elements selected by the block.
5019 * - #find_index: Returns the index of an element selected by a given object or block.
5020 * - #reject: Returns elements not rejected by the block.
5021 * - #uniq: Returns elements that are not duplicates.
5022 *
5023 * === Methods for Sorting
5024 *
5025 * These methods return elements in sorted order:
5026 *
5027 * - #sort: Returns the elements, sorted by <tt>#<=></tt> or the given block.
5028 * - #sort_by: Returns the elements, sorted by the given block.
5029 *
5030 * === Methods for Iterating
5031 *
5032 * - #each_entry: Calls the block with each successive element
5033 * (slightly different from #each).
5034 * - #each_with_index: Calls the block with each successive element and its index.
5035 * - #each_with_object: Calls the block with each successive element and a given object.
5036 * - #each_slice: Calls the block with successive non-overlapping slices.
5037 * - #each_cons: Calls the block with successive overlapping slices.
5038 * (different from #each_slice).
5039 * - #reverse_each: Calls the block with each successive element, in reverse order.
5040 *
5041 * === Other Methods
5042 *
5043 * - #collect (aliased as #map): Returns objects returned by the block.
5044 * - #filter_map: Returns truthy objects returned by the block.
5045 * - #flat_map (aliased as #collect_concat): Returns flattened objects returned by the block.
5046 * - #grep: Returns elements selected by a given object
5047 * or objects returned by a given block.
5048 * - #grep_v: Returns elements not selected by a given object
5049 * or objects returned by a given block.
5050 * - #inject (aliased as #reduce): Returns the object formed by combining all elements.
5051 * - #sum: Returns the sum of the elements, using method <tt>+</tt>.
5052 * - #zip: Combines each element with elements from other enumerables;
5053 * returns the n-tuples or calls the block with each.
5054 * - #cycle: Calls the block with each element, cycling repeatedly.
5055 *
5056 * == Usage
5057 *
5058 * To use module \Enumerable in a collection class:
5059 *
5060 * - Include it:
5061 *
5062 * include Enumerable
5063 *
5064 * - Implement method <tt>#each</tt>
5065 * which must yield successive elements of the collection.
5066 * The method will be called by almost any \Enumerable method.
5067 *
5068 * Example:
5069 *
5070 * class Foo
5071 * include Enumerable
5072 * def each
5073 * yield 1
5074 * yield 1, 2
5075 * yield
5076 * end
5077 * end
5078 * Foo.new.each_entry{ |element| p element }
5079 *
5080 * Output:
5081 *
5082 * 1
5083 * [1, 2]
5084 * nil
5085 *
5086 * == \Enumerable in Ruby Classes
5087 *
5088 * These Ruby core classes include (or extend) \Enumerable:
5089 *
5090 * - ARGF
5091 * - Array
5092 * - Dir
5093 * - Enumerator
5094 * - ENV (extends)
5095 * - Hash
5096 * - IO
5097 * - Range
5098 * - Struct
5099 *
5100 * These Ruby standard library classes include \Enumerable:
5101 *
5102 * - CSV
5103 * - CSV::Table
5104 * - CSV::Row
5105 * - Set
5106 *
5107 * Virtually all methods in \Enumerable call method +#each+ in the including class:
5108 *
5109 * - <tt>Hash#each</tt> yields the next key-value pair as a 2-element Array.
5110 * - <tt>Struct#each</tt> yields the next name-value pair as a 2-element Array.
5111 * - For the other classes above, +#each+ yields the next object from the collection.
5112 *
5113 * == About the Examples
5114 *
5115 * The example code snippets for the \Enumerable methods:
5116 *
5117 * - Always show the use of one or more Array-like classes (often Array itself).
5118 * - Sometimes show the use of a Hash-like class.
5119 * For some methods, though, the usage would not make sense,
5120 * and so it is not shown. Example: #tally would find exactly one of each Hash entry.
5121 *
5122 * == Extended Methods
5123 *
5124 * A Enumerable class may define extended methods. This section describes the standard
5125 * behavior of extension methods for reference purposes.
5126 *
5127 * === #size
5128 *
5129 * \Enumerator has a #size method.
5130 * It uses the size function argument passed to +Enumerator.new+.
5131 *
5132 * e = Enumerator.new(-> { 3 }) {|y| p y; y.yield :a; y.yield :b; y.yield :c; :z }
5133 * p e.size #=> 3
5134 * p e.next #=> :a
5135 * p e.next #=> :b
5136 * p e.next #=> :c
5137 * begin
5138 * e.next
5139 * rescue StopIteration
5140 * p $!.result #=> :z
5141 * end
5142 *
5143 * The result of the size function should represent the number of iterations
5144 * (i.e., the number of times Enumerator::Yielder#yield is called).
5145 * In the above example, the block calls #yield three times, and
5146 * the size function, +-> { 3 }+, returns 3 accordingly.
5147 * The result of the size function can be an integer, +Float::INFINITY+,
5148 * or +nil+.
5149 * An integer means the exact number of times #yield will be called,
5150 * as shown above.
5151 * +Float::INFINITY+ indicates an infinite number of #yield calls.
5152 * +nil+ means the number of #yield calls is difficult or impossible to
5153 * determine.
5154 *
5155 * Many iteration methods return an \Enumerator object with an
5156 * appropriate size function if no block is given.
5157 *
5158 * Examples:
5159 *
5160 * ["a", "b", "c"].each.size #=> 3
5161 * {a: "x", b: "y", c: "z"}.each.size #=> 3
5162 * (0..20).to_a.permutation.size #=> 51090942171709440000
5163 * loop.size #=> Float::INFINITY
5164 * (1..100).drop_while.size #=> nil # size depends on the block's behavior
5165 * STDIN.each.size #=> nil # cannot be computed without consuming input
5166 * File.open("/etc/resolv.conf").each.size #=> nil # cannot be computed without reading the file
5167 *
5168 * The behavior of #size for Range-based enumerators depends on the #begin element:
5169 *
5170 * - If the #begin element is an Integer, the #size method returns an Integer or +Float::INFINITY+.
5171 * - If the #begin element is an object with a #succ method (other than Integer), #size returns +nil+.
5172 * (Computing the size would require repeatedly calling #succ, which may be too slow.)
5173 * - If the #begin element does not have a #succ method, #size raises a TypeError.
5174 *
5175 * Examples:
5176 *
5177 * (10..42).each.size #=> 33
5178 * (10..42.9).each.size #=> 33 (the #end element may be a non-integer numeric)
5179 * (10..).each.size #=> Float::INFINITY
5180 * ("a".."z").each.size #=> nil
5181 * ("a"..).each.size #=> nil
5182 * (1.0..9.0).each.size # raises TypeError (Float does not have #succ)
5183 * (..10).each.size # raises TypeError (beginless range has nil as its #begin)
5184 *
5185 * The \Enumerable module itself does not define a #size method.
5186 * A class that includes \Enumerable may define its own #size method.
5187 * It is recommended that such a #size method be consistent with
5188 * Enumerator#size.
5189 *
5190 * Array and Hash implement #size and return values consistent with
5191 * Enumerator#size.
5192 * IO and Dir do not define #size, which is also consistent because the
5193 * corresponding enumerator's size function returns +nil+.
5194 *
5195 * However, it is not strictly required for a class's #size method to match Enumerator#size.
5196 * For example, File#size returns the number of bytes in the file, not the number of lines.
5197 *
5198 */
5199
5200void
5201Init_Enumerable(void)
5202{
5203 rb_mEnumerable = rb_define_module("Enumerable");
5204
5205 rb_define_method(rb_mEnumerable, "to_a", enum_to_a, -1);
5206 rb_define_method(rb_mEnumerable, "entries", enum_to_a, -1);
5207 rb_define_method(rb_mEnumerable, "to_h", enum_to_h, -1);
5208
5209 rb_define_method(rb_mEnumerable, "sort", enum_sort, 0);
5210 rb_define_method(rb_mEnumerable, "sort_by", enum_sort_by, 0);
5211 rb_define_method(rb_mEnumerable, "grep", enum_grep, 1);
5212 rb_define_method(rb_mEnumerable, "grep_v", enum_grep_v, 1);
5213 rb_define_method(rb_mEnumerable, "count", enum_count, -1);
5214 rb_define_method(rb_mEnumerable, "find", enum_find, -1);
5215 rb_define_method(rb_mEnumerable, "detect", enum_find, -1);
5216 rb_define_method(rb_mEnumerable, "find_index", enum_find_index, -1);
5217 rb_define_method(rb_mEnumerable, "find_all", enum_find_all, 0);
5218 rb_define_method(rb_mEnumerable, "select", enum_find_all, 0);
5219 rb_define_method(rb_mEnumerable, "filter", enum_find_all, 0);
5220 rb_define_method(rb_mEnumerable, "filter_map", enum_filter_map, 0);
5221 rb_define_method(rb_mEnumerable, "reject", enum_reject, 0);
5222 rb_define_method(rb_mEnumerable, "collect", enum_collect, 0);
5223 rb_define_method(rb_mEnumerable, "map", enum_collect, 0);
5224 rb_define_method(rb_mEnumerable, "flat_map", enum_flat_map, 0);
5225 rb_define_method(rb_mEnumerable, "collect_concat", enum_flat_map, 0);
5226 rb_define_method(rb_mEnumerable, "inject", enum_inject, -1);
5227 rb_define_method(rb_mEnumerable, "reduce", enum_inject, -1);
5228 rb_define_method(rb_mEnumerable, "partition", enum_partition, 0);
5229 rb_define_method(rb_mEnumerable, "group_by", enum_group_by, 0);
5230 rb_define_method(rb_mEnumerable, "tally", enum_tally, -1);
5231 rb_define_method(rb_mEnumerable, "first", enum_first, -1);
5232 rb_define_method(rb_mEnumerable, "all?", enum_all, -1);
5233 rb_define_method(rb_mEnumerable, "any?", enum_any, -1);
5234 rb_define_method(rb_mEnumerable, "one?", enum_one, -1);
5235 rb_define_method(rb_mEnumerable, "none?", enum_none, -1);
5236 rb_define_method(rb_mEnumerable, "min", enum_min, -1);
5237 rb_define_method(rb_mEnumerable, "max", enum_max, -1);
5238 rb_define_method(rb_mEnumerable, "minmax", enum_minmax, 0);
5239 rb_define_method(rb_mEnumerable, "min_by", enum_min_by, -1);
5240 rb_define_method(rb_mEnumerable, "max_by", enum_max_by, -1);
5241 rb_define_method(rb_mEnumerable, "minmax_by", enum_minmax_by, 0);
5242 rb_define_method(rb_mEnumerable, "member?", enum_member, 1);
5243 rb_define_method(rb_mEnumerable, "include?", enum_member, 1);
5244 rb_define_method(rb_mEnumerable, "each_with_index", enum_each_with_index, -1);
5245 rb_define_method(rb_mEnumerable, "reverse_each", enum_reverse_each, -1);
5246 rb_define_method(rb_mEnumerable, "each_entry", enum_each_entry, -1);
5247 rb_define_method(rb_mEnumerable, "each_slice", enum_each_slice, 1);
5248 rb_define_method(rb_mEnumerable, "each_cons", enum_each_cons, 1);
5249 rb_define_method(rb_mEnumerable, "each_with_object", enum_each_with_object, 1);
5250 rb_define_method(rb_mEnumerable, "zip", enum_zip, -1);
5251 rb_define_method(rb_mEnumerable, "take", enum_take, 1);
5252 rb_define_method(rb_mEnumerable, "take_while", enum_take_while, 0);
5253 rb_define_method(rb_mEnumerable, "drop", enum_drop, 1);
5254 rb_define_method(rb_mEnumerable, "drop_while", enum_drop_while, 0);
5255 rb_define_method(rb_mEnumerable, "cycle", enum_cycle, -1);
5256 rb_define_method(rb_mEnumerable, "chunk", enum_chunk, 0);
5257 rb_define_method(rb_mEnumerable, "slice_before", enum_slice_before, -1);
5258 rb_define_method(rb_mEnumerable, "slice_after", enum_slice_after, -1);
5259 rb_define_method(rb_mEnumerable, "slice_when", enum_slice_when, 0);
5260 rb_define_method(rb_mEnumerable, "chunk_while", enum_chunk_while, 0);
5261 rb_define_method(rb_mEnumerable, "sum", enum_sum, -1);
5262 rb_define_method(rb_mEnumerable, "uniq", enum_uniq, 0);
5263 rb_define_method(rb_mEnumerable, "compact", enum_compact, 0);
5264
5265 id__alone = rb_intern_const("_alone");
5266 id__separator = rb_intern_const("_separator");
5267 id_chunk_categorize = rb_intern_const("chunk_categorize");
5268 id_chunk_enumerable = rb_intern_const("chunk_enumerable");
5269 id_next = rb_intern_const("next");
5270 id_sliceafter_enum = rb_intern_const("sliceafter_enum");
5271 id_sliceafter_pat = rb_intern_const("sliceafter_pat");
5272 id_sliceafter_pred = rb_intern_const("sliceafter_pred");
5273 id_slicebefore_enumerable = rb_intern_const("slicebefore_enumerable");
5274 id_slicebefore_sep_pat = rb_intern_const("slicebefore_sep_pat");
5275 id_slicebefore_sep_pred = rb_intern_const("slicebefore_sep_pred");
5276 id_slicewhen_enum = rb_intern_const("slicewhen_enum");
5277 id_slicewhen_inverted = rb_intern_const("slicewhen_inverted");
5278 id_slicewhen_pred = rb_intern_const("slicewhen_pred");
5279}
#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:2635
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 SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#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 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:2108
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:41
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2121
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:3739
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
#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_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:1838
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:3238
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:1924
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:1415
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:2958
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:2942
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:1133
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:986
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:105
Definition enum.c:2400
Definition enum.c:2277
IFUNC (Internal FUNCtion)
Definition imemo.h:84
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