2018-05-10 15:22:19 +03:00
|
|
|
import struct
|
|
|
|
|
2019-03-12 03:12:55 +03:00
|
|
|
from .connection import Connection, PacketCodec
|
2018-05-10 15:22:19 +03:00
|
|
|
|
|
|
|
|
2019-03-12 03:12:55 +03:00
|
|
|
class AbridgedPacketCodec(PacketCodec):
|
2019-03-10 03:00:11 +03:00
|
|
|
tag = b'\xef'
|
2019-03-12 03:12:55 +03:00
|
|
|
obfuscate_tag = b'\xef\xef\xef\xef'
|
2019-03-10 03:00:11 +03:00
|
|
|
|
|
|
|
def encode_packet(self, data):
|
2018-09-27 20:22:35 +03:00
|
|
|
length = len(data) >> 2
|
2018-05-10 15:22:19 +03:00
|
|
|
if length < 127:
|
|
|
|
length = struct.pack('B', length)
|
|
|
|
else:
|
|
|
|
length = b'\x7f' + int.to_bytes(length, 3, 'little')
|
2019-03-10 03:00:11 +03:00
|
|
|
return length + data
|
2018-05-10 15:22:19 +03:00
|
|
|
|
2019-03-10 03:00:11 +03:00
|
|
|
async def read_packet(self, reader):
|
|
|
|
length = struct.unpack('<B', await reader.readexactly(1))[0]
|
2018-09-27 20:22:35 +03:00
|
|
|
if length >= 127:
|
|
|
|
length = struct.unpack(
|
2019-03-10 03:00:11 +03:00
|
|
|
'<i', await reader.readexactly(3) + b'\0')[0]
|
2018-09-27 20:22:35 +03:00
|
|
|
|
2019-03-10 03:00:11 +03:00
|
|
|
return await reader.readexactly(length << 2)
|
2019-03-12 03:12:55 +03:00
|
|
|
|
|
|
|
|
|
|
|
class ConnectionTcpAbridged(Connection):
|
|
|
|
"""
|
|
|
|
This is the mode with the lowest overhead, as it will
|
|
|
|
only require 1 byte if the packet length is less than
|
|
|
|
508 bytes (127 << 2, which is very common).
|
|
|
|
"""
|
|
|
|
packet_codec = AbridgedPacketCodec
|