Module: Takumi::Packet

Defined in:
lib/takumi/packet.rb,
lib/takumi/packet/dsl.rb,
lib/takumi/packet/string.rb,
lib/takumi/packet/ushort.rb,
lib/takumi/packet/varint.rb,
lib/takumi/packet/version.rb

Defined Under Namespace

Modules: Dsl Classes: String, UnknownField, Ushort, Varint

Constant Summary collapse

VERSION =
"0.0.2"

Class Method Summary collapse

Class Method Details

.decode(packet_type, packet) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/takumi/packet.rb', line 7

def decode(packet_type, packet)
  packet_size, read = Packet::Varint.decode(packet)
  packet = packet[read, packet_size]

  fields = {}
  packet_type.fields.each do |field|
    case field[:type]
    when :varint
      data, read = ::Takumi::Packet::Varint.decode(packet)
    when :string
      data, read = ::Takumi::Packet::String.decode(packet)
    when :ushort
      data, read = ::Takumi::Packet::Ushort.decode(packet)
    else
      raise ::Takumi::Packet::UnknownField, field.inspect
    end
    fields[field[:name]] = data
    packet = packet[read..-1]
  end
  fields
end

.encode(packet_type, object) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/takumi/packet.rb', line 29

def encode(packet_type, object)
  packet = "".encode(Encoding::BINARY)
  packet_type.fields.each do |field|
    val = object.send(field[:name])

    case field[:type]
    when :varint
      packet << ::Takumi::Packet::Varint.new(val).to_s
    when :string
      packet << ::Takumi::Packet::String.new(val).to_s
    when :ushort
      packet << ::Takumi::Packet::Ushort.new(val).to_s
    else
      raise ::Takumi::Packet::UnknownField, field.inspect
    end
  end
  size = ::Takumi::Packet::Varint.new(packet.size).to_s
  size + packet
end