make_data_cpp.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python
  2. # Copyright 2019 Google LLC.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. '''
  6. Generate a source file containing the given binary data.
  7. Output type is C++.
  8. '''
  9. import os
  10. import struct
  11. import sys
  12. import mmap
  13. def iterate_as_uint32(path):
  14. with open(path, 'rb') as f:
  15. s = struct.Struct('@I')
  16. assert s.size == 4
  17. mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
  18. assert (len(mm) % s.size) == 0
  19. for offset in xrange(0, len(mm), s.size):
  20. yield s.unpack_from(mm, offset)[0]
  21. mm.close()
  22. def convert(fmt, name, src_path, dst_path):
  23. header, line_begin, line_end, footer = fmt
  24. assert os.path.exists(src_path)
  25. src = iterate_as_uint32(src_path)
  26. with open(dst_path, 'w') as o:
  27. o.write(header.format(name))
  28. while True:
  29. line = ','.join('%d' % v for _, v in zip(range(8), src))
  30. if not line:
  31. break
  32. o.write('%s%s%s\n' % (line_begin, line, line_end))
  33. o.write(footer.format(name))
  34. cpp = ('#include <cstdint>\nextern "C" uint32_t {0}[] __attribute__((aligned(16))) = {{\n',
  35. '', ',', '}};\n')
  36. if __name__ == '__main__':
  37. print '\n'.join('>>> %r' % x for x in sys.argv)
  38. convert(cpp, sys.argv[1], sys.argv[2], sys.argv[3])