da0ff6e6d832bf6186787b6dba28f966bcfdd4f8
[gnulib.git] / lib / uniconv / u8-strconv-to-enc.c
1 /* Conversion from UTF-8 to legacy encodings.
2    Copyright (C) 2002, 2006-2007, 2009-2012 Free Software Foundation, Inc.
3
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.
8
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.
13
14    You should have received a copy of the GNU Lesser General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Bruno Haible <bruno@clisp.org>.  */
18
19 #include <config.h>
20
21 /* Specification.  */
22 #include "uniconv.h"
23
24 #include <errno.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "c-strcaseeq.h"
29 #include "striconveha.h"
30 #include "unistr.h"
31
32 char *
33 u8_strconv_to_encoding (const uint8_t *string,
34                         const char *tocode,
35                         enum iconv_ilseq_handler handler)
36 {
37   char *result;
38   size_t length;
39
40   if (STRCASEEQ (tocode, "UTF-8", 'U','T','F','-','8',0,0,0,0))
41     {
42       /* Conversion from UTF-8 to UTF-8.  No need to go through iconv().  */
43       length = u8_strlen (string) + 1;
44 #if CONFIG_UNICODE_SAFETY
45       if (u8_check (string, length))
46         {
47           errno = EILSEQ;
48           return NULL;
49         }
50 #endif
51       result = (char *) malloc (length);
52       if (result == NULL)
53         {
54           errno = ENOMEM;
55           return NULL;
56         }
57       memcpy (result, (const char *) string, length);
58       return result;
59     }
60   else
61     {
62       result = NULL;
63       length = 0;
64       if (mem_iconveha ((const char *) string, u8_strlen (string) + 1,
65                         "UTF-8", tocode,
66                         handler == iconveh_question_mark, handler,
67                         NULL, &result, &length) < 0)
68         return NULL;
69       /* Verify the result has exactly one NUL byte, at the end.  */
70       if (!(length > 0 && result[length-1] == '\0'
71             && strlen (result) == length-1))
72         {
73           free (result);
74           errno = EILSEQ;
75           return NULL;
76         }
77       return result;
78     }
79 }