1 # -*- encoding: binary -*-
2 # frozen_string_literal: false
4 # This is a wrapper around Raindrops objects much like the core Ruby
5 # \Struct can be seen as a wrapper around the core \Array class.
6 # It's usage is similar to the core \Struct class, except its fields
7 # may only be used to house unsigned long integers.
9 # class Foo < Raindrops::Struct.new(:readers, :writers)
14 # foo.incr_writers -> 1
15 # foo.incr_readers -> 1
17 class Raindrops::Struct
19 # returns a new class derived from Raindrops::Struct and supporting
20 # the given +members+ as fields, just like \Struct.new in core Ruby.
21 def self.new(*members)
22 members = members.map { |x| x.to_sym }.freeze
24 def initialize(*values)
25 (MEMBERS.size >= values.size) or raise ArgumentError, "too many arguments"
26 @raindrops = Raindrops.new(MEMBERS.size)
27 values.each_with_index { |val,i| @raindrops[i] = values[i] }
30 def initialize_copy(src)
31 @raindrops = src.instance_variable_get(:@raindrops).dup
35 @raindrops[index] = value
43 ary = @raindrops.to_ary
45 MEMBERS.each_with_index { |member, i| rv[member] = ary[i] }
50 members.each_with_index do |member, i|
51 str << "def incr_#{member}; @raindrops.incr(#{i}); end; " \
52 "def decr_#{member}; @raindrops.decr(#{i}); end; " \
53 "def #{member}; @raindrops[#{i}]; end; " \
54 "def #{member}=(val); @raindrops[#{i}] = val; end; "
58 klass.const_set(:MEMBERS, members)