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