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