Ruby 4.1.0dev (2026-10-01 revision 528c70471f4c9fbac6d924e684fc397617bdf4be)
enumerator.c (528c70471f4c9fbac6d924e684fc397617bdf4be)
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, long);
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 long 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_LONG
631 /* check int range overflow */
632 rb_long2int(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 long 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 long 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 long 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, long 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, long 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, long 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 long 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, long 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, long memo_index)
2109{
2110 VALUE value = lazyenum_yield_values(proc_entry, result);
2111 VALUE ary = 0;
2112 const long 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 long 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, long 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, long 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, long 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, long 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, long 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, long 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, long 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, long 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 long i, count = NIL_P(memo) ? 0 : NUM2LONG(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, LONG2NUM(++count));
2385 return result;
2386}
2387
2388static struct MEMO *
2389lazy_zip_func(VALUE proc_entry, struct MEMO *result, VALUE memos, long 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 long 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 }
2450 ary = rb_ary_new4(argc, argv);
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, long memo_index)
2462{
2463 long 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 = NUM2LONG(memo);
2472 if (--remain == 0) LAZY_MEMO_SET_BREAK(result);
2473 rb_ary_store(memos, memo_index, LONG2NUM(remain));
2474 return result;
2475}
2476
2477static VALUE
2478lazy_take_size(VALUE entry, VALUE receiver)
2479{
2480 long len = NUM2LONG(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 LONG2NUM(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 long len = NUM2LONG(n);
2508
2509 if (len < 0) {
2510 rb_raise(rb_eArgError, "attempt to take negative size");
2511 }
2512
2513 n = LONG2NUM(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, long 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 long len = NUM2LONG(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 LONG2FIX(len < 0 ? 0 : len);
2556 }
2557 return rb_funcall(receiver, '-', 1, LONG2NUM(len));
2558}
2559
2560static struct MEMO *
2561lazy_drop_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2562{
2563 long 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 = NUM2LONG(memo);
2571 if (remain > 0) {
2572 --remain;
2573 rb_ary_store(memos, memo_index, LONG2NUM(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 long len = NUM2LONG(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, long 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, long 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, long 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, long 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, long 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, long 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, LONG2NUM(NUM2LONG(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 return lazy_with_index_from(obj, LONG2NUM(0));
2774}
2775
2776/*
2777 * call-seq:
2778 * lazy.with_index(offset = 0) {|(*args), idx| block }
2779 * lazy.with_index(offset = 0)
2780 *
2781 * If a block is given, returns a lazy enumerator that will
2782 * iterate over the given block for each element
2783 * with an index, which starts from +offset+, and returns a
2784 * lazy enumerator that yields the same values (without the index).
2785 *
2786 * If a block is not given, returns a new lazy enumerator that
2787 * includes the index, starting from +offset+.
2788 *
2789 * +offset+:: the starting index to use
2790 *
2791 * See Enumerator#with_index.
2792 */
2793static VALUE
2794lazy_with_index(int argc, VALUE *argv, VALUE obj)
2795{
2796 VALUE memo;
2797
2798 rb_scan_args(argc, argv, "01", &memo);
2799 if (NIL_P(memo))
2800 memo = LONG2NUM(0);
2801
2802 return lazy_with_index_from(obj, memo);
2803}
2804
2805static struct MEMO *
2806lazy_tap_each_proc(VALUE proc_entry, struct MEMO *result, VALUE memos, long memo_index)
2807{
2808 struct proc_entry *entry = proc_entry_ptr(proc_entry);
2809
2810 rb_proc_call_with_block(entry->proc, 1, &result->memo_value, Qnil);
2811
2812 return result;
2813}
2814
2815static const lazyenum_funcs lazy_tap_each_funcs = {
2816 lazy_tap_each_proc, 0,
2817};
2818
2819/*
2820 * call-seq:
2821 * lazy.tap_each { |item| ... } -> lazy_enumerator
2822 *
2823 * Passes each element through to the block for side effects only,
2824 * without modifying the element or affecting the enumeration.
2825 * Returns a new lazy enumerator.
2826 *
2827 * This is useful for debugging or logging inside lazy chains,
2828 * without breaking laziness or misusing +map+.
2829 *
2830 * (1..).lazy
2831 * .tap_each { |x| puts "got #{x}" }
2832 * .select(&:even?)
2833 * .first(3)
2834 * # prints: got 1, got 2, ..., got 6
2835 * # returns: [2, 4, 6]
2836 *
2837 * Similar in intent to Java's Stream#peek.
2838 */
2839
2840static VALUE
2841lazy_tap_each(VALUE obj)
2842{
2843 if (!rb_block_given_p())
2844 {
2845 rb_raise(rb_eArgError, "tried to call lazy tap_each without a block");
2846 }
2847
2848 return lazy_add_method(obj, 0, 0, Qnil, Qnil, &lazy_tap_each_funcs);
2849}
2850
2851#if 0 /* for RDoc */
2852
2853/*
2854 * call-seq:
2855 * lazy.chunk { |elt| ... } -> lazy_enumerator
2856 *
2857 * Like Enumerable#chunk, but chains operation to be lazy-evaluated.
2858 */
2859static VALUE
2860lazy_chunk(VALUE self)
2861{
2862}
2863
2864/*
2865 * call-seq:
2866 * lazy.chunk_while {|elt_before, elt_after| bool } -> lazy_enumerator
2867 *
2868 * Like Enumerable#chunk_while, but chains operation to be lazy-evaluated.
2869 */
2870static VALUE
2871lazy_chunk_while(VALUE self)
2872{
2873}
2874
2875/*
2876 * call-seq:
2877 * lazy.slice_after(pattern) -> lazy_enumerator
2878 * lazy.slice_after { |elt| bool } -> lazy_enumerator
2879 *
2880 * Like Enumerable#slice_after, but chains operation to be lazy-evaluated.
2881 */
2882static VALUE
2883lazy_slice_after(VALUE self)
2884{
2885}
2886
2887/*
2888 * call-seq:
2889 * lazy.slice_before(pattern) -> lazy_enumerator
2890 * lazy.slice_before { |elt| bool } -> lazy_enumerator
2891 *
2892 * Like Enumerable#slice_before, but chains operation to be lazy-evaluated.
2893 */
2894static VALUE
2895lazy_slice_before(VALUE self)
2896{
2897}
2898
2899/*
2900 * call-seq:
2901 * lazy.slice_when {|elt_before, elt_after| bool } -> lazy_enumerator
2902 *
2903 * Like Enumerable#slice_when, but chains operation to be lazy-evaluated.
2904 */
2905static VALUE
2906lazy_slice_when(VALUE self)
2907{
2908}
2909# endif
2910
2911static VALUE
2912lazy_super(int argc, VALUE *argv, VALUE lazy)
2913{
2914 return enumerable_lazy(rb_call_super(argc, argv));
2915}
2916
2917/*
2918 * call-seq:
2919 * enum.lazy -> lazy_enumerator
2920 *
2921 * Returns self.
2922 */
2923
2924static VALUE
2925lazy_lazy(VALUE obj)
2926{
2927 return obj;
2928}
2929
2930/*
2931 * Document-class: StopIteration
2932 *
2933 * Raised to stop the iteration, in particular by Enumerator#next. It is
2934 * rescued by Kernel#loop.
2935 *
2936 * loop do
2937 * puts "Hello"
2938 * raise StopIteration
2939 * puts "World"
2940 * end
2941 * puts "Done!"
2942 *
2943 * <em>produces:</em>
2944 *
2945 * Hello
2946 * Done!
2947 */
2948
2949/*
2950 * call-seq:
2951 * result -> value
2952 *
2953 * Returns the return value of the iterator.
2954 *
2955 * o = Object.new
2956 * def o.each
2957 * yield 1
2958 * yield 2
2959 * yield 3
2960 * 100
2961 * end
2962 *
2963 * e = o.to_enum
2964 *
2965 * puts e.next #=> 1
2966 * puts e.next #=> 2
2967 * puts e.next #=> 3
2968 *
2969 * begin
2970 * e.next
2971 * rescue StopIteration => ex
2972 * puts ex.result #=> 100
2973 * end
2974 *
2975 */
2976
2977static VALUE
2978stop_result(VALUE self)
2979{
2980 return rb_attr_get(self, id_result);
2981}
2982
2983/*
2984 * Producer
2985 */
2986
2987static void
2988producer_mark_and_move(void *p)
2989{
2990 struct producer *ptr = p;
2991 rb_gc_mark_and_move(&ptr->init);
2992 rb_gc_mark_and_move(&ptr->proc);
2993 rb_gc_mark_and_move(&ptr->size);
2994}
2995
2996#define producer_free RUBY_TYPED_DEFAULT_FREE
2997
2998static size_t
2999producer_memsize(const void *p)
3000{
3001 return sizeof(struct producer);
3002}
3003
3004static const rb_data_type_t producer_data_type = {
3005 "producer",
3006 {
3007 producer_mark_and_move,
3008 producer_free,
3009 producer_memsize,
3010 producer_mark_and_move,
3011 },
3012 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
3013};
3014
3015static struct producer *
3016producer_ptr(VALUE obj)
3017{
3018 struct producer *ptr;
3019
3020 TypedData_Get_Struct(obj, struct producer, &producer_data_type, ptr);
3021 if (!ptr || UNDEF_P(ptr->proc)) {
3022 rb_raise(rb_eArgError, "uninitialized producer");
3023 }
3024 return ptr;
3025}
3026
3027/* :nodoc: */
3028static VALUE
3029producer_allocate(VALUE klass)
3030{
3031 struct producer *ptr;
3032 VALUE obj;
3033
3034 obj = TypedData_Make_Struct(klass, struct producer, &producer_data_type, ptr);
3035 ptr->init = Qundef;
3036 ptr->proc = Qundef;
3037 ptr->size = Qnil;
3038
3039 return obj;
3040}
3041
3042static VALUE
3043producer_init(VALUE obj, VALUE init, VALUE proc, VALUE size)
3044{
3045 struct producer *ptr;
3046
3047 TypedData_Get_Struct(obj, struct producer, &producer_data_type, ptr);
3048
3049 if (!ptr) {
3050 rb_raise(rb_eArgError, "unallocated producer");
3051 }
3052
3053 RB_OBJ_WRITE(obj, &ptr->init, init);
3054 RB_OBJ_WRITE(obj, &ptr->proc, proc);
3055 RB_OBJ_WRITE(obj, &ptr->size, size);
3056
3057 return obj;
3058}
3059
3060static VALUE
3061producer_each_stop(VALUE dummy, VALUE exc)
3062{
3063 return rb_attr_get(exc, id_result);
3064}
3065
3066NORETURN(static VALUE producer_each_i(VALUE obj));
3067
3068static VALUE
3069producer_each_i(VALUE obj)
3070{
3071 struct producer *ptr;
3072 VALUE init, proc, curr;
3073
3074 ptr = producer_ptr(obj);
3075 init = ptr->init;
3076 proc = ptr->proc;
3077
3078 if (UNDEF_P(init)) {
3079 curr = Qnil;
3080 }
3081 else {
3082 rb_yield(init);
3083 curr = init;
3084 }
3085
3086 for (;;) {
3087 curr = rb_funcall(proc, id_call, 1, curr);
3088 rb_yield(curr);
3089 }
3090
3092}
3093
3094/* :nodoc: */
3095static VALUE
3096producer_each(VALUE obj)
3097{
3098 rb_need_block();
3099
3100 return rb_rescue2(producer_each_i, obj, producer_each_stop, (VALUE)0, rb_eStopIteration, (VALUE)0);
3101}
3102
3103static VALUE
3104producer_size(VALUE obj, VALUE args, VALUE eobj)
3105{
3106 struct producer *ptr = producer_ptr(obj);
3107 VALUE size = ptr->size;
3108
3109 if (NIL_P(size)) return Qnil;
3110 if (RB_INTEGER_TYPE_P(size) || RB_FLOAT_TYPE_P(size)) return size;
3111
3112 return rb_funcall(size, id_call, 0);
3113}
3114
3115/*
3116 * call-seq:
3117 * Enumerator.produce(initial = nil, size: nil) { |prev| block } -> enumerator
3118 *
3119 * Creates an infinite enumerator from any block, just called over and
3120 * over. The result of the previous iteration is passed to the next one.
3121 * If +initial+ is provided, it is passed to the first iteration, and
3122 * becomes the first element of the enumerator; if it is not provided,
3123 * the first iteration receives +nil+, and its result becomes the first
3124 * element of the iterator.
3125 *
3126 * Raising StopIteration from the block stops an iteration.
3127 *
3128 * Enumerator.produce(1, &:succ) # => enumerator of 1, 2, 3, 4, ....
3129 *
3130 * Enumerator.produce { rand(10) } # => infinite random number sequence
3131 *
3132 * ancestors = Enumerator.produce(node) { |prev| node = prev.parent or raise StopIteration }
3133 * enclosing_section = ancestors.find { |n| n.type == :section }
3134 *
3135 * Using ::produce together with Enumerable methods like Enumerable#detect,
3136 * Enumerable#slice_after, Enumerable#take_while can provide Enumerator-based alternatives
3137 * for +while+ and +until+ cycles:
3138 *
3139 * # Find next Tuesday
3140 * require "date"
3141 * Enumerator.produce(Date.today, &:succ).detect(&:tuesday?)
3142 *
3143 * # Simple lexer:
3144 * require "strscan"
3145 * scanner = StringScanner.new("7+38/6")
3146 * PATTERN = %r{\d+|[-/+*]}
3147 * Enumerator.produce { scanner.scan(PATTERN) }.slice_after { scanner.eos? }.first
3148 * # => ["7", "+", "38", "/", "6"]
3149 *
3150 * The optional +size+ keyword argument specifies the size of the enumerator,
3151 * which can be retrieved by Enumerator#size. It can be an integer,
3152 * +Float::INFINITY+, a callable object (such as a lambda), or +nil+ to
3153 * indicate unknown size. When not specified, the size defaults to
3154 * +Float::INFINITY+.
3155 *
3156 * # Infinite enumerator
3157 * enum = Enumerator.produce(1, size: Float::INFINITY, &:succ)
3158 * enum.size # => Float::INFINITY
3159 *
3160 * # Finite enumerator with known/computable size
3161 * abs_dir = File.expand_path("./baz") # => "/foo/bar/baz"
3162 * traverser = Enumerator.produce(abs_dir, size: -> { abs_dir.count("/") + 1 }) {
3163 * raise StopIteration if it == "/"
3164 * File.dirname(it)
3165 * }
3166 * traverser.size # => 4
3167 *
3168 * # Finite enumerator with unknown size
3169 * calendar = Enumerator.produce(Date.today, size: nil) {
3170 * it.monday? ? raise(StopIteration) : it + 1
3171 * }
3172 * calendar.size # => nil
3173 */
3174static VALUE
3175enumerator_s_produce(int argc, VALUE *argv, VALUE klass)
3176{
3177 VALUE init, producer, opts, size;
3178 ID keyword_ids[1];
3179
3180 if (!rb_block_given_p()) rb_raise(rb_eArgError, "no block given");
3181
3182 keyword_ids[0] = rb_intern("size");
3183 rb_scan_args_kw(RB_SCAN_ARGS_LAST_HASH_KEYWORDS, argc, argv, "01:", &init, &opts);
3184 rb_get_kwargs(opts, keyword_ids, 0, 1, &size);
3185
3186 size = UNDEF_P(size) ? DBL2NUM(HUGE_VAL) : convert_to_feasible_size_value(size);
3187
3188 if (argc == 0 || (argc == 1 && !NIL_P(opts))) {
3189 init = Qundef;
3190 }
3191
3192 producer = producer_init(producer_allocate(rb_cEnumProducer), init, rb_block_proc(), size);
3193
3194 return rb_enumeratorize_with_size_kw(producer, sym_each, 0, 0, producer_size, RB_NO_KEYWORDS);
3195}
3196
3197/*
3198 * Document-class: Enumerator::Chain
3199 *
3200 * Enumerator::Chain is a subclass of Enumerator, which represents a
3201 * chain of enumerables that works as a single enumerator.
3202 *
3203 * This type of objects can be created by Enumerable#chain and
3204 * Enumerator#+.
3205 */
3206
3207static void
3208enum_chain_mark_and_move(void *p)
3209{
3210 struct enum_chain *ptr = p;
3211 rb_gc_mark_and_move(&ptr->enums);
3212}
3213
3214#define enum_chain_free RUBY_TYPED_DEFAULT_FREE
3215
3216static size_t
3217enum_chain_memsize(const void *p)
3218{
3219 return sizeof(struct enum_chain);
3220}
3221
3222static const rb_data_type_t enum_chain_data_type = {
3223 "chain",
3224 {
3225 enum_chain_mark_and_move,
3226 enum_chain_free,
3227 enum_chain_memsize,
3228 enum_chain_mark_and_move,
3229 },
3230 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED
3231};
3232
3233static struct enum_chain *
3234enum_chain_ptr(VALUE obj)
3235{
3236 struct enum_chain *ptr;
3237
3238 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr);
3239 if (!ptr || UNDEF_P(ptr->enums)) {
3240 rb_raise(rb_eArgError, "uninitialized chain");
3241 }
3242 return ptr;
3243}
3244
3245/* :nodoc: */
3246static VALUE
3247enum_chain_allocate(VALUE klass)
3248{
3249 struct enum_chain *ptr;
3250 VALUE obj;
3251
3252 obj = TypedData_Make_Struct(klass, struct enum_chain, &enum_chain_data_type, ptr);
3253 ptr->enums = Qundef;
3254 ptr->pos = -1;
3255
3256 return obj;
3257}
3258
3259/*
3260 * call-seq:
3261 * Enumerator::Chain.new(*enums) -> enum
3262 *
3263 * Generates a new enumerator object that iterates over the elements
3264 * of given enumerable objects in sequence.
3265 *
3266 * e = Enumerator::Chain.new(1..3, [4, 5])
3267 * e.to_a #=> [1, 2, 3, 4, 5]
3268 * e.size #=> 5
3269 */
3270static VALUE
3271enum_chain_initialize(VALUE obj, VALUE enums)
3272{
3273 struct enum_chain *ptr;
3274
3275 rb_check_frozen(obj);
3276 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr);
3277
3278 if (!ptr) rb_raise(rb_eArgError, "unallocated chain");
3279
3280 RB_OBJ_WRITE(obj, &ptr->enums, rb_ary_freeze(enums));
3281 ptr->pos = -1;
3282
3283 return obj;
3284}
3285
3286static VALUE
3287new_enum_chain(VALUE enums)
3288{
3289 long i;
3290 VALUE obj = enum_chain_initialize(enum_chain_allocate(rb_cEnumChain), enums);
3291
3292 for (i = 0; i < RARRAY_LEN(enums); i++) {
3293 if (RTEST(rb_obj_is_kind_of(RARRAY_AREF(enums, i), rb_cLazy))) {
3294 return enumerable_lazy(obj);
3295 }
3296 }
3297
3298 return obj;
3299}
3300
3301/* :nodoc: */
3302static VALUE
3303enum_chain_init_copy(VALUE obj, VALUE orig)
3304{
3305 struct enum_chain *ptr0, *ptr1;
3306
3307 if (!OBJ_INIT_COPY(obj, orig)) return obj;
3308 ptr0 = enum_chain_ptr(orig);
3309
3310 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr1);
3311
3312 if (!ptr1) rb_raise(rb_eArgError, "unallocated chain");
3313
3314 RB_OBJ_WRITE(obj, &ptr1->enums, ptr0->enums);
3315 ptr1->pos = ptr0->pos;
3316
3317 return obj;
3318}
3319
3320static VALUE
3321enum_chain_total_size(VALUE enums)
3322{
3323 VALUE total = INT2FIX(0);
3324 long i;
3325
3326 for (i = 0; i < RARRAY_LEN(enums); i++) {
3327 VALUE size = enum_size(RARRAY_AREF(enums, i));
3328
3329 if (NIL_P(size) || (RB_FLOAT_TYPE_P(size) && isinf(NUM2DBL(size)))) {
3330 return size;
3331 }
3332 if (!RB_INTEGER_TYPE_P(size)) {
3333 return Qnil;
3334 }
3335
3336 total = rb_funcall(total, '+', 1, size);
3337 }
3338
3339 return total;
3340}
3341
3342/*
3343 * call-seq:
3344 * obj.size -> int, Float::INFINITY or nil
3345 *
3346 * Returns the total size of the enumerator chain calculated by
3347 * summing up the size of each enumerable in the chain. If any of the
3348 * enumerables reports its size as nil or Float::INFINITY, that value
3349 * is returned as the total size.
3350 */
3351static VALUE
3352enum_chain_size(VALUE obj)
3353{
3354 return enum_chain_total_size(enum_chain_ptr(obj)->enums);
3355}
3356
3357static VALUE
3358enum_chain_enum_size(VALUE obj, VALUE args, VALUE eobj)
3359{
3360 return enum_chain_size(obj);
3361}
3362
3363static VALUE
3364enum_chain_enum_no_size(VALUE obj, VALUE args, VALUE eobj)
3365{
3366 return Qnil;
3367}
3368
3369/*
3370 * call-seq:
3371 * obj.each(*args) { |...| ... } -> obj
3372 * obj.each(*args) -> enumerator
3373 *
3374 * Iterates over the elements of the first enumerable by calling the
3375 * "each" method on it with the given arguments, then proceeds to the
3376 * following enumerables in sequence until all of the enumerables are
3377 * exhausted.
3378 *
3379 * If no block is given, returns an enumerator.
3380 */
3381static VALUE
3382enum_chain_each(int argc, VALUE *argv, VALUE obj)
3383{
3384 VALUE enums, block;
3385 struct enum_chain *objptr;
3386 long i;
3387
3388 RETURN_SIZED_ENUMERATOR(obj, argc, argv, argc > 0 ? enum_chain_enum_no_size : enum_chain_enum_size);
3389
3390 objptr = enum_chain_ptr(obj);
3391 enums = objptr->enums;
3392 block = rb_block_proc();
3393
3394 for (i = 0; i < RARRAY_LEN(enums); i++) {
3395 objptr->pos = i;
3396 rb_funcall_with_block(RARRAY_AREF(enums, i), id_each, argc, argv, block);
3397 }
3398
3399 return obj;
3400}
3401
3402/*
3403 * call-seq:
3404 * obj.rewind -> obj
3405 *
3406 * Rewinds the enumerator chain by calling the "rewind" method on each
3407 * enumerable in reverse order. Each call is performed only if the
3408 * enumerable responds to the method.
3409 */
3410static VALUE
3411enum_chain_rewind(VALUE obj)
3412{
3413 struct enum_chain *objptr = enum_chain_ptr(obj);
3414 VALUE enums = objptr->enums;
3415 long i;
3416
3417 for (i = objptr->pos; 0 <= i && i < RARRAY_LEN(enums); objptr->pos = --i) {
3418 rb_check_funcall(RARRAY_AREF(enums, i), id_rewind, 0, 0);
3419 }
3420
3421 return obj;
3422}
3423
3424static VALUE
3425inspect_enum_chain(VALUE obj, VALUE dummy, int recur)
3426{
3427 VALUE klass = rb_obj_class(obj);
3428 struct enum_chain *ptr;
3429
3430 TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr);
3431
3432 if (!ptr || UNDEF_P(ptr->enums)) {
3433 return rb_sprintf("#<%"PRIsVALUE": uninitialized>", rb_class_path(klass));
3434 }
3435
3436 if (recur) {
3437 return rb_sprintf("#<%"PRIsVALUE": ...>", rb_class_path(klass));
3438 }
3439
3440 return rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE">", rb_class_path(klass), ptr->enums);
3441}
3442
3443/*
3444 * call-seq:
3445 * obj.inspect -> string
3446 *
3447 * Returns a printable version of the enumerator chain.
3448 */
3449static VALUE
3450enum_chain_inspect(VALUE obj)
3451{
3452 return rb_exec_recursive(inspect_enum_chain, obj, 0);
3453}
3454
3455/*
3456 * call-seq:
3457 * e.chain(*enums) -> enumerator
3458 *
3459 * Returns an enumerator object generated from this enumerator and
3460 * given enumerables.
3461 *
3462 * e = (1..3).chain([4, 5])
3463 * e.to_a #=> [1, 2, 3, 4, 5]
3464 */
3465static VALUE
3466enum_chain(int argc, VALUE *argv, VALUE obj)
3467{
3468 VALUE enums = rb_ary_new_from_values(1, &obj);
3469 rb_ary_cat(enums, argv, argc);
3470 return new_enum_chain(enums);
3471}
3472
3473/*
3474 * call-seq:
3475 * e + enum -> enumerator
3476 *
3477 * Returns an enumerator object generated from this enumerator and a
3478 * given enumerable.
3479 *
3480 * e = (1..3).each + [4, 5]
3481 * e.to_a #=> [1, 2, 3, 4, 5]
3482 */
3483static VALUE
3484enumerator_plus(VALUE obj, VALUE eobj)
3485{
3486 return new_enum_chain(rb_ary_new_from_args(2, obj, eobj));
3487}
3488
3489/*
3490 * Document-class: Enumerator::Product
3491 *
3492 * Enumerator::Product generates a Cartesian product of any number of
3493 * enumerable objects. Iterating over the product of enumerable
3494 * objects is roughly equivalent to nested each_entry loops where the
3495 * loop for the rightmost object is put innermost.
3496 *
3497 * innings = Enumerator::Product.new(1..9, ['top', 'bottom'])
3498 *
3499 * innings.each do |i, h|
3500 * p [i, h]
3501 * end
3502 * # [1, "top"]
3503 * # [1, "bottom"]
3504 * # [2, "top"]
3505 * # [2, "bottom"]
3506 * # [3, "top"]
3507 * # [3, "bottom"]
3508 * # ...
3509 * # [9, "top"]
3510 * # [9, "bottom"]
3511 *
3512 * The method used against each enumerable object is `each_entry`
3513 * instead of `each` so that the product of N enumerable objects
3514 * yields an array of exactly N elements in each iteration.
3515 *
3516 * When no enumerator is given, it calls a given block once yielding
3517 * an empty argument list.
3518 *
3519 * This type of objects can be created by Enumerator.product.
3520 */
3521
3522static void
3523enum_product_mark_and_move(void *p)
3524{
3525 struct enum_product *ptr = p;
3526 rb_gc_mark_and_move(&ptr->enums);
3527}
3528
3529#define enum_product_free RUBY_TYPED_DEFAULT_FREE
3530
3531static size_t
3532enum_product_memsize(const void *p)
3533{
3534 return sizeof(struct enum_product);
3535}
3536
3537static const rb_data_type_t enum_product_data_type = {
3538 "product",
3539 {
3540 enum_product_mark_and_move,
3541 enum_product_free,
3542 enum_product_memsize,
3543 enum_product_mark_and_move,
3544 },
3545 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED
3546};
3547
3548static struct enum_product *
3549enum_product_ptr(VALUE obj)
3550{
3551 struct enum_product *ptr;
3552
3553 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr);
3554 if (!ptr || UNDEF_P(ptr->enums)) {
3555 rb_raise(rb_eArgError, "uninitialized product");
3556 }
3557 return ptr;
3558}
3559
3560/* :nodoc: */
3561static VALUE
3562enum_product_allocate(VALUE klass)
3563{
3564 struct enum_product *ptr;
3565 VALUE obj;
3566
3567 obj = TypedData_Make_Struct(klass, struct enum_product, &enum_product_data_type, ptr);
3568 ptr->enums = Qundef;
3569
3570 return obj;
3571}
3572
3573/*
3574 * call-seq:
3575 * Enumerator::Product.new(*enums) -> enum
3576 *
3577 * Generates a new enumerator object that generates a Cartesian
3578 * product of given enumerable objects.
3579 *
3580 * e = Enumerator::Product.new(1..3, [4, 5])
3581 * e.to_a #=> [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
3582 * e.size #=> 6
3583 */
3584static VALUE
3585enum_product_initialize(int argc, VALUE *argv, VALUE obj)
3586{
3587 struct enum_product *ptr;
3588 VALUE enums = Qnil, options = Qnil;
3589
3590 rb_scan_args(argc, argv, "*:", &enums, &options);
3591
3592 if (!NIL_P(options) && !RHASH_EMPTY_P(options)) {
3593 rb_exc_raise(rb_keyword_error_new("unknown", rb_hash_keys(options)));
3594 }
3595
3596 rb_check_frozen(obj);
3597 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr);
3598
3599 if (!ptr) rb_raise(rb_eArgError, "unallocated product");
3600
3601 RB_OBJ_WRITE(obj, &ptr->enums, rb_ary_freeze(enums));
3602
3603 return obj;
3604}
3605
3606/* :nodoc: */
3607static VALUE
3608enum_product_init_copy(VALUE obj, VALUE orig)
3609{
3610 struct enum_product *ptr0, *ptr1;
3611
3612 if (!OBJ_INIT_COPY(obj, orig)) return obj;
3613 ptr0 = enum_product_ptr(orig);
3614
3615 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr1);
3616
3617 if (!ptr1) rb_raise(rb_eArgError, "unallocated product");
3618
3619 RB_OBJ_WRITE(obj, &ptr1->enums, ptr0->enums);
3620
3621 return obj;
3622}
3623
3624static VALUE
3625enum_product_total_size(VALUE enums)
3626{
3627 VALUE total = INT2FIX(1);
3628 VALUE sizes = rb_ary_hidden_new(RARRAY_LEN(enums));
3629 long i;
3630
3631 for (i = 0; i < RARRAY_LEN(enums); i++) {
3632 VALUE size = enum_size(RARRAY_AREF(enums, i));
3633 if (size == INT2FIX(0)) {
3634 rb_ary_resize(sizes, 0);
3635 return size;
3636 }
3637 rb_ary_push(sizes, size);
3638 }
3639 for (i = 0; i < RARRAY_LEN(sizes); i++) {
3640 VALUE size = RARRAY_AREF(sizes, i);
3641
3642 if (NIL_P(size) || (RB_TYPE_P(size, T_FLOAT) && isinf(NUM2DBL(size)))) {
3643 return size;
3644 }
3645 if (!RB_INTEGER_TYPE_P(size)) {
3646 return Qnil;
3647 }
3648
3649 total = rb_funcall(total, '*', 1, size);
3650 }
3651
3652 return total;
3653}
3654
3655/*
3656 * call-seq:
3657 * obj.size -> int, Float::INFINITY or nil
3658 *
3659 * Returns the total size of the enumerator product calculated by
3660 * multiplying the sizes of enumerables in the product. If any of the
3661 * enumerables reports its size as nil or Float::INFINITY, that value
3662 * is returned as the size.
3663 */
3664static VALUE
3665enum_product_size(VALUE obj)
3666{
3667 return enum_product_total_size(enum_product_ptr(obj)->enums);
3668}
3669
3670static VALUE
3671enum_product_enum_size(VALUE obj, VALUE args, VALUE eobj)
3672{
3673 return enum_product_size(obj);
3674}
3675
3677 VALUE obj;
3678 VALUE block;
3679 int index;
3680 int argc;
3681 VALUE *argv;
3682};
3683
3684static VALUE product_each(VALUE, struct product_state *);
3685
3686static VALUE
3687product_each_i(RB_BLOCK_CALL_FUNC_ARGLIST(value, state))
3688{
3689 struct product_state *pstate = (struct product_state *)state;
3690 pstate->argv[pstate->index++] = value;
3691
3692 VALUE val = product_each(pstate->obj, pstate);
3693 pstate->index--;
3694 return val;
3695}
3696
3697static VALUE
3698product_each(VALUE obj, struct product_state *pstate)
3699{
3700 struct enum_product *ptr = enum_product_ptr(obj);
3701 VALUE enums = ptr->enums;
3702
3703 if (pstate->index < pstate->argc) {
3704 VALUE eobj = RARRAY_AREF(enums, pstate->index);
3705
3706 rb_block_call(eobj, id_each_entry, 0, NULL, product_each_i, (VALUE)pstate);
3707 }
3708 else {
3709 rb_funcall(pstate->block, id_call, 1, rb_ary_new_from_values(pstate->argc, pstate->argv));
3710 }
3711
3712 return obj;
3713}
3714
3715static VALUE
3716enum_product_run(VALUE obj, VALUE block)
3717{
3718 struct enum_product *ptr = enum_product_ptr(obj);
3719 int argc = RARRAY_LENINT(ptr->enums);
3720 if (argc == 0) { /* no need to allocate state.argv */
3721 rb_funcall(block, id_call, 1, rb_ary_new());
3722 return obj;
3723 }
3724
3725 VALUE argsbuf = 0;
3726 struct product_state state = {
3727 .obj = obj,
3728 .block = block,
3729 .index = 0,
3730 .argc = argc,
3731 .argv = ALLOCV_N(VALUE, argsbuf, argc),
3732 };
3733
3734 VALUE ret = product_each(obj, &state);
3735 ALLOCV_END(argsbuf);
3736 return ret;
3737}
3738
3739/*
3740 * call-seq:
3741 * obj.each { |...| ... } -> obj
3742 * obj.each -> enumerator
3743 *
3744 * Iterates over the elements of the first enumerable by calling the
3745 * "each_entry" method on it with the given arguments, then proceeds
3746 * to the following enumerables in sequence until all of the
3747 * enumerables are exhausted.
3748 *
3749 * If no block is given, returns an enumerator. Otherwise, returns self.
3750 */
3751static VALUE
3752enum_product_each(VALUE obj)
3753{
3754 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_product_enum_size);
3755
3756 return enum_product_run(obj, rb_block_proc());
3757}
3758
3759/*
3760 * call-seq:
3761 * obj.rewind -> obj
3762 *
3763 * Rewinds the product enumerator by calling the "rewind" method on
3764 * each enumerable in reverse order. Each call is performed only if
3765 * the enumerable responds to the method.
3766 */
3767static VALUE
3768enum_product_rewind(VALUE obj)
3769{
3770 struct enum_product *ptr = enum_product_ptr(obj);
3771 VALUE enums = ptr->enums;
3772 long i;
3773
3774 for (i = 0; i < RARRAY_LEN(enums); i++) {
3775 rb_check_funcall(RARRAY_AREF(enums, i), id_rewind, 0, 0);
3776 }
3777
3778 return obj;
3779}
3780
3781static VALUE
3782inspect_enum_product(VALUE obj, VALUE dummy, int recur)
3783{
3784 VALUE klass = rb_obj_class(obj);
3785 struct enum_product *ptr;
3786
3787 TypedData_Get_Struct(obj, struct enum_product, &enum_product_data_type, ptr);
3788
3789 if (!ptr || UNDEF_P(ptr->enums)) {
3790 return rb_sprintf("#<%"PRIsVALUE": uninitialized>", rb_class_path(klass));
3791 }
3792
3793 if (recur) {
3794 return rb_sprintf("#<%"PRIsVALUE": ...>", rb_class_path(klass));
3795 }
3796
3797 return rb_sprintf("#<%"PRIsVALUE": %+"PRIsVALUE">", rb_class_path(klass), ptr->enums);
3798}
3799
3800/*
3801 * call-seq:
3802 * obj.inspect -> string
3803 *
3804 * Returns a printable version of the product enumerator.
3805 */
3806static VALUE
3807enum_product_inspect(VALUE obj)
3808{
3809 return rb_exec_recursive(inspect_enum_product, obj, 0);
3810}
3811
3812/*
3813 * call-seq:
3814 * Enumerator.product(*enums) -> enumerator
3815 * Enumerator.product(*enums) { |elts| ... } -> enumerator
3816 *
3817 * Generates a new enumerator object that generates a Cartesian
3818 * product of given enumerable objects. This is equivalent to
3819 * Enumerator::Product.new.
3820 *
3821 * e = Enumerator.product(1..3, [4, 5])
3822 * e.to_a #=> [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
3823 * e.size #=> 6
3824 *
3825 * When a block is given, calls the block with each N-element array
3826 * generated and returns +nil+.
3827 */
3828static VALUE
3829enumerator_s_product(int argc, VALUE *argv, VALUE klass)
3830{
3831 VALUE enums = Qnil, options = Qnil, block = Qnil;
3832
3833 rb_scan_args(argc, argv, "*:&", &enums, &options, &block);
3834
3835 if (!NIL_P(options) && !RHASH_EMPTY_P(options)) {
3836 rb_exc_raise(rb_keyword_error_new("unknown", rb_hash_keys(options)));
3837 }
3838
3839 VALUE obj = enum_product_initialize(argc, argv, enum_product_allocate(rb_cEnumProduct));
3840
3841 if (!NIL_P(block)) {
3842 enum_product_run(obj, block);
3843 return Qnil;
3844 }
3845
3846 return obj;
3847}
3848
3850 struct enumerator enumerator;
3851 VALUE begin;
3852 VALUE end;
3853 VALUE step;
3854 bool exclude_end;
3855};
3856
3857RUBY_REFERENCES(arith_seq_refs) = {
3858 RUBY_REF_EDGE(struct enumerator, obj),
3859 RUBY_REF_EDGE(struct enumerator, args),
3860 RUBY_REF_EDGE(struct enumerator, fib),
3861 RUBY_REF_EDGE(struct enumerator, dst),
3862 RUBY_REF_EDGE(struct enumerator, lookahead),
3863 RUBY_REF_EDGE(struct enumerator, feedvalue),
3864 RUBY_REF_EDGE(struct enumerator, stop_exc),
3865 RUBY_REF_EDGE(struct enumerator, size),
3866 RUBY_REF_EDGE(struct enumerator, procs),
3867
3868 RUBY_REF_EDGE(struct arith_seq, begin),
3869 RUBY_REF_EDGE(struct arith_seq, end),
3870 RUBY_REF_EDGE(struct arith_seq, step),
3871 RUBY_REF_END
3872};
3873
3874static const rb_data_type_t arith_seq_data_type = {
3875 "arithmetic_sequence",
3876 {
3877 RUBY_REFS_LIST_PTR(arith_seq_refs),
3879 NULL, // Nothing allocated externally, so don't need a memsize function
3880 NULL,
3881 },
3882 .parent = &enumerator_data_type,
3883 .flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_DECL_MARKING | RUBY_TYPED_EMBEDDABLE
3884};
3885
3886static VALUE
3887arith_seq_allocate(VALUE klass)
3888{
3889 struct arith_seq *ptr;
3890 VALUE enum_obj;
3891
3892 enum_obj = TypedData_Make_Struct(klass, struct arith_seq, &arith_seq_data_type, ptr);
3893 ptr->enumerator.obj = Qundef;
3894
3895 return enum_obj;
3896}
3897
3898/*
3899 * Document-class: Enumerator::ArithmeticSequence
3900 *
3901 * Enumerator::ArithmeticSequence is a subclass of Enumerator,
3902 * that is a representation of sequences of numbers with common difference.
3903 * Instances of this class can be generated by the Range#step and Numeric#step
3904 * methods.
3905 *
3906 * The class can be used for slicing Array (see Array#slice) or custom
3907 * collections.
3908 */
3909
3910VALUE
3911rb_arith_seq_new(VALUE obj, VALUE meth, int argc, VALUE const *argv,
3912 rb_enumerator_size_func *size_fn,
3913 VALUE beg, VALUE end, VALUE step, int excl)
3914{
3915 VALUE aseq = enumerator_init(arith_seq_allocate(rb_cArithSeq),
3916 obj, meth, argc, argv, size_fn, Qnil, rb_keyword_given_p());
3917 struct arith_seq *ptr;
3918 TypedData_Get_Struct(aseq, struct arith_seq, &enumerator_data_type, ptr);
3919
3920 RB_OBJ_WRITE(aseq, &ptr->begin, beg);
3921 RB_OBJ_WRITE(aseq, &ptr->end, end);
3922 RB_OBJ_WRITE(aseq, &ptr->step, step);
3923 ptr->exclude_end = excl;
3924
3925 return aseq;
3926}
3927
3928/*
3929 * call-seq: aseq.begin -> num or nil
3930 *
3931 * Returns the number that defines the first element of this arithmetic
3932 * sequence.
3933 */
3934static inline VALUE
3935arith_seq_begin(VALUE self)
3936{
3937 struct arith_seq *ptr;
3938 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3939 return ptr->begin;
3940}
3941
3942/*
3943 * call-seq: aseq.end -> num or nil
3944 *
3945 * Returns the number that defines the end of this arithmetic sequence.
3946 */
3947static inline VALUE
3948arith_seq_end(VALUE self)
3949{
3950 struct arith_seq *ptr;
3951 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3952 return ptr->end;
3953}
3954
3955/*
3956 * call-seq: aseq.step -> num
3957 *
3958 * Returns the number that defines the common difference between
3959 * two adjacent elements in this arithmetic sequence.
3960 */
3961static inline VALUE
3962arith_seq_step(VALUE self)
3963{
3964 struct arith_seq *ptr;
3965 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3966 return ptr->step;
3967}
3968
3969/*
3970 * call-seq: aseq.exclude_end? -> true or false
3971 *
3972 * Returns <code>true</code> if this arithmetic sequence excludes its end value.
3973 */
3974static inline VALUE
3975arith_seq_exclude_end(VALUE self)
3976{
3977 struct arith_seq *ptr;
3978 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3979 return RBOOL(ptr->exclude_end);
3980}
3981
3982static inline int
3983arith_seq_exclude_end_p(VALUE self)
3984{
3985 struct arith_seq *ptr;
3986 TypedData_Get_Struct(self, struct arith_seq, &enumerator_data_type, ptr);
3987 return ptr->exclude_end;
3988}
3989
3990int
3991rb_arithmetic_sequence_extract(VALUE obj, rb_arithmetic_sequence_components_t *component)
3992{
3993 if (rb_obj_is_kind_of(obj, rb_cArithSeq)) {
3994 component->begin = arith_seq_begin(obj);
3995 component->end = arith_seq_end(obj);
3996 component->step = arith_seq_step(obj);
3997 component->exclude_end = arith_seq_exclude_end_p(obj);
3998 return 1;
3999 }
4000 else if (rb_range_values(obj, &component->begin, &component->end, &component->exclude_end)) {
4001 component->step = INT2FIX(1);
4002 return 1;
4003 }
4004
4005 return 0;
4006}
4007
4008VALUE
4009rb_arithmetic_sequence_beg_len_step(VALUE obj, long *begp, long *lenp, long *stepp, long len, int err)
4010{
4011 RBIMPL_NONNULL_ARG(begp);
4012 RBIMPL_NONNULL_ARG(lenp);
4013 RBIMPL_NONNULL_ARG(stepp);
4014
4016 if (!rb_arithmetic_sequence_extract(obj, &aseq)) {
4017 return Qfalse;
4018 }
4019
4020 long step = NIL_P(aseq.step) ? 1 : NUM2LONG(aseq.step);
4021 *stepp = step;
4022
4023 if (step < 0) {
4024 if (aseq.exclude_end && !NIL_P(aseq.end)) {
4025 /* Handle exclusion before range reversal */
4026 aseq.end = LONG2NUM(NUM2LONG(aseq.end) + 1);
4027
4028 /* Don't exclude the previous beginning */
4029 aseq.exclude_end = 0;
4030 }
4031 VALUE tmp = aseq.begin;
4032 aseq.begin = aseq.end;
4033 aseq.end = tmp;
4034 }
4035
4036 if (err == 0 && (step < -1 || step > 1)) {
4037 if (rb_range_component_beg_len(aseq.begin, aseq.end, aseq.exclude_end, begp, lenp, len, 1) == Qtrue) {
4038 if (*begp > len)
4039 goto out_of_range;
4040 if (*lenp > len)
4041 goto out_of_range;
4042 return Qtrue;
4043 }
4044 }
4045 else {
4046 return rb_range_component_beg_len(aseq.begin, aseq.end, aseq.exclude_end, begp, lenp, len, err);
4047 }
4048
4049 out_of_range:
4050 rb_raise(rb_eRangeError, "%+"PRIsVALUE" out of range", obj);
4051 return Qnil;
4052}
4053
4054static VALUE
4055arith_seq_take(VALUE self, VALUE num)
4056{
4057 VALUE b, e, s, ary;
4058 long n;
4059 int x;
4060
4061 n = NUM2LONG(num);
4062 if (n < 0) {
4063 rb_raise(rb_eArgError, "attempt to take negative size");
4064 }
4065 if (n == 0) {
4066 return rb_ary_new_capa(0);
4067 }
4068
4069 b = arith_seq_begin(self);
4070 e = arith_seq_end(self);
4071 s = arith_seq_step(self);
4072 x = arith_seq_exclude_end_p(self);
4073
4074 if (FIXNUM_P(b) && NIL_P(e) && FIXNUM_P(s)) {
4075 long i = FIX2LONG(b), unit = FIX2LONG(s);
4076 ary = rb_ary_new_capa(n);
4077 while (n > 0 && FIXABLE(i)) {
4078 rb_ary_push(ary, LONG2FIX(i));
4079 i += unit; // FIXABLE + FIXABLE never overflow;
4080 --n;
4081 }
4082 if (n > 0) {
4083 b = LONG2NUM(i);
4084 while (n > 0) {
4085 rb_ary_push(ary, b);
4086 b = rb_big_plus(b, s);
4087 --n;
4088 }
4089 }
4090 return ary;
4091 }
4092 else if (FIXNUM_P(b) && FIXNUM_P(e) && FIXNUM_P(s)) {
4093 long i = FIX2LONG(b);
4094 long end = FIX2LONG(e);
4095 long unit = FIX2LONG(s);
4096 long len;
4097
4098 if (unit >= 0) {
4099 if (!x) end += 1;
4100
4101 len = end - i;
4102 if (len < 0) len = 0;
4103 ary = rb_ary_new_capa((n < len) ? n : len);
4104 while (n > 0 && i < end) {
4105 rb_ary_push(ary, LONG2FIX(i));
4106 if (i > LONG_MAX - unit) break;
4107 i += unit;
4108 --n;
4109 }
4110 }
4111 else {
4112 if (!x) end -= 1;
4113
4114 len = i - end;
4115 if (len < 0) len = 0;
4116 ary = rb_ary_new_capa((n < len) ? n : len);
4117 while (n > 0 && i > end) {
4118 rb_ary_push(ary, LONG2FIX(i));
4119 if (i < LONG_MIN - unit) break;
4120 i += unit;
4121 --n;
4122 }
4123 }
4124 return ary;
4125 }
4126 else if (RB_FLOAT_TYPE_P(b) || RB_FLOAT_TYPE_P(e) || RB_FLOAT_TYPE_P(s)) {
4127 /* generate values like ruby_float_step */
4128
4129 double unit = NUM2DBL(s);
4130 double beg = NUM2DBL(b);
4131 double end = NIL_P(e) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(e);
4132 double len = ruby_float_step_size(beg, end, unit, x);
4133 long i;
4134
4135 if (n > len)
4136 n = (long)len;
4137
4138 if (isinf(unit)) {
4139 if (len > 0) {
4140 ary = rb_ary_new_capa(1);
4141 rb_ary_push(ary, DBL2NUM(beg));
4142 }
4143 else {
4144 ary = rb_ary_new_capa(0);
4145 }
4146 }
4147 else if (unit == 0) {
4148 VALUE val = DBL2NUM(beg);
4149 ary = rb_ary_new_capa(n);
4150 for (i = 0; i < len; ++i) {
4151 rb_ary_push(ary, val);
4152 }
4153 }
4154 else {
4155 ary = rb_ary_new_capa(n);
4156 for (i = 0; i < n; ++i) {
4157 double d = i*unit+beg;
4158 if (unit >= 0 ? end < d : d < end) d = end;
4159 rb_ary_push(ary, DBL2NUM(d));
4160 }
4161 }
4162
4163 return ary;
4164 }
4165
4166 {
4167 VALUE argv[1];
4168 argv[0] = num;
4169 return rb_call_super(1, argv);
4170 }
4171}
4172
4173/*
4174 * call-seq:
4175 * aseq.first -> num or nil
4176 * aseq.first(n) -> an_array
4177 *
4178 * Returns the first number in this arithmetic sequence,
4179 * or an array of the first +n+ elements.
4180 */
4181static VALUE
4182arith_seq_first(int argc, VALUE *argv, VALUE self)
4183{
4184 VALUE b, e, s;
4185
4186 rb_check_arity(argc, 0, 1);
4187
4188 b = arith_seq_begin(self);
4189 e = arith_seq_end(self);
4190 s = arith_seq_step(self);
4191 if (argc == 0) {
4192 if (NIL_P(b)) {
4193 return Qnil;
4194 }
4195 if (!NIL_P(e)) {
4196 VALUE zero = INT2FIX(0);
4197 int r = rb_cmpint(rb_num_coerce_cmp(s, zero, idCmp), s, zero);
4198 if (r > 0 && RTEST(rb_funcall(b, '>', 1, e))) {
4199 return Qnil;
4200 }
4201 if (r < 0 && RTEST(rb_funcall(b, '<', 1, e))) {
4202 return Qnil;
4203 }
4204 }
4205 return b;
4206 }
4207
4208 return arith_seq_take(self, argv[0]);
4209}
4210
4211static inline VALUE
4212num_plus(VALUE a, VALUE b)
4213{
4214 if (RB_INTEGER_TYPE_P(a)) {
4215 return rb_int_plus(a, b);
4216 }
4217 else if (RB_FLOAT_TYPE_P(a)) {
4218 return rb_float_plus(a, b);
4219 }
4220 else if (RB_TYPE_P(a, T_RATIONAL)) {
4221 return rb_rational_plus(a, b);
4222 }
4223 else {
4224 return rb_funcallv(a, '+', 1, &b);
4225 }
4226}
4227
4228static inline VALUE
4229num_minus(VALUE a, VALUE b)
4230{
4231 if (RB_INTEGER_TYPE_P(a)) {
4232 return rb_int_minus(a, b);
4233 }
4234 else if (RB_FLOAT_TYPE_P(a)) {
4235 return rb_float_minus(a, b);
4236 }
4237 else if (RB_TYPE_P(a, T_RATIONAL)) {
4238 return rb_rational_minus(a, b);
4239 }
4240 else {
4241 return rb_funcallv(a, '-', 1, &b);
4242 }
4243}
4244
4245static inline VALUE
4246num_mul(VALUE a, VALUE b)
4247{
4248 if (RB_INTEGER_TYPE_P(a)) {
4249 return rb_int_mul(a, b);
4250 }
4251 else if (RB_FLOAT_TYPE_P(a)) {
4252 return rb_float_mul(a, b);
4253 }
4254 else if (RB_TYPE_P(a, T_RATIONAL)) {
4255 return rb_rational_mul(a, b);
4256 }
4257 else {
4258 return rb_funcallv(a, '*', 1, &b);
4259 }
4260}
4261
4262static inline VALUE
4263num_idiv(VALUE a, VALUE b)
4264{
4265 VALUE q;
4266 if (RB_INTEGER_TYPE_P(a)) {
4267 q = rb_int_idiv(a, b);
4268 }
4269 else if (RB_FLOAT_TYPE_P(a)) {
4270 q = rb_float_div(a, b);
4271 }
4272 else if (RB_TYPE_P(a, T_RATIONAL)) {
4273 q = rb_rational_div(a, b);
4274 }
4275 else {
4276 q = rb_funcallv(a, idDiv, 1, &b);
4277 }
4278
4279 if (RB_INTEGER_TYPE_P(q)) {
4280 return q;
4281 }
4282 else if (RB_FLOAT_TYPE_P(q)) {
4283 return rb_float_floor(q, 0);
4284 }
4285 else if (RB_TYPE_P(q, T_RATIONAL)) {
4286 return rb_rational_floor(q, 0);
4287 }
4288 else {
4289 return rb_funcall(q, rb_intern("floor"), 0);
4290 }
4291}
4292
4293/*
4294 * call-seq:
4295 * aseq.last -> num or nil
4296 * aseq.last(n) -> an_array
4297 *
4298 * Returns the last number in this arithmetic sequence,
4299 * or an array of the last +n+ elements.
4300 */
4301static VALUE
4302arith_seq_last(int argc, VALUE *argv, VALUE self)
4303{
4304 VALUE b, e, s, len_1, len, last, nv, ary;
4305 int last_is_adjusted;
4306 long n;
4307
4308 e = arith_seq_end(self);
4309 if (NIL_P(e)) {
4310 rb_raise(rb_eRangeError,
4311 "cannot get the last element of endless arithmetic sequence");
4312 }
4313
4314 b = arith_seq_begin(self);
4315 s = arith_seq_step(self);
4316
4317 len_1 = num_idiv(num_minus(e, b), s);
4318 if (rb_num_negative_int_p(len_1)) {
4319 if (argc == 0) {
4320 return Qnil;
4321 }
4322 return rb_ary_new_capa(0);
4323 }
4324
4325 last = num_plus(b, num_mul(s, len_1));
4326 if ((last_is_adjusted = arith_seq_exclude_end_p(self) && rb_equal(last, e))) {
4327 last = num_minus(last, s);
4328 }
4329
4330 if (argc == 0) {
4331 return last;
4332 }
4333
4334 if (last_is_adjusted) {
4335 len = len_1;
4336 }
4337 else {
4338 len = rb_int_plus(len_1, INT2FIX(1));
4339 }
4340
4341 rb_scan_args(argc, argv, "1", &nv);
4342 if (!RB_INTEGER_TYPE_P(nv)) {
4343 nv = rb_to_int(nv);
4344 }
4345 if (RTEST(rb_int_gt(nv, len))) {
4346 nv = len;
4347 }
4348 n = NUM2LONG(nv);
4349 if (n < 0) {
4350 rb_raise(rb_eArgError, "negative array size");
4351 }
4352
4353 ary = rb_ary_new_capa(n);
4354 b = rb_int_minus(last, rb_int_mul(s, nv));
4355 while (n) {
4356 b = rb_int_plus(b, s);
4357 rb_ary_push(ary, b);
4358 --n;
4359 }
4360
4361 return ary;
4362}
4363
4364/*
4365 * call-seq:
4366 * aseq.inspect -> string
4367 *
4368 * Convert this arithmetic sequence to a printable form.
4369 */
4370static VALUE
4371arith_seq_inspect(VALUE self)
4372{
4373 struct enumerator *e;
4374 VALUE eobj, str;
4375 int range_p;
4376
4377 TypedData_Get_Struct(self, struct enumerator, &enumerator_data_type, e);
4378
4379 eobj = rb_attr_get(self, id_receiver);
4380 if (NIL_P(eobj)) {
4381 eobj = e->obj;
4382 }
4383
4384 range_p = RTEST(rb_obj_is_kind_of(eobj, rb_cRange));
4385 str = rb_sprintf("(%s%"PRIsVALUE"%s.", range_p ? "(" : "", eobj, range_p ? ")" : "");
4386
4387 rb_str_buf_append(str, rb_id2str(e->meth));
4388 append_method_args(eobj, str, e->args);
4389
4390 rb_str_buf_cat2(str, ")");
4391
4392 return str;
4393}
4394
4395/*
4396 * call-seq:
4397 * aseq == obj -> true or false
4398 *
4399 * Returns <code>true</code> only if +obj+ is an Enumerator::ArithmeticSequence,
4400 * has equivalent begin, end, step, and exclude_end? settings.
4401 */
4402static VALUE
4403arith_seq_eq(VALUE self, VALUE other)
4404{
4405 if (!RTEST(rb_obj_is_kind_of(other, rb_cArithSeq))) {
4406 return Qfalse;
4407 }
4408
4409 if (!rb_equal(arith_seq_begin(self), arith_seq_begin(other))) {
4410 return Qfalse;
4411 }
4412
4413 if (!rb_equal(arith_seq_end(self), arith_seq_end(other))) {
4414 return Qfalse;
4415 }
4416
4417 if (!rb_equal(arith_seq_step(self), arith_seq_step(other))) {
4418 return Qfalse;
4419 }
4420
4421 if (arith_seq_exclude_end_p(self) != arith_seq_exclude_end_p(other)) {
4422 return Qfalse;
4423 }
4424
4425 return Qtrue;
4426}
4427
4428/*
4429 * call-seq:
4430 * aseq.hash -> integer
4431 *
4432 * Compute a hash-value for this arithmetic sequence.
4433 * Two arithmetic sequences with same begin, end, step, and exclude_end?
4434 * values will generate the same hash-value.
4435 *
4436 * See also Object#hash.
4437 */
4438static VALUE
4439arith_seq_hash(VALUE self)
4440{
4441 st_index_t hash;
4442 VALUE v;
4443
4444 hash = rb_hash_start(arith_seq_exclude_end_p(self));
4445 v = rb_hash(arith_seq_begin(self));
4446 hash = rb_hash_uint(hash, NUM2LONG(v));
4447 v = rb_hash(arith_seq_end(self));
4448 hash = rb_hash_uint(hash, NUM2LONG(v));
4449 v = rb_hash(arith_seq_step(self));
4450 hash = rb_hash_uint(hash, NUM2LONG(v));
4451 hash = rb_hash_end(hash);
4452
4453 return ST2FIX(hash);
4454}
4455
4456#define NUM_GE(x, y) RTEST(rb_num_coerce_relop((x), (y), idGE))
4457
4459 VALUE current;
4460 VALUE end;
4461 VALUE step;
4462 int excl;
4463};
4464
4465/*
4466 * call-seq:
4467 * aseq.each {|i| block } -> aseq
4468 * aseq.each -> aseq
4469 */
4470static VALUE
4471arith_seq_each(VALUE self)
4472{
4473 VALUE c, e, s, len_1, last;
4474 int x;
4475
4476 if (!rb_block_given_p()) return self;
4477
4478 c = arith_seq_begin(self);
4479 e = arith_seq_end(self);
4480 s = arith_seq_step(self);
4481 x = arith_seq_exclude_end_p(self);
4482
4483 if (!RB_TYPE_P(s, T_COMPLEX) && ruby_float_step(c, e, s, x, TRUE)) {
4484 return self;
4485 }
4486
4487 if (NIL_P(e)) {
4488 while (1) {
4489 rb_yield(c);
4490 c = rb_int_plus(c, s);
4491 }
4492
4493 return self;
4494 }
4495
4496 if (rb_equal(s, INT2FIX(0))) {
4497 while (1) {
4498 rb_yield(c);
4499 }
4500
4501 return self;
4502 }
4503
4504 len_1 = num_idiv(num_minus(e, c), s);
4505 last = num_plus(c, num_mul(s, len_1));
4506 if (x && rb_equal(last, e)) {
4507 last = num_minus(last, s);
4508 }
4509
4510 if (rb_num_negative_int_p(s)) {
4511 while (NUM_GE(c, last)) {
4512 rb_yield(c);
4513 c = num_plus(c, s);
4514 }
4515 }
4516 else {
4517 while (NUM_GE(last, c)) {
4518 rb_yield(c);
4519 c = num_plus(c, s);
4520 }
4521 }
4522
4523 return self;
4524}
4525
4526/*
4527 * call-seq:
4528 * aseq.size -> num or nil
4529 *
4530 * Returns the number of elements in this arithmetic sequence if it is a finite
4531 * sequence. Otherwise, returns <code>nil</code>.
4532 */
4533static VALUE
4534arith_seq_size(VALUE self)
4535{
4536 VALUE b, e, s, len_1, len, last;
4537 int x;
4538
4539 b = arith_seq_begin(self);
4540 e = arith_seq_end(self);
4541 s = arith_seq_step(self);
4542 x = arith_seq_exclude_end_p(self);
4543
4544 if (RB_FLOAT_TYPE_P(b) || RB_FLOAT_TYPE_P(e) || RB_FLOAT_TYPE_P(s)) {
4545 double ee, n;
4546
4547 if (NIL_P(e)) {
4548 if (rb_num_negative_int_p(s)) {
4549 ee = -HUGE_VAL;
4550 }
4551 else {
4552 ee = HUGE_VAL;
4553 }
4554 }
4555 else {
4556 ee = NUM2DBL(e);
4557 }
4558
4559 n = ruby_float_step_size(NUM2DBL(b), ee, NUM2DBL(s), x);
4560 if (isinf(n)) return DBL2NUM(n);
4561 if (POSFIXABLE(n)) return LONG2FIX((long)n);
4562 return rb_dbl2big(n);
4563 }
4564
4565 if (NIL_P(e)) {
4566 return DBL2NUM(HUGE_VAL);
4567 }
4568
4569 if (!rb_obj_is_kind_of(s, rb_cNumeric)) {
4570 s = rb_to_int(s);
4571 }
4572
4573 if (rb_equal(s, INT2FIX(0))) {
4574 return DBL2NUM(HUGE_VAL);
4575 }
4576
4577 len_1 = rb_int_idiv(rb_int_minus(e, b), s);
4578 if (rb_num_negative_int_p(len_1)) {
4579 return INT2FIX(0);
4580 }
4581
4582 last = rb_int_plus(b, rb_int_mul(s, len_1));
4583 if (x && rb_equal(last, e)) {
4584 len = len_1;
4585 }
4586 else {
4587 len = rb_int_plus(len_1, INT2FIX(1));
4588 }
4589
4590 return len;
4591}
4592
4593#define sym(name) ID2SYM(rb_intern_const(name))
4594void
4595InitVM_Enumerator(void)
4596{
4597 rb_define_method(rb_mKernel, "to_enum", obj_to_enum, -1);
4598 rb_define_method(rb_mKernel, "enum_for", obj_to_enum, -1);
4599
4600 rb_cEnumerator = rb_define_class("Enumerator", rb_cObject);
4602
4603 rb_define_alloc_func(rb_cEnumerator, enumerator_allocate);
4604 rb_define_method(rb_cEnumerator, "initialize", enumerator_initialize, -1);
4605 rb_define_method(rb_cEnumerator, "initialize_copy", enumerator_init_copy, 1);
4606 rb_define_method(rb_cEnumerator, "each", enumerator_each, -1);
4607 rb_define_method(rb_cEnumerator, "each_with_index", enumerator_each_with_index, 0);
4608 rb_define_method(rb_cEnumerator, "each_with_object", enumerator_with_object, 1);
4609 rb_define_method(rb_cEnumerator, "with_index", enumerator_with_index, -1);
4610 rb_define_method(rb_cEnumerator, "with_object", enumerator_with_object, 1);
4611 rb_define_method(rb_cEnumerator, "next_values", enumerator_next_values, 0);
4612 rb_define_method(rb_cEnumerator, "peek_values", enumerator_peek_values_m, 0);
4613 rb_define_method(rb_cEnumerator, "next", enumerator_next, 0);
4614 rb_define_method(rb_cEnumerator, "peek", enumerator_peek, 0);
4615 rb_define_method(rb_cEnumerator, "feed", enumerator_feed, 1);
4616 rb_define_method(rb_cEnumerator, "rewind", enumerator_rewind, 0);
4617 rb_define_method(rb_cEnumerator, "inspect", enumerator_inspect, 0);
4618 rb_define_method(rb_cEnumerator, "size", enumerator_size, 0);
4619 rb_define_method(rb_cEnumerator, "+", enumerator_plus, 1);
4621
4622 /* Lazy */
4623 rb_cLazy = rb_define_class_under(rb_cEnumerator, "Lazy", rb_cEnumerator);
4624 rb_define_method(rb_mEnumerable, "lazy", enumerable_lazy, 0);
4625
4626 lazy_use_super_method = rb_ident_hash_new_capa(19);
4627 rb_vm_register_global_object(lazy_use_super_method);
4628#define define_lazy_alias(name) do { \
4629 ID name_super = rb_intern_const("_enumerable_" name); \
4630 ID name_orig = rb_intern_const(name); \
4631 rb_add_alias(rb_cLazy, name_super, name_orig, METHOD_VISI_PRIVATE); \
4632 rb_hash_aset(lazy_use_super_method, ID2SYM(name_orig), ID2SYM(name_super)); \
4633 } while (0)
4634
4635 define_lazy_alias("map");
4636 define_lazy_alias("collect");
4637 define_lazy_alias("flat_map");
4638 define_lazy_alias("collect_concat");
4639 define_lazy_alias("select");
4640 define_lazy_alias("find_all");
4641 define_lazy_alias("filter");
4642 define_lazy_alias("filter_map");
4643 define_lazy_alias("reject");
4644 define_lazy_alias("grep");
4645 define_lazy_alias("grep_v");
4646 define_lazy_alias("zip");
4647 define_lazy_alias("take");
4648 define_lazy_alias("take_while");
4649 define_lazy_alias("drop");
4650 define_lazy_alias("drop_while");
4651 define_lazy_alias("uniq");
4652 define_lazy_alias("with_index");
4653 define_lazy_alias("each_with_index");
4654
4655 rb_obj_freeze(lazy_use_super_method);
4656
4657 rb_define_method(rb_cLazy, "initialize", lazy_initialize, -1);
4658 rb_define_method(rb_cLazy, "to_enum", lazy_to_enum, -1);
4659 rb_define_method(rb_cLazy, "enum_for", lazy_to_enum, -1);
4660 rb_define_method(rb_cLazy, "eager", lazy_eager, 0);
4661 rb_define_method(rb_cLazy, "map", lazy_map, 0);
4662 rb_define_method(rb_cLazy, "collect", lazy_map, 0);
4663 rb_define_method(rb_cLazy, "flat_map", lazy_flat_map, 0);
4664 rb_define_method(rb_cLazy, "collect_concat", lazy_flat_map, 0);
4665 rb_define_method(rb_cLazy, "select", lazy_select, 0);
4666 rb_define_method(rb_cLazy, "find_all", lazy_select, 0);
4667 rb_define_method(rb_cLazy, "filter", lazy_select, 0);
4668 rb_define_method(rb_cLazy, "filter_map", lazy_filter_map, 0);
4669 rb_define_method(rb_cLazy, "reject", lazy_reject, 0);
4670 rb_define_method(rb_cLazy, "grep", lazy_grep, 1);
4671 rb_define_method(rb_cLazy, "grep_v", lazy_grep_v, 1);
4672 rb_define_method(rb_cLazy, "zip", lazy_zip, -1);
4673 rb_define_method(rb_cLazy, "take", lazy_take, 1);
4674 rb_define_method(rb_cLazy, "take_while", lazy_take_while, 0);
4675 rb_define_method(rb_cLazy, "drop", lazy_drop, 1);
4676 rb_define_method(rb_cLazy, "drop_while", lazy_drop_while, 0);
4677 rb_define_method(rb_cLazy, "lazy", lazy_lazy, 0);
4678 rb_define_method(rb_cLazy, "chunk", lazy_super, -1);
4679 rb_define_method(rb_cLazy, "slice_before", lazy_super, -1);
4680 rb_define_method(rb_cLazy, "slice_after", lazy_super, -1);
4681 rb_define_method(rb_cLazy, "slice_when", lazy_super, -1);
4682 rb_define_method(rb_cLazy, "chunk_while", lazy_super, -1);
4683 rb_define_method(rb_cLazy, "uniq", lazy_uniq, 0);
4684 rb_define_method(rb_cLazy, "compact", lazy_compact, 0);
4685 rb_define_method(rb_cLazy, "with_index", lazy_with_index, -1);
4686 rb_define_method(rb_cLazy, "each_with_index", lazy_each_with_index, 0);
4687 rb_define_method(rb_cLazy, "tap_each", lazy_tap_each, 0);
4688
4689#if 0 /* for RDoc */
4690 rb_define_method(rb_cLazy, "to_a", lazy_to_a, 0);
4691 rb_define_method(rb_cLazy, "chunk", lazy_chunk, 0);
4692 rb_define_method(rb_cLazy, "chunk_while", lazy_chunk_while, 0);
4693 rb_define_method(rb_cLazy, "slice_after", lazy_slice_after, 0);
4694 rb_define_method(rb_cLazy, "slice_before", lazy_slice_before, 0);
4695 rb_define_method(rb_cLazy, "slice_when", lazy_slice_when, 0);
4696#endif
4697 rb_define_alias(rb_cLazy, "force", "to_a");
4698
4699 rb_eStopIteration = rb_define_class("StopIteration", rb_eIndexError);
4700 rb_define_method(rb_eStopIteration, "result", stop_result, 0);
4701
4702 /* :nodoc: Generator */
4703 rb_cGenerator = rb_define_class_under(rb_cEnumerator, "Generator", rb_cObject);
4704 rb_include_module(rb_cGenerator, rb_mEnumerable);
4705 rb_define_alloc_func(rb_cGenerator, generator_allocate);
4706 rb_define_method(rb_cGenerator, "initialize", generator_initialize, -1);
4707 rb_define_method(rb_cGenerator, "initialize_copy", generator_init_copy, 1);
4708 rb_define_method(rb_cGenerator, "each", generator_each, -1);
4709
4710 /* :nodoc: Yielder */
4711 rb_cYielder = rb_define_class_under(rb_cEnumerator, "Yielder", rb_cObject);
4712 rb_define_alloc_func(rb_cYielder, yielder_allocate);
4713 rb_define_method(rb_cYielder, "initialize", yielder_initialize, 0);
4714 rb_define_method(rb_cYielder, "yield", yielder_yield, -2);
4715 rb_define_method(rb_cYielder, "<<", yielder_yield_push, 1);
4716 rb_define_method(rb_cYielder, "to_proc", yielder_to_proc, 0);
4717
4718 /* :nodoc: Producer */
4719 rb_cEnumProducer = rb_define_class_under(rb_cEnumerator, "Producer", rb_cObject);
4720 rb_define_alloc_func(rb_cEnumProducer, producer_allocate);
4721 rb_define_method(rb_cEnumProducer, "each", producer_each, 0);
4722 rb_define_singleton_method(rb_cEnumerator, "produce", enumerator_s_produce, -1);
4723
4724 /* Chain */
4725 rb_cEnumChain = rb_define_class_under(rb_cEnumerator, "Chain", rb_cEnumerator);
4726 rb_define_alloc_func(rb_cEnumChain, enum_chain_allocate);
4727 rb_define_method(rb_cEnumChain, "initialize", enum_chain_initialize, -2);
4728 rb_define_method(rb_cEnumChain, "initialize_copy", enum_chain_init_copy, 1);
4729 rb_define_method(rb_cEnumChain, "each", enum_chain_each, -1);
4730 rb_define_method(rb_cEnumChain, "size", enum_chain_size, 0);
4731 rb_define_method(rb_cEnumChain, "rewind", enum_chain_rewind, 0);
4732 rb_define_method(rb_cEnumChain, "inspect", enum_chain_inspect, 0);
4733 rb_undef_method(rb_cEnumChain, "feed");
4734 rb_undef_method(rb_cEnumChain, "next");
4735 rb_undef_method(rb_cEnumChain, "next_values");
4736 rb_undef_method(rb_cEnumChain, "peek");
4737 rb_undef_method(rb_cEnumChain, "peek_values");
4738
4739 /* Product */
4740 rb_cEnumProduct = rb_define_class_under(rb_cEnumerator, "Product", rb_cEnumerator);
4741 rb_define_alloc_func(rb_cEnumProduct, enum_product_allocate);
4742 rb_define_method(rb_cEnumProduct, "initialize", enum_product_initialize, -1);
4743 rb_define_method(rb_cEnumProduct, "initialize_copy", enum_product_init_copy, 1);
4744 rb_define_method(rb_cEnumProduct, "each", enum_product_each, 0);
4745 rb_define_method(rb_cEnumProduct, "size", enum_product_size, 0);
4746 rb_define_method(rb_cEnumProduct, "rewind", enum_product_rewind, 0);
4747 rb_define_method(rb_cEnumProduct, "inspect", enum_product_inspect, 0);
4748 rb_undef_method(rb_cEnumProduct, "feed");
4749 rb_undef_method(rb_cEnumProduct, "next");
4750 rb_undef_method(rb_cEnumProduct, "next_values");
4751 rb_undef_method(rb_cEnumProduct, "peek");
4752 rb_undef_method(rb_cEnumProduct, "peek_values");
4753 rb_define_singleton_method(rb_cEnumerator, "product", enumerator_s_product, -1);
4754
4755 /* ArithmeticSequence */
4756 rb_cArithSeq = rb_define_class_under(rb_cEnumerator, "ArithmeticSequence", rb_cEnumerator);
4757 rb_undef_alloc_func(rb_cArithSeq);
4758 rb_undef_method(CLASS_OF(rb_cArithSeq), "new");
4759 rb_define_method(rb_cArithSeq, "begin", arith_seq_begin, 0);
4760 rb_define_method(rb_cArithSeq, "end", arith_seq_end, 0);
4761 rb_define_method(rb_cArithSeq, "exclude_end?", arith_seq_exclude_end, 0);
4762 rb_define_method(rb_cArithSeq, "step", arith_seq_step, 0);
4763 rb_define_method(rb_cArithSeq, "first", arith_seq_first, -1);
4764 rb_define_method(rb_cArithSeq, "last", arith_seq_last, -1);
4765 rb_define_method(rb_cArithSeq, "inspect", arith_seq_inspect, 0);
4766 rb_define_method(rb_cArithSeq, "==", arith_seq_eq, 1);
4767 rb_define_method(rb_cArithSeq, "===", arith_seq_eq, 1);
4768 rb_define_method(rb_cArithSeq, "eql?", arith_seq_eq, 1);
4769 rb_define_method(rb_cArithSeq, "hash", arith_seq_hash, 0);
4770 rb_define_method(rb_cArithSeq, "each", arith_seq_each, 0);
4771 rb_define_method(rb_cArithSeq, "size", arith_seq_size, 0);
4772
4773 rb_provide("enumerator.so"); /* for backward compatibility */
4774}
4775#undef sym
4776
4777void
4778Init_Enumerator(void)
4779{
4780 id_rewind = rb_intern_const("rewind");
4781 id_next = rb_intern_const("next");
4782 id_result = rb_intern_const("result");
4783 id_receiver = rb_intern_const("receiver");
4784 id_arguments = rb_intern_const("arguments");
4785 id_memo = rb_intern_const("memo");
4786 id_method = rb_intern_const("method");
4787 id_force = rb_intern_const("force");
4788 id_to_enum = rb_intern_const("to_enum");
4789 id_each_entry = rb_intern_const("each_entry");
4790 sym_each = ID2SYM(id_each);
4791 sym_yield = ID2SYM(rb_intern_const("yield"));
4792
4793 InitVM(Enumerator);
4794}
#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:1769
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3094
void rb_need_block(void)
Declares that the current method needs a block.
Definition eval.c:1056
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2897
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:3397
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3384
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1048
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1035
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3173
#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 T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define rb_exc_new2
Old name of rb_exc_new_cstr.
Definition error.h:37
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
#define POSFIXABLE
Old name of RB_POSFIXABLE.
Definition fixnum.h:29
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
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:2381
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1477
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1473
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1471
VALUE rb_eStopIteration
StopIteration exception.
Definition enumerator.c:196
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:468
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:1524
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1475
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:234
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:556
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:669
VALUE rb_cRange
Range class.
Definition range.c:35
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:140
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:906
VALUE rb_obj_freeze(VALUE obj)
Same as RB_OBJ_FREEZE(), but returns the given object.
Definition object.c:1309
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3328
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1123
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition vm_eval.c:1081
VALUE rb_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:1200
#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:363
VALUE rb_ary_new_from_values(long n, const VALUE *elts)
Identical to rb_ary_new_from_args(), except how objects are passed.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_cat(VALUE ary, const VALUE *train, long len)
Destructively appends multiple elements at the end of the array.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_resize(VALUE ary, long len)
Expands or shrinks the passed array to the passed length.
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
VALUE rb_enumerator_size_func(VALUE recv, VALUE argv, VALUE eobj)
This is the type of functions that rb_enumeratorize_with_size() expects.
Definition enumerator.h:45
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
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:710
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:2916
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:1575
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:1763
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:1717
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:386
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:2352
#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:3913
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2038
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:3879
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3500
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.
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2141
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition variable.c:1641
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:398
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3693
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1846
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:691
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:685
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:1148
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:14145
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:14135
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:1401
VALUE rb_yield_values2(int n, const VALUE *argv)
Identical to rb_yield_values(), except it takes the parameters as a C array instead of variadic argum...
Definition vm_eval.c:1423
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1378
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:1429
VALUE rb_block_call_func(RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg))
This is the type of a function that the interpreter expect for C-backended blocks.
Definition iterator.h:83
VALUE rb_block_call_kw(VALUE obj, ID mid, int argc, const VALUE *argv, rb_block_call_func_t proc, VALUE data2, int kw_splat)
Identical to rb_funcallv_kw(), except it additionally passes a function as a block.
Definition vm_eval.c:1570
#define rb_long2int
Just another name of rb_long2int_inline.
Definition long.h:62
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE rb_block_call(VALUE q, ID w, int e, const VALUE *r, type *t, VALUE y)
Call a method with a block.
VALUE rb_proc_new(type *q, VALUE w)
Creates a rb_cProc instance.
VALUE rb_fiber_new(type *q, VALUE w)
Creates a rb_cFiber 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)
Definition rarray.h:402
#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
#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:116
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
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:242
VALUE flags
Type-specific behavioural characteristics.
Definition rtypeddata.h:356
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