Python client for GEX

PayloadBuilder.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import struct
  2. class PayloadBuilder:
  3. """
  4. Utility for building binary payloads
  5. """
  6. def __init__(self, endian:str='little'):
  7. self.buf = bytearray()
  8. self.endian = endian
  9. def close(self) -> bytearray:
  10. """ Get the byte buffer """
  11. return self.buf
  12. def reset(self):
  13. """ Clear the buffer """
  14. self.buf.clear()
  15. def u8(self, num:int):
  16. """ Add a uint8_t """
  17. self.buf.extend((num&0xFF).to_bytes(length=1, byteorder=self.endian, signed=False))
  18. def u16(self, num:int):
  19. """ Add a uint16_t """
  20. self.buf.extend((num&0xFFFF).to_bytes(length=2, byteorder=self.endian, signed=False))
  21. def u24(self, num:int):
  22. """ Add a uint24_t (for use with RGB colors) """
  23. self.buf.extend((num&0xFFFFFF).to_bytes(length=3, byteorder=self.endian, signed=False))
  24. def u32(self, num:int):
  25. """ Add a uint32_t """
  26. self.buf.extend(num.to_bytes(length=4, byteorder=self.endian, signed=False))
  27. def u64(self, num:int):
  28. """ Add a uint64_t """
  29. self.buf.extend(num.to_bytes(length=8, byteorder=self.endian, signed=False))
  30. def i8(self, num:int):
  31. """ Add a int8_t """
  32. self.buf.extend(num.to_bytes(length=1, byteorder=self.endian, signed=True))
  33. def i16(self, num:int):
  34. """ Add a int16_t """
  35. self.buf.extend(num.to_bytes(length=2, byteorder=self.endian, signed=True))
  36. def i32(self, num:int):
  37. """ Add a int32_t """
  38. self.buf.extend(num.to_bytes(length=4, byteorder=self.endian, signed=True))
  39. def i64(self, num:int):
  40. """ Add a int64_t """
  41. self.buf.extend(num.to_bytes(length=8, byteorder=self.endian, signed=True))
  42. def float(self, num:float):
  43. """ Add a float (4 bytes) """
  44. fmt = '<f' if self.endian == 'little' else '>f'
  45. self.buf.extend(struct.pack(fmt, num))
  46. def double(self, num:float):
  47. """ Add a double (8 bytes) """
  48. fmt = '<d' if self.endian == 'little' else '>d'
  49. self.buf.extend(struct.pack(fmt, num))
  50. def bool(self, num:bool):
  51. """ Add a bool (0 or 1) """
  52. self.buf.append(1 if num != False else 0)
  53. def str(self, string:str):
  54. """ Add a 0-terminated string """
  55. self.buf.extend(string.encode('utf-8'))
  56. self.buf.append(0)
  57. def blob(self, blob):
  58. """ Ad an arbitrary blob (bytearray or binary string) """
  59. self.buf.extend(blob)
  60. def zeros(self, count):
  61. for i in range(0,count):
  62. self.buf.append(0)