Module: BitFields::InstanceMethods

Included in:
BitFields
Defined in:
lib/bit_fields.rb

Defined Under Namespace

Classes: ValueOverflow

Instance Attribute Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



251
252
253
254
255
256
257
# File 'lib/bit_fields.rb', line 251

def method_missing name, *args
  if @raw.respond_to? name
    @raw.send name, *args
  else
    super
  end
end

Instance Attribute Details

#attributesObject (readonly)

caches the bit field values



160
161
162
# File 'lib/bit_fields.rb', line 160

def attributes
  @attributes
end

#rawObject (readonly)

Contains the raw string



157
158
159
# File 'lib/bit_fields.rb', line 157

def raw
  @raw
end

#unpackedObject (readonly)

caches the bin string unpacked values



163
164
165
# File 'lib/bit_fields.rb', line 163

def unpacked
  @unpacked
end

Instance Method Details

#[](name) ⇒ Object

Makes defined fields accessible like a Hash



179
180
181
# File 'lib/bit_fields.rb', line 179

def [](name) 
  self.attributes[name]
end

#initialize(bit_string_or_hash) ⇒ Object

Takes the raw binary string and parses it



169
170
171
172
173
174
175
176
# File 'lib/bit_fields.rb', line 169

def initialize bit_string_or_hash
  if bit_string_or_hash.kind_of?(Hash)
    @attributes = bit_string_or_hash
    pack_bit_fields
  else
    parse_bit_fields(bit_string_or_hash) #.dup.freeze REMOVED: seems useless
  end
end

#pack_bit_fieldsObject Also known as: pack

Parses the raw value extracting the defined bit fields



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/bit_fields.rb', line 215

def pack_bit_fields
  @unpacked = []
  
  self.class.fields.each_with_index do |name, position|
    
    if bit_fields = self.class.bit_fields[name]
    
      bit_value = 0
      bit_fields.each do |(bit_name, bits_number, bit_mask)|
        masked = @attributes[bit_name] & bit_mask
        
        raise ValueOverflow, 
              "the value #{@attributes[bit_name]} "+
              "is too big for #{bits_number} bits" if masked != @attributes[bit_name]
        
        bit_value = bit_value << bits_number
        bit_value |= masked
      end
      
      # Value of fields composed by binary fields is always overwritten
      # by the composition of the latter
      attributes[name] = bit_value
    end
    
    @unpacked[position] = @attributes[name] || 0
    
  end
  
  @raw = @unpacked.pack( self.class.unpack_recipe )
end

#to_sObject



247
248
249
# File 'lib/bit_fields.rb', line 247

def to_s
  raw.to_s
end