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