rand_array.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env python3
  2. '''
  3. This script generates a rust array filled with random bytes.
  4. '''
  5. import random
  6. import unittest
  7. import sys
  8. LINESEP = "\n"
  9. def better_hex(byte: int) -> str:
  10. return "0x{:02X}".format(byte)
  11. def make_array(bytes: bytes, col_limit: int = 100, indent: int = 4) -> str:
  12. indent_str = " " * (indent - 1)
  13. output = "[" + LINESEP
  14. line = indent_str
  15. for byte in bytes:
  16. next = " " + better_hex(byte) + ","
  17. if len(line) + len(next) >= col_limit:
  18. output += line + LINESEP
  19. line = indent_str
  20. line += next
  21. output += line + LINESEP + "];"
  22. return output
  23. class TestMakeArray(unittest.TestCase):
  24. def test_make_array(self):
  25. bytes = b"\x8b!\xe9z\x14\xbc\xc6\xef\xf9(Y\xd5\xbd\xe8\xfb\x8a\x13I\xea,\xac\x9b\x7f\xf18\x8b\x94\x81\xe3\xf9!\xcc"
  26. expected = '''[
  27. 0x8B, 0x21, 0xE9, 0x7A, 0x14, 0xBC, 0xC6, 0xEF, 0xF9, 0x28, 0x59, 0xD5, 0xBD, 0xE8, 0xFB, 0x8A,
  28. 0x13, 0x49, 0xEA, 0x2C, 0xAC, 0x9B, 0x7F, 0xF1, 0x38, 0x8B, 0x94, 0x81, 0xE3, 0xF9, 0x21, 0xCC,
  29. ];'''
  30. actual = make_array(bytes)
  31. self.assertEqual(expected, actual)
  32. if __name__ == "__main__":
  33. if len(sys.argv) < 2:
  34. unittest.main()
  35. else:
  36. length = int(sys.argv[1])
  37. bytes = random.randbytes(length)
  38. array = make_array(bytes)
  39. print(array)