Only allocate space for four digits in the score screen -- if somebody actually gets...
[ccbs] / bigscreen / widestring.cpp
1 #include <iconv.h>
2 #include <endian.h>
3 #include <exception>
4 #include <pqxx/util>
5 #include "widestring.h"
6
7 static iconv_t ucs4_iconv;
8 static bool iconv_initialized = false;
9
10 widestring::widestring()
11 {
12 }
13
14 widestring::widestring(const char *from)
15 {
16         *this = from;
17 }
18
19 void widestring::operator= (const char *from)
20 {
21         if (!iconv_initialized) {
22 #if __BYTE_ORDER == __LITTLE_ENDIAN
23                 ucs4_iconv = iconv_open("ucs-4le", "utf-8");
24 #else
25                 ucs4_iconv = iconv_open("ucs-4be", "utf-8");
26 #endif
27
28                 iconv_initialized = true;
29         }
30         
31         unsigned bytes = std::strlen(from);
32         char *from_buf = strdup(from);
33         wchar_t *to_buf = new wchar_t[bytes + 1];
34
35         char *inptr = from_buf, *outptr = reinterpret_cast<char *> (to_buf);
36
37         size_t in_left = bytes;
38         size_t out_left = bytes * sizeof(wchar_t);
39
40         size_t ret = iconv(ucs4_iconv, NULL, NULL, &outptr, &out_left);
41         if (ret == (size_t)(-1)) {
42                 throw std::runtime_error("Error in iconv during initialization");
43         }
44
45         ret = iconv(ucs4_iconv, &inptr, &in_left, &outptr, &out_left);
46         if (ret == (size_t)(-1)) {
47                 perror("iconv");
48                 throw std::runtime_error("Error in iconv during conversion");
49         }
50
51         erase(begin(), end());
52         std::copy(to_buf, reinterpret_cast<wchar_t *> (outptr), std::back_inserter(*this));
53
54         free(from_buf);
55         delete[] to_buf;
56 }
57
58 template<>
59 void pqxx::from_string<widestring>(const char *from, widestring &to)
60 {
61         to = from;
62 }
63