File: filetoinc.py

package info (click to toggle)
termpaint 0.3.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,760 kB
  • sloc: cpp: 40,344; ansic: 10,323; python: 402; sh: 36; makefile: 14
file content (31 lines) | stat: -rwxr-xr-x 795 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#! /usr/bin/env python3
# SPDX-License-Identifier: BSL-1.0

import sys

name = sys.argv[1]
infile = sys.argv[2]
outfile = sys.argv[3]

with open(infile, 'rb') as f:
    data = f.read()

data_encoded = [""]

# intentionally excluding some whitespace and some special characters
basic_c_source_chars = set(b' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_{}[]#()<>%:;.?*+-/^&|~!=,\'')

for ch in data:
    if ch in basic_c_source_chars:
        data_encoded[-1] += chr(ch)
    else:
        data_encoded[-1] += "\\{:o}".format(ch)

    if len(data_encoded[-1]) > 70:
        data_encoded.append("")

with open(outfile, 'w') as f:
    f.write('static const unsigned char {}[] = {{\n'.format(name))
    for line in data_encoded:
        f.write('    "{}"\n'.format(line))
    f.write('};\n')