Skip to content

Instantly share code, notes, and snippets.

@foxx
Created November 2, 2016 17:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foxx/91de22cb889fdcf2c8c5ed91e114889c to your computer and use it in GitHub Desktop.
Save foxx/91de22cb889fdcf2c8c5ed91e114889c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Embed files into C arrays
Hacky solution because xxd didn't have enough features
"""
from __future__ import with_statement
from __future__ import print_function
import os
import sys
import re
import glob
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in xrange(0, len(l), n):
yield l[i:i + n]
def main(testdata_path, c_path, h_path):
print("Embedding testdata files into C")
os.path.isdir(testdata_path)
cout = ""
cout += "#include \"testdata.h\"\n"
cout += "#include <glib.h>\n\n"
hout = ""
hout += "#pragma once\n"
hout += "#include <glib.h>\n\n"
for path in glob.glob(testdata_path+'/*'):
if not os.path.isfile(path):
continue
print("Embedding %s" % path)
name = re.sub('[^a-zA-Z0-9]', '_', path)
# read file and build array
arr = []
with open(path, 'rb') as fh:
for c in fh.read():
nc = format(ord(c), "#04x");
arr.append(nc)
# output as chunks
filearr = "{\n"
for chunk in chunks(arr, 12):
filearr += " "
filearr += ", ".join(chunk)
filearr += ",\n"
filearr += " };"
# build c file
cout += "gchar *\n%s()\n{\n char out[%d] = %s\n" % (name, len(arr), filearr )
cout += " return g_strndup(out, sizeof(out));\n}\n\n"
# build h file
hout += "gchar *\n%s();\n\n" % (name)
# write C file
with open(c_path, "wb") as fh:
fh.write(cout)
# write H file
with open(h_path, "wb") as fh:
fh.write(hout)
print("Files generated OK")
if __name__ == '__main__':
import sys
if (len(sys.argv) != 4):
print("syntax: %s <testdata_path> <c_path> <h_path>" % sys.argv[0])
sys.exit(1)
main(*sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment