bta-proxy/bta_proxy/datainputstream.py

65 lines
2.0 KiB
Python
Raw Normal View History

2023-08-25 21:49:10 +03:00
from asyncio.queues import Queue
2023-08-24 15:29:57 +03:00
import struct
2023-08-25 21:49:10 +03:00
class AsyncDataInputStream:
def __init__(self, queue: Queue):
self._queue = queue
self._last = b''
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_bytes(self, n: int) -> bytes:
if len(self._last) < n:
self._last += await self._queue.get()
out, self._last = self._last[:n], self._last[n:]
return out
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read(self) -> int:
return (await self.read_bytes(1))[0]
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_boolean(self) -> bool:
return (await self.read()) != 0
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_short(self) -> int:
return struct.unpack('>h', await self.read_bytes(2))[0]
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_ushort(self) -> int:
return struct.unpack('>H', await self.read_bytes(2))[0]
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_int(self) -> int:
return struct.unpack('>i', await self.read_bytes(4))[0]
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_uint(self) -> int:
return struct.unpack('>I', await self.read_bytes(4))[0]
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_long(self) -> int:
return struct.unpack('>q', await self.read_bytes(8))[0]
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_ulong(self) -> int:
return struct.unpack('>Q', await self.read_bytes(8))[0]
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_float(self) -> float:
return struct.unpack('>f', await self.read_bytes(4))[0]
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_double(self) -> float:
return struct.unpack('>d', await self.read_bytes(8))[0]
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_char(self) -> str:
return chr(await self.read_ushort())
2023-08-24 15:29:57 +03:00
2023-08-25 21:49:10 +03:00
async def read_varint(self, bits: int = 32) -> int:
2023-08-24 15:29:57 +03:00
value: int = 0
position: int = 0
while True:
2023-08-25 21:49:10 +03:00
byte = await self.read()
2023-08-24 15:29:57 +03:00
value |= (byte & 0x7F) << position
if ((byte & 0x80) == 0):
break
position += 7
if position >= bits:
raise ValueError('varint too big')
return value
2023-08-25 21:49:10 +03:00
async def read_string(self) -> str:
size = await self.read_short()
return (await self.read_bytes(size)).decode('utf-8')
2023-08-24 15:29:57 +03:00