Port to_array.py to C++

This gets rid of a dependency on Python in $PATH (although Python is likely installed if we're using Meson). Nix people will like this a lot.
This commit is contained in:
Tamás Bálint Misius 2021-12-07 17:15:21 +01:00
parent b587732d7b
commit 9f75f7e5fc
No known key found for this signature in database
GPG Key ID: 5B472A12F6ECA9F2
3 changed files with 54 additions and 18 deletions

52
data/ToArray.cpp Normal file
View File

@ -0,0 +1,52 @@
#include <fstream>
int main(int argc, char *argv[])
{
if (argc != 5)
{
return 1;
}
auto *outputCppPath = argv[1];
auto *outputHPath = argv[2];
auto *inputAnyPath = argv[3];
auto *symbolName = argv[4];
std::ifstream inputAny(inputAnyPath, std::ios::binary);
std::ofstream outputCpp(outputCppPath);
if (!outputCpp)
{
return 2;
}
outputCpp << "#include \"" << outputHPath << "\"\nconst unsigned char " << symbolName << "[] = { ";
auto dataLen = 0U;
while (true)
{
if (inputAny.eof())
{
break;
}
if (!inputAny)
{
return 3;
}
char ch;
inputAny.read(&ch, 1);
outputCpp << (unsigned int)(unsigned char)(ch) << ", ";
dataLen += 1;
}
outputCpp << " }; const unsigned int " << symbolName << "_size = " << dataLen << ";\n";
if (!outputCpp)
{
return 4;
}
std::ofstream outputH(outputHPath);
if (!outputH)
{
return 5;
}
outputH << "#pragma once\nextern const unsigned char " << symbolName << "[]; extern const unsigned int " << symbolName << "_size;\n";
if (!outputH)
{
return 6;
}
return 0;
}

View File

@ -3,9 +3,9 @@ project('the-powder-toy', [ 'c', 'cpp' ], version: 'the.cake.is.a.lie', default_
])
to_array = generator(
import('python').find_installation('python3'),
executable('toarray', sources: 'data/ToArray.cpp'),
output: [ '@PLAINNAME@.cpp', '@PLAINNAME@.h' ],
arguments: [ join_paths(meson.current_source_dir(), 'to_array.py'), '@BUILD_DIR@', '@OUTPUT0@', '@OUTPUT1@', '@INPUT@', '@EXTRA_ARGS@' ]
arguments: [ '@OUTPUT0@', '@OUTPUT1@', '@INPUT@', '@EXTRA_ARGS@' ]
)
cpp_compiler = meson.get_compiler('cpp')

View File

@ -1,16 +0,0 @@
import sys
build_dir = sys.argv[1]
output_cpp = sys.argv[2]
output_h = sys.argv[3]
input_any = sys.argv[4]
symbol_name = sys.argv[5]
with open(input_any, 'rb') as input_any_f:
data = input_any_f.read()
with open(output_cpp, 'w') as output_cpp_f:
output_cpp_f.write('#include "{0}"\nconst unsigned char {1}[] = {{ {2} }}; const unsigned int {1}_size = {3};\n'.format(output_h, symbol_name, ','.join([ str(b) for b in data ]), len(data)))
with open(output_h, 'w') as output_h_f:
output_h_f.write('#pragma once\nextern const unsigned char {0}[]; extern const unsigned int {0}_size;\n'.format(symbol_name))