-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwcs.c
77 lines (64 loc) · 1.75 KB
/
wcs.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "driver.h"
#include "wcs.h"
int sqlwcharbytelen(SQLWCHAR *str)
{
int len;
for (len = 0; str[len] != 0; ++len) ;
return len * sizeof(SQLWCHAR);
}
#ifdef _MSC_VER
#include <stringapiset.h>
int utf8_to_ucs2(SQLCHAR *src, SQLWCHAR *dest, size_t len)
{
__debug(__func__);
return MultiByteToWideChar(CP_UTF8, 0, src, -1, dest, len);
}
int ucs2_to_utf8(SQLWCHAR *src, SQLCHAR *dest, size_t len)
{
__debug(__func__);
return WideCharToMultiByte(CP_UTF8, 0, src, -1, dest, len, NULL, NULL);
}
#else
#include <iconv.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
int utf8_to_ucs2(SQLCHAR *src, SQLWCHAR *dest, size_t len)
{
int rv = 0;
iconv_t cb = iconv_open("UTF-16//IGNORE", "UTF-8");
if (cb == (iconv_t)(-1))
return 0;
size_t inbytesleft = strlen((char *)src) + 1;
size_t outbytesleft = len;
size_t ret = iconv(cb, (char**)&src, (size_t*)&inbytesleft, (char**)&dest, (size_t*)&outbytesleft);
if (ret == (size_t) - 1) {
__warn("error:%s, %d", strerror(errno), errno);
rv = -1;
} else {
rv = len - outbytesleft;
}
iconv_close(cb);
return rv;
}
int ucs2_to_utf8(SQLWCHAR *src, SQLCHAR *dest, size_t len)
{
int rv = 0;
iconv_t cb = iconv_open("UTF-8//IGNORE", "UTF-16");
if (cb == (iconv_t)(-1))
return 0;
size_t inbytesleft = sqlwcharbytelen(src) + sizeof(SQLWCHAR);
size_t outbytesleft = len;
size_t ret = iconv(cb, (char**)&src, (size_t*)&inbytesleft, (char**)&dest, (size_t*)&outbytesleft);
if (ret == (size_t) - 1) {
abort();
__warn("error:%s, %d", strerror(errno), errno);
rv = -1;
} else {
rv = len - outbytesleft;
}
iconv_close(cb);
return rv;
}
#endif