Class: MTProto::Transport::AbridgedPacketCodec

Inherits:
Object
  • Object
show all
Defined in:
lib/mtproto/transport/abridged_packet_codec.rb

Constant Summary collapse

TAG =
"\xef".b
OBFUSCATE_TAG =
"\xef\xef\xef\xef".b
MAX_PACKET_SIZE =
1_048_576

Instance Method Summary collapse

Constructor Details

#initialize(stream) ⇒ AbridgedPacketCodec

Returns a new instance of AbridgedPacketCodec.



9
10
11
# File 'lib/mtproto/transport/abridged_packet_codec.rb', line 9

def initialize(stream)
  @stream = stream
end

Instance Method Details

#scanObject

Raises:



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/mtproto/transport/abridged_packet_codec.rb', line 27

def scan
  first_byte = read_exactly(1)
  length = first_byte.unpack1('C')

  if length >= 127
    length_bytes = read_exactly(3)
    length = "#{length_bytes}\x00".unpack1('L<')
  end

  actual_length = length << 2

  raise PacketReadError, "Packet too large: #{actual_length} bytes" if actual_length > MAX_PACKET_SIZE

  data = read_exactly(actual_length)
  Packet.new(data.bytes)
end

#send(packet) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/mtproto/transport/abridged_packet_codec.rb', line 13

def send(packet)
  length = packet.size >> 2

  if length < 127
    @stream.write [length].pack('C')
  else
    @stream.write "\x7f".b + [length].pack('L<')[0, 3]
  end

  @stream.write packet.data.pack('C*')
end