Class: DataTypes::BitField

Inherits:
BaseType show all
Defined in:
lib/active_model_serializers_binary/data_types.rb

Instance Attribute Summary

Attributes inherited from BaseType

#bit_length, #count, #length, #name, #parent, #raw_value, #sign, #type, #value

Instance Method Summary collapse

Methods inherited from BaseType

#after_load, #before_dump, #check, #check_raw_value, #check_value, #size, #to_s, #trim

Constructor Details

#initialize(options = {}) ⇒ BitField

Returns a new instance of BitField.



103
104
105
106
# File 'lib/active_model_serializers_binary/data_types.rb', line 103

def initialize(options = {})
  length = options[:bin_length].blank? ? 1 : (options[:bin_length] > 32 ? 32 : options[:bin_length])
  super options.merge :bit_length => length, :sign => :unsigned
end

Instance Method Details

#dump(value = nil) ⇒ Object



128
129
130
131
132
# File 'lib/active_model_serializers_binary/data_types.rb', line 128

def dump(value=nil)
  before_dump( value )
  data = @value.pack(format).unpack('b*').first.chars.each_slice(word_length).map(&:join).map{|n| n.slice(0,bit_length)}
  @raw_value = [data.join].pack('b*').unpack('C*')
end

#formatObject



108
109
110
111
112
113
114
115
116
# File 'lib/active_model_serializers_binary/data_types.rb', line 108

def format
  if bit_length <= 8 # 8 bits
    'C*'
  elsif bit_length <= 16 # 16 bits
    'v*'
  else # 32 bits
    'l*'
  end
end

#load(raw_value) ⇒ Object



134
135
136
137
# File 'lib/active_model_serializers_binary/data_types.rb', line 134

def load(raw_value)
  self.value = check_raw_value(raw_value).pack('C*').unpack('b*').first.chars.slice(0,@bit_length*@count).each_slice(bit_length).map(&:join).map{|n| [n].pack('b*').unpack('C*').first}
  after_load
end

#word_lengthObject



118
119
120
121
122
123
124
125
126
# File 'lib/active_model_serializers_binary/data_types.rb', line 118

def word_length
  if bit_length <= 8 # 8 bits
    8
  elsif bit_length <= 16 # 16 bits
    16
  else # 32 bits
    32
  end
end