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