|
| 1 | +-- this script is used to convert a source input file into a C header to embed |
| 2 | +-- that file as a string. Works the same as xxd -i |
| 3 | + |
| 4 | +local input = ... |
| 5 | + |
| 6 | +local function read_file(file_path) |
| 7 | + local file = assert(io.open(file_path, "rb")) |
| 8 | + local content = file:read("*a") |
| 9 | + file:close() |
| 10 | + return content |
| 11 | +end |
| 12 | + |
| 13 | +local function generate_c_header(input_file) |
| 14 | + local function byte_to_hex(byte) |
| 15 | + return string.format("0x%02x", byte:byte()) |
| 16 | + end |
| 17 | + |
| 18 | + local function sanitize_name(name) |
| 19 | + return (name:gsub("[^%w_]", "_")) |
| 20 | + end |
| 21 | + |
| 22 | + local data = read_file(input_file) |
| 23 | + local name = sanitize_name(input_file) |
| 24 | + local header = {} |
| 25 | + |
| 26 | + table.insert(header, string.format("unsigned char %s[] = {", name)) |
| 27 | + for i = 1, #data do |
| 28 | + if i % 16 == 1 then |
| 29 | + table.insert(header, "\n ") |
| 30 | + end |
| 31 | + table.insert(header, byte_to_hex(data:sub(i, i))) |
| 32 | + if i ~= #data then |
| 33 | + table.insert(header, ", ") |
| 34 | + end |
| 35 | + end |
| 36 | + table.insert(header, "\n};\n") |
| 37 | + table.insert(header, string.format("unsigned int %s_len = %d;\n", name, #data)) |
| 38 | + |
| 39 | + return table.concat(header) |
| 40 | +end |
| 41 | + |
| 42 | +print(generate_c_header(input)) |
0 commit comments