summaryrefslogtreecommitdiffstatshomepage
path: root/3rdparty/bx/tools/bin2c/bin2c.cpp
blob: ef0e2fc7810bc5876ee9cc50e3b237005f5b6b34 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*
 * Copyright 2011-2023 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bx/blob/master/LICENSE
 */

#include <bx/allocator.h>
#include <bx/commandline.h>
#include <bx/file.h>
#include <bx/string.h>

#include <bx/debug.h>

class Bin2cWriter : public bx::WriterI
{
public:
	Bin2cWriter(bx::AllocatorI* _allocator, const bx::StringView& _name)
		: m_mb(_allocator)
		, m_mw(&m_mb)
		, m_name(_name)
		, m_outputAsCStr(false)
	{
	}

	virtual ~Bin2cWriter()
	{
	}

	virtual int32_t write(const void* _data, int32_t _size, bx::Error* _err) override
	{
		bool asCStr = true;

		const char* data = (const char*)_data;
		for (int32_t ii = 0; ii < _size && asCStr; ++ii)
		{
			char ch = data[ii];

			asCStr &= false
				| bx::isPrint(ch)
				| bx::isSpace(ch)
				;
		}

		m_outputAsCStr = asCStr;

		return bx::write(&m_mw, _data, _size, _err);
	}

	void output(bx::WriterI* _writer)
	{
		if (m_outputAsCStr)
		{
			outputString(_writer);
		}
		else
		{
			outputHex(_writer);
		}
	}

	void outputString(bx::WriterI* _writer)
	{
		const uint8_t* data = (const uint8_t*)m_mb.more(0);
		uint32_t size = uint32_t(bx::seek(&m_mw) );

		bx::Error err;

		bx::write(
			  _writer
			, &err
			, "static const char* %.*s = /* Generated with bin2c. */\n\t\""
			, m_name.getLength()
			, m_name.getPtr()
			);

		if (NULL != data)
		{
			bool escaped = false;

			for (uint32_t ii = 0; ii < size; ++ii)
			{
				const char ch = char(data[ii]);

				if (!escaped)
				{
					switch (ch)
					{
					case '\"': bx::write(_writer, "\\\"",        &err); break;
					case '\n': bx::write(_writer, "\\n\"\n\t\"", &err); break;
					case '\r': bx::write(_writer, "\\r",         &err); break;
					case '\\': escaped = true;                 BX_FALLTHROUGH;
					default:   bx::write(_writer, ch, &err);            break;
					}
				}
				else
				{
					switch (ch)
					{
					case '\n': bx::write(_writer, "\\\"\n\t\"", &err);  break;
					case '\r':                                 BX_FALLTHROUGH;
					case '\t': bx::write(_writer, "\\", &err); BX_FALLTHROUGH;
					default  : bx::write(_writer, ch,   &err);          break;
					}

					escaped = false;
				}
			}
		}

		bx::write(_writer, &err, "\"\n\t;\n");
	}

	void outputHex(bx::WriterI* _writer)
	{
#define HEX_DUMP_WIDTH 16
#define HEX_DUMP_SPACE_WIDTH 96
#define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
		const uint8_t* data = (const uint8_t*)m_mb.more(0);
		uint32_t size = uint32_t(bx::seek(&m_mw) );

		bx::Error err;

		bx::write(
			  _writer
			, &err
			, "static const uint8_t %.*s[%d] = /* Generated with bin2c. */\n{\n"
			, m_name.getLength()
			, m_name.getPtr()
			, size
			);

		if (NULL != data)
		{
			char hex[HEX_DUMP_SPACE_WIDTH+1];
			char ascii[HEX_DUMP_WIDTH+1];
			uint32_t hexPos = 0;
			uint32_t asciiPos = 0;
			for (uint32_t ii = 0; ii < size; ++ii)
			{
				bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]);
				hexPos += 6;

				ascii[asciiPos] = bx::isPrint(data[asciiPos]) && data[asciiPos] != '\\' ? data[asciiPos] : '.';
				asciiPos++;

				if (HEX_DUMP_WIDTH == asciiPos)
				{
					ascii[asciiPos] = '\0';
					bx::write(_writer, &err, "\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
					data += asciiPos;
					hexPos   = 0;
					asciiPos = 0;
				}
			}

			if (0 != asciiPos)
			{
				ascii[asciiPos] = '\0';
				bx::write(_writer, &err, "\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
			}
		}

		bx::write(_writer, &err, "};\n");
#undef HEX_DUMP_WIDTH
#undef HEX_DUMP_SPACE_WIDTH
#undef HEX_DUMP_FORMAT
	}

	bx::MemoryBlock  m_mb;
	bx::MemoryWriter m_mw;
	bx::StringView   m_name;
	bool             m_outputAsCStr;
};

void error(const char* _format, ...)
{
	bx::WriterI* stdOut = bx::getStdOut();
	bx::Error err;

	va_list argList;
	va_start(argList, _format);
	bx::write(stdOut, &err, "Error:\n");
	bx::write(stdOut, _format, argList, &err);
	bx::write(stdOut, &err, "\n\n");
	va_end(argList);
}

void help(const char* _error = NULL)
{
	bx::WriterI* stdOut = bx::getStdOut();
	bx::Error err;

	if (NULL != _error)
	{
		error(_error);
	}

	bx::write(stdOut, &err
		, "bin2c, binary to C\n"
		  "Copyright 2011-2023 Branimir Karadzic. All rights reserved.\n"
		  "License: https://github.com/bkaradzic/bx/blob/master/LICENSE\n\n"
		);

	bx::write(stdOut, &err
		, "Usage: bin2c -f <in> -o <out> -n <name>\n"
		  "\n"
		  "Options:\n"
		  "  -f <file path>    Input file path.\n"
		  "  -o <file path>    Output file path.\n"
		  "  -n <name>         Array name.\n"
		  "\n"
		  "For additional information, see https://github.com/bkaradzic/bx\n"
		);
}

int main(int _argc, const char* _argv[])
{
	bx::CommandLine cmdLine(_argc, _argv);

	if (cmdLine.hasArg('h', "help") )
	{
		help();
		return bx::kExitFailure;
	}

	bx::FilePath filePath = cmdLine.findOption('f');
	if (filePath.isEmpty() )
	{
		help("Input file name must be specified.");
		return bx::kExitFailure;
	}

	bx::FilePath outFilePath = cmdLine.findOption('o');
	if (outFilePath.isEmpty() )
	{
		help("Output file name must be specified.");
		return bx::kExitFailure;
	}

	bx::StringView name = cmdLine.findOption('n');
	if (name.isEmpty() )
	{
		name.set("data");
	}

	void* data = NULL;
	uint32_t size = 0;

	bx::FileReader fr;
	if (bx::open(&fr, filePath) )
	{
		size = uint32_t(bx::getSize(&fr) );

		bx::DefaultAllocator allocator;
		data = bx::alloc(&allocator, size);
		bx::read(&fr, data, size, bx::ErrorAssert{});
		bx::close(&fr);

		bx::FileWriter fw;
		if (bx::open(&fw, outFilePath) )
		{
			Bin2cWriter writer(&allocator, name);
			bx::write(&writer, data, size, bx::ErrorAssert{});

			writer.output(&fw);
			bx::close(&fw);
		}
		else
		{
			bx::StringView path = outFilePath;
			error("Failed to open output file '%.*s'.\n", path.getLength(), path.getPtr() );
		}

		bx::free(&allocator, data);
	}
	else
	{
		bx::StringView path = filePath;
		error("Failed to open input file '%.*s'.\n", path.getLength(), path.getPtr() );
	}

	return 0;
}