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
13from __future__ import print_function
14
15import os
16import struct
17import sys
18import mmap
19
20def 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
31def 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
45cpp = ('#include <cstdint>\nextern "C" uint32_t {0}[] __attribute__((aligned(16))) = {{\n',
46       '', ',', '}};\n')
47
48if __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])
51