]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/configuration/rpcconfig/utils.cpp
Minor ChangeLog fix
[stg.git] / projects / stargazer / plugins / configuration / rpcconfig / utils.cpp
1 #include <string>
2 #include <cerrno>
3 #include <cstring>
4 #include <iconv.h>
5
6 #include "utils.h"
7 #include "common.h"
8
9 //-----------------------------------------------------------------------------
10 std::string IconvString(const std::string & src,
11                         const std::string & from,
12                         const std::string & to)
13 {
14 if (src.empty())
15     return std::string();
16
17 size_t inBytesLeft = src.length() + 1;
18 size_t outBytesLeft = src.length() * 2 + 1;
19
20 char * inBuf = new char[inBytesLeft];
21 char * outBuf = new char[outBytesLeft];
22
23 strncpy(inBuf, src.c_str(), src.length());
24
25 inBuf[src.length()] = 0;
26
27 #if defined(FREE_BSD) || defined(FREE_BSD5)
28 const char * srcPos = inBuf;
29 #else
30 char * srcPos = inBuf;
31 #endif
32 char * dstPos = outBuf;
33
34 iconv_t handle = iconv_open(to.c_str(),
35                             from.c_str());
36
37 if (handle == iconv_t(-1))
38     {
39     if (errno == EINVAL)
40         {
41         printfd(__FILE__, "IconvString(): iconv from %s to %s failed\n", from.c_str(), to.c_str());
42         delete[] outBuf;
43         delete[] inBuf;
44         return src;
45         }
46     else
47         printfd(__FILE__, "IconvString(): iconv_open error\n");
48
49     delete[] outBuf;
50     delete[] inBuf;
51     return src;
52     }
53
54 size_t res = iconv(handle,
55                    &srcPos, &inBytesLeft,
56                    &dstPos, &outBytesLeft);
57
58 if (res == size_t(-1))
59     {
60     printfd(__FILE__, "IconvString(): '%s'\n", strerror(errno));
61
62     iconv_close(handle);
63     delete[] outBuf;
64     delete[] inBuf;
65     return src;
66     }
67
68 dstPos = 0;
69
70 std::string dst(outBuf);
71
72 iconv_close(handle);
73
74 delete[] outBuf;
75 delete[] inBuf;
76
77 return dst;
78 }