]> git.sesse.net Git - ccbs/blob - bigscreen/widestring.cpp
a0d781a4edf5d22ded01667e4e84bc259c522670
[ccbs] / bigscreen / widestring.cpp
1 #include <stdlib.h>
2 #include <cstring>
3 #include <iconv.h>
4 #include <endian.h>
5 #include <exception>
6 #include <pqxx/util>
7 #include "widestring.h"
8
9 static iconv_t ucs4_iconv;
10 static bool iconv_initialized = false;
11
12 widestring::widestring()
13 {
14 }
15
16 widestring::widestring(const char *from)
17 {
18         *this = from;
19 }
20
21 widestring::widestring(const std::string &from)
22 {
23         *this = from.c_str();
24 }
25
26 widestring::widestring(const std::wstring &from)
27         : std::wstring(from)
28 {
29 }
30
31 void widestring::operator= (const char *from)
32 {
33         if (!iconv_initialized) {
34 #if __BYTE_ORDER == __LITTLE_ENDIAN
35                 ucs4_iconv = iconv_open("ucs-4le", "utf-8");
36 #else
37                 ucs4_iconv = iconv_open("ucs-4be", "utf-8");
38 #endif
39
40                 iconv_initialized = true;
41         }
42         
43         unsigned bytes = std::strlen(from);
44         char *from_buf = strdup(from);
45         wchar_t *to_buf = new wchar_t[bytes + 1];
46
47         char *inptr = from_buf, *outptr = reinterpret_cast<char *> (to_buf);
48
49         size_t in_left = bytes;
50         size_t out_left = bytes * sizeof(wchar_t);
51
52         size_t ret = iconv(ucs4_iconv, NULL, NULL, &outptr, &out_left);
53         if (ret == (size_t)(-1)) {
54                 throw std::runtime_error("Error in iconv during initialization");
55         }
56
57         ret = iconv(ucs4_iconv, &inptr, &in_left, &outptr, &out_left);
58         if (ret == (size_t)(-1)) {
59                 perror("iconv");
60                 throw std::runtime_error("Error in iconv during conversion");
61         }
62
63         erase(begin(), end());
64         std::copy(to_buf, reinterpret_cast<wchar_t *> (outptr), std::back_inserter(*this));
65
66         free(from_buf);
67         delete[] to_buf;
68 }
69
70 namespace pqxx
71 {
72
73 template<>
74 void from_string<widestring>(const char *from, widestring &to)
75 {
76         to = from;
77 }
78
79 }