Make wrapper for boost::lexical_cast
[lsnes.git] / buildaux / txt2cstr.cpp
blob95f96fc5d0186dc9a5afc13f7f7575d5f82f780b
1 #include <iostream>
2 #include <fstream>
3 #include <sstream>
4 #include <cstring>
6 const char* hexes = "0123456789ABCDEF";
8 struct encoder
10 encoder(std::ostream& _output) : output(_output)
12 have_quote = false;
14 size_t operator()(unsigned char* buf, size_t bufuse, bool eof)
16 if(!bufuse) return 0;
17 std::ostringstream out;
18 size_t i = 0;
19 while(i < bufuse) {
20 if(!have_quote) {
21 out << "\"";
22 have_quote = true;
24 unsigned char ch = buf[i];
25 if(ch == 9) {
26 out << "\\t";
27 } else if(ch == 10) {
28 out << "\\n\"" << std::endl;
29 have_quote = false;
30 } else if(ch == 13) {
31 out << "\\r";
32 } else if(ch < 32) {
33 out << "\\x" << hexes[(ch >> 4)] << hexes[ch & 15];
34 } else if(ch == '\"') {
35 out << "\\\"";
36 } else if(ch == '\\') {
37 out << "\\\\";
38 } else if(ch < 127) {
39 out << ch;
40 } else {
41 out << "\\x" << hexes[(ch >> 4)] << hexes[ch & 15];
43 i++;
45 output << out.str();
46 return i;
48 size_t operator()()
50 if(have_quote) {
51 output << "\"";
52 have_quote = false;
55 private:
56 std::ostream& output;
57 bool have_quote;
60 void do_encode(std::istream& input, std::ostream& output)
62 char buf[4096];
63 size_t bufuse = 0;
64 bool eof = false;
65 encoder e(output);
66 while(true) {
67 if(!eof) {
68 input.read(buf + bufuse, 4096 - bufuse);
69 bufuse += input.gcount();
71 if(!input)
72 eof = true;
73 size_t bytes = e(reinterpret_cast<unsigned char*>(buf), bufuse, eof);
74 memmove(buf, buf + bytes, bufuse - bytes);
75 bufuse -= bytes;
76 if(eof && !bufuse) break;
78 e();
81 int main(int argc, char** argv)
83 if(argc != 3) {
84 std::cerr << "Usage: txt2cstr <symbol> <file>" << std::endl;
85 return 1;
87 std::ifstream in(argv[2], std::ios::binary);
88 std::cout << "const char* " << argv[1] << " =" << std::endl;
89 do_encode(in, std::cout);
90 std::cout << ";" << std::endl;