Last active
June 24, 2020 05:20
-
-
Save kleinron/d5c32fb3d7135a31fc22b31435fc725e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from itertools import zip_longest | |
from traceback import print_exc | |
def grouper(iterable, n, fillvalue=None): | |
"""Collect data into fixed-length chunks or blocks""" | |
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" | |
args = [iter(iterable)] * n | |
return zip_longest(*args, fillvalue=fillvalue) | |
def convert_handlers(in_f, out_f, var_name): | |
content = in_f.read() | |
out_f.write('const size_t %s_size = %d;\n' % (var_name, len(content))) | |
out_f.write('const char %s[%d] = {\n' % (var_name, len(content))) | |
content = map(lambda c: '\\t' if c == '\t' else c, content) | |
content = map(lambda c: '\\n' if c == '\n' else c, content) | |
content = map(lambda c: "\\'" if c == "'" else c, content) | |
tokens = map(lambda c: "'%s'" % c, content) | |
lines = map(lambda x: filter(None, x), grouper(tokens, 15)) | |
lines_as_text = map(lambda line: ' ' + ', '.join(line), lines) | |
out_f.write(',\n'.join(lines_as_text)) | |
out_f.write('\n};') | |
def convert(in_path, out_path, var_name): | |
with open(in_path, 'rt') as in_f: | |
with open(out_path, 'wt') as out_f: | |
convert_handlers(in_f, out_f, var_name) | |
def usage(): | |
print("<python-executable> " + __file__ + " input_text_file output_ansi_c_file variable_name") | |
def main(argv): | |
if len(sys.argv) != 4: | |
usage() | |
return -1 | |
try: | |
convert(argv[1], argv[2], argv[3]) | |
return 0 | |
except: | |
print_exc() | |
return -2 | |
if __name__ == '__main__': | |
exit(main(sys.argv)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment