rdoc: 100% documentation coverage!
[raindrops.git] / lib / raindrops / struct.rb
blobe81a78eb7d3dc1f440154d7157dc6c542947dc40
1 # -*- encoding: binary -*-
3 # This is a wrapper around Raindrops objects much like the core Ruby
4 # \Struct can be seen as a wrapper around the core \Array class.
5 # It's usage is similar to the core \Struct class, except its fields
6 # may only be used to house unsigned long integers.
8 #   class Foo < Raindrops::Struct.new(:readers, :writers)
9 #   end
11 #   foo = Foo.new 0, 0
13 #   foo.incr_writers    -> 1
14 #   foo.incr_readers    -> 1
16 class Raindrops::Struct
18   # returns a new class derived from Raindrops::Struct and supporting
19   # the given +members+ as fields, just like \Struct.new in core Ruby.
20   def self.new(*members)
21     members = members.map { |x| x.to_sym }.freeze
22     str = <<EOS
23 def initialize(*values)
24   (MEMBERS.size >= values.size) or raise ArgumentError, "too many arguments"
25   @raindrops = Raindrops.new(MEMBERS.size)
26   values.each_with_index { |val,i| @raindrops[i] = values[i] }
27 end
29 def initialize_copy(src)
30   @raindrops = src.instance_variable_get(:@raindrops).dup
31 end
33 def []=(index, value)
34   @raindrops[index] = value
35 end
37 def [](index)
38   @raindrops[index]
39 end
41 def to_hash
42   ary = @raindrops.to_ary
43   rv = {}
44   MEMBERS.each_with_index { |member, i| rv[member] = ary[i] }
45   rv
46 end
47 EOS
49     members.each_with_index do |member, i|
50       str << "def incr_#{member}; @raindrops.incr(#{i}); end; " \
51              "def decr_#{member}; @raindrops.decr(#{i}); end; " \
52              "def #{member}; @raindrops[#{i}]; end; " \
53              "def #{member}=(val); @raindrops[#{i}] = val; end; "
54     end
56     klass = Class.new
57     klass.const_set(:MEMBERS, members)
58     klass.class_eval(str)
59     klass
60   end
62 end