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