Ruby 4.0.10p0 (2026-11-19 revision a704b7cd95a42cc0cf5f307137bf3aac0285b915)
enumerator.c
1/************************************************
2
3 enumerator.c - provides Enumerator class
4
5 $Author$
6
7 Copyright (C) 2001-2003 Akinori MUSHA
8
9 $Idaemons: /home/cvs/rb/enumerator/enumerator.c,v 1.1.1.1 2001/07/15 10:12:48 knu Exp $
10 $RoughId: enumerator.c,v 1.6 2003/07/27 11:03:24 nobu Exp $
11 $Id$
12
13************************************************/
14
15#include "ruby/internal/config.h"
16
17#ifdef HAVE_FLOAT_H
18#include <float.h>
19#endif
20
21#include <limits.h>
22#include "id.h"
23#include "internal.h"
24#include "internal/class.h"
25#include "internal/enumerator.h"
26#include "internal/error.h"
27#include "internal/hash.h"
28#include "internal/imemo.h"
29#include "internal/numeric.h"
30#include "internal/range.h"
31#include "internal/rational.h"
32#include "ruby/ruby.h"
33
34/*
35 * Document-class: Enumerator
36 *
37 * A class which allows both internal and external iteration.
38 *
39 * An Enumerator can be created by the following methods.
40 * - Object#to_enum
41 * - Object#enum_for
42 * - Enumerator.new
43 *
44 * Most methods have two forms: a block form where the contents
45 * are evaluated for each item in the enumeration, and a non-block form
46 * which returns a new Enumerator wrapping the iteration.
47 *
48 * enumerator = %w(one two three).each
49 * puts enumerator.class # => Enumerator
50 *
51 * enumerator.each_with_object("foo") do |item, obj|
52 * puts "#{obj}: #{item}"
53 * end
54 *
55 * # foo: one
56 * # foo: two
57 * # foo: three
58 *
59 * enum_with_obj = enumerator.each_with_object("foo")
60 * puts enum_with_obj.class # => Enumerator
61 *
62 * enum_with_obj.each do |item, obj|
63 * puts "#{obj}: #{item}"
64 * end
65 *
66 * # foo: one
67 * # foo: two
68 * # foo: three
69 *
70 * This allows you to chain Enumerators together. For example, you
71 * can map a list's elements to strings containing the index
72 * and the element as a string via:
73 *
74 * puts %w[foo bar baz].map.with_index { |w, i| "#{i}:#{w}" }
75 * # => ["0:foo", "1:bar", "2:baz"]
76 *
77 * == External Iteration
78 *
79 * An Enumerator can also be used as an external iterator.
80 * For example, Enumerator#next returns the next value of the iterator
81 * or raises StopIteration if the Enumerator is at the end.
82 *
83 * e = [1,2,3].each # returns an enumerator object.
84 * puts e.next # => 1
85 * puts e.next # => 2
86 * puts e.next # => 3
87 * puts e.next # raises StopIteration
88 *
89 * +next+, +next_values+, +peek+, and +peek_values+ are the only methods
90 * which use external iteration (and Array#zip(Enumerable-not-Array) which uses +next+ internally).
91 *
92 * These methods do not affect other internal enumeration methods,
93 * unless the underlying iteration method itself has side-effect, e.g. IO#each_line.
94 *
95 * FrozenError will be raised if these methods are called against a frozen enumerator.
96 * Since +rewind+ and +feed+ also change state for external iteration,
97 * these methods may raise FrozenError too.
98 *
99 * External iteration differs *significantly* from internal iteration
100 * due to using a Fiber:
101 * - The Fiber adds some overhead compared to internal enumeration.
102 * - The stacktrace will only include the stack from the Enumerator, not above.
103 * - Fiber-local variables are *not* inherited inside the Enumerator Fiber,
104 * which instead starts with no Fiber-local variables.
105 * - Fiber storage variables *are* inherited and are designed
106 * to handle Enumerator Fibers. Assigning to a Fiber storage variable
107 * only affects the current Fiber, so if you want to change state
108 * in the caller Fiber of the Enumerator Fiber, you need to use an
109 * extra indirection (e.g., use some object in the Fiber storage
110 * variable and mutate some ivar of it).
111 *
112 * Concretely:
113 *
114 * Thread.current[:fiber_local] = 1
115 * Fiber[:storage_var] = 1
116 * e = Enumerator.new do |y|
117 * p Thread.current[:fiber_local] # for external iteration: nil, for internal iteration: 1
118 * p Fiber[:storage_var] # => 1, inherited
119 * Fiber[:storage_var] += 1
120 * y << 42
121 * end
122 *
123 * p e.next # => 42
124 * p Fiber[:storage_var] # => 1 (it ran in a different Fiber)
125 *
126 * e.each { p _1 }
127 * p Fiber[:storage_var] # => 2 (it ran in the same Fiber/"stack" as the current Fiber)
128 *
129 * == Convert External Iteration to Internal Iteration
130 *
131 * You can use an external iterator to implement an internal iterator as follows:
132 *
133 * def ext_each(e)
134 * while true
135 * begin
136 * vs = e.next_values
137 * rescue StopIteration
138 * return $!.result
139 * end
140 * y = yield(*vs)
141 * e.feed y
142 * end
143 * end
144 *
145 * o = Object.new
146 *
147 * def o.each
148 * puts yield
149 * puts yield(1)
150 * puts yield(1, 2)
151 * 3
152 * end
153 *
154 * # use o.each as an internal iterator directly.
155 * puts o.each {|*x| puts x; [:b, *x] }
156 * # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3
157 *
158 * # convert o.each to an external iterator for
159 * # implementing an internal iterator.
160 * puts ext_each(o.to_enum) {|*x| puts x; [:b, *x] }
161 * # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3
162 *
163 */
165static VALUE rb_cLazy;
166static ID id_rewind, id_to_enum, id_each_entry;
167static ID id_next, id_result, id_receiver, id_arguments, id_memo, id_method, id_force;
168static VALUE sym_each, sym_yield;
169
170static VALUE lazy_use_super_method;
171
172extern ID ruby_static_id_cause;
173
174#define id_call idCall
175#define id_cause ruby_static_id_cause
176#define id_each idEach
177#define id_eqq idEqq
178#define id_initialize idInitialize
179#define id_size idSize
180
182
184 VALUE obj;
185 ID meth;
186 VALUE args;
187 VALUE fib;
188 VALUE dst;
189 VALUE lookahead;
190 VALUE feedvalue;
191 VALUE stop_exc;
192 VALUE size;
193 VALUE procs;
195 int kw_splat;
196};
197
198RUBY_REFERENCES(enumerator_refs) = {
199 RUBY_REF_EDGE(struct enumerator, obj),
200 RUBY_REF_EDGE(struct enumerator, args),
201 RUBY_REF_EDGE(struct enumerator, fib),
202 RUBY_REF_EDGE(struct enumerator, dst),
203 RUBY_REF_EDGE(struct enumerator, lookahead),
204 RUBY_REF_EDGE(struct enumerator, feedvalue),
205 RUBY_REF_EDGE(struct enumerator, stop_exc),
206 RUBY_REF_EDGE(struct enumerator, size),
207 RUBY_REF_EDGE(struct enumerator, procs),
208 RUBY_REF_END
209};
210
211static VALUE rb_cGenerator, rb_cYielder, rb_cEnumProducer;
212
213struct generator {
214 VALUE proc;
215 VALUE obj;
216};
217
218struct yielder {
219 VALUE proc;
220};
221
222struct producer {
223 VALUE init;
224 VALUE proc;
225 VALUE size;
226};
227
228typedef struct MEMO *lazyenum_proc_func(VALUE, struct MEMO *, VALUE, long);
229typedef VALUE lazyenum_size_func(VALUE, VALUE);
230typedef int lazyenum_precheck_func(VALUE proc_entry);
231typedef struct {
232 lazyenum_proc_func *proc;
233 lazyenum_size_func *size;
234 lazyenum_precheck_func *precheck;
236
238 VALUE proc;
239 VALUE memo;
240 const lazyenum_funcs *fn;
241};
242
243static VALUE generator_allocate(VALUE klass);
244static VALUE generator_init(VALUE obj, VALUE proc);
245
246static VALUE rb_cEnumChain;
247
249 VALUE enums;
250 long pos;
251};
252
253static VALUE rb_cEnumProduct;
254
256 VALUE enums;
257};
258
259VALUE rb_cArithSeq;
260
261static const rb_data_type_t enumerator_data_type = {
262 "enumerator",
263 {
264 RUBY_REFS_LIST_PTR(enumerator_refs),
266 NULL, // Nothing allocated externally, so don't need a memsize function
267 NULL,
268 },
269 0, NULL, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_DECL_MARKING | RUBY_TYPED_EMBEDDABLE
270};
271
272static struct enumerator *
273enumerator_ptr(VALUE obj)
274{
275 struct enumerator *ptr;
276
277 TypedData_Get_Struct(obj, struct enumerator, &enumerator_data_type, ptr);
278 if (!ptr || UNDEF_P(ptr->obj)) {
279 rb_raise(rb_eArgError, "uninitialized enumerator");
280 }
281 return ptr;
282}
283
284static void
285proc_entry_mark_and_move(void *p)
286{
287 struct proc_entry *ptr = p;
288 rb_gc_mark_and_move(&ptr->proc);
289 rb_gc_mark_and_move(&ptr->memo);
290}
291
292static const rb_data_type_t proc_entry_data_type = {
293 "proc_entry",
294 {
295 proc_entry_mark_and_move,
297 NULL, // Nothing allocated externally, so don't need a memsize function
298 proc_entry_mark_and_move,
299 },
300 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
301};
302
303static struct proc_entry *
304proc_entry_ptr(VALUE proc_entry)
305{
306 struct proc_entry *ptr;
307
308 TypedData_Get_Struct(proc_entry, struct proc_entry, &proc_entry_data_type, ptr);
309
310 return ptr;
311}
312
313/*
314 * call-seq:
315 * obj.to_enum(method = :each, *args) -> enum
316 * obj.enum_for(method = :each, *args) -> enum
317 * obj.to_enum(method = :each, *args) {|*args| block} -> enum
318 * obj.enum_for(method = :each, *args){|*args| block} -> enum
319 *
320 * Creates a new Enumerator which will enumerate by calling +method+ on
321 * +obj+, passing +args+ if any. What was _yielded_ by method becomes
322 * values of enumerator.
323 *
324 * If a block is given, it will be used to calculate the size of
325 * the enumerator without the need to iterate it (see Enumerator#size).
326 *
327 * === Examples
328 *
329 * str = "xyz"
330 *
331 * enum = str.enum_for(:each_byte)
332 * enum.each { |b| puts b }
333 * # => 120
334 * # => 121
335 * # => 122
336 *
337 * # protect an array from being modified by some_method
338 * a = [1, 2, 3]
339 * some_method(a.to_enum)
340 *
341 * # String#split in block form is more memory-effective:
342 * very_large_string.split("|") { |chunk| return chunk if chunk.include?('DATE') }
343 * # This could be rewritten more idiomatically with to_enum:
344 * very_large_string.to_enum(:split, "|").lazy.grep(/DATE/).first
345 *
346 * It is typical to call to_enum when defining methods for
347 * a generic Enumerable, in case no block is passed.
348 *
349 * Here is such an example, with parameter passing and a sizing block:
350 *
351 * module Enumerable
352 * # a generic method to repeat the values of any enumerable
353 * def repeat(n)
354 * raise ArgumentError, "#{n} is negative!" if n < 0
355 * unless block_given?
356 * return to_enum(__method__, n) do # __method__ is :repeat here
357 * sz = size # Call size and multiply by n...
358 * sz * n if sz # but return nil if size itself is nil
359 * end
360 * end
361 * each do |*val|
362 * n.times { yield *val }
363 * end
364 * end
365 * end
366 *
367 * %i[hello world].repeat(2) { |w| puts w }
368 * # => Prints 'hello', 'hello', 'world', 'world'
369 * enum = (1..14).repeat(3)
370 * # => returns an Enumerator when called without a block
371 * enum.first(4) # => [1, 1, 1, 2]
372 * enum.size # => 42
373 */
374static VALUE
375obj_to_enum(int argc, VALUE *argv, VALUE obj)
376{
377 VALUE enumerator, meth = sym_each;
378
379 if (argc > 0) {
380 --argc;
381 meth = *argv++;
382 }
383 enumerator = rb_enumeratorize_with_size(obj, meth, argc, argv, 0);
384 if (rb_block_given_p()) {
385 RB_OBJ_WRITE(enumerator, &enumerator_ptr(enumerator)->size, rb_block_proc());
386 }
387 return enumerator;
388}
389
390static VALUE
391enumerator_allocate(VALUE klass)
392{
393 struct enumerator *ptr;
394 VALUE enum_obj;
395
396 enum_obj = TypedData_Make_Struct(klass, struct enumerator, &enumerator_data_type, ptr);
397 ptr->obj = Qundef;
398
399 return enum_obj;
400}
401
402static VALUE
403enumerator_init(VALUE enum_obj, VALUE obj, VALUE meth, int argc, const VALUE *argv, rb_enumerator_size_func *size_fn, VALUE size, int kw_splat)
404{
405 struct enumerator *ptr;
406
407 rb_check_frozen(enum_obj);
408 TypedData_Get_Struct(enum_obj, struct enumerator, &enumerator_data_type, ptr);
409
410 if (!ptr) {
411 rb_raise(rb_eArgError, "unallocated enumerator");
412 }
413
414 RB_OBJ_WRITE(enum_obj, &ptr->obj, obj);
415 ptr->meth = rb_to_id(meth);
416 if (argc) RB_OBJ_WRITE(enum_obj, &ptr->args, rb_ary_new4(argc, argv));
417 ptr->fib = 0;
418 ptr->dst = Qnil;
419 ptr->lookahead = Qundef;
420 ptr->feedvalue = Qundef;
421 ptr->stop_exc = Qfalse;
422 RB_OBJ_WRITE(enum_obj, &ptr->size, size);
423 ptr->size_fn = size_fn;
424 ptr->kw_splat = kw_splat;
425
426 return enum_obj;
427}
428
429static VALUE
430convert_to_feasible_size_value(VALUE obj)
431{
432 if (NIL_P(obj)) {
433 return obj;
434 }
435 else if (rb_respond_to(obj, id_call)) {
436 return obj;
437 }
438 else if (RB_FLOAT_TYPE_P(obj) && RFLOAT_VALUE(obj) == HUGE_VAL) {
439 return obj;
440 }
441 else {
442 return rb_to_int(obj);
443 }
444}
445
446/*
447 * call-seq:
448 * Enumerator.new(size = nil) { |yielder| ... }
449 *
450 * Creates a new Enumerator object, which can be used as an
451 * Enumerable.
452 *
453 * Iteration is defined by the given block, in
454 * which a "yielder" object, given as block parameter, can be used to
455 * yield a value by calling the +yield+ method (aliased as <code><<</code>):
456 *
457 * fib = Enumerator.new do |y|
458 * a = b = 1
459 * loop do
460 * y << a
461 * a, b = b, a + b
462 * end
463 * end
464 *
465 * fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
466 *
467 * The optional parameter can be used to specify how to calculate the size
468 * in a lazy fashion (see Enumerator#size). It can either be a value or
469 * a callable object.
470 */
471static VALUE
472enumerator_initialize(int argc, VALUE *argv, VALUE obj)
473{
474 VALUE iter = rb_block_proc();
475 VALUE recv = generator_init(generator_allocate(rb_cGenerator), iter);
476 VALUE arg0 = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
477 VALUE size = convert_to_feasible_size_value(arg0);
478
479 return enumerator_init(obj, recv, sym_each, 0, 0, 0, size, false);
480}
481
482/* :nodoc: */
483static VALUE
484enumerator_init_copy(VALUE obj, VALUE orig)
485{
486 struct enumerator *ptr0, *ptr1;
487
488 if (!OBJ_INIT_COPY(obj, orig)) return obj;
489 ptr0 = enumerator_ptr(orig);
490 if (ptr0->fib) {
491 /* Fibers cannot be copied */
492 rb_raise(rb_eTypeError, "can't copy execution context");
493 }
494
495 TypedData_Get_Struct(obj, struct enumerator, &enumerator_data_type, ptr1);
496
497 if (!ptr1) {
498 rb_raise(rb_eArgError, "unallocated enumerator");
499 }
500
501 RB_OBJ_WRITE(obj, &ptr1->obj, ptr0->obj);
502 ptr1->meth = ptr0->meth;
503 RB_OBJ_WRITE(obj, &ptr1->args, ptr0->args);
504 ptr1->fib = 0;
505 ptr1->lookahead = Qundef;
506 ptr1->feedvalue = Qundef;
507 RB_OBJ_WRITE(obj, &ptr1->size, ptr0->size);
508 ptr1->size_fn = ptr0->size_fn;
509
510 return obj;
511}
512
513/*
514 * For backwards compatibility; use rb_enumeratorize_with_size
515 */
516VALUE
517rb_enumeratorize(VALUE obj, VALUE meth, int argc, const VALUE *argv)
518{
519 return rb_enumeratorize_with_size(obj, meth, argc, argv, 0);
520}
521
522static VALUE lazy_to_enum_i(VALUE self, VALUE meth, int argc, const VALUE *argv, rb_enumerator_size_func *size_fn, int kw_splat);
523static int lazy_precheck(VALUE procs);
524
525VALUE
526rb_enumeratorize_with_size_kw(VALUE obj, VALUE meth, int argc, const VALUE *argv, rb_enumerator_size_func *size_fn, int kw_splat)
527{
528 VALUE base_class = rb_cEnumerator;
529
530 if (RTEST(rb_obj_is_kind_of(obj, rb_cLazy))) {
531 base_class = rb_cLazy;
532 }
533 else if (RTEST(rb_obj_is_kind_of(obj, rb_cEnumChain))) {
534 obj = enumerator_init(enumerator_allocate(rb_cEnumerator), obj, sym_each, 0, 0, 0, Qnil, false);
535 }
536
537 return enumerator_init(enumerator_allocate(base_class),
538 obj, meth, argc, argv, size_fn, Qnil, kw_splat);
539}
540
541VALUE
542rb_enumeratorize_with_size(VALUE obj, VALUE meth, int argc, const VALUE *argv, rb_enumerator_size_func *size_fn)
543{
544 return rb_enumeratorize_with_size_kw(obj, meth, argc, argv, size_fn, rb_keyword_given_p());
545}
546
547static VALUE
548enumerator_block_call(VALUE obj, rb_block_call_func *func, VALUE arg)
549{
550 int argc = 0;
551 const VALUE *argv = 0;
552 const struct enumerator *e = enumerator_ptr(obj);
553 ID meth = e->meth;
554
555 VALUE args = e->args;
556 if (args) {
557 argc = RARRAY_LENINT(args);
558 argv = RARRAY_CONST_PTR(args);
559 }
560
561 VALUE ret = rb_block_call_kw(e->obj, meth, argc, argv, func, arg, e->kw_splat);
562
563 RB_GC_GUARD(args);
564
565 return ret;
566}
567
568/*
569 * call-seq:
570 * enum.each { |elm| block } -> obj
571 * enum.each -> enum
572 * enum.each(*appending_args) { |elm| block } -> obj
573 * enum.each(*appending_args) -> an_enumerator
574 *
575 * Iterates over the block according to how this Enumerator was constructed.
576 * If no block and no arguments are given, returns self.
577 *
578 * === Examples
579 *
580 * "Hello, world!".scan(/\w+/) #=> ["Hello", "world"]
581 * "Hello, world!".to_enum(:scan, /\w+/).to_a #=> ["Hello", "world"]
582 * "Hello, world!".to_enum(:scan).each(/\w+/).to_a #=> ["Hello", "world"]
583 *
584 * obj = Object.new
585 *
586 * def obj.each_arg(a, b=:b, *rest)
587 * yield a
588 * yield b
589 * yield rest
590 * :method_returned
591 * end
592 *
593 * enum = obj.to_enum :each_arg, :a, :x
594 *
595 * enum.each.to_a #=> [:a, :x, []]
596 * enum.each.equal?(enum) #=> true
597 * enum.each { |elm| elm } #=> :method_returned
598 *
599 * enum.each(:y, :z).to_a #=> [:a, :x, [:y, :z]]
600 * enum.each(:y, :z).equal?(enum) #=> false
601 * enum.each(:y, :z) { |elm| elm } #=> :method_returned
602 *
603 */
604static VALUE
605enumerator_each(int argc, VALUE *argv, VALUE obj)
606{
607 struct enumerator *e = enumerator_ptr(obj);
608
609 if (argc > 0) {
610 VALUE args = (e = enumerator_ptr(obj = rb_obj_dup(obj)))->args;
611 if (args) {
612#if SIZEOF_INT < SIZEOF_LONG
613 /* check int range overflow */
614 rb_long2int(RARRAY_LEN(args) + argc);
615#endif
616 args = rb_ary_dup(args);
617 rb_ary_cat(args, argv, argc);
618 }
619 else {
620 args = rb_ary_new4(argc, argv);
621 }
622 RB_OBJ_WRITE(obj, &e->args, args);
623 e->size = Qnil;
624 e->size_fn = 0;
625 }
626 if (!rb_block_given_p()) return obj;
627
628 if (!lazy_precheck(e->procs)) return Qnil;
629
630 return enumerator_block_call(obj, 0, obj);
631}
632
633static VALUE
634enumerator_with_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, m))
635{
636 struct MEMO *memo = (struct MEMO *)m;
637 VALUE idx = memo->v1;
638 MEMO_V1_SET(memo, rb_int_succ(idx));
639
640 if (argc <= 1)
641 return rb_yield_values(2, val, idx);
642
643 return rb_yield_values(2, rb_ary_new4(argc, argv), idx);
644}
645
646static VALUE
647enumerator_size(VALUE obj);
648
649static VALUE
650enumerator_enum_size(VALUE obj, VALUE args, VALUE eobj)
651{
652 return enumerator_size(obj);
653}
654
655/*
656 * call-seq:
657 * e.with_index(offset = 0) {|(*args), idx| ... }
658 * e.with_index(offset = 0)
659 *
660 * Iterates the given block for each element with an index, which
661 * starts from +offset+. If no block is given, returns a new Enumerator
662 * that includes the index, starting from +offset+
663 *
664 * +offset+:: the starting index to use
665 *
666 */
667static VALUE
668enumerator_with_index(int argc, VALUE *argv, VALUE obj)
669{
670 VALUE memo;
671
672 rb_check_arity(argc, 0, 1);
673 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enumerator_enum_size);
674 memo = (!argc || NIL_P(memo = argv[0])) ? INT2FIX(0) : rb_to_int(memo);
675 return enumerator_block_call(obj, enumerator_with_index_i, (VALUE)MEMO_NEW(memo, 0, 0));
676}
677
678/*
679 * call-seq:
680 * e.each_with_index {|(*args), idx| ... }
681 * e.each_with_index
682 *
683 * Same as Enumerator#with_index(0), i.e. there is no starting offset.
684 *
685 * If no block is given, a new Enumerator is returned that includes the index.
686 *
687 */
688static VALUE
689enumerator_each_with_index(VALUE obj)
690{
691 return enumerator_with_index(0, NULL, obj);
692}
693
694static VALUE
695enumerator_with_object_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, memo))
696{
697 if (argc <= 1)
698 return rb_yield_values(2, val, memo);
699
700 return rb_yield_values(2, rb_ary_new4(argc, argv), memo);
701}
702
703/*
704 * call-seq:
705 * e.each_with_object(obj) {|(*args), obj| ... }
706 * e.each_with_object(obj)
707 * e.with_object(obj) {|(*args), obj| ... }
708 * e.with_object(obj)
709 *
710 * Iterates the given block for each element with an arbitrary object, +obj+,
711 * and returns +obj+
712 *
713 * If no block is given, returns a new Enumerator.
714 *
715 * === Example
716 *
717 * to_three = Enumerator.new do |y|
718 * 3.times do |x|
719 * y << x
720 * end
721 * end
722 *
723 * to_three_with_string = to_three.with_object("foo")
724 * to_three_with_string.each do |x,string|
725 * puts "#{string}: #{x}"
726 * end
727 *
728 * # => foo: 0
729 * # => foo: 1
730 * # => foo: 2
731 */
732static VALUE
733enumerator_with_object(VALUE obj, VALUE memo)
734{
735 RETURN_SIZED_ENUMERATOR(obj, 1, &memo, enumerator_enum_size);
736 enumerator_block_call(obj, enumerator_with_object_i, memo);
737
738 return memo;
739}
740
741static VALUE
742next_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, obj))
743{
744 struct enumerator *e = enumerator_ptr(obj);
745 VALUE feedvalue = Qnil;
746 VALUE args = rb_ary_new4(argc, argv);
747 rb_fiber_yield(1, &args);
748 if (!UNDEF_P(e->feedvalue)) {
749 feedvalue = e->feedvalue;
750 e->feedvalue = Qundef;
751 }
752 return feedvalue;
753}
754
755static VALUE
756next_i(RB_BLOCK_CALL_FUNC_ARGLIST(_, obj))
757{
758 struct enumerator *e = enumerator_ptr(obj);
759 VALUE nil = Qnil;
760 VALUE result;
761
762 result = rb_block_call(obj, id_each, 0, 0, next_ii, obj);
763 RB_OBJ_WRITE(obj, &e->stop_exc, rb_exc_new2(rb_eStopIteration, "iteration reached an end"));
764 rb_ivar_set(e->stop_exc, id_result, result);
765 return rb_fiber_yield(1, &nil);
766}
767
768static void
769next_init(VALUE obj, struct enumerator *e)
770{
771 VALUE curr = rb_fiber_current();
772 RB_OBJ_WRITE(obj, &e->dst, curr);
773 RB_OBJ_WRITE(obj, &e->fib, rb_fiber_new(next_i, obj));
774 e->lookahead = Qundef;
775}
776
777static VALUE
778get_next_values(VALUE obj, struct enumerator *e)
779{
780 VALUE curr, vs;
781
782 if (e->stop_exc) {
783 VALUE exc = e->stop_exc;
784 VALUE result = rb_attr_get(exc, id_result);
785 VALUE mesg = rb_attr_get(exc, idMesg);
786 if (!NIL_P(mesg)) mesg = rb_str_dup(mesg);
787 VALUE stop_exc = rb_exc_new_str(rb_eStopIteration, mesg);
788 rb_ivar_set(stop_exc, id_cause, exc);
789 rb_ivar_set(stop_exc, id_result, result);
790 rb_exc_raise(stop_exc);
791 }
792
793 curr = rb_fiber_current();
794
795 if (!e->fib || !rb_fiber_alive_p(e->fib)) {
796 next_init(obj, e);
797 }
798
799 vs = rb_fiber_resume(e->fib, 1, &curr);
800 if (e->stop_exc) {
801 e->fib = 0;
802 e->dst = Qnil;
803 e->lookahead = Qundef;
804 e->feedvalue = Qundef;
805 rb_exc_raise(e->stop_exc);
806 }
807 return vs;
808}
809
810/*
811 * call-seq:
812 * e.next_values -> array
813 *
814 * Returns the next object as an array in the enumerator, and move the
815 * internal position forward. When the position reached at the end,
816 * StopIteration is raised.
817 *
818 * See class-level notes about external iterators.
819 *
820 * This method can be used to distinguish <code>yield</code> and <code>yield
821 * nil</code>.
822 *
823 * === Example
824 *
825 * o = Object.new
826 * def o.each
827 * yield
828 * yield 1
829 * yield 1, 2
830 * yield nil
831 * yield [1, 2]
832 * end
833 * e = o.to_enum
834 * p e.next_values
835 * p e.next_values
836 * p e.next_values
837 * p e.next_values
838 * p e.next_values
839 * e = o.to_enum
840 * p e.next
841 * p e.next
842 * p e.next
843 * p e.next
844 * p e.next
845 *
846 * ## yield args next_values next
847 * # yield [] nil
848 * # yield 1 [1] 1
849 * # yield 1, 2 [1, 2] [1, 2]
850 * # yield nil [nil] nil
851 * # yield [1, 2] [[1, 2]] [1, 2]
852 *
853 */
854
855static VALUE
856enumerator_next_values(VALUE obj)
857{
858 struct enumerator *e = enumerator_ptr(obj);
859 VALUE vs;
860
861 rb_check_frozen(obj);
862
863 if (!UNDEF_P(e->lookahead)) {
864 vs = e->lookahead;
865 e->lookahead = Qundef;
866 return vs;
867 }
868
869 return get_next_values(obj, e);
870}
871
872static VALUE
873ary2sv(VALUE args, int dup)
874{
875 if (!RB_TYPE_P(args, T_ARRAY))
876 return args;
877
878 switch (RARRAY_LEN(args)) {
879 case 0:
880 return Qnil;
881
882 case 1:
883 return RARRAY_AREF(args, 0);
884
885 default:
886 if (dup)
887 return rb_ary_dup(args);
888 return args;
889 }
890}
891
892/*
893 * call-seq:
894 * e.next -> object
895 *
896 * Returns the next object in the enumerator, and move the internal position
897 * forward. When the position reached at the end, StopIteration is raised.
898 *
899 * === Example
900 *
901 * a = [1,2,3]
902 * e = a.to_enum
903 * p e.next #=> 1
904 * p e.next #=> 2
905 * p e.next #=> 3
906 * p e.next #raises StopIteration
907 *
908 * See class-level notes about external iterators.
909 *
910 */
911
912static VALUE
913enumerator_next(VALUE obj)
914{
915 VALUE vs = enumerator_next_values(obj);
916 return ary2sv(vs, 0);
917}
918
919static VALUE
920enumerator_peek_values(VALUE obj)
921{
922 struct enumerator *e = enumerator_ptr(obj);
923
924 rb_check_frozen(obj);
925
926 if (UNDEF_P(e->lookahead)) {
927 RB_OBJ_WRITE(obj, &e->lookahead, get_next_values(obj, e));
928 }
929
930 return e->lookahead;
931}
932
933/*
934 * call-seq:
935 * e.peek_values -> array
936 *
937 * Returns the next object as an array, similar to Enumerator#next_values, but
938 * doesn't move the internal position forward. If the position is already at
939 * the end, StopIteration is raised.
940 *
941 * See class-level notes about external iterators.
942 *
943 * === Example
944 *
945 * o = Object.new
946 * def o.each
947 * yield
948 * yield 1
949 * yield 1, 2
950 * end
951 * e = o.to_enum
952 * p e.peek_values #=> []
953 * e.next
954 * p e.peek_values #=> [1]
955 * p e.peek_values #=> [1]
956 * e.next
957 * p e.peek_values #=> [1, 2]
958 * e.next
959 * p e.peek_values # raises StopIteration
960 *
961 */
962
963static VALUE
964enumerator_peek_values_m(VALUE obj)
965{
966 return rb_ary_dup(enumerator_peek_values(obj));
967}
968
969/*
970 * call-seq:
971 * e.peek -> object
972 *
973 * Returns the next object in the enumerator, but doesn't move the internal
974 * position forward. If the position is already at the end, StopIteration
975 * is raised.
976 *
977 * See class-level notes about external iterators.
978 *
979 * === Example
980 *
981 * a = [1,2,3]
982 * e = a.to_enum
983 * p e.next #=> 1
984 * p e.peek #=> 2
985 * p e.peek #=> 2
986 * p e.peek #=> 2
987 * p e.next #=> 2
988 * p e.next #=> 3
989 * p e.peek #raises StopIteration
990 *
991 */
992
993static VALUE
994enumerator_peek(VALUE obj)
995{
996 VALUE vs = enumerator_peek_values(obj);
997 return ary2sv(vs, 1);
998}
999
1000/*
1001 * call-seq:
1002 * e.feed obj -> nil
1003 *
1004 * Sets the value to be returned by the next yield inside +e+.
1005 *
1006 * If the value is not set, the yield returns nil.
1007 *
1008 * This value is cleared after being yielded.
1009 *
1010 * # Array#map passes the array's elements to "yield" and collects the
1011 * # results of "yield" as an array.
1012 * # Following example shows that "next" returns the passed elements and
1013 * # values passed to "feed" are collected as an array which can be
1014 * # obtained by StopIteration#result.
1015 * e = [1,2,3].map
1016 * p e.next #=> 1
1017 * e.feed "a"
1018 * p e.next #=> 2
1019 * e.feed "b"
1020 * p e.next #=> 3
1021 * e.feed "c"
1022 * begin
1023 * e.next
1024 * rescue StopIteration
1025 * p $!.result #=> ["a", "b", "c"]
1026 * end
1027 *
1028 * o = Object.new
1029 * def o.each
1030 * x = yield # (2) blocks
1031 * p x # (5) => "foo"
1032 * x = yield # (6) blocks
1033 * p x # (8) => nil
1034 * x = yield # (9) blocks
1035 * p x # not reached w/o another e.next
1036 * end
1037 *
1038 * e = o.to_enum
1039 * e.next # (1)
1040 * e.feed "foo" # (3)
1041 * e.next # (4)
1042 * e.next # (7)
1043 * # (10)
1044 */
1045
1046static VALUE
1047enumerator_feed(VALUE obj, VALUE v)
1048{
1049 struct enumerator *e = enumerator_ptr(obj);
1050
1051 rb_check_frozen(obj);
1052
1053 if (!UNDEF_P(e->feedvalue)) {
1054 rb_raise(rb_eTypeError, "feed value already set");
1055 }
1056 RB_OBJ_WRITE(obj, &e->feedvalue, v);
1057
1058 return Qnil;
1059}
1060
1061/*
1062 * call-seq:
1063 * e.rewind -> e
1064 *
1065 * Rewinds the enumeration sequence to the beginning.
1066 *
1067 * If the enclosed object responds to a "rewind" method, it is called.
1068 */
1069
1070static VALUE
1071enumerator_rewind(VALUE obj)
1072{
1073 struct enumerator *e = enumerator_ptr(obj);
1074
1075 rb_check_frozen(obj);
1076
1077 rb_check_funcall(e->obj, id_rewind, 0, 0);
1078
1079 e->fib = 0;
1080 e->dst = Qnil;
1081 e->lookahead = Qundef;
1082 e->feedvalue = Qundef;
1083 e->stop_exc = Qfalse;
1084 return obj;
1085}
1086
1087static struct generator *generator_ptr(VALUE obj);
1088static VALUE append_method(VALUE obj, VALUE str, ID default_method, VALUE default_args);
1089
1090static VALUE
1091inspect_enumerator(VALUE obj, VALUE dummy, int recur)
1092{
1093 struct enumerator *e;
1094 VALUE eobj, str, cname;
1095
1096 TypedData_Get_Struct(obj, struct enumerator, &enumerator_data_type, e);
1097
1098 cname = rb_obj_class(obj);
1099
1100 if (!e || UNDEF_P(e->obj)) {
1101 return rb_sprintf("#<%"PRIsVALUE": uninitialized>", rb_class_path(cname));
1102 }
1103
1104 if (recur) {
1105 str = rb_sprintf("#<%"PRIsVALUE": ...>", rb_class_path(cname));
1106 return str;
1107 }
1108
1109 if (e->procs) {
1110 long i;
1111
1112 eobj = generator_ptr(e->obj)->obj;
1113 /* In case procs chained enumerator traversing all proc entries manually */
1114 if (rb_obj_class(eobj) == cname) {
1115 str = rb_inspect(eobj);
1116 }
1117 else {
1118 str = rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE">", rb_class_path(cname), eobj);
1119 }
1120 for (i = 0; i < RARRAY_LEN(e->procs); i++) {
1121 str = rb_sprintf("#<%"PRIsVALUE": %"PRIsVALUE, cname, str);
1122 append_method(RARRAY_AREF(e->procs, i), str, e->meth, e->args);
1123 rb_str_buf_cat2(str, ">");
1124 }
1125 return str;
1126 }
1127
1128 eobj = rb_attr_get(obj, id_receiver);
1129 if (NIL_P(eobj)) {
1130 eobj = e->obj;
1131 }
1132
1133 /* (1..100).each_cons(2) => "#<Enumerator: 1..100:each_cons(2)>" */
1134 str = rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE, rb_class_path(cname), eobj);
1135 append_method(obj, str, e->meth, e->args);
1136
1137 rb_str_buf_cat2(str, ">");
1138
1139 return str;
1140}
1141
1142static int
1143key_symbol_p(VALUE key, VALUE val, VALUE arg)
1144{
1145 if (SYMBOL_P(key)) return ST_CONTINUE;
1146 *(int *)arg = FALSE;
1147 return ST_STOP;
1148}
1149
1150static int
1151kwd_append(VALUE key, VALUE val, VALUE str)
1152{
1153 if (!SYMBOL_P(key)) rb_raise(rb_eRuntimeError, "non-symbol key inserted");
1154 rb_str_catf(str, "% "PRIsVALUE": %"PRIsVALUE", ", key, val);
1155 return ST_CONTINUE;
1156}
1157
1158static VALUE
1159append_method(VALUE obj, VALUE str, ID default_method, VALUE default_args)
1160{
1161 VALUE method, eargs;
1162
1163 method = rb_attr_get(obj, id_method);
1164 if (method != Qfalse) {
1165 if (!NIL_P(method)) {
1166 Check_Type(method, T_SYMBOL);
1167 method = rb_sym2str(method);
1168 }
1169 else {
1170 method = rb_id2str(default_method);
1171 }
1172 rb_str_buf_cat2(str, ":");
1173 rb_str_buf_append(str, method);
1174 }
1175
1176 eargs = rb_attr_get(obj, id_arguments);
1177 if (NIL_P(eargs)) {
1178 eargs = default_args;
1179 }
1180 if (eargs != Qfalse) {
1181 long argc = RARRAY_LEN(eargs);
1182 const VALUE *argv = RARRAY_CONST_PTR(eargs); /* WB: no new reference */
1183
1184 if (argc > 0) {
1185 VALUE kwds = Qnil;
1186
1187 rb_str_buf_cat2(str, "(");
1188
1189 if (RB_TYPE_P(argv[argc-1], T_HASH) && !RHASH_EMPTY_P(argv[argc-1])) {
1190 int all_key = TRUE;
1191 rb_hash_foreach(argv[argc-1], key_symbol_p, (VALUE)&all_key);
1192 if (all_key) kwds = argv[--argc];
1193 }
1194
1195 while (argc--) {
1196 VALUE arg = *argv++;
1197
1198 rb_str_append(str, rb_inspect(arg));
1199 rb_str_buf_cat2(str, ", ");
1200 }
1201 if (!NIL_P(kwds)) {
1202 rb_hash_foreach(kwds, kwd_append, str);
1203 }
1204 rb_str_set_len(str, RSTRING_LEN(str)-2);
1205 rb_str_buf_cat2(str, ")");
1206 }
1207 }
1208 RB_GC_GUARD(eargs);
1209
1210 return str;
1211}
1212
1213/*
1214 * call-seq:
1215 * e.inspect -> string
1216 *
1217 * Creates a printable version of <i>e</i>.
1218 */
1219
1220static VALUE
1221enumerator_inspect(VALUE obj)
1222{
1223 return rb_exec_recursive(inspect_enumerator, obj, 0);
1224}
1225
1226/*
1227 * call-seq:
1228 * e.size -> int, Float::INFINITY or nil
1229 *
1230 * Returns the size of the enumerator, or +nil+ if it can't be calculated lazily.
1231 *
1232 * (1..100).to_a.permutation(4).size # => 94109400
1233 * loop.size # => Float::INFINITY
1234 * (1..100).drop_while.size # => nil
1235 *
1236 * Note that enumerator size might be inaccurate, and should be rather treated as a hint.
1237 * For example, there is no check that the size provided to ::new is accurate:
1238 *
1239 * e = Enumerator.new(5) { |y| 2.times { y << it} }
1240 * e.size # => 5
1241 * e.to_a.size # => 2
1242 *
1243 * Another example is an enumerator created by ::produce without a +size+ argument.
1244 * Such enumerators return +Infinity+ for size, but this is inaccurate if the passed
1245 * block raises StopIteration:
1246 *
1247 * e = Enumerator.produce(1) { it + 1 }
1248 * e.size # => Infinity
1249 *
1250 * e = Enumerator.produce(1) { it > 3 ? raise(StopIteration) : it + 1 }
1251 * e.size # => Infinity
1252 * e.to_a.size # => 4
1253 */
1254
1255static VALUE
1256enumerator_size(VALUE obj)
1257{
1258 struct enumerator *e = enumerator_ptr(obj);
1259 int argc = 0;
1260 const VALUE *argv = NULL;
1261 VALUE size;
1262
1263 if (e->procs) {
1264 struct generator *g = generator_ptr(e->obj);
1265 VALUE receiver = rb_check_funcall(g->obj, id_size, 0, 0);
1266 long i = 0;
1267
1268 for (i = 0; i < RARRAY_LEN(e->procs); i++) {
1269 VALUE proc = RARRAY_AREF(e->procs, i);
1270 struct proc_entry *entry = proc_entry_ptr(proc);
1271 lazyenum_size_func *size_fn = entry->fn->size;
1272 if (!size_fn) {
1273 return Qnil;
1274 }
1275 receiver = (*size_fn)(proc, receiver);
1276 }
1277 return receiver;
1278 }
1279
1280 if (e->size_fn) {
1281 return (*e->size_fn)(e->obj, e->args, obj);
1282 }
1283 if (e->args) {
1284 argc = (int)RARRAY_LEN(e->args);
1285 argv = RARRAY_CONST_PTR(e->args);
1286 }
1287 size = rb_check_funcall_kw(e->size, id_call, argc, argv, e->kw_splat);
1288 if (!UNDEF_P(size)) return size;
1289 return e->size;
1290}
1291
1292/*
1293 * Yielder
1294 */
1295static void
1296yielder_mark_and_move(void *p)
1297{
1298 struct yielder *ptr = p;
1299 rb_gc_mark_and_move(&ptr->proc);
1300}
1301
1302static const rb_data_type_t yielder_data_type = {
1303 "yielder",
1304 {
1305 yielder_mark_and_move,
1307 NULL,
1308 yielder_mark_and_move,
1309 },
1310 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
1311};
1312
1313static struct yielder *
1314yielder_ptr(VALUE obj)
1315{
1316 struct yielder *ptr;
1317
1318 TypedData_Get_Struct(obj, struct yielder, &yielder_data_type, ptr);
1319 if (!ptr || UNDEF_P(ptr->proc)) {
1320 rb_raise(rb_eArgError, "uninitialized yielder");
1321 }
1322 return ptr;
1323}
1324
1325/* :nodoc: */
1326static VALUE
1327yielder_allocate(VALUE klass)
1328{
1329 struct yielder *ptr;
1330 VALUE obj;
1331
1332 obj = TypedData_Make_Struct(klass, struct yielder, &yielder_data_type, ptr);
1333 ptr->proc = Qundef;
1334
1335 return obj;
1336}
1337
1338static VALUE
1339yielder_init(VALUE obj, VALUE proc)
1340{
1341 struct yielder *ptr;
1342
1343 TypedData_Get_Struct(obj, struct yielder, &yielder_data_type, ptr);
1344
1345 if (!ptr) {
1346 rb_raise(rb_eArgError, "unallocated yielder");
1347 }
1348
1349 RB_OBJ_WRITE(obj, &ptr->proc, proc);
1350
1351 return obj;
1352}
1353
1354/* :nodoc: */
1355static VALUE
1356yielder_initialize(VALUE obj)
1357{
1358 rb_need_block();
1359
1360 return yielder_init(obj, rb_block_proc());
1361}
1362
1363/* :nodoc: */
1364static VALUE
1365yielder_yield(VALUE obj, VALUE args)
1366{
1367 struct yielder *ptr = yielder_ptr(obj);
1368
1369 return rb_proc_call_kw(ptr->proc, args, RB_PASS_CALLED_KEYWORDS);
1370}
1371
1372/* :nodoc: */
1373static VALUE
1374yielder_yield_push(VALUE obj, VALUE arg)
1375{
1376 struct yielder *ptr = yielder_ptr(obj);
1377
1378 rb_proc_call_with_block(ptr->proc, 1, &arg, Qnil);
1379
1380 return obj;
1381}
1382
1383/*
1384 * Returns a Proc object that takes arguments and yields them.
1385 *
1386 * This method is implemented so that a Yielder object can be directly
1387 * passed to another method as a block argument.
1388 *
1389 * enum = Enumerator.new { |y|
1390 * Dir.glob("*.rb") { |file|
1391 * File.open(file) { |f| f.each_line(&y) }
1392 * }
1393 * }
1394 */
1395static VALUE
1396yielder_to_proc(VALUE obj)
1397{
1398 VALUE method = rb_obj_method(obj, sym_yield);
1399
1400 return rb_funcall(method, idTo_proc, 0);
1401}
1402
1403static VALUE
1404yielder_yield_i(RB_BLOCK_CALL_FUNC_ARGLIST(obj, memo))
1405{
1406 return rb_yield_values_kw(argc, argv, RB_PASS_CALLED_KEYWORDS);
1407}
1408
1409static VALUE
1410yielder_new(void)
1411{
1412 return yielder_init(yielder_allocate(rb_cYielder), rb_proc_new(yielder_yield_i, 0));
1413}
1414
1415/*
1416 * Generator
1417 */
1418static void
1419generator_mark_and_move(void *p)
1420{
1421 struct generator *ptr = p;
1422 rb_gc_mark_and_move(&ptr->proc);
1423 rb_gc_mark_and_move(&ptr->obj);
1424}
1425
1426static const rb_data_type_t generator_data_type = {
1427 "generator",
1428 {
1429 generator_mark_and_move,
1431 NULL,
1432 generator_mark_and_move,
1433 },
1434 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
1435};
1436
1437static struct generator *
1438generator_ptr(VALUE obj)
1439{
1440 struct generator *ptr;
1441
1442 TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr);
1443 if (!ptr || UNDEF_P(ptr->proc)) {
1444 rb_raise(rb_eArgError, "uninitialized generator");
1445 }
1446 return ptr;
1447}
1448
1449/* :nodoc: */
1450static VALUE
1451generator_allocate(VALUE klass)
1452{
1453 struct generator *ptr;
1454 VALUE obj;
1455
1456 obj = TypedData_Make_Struct(klass, struct generator, &generator_data_type, ptr);
1457 ptr->proc = Qundef;
1458
1459 return obj;
1460}
1461
1462static VALUE
1463generator_init(VALUE obj, VALUE proc)
1464{
1465 struct generator *ptr;
1466
1467 rb_check_frozen(obj);
1468 TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr);
1469
1470 if (!ptr) {
1471 rb_raise(rb_eArgError, "unallocated generator");
1472 }
1473
1474 RB_OBJ_WRITE(obj, &ptr->proc, proc);
1475
1476 return obj;
1477}
1478
1479/* :nodoc: */
1480static VALUE
1481generator_initialize(int argc, VALUE *argv, VALUE obj)
1482{
1483 VALUE proc;
1484
1485 if (argc == 0) {
1486 rb_need_block();
1487
1488 proc = rb_block_proc();
1489 }
1490 else {
1491 rb_scan_args(argc, argv, "1", &proc);
1492
1493 if (!rb_obj_is_proc(proc))
1494 rb_raise(rb_eTypeError,
1495 "wrong argument type %"PRIsVALUE" (expected Proc)",
1496 rb_obj_class(proc));
1497
1498 if (rb_block_given_p()) {
1499 rb_warn("given block not used");
1500 }
1501 }
1502
1503 return generator_init(obj, proc);
1504}
1505
1506/* :nodoc: */
1507static VALUE
1508generator_init_copy(VALUE obj, VALUE orig)
1509{
1510 struct generator *ptr0, *ptr1;
1511
1512 if (!OBJ_INIT_COPY(obj, orig)) return obj;
1513
1514 ptr0 = generator_ptr(orig);
1515
1516 TypedData_Get_Struct(obj, struct generator, &generator_data_type, ptr1);
1517
1518 if (!ptr1) {
1519 rb_raise(rb_eArgError, "unallocated generator");
1520 }
1521
1522 RB_OBJ_WRITE(obj, &ptr1->proc, ptr0->proc);
1523
1524 return obj;
1525}
1526
1527/* :nodoc: */
1528static VALUE
1529generator_each(int argc, VALUE *argv, VALUE obj)
1530{
1531 struct generator *ptr = generator_ptr(obj);
1532 VALUE args = rb_ary_new2(argc + 1);
1533
1534 rb_ary_push(args, yielder_new());
1535 if (argc > 0) {
1536 rb_ary_cat(args, argv, argc);
1537 }
1538
1539 return rb_proc_call_kw(ptr->proc, args, RB_PASS_CALLED_KEYWORDS);
1540}
1541
1542/* Lazy Enumerator methods */
1543static VALUE
1544enum_size(VALUE self)
1545{
1546 VALUE r = rb_check_funcall(self, id_size, 0, 0);
1547 return UNDEF_P(r) ? Qnil : r;
1548}
1549
1550static VALUE
1551lazyenum_size(VALUE self, VALUE args, VALUE eobj)
1552{
1553 return enum_size(self);
1554}
1555
1556#define lazy_receiver_size lazy_map_size
1557
1558static VALUE
1559lazy_init_iterator(RB_BLOCK_CALL_FUNC_ARGLIST(val, m))
1560{
1561 VALUE result;
1562 if (argc == 1) {
1563 VALUE args[2];
1564 args[0] = m;
1565 args[1] = val;
1566 result = rb_yield_values2(2, args);
1567 }
1568 else {
1569 VALUE args;
1570 int len = rb_long2int((long)argc + 1);
1571 VALUE *nargv = ALLOCV_N(VALUE, args, len);
1572
1573 nargv[0] = m;
1574 if (argc > 0) {
1575 MEMCPY(nargv + 1, argv, VALUE, argc);
1576 }
1577 result = rb_yield_values2(len, nargv);
1578 ALLOCV_END(args);
1579 }
1580 if (UNDEF_P(result)) rb_iter_break();
1581 return Qnil;
1582}
1583
1584static VALUE
1585lazy_init_block_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, m))
1586{
1587 rb_block_call(m, id_each, argc-1, argv+1, lazy_init_iterator, val);
1588 return Qnil;
1589}
1590
1591#define memo_value v2
1592#define memo_flags u3.state
1593#define LAZY_MEMO_BREAK 1
1594#define LAZY_MEMO_PACKED 2
1595#define LAZY_MEMO_BREAK_P(memo) ((memo)->memo_flags & LAZY_MEMO_BREAK)
1596#define LAZY_MEMO_PACKED_P(memo) ((memo)->memo_flags & LAZY_MEMO_PACKED)
1597#define LAZY_MEMO_SET_BREAK(memo) ((memo)->memo_flags |= LAZY_MEMO_BREAK)
1598#define LAZY_MEMO_RESET_BREAK(memo) ((memo)->memo_flags &= ~LAZY_MEMO_BREAK)
1599#define LAZY_MEMO_SET_VALUE(memo, value) MEMO_V2_SET(memo, value)
1600#define LAZY_MEMO_SET_PACKED(memo) ((memo)->memo_flags |= LAZY_MEMO_PACKED)
1601#define LAZY_MEMO_RESET_PACKED(memo) ((memo)->memo_flags &= ~LAZY_MEMO_PACKED)
1602
1603#define LAZY_NEED_BLOCK(func) \
1604 if (!rb_block_given_p()) { \
1605 rb_raise(rb_eArgError, "tried to call lazy " #func " without a block"); \
1606 }
1607
1608static VALUE lazy_yielder_result(struct MEMO *result, VALUE yielder, VALUE procs_array, VALUE memos, long i);
1609
1610static VALUE
1611lazy_init_yielder(RB_BLOCK_CALL_FUNC_ARGLIST(_, m))
1612{
1613 VALUE yielder = RARRAY_AREF(m, 0);
1614 VALUE procs_array = RARRAY_AREF(m, 1);
1615 VALUE memos = rb_attr_get(yielder, id_memo);
1616 struct MEMO *result;
1617
1618 result = MEMO_NEW(m, rb_enum_values_pack(argc, argv),
1619 argc > 1 ? LAZY_MEMO_PACKED : 0);
1620 return lazy_yielder_result(result, yielder, procs_array, memos, 0);
1621}
1622
1623static VALUE
1624lazy_yielder_yield(struct MEMO *result, long memo_index, int argc, const VALUE *argv)
1625{
1626 VALUE m = result->v1;
1627 VALUE yielder = RARRAY_AREF(m, 0);
1628 VALUE procs_array = RARRAY_AREF(m, 1);
1629 VALUE memos = rb_attr_get(yielder, id_memo);
1630 LAZY_MEMO_SET_VALUE(result, rb_enum_values_pack(argc, argv));
1631 if (argc > 1)
1632 LAZY_MEMO_SET_PACKED(result);
1633 else
1634 LAZY_MEMO_RESET_PACKED(result);
1635 return lazy_yielder_result(result, yielder, procs_array, memos, memo_index);
1636}
1637
1638static VALUE
1639lazy_yielder_result(struct MEMO *result, VALUE yielder, VALUE procs_array, VALUE memos, long i)
1640{
1641 int cont = 1;
1642
1643 for (; i < RARRAY_LEN(procs_array); i++) {
1644 VALUE proc = RARRAY_AREF(procs_array, i);
1645 struct proc_entry *entry = proc_entry_ptr(proc);
1646 if (!(*entry->fn->proc)(proc, result, memos, i)) {
1647 cont = 0;
1648 break;
1649 }
1650 }
1651
1652 if (cont) {
1653 rb_funcall2(yielder, idLTLT, 1, &(result->memo_value));
1654 }
1655 if (LAZY_MEMO_BREAK_P(result)) {
1656 rb_iter_break();
1657 }
1658 return result->memo_value;
1659}
1660
1661static VALUE
1662lazy_init_block(RB_BLOCK_CALL_FUNC_ARGLIST(val, m))
1663{
1664 VALUE procs = RARRAY_AREF(m, 1);
1665
1666 rb_ivar_set(val, id_memo, rb_ary_new2(RARRAY_LEN(procs)));
1667 rb_block_call(RARRAY_AREF(m, 0), id_each, 0, 0,
1668 lazy_init_yielder, rb_ary_new3(2, val, procs));
1669 return Qnil;
1670}
1671
1672static VALUE
1673lazy_generator_init(VALUE enumerator, VALUE procs)
1674{
1676 VALUE obj;
1677 struct generator *gen_ptr;
1678 struct enumerator *e = enumerator_ptr(enumerator);
1679
1680 if (RARRAY_LEN(procs) > 0) {
1681 struct generator *old_gen_ptr = generator_ptr(e->obj);
1682 obj = old_gen_ptr->obj;
1683 }
1684 else {
1685 obj = enumerator;
1686 }
1687
1688 generator = generator_allocate(rb_cGenerator);
1689
1690 rb_block_call(generator, id_initialize, 0, 0,
1691 lazy_init_block, rb_ary_new3(2, obj, procs));
1692
1693 gen_ptr = generator_ptr(generator);
1694 RB_OBJ_WRITE(generator, &gen_ptr->obj, obj);
1695
1696 return generator;
1697}
1698
1699static int
1700lazy_precheck(VALUE procs)
1701{
1702 if (RTEST(procs)) {
1703 long num_procs = RARRAY_LEN(procs), i = num_procs;
1704 while (i-- > 0) {
1705 VALUE proc = RARRAY_AREF(procs, i);
1706 struct proc_entry *entry = proc_entry_ptr(proc);
1707 lazyenum_precheck_func *precheck = entry->fn->precheck;
1708 if (precheck && !precheck(proc)) return FALSE;
1709 }
1710 }
1711
1712 return TRUE;
1713}
1714
1715/*
1716 * Document-class: Enumerator::Lazy
1717 *
1718 * Enumerator::Lazy is a special type of Enumerator, that allows constructing
1719 * chains of operations without evaluating them immediately, and evaluating
1720 * values on as-needed basis. In order to do so it redefines most of Enumerable
1721 * methods so that they just construct another lazy enumerator.
1722 *
1723 * Enumerator::Lazy can be constructed from any Enumerable with the
1724 * Enumerable#lazy method.
1725 *
1726 * lazy = (1..Float::INFINITY).lazy.select(&:odd?).drop(10).take_while { |i| i < 30 }
1727 * # => #<Enumerator::Lazy: #<Enumerator::Lazy: #<Enumerator::Lazy: #<Enumerator::Lazy: 1..Infinity>:select>:drop(10)>:take_while>
1728 *
1729 * The real enumeration is performed when any non-redefined Enumerable method
1730 * is called, like Enumerable#first or Enumerable#to_a (the latter is aliased
1731 * as #force for more semantic code):
1732 *
1733 * lazy.first(2)
1734 * #=> [21, 23]
1735 *
1736 * lazy.force
1737 * #=> [21, 23, 25, 27, 29]
1738 *
1739 * Note that most Enumerable methods that could be called with or without
1740 * a block, on Enumerator::Lazy will always require a block:
1741 *
1742 * [1, 2, 3].map #=> #<Enumerator: [1, 2, 3]:map>
1743 * [1, 2, 3].lazy.map # ArgumentError: tried to call lazy map without a block
1744 *
1745 * This class allows idiomatic calculations on long or infinite sequences, as well
1746 * as chaining of calculations without constructing intermediate arrays.
1747 *
1748 * Example for working with a slowly calculated sequence:
1749 *
1750 * require 'open-uri'
1751 *
1752 * # This will fetch all URLs before selecting
1753 * # necessary data
1754 * URLS.map { |u| JSON.parse(URI.open(u).read) }
1755 * .select { |data| data.key?('stats') }
1756 * .first(5)
1757 *
1758 * # This will fetch URLs one-by-one, only till
1759 * # there is enough data to satisfy the condition
1760 * URLS.lazy.map { |u| JSON.parse(URI.open(u).read) }
1761 * .select { |data| data.key?('stats') }
1762 * .first(5)
1763 *
1764 * Ending a chain with ".eager" generates a non-lazy enumerator, which
1765 * is suitable for returning or passing to another method that expects
1766 * a normal enumerator.
1767 *
1768 * def active_items
1769 * groups
1770 * .lazy
1771 * .flat_map(&:items)
1772 * .reject(&:disabled)
1773 * .eager
1774 * end
1775 *
1776 * # This works lazily; if a checked item is found, it stops
1777 * # iteration and does not look into remaining groups.
1778 * first_checked = active_items.find(&:checked)
1779 *
1780 * # This returns an array of items like a normal enumerator does.
1781 * all_checked = active_items.select(&:checked)
1782 *
1783 */
1784
1785/*
1786 * call-seq:
1787 * Lazy.new(obj, size=nil) { |yielder, *values| block }
1788 *
1789 * Creates a new Lazy enumerator. When the enumerator is actually enumerated
1790 * (e.g. by calling #force), +obj+ will be enumerated and each value passed
1791 * to the given block. The block can yield values back using +yielder+.
1792 * For example, to create a "filter+map" enumerator:
1793 *
1794 * def filter_map(sequence)
1795 * Lazy.new(sequence) do |yielder, *values|
1796 * result = yield *values
1797 * yielder << result if result
1798 * end
1799 * end
1800 *
1801 * filter_map(1..Float::INFINITY) {|i| i*i if i.even?}.first(5)
1802 * #=> [4, 16, 36, 64, 100]
1803 */
1804static VALUE
1805lazy_initialize(int argc, VALUE *argv, VALUE self)
1806{
1807 VALUE obj, size = Qnil;
1809
1810 rb_check_arity(argc, 1, 2);
1811 LAZY_NEED_BLOCK(new);
1812 obj = argv[0];
1813 if (argc > 1) {
1814 size = argv[1];
1815 }
1816 generator = generator_allocate(rb_cGenerator);
1817 rb_block_call(generator, id_initialize, 0, 0, lazy_init_block_i, obj);
1818 enumerator_init(self, generator, sym_each, 0, 0, 0, size, 0);
1819 rb_ivar_set(self, id_receiver, obj);
1820
1821 return self;
1822}
1823
1824#if 0 /* for RDoc */
1825/*
1826 * call-seq:
1827 * lazy.to_a -> array
1828 * lazy.force -> array
1829 *
1830 * Expands +lazy+ enumerator to an array.
1831 * See Enumerable#to_a.
1832 */
1833static VALUE
1834lazy_to_a(VALUE self)
1835{
1836}
1837#endif
1838
1839static void
1840lazy_set_args(VALUE lazy, VALUE args)
1841{
1842 ID id = rb_frame_this_func();
1843 rb_ivar_set(lazy, id_method, ID2SYM(id));
1844 if (NIL_P(args)) {
1845 /* Qfalse indicates that the arguments are empty */
1846 rb_ivar_set(lazy, id_arguments, Qfalse);
1847 }
1848 else {
1849 rb_ivar_set(lazy, id_arguments, args);
1850 }
1851}
1852
1853#if 0
1854static VALUE
1855lazy_set_method(VALUE lazy, VALUE args, rb_enumerator_size_func *size_fn)
1856{
1857 struct enumerator *e = enumerator_ptr(lazy);
1858 lazy_set_args(lazy, args);
1859 e->size_fn = size_fn;
1860 return lazy;
1861}
1862#endif
1863
1864static VALUE
1865lazy_add_method(VALUE obj, int argc, VALUE *argv, VALUE args, VALUE memo,
1866 const lazyenum_funcs *fn)
1867{
1868 struct enumerator *new_e;
1869 VALUE new_obj;
1870 VALUE new_generator;
1871 VALUE new_procs;
1872 struct enumerator *e = enumerator_ptr(obj);
1873 struct proc_entry *entry;
1874 VALUE entry_obj = TypedData_Make_Struct(rb_cObject, struct proc_entry,
1875 &proc_entry_data_type, entry);
1876 if (rb_block_given_p()) {
1877 RB_OBJ_WRITE(entry_obj, &entry->proc, rb_block_proc());
1878 }
1879 entry->fn = fn;
1880 RB_OBJ_WRITE(entry_obj, &entry->memo, args);
1881
1882 lazy_set_args(entry_obj, memo);
1883
1884 new_procs = RTEST(e->procs) ? rb_ary_dup(e->procs) : rb_ary_new();
1885 new_generator = lazy_generator_init(obj, new_procs);
1886 rb_ary_push(new_procs, entry_obj);
1887
1888 new_obj = enumerator_init_copy(enumerator_allocate(rb_cLazy), obj);
1889 new_e = RTYPEDDATA_GET_DATA(new_obj);
1890 RB_OBJ_WRITE(new_obj, &new_e->obj, new_generator);
1891 RB_OBJ_WRITE(new_obj, &new_e->procs, new_procs);
1892
1893 if (argc > 0) {
1894 new_e->meth = rb_to_id(*argv++);
1895 --argc;
1896 }
1897 else {
1898 new_e->meth = id_each;
1899 }
1900
1901 RB_OBJ_WRITE(new_obj, &new_e->args, rb_ary_new4(argc, argv));
1902
1903 return new_obj;
1904}
1905
1906/*
1907 * call-seq:
1908 * e.lazy -> lazy_enumerator
1909 *
1910 * Returns an Enumerator::Lazy, which redefines most Enumerable
1911 * methods to postpone enumeration and enumerate values only on an
1912 * as-needed basis.
1913 *
1914 * === Example
1915 *
1916 * The following program finds pythagorean triples:
1917 *
1918 * def pythagorean_triples
1919 * (1..Float::INFINITY).lazy.flat_map {|z|
1920 * (1..z).flat_map {|x|
1921 * (x..z).select {|y|
1922 * x**2 + y**2 == z**2
1923 * }.map {|y|
1924 * [x, y, z]
1925 * }
1926 * }
1927 * }
1928 * end
1929 * # show first ten pythagorean triples
1930 * p pythagorean_triples.take(10).force # take is lazy, so force is needed
1931 * p pythagorean_triples.first(10) # first is eager
1932 * # show pythagorean triples less than 100
1933 * p pythagorean_triples.take_while { |*, z| z < 100 }.force
1934 */
1935static VALUE
1936enumerable_lazy(VALUE obj)
1937{
1938 VALUE result = lazy_to_enum_i(obj, sym_each, 0, 0, lazyenum_size, rb_keyword_given_p());
1939 /* Qfalse indicates that the Enumerator::Lazy has no method name */
1940 rb_ivar_set(result, id_method, Qfalse);
1941 return result;
1942}
1943
1944static VALUE
1945lazy_to_enum_i(VALUE obj, VALUE meth, int argc, const VALUE *argv, rb_enumerator_size_func *size_fn, int kw_splat)
1946{
1947 return enumerator_init(enumerator_allocate(rb_cLazy),
1948 obj, meth, argc, argv, size_fn, Qnil, kw_splat);
1949}
1950
1951/*
1952 * call-seq:
1953 * lzy.to_enum(method = :each, *args) -> lazy_enum
1954 * lzy.enum_for(method = :each, *args) -> lazy_enum
1955 * lzy.to_enum(method = :each, *args) {|*args| block } -> lazy_enum
1956 * lzy.enum_for(method = :each, *args) {|*args| block } -> lazy_enum
1957 *
1958 * Similar to Object#to_enum, except it returns a lazy enumerator.
1959 * This makes it easy to define Enumerable methods that will
1960 * naturally remain lazy if called from a lazy enumerator.
1961 *
1962 * For example, continuing from the example in Object#to_enum:
1963 *
1964 * # See Object#to_enum for the definition of repeat
1965 * r = 1..Float::INFINITY
1966 * r.repeat(2).first(5) # => [1, 1, 2, 2, 3]
1967 * r.repeat(2).class # => Enumerator
1968 * r.repeat(2).map{|n| n ** 2}.first(5) # => endless loop!
1969 * # works naturally on lazy enumerator:
1970 * r.lazy.repeat(2).class # => Enumerator::Lazy
1971 * r.lazy.repeat(2).map{|n| n ** 2}.first(5) # => [1, 1, 4, 4, 9]
1972 */
1973
1974static VALUE
1975lazy_to_enum(int argc, VALUE *argv, VALUE self)
1976{
1977 VALUE lazy, meth = sym_each, super_meth;
1978
1979 if (argc > 0) {
1980 --argc;
1981 meth = rb_to_symbol(*argv++);
1982 }
1983 if (RTEST((super_meth = rb_hash_aref(lazy_use_super_method, meth)))) {
1984 meth = super_meth;
1985 }
1986 lazy = lazy_to_enum_i(self, meth, argc, argv, 0, rb_keyword_given_p());
1987 if (rb_block_given_p()) {
1988 RB_OBJ_WRITE(lazy, &enumerator_ptr(lazy)->size, rb_block_proc());
1989 }
1990 return lazy;
1991}
1992
1993static VALUE
1994lazy_eager_size(VALUE self, VALUE args, VALUE eobj)
1995{
1996 return enum_size(self);
1997}
1998
1999/*
2000 * call-seq:
2001 * lzy.eager -> enum
2002 *
2003 * Returns a non-lazy Enumerator converted from the lazy enumerator.
2004 */
2005
2006static VALUE
2007lazy_eager(VALUE self)
2008{
2009 return enumerator_init(enumerator_allocate(rb_cEnumerator),
2010 self, sym_each, 0, 0, lazy_eager_size, Qnil, 0);
2011}
2012
2013static VALUE
2014lazyenum_yield(VALUE proc_entry, struct MEMO *result)
2015{
2016 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2017 return rb_proc_call_with_block(entry->proc, 1, &result->memo_value, Qnil);
2018}
2019
2020static VALUE
2021lazyenum_yield_values(VALUE proc_entry, struct MEMO *result)
2022{
2023 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2024 int argc = 1;
2025 const VALUE *argv = &result->memo_value;
2026 if (LAZY_MEMO_PACKED_P(result)) {
2027 const VALUE args = *argv;
2028 argc = RARRAY_LENINT(args);
2029 argv = RARRAY_CONST_PTR(args);
2030 }
2031 return rb_proc_call_with_block(entry->proc, argc, argv, Qnil);
2032}
2033
2034static struct MEMO *
2035lazy_map_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2036{
2037 VALUE value = lazyenum_yield_values(proc_entry, result);
2038 LAZY_MEMO_SET_VALUE(result, value);
2039 LAZY_MEMO_RESET_PACKED(result);
2040 return result;
2041}
2042
2043static VALUE
2044lazy_map_size(VALUE entry, VALUE receiver)
2045{
2046 return receiver;
2047}
2048
2049static const lazyenum_funcs lazy_map_funcs = {
2050 lazy_map_proc, lazy_map_size,
2051};
2052
2053/*
2054 * call-seq:
2055 * lazy.collect { |obj| block } -> lazy_enumerator
2056 * lazy.map { |obj| block } -> lazy_enumerator
2057 *
2058 * Like Enumerable#map, but chains operation to be lazy-evaluated.
2059 *
2060 * (1..Float::INFINITY).lazy.map {|i| i**2 }
2061 * #=> #<Enumerator::Lazy: #<Enumerator::Lazy: 1..Infinity>:map>
2062 * (1..Float::INFINITY).lazy.map {|i| i**2 }.first(3)
2063 * #=> [1, 4, 9]
2064 */
2065
2066static VALUE
2067lazy_map(VALUE obj)
2068{
2069 LAZY_NEED_BLOCK(map);
2070 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_map_funcs);
2071}
2072
2073static VALUE
2074lazy_flat_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, y))
2075{
2076 struct MEMO *arg = MEMO_CAST(y);
2077
2078 return lazy_yielder_yield(MEMO_CAST(arg->v1), arg->u3.cnt, argc, argv);
2079}
2080
2081static struct MEMO *
2082lazy_flat_map_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2083{
2084 VALUE value = lazyenum_yield_values(proc_entry, result);
2085 VALUE ary = 0;
2086 const long proc_index = memo_index + 1;
2087 int break_p = LAZY_MEMO_BREAK_P(result);
2088
2089 if (RB_TYPE_P(value, T_ARRAY)) {
2090 ary = value;
2091 }
2092 else if (rb_respond_to(value, id_force) && rb_respond_to(value, id_each)) {
2093 VALUE arg = (VALUE)MEMO_NEW((VALUE)result, Qnil, proc_index);
2094 LAZY_MEMO_RESET_BREAK(result);
2095 rb_block_call(value, id_each, 0, 0, lazy_flat_map_i, arg);
2096 if (break_p) LAZY_MEMO_SET_BREAK(result);
2097 RB_GC_GUARD(arg);
2098 return 0;
2099 }
2100
2101 if (ary || !NIL_P(ary = rb_check_array_type(value))) {
2102 long i;
2103 LAZY_MEMO_RESET_BREAK(result);
2104 for (i = 0; i + 1 < RARRAY_LEN(ary); i++) {
2105 const VALUE argv = RARRAY_AREF(ary, i);
2106 lazy_yielder_yield(result, proc_index, 1, &argv);
2107 }
2108 if (break_p) LAZY_MEMO_SET_BREAK(result);
2109 if (i >= RARRAY_LEN(ary)) return 0;
2110 value = RARRAY_AREF(ary, i);
2111 }
2112 LAZY_MEMO_SET_VALUE(result, value);
2113 LAZY_MEMO_RESET_PACKED(result);
2114 return result;
2115}
2116
2117static const lazyenum_funcs lazy_flat_map_funcs = {
2118 lazy_flat_map_proc, 0,
2119};
2120
2121/*
2122 * call-seq:
2123 * lazy.collect_concat { |obj| block } -> a_lazy_enumerator
2124 * lazy.flat_map { |obj| block } -> a_lazy_enumerator
2125 *
2126 * Returns a new lazy enumerator with the concatenated results of running
2127 * +block+ once for every element in the lazy enumerator.
2128 *
2129 * ["foo", "bar"].lazy.flat_map {|i| i.each_char.lazy}.force
2130 * #=> ["f", "o", "o", "b", "a", "r"]
2131 *
2132 * A value +x+ returned by +block+ is decomposed if either of
2133 * the following conditions is true:
2134 *
2135 * * +x+ responds to both each and force, which means that
2136 * +x+ is a lazy enumerator.
2137 * * +x+ is an array or responds to to_ary.
2138 *
2139 * Otherwise, +x+ is contained as-is in the return value.
2140 *
2141 * [{a:1}, {b:2}].lazy.flat_map {|i| i}.force
2142 * #=> [{:a=>1}, {:b=>2}]
2143 */
2144static VALUE
2145lazy_flat_map(VALUE obj)
2146{
2147 LAZY_NEED_BLOCK(flat_map);
2148 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_flat_map_funcs);
2149}
2150
2151static struct MEMO *
2152lazy_select_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2153{
2154 VALUE chain = lazyenum_yield(proc_entry, result);
2155 if (!RTEST(chain)) return 0;
2156 return result;
2157}
2158
2159static const lazyenum_funcs lazy_select_funcs = {
2160 lazy_select_proc, 0,
2161};
2162
2163/*
2164 * call-seq:
2165 * lazy.find_all { |obj| block } -> lazy_enumerator
2166 * lazy.select { |obj| block } -> lazy_enumerator
2167 * lazy.filter { |obj| block } -> lazy_enumerator
2168 *
2169 * Like Enumerable#select, but chains operation to be lazy-evaluated.
2170 */
2171static VALUE
2172lazy_select(VALUE obj)
2173{
2174 LAZY_NEED_BLOCK(select);
2175 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_select_funcs);
2176}
2177
2178static struct MEMO *
2179lazy_filter_map_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2180{
2181 VALUE value = lazyenum_yield_values(proc_entry, result);
2182 if (!RTEST(value)) return 0;
2183 LAZY_MEMO_SET_VALUE(result, value);
2184 LAZY_MEMO_RESET_PACKED(result);
2185 return result;
2186}
2187
2188static const lazyenum_funcs lazy_filter_map_funcs = {
2189 lazy_filter_map_proc, 0,
2190};
2191
2192/*
2193 * call-seq:
2194 * lazy.filter_map { |obj| block } -> lazy_enumerator
2195 *
2196 * Like Enumerable#filter_map, but chains operation to be lazy-evaluated.
2197 *
2198 * (1..).lazy.filter_map { |i| i * 2 if i.even? }.first(5)
2199 * #=> [4, 8, 12, 16, 20]
2200 */
2201
2202static VALUE
2203lazy_filter_map(VALUE obj)
2204{
2205 LAZY_NEED_BLOCK(filter_map);
2206 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_filter_map_funcs);
2207}
2208
2209static struct MEMO *
2210lazy_reject_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2211{
2212 VALUE chain = lazyenum_yield(proc_entry, result);
2213 if (RTEST(chain)) return 0;
2214 return result;
2215}
2216
2217static const lazyenum_funcs lazy_reject_funcs = {
2218 lazy_reject_proc, 0,
2219};
2220
2221/*
2222 * call-seq:
2223 * lazy.reject { |obj| block } -> lazy_enumerator
2224 *
2225 * Like Enumerable#reject, but chains operation to be lazy-evaluated.
2226 */
2227
2228static VALUE
2229lazy_reject(VALUE obj)
2230{
2231 LAZY_NEED_BLOCK(reject);
2232 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_reject_funcs);
2233}
2234
2235static struct MEMO *
2236lazy_grep_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2237{
2238 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2239 VALUE chain = rb_funcall(entry->memo, id_eqq, 1, result->memo_value);
2240 if (!RTEST(chain)) return 0;
2241 return result;
2242}
2243
2244static struct MEMO *
2245lazy_grep_iter_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2246{
2247 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2248 VALUE value, chain = rb_funcall(entry->memo, id_eqq, 1, result->memo_value);
2249
2250 if (!RTEST(chain)) return 0;
2251 value = rb_proc_call_with_block(entry->proc, 1, &(result->memo_value), Qnil);
2252 /* entry is embedded in proc_entry, which only the procs array references */
2254 LAZY_MEMO_SET_VALUE(result, value);
2255 LAZY_MEMO_RESET_PACKED(result);
2256
2257 return result;
2258}
2259
2260static const lazyenum_funcs lazy_grep_iter_funcs = {
2261 lazy_grep_iter_proc, 0,
2262};
2263
2264static const lazyenum_funcs lazy_grep_funcs = {
2265 lazy_grep_proc, 0,
2266};
2267
2268/*
2269 * call-seq:
2270 * lazy.grep(pattern) -> lazy_enumerator
2271 * lazy.grep(pattern) { |obj| block } -> lazy_enumerator
2272 *
2273 * Like Enumerable#grep, but chains operation to be lazy-evaluated.
2274 */
2275
2276static VALUE
2277lazy_grep(VALUE obj, VALUE pattern)
2278{
2279 const lazyenum_funcs *const funcs = rb_block_given_p() ?
2280 &lazy_grep_iter_funcs : &lazy_grep_funcs;
2281 return lazy_add_method(obj, 0, 0, pattern, rb_ary_new3(1, pattern), funcs);
2282}
2283
2284static struct MEMO *
2285lazy_grep_v_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2286{
2287 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2288 VALUE chain = rb_funcall(entry->memo, id_eqq, 1, result->memo_value);
2289 if (RTEST(chain)) return 0;
2290 return result;
2291}
2292
2293static struct MEMO *
2294lazy_grep_v_iter_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2295{
2296 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2297 VALUE value, chain = rb_funcall(entry->memo, id_eqq, 1, result->memo_value);
2298
2299 if (RTEST(chain)) return 0;
2300 value = rb_proc_call_with_block(entry->proc, 1, &(result->memo_value), Qnil);
2302 LAZY_MEMO_SET_VALUE(result, value);
2303 LAZY_MEMO_RESET_PACKED(result);
2304
2305 return result;
2306}
2307
2308static const lazyenum_funcs lazy_grep_v_iter_funcs = {
2309 lazy_grep_v_iter_proc, 0,
2310};
2311
2312static const lazyenum_funcs lazy_grep_v_funcs = {
2313 lazy_grep_v_proc, 0,
2314};
2315
2316/*
2317 * call-seq:
2318 * lazy.grep_v(pattern) -> lazy_enumerator
2319 * lazy.grep_v(pattern) { |obj| block } -> lazy_enumerator
2320 *
2321 * Like Enumerable#grep_v, but chains operation to be lazy-evaluated.
2322 */
2323
2324static VALUE
2325lazy_grep_v(VALUE obj, VALUE pattern)
2326{
2327 const lazyenum_funcs *const funcs = rb_block_given_p() ?
2328 &lazy_grep_v_iter_funcs : &lazy_grep_v_funcs;
2329 return lazy_add_method(obj, 0, 0, pattern, rb_ary_new3(1, pattern), funcs);
2330}
2331
2332static VALUE
2333call_next(VALUE obj)
2334{
2335 return rb_funcall(obj, id_next, 0);
2336}
2337
2338static VALUE
2339next_stopped(VALUE obj, VALUE _)
2340{
2341 return Qnil;
2342}
2343
2344static struct MEMO *
2345lazy_zip_arrays_func(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2346{
2347 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2348 VALUE ary, arrays = entry->memo;
2349 VALUE memo = rb_ary_entry(memos, memo_index);
2350 long i, count = NIL_P(memo) ? 0 : NUM2LONG(memo);
2351
2352 ary = rb_ary_new2(RARRAY_LEN(arrays) + 1);
2353 rb_ary_push(ary, result->memo_value);
2354 for (i = 0; i < RARRAY_LEN(arrays); i++) {
2355 rb_ary_push(ary, rb_ary_entry(RARRAY_AREF(arrays, i), count));
2356 }
2357 LAZY_MEMO_SET_VALUE(result, ary);
2358 rb_ary_store(memos, memo_index, LONG2NUM(++count));
2359 return result;
2360}
2361
2362static struct MEMO *
2363lazy_zip_func(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2364{
2365 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2366 VALUE arg = rb_ary_entry(memos, memo_index);
2367 VALUE zip_args = entry->memo;
2368 VALUE ary, v;
2369 long i;
2370
2371 if (NIL_P(arg)) {
2372 arg = rb_ary_new2(RARRAY_LEN(zip_args));
2373 for (i = 0; i < RARRAY_LEN(zip_args); i++) {
2374 rb_ary_push(arg, rb_funcall(RARRAY_AREF(zip_args, i), id_to_enum, 0));
2375 }
2376 rb_ary_store(memos, memo_index, arg);
2377 }
2378
2379 ary = rb_ary_new2(RARRAY_LEN(arg) + 1);
2380 rb_ary_push(ary, result->memo_value);
2381 for (i = 0; i < RARRAY_LEN(arg); i++) {
2382 v = rb_rescue2(call_next, RARRAY_AREF(arg, i), next_stopped, 0,
2384 rb_ary_push(ary, v);
2385 }
2386 LAZY_MEMO_SET_VALUE(result, ary);
2387 return result;
2388}
2389
2390static const lazyenum_funcs lazy_zip_funcs[] = {
2391 {lazy_zip_func, lazy_receiver_size,},
2392 {lazy_zip_arrays_func, lazy_receiver_size,},
2393};
2394
2395/*
2396 * call-seq:
2397 * lazy.zip(arg, ...) -> lazy_enumerator
2398 * lazy.zip(arg, ...) { |arr| block } -> nil
2399 *
2400 * Like Enumerable#zip, but chains operation to be lazy-evaluated.
2401 * However, if a block is given to zip, values are enumerated immediately.
2402 */
2403static VALUE
2404lazy_zip(int argc, VALUE *argv, VALUE obj)
2405{
2406 VALUE ary, v;
2407 long i;
2408 const lazyenum_funcs *funcs = &lazy_zip_funcs[1];
2409
2410 if (rb_block_given_p()) {
2411 return rb_call_super(argc, argv);
2412 }
2413
2414 ary = rb_ary_new2(argc);
2415 for (i = 0; i < argc; i++) {
2416 v = rb_check_array_type(argv[i]);
2417 if (NIL_P(v)) {
2418 for (; i < argc; i++) {
2419 if (!rb_respond_to(argv[i], id_each)) {
2420 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (must respond to :each)",
2421 rb_obj_class(argv[i]));
2422 }
2423 }
2424 ary = rb_ary_new4(argc, argv);
2425 funcs = &lazy_zip_funcs[0];
2426 break;
2427 }
2428 rb_ary_push(ary, v);
2429 }
2430
2431 return lazy_add_method(obj, 0, 0, ary, ary, funcs);
2432}
2433
2434static struct MEMO *
2435lazy_take_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2436{
2437 long remain;
2438 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2439 VALUE memo = rb_ary_entry(memos, memo_index);
2440
2441 if (NIL_P(memo)) {
2442 memo = entry->memo;
2443 }
2444
2445 remain = NUM2LONG(memo);
2446 if (--remain == 0) LAZY_MEMO_SET_BREAK(result);
2447 rb_ary_store(memos, memo_index, LONG2NUM(remain));
2448 return result;
2449}
2450
2451static VALUE
2452lazy_take_size(VALUE entry, VALUE receiver)
2453{
2454 long len = NUM2LONG(RARRAY_AREF(rb_ivar_get(entry, id_arguments), 0));
2455 if (NIL_P(receiver) || (FIXNUM_P(receiver) && FIX2LONG(receiver) < len))
2456 return receiver;
2457 return LONG2NUM(len);
2458}
2459
2460static int
2461lazy_take_precheck(VALUE proc_entry)
2462{
2463 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2464 return entry->memo != INT2FIX(0);
2465}
2466
2467static const lazyenum_funcs lazy_take_funcs = {
2468 lazy_take_proc, lazy_take_size, lazy_take_precheck,
2469};
2470
2471/*
2472 * call-seq:
2473 * lazy.take(n) -> lazy_enumerator
2474 *
2475 * Like Enumerable#take, but chains operation to be lazy-evaluated.
2476 */
2477
2478static VALUE
2479lazy_take(VALUE obj, VALUE n)
2480{
2481 long len = NUM2LONG(n);
2482
2483 if (len < 0) {
2484 rb_raise(rb_eArgError, "attempt to take negative size");
2485 }
2486
2487 n = LONG2NUM(len); /* no more conversion */
2488
2489 return lazy_add_method(obj, 0, 0, n, rb_ary_new3(1, n), &lazy_take_funcs);
2490}
2491
2492static struct MEMO *
2493lazy_take_while_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2494{
2495 VALUE take = lazyenum_yield_values(proc_entry, result);
2496 if (!RTEST(take)) {
2497 LAZY_MEMO_SET_BREAK(result);
2498 return 0;
2499 }
2500 return result;
2501}
2502
2503static const lazyenum_funcs lazy_take_while_funcs = {
2504 lazy_take_while_proc, 0,
2505};
2506
2507/*
2508 * call-seq:
2509 * lazy.take_while { |obj| block } -> lazy_enumerator
2510 *
2511 * Like Enumerable#take_while, but chains operation to be lazy-evaluated.
2512 */
2513
2514static VALUE
2515lazy_take_while(VALUE obj)
2516{
2517 LAZY_NEED_BLOCK(take_while);
2518 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_take_while_funcs);
2519}
2520
2521static VALUE
2522lazy_drop_size(VALUE proc_entry, VALUE receiver)
2523{
2524 long len = NUM2LONG(RARRAY_AREF(rb_ivar_get(proc_entry, id_arguments), 0));
2525 if (NIL_P(receiver))
2526 return receiver;
2527 if (FIXNUM_P(receiver)) {
2528 len = FIX2LONG(receiver) - len;
2529 return LONG2FIX(len < 0 ? 0 : len);
2530 }
2531 return rb_funcall(receiver, '-', 1, LONG2NUM(len));
2532}
2533
2534static struct MEMO *
2535lazy_drop_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2536{
2537 long remain;
2538 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2539 VALUE memo = rb_ary_entry(memos, memo_index);
2540
2541 if (NIL_P(memo)) {
2542 memo = entry->memo;
2543 }
2544 remain = NUM2LONG(memo);
2545 if (remain > 0) {
2546 --remain;
2547 rb_ary_store(memos, memo_index, LONG2NUM(remain));
2548 return 0;
2549 }
2550
2551 return result;
2552}
2553
2554static const lazyenum_funcs lazy_drop_funcs = {
2555 lazy_drop_proc, lazy_drop_size,
2556};
2557
2558/*
2559 * call-seq:
2560 * lazy.drop(n) -> lazy_enumerator
2561 *
2562 * Like Enumerable#drop, but chains operation to be lazy-evaluated.
2563 */
2564
2565static VALUE
2566lazy_drop(VALUE obj, VALUE n)
2567{
2568 long len = NUM2LONG(n);
2569 VALUE argv[2];
2570 argv[0] = sym_each;
2571 argv[1] = n;
2572
2573 if (len < 0) {
2574 rb_raise(rb_eArgError, "attempt to drop negative size");
2575 }
2576
2577 return lazy_add_method(obj, 2, argv, n, rb_ary_new3(1, n), &lazy_drop_funcs);
2578}
2579
2580static struct MEMO *
2581lazy_drop_while_proc(VALUE proc_entry, struct MEMO* result, VALUE memos, long memo_index)
2582{
2583 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2584 VALUE memo = rb_ary_entry(memos, memo_index);
2585
2586 if (NIL_P(memo)) {
2587 memo = entry->memo;
2588 }
2589
2590 if (!RTEST(memo)) {
2591 VALUE drop = lazyenum_yield_values(proc_entry, result);
2592 if (RTEST(drop)) return 0;
2593 rb_ary_store(memos, memo_index, Qtrue);
2594 }
2595 return result;
2596}
2597
2598static const lazyenum_funcs lazy_drop_while_funcs = {
2599 lazy_drop_while_proc, 0,
2600};
2601
2602/*
2603 * call-seq:
2604 * lazy.drop_while { |obj| block } -> lazy_enumerator
2605 *
2606 * Like Enumerable#drop_while, but chains operation to be lazy-evaluated.
2607 */
2608
2609static VALUE
2610lazy_drop_while(VALUE obj)
2611{
2612 LAZY_NEED_BLOCK(drop_while);
2613 return lazy_add_method(obj, 0, 0, Qfalse, Qnil, &lazy_drop_while_funcs);
2614}
2615
2616static int
2617lazy_uniq_check(VALUE chain, VALUE memos, long memo_index)
2618{
2619 VALUE hash = rb_ary_entry(memos, memo_index);
2620
2621 if (NIL_P(hash)) {
2622 hash = rb_obj_hide(rb_hash_new());
2623 rb_ary_store(memos, memo_index, hash);
2624 }
2625
2626 return rb_hash_add_new_element(hash, chain, Qfalse);
2627}
2628
2629static struct MEMO *
2630lazy_uniq_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2631{
2632 if (lazy_uniq_check(result->memo_value, memos, memo_index)) return 0;
2633 return result;
2634}
2635
2636static struct MEMO *
2637lazy_uniq_iter_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2638{
2639 VALUE chain = lazyenum_yield(proc_entry, result);
2640
2641 if (lazy_uniq_check(chain, memos, memo_index)) return 0;
2642 return result;
2643}
2644
2645static const lazyenum_funcs lazy_uniq_iter_funcs = {
2646 lazy_uniq_iter_proc, 0,
2647};
2648
2649static const lazyenum_funcs lazy_uniq_funcs = {
2650 lazy_uniq_proc, 0,
2651};
2652
2653/*
2654 * call-seq:
2655 * lazy.uniq -> lazy_enumerator
2656 * lazy.uniq { |item| block } -> lazy_enumerator
2657 *
2658 * Like Enumerable#uniq, but chains operation to be lazy-evaluated.
2659 */
2660
2661static VALUE
2662lazy_uniq(VALUE obj)
2663{
2664 const lazyenum_funcs *const funcs =
2665 rb_block_given_p() ? &lazy_uniq_iter_funcs : &lazy_uniq_funcs;
2666 return lazy_add_method(obj, 0, 0, Qnil, Qnil, funcs);
2667}
2668
2669static struct MEMO *
2670lazy_compact_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2671{
2672 if (NIL_P(result->memo_value)) return 0;
2673 return result;
2674}
2675
2676static const lazyenum_funcs lazy_compact_funcs = {
2677 lazy_compact_proc, 0,
2678};
2679
2680/*
2681 * call-seq:
2682 * lazy.compact -> lazy_enumerator
2683 *
2684 * Like Enumerable#compact, but chains operation to be lazy-evaluated.
2685 */
2686
2687static VALUE
2688lazy_compact(VALUE obj)
2689{
2690 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_compact_funcs);
2691}
2692
2693static struct MEMO *
2694lazy_with_index_proc(VALUE proc_entry, struct MEMO* result, VALUE memos, long memo_index)
2695{
2696 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2697 VALUE memo = rb_ary_entry(memos, memo_index);
2698 VALUE argv[2];
2699
2700 if (NIL_P(memo)) {
2701 memo = entry->memo;
2702 }
2703
2704 argv[0] = result->memo_value;
2705 argv[1] = memo;
2706 if (entry->proc) {
2707 rb_proc_call_with_block(entry->proc, 2, argv, Qnil);
2708 LAZY_MEMO_RESET_PACKED(result);
2709 }
2710 else {
2711 LAZY_MEMO_SET_VALUE(result, rb_ary_new_from_values(2, argv));
2712 LAZY_MEMO_SET_PACKED(result);
2713 }
2714 rb_ary_store(memos, memo_index, LONG2NUM(NUM2LONG(memo) + 1));
2715 return result;
2716}
2717
2718static VALUE
2719lazy_with_index_size(VALUE proc, VALUE receiver)
2720{
2721 return receiver;
2722}
2723
2724static const lazyenum_funcs lazy_with_index_funcs = {
2725 lazy_with_index_proc, lazy_with_index_size,
2726};
2727
2728static VALUE
2729lazy_with_index_from(VALUE obj, VALUE memo)
2730{
2731 return lazy_add_method(obj, 0, 0, memo, rb_ary_new_from_values(1, &memo),
2732 &lazy_with_index_funcs);
2733}
2734
2735/*
2736 * call-seq:
2737 * lazy.each_with_index {|(*args), idx| block }
2738 * lazy.each_with_index
2739 *
2740 * Equals to <tt>with_index(0)</tt>.
2741 *
2742 * See Enumerator#with_index.
2743 */
2744static VALUE
2745lazy_each_with_index(VALUE obj)
2746{
2747 if (rb_block_given_p()) {
2748 return rb_call_super(0, 0);
2749 }
2750 return lazy_with_index_from(obj, LONG2NUM(0));
2751}
2752
2753/*
2754 * call-seq:
2755 * lazy.with_index(offset = 0) {|(*args), idx| block }
2756 * lazy.with_index(offset = 0)
2757 *
2758 * If a block is given, returns a lazy enumerator that will
2759 * iterate over the given block for each element
2760 * with an index, which starts from +offset+, and returns a
2761 * lazy enumerator that yields the same values (without the index).
2762 *
2763 * If a block is not given, returns a new lazy enumerator that
2764 * includes the index, starting from +offset+.
2765 *
2766 * +offset+:: the starting index to use
2767 *
2768 * See Enumerator#with_index.
2769 */
2770static VALUE
2771lazy_with_index(int argc, VALUE *argv, VALUE obj)
2772{
2773 VALUE memo;
2774
2775 rb_scan_args(argc, argv, "01", &memo);
2776 if (NIL_P(memo))
2777 memo = LONG2NUM(0);
2778
2779 return lazy_with_index_from(obj, memo);
2780}
2781
2782#if 0 /* for RDoc */
2783
2784/*
2785 * call-seq:
2786 * lazy.chunk { |elt| ... } -> lazy_enumerator
2787 *
2788 * Like Enumerable#chunk, but chains operation to be lazy-evaluated.
2789 */
2790static VALUE
2791lazy_chunk(VALUE self)
2792{
2793}
2794
2795/*
2796 * call-seq:
2797 * lazy.chunk_while {|elt_before, elt_after| bool } -> lazy_enumerator
2798 *
2799 * Like Enumerable#chunk_while, but chains operation to be lazy-evaluated.
2800 */
2801static VALUE
2802lazy_chunk_while(VALUE self)
2803{
2804}
2805
2806/*
2807 * call-seq:
2808 * lazy.slice_after(pattern) -> lazy_enumerator
2809 * lazy.slice_after { |elt| bool } -> lazy_enumerator
2810 *
2811 * Like Enumerable#slice_after, but chains operation to be lazy-evaluated.
2812 */
2813static VALUE
2814lazy_slice_after(VALUE self)
2815{
2816}
2817
2818/*
2819 * call-seq:
2820 * lazy.slice_before(pattern) -> lazy_enumerator
2821 * lazy.slice_before { |elt| bool } -> lazy_enumerator
2822 *
2823 * Like Enumerable#slice_before, but chains operation to be lazy-evaluated.
2824 */
2825static VALUE
2826lazy_slice_before(VALUE self)
2827{
2828}
2829
2830/*
2831 * call-seq:
2832 * lazy.slice_when {|elt_before, elt_after| bool } -> lazy_enumerator
2833 *
2834 * Like Enumerable#slice_when, but chains operation to be lazy-evaluated.
2835 */
2836static VALUE
2837lazy_slice_when(VALUE self)
2838{
2839}
2840# endif
2841
2842static VALUE
2843lazy_super(int argc, VALUE *argv, VALUE lazy)
2844{
2845 return enumerable_lazy(rb_call_super(argc, argv));
2846}
2847
2848/*
2849 * call-seq:
2850 * enum.lazy -> lazy_enumerator
2851 *
2852 * Returns self.
2853 */
2854
2855static VALUE
2856lazy_lazy(VALUE obj)
2857{
2858 return obj;
2859}
2860
2861/*
2862 * Document-class: StopIteration
2863 *
2864 * Raised to stop the iteration, in particular by Enumerator#next. It is
2865 * rescued by Kernel#loop.
2866 *
2867 * loop do
2868 * puts "Hello"
2869 * raise StopIteration
2870 * puts "World"
2871 * end
2872 * puts "Done!"
2873 *
2874 * <em>produces:</em>
2875 *
2876 * Hello
2877 * Done!
2878 */
2879
2880/*
2881 * call-seq:
2882 * result -> value
2883 *
2884 * Returns the return value of the iterator.
2885 *
2886 * o = Object.new
2887 * def o.each
2888 * yield 1
2889 * yield 2
2890 * yield 3
2891 * 100
2892 * end
2893 *
2894 * e = o.to_enum
2895 *
2896 * puts e.next #=> 1
2897 * puts e.next #=> 2
2898 * puts e.next #=> 3
2899 *
2900 * begin
2901 * e.next
2902 * rescue StopIteration => ex
2903 * puts ex.result #=> 100
2904 * end
2905 *
2906 */
2907
2908static VALUE
2909stop_result(VALUE self)
2910{
2911 return rb_attr_get(self, id_result);
2912}
2913
2914/*
2915 * Producer
2916 */
2917
2918static void
2919producer_mark_and_move(void *p)
2920{
2921 struct producer *ptr = p;
2922 rb_gc_mark_and_move(&ptr->init);
2923 rb_gc_mark_and_move(&ptr->proc);
2924 rb_gc_mark_and_move(&ptr->size);
2925}
2926
2927#define producer_free RUBY_TYPED_DEFAULT_FREE
2928
2929static size_t
2930producer_memsize(const void *p)
2931{
2932 return sizeof(struct producer);
2933}
2934
2935static const rb_data_type_t producer_data_type = {
2936 "producer",
2937 {
2938 producer_mark_and_move,
2939 producer_free,
2940 producer_memsize,
2941 producer_mark_and_move,
2942 },
2943 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
2944};
2945
2946static struct producer *
2947producer_ptr(VALUE obj)
2948{
2949 struct producer *ptr;
2950
2951 TypedData_Get_Struct(obj, struct producer, &producer_data_type, ptr);
2952 if (!ptr || UNDEF_P(ptr->proc)) {
2953 rb_raise(rb_eArgError, "uninitialized producer");
2954 }
2955 return ptr;
2956}
2957
2958/* :nodoc: */
2959static VALUE
2960producer_allocate(VALUE klass)
2961{
2962 struct producer *ptr;
2963 VALUE obj;
2964
2965 obj = TypedData_Make_Struct(klass, struct producer, &producer_data_type, ptr);
2966 ptr->init = Qundef;
2967 ptr->proc = Qundef;
2968 ptr->size = Qnil;
2969
2970 return obj;
2971}
2972
2973static VALUE
2974producer_init(VALUE obj, VALUE init, VALUE proc, VALUE size)
2975{
2976 struct producer *ptr;
2977
2978 TypedData_Get_Struct(obj, struct producer, &producer_data_type, ptr);
2979
2980 if (!ptr) {
2981 rb_raise(rb_eArgError, "unallocated producer");
2982 }
2983
2984 RB_OBJ_WRITE(obj, &ptr->init, init);
2985 RB_OBJ_WRITE(obj, &ptr->proc, proc);
2986 RB_OBJ_WRITE(obj, &ptr->size, size);
2987
2988 return obj;
2989}
2990
2991static VALUE
2992producer_each_stop(VALUE dummy, VALUE exc)
2993{
2994 return rb_attr_get(exc, id_result);
2995}
2996
2997NORETURN(static VALUE producer_each_i(VALUE obj));
2998
2999static VALUE
3000producer_each_i(VALUE obj)
3001{
3002 struct producer *ptr;
3003 VALUE init, proc, curr;
3004
3005 ptr = producer_ptr(obj);
3006 init = ptr->init;
3007 proc = ptr->proc;
3008
3009 if (UNDEF_P(init)) {
3010 curr = Qnil;
3011 }
3012 else {
3013 rb_yield(init);
3014 curr = init;
3015 }
3016
3017 for (;;) {
3018 curr = rb_funcall(proc, id_call, 1, curr);
3019 rb_yield(curr);
3020 }
3021
3023}
3024
3025/* :nodoc: */
3026static VALUE
3027producer_each(VALUE obj)
3028{
3029 rb_need_block();
3030
3031 return rb_rescue2(producer_each_i, obj, producer_each_stop, (VALUE)0, rb_eStopIteration, (VALUE)0);
3032}
3033
3034static VALUE
3035producer_size(VALUE obj, VALUE args, VALUE eobj)
3036{
3037 struct producer *ptr = producer_ptr(obj);
3038 VALUE size = ptr->size;
3039
3040 if (NIL_P(size)) return Qnil;
3041 if (RB_INTEGER_TYPE_P(size) || RB_FLOAT_TYPE_P(size)) return size;
3042
3043 return rb_funcall(size, id_call, 0);
3044}
3045
3046/*
3047 * call-seq:
3048 * Enumerator.produce(initial = nil, size: nil) { |prev| block } -> enumerator
3049 *
3050 * Creates an infinite enumerator from any block, just called over and
3051 * over. The result of the previous iteration is passed to the next one.
3052 * If +initial+ is provided, it is passed to the first iteration, and
3053 * becomes the first element of the enumerator; if it is not provided,
3054 * the first iteration receives +nil+, and its result becomes the first
3055 * element of the iterator.
3056 *
3057 * Raising StopIteration from the block stops an iteration.
3058 *
3059 * Enumerator.produce(1, &:succ) # => enumerator of 1, 2, 3, 4, ....
3060 *
3061 * Enumerator.produce { rand(10) } # => infinite random number sequence
3062 *
3063 * ancestors = Enumerator.produce(node) { |prev| node = prev.parent or raise StopIteration }
3064 * enclosing_section = ancestors.find { |n| n.type == :section }
3065 *
3066 * Using ::produce together with Enumerable methods like Enumerable#detect,
3067 * Enumerable#slice_after, Enumerable#take_while can provide Enumerator-based alternatives
3068 * for +while+ and +until+ cycles:
3069 *
3070 * # Find next Tuesday
3071 * require "date"
3072 * Enumerator.produce(Date.today, &:succ).detect(&:tuesday?)
3073 *
3074 * # Simple lexer:
3075 * require "strscan"
3076 * scanner = StringScanner.new("7+38/6")
3077 * PATTERN = %r{\d+|[-/+*]}
3078 * Enumerator.produce { scanner.scan(PATTERN) }.slice_after { scanner.eos? }.first
3079 * # => ["7", "+", "38", "/", "6"]
3080 *
3081 * The optional +size+ keyword argument specifies the size of the enumerator,
3082 * which can be retrieved by Enumerator#size. It can be an integer,
3083 * +Float::INFINITY+, a callable object (such as a lambda), or +nil+ to
3084 * indicate unknown size. When not specified, the size defaults to
3085 * +Float::INFINITY+.
3086 *
3087 * # Infinite enumerator
3088 * enum = Enumerator.produce(1, size: Float::INFINITY, &:succ)
3089 * enum.size # => Float::INFINITY
3090 *
3091 * # Finite enumerator with known/computable size
3092 * abs_dir = File.expand_path("./baz") # => "/foo/bar/baz"
3093 * traverser = Enumerator.produce(abs_dir, size: -> { abs_dir.count("/") + 1 }) {
3094 * raise StopIteration if it == "/"
3095 * File.dirname(it)
3096 * }
3097 * traverser.size # => 4
3098 *
3099 * # Finite enumerator with unknown size
3100 * calendar = Enumerator.produce(Date.today, size: nil) {
3101 * it.monday? ? raise(StopIteration) : it + 1
3102 * }
3103 * calendar.size # => nil
3104 */
3105static VALUE
3106enumerator_s_produce(int argc, VALUE *argv, VALUE klass)
3107{
3108 VALUE init, producer, opts, size;
3109 ID keyword_ids[1];
3110
3111 if (!rb_block_given_p()) rb_raise(rb_eArgError, "no block given");
3112
3113 keyword_ids[0] = rb_intern("size");
3114 rb_scan_args_kw(RB_SCAN_ARGS_LAST_HASH_KEYWORDS, argc, argv, "01:", &init, &opts);
3115 rb_get_kwargs(opts, keyword_ids, 0, 1, &size);
3116
3117 size = UNDEF_P(size) ? DBL2NUM(HUGE_VAL) : convert_to_feasible_size_value(size);
3118
3119 if (argc == 0 || (argc == 1 && !NIL_P(opts))) {
3120 init = Qundef;
3121 }
3122
3123 producer = producer_init(producer_allocate(rb_cEnumProducer), init, rb_block_proc(), size);
3124
3125 return rb_enumeratorize_with_size_kw(producer, sym_each, 0, 0, producer_size, RB_NO_KEYWORDS);
3126}
3127
3128/*
3129 * Document-class: Enumerator::Chain
3130 *
3131 * Enumerator::Chain is a subclass of Enumerator, which represents a
3132 * chain of enumerables that works as a single enumerator.
3133 *
3134 * This type of objects can be created by Enumerable#chain and
3135 * Enumerator#+.
3136 */
3137
3138static void
3139enum_chain_mark_and_move(void *p)
3140{
3141 struct enum_chain *ptr = p;
3142 rb_gc_mark_and_move(&ptr->enums);
3143}
3144
3145#define enum_chain_free RUBY_TYPED_DEFAULT_FREE
3146
3147static size_t
3148enum_chain_memsize(const void *p)
3149{
3150 return sizeof(struct enum_chain);
3151}
3152
3153static const rb_data_type_t enum_chain_data_type = {
3154 "chain",
3155 {
3156 enum_chain_mark_and_move,
3157 enum_chain_free,
3158 enum_chain_memsize,
3159 enum_chain_mark_and_move,
3160 },
3161 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
3162};
3163
3164static struct enum_chain *
3165enum_chain_ptr(VALUE obj)
3166{
3167 struct enum_chain *ptr;
3168
3169 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr);
3170 if (!ptr || UNDEF_P(ptr->enums)) {
3171 rb_raise(rb_eArgError, "uninitialized chain");
3172 }
3173 return ptr;
3174}
3175
3176/* :nodoc: */
3177static VALUE
3178enum_chain_allocate(VALUE klass)
3179{
3180 struct enum_chain *ptr;
3181 VALUE obj;
3182
3183 obj = TypedData_Make_Struct(klass, struct enum_chain, &enum_chain_data_type, ptr);
3184 ptr->enums = Qundef;
3185 ptr->pos = -1;
3186
3187 return obj;
3188}
3189
3190/*
3191 * call-seq:
3192 * Enumerator::Chain.new(*enums) -> enum
3193 *
3194 * Generates a new enumerator object that iterates over the elements
3195 * of given enumerable objects in sequence.
3196 *
3197 * e = Enumerator::Chain.new(1..3, [4, 5])
3198 * e.to_a #=> [1, 2, 3, 4, 5]
3199 * e.size #=> 5
3200 */
3201static VALUE
3202enum_chain_initialize(VALUE obj, VALUE enums)
3203{
3204 struct enum_chain *ptr;
3205
3206 rb_check_frozen(obj);
3207 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr);
3208
3209 if (!ptr) rb_raise(rb_eArgError, "unallocated chain");
3210
3211 RB_OBJ_WRITE(obj, &ptr->enums, rb_ary_freeze(enums));
3212 ptr->pos = -1;
3213
3214 return obj;
3215}
3216
3217static VALUE
3218new_enum_chain(VALUE enums)
3219{
3220 long i;
3221 VALUE obj = enum_chain_initialize(enum_chain_allocate(rb_cEnumChain), enums);
3222
3223 for (i = 0; i < RARRAY_LEN(enums); i++) {
3224 if (RTEST(rb_obj_is_kind_of(RARRAY_AREF(enums, i), rb_cLazy))) {
3225 return enumerable_lazy(obj);
3226 }
3227 }
3228
3229 return obj;
3230}
3231
3232/* :nodoc: */
3233static VALUE
3234enum_chain_init_copy(VALUE obj, VALUE orig)
3235{
3236 struct enum_chain *ptr0, *ptr1;
3237
3238 if (!OBJ_INIT_COPY(obj, orig)) return obj;
3239 ptr0 = enum_chain_ptr(orig);
3240
3241 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr1);
3242
3243 if (!ptr1) rb_raise(rb_eArgError, "unallocated chain");
3244
3245 RB_OBJ_WRITE(obj, &ptr1->enums, ptr0->enums);
3246 ptr1->pos = ptr0->pos;
3247
3248 return obj;
3249}
3250
3251static VALUE
3252enum_chain_total_size(VALUE enums)
3253{
3254 VALUE total = INT2FIX(0);
3255 long i;
3256
3257 for (i = 0; i < RARRAY_LEN(enums); i++) {
3258 VALUE size = enum_size(RARRAY_AREF(enums, i));
3259
3260 if (NIL_P(size) || (RB_FLOAT_TYPE_P(size) && isinf(NUM2DBL(size)))) {
3261 return size;
3262 }
3263 if (!RB_INTEGER_TYPE_P(size)) {
3264 return Qnil;
3265 }
3266
3267 total = rb_funcall(total, '+', 1, size);
3268 }
3269
3270 return total;
3271}
3272
3273/*
3274 * call-seq:
3275 * obj.size -> int, Float::INFINITY or nil
3276 *
3277 * Returns the total size of the enumerator chain calculated by
3278 * summing up the size of each enumerable in the chain. If any of the
3279 * enumerables reports its size as nil or Float::INFINITY, that value
3280 * is returned as the total size.
3281 */
3282static VALUE
3283enum_chain_size(VALUE obj)
3284{
3285 return enum_chain_total_size(enum_chain_ptr(obj)->enums);
3286}
3287
3288static VALUE
3289enum_chain_enum_size(VALUE obj, VALUE args, VALUE eobj)
3290{
3291 return enum_chain_size(obj);
3292}
3293
3294static VALUE
3295enum_chain_enum_no_size(VALUE obj, VALUE args, VALUE eobj)
3296{
3297 return Qnil;
3298}
3299
3300/*
3301 * call-seq:
3302 * obj.each(*args) { |...| ... } -> obj
3303 * obj.each(*args) -> enumerator
3304 *
3305 * Iterates over the elements of the first enumerable by calling the
3306 * "each" method on it with the given arguments, then proceeds to the
3307 * following enumerables in sequence until all of the enumerables are
3308 * exhausted.
3309 *
3310 * If no block is given, returns an enumerator.
3311 */
3312static VALUE
3313enum_chain_each(int argc, VALUE *argv, VALUE obj)
3314{
3315 VALUE enums, block;
3316 struct enum_chain *objptr;
3317 long i;
3318
3319 RETURN_SIZED_ENUMERATOR(obj, argc, argv, argc > 0 ? enum_chain_enum_no_size : enum_chain_enum_size);
3320
3321 objptr = enum_chain_ptr(obj);
3322 enums = objptr->enums;
3323 block = rb_block_proc();
3324
3325 for (i = 0; i < RARRAY_LEN(enums); i++) {
3326 objptr->pos = i;
3327 rb_funcall_with_block(RARRAY_AREF(enums, i), id_each, argc, argv, block);
3328 }
3329
3330 return obj;
3331}
3332
3333/*
3334 * call-seq:
3335 * obj.rewind -> obj
3336 *
3337 * Rewinds the enumerator chain by calling the "rewind" method on each
3338 * enumerable in reverse order. Each call is performed only if the
3339 * enumerable responds to the method.
3340 */
3341static VALUE
3342enum_chain_rewind(VALUE obj)
3343{
3344 struct enum_chain *objptr = enum_chain_ptr(obj);
3345 VALUE enums = objptr->enums;
3346 long i;
3347
3348 for (i = objptr->pos; 0 <= i && i < RARRAY_LEN(enums); objptr->pos = --i) {
3349 rb_check_funcall(RARRAY_AREF(enums, i), id_rewind, 0, 0);
3350 }
3351
3352 return obj;
3353}
3354
3355static VALUE
3356inspect_enum_chain(VALUE obj, VALUE dummy, int recur)
3357{
3358 VALUE klass = rb_obj_class(obj);
3359 struct enum_chain *ptr;
3360
3361 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr);
3362
3363 if (!ptr || UNDEF_P(ptr->enums)) {
3364 return rb_sprintf("#<%"PRIsVALUE": uninitialized>", rb_class_path(klass));
3365 }
3366
3367 if (recur) {
3368 return rb_sprintf("#<%"PRIsVALUE": ...>", rb_class_path(klass));
3369 }
3370
3371 return rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE">", rb_class_path(klass), ptr->enums);
3372}
3373
3374/*
3375 * call-seq:
3376 * obj.inspect -> string
3377 *
3378 * Returns a printable version of the enumerator chain.
3379 */
3380static VALUE
3381enum_chain_inspect(VALUE obj)
3382{
3383 return rb_exec_recursive(inspect_enum_chain, obj, 0);
3384}
3385
3386/*
3387 * call-seq:
3388 * e.chain(*enums) -> enumerator
3389 *
3390 * Returns an enumerator object generated from this enumerator and
3391 * given enumerables.
3392 *
3393 * e = (1..3).chain([4, 5])
3394 * e.to_a #=> [1, 2, 3, 4, 5]
3395 */
3396static VALUE
3397enum_chain(int argc, VALUE *argv, VALUE obj)
3398{
3399 VALUE enums = rb_ary_new_from_values(1, &obj);
3400 rb_ary_cat(enums, argv, argc);
3401 return new_enum_chain(enums);
3402}
3403
3404/*
3405 * call-seq:
3406 * e + enum -> enumerator
3407 *
3408 * Returns an enumerator object generated from this enumerator and a
3409 * given enumerable.
3410 *
3411 * e = (1..3).each + [4, 5]
3412 * e.to_a #=> [1, 2, 3, 4, 5]
3413 */
3414static VALUE
3415enumerator_plus(VALUE obj, VALUE eobj)
3416{
3417 return new_enum_chain(rb_ary_new_from_args(2, obj, eobj));
3418}
3419
3420/*
3421 * Document-class: Enumerator::Product
3422 *
3423 * Enumerator::Product generates a Cartesian product of any number of
3424 * enumerable objects. Iterating over the product of enumerable
3425 * objects is roughly equivalent to nested each_entry loops where the
3426 * loop for the rightmost object is put innermost.
3427 *
3428 * innings = Enumerator::Product.new(1..9, ['top', 'bottom'])
3429 *
3430 * innings.each do |i, h|
3431 * p [i, h]
3432 * end
3433 * # [1, "top"]
3434 * # [1, "bottom"]
3435 * # [2, "top"]
3436 * # [2, "bottom"]
3437 * # [3, "top"]
3438 * # [3, "bottom"]
3439 * # ...
3440 * # [9, "top"]
3441 * # [9, "bottom"]
3442 *
3443 * The method used against each enumerable object is `each_entry`
3444 * instead of `each` so that the product of N enumerable objects
3445 * yields an array of exactly N elements in each iteration.
3446 *
3447 * When no enumerator is given, it calls a given block once yielding
3448 * an empty argument list.
3449 *
3450 * This type of objects can be created by Enumerator.product.
3451 */
3452
3453static void
3454enum_product_mark_and_move(void *p)
3455{
3456 struct enum_product *ptr = p;
3457 rb_gc_mark_and_move(&ptr->enums);
3458}
3459
3460#define enum_product_free RUBY_TYPED_DEFAULT_FREE
3461
3462static size_t
3463enum_product_memsize(const void *p)
3464{
3465 return sizeof(struct enum_product);
3466}
3467
3468static const rb_data_type_t enum_product_data_type = {
3469 "product",
3470 {
3471 enum_product_mark_and_move,
3472 enum_product_free,
3473 enum_product_memsize,
3474 enum_product_mark_and_move,
3475 },
3476 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
3477};
3478
3479static struct enum_product *
3480enum_product_ptr(VALUE obj)
3481{
3482 struct enum_product *ptr;
3483
3484 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr);
3485 if (!ptr || UNDEF_P(ptr->enums)) {
3486 rb_raise(rb_eArgError, "uninitialized product");
3487 }
3488 return ptr;
3489}
3490
3491/* :nodoc: */
3492static VALUE
3493enum_product_allocate(VALUE klass)
3494{
3495 struct enum_product *ptr;
3496 VALUE obj;
3497
3498 obj = TypedData_Make_Struct(klass, struct enum_product, &enum_product_data_type, ptr);
3499 ptr->enums = Qundef;
3500
3501 return obj;
3502}
3503
3504/*
3505 * call-seq:
3506 * Enumerator::Product.new(*enums) -> enum
3507 *
3508 * Generates a new enumerator object that generates a Cartesian
3509 * product of given enumerable objects.
3510 *
3511 * e = Enumerator::Product.new(1..3, [4, 5])
3512 * e.to_a #=> [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
3513 * e.size #=> 6
3514 */
3515static VALUE
3516enum_product_initialize(int argc, VALUE *argv, VALUE obj)
3517{
3518 struct enum_product *ptr;
3519 VALUE enums = Qnil, options = Qnil;
3520
3521 rb_scan_args(argc, argv, "*:", &enums, &options);
3522
3523 if (!NIL_P(options) && !RHASH_EMPTY_P(options)) {
3524 rb_exc_raise(rb_keyword_error_new("unknown", rb_hash_keys(options)));
3525 }
3526
3527 rb_check_frozen(obj);
3528 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr);
3529
3530 if (!ptr) rb_raise(rb_eArgError, "unallocated product");
3531
3532 RB_OBJ_WRITE(obj, &ptr->enums, rb_ary_freeze(enums));
3533
3534 return obj;
3535}
3536
3537/* :nodoc: */
3538static VALUE
3539enum_product_init_copy(VALUE obj, VALUE orig)
3540{
3541 struct enum_product *ptr0, *ptr1;
3542
3543 if (!OBJ_INIT_COPY(obj, orig)) return obj;
3544 ptr0 = enum_product_ptr(orig);
3545
3546 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr1);
3547
3548 if (!ptr1) rb_raise(rb_eArgError, "unallocated product");
3549
3550 RB_OBJ_WRITE(obj, &ptr1->enums, ptr0->enums);
3551
3552 return obj;
3553}
3554
3555static VALUE
3556enum_product_total_size(VALUE enums)
3557{
3558 VALUE total = INT2FIX(1);
3559 VALUE sizes = rb_ary_hidden_new(RARRAY_LEN(enums));
3560 long i;
3561
3562 for (i = 0; i < RARRAY_LEN(enums); i++) {
3563 VALUE size = enum_size(RARRAY_AREF(enums, i));
3564 if (size == INT2FIX(0)) {
3565 rb_ary_resize(sizes, 0);
3566 return size;
3567 }
3568 rb_ary_push(sizes, size);
3569 }
3570 for (i = 0; i < RARRAY_LEN(sizes); i++) {
3571 VALUE size = RARRAY_AREF(sizes, i);
3572
3573 if (NIL_P(size) || (RB_TYPE_P(size, T_FLOAT) && isinf(NUM2DBL(size)))) {
3574 return size;
3575 }
3576 if (!RB_INTEGER_TYPE_P(size)) {
3577 return Qnil;
3578 }
3579
3580 total = rb_funcall(total, '*', 1, size);
3581 }
3582
3583 return total;
3584}
3585
3586/*
3587 * call-seq:
3588 * obj.size -> int, Float::INFINITY or nil
3589 *
3590 * Returns the total size of the enumerator product calculated by
3591 * multiplying the sizes of enumerables in the product. If any of the
3592 * enumerables reports its size as nil or Float::INFINITY, that value
3593 * is returned as the size.
3594 */
3595static VALUE
3596enum_product_size(VALUE obj)
3597{
3598 return enum_product_total_size(enum_product_ptr(obj)->enums);
3599}
3600
3601static VALUE
3602enum_product_enum_size(VALUE obj, VALUE args, VALUE eobj)
3603{
3604 return enum_product_size(obj);
3605}
3606
3608 VALUE obj;
3609 VALUE block;
3610 int index;
3611 int argc;
3612 VALUE *argv;
3613};
3614
3615static VALUE product_each(VALUE, struct product_state *);
3616
3617static VALUE
3618product_each_i(RB_BLOCK_CALL_FUNC_ARGLIST(value, state))
3619{
3620 struct product_state *pstate = (struct product_state *)state;
3621 pstate->argv[pstate->index++] = value;
3622
3623 VALUE val = product_each(pstate->obj, pstate);
3624 pstate->index--;
3625 return val;
3626}
3627
3628static VALUE
3629product_each(VALUE obj, struct product_state *pstate)
3630{
3631 struct enum_product *ptr = enum_product_ptr(obj);
3632 VALUE enums = ptr->enums;
3633
3634 if (pstate->index < pstate->argc) {
3635 VALUE eobj = RARRAY_AREF(enums, pstate->index);
3636
3637 rb_block_call(eobj, id_each_entry, 0, NULL, product_each_i, (VALUE)pstate);
3638 }
3639 else {
3640 rb_funcall(pstate->block, id_call, 1, rb_ary_new_from_values(pstate->argc, pstate->argv));
3641 }
3642
3643 return obj;
3644}
3645
3646static VALUE
3647enum_product_run(VALUE obj, VALUE block)
3648{
3649 struct enum_product *ptr = enum_product_ptr(obj);
3650 int argc = RARRAY_LENINT(ptr->enums);
3651 if (argc == 0) { /* no need to allocate state.argv */
3652 rb_funcall(block, id_call, 1, rb_ary_new());
3653 return obj;
3654 }
3655
3656 VALUE argsbuf = 0;
3657 struct product_state state = {
3658 .obj = obj,
3659 .block = block,
3660 .index = 0,
3661 .argc = argc,
3662 .argv = ALLOCV_N(VALUE, argsbuf, argc),
3663 };
3664
3665 VALUE ret = product_each(obj, &state);
3666 ALLOCV_END(argsbuf);
3667 return ret;
3668}
3669
3670/*
3671 * call-seq:
3672 * obj.each { |...| ... } -> obj
3673 * obj.each -> enumerator
3674 *
3675 * Iterates over the elements of the first enumerable by calling the
3676 * "each_entry" method on it with the given arguments, then proceeds
3677 * to the following enumerables in sequence until all of the
3678 * enumerables are exhausted.
3679 *
3680 * If no block is given, returns an enumerator. Otherwise, returns self.
3681 */
3682static VALUE
3683enum_product_each(VALUE obj)
3684{
3685 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_product_enum_size);
3686
3687 return enum_product_run(obj, rb_block_proc());
3688}
3689
3690/*
3691 * call-seq:
3692 * obj.rewind -> obj
3693 *
3694 * Rewinds the product enumerator by calling the "rewind" method on
3695 * each enumerable in reverse order. Each call is performed only if
3696 * the enumerable responds to the method.
3697 */
3698static VALUE
3699enum_product_rewind(VALUE obj)
3700{
3701 struct enum_product *ptr = enum_product_ptr(obj);
3702 VALUE enums = ptr->enums;
3703 long i;
3704
3705 for (i = 0; i < RARRAY_LEN(enums); i++) {
3706 rb_check_funcall(RARRAY_AREF(enums, i), id_rewind, 0, 0);
3707 }
3708
3709 return obj;
3710}
3711
3712static VALUE
3713inspect_enum_product(VALUE obj, VALUE dummy, int recur)
3714{
3715 VALUE klass = rb_obj_class(obj);
3716 struct enum_product *ptr;
3717
3718 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr);
3719
3720 if (!ptr || UNDEF_P(ptr->enums)) {
3721 return rb_sprintf("#<%"PRIsVALUE": uninitialized>", rb_class_path(klass));
3722 }
3723
3724 if (recur) {
3725 return rb_sprintf("#<%"PRIsVALUE": ...>", rb_class_path(klass));
3726 }
3727
3728 return rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE">", rb_class_path(klass), ptr->enums);
3729}
3730
3731/*
3732 * call-seq:
3733 * obj.inspect -> string
3734 *
3735 * Returns a printable version of the product enumerator.
3736 */
3737static VALUE
3738enum_product_inspect(VALUE obj)
3739{
3740 return rb_exec_recursive(inspect_enum_product, obj, 0);
3741}
3742
3743/*
3744 * call-seq:
3745 * Enumerator.product(*enums) -> enumerator
3746 * Enumerator.product(*enums) { |elts| ... } -> enumerator
3747 *
3748 * Generates a new enumerator object that generates a Cartesian
3749 * product of given enumerable objects. This is equivalent to
3750 * Enumerator::Product.new.
3751 *
3752 * e = Enumerator.product(1..3, [4, 5])
3753 * e.to_a #=> [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
3754 * e.size #=> 6
3755 *
3756 * When a block is given, calls the block with each N-element array
3757 * generated and returns +nil+.
3758 */
3759static VALUE
3760enumerator_s_product(int argc, VALUE *argv, VALUE klass)
3761{
3762 VALUE enums = Qnil, options = Qnil, block = Qnil;
3763
3764 rb_scan_args(argc, argv, "*:&", &enums, &options, &block);
3765
3766 if (!NIL_P(options) && !RHASH_EMPTY_P(options)) {
3767 rb_exc_raise(rb_keyword_error_new("unknown", rb_hash_keys(options)));
3768 }
3769
3770 VALUE obj = enum_product_initialize(argc, argv, enum_product_allocate(rb_cEnumProduct));
3771
3772 if (!NIL_P(block)) {
3773 enum_product_run(obj, block);
3774 return Qnil;
3775 }
3776
3777 return obj;
3778}
3779
3781 struct enumerator enumerator;
3782 VALUE begin;
3783 VALUE end;
3784 VALUE step;
3785 bool exclude_end;
3786};
3787
3788RUBY_REFERENCES(arith_seq_refs) = {
3789 RUBY_REF_EDGE(struct enumerator, obj),
3790 RUBY_REF_EDGE(struct enumerator, args),
3791 RUBY_REF_EDGE(struct enumerator, fib),
3792 RUBY_REF_EDGE(struct enumerator, dst),
3793 RUBY_REF_EDGE(struct enumerator, lookahead),
3794 RUBY_REF_EDGE(struct enumerator, feedvalue),
3795 RUBY_REF_EDGE(struct enumerator, stop_exc),
3796 RUBY_REF_EDGE(struct enumerator, size),
3797 RUBY_REF_EDGE(struct enumerator, procs),
3798
3799 RUBY_REF_EDGE(struct arith_seq, begin),
3800 RUBY_REF_EDGE(struct arith_seq, end),
3801 RUBY_REF_EDGE(struct arith_seq, step),
3802 RUBY_REF_END
3803};
3804
3805static const rb_data_type_t arith_seq_data_type = {
3806 "arithmetic_sequence",
3807 {
3808 RUBY_REFS_LIST_PTR(arith_seq_refs),
3810 NULL, // Nothing allocated externally, so don't need a memsize function
3811 NULL,
3812 },
3813 .parent = &enumerator_data_type,
3814 .flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_DECL_MARKING | RUBY_TYPED_EMBEDDABLE
3815};
3816
3817static VALUE
3818arith_seq_allocate(VALUE klass)
3819{
3820 struct arith_seq *ptr;
3821 VALUE enum_obj;
3822
3823 enum_obj = TypedData_Make_Struct(klass, struct arith_seq, &arith_seq_data_type, ptr);
3824 ptr->enumerator.obj = Qundef;
3825
3826 return enum_obj;
3827}
3828
3829/*
3830 * Document-class: Enumerator::ArithmeticSequence
3831 *
3832 * Enumerator::ArithmeticSequence is a subclass of Enumerator,
3833 * that is a representation of sequences of numbers with common difference.
3834 * Instances of this class can be generated by the Range#step and Numeric#step
3835 * methods.
3836 *
3837 * The class can be used for slicing Array (see Array#slice) or custom
3838 * collections.
3839 */
3840
3841VALUE
3842rb_arith_seq_new(VALUE obj, VALUE meth, int argc, VALUE const *argv,
3843 rb_enumerator_size_func *size_fn,
3844 VALUE beg, VALUE end, VALUE step, int excl)
3845{
3846 VALUE aseq = enumerator_init(arith_seq_allocate(rb_cArithSeq),
3847 obj, meth, argc, argv, size_fn, Qnil, rb_keyword_given_p());
3848 struct arith_seq *ptr;
3849 TypedData_Get_Struct(aseq, struct arith_seq, &enumerator_data_type, ptr);
3850
3851 RB_OBJ_WRITE(aseq, &ptr->begin, beg);
3852 RB_OBJ_WRITE(aseq, &ptr->end, end);
3853 RB_OBJ_WRITE(aseq, &ptr->step, step);
3854 ptr->exclude_end = excl;
3855
3856 return aseq;
3857}
3858
3859/*
3860 * call-seq: aseq.begin -> num or nil
3861 *
3862 * Returns the number that defines the first element of this arithmetic
3863 * sequence.
3864 */
3865static inline VALUE
3866arith_seq_begin(VALUE self)
3867{
3868 struct arith_seq *ptr;
3869 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3870 return ptr->begin;
3871}
3872
3873/*
3874 * call-seq: aseq.end -> num or nil
3875 *
3876 * Returns the number that defines the end of this arithmetic sequence.
3877 */
3878static inline VALUE
3879arith_seq_end(VALUE self)
3880{
3881 struct arith_seq *ptr;
3882 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3883 return ptr->end;
3884}
3885
3886/*
3887 * call-seq: aseq.step -> num
3888 *
3889 * Returns the number that defines the common difference between
3890 * two adjacent elements in this arithmetic sequence.
3891 */
3892static inline VALUE
3893arith_seq_step(VALUE self)
3894{
3895 struct arith_seq *ptr;
3896 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3897 return ptr->step;
3898}
3899
3900/*
3901 * call-seq: aseq.exclude_end? -> true or false
3902 *
3903 * Returns <code>true</code> if this arithmetic sequence excludes its end value.
3904 */
3905static inline VALUE
3906arith_seq_exclude_end(VALUE self)
3907{
3908 struct arith_seq *ptr;
3909 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3910 return RBOOL(ptr->exclude_end);
3911}
3912
3913static inline int
3914arith_seq_exclude_end_p(VALUE self)
3915{
3916 struct arith_seq *ptr;
3917 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3918 return ptr->exclude_end;
3919}
3920
3921int
3922rb_arithmetic_sequence_extract(VALUE obj, rb_arithmetic_sequence_components_t *component)
3923{
3924 if (rb_obj_is_kind_of(obj, rb_cArithSeq)) {
3925 component->begin = arith_seq_begin(obj);
3926 component->end = arith_seq_end(obj);
3927 component->step = arith_seq_step(obj);
3928 component->exclude_end = arith_seq_exclude_end_p(obj);
3929 return 1;
3930 }
3931 else if (rb_range_values(obj, &component->begin, &component->end, &component->exclude_end)) {
3932 component->step = INT2FIX(1);
3933 return 1;
3934 }
3935
3936 return 0;
3937}
3938
3939VALUE
3940rb_arithmetic_sequence_beg_len_step(VALUE obj, long *begp, long *lenp, long *stepp, long len, int err)
3941{
3942 RBIMPL_NONNULL_ARG(begp);
3943 RBIMPL_NONNULL_ARG(lenp);
3944 RBIMPL_NONNULL_ARG(stepp);
3945
3947 if (!rb_arithmetic_sequence_extract(obj, &aseq)) {
3948 return Qfalse;
3949 }
3950
3951 long step = NIL_P(aseq.step) ? 1 : NUM2LONG(aseq.step);
3952 *stepp = step;
3953
3954 if (step < 0) {
3955 if (aseq.exclude_end && !NIL_P(aseq.end)) {
3956 /* Handle exclusion before range reversal */
3957 aseq.end = LONG2NUM(NUM2LONG(aseq.end) + 1);
3958
3959 /* Don't exclude the previous beginning */
3960 aseq.exclude_end = 0;
3961 }
3962 VALUE tmp = aseq.begin;
3963 aseq.begin = aseq.end;
3964 aseq.end = tmp;
3965 }
3966
3967 if (err == 0 && (step < -1 || step > 1)) {
3968 if (rb_range_component_beg_len(aseq.begin, aseq.end, aseq.exclude_end, begp, lenp, len, 1) == Qtrue) {
3969 if (*begp > len)
3970 goto out_of_range;
3971 if (*lenp > len)
3972 goto out_of_range;
3973 return Qtrue;
3974 }
3975 }
3976 else {
3977 return rb_range_component_beg_len(aseq.begin, aseq.end, aseq.exclude_end, begp, lenp, len, err);
3978 }
3979
3980 out_of_range:
3981 rb_raise(rb_eRangeError, "%+"PRIsVALUE" out of range", obj);
3982 return Qnil;
3983}
3984
3985static VALUE
3986arith_seq_take(VALUE self, VALUE num)
3987{
3988 VALUE b, e, s, ary;
3989 long n;
3990 int x;
3991
3992 n = NUM2LONG(num);
3993 if (n < 0) {
3994 rb_raise(rb_eArgError, "attempt to take negative size");
3995 }
3996 if (n == 0) {
3997 return rb_ary_new_capa(0);
3998 }
3999
4000 b = arith_seq_begin(self);
4001 e = arith_seq_end(self);
4002 s = arith_seq_step(self);
4003 x = arith_seq_exclude_end_p(self);
4004
4005 if (FIXNUM_P(b) && NIL_P(e) && FIXNUM_P(s)) {
4006 long i = FIX2LONG(b), unit = FIX2LONG(s);
4007 ary = rb_ary_new_capa(n);
4008 while (n > 0 && FIXABLE(i)) {
4009 rb_ary_push(ary, LONG2FIX(i));
4010 i += unit; // FIXABLE + FIXABLE never overflow;
4011 --n;
4012 }
4013 if (n > 0) {
4014 b = LONG2NUM(i);
4015 while (n > 0) {
4016 rb_ary_push(ary, b);
4017 b = rb_big_plus(b, s);
4018 --n;
4019 }
4020 }
4021 return ary;
4022 }
4023 else if (FIXNUM_P(b) && FIXNUM_P(e) && FIXNUM_P(s)) {
4024 long i = FIX2LONG(b);
4025 long end = FIX2LONG(e);
4026 long unit = FIX2LONG(s);
4027 long len;
4028
4029 if (unit >= 0) {
4030 if (!x) end += 1;
4031
4032 len = end - i;
4033 if (len < 0) len = 0;
4034 ary = rb_ary_new_capa((n < len) ? n : len);
4035 while (n > 0 && i < end) {
4036 rb_ary_push(ary, LONG2FIX(i));
4037 if (i > LONG_MAX - unit) break;
4038 i += unit;
4039 --n;
4040 }
4041 }
4042 else {
4043 if (!x) end -= 1;
4044
4045 len = i - end;
4046 if (len < 0) len = 0;
4047 ary = rb_ary_new_capa((n < len) ? n : len);
4048 while (n > 0 && i > end) {
4049 rb_ary_push(ary, LONG2FIX(i));
4050 if (i < LONG_MIN - unit) break;
4051 i += unit;
4052 --n;
4053 }
4054 }
4055 return ary;
4056 }
4057 else if (RB_FLOAT_TYPE_P(b) || RB_FLOAT_TYPE_P(e) || RB_FLOAT_TYPE_P(s)) {
4058 /* generate values like ruby_float_step */
4059
4060 double unit = NUM2DBL(s);
4061 double beg = NUM2DBL(b);
4062 double end = NIL_P(e) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(e);
4063 double len = ruby_float_step_size(beg, end, unit, x);
4064 long i;
4065
4066 if (n > len)
4067 n = (long)len;
4068
4069 if (isinf(unit)) {
4070 if (len > 0) {
4071 ary = rb_ary_new_capa(1);
4072 rb_ary_push(ary, DBL2NUM(beg));
4073 }
4074 else {
4075 ary = rb_ary_new_capa(0);
4076 }
4077 }
4078 else if (unit == 0) {
4079 VALUE val = DBL2NUM(beg);
4080 ary = rb_ary_new_capa(n);
4081 for (i = 0; i < len; ++i) {
4082 rb_ary_push(ary, val);
4083 }
4084 }
4085 else {
4086 ary = rb_ary_new_capa(n);
4087 for (i = 0; i < n; ++i) {
4088 double d = i*unit+beg;
4089 if (unit >= 0 ? end < d : d < end) d = end;
4090 rb_ary_push(ary, DBL2NUM(d));
4091 }
4092 }
4093
4094 return ary;
4095 }
4096
4097 {
4098 VALUE argv[1];
4099 argv[0] = num;
4100 return rb_call_super(1, argv);
4101 }
4102}
4103
4104/*
4105 * call-seq:
4106 * aseq.first -> num or nil
4107 * aseq.first(n) -> an_array
4108 *
4109 * Returns the first number in this arithmetic sequence,
4110 * or an array of the first +n+ elements.
4111 */
4112static VALUE
4113arith_seq_first(int argc, VALUE *argv, VALUE self)
4114{
4115 VALUE b, e, s;
4116
4117 rb_check_arity(argc, 0, 1);
4118
4119 b = arith_seq_begin(self);
4120 e = arith_seq_end(self);
4121 s = arith_seq_step(self);
4122 if (argc == 0) {
4123 if (NIL_P(b)) {
4124 return Qnil;
4125 }
4126 if (!NIL_P(e)) {
4127 VALUE zero = INT2FIX(0);
4128 int r = rb_cmpint(rb_num_coerce_cmp(s, zero, idCmp), s, zero);
4129 if (r > 0 && RTEST(rb_funcall(b, '>', 1, e))) {
4130 return Qnil;
4131 }
4132 if (r < 0 && RTEST(rb_funcall(b, '<', 1, e))) {
4133 return Qnil;
4134 }
4135 }
4136 return b;
4137 }
4138
4139 return arith_seq_take(self, argv[0]);
4140}
4141
4142static inline VALUE
4143num_plus(VALUE a, VALUE b)
4144{
4145 if (RB_INTEGER_TYPE_P(a)) {
4146 return rb_int_plus(a, b);
4147 }
4148 else if (RB_FLOAT_TYPE_P(a)) {
4149 return rb_float_plus(a, b);
4150 }
4151 else if (RB_TYPE_P(a, T_RATIONAL)) {
4152 return rb_rational_plus(a, b);
4153 }
4154 else {
4155 return rb_funcallv(a, '+', 1, &b);
4156 }
4157}
4158
4159static inline VALUE
4160num_minus(VALUE a, VALUE b)
4161{
4162 if (RB_INTEGER_TYPE_P(a)) {
4163 return rb_int_minus(a, b);
4164 }
4165 else if (RB_FLOAT_TYPE_P(a)) {
4166 return rb_float_minus(a, b);
4167 }
4168 else if (RB_TYPE_P(a, T_RATIONAL)) {
4169 return rb_rational_minus(a, b);
4170 }
4171 else {
4172 return rb_funcallv(a, '-', 1, &b);
4173 }
4174}
4175
4176static inline VALUE
4177num_mul(VALUE a, VALUE b)
4178{
4179 if (RB_INTEGER_TYPE_P(a)) {
4180 return rb_int_mul(a, b);
4181 }
4182 else if (RB_FLOAT_TYPE_P(a)) {
4183 return rb_float_mul(a, b);
4184 }
4185 else if (RB_TYPE_P(a, T_RATIONAL)) {
4186 return rb_rational_mul(a, b);
4187 }
4188 else {
4189 return rb_funcallv(a, '*', 1, &b);
4190 }
4191}
4192
4193static inline VALUE
4194num_idiv(VALUE a, VALUE b)
4195{
4196 VALUE q;
4197 if (RB_INTEGER_TYPE_P(a)) {
4198 q = rb_int_idiv(a, b);
4199 }
4200 else if (RB_FLOAT_TYPE_P(a)) {
4201 q = rb_float_div(a, b);
4202 }
4203 else if (RB_TYPE_P(a, T_RATIONAL)) {
4204 q = rb_rational_div(a, b);
4205 }
4206 else {
4207 q = rb_funcallv(a, idDiv, 1, &b);
4208 }
4209
4210 if (RB_INTEGER_TYPE_P(q)) {
4211 return q;
4212 }
4213 else if (RB_FLOAT_TYPE_P(q)) {
4214 return rb_float_floor(q, 0);
4215 }
4216 else if (RB_TYPE_P(q, T_RATIONAL)) {
4217 return rb_rational_floor(q, 0);
4218 }
4219 else {
4220 return rb_funcall(q, rb_intern("floor"), 0);
4221 }
4222}
4223
4224/*
4225 * call-seq:
4226 * aseq.last -> num or nil
4227 * aseq.last(n) -> an_array
4228 *
4229 * Returns the last number in this arithmetic sequence,
4230 * or an array of the last +n+ elements.
4231 */
4232static VALUE
4233arith_seq_last(int argc, VALUE *argv, VALUE self)
4234{
4235 VALUE b, e, s, len_1, len, last, nv, ary;
4236 int last_is_adjusted;
4237 long n;
4238
4239 e = arith_seq_end(self);
4240 if (NIL_P(e)) {
4241 rb_raise(rb_eRangeError,
4242 "cannot get the last element of endless arithmetic sequence");
4243 }
4244
4245 b = arith_seq_begin(self);
4246 s = arith_seq_step(self);
4247
4248 len_1 = num_idiv(num_minus(e, b), s);
4249 if (rb_num_negative_int_p(len_1)) {
4250 if (argc == 0) {
4251 return Qnil;
4252 }
4253 return rb_ary_new_capa(0);
4254 }
4255
4256 last = num_plus(b, num_mul(s, len_1));
4257 if ((last_is_adjusted = arith_seq_exclude_end_p(self) && rb_equal(last, e))) {
4258 last = num_minus(last, s);
4259 }
4260
4261 if (argc == 0) {
4262 return last;
4263 }
4264
4265 if (last_is_adjusted) {
4266 len = len_1;
4267 }
4268 else {
4269 len = rb_int_plus(len_1, INT2FIX(1));
4270 }
4271
4272 rb_scan_args(argc, argv, "1", &nv);
4273 if (!RB_INTEGER_TYPE_P(nv)) {
4274 nv = rb_to_int(nv);
4275 }
4276 if (RTEST(rb_int_gt(nv, len))) {
4277 nv = len;
4278 }
4279 n = NUM2LONG(nv);
4280 if (n < 0) {
4281 rb_raise(rb_eArgError, "negative array size");
4282 }
4283
4284 ary = rb_ary_new_capa(n);
4285 b = rb_int_minus(last, rb_int_mul(s, nv));
4286 while (n) {
4287 b = rb_int_plus(b, s);
4288 rb_ary_push(ary, b);
4289 --n;
4290 }
4291
4292 return ary;
4293}
4294
4295/*
4296 * call-seq:
4297 * aseq.inspect -> string
4298 *
4299 * Convert this arithmetic sequence to a printable form.
4300 */
4301static VALUE
4302arith_seq_inspect(VALUE self)
4303{
4304 struct enumerator *e;
4305 VALUE eobj, str, eargs;
4306 int range_p;
4307
4308 TypedData_Get_Struct(self, struct enumerator, &enumerator_data_type, e);
4309
4310 eobj = rb_attr_get(self, id_receiver);
4311 if (NIL_P(eobj)) {
4312 eobj = e->obj;
4313 }
4314
4315 range_p = RTEST(rb_obj_is_kind_of(eobj, rb_cRange));
4316 str = rb_sprintf("(%s%"PRIsVALUE"%s.", range_p ? "(" : "", eobj, range_p ? ")" : "");
4317
4318 rb_str_buf_append(str, rb_id2str(e->meth));
4319
4320 eargs = rb_attr_get(eobj, id_arguments);
4321 if (NIL_P(eargs)) {
4322 eargs = e->args;
4323 }
4324 if (eargs != Qfalse) {
4325 long argc = RARRAY_LEN(eargs);
4326 const VALUE *argv = RARRAY_CONST_PTR(eargs); /* WB: no new reference */
4327
4328 if (argc > 0) {
4329 VALUE kwds = Qnil;
4330
4331 rb_str_buf_cat2(str, "(");
4332
4333 if (RB_TYPE_P(argv[argc-1], T_HASH)) {
4334 int all_key = TRUE;
4335 rb_hash_foreach(argv[argc-1], key_symbol_p, (VALUE)&all_key);
4336 if (all_key) kwds = argv[--argc];
4337 }
4338
4339 while (argc--) {
4340 VALUE arg = *argv++;
4341
4342 rb_str_append(str, rb_inspect(arg));
4343 rb_str_buf_cat2(str, ", ");
4344 }
4345 if (!NIL_P(kwds)) {
4346 rb_hash_foreach(kwds, kwd_append, str);
4347 }
4348 rb_str_set_len(str, RSTRING_LEN(str)-2); /* drop the last ", " */
4349 rb_str_buf_cat2(str, ")");
4350 }
4351 }
4352 RB_GC_GUARD(eargs);
4353
4354 rb_str_buf_cat2(str, ")");
4355
4356 return str;
4357}
4358
4359/*
4360 * call-seq:
4361 * aseq == obj -> true or false
4362 *
4363 * Returns <code>true</code> only if +obj+ is an Enumerator::ArithmeticSequence,
4364 * has equivalent begin, end, step, and exclude_end? settings.
4365 */
4366static VALUE
4367arith_seq_eq(VALUE self, VALUE other)
4368{
4369 if (!RTEST(rb_obj_is_kind_of(other, rb_cArithSeq))) {
4370 return Qfalse;
4371 }
4372
4373 if (!rb_equal(arith_seq_begin(self), arith_seq_begin(other))) {
4374 return Qfalse;
4375 }
4376
4377 if (!rb_equal(arith_seq_end(self), arith_seq_end(other))) {
4378 return Qfalse;
4379 }
4380
4381 if (!rb_equal(arith_seq_step(self), arith_seq_step(other))) {
4382 return Qfalse;
4383 }
4384
4385 if (arith_seq_exclude_end_p(self) != arith_seq_exclude_end_p(other)) {
4386 return Qfalse;
4387 }
4388
4389 return Qtrue;
4390}
4391
4392/*
4393 * call-seq:
4394 * aseq.hash -> integer
4395 *
4396 * Compute a hash-value for this arithmetic sequence.
4397 * Two arithmetic sequences with same begin, end, step, and exclude_end?
4398 * values will generate the same hash-value.
4399 *
4400 * See also Object#hash.
4401 */
4402static VALUE
4403arith_seq_hash(VALUE self)
4404{
4405 st_index_t hash;
4406 VALUE v;
4407
4408 hash = rb_hash_start(arith_seq_exclude_end_p(self));
4409 v = rb_hash(arith_seq_begin(self));
4410 hash = rb_hash_uint(hash, NUM2LONG(v));
4411 v = rb_hash(arith_seq_end(self));
4412 hash = rb_hash_uint(hash, NUM2LONG(v));
4413 v = rb_hash(arith_seq_step(self));
4414 hash = rb_hash_uint(hash, NUM2LONG(v));
4415 hash = rb_hash_end(hash);
4416
4417 return ST2FIX(hash);
4418}
4419
4420#define NUM_GE(x, y) RTEST(rb_num_coerce_relop((x), (y), idGE))
4421
4423 VALUE current;
4424 VALUE end;
4425 VALUE step;
4426 int excl;
4427};
4428
4429/*
4430 * call-seq:
4431 * aseq.each {|i| block } -> aseq
4432 * aseq.each -> aseq
4433 */
4434static VALUE
4435arith_seq_each(VALUE self)
4436{
4437 VALUE c, e, s, len_1, last;
4438 int x;
4439
4440 if (!rb_block_given_p()) return self;
4441
4442 c = arith_seq_begin(self);
4443 e = arith_seq_end(self);
4444 s = arith_seq_step(self);
4445 x = arith_seq_exclude_end_p(self);
4446
4447 if (!RB_TYPE_P(s, T_COMPLEX) && ruby_float_step(c, e, s, x, TRUE)) {
4448 return self;
4449 }
4450
4451 if (NIL_P(e)) {
4452 while (1) {
4453 rb_yield(c);
4454 c = rb_int_plus(c, s);
4455 }
4456
4457 return self;
4458 }
4459
4460 if (rb_equal(s, INT2FIX(0))) {
4461 while (1) {
4462 rb_yield(c);
4463 }
4464
4465 return self;
4466 }
4467
4468 len_1 = num_idiv(num_minus(e, c), s);
4469 last = num_plus(c, num_mul(s, len_1));
4470 if (x && rb_equal(last, e)) {
4471 last = num_minus(last, s);
4472 }
4473
4474 if (rb_num_negative_int_p(s)) {
4475 while (NUM_GE(c, last)) {
4476 rb_yield(c);
4477 c = num_plus(c, s);
4478 }
4479 }
4480 else {
4481 while (NUM_GE(last, c)) {
4482 rb_yield(c);
4483 c = num_plus(c, s);
4484 }
4485 }
4486
4487 return self;
4488}
4489
4490/*
4491 * call-seq:
4492 * aseq.size -> num or nil
4493 *
4494 * Returns the number of elements in this arithmetic sequence if it is a finite
4495 * sequence. Otherwise, returns <code>nil</code>.
4496 */
4497static VALUE
4498arith_seq_size(VALUE self)
4499{
4500 VALUE b, e, s, len_1, len, last;
4501 int x;
4502
4503 b = arith_seq_begin(self);
4504 e = arith_seq_end(self);
4505 s = arith_seq_step(self);
4506 x = arith_seq_exclude_end_p(self);
4507
4508 if (RB_FLOAT_TYPE_P(b) || RB_FLOAT_TYPE_P(e) || RB_FLOAT_TYPE_P(s)) {
4509 double ee, n;
4510
4511 if (NIL_P(e)) {
4512 if (rb_num_negative_int_p(s)) {
4513 ee = -HUGE_VAL;
4514 }
4515 else {
4516 ee = HUGE_VAL;
4517 }
4518 }
4519 else {
4520 ee = NUM2DBL(e);
4521 }
4522
4523 n = ruby_float_step_size(NUM2DBL(b), ee, NUM2DBL(s), x);
4524 if (isinf(n)) return DBL2NUM(n);
4525 if (POSFIXABLE(n)) return LONG2FIX((long)n);
4526 return rb_dbl2big(n);
4527 }
4528
4529 if (NIL_P(e)) {
4530 return DBL2NUM(HUGE_VAL);
4531 }
4532
4533 if (!rb_obj_is_kind_of(s, rb_cNumeric)) {
4534 s = rb_to_int(s);
4535 }
4536
4537 if (rb_equal(s, INT2FIX(0))) {
4538 return DBL2NUM(HUGE_VAL);
4539 }
4540
4541 len_1 = rb_int_idiv(rb_int_minus(e, b), s);
4542 if (rb_num_negative_int_p(len_1)) {
4543 return INT2FIX(0);
4544 }
4545
4546 last = rb_int_plus(b, rb_int_mul(s, len_1));
4547 if (x && rb_equal(last, e)) {
4548 len = len_1;
4549 }
4550 else {
4551 len = rb_int_plus(len_1, INT2FIX(1));
4552 }
4553
4554 return len;
4555}
4556
4557#define sym(name) ID2SYM(rb_intern_const(name))
4558void
4559InitVM_Enumerator(void)
4560{
4561 ID id_private = rb_intern_const("private");
4562
4563 rb_define_method(rb_mKernel, "to_enum", obj_to_enum, -1);
4564 rb_define_method(rb_mKernel, "enum_for", obj_to_enum, -1);
4565
4566 rb_cEnumerator = rb_define_class("Enumerator", rb_cObject);
4568
4569 rb_define_alloc_func(rb_cEnumerator, enumerator_allocate);
4570 rb_define_method(rb_cEnumerator, "initialize", enumerator_initialize, -1);
4571 rb_define_method(rb_cEnumerator, "initialize_copy", enumerator_init_copy, 1);
4572 rb_define_method(rb_cEnumerator, "each", enumerator_each, -1);
4573 rb_define_method(rb_cEnumerator, "each_with_index", enumerator_each_with_index, 0);
4574 rb_define_method(rb_cEnumerator, "each_with_object", enumerator_with_object, 1);
4575 rb_define_method(rb_cEnumerator, "with_index", enumerator_with_index, -1);
4576 rb_define_method(rb_cEnumerator, "with_object", enumerator_with_object, 1);
4577 rb_define_method(rb_cEnumerator, "next_values", enumerator_next_values, 0);
4578 rb_define_method(rb_cEnumerator, "peek_values", enumerator_peek_values_m, 0);
4579 rb_define_method(rb_cEnumerator, "next", enumerator_next, 0);
4580 rb_define_method(rb_cEnumerator, "peek", enumerator_peek, 0);
4581 rb_define_method(rb_cEnumerator, "feed", enumerator_feed, 1);
4582 rb_define_method(rb_cEnumerator, "rewind", enumerator_rewind, 0);
4583 rb_define_method(rb_cEnumerator, "inspect", enumerator_inspect, 0);
4584 rb_define_method(rb_cEnumerator, "size", enumerator_size, 0);
4585 rb_define_method(rb_cEnumerator, "+", enumerator_plus, 1);
4587
4588 /* Lazy */
4590 rb_define_method(rb_mEnumerable, "lazy", enumerable_lazy, 0);
4591
4592 rb_define_alias(rb_cLazy, "_enumerable_map", "map");
4593 rb_define_alias(rb_cLazy, "_enumerable_collect", "collect");
4594 rb_define_alias(rb_cLazy, "_enumerable_flat_map", "flat_map");
4595 rb_define_alias(rb_cLazy, "_enumerable_collect_concat", "collect_concat");
4596 rb_define_alias(rb_cLazy, "_enumerable_select", "select");
4597 rb_define_alias(rb_cLazy, "_enumerable_find_all", "find_all");
4598 rb_define_alias(rb_cLazy, "_enumerable_filter", "filter");
4599 rb_define_alias(rb_cLazy, "_enumerable_filter_map", "filter_map");
4600 rb_define_alias(rb_cLazy, "_enumerable_reject", "reject");
4601 rb_define_alias(rb_cLazy, "_enumerable_grep", "grep");
4602 rb_define_alias(rb_cLazy, "_enumerable_grep_v", "grep_v");
4603 rb_define_alias(rb_cLazy, "_enumerable_zip", "zip");
4604 rb_define_alias(rb_cLazy, "_enumerable_take", "take");
4605 rb_define_alias(rb_cLazy, "_enumerable_take_while", "take_while");
4606 rb_define_alias(rb_cLazy, "_enumerable_drop", "drop");
4607 rb_define_alias(rb_cLazy, "_enumerable_drop_while", "drop_while");
4608 rb_define_alias(rb_cLazy, "_enumerable_uniq", "uniq");
4609 rb_define_private_method(rb_cLazy, "_enumerable_with_index", enumerator_with_index, -1);
4610 rb_define_alias(rb_cLazy, "_enumerable_each_with_index", "each_with_index");
4611
4612 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_map"));
4613 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_collect"));
4614 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_flat_map"));
4615 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_collect_concat"));
4616 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_select"));
4617 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_find_all"));
4618 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_filter"));
4619 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_filter_map"));
4620 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_reject"));
4621 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_grep"));
4622 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_grep_v"));
4623 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_zip"));
4624 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_take"));
4625 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_take_while"));
4626 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_drop"));
4627 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_drop_while"));
4628 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_uniq"));
4629 rb_funcall(rb_cLazy, id_private, 1, sym("_enumerable_each_with_index"));
4630
4631 rb_define_method(rb_cLazy, "initialize", lazy_initialize, -1);
4632 rb_define_method(rb_cLazy, "to_enum", lazy_to_enum, -1);
4633 rb_define_method(rb_cLazy, "enum_for", lazy_to_enum, -1);
4634 rb_define_method(rb_cLazy, "eager", lazy_eager, 0);
4635 rb_define_method(rb_cLazy, "map", lazy_map, 0);
4636 rb_define_method(rb_cLazy, "collect", lazy_map, 0);
4637 rb_define_method(rb_cLazy, "flat_map", lazy_flat_map, 0);
4638 rb_define_method(rb_cLazy, "collect_concat", lazy_flat_map, 0);
4639 rb_define_method(rb_cLazy, "select", lazy_select, 0);
4640 rb_define_method(rb_cLazy, "find_all", lazy_select, 0);
4641 rb_define_method(rb_cLazy, "filter", lazy_select, 0);
4642 rb_define_method(rb_cLazy, "filter_map", lazy_filter_map, 0);
4643 rb_define_method(rb_cLazy, "reject", lazy_reject, 0);
4644 rb_define_method(rb_cLazy, "grep", lazy_grep, 1);
4645 rb_define_method(rb_cLazy, "grep_v", lazy_grep_v, 1);
4646 rb_define_method(rb_cLazy, "zip", lazy_zip, -1);
4647 rb_define_method(rb_cLazy, "take", lazy_take, 1);
4648 rb_define_method(rb_cLazy, "take_while", lazy_take_while, 0);
4649 rb_define_method(rb_cLazy, "drop", lazy_drop, 1);
4650 rb_define_method(rb_cLazy, "drop_while", lazy_drop_while, 0);
4651 rb_define_method(rb_cLazy, "lazy", lazy_lazy, 0);
4652 rb_define_method(rb_cLazy, "chunk", lazy_super, -1);
4653 rb_define_method(rb_cLazy, "slice_before", lazy_super, -1);
4654 rb_define_method(rb_cLazy, "slice_after", lazy_super, -1);
4655 rb_define_method(rb_cLazy, "slice_when", lazy_super, -1);
4656 rb_define_method(rb_cLazy, "chunk_while", lazy_super, -1);
4657 rb_define_method(rb_cLazy, "uniq", lazy_uniq, 0);
4658 rb_define_method(rb_cLazy, "compact", lazy_compact, 0);
4659 rb_define_method(rb_cLazy, "with_index", lazy_with_index, -1);
4660 rb_define_method(rb_cLazy, "each_with_index", lazy_each_with_index, 0);
4661
4662 lazy_use_super_method = rb_hash_new_with_size(19);
4663 rb_hash_aset(lazy_use_super_method, sym("map"), sym("_enumerable_map"));
4664 rb_hash_aset(lazy_use_super_method, sym("collect"), sym("_enumerable_collect"));
4665 rb_hash_aset(lazy_use_super_method, sym("flat_map"), sym("_enumerable_flat_map"));
4666 rb_hash_aset(lazy_use_super_method, sym("collect_concat"), sym("_enumerable_collect_concat"));
4667 rb_hash_aset(lazy_use_super_method, sym("select"), sym("_enumerable_select"));
4668 rb_hash_aset(lazy_use_super_method, sym("find_all"), sym("_enumerable_find_all"));
4669 rb_hash_aset(lazy_use_super_method, sym("filter"), sym("_enumerable_filter"));
4670 rb_hash_aset(lazy_use_super_method, sym("filter_map"), sym("_enumerable_filter_map"));
4671 rb_hash_aset(lazy_use_super_method, sym("reject"), sym("_enumerable_reject"));
4672 rb_hash_aset(lazy_use_super_method, sym("grep"), sym("_enumerable_grep"));
4673 rb_hash_aset(lazy_use_super_method, sym("grep_v"), sym("_enumerable_grep_v"));
4674 rb_hash_aset(lazy_use_super_method, sym("zip"), sym("_enumerable_zip"));
4675 rb_hash_aset(lazy_use_super_method, sym("take"), sym("_enumerable_take"));
4676 rb_hash_aset(lazy_use_super_method, sym("take_while"), sym("_enumerable_take_while"));
4677 rb_hash_aset(lazy_use_super_method, sym("drop"), sym("_enumerable_drop"));
4678 rb_hash_aset(lazy_use_super_method, sym("drop_while"), sym("_enumerable_drop_while"));
4679 rb_hash_aset(lazy_use_super_method, sym("uniq"), sym("_enumerable_uniq"));
4680 rb_hash_aset(lazy_use_super_method, sym("with_index"), sym("_enumerable_with_index"));
4681 rb_hash_aset(lazy_use_super_method, sym("each_with_index"), sym("_enumerable_each_with_index"));
4682 rb_obj_freeze(lazy_use_super_method);
4683 rb_vm_register_global_object(lazy_use_super_method);
4684
4685#if 0 /* for RDoc */
4686 rb_define_method(rb_cLazy, "to_a", lazy_to_a, 0);
4687 rb_define_method(rb_cLazy, "chunk", lazy_chunk, 0);
4688 rb_define_method(rb_cLazy, "chunk_while", lazy_chunk_while, 0);
4689 rb_define_method(rb_cLazy, "slice_after", lazy_slice_after, 0);
4690 rb_define_method(rb_cLazy, "slice_before", lazy_slice_before, 0);
4691 rb_define_method(rb_cLazy, "slice_when", lazy_slice_when, 0);
4692#endif
4693 rb_define_alias(rb_cLazy, "force", "to_a");
4694
4696 rb_define_method(rb_eStopIteration, "result", stop_result, 0);
4697
4698 /* Generator */
4699 rb_cGenerator = rb_define_class_under(rb_cEnumerator, "Generator", rb_cObject);
4700 rb_include_module(rb_cGenerator, rb_mEnumerable);
4701 rb_define_alloc_func(rb_cGenerator, generator_allocate);
4702 rb_define_method(rb_cGenerator, "initialize", generator_initialize, -1);
4703 rb_define_method(rb_cGenerator, "initialize_copy", generator_init_copy, 1);
4704 rb_define_method(rb_cGenerator, "each", generator_each, -1);
4705
4706 /* Yielder */
4707 rb_cYielder = rb_define_class_under(rb_cEnumerator, "Yielder", rb_cObject);
4708 rb_define_alloc_func(rb_cYielder, yielder_allocate);
4709 rb_define_method(rb_cYielder, "initialize", yielder_initialize, 0);
4710 rb_define_method(rb_cYielder, "yield", yielder_yield, -2);
4711 rb_define_method(rb_cYielder, "<<", yielder_yield_push, 1);
4712 rb_define_method(rb_cYielder, "to_proc", yielder_to_proc, 0);
4713
4714 /* Producer */
4715 rb_cEnumProducer = rb_define_class_under(rb_cEnumerator, "Producer", rb_cObject);
4716 rb_define_alloc_func(rb_cEnumProducer, producer_allocate);
4717 rb_define_method(rb_cEnumProducer, "each", producer_each, 0);
4718 rb_define_singleton_method(rb_cEnumerator, "produce", enumerator_s_produce, -1);
4719
4720 /* Chain */
4721 rb_cEnumChain = rb_define_class_under(rb_cEnumerator, "Chain", rb_cEnumerator);
4722 rb_define_alloc_func(rb_cEnumChain, enum_chain_allocate);
4723 rb_define_method(rb_cEnumChain, "initialize", enum_chain_initialize, -2);
4724 rb_define_method(rb_cEnumChain, "initialize_copy", enum_chain_init_copy, 1);
4725 rb_define_method(rb_cEnumChain, "each", enum_chain_each, -1);
4726 rb_define_method(rb_cEnumChain, "size", enum_chain_size, 0);
4727 rb_define_method(rb_cEnumChain, "rewind", enum_chain_rewind, 0);
4728 rb_define_method(rb_cEnumChain, "inspect", enum_chain_inspect, 0);
4729 rb_undef_method(rb_cEnumChain, "feed");
4730 rb_undef_method(rb_cEnumChain, "next");
4731 rb_undef_method(rb_cEnumChain, "next_values");
4732 rb_undef_method(rb_cEnumChain, "peek");
4733 rb_undef_method(rb_cEnumChain, "peek_values");
4734
4735 /* Product */
4736 rb_cEnumProduct = rb_define_class_under(rb_cEnumerator, "Product", rb_cEnumerator);
4737 rb_define_alloc_func(rb_cEnumProduct, enum_product_allocate);
4738 rb_define_method(rb_cEnumProduct, "initialize", enum_product_initialize, -1);
4739 rb_define_method(rb_cEnumProduct, "initialize_copy", enum_product_init_copy, 1);
4740 rb_define_method(rb_cEnumProduct, "each", enum_product_each, 0);
4741 rb_define_method(rb_cEnumProduct, "size", enum_product_size, 0);
4742 rb_define_method(rb_cEnumProduct, "rewind", enum_product_rewind, 0);
4743 rb_define_method(rb_cEnumProduct, "inspect", enum_product_inspect, 0);
4744 rb_undef_method(rb_cEnumProduct, "feed");
4745 rb_undef_method(rb_cEnumProduct, "next");
4746 rb_undef_method(rb_cEnumProduct, "next_values");
4747 rb_undef_method(rb_cEnumProduct, "peek");
4748 rb_undef_method(rb_cEnumProduct, "peek_values");
4749 rb_define_singleton_method(rb_cEnumerator, "product", enumerator_s_product, -1);
4750
4751 /* ArithmeticSequence */
4752 rb_cArithSeq = rb_define_class_under(rb_cEnumerator, "ArithmeticSequence", rb_cEnumerator);
4753 rb_undef_alloc_func(rb_cArithSeq);
4754 rb_undef_method(CLASS_OF(rb_cArithSeq), "new");
4755 rb_define_method(rb_cArithSeq, "begin", arith_seq_begin, 0);
4756 rb_define_method(rb_cArithSeq, "end", arith_seq_end, 0);
4757 rb_define_method(rb_cArithSeq, "exclude_end?", arith_seq_exclude_end, 0);
4758 rb_define_method(rb_cArithSeq, "step", arith_seq_step, 0);
4759 rb_define_method(rb_cArithSeq, "first", arith_seq_first, -1);
4760 rb_define_method(rb_cArithSeq, "last", arith_seq_last, -1);
4761 rb_define_method(rb_cArithSeq, "inspect", arith_seq_inspect, 0);
4762 rb_define_method(rb_cArithSeq, "==", arith_seq_eq, 1);
4763 rb_define_method(rb_cArithSeq, "===", arith_seq_eq, 1);
4764 rb_define_method(rb_cArithSeq, "eql?", arith_seq_eq, 1);
4765 rb_define_method(rb_cArithSeq, "hash", arith_seq_hash, 0);
4766 rb_define_method(rb_cArithSeq, "each", arith_seq_each, 0);
4767 rb_define_method(rb_cArithSeq, "size", arith_seq_size, 0);
4768
4769 rb_provide("enumerator.so"); /* for backward compatibility */
4770}
4771#undef sym
4772
4773void
4774Init_Enumerator(void)
4775{
4776 id_rewind = rb_intern_const("rewind");
4777 id_next = rb_intern_const("next");
4778 id_result = rb_intern_const("result");
4779 id_receiver = rb_intern_const("receiver");
4780 id_arguments = rb_intern_const("arguments");
4781 id_memo = rb_intern_const("memo");
4782 id_method = rb_intern_const("method");
4783 id_force = rb_intern_const("force");
4784 id_to_enum = rb_intern_const("to_enum");
4785 id_each_entry = rb_intern_const("each_entry");
4786 sym_each = ID2SYM(id_each);
4787 sym_yield = ID2SYM(rb_intern_const("yield"));
4788
4789 InitVM(Enumerator);
4790}
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1695
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1488
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1519
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2868
void rb_need_block(void)
Declares that the current method needs a block.
Definition eval.c:1048
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2680
int rb_scan_args_kw(int kw_flag, int argc, const VALUE *argv, const char *fmt,...)
Identical to rb_scan_args(), except it also accepts kw_splat.
Definition class.c:3171
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3158
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1040
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1027
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2947
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1683
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#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 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 UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define rb_exc_new2
Old name of rb_exc_new_cstr.
Definition error.h:37
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#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 ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
#define POSFIXABLE
Old name of RB_POSFIXABLE.
Definition fixnum.h:29
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#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 rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
VALUE rb_rescue2(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2,...)
An equivalent of rescue clause.
Definition eval.c:1056
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:664
void rb_iter_break(void)
Breaks from a block.
Definition vm.c:2306
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1435
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
VALUE rb_eStopIteration
StopIteration exception.
Definition enumerator.c:181
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1482
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1433
VALUE rb_mKernel
Kernel module.
Definition object.c:60
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:27
VALUE rb_cEnumerator
Enumerator class.
Definition enumerator.c:164
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:100
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:198
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:582
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:686
VALUE rb_cRange
Range class.
Definition range.c:31
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:176
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:923
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1342
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3306
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1119
VALUE rb_funcall_with_block(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE procval)
Identical to rb_funcallv_public(), except you can pass a block.
Definition vm_eval.c:1196
#define rb_funcall2
Definition eval.h:207
VALUE rb_call_super(int argc, const VALUE *argv)
This resembles ruby's super.
Definition vm_eval.c:362
VALUE rb_ary_new_from_values(long n, const VALUE *elts)
Identical to rb_ary_new_from_args(), except how objects are passed.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_cat(VALUE ary, const VALUE *train, long len)
Destructively appends multiple elements at the end of the array.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_resize(VALUE ary, long len)
Expands or shrinks the passed array to the passed length.
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
VALUE rb_enumerator_size_func(VALUE recv, VALUE argv, VALUE eobj)
This is the type of functions that rb_enumeratorize_with_size() expects.
Definition enumerator.h:45
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:695
VALUE rb_num_coerce_cmp(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_bin(), except for return values.
Definition numeric.c:486
VALUE rb_obj_method(VALUE recv, VALUE mid)
Creates a method object.
Definition proc.c:2290
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:994
VALUE rb_proc_call_with_block(VALUE recv, int argc, const VALUE *argv, VALUE proc)
Identical to rb_proc_call(), except you can additionally pass another proc object,...
Definition proc.c:1180
VALUE rb_proc_call_kw(VALUE recv, VALUE args, int kw_splat)
Identical to rb_proc_call(), except you can specify how to handle the last element of the given array...
Definition proc.c:1136
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:126
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1862
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:943
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:946
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3833
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2014
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition string.c:3797
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3418
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1784
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5616
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2030
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition variable.c:1505
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:380
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3480
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1719
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:688
VALUE rb_check_funcall_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
Identical to rb_check_funcall(), except you can specify how to handle the last element of the given a...
Definition vm_eval.c:682
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:994
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:12779
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:12769
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition io.h:2
int len
Length of the buffer.
Definition io.h:8
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition iterator.h:58
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
Definition vm_eval.c:1397
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:1419
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1374
VALUE rb_yield_values_kw(int n, const VALUE *argv, int kw_splat)
Identical to rb_yield_values2(), except you can specify how to handle the last element of the given a...
Definition vm_eval.c:1425
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:1572
#define rb_long2int
Just another name of rb_long2int_inline.
Definition long.h:62
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE rb_block_call(VALUE q, ID w, int e, const VALUE *r, type *t, VALUE y)
Call a method with a block.
VALUE rb_proc_new(type *q, VALUE w)
Creates a rb_cProc instance.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:79
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:80
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:649
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:205
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:508
#define InitVM(ext)
This macro is for internal use.
Definition ruby.h:231
#define RB_SCAN_ARGS_LAST_HASH_KEYWORDS
Treat a final argument as keywords if it is a hash, and not as keywords otherwise.
Definition scan_args.h:59
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition scan_args.h:78
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
MEMO.
Definition imemo.h:105
Definition enumerator.c:237
Decomposed Enumerator::ArithmeicSequence.
Definition enumerator.h:53
int exclude_end
Whether the endpoint is open or closed.
Definition enumerator.h:57
VALUE end
"Right" or "highest" endpoint of the sequence.
Definition enumerator.h:55
VALUE step
Step between a sequence.
Definition enumerator.h:56
VALUE begin
"Left" or "lowest" endpoint of the sequence.
Definition enumerator.h:54
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