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