#!/usr/bin/python3 "Embed zlib compressed data as a C string." import zlib import sys safe = set(range(ord(' '), ord('~')+1)) for c in '"\\': safe.remove(ord(c)) def format(buf): return f' "{"".join(buf)}"\n' def embed(outdata, maxwidth): width = 0 buf = [] empty = [] for b in outdata: c = chr(b) if b in safe else f"\\{b:03o}" if len(c) + width > maxwidth: yield format(buf) buf[:] = empty width = 0 buf.append(c) width += len(c) yield format(buf) def main(infname, maxwidth, log=lambda s: 0): indata = open(infname, 'rb').read() outdata = zlib.compress(indata) log(f'{len(indata)} compress to {len(outdata)}\n') return embed(outdata, maxwidth) if __name__ == '__main__': sys.stdout.writelines(main(sys.argv[1], 40, sys.stderr.write))