1 /* Conversion from UTF-16/UTF-32 to legacy encodings.
2 Copyright (C) 2002, 2006-2007, 2009-2021 Free Software Foundation, Inc.
3
4 This file is free software.
5 It is dual-licensed under "the GNU LGPLv3+ or the GNU GPLv2+".
6 You can redistribute it and/or modify it under either
7 - the terms of the GNU Lesser General Public License as published
8 by the Free Software Foundation; either version 3, or (at your
9 option) any later version, or
10 - the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option)
12 any later version, or
13 - the same dual license "the GNU LGPLv3+ or the GNU GPLv2+".
14
15 This file is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 Lesser General Public License and the GNU General Public License
19 for more details.
20
21 You should have received a copy of the GNU Lesser General Public
22 License and of the GNU General Public License along with this
23 program. If not, see <https://www.gnu.org/licenses/>. */
24
25 char *
26 FUNC (const UNIT *string,
/* ![[previous]](../icons/n_left.png)
![[next]](../icons/n_right.png)
![[first]](../icons/n_first.png)
![[last]](../icons/n_last.png)
![[top]](../icons/top.png)
![[bottom]](../icons/bottom.png)
![[index]](../icons/index.png)
*/
27 const char *tocode,
28 enum iconv_ilseq_handler handler)
29 {
30 #if HAVE_UTF_NAME
31 char *result = NULL;
32 size_t length = 0;
33
34 if (mem_iconveha ((const char *) string, (U_STRLEN (string) + 1) * sizeof (UNIT),
35 UTF_NAME, tocode,
36 handler == iconveh_question_mark, handler,
37 NULL, &result, &length) < 0)
38 return NULL;
39 /* Verify the result has exactly one NUL byte, at the end. */
40 if (!(length > 0 && result[length-1] == '\0' && strlen (result) == length-1))
41 {
42 free (result);
43 errno = EILSEQ;
44 return NULL;
45 }
46 return result;
47 #else
48 uint8_t tmpbuf[4096];
49 size_t tmpbufsize = SIZEOF (tmpbuf);
50 uint8_t *utf8_string;
51 char *result;
52
53 utf8_string = U_TO_U8 (string, U_STRLEN (string) + 1, tmpbuf, &tmpbufsize);
54 if (utf8_string == NULL)
55 return NULL;
56 result = u8_strconv_to_encoding (utf8_string, tocode, handler);
57 if (result == NULL)
58 {
59 if (utf8_string != tmpbuf)
60 {
61 int saved_errno = errno;
62 free (utf8_string);
63 errno = saved_errno;
64 }
65 return NULL;
66 }
67 if (utf8_string != tmpbuf)
68 free (utf8_string);
69 return result;
70 #endif
71 }