Ruby 4.1.0dev (2026-09-27 revision f6ff9e7d02e46360f8930b280a3dd921cccbda29)
enum.c (f6ff9e7d02e46360f8930b280a3dd921cccbda29)
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 long n;
1950 long bufmax;
1951 long curlen;
1952 VALUE buf;
1953 VALUE limit;
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(RB_BLOCK_CALL_FUNC_ARGLIST(i, _data))
2075{
2076 struct nmin_data *data = (struct nmin_data *)_data;
2077 VALUE cmpv;
2078
2079 ENUM_WANT_SVALUE();
2080
2081 if (data->by)
2082 cmpv = enum_yield(argc, i);
2083 else
2084 cmpv = i;
2085
2086 if (!UNDEF_P(data->limit)) {
2087 int c = data->cmpfunc(&cmpv, &data->limit, data);
2088 if (data->rev)
2089 c = -c;
2090 if (c >= 0)
2091 return Qnil;
2092 }
2093
2094 if (data->by)
2095 rb_ary_push(data->buf, cmpv);
2096 rb_ary_push(data->buf, i);
2097
2098 data->curlen++;
2099
2100 if (data->curlen == data->bufmax) {
2101 nmin_filter(data);
2102 }
2103
2104 return Qnil;
2105}
2106
2107VALUE
2108rb_nmin_run(VALUE obj, VALUE num, int by, int rev, int ary)
2109{
2110 VALUE result;
2111 struct nmin_data data;
2112
2113 data.n = NUM2LONG(num);
2114 if (data.n < 0)
2115 rb_raise(rb_eArgError, "negative size (%ld)", data.n);
2116 if (data.n == 0)
2117 return rb_ary_new2(0);
2118 if (LONG_MAX/4/(by ? 2 : 1) < data.n)
2119 rb_raise(rb_eArgError, "too big size");
2120 data.bufmax = data.n * 4;
2121 data.curlen = 0;
2122 data.buf = rb_ary_hidden_new(data.bufmax * (by ? 2 : 1));
2123 data.limit = Qundef;
2124 data.cmpfunc = by ? nmin_cmp :
2125 rb_block_given_p() ? nmin_block_cmp :
2126 nmin_cmp;
2127 data.rev = rev;
2128 data.by = by;
2129 if (ary) {
2130 long i;
2131 for (i = 0; i < RARRAY_LEN(obj); i++) {
2132 VALUE args[1];
2133 args[0] = RARRAY_AREF(obj, i);
2134 nmin_i(obj, (VALUE)&data, 1, args, Qundef);
2135 }
2136 }
2137 else {
2138 rb_block_call(obj, id_each, 0, 0, nmin_i, (VALUE)&data);
2139 }
2140 nmin_filter(&data);
2141 result = data.buf;
2142 if (by) {
2143 long i;
2144 RARRAY_PTR_USE(result, ptr, {
2145 ruby_qsort(ptr,
2146 RARRAY_LEN(result)/2,
2147 sizeof(VALUE)*2,
2148 data.cmpfunc, (void *)&data);
2149 for (i=1; i<RARRAY_LEN(result); i+=2) {
2150 ptr[i/2] = ptr[i];
2151 }
2152 });
2153 rb_ary_resize(result, RARRAY_LEN(result)/2);
2154 }
2155 else {
2156 RARRAY_PTR_USE(result, ptr, {
2157 ruby_qsort(ptr, RARRAY_LEN(result), sizeof(VALUE),
2158 data.cmpfunc, (void *)&data);
2159 });
2160 }
2161 if (rev) {
2162 rb_ary_reverse(result);
2163 }
2164 RBASIC_SET_CLASS(result, rb_cArray);
2165 return result;
2166
2167}
2168
2169/*
2170 * call-seq:
2171 * one? -> true or false
2172 * one?(pattern) -> true or false
2173 * one? {|element| ... } -> true or false
2174 *
2175 * Returns whether exactly one element meets a given criterion.
2176 *
2177 * With no argument and no block,
2178 * returns whether exactly one element is truthy:
2179 *
2180 * (1..1).one? # => true
2181 * [1, nil, false].one? # => true
2182 * (1..4).one? # => false
2183 * {foo: 0}.one? # => true
2184 * {foo: 0, bar: 1}.one? # => false
2185 * [].one? # => false
2186 *
2187 * With argument +pattern+ and no block,
2188 * returns whether for exactly one element +element+,
2189 * <tt>pattern === element</tt>:
2190 *
2191 * [nil, false, 0].one?(Integer) # => true
2192 * [nil, false, 0].one?(Numeric) # => true
2193 * [nil, false, 0].one?(Float) # => false
2194 * %w[bar baz bat bam].one?(/m/) # => true
2195 * %w[bar baz bat bam].one?(/foo/) # => false
2196 * %w[bar baz bat bam].one?('ba') # => false
2197 * {foo: 0, bar: 1, baz: 2}.one?(Array) # => false
2198 * {foo: 0}.one?(Array) # => true
2199 * [].one?(Integer) # => false
2200 *
2201 * With a block given, returns whether the block returns a truthy value
2202 * for exactly one element:
2203 *
2204 * (1..4).one? {|element| element < 2 } # => true
2205 * (1..4).one? {|element| element < 1 } # => false
2206 * {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 1 } # => true
2207 * {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 2 } # => false
2208 *
2209 * Related: #none?, #all?, #any?.
2210 *
2211 */
2212static VALUE
2213enum_one(int argc, VALUE *argv, VALUE obj)
2214{
2215 struct MEMO *memo = MEMO_ENUM_NEW(Qundef);
2216 VALUE result;
2217
2218 WARN_UNUSED_BLOCK(argc);
2219 ENUM_BLOCK_CALL(one);
2220 result = memo->v1;
2221 if (UNDEF_P(result)) return Qfalse;
2222 return result;
2223}
2224
2225DEFINE_ENUMFUNCS(none)
2226{
2227 if (RTEST(result)) {
2228 MEMO_V1_SET(memo, Qfalse);
2229 rb_iter_break();
2230 }
2231 return Qnil;
2232}
2233
2234/*
2235 * call-seq:
2236 * none? -> true or false
2237 * none?(pattern) -> true or false
2238 * none? {|element| ... } -> true or false
2239 *
2240 * Returns whether no element meets a given criterion.
2241 *
2242 * With no argument and no block,
2243 * returns whether no element is truthy:
2244 *
2245 * (1..4).none? # => false
2246 * [nil, false].none? # => true
2247 * {foo: 0}.none? # => false
2248 * {foo: 0, bar: 1}.none? # => false
2249 * [].none? # => true
2250 *
2251 * With argument +pattern+ and no block,
2252 * returns whether for no element +element+,
2253 * <tt>pattern === element</tt>:
2254 *
2255 * [nil, false, 1.1].none?(Integer) # => true
2256 * %w[bar baz bat bam].none?(/m/) # => false
2257 * %w[bar baz bat bam].none?(/foo/) # => true
2258 * %w[bar baz bat bam].none?('ba') # => true
2259 * {foo: 0, bar: 1, baz: 2}.none?(Hash) # => true
2260 * {foo: 0}.none?(Array) # => false
2261 * [].none?(Integer) # => true
2262 *
2263 * With a block given, returns whether the block returns a truthy value
2264 * for no element:
2265 *
2266 * (1..4).none? {|element| element < 1 } # => true
2267 * (1..4).none? {|element| element < 2 } # => false
2268 * {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 0 } # => true
2269 * {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 1 } # => false
2270 *
2271 * Related: #one?, #all?, #any?.
2272 *
2273 */
2274static VALUE
2275enum_none(int argc, VALUE *argv, VALUE obj)
2276{
2277 struct MEMO *memo = MEMO_ENUM_NEW(Qtrue);
2278
2279 WARN_UNUSED_BLOCK(argc);
2280 ENUM_BLOCK_CALL(none);
2281 return memo->v1;
2282}
2283
2284struct min_t {
2285 VALUE min;
2286};
2287
2288static VALUE
2289min_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2290{
2291 struct min_t *memo = MEMO_FOR(struct min_t, args);
2292
2293 ENUM_WANT_SVALUE();
2294
2295 if (UNDEF_P(memo->min)) {
2296 memo->min = i;
2297 }
2298 else {
2299 if (OPTIMIZED_CMP(i, memo->min) < 0) {
2300 memo->min = i;
2301 }
2302 }
2303 return Qnil;
2304}
2305
2306static VALUE
2307min_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2308{
2309 VALUE cmp;
2310 struct min_t *memo = MEMO_FOR(struct min_t, args);
2311
2312 ENUM_WANT_SVALUE();
2313
2314 if (UNDEF_P(memo->min)) {
2315 memo->min = i;
2316 }
2317 else {
2318 cmp = rb_yield_values(2, i, memo->min);
2319 if (rb_cmpint(cmp, i, memo->min) < 0) {
2320 memo->min = i;
2321 }
2322 }
2323 return Qnil;
2324}
2325
2326
2327/*
2328 * call-seq:
2329 * min -> element
2330 * min(n) -> array
2331 * min {|a, b| ... } -> element
2332 * min(n) {|a, b| ... } -> array
2333 *
2334 * Returns the element with the minimum element according to a given criterion.
2335 * The ordering of equal elements is indeterminate and may be unstable.
2336 *
2337 * With no argument and no block, returns the minimum element,
2338 * using the elements' own method <tt>#<=></tt> for comparison:
2339 *
2340 * (1..4).min # => 1
2341 * (-4..-1).min # => -4
2342 * %w[d c b a].min # => "a"
2343 * {foo: 0, bar: 1, baz: 2}.min # => [:bar, 1]
2344 * [].min # => nil
2345 *
2346 * With positive integer argument +n+ given, and no block,
2347 * returns an array containing the first +n+ minimum elements that exist:
2348 *
2349 * (1..4).min(2) # => [1, 2]
2350 * (-4..-1).min(2) # => [-4, -3]
2351 * %w[d c b a].min(2) # => ["a", "b"]
2352 * {foo: 0, bar: 1, baz: 2}.min(2) # => [[:bar, 1], [:baz, 2]]
2353 * [].min(2) # => []
2354 *
2355 * With a block given, the block determines the minimum elements.
2356 * The block is called with two elements +a+ and +b+, and must return:
2357 *
2358 * - A negative integer if <tt>a < b</tt>.
2359 * - Zero if <tt>a == b</tt>.
2360 * - A positive integer if <tt>a > b</tt>.
2361 *
2362 * With a block given and no argument,
2363 * returns the minimum element as determined by the block:
2364 *
2365 * %w[xxx x xxxx xx].min {|a, b| a.size <=> b.size } # => "x"
2366 * h = {foo: 0, bar: 1, baz: 2}
2367 * h.min {|pair1, pair2| pair1[1] <=> pair2[1] } # => [:foo, 0]
2368 * [].min {|a, b| a <=> b } # => nil
2369 *
2370 * With a block given and positive integer argument +n+ given,
2371 * returns an array containing the first +n+ minimum elements that exist,
2372 * as determined by the block.
2373 *
2374 * %w[xxx x xxxx xx].min(2) {|a, b| a.size <=> b.size } # => ["x", "xx"]
2375 * h = {foo: 0, bar: 1, baz: 2}
2376 * h.min(2) {|pair1, pair2| pair1[1] <=> pair2[1] }
2377 * # => [[:foo, 0], [:bar, 1]]
2378 * [].min(2) {|a, b| a <=> b } # => []
2379 *
2380 * Related: #min_by, #minmax, #max.
2381 *
2382 */
2383
2384static VALUE
2385enum_min(int argc, VALUE *argv, VALUE obj)
2386{
2387 VALUE memo;
2388 struct min_t *m = NEW_MEMO_FOR(struct min_t, memo);
2389 VALUE result;
2390 VALUE num;
2391
2392 if (rb_check_arity(argc, 0, 1) && !NIL_P(num = argv[0]))
2393 return rb_nmin_run(obj, num, 0, 0, 0);
2394
2395 m->min = Qundef;
2396 if (rb_block_given_p()) {
2397 rb_block_call(obj, id_each, 0, 0, min_ii, memo);
2398 }
2399 else {
2400 rb_block_call(obj, id_each, 0, 0, min_i, memo);
2401 }
2402 result = m->min;
2403 if (UNDEF_P(result)) return Qnil;
2404 return result;
2405}
2406
2407struct max_t {
2408 VALUE max;
2409};
2410
2411static VALUE
2412max_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2413{
2414 struct max_t *memo = MEMO_FOR(struct max_t, args);
2415
2416 ENUM_WANT_SVALUE();
2417
2418 if (UNDEF_P(memo->max)) {
2419 memo->max = i;
2420 }
2421 else {
2422 if (OPTIMIZED_CMP(i, memo->max) > 0) {
2423 memo->max = i;
2424 }
2425 }
2426 return Qnil;
2427}
2428
2429static VALUE
2430max_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2431{
2432 struct max_t *memo = MEMO_FOR(struct max_t, args);
2433 VALUE cmp;
2434
2435 ENUM_WANT_SVALUE();
2436
2437 if (UNDEF_P(memo->max)) {
2438 memo->max = i;
2439 }
2440 else {
2441 cmp = rb_yield_values(2, i, memo->max);
2442 if (rb_cmpint(cmp, i, memo->max) > 0) {
2443 memo->max = i;
2444 }
2445 }
2446 return Qnil;
2447}
2448
2449/*
2450 * call-seq:
2451 * max -> element
2452 * max(n) -> array
2453 * max {|a, b| ... } -> element
2454 * max(n) {|a, b| ... } -> array
2455 *
2456 * Returns the element with the maximum element according to a given criterion.
2457 * The ordering of equal elements is indeterminate and may be unstable.
2458 *
2459 * With no argument and no block, returns the maximum element,
2460 * using the elements' own method <tt>#<=></tt> for comparison:
2461 *
2462 * (1..4).max # => 4
2463 * (-4..-1).max # => -1
2464 * %w[d c b a].max # => "d"
2465 * {foo: 0, bar: 1, baz: 2}.max # => [:foo, 0]
2466 * [].max # => nil
2467 *
2468 * With positive integer argument +n+ given, and no block,
2469 * returns an array containing the first +n+ maximum elements that exist:
2470 *
2471 * (1..4).max(2) # => [4, 3]
2472 * (-4..-1).max(2) # => [-1, -2]
2473 * %w[d c b a].max(2) # => ["d", "c"]
2474 * {foo: 0, bar: 1, baz: 2}.max(2) # => [[:foo, 0], [:baz, 2]]
2475 * [].max(2) # => []
2476 *
2477 * With a block given, the block determines the maximum elements.
2478 * The block is called with two elements +a+ and +b+, and must return:
2479 *
2480 * - A negative integer if <tt>a < b</tt>.
2481 * - Zero if <tt>a == b</tt>.
2482 * - A positive integer if <tt>a > b</tt>.
2483 *
2484 * With a block given and no argument,
2485 * returns the maximum element as determined by the block:
2486 *
2487 * %w[xxx x xxxx xx].max {|a, b| a.size <=> b.size } # => "xxxx"
2488 * h = {foo: 0, bar: 1, baz: 2}
2489 * h.max {|pair1, pair2| pair1[1] <=> pair2[1] } # => [:baz, 2]
2490 * [].max {|a, b| a <=> b } # => nil
2491 *
2492 * With a block given and positive integer argument +n+ given,
2493 * returns an array containing the first +n+ maximum elements that exist,
2494 * as determined by the block.
2495 *
2496 * %w[xxx x xxxx xx].max(2) {|a, b| a.size <=> b.size } # => ["xxxx", "xxx"]
2497 * h = {foo: 0, bar: 1, baz: 2}
2498 * h.max(2) {|pair1, pair2| pair1[1] <=> pair2[1] }
2499 * # => [[:baz, 2], [:bar, 1]]
2500 * [].max(2) {|a, b| a <=> b } # => []
2501 *
2502 * Related: #min, #minmax, #max_by.
2503 *
2504 */
2505
2506static VALUE
2507enum_max(int argc, VALUE *argv, VALUE obj)
2508{
2509 VALUE memo;
2510 struct max_t *m = NEW_MEMO_FOR(struct max_t, memo);
2511 VALUE result;
2512 VALUE num;
2513
2514 if (rb_check_arity(argc, 0, 1) && !NIL_P(num = argv[0]))
2515 return rb_nmin_run(obj, num, 0, 1, 0);
2516
2517 m->max = Qundef;
2518 if (rb_block_given_p()) {
2519 rb_block_call(obj, id_each, 0, 0, max_ii, (VALUE)memo);
2520 }
2521 else {
2522 rb_block_call(obj, id_each, 0, 0, max_i, (VALUE)memo);
2523 }
2524 result = m->max;
2525 if (UNDEF_P(result)) return Qnil;
2526 return result;
2527}
2528
2529struct minmax_t {
2530 VALUE min;
2531 VALUE max;
2532 VALUE last;
2533};
2534
2535static void
2536minmax_i_update(VALUE i, VALUE j, struct minmax_t *memo)
2537{
2538 int n;
2539
2540 if (UNDEF_P(memo->min)) {
2541 memo->min = i;
2542 memo->max = j;
2543 }
2544 else {
2545 n = OPTIMIZED_CMP(i, memo->min);
2546 if (n < 0) {
2547 memo->min = i;
2548 }
2549 n = OPTIMIZED_CMP(j, memo->max);
2550 if (n > 0) {
2551 memo->max = j;
2552 }
2553 }
2554}
2555
2556static VALUE
2557minmax_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
2558{
2559 struct minmax_t *memo = MEMO_FOR(struct minmax_t, _memo);
2560 int n;
2561 VALUE j;
2562
2563 ENUM_WANT_SVALUE();
2564
2565 if (UNDEF_P(memo->last)) {
2566 memo->last = i;
2567 return Qnil;
2568 }
2569 j = memo->last;
2570 memo->last = Qundef;
2571
2572 n = OPTIMIZED_CMP(j, i);
2573 if (n == 0)
2574 i = j;
2575 else if (n < 0) {
2576 VALUE tmp;
2577 tmp = i;
2578 i = j;
2579 j = tmp;
2580 }
2581
2582 minmax_i_update(i, j, memo);
2583
2584 return Qnil;
2585}
2586
2587static void
2588minmax_ii_update(VALUE i, VALUE j, struct minmax_t *memo)
2589{
2590 int n;
2591
2592 if (UNDEF_P(memo->min)) {
2593 memo->min = i;
2594 memo->max = j;
2595 }
2596 else {
2597 n = rb_cmpint(rb_yield_values(2, i, memo->min), i, memo->min);
2598 if (n < 0) {
2599 memo->min = i;
2600 }
2601 n = rb_cmpint(rb_yield_values(2, j, memo->max), j, memo->max);
2602 if (n > 0) {
2603 memo->max = j;
2604 }
2605 }
2606}
2607
2608static VALUE
2609minmax_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
2610{
2611 struct minmax_t *memo = MEMO_FOR(struct minmax_t, _memo);
2612 int n;
2613 VALUE j;
2614
2615 ENUM_WANT_SVALUE();
2616
2617 if (UNDEF_P(memo->last)) {
2618 memo->last = i;
2619 return Qnil;
2620 }
2621 j = memo->last;
2622 memo->last = Qundef;
2623
2624 n = rb_cmpint(rb_yield_values(2, j, i), j, i);
2625 if (n == 0)
2626 i = j;
2627 else if (n < 0) {
2628 VALUE tmp;
2629 tmp = i;
2630 i = j;
2631 j = tmp;
2632 }
2633
2634 minmax_ii_update(i, j, memo);
2635
2636 return Qnil;
2637}
2638
2639/*
2640 * call-seq:
2641 * minmax -> [minimum, maximum]
2642 * minmax {|a, b| ... } -> [minimum, maximum]
2643 *
2644 * Returns a 2-element array containing the minimum and maximum elements
2645 * according to a given criterion.
2646 * The ordering of equal elements is indeterminate and may be unstable.
2647 *
2648 * With no argument and no block, returns the minimum and maximum elements,
2649 * using the elements' own method <tt>#<=></tt> for comparison:
2650 *
2651 * (1..4).minmax # => [1, 4]
2652 * (-4..-1).minmax # => [-4, -1]
2653 * %w[d c b a].minmax # => ["a", "d"]
2654 * {foo: 0, bar: 1, baz: 2}.minmax # => [[:bar, 1], [:foo, 0]]
2655 * [].minmax # => [nil, nil]
2656 *
2657 * With a block given, returns the minimum and maximum elements
2658 * as determined by the block:
2659 *
2660 * %w[xxx x xxxx xx].minmax {|a, b| a.size <=> b.size } # => ["x", "xxxx"]
2661 * h = {foo: 0, bar: 1, baz: 2}
2662 * h.minmax {|pair1, pair2| pair1[1] <=> pair2[1] }
2663 * # => [[:foo, 0], [:baz, 2]]
2664 * [].minmax {|a, b| a <=> b } # => [nil, nil]
2665 *
2666 * Related: #min, #max, #minmax_by.
2667 *
2668 */
2669
2670static VALUE
2671enum_minmax(VALUE obj)
2672{
2673 VALUE memo;
2674 struct minmax_t *m = NEW_MEMO_FOR(struct minmax_t, memo);
2675
2676 m->min = Qundef;
2677 m->last = Qundef;
2678 if (rb_block_given_p()) {
2679 rb_block_call(obj, id_each, 0, 0, minmax_ii, memo);
2680 if (!UNDEF_P(m->last))
2681 minmax_ii_update(m->last, m->last, m);
2682 }
2683 else {
2684 rb_block_call(obj, id_each, 0, 0, minmax_i, memo);
2685 if (!UNDEF_P(m->last))
2686 minmax_i_update(m->last, m->last, m);
2687 }
2688 if (!UNDEF_P(m->min)) {
2689 return rb_assoc_new(m->min, m->max);
2690 }
2691 return rb_assoc_new(Qnil, Qnil);
2692}
2693
2694static VALUE
2695min_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2696{
2697 struct MEMO *memo = MEMO_CAST(args);
2698 VALUE v;
2699
2700 ENUM_WANT_SVALUE();
2701
2702 v = enum_yield(argc, i);
2703 if (UNDEF_P(memo->v1)) {
2704 MEMO_V1_SET(memo, v);
2705 MEMO_V2_SET(memo, i);
2706 }
2707 else if (OPTIMIZED_CMP(v, memo->v1) < 0) {
2708 MEMO_V1_SET(memo, v);
2709 MEMO_V2_SET(memo, i);
2710 }
2711 return Qnil;
2712}
2713
2714/*
2715 * call-seq:
2716 * min_by {|element| ... } -> element
2717 * min_by(n) {|element| ... } -> array
2718 * min_by -> enumerator
2719 * min_by(n) -> enumerator
2720 *
2721 * Returns the elements for which the block returns the minimum values.
2722 *
2723 * With a block given and no argument,
2724 * returns the element for which the block returns the minimum value:
2725 *
2726 * (1..4).min_by {|element| -element } # => 4
2727 * %w[a b c d].min_by {|element| -element.ord } # => "d"
2728 * {foo: 0, bar: 1, baz: 2}.min_by {|key, value| -value } # => [:baz, 2]
2729 * [].min_by {|element| -element } # => nil
2730 *
2731 * With a block given and positive integer argument +n+ given,
2732 * returns an array containing the +n+ elements
2733 * for which the block returns minimum values:
2734 *
2735 * (1..4).min_by(2) {|element| -element }
2736 * # => [4, 3]
2737 * %w[a b c d].min_by(2) {|element| -element.ord }
2738 * # => ["d", "c"]
2739 * {foo: 0, bar: 1, baz: 2}.min_by(2) {|key, value| -value }
2740 * # => [[:baz, 2], [:bar, 1]]
2741 * [].min_by(2) {|element| -element }
2742 * # => []
2743 *
2744 * Returns an Enumerator if no block is given.
2745 *
2746 * Related: #min, #minmax, #max_by.
2747 *
2748 */
2749
2750static VALUE
2751enum_min_by(int argc, VALUE *argv, VALUE obj)
2752{
2753 struct MEMO *memo;
2754 VALUE num;
2755
2756 rb_check_arity(argc, 0, 1);
2757
2758 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
2759
2760 if (argc && !NIL_P(num = argv[0]))
2761 return rb_nmin_run(obj, num, 1, 0, 0);
2762
2763 memo = rb_imemo_memo_new(Qundef, Qnil, 0);
2764 rb_block_call(obj, id_each, 0, 0, min_by_i, (VALUE)memo);
2765 return memo->v2;
2766}
2767
2768static VALUE
2769max_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2770{
2771 struct MEMO *memo = MEMO_CAST(args);
2772 VALUE v;
2773
2774 ENUM_WANT_SVALUE();
2775
2776 v = enum_yield(argc, i);
2777 if (UNDEF_P(memo->v1)) {
2778 MEMO_V1_SET(memo, v);
2779 MEMO_V2_SET(memo, i);
2780 }
2781 else if (OPTIMIZED_CMP(v, memo->v1) > 0) {
2782 MEMO_V1_SET(memo, v);
2783 MEMO_V2_SET(memo, i);
2784 }
2785 return Qnil;
2786}
2787
2788/*
2789 * call-seq:
2790 * max_by {|element| ... } -> element
2791 * max_by(n) {|element| ... } -> array
2792 * max_by -> enumerator
2793 * max_by(n) -> enumerator
2794 *
2795 * Returns the elements for which the block returns the maximum values.
2796 *
2797 * With a block given and no argument,
2798 * returns the element for which the block returns the maximum value:
2799 *
2800 * (1..4).max_by {|element| -element } # => 1
2801 * %w[a b c d].max_by {|element| -element.ord } # => "a"
2802 * {foo: 0, bar: 1, baz: 2}.max_by {|key, value| -value } # => [:foo, 0]
2803 * [].max_by {|element| -element } # => nil
2804 *
2805 * With a block given and positive integer argument +n+ given,
2806 * returns an array containing the +n+ elements
2807 * for which the block returns maximum values:
2808 *
2809 * (1..4).max_by(2) {|element| -element }
2810 * # => [1, 2]
2811 * %w[a b c d].max_by(2) {|element| -element.ord }
2812 * # => ["a", "b"]
2813 * {foo: 0, bar: 1, baz: 2}.max_by(2) {|key, value| -value }
2814 * # => [[:foo, 0], [:bar, 1]]
2815 * [].max_by(2) {|element| -element }
2816 * # => []
2817 *
2818 * Returns an Enumerator if no block is given.
2819 *
2820 * Related: #max, #minmax, #min_by.
2821 *
2822 */
2823
2824static VALUE
2825enum_max_by(int argc, VALUE *argv, VALUE obj)
2826{
2827 struct MEMO *memo;
2828 VALUE num;
2829
2830 rb_check_arity(argc, 0, 1);
2831
2832 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
2833
2834 if (argc && !NIL_P(num = argv[0]))
2835 return rb_nmin_run(obj, num, 1, 1, 0);
2836
2837 memo = rb_imemo_memo_new(Qundef, Qnil, 0);
2838 rb_block_call(obj, id_each, 0, 0, max_by_i, (VALUE)memo);
2839 return memo->v2;
2840}
2841
2843 VALUE min_bv;
2844 VALUE max_bv;
2845 VALUE min;
2846 VALUE max;
2847 VALUE last_bv;
2848 VALUE last;
2849};
2850
2851static void
2852minmax_by_i_update(VALUE v1, VALUE v2, VALUE i1, VALUE i2, struct minmax_by_t *memo)
2853{
2854 if (UNDEF_P(memo->min_bv)) {
2855 memo->min_bv = v1;
2856 memo->max_bv = v2;
2857 memo->min = i1;
2858 memo->max = i2;
2859 }
2860 else {
2861 if (OPTIMIZED_CMP(v1, memo->min_bv) < 0) {
2862 memo->min_bv = v1;
2863 memo->min = i1;
2864 }
2865 if (OPTIMIZED_CMP(v2, memo->max_bv) > 0) {
2866 memo->max_bv = v2;
2867 memo->max = i2;
2868 }
2869 }
2870}
2871
2872static VALUE
2873minmax_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
2874{
2875 struct minmax_by_t *memo = MEMO_FOR(struct minmax_by_t, _memo);
2876 VALUE vi, vj, j;
2877 int n;
2878
2879 ENUM_WANT_SVALUE();
2880
2881 vi = enum_yield(argc, i);
2882
2883 if (UNDEF_P(memo->last_bv)) {
2884 memo->last_bv = vi;
2885 memo->last = i;
2886 return Qnil;
2887 }
2888 vj = memo->last_bv;
2889 j = memo->last;
2890 memo->last_bv = Qundef;
2891
2892 n = OPTIMIZED_CMP(vj, vi);
2893 if (n == 0) {
2894 i = j;
2895 vi = vj;
2896 }
2897 else if (n < 0) {
2898 VALUE tmp;
2899 tmp = i;
2900 i = j;
2901 j = tmp;
2902 tmp = vi;
2903 vi = vj;
2904 vj = tmp;
2905 }
2906
2907 minmax_by_i_update(vi, vj, i, j, memo);
2908
2909 return Qnil;
2910}
2911
2912/*
2913 * call-seq:
2914 * minmax_by {|element| ... } -> [minimum, maximum]
2915 * minmax_by -> enumerator
2916 *
2917 * Returns a 2-element array containing the elements
2918 * for which the block returns minimum and maximum values:
2919 *
2920 * (1..4).minmax_by {|element| -element }
2921 * # => [4, 1]
2922 * %w[a b c d].minmax_by {|element| -element.ord }
2923 * # => ["d", "a"]
2924 * {foo: 0, bar: 1, baz: 2}.minmax_by {|key, value| -value }
2925 * # => [[:baz, 2], [:foo, 0]]
2926 * [].minmax_by {|element| -element }
2927 * # => [nil, nil]
2928 *
2929 * Returns an Enumerator if no block is given.
2930 *
2931 * Related: #max_by, #minmax, #min_by.
2932 *
2933 */
2934
2935static VALUE
2936enum_minmax_by(VALUE obj)
2937{
2938 VALUE memo;
2939 struct minmax_by_t *m = NEW_MEMO_FOR(struct minmax_by_t, memo);
2940
2941 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
2942
2943 m->min_bv = Qundef;
2944 m->max_bv = Qundef;
2945 m->min = Qnil;
2946 m->max = Qnil;
2947 m->last_bv = Qundef;
2948 m->last = Qundef;
2949 rb_block_call(obj, id_each, 0, 0, minmax_by_i, memo);
2950 if (!UNDEF_P(m->last_bv))
2951 minmax_by_i_update(m->last_bv, m->last_bv, m->last, m->last, m);
2952 m = MEMO_FOR(struct minmax_by_t, memo);
2953 return rb_assoc_new(m->min, m->max);
2954}
2955
2956static VALUE
2957member_i(RB_BLOCK_CALL_FUNC_ARGLIST(iter, args))
2958{
2959 struct MEMO *memo = MEMO_CAST(args);
2960
2961 if (rb_equal(rb_enum_values_pack(argc, argv), memo->v1)) {
2962 MEMO_V2_SET(memo, Qtrue);
2963 rb_iter_break();
2964 }
2965 return Qnil;
2966}
2967
2968/*
2969 * call-seq:
2970 * include?(object) -> true or false
2971 *
2972 * Returns whether for any element <tt>object == element</tt>:
2973 *
2974 * (1..4).include?(2) # => true
2975 * (1..4).include?(5) # => false
2976 * (1..4).include?('2') # => false
2977 * %w[a b c d].include?('b') # => true
2978 * %w[a b c d].include?('2') # => false
2979 * {foo: 0, bar: 1, baz: 2}.include?(:foo) # => true
2980 * {foo: 0, bar: 1, baz: 2}.include?('foo') # => false
2981 * {foo: 0, bar: 1, baz: 2}.include?(0) # => false
2982 *
2983 */
2984
2985static VALUE
2986enum_member(VALUE obj, VALUE val)
2987{
2988 struct MEMO *memo = rb_imemo_memo_new(val, Qfalse, 0);
2989
2990 rb_block_call(obj, id_each, 0, 0, member_i, (VALUE)memo);
2991 return memo->v2;
2992}
2993
2994static VALUE
2995each_with_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(_, index))
2996{
2997 struct vm_ifunc *ifunc = rb_current_ifunc();
2998 ifunc->data = (const void *)rb_int_succ(index);
2999
3000 return rb_yield_values(2, rb_enum_values_pack(argc, argv), index);
3001}
3002
3003/*
3004 * call-seq:
3005 * each_with_index(*args) {|element, i| ..... } -> self
3006 * each_with_index(*args) -> enumerator
3007 *
3008 * Invoke <tt>self.each</tt> with <tt>*args</tt>.
3009 * With a block given, the block receives each element and its index;
3010 * returns +self+:
3011 *
3012 * h = {}
3013 * (1..4).each_with_index {|element, i| h[element] = i } # => 1..4
3014 * h # => {1=>0, 2=>1, 3=>2, 4=>3}
3015 *
3016 * h = {}
3017 * %w[a b c d].each_with_index {|element, i| h[element] = i }
3018 * # => ["a", "b", "c", "d"]
3019 * h # => {"a"=>0, "b"=>1, "c"=>2, "d"=>3}
3020 *
3021 * a = []
3022 * h = {foo: 0, bar: 1, baz: 2}
3023 * h.each_with_index {|element, i| a.push([i, element]) }
3024 * # => {:foo=>0, :bar=>1, :baz=>2}
3025 * a # => [[0, [:foo, 0]], [1, [:bar, 1]], [2, [:baz, 2]]]
3026 *
3027 * With no block given, returns an Enumerator.
3028 *
3029 */
3030
3031static VALUE
3032enum_each_with_index(int argc, VALUE *argv, VALUE obj)
3033{
3034 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
3035
3036 rb_block_call(obj, id_each, argc, argv, each_with_index_i, INT2FIX(0));
3037 return obj;
3038}
3039
3040
3041/*
3042 * call-seq:
3043 * reverse_each(*args) {|element| ... } -> self
3044 * reverse_each(*args) -> enumerator
3045 *
3046 * With a block given, calls the block with each element,
3047 * but in reverse order; returns +self+:
3048 *
3049 * a = []
3050 * (1..4).reverse_each {|element| a.push(-element) } # => 1..4
3051 * a # => [-4, -3, -2, -1]
3052 *
3053 * a = []
3054 * %w[a b c d].reverse_each {|element| a.push(element) }
3055 * # => ["a", "b", "c", "d"]
3056 * a # => ["d", "c", "b", "a"]
3057 *
3058 * a = []
3059 * h.reverse_each {|element| a.push(element) }
3060 * # => {:foo=>0, :bar=>1, :baz=>2}
3061 * a # => [[:baz, 2], [:bar, 1], [:foo, 0]]
3062 *
3063 * With no block given, returns an Enumerator.
3064 *
3065 */
3066
3067static VALUE
3068enum_reverse_each(int argc, VALUE *argv, VALUE obj)
3069{
3070 VALUE ary;
3071 long len;
3072
3073 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
3074
3075 ary = enum_to_a(argc, argv, obj);
3076
3077 len = RARRAY_LEN(ary);
3078 while (len--) {
3079 long nlen;
3080 rb_yield(RARRAY_AREF(ary, len));
3081 nlen = RARRAY_LEN(ary);
3082 if (nlen < len) {
3083 len = nlen;
3084 }
3085 }
3086
3087 return obj;
3088}
3089
3090
3091static VALUE
3092each_val_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
3093{
3094 ENUM_WANT_SVALUE();
3095 enum_yield(argc, i);
3096 return Qnil;
3097}
3098
3099/*
3100 * call-seq:
3101 * each_entry(*args) {|element| ... } -> self
3102 * each_entry(*args) -> enumerator
3103 *
3104 * Calls the given block with each element,
3105 * converting multiple values from yield to an array; returns +self+:
3106 *
3107 * a = []
3108 * (1..4).each_entry {|element| a.push(element) } # => 1..4
3109 * a # => [1, 2, 3, 4]
3110 *
3111 * a = []
3112 * h = {foo: 0, bar: 1, baz:2}
3113 * h.each_entry {|element| a.push(element) }
3114 * # => {:foo=>0, :bar=>1, :baz=>2}
3115 * a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3116 *
3117 * class Foo
3118 * include Enumerable
3119 * def each
3120 * yield 1
3121 * yield 1, 2
3122 * yield
3123 * end
3124 * end
3125 * Foo.new.each_entry {|yielded| p yielded }
3126 *
3127 * Output:
3128 *
3129 * 1
3130 * [1, 2]
3131 * nil
3132 *
3133 * With no block given, returns an Enumerator.
3134 *
3135 */
3136
3137static VALUE
3138enum_each_entry(int argc, VALUE *argv, VALUE obj)
3139{
3140 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
3141 rb_block_call(obj, id_each, argc, argv, each_val_i, 0);
3142 return obj;
3143}
3144
3145static VALUE
3146add_int(VALUE x, long n)
3147{
3148 const VALUE y = LONG2NUM(n);
3149 if (RB_INTEGER_TYPE_P(x)) return rb_int_plus(x, y);
3150 return rb_funcallv(x, '+', 1, &y);
3151}
3152
3153static VALUE
3154div_int(VALUE x, long n)
3155{
3156 const VALUE y = LONG2NUM(n);
3157 if (RB_INTEGER_TYPE_P(x)) return rb_int_idiv(x, y);
3158 return rb_funcallv(x, id_div, 1, &y);
3159}
3160
3161#define dont_recycle_block_arg(arity) ((arity) == 1 || (arity) < 0)
3162
3163static VALUE
3164each_slice_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, m))
3165{
3166 struct MEMO *memo = MEMO_CAST(m);
3167 VALUE ary = memo->v1;
3168 VALUE v = Qnil;
3169 long size = memo->u3.cnt;
3170 ENUM_WANT_SVALUE();
3171
3172 rb_ary_push(ary, i);
3173
3174 if (RARRAY_LEN(ary) == size) {
3175 v = rb_yield(ary);
3176
3177 if (memo->v2) {
3178 MEMO_V1_SET(memo, rb_ary_new2(size));
3179 }
3180 else {
3181 rb_ary_clear(ary);
3182 }
3183 }
3184
3185 return v;
3186}
3187
3188static VALUE
3189enum_each_slice_size(VALUE obj, VALUE args, VALUE eobj)
3190{
3191 VALUE n, size;
3192 long slice_size = NUM2LONG(RARRAY_AREF(args, 0));
3193 ID infinite_p;
3194 CONST_ID(infinite_p, "infinite?");
3195 if (slice_size <= 0) rb_raise(rb_eArgError, "invalid slice size");
3196
3197 size = enum_size(obj, 0, 0);
3198 if (NIL_P(size)) return Qnil;
3199 if (RB_FLOAT_TYPE_P(size) && RTEST(rb_funcall(size, infinite_p, 0))) {
3200 return size;
3201 }
3202
3203 n = add_int(size, slice_size-1);
3204 return div_int(n, slice_size);
3205}
3206
3207/*
3208 * call-seq:
3209 * each_slice(n) { ... } -> self
3210 * each_slice(n) -> enumerator
3211 *
3212 * Calls the block with each successive disjoint +n+-tuple of elements;
3213 * returns +self+:
3214 *
3215 * a = []
3216 * (1..10).each_slice(3) {|tuple| a.push(tuple) }
3217 * a # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
3218 *
3219 * a = []
3220 * h = {foo: 0, bar: 1, baz: 2, bat: 3, bam: 4}
3221 * h.each_slice(2) {|tuple| a.push(tuple) }
3222 * a # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]], [[:bam, 4]]]
3223 *
3224 * With no block given, returns an Enumerator.
3225 *
3226 */
3227static VALUE
3228enum_each_slice(VALUE obj, VALUE n)
3229{
3230 long size = NUM2LONG(n);
3231 VALUE ary;
3232 struct MEMO *memo;
3233 int arity;
3234
3235 if (size <= 0) rb_raise(rb_eArgError, "invalid slice size");
3236 RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_slice_size);
3237 size = limit_by_enum_size(obj, size);
3238 ary = rb_ary_new2(size);
3239 arity = rb_block_arity();
3240 memo = rb_imemo_memo_new(ary, dont_recycle_block_arg(arity), size);
3241 rb_block_call(obj, id_each, 0, 0, each_slice_i, (VALUE)memo);
3242 ary = memo->v1;
3243 if (RARRAY_LEN(ary) > 0) rb_yield(ary);
3244
3245 return obj;
3246}
3247
3248static VALUE
3249each_cons_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3250{
3251 struct MEMO *memo = MEMO_CAST(args);
3252 VALUE ary = memo->v1;
3253 VALUE v = Qnil;
3254 long size = memo->u3.cnt;
3255 ENUM_WANT_SVALUE();
3256
3257 if (RARRAY_LEN(ary) == size) {
3258 rb_ary_shift(ary);
3259 }
3260 rb_ary_push(ary, i);
3261 if (RARRAY_LEN(ary) == size) {
3262 if (memo->v2) {
3263 ary = rb_ary_dup(ary);
3264 }
3265 v = rb_yield(ary);
3266 }
3267 return v;
3268}
3269
3270static VALUE
3271enum_each_cons_size(VALUE obj, VALUE args, VALUE eobj)
3272{
3273 const VALUE zero = LONG2FIX(0);
3274 VALUE n, size;
3275 long cons_size = NUM2LONG(RARRAY_AREF(args, 0));
3276 if (cons_size <= 0) rb_raise(rb_eArgError, "invalid size");
3277
3278 size = enum_size(obj, 0, 0);
3279 if (NIL_P(size)) return Qnil;
3280
3281 n = add_int(size, 1 - cons_size);
3282 return (OPTIMIZED_CMP(n, zero) == -1) ? zero : n;
3283}
3284
3285/*
3286 * call-seq:
3287 * each_cons(n) { ... } -> self
3288 * each_cons(n) -> enumerator
3289 *
3290 * Calls the block with each successive overlapped +n+-tuple of elements;
3291 * returns +self+:
3292 *
3293 * a = []
3294 * (1..5).each_cons(3) {|element| a.push(element) }
3295 * a # => [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
3296 *
3297 * a = []
3298 * h = {foo: 0, bar: 1, baz: 2, bam: 3}
3299 * h.each_cons(2) {|element| a.push(element) }
3300 * a # => [[[:foo, 0], [:bar, 1]], [[:bar, 1], [:baz, 2]], [[:baz, 2], [:bam, 3]]]
3301 *
3302 * With no block given, returns an Enumerator.
3303 *
3304 */
3305static VALUE
3306enum_each_cons(VALUE obj, VALUE n)
3307{
3308 long size = NUM2LONG(n);
3309 struct MEMO *memo;
3310 int arity;
3311
3312 if (size <= 0) rb_raise(rb_eArgError, "invalid size");
3313 RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_cons_size);
3314 arity = rb_block_arity();
3315 if (enum_size_over_p(obj, size)) return obj;
3316 memo = rb_imemo_memo_new(rb_ary_new2(size), dont_recycle_block_arg(arity), size);
3317 rb_block_call(obj, id_each, 0, 0, each_cons_i, (VALUE)memo);
3318
3319 return obj;
3320}
3321
3322static VALUE
3323each_with_object_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo))
3324{
3325 ENUM_WANT_SVALUE();
3326 return rb_yield_values(2, i, memo);
3327}
3328
3329/*
3330 * call-seq:
3331 * each_with_object(object) { |(*args), memo_object| ... } -> object
3332 * each_with_object(object) -> enumerator
3333 *
3334 * Calls the block once for each element, passing both the element
3335 * and the given object:
3336 *
3337 * (1..4).each_with_object([]) {|i, a| a.push(i**2) }
3338 * # => [1, 4, 9, 16]
3339 *
3340 * {foo: 0, bar: 1, baz: 2}.each_with_object({}) {|(k, v), h| h[v] = k }
3341 * # => {0=>:foo, 1=>:bar, 2=>:baz}
3342 *
3343 * With no block given, returns an Enumerator.
3344 *
3345 */
3346static VALUE
3347enum_each_with_object(VALUE obj, VALUE memo)
3348{
3349 RETURN_SIZED_ENUMERATOR(obj, 1, &memo, enum_size);
3350
3351 rb_block_call(obj, id_each, 0, 0, each_with_object_i, memo);
3352
3353 return memo;
3354}
3355
3356static VALUE
3357zip_ary(RB_BLOCK_CALL_FUNC_ARGLIST(val, memoval))
3358{
3359 struct MEMO *memo = (struct MEMO *)memoval;
3360 VALUE result = memo->v1;
3361 VALUE args = memo->v2;
3362 long n = memo->u3.cnt++;
3363 VALUE tmp;
3364 int i;
3365
3366 tmp = rb_ary_new2(RARRAY_LEN(args) + 1);
3367 rb_ary_store(tmp, 0, rb_enum_values_pack(argc, argv));
3368 for (i=0; i<RARRAY_LEN(args); i++) {
3369 VALUE e = RARRAY_AREF(args, i);
3370
3371 if (RARRAY_LEN(e) <= n) {
3372 rb_ary_push(tmp, Qnil);
3373 }
3374 else {
3375 rb_ary_push(tmp, RARRAY_AREF(e, n));
3376 }
3377 }
3378 if (NIL_P(result)) {
3379 enum_yield_array(tmp);
3380 }
3381 else {
3382 rb_ary_push(result, tmp);
3383 }
3384
3385 RB_GC_GUARD(args);
3386
3387 return Qnil;
3388}
3389
3390static VALUE
3391call_next(VALUE w)
3392{
3393 VALUE *v = (VALUE *)w;
3394 return v[0] = rb_funcallv(v[1], id_next, 0, 0);
3395}
3396
3397static VALUE
3398call_stop(VALUE w, VALUE _)
3399{
3400 VALUE *v = (VALUE *)w;
3401 return v[0] = Qundef;
3402}
3403
3404static VALUE
3405zip_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, memoval))
3406{
3407 struct MEMO *memo = (struct MEMO *)memoval;
3408 VALUE result = memo->v1;
3409 VALUE args = memo->v2;
3410 VALUE tmp;
3411 int i;
3412
3413 tmp = rb_ary_new2(RARRAY_LEN(args) + 1);
3414 rb_ary_store(tmp, 0, rb_enum_values_pack(argc, argv));
3415 for (i=0; i<RARRAY_LEN(args); i++) {
3416 if (NIL_P(RARRAY_AREF(args, i))) {
3417 rb_ary_push(tmp, Qnil);
3418 }
3419 else {
3420 VALUE v[2];
3421
3422 v[1] = RARRAY_AREF(args, i);
3423 rb_rescue2(call_next, (VALUE)v, call_stop, (VALUE)v, rb_eStopIteration, (VALUE)0);
3424 if (UNDEF_P(v[0])) {
3425 RARRAY_ASET(args, i, Qnil);
3426 v[0] = Qnil;
3427 }
3428 rb_ary_push(tmp, v[0]);
3429 }
3430 }
3431 if (NIL_P(result)) {
3432 enum_yield_array(tmp);
3433 }
3434 else {
3435 rb_ary_push(result, tmp);
3436 }
3437
3438 RB_GC_GUARD(args);
3439
3440 return Qnil;
3441}
3442
3443/*
3444 * call-seq:
3445 * zip(*other_enums) -> array
3446 * zip(*other_enums) {|array| ... } -> nil
3447 *
3448 * With no block given, returns a new array +new_array+ of size self.size
3449 * whose elements are arrays.
3450 * Each nested array <tt>new_array[n]</tt>
3451 * is of size <tt>other_enums.size+1</tt>, and contains:
3452 *
3453 * - The +n+-th element of self.
3454 * - The +n+-th element of each of the +other_enums+.
3455 *
3456 * If all +other_enums+ and self are the same size,
3457 * all elements are included in the result, and there is no +nil+-filling:
3458 *
3459 * a = [:a0, :a1, :a2, :a3]
3460 * b = [:b0, :b1, :b2, :b3]
3461 * c = [:c0, :c1, :c2, :c3]
3462 * d = a.zip(b, c)
3463 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
3464 *
3465 * f = {foo: 0, bar: 1, baz: 2}
3466 * g = {goo: 3, gar: 4, gaz: 5}
3467 * h = {hoo: 6, har: 7, haz: 8}
3468 * d = f.zip(g, h)
3469 * d # => [
3470 * # [[:foo, 0], [:goo, 3], [:hoo, 6]],
3471 * # [[:bar, 1], [:gar, 4], [:har, 7]],
3472 * # [[:baz, 2], [:gaz, 5], [:haz, 8]]
3473 * # ]
3474 *
3475 * If any enumerable in other_enums is smaller than self,
3476 * fills to <tt>self.size</tt> with +nil+:
3477 *
3478 * a = [:a0, :a1, :a2, :a3]
3479 * b = [:b0, :b1, :b2]
3480 * c = [:c0, :c1]
3481 * d = a.zip(b, c)
3482 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, nil], [:a3, nil, nil]]
3483 *
3484 * If any enumerable in other_enums is larger than self,
3485 * its trailing elements are ignored:
3486 *
3487 * a = [:a0, :a1, :a2, :a3]
3488 * b = [:b0, :b1, :b2, :b3, :b4]
3489 * c = [:c0, :c1, :c2, :c3, :c4, :c5]
3490 * d = a.zip(b, c)
3491 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
3492 *
3493 * When a block is given, calls the block with each of the sub-arrays
3494 * (formed as above); returns nil:
3495 *
3496 * a = [:a0, :a1, :a2, :a3]
3497 * b = [:b0, :b1, :b2, :b3]
3498 * c = [:c0, :c1, :c2, :c3]
3499 * a.zip(b, c) {|sub_array| p sub_array} # => nil
3500 *
3501 * Output:
3502 *
3503 * [:a0, :b0, :c0]
3504 * [:a1, :b1, :c1]
3505 * [:a2, :b2, :c2]
3506 * [:a3, :b3, :c3]
3507 *
3508 */
3509
3510static VALUE
3511enum_zip(int argc, VALUE *argv, VALUE obj)
3512{
3513 int i;
3514 ID conv;
3515 struct MEMO *memo;
3516 VALUE result = Qnil;
3517 VALUE args = rb_ary_new4(argc, argv);
3518 int allary = TRUE;
3519
3520 argv = RARRAY_PTR(args);
3521 for (i=0; i<argc; i++) {
3522 VALUE ary = rb_check_array_type(argv[i]);
3523 if (NIL_P(ary)) {
3524 allary = FALSE;
3525 break;
3526 }
3527 argv[i] = ary;
3528 }
3529 if (!allary) {
3530 static const VALUE sym_each = STATIC_ID2SYM(id_each);
3531 CONST_ID(conv, "to_enum");
3532 for (i=0; i<argc; i++) {
3533 if (!rb_respond_to(argv[i], id_each)) {
3534 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (must respond to :each)",
3535 rb_obj_class(argv[i]));
3536 }
3537 argv[i] = rb_funcallv(argv[i], conv, 1, &sym_each);
3538 }
3539 }
3540 if (!rb_block_given_p()) {
3541 result = rb_ary_new();
3542 }
3543
3544 /* TODO: use NODE_DOT2 as memo(v, v, -) */
3545 memo = rb_imemo_memo_new(result, args, 0);
3546 rb_block_call(obj, id_each, 0, 0, allary ? zip_ary : zip_i, (VALUE)memo);
3547
3548 return result;
3549}
3550
3551static VALUE
3552take_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3553{
3554 struct MEMO *memo = MEMO_CAST(args);
3555 rb_ary_push(memo->v1, rb_enum_values_pack(argc, argv));
3556 if (--memo->u3.cnt == 0) rb_iter_break();
3557 return Qnil;
3558}
3559
3560/*
3561 * call-seq:
3562 * take(n) -> array
3563 *
3564 * For non-negative integer +n+, returns the first +n+ elements:
3565 *
3566 * r = (1..4)
3567 * r.take(2) # => [1, 2]
3568 * r.take(0) # => []
3569 *
3570 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
3571 * h.take(2) # => [[:foo, 0], [:bar, 1]]
3572 *
3573 */
3574
3575static VALUE
3576enum_take(VALUE obj, VALUE n)
3577{
3578 struct MEMO *memo;
3579 VALUE result;
3580 long len = NUM2LONG(n);
3581
3582 if (len < 0) {
3583 rb_raise(rb_eArgError, "attempt to take negative size");
3584 }
3585
3586 if (len == 0) return rb_ary_new2(0);
3587 result = rb_ary_new2(len);
3588 memo = rb_imemo_memo_new(result, 0, len);
3589 rb_block_call(obj, id_each, 0, 0, take_i, (VALUE)memo);
3590 return result;
3591}
3592
3593
3594static VALUE
3595take_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
3596{
3597 if (!RTEST(rb_yield_values2(argc, argv))) rb_iter_break();
3598 rb_ary_push(ary, rb_enum_values_pack(argc, argv));
3599 return Qnil;
3600}
3601
3602/*
3603 * call-seq:
3604 * take_while {|element| ... } -> array
3605 * take_while -> enumerator
3606 *
3607 * Calls the block with successive elements as long as the block
3608 * returns a truthy value;
3609 * returns an array of all elements up to that point:
3610 *
3611 *
3612 * (1..4).take_while{|i| i < 3 } # => [1, 2]
3613 * h = {foo: 0, bar: 1, baz: 2}
3614 * h.take_while{|element| key, value = *element; value < 2 }
3615 * # => [[:foo, 0], [:bar, 1]]
3616 *
3617 * With no block given, returns an Enumerator.
3618 *
3619 */
3620
3621static VALUE
3622enum_take_while(VALUE obj)
3623{
3624 VALUE ary;
3625
3626 RETURN_ENUMERATOR(obj, 0, 0);
3627 ary = rb_ary_new();
3628 rb_block_call(obj, id_each, 0, 0, take_while_i, ary);
3629 return ary;
3630}
3631
3632static VALUE
3633drop_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3634{
3635 struct MEMO *memo = MEMO_CAST(args);
3636 if (memo->u3.cnt == 0) {
3637 rb_ary_push(memo->v1, rb_enum_values_pack(argc, argv));
3638 }
3639 else {
3640 memo->u3.cnt--;
3641 }
3642 return Qnil;
3643}
3644
3645/*
3646 * call-seq:
3647 * drop(n) -> array
3648 *
3649 * For positive integer +n+, returns an array containing
3650 * all but the first +n+ elements:
3651 *
3652 * r = (1..4)
3653 * r.drop(3) # => [4]
3654 * r.drop(2) # => [3, 4]
3655 * r.drop(1) # => [2, 3, 4]
3656 * r.drop(0) # => [1, 2, 3, 4]
3657 * r.drop(50) # => []
3658 *
3659 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
3660 * h.drop(2) # => [[:baz, 2], [:bat, 3]]
3661 *
3662 */
3663
3664static VALUE
3665enum_drop(VALUE obj, VALUE n)
3666{
3667 VALUE result;
3668 struct MEMO *memo;
3669 long len = NUM2LONG(n);
3670
3671 if (len < 0) {
3672 rb_raise(rb_eArgError, "attempt to drop negative size");
3673 }
3674
3675 result = rb_ary_new();
3676 memo = rb_imemo_memo_new(result, 0, len);
3677 rb_block_call(obj, id_each, 0, 0, drop_i, (VALUE)memo);
3678 return result;
3679}
3680
3681
3682static VALUE
3683drop_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3684{
3685 struct MEMO *memo = MEMO_CAST(args);
3686 ENUM_WANT_SVALUE();
3687
3688 if (!memo->u3.state && !RTEST(enum_yield(argc, i))) {
3689 memo->u3.state = TRUE;
3690 }
3691 if (memo->u3.state) {
3692 rb_ary_push(memo->v1, i);
3693 }
3694 return Qnil;
3695}
3696
3697/*
3698 * call-seq:
3699 * drop_while {|element| ... } -> array
3700 * drop_while -> enumerator
3701 *
3702 * Calls the block with successive elements as long as the block
3703 * returns a truthy value;
3704 * returns an array of all elements after that point:
3705 *
3706 *
3707 * (1..4).drop_while{|i| i < 3 } # => [3, 4]
3708 * h = {foo: 0, bar: 1, baz: 2}
3709 * a = h.drop_while{|element| key, value = *element; value < 2 }
3710 * a # => [[:baz, 2]]
3711 *
3712 * With no block given, returns an Enumerator.
3713 *
3714 * e = (1..4).drop_while
3715 * p e #=> #<Enumerator: 1..4:drop_while>
3716 * i = e.next; p i; e.feed(i < 3) #=> 1
3717 * i = e.next; p i; e.feed(i < 3) #=> 2
3718 * i = e.next; p i; e.feed(i < 3) #=> 3
3719 * begin
3720 * e.next
3721 * rescue StopIteration
3722 * p $!.result #=> [3, 4]
3723 * end
3724 *
3725 */
3726
3727static VALUE
3728enum_drop_while(VALUE obj)
3729{
3730 VALUE result;
3731 struct MEMO *memo;
3732
3733 RETURN_ENUMERATOR(obj, 0, 0);
3734 result = rb_ary_new();
3735 memo = rb_imemo_memo_new(result, 0, FALSE);
3736 rb_block_call(obj, id_each, 0, 0, drop_while_i, (VALUE)memo);
3737 return result;
3738}
3739
3740static VALUE
3741cycle_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
3742{
3743 ENUM_WANT_SVALUE();
3744
3745 rb_ary_push(ary, argc > 1 ? i : rb_ary_new_from_values(argc, argv));
3746 enum_yield(argc, i);
3747 return Qnil;
3748}
3749
3750static VALUE
3751enum_cycle_size(VALUE self, VALUE args, VALUE eobj)
3752{
3753 long mul = 0;
3754 VALUE n = Qnil;
3755 VALUE size;
3756
3757 if (args && (RARRAY_LEN(args) > 0)) {
3758 n = RARRAY_AREF(args, 0);
3759 if (!NIL_P(n)) mul = NUM2LONG(n);
3760 }
3761
3762 size = enum_size(self, args, 0);
3763 if (NIL_P(size) || FIXNUM_ZERO_P(size)) return size;
3764
3765 if (NIL_P(n)) return DBL2NUM(HUGE_VAL);
3766 if (mul <= 0) return INT2FIX(0);
3767 n = LONG2FIX(mul);
3768 return rb_funcallv(size, '*', 1, &n);
3769}
3770
3771/*
3772 * call-seq:
3773 * cycle(n = nil) {|element| ...} -> nil
3774 * cycle(n = nil) -> enumerator
3775 *
3776 * When called with positive integer argument +n+ and a block,
3777 * calls the block with each element, then does so again,
3778 * until it has done so +n+ times; returns +nil+:
3779 *
3780 * a = []
3781 * (1..4).cycle(3) {|element| a.push(element) } # => nil
3782 * a # => [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
3783 * a = []
3784 * ('a'..'d').cycle(2) {|element| a.push(element) }
3785 * a # => ["a", "b", "c", "d", "a", "b", "c", "d"]
3786 * a = []
3787 * {foo: 0, bar: 1, baz: 2}.cycle(2) {|element| a.push(element) }
3788 * a # => [[:foo, 0], [:bar, 1], [:baz, 2], [:foo, 0], [:bar, 1], [:baz, 2]]
3789 *
3790 * If count is zero or negative, does not call the block.
3791 *
3792 * When called with a block and +n+ is +nil+, cycles forever.
3793 *
3794 * When no block is given, returns an Enumerator.
3795 *
3796 */
3797
3798static VALUE
3799enum_cycle(int argc, VALUE *argv, VALUE obj)
3800{
3801 VALUE ary;
3802 VALUE nv = Qnil;
3803 long n, i, len;
3804
3805 rb_check_arity(argc, 0, 1);
3806
3807 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_cycle_size);
3808 if (!argc || NIL_P(nv = argv[0])) {
3809 n = -1;
3810 }
3811 else {
3812 n = NUM2LONG(nv);
3813 if (n <= 0) return Qnil;
3814 }
3815 ary = rb_ary_new();
3816 RBASIC_CLEAR_CLASS(ary);
3817 rb_block_call(obj, id_each, 0, 0, cycle_i, ary);
3818 len = RARRAY_LEN(ary);
3819 if (len == 0) return Qnil;
3820 while (n < 0 || 0 < --n) {
3821 for (i=0; i<len; i++) {
3822 enum_yield_array(RARRAY_AREF(ary, i));
3823 }
3824 }
3825 return Qnil;
3826}
3827
3829 VALUE categorize;
3830 VALUE prev_value;
3831 VALUE prev_elts;
3832 VALUE yielder;
3833};
3834
3835static VALUE
3836chunk_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
3837{
3838 struct chunk_arg *argp = MEMO_FOR(struct chunk_arg, _argp);
3839 VALUE v, s;
3840 VALUE alone = ID2SYM(id__alone);
3841 VALUE separator = ID2SYM(id__separator);
3842
3843 ENUM_WANT_SVALUE();
3844
3845 v = rb_funcallv(argp->categorize, id_call, 1, &i);
3846
3847 if (v == alone) {
3848 if (!NIL_P(argp->prev_value)) {
3849 s = rb_assoc_new(argp->prev_value, argp->prev_elts);
3850 rb_funcallv(argp->yielder, id_lshift, 1, &s);
3851 argp->prev_value = argp->prev_elts = Qnil;
3852 }
3853 v = rb_assoc_new(v, rb_ary_new3(1, i));
3854 rb_funcallv(argp->yielder, id_lshift, 1, &v);
3855 }
3856 else if (NIL_P(v) || v == separator) {
3857 if (!NIL_P(argp->prev_value)) {
3858 v = rb_assoc_new(argp->prev_value, argp->prev_elts);
3859 rb_funcallv(argp->yielder, id_lshift, 1, &v);
3860 argp->prev_value = argp->prev_elts = Qnil;
3861 }
3862 }
3863 else if (SYMBOL_P(v) && (s = rb_sym2str(v), RSTRING_PTR(s)[0] == '_')) {
3864 rb_raise(rb_eRuntimeError, "symbols beginning with an underscore are reserved");
3865 }
3866 else {
3867 if (NIL_P(argp->prev_value)) {
3868 argp->prev_value = v;
3869 argp->prev_elts = rb_ary_new3(1, i);
3870 }
3871 else {
3872 if (rb_equal(argp->prev_value, v)) {
3873 rb_ary_push(argp->prev_elts, i);
3874 }
3875 else {
3876 s = rb_assoc_new(argp->prev_value, argp->prev_elts);
3877 rb_funcallv(argp->yielder, id_lshift, 1, &s);
3878 argp->prev_value = v;
3879 argp->prev_elts = rb_ary_new3(1, i);
3880 }
3881 }
3882 }
3883 return Qnil;
3884}
3885
3886static VALUE
3888{
3889 VALUE enumerable;
3890 VALUE arg;
3891 struct chunk_arg *memo = NEW_MEMO_FOR(struct chunk_arg, arg);
3892
3893 enumerable = rb_ivar_get(enumerator, id_chunk_enumerable);
3894 memo->categorize = rb_ivar_get(enumerator, id_chunk_categorize);
3895 memo->prev_value = Qnil;
3896 memo->prev_elts = Qnil;
3897 memo->yielder = yielder;
3898
3899 rb_block_call(enumerable, id_each, 0, 0, chunk_ii, arg);
3900 memo = MEMO_FOR(struct chunk_arg, arg);
3901 if (!NIL_P(memo->prev_elts)) {
3902 arg = rb_assoc_new(memo->prev_value, memo->prev_elts);
3903 rb_funcallv(memo->yielder, id_lshift, 1, &arg);
3904 }
3905 return Qnil;
3906}
3907
3908/*
3909 * call-seq:
3910 * chunk {|array| ... } -> enumerator
3911 *
3912 * Each element in the returned enumerator is a 2-element array consisting of:
3913 *
3914 * - A value returned by the block.
3915 * - An array ("chunk") containing the element for which that value was returned,
3916 * and all following elements for which the block returned the same value:
3917 *
3918 * So that:
3919 *
3920 * - Each block return value that is different from its predecessor
3921 * begins a new chunk.
3922 * - Each block return value that is the same as its predecessor
3923 * continues the same chunk.
3924 *
3925 * Example:
3926 *
3927 * e = (0..10).chunk {|i| (i / 3).floor } # => #<Enumerator: ...>
3928 * # The enumerator elements.
3929 * e.next # => [0, [0, 1, 2]]
3930 * e.next # => [1, [3, 4, 5]]
3931 * e.next # => [2, [6, 7, 8]]
3932 * e.next # => [3, [9, 10]]
3933 *
3934 * Method +chunk+ is especially useful for an enumerable that is already sorted.
3935 * This example counts words for each initial letter in a large array of words:
3936 *
3937 * # Get sorted words from a web page.
3938 * url = 'https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt'
3939 * words = URI::open(url).readlines
3940 * # Make chunks, one for each letter.
3941 * e = words.chunk {|word| word.upcase[0] } # => #<Enumerator: ...>
3942 * # Display 'A' through 'F'.
3943 * e.each {|c, words| p [c, words.length]; break if c == 'F' }
3944 *
3945 * Output:
3946 *
3947 * ["A", 17096]
3948 * ["B", 11070]
3949 * ["C", 19901]
3950 * ["D", 10896]
3951 * ["E", 8736]
3952 * ["F", 6860]
3953 *
3954 * You can use the special symbol <tt>:_alone</tt> to force an element
3955 * into its own separate chunk:
3956 *
3957 * a = [0, 0, 1, 1]
3958 * e = a.chunk{|i| i.even? ? :_alone : true }
3959 * e.to_a # => [[:_alone, [0]], [:_alone, [0]], [true, [1, 1]]]
3960 *
3961 * For example, you can put each line that contains a URL into its own chunk:
3962 *
3963 * pattern = /http/
3964 * open(filename) { |f|
3965 * f.chunk { |line| line =~ pattern ? :_alone : true }.each { |key, lines|
3966 * pp lines
3967 * }
3968 * }
3969 *
3970 * You can use the special symbol <tt>:_separator</tt> or +nil+
3971 * to force an element to be ignored (not included in any chunk):
3972 *
3973 * a = [0, 0, -1, 1, 1]
3974 * e = a.chunk{|i| i < 0 ? :_separator : true }
3975 * e.to_a # => [[true, [0, 0]], [true, [1, 1]]]
3976 *
3977 * Note that the separator does end the chunk:
3978 *
3979 * a = [0, 0, -1, 1, -1, 1]
3980 * e = a.chunk{|i| i < 0 ? :_separator : true }
3981 * e.to_a # => [[true, [0, 0]], [true, [1]], [true, [1]]]
3982 *
3983 * For example, the sequence of hyphens in svn log can be eliminated as follows:
3984 *
3985 * sep = "-"*72 + "\n"
3986 * IO.popen("svn log README") { |f|
3987 * f.chunk { |line|
3988 * line != sep || nil
3989 * }.each { |_, lines|
3990 * pp lines
3991 * }
3992 * }
3993 * #=> ["r20018 | knu | 2008-10-29 13:20:42 +0900 (Wed, 29 Oct 2008) | 2 lines\n",
3994 * # "\n",
3995 * # "* README, README.ja: Update the portability section.\n",
3996 * # "\n"]
3997 * # ["r16725 | knu | 2008-05-31 23:34:23 +0900 (Sat, 31 May 2008) | 2 lines\n",
3998 * # "\n",
3999 * # "* README, README.ja: Add a note about default C flags.\n",
4000 * # "\n"]
4001 * # ...
4002 *
4003 * Paragraphs separated by empty lines can be parsed as follows:
4004 *
4005 * File.foreach("README").chunk { |line|
4006 * /\A\s*\z/ !~ line || nil
4007 * }.each { |_, lines|
4008 * pp lines
4009 * }
4010 *
4011 */
4012static VALUE
4013enum_chunk(VALUE enumerable)
4014{
4016
4017 RETURN_SIZED_ENUMERATOR(enumerable, 0, 0, enum_size);
4018
4020 rb_ivar_set(enumerator, id_chunk_enumerable, enumerable);
4021 rb_ivar_set(enumerator, id_chunk_categorize, rb_block_proc());
4022 rb_block_call(enumerator, idInitialize, 0, 0, chunk_i, enumerator);
4023 return enumerator;
4024}
4025
4026
4028 VALUE sep_pred;
4029 VALUE sep_pat;
4030 VALUE prev_elts;
4031 VALUE yielder;
4032};
4033
4034static VALUE
4035slicebefore_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
4036{
4037 struct slicebefore_arg *argp = MEMO_FOR(struct slicebefore_arg, _argp);
4038 VALUE header_p;
4039
4040 ENUM_WANT_SVALUE();
4041
4042 if (!NIL_P(argp->sep_pat))
4043 header_p = rb_funcallv(argp->sep_pat, id_eqq, 1, &i);
4044 else
4045 header_p = rb_funcallv(argp->sep_pred, id_call, 1, &i);
4046 if (RTEST(header_p)) {
4047 if (!NIL_P(argp->prev_elts))
4048 rb_funcallv(argp->yielder, id_lshift, 1, &argp->prev_elts);
4049 argp->prev_elts = rb_ary_new3(1, i);
4050 }
4051 else {
4052 if (NIL_P(argp->prev_elts))
4053 argp->prev_elts = rb_ary_new3(1, i);
4054 else
4055 rb_ary_push(argp->prev_elts, i);
4056 }
4057
4058 return Qnil;
4059}
4060
4061static VALUE
4063{
4064 VALUE enumerable;
4065 VALUE arg;
4066 struct slicebefore_arg *memo = NEW_MEMO_FOR(struct slicebefore_arg, arg);
4067
4068 enumerable = rb_ivar_get(enumerator, id_slicebefore_enumerable);
4069 memo->sep_pred = rb_attr_get(enumerator, id_slicebefore_sep_pred);
4070 memo->sep_pat = NIL_P(memo->sep_pred) ? rb_ivar_get(enumerator, id_slicebefore_sep_pat) : Qnil;
4071 memo->prev_elts = Qnil;
4072 memo->yielder = yielder;
4073
4074 rb_block_call(enumerable, id_each, 0, 0, slicebefore_ii, arg);
4075 memo = MEMO_FOR(struct slicebefore_arg, arg);
4076 if (!NIL_P(memo->prev_elts))
4077 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4078 return Qnil;
4079}
4080
4081/*
4082 * call-seq:
4083 * slice_before(pattern) -> enumerator
4084 * slice_before {|elt| ... } -> enumerator
4085 *
4086 * With argument +pattern+, returns an enumerator that uses the pattern
4087 * to partition elements into arrays ("slices").
4088 * An element begins a new slice if <tt>element === pattern</tt>
4089 * (or if it is the first element).
4090 *
4091 * a = %w[foo bar fop for baz fob fog bam foy]
4092 * e = a.slice_before(/ba/) # => #<Enumerator: ...>
4093 * e.each {|array| p array }
4094 *
4095 * Output:
4096 *
4097 * ["foo"]
4098 * ["bar", "fop", "for"]
4099 * ["baz", "fob", "fog"]
4100 * ["bam", "foy"]
4101 *
4102 * With a block, returns an enumerator that uses the block
4103 * to partition elements into arrays.
4104 * An element begins a new slice if its block return is a truthy value
4105 * (or if it is the first element):
4106 *
4107 * e = (1..20).slice_before {|i| i % 4 == 2 } # => #<Enumerator: ...>
4108 * e.each {|array| p array }
4109 *
4110 * Output:
4111 *
4112 * [1]
4113 * [2, 3, 4, 5]
4114 * [6, 7, 8, 9]
4115 * [10, 11, 12, 13]
4116 * [14, 15, 16, 17]
4117 * [18, 19, 20]
4118 *
4119 * Other methods of the Enumerator class and Enumerable module,
4120 * such as +to_a+, +map+, etc., are also usable.
4121 *
4122 * For example, iteration over ChangeLog entries can be implemented as
4123 * follows:
4124 *
4125 * # iterate over ChangeLog entries.
4126 * open("ChangeLog") { |f|
4127 * f.slice_before(/\A\S/).each { |e| pp e }
4128 * }
4129 *
4130 * # same as above. block is used instead of pattern argument.
4131 * open("ChangeLog") { |f|
4132 * f.slice_before { |line| /\A\S/ === line }.each { |e| pp e }
4133 * }
4134 *
4135 * "svn proplist -R" produces multiline output for each file.
4136 * They can be chunked as follows:
4137 *
4138 * IO.popen([{"LC_ALL"=>"C"}, "svn", "proplist", "-R"]) { |f|
4139 * f.lines.slice_before(/\AProp/).each { |lines| p lines }
4140 * }
4141 * #=> ["Properties on '.':\n", " svn:ignore\n", " svk:merge\n"]
4142 * # ["Properties on 'goruby.c':\n", " svn:eol-style\n"]
4143 * # ["Properties on 'complex.c':\n", " svn:mime-type\n", " svn:eol-style\n"]
4144 * # ["Properties on 'regparse.c':\n", " svn:eol-style\n"]
4145 * # ...
4146 *
4147 * If the block needs to maintain state over multiple elements,
4148 * local variables can be used.
4149 * For example, three or more consecutive increasing numbers can be squashed
4150 * as follows (see +chunk_while+ for a better way):
4151 *
4152 * a = [0, 2, 3, 4, 6, 7, 9]
4153 * prev = a[0]
4154 * p a.slice_before { |e|
4155 * prev, prev2 = e, prev
4156 * prev2 + 1 != e
4157 * }.map { |es|
4158 * es.length <= 2 ? es.join(",") : "#{es.first}-#{es.last}"
4159 * }.join(",")
4160 * #=> "0,2-4,6,7,9"
4161 *
4162 * However local variables should be used carefully
4163 * if the result enumerator is enumerated twice or more.
4164 * The local variables should be initialized for each enumeration.
4165 * Enumerator.new can be used to do it.
4166 *
4167 * # Word wrapping. This assumes all characters have same width.
4168 * def wordwrap(words, maxwidth)
4169 * Enumerator.new {|y|
4170 * # cols is initialized in Enumerator.new.
4171 * cols = 0
4172 * words.slice_before { |w|
4173 * cols += 1 if cols != 0
4174 * cols += w.length
4175 * if maxwidth < cols
4176 * cols = w.length
4177 * true
4178 * else
4179 * false
4180 * end
4181 * }.each {|ws| y.yield ws }
4182 * }
4183 * end
4184 * text = (1..20).to_a.join(" ")
4185 * enum = wordwrap(text.split(/\s+/), 10)
4186 * puts "-"*10
4187 * enum.each { |ws| puts ws.join(" ") } # first enumeration.
4188 * puts "-"*10
4189 * enum.each { |ws| puts ws.join(" ") } # second enumeration generates same result as the first.
4190 * puts "-"*10
4191 * #=> ----------
4192 * # 1 2 3 4 5
4193 * # 6 7 8 9 10
4194 * # 11 12 13
4195 * # 14 15 16
4196 * # 17 18 19
4197 * # 20
4198 * # ----------
4199 * # 1 2 3 4 5
4200 * # 6 7 8 9 10
4201 * # 11 12 13
4202 * # 14 15 16
4203 * # 17 18 19
4204 * # 20
4205 * # ----------
4206 *
4207 * mbox contains series of mails which start with Unix From line.
4208 * So each mail can be extracted by slice before Unix From line.
4209 *
4210 * # parse mbox
4211 * open("mbox") { |f|
4212 * f.slice_before { |line|
4213 * line.start_with? "From "
4214 * }.each { |mail|
4215 * unix_from = mail.shift
4216 * i = mail.index("\n")
4217 * header = mail[0...i]
4218 * body = mail[(i+1)..-1]
4219 * body.pop if body.last == "\n"
4220 * fields = header.slice_before { |line| !" \t".include?(line[0]) }.to_a
4221 * p unix_from
4222 * pp fields
4223 * pp body
4224 * }
4225 * }
4226 *
4227 * # split mails in mbox (slice before Unix From line after an empty line)
4228 * open("mbox") { |f|
4229 * emp = true
4230 * f.slice_before { |line|
4231 * prevemp = emp
4232 * emp = line == "\n"
4233 * prevemp && line.start_with?("From ")
4234 * }.each { |mail|
4235 * mail.pop if mail.last == "\n"
4236 * pp mail
4237 * }
4238 * }
4239 *
4240 */
4241static VALUE
4242enum_slice_before(int argc, VALUE *argv, VALUE enumerable)
4243{
4245
4246 if (rb_block_given_p()) {
4247 if (argc != 0)
4248 rb_error_arity(argc, 0, 0);
4250 rb_ivar_set(enumerator, id_slicebefore_sep_pred, rb_block_proc());
4251 }
4252 else {
4253 VALUE sep_pat;
4254 rb_scan_args(argc, argv, "1", &sep_pat);
4256 rb_ivar_set(enumerator, id_slicebefore_sep_pat, sep_pat);
4257 }
4258 rb_ivar_set(enumerator, id_slicebefore_enumerable, enumerable);
4259 rb_block_call(enumerator, idInitialize, 0, 0, slicebefore_i, enumerator);
4260 return enumerator;
4261}
4262
4263
4265 VALUE pat;
4266 VALUE pred;
4267 VALUE prev_elts;
4268 VALUE yielder;
4269};
4270
4271static VALUE
4272sliceafter_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
4273{
4274#define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct sliceafter_arg, _memo)))
4275 struct sliceafter_arg *memo;
4276 int split_p;
4277 UPDATE_MEMO;
4278
4279 ENUM_WANT_SVALUE();
4280
4281 if (NIL_P(memo->prev_elts)) {
4282 memo->prev_elts = rb_ary_new3(1, i);
4283 }
4284 else {
4285 rb_ary_push(memo->prev_elts, i);
4286 }
4287
4288 if (NIL_P(memo->pred)) {
4289 split_p = RTEST(rb_funcallv(memo->pat, id_eqq, 1, &i));
4290 UPDATE_MEMO;
4291 }
4292 else {
4293 split_p = RTEST(rb_funcallv(memo->pred, id_call, 1, &i));
4294 UPDATE_MEMO;
4295 }
4296
4297 if (split_p) {
4298 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4299 UPDATE_MEMO;
4300 memo->prev_elts = Qnil;
4301 }
4302
4303 return Qnil;
4304#undef UPDATE_MEMO
4305}
4306
4307static VALUE
4309{
4310 VALUE enumerable;
4311 VALUE arg;
4312 struct sliceafter_arg *memo = NEW_MEMO_FOR(struct sliceafter_arg, arg);
4313
4314 enumerable = rb_ivar_get(enumerator, id_sliceafter_enum);
4315 memo->pat = rb_ivar_get(enumerator, id_sliceafter_pat);
4316 memo->pred = rb_attr_get(enumerator, id_sliceafter_pred);
4317 memo->prev_elts = Qnil;
4318 memo->yielder = yielder;
4319
4320 rb_block_call(enumerable, id_each, 0, 0, sliceafter_ii, arg);
4321 memo = MEMO_FOR(struct sliceafter_arg, arg);
4322 if (!NIL_P(memo->prev_elts))
4323 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4324 return Qnil;
4325}
4326
4327/*
4328 * call-seq:
4329 * enum.slice_after(pattern) -> an_enumerator
4330 * enum.slice_after { |elt| bool } -> an_enumerator
4331 *
4332 * Creates an enumerator for each chunked elements.
4333 * The ends of chunks are defined by _pattern_ and the block.
4334 *
4335 * If <code>_pattern_ === _elt_</code> returns <code>true</code> or the block
4336 * returns <code>true</code> for the element, the element is end of a
4337 * chunk.
4338 *
4339 * The <code>===</code> and _block_ is called from the first element to the last
4340 * element of _enum_.
4341 *
4342 * The result enumerator yields the chunked elements as an array.
4343 * So +each+ method can be called as follows:
4344 *
4345 * enum.slice_after(pattern).each { |ary| ... }
4346 * enum.slice_after { |elt| bool }.each { |ary| ... }
4347 *
4348 * Other methods of the Enumerator class and Enumerable module,
4349 * such as +map+, etc., are also usable.
4350 *
4351 * For example, continuation lines (lines end with backslash) can be
4352 * concatenated as follows:
4353 *
4354 * lines = ["foo\n", "bar\\\n", "baz\n", "\n", "qux\n"]
4355 * e = lines.slice_after(/(?<!\\‍)\n\z/)
4356 * p e.to_a
4357 * #=> [["foo\n"], ["bar\\\n", "baz\n"], ["\n"], ["qux\n"]]
4358 * p e.map {|ll| ll[0...-1].map {|l| l.sub(/\\\n\z/, "") }.join + ll.last }
4359 * #=>["foo\n", "barbaz\n", "\n", "qux\n"]
4360 *
4361 */
4362
4363static VALUE
4364enum_slice_after(int argc, VALUE *argv, VALUE enumerable)
4365{
4367 VALUE pat = Qnil, pred = Qnil;
4368
4369 if (rb_block_given_p()) {
4370 if (0 < argc)
4371 rb_raise(rb_eArgError, "both pattern and block are given");
4372 pred = rb_block_proc();
4373 }
4374 else {
4375 rb_scan_args(argc, argv, "1", &pat);
4376 }
4377
4379 rb_ivar_set(enumerator, id_sliceafter_enum, enumerable);
4380 rb_ivar_set(enumerator, id_sliceafter_pat, pat);
4381 rb_ivar_set(enumerator, id_sliceafter_pred, pred);
4382
4383 rb_block_call(enumerator, idInitialize, 0, 0, sliceafter_i, enumerator);
4384 return enumerator;
4385}
4386
4388 VALUE pred;
4389 VALUE prev_elt;
4390 VALUE prev_elts;
4391 VALUE yielder;
4392 int inverted; /* 0 for slice_when and 1 for chunk_while. */
4393};
4394
4395static VALUE
4396slicewhen_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
4397{
4398#define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct slicewhen_arg, _memo)))
4399 struct slicewhen_arg *memo;
4400 int split_p;
4401 UPDATE_MEMO;
4402
4403 ENUM_WANT_SVALUE();
4404
4405 if (UNDEF_P(memo->prev_elt)) {
4406 /* The first element */
4407 memo->prev_elt = i;
4408 memo->prev_elts = rb_ary_new3(1, i);
4409 }
4410 else {
4411 VALUE args[2];
4412 args[0] = memo->prev_elt;
4413 args[1] = i;
4414 split_p = RTEST(rb_funcallv(memo->pred, id_call, 2, args));
4415 UPDATE_MEMO;
4416
4417 if (memo->inverted)
4418 split_p = !split_p;
4419
4420 if (split_p) {
4421 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4422 UPDATE_MEMO;
4423 memo->prev_elts = rb_ary_new3(1, i);
4424 }
4425 else {
4426 rb_ary_push(memo->prev_elts, i);
4427 }
4428
4429 memo->prev_elt = i;
4430 }
4431
4432 return Qnil;
4433#undef UPDATE_MEMO
4434}
4435
4436static VALUE
4438{
4439 VALUE enumerable;
4440 VALUE arg;
4441 struct slicewhen_arg *memo =
4442 NEW_PARTIAL_MEMO_FOR(struct slicewhen_arg, arg, inverted);
4443
4444 enumerable = rb_ivar_get(enumerator, id_slicewhen_enum);
4445 memo->pred = rb_attr_get(enumerator, id_slicewhen_pred);
4446 memo->prev_elt = Qundef;
4447 memo->prev_elts = Qnil;
4448 memo->yielder = yielder;
4449 memo->inverted = RTEST(rb_attr_get(enumerator, id_slicewhen_inverted));
4450
4451 rb_block_call(enumerable, id_each, 0, 0, slicewhen_ii, arg);
4452 memo = MEMO_FOR(struct slicewhen_arg, arg);
4453 if (!NIL_P(memo->prev_elts))
4454 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4455 return Qnil;
4456}
4457
4458/*
4459 * call-seq:
4460 * enum.slice_when {|elt_before, elt_after| bool } -> an_enumerator
4461 *
4462 * Creates an enumerator for each chunked elements.
4463 * The beginnings of chunks are defined by the block.
4464 *
4465 * This method splits each chunk using adjacent elements,
4466 * _elt_before_ and _elt_after_,
4467 * in the receiver enumerator.
4468 * This method split chunks between _elt_before_ and _elt_after_ where
4469 * the block returns <code>true</code>.
4470 *
4471 * The block is called the length of the receiver enumerator minus one.
4472 *
4473 * The result enumerator yields the chunked elements as an array.
4474 * So +each+ method can be called as follows:
4475 *
4476 * enum.slice_when { |elt_before, elt_after| bool }.each { |ary| ... }
4477 *
4478 * Other methods of the Enumerator class and Enumerable module,
4479 * such as +to_a+, +map+, etc., are also usable.
4480 *
4481 * For example, one-by-one increasing subsequence can be chunked as follows:
4482 *
4483 * a = [1,2,4,9,10,11,12,15,16,19,20,21]
4484 * b = a.slice_when {|i, j| i+1 != j }
4485 * p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
4486 * c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
4487 * p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
4488 * d = c.join(",")
4489 * p d #=> "1,2,4,9-12,15,16,19-21"
4490 *
4491 * Near elements (threshold: 6) in sorted array can be chunked as follows:
4492 *
4493 * a = [3, 11, 14, 25, 28, 29, 29, 41, 55, 57]
4494 * p a.slice_when {|i, j| 6 < j - i }.to_a
4495 * #=> [[3], [11, 14], [25, 28, 29, 29], [41], [55, 57]]
4496 *
4497 * Increasing (non-decreasing) subsequence can be chunked as follows:
4498 *
4499 * a = [0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
4500 * p a.slice_when {|i, j| i > j }.to_a
4501 * #=> [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
4502 *
4503 * Adjacent evens and odds can be chunked as follows:
4504 * (Enumerable#chunk is another way to do it.)
4505 *
4506 * a = [7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
4507 * p a.slice_when {|i, j| i.even? != j.even? }.to_a
4508 * #=> [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
4509 *
4510 * Paragraphs (non-empty lines with trailing empty lines) can be chunked as follows:
4511 * (See Enumerable#chunk to ignore empty lines.)
4512 *
4513 * lines = ["foo\n", "bar\n", "\n", "baz\n", "qux\n"]
4514 * p lines.slice_when {|l1, l2| /\A\s*\z/ =~ l1 && /\S/ =~ l2 }.to_a
4515 * #=> [["foo\n", "bar\n", "\n"], ["baz\n", "qux\n"]]
4516 *
4517 * Enumerable#chunk_while does the same, except splitting when the block
4518 * returns <code>false</code> instead of <code>true</code>.
4519 */
4520static VALUE
4521enum_slice_when(VALUE enumerable)
4522{
4524 VALUE pred;
4525
4526 pred = rb_block_proc();
4527
4529 rb_ivar_set(enumerator, id_slicewhen_enum, enumerable);
4530 rb_ivar_set(enumerator, id_slicewhen_pred, pred);
4531 rb_ivar_set(enumerator, id_slicewhen_inverted, Qfalse);
4532
4533 rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
4534 return enumerator;
4535}
4536
4537/*
4538 * call-seq:
4539 * enum.chunk_while {|elt_before, elt_after| bool } -> an_enumerator
4540 *
4541 * Creates an enumerator for each chunked elements.
4542 * The beginnings of chunks are defined by the block.
4543 *
4544 * This method splits each chunk using adjacent elements,
4545 * _elt_before_ and _elt_after_,
4546 * in the receiver enumerator.
4547 * This method split chunks between _elt_before_ and _elt_after_ where
4548 * the block returns <code>false</code>.
4549 *
4550 * The block is called the length of the receiver enumerator minus one.
4551 *
4552 * The result enumerator yields the chunked elements as an array.
4553 * So +each+ method can be called as follows:
4554 *
4555 * enum.chunk_while { |elt_before, elt_after| bool }.each { |ary| ... }
4556 *
4557 * Other methods of the Enumerator class and Enumerable module,
4558 * such as +to_a+, +map+, etc., are also usable.
4559 *
4560 * For example, one-by-one increasing subsequence can be chunked as follows:
4561 *
4562 * a = [1,2,4,9,10,11,12,15,16,19,20,21]
4563 * b = a.chunk_while {|i, j| i+1 == j }
4564 * p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
4565 * c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
4566 * p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
4567 * d = c.join(",")
4568 * p d #=> "1,2,4,9-12,15,16,19-21"
4569 *
4570 * Increasing (non-decreasing) subsequence can be chunked as follows:
4571 *
4572 * a = [0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
4573 * p a.chunk_while {|i, j| i <= j }.to_a
4574 * #=> [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
4575 *
4576 * Adjacent evens and odds can be chunked as follows:
4577 * (Enumerable#chunk is another way to do it.)
4578 *
4579 * a = [7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
4580 * p a.chunk_while {|i, j| i.even? == j.even? }.to_a
4581 * #=> [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
4582 *
4583 * Enumerable#slice_when does the same, except splitting when the block
4584 * returns <code>true</code> instead of <code>false</code>.
4585 */
4586static VALUE
4587enum_chunk_while(VALUE enumerable)
4588{
4590 VALUE pred;
4591
4592 pred = rb_block_proc();
4593
4595 rb_ivar_set(enumerator, id_slicewhen_enum, enumerable);
4596 rb_ivar_set(enumerator, id_slicewhen_pred, pred);
4597 rb_ivar_set(enumerator, id_slicewhen_inverted, Qtrue);
4598
4599 rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
4600 return enumerator;
4601}
4602
4604 VALUE v, r;
4605 long n;
4606 double f, c;
4607 int block_given;
4608 int float_value;
4609};
4610
4611static void
4612sum_iter_normalize_memo(struct enum_sum_memo *memo)
4613{
4614 RUBY_ASSERT(FIXABLE(memo->n));
4615 memo->v = rb_fix_plus(LONG2FIX(memo->n), memo->v);
4616 memo->n = 0;
4617
4618 switch (TYPE(memo->r)) {
4619 case T_RATIONAL: memo->v = rb_rational_plus(memo->r, memo->v); break;
4620 case T_UNDEF: break;
4621 default: UNREACHABLE; /* or ...? */
4622 }
4623 memo->r = Qundef;
4624}
4625
4626static void
4627sum_iter_fixnum(VALUE i, struct enum_sum_memo *memo)
4628{
4629 memo->n += FIX2LONG(i); /* should not overflow long type */
4630 if (! FIXABLE(memo->n)) {
4631 memo->v = rb_big_plus(LONG2NUM(memo->n), memo->v);
4632 memo->n = 0;
4633 }
4634}
4635
4636static void
4637sum_iter_bignum(VALUE i, struct enum_sum_memo *memo)
4638{
4639 memo->v = rb_big_plus(i, memo->v);
4640}
4641
4642static void
4643sum_iter_rational(VALUE i, struct enum_sum_memo *memo)
4644{
4645 if (UNDEF_P(memo->r)) {
4646 memo->r = i;
4647 }
4648 else {
4649 memo->r = rb_rational_plus(memo->r, i);
4650 }
4651}
4652
4653static void
4654sum_iter_some_value(VALUE i, struct enum_sum_memo *memo)
4655{
4656 memo->v = rb_funcallv(memo->v, idPLUS, 1, &i);
4657}
4658
4659static void
4660sum_iter_Kahan_Babuska(VALUE i, struct enum_sum_memo *memo)
4661{
4662 /*
4663 * Kahan-Babuska balancing compensated summation algorithm
4664 * See https://link.springer.com/article/10.1007/s00607-005-0139-x
4665 */
4666 double x;
4667
4668 switch (TYPE(i)) {
4669 case T_FLOAT: x = RFLOAT_VALUE(i); break;
4670 case T_FIXNUM: x = FIX2LONG(i); break;
4671 case T_BIGNUM: x = rb_big2dbl(i); break;
4672 case T_RATIONAL: x = rb_num2dbl(i); break;
4673 default:
4674 memo->v = DBL2NUM(memo->f);
4675 memo->float_value = 0;
4676 sum_iter_some_value(i, memo);
4677 return;
4678 }
4679
4680 double f = memo->f;
4681
4682 if (isnan(f)) {
4683 return;
4684 }
4685 else if (! isfinite(x)) {
4686 if (isinf(x) && isinf(f) && signbit(x) != signbit(f)) {
4687 i = DBL2NUM(f);
4688 x = nan("");
4689 }
4690 memo->v = i;
4691 memo->f = x;
4692 return;
4693 }
4694 else if (isinf(f)) {
4695 return;
4696 }
4697
4698 double c = memo->c;
4699 double t = f + x;
4700
4701 if (fabs(f) >= fabs(x)) {
4702 c += ((f - t) + x);
4703 }
4704 else {
4705 c += ((x - t) + f);
4706 }
4707 f = t;
4708
4709 memo->f = f;
4710 memo->c = c;
4711}
4712
4713static void
4714sum_iter(VALUE i, struct enum_sum_memo *memo)
4715{
4716 RUBY_ASSERT(memo != NULL);
4717 if (memo->block_given) {
4718 i = rb_yield(i);
4719 }
4720
4721 if (memo->float_value) {
4722 sum_iter_Kahan_Babuska(i, memo);
4723 }
4724 else switch (TYPE(memo->v)) {
4725 default: sum_iter_some_value(i, memo); return;
4726 case T_FLOAT:
4727 case T_FIXNUM:
4728 case T_BIGNUM:
4729 case T_RATIONAL:
4730 switch (TYPE(i)) {
4731 case T_FIXNUM: sum_iter_fixnum(i, memo); return;
4732 case T_BIGNUM: sum_iter_bignum(i, memo); return;
4733 case T_RATIONAL: sum_iter_rational(i, memo); return;
4734 case T_FLOAT:
4735 sum_iter_normalize_memo(memo);
4736 memo->f = NUM2DBL(memo->v);
4737 memo->c = 0.0;
4738 memo->float_value = 1;
4739 sum_iter_Kahan_Babuska(i, memo);
4740 return;
4741 default:
4742 sum_iter_normalize_memo(memo);
4743 sum_iter_some_value(i, memo);
4744 return;
4745 }
4746 }
4747}
4748
4749static VALUE
4750enum_sum_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
4751{
4752 ENUM_WANT_SVALUE();
4753 sum_iter(i, (struct enum_sum_memo *) args);
4754 return Qnil;
4755}
4756
4757static int
4758hash_sum_i(VALUE key, VALUE value, VALUE arg)
4759{
4760 sum_iter(rb_assoc_new(key, value), (struct enum_sum_memo *) arg);
4761 return ST_CONTINUE;
4762}
4763
4764static void
4765hash_sum(VALUE hash, struct enum_sum_memo *memo)
4766{
4768 RUBY_ASSERT(memo != NULL);
4769
4770 rb_hash_foreach(hash, hash_sum_i, (VALUE)memo);
4771}
4772
4773static VALUE
4774int_range_sum(VALUE beg, VALUE end, int excl, VALUE init)
4775{
4776 if (excl) {
4777 if (FIXNUM_P(end))
4778 end = LONG2FIX(FIX2LONG(end) - 1);
4779 else
4780 end = rb_big_minus(end, LONG2FIX(1));
4781 }
4782
4783 if (rb_int_ge(end, beg)) {
4784 VALUE a;
4785 a = rb_int_plus(rb_int_minus(end, beg), LONG2FIX(1));
4786 a = rb_int_mul(a, rb_int_plus(end, beg));
4787 a = rb_int_idiv(a, LONG2FIX(2));
4788 return rb_int_plus(init, a);
4789 }
4790
4791 return init;
4792}
4793
4794/*
4795 * call-seq:
4796 * sum(initial_value = 0) -> number
4797 * sum(initial_value = 0) {|element| ... } -> object
4798 *
4799 * With no block given,
4800 * returns the sum of +initial_value+ and the elements:
4801 *
4802 * (1..100).sum # => 5050
4803 * (1..100).sum(1) # => 5051
4804 * ('a'..'d').sum('foo') # => "fooabcd"
4805 *
4806 * Generally, the sum is computed using methods <tt>+</tt> and +each+;
4807 * for performance optimizations, those methods may not be used,
4808 * and so any redefinition of those methods may not have effect here.
4809 *
4810 * One such optimization: When possible, computes using Gauss's summation
4811 * formula <em>n(n+1)/2</em>:
4812 *
4813 * 100 * (100 + 1) / 2 # => 5050
4814 *
4815 * With a block given, calls the block with each element;
4816 * returns the sum of +initial_value+ and the block return values:
4817 *
4818 * (1..4).sum {|i| i*i } # => 30
4819 * (1..4).sum(100) {|i| i*i } # => 130
4820 * h = {a: 0, b: 1, c: 2, d: 3, e: 4, f: 5}
4821 * h.sum {|key, value| value.odd? ? value : 0 } # => 9
4822 * ('a'..'f').sum('x') {|c| c < 'd' ? c : '' } # => "xabc"
4823 *
4824 */
4825static VALUE
4826enum_sum(int argc, VALUE* argv, VALUE obj)
4827{
4828 struct enum_sum_memo memo;
4829 VALUE beg, end;
4830 int excl;
4831
4832 memo.v = (rb_check_arity(argc, 0, 1) == 0) ? LONG2FIX(0) : argv[0];
4833 memo.block_given = rb_block_given_p();
4834 memo.n = 0;
4835 memo.r = Qundef;
4836
4837 if ((memo.float_value = RB_FLOAT_TYPE_P(memo.v))) {
4838 memo.f = RFLOAT_VALUE(memo.v);
4839 memo.c = 0.0;
4840 }
4841 else {
4842 memo.f = 0.0;
4843 memo.c = 0.0;
4844 }
4845
4846 if (RTEST(rb_range_values(obj, &beg, &end, &excl))) {
4847 if (!memo.block_given && !memo.float_value &&
4848 (FIXNUM_P(beg) || RB_BIGNUM_TYPE_P(beg)) &&
4849 (FIXNUM_P(end) || RB_BIGNUM_TYPE_P(end))) {
4850 return int_range_sum(beg, end, excl, memo.v);
4851 }
4852 }
4853
4854 if (RB_TYPE_P(obj, T_HASH) &&
4856 hash_sum(obj, &memo);
4857 else
4858 rb_block_call(obj, id_each, 0, 0, enum_sum_i, (VALUE)&memo);
4859
4860 if (memo.float_value) {
4861 return DBL2NUM(memo.f + memo.c);
4862 }
4863 else {
4864 if (memo.n != 0)
4865 memo.v = rb_fix_plus(LONG2FIX(memo.n), memo.v);
4866 if (!UNDEF_P(memo.r)) {
4867 memo.v = rb_rational_plus(memo.r, memo.v);
4868 }
4869 return memo.v;
4870 }
4871}
4872
4873static VALUE
4874uniq_func(RB_BLOCK_CALL_FUNC_ARGLIST(i, set))
4875{
4876 ENUM_WANT_SVALUE();
4877 rb_set_add_no_check(set, i);
4878 return Qnil;
4879}
4880
4881static VALUE
4882uniq_iter(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
4883{
4884 ENUM_WANT_SVALUE();
4885 rb_hash_add_new_element(hash, rb_yield_values2(argc, argv), i);
4886 return Qnil;
4887}
4888
4889/*
4890 * call-seq:
4891 * uniq -> array
4892 * uniq {|element| ... } -> array
4893 *
4894 * With no block, returns a new array containing only unique elements;
4895 * the array has no two elements +e0+ and +e1+ such that <tt>e0.eql?(e1)</tt>:
4896 *
4897 * %w[a b c c b a a b c].uniq # => ["a", "b", "c"]
4898 * [0, 1, 2, 2, 1, 0, 0, 1, 2].uniq # => [0, 1, 2]
4899 *
4900 * With a block, returns a new array containing elements only for which the block
4901 * returns a unique value:
4902 *
4903 * a = [0, 1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
4904 * a.uniq {|i| i.even? ? i : 0 } # => [0, 2, 4]
4905 * a = %w[a b c d e e d c b a a b c d e]
4906 * a.uniq {|c| c < 'c' } # => ["a", "c"]
4907 *
4908 */
4909
4910static VALUE
4911enum_uniq(VALUE obj)
4912{
4913 VALUE ret;
4914 if (rb_block_given_p()) {
4915 VALUE hash = rb_obj_hide(rb_hash_new());
4916 rb_block_call(obj, id_each, 0, 0, uniq_iter, hash);
4917 ret = rb_hash_values(hash);
4918 rb_hash_clear(hash);
4919 }
4920 else {
4921 VALUE set = rb_obj_hide(rb_set_new());
4922 rb_block_call(obj, id_each, 0, 0, uniq_func, set);
4923 ret = rb_set_to_a(set);
4924 rb_set_clear(set);
4925 }
4926 return ret;
4927}
4928
4929static VALUE
4930compact_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
4931{
4932 ENUM_WANT_SVALUE();
4933
4934 if (!NIL_P(i)) {
4935 rb_ary_push(ary, i);
4936 }
4937 return Qnil;
4938}
4939
4940/*
4941 * call-seq:
4942 * compact -> array
4943 *
4944 * Returns an array of all non-+nil+ elements:
4945 *
4946 * a = [nil, 0, nil, 'a', false, nil, false, nil, 'a', nil, 0, nil]
4947 * a.compact # => [0, "a", false, false, "a", 0]
4948 *
4949 */
4950
4951static VALUE
4952enum_compact(VALUE obj)
4953{
4954 VALUE ary;
4955
4956 ary = rb_ary_new();
4957 rb_block_call(obj, id_each, 0, 0, compact_i, ary);
4958
4959 return ary;
4960}
4961
4962
4963/*
4964 * == What's Here
4965 *
4966 * Module \Enumerable provides methods that are useful to a collection class for:
4967 *
4968 * - {Querying}[rdoc-ref:Enumerable@Methods+for+Querying]
4969 * - {Fetching}[rdoc-ref:Enumerable@Methods+for+Fetching]
4970 * - {Searching and Filtering}[rdoc-ref:Enumerable@Methods+for+Searching+and+Filtering]
4971 * - {Sorting}[rdoc-ref:Enumerable@Methods+for+Sorting]
4972 * - {Iterating}[rdoc-ref:Enumerable@Methods+for+Iterating]
4973 * - {And more....}[rdoc-ref:Enumerable@Other+Methods]
4974 *
4975 * === Methods for Querying
4976 *
4977 * These methods return information about the \Enumerable other than the elements themselves:
4978 *
4979 * - #member? (aliased as #include?): Returns +true+ if <tt>self == object</tt>, +false+ otherwise.
4980 * - #all?: Returns +true+ if all elements meet a specified criterion; +false+ otherwise.
4981 * - #any?: Returns +true+ if any element meets a specified criterion; +false+ otherwise.
4982 * - #none?: Returns +true+ if no element meets a specified criterion; +false+ otherwise.
4983 * - #one?: Returns +true+ if exactly one element meets a specified criterion; +false+ otherwise.
4984 * - #count: Returns the count of elements,
4985 * based on an argument or block criterion, if given.
4986 * - #tally: Returns a new Hash containing the counts of occurrences of each element.
4987 *
4988 * === Methods for Fetching
4989 *
4990 * These methods return entries from the \Enumerable, without modifying it:
4991 *
4992 * <i>Leading, trailing, or all elements</i>:
4993 *
4994 * - #to_a (aliased as #entries): Returns all elements.
4995 * - #first: Returns the first element or leading elements.
4996 * - #take: Returns a specified number of leading elements.
4997 * - #drop: Returns a specified number of trailing elements.
4998 * - #take_while: Returns leading elements as specified by the given block.
4999 * - #drop_while: Returns trailing elements as specified by the given block.
5000 *
5001 * <i>Minimum and maximum value elements</i>:
5002 *
5003 * - #min: Returns the elements whose values are smallest among the elements,
5004 * as determined by <tt>#<=></tt> or a given block.
5005 * - #max: Returns the elements whose values are largest among the elements,
5006 * as determined by <tt>#<=></tt> or a given block.
5007 * - #minmax: Returns a 2-element Array containing the smallest and largest elements.
5008 * - #min_by: Returns the smallest element, as determined by the given block.
5009 * - #max_by: Returns the largest element, as determined by the given block.
5010 * - #minmax_by: Returns the smallest and largest elements, as determined by the given block.
5011 *
5012 * <i>Groups, slices, and partitions</i>:
5013 *
5014 * - #group_by: Returns a Hash that partitions the elements into groups.
5015 * - #partition: Returns elements partitioned into two new Arrays, as determined by the given block.
5016 * - #slice_after: Returns a new Enumerator whose entries are a partition of +self+,
5017 * based either on a given +object+ or a given block.
5018 * - #slice_before: Returns a new Enumerator whose entries are a partition of +self+,
5019 * based either on a given +object+ or a given block.
5020 * - #slice_when: Returns a new Enumerator whose entries are a partition of +self+
5021 * based on the given block.
5022 * - #chunk: Returns elements organized into chunks as specified by the given block.
5023 * - #chunk_while: Returns elements organized into chunks as specified by the given block.
5024 *
5025 * === Methods for Searching and Filtering
5026 *
5027 * These methods return elements that meet a specified criterion:
5028 *
5029 * - #find (aliased as #detect): Returns an element selected by the block.
5030 * - #find_all (aliased as #filter, #select): Returns elements selected by the block.
5031 * - #find_index: Returns the index of an element selected by a given object or block.
5032 * - #reject: Returns elements not rejected by the block.
5033 * - #uniq: Returns elements that are not duplicates.
5034 *
5035 * === Methods for Sorting
5036 *
5037 * These methods return elements in sorted order:
5038 *
5039 * - #sort: Returns the elements, sorted by <tt>#<=></tt> or the given block.
5040 * - #sort_by: Returns the elements, sorted by the given block.
5041 *
5042 * === Methods for Iterating
5043 *
5044 * - #each_entry: Calls the block with each successive element
5045 * (slightly different from #each).
5046 * - #each_with_index: Calls the block with each successive element and its index.
5047 * - #each_with_object: Calls the block with each successive element and a given object.
5048 * - #each_slice: Calls the block with successive non-overlapping slices.
5049 * - #each_cons: Calls the block with successive overlapping slices.
5050 * (different from #each_slice).
5051 * - #reverse_each: Calls the block with each successive element, in reverse order.
5052 *
5053 * === Other Methods
5054 *
5055 * - #collect (aliased as #map): Returns objects returned by the block.
5056 * - #filter_map: Returns truthy objects returned by the block.
5057 * - #flat_map (aliased as #collect_concat): Returns flattened objects returned by the block.
5058 * - #grep: Returns elements selected by a given object
5059 * or objects returned by a given block.
5060 * - #grep_v: Returns elements not selected by a given object
5061 * or objects returned by a given block.
5062 * - #inject (aliased as #reduce): Returns the object formed by combining all elements.
5063 * - #sum: Returns the sum of the elements, using method <tt>+</tt>.
5064 * - #zip: Combines each element with elements from other enumerables;
5065 * returns the n-tuples or calls the block with each.
5066 * - #cycle: Calls the block with each element, cycling repeatedly.
5067 *
5068 * == Usage
5069 *
5070 * To use module \Enumerable in a collection class:
5071 *
5072 * - Include it:
5073 *
5074 * include Enumerable
5075 *
5076 * - Implement method <tt>#each</tt>
5077 * which must yield successive elements of the collection.
5078 * The method will be called by almost any \Enumerable method.
5079 *
5080 * Example:
5081 *
5082 * class Foo
5083 * include Enumerable
5084 * def each
5085 * yield 1
5086 * yield 1, 2
5087 * yield
5088 * end
5089 * end
5090 * Foo.new.each_entry{ |element| p element }
5091 *
5092 * Output:
5093 *
5094 * 1
5095 * [1, 2]
5096 * nil
5097 *
5098 * == \Enumerable in Ruby Classes
5099 *
5100 * These Ruby core classes include (or extend) \Enumerable:
5101 *
5102 * - ARGF
5103 * - Array
5104 * - Dir
5105 * - Enumerator
5106 * - ENV (extends)
5107 * - Hash
5108 * - IO
5109 * - Range
5110 * - Struct
5111 *
5112 * These Ruby standard library classes include \Enumerable:
5113 *
5114 * - CSV
5115 * - CSV::Table
5116 * - CSV::Row
5117 * - Set
5118 *
5119 * Virtually all methods in \Enumerable call method +#each+ in the including class:
5120 *
5121 * - <tt>Hash#each</tt> yields the next key-value pair as a 2-element Array.
5122 * - <tt>Struct#each</tt> yields the next name-value pair as a 2-element Array.
5123 * - For the other classes above, +#each+ yields the next object from the collection.
5124 *
5125 * == About the Examples
5126 *
5127 * The example code snippets for the \Enumerable methods:
5128 *
5129 * - Always show the use of one or more Array-like classes (often Array itself).
5130 * - Sometimes show the use of a Hash-like class.
5131 * For some methods, though, the usage would not make sense,
5132 * and so it is not shown. Example: #tally would find exactly one of each Hash entry.
5133 *
5134 * == Extended Methods
5135 *
5136 * A Enumerable class may define extended methods. This section describes the standard
5137 * behavior of extension methods for reference purposes.
5138 *
5139 * === #size
5140 *
5141 * \Enumerator has a #size method.
5142 * It uses the size function argument passed to +Enumerator.new+.
5143 *
5144 * e = Enumerator.new(-> { 3 }) {|y| p y; y.yield :a; y.yield :b; y.yield :c; :z }
5145 * p e.size #=> 3
5146 * p e.next #=> :a
5147 * p e.next #=> :b
5148 * p e.next #=> :c
5149 * begin
5150 * e.next
5151 * rescue StopIteration
5152 * p $!.result #=> :z
5153 * end
5154 *
5155 * The result of the size function should represent the number of iterations
5156 * (i.e., the number of times you yield to the block argument).
5157 * In the above example, the block calls #yield three times, and
5158 * the size function, +-> { 3 }+, returns 3 accordingly.
5159 * The result of the size function can be an integer, +Float::INFINITY+,
5160 * or +nil+.
5161 * An integer means the exact number of times #yield will be called,
5162 * as shown above.
5163 * +Float::INFINITY+ indicates an infinite number of #yield calls.
5164 * +nil+ means the number of #yield calls is difficult or impossible to
5165 * determine.
5166 *
5167 * Many iteration methods return an \Enumerator object with an
5168 * appropriate size function if no block is given.
5169 *
5170 * Examples:
5171 *
5172 * ["a", "b", "c"].each.size #=> 3
5173 * {a: "x", b: "y", c: "z"}.each.size #=> 3
5174 * (0..20).to_a.permutation.size #=> 51090942171709440000
5175 * loop.size #=> Float::INFINITY
5176 * (1..100).drop_while.size #=> nil # size depends on the block's behavior
5177 * STDIN.each.size #=> nil # cannot be computed without consuming input
5178 * File.open("/etc/resolv.conf").each.size #=> nil # cannot be computed without reading the file
5179 *
5180 * The behavior of #size for Range-based enumerators depends on the #begin element:
5181 *
5182 * - If the #begin element is an Integer, the #size method returns an Integer or +Float::INFINITY+.
5183 * - If the #begin element is an object with a #succ method (other than Integer), #size returns +nil+.
5184 * (Computing the size would require repeatedly calling #succ, which may be too slow.)
5185 * - If the #begin element does not have a #succ method, #size raises a TypeError.
5186 *
5187 * Examples:
5188 *
5189 * (10..42).each.size #=> 33
5190 * (10..42.9).each.size #=> 33 (the #end element may be a non-integer numeric)
5191 * (10..).each.size #=> Float::INFINITY
5192 * ("a".."z").each.size #=> nil
5193 * ("a"..).each.size #=> nil
5194 * (1.0..9.0).each.size # raises TypeError (Float does not have #succ)
5195 * (..10).each.size # raises TypeError (beginless range has nil as its #begin)
5196 *
5197 * The \Enumerable module itself does not define a #size method.
5198 * A class that includes \Enumerable may define its own #size method.
5199 * It is recommended that such a #size method be consistent with
5200 * Enumerator#size.
5201 *
5202 * Array and Hash implement #size and return values consistent with
5203 * Enumerator#size.
5204 * IO and Dir do not define #size, which is also consistent because the
5205 * corresponding enumerator's size function returns +nil+.
5206 *
5207 * However, it is not strictly required for a class's #size method to match Enumerator#size.
5208 * For example, File#size returns the number of bytes in the file, not the number of lines.
5209 *
5210 */
5211
5212void
5213Init_Enumerable(void)
5214{
5215 rb_mEnumerable = rb_define_module("Enumerable");
5216
5217 rb_define_method(rb_mEnumerable, "to_a", enum_to_a, -1);
5218 rb_define_method(rb_mEnumerable, "entries", enum_to_a, -1);
5219 rb_define_method(rb_mEnumerable, "to_h", enum_to_h, -1);
5220
5221 rb_define_method(rb_mEnumerable, "sort", enum_sort, 0);
5222 rb_define_method(rb_mEnumerable, "sort_by", enum_sort_by, 0);
5223 rb_define_method(rb_mEnumerable, "grep", enum_grep, 1);
5224 rb_define_method(rb_mEnumerable, "grep_v", enum_grep_v, 1);
5225 rb_define_method(rb_mEnumerable, "count", enum_count, -1);
5226 rb_define_method(rb_mEnumerable, "find", enum_find, -1);
5227 rb_define_method(rb_mEnumerable, "detect", enum_find, -1);
5228 rb_define_method(rb_mEnumerable, "find_index", enum_find_index, -1);
5229 rb_define_method(rb_mEnumerable, "find_all", enum_find_all, 0);
5230 rb_define_method(rb_mEnumerable, "select", enum_find_all, 0);
5231 rb_define_method(rb_mEnumerable, "filter", enum_find_all, 0);
5232 rb_define_method(rb_mEnumerable, "filter_map", enum_filter_map, 0);
5233 rb_define_method(rb_mEnumerable, "reject", enum_reject, 0);
5234 rb_define_method(rb_mEnumerable, "collect", enum_collect, 0);
5235 rb_define_method(rb_mEnumerable, "map", enum_collect, 0);
5236 rb_define_method(rb_mEnumerable, "flat_map", enum_flat_map, 0);
5237 rb_define_method(rb_mEnumerable, "collect_concat", enum_flat_map, 0);
5238 rb_define_method(rb_mEnumerable, "inject", enum_inject, -1);
5239 rb_define_method(rb_mEnumerable, "reduce", enum_inject, -1);
5240 rb_define_method(rb_mEnumerable, "partition", enum_partition, 0);
5241 rb_define_method(rb_mEnumerable, "group_by", enum_group_by, 0);
5242 rb_define_method(rb_mEnumerable, "tally", enum_tally, -1);
5243 rb_define_method(rb_mEnumerable, "first", enum_first, -1);
5244 rb_define_method(rb_mEnumerable, "all?", enum_all, -1);
5245 rb_define_method(rb_mEnumerable, "any?", enum_any, -1);
5246 rb_define_method(rb_mEnumerable, "one?", enum_one, -1);
5247 rb_define_method(rb_mEnumerable, "none?", enum_none, -1);
5248 rb_define_method(rb_mEnumerable, "min", enum_min, -1);
5249 rb_define_method(rb_mEnumerable, "max", enum_max, -1);
5250 rb_define_method(rb_mEnumerable, "minmax", enum_minmax, 0);
5251 rb_define_method(rb_mEnumerable, "min_by", enum_min_by, -1);
5252 rb_define_method(rb_mEnumerable, "max_by", enum_max_by, -1);
5253 rb_define_method(rb_mEnumerable, "minmax_by", enum_minmax_by, 0);
5254 rb_define_method(rb_mEnumerable, "member?", enum_member, 1);
5255 rb_define_method(rb_mEnumerable, "include?", enum_member, 1);
5256 rb_define_method(rb_mEnumerable, "each_with_index", enum_each_with_index, -1);
5257 rb_define_method(rb_mEnumerable, "reverse_each", enum_reverse_each, -1);
5258 rb_define_method(rb_mEnumerable, "each_entry", enum_each_entry, -1);
5259 rb_define_method(rb_mEnumerable, "each_slice", enum_each_slice, 1);
5260 rb_define_method(rb_mEnumerable, "each_cons", enum_each_cons, 1);
5261 rb_define_method(rb_mEnumerable, "each_with_object", enum_each_with_object, 1);
5262 rb_define_method(rb_mEnumerable, "zip", enum_zip, -1);
5263 rb_define_method(rb_mEnumerable, "take", enum_take, 1);
5264 rb_define_method(rb_mEnumerable, "take_while", enum_take_while, 0);
5265 rb_define_method(rb_mEnumerable, "drop", enum_drop, 1);
5266 rb_define_method(rb_mEnumerable, "drop_while", enum_drop_while, 0);
5267 rb_define_method(rb_mEnumerable, "cycle", enum_cycle, -1);
5268 rb_define_method(rb_mEnumerable, "chunk", enum_chunk, 0);
5269 rb_define_method(rb_mEnumerable, "slice_before", enum_slice_before, -1);
5270 rb_define_method(rb_mEnumerable, "slice_after", enum_slice_after, -1);
5271 rb_define_method(rb_mEnumerable, "slice_when", enum_slice_when, 0);
5272 rb_define_method(rb_mEnumerable, "chunk_while", enum_chunk_while, 0);
5273 rb_define_method(rb_mEnumerable, "sum", enum_sum, -1);
5274 rb_define_method(rb_mEnumerable, "uniq", enum_uniq, 0);
5275 rb_define_method(rb_mEnumerable, "compact", enum_compact, 0);
5276
5277 id__alone = rb_intern_const("_alone");
5278 id__separator = rb_intern_const("_separator");
5279 id_chunk_categorize = rb_intern_const("chunk_categorize");
5280 id_chunk_enumerable = rb_intern_const("chunk_enumerable");
5281 id_next = rb_intern_const("next");
5282 id_sliceafter_enum = rb_intern_const("sliceafter_enum");
5283 id_sliceafter_pat = rb_intern_const("sliceafter_pat");
5284 id_sliceafter_pred = rb_intern_const("sliceafter_pred");
5285 id_slicebefore_enumerable = rb_intern_const("slicebefore_enumerable");
5286 id_slicebefore_sep_pat = rb_intern_const("slicebefore_sep_pat");
5287 id_slicebefore_sep_pred = rb_intern_const("slicebefore_sep_pred");
5288 id_slicewhen_enum = rb_intern_const("slicewhen_enum");
5289 id_slicewhen_inverted = rb_intern_const("slicewhen_inverted");
5290 id_slicewhen_pred = rb_intern_const("slicewhen_pred");
5291}
#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:2362
VALUE rb_set_new(void)
Creates a new, empty set object.
Definition set.c:2338
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:3040
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:3683
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:3561
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:3667
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:2407
Definition enum.c:2284
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