File: iconv.c

package info (click to toggle)
mysql-8.0 8.0.43-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,904 kB
  • sloc: cpp: 4,684,605; ansic: 412,450; pascal: 108,398; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; sh: 24,184; python: 21,816; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,076; makefile: 2,196; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (51 lines) | stat: -rw-r--r-- 1,319 bytes parent folder | download | duplicates (15)
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
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <iconv.h>

static iconv_t s_cd;

/* Call iconv_open only once so the benchmark will be faster? */
static void __attribute__ ((constructor)) init_iconv(void)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    s_cd = iconv_open("UTF-16LE", "UTF-8");
#else
    s_cd = iconv_open("UTF-16BE", "UTF-8");
#endif
    if (s_cd == (iconv_t)-1) {
        perror("iconv_open");
        exit(1);
    }
}

/*
 * Parameters:
 * - buf8, len8: input utf-8 string
 * - buf16: buffer to store decoded utf-16 string
 * - *len16: on entry - utf-16 buffer length in bytes
 *           on exit  - length in bytes of valid decoded utf-16 string
 * Returns:
 *  -  0: success
 *  - >0: error position of input utf-8 string
 *  - -1: utf-16 buffer overflow
 * LE/BE depends on host
 */
int utf8_to16_iconv(const unsigned char *buf8, size_t len8,
        unsigned short *buf16, size_t *len16)
{
    size_t ret, len16_save = *len16;
    const unsigned char *buf8_0 = buf8;

    ret = iconv(s_cd, (char **)&buf8, &len8, (char **)&buf16, len16);

    *len16 = len16_save - *len16;

    if (ret != (size_t)-1)
        return 0;

    if (errno == E2BIG)
        return -1;              /* Output buffer full */

    return buf8 - buf8_0 + 1;   /* EILSEQ, EINVAL, error position */
}