giants-maps-gui/lib/packet.py
2021-12-23 00:25:10 +01:00

71 lines
1.9 KiB
Python

import io
import struct
class Packet(io.BytesIO):
def put_byte(self, val) -> None:
self.write(struct.pack('<B', val % 256))
def get_byte(self) -> int:
return struct.unpack('<B', self.read(1))[0]
def put_bytes(self, b) -> None:
for byte in b:
self.write(struct.pack('<B', byte))
def get_bytes(self, num) -> bytes:
return bytes(struct.unpack('<'+str(num)+'B', self.read(num)))
def put_short(self, val) -> None:
self.write(struct.pack('<H', val))
def get_short(self) -> int:
return struct.unpack('<H', self.read(2))[0]
def put_long(self, val) -> None:
self.write(struct.pack('<l', val))
def put_ulong(self, val) -> None:
self.write(struct.pack('<L', val))
def get_long(self) -> int:
return struct.unpack('<l', self.read(4))[0]
def get_ulong(self) -> int:
return struct.unpack('<L', self.read(4))[0]
def put_longlong(self, val) -> None:
self.write(struct.pack('<Q', val))
def get_longlong(self) -> int:
return struct.unpack('<Q', self.read(8))[0]
def put_float(self, val) -> None:
self.write(struct.pack('<f', val))
def get_float(self) -> float:
return struct.unpack('<f', self.read(4))[0]
def put_string(self, val) -> None:
self.write(val + b'\x00')
def put_string_size(self, val, size) -> None:
self.write(val.encode("utf8") + b"\x00" * (size - len(val)))
def get_string_until_none(self) -> str:
s = ""
c = self.get_byte()
while c != 0x00:
s += chr(c)
c = self.get_byte()
return s
def get_string(self, size) -> str:
return self.get_bytes(size).decode("utf8").replace("\x00", "")
def get_3bytes_int(self) -> int:
return struct.unpack("<L", self.read(3)+b"\x00")[0]
def put_3bytes_int(self, val) -> None:
self.write(struct.pack("<L", val)[:-1])