1 /* Conversion from UTF-16/UTF-32 to legacy encodings.
2 Copyright (C) 2002, 2006-2019 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify it
5 under the terms of the GNU Lesser General Public License as published
6 by the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 FUNC (const char *tocode
,
19 enum iconv_ilseq_handler handler
,
20 const UNIT
*src
, size_t srclen
,
22 char *resultbuf
, size_t *lengthp
)
25 size_t *scaled_offsets
;
29 if (offsets
!= NULL
&& srclen
> 0)
32 (size_t *) malloc (srclen
* sizeof (UNIT
) * sizeof (size_t));
33 if (scaled_offsets
== NULL
)
40 scaled_offsets
= NULL
;
44 if (mem_iconveha ((const char *) src
, srclen
* sizeof (UNIT
),
46 handler
== iconveh_question_mark
, handler
,
47 scaled_offsets
, &result
, &length
) < 0)
49 int saved_errno
= errno
;
50 free (scaled_offsets
);
57 /* Convert scaled_offsets[srclen * sizeof (UNIT)] to
61 for (i
= 0; i
< srclen
; i
++)
62 offsets
[i
] = scaled_offsets
[i
* sizeof (UNIT
)];
63 free (scaled_offsets
);
66 if (result
== NULL
) /* when (resultbuf == NULL && length == 0) */
68 result
= (char *) malloc (1);
79 size_t tmpbufsize
= SIZEOF (tmpbuf
);
82 size_t *scaled_offsets
;
85 utf8_src
= U_TO_U8 (src
, srclen
, tmpbuf
, &tmpbufsize
);
88 utf8_srclen
= tmpbufsize
;
90 if (offsets
!= NULL
&& utf8_srclen
> 0)
92 scaled_offsets
= (size_t *) malloc (utf8_srclen
* sizeof (size_t));
93 if (scaled_offsets
== NULL
)
95 if (utf8_src
!= tmpbuf
)
102 scaled_offsets
= NULL
;
104 result
= u8_conv_to_encoding (tocode
, handler
, utf8_src
, utf8_srclen
,
105 scaled_offsets
, resultbuf
, lengthp
);
108 int saved_errno
= errno
;
109 free (scaled_offsets
);
110 if (utf8_src
!= tmpbuf
)
117 size_t iunit
; /* offset into src */
118 size_t i8
; /* offset into utf8_src */
120 for (iunit
= 0; iunit
< srclen
; iunit
++)
121 offsets
[iunit
] = (size_t)(-1);
125 while (iunit
< srclen
&& i8
< utf8_srclen
)
130 offsets
[iunit
] = scaled_offsets
[i8
];
132 countunit
= U_MBLEN (src
+ iunit
, srclen
- iunit
);
133 count8
= u8_mblen (utf8_src
+ i8
, utf8_srclen
- i8
);
134 if (countunit
< 0 || count8
< 0)
139 /* Check that utf8_src has been traversed entirely. */
140 if (i8
< utf8_srclen
)
142 /* Check that src has been traversed entirely, except possibly for an
143 incomplete sequence of units at the end. */
146 offsets
[iunit
] = *lengthp
;
147 if (!(U_MBLEN (src
+ iunit
, srclen
- iunit
) < 0))
150 free (scaled_offsets
);
152 if (utf8_src
!= tmpbuf
)