Move widestring into its own file.
[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 void widestring::operator= (const char *from)
11 {
12         if (!iconv_initialized) {
13 #if __BYTE_ORDER == __LITTLE_ENDIAN
14                 ucs4_iconv = iconv_open("ucs-4le", "utf-8");
15 #else
16                 ucs4_iconv = iconv_open("ucs-4be", "utf-8");
17 #endif
18
19                 iconv_initialized = true;
20         }
21         
22         unsigned bytes = std::strlen(from);
23         char *from_buf = strdup(from);
24         wchar_t *to_buf = new wchar_t[bytes + 1];
25
26         char *inptr = from_buf, *outptr = reinterpret_cast<char *> (to_buf);
27
28         size_t in_left = bytes;
29         size_t out_left = bytes * sizeof(wchar_t);
30
31         size_t ret = iconv(ucs4_iconv, NULL, NULL, &outptr, &out_left);
32         if (ret == (size_t)(-1)) {
33                 throw std::runtime_error("Error in iconv during initialization");
34         }
35
36         ret = iconv(ucs4_iconv, &inptr, &in_left, &outptr, &out_left);
37         if (ret == (size_t)(-1)) {
38                 perror("iconv");
39                 throw std::runtime_error("Error in iconv during conversion");
40         }
41
42         erase(begin(), end());
43         std::copy(to_buf, reinterpret_cast<wchar_t *> (outptr), std::back_inserter(*this));
44
45         free(from_buf);
46         delete[] to_buf;
47 }
48
49 template<>
50 void pqxx::from_string<widestring>(const char *from, widestring &to)
51 {
52         to = from;
53 }
54