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