1 /* Convert UTF-16 string to UTF-8 string.
2 Copyright (C) 2002, 2006-2007 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2002.
5 This program is free software; you can redistribute it and/or modify it
6 under the terms of the GNU Library General Public License as published
7 by the Free Software Foundation; either version 2, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
25 #define FUNC u16_to_u8
26 #define SRC_UNIT uint16_t
27 #define DST_UNIT uint8_t
34 FUNC (const SRC_UNIT *s, size_t n, DST_UNIT *resultbuf, size_t *lengthp)
36 const SRC_UNIT *s_end = s + n;
37 /* Output string accumulator. */
42 if (resultbuf != NULL)
54 result is either == resultbuf or == NULL or malloc-allocated.
55 If length > 0, then result != NULL. */
62 /* Fetch a Unicode character from the input string. */
63 count = u16_mbtouc_safe (&uc, s, s_end - s);
66 if (!(result == resultbuf || result == NULL))
73 /* Store it in the output string. */
74 count = u8_uctomb (result + length, uc, allocated - length);
77 if (!(result == resultbuf || result == NULL))
86 allocated = (allocated > 0 ? 2 * allocated : 12);
87 if (length + 6 > allocated)
88 allocated = length + 6;
89 if (result == resultbuf || result == NULL)
90 memory = (DST_UNIT *) malloc (allocated * sizeof (DST_UNIT));
93 (DST_UNIT *) realloc (result, allocated * sizeof (DST_UNIT));
97 if (!(result == resultbuf || result == NULL))
102 if (result == resultbuf && length > 0)
103 memcpy ((char *) memory, (char *) result,
104 length * sizeof (DST_UNIT));
106 count = u8_uctomb (result + length, uc, allocated - length);
117 /* Return a non-NULL value. NULL means error. */
118 result = (DST_UNIT *) malloc (1);
126 else if (result != resultbuf && length < allocated)
128 /* Shrink the allocated memory if possible. */
131 memory = (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));