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