]> git.sesse.net Git - ccbs/blob - bigscreen/widestring.cpp
Lots of changes/fixes to the new translation stuff.
[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 widestring::widestring(const std::string &from)
20 {
21         *this = from.c_str();
22 }
23
24 widestring::widestring(const std::wstring &from)
25         : std::wstring(from)
26 {
27 }
28
29 void widestring::operator= (const char *from)
30 {
31         if (!iconv_initialized) {
32 #if __BYTE_ORDER == __LITTLE_ENDIAN
33                 ucs4_iconv = iconv_open("ucs-4le", "utf-8");
34 #else
35                 ucs4_iconv = iconv_open("ucs-4be", "utf-8");
36 #endif
37
38                 iconv_initialized = true;
39         }
40         
41         unsigned bytes = std::strlen(from);
42         char *from_buf = strdup(from);
43         wchar_t *to_buf = new wchar_t[bytes + 1];
44
45         char *inptr = from_buf, *outptr = reinterpret_cast<char *> (to_buf);
46
47         size_t in_left = bytes;
48         size_t out_left = bytes * sizeof(wchar_t);
49
50         size_t ret = iconv(ucs4_iconv, NULL, NULL, &outptr, &out_left);
51         if (ret == (size_t)(-1)) {
52                 throw std::runtime_error("Error in iconv during initialization");
53         }
54
55         ret = iconv(ucs4_iconv, &inptr, &in_left, &outptr, &out_left);
56         if (ret == (size_t)(-1)) {
57                 perror("iconv");
58                 throw std::runtime_error("Error in iconv during conversion");
59         }
60
61         erase(begin(), end());
62         std::copy(to_buf, reinterpret_cast<wchar_t *> (outptr), std::back_inserter(*this));
63
64         free(from_buf);
65         delete[] to_buf;
66 }
67
68 template<>
69 void pqxx::from_string<widestring>(const char *from, widestring &to)
70 {
71         to = from;
72 }
73