Class: Scale::Types::Bytes

Inherits:
Object
  • Object
show all
Includes:
Base
Defined in:
lib/scale/types.rb

Instance Attribute Summary

Attributes included from Base

#value

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Base

#==, included, #initialize, #to_human

Class Method Details

.decode(scale_bytes) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/scale/types.rb', line 182

def self.decode(scale_bytes)
  puts "BEGIN " + self::TYPE_NAME + ": #{scale_bytes}" if Scale::Types.debug == true
  length = Scale::Types::Compact.decode(scale_bytes).value
  bytes = scale_bytes.get_next_bytes(length)

  # [67, 97, 102, 195, 169].pack('C*').force_encoding('utf-8')
  # => "Café"
  str = bytes.pack("C*").force_encoding("utf-8")
  # TODO: ?
  if (not str.include?("\u0000")) && str.valid_encoding?
    puts "  END " + self::TYPE_NAME + ": #{scale_bytes}" if Scale::Types.debug == true
    new str
  else
    puts "  END " + self::TYPE_NAME + ": #{scale_bytes}" if Scale::Types.debug == true
    new bytes.bytes_to_hex
  end
end

Instance Method Details

#encodeObject



200
201
202
203
204
205
206
207
208
209
210
# File 'lib/scale/types.rb', line 200

def encode
  if value.start_with?("0x")
    length = Compact.new((value.length - 2)/2).encode
    "#{length}#{value[2..]}"
  else
    bytes = value.unpack("C*")
    hex_string = bytes.bytes_to_hex[2..]
    length = Compact.new(bytes.length).encode
    "#{length}#{hex_string}"
  end
end