Class: Majoron::AntHill::ByteBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/byte_buffer.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(buf) ⇒ ByteBuffer

Constructor



23
24
25
# File 'lib/byte_buffer.rb', line 23

def initialize(buf)
  @buffer = buf
end

Class Method Details

.decode_hex(hex) ⇒ Object

Decode buffer from hex Support two types: 0B 05 04 and 0B0504



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/byte_buffer.rb', line 63

def self.decode_hex(hex)
  data = String.new
  return data if hex.nil?
  if hex.index(' ')
    hex.split(" ").each do |val|
      data << val.hex.chr
    end
  else
    digits  = String.new
    hex.each_char do |char|
      digits << char
      if digits.size.divmod(2)[1] == 0
        data << digits.hex.chr
        digits.clear
      end
    end
  end
  data
end

.encode_hex(data) ⇒ Object

Encode buffer to hex



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/byte_buffer.rb', line 46

def self.encode_hex(data)
  hex = String.new
  return hex if data.nil?
  0.upto(data.size() - 1) do |i|
    if RUBY_VERSION >= "1.9.0"
      hex << data[i..i].unpack("H2")[0].to_s
    else
      hex << data[i..i].unpack("H2").to_s
    end
    #hex << data[i..i].unpack("H2").to_s
    hex << " " if i != data.size() - 1
  end
  return hex.upcase
end

Instance Method Details

#dump_buffer(ostream) ⇒ Object

Dump buffer to stream



40
41
42
# File 'lib/byte_buffer.rb', line 40

def dump_buffer (ostream)
  reaise "not impelemented yet"
end

#read_dump(istream) ⇒ Object

Read data from stream to buffer



28
29
30
31
32
# File 'lib/byte_buffer.rb', line 28

def read_dump (istream)
  istream.each do |line|
    @buffer << ByteBuffer.decode_hex(line)
  end
end

#write_dump(ostream) ⇒ Object

Write data from buffer to stream



35
36
37
# File 'lib/byte_buffer.rb', line 35

def write_dump (ostream)
  ostream << ByteBuffer.encode_hex(@buffer)
end