summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-enum-chain/mrblib/chain.rb
blob: 98515ea1406d77ecf2cc6fa2291342c4e9025fcc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
##
# chain.rb Enumerator::Chain class
# See Copyright Notice in mruby.h

module Enumerable
  def chain(*args)
    Enumerator::Chain.new(self, *args)
  end

  def +(other)
    Enumerator::Chain.new(self, other)
  end
end

class Enumerator
  class Chain
    include Enumerable

    def initialize(*args)
      @enums = args
    end

    def initialize_copy(orig)
      @enums = orig.__copy_enums
    end

    def each(&block)
      return to_enum unless block_given?

      @enums.each { |e| e.each(&block) }

      self
    end

    def size
      @enums.reduce(0) do |a, e|
        return nil unless e.respond_to?(:size)
        a + e.size
      end
    end

    def rewind
      @enums.reverse_each do |e|
        e.rewind if e.respond_to?(:rewind)
      end

      self
    end

    def inspect
      "#<#{self.class}: #{@enums.inspect}>"
    end

    def __copy_enums
      @enums.each_with_object([]) do |e, a|
        a << e.clone
      end
    end
  end
end