class Scale::Bytes

Attributes

bytes[R]
data[R]
offset[R]

Public Class Methods

new(data) click to toggle source
# File lib/scale_bytes.rb, line 6
def initialize(data)
  if (data.class == Array) && data.is_byte_array?
    @bytes = data
  elsif (data.class == String) && data.start_with?("0x") && (data.length % 2 == 0)
    arr = data[2..].scan(/../).map(&:hex)
    @bytes = arr
  else
    raise "Provided data is not valid"
  end

  @data = data
  @offset = 0
end

Public Instance Methods

==(other) click to toggle source
# File lib/scale_bytes.rb, line 55
def ==(other)
  bytes == other.bytes && offset == other.offset
end
get_next_bytes(length) click to toggle source
# File lib/scale_bytes.rb, line 24
def get_next_bytes(length)
  result = @bytes[@offset...@offset + length]
  if result.length < length
    str = @data[(2 + @offset * 2)..]
    str = str.length > 40 ? (str[0...40]).to_s + "..." : str
    raise "No enough data: #{str}, expect length: #{length}, but #{result.length}" 
  end
  @offset += length
  result
rescue RangeError => ex
  puts "length: #{length}"
  puts ex.message
  puts ex.backtrace
end
get_remaining_bytes() click to toggle source
# File lib/scale_bytes.rb, line 39
def get_remaining_bytes
  @bytes[offset..]
end
reset_offset() click to toggle source
# File lib/scale_bytes.rb, line 20
def reset_offset
  @offset = 0
end
to_ascii() click to toggle source
# File lib/scale_bytes.rb, line 51
def to_ascii 
  @bytes[0...offset].pack("C*") + "<================================>" + @bytes[offset..].pack("C*")
end
to_bin_string() click to toggle source
# File lib/scale_bytes.rb, line 47
def to_bin_string
  @bytes.bytes_to_bin
end
to_hex_string() click to toggle source
# File lib/scale_bytes.rb, line 43
def to_hex_string
  @bytes.bytes_to_hex
end
to_s() click to toggle source
# File lib/scale_bytes.rb, line 59
def to_s
  green(@bytes[0...offset].bytes_to_hex) + yellow(@bytes[offset..].bytes_to_hex[2..])
end